voirs-spatial 0.1.0-rc.1

3D spatial audio and HRTF processing for VoiRS
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
//! GPU Acceleration for Spatial Audio Processing
//!
//! This module provides GPU-accelerated implementations of computationally intensive
//! spatial audio operations using CUDA or other GPU compute platforms.

use crate::{Error, Position3D, Result};
use candle_core::{DType, Device, Tensor};
use scirs2_core::ndarray::{Array1, Array2, Array3};
use serde::{Deserialize, Serialize};
use std::sync::Arc;

/// GPU device configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GpuConfig {
    /// Prefer GPU over CPU when available
    pub prefer_gpu: bool,
    /// Device ID to use (for multi-GPU systems)
    pub device_id: usize,
    /// Memory limit in bytes (0 = no limit)
    pub memory_limit: usize,
    /// Batch size for parallel processing
    pub batch_size: usize,
    /// Enable mixed precision computation
    pub mixed_precision: bool,
}

impl Default for GpuConfig {
    fn default() -> Self {
        Self {
            prefer_gpu: true,
            device_id: 0,
            memory_limit: 0, // No limit
            batch_size: 32,
            mixed_precision: true,
        }
    }
}

/// GPU device wrapper with automatic fallback
pub struct GpuDevice {
    device: Device,
    config: GpuConfig,
    is_gpu: bool,
}

impl GpuDevice {
    /// Create a new GPU device with automatic selection
    pub fn new(config: GpuConfig) -> Result<Self> {
        let device = if config.prefer_gpu {
            match std::panic::catch_unwind(|| Device::cuda_if_available(config.device_id)) {
                Ok(Ok(device)) => device,
                _ => {
                    tracing::warn!("GPU not available, falling back to CPU");
                    Device::Cpu
                }
            }
        } else {
            Device::Cpu
        };

        let is_gpu = matches!(device, Device::Cuda(_));

        if is_gpu {
            tracing::info!(
                "Using GPU device {} for spatial audio processing",
                config.device_id
            );
        } else {
            tracing::info!("Using CPU for spatial audio processing");
        }

        Ok(Self {
            device,
            config,
            is_gpu,
        })
    }

    /// Get the underlying device
    pub fn device(&self) -> &Device {
        &self.device
    }

    /// Check if using GPU
    pub fn is_gpu(&self) -> bool {
        self.is_gpu
    }

    /// Get device configuration
    pub fn config(&self) -> &GpuConfig {
        &self.config
    }
}

/// GPU-accelerated convolution processor for HRTF and reverb
pub struct GpuConvolution {
    device: Arc<GpuDevice>,
    fft_size: usize,
    hop_size: usize,
    // Pre-allocated buffers for efficient processing
    input_buffer: Option<Tensor>,
    output_buffer: Option<Tensor>,
    frequency_domain_buffer: Option<Tensor>,
}

impl GpuConvolution {
    /// Create new GPU convolution processor
    pub fn new(device: Arc<GpuDevice>, fft_size: usize, hop_size: usize) -> Result<Self> {
        Ok(Self {
            device,
            fft_size,
            hop_size,
            input_buffer: None,
            output_buffer: None,
            frequency_domain_buffer: None,
        })
    }

    /// Process convolution with impulse response on GPU
    pub fn convolve(
        &mut self,
        input: &Array1<f32>,
        impulse_response: &Array1<f32>,
    ) -> Result<Array1<f32>> {
        let device = self.device.device();

        // Convert input to tensor - handle non-contiguous arrays properly
        let input_slice = input.as_slice().ok_or_else(|| {
            Error::LegacyProcessing(
                "Input array is not contiguous in memory, cannot create tensor efficiently"
                    .to_string(),
            )
        })?;
        let input_tensor = Tensor::from_slice(input_slice, input.len(), device)
            .map_err(|e| Error::LegacyProcessing(format!("Failed to create input tensor: {e}")))?;

        let ir_slice = impulse_response.as_slice().ok_or_else(|| {
            Error::LegacyProcessing(
                "Impulse response array is not contiguous in memory, cannot create tensor efficiently"
                    .to_string(),
            )
        })?;
        let ir_tensor = Tensor::from_slice(ir_slice, impulse_response.len(), device)
            .map_err(|e| Error::LegacyProcessing(format!("Failed to create IR tensor: {e}")))?;

        // Perform FFT-based convolution
        let result = self.fft_convolve(&input_tensor, &ir_tensor)?;

        // Convert back to ndarray
        let result_vec: Vec<f32> = result.to_vec1().map_err(|e| {
            Error::LegacyProcessing(format!("Failed to convert result tensor: {e}"))
        })?;

        Ok(Array1::from_vec(result_vec))
    }

