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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
//! HRTF (Head-Related Transfer Function) processing for spatial audio

pub mod ai_personalization;
pub mod database;

use crate::types::Position3D;
pub use database::{
    DatabaseConfig, DatabaseStatistics, HrtfDatabaseManager, HrtfMeasurement as DbHrtfMeasurement,
    HrtfPosition, InterpolationMethod as DbInterpolationMethod, PersonalizedHrtf, StorageFormat,
};
use scirs2_core::ndarray::Array1;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;

/// HRTF processor for binaural audio rendering
pub struct HrtfProcessor {
    /// HRTF database
    database: Arc<HrtfDatabase>,
    /// Convolution buffer size
    #[allow(dead_code)]
    buffer_size: usize,
    /// Overlap-add state for left channel
    #[allow(dead_code)]
    overlap_left: Array1<f32>,
    /// Overlap-add state for right channel
    #[allow(dead_code)]
    overlap_right: Array1<f32>,
    /// Processing configuration
    config: HrtfConfig,
}

/// HRTF database containing impulse responses
#[derive(Clone)]
pub struct HrtfDatabase {
    /// Database metadata
    metadata: HrtfMetadata,
    /// Left ear impulse responses indexed by (azimuth, elevation)
    left_responses: HashMap<(i32, i32), Array1<f32>>,
    /// Right ear impulse responses indexed by (azimuth, elevation)
    right_responses: HashMap<(i32, i32), Array1<f32>>,
    /// Frequency responses (optional, for analysis)
    #[allow(dead_code)]
    #[allow(clippy::type_complexity)]
    frequency_responses: Option<HashMap<(i32, i32), (Array1<f32>, Array1<f32>)>>,
    /// Distance-dependent responses (if available)
    #[allow(dead_code)]
    #[allow(clippy::type_complexity)]
    distance_responses: Option<HashMap<(i32, i32, u32), (Array1<f32>, Array1<f32>)>>,
}

/// HRTF configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HrtfConfig {
    /// Sample rate
    pub sample_rate: u32,
    /// HRIR length
    pub hrir_length: usize,
    /// Crossfade time for smooth transitions
    pub crossfade_time: f32,
    /// Distance modeling enabled
    pub enable_distance_modeling: bool,
    /// Interpolation method
    pub interpolation_method: InterpolationMethod,
    /// Head circumference for personalization (in cm)
    pub head_circumference: Option<f32>,
    /// Near-field distance threshold (meters)
    pub near_field_distance: f32,
    /// Far-field distance threshold (meters)
    pub far_field_distance: f32,
    /// Enable air absorption
    pub enable_air_absorption: bool,
    /// Temperature for air absorption (Celsius)
    pub temperature: f32,
    /// Humidity for air absorption (relative, 0.0-1.0)
    pub humidity: f32,
    /// Enable SIMD optimizations
    pub enable_simd: bool,
}

/// HRTF database metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HrtfMetadata {
    /// Database name/source
    pub name: String,
    /// Sample rate of recordings
    pub sample_rate: u32,
    /// Length of impulse responses
    pub hrir_length: usize,
    /// Available azimuth angles (degrees)
    pub azimuth_angles: Vec<i32>,
    /// Available elevation angles (degrees)
    pub elevation_angles: Vec<i32>,
    /// Available distances (if any)
    pub distances: Option<Vec<f32>>,
    /// Subject information
    pub subject_info: Option<SubjectInfo>,
}

/// Subject information for personalized HRTF
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SubjectInfo {
    /// Head circumference in cm
    pub head_circumference: f32,
    /// Head width in cm
    pub head_width: f32,
    /// Head height in cm
    pub head_height: f32,
    /// Ear height in cm
    pub ear_height: f32,
    /// Shoulder width in cm
    pub shoulder_width: f32,
}

/// Interpolation methods for HRTF
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum InterpolationMethod {
    /// Nearest neighbor (fastest)
    Nearest,
    /// Bilinear interpolation
    Bilinear,
    /// Spherical interpolation
    Spherical,
    /// Weighted interpolation based on distance
    Weighted,
}

/// Spherical coordinates for HRTF lookup
#[derive(Debug, Clone, Copy)]
pub struct SphericalCoordinates {
    /// Azimuth angle in degrees (-180 to 180)
    pub azimuth: f32,
    /// Elevation angle in degrees (-90 to 90)
    pub elevation: f32,
    /// Distance in meters
    pub distance: f32,
}

/// HRTF measurement point
#[derive(Debug, Clone)]
pub struct HrtfMeasurement {
    /// Spherical coordinates
    pub coordinates: SphericalCoordinates,
    /// Left ear impulse response
    pub left_hrir: Array1<f32>,
    /// Right ear impulse response
    pub right_hrir: Array1<f32>,
}

impl HrtfProcessor {
    /// Create new HRTF processor
    pub async fn new(database_path: Option<PathBuf>) -> crate::Result<Self> {
        let database = if let Some(path) = database_path {
            HrtfDatabase::load_from_file(&path).await?
        } else {
            HrtfDatabase::load_default().await?
        };

        let config = HrtfConfig::default();
        let buffer_size = config.hrir_length * 2; // For overlap-add

        Ok(Self {
            database: Arc::new(database),
            buffer_size,
            overlap_left: Array1::zeros(buffer_size),
            overlap_right: Array1::zeros(buffer_size),
            config,
        })
    }

    /// Create new HRTF processor with default database
    pub async fn new_default() -> crate::Result<Self> {
        Self::new(None).await
    }

    /// Create HRTF processor with custom configuration
    pub async fn with_config(
        database_path: Option<PathBuf>,
        config: HrtfConfig,
    ) -> crate::Result<Self> {
        let database = if let Some(path) = database_path {
            HrtfDatabase::load_from_file(&path).await?
        } else {
            HrtfDatabase::load_default().await?
        };

        let buffer_size = config.hrir_length * 2;

        Ok(Self {
            database: Arc::new(database),
            buffer_size,
            overlap_left: Array1::zeros(buffer_size),
            overlap_right: Array1::zeros(buffer_size),
            config,
        })
    }

    /// Process audio with HRTF for a specific position
    pub async fn process_position(
        &self,
        input: &Array1<f32>,
        left_output: &mut Array1<f32>,
        right_output: &mut Array1<f32>,
        position: &Position3D,
    ) -> crate::Result<()> {
        // Convert Cartesian to spherical coordinates
        let spherical = self.cartesian_to_spherical(position);

        // Get HRTF for this position (with distance modeling if enabled)
        let (mut left_hrir, mut right_hrir) = self.get_hrtf(&spherical)?;

        // Apply distance modeling if enabled
        if self.config.enable_distance_modeling {
            self.apply_distance_modeling(&mut left_hrir, &mut right_hrir, &spherical)?;
        }

        // Apply air absorption if enabled
        if self.config.enable_air_absorption && spherical.distance > self.config.near_field_distance
        {
            self.apply_air_absorption(&mut left_hrir, &mut right_hrir, spherical.distance)?;
        }

        // Convolve input with processed HRIRs
        self.convolve_hrtf(input, &left_hrir, &right_hrir, left_output, right_output)?;

        Ok(())
    }

    /// Process audio with smooth position interpolation
    pub async fn process_position_smooth(
        &self,
        input: &Array1<f32>,
        left_output: &mut Array1<f32>,
        right_output: &mut Array1<f32>,
        start_position: &Position3D,
        end_position: &Position3D,
        progress: f32,
    ) -> crate::Result<()> {
        // Interpolate position
        let current_position = Position3D::new(
            start_position.x * (1.0 - progress) + end_position.x * progress,
            start_position.y * (1.0 - progress) + end_position.y * progress,
            start_position.z * (1.0 - progress) + end_position.z * progress,
        );

        self.process_position(input, left_output, right_output, &current_position)
            .await
    }

