Skip to main content

voirs_spatial/
lib.rs

1//! # VoiRS Spatial Audio System
2//!
3//! This crate provides 3D spatial audio processing capabilities including
4//! HRTF (Head-Related Transfer Function) processing, binaural audio rendering,
5//! 3D position tracking, room acoustics simulation, and AR/VR integration.
6//!
7//! ## Features
8//!
9//! ### Core Spatial Audio
10//! - **3D Audio Positioning**: Accurate spatial audio placement using Position3D
11//! - **HRTF Processing**: Head-Related Transfer Function for realistic spatial cues
12//! - **Binaural Rendering**: Real-time binaural audio synthesis with up to 32 sources
13//! - **Room Acoustics**: Ray-traced room simulation with material properties
14//! - **Distance Modeling**: Natural distance attenuation with air absorption
15//!
16//! ### Advanced Features
17//! - **Higher-Order Ambisonics**: 1st-3rd order ambisonics encoding/decoding
18//! - **VR/AR Integration**: Platform support for Oculus, SteamVR, ARKit, ARCore, WMR
19//! - **Multi-user Environments**: Shared spatial audio experiences with networking
20//! - **Neural Spatial Audio**: AI-powered HRTF personalization and synthesis
21//! - **Gesture Control**: Hand and body gesture-based audio interaction
22//!
23//! ### Platform Support
24//! - **Gaming**: Unity, Unreal Engine integration via C API
25//! - **Console**: PlayStation, Xbox, Nintendo Switch optimization
26//! - **Mobile**: iOS and Android with power management
27//! - **Web**: WebXR browser-based immersive audio
28//!
29//! ## Performance Characteristics
30//!
31//! ### Real-time Performance Targets
32//! - **VR/AR Latency**: <20ms motion-to-sound latency
33//! - **Gaming Latency**: <30ms for interactive applications
34//! - **General Use**: <50ms for non-critical applications
35//! - **CPU Usage**: <25% for real-time spatial processing
36//! - **Source Count**: Supports 32+ simultaneous spatial sources
37//!
38//! ### Quality Metrics
39//! - **Localization Accuracy**: 95%+ correct front/back discrimination
40//! - **Distance Accuracy**: 90%+ accurate distance perception
41//! - **Elevation Accuracy**: 85%+ accurate elevation perception
42//! - **Naturalness**: MOS 4.2+ for spatial audio quality
43//!
44//! ### Optimization Features
45//! - **SIMD Acceleration**: AVX2/AVX512/NEON optimizations for spatial math
46//! - **GPU Support**: CUDA/Metal acceleration for convolution and neural processing
47//! - **Memory Pools**: Efficient buffer reuse and cache optimization
48//! - **Adaptive Quality**: Dynamic quality scaling based on system load
49//!
50//! ## Quick Start Examples
51//!
52//! ### Simple 3D Positioning
53//!
54//! ```no_run
55//! use voirs_spatial::{Position3D, SpatialConfig};
56//!
57//! # #[tokio::main]
58//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
59//! // Create spatial audio configuration
60//! let config = SpatialConfig::default();
61//! println!("Sample rate: {} Hz", config.sample_rate);
62//! println!("Buffer size: {} samples", config.buffer_size);
63//!
64//! // Position sound source to the right
65//! let position = Position3D::new(2.0, 0.0, 0.0);
66//! let distance = position.distance_to(&Position3D::new(0.0, 0.0, 0.0));
67//! println!("Source distance: {:.2}m", distance);
68//! # Ok(())
69//! # }
70//! ```
71//!
72//! ### Binaural Rendering with Multiple Sources
73//!
74//! ```no_run
75//! use std::sync::Arc;
76//! use voirs_spatial::{BinauralConfig, HrtfDatabase, Position3D, SourceType};
77//!
78//! # #[tokio::main]
79//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
80//! // Create binaural renderer configuration
81//! let config = BinauralConfig {
82//!     sample_rate: 48000,
83//!     buffer_size: 512,
84//!     hrir_length: 200,
85//!     max_sources: 8,
86//!     use_gpu: false,
87//!     crossfade_duration: 0.05,
88//!     quality_level: 0.8,
89//!     enable_distance_modeling: true,
90//!     enable_air_absorption: true,
91//!     near_field_distance: 0.2,
92//!     far_field_distance: 10.0,
93//!     optimize_for_latency: true,
94//! };
95//!
96//! // Create HRTF database
97//! let hrtf_db = HrtfDatabase::load_default().await.expect("Failed to load HRTF database");
98//! println!("HRTF database created with default settings");
99//!
100//! // Define source positions
101//! let front = Position3D::new(0.0, 2.0, 0.0);
102//! let left = Position3D::new(-1.5, 1.0, 0.0);
103//! println!("Configured binaural renderer with {} max sources", config.max_sources);
104//! # Ok(())
105//! # }
106//! ```
107//!
108//! ### Higher-Order Ambisonics
109//!
110//! ```rust
111//! use scirs2_core::ndarray::Array1;
112//! use voirs_spatial::{AmbisonicsEncoder, AmbisonicsDecoder, Position3D, NormalizationScheme,
113//!                     ChannelOrdering, SpeakerConfiguration};
114//!
115//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
116//! // Create encoder and decoder
117//! let encoder = AmbisonicsEncoder::new(2, NormalizationScheme::N3D, ChannelOrdering::ACN);
118//! let decoder = AmbisonicsDecoder::for_speaker_config(2, SpeakerConfiguration::Stereo)?;
119//!
120//! // Encode mono audio to ambisonics
121//! let audio = Array1::from_vec(vec![0.0; 1000]);
122//! let position = Position3D::new(1.0, 1.0, 0.0);
123//! let encoded = encoder.encode_mono(&audio, &position)?;
124//!
125//! // Decode to stereo
126//! let stereo = decoder.decode(&encoded)?;
127//! println!("Decoded to {} channels", stereo.shape()[0]);
128//! # Ok(())
129//! # }
130//! ```
131//!
132//! ## Feature Flags
133//!
134//! Enable optional features in your `Cargo.toml`:
135//!
136//! ```toml
137//! [dependencies]
138//! voirs-spatial = { version = "0.1.0-alpha.2", features = ["steamvr", "webxr"] }
139//! ```
140//!
141//! Available features:
142//! - `gpu` - GPU acceleration support (CUDA/Metal)
143//! - `cuda` - CUDA-specific GPU acceleration
144//! - `metal` - Metal GPU acceleration for macOS/iOS
145//! - `steamvr` - SteamVR/OpenVR platform integration
146//! - `webxr` - WebXR browser integration
147//! - `windows_mr` - Windows Mixed Reality support
148//! - `arcore` - Android ARCore integration
149//! - `arkit` - iOS ARKit integration
150//! - `all_platforms` - Enable all VR/AR platforms
151//!
152//! ## Performance Tips
153//!
154//! ### For Real-time Applications
155//! 1. Use smaller buffer sizes (256-512 samples) for lower latency
156//! 2. Enable SIMD optimizations (automatic on supported platforms)
157//! 3. Limit simultaneous sources based on target platform (8-16 for mobile, 32+ for desktop)
158//! 4. Use adaptive quality settings for variable system load
159//!
160//! ### For High-Quality Rendering
161//! 1. Use larger buffer sizes (1024-2048 samples) for better frequency resolution
162//! 2. Enable GPU acceleration for convolution-heavy workloads
163//! 3. Use higher-order ambisonics (2nd-3rd order) for better spatial resolution
164//! 4. Enable full room acoustics simulation with ray tracing
165//!
166//! ### Memory Optimization
167//! 1. Reuse audio buffers with `MemoryManager` buffer pools
168//! 2. Enable HRTF caching for frequently-used positions
169//! 3. Use distance-based culling for far-away sources
170//! 4. Adjust cache policies based on available memory
171//!
172//! ## Architecture
173//!
174//! The spatial audio system follows a modular pipeline architecture:
175//!
176//! ```text
177//! Input Audio → Position3D → HRTF/Ambisonics → Room Acoustics → Binaural Output
178//!                    ↓              ↓                  ↓
179//!              Head Tracking   Distance Model   Reflection/Reverb
180//! ```
181//!
182//! Each module can be used independently or combined for complete spatial audio processing.
183//!
184//! ## Safety and Compliance
185//!
186//! - **Memory Safety**: 100% safe Rust with `#![deny(unsafe_code)]`
187//! - **Thread Safety**: Lock-free algorithms for real-time processing
188//! - **Error Handling**: Comprehensive error types with recovery suggestions
189//! - **SciRS2 Integration**: Uses SciRS2-Core for scientific computing abstractions
190
191// Allow pedantic lints that are acceptable for audio/DSP processing code
192#![allow(clippy::cast_precision_loss)] // Acceptable for audio sample conversions
193#![allow(clippy::cast_possible_truncation)] // Controlled truncation in audio processing
194#![allow(clippy::cast_sign_loss)] // Intentional in index calculations
195#![allow(clippy::missing_errors_doc)] // Many internal functions with self-documenting error types
196#![allow(clippy::missing_panics_doc)] // Panics are documented where relevant
197#![allow(clippy::unused_self)] // Some trait implementations require &self for consistency
198#![allow(clippy::must_use_candidate)] // Not all return values need must_use annotation
199#![allow(clippy::doc_markdown)] // Technical terms don't all need backticks
200#![allow(clippy::unnecessary_wraps)] // Result wrappers maintained for API consistency
201#![allow(clippy::float_cmp)] // Exact float comparisons are intentional in some contexts
202#![allow(clippy::match_same_arms)] // Pattern matching clarity sometimes requires duplication
203#![allow(clippy::module_name_repetitions)] // Type names often repeat module names
204#![allow(clippy::struct_excessive_bools)] // Config structs naturally have many boolean flags
205#![allow(clippy::too_many_lines)] // Some functions are inherently complex
206#![allow(clippy::needless_pass_by_value)] // Some functions designed for ownership transfer
207#![allow(clippy::similar_names)] // Many similar variable names in algorithms
208#![allow(clippy::unused_async)] // Public API functions may need async for consistency
209#![allow(clippy::needless_range_loop)] // Range loops sometimes clearer than iterators
210#![allow(clippy::uninlined_format_args)] // Explicit argument names can improve clarity
211#![allow(clippy::manual_clamp)] // Manual clamping sometimes clearer
212#![allow(clippy::return_self_not_must_use)] // Not all builder methods need must_use
213#![allow(clippy::cast_possible_wrap)] // Controlled wrapping in processing code
214#![allow(clippy::cast_lossless)] // Explicit casts preferred for clarity
215#![allow(clippy::wildcard_imports)] // Prelude imports are convenient and standard
216#![allow(clippy::format_push_string)] // Sometimes more readable than alternative
217#![allow(clippy::redundant_closure_for_method_calls)] // Closures sometimes needed for type inference
218#![deny(unsafe_code)]
219#![warn(missing_docs)]
220
221pub mod ambisonics;
222pub mod automotive;
223/// ONNX and other inference backends for spatial audio
224pub mod backends;
225pub mod beamforming;
226pub mod binaural;
227pub mod compression;
228pub mod config;
229pub mod core;
230pub mod gaming;
231pub mod gestures;
232pub mod gpu;
233pub mod haptic;
234pub mod hrtf;
235pub mod memory;
236pub mod mobile;
237pub mod multiuser;
238pub mod neural;
239pub mod performance;
240pub mod performance_targets;
241pub mod platforms;
242pub mod plugins;
243pub mod position;
244pub mod power;
245pub mod public_spaces;
246pub mod realtime; // Real-time optimizations: lock-free buffers, SIMD alignment, zero-copy
247pub mod room;
248pub mod smart_speakers;
249pub mod technical_testing;
250pub mod telepresence;
251pub mod types;
252pub mod utils;
253pub mod validation;
254pub mod visual_audio;
255pub mod webxr;
256pub mod wfs;
257
258// Re-export main types and traits
259pub use ambisonics::{
260    channel_count, AmbisonicsDecoder, AmbisonicsEncoder, AmbisonicsOrder, AmbisonicsProcessor,
261    ChannelOrdering, NormalizationScheme, SpeakerConfiguration, SphericalCoordinate,
262    SphericalHarmonics,
263};
264pub use automotive::{
265    AcousticTreatment, AdaptiveVolumeConfig, AudioZone, DashboardSide, DriverProtectionConfig,
266    EmergencyAlertType, EmergencyAudioConfig, EngineNoiseCompensation, EngineType,
267    ExternalAwarenessConfig, ExternalConditions, FrequencyBand, FrequencyWeighting, GearPosition,
268    HearingCharacteristics, HvacConfig, HvacState, InteriorMaterials, LegalComplianceConfig,
269    MaterialType, NoiseCompensationConfig, PassengerActivity, PassengerConfig, PassengerInfo,
270    PassengerPreferences, PrecipitationType, ResourceUsage, RoadNoiseCompensation, SafetyConfig,
271    SeatPosition, SpatialPreferences, SpeakerCharacteristics, SpeakerMounting, SpeakerType,
272    SurfaceType, TimeLimits, TireNoiseModel, TireType, VehicleAcousticConfig, VehicleAudioConfig,
273    VehicleAudioConfigBuilder, VehicleAudioMetrics, VehicleAudioProcessor, VehicleSide,
274    VehicleSpeaker, VehicleSpeakerConfig, VehicleState, VehicleType, VentPosition,
275    WindNoiseCompensation, WindowConfig, WindowState, WindowTinting, ZoneAudioSource,
276};
277pub use beamforming::{
278    AdaptationConfig, BeamPattern, BeamformerWeights, BeamformingAlgorithm, BeamformingConfig,
279    BeamformingProcessor, DoaResult, SpatialSmoothingConfig,
280};
281pub use binaural::{BinauralConfig, BinauralMetrics, BinauralRenderer, SourceType};
282pub use compression::{
283    AdaptiveParams, CompressedFrame, CompressionCodec, CompressionQuality, CompressionStats,
284    PerceptualParams, SourceClustering, SpatialCompressionConfig, SpatialCompressor,
285    SpatialMetadata, SpatialParams, TemporalMasking,
286};
287pub use config::{SpatialConfig, SpatialConfigBuilder};
288pub use core::{SpatialProcessor, SpatialProcessorBuilder};
289pub use gaming::{
290    console, AttenuationCurve, AttenuationSettings, AudioCategory, GameAudioSource, GameEngine,
291    GamingAudioManager, GamingConfig, GamingMetrics,
292};
293pub use gestures::{
294    AudioAction, GestureBuilder, GestureConfidence, GestureConfig, GestureController, GestureData,
295    GestureDirection, GestureEvent, GestureEventType, GestureRecognitionMethod, GestureType, Hand,
296};
297pub use gpu::{
298    GpuAmbisonics, GpuConfig, GpuConvolution, GpuDevice, GpuResourceManager, GpuSpatialMath,
299};
300pub use haptic::{
301    AudioHapticMapping, DistanceAttenuation, HapticAccessibilitySettings, HapticAudioConfig,
302    HapticAudioProcessor, HapticCapabilities, HapticComfortSettings, HapticDevice,
303    HapticEffectType, HapticElement, HapticMetrics, HapticPattern, PatternStyle,
304};
305pub use hrtf::{
306    ai_personalization::{
307        AdaptationStrategy, AiHrtfPersonalizer, AnthropometricMeasurements, HrtfModifications,
308        PerceptualFeedback, PersonalizationConfig, PersonalizationMetadata, PersonalizedHrtf,
309        TrainingResults,
310    },
311    HrtfDatabase, HrtfProcessor,
312};
313pub use memory::{
314    cache_optimization, Array2Pool, BufferPool, CacheManager, CachePolicy, MemoryConfig,
315    MemoryManager, MemoryStatistics,
316};
317pub use mobile::{
318    android, ios, MobileConfig, MobileDevice, MobileMetrics, MobileOptimizer, MobilePlatform,
319    PowerState, QualityPreset,
320};
321pub use multiuser::{
322    AccessibilitySettings, AcousticSettings, AudioEffect, AudioEffectsProcessor,
323    AudioQualityMetrics, AudioSourceType, BandwidthSettings, CodecState, CodecTiming,
324    CompensationMethod, ConnectionStatus, DirectionalPattern, DisconnectReason,
325    InterpolationMethod, LatencyCompensator, LowBandwidthMode, MicrophoneSettings, MixerConfig,
326    MultiUserAttenuationCurve, MultiUserAudioProcessor, MultiUserAudioSource, MultiUserConfig,
327    MultiUserConfigBuilder, MultiUserEnvironment, MultiUserEvent, MultiUserMetrics, MultiUserUser,
328    NetworkEventType, NetworkStats, OptimizationLevel, Permission, PermissionSystem,
329    PositionInterpolator, PositionSnapshot, RoomId, SourceAccessControl, SourceId,
330    SourceProcessingState, SourceQualitySettings, SourceVisibility, SpatialAudioMixer,
331    SpatialProperties, SpatialZone, SynchronizationManager, SynchronizedClock, UserId, UserRole,
332    VadAlgorithm, VadState, VadThresholds, VoiceActivityDetector, ZoneAudioProperties, ZoneBounds,
333    ZoneType,
334};
335pub use neural::{
336    AdaptiveQualityController, AugmentationConfig, ConvolutionalModel, FeedforwardModel,
337    LossFunction, NeuralInputFeatures, NeuralModel, NeuralModelType, NeuralPerformanceMetrics,
338    NeuralSpatialConfig, NeuralSpatialConfigBuilder, NeuralSpatialOutput, NeuralSpatialProcessor,
339    NeuralTrainer, NeuralTrainingResults, OptimizerType, RealtimeConstraints, TrainingConfig,
340    TransformerModel,
341};
342pub use performance::{
343    PerformanceConfig, PerformanceMetrics, PerformanceReport, PerformanceSummary,
344    PerformanceTargetResult, PerformanceTestSuite, ResourceMonitor, ResourceStatistics,
345};
346pub use performance_targets::{
347    LatencyMeasurements, PerformanceTargetReport, PerformanceTargetValidator, PerformanceTargets,
348    PerformanceValidationResult, QualityMeasurements, QualityTargets, RealtimeTargets,
349    ResourceMeasurements, ResourceTargets, ResourceUsageStats, ScalabilityMeasurements,
350    ScalabilityTargets, TargetCategory, TargetComparison,
351};
352pub use platforms::{
353    ARCorePlatform, ARKitPlatform, DeviceInfo, EyeData, EyeTrackingData, GenericPlatform, HandData,
354    HandGesture, HandTrackingData, OculusPlatform, PlatformCapabilities, PlatformFactory,
355    PlatformIntegration, PlatformTrackingData, PoseData, TrackingConfig, TrackingQuality,
356    TrackingState, WMRPlatform,
357};
358
359#[cfg(feature = "steamvr")]
360pub use platforms::SteamVRPlatform;
361pub use plugins::{
362    PluginCapabilities, PluginConfig, PluginManager, PluginParameter, PluginParameters,
363    PluginState, ProcessingChain, ProcessingContext, ReverbPlugin, SpatialPlugin,
364};
365pub use position::{
366    advanced_prediction::{
367        AdaptationPhase, AdvancedPredictiveTracker, ModelSelectionStrategy, MotionPattern,
368        MotionPatternType, PatternRecognitionConfig, PredictedPosition, PredictionMetrics,
369        PredictionModelType, PredictiveTrackingConfig,
370    },
371    Box3D, CalibrationData, ComfortSettings, DopplerProcessor, DynamicSource, DynamicSourceManager,
372    HeadTracker, Listener, ListenerMovementSystem, MotionPredictor, MotionSnapshot,
373    MovementConstraints, MovementMetrics, NavigationMode, OcclusionDetector, OcclusionMaterial,
374    OcclusionMethod, OcclusionResult, PlatformData, PlatformType, SoundSource,
375    SpatialSourceManager,
376};
377pub use power::{
378    DeviceType, PowerConfig, PowerMetrics, PowerOptimizer, PowerProfile, PowerStrategy,
379};
380pub use room::{
381    adaptive_acoustics::{
382        AdaptationAction, AdaptationController, AdaptationMetrics, AdaptationTrigger,
383        AdaptiveAcousticEnvironment, AdaptiveAcousticsConfig, EnvironmentSensors,
384        EnvironmentSnapshot, EnvironmentType, SensorConfig, UserFeedback,
385    },
386    ConnectionAcousticProperties, ConnectionState, ConnectionType, GlobalAcousticConfig,
387    MultiRoomEnvironment, Room, RoomAcoustics, RoomConnection, RoomSimulator,
388};
389pub use smart_speakers::{
390    ArrayMetrics, ArrayTopology, AudioFormat, AudioRoute, AudioRouter, AudioSource, AudioSpecs,
391    CalibrationEngine, CalibrationMethod, CalibrationResults, CalibrationStatus, ClockSource,
392    CompressionConfig, DeviceFilter, DirectivityPattern, DiscoveryProtocol, DiscoveryService,
393    DspFeature, EQFilter, FilterType, LimitingConfig, MixSettings, NetworkConfig, NetworkInfo,
394    NetworkProtocol, ProcessingConfig, ProcessingStep, RoomCorrection, SmartSpeaker,
395    SpeakerArrayConfig, SpeakerArrayConfigBuilder, SpeakerArrayManager, SpeakerCapabilities,
396    SyncConfig,
397};
398pub use technical_testing::{
399    create_standard_technical_configs, LatencyAnalysis, MemoryConstraints, PlatformAnalysis,
400    PlatformTestResult, StabilityAnalysis, StressTestParams, TechnicalSuccessCriteria,
401    TechnicalTestConfig, TechnicalTestParameters, TechnicalTestReport, TechnicalTestResult,
402    TechnicalTestSuite, TechnicalTestType, TestOutcome,
403};
404pub use telepresence::{
405    AcousticEchoSettings, AcousticMatchingSettings, AcousticProperties, AdaptiveQualitySettings,
406    AirAbsorptionSettings, AnonymizationMethod, AnonymizationSettings, AudioCodec,
407    AudioDeviceConfig, AudioEnhancementSettings, AudioFormat as TelepresenceAudioFormat,
408    AudioMetadata, AudioPresenceSettings, AudioQualityPreferences, AudioQualitySettings,
409    BandwidthConstraints, BandwidthExtensionSettings, CodecPreferences, CompressionSettings,
410    ConsentManagementSettings, CrossRoomSettings, DataCollectionSettings, DistanceModelingSettings,
411    DopplerEffectsSettings, EchoCancellationSettings, EnvironmentalAwarenessSettings,
412    EqualizationSettings, HeadTrackingSettings, HrtfPersonalizationSettings, NetworkSettings,
413    NoiseSuppressionSettings, Orientation, PresenceIndicatorSettings, PrivacySettings,
414    QualityLevel, QualitySettings, ReceivedAudio, RoomSimulationSettings, SessionJoinResult,
415    SessionState, SessionStatistics, SpatialTelepresenceSettings, TelepresenceAudioSettings,
416    TelepresenceConfig, TelepresenceProcessor, TelepresenceSession, TrackingPredictionSettings,
417    UserConfig, VadSettings, Velocity, VirtualRoomParameters, VisualPresenceSettings,
418    VoiceProcessingSettings, VoiceSpatializationSettings,
419};
420pub use types::{
421    AudioChannel, BinauraAudio, Position3D, SIMDSpatialOps, SpatialEffect, SpatialRequest,
422    SpatialResult,
423};
424pub use validation::{
425    create_standard_test_configs, create_test_subjects, AccuracyMetrics, AudioExpertise,
426    ExperienceLevel, Gender, HearingAbility, PerceptualTestSuite, PopulationAnalysis, ResponseData,
427    StimulusData, SubjectiveRatings, SuccessCriteria, TestParameters, TestStatistics, TestSubject,
428    ValidationReport, ValidationTestConfig, ValidationTestResult, ValidationTestType,
429};
430pub use visual_audio::{
431    AnimationParams, AnimationType, AudioVisualMapping, ColorRGBA, ColorScheme, ColorSchemeType,
432    DirectionZone, DirectionalCueMapping, EasingFunction, EventTriggerMapping,
433    FrequencyVisualMapping, OnsetTrigger, RhythmTrigger, ScalingCurve, ShapeType, SilenceTrigger,
434    SpectralTrigger, VisualAccessibilitySettings, VisualAudioConfig, VisualAudioMetrics,
435    VisualAudioProcessor, VisualDisplay, VisualDisplayCapabilities, VisualDistanceAttenuation,
436    VisualEffect, VisualElement, VisualElementType, VisualPerformanceSettings, VisualResourceUsage,
437    VisualSyncSettings,
438};
439pub use webxr::{
440    utils as webxr_utils, BrowserType, WebXRCapabilities, WebXRConfig, WebXRMetrics, WebXRPose,
441    WebXRProcessor, WebXRSessionType, WebXRSourceType,
442};
443pub use wfs::{
444    ArrayGeometry, PreEmphasisConfig, WfsArrayBuilder, WfsConfig, WfsDrivingFunction, WfsProcessor,
445    WfsSource, WfsSourceType,
446};
447
448/// Result type for spatial audio operations
449pub type Result<T> = std::result::Result<T, Error>;
450
451/// Error types for spatial audio processing
452#[derive(Debug, thiserror::Error)]
453pub enum Error {
454    /// Configuration error (structured)
455    #[error("Configuration error: {0}")]
456    Config(#[from] ConfigError),
457
458    /// Processing error (structured)
459    #[error("Processing error: {0}")]
460    Processing(#[from] ProcessingError),
461
462    /// HRTF error (structured)
463    #[error("HRTF error: {0}")]
464    Hrtf(#[from] HrtfError),
465
466    /// Position error (structured)
467    #[error("Position error: {0}")]
468    Position(#[from] PositionError),
469
470    /// Room acoustics error (structured)
471    #[error("Room acoustics error: {0}")]
472    Room(#[from] RoomError),
473
474    /// Audio error (structured)
475    #[error("Audio error: {0}")]
476    Audio(#[from] AudioError),
477
478    /// Memory error (structured)
479    #[error("Memory error: {0}")]
480    Memory(#[from] MemoryError),
481
482    /// GPU error (structured)
483    #[error("GPU error: {0}")]
484    Gpu(#[from] GpuError),
485
486    /// Platform error (structured)
487    #[error("Platform error: {0}")]
488    Platform(#[from] PlatformError),
489
490    /// Validation error (structured)
491    #[error("Validation error: {0}")]
492    Validation(#[from] ValidationError),
493
494    /// I/O error
495    #[error("I/O error: {0}")]
496    Io(#[from] std::io::Error),
497
498    /// Serialization error
499    #[error("Serialization error: {0}")]
500    Serialization(#[from] serde_json::Error),
501
502    /// Candle error
503    #[error("Candle error: {0}")]
504    Candle(#[from] candle_core::Error),
505
506    /// Generic error with context
507    #[error("Error: {message}")]
508    Generic {
509        /// Error message
510        message: String,
511        /// Error code
512        code: ErrorCode,
513        /// Error context
514        context: Option<Box<ErrorContext>>,
515    },
516
517    /// Legacy errors for backward compatibility (will be migrated)
518    #[error("Configuration error: {0}")]
519    LegacyConfig(String),
520
521    /// Legacy processing error for backward compatibility
522    #[error("Processing error: {0}")]
523    LegacyProcessing(String),
524
525    /// Legacy HRTF error for backward compatibility
526    #[error("HRTF error: {0}")]
527    LegacyHrtf(String),
528
529    /// Legacy position error for backward compatibility
530    #[error("Position error: {0}")]
531    LegacyPosition(String),
532
533    /// Legacy room acoustics error for backward compatibility
534    #[error("Room acoustics error: {0}")]
535    LegacyRoom(String),
536
537    /// Legacy audio error for backward compatibility
538    #[error("Audio error: {0}")]
539    LegacyAudio(String),
540
541    /// Legacy validation error for backward compatibility
542    #[error("Validation error: {0}")]
543    LegacyValidation(String),
544}
545
546/// Configuration-specific errors
547#[derive(Debug, thiserror::Error)]
548pub enum ConfigError {
549    /// Invalid parameter value
550    #[error("Invalid parameter '{parameter}': {message}. Expected: {expected}")]
551    InvalidParameter {
552        /// Parameter name
553        parameter: String,
554        /// Error message
555        message: String,
556        /// Expected value or format
557        expected: String,
558    },
559
560    /// Missing required parameter
561    #[error("Missing required parameter: {parameter}")]
562    MissingParameter {
563        /// Parameter name
564        parameter: String,
565    },
566
567    /// Conflicting parameters
568    #[error("Conflicting parameters: {params:?}. {resolution}")]
569    ConflictingParameters {
570        /// Conflicting parameter names
571        params: Vec<String>,
572        /// Resolution suggestion
573        resolution: String,
574    },
575
576    /// File not found
577    #[error("Configuration file not found: {path}")]
578    FileNotFound {
579        /// File path
580        path: String,
581    },
582}
583
584/// Processing-specific errors
585#[derive(Debug, thiserror::Error)]
586pub enum ProcessingError {
587    /// Buffer size mismatch
588    #[error("Buffer size mismatch: expected {expected}, got {actual}")]
589    BufferSizeMismatch {
590        /// Expected size
591        expected: usize,
592        /// Actual size
593        actual: usize,
594    },
595
596    /// Sample rate mismatch
597    #[error("Sample rate mismatch: expected {expected}Hz, got {actual}Hz")]
598    SampleRateMismatch {
599        /// Expected sample rate
600        expected: u32,
601        /// Actual sample rate
602        actual: u32,
603    },
604
605    /// Real-time constraint violation
606    #[error("Real-time processing constraint violated: {duration_ms}ms > {max_ms}ms")]
607    RealtimeViolation {
608        /// Processing duration
609        duration_ms: f64,
610        /// Maximum allowed duration
611        max_ms: f64,
612    },
613
614    /// Resource exhaustion
615    #[error("Resource exhausted: {resource}. Usage: {usage}/{limit}")]
616    ResourceExhausted {
617        /// Resource type
618        resource: String,
619        /// Current usage
620        usage: u64,
621        /// Resource limit
622        limit: u64,
623    },
624}
625
626/// HRTF-specific errors
627#[derive(Debug, thiserror::Error)]
628pub enum HrtfError {
629    /// Database loading failed
630    #[error("Failed to load HRTF database from {path}: {reason}")]
631    DatabaseLoadFailed {
632        /// Database path
633        path: String,
634        /// Failure reason
635        reason: String,
636    },
637
638    /// Invalid position for HRTF lookup
639    #[error("Invalid position for HRTF lookup: azimuth={azimuth}°, elevation={elevation}°")]
640    InvalidPosition {
641        /// Azimuth in degrees
642        azimuth: f32,
643        /// Elevation in degrees
644        elevation: f32,
645    },
646
647    /// Interpolation failed
648    #[error("HRTF interpolation failed: {reason}")]
649    InterpolationFailed {
650        /// Failure reason
651        reason: String,
652    },
653}
654
655/// Position-specific errors
656#[derive(Debug, thiserror::Error)]
657pub enum PositionError {
658    /// Invalid coordinates
659    #[error("Invalid coordinates: x={x}, y={y}, z={z}. {constraint}")]
660    InvalidCoordinates {
661        /// X coordinate
662        x: f32,
663        /// Y coordinate
664        y: f32,
665        /// Z coordinate
666        z: f32,
667        /// Constraint description
668        constraint: String,
669    },
670
671    /// Tracking system unavailable
672    #[error("Tracking system unavailable: {system}")]
673    TrackingUnavailable {
674        /// Tracking system name
675        system: String,
676    },
677
678    /// Calibration required
679    #[error("Calibration required for {component}: {instructions}")]
680    CalibrationRequired {
681        /// Component requiring calibration
682        component: String,
683        /// Calibration instructions
684        instructions: String,
685    },
686}
687
688/// Room acoustics errors
689#[derive(Debug, thiserror::Error)]
690pub enum RoomError {
691    /// Invalid room dimensions
692    #[error("Invalid room dimensions: {width}x{height}x{depth}m. {constraint}")]
693    InvalidDimensions {
694        /// Room width
695        width: f32,
696        /// Room height
697        height: f32,
698        /// Room depth
699        depth: f32,
700        /// Constraint description
701        constraint: String,
702    },
703
704    /// Material properties error
705    #[error("Invalid material properties: {material}. {issue}")]
706    InvalidMaterial {
707        /// Material name
708        material: String,
709        /// Issue description
710        issue: String,
711    },
712
713    /// Ray tracing failed
714    #[error("Ray tracing computation failed: {reason}")]
715    RayTracingFailed {
716        /// Failure reason
717        reason: String,
718    },
719}
720
721/// Audio-specific errors
722#[derive(Debug, thiserror::Error)]
723pub enum AudioError {
724    /// Unsupported format
725    #[error("Unsupported audio format: {format}. Supported: {supported:?}")]
726    UnsupportedFormat {
727        /// Current format
728        format: String,
729        /// List of supported formats
730        supported: Vec<String>,
731    },
732
733    /// Clipping detected
734    #[error("Audio clipping detected: {severity}% samples above threshold")]
735    ClippingDetected {
736        /// Clipping severity as percentage
737        severity: f32,
738    },
739
740    /// Underrun or overrun
741    #[error("Audio buffer {kind}: {samples} samples")]
742    BufferIssue {
743        /// Type of buffer issue
744        kind: AudioBufferIssue,
745        /// Number of affected samples
746        samples: usize,
747    },
748}
749
750/// Memory-specific errors
751#[derive(Debug, thiserror::Error)]
752pub enum MemoryError {
753    /// Out of memory
754    #[error("Out of memory: requested {requested}MB, available {available}MB")]
755    OutOfMemory {
756        /// Requested memory in MB
757        requested: u64,
758        /// Available memory in MB
759        available: u64,
760    },
761
762    /// Pool exhausted
763    #[error("Memory pool exhausted: {pool_type}, size={size}")]
764    PoolExhausted {
765        /// Pool type
766        pool_type: String,
767        /// Pool size
768        size: usize,
769    },
770
771    /// Cache miss
772    #[error("Cache miss: {cache_type}, key={key}")]
773    CacheMiss {
774        /// Cache type
775        cache_type: String,
776        /// Cache key
777        key: String,
778    },
779}
780
781/// GPU-specific errors
782#[derive(Debug, thiserror::Error)]
783pub enum GpuError {
784    /// GPU not available
785    #[error("GPU not available: {reason}")]
786    NotAvailable {
787        /// Reason for unavailability
788        reason: String,
789    },
790
791    /// CUDA error
792    #[error("CUDA error: {message}")]
793    Cuda {
794        /// CUDA error message
795        message: String,
796    },
797
798    /// Memory allocation failed
799    #[error("GPU memory allocation failed: requested {requested}MB")]
800    AllocationFailed {
801        /// Requested memory in MB
802        requested: u64,
803    },
804}
805
806/// Platform-specific errors
807#[derive(Debug, thiserror::Error)]
808pub enum PlatformError {
809    /// Platform not supported
810    #[error("Platform not supported: {platform}")]
811    NotSupported {
812        /// Platform name
813        platform: String,
814    },
815
816    /// SDK initialization failed
817    #[error("SDK initialization failed: {sdk}, reason: {reason}")]
818    SdkInitFailed {
819        /// SDK name
820        sdk: String,
821        /// Failure reason
822        reason: String,
823    },
824
825    /// Feature not available
826    #[error("Feature not available: {feature} on {platform}")]
827    FeatureUnavailable {
828        /// Feature name
829        feature: String,
830        /// Platform name
831        platform: String,
832    },
833}
834
835/// Validation-specific errors
836#[derive(Debug, thiserror::Error)]
837pub enum ValidationError {
838    /// Schema validation failed
839    #[error("Schema validation failed: {field}. {message}")]
840    SchemaFailed {
841        /// Field that failed validation
842        field: String,
843        /// Validation message
844        message: String,
845    },
846
847    /// Range validation failed
848    #[error("Value out of range: {field}={value}, expected [{min}, {max}]")]
849    RangeError {
850        /// Field name
851        field: String,
852        /// Actual value
853        value: f64,
854        /// Minimum allowed value
855        min: f64,
856        /// Maximum allowed value
857        max: f64,
858    },
859
860    /// Test failed
861    #[error("Test failed: {test_name}. Expected: {expected}, Got: {actual}")]
862    TestFailed {
863        /// Test name
864        test_name: String,
865        /// Expected result
866        expected: String,
867        /// Actual result
868        actual: String,
869    },
870}
871
872/// Error codes for programmatic error handling
873#[derive(Debug, Clone, Copy, PartialEq, Eq)]
874pub enum ErrorCode {
875    /// Configuration errors (1000-1999)
876    /// Invalid parameter error code
877    ConfigInvalidParameter = 1001,
878    /// Missing parameter error code
879    ConfigMissingParameter = 1002,
880    /// Conflicting parameters error code
881    ConfigConflictingParameters = 1003,
882    /// Configuration file not found error code
883    ConfigFileNotFound = 1004,
884
885    /// Processing errors (2000-2999)
886    /// Buffer size mismatch error code
887    ProcessingBufferSizeMismatch = 2001,
888    /// Sample rate mismatch error code
889    ProcessingSampleRateMismatch = 2002,
890    /// Real-time constraint violation error code
891    ProcessingRealtimeViolation = 2003,
892    /// Resource exhaustion error code
893    ProcessingResourceExhausted = 2004,
894
895    /// HRTF errors (3000-3999)
896    /// HRTF database load failed error code
897    HrtfDatabaseLoadFailed = 3001,
898    /// Invalid HRTF position error code
899    HrtfInvalidPosition = 3002,
900    /// HRTF interpolation failed error code
901    HrtfInterpolationFailed = 3003,
902
903    /// Position errors (4000-4999)
904    /// Invalid coordinates error code
905    PositionInvalidCoordinates = 4001,
906    /// Tracking system unavailable error code
907    PositionTrackingUnavailable = 4002,
908    /// Calibration required error code
909    PositionCalibrationRequired = 4003,
910
911    /// Room errors (5000-5999)
912    /// Invalid room dimensions error code
913    RoomInvalidDimensions = 5001,
914    /// Invalid material properties error code
915    RoomInvalidMaterial = 5002,
916    /// Ray tracing computation failed error code
917    RoomRayTracingFailed = 5003,
918
919    /// Audio errors (6000-6999)
920    /// Unsupported audio format error code
921    AudioUnsupportedFormat = 6001,
922    /// Audio clipping detected error code
923    AudioClippingDetected = 6002,
924    /// Audio buffer issue error code
925    AudioBufferIssue = 6003,
926
927    /// Memory errors (7000-7999)
928    /// Out of memory error code
929    MemoryOutOfMemory = 7001,
930    /// Memory pool exhausted error code
931    MemoryPoolExhausted = 7002,
932    /// Cache miss error code
933    MemoryCacheMiss = 7003,
934
935    /// GPU errors (8000-8999)
936    /// GPU not available error code
937    GpuNotAvailable = 8001,
938    /// CUDA error code
939    GpuCudaError = 8002,
940    /// GPU memory allocation failed error code
941    GpuAllocationFailed = 8003,
942
943    /// Platform errors (9000-9999)
944    /// Platform not supported error code
945    PlatformNotSupported = 9001,
946    /// Platform SDK initialization failed error code
947    PlatformSdkInitFailed = 9002,
948    /// Platform feature unavailable error code
949    PlatformFeatureUnavailable = 9003,
950
951    /// Generic errors (10000+)
952    /// Generic error code
953    Generic = 10000,
954}
955
956/// Audio buffer issue types
957#[derive(Debug, Clone, Copy, PartialEq, Eq)]
958pub enum AudioBufferIssue {
959    /// Buffer underrun (not enough data)
960    Underrun,
961    /// Buffer overrun (too much data)
962    Overrun,
963    /// Buffer corruption detected
964    Corruption,
965}
966
967impl std::fmt::Display for AudioBufferIssue {
968    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
969        match self {
970            AudioBufferIssue::Underrun => write!(f, "underrun"),
971            AudioBufferIssue::Overrun => write!(f, "overrun"),
972            AudioBufferIssue::Corruption => write!(f, "corruption"),
973        }
974    }
975}
976
977/// Error context for additional debugging information
978#[derive(Debug, Clone)]
979pub struct ErrorContext {
980    /// Module where error occurred
981    pub module: String,
982    /// Function where error occurred
983    pub function: String,
984    /// Line number (if available)
985    pub line: Option<u32>,
986    /// Additional context data
987    pub data: std::collections::HashMap<String, String>,
988    /// Recovery suggestions
989    pub recovery_suggestions: Vec<String>,
990    /// Related errors (for error chains)
991    pub related_errors: Vec<String>,
992}
993
994impl ErrorContext {
995    /// Create new error context
996    pub fn new(module: &str, function: &str) -> Self {
997        Self {
998            module: module.to_string(),
999            function: function.to_string(),
1000            line: None,
1001            data: std::collections::HashMap::new(),
1002            recovery_suggestions: Vec::new(),
1003            related_errors: Vec::new(),
1004        }
1005    }
1006
1007    /// Add context data
1008    pub fn with_data(mut self, key: &str, value: &str) -> Self {
1009        self.data.insert(key.to_string(), value.to_string());
1010        self
1011    }
1012
1013    /// Add recovery suggestion
1014    pub fn with_suggestion(mut self, suggestion: &str) -> Self {
1015        self.recovery_suggestions.push(suggestion.to_string());
1016        self
1017    }
1018
1019    /// Add related error
1020    pub fn with_related_error(mut self, error: &str) -> Self {
1021        self.related_errors.push(error.to_string());
1022        self
1023    }
1024}
1025
1026impl Error {
1027    /// Create a generic configuration error from a string message
1028    pub fn config(message: &str) -> Self {
1029        Self::Config(ConfigError::InvalidParameter {
1030            parameter: "unknown".to_string(),
1031            message: message.to_string(),
1032            expected: "valid configuration".to_string(),
1033        })
1034    }
1035
1036    /// Create a generic processing error from a string message
1037    pub fn processing(message: &str) -> Self {
1038        Self::Processing(ProcessingError::ResourceExhausted {
1039            resource: "processing".to_string(),
1040            usage: 0,
1041            limit: 0,
1042        })
1043    }
1044
1045    /// Create a generic HRTF error from a string message
1046    pub fn hrtf(message: &str) -> Self {
1047        Self::Hrtf(HrtfError::InterpolationFailed {
1048            reason: message.to_string(),
1049        })
1050    }
1051
1052    /// Create a generic room error from a string message
1053    pub fn room(message: &str) -> Self {
1054        Self::Room(RoomError::RayTracingFailed {
1055            reason: message.to_string(),
1056        })
1057    }
1058
1059    /// Get error code for programmatic handling
1060    pub fn code(&self) -> ErrorCode {
1061        match self {
1062            Error::Config(config_err) => match config_err {
1063                ConfigError::InvalidParameter { .. } => ErrorCode::ConfigInvalidParameter,
1064                ConfigError::MissingParameter { .. } => ErrorCode::ConfigMissingParameter,
1065                ConfigError::ConflictingParameters { .. } => ErrorCode::ConfigConflictingParameters,
1066                ConfigError::FileNotFound { .. } => ErrorCode::ConfigFileNotFound,
1067            },
1068            // Legacy errors
1069            Error::LegacyConfig(_) => ErrorCode::ConfigInvalidParameter,
1070            Error::LegacyProcessing(_) => ErrorCode::ProcessingResourceExhausted,
1071            Error::LegacyHrtf(_) => ErrorCode::HrtfInterpolationFailed,
1072            Error::LegacyPosition(_) => ErrorCode::PositionInvalidCoordinates,
1073            Error::LegacyRoom(_) => ErrorCode::RoomRayTracingFailed,
1074            Error::LegacyAudio(_) => ErrorCode::AudioBufferIssue,
1075            Error::LegacyValidation(_) => ErrorCode::Generic,
1076            Error::Processing(processing_err) => match processing_err {
1077                ProcessingError::BufferSizeMismatch { .. } => {
1078                    ErrorCode::ProcessingBufferSizeMismatch
1079                }
1080                ProcessingError::SampleRateMismatch { .. } => {
1081                    ErrorCode::ProcessingSampleRateMismatch
1082                }
1083                ProcessingError::RealtimeViolation { .. } => ErrorCode::ProcessingRealtimeViolation,
1084                ProcessingError::ResourceExhausted { .. } => ErrorCode::ProcessingResourceExhausted,
1085            },
1086            Error::Hrtf(hrtf_err) => match hrtf_err {
1087                HrtfError::DatabaseLoadFailed { .. } => ErrorCode::HrtfDatabaseLoadFailed,
1088                HrtfError::InvalidPosition { .. } => ErrorCode::HrtfInvalidPosition,
1089                HrtfError::InterpolationFailed { .. } => ErrorCode::HrtfInterpolationFailed,
1090            },
1091            Error::Position(position_err) => match position_err {
1092                PositionError::InvalidCoordinates { .. } => ErrorCode::PositionInvalidCoordinates,
1093                PositionError::TrackingUnavailable { .. } => ErrorCode::PositionTrackingUnavailable,
1094                PositionError::CalibrationRequired { .. } => ErrorCode::PositionCalibrationRequired,
1095            },
1096            Error::Room(room_err) => match room_err {
1097                RoomError::InvalidDimensions { .. } => ErrorCode::RoomInvalidDimensions,
1098                RoomError::InvalidMaterial { .. } => ErrorCode::RoomInvalidMaterial,
1099                RoomError::RayTracingFailed { .. } => ErrorCode::RoomRayTracingFailed,
1100            },
1101            Error::Audio(audio_err) => match audio_err {
1102                AudioError::UnsupportedFormat { .. } => ErrorCode::AudioUnsupportedFormat,
1103                AudioError::ClippingDetected { .. } => ErrorCode::AudioClippingDetected,
1104                AudioError::BufferIssue { .. } => ErrorCode::AudioBufferIssue,
1105            },
1106            Error::Memory(memory_err) => match memory_err {
1107                MemoryError::OutOfMemory { .. } => ErrorCode::MemoryOutOfMemory,
1108                MemoryError::PoolExhausted { .. } => ErrorCode::MemoryPoolExhausted,
1109                MemoryError::CacheMiss { .. } => ErrorCode::MemoryCacheMiss,
1110            },
1111            Error::Gpu(gpu_err) => match gpu_err {
1112                GpuError::NotAvailable { .. } => ErrorCode::GpuNotAvailable,
1113                GpuError::Cuda { .. } => ErrorCode::GpuCudaError,
1114                GpuError::AllocationFailed { .. } => ErrorCode::GpuAllocationFailed,
1115            },
1116            Error::Platform(platform_err) => match platform_err {
1117                PlatformError::NotSupported { .. } => ErrorCode::PlatformNotSupported,
1118                PlatformError::SdkInitFailed { .. } => ErrorCode::PlatformSdkInitFailed,
1119                PlatformError::FeatureUnavailable { .. } => ErrorCode::PlatformFeatureUnavailable,
1120            },
1121            Error::Validation(validation_err) => match validation_err {
1122                ValidationError::SchemaFailed { .. } => ErrorCode::Generic,
1123                ValidationError::RangeError { .. } => ErrorCode::Generic,
1124                ValidationError::TestFailed { .. } => ErrorCode::Generic,
1125            },
1126            Error::Generic { code, .. } => *code,
1127            _ => ErrorCode::Generic,
1128        }
1129    }
1130
1131    /// Create error with context
1132    pub fn with_context(message: &str, code: ErrorCode, context: ErrorContext) -> Self {
1133        Error::Generic {
1134            message: message.to_string(),
1135            code,
1136            context: Some(Box::new(context)),
1137        }
1138    }
1139
1140    /// Check if error is recoverable
1141    pub fn is_recoverable(&self) -> bool {
1142        match self {
1143            Error::Config(_) => false, // Config errors usually require restart
1144            Error::Processing(ProcessingError::RealtimeViolation { .. }) => true,
1145            Error::Processing(ProcessingError::ResourceExhausted { .. }) => true,
1146            Error::Memory(_) => true, // Memory issues can often be resolved
1147            Error::Gpu(_) => true,    // GPU issues may be temporary
1148            Error::Position(PositionError::TrackingUnavailable { .. }) => true,
1149            Error::Audio(AudioError::BufferIssue { .. }) => true,
1150            _ => false,
1151        }
1152    }
1153
1154    /// Get recovery suggestions
1155    pub fn recovery_suggestions(&self) -> Vec<String> {
1156        match self {
1157            Error::Processing(ProcessingError::RealtimeViolation { max_ms, .. }) => {
1158                vec![
1159                    "Reduce buffer size to improve latency".to_string(),
1160                    format!("Increase processing timeout above {}ms", max_ms),
1161                    "Consider using GPU acceleration".to_string(),
1162                ]
1163            }
1164            Error::Memory(MemoryError::OutOfMemory { .. }) => {
1165                vec![
1166                    "Clear cache memory".to_string(),
1167                    "Reduce buffer pool sizes".to_string(),
1168                    "Close unused audio sources".to_string(),
1169                ]
1170            }
1171            Error::Gpu(GpuError::NotAvailable { .. }) => {
1172                vec![
1173                    "Fallback to CPU processing".to_string(),
1174                    "Check GPU drivers".to_string(),
1175                    "Verify CUDA installation".to_string(),
1176                ]
1177            }
1178            Error::Generic {
1179                context: Some(ctx), ..
1180            } => ctx.recovery_suggestions.clone(),
1181            _ => vec!["Check configuration and retry".to_string()],
1182        }
1183    }
1184}
1185
1186/// Prelude module for convenient imports
1187pub mod prelude {
1188    pub use crate::{
1189        ambisonics::{
1190            channel_count, AmbisonicsDecoder, AmbisonicsEncoder, AmbisonicsOrder,
1191            AmbisonicsProcessor, ChannelOrdering, NormalizationScheme, SpeakerConfiguration,
1192            SphericalCoordinate, SphericalHarmonics,
1193        },
1194        beamforming::{
1195            AdaptationConfig, BeamPattern, BeamformerWeights, BeamformingAlgorithm,
1196            BeamformingConfig, BeamformingProcessor, DoaResult, SpatialSmoothingConfig,
1197        },
1198        binaural::{BinauralConfig, BinauralMetrics, BinauralRenderer, SourceType},
1199        compression::{
1200            AdaptiveParams, CompressedFrame, CompressionCodec, CompressionQuality,
1201            CompressionStats, PerceptualParams, SourceClustering, SpatialCompressionConfig,
1202            SpatialCompressor, SpatialMetadata, SpatialParams, TemporalMasking,
1203        },
1204        config::{SpatialConfig, SpatialConfigBuilder},
1205        core::{SpatialProcessor, SpatialProcessorBuilder},
1206        gaming::{
1207            console, AttenuationCurve, AttenuationSettings, AudioCategory, GameAudioSource,
1208            GameEngine, GamingAudioManager, GamingConfig, GamingMetrics,
1209        },
1210        gestures::{
1211            AudioAction, GestureBuilder, GestureConfidence, GestureConfig, GestureController,
1212            GestureData, GestureDirection, GestureEvent, GestureEventType,
1213            GestureRecognitionMethod, GestureType, Hand,
1214        },
1215        gpu::{
1216            GpuAmbisonics, GpuConfig, GpuConvolution, GpuDevice, GpuResourceManager, GpuSpatialMath,
1217        },
1218        haptic::{
1219            AudioHapticMapping, DistanceAttenuation, HapticAccessibilitySettings,
1220            HapticAudioConfig, HapticAudioProcessor, HapticCapabilities, HapticComfortSettings,
1221            HapticDevice, HapticEffectType, HapticElement, HapticMetrics, HapticPattern,
1222            PatternStyle,
1223        },
1224        hrtf::{
1225            ai_personalization::{
1226                AdaptationStrategy, AiHrtfPersonalizer, AnthropometricMeasurements,
1227                HrtfModifications, PerceptualFeedback, PersonalizationConfig,
1228                PersonalizationMetadata, PersonalizedHrtf, TrainingResults,
1229            },
1230            HrtfDatabase, HrtfProcessor,
1231        },
1232        multiuser::{
1233            AccessibilitySettings, AcousticSettings, AudioEffect, AudioEffectsProcessor,
1234            AudioQualityMetrics, AudioSourceType, BandwidthSettings, CodecState, CodecTiming,
1235            CompensationMethod, ConnectionStatus, DirectionalPattern, DisconnectReason,
1236            InterpolationMethod, LatencyCompensator, LowBandwidthMode, MicrophoneSettings,
1237            MixerConfig, MultiUserAttenuationCurve, MultiUserAudioProcessor, MultiUserAudioSource,
1238            MultiUserConfig, MultiUserConfigBuilder, MultiUserEnvironment, MultiUserEvent,
1239            MultiUserMetrics, MultiUserUser, NetworkEventType, NetworkStats, OptimizationLevel,
1240            Permission, PermissionSystem, PositionInterpolator, PositionSnapshot, RoomId,
1241            SourceAccessControl, SourceId, SourceProcessingState, SourceQualitySettings,
1242            SourceVisibility, SpatialAudioMixer, SpatialProperties, SpatialZone,
1243            SynchronizationManager, SynchronizedClock, UserId, UserRole, VadAlgorithm, VadState,
1244            VadThresholds, VoiceActivityDetector, ZoneAudioProperties, ZoneBounds, ZoneType,
1245        },
1246        neural::{
1247            AdaptiveQualityController, AugmentationConfig, ConvolutionalModel, FeedforwardModel,
1248            LossFunction, NeuralInputFeatures, NeuralModel, NeuralModelType,
1249            NeuralPerformanceMetrics, NeuralSpatialConfig, NeuralSpatialConfigBuilder,
1250            NeuralSpatialOutput, NeuralSpatialProcessor, NeuralTrainer, NeuralTrainingResults,
1251            OptimizerType, RealtimeConstraints, TrainingConfig, TransformerModel,
1252        },
1253        performance::{
1254            PerformanceConfig, PerformanceMetrics, PerformanceReport, PerformanceSummary,
1255            PerformanceTargetResult, PerformanceTestSuite, ResourceMonitor, ResourceStatistics,
1256        },
1257        platforms::{
1258            ARCorePlatform, ARKitPlatform, DeviceInfo, EyeData, EyeTrackingData, GenericPlatform,
1259            HandData, HandGesture, HandTrackingData, OculusPlatform, PlatformCapabilities,
1260            PlatformFactory, PlatformIntegration, PlatformTrackingData, PoseData, TrackingConfig,
1261            TrackingQuality, TrackingState, WMRPlatform,
1262        },
1263        plugins::{
1264            PluginCapabilities, PluginConfig, PluginManager, PluginParameter, PluginParameters,
1265            PluginState, ProcessingChain, ProcessingContext, ReverbPlugin, SpatialPlugin,
1266        },
1267        position::{
1268            advanced_prediction::{
1269                AdaptationPhase, AdvancedPredictiveTracker, ModelSelectionStrategy, MotionPattern,
1270                MotionPatternType, PatternRecognitionConfig, PredictedPosition, PredictionMetrics,
1271                PredictionModelType, PredictiveTrackingConfig,
1272            },
1273            Box3D, CalibrationData, ComfortSettings, DopplerProcessor, DynamicSource,
1274            DynamicSourceManager, HeadTracker, Listener, ListenerMovementSystem, MotionPredictor,
1275            MotionSnapshot, MovementConstraints, MovementMetrics, NavigationMode,
1276            OcclusionDetector, OcclusionMaterial, OcclusionMethod, OcclusionResult, PlatformData,
1277            PlatformType, SoundSource, SpatialSourceManager,
1278        },
1279        room::{
1280            adaptive_acoustics::{
1281                AdaptationAction, AdaptationController, AdaptationMetrics, AdaptationTrigger,
1282                AdaptiveAcousticEnvironment, AdaptiveAcousticsConfig, EnvironmentSensors,
1283                EnvironmentSnapshot, EnvironmentType, SensorConfig, UserFeedback,
1284            },
1285            ConnectionAcousticProperties, ConnectionState, ConnectionType, GlobalAcousticConfig,
1286            MultiRoomEnvironment, Room, RoomAcoustics, RoomConnection, RoomSimulator,
1287        },
1288        smart_speakers::{
1289            ArrayMetrics, ArrayTopology, AudioFormat, AudioRoute, AudioRouter, AudioSource,
1290            AudioSpecs, CalibrationEngine, CalibrationMethod, CalibrationResults,
1291            CalibrationStatus, ClockSource, CompressionConfig, DeviceFilter, DirectivityPattern,
1292            DiscoveryProtocol, DiscoveryService, DspFeature, EQFilter, FilterType, LimitingConfig,
1293            MixSettings, NetworkConfig, NetworkInfo, NetworkProtocol, ProcessingConfig,
1294            ProcessingStep, RoomCorrection, SmartSpeaker, SpeakerArrayConfig,
1295            SpeakerArrayConfigBuilder, SpeakerArrayManager, SpeakerCapabilities, SyncConfig,
1296        },
1297        technical_testing::{
1298            create_standard_technical_configs, LatencyAnalysis, MemoryConstraints,
1299            PlatformAnalysis, PlatformTestResult, StabilityAnalysis, StressTestParams,
1300            TechnicalSuccessCriteria, TechnicalTestConfig, TechnicalTestParameters,
1301            TechnicalTestReport, TechnicalTestResult, TechnicalTestSuite, TechnicalTestType,
1302            TestOutcome,
1303        },
1304        telepresence::{
1305            AcousticEchoSettings, AcousticMatchingSettings, AcousticProperties,
1306            AdaptiveQualitySettings, AirAbsorptionSettings, AnonymizationMethod,
1307            AnonymizationSettings, AudioCodec, AudioDeviceConfig, AudioEnhancementSettings,
1308            AudioFormat as TelepresenceAudioFormat, AudioMetadata, AudioPresenceSettings,
1309            AudioQualityPreferences, AudioQualitySettings, BandwidthConstraints,
1310            BandwidthExtensionSettings, CodecPreferences, CompressionSettings,
1311            ConsentManagementSettings, CrossRoomSettings, DataCollectionSettings,
1312            DistanceModelingSettings, DopplerEffectsSettings, EchoCancellationSettings,
1313            EnvironmentalAwarenessSettings, EqualizationSettings, HeadTrackingSettings,
1314            HrtfPersonalizationSettings, NetworkSettings, NoiseSuppressionSettings, Orientation,
1315            PresenceIndicatorSettings, PrivacySettings, QualityLevel, QualitySettings,
1316            ReceivedAudio, RoomSimulationSettings, SessionJoinResult, SessionState,
1317            SessionStatistics, SpatialTelepresenceSettings, TelepresenceAudioSettings,
1318            TelepresenceConfig, TelepresenceProcessor, TelepresenceSession,
1319            TrackingPredictionSettings, UserConfig, VadSettings, Velocity, VirtualRoomParameters,
1320            VisualPresenceSettings, VoiceProcessingSettings, VoiceSpatializationSettings,
1321        },
1322        types::{
1323            AudioChannel, BinauraAudio, Position3D, SIMDSpatialOps, SpatialEffect, SpatialRequest,
1324            SpatialResult,
1325        },
1326        validation::{
1327            create_standard_test_configs, create_test_subjects, AccuracyMetrics, AudioExpertise,
1328            ExperienceLevel, Gender, HearingAbility, PerceptualTestSuite, PopulationAnalysis,
1329            ResponseData, StimulusData, SubjectiveRatings, SuccessCriteria, TestParameters,
1330            TestStatistics, TestSubject, ValidationReport, ValidationTestConfig,
1331            ValidationTestResult, ValidationTestType,
1332        },
1333        visual_audio::{
1334            AnimationParams, AnimationType, AudioVisualMapping, ColorRGBA, ColorScheme,
1335            ColorSchemeType, DirectionZone, DirectionalCueMapping, EasingFunction,
1336            EventTriggerMapping, FrequencyVisualMapping, OnsetTrigger, RhythmTrigger, ScalingCurve,
1337            ShapeType, SilenceTrigger, SpectralTrigger, VisualAccessibilitySettings,
1338            VisualAudioConfig, VisualAudioMetrics, VisualAudioProcessor, VisualDisplay,
1339            VisualDisplayCapabilities, VisualDistanceAttenuation, VisualEffect, VisualElement,
1340            VisualElementType, VisualPerformanceSettings, VisualResourceUsage, VisualSyncSettings,
1341        },
1342        wfs::{
1343            ArrayGeometry, PreEmphasisConfig, WfsArrayBuilder, WfsConfig, WfsDrivingFunction,
1344            WfsProcessor, WfsSource, WfsSourceType,
1345        },
1346        Error, Result,
1347    };
1348}