    /// FFT-based convolution implementation
    #[allow(clippy::single_range_in_vec_init)]
    fn fft_convolve(&self, input: &Tensor, impulse_response: &Tensor) -> Result<Tensor> {
        // For now, implement basic convolution
        // In practice, would use proper FFT operations
        let device = self.device.device();

        let input_len = input
            .dims1()
            .map_err(|e| Error::LegacyProcessing(format!("Invalid input dimensions: {e}")))?;
        let ir_len = impulse_response
            .dims1()
            .map_err(|e| Error::LegacyProcessing(format!("Invalid IR dimensions: {e}")))?;

        let output_len = input_len + ir_len - 1;

        // Create output tensor
        let zeros = Tensor::zeros((output_len,), DType::F32, device)
            .map_err(|e| Error::LegacyProcessing(format!("Failed to create output tensor: {e}")))?;

        // Simple direct convolution for now (would use FFT for efficiency)
        let mut result = zeros;
        for i in 0..input_len {
            for j in 0..ir_len {
                let idx = i + j;
                if idx < output_len {
                    let input_val = input
                        .get(i)
                        .map_err(|e| Error::LegacyProcessing(format!("Input access error: {e}")))?;
                    let ir_val = impulse_response
                        .get(j)
                        .map_err(|e| Error::LegacyProcessing(format!("IR access error: {e}")))?;
                    let current = result.get(idx).map_err(|e| {
                        Error::LegacyProcessing(format!("Result access error: {e}"))
                    })?;
                    let new_val = (current + (input_val * ir_val))?;
                    result = result.slice_assign(&[idx..idx + 1], &new_val)?;
                }
            }
        }

        Ok(result)
    }

    /// Batch process multiple convolutions
    pub fn convolve_batch(
        &mut self,
        inputs: &Array2<f32>,
        impulse_responses: &Array2<f32>,
    ) -> Result<Array2<f32>> {
        let batch_size = inputs.shape()[0];
        let input_len = inputs.shape()[1];
        let ir_len = impulse_responses.shape()[1];
        let output_len = input_len + ir_len - 1;

        let mut results = Array2::zeros((batch_size, output_len));

        // Process in batches for GPU efficiency
        for i in 0..batch_size {
            let input = inputs.row(i).to_owned();
            let ir = impulse_responses.row(i).to_owned();
            let result = self.convolve(&input, &ir)?;
            results.row_mut(i).assign(&result);
        }

        Ok(results)
    }
}

/// GPU-accelerated distance calculations for spatial audio
pub struct GpuSpatialMath {
    device: Arc<GpuDevice>,
}

impl GpuSpatialMath {
    /// Create new GPU spatial math processor
    pub fn new(device: Arc<GpuDevice>) -> Self {
        Self { device }
    }