    /// Process audio stream with overlap-add for real-time applications
    pub async fn process_realtime_chunk(
        &mut self,
        input: &Array1<f32>,
        left_output: &mut Array1<f32>,
        right_output: &mut Array1<f32>,
        position: &Position3D,
    ) -> crate::Result<()> {
        let chunk_size = input.len();
        let hrir_len = self.config.hrir_length;

        // Ensure output buffers are correct size
        if left_output.len() != chunk_size || right_output.len() != chunk_size {
            return Err(crate::Error::processing(
                "Output buffer size must match input chunk size",
            ));
        }

        // Convert position to spherical coordinates
        let spherical = self.cartesian_to_spherical(position);

        // Get HRTF for this position
        let (left_hrir, right_hrir) = self.get_hrtf(&spherical)?;

        // Prepare extended buffers for convolution
        let conv_len = chunk_size + hrir_len - 1;
        let mut left_conv = Array1::zeros(conv_len);
        let mut right_conv = Array1::zeros(conv_len);

        // Perform convolution
        self.convolve_hrtf(
            input,
            &left_hrir,
            &right_hrir,
            &mut left_conv,
            &mut right_conv,
        )?;

        // Overlap-add with previous tail
        for i in 0..chunk_size {
            left_output[i] = left_conv[i] + self.overlap_left[i];
            right_output[i] = right_conv[i] + self.overlap_right[i];
        }

        // Store tail for next chunk
        self.overlap_left.fill(0.0);
        self.overlap_right.fill(0.0);

        let tail_start = chunk_size;
        let tail_len = (conv_len - chunk_size).min(self.overlap_left.len());

        for i in 0..tail_len {
            self.overlap_left[i] = left_conv[tail_start + i];
            self.overlap_right[i] = right_conv[tail_start + i];
        }

        Ok(())
    }

    /// Reset overlap-add buffers (call when starting new stream)
    pub fn reset_buffers(&mut self) {
        self.overlap_left.fill(0.0);
        self.overlap_right.fill(0.0);
    }

    /// Process multiple positions with crossfading between them
    pub async fn process_crossfade(
        &self,
        input: &Array1<f32>,
        left_output: &mut Array1<f32>,
        right_output: &mut Array1<f32>,
        positions: &[(Position3D, f32)], // (position, weight)
    ) -> crate::Result<()> {
        left_output.fill(0.0);
        right_output.fill(0.0);

        let mut temp_left = Array1::zeros(input.len());
        let mut temp_right = Array1::zeros(input.len());

        for (position, weight) in positions {
            // Process audio for this position
            self.process_position(input, &mut temp_left, &mut temp_right, position)
                .await?;

            // Add weighted contribution
            for i in 0..left_output.len() {
                left_output[i] += temp_left[i] * weight;
                right_output[i] += temp_right[i] * weight;
            }
        }

        Ok(())
    }

    /// Get HRTF for spherical coordinates
    fn get_hrtf(&self, coords: &SphericalCoordinates) -> crate::Result<(Array1<f32>, Array1<f32>)> {
        match self.config.interpolation_method {
            InterpolationMethod::Nearest => self.get_nearest_hrtf(coords),
            InterpolationMethod::Bilinear => self.get_bilinear_hrtf(coords),
            InterpolationMethod::Spherical => self.get_spherical_hrtf(coords),
            InterpolationMethod::Weighted => self.get_weighted_hrtf(coords),
        }
    }

    /// Get nearest neighbor HRTF
    fn get_nearest_hrtf(
        &self,
        coords: &SphericalCoordinates,
    ) -> crate::Result<(Array1<f32>, Array1<f32>)> {
        let azimuth = coords.azimuth.round() as i32;
        let elevation = coords.elevation.round() as i32;

        // Find closest available angles
        let closest_azimuth =
            self.find_closest_angle(azimuth, &self.database.metadata.azimuth_angles);
        let closest_elevation =
            self.find_closest_angle(elevation, &self.database.metadata.elevation_angles);

        let key = (closest_azimuth, closest_elevation);

        let left_hrir = self.database.left_responses.get(&key).ok_or_else(|| {
            crate::Error::LegacyHrtf(format!(
                "No HRTF found for angles ({closest_azimuth}, {closest_elevation})"
            ))
        })?;
        let right_hrir = self.database.right_responses.get(&key).ok_or_else(|| {
            crate::Error::LegacyHrtf(format!(
                "No HRTF found for angles ({closest_azimuth}, {closest_elevation})"
            ))
        })?;

        Ok((left_hrir.clone(), right_hrir.clone()))
    }

    /// Get bilinear interpolated HRTF
    fn get_bilinear_hrtf(
        &self,
        coords: &SphericalCoordinates,
    ) -> crate::Result<(Array1<f32>, Array1<f32>)> {
        // Find surrounding angles
        let az_low = self.find_lower_angle(
            coords.azimuth as i32,
            &self.database.metadata.azimuth_angles,
        );
        let az_high = self.find_higher_angle(
            coords.azimuth as i32,
            &self.database.metadata.azimuth_angles,
        );
        let el_low = self.find_lower_angle(
            coords.elevation as i32,
            &self.database.metadata.elevation_angles,
        );
        let el_high = self.find_higher_angle(
            coords.elevation as i32,
            &self.database.metadata.elevation_angles,
        );

        // Get four corner HRTFs
        let hrtf_00 = self.get_hrtf_at_angles(az_low, el_low)?;
        let hrtf_01 = self.get_hrtf_at_angles(az_low, el_high)?;
        let hrtf_10 = self.get_hrtf_at_angles(az_high, el_low)?;
        let hrtf_11 = self.get_hrtf_at_angles(az_high, el_high)?;

        // Calculate interpolation weights
        let az_weight = if az_high != az_low {
            (coords.azimuth - az_low as f32) / (az_high - az_low) as f32
        } else {
            0.0
        };
        let el_weight = if el_high != el_low {
            (coords.elevation - el_low as f32) / (el_high - el_low) as f32
        } else {
            0.0
        };

        // Bilinear interpolation
        let left_hrir = self.interpolate_hrtf(&[
            (&hrtf_00.0, (1.0 - az_weight) * (1.0 - el_weight)),
            (&hrtf_01.0, (1.0 - az_weight) * el_weight),
            (&hrtf_10.0, az_weight * (1.0 - el_weight)),
            (&hrtf_11.0, az_weight * el_weight),
        ]);

        let right_hrir = self.interpolate_hrtf(&[
            (&hrtf_00.1, (1.0 - az_weight) * (1.0 - el_weight)),
            (&hrtf_01.1, (1.0 - az_weight) * el_weight),
            (&hrtf_10.1, az_weight * (1.0 - el_weight)),
            (&hrtf_11.1, az_weight * el_weight),
        ]);

        Ok((left_hrir, right_hrir))
    }