    /// Calculate distances between listener and multiple sources
    pub fn calculate_distances(
        &self,
        listener_pos: &Position3D,
        source_positions: &[Position3D],
    ) -> Result<Array1<f32>> {
        let device = self.device.device();
        let num_sources = source_positions.len();

        // Convert positions to tensors
        let listener_tensor = Tensor::from_slice(
            &[listener_pos.x, listener_pos.y, listener_pos.z],
            (3,),
            device,
        )
        .map_err(|e| Error::LegacyProcessing(format!("Failed to create listener tensor: {e}")))?;

        let source_data: Vec<f32> = source_positions
            .iter()
            .flat_map(|pos| vec![pos.x, pos.y, pos.z])
            .collect();

        let source_tensor = Tensor::from_slice(&source_data, (num_sources, 3), device)
            .map_err(|e| Error::LegacyProcessing(format!("Failed to create source tensor: {e}")))?;

        // Calculate differences
        let listener_expanded = listener_tensor.unsqueeze(0)?.expand((num_sources, 3))?;

        let differences = (&source_tensor - &listener_expanded)?;

        // Calculate squared distances
        let squared_diffs = differences.sqr()?;
        let distances_squared = squared_diffs.sum(1)?;

        // Take square root
        let distances = distances_squared.sqrt()?;

        // Convert back to ndarray
        let result_vec: Vec<f32> = distances
            .to_vec1()
            .map_err(|e| Error::LegacyProcessing(format!("Failed to convert distances: {e}")))?;

        Ok(Array1::from_vec(result_vec))
    }

    /// Calculate batch of dot products
    pub fn batch_dot_product(
        &self,
        vectors_a: &Array2<f32>,
        vectors_b: &Array2<f32>,
    ) -> Result<Array1<f32>> {
        let device = self.device.device();

        if vectors_a.shape() != vectors_b.shape() {
            return Err(Error::LegacyProcessing(
                "Vector arrays must have same shape".to_string(),
            ));
        }

        let batch_size = vectors_a.shape()[0];
        let vector_len = vectors_a.shape()[1];

        // Convert to tensors - handle non-contiguous arrays properly
        let slice_a = vectors_a.as_slice().ok_or_else(|| {
            Error::LegacyProcessing(
                "Vector array A is not contiguous in memory, cannot create tensor efficiently"
                    .to_string(),
            )
        })?;
        let tensor_a = Tensor::from_slice(slice_a, (batch_size, vector_len), device)
            .map_err(|e| Error::LegacyProcessing(format!("Failed to create tensor A: {e}")))?;

        let slice_b = vectors_b.as_slice().ok_or_else(|| {
            Error::LegacyProcessing(
                "Vector array B is not contiguous in memory, cannot create tensor efficiently"
                    .to_string(),
            )
        })?;
        let tensor_b = Tensor::from_slice(slice_b, (batch_size, vector_len), device)
            .map_err(|e| Error::LegacyProcessing(format!("Failed to create tensor B: {e}")))?;

        // Element-wise multiplication and sum along vector dimension
        let products = (&tensor_a * &tensor_b)?;
        let dot_products = products.sum(1)?;

        // Convert result
        let result_vec: Vec<f32> = dot_products
            .to_vec1()
            .map_err(|e| Error::LegacyProcessing(format!("Failed to convert dot products: {e}")))?;

        Ok(Array1::from_vec(result_vec))
    }

    /// Normalize batch of vectors
    pub fn normalize_batch(&self, vectors: &Array2<f32>) -> Result<Array2<f32>> {
        let device = self.device.device();
        let batch_size = vectors.shape()[0];
        let vector_len = vectors.shape()[1];

        // Convert to tensor - handle non-contiguous arrays properly
        let slice = vectors.as_slice().ok_or_else(|| {
            Error::LegacyProcessing(
                "Vector array is not contiguous in memory, cannot create tensor efficiently"
                    .to_string(),
            )
        })?;
        let tensor = Tensor::from_slice(slice, (batch_size, vector_len), device)
            .map_err(|e| Error::LegacyProcessing(format!("Failed to create tensor: {e}")))?;

        // Calculate magnitudes
        let squared = tensor.sqr()?;
        let magnitudes_squared = squared.sum_keepdim(1)?;
        let magnitudes = magnitudes_squared.sqrt()?;

        // Avoid division by zero
        let epsilon = Tensor::from_slice(&[1e-8f32], (1,), device)?.expand((batch_size, 1))?;
        let safe_magnitudes = magnitudes.maximum(&epsilon)?;

        // Normalize
        let normalized = tensor.broadcast_div(&safe_magnitudes)?;

        // Convert back
        let result_vec: Vec<f32> = normalized
            .to_vec2()
            .map_err(|e| {
                Error::LegacyProcessing(format!("Failed to convert normalized vectors: {e}"))
            })?
            .into_iter()
            .flatten()
            .collect();

        let result = Array2::from_shape_vec((batch_size, vector_len), result_vec)
            .map_err(|e| Error::LegacyProcessing(format!("Failed to reshape result: {e}")))?;

        Ok(result)
    }
}

/// GPU-accelerated ambisonics processor
pub struct GpuAmbisonics {
    device: Arc<GpuDevice>,
    order: u32,
    encoding_matrices: Option<Tensor>,
    decoding_matrices: Option<Tensor>,
}

impl GpuAmbisonics {
    /// Create new GPU ambisonics processor
    pub fn new(device: Arc<GpuDevice>, order: u32) -> Result<Self> {
        Ok(Self {
            device,
            order,
            encoding_matrices: None,
            decoding_matrices: None,
        })
    }

    /// Pre-compute encoding matrices for common source positions
    pub fn precompute_encoding_matrices(&mut self, source_positions: &[Position3D]) -> Result<()> {
        let device = self.device.device();
        let num_sources = source_positions.len();
        let num_channels = ((self.order + 1) * (self.order + 1)) as usize;

        // Calculate spherical harmonics for all positions
        let mut encoding_data = Vec::with_capacity(num_sources * num_channels);

        for position in source_positions {
            // Convert to spherical coordinates
            let distance =
                (position.x * position.x + position.y * position.y + position.z * position.z)
                    .sqrt();
            let azimuth = position.y.atan2(position.x);
            let elevation = (position.z / distance.max(1e-8)).asin();

            // Calculate spherical harmonics (simplified)
            for l in 0..=self.order {
                for m in -(l as i32)..=(l as i32) {
                    let coeff = self.spherical_harmonic(l, m, azimuth, elevation);
                    encoding_data.push(coeff);
                }
            }
        }

        self.encoding_matrices = Some(
            Tensor::from_slice(&encoding_data, (num_sources, num_channels), device).map_err(
                |e| Error::LegacyProcessing(format!("Failed to create encoding matrices: {e}")),
            )?,
        );

        Ok(())
    }

    /// Simplified spherical harmonic calculation
    fn spherical_harmonic(&self, l: u32, m: i32, azimuth: f32, elevation: f32) -> f32 {
        // Simplified implementation - in practice would use proper spherical harmonics
        let cos_el = elevation.cos();
        let sin_el = elevation.sin();

        match (l, m) {
            (0, 0) => 1.0,
            (1, -1) => sin_el * azimuth.sin(),
            (1, 0) => cos_el,
            (1, 1) => sin_el * azimuth.cos(),
            _ => 0.5, // Placeholder for higher orders
        }
    }

    /// Encode multiple sources to ambisonics using pre-computed matrices
    pub fn encode_batch(&self, audio_samples: &Array2<f32>) -> Result<Array2<f32>> {
        let encoding_matrices = self
            .encoding_matrices
            .as_ref()
            .ok_or_else(|| Error::LegacyProcessing("Encoding matrices not computed".to_string()))?;

        let device = self.device.device();
        let num_sources = audio_samples.shape()[0];
        let num_samples = audio_samples.shape()[1];
        let num_channels = ((self.order + 1) * (self.order + 1)) as usize;

        // Convert audio to tensor - handle non-contiguous arrays properly
        let audio_slice = audio_samples.as_slice().ok_or_else(|| {
            Error::LegacyProcessing(
                "Audio samples array is not contiguous in memory, cannot create tensor efficiently"
                    .to_string(),
            )
        })?;
        let audio_tensor = Tensor::from_slice(audio_slice, (num_sources, num_samples), device)
            .map_err(|e| Error::LegacyProcessing(format!("Failed to create audio tensor: {e}")))?;

        // Matrix multiplication: [num_channels, num_sources] × [num_sources, num_samples]
        let encoding_transposed = encoding_matrices.transpose(0, 1)?;
        let encoded = encoding_transposed.matmul(&audio_tensor)?;

        // Convert back to ndarray
        let result_vec: Vec<f32> = encoded
            .to_vec2()
            .map_err(|e| Error::LegacyProcessing(format!("Failed to convert encoded audio: {e}")))?
            .into_iter()
            .flatten()
            .collect();

        let result =
            Array2::from_shape_vec((num_channels, num_samples), result_vec).map_err(|e| {
                Error::LegacyProcessing(format!("Failed to reshape encoded audio: {e}"))
            })?;

        Ok(result)
    }
}