    /// Get spherical interpolated HRTF using great circle distances
    fn get_spherical_hrtf(
        &self,
        coords: &SphericalCoordinates,
    ) -> crate::Result<(Array1<f32>, Array1<f32>)> {
        let mut left_sum = Array1::zeros(self.config.hrir_length);
        let mut right_sum = Array1::zeros(self.config.hrir_length);
        let mut weight_sum = 0.0;

        // Find the 4 nearest neighbors on the sphere
        let mut nearest_points = Vec::new();

        for (&(az, el), left_hrir) in &self.database.left_responses {
            let Some(right_hrir) = self.database.right_responses.get(&(az, el)) else {
                continue;
            };

            // Calculate great circle distance (spherical distance)
            let angular_distance = self.calculate_angular_distance(
                coords.azimuth,
                coords.elevation,
                az as f32,
                el as f32,
            );

            nearest_points.push((angular_distance, left_hrir, right_hrir));
        }

        // Sort by distance and take the 4 nearest
        nearest_points.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
        nearest_points.truncate(4);

        // Use inverse distance weighting with spherical consideration
        for (distance, left_hrir, right_hrir) in nearest_points {
            let weight = if distance < 0.01 {
                1.0 // Very close, use full weight
            } else {
                // Inverse distance weighting with spherical correction
                1.0 / (distance.to_radians().sin() + 0.001)
            };

            weight_sum += weight;

            for i in 0..left_sum.len().min(left_hrir.len()) {
                left_sum[i] += left_hrir[i] * weight;
                right_sum[i] += right_hrir[i] * weight;
            }
        }

        // Normalize
        if weight_sum > 0.0 {
            left_sum /= weight_sum;
            right_sum /= weight_sum;
        }

        Ok((left_sum, right_sum))
    }

    /// Get weighted interpolated HRTF
    fn get_weighted_hrtf(
        &self,
        coords: &SphericalCoordinates,
    ) -> crate::Result<(Array1<f32>, Array1<f32>)> {
        let mut left_sum = Array1::zeros(self.config.hrir_length);
        let mut right_sum = Array1::zeros(self.config.hrir_length);
        let mut weight_sum = 0.0;

        // Find nearby measurements and weight by distance
        for (&(az, el), left_hrir) in &self.database.left_responses {
            let Some(right_hrir) = self.database.right_responses.get(&(az, el)) else {
                continue;
            };

            // Calculate angular distance
            let angular_distance = self.calculate_angular_distance(
                coords.azimuth,
                coords.elevation,
                az as f32,
                el as f32,
            );

            if angular_distance < 30.0 {
                // Only use nearby measurements
                let weight = 1.0 / (1.0 + angular_distance);
                weight_sum += weight;

                for i in 0..left_sum.len() {
                    left_sum[i] += left_hrir[i] * weight;
                    right_sum[i] += right_hrir[i] * weight;
                }
            }
        }

        if weight_sum > 0.0 {
            left_sum /= weight_sum;
            right_sum /= weight_sum;
        }

        Ok((left_sum, right_sum))
    }

    /// Convolve input with HRTF using overlap-add FFT convolution
    fn convolve_hrtf(
        &self,
        input: &Array1<f32>,
        left_hrir: &Array1<f32>,
        right_hrir: &Array1<f32>,
        left_output: &mut Array1<f32>,
        right_output: &mut Array1<f32>,
    ) -> crate::Result<()> {
        let input_len = input.len();
        let hrir_len = left_hrir.len();

        // For small inputs or HRIRs, use time-domain convolution
        if input_len < 64 || hrir_len < 64 {
            return self.convolve_time_domain(
                input,
                left_hrir,
                right_hrir,
                left_output,
                right_output,
            );
        }

        // Use frequency-domain convolution for better performance
        self.convolve_frequency_domain(input, left_hrir, right_hrir, left_output, right_output)
    }

    /// Time-domain convolution for small inputs
    fn convolve_time_domain(
        &self,
        input: &Array1<f32>,
        left_hrir: &Array1<f32>,
        right_hrir: &Array1<f32>,
        left_output: &mut Array1<f32>,
        right_output: &mut Array1<f32>,
    ) -> crate::Result<()> {
        left_output.fill(0.0);
        right_output.fill(0.0);

        for (i, &sample) in input.iter().enumerate() {
            for (j, &hrir_sample) in left_hrir.iter().enumerate() {
                if i + j < left_output.len() {
                    left_output[i + j] += sample * hrir_sample;
                }
            }
            for (j, &hrir_sample) in right_hrir.iter().enumerate() {
                if i + j < right_output.len() {
                    right_output[i + j] += sample * hrir_sample;
                }
            }
        }

        Ok(())
    }

    /// Frequency-domain convolution using FFT
    fn convolve_frequency_domain(
        &self,
        input: &Array1<f32>,
        left_hrir: &Array1<f32>,
        right_hrir: &Array1<f32>,
        left_output: &mut Array1<f32>,
        right_output: &mut Array1<f32>,
    ) -> crate::Result<()> {
        let input_len = input.len();
        let hrir_len = left_hrir.len();
        let conv_len = input_len + hrir_len - 1;

        // Find next power of 2 for FFT
        let fft_len = conv_len.next_power_of_two();

        // Convert to f64 and create complex input for FFT
        let input_complex: Vec<scirs2_core::Complex<f64>> = input
            .iter()
            .map(|&x| scirs2_core::Complex::new(x as f64, 0.0))
            .chain(std::iter::repeat(scirs2_core::Complex::new(0.0, 0.0)))
            .take(fft_len)
            .collect();

        let left_hrir_complex: Vec<scirs2_core::Complex<f64>> = left_hrir
            .iter()
            .map(|&x| scirs2_core::Complex::new(x as f64, 0.0))
            .chain(std::iter::repeat(scirs2_core::Complex::new(0.0, 0.0)))
            .take(fft_len)
            .collect();

        let right_hrir_complex: Vec<scirs2_core::Complex<f64>> = right_hrir
            .iter()
            .map(|&x| scirs2_core::Complex::new(x as f64, 0.0))
            .chain(std::iter::repeat(scirs2_core::Complex::new(0.0, 0.0)))
            .take(fft_len)
            .collect();

        // Perform FFT
        let input_spectrum = scirs2_fft::fft(&input_complex, None)
            .map_err(|e| crate::Error::LegacyProcessing(format!("FFT error: {e}")))?;

        let left_hrir_spectrum = scirs2_fft::fft(&left_hrir_complex, None)
            .map_err(|e| crate::Error::LegacyProcessing(format!("FFT error: {e}")))?;

        let right_hrir_spectrum = scirs2_fft::fft(&right_hrir_complex, None)
            .map_err(|e| crate::Error::LegacyProcessing(format!("FFT error: {e}")))?;

        // Complex multiplication in frequency domain
        let left_result_spectrum: Vec<scirs2_core::Complex<f64>> = input_spectrum
            .iter()
            .zip(left_hrir_spectrum.iter())
            .map(|(a, b)| a * b)
            .collect();

        let right_result_spectrum: Vec<scirs2_core::Complex<f64>> = input_spectrum
            .iter()
            .zip(right_hrir_spectrum.iter())
            .map(|(a, b)| a * b)
            .collect();

        // IFFT back to time domain
        let left_result_time = scirs2_fft::ifft(&left_result_spectrum, None)
            .map_err(|e| crate::Error::LegacyProcessing(format!("IFFT error: {e}")))?;

        let right_result_time = scirs2_fft::ifft(&right_result_spectrum, None)
            .map_err(|e| crate::Error::LegacyProcessing(format!("IFFT error: {e}")))?;

        // Copy to output (no additional scaling needed as scirs2_fft handles it)
        let output_len = left_output.len().min(conv_len);

        for i in 0..output_len {
            left_output[i] = left_result_time[i].re as f32;
            right_output[i] = right_result_time[i].re as f32;
        }

        Ok(())
    }

    /// Convert Cartesian to spherical coordinates
    fn cartesian_to_spherical(&self, position: &Position3D) -> SphericalCoordinates {
        let distance =
            (position.x * position.x + position.y * position.y + position.z * position.z).sqrt();

        let azimuth = if distance > 0.0 {
            position.z.atan2(position.x).to_degrees()
        } else {
            0.0
        };

        let elevation = if distance > 0.0 {
            (position.y / distance).asin().to_degrees()
        } else {
            0.0
        };

        SphericalCoordinates {
            azimuth,
            elevation,
            distance,
        }
    }

    /// Find closest angle from available angles
    fn find_closest_angle(&self, target: i32, available: &[i32]) -> i32 {
        available
            .iter()
            .min_by_key(|&&angle| (angle - target).abs())
            .copied()
            .unwrap_or(0)
    }

    /// Find lower angle
    fn find_lower_angle(&self, target: i32, available: &[i32]) -> i32 {
        available
            .iter()
            .filter(|&&angle| angle <= target)
            .max()
            .copied()
            .unwrap_or(*available.first().unwrap_or(&0))
    }

    /// Find higher angle
    fn find_higher_angle(&self, target: i32, available: &[i32]) -> i32 {
        available
            .iter()
            .filter(|&&angle| angle >= target)
            .min()
            .copied()
            .unwrap_or(*available.last().unwrap_or(&0))
    }

    /// Get HRTF at specific angles
    fn get_hrtf_at_angles(
        &self,
        azimuth: i32,
        elevation: i32,
    ) -> crate::Result<(Array1<f32>, Array1<f32>)> {
        let key = (azimuth, elevation);
        let left = self.database.left_responses.get(&key).ok_or_else(|| {
            crate::Error::LegacyHrtf(format!("No HRTF for angles ({azimuth}, {elevation})"))
        })?;
        let right = self.database.right_responses.get(&key).ok_or_else(|| {
            crate::Error::LegacyHrtf(format!("No HRTF for angles ({azimuth}, {elevation})"))
        })?;
        Ok((left.clone(), right.clone()))
    }

    /// Interpolate HRTF from weighted samples
    fn interpolate_hrtf(&self, weighted_hrirs: &[(&Array1<f32>, f32)]) -> Array1<f32> {
        let mut result = Array1::zeros(self.config.hrir_length);

        for (hrir, weight) in weighted_hrirs {
            for i in 0..result.len().min(hrir.len()) {
                result[i] += hrir[i] * weight;
            }
        }

        result
    }

    /// Calculate angular distance between two points
    fn calculate_angular_distance(&self, az1: f32, el1: f32, az2: f32, el2: f32) -> f32 {
        let az1_rad = az1.to_radians();
        let el1_rad = el1.to_radians();
        let az2_rad = az2.to_radians();
        let el2_rad = el2.to_radians();

        // Spherical distance formula
        let cos_distance = el1_rad.sin() * el2_rad.sin()
            + el1_rad.cos() * el2_rad.cos() * (az1_rad - az2_rad).cos();

        cos_distance.clamp(-1.0, 1.0).acos().to_degrees()
    }

    /// Apply distance modeling to HRIRs
    fn apply_distance_modeling(
        &self,
        left_hrir: &mut Array1<f32>,
        right_hrir: &mut Array1<f32>,
        coords: &SphericalCoordinates,
    ) -> crate::Result<()> {
        let distance = coords.distance.max(0.01); // Minimum distance to avoid division by zero

        // Distance attenuation (inverse square law)
        let attenuation = 1.0 / distance;

        // Near-field effects (head shadowing and proximity effects)
        let near_field_factor = if distance < self.config.near_field_distance {
            // Enhance proximity effect for close sources
            let proximity_boost = (self.config.near_field_distance / distance).powf(0.3);
            proximity_boost.min(3.0) // Limit boost to avoid excessive amplification
        } else {
            1.0
        };

        // Far-field approximation (simple attenuation)
        let far_field_factor = if distance > self.config.far_field_distance {
            // Apply additional high-frequency attenuation for very distant sources
            0.8 + 0.2 * (self.config.far_field_distance / distance)
        } else {
            1.0
        };

        // Apply combined distance effects
        let total_gain = attenuation * near_field_factor * far_field_factor;

        // Scale HRIRs
        left_hrir.mapv_inplace(|x| x * total_gain);
        right_hrir.mapv_inplace(|x| x * total_gain);

        // Add distance-dependent delay for very close sources
        if distance < self.config.near_field_distance {
            self.apply_proximity_delay(left_hrir, right_hrir, coords)?;
        }

        Ok(())
    }

    /// Apply air absorption based on distance and atmospheric conditions
    fn apply_air_absorption(
        &self,
        left_hrir: &mut Array1<f32>,
        right_hrir: &mut Array1<f32>,
        distance: f32,
    ) -> crate::Result<()> {
        // Calculate frequency-dependent absorption coefficients
        // Based on ISO 9613-1 standard for atmospheric absorption

        let temp_celsius = self.config.temperature;
        let relative_humidity = self.config.humidity;

        // Convert to Kelvin and calculate atmospheric parameters
        let temp_kelvin = temp_celsius + 273.15;
        let temp_ratio = temp_kelvin / 293.15; // Reference temperature 20°C

        // Calculate oxygen and nitrogen absorption
        let h_rel = relative_humidity * (101.325 * temp_ratio.powf(-5.0241));

        // Simplified high-frequency attenuation for air absorption
        // In practice, this would be applied in frequency domain
        let distance_factor = (-distance / 100.0).exp(); // Simple exponential decay
        let temp_factor = temp_ratio.powf(-0.1);
        let humidity_factor = 1.0 - relative_humidity * 0.1;

        let absorption_factor = distance_factor * temp_factor * humidity_factor;

        // Apply frequency-dependent attenuation (simplified)
        // Higher frequencies are attenuated more
        for i in 0..left_hrir.len() {
            let freq_weight = if i as f32 / left_hrir.len() as f32 > 0.5 {
                // Attenuate high frequencies more
                absorption_factor.powf(1.0 + i as f32 / left_hrir.len() as f32)
            } else {
                absorption_factor
            };

            left_hrir[i] *= freq_weight;
            right_hrir[i] *= freq_weight;
        }

        Ok(())
    }

    /// Apply proximity delay effects for very close sources
    fn apply_proximity_delay(
        &self,
        left_hrir: &mut Array1<f32>,
        right_hrir: &mut Array1<f32>,
        coords: &SphericalCoordinates,
    ) -> crate::Result<()> {
        let distance = coords.distance;
        let azimuth_rad = coords.azimuth.to_radians();

        // Calculate inter-aural time difference (ITD) enhancement for close sources
        let head_radius =
            self.config.head_circumference.unwrap_or(57.0) / (2.0 * std::f32::consts::PI);
        let sound_speed = 343.0; // m/s at 20°C

        // Enhanced ITD calculation for near field
        let itd_samples = if distance < head_radius * 2.0 {
            // Use enhanced ITD model for very close sources
            let enhanced_itd =
                (head_radius * azimuth_rad.sin() * (1.0 + azimuth_rad.cos())) / sound_speed;
            (enhanced_itd * self.config.sample_rate as f32) as usize
        } else {
            0
        };

        // Apply fractional delay if needed (simplified integer delay for now)
        if itd_samples > 0 && azimuth_rad.abs() > 0.1 {
            let delay_samples = itd_samples.min(left_hrir.len() / 4);

            if azimuth_rad > 0.0 {
                // Source on the right, delay left ear
                self.apply_delay(left_hrir, delay_samples);
            } else {
                // Source on the left, delay right ear
                self.apply_delay(right_hrir, delay_samples);
            }
        }

        Ok(())
    }