/// GPU resource manager for spatial audio
pub struct GpuResourceManager {
    devices: Vec<Arc<GpuDevice>>,
    current_device: usize,
    memory_usage: Vec<usize>,
}

impl GpuResourceManager {
    /// Create new GPU resource manager
    pub fn new(configs: Vec<GpuConfig>) -> Result<Self> {
        let mut devices = Vec::new();
        let mut memory_usage = Vec::new();

        for config in configs {
            let device = Arc::new(GpuDevice::new(config)?);
            devices.push(device);
            memory_usage.push(0);
        }

        if devices.is_empty() {
            // Create default CPU device
            devices.push(Arc::new(GpuDevice::new(GpuConfig {
                prefer_gpu: false,
                ..Default::default()
            })?));
            memory_usage.push(0);
        }

        Ok(Self {
            devices,
            current_device: 0,
            memory_usage,
        })
    }

    /// Get optimal device for processing
    pub fn get_optimal_device(&mut self) -> Arc<GpuDevice> {
        // Simple round-robin for now
        // In practice, would consider memory usage and load
        let device = self.devices[self.current_device].clone();
        self.current_device = (self.current_device + 1) % self.devices.len();
        device
    }

    /// Get all available devices
    pub fn get_all_devices(&self) -> &[Arc<GpuDevice>] {
        &self.devices
    }

    /// Get device count
    pub fn device_count(&self) -> usize {
        self.devices.len()
    }