    /// Apply delay to HRIR
    fn apply_delay(&self, hrir: &mut Array1<f32>, delay_samples: usize) {
        if delay_samples == 0 || delay_samples >= hrir.len() {
            return;
        }

        // Shift samples to apply delay
        let original = hrir.clone();
        hrir.fill(0.0);

        for i in 0..(hrir.len() - delay_samples) {
            hrir[i + delay_samples] = original[i];
        }
    }
}

impl HrtfDatabase {
    /// Load HRTF database from file
    pub async fn load_from_file(path: &std::path::Path) -> crate::Result<Self> {
        let extension = path
            .extension()
            .and_then(|ext| ext.to_str())
            .map(|ext| ext.to_lowercase());

        match extension.as_deref() {
            Some("sofa") => Self::load_sofa_file(path).await,
            Some("json") => Self::load_json_file(path).await,
            Some("bin") | Some("hrtf") => Self::load_binary_file(path).await,
            _ => {
                tracing::warn!("Unknown HRTF file format, using default database");
                Self::load_default().await
            }
        }
    }

    /// Load HRTF from SOFA (Spatially Oriented Format for Acoustics) file
    async fn load_sofa_file(path: &std::path::Path) -> crate::Result<Self> {
        tracing::info!("Loading SOFA HRTF file: {:?}", path);

        // For this implementation, we'll handle a simplified text-based SOFA format
        // Real SOFA files are HDF5-based, but this provides basic compatibility
        let content = tokio::fs::read_to_string(path)
            .await
            .map_err(|e| crate::Error::hrtf(&format!("Failed to read SOFA file: {e}")))?;

        let mut metadata = HrtfMetadata {
            name: "SOFA HRTF Database".to_string(),
            sample_rate: 44100,
            hrir_length: 512,
            azimuth_angles: Vec::new(),
            elevation_angles: Vec::new(),
            distances: Some(vec![1.0]),
            subject_info: Some(SubjectInfo {
                head_circumference: 56.0,
                head_width: 15.0,
                head_height: 20.0,
                ear_height: 10.0,
                shoulder_width: 40.0,
            }),
        };

        let mut left_responses = HashMap::new();
        let mut right_responses = HashMap::new();
        let mut current_section = "";
        let mut current_measurement: Option<(i32, i32)> = None;
        let mut left_hrir_data = Vec::new();
        let mut right_hrir_data = Vec::new();

        for line in content.lines() {
            let line = line.trim();
            if line.is_empty() || line.starts_with('#') {
                continue;
            }

            // Parse SOFA-like sections
            if line.starts_with('[') && line.ends_with(']') {
                current_section = &line[1..line.len() - 1];
                continue;
            }

            match current_section {
                "GLOBAL" => {
                    if let Some((key, value)) = line.split_once('=') {
                        let key = key.trim();
                        let value = value.trim();
                        match key {
                            "Data.SamplingRate" => {
                                if let Ok(rate) = value.parse::<u32>() {
                                    metadata.sample_rate = rate;
                                }
                            }
                            "Data.IRLength" => {
                                if let Ok(length) = value.parse::<usize>() {
                                    metadata.hrir_length = length;
                                }
                            }
                            "GLOBAL:DatabaseName" => {
                                metadata.name = value.to_string();
                            }
                            "GLOBAL:ListenerShortName" => {
                                metadata.subject_info = Some(SubjectInfo {
                                    head_circumference: 56.0,
                                    head_width: 15.0,
                                    head_height: 20.0,
                                    ear_height: 10.0,
                                    shoulder_width: 40.0,
                                });
                            }
                            _ => {}
                        }
                    }
                }
                "POSITION" if line.starts_with("SourcePosition") => {
                    // Parse source position: SourcePosition=azimuth,elevation,distance
                    if let Some((_, coords)) = line.split_once('=') {
                        let parts: Vec<&str> = coords.split(',').collect();
                        if parts.len() >= 3 {
                            if let (Ok(azimuth), Ok(elevation), Ok(distance)) = (
                                parts[0].trim().parse::<f32>(),
                                parts[1].trim().parse::<f32>(),
                                parts[2].trim().parse::<f32>(),
                            ) {
                                current_measurement = Some((azimuth as i32, elevation as i32));
                                metadata.distances = Some(vec![distance]);
                            }
                        }
                    }
                }
                "DATA_IR" => {
                    if let Some((azimuth, elevation)) = current_measurement {
                        if let Some(data_str) = line.strip_prefix("L:") {
                            // Left channel HRIR data
                            left_hrir_data = data_str
                                .split_whitespace()
                                .filter_map(|s| s.parse::<f32>().ok())
                                .collect();
                        } else if let Some(data_str) = line.strip_prefix("R:") {
                            // Right channel HRIR data
                            right_hrir_data = data_str
                                .split_whitespace()
                                .filter_map(|s| s.parse::<f32>().ok())
                                .collect();
                        }

                        // If both channels are loaded, store the measurement
                        if !left_hrir_data.is_empty() && !right_hrir_data.is_empty() {
                            left_responses
                                .insert((azimuth, elevation), Array1::from(left_hrir_data.clone()));
                            right_responses.insert(
                                (azimuth, elevation),
                                Array1::from(right_hrir_data.clone()),
                            );

                            if !metadata.azimuth_angles.contains(&azimuth) {
                                metadata.azimuth_angles.push(azimuth);
                            }
                            if !metadata.elevation_angles.contains(&elevation) {
                                metadata.elevation_angles.push(elevation);
                            }

                            left_hrir_data.clear();
                            right_hrir_data.clear();
                            current_measurement = None;
                        }
                    }
                }
                _ => {}
            }
        }

        metadata.azimuth_angles.sort();
        metadata.elevation_angles.sort();

        // If no valid measurements found, use enhanced default
        if left_responses.is_empty() || right_responses.is_empty() {
            tracing::warn!("No valid HRTF measurements found in SOFA file, using enhanced default");
            return Self::load_enhanced_default().await;
        }

        tracing::info!(
            "Successfully loaded {} HRTF measurements from SOFA file",
            left_responses.len()
        );

        Ok(Self {
            metadata,
            left_responses,
            right_responses,
            frequency_responses: None,
            distance_responses: None,
        })
    }

    /// Load HRTF from JSON file
    async fn load_json_file(path: &std::path::Path) -> crate::Result<Self> {
        tracing::info!("Loading JSON HRTF file: {:?}", path);

        let content = tokio::fs::read_to_string(path)
            .await
            .map_err(|e| crate::Error::hrtf(&format!("Failed to read JSON file: {e}")))?;

        let json_data: serde_json::Value = serde_json::from_str(&content)
            .map_err(|e| crate::Error::hrtf(&format!("Failed to parse JSON: {e}")))?;

        // Parse metadata
        let metadata = if let Some(meta) = json_data.get("metadata") {
            HrtfMetadata {
                name: meta
                    .get("name")
                    .and_then(|v| v.as_str())
                    .unwrap_or("JSON HRTF Database")
                    .to_string(),
                sample_rate: meta
                    .get("sample_rate")
                    .and_then(|v| v.as_u64())
                    .unwrap_or(44100) as u32,
                hrir_length: meta
                    .get("hrir_length")
                    .and_then(|v| v.as_u64())
                    .unwrap_or(512) as usize,
                azimuth_angles: meta
                    .get("azimuth_angles")
                    .and_then(|v| v.as_array())
                    .map(|arr| {
                        arr.iter()
                            .filter_map(|x| x.as_i64().map(|i| i as i32))
                            .collect()
                    })
                    .unwrap_or_else(|| (-180..=180).step_by(15).collect()),
                elevation_angles: meta
                    .get("elevation_angles")
                    .and_then(|v| v.as_array())
                    .map(|arr| {
                        arr.iter()
                            .filter_map(|x| x.as_i64().map(|i| i as i32))
                            .collect()
                    })
                    .unwrap_or_else(|| (-40..=90).step_by(10).collect()),
                distances: meta
                    .get("distance")
                    .and_then(|v| v.as_f64())
                    .map(|d| vec![d as f32]),
                subject_info: meta.get("subject_id").and_then(|v| v.as_str()).map(|_| {
                    SubjectInfo {
                        head_circumference: 56.0,
                        head_width: 15.0,
                        head_height: 20.0,
                        ear_height: 10.0,
                        shoulder_width: 40.0,
                    }
                }),
            }
        } else {
            return Self::load_enhanced_default().await;
        };

        // Parse measurements
        let mut left_responses = HashMap::new();
        let mut right_responses = HashMap::new();

        if let Some(measurements) = json_data.get("measurements").and_then(|v| v.as_array()) {
            for measurement in measurements {
                let azimuth = measurement
                    .get("azimuth")
                    .and_then(|v| v.as_i64())
                    .unwrap_or(0) as i32;
                let elevation = measurement
                    .get("elevation")
                    .and_then(|v| v.as_i64())
                    .unwrap_or(0) as i32;

                // Parse left HRIR
                if let Some(left_hrir) = measurement.get("left_hrir").and_then(|v| v.as_array()) {
                    let left_data: Vec<f32> = left_hrir
                        .iter()
                        .filter_map(|x| x.as_f64().map(|f| f as f32))
                        .collect();
                    if !left_data.is_empty() {
                        left_responses.insert((azimuth, elevation), Array1::from(left_data));
                    }
                }

                // Parse right HRIR
                if let Some(right_hrir) = measurement.get("right_hrir").and_then(|v| v.as_array()) {
                    let right_data: Vec<f32> = right_hrir
                        .iter()
                        .filter_map(|x| x.as_f64().map(|f| f as f32))
                        .collect();
                    if !right_data.is_empty() {
                        right_responses.insert((azimuth, elevation), Array1::from(right_data));
                    }
                }
            }
        }

        // If no valid measurements found, use enhanced default
        if left_responses.is_empty() || right_responses.is_empty() {
            tracing::warn!("No valid HRTF measurements found in JSON file, using enhanced default");
            return Self::load_enhanced_default().await;
        }

        tracing::info!(
            "Successfully loaded {} HRTF measurements from JSON",
            left_responses.len()
        );

        Ok(Self {
            metadata,
            left_responses,
            right_responses,
            frequency_responses: None,
            distance_responses: None,
        })
    }

    /// Load HRTF from binary file
    async fn load_binary_file(path: &std::path::Path) -> crate::Result<Self> {
        tracing::info!("Loading binary HRTF file: {:?}", path);

        let data = tokio::fs::read(path)
            .await
            .map_err(|e| crate::Error::hrtf(&format!("Failed to read binary file: {e}")))?;

        if data.len() < 32 {
            return Err(crate::Error::hrtf(
                "Binary file too small to contain valid HRTF data",
            ));
        }

        let mut cursor = 0;

        // Parse binary header (simple format)
        // Magic number (4 bytes): "HRTF"
        let magic = &data[cursor..cursor + 4];
        if magic != b"HRTF" {
            return Err(crate::Error::hrtf("Invalid binary HRTF file format"));
        }
        cursor += 4;

        // Version (4 bytes)
        let version = u32::from_le_bytes([
            data[cursor],
            data[cursor + 1],
            data[cursor + 2],
            data[cursor + 3],
        ]);
        cursor += 4;
        if version != 1 {
            return Err(crate::Error::hrtf(&format!(
                "Unsupported HRTF binary version: {version}"
            )));
        }

        // Sample rate (4 bytes)
        let sample_rate = u32::from_le_bytes([
            data[cursor],
            data[cursor + 1],
            data[cursor + 2],
            data[cursor + 3],
        ]);
        cursor += 4;

        // HRIR length (4 bytes)
        let hrir_length = u32::from_le_bytes([
            data[cursor],
            data[cursor + 1],
            data[cursor + 2],
            data[cursor + 3],
        ]) as usize;
        cursor += 4;

        // Number of measurements (4 bytes)
        let measurement_count = u32::from_le_bytes([
            data[cursor],
            data[cursor + 1],
            data[cursor + 2],
            data[cursor + 3],
        ]) as usize;
        cursor += 4;

        // Distance (4 bytes)
        let distance = f32::from_le_bytes([
            data[cursor],
            data[cursor + 1],
            data[cursor + 2],
            data[cursor + 3],
        ]);
        cursor += 4;

        // Subject ID length (4 bytes) + subject ID
        let subject_id_len = u32::from_le_bytes([
            data[cursor],
            data[cursor + 1],
            data[cursor + 2],
            data[cursor + 3],
        ]) as usize;
        cursor += 4;

        if cursor + subject_id_len > data.len() {
            return Err(crate::Error::hrtf(
                "Invalid subject ID length in binary file",
            ));
        }

        let subject_id =
            String::from_utf8_lossy(&data[cursor..cursor + subject_id_len]).to_string();
        cursor += subject_id_len;

        // Parse measurements
        let mut left_responses = HashMap::new();
        let mut right_responses = HashMap::new();
        let mut azimuth_angles = Vec::new();
        let mut elevation_angles = Vec::new();

        for _ in 0..measurement_count {
            if cursor + 8 + (hrir_length * 8) > data.len() {
                return Err(crate::Error::hrtf("Insufficient data for measurement"));
            }

            // Azimuth (4 bytes)
            let azimuth = i32::from_le_bytes([
                data[cursor],
                data[cursor + 1],
                data[cursor + 2],
                data[cursor + 3],
            ]);
            cursor += 4;

            // Elevation (4 bytes)
            let elevation = i32::from_le_bytes([
                data[cursor],
                data[cursor + 1],
                data[cursor + 2],
                data[cursor + 3],
            ]);
            cursor += 4;

            // Left HRIR (hrir_length * 4 bytes)
            let mut left_hrir = Vec::with_capacity(hrir_length);
            for _ in 0..hrir_length {
                let sample = f32::from_le_bytes([
                    data[cursor],
                    data[cursor + 1],
                    data[cursor + 2],
                    data[cursor + 3],
                ]);
                left_hrir.push(sample);
                cursor += 4;
            }

            // Right HRIR (hrir_length * 4 bytes)
            let mut right_hrir = Vec::with_capacity(hrir_length);
            for _ in 0..hrir_length {
                let sample = f32::from_le_bytes([
                    data[cursor],
                    data[cursor + 1],
                    data[cursor + 2],
                    data[cursor + 3],
                ]);
                right_hrir.push(sample);
                cursor += 4;
            }

            left_responses.insert((azimuth, elevation), Array1::from(left_hrir));
            right_responses.insert((azimuth, elevation), Array1::from(right_hrir));

            if !azimuth_angles.contains(&azimuth) {
                azimuth_angles.push(azimuth);
            }
            if !elevation_angles.contains(&elevation) {
                elevation_angles.push(elevation);
            }
        }

        azimuth_angles.sort();
        elevation_angles.sort();

        if left_responses.is_empty() || right_responses.is_empty() {
            return Err(crate::Error::hrtf(
                "No valid HRTF measurements found in binary file",
            ));
        }

        let metadata = HrtfMetadata {
            name: format!("Binary HRTF Database ({subject_id})"),
            sample_rate,
            hrir_length,
            azimuth_angles,
            elevation_angles,
            distances: Some(vec![distance]),
            subject_info: Some(SubjectInfo {
                head_circumference: 56.0,
                head_width: 15.0,
                head_height: 20.0,
                ear_height: 10.0,
                shoulder_width: 40.0,
            }),
        };

        tracing::info!(
            "Successfully loaded {} HRTF measurements from binary file",
            left_responses.len()
        );

        Ok(Self {
            metadata,
            left_responses,
            right_responses,
            frequency_responses: None,
            distance_responses: None,
        })
    }