    /// Get memory usage for device
    pub fn get_memory_usage(&self, device_id: usize) -> Option<usize> {
        self.memory_usage.get(device_id).copied()
    }
}

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

    #[test]
    fn test_gpu_config() {
        let config = GpuConfig::default();
        assert!(config.prefer_gpu);
        assert_eq!(config.batch_size, 32);
        assert!(config.mixed_precision);
    }

    #[test]
    fn test_gpu_device_creation() {
        let config = GpuConfig {
            prefer_gpu: false, // Force CPU for testing
            ..Default::default()
        };
        let device = GpuDevice::new(config).expect("Should successfully create GPU device");
        assert!(!device.is_gpu());
    }

    #[test]
    fn test_gpu_spatial_math() {
        let config = GpuConfig {
            prefer_gpu: false,
            ..Default::default()
        };
        let device =
            Arc::new(GpuDevice::new(config).expect("Should successfully create GPU device"));
        let math = GpuSpatialMath::new(device);

        let listener = Position3D::new(0.0, 0.0, 0.0);
        let sources = vec![
            Position3D::new(1.0, 0.0, 0.0),
            Position3D::new(0.0, 1.0, 0.0),
            Position3D::new(0.0, 0.0, 1.0),
        ];

        let distances = math
            .calculate_distances(&listener, &sources)
            .expect("Should successfully calculate distances");
        assert_eq!(distances.len(), 3);

        // All distances should be approximately 1.0
        for distance in distances.iter() {
            assert!((distance - 1.0).abs() < 1e-6);
        }
    }

    #[test]
    fn test_batch_dot_product() {
        let config = GpuConfig {
            prefer_gpu: false,
            ..Default::default()
        };
        let device =
            Arc::new(GpuDevice::new(config).expect("Should successfully create GPU device"));
        let math = GpuSpatialMath::new(device);

        let vectors_a = Array2::from_shape_vec(
            (2, 3),
            vec![
                1.0, 0.0, 0.0, // First vector
                0.0, 1.0, 0.0, // Second vector
            ],
        )
        .expect("Should successfully create Array2 from shape vec");

        let vectors_b = Array2::from_shape_vec(
            (2, 3),
            vec![
                1.0, 0.0, 0.0, // First vector
                0.0, 1.0, 0.0, // Second vector
            ],
        )
        .expect("Should successfully create Array2 from shape vec");

        let dot_products = math
            .batch_dot_product(&vectors_a, &vectors_b)
            .expect("Should successfully calculate batch dot product");
        assert_eq!(dot_products.len(), 2);

        // Both dot products should be 1.0
        for &dot_product in dot_products.iter() {
            assert!((dot_product - 1.0).abs() < 1e-6);
        }
    }

    #[test]
    fn test_normalize_batch() {
        let config = GpuConfig {
            prefer_gpu: false,
            ..Default::default()
        };
        let device =
            Arc::new(GpuDevice::new(config).expect("Should successfully create GPU device"));
        let math = GpuSpatialMath::new(device);

        let vectors = Array2::from_shape_vec(
            (2, 3),
            vec![
                2.0, 0.0, 0.0, // First vector
                0.0, 3.0, 0.0, // Second vector
            ],
        )
        .expect("Should successfully create Array2 from shape vec");

        let normalized = math
            .normalize_batch(&vectors)
            .expect("Should successfully normalize batch");
        assert_eq!(normalized.shape(), [2, 3]);

        // Check that vectors are normalized
        let first_magnitude =
            (normalized[[0, 0]].powi(2) + normalized[[0, 1]].powi(2) + normalized[[0, 2]].powi(2))
                .sqrt();
        let second_magnitude =
            (normalized[[1, 0]].powi(2) + normalized[[1, 1]].powi(2) + normalized[[1, 2]].powi(2))
                .sqrt();

        assert!((first_magnitude - 1.0).abs() < 1e-6);
        assert!((second_magnitude - 1.0).abs() < 1e-6);
    }

    #[test]
    fn test_gpu_convolution_creation() {
        let config = GpuConfig {
            prefer_gpu: false,
            ..Default::default()
        };
        let device =
            Arc::new(GpuDevice::new(config).expect("Should successfully create GPU device"));
        let convolution = GpuConvolution::new(device, 1024, 256)
            .expect("Should successfully create GPU convolution");
        assert_eq!(convolution.fft_size, 1024);
        assert_eq!(convolution.hop_size, 256);
    }

    #[test]
    fn test_gpu_resource_manager() {
        let configs = vec![GpuConfig {
            prefer_gpu: false,
            ..Default::default()
        }];

        let mut manager = GpuResourceManager::new(configs)
            .expect("Should successfully create GPU resource manager");
        assert_eq!(manager.device_count(), 1);

        let device = manager.get_optimal_device();
        assert!(!device.is_gpu());
    }

    #[test]
    fn test_gpu_ambisonics_creation() {
        let config = GpuConfig {
            prefer_gpu: false,
            ..Default::default()
        };
        let device =
            Arc::new(GpuDevice::new(config).expect("Should successfully create GPU device"));
        let ambisonics =
            GpuAmbisonics::new(device, 1).expect("Should successfully create GPU ambisonics");
        assert_eq!(ambisonics.order, 1);
    }

    #[test]
    fn test_spherical_harmonic_calculation() {
        let config = GpuConfig {
            prefer_gpu: false,
            ..Default::default()
        };
        let device =
            Arc::new(GpuDevice::new(config).expect("Should successfully create GPU device"));
        let ambisonics =
            GpuAmbisonics::new(device, 1).expect("Should successfully create GPU ambisonics");

        // Test basic spherical harmonics
        let coeff = ambisonics.spherical_harmonic(0, 0, 0.0, 0.0);
        assert_eq!(coeff, 1.0);

        let coeff = ambisonics.spherical_harmonic(1, 0, 0.0, 0.0);
        assert_eq!(coeff, 1.0); // cos(0) = 1
    }
}