    /// Create enhanced default HRTF database with higher quality measurements
    async fn load_enhanced_default() -> crate::Result<Self> {
        let metadata = HrtfMetadata {
            name: "Enhanced Default HRTF".to_string(),
            sample_rate: 44100,
            hrir_length: 512, // Longer impulse responses for better quality
            azimuth_angles: (-180..=180).step_by(5).collect(), // Higher resolution
            elevation_angles: (-90..=90).step_by(5).collect(), // Higher resolution
            distances: Some(vec![0.2, 0.5, 1.0, 2.0, 5.0]), // Multiple distance measurements
            subject_info: Some(SubjectInfo {
                head_circumference: 57.0,
                head_width: 15.5,
                head_height: 24.0,
                ear_height: 12.0,
                shoulder_width: 45.0,
            }),
        };

        let mut left_responses = HashMap::new();
        let mut right_responses = HashMap::new();
        let mut distance_responses = HashMap::new();

        // Generate enhanced HRTFs with multiple distances
        for &azimuth in &metadata.azimuth_angles {
            for &elevation in &metadata.elevation_angles {
                let distances = metadata
                    .distances
                    .as_ref()
                    .expect("distances must be provided in enhanced HRTF metadata");
                for &distance in distances {
                    let (left_hrir, right_hrir) = Self::generate_enhanced_hrtf(
                        azimuth,
                        elevation,
                        distance,
                        metadata.hrir_length,
                    );

                    // Store default distance (1.0m)
                    if (distance - 1.0).abs() < 0.1 {
                        left_responses.insert((azimuth, elevation), left_hrir.clone());
                        right_responses.insert((azimuth, elevation), right_hrir.clone());
                    }

                    // Store distance-specific responses
                    let distance_key = (distance * 100.0) as u32; // Store as cm
                    distance_responses
                        .insert((azimuth, elevation, distance_key), (left_hrir, right_hrir));
                }
            }
        }

        Ok(Self {
            metadata,
            left_responses,
            right_responses,
            frequency_responses: None,
            distance_responses: Some(distance_responses),
        })
    }

    /// Load default HRTF database
    pub async fn load_default() -> crate::Result<Self> {
        // Create a simple default HRTF database
        let metadata = HrtfMetadata {
            name: "Default HRTF".to_string(),
            sample_rate: 44100,
            hrir_length: 256,
            azimuth_angles: (-180..=180).step_by(15).collect(),
            elevation_angles: (-90..=90).step_by(15).collect(),
            distances: None,
            subject_info: None,
        };

        let mut left_responses = HashMap::new();
        let mut right_responses = HashMap::new();

        // Generate simple HRTFs (in practice, these would be measured)
        for &azimuth in &metadata.azimuth_angles {
            for &elevation in &metadata.elevation_angles {
                let (left_hrir, right_hrir) =
                    Self::generate_simple_hrtf(azimuth, elevation, metadata.hrir_length);
                left_responses.insert((azimuth, elevation), left_hrir);
                right_responses.insert((azimuth, elevation), right_hrir);
            }
        }

        Ok(Self {
            metadata,
            left_responses,
            right_responses,
            frequency_responses: None,
            distance_responses: None,
        })
    }

    /// Generate simple HRTF for testing
    fn generate_simple_hrtf(
        azimuth: i32,
        _elevation: i32,
        length: usize,
    ) -> (Array1<f32>, Array1<f32>) {
        let mut left_hrir = Array1::zeros(length);
        let mut right_hrir = Array1::zeros(length);

        // Very simple HRTF model - just delay and attenuation based on angle
        let _azimuth_rad = (azimuth as f32).to_radians();

        // Left ear delay (negative azimuth = sound from left)
        let left_delay = if azimuth < 0 {
            0
        } else {
            (azimuth as f32 / 180.0 * 10.0) as usize
        };
        let left_gain = 1.0 - (azimuth as f32).abs() / 180.0 * 0.3;

        // Right ear delay
        let right_delay = if azimuth > 0 {
            0
        } else {
            ((-azimuth) as f32 / 180.0 * 10.0) as usize
        };
        let right_gain = 1.0 - (azimuth as f32).abs() / 180.0 * 0.3;

        // Set impulse responses
        if left_delay < length {
            left_hrir[left_delay] = left_gain;
        }
        if right_delay < length {
            right_hrir[right_delay] = right_gain;
        }

        (left_hrir, right_hrir)
    }

    /// Generate enhanced HRTF with distance modeling
    fn generate_enhanced_hrtf(
        azimuth: i32,
        elevation: i32,
        distance: f32,
        length: usize,
    ) -> (Array1<f32>, Array1<f32>) {
        let sample_rate = 44100.0; // Use standard sample rate for calculations
        let mut left_hrir = Array1::zeros(length);
        let mut right_hrir = Array1::zeros(length);

        // More sophisticated HRTF model with distance modeling
        let azimuth_rad = (azimuth as f32).to_radians();
        let elevation_rad = (elevation as f32).to_radians();

        // Head model parameters
        let head_radius = 0.09; // Average head radius in meters

        // Distance attenuation (inverse square law)
        let distance_attenuation = 1.0 / (distance + 0.01);

        // ITD (Interaural Time Difference) calculation using Woodworth model
        let itd = if azimuth_rad.abs() <= std::f32::consts::PI / 2.0 {
            // For azimuth <= 90 degrees
            (head_radius / 343.0) * (azimuth_rad + azimuth_rad.sin()) * sample_rate
        } else {
            // For azimuth > 90 degrees
            (head_radius / 343.0) * (std::f32::consts::PI / 2.0 + azimuth_rad.sin()) * sample_rate
        };

        // Convert ITD to sample delay
        let left_delay = if azimuth >= 0 {
            (itd / 2.0) as usize
        } else {
            0
        };
        let right_delay = if azimuth < 0 {
            (-itd / 2.0) as usize
        } else {
            0
        };

        // ILD (Interaural Level Difference) - frequency-dependent attenuation
        let frequency_factor = 1.0; // Simplified - in practice this would be frequency-dependent
        let shadow_attenuation = if azimuth_rad.abs() > std::f32::consts::PI / 2.0 {
            0.3
        } else {
            0.0
        };

        let left_gain = distance_attenuation
            * frequency_factor
            * (1.0 - if azimuth > 0 { shadow_attenuation } else { 0.0 });
        let right_gain = distance_attenuation
            * frequency_factor
            * (1.0 - if azimuth < 0 { shadow_attenuation } else { 0.0 });

        // Elevation effects (simplified pinna filtering)
        let elevation_gain = (1.0 + 0.2 * elevation_rad.sin()).clamp(0.5, 1.5);

        // Near-field effects for close distances
        let near_field_boost = if distance < 0.5 {
            1.0 + (0.5 - distance) * 0.5
        } else {
            1.0
        };

        // Generate impulse response with multiple components
        let primary_delay = (distance / 343.0 * sample_rate) as usize;

        // Primary arrival
        if primary_delay + left_delay < length {
            left_hrir[primary_delay + left_delay] = left_gain * elevation_gain * near_field_boost;
        }
        if primary_delay + right_delay < length {
            right_hrir[primary_delay + right_delay] =
                right_gain * elevation_gain * near_field_boost;
        }

        // Add some early reflections for realism (simplified)
        let reflection_delay = primary_delay + (0.002 * sample_rate) as usize;
        if reflection_delay < length {
            let reflection_gain = 0.1 * distance_attenuation;
            if reflection_delay + left_delay < length {
                left_hrir[reflection_delay + left_delay] += reflection_gain;
            }
            if reflection_delay + right_delay < length {
                right_hrir[reflection_delay + right_delay] += reflection_gain;
            }
        }

        // Apply a simple smoothing window to make it more realistic
        let window_size = (length / 8).min(32);
        for i in 0..window_size {
            let window_val =
                0.5 * (1.0 - ((i as f32) / (window_size as f32) * std::f32::consts::PI).cos());
            if i < left_hrir.len() {
                left_hrir[i] *= window_val;
            }
            if i < right_hrir.len() {
                right_hrir[i] *= window_val;
            }
        }

        (left_hrir, right_hrir)
    }

    /// Get metadata
    pub fn metadata(&self) -> &HrtfMetadata {
        &self.metadata
    }

    /// Get available positions
    pub fn available_positions(&self) -> Vec<SphericalCoordinates> {
        let mut positions = Vec::new();
        for &azimuth in &self.metadata.azimuth_angles {
            for &elevation in &self.metadata.elevation_angles {
                positions.push(SphericalCoordinates {
                    azimuth: azimuth as f32,
                    elevation: elevation as f32,
                    distance: 1.0, // Default distance
                });
            }
        }
        positions
    }
}

impl Default for HrtfConfig {
    fn default() -> Self {
        Self {
            sample_rate: 44100,
            hrir_length: 256,
            crossfade_time: 0.01, // 10ms
            enable_distance_modeling: true,
            interpolation_method: InterpolationMethod::Bilinear,
            head_circumference: None,
            near_field_distance: 0.2, // 20cm - near field starts
            far_field_distance: 10.0, // 10m - far field approximation
            enable_air_absorption: true,
            temperature: 20.0, // 20°C
            humidity: 0.5,     // 50% relative humidity
            enable_simd: true,
        }
    }
}

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

    #[tokio::test]
    async fn test_hrtf_processor_creation() {
        let processor = HrtfProcessor::new(None).await;
        assert!(processor.is_ok());
    }

    #[tokio::test]
    async fn test_hrtf_database_loading() {
        let database = HrtfDatabase::load_default().await;
        assert!(database.is_ok());

        let db = database.unwrap();
        assert!(!db.left_responses.is_empty());
        assert!(!db.right_responses.is_empty());
        assert_eq!(db.left_responses.len(), db.right_responses.len());
    }

    #[tokio::test]
    async fn test_cartesian_to_spherical() {
        let processor = HrtfProcessor::new(None).await.unwrap();

        // Test point to the right
        let pos = Position3D::new(1.0, 0.0, 0.0);
        let spherical = processor.cartesian_to_spherical(&pos);
        assert!((spherical.azimuth - 0.0).abs() < 0.1);
        assert!((spherical.elevation - 0.0).abs() < 0.1);

        // Test point to the front
        let pos = Position3D::new(0.0, 0.0, 1.0);
        let spherical = processor.cartesian_to_spherical(&pos);
        assert!((spherical.azimuth - 90.0).abs() < 0.1);
    }

    #[tokio::test]
    async fn test_hrtf_processing() {
        let processor = HrtfProcessor::new(None).await.unwrap();
        let input = Array1::from_vec(vec![1.0, 0.5, -0.5, -1.0]);
        let mut left_output = Array1::zeros(input.len());
        let mut right_output = Array1::zeros(input.len());

        let position = Position3D::new(1.0, 0.0, 0.0);
        let result = processor
            .process_position(&input, &mut left_output, &mut right_output, &position)
            .await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_realtime_processing() {
        let mut processor = HrtfProcessor::new(None).await.unwrap();
        let chunk_size = 64;
        let input = Array1::from_vec(vec![0.1; chunk_size]);
        let mut left_output = Array1::zeros(chunk_size);
        let mut right_output = Array1::zeros(chunk_size);

        let position = Position3D::new(1.0, 0.0, 0.0);

        // Process first chunk
        let result1 = processor
            .process_realtime_chunk(&input, &mut left_output, &mut right_output, &position)
            .await;
        assert!(result1.is_ok());

        // Process second chunk (should use overlap-add)
        let result2 = processor
            .process_realtime_chunk(&input, &mut left_output, &mut right_output, &position)
            .await;
        assert!(result2.is_ok());
    }

    #[tokio::test]
    async fn test_interpolation_methods() {
        // Test different interpolation methods
        let configs = [
            (InterpolationMethod::Nearest, "Nearest"),
            (InterpolationMethod::Bilinear, "Bilinear"),
            (InterpolationMethod::Spherical, "Spherical"),
            (InterpolationMethod::Weighted, "Weighted"),
        ];

        for (method, name) in configs {
            let config = HrtfConfig {
                interpolation_method: method,
                ..Default::default()
            };

            let processor = HrtfProcessor::with_config(None, config).await.unwrap();
            let coords = SphericalCoordinates {
                azimuth: 45.0,
                elevation: 15.0,
                distance: 1.0,
            };

            let result = processor.get_hrtf(&coords);
            assert!(result.is_ok(), "Failed interpolation method: {}", name);
        }
    }

    #[tokio::test]
    async fn test_crossfade_processing() {
        let processor = HrtfProcessor::new(None).await.unwrap();
        let input = Array1::from_vec(vec![1.0, 0.5, -0.5, -1.0]);
        let mut left_output = Array1::zeros(input.len());
        let mut right_output = Array1::zeros(input.len());

        let positions = vec![
            (Position3D::new(1.0, 0.0, 0.0), 0.7),  // 70% weight
            (Position3D::new(-1.0, 0.0, 0.0), 0.3), // 30% weight
        ];

        let result = processor
            .process_crossfade(&input, &mut left_output, &mut right_output, &positions)
            .await;
        assert!(result.is_ok());

        // Check that output is not all zeros
        let left_sum: f32 = left_output.iter().map(|x| x.abs()).sum();
        let right_sum: f32 = right_output.iter().map(|x| x.abs()).sum();
        assert!(left_sum > 0.0);
        assert!(right_sum > 0.0);
    }

    #[tokio::test]
    async fn test_frequency_domain_convolution() {
        let processor = HrtfProcessor::new(None).await.unwrap();

        // Create input large enough to trigger frequency-domain convolution
        let input = Array1::from_vec(vec![0.1; 128]);
        let hrir_len = processor.config.hrir_length;
        let left_hrir = Array1::from_vec(vec![1.0; hrir_len]);
        let right_hrir = Array1::from_vec(vec![0.8; hrir_len]);

        let mut left_output = Array1::zeros(input.len());
        let mut right_output = Array1::zeros(input.len());

        let result = processor.convolve_hrtf(
            &input,
            &left_hrir,
            &right_hrir,
            &mut left_output,
            &mut right_output,
        );
        assert!(result.is_ok());

        // Check that convolution produced non-zero output
        let left_energy: f32 = left_output.iter().map(|x| x * x).sum();
        let right_energy: f32 = right_output.iter().map(|x| x * x).sum();
        assert!(left_energy > 0.0);
        assert!(right_energy > 0.0);
    }
}