-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhighp_spatial_landmarks.py
More file actions
3181 lines (2674 loc) · 147 KB
/
highp_spatial_landmarks.py
File metadata and controls
3181 lines (2674 loc) · 147 KB
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
import threading
import typing
import torch.fft
import torch.utils.dlpack
from typing import List, Dict
import torch.fft
import cupy
import numpy as np
import os
import itertools
from scipy.io import loadmat
from scipy.spatial import Delaunay
from scipy.fft import next_fast_len
from typing import Tuple
from scipy.signal import lfilter
from typing import Union
import torch
import math
from line_profiler_pycharm import profile
from utils import check_nans
_indexing_type = typing.Union[slice, int, torch.Tensor]
class Head:
"""
Optimized Head class for loading and caching 3D audio data.
This class loads CIPIC HRIR data at its native 44.1kHz sample rate,
pre-calculates a 360-degree HRIR grid, and saves it to a highly
optimized cache.
It no longer performs any resampling; it assumes the audio engine
will handle the "resampling" in the frequency domain during convolution.
"""
# --- CIPIC Database Definitions ---
AZIMUTH_ANGLES = [
-90, -65, -55, -45, -40, -35, -30, -25, -20, -15, -10, -5, 0, 5, 10, 15,
20, 25, 30, 35, 40, 45, 55, 65, 90,
]
ELEVATION_ANGLES = -45 + 5.625 * np.arange(0, 50)
POINTS_NP = np.array(list(itertools.product(AZIMUTH_ANGLES, ELEVATION_ANGLES)))
AZ_DICT = dict(zip(AZIMUTH_ANGLES, np.arange(len(AZIMUTH_ANGLES))))
EL_DICT = dict(zip(ELEVATION_ANGLES, np.arange(len(ELEVATION_ANGLES))))
# --- Anthropometry Data Loading ---
try:
anthro_data = loadmat('CIPIC_hrtf_database/anthropometry/anthro.mat')
PARAMETERS = {
'info': ['Age:', 'Sex:', 'Weight:'],
'X': ['Head width:', 'Head height:', 'Head depth:', 'Pinna offset down:',
'Pinna offset back:', 'Neck width:', 'Neck height:', 'Neck depth:',
'Torso top width:', 'Torso top height:', 'Torso top depth:',
'Shoulder width:', 'Head offset forward:', 'Height:',
'Seated height:', 'Head circumference:', 'Shoulder circumference:'],
'D': ['Cavum concha height:', 'Cymba concha height:', 'Cavum concha width:',
'Fossa height:', 'Pinna height:', 'Pinna width:',
'Intertragal incisure width:', 'Cavum concha depth:'],
'theta': ['Pinna rotation angle:', 'Pinna flare angle:']
}
anthro_ids_raw = np.squeeze(anthro_data['id'])
ANTHRO_ID = [str(int(id_)) for id_ in anthro_ids_raw]
ID_TO_IDX = dict(zip([int(id_) for id_ in ANTHRO_ID], range(len(ANTHRO_ID))))
for key, value in anthro_data.items():
if key not in ['__header__', '__version__', '__globals__', 'id', 'sex']:
if key == 'age':
anthro_data[key][np.isnan(anthro_data[key])] = 0
anthro_data[key] = np.squeeze(value.astype('int')).astype('str')
anthro_data[key][anthro_data[key] == '0'] = '-'
else:
anthro_data[key] = np.around(np.squeeze(value), 1).astype('str')
anthro_data[key][anthro_data[key] == 'nan'] = '-'
except Exception as e:
print(f"CRITICAL WARNING: Could not parse 'id' from anthro.mat: {e}")
ID_TO_IDX = {}
def __init__(self, num_speakers, block_size: int, subject='018', device='cuda', dtype=torch.float32,
grid_size: Tuple[int, int] = (256, 256)):
"""
Initialize Head.
Args:
block_size: Audio processing block size in samples (e.g., 512, 1024).
This is the *only* parameter needed from the audio engine.
subject: CIPIC subject ID.
device: Torch device ('cuda' or 'cpu').
dtype: Torch dtype.
grid_size: HRIR cache grid resolution (azimuth, elevation).
"""
if not Head.ID_TO_IDX:
raise RuntimeError("Head class failed to initialize. Could not load subject IDs.")
idx = Head.ID_TO_IDX[int(subject)]
self.properties_cm = {}
for param, values in Head.PARAMETERS.items():
if param != 'info':
LR_const = 2 if param in ('D', 'theta') else 1
for j in range(LR_const * len(values)):
if Head.anthro_data[param][idx][j] != '-':
key = values[j % len(values)].strip().lower().replace(':', '').replace(' ', '_')
self.properties_cm[key] = float(Head.anthro_data[param][idx][j])
self.device = device
self.dtype = dtype
self.subject = subject
self.block_size = block_size
self.native_sample_rate = 44100 # Hard-coded, we never resample
if not (isinstance(grid_size, tuple) and len(grid_size) == 2):
raise ValueError("grid_size must be a tuple of two integers (e.g., (256, 256))")
self.grid_size = grid_size
# --- Cache Management ---
cache_dir = "hrir_cache"
# FFT cache is specific to subject, block size, and grid.
cache_file = f"subject_{self.subject}_b{self.block_size}_grid{self.grid_size[0]}x{self.grid_size[1]}_NATIVE_FFT.pt"
cache_path = os.path.join(cache_dir, cache_file)
N_AZ, N_EL = self.grid_size
print(f"\rFFT HRIR cache initialized ({N_AZ}x{N_EL}) ")
self.cache_az_step = 360.0 / (N_AZ - 1)
self.cache_el_step = 135.0 / (N_EL - 1)
# --- Head State (Global) ---
self.head_position = torch.tensor([0.0, 0.0, 0.0], device=device, dtype=dtype)
self.head_rotation = torch.eye(3, device=device, dtype=dtype)
self.head_rotation_dirty = True
# Add to __init__ or cache initialization:
self.cache_az_offset = 180.0
self.cache_el_offset = 45.0
self.cache_az_step_inv = 1.0 / self.cache_az_step
self.cache_el_step_inv = 1.0 / self.cache_el_step
self.hypot_buf = torch.empty(num_speakers*5*8, device=device, dtype=dtype)
self.arctan2_buf = torch.empty(num_speakers*5*8, device=device, dtype=dtype)
self.arctan2_buf2 = torch.empty(num_speakers*5*8, device=device, dtype=dtype)
self.az_idx = torch.empty(num_speakers*5*8*8, device=device, dtype=torch.long)
self.el_idx = torch.empty(num_speakers*5*8*8, device=device, dtype=torch.long)
self.azimuth_add_buf = torch.empty(num_speakers*8, dtype=dtype, device=device)
self.elevation_add_buf = torch.empty(num_speakers*8, dtype=dtype, device=device)
if os.path.exists(cache_path):
try:
print(f"Loading cached FFT Head data from {cache_path}...")
cached_data = torch.load(cache_path, map_location=self.device, weights_only=True)
# Validate cache
if (tuple(cached_data.get('grid_size', (0, 0))) != self.grid_size or
cached_data.get('block_size', 0) != self.block_size):
print("Cache parameter mismatch! Re-initializing...")
raise ValueError("Cache parameter mismatch")
self.hrir_length = cached_data['hrir_length']
self.fft_size = cached_data['fft_size']
self.overlap_size = cached_data['overlap_size']
self.hrir_fft_cache = cached_data['hrir_fft_cache']
self.T_inv = cached_data['T_inv']
self.cache_az_step = cached_data['cache_az_step']
self.cache_el_step = cached_data['cache_el_step']
self.hrtf_points = torch.from_numpy(self.POINTS_NP).to(device=self.device, dtype=self.dtype)
self.triangulation = Delaunay(self.POINTS_NP)
print(f"Cache loaded. FFT size: {self.fft_size}, Block: {self.block_size}")
except Exception as e:
print(f"Failed to load cache: {e}. Re-initializing...")
self._full_initialization(subject)
else:
print(f"Cache not found. Initializing FFT HRIR cache...")
self._full_initialization(subject)
@staticmethod
def _muffle(hrir_np: np.ndarray, a: float = 0.6) -> np.ndarray:
"""
Applies a simple one-pole low-pass filter to simulate rear-hemisphere muffling.
Vectorized using scipy.signal.lfilter (direct form II transposed).
"""
# Numerator (b) coefficients: applied to input x[n]
b = [1.0 - a]
# Denominator (a) coefficients: applied to output y[n]
# The '1.0' corresponds to y[n], the '-a' corresponds to y[n-1]
# (scipy expects coefficients on the left side of the difference equation)
a_coeffs = [1.0, -a]
return lfilter(b, a_coeffs, hrir_np)
def _full_initialization(self, subject):
"""Full initialization with NATIVE 44.1kHz HRIRs."""
hrir = loadmat(f'CIPIC_hrtf_database/standard_hrir_database/subject_{subject}/hrir_final.mat')
hrir_l = np.array(hrir['hrir_l'])
hrir_r = np.array(hrir['hrir_r'])
hrir_combined = np.concatenate([hrir_l[..., None], hrir_r[..., None]], -1)
# Transpose to [Az, El, Channel, Samples]
hrir_combined = hrir_combined.transpose(0, 1, 3, 2)
self.hrir_data_native = torch.from_numpy(hrir_combined).to(device=self.device, dtype=self.dtype)
self.hrir_length = self.hrir_data_native.shape[-1] # Should be 200
self.hrtf_points = torch.from_numpy(self.POINTS_NP).to(device=self.device, dtype=self.dtype)
# --- FFT Size Calculation ---
self.fft_size = next_fast_len(self.hrir_length + self.block_size - 1)
self.overlap_size = self.hrir_length - 1
print(f"Native HRIR length: {self.hrir_length} samples.")
print(f"FFT size: {self.fft_size}, Block: {self.block_size}")
# Initialize FFT cache
self.N_AZ, self.N_EL = self.grid_size
self.hrir_fft_cache = torch.zeros((self.N_AZ, self.N_EL, 2, self.fft_size),
device=self.device, dtype=torch.complex64)
self._initialize_triangulation()
self._initialize_fft_cache_360()
# Save cache atomically
self._save_cache()
def _save_cache(self):
"""Save FFT cache atomically to prevent corruption."""
cache_dir = "hrir_cache"
cache_file = f"subject_{self.subject}_b{self.block_size}_grid{self.grid_size[0]}x{self.grid_size[1]}_NATIVE_FFT.pt"
cache_path = os.path.join(cache_dir, cache_file)
temp_cache_path = cache_path + ".tmp"
print(f"Saving initialized FFT cache to {cache_path}...")
try:
os.makedirs(cache_dir, exist_ok=True)
data_to_save = {
'hrir_length': self.hrir_length,
'fft_size': self.fft_size,
'overlap_size': self.overlap_size,
'hrir_fft_cache': self.hrir_fft_cache.cpu(),
'T_inv': self.T_inv.cpu(),
'cache_az_step': self.cache_az_step,
'cache_el_step': self.cache_el_step,
'grid_size': self.grid_size,
'block_size': self.block_size,
}
torch.save(data_to_save, temp_cache_path, _use_new_zipfile_serialization=True)
os.replace(temp_cache_path, cache_path)
print(f"FFT cache saved successfully.")
except Exception as e:
print(f"WARNING: Failed to save RFFT cache: {e}")
if os.path.exists(temp_cache_path):
try:
os.remove(temp_cache_path)
except Exception as e:
print(f"WARNING: Failed to remove failed RFFT cache: {e}")
pass
def _initialize_fft_cache_360(self):
"""Initialize 360-degree FFT cache."""
self.cache_az_range = np.linspace(-180, 180, self.N_AZ)
self.cache_el_range = np.linspace(-45, 90, self.N_EL)
print(f"Caching 360° FFT HRIRs ({self.N_AZ}x{self.N_EL})...", end="", flush=True)
# Pre-allocate padding buffers
padded_left = torch.zeros(self.fft_size, device=self.device, dtype=self.dtype)
padded_right = torch.zeros(self.fft_size, device=self.device, dtype=self.dtype)
for i, azimuth in enumerate(self.cache_az_range):
for j, elevation in enumerate(self.cache_el_range):
interp_az = azimuth
is_rear = False
if azimuth > 90.0:
interp_az = 180.0 - azimuth
is_rear = True
elif azimuth < -90.0:
interp_az = -180.0 - azimuth
is_rear = True
hrir_left_np, hrir_right_np = self._interpolate_hrir_triangulation(interp_az, elevation)
if is_rear:
hrir_left_np = self._muffle(hrir_left_np)
hrir_right_np = self._muffle(hrir_right_np)
padded_left.zero_()
padded_right.zero_()
padded_left[:self.hrir_length] = torch.from_numpy(hrir_left_np).to(self.device)
padded_right[:self.hrir_length] = torch.from_numpy(hrir_right_np).to(self.device)
# --- Perform FFT ---
self.hrir_fft_cache[i, j, 0] = torch.fft.fft(padded_left, n=self.fft_size)
self.hrir_fft_cache[i, j, 1] = torch.fft.fft(padded_right, n=self.fft_size)
if i % (max(1, self.N_AZ // 20)) == 0 or i == self.N_AZ - 1:
progress = int((i + 1) / self.N_AZ * 100)
print(f"\rCaching 360° FFT HRIRs... {progress}%", end="", flush=True)
def _initialize_triangulation(self):
"""Initialize Delaunay triangulation."""
self.triangulation = Delaunay(self.POINTS_NP)
T_inv_np = self._calculate_T_inv_np()
self.T_inv = torch.from_numpy(T_inv_np).to(device=self.device, dtype=self.dtype)
def _calculate_T_inv_np(self):
"""Calculate inverse transformation matrices for triangulation."""
A = self.POINTS_NP[self.triangulation.simplices][:, 0, :]
B = self.POINTS_NP[self.triangulation.simplices][:, 1, :]
C = self.POINTS_NP[self.triangulation.simplices][:, 2, :]
T = np.empty((2 * A.shape[0], A.shape[1]))
T[::2, :] = A - C
T[1::2, :] = B - C
T = T.reshape(-1, 2, 2)
return np.linalg.inv(T)
def _interpolate_hrir_triangulation(self, azimuth: float, elevation: float) -> Tuple[np.ndarray, np.ndarray]:
"""Interpolate HRIR using triangulation (used during caching)."""
azimuth = np.clip(azimuth, -90, 90)
elevation = np.clip(elevation, -45, 231.875)
position = np.array([azimuth, elevation])
triangle_idx = self.triangulation.find_simplex(position)
if triangle_idx == -1:
# Fallback: nearest neighbor
distances = np.sum((self.POINTS_NP - position) ** 2, axis=1)
nearest_idx = np.argmin(distances)
az_idx = self.AZ_DICT[self.AZIMUTH_ANGLES[nearest_idx % len(self.AZIMUTH_ANGLES)]]
el_idx = self.EL_DICT[self.ELEVATION_ANGLES[nearest_idx // len(self.AZIMUTH_ANGLES)]]
return (self.hrir_data_native[az_idx, el_idx, 0].cpu().numpy(),
self.hrir_data_native[az_idx, el_idx, 1].cpu().numpy())
vertices = self.POINTS_NP[self.triangulation.simplices[triangle_idx]]
T_inv_np = self.T_inv[triangle_idx].cpu().numpy()
g = np.dot(position - vertices[2], T_inv_np)
g_1, g_2 = g[0], g[1]
g_3 = 1 - g_1 - g_2
if g_1 >= 0 and g_2 >= 0 and g_3 >= 0:
# Barycentric interpolation
v_indices = [
(self.AZ_DICT[v[0]], self.EL_DICT[v[1]]) for v in vertices
]
hrir_l = (g_1 * self.hrir_data_native[v_indices[0][0], v_indices[0][1], 0] +
g_2 * self.hrir_data_native[v_indices[1][0], v_indices[1][1], 0] +
g_3 * self.hrir_data_native[v_indices[2][0], v_indices[2][1], 0])
hrir_r = (g_1 * self.hrir_data_native[v_indices[0][0], v_indices[0][1], 1] +
g_2 * self.hrir_data_native[v_indices[1][0], v_indices[1][1], 1] +
g_3 * self.hrir_data_native[v_indices[2][0], v_indices[2][1], 1])
return hrir_l.cpu().numpy(), hrir_r.cpu().numpy()
else:
# Fallback: nearest vertex in triangle
distances = [np.linalg.norm(position - v) for v in vertices]
nearest_vertex = vertices[np.argmin(distances)]
az_idx, el_idx = self.AZ_DICT[nearest_vertex[0]], self.EL_DICT[nearest_vertex[1]]
return (self.hrir_data_native[az_idx, el_idx, 0].cpu().numpy(),
self.hrir_data_native[az_idx, el_idx, 1].cpu().numpy())
def get_cached_fft_hrir(self, azimuth, elevation) -> torch.Tensor:
"""
Get interpolated FFT HRIR from 360° cache.
Supports batched inputs [...].
Returns: [..., 2, fft_size] complex tensor
"""
# Track if input was scalar-like (scalar or single-element 1D)
is_scalar_like = azimuth.dim() == 0 or (azimuth.dim() == 1 and azimuth.shape[0] == 1)
size = azimuth.flatten().shape[0]
# Convert scalar to 1D for uniform processing
if azimuth.dim() == 0:
azimuth = azimuth[None]
elevation = elevation[None]
# Map to cache indices - no flattening needed!
az_idx = make_shape(azimuth, self.az_idx).copy_(torch.add(azimuth, self.cache_az_offset, out=make_shape(azimuth, self.azimuth_add_buf)).mul_(self.cache_az_step_inv))
el_idx = make_shape(azimuth, self.el_idx).copy_(torch.add(elevation, self.cache_el_offset, out=make_shape(elevation, self.elevation_add_buf)).mul_(self.cache_el_step_inv))
# Advanced indexing preserves the shape of index tensors
fft_stereo = self.hrir_fft_cache[az_idx, el_idx] # [..., 2, fft_size]
# Return scalar result if input was scalar-like
return fft_stereo[0] if is_scalar_like else fft_stereo
# --- Coordinate Transforms & Setters ---
def world_to_head_coordinates(self, world_pos: torch.Tensor) -> torch.Tensor:
"""Transform world to head-relative coordinates. Supports batched [..., 3]."""
# This is the exact transformation used by well tested transform_global_point_to_screen_space()
relative_pos = world_pos - self.head_position
return relative_pos @ self.head_rotation
def head_coords_to_cipic_angles(self, head_coords: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""Convert head coords to CIPIC angles. Supports batched [..., 3]."""
x = head_coords[..., 0]
y = head_coords[..., 1]
z = head_coords[..., 2]
azimuth_deg = torch.rad2deg_(torch.arctan2(x, z, out=make_shape(z, self.arctan2_buf)))
elevation_deg = torch.rad2deg_(torch.arctan2(
y, torch.hypot(x, z, out=make_shape(x, self.hypot_buf)), out=make_shape(x, self.arctan2_buf2))
)
return azimuth_deg, elevation_deg
def set_head_rotation(self, rotation_matrix: torch.Tensor):
"""Set head rotation matrix."""
if rotation_matrix.shape != (3, 3):
raise ValueError("Rotation matrix must be 3x3")
# This unfortunately stalls the GPU to a level where it's better to just always make head_rotation_dirty
# Interleave all position and HRIR assignments to prevent stalls
# if not torch.allclose(self.head_rotation, rotation_matrix):
self.head_rotation = rotation_matrix
self.head_rotation_dirty = True
class LocalizationBlueprint:
def __init__(self, device, dtype, num_speakers=1, speed_of_sound=343.0):
self.memory_lock = threading.RLock()
self.device = device
self.dtype = dtype
self.num_speakers = num_speakers
self.speed_of_sound = speed_of_sound
self.late_spatial_regions = 4 # Reduced from 8
self.late_reverb_mix = 0.9
# --- BATCHIFIED ---
self.speaker_positions = torch.zeros((self.num_speakers, 3), device=device, dtype=dtype)
self.fine_speaker_positions = torch.zeros((self.num_speakers, 3), device=device, dtype=dtype)
self.course_speaker_positions = torch.zeros((self.num_speakers, 3), device=device, dtype=dtype)
self.fine_speaker_positions[:, 1] = 0
self.course_speaker_positions[:, 1] = 0
# Set a default position
self.speaker_positions[:, 2] = 15.0
# --- GLOBAL ---
self.room_dimensions = torch.tensor([40.0, 20.0, 60.0], device=device, dtype=dtype)
self.half_dims = self.room_dimensions / 2.0
self.absorption_db = torch.tensor(-4.8, device=device, dtype=dtype)
self.params_dirty = True
self.small_val_tensor = torch.tensor(1e9, device=device, dtype=dtype)
self.rot60 = self.compute_rt60()
self.speaker_indices = torch.arange(self.num_speakers, device=self.device, dtype=torch.long)
self._position_change_intermediate_buffer = [torch.empty(
[self.num_speakers, 3],
dtype=self.dtype,
device=self.device
) for _ in range(4)]
self._position_sub_intermediate_buffer = [torch.empty(
[self.num_speakers, 3],
dtype=self.dtype,
device=self.device
) for _ in range(4)]
self._position_minimum_intermediate_buffer = [torch.empty(
(self.num_speakers, 3),
dtype=self.dtype,
device=self.device
) for _ in range(4)]
self._position_greater_intermediate_buffer = [torch.empty(
[self.num_speakers, 3],
dtype=torch.bool,
device=self.device
) for _ in range(4)]
self._position_sum_intermediate_buffer = [torch.empty(
self.num_speakers,
dtype=self.dtype,
device=self.device
) for _ in range(4)]
self._position_thresh_intermediate_buffer = [torch.empty(
self.num_speakers,
dtype=self.dtype,
device=self.device
) for _ in range(4)]
self._position_greater_output_intermediate_buffer = [torch.empty(
self.num_speakers,
dtype=torch.bool,
device=self.device
) for _ in range(4)]
# --- GLOBAL (Image source indices are constant) ---
self.er_indices_np = self._get_early_reflection_indices()
self.er_indices = torch.from_numpy(self.er_indices_np).to(device=self.device, dtype=self.dtype)
self.num_er_sources = len(self.er_indices) + 1 # +1 for direct path
self.dist_to_walls = torch.zeros([self.num_speakers, 6], dtype=self.dtype, device=device)
# --- GLOBAL (Optimized reflection index calculations) ---
W, H, D = self.room_dimensions
self.scaled_er_indices_w = self.er_indices[:, 0] * W
self.scaled_er_indices_h = self.er_indices[:, 1] * H
self.scaled_er_indices_d = self.er_indices[:, 2] * D
self.centered_er_indices_w = (self.er_indices[:, 0] % 2 * 2 - 1)
self.centered_er_indices_h = (self.er_indices[:, 1] % 2 * 2 - 1)
self.centered_er_indices_d = (self.er_indices[:, 2] % 2 - 1)
self.mirrors = torch.tensor([
[-1, 1, 1], [1, -1, 1], [1, 1, -1],
[-1, 1, 1], [1, -1, 1], [1, 1, -1]
], device=device, dtype=dtype)
self.offsets = torch.tensor([
[-W, 0, 0], [0, -H, 0], [0, 0, -D],
[W, 0, 0], [0, H, 0], [0, 0, D]
], device=device, dtype=dtype)
# --- GLOBAL (Cluster definitions are global) ---
self.enhanced_clusters = torch.tensor(
LocalizationBlueprint._define_optimized_clusters(), device=self.device, dtype=self.dtype
)
self.num_enhanced_clusters = len(self.enhanced_clusters)
# --- GLOBAL Late Reverb Setup ---
self.comb_delays_s = torch.tensor([0.0297, 0.0371, 0.0411, 0.0437], device=self.device, dtype=self.dtype)
self.allpass_delays_s = torch.tensor([0.0051, 0.0037], device=self.device, dtype=self.dtype)
self.late_weights = torch.tensor([0.3, 0.25, 0.25, 0.2], device=self.device, dtype=self.dtype) # Added
self.max_speakers = self.num_speakers + 50 + self.num_speakers // 2
self.buf_delta = torch.zeros((self.max_speakers, 3), device=device, dtype=dtype)
self.buf_dist_direct = torch.zeros(self.max_speakers, device=device, dtype=dtype)
self.buf_g_direct = torch.zeros(self.max_speakers, device=device, dtype=dtype)
self.buf_amp_direct = torch.zeros(self.max_speakers, device=device, dtype=dtype) # Output Accumulator
# 2. Proximity Effect Buffers
self.buf_walls_neg = torch.zeros((self.max_speakers, 3), device=device, dtype=dtype)
self.buf_walls_pos = torch.zeros((self.max_speakers, 3), device=device, dtype=dtype)
self.buf_min_wall = torch.zeros(self.max_speakers, device=device, dtype=dtype)
self.buf_indices = torch.zeros(self.max_speakers, device=device, dtype=torch.long) # for torch.min
self.buf_prox_gain = torch.zeros(self.max_speakers, device=device, dtype=dtype)
# 3. Reflection & Image Source Buffers
self.buf_img_src = torch.zeros((self.max_speakers, 6, 3), device=device, dtype=dtype)
self.buf_d_refs = torch.zeros((self.max_speakers, 6), device=device, dtype=dtype)
self.buf_amp_refs = torch.zeros((self.max_speakers, 6), device=device, dtype=dtype)
self.buf_rms_refs = torch.zeros(self.max_speakers, device=device, dtype=dtype)
# 4. Cluster & Scratch Buffers
self.buf_dist_sq = torch.zeros(self.max_speakers, device=device, dtype=dtype)
self.buf_reverb_scratch = torch.zeros(4, device=device, dtype=dtype) # Tiny buffer for reverb
self.k_decay = 0.67
self.asymptote = 0.985
self.dynamic_range = 1.8 - 0.985
self.proximity_dirty = torch.ones(self.num_speakers, dtype=torch.bool, device=self.device)
self.reflections_dirty = torch.ones(self.num_speakers, dtype=torch.bool, device=self.device)
self.hrirs_dirty = torch.ones(self.num_speakers, dtype=torch.bool, device=self.device)
self.absorption_gains_dirty = True
self.any_reflections_dirty = True
@staticmethod
def _define_optimized_clusters() -> List[Tuple[float, float]]:
"""Define optimized angular clusters (Global)."""
return [
(0, 0), # Front center
(-45, 0), # Front left
(45, 0), # Front right
(-90, 0), # Left
(90, 0), # Right
(0, 45), # Above
(0, -30), # Below
(-90, 30), # Left up (represents back/up region)
]
@staticmethod
def _get_early_reflection_indices():
"""Get image source indices for early reflections - (NumPy Init, Global)."""
return np.array([
[0, 1, 0], # top
[0, -1, 0], # bottom
[-1, 0, 0], # left
[1, 0, 0], # right
], dtype=np.float32)
def compute_rt60(self):
"""Compute RT60 (PyTorch) (Global)."""
# Remove this, that if check is a GPU Stall
# if self.absorption_db >= -0.0001:
# return self.small_val_tensor
volume = torch.prod(self.room_dimensions)
surface_area = 2 * torch.sum(self.room_dimensions * torch.roll(self.room_dimensions, 1))
alpha = 1.0 - 10 ** (self.absorption_db / 10.0)
rt60 = 0.161 * volume / (surface_area * alpha)
return torch.clamp_(rt60, min=0.1, max=1000.0)
# ============================================================================
# 1. MODIFIED CUDA KERNEL FOR 1ST-ORDER FILTERS (Prox Filter)
# ============================================================================
# This kernel is ALREADY BATCHED (B = blockIdx.x). We will use B = num_speakers.
first_order_iir_batched_N_filters_kernel = cupy.RawKernel(r'''
extern "C" __global__
void first_order_iir_batched_N_filters_kernel(
const float* x_in, // Input tensor [B, N]
float* y_out, // Output tensor [B, N]
const float* zi_in, // Input state [B]
float* zf_out, // Output state [B]
const float* b0_in, // Batched b0 [B]
const float* b1_in, // Batched b1 [B]
const float* a1_in, // Batched a1 [B]
int N_samples
) {
int batch_id = blockIdx.x; // This will be speaker_id (0 to num_speakers-1)
// Get filter coefficients for this batch item
float b0 = b0_in[batch_id];
float b1 = b1_in[batch_id];
float a1 = a1_in[batch_id];
const float* x = x_in + batch_id * N_samples;
float* y = y_out + batch_id * N_samples;
float z = zi_in[batch_id];
for (int i = 0; i < N_samples; i++) {
float xi = x[i];
float yi = b0 * xi + z;
y[i] = yi;
z = b1 * xi - a1 * yi;
}
zf_out[batch_id] = z;
}
''', 'first_order_iir_batched_N_filters_kernel')
# ============================================================================
# 3. MODIFIED CUDA KERNEL FOR PARALLEL MULTI-FILTER COMB
# ============================================================================
# This kernel is ALREADY BATCHED (speaker_id = blockIdx.x).
multi_comb_filter_N_speakers_kernel = cupy.RawKernel(r'''
extern "C" __global__
void multi_comb_filter_N_speakers_kernel(
const float* x_in, // Input signals [num_speakers, N_samples]
float* y_out, // Output signals [num_speakers, N_filters, N_samples]
float* packed_buffer, // Packed state buffer [num_speakers, sum(N_delays)]
const int* buffer_offsets, // Shared Offsets for each filter [N_filters]
int* buffer_idx_inout, // State indices [num_speakers, N_filters]
const float* feedback_in, // Feedback values [num_speakers, N_filters]
const int* N_delays_in, // Shared Delay lengths [N_filters]
int N_samples,
int N_filters, // e.g., 4
int total_N_delays // sum(N_delays)
) {
int speaker_id = blockIdx.x; // num_speakers
int filter_id = blockIdx.y; // N_filters (e.g., 4)
// Get parameters for this specific filter
int N_delays = N_delays_in[filter_id];
// Get pointers for this filter
const float* x = x_in + speaker_id * N_samples; // Shared input for this speaker
// Output: y_out[speaker_id, filter_id, sample]
float* y = y_out + (speaker_id * N_filters + filter_id) * N_samples;
// Buffer: packed_buffer[speaker_id, offset + sample]
float* buf_batch = packed_buffer + speaker_id * total_N_delays + buffer_offsets[filter_id];
// Index: buffer_idx_inout[speaker_id, filter_id]
int idx_pos = speaker_id * N_filters + filter_id;
int idx = buffer_idx_inout[idx_pos];
// Feedback: feedback_in[speaker_id, filter_id]
float feedback = feedback_in[idx_pos];
// The core logic is identical
for (int i = 0; i < N_samples; i++) {
float delayed = buf_batch[idx];
float yi = x[i] + delayed;
y[i] = yi;
buf_batch[idx] = feedback * yi;
idx++;
if (idx == N_delays) {
idx = 0;
}
}
// Write back the updated index
buffer_idx_inout[idx_pos] = idx;
}
''', 'multi_comb_filter_N_speakers_kernel')
# ============================================================================
# 5. NEW CUDA KERNEL FOR ALL-PASS FILTERS
# ============================================================================
# This kernel is ALREADY BATCHED (speaker_id = blockIdx.x).
allpass_filter_N_speakers_kernel = cupy.RawKernel(r'''
extern "C" __global__
void allpass_filter_N_speakers_kernel(
const float* x_in, // Input signals [num_speakers, N_filters, N_samples]
float* y_out, // Output signals [num_speakers, N_filters, N_samples]
float* buffer, // State buffer [num_speakers, N_filters, N_delays]
int* buffer_idx_inout, // State indices [num_speakers, N_filters]
const float* gain_in, // Gain values (g) [num_speakers, N_filters]
int N_delays, // Delay length for this filter
int N_samples,
int N_filters // e.g., 4
) {
int speaker_id = blockIdx.x; // num_speakers
int filter_id = blockIdx.y; // N_filters (e.g., 4)
// Get pointers for this filter
const float* x = x_in + (speaker_id * N_filters + filter_id) * N_samples;
float* y = y_out + (speaker_id * N_filters + filter_id) * N_samples;
// Buffer: buffer[speaker_id, filter_id, sample]
float* buf = buffer + (speaker_id * N_filters + filter_id) * N_delays;
// Index: buffer_idx_inout[speaker_id, filter_id]
int idx_pos = speaker_id * N_filters + filter_id;
int idx = buffer_idx_inout[idx_pos];
// Gain: gain_in[speaker_id, filter_id]
float g = gain_in[idx_pos];
// Loop for all samples
for (int i = 0; i < N_samples; i++) {
float delayed_v = buf[idx]; // v[n-M]
float xi = x[i]; // x[n]
// v[n] = x[n] - g*v[n-M]
float vi = xi - g * delayed_v;
// y[n] = g*v[n] + v[n-M]
float yi = g * vi + delayed_v;
y[i] = yi;
buf[idx] = vi; // Store v[n]
idx++;
if (idx == N_delays) {
idx = 0;
}
}
// Write back the updated index
buffer_idx_inout[idx_pos] = idx;
}
''', 'allpass_filter_N_speakers_kernel')
# ============================================================================
# 4. MODIFIED CUDA KERNEL WRAPPERS (Now accept pre-converted CuPy arrays)
# ============================================================================
def first_order_iir_cupy_batched(
b0_cupy: cupy.ndarray, b1_cupy: cupy.ndarray, a1_cupy: cupy.ndarray,
x_cp: cupy.ndarray,
z_cupy: cupy.ndarray,
y_out_cupy: cupy.ndarray,
stream: cupy.cuda.ExternalStream
):
"""
Batched First-order IIR using CuPy kernel.
Accepts pre-converted CuPy arrays for persistent state (z), output (y),
and coefficients (b, a).
Accepts Torch tensor for the DYNAMIC input signal (x).
"""
B, N_samples = x_cp.shape
# --- Convert DYNAMIC input (signal) ---
first_order_iir_batched_N_filters_kernel(
(B,), (1,), # Grid = (num_speakers,), Block = (1,)
(x_cp, y_out_cupy, z_cupy, z_cupy,
b0_cupy, b1_cupy, a1_cupy, N_samples),
stream=stream
)
# No return needed; y_out_cupy and z_cupy are modified in-place (and share
# memory with their corresponding torch tensors).
def multi_comb_filter_N_speakers_cupy(
x_cp: cupy.ndarray, # [num_speakers, N_samples] (Dynamic)
y_cupy: cupy.ndarray, # [num_speakers, N_filters, N_samples] (Persistent)
packed_buffer_cupy: cupy.ndarray, # [num_speakers, sum(N_delays)] (Persistent)
buffer_offsets_cupy: cupy.ndarray, # [N_filters] (Persistent)
buffer_idx_cupy: cupy.ndarray, # [num_speakers, N_filters] (Persistent)
feedback_cupy: cupy.ndarray, # [num_speakers, N_filters] (Persistent, smoothed)
N_delays_cupy: cupy.ndarray, # [N_filters] (Persistent)
total_N_delays: int, # sum(N_delays)
stream: cupy.cuda.ExternalStream
) -> None:
"""
Batched Multi-Comb Filter for N speakers.
Accepts pre-converted CuPy arrays for persistent state/buffers.
Accepts Torch tensor for DYNAMIC input (x).
"""
num_speakers, N_samples = x_cp.shape
N_filters = N_delays_cupy.shape[0]
# --- Convert DYNAMIC input (signal) ---
# Grid: (num_speakers, N_filters), Block: (1,)
multi_comb_filter_N_speakers_kernel(
(num_speakers, N_filters), (1,),
(x_cp, y_cupy,
packed_buffer_cupy, buffer_offsets_cupy, buffer_idx_cupy,
feedback_cupy, N_delays_cupy,
N_samples, N_filters, total_N_delays),
stream=stream
)
# No return needed, y_cupy is modified in-place
def allpass_filter_N_speakers_cupy(
x_cupy: cupy.ndarray, # [num_speakers, N_filters, N_samples] (Persistent)
y_cupy: cupy.ndarray, # [num_speakers, N_filters, N_samples] (Persistent)
buffer_cupy: cupy.ndarray, # [num_speakers, N_filters, N_delays] (Persistent)
buffer_idx_cupy: cupy.ndarray, # [num_speakers, N_filters] (Persistent)
gain_cupy: cupy.ndarray, # [num_speakers, N_filters] (Persistent)
N_delays: int,
stream: cupy.cuda.ExternalStream
) -> None:
"""
Batched All-Pass Filter for N speakers.
Accepts pre-converted CuPy arrays for all inputs/outputs.
NO DLPack calls needed here.
"""
num_speakers, N_filters, N_samples = x_cupy.shape
# Grid: (num_speakers, N_filters), Block: (1,)
allpass_filter_N_speakers_kernel(
(num_speakers, N_filters), (1,),
(x_cupy, y_cupy,
buffer_cupy, buffer_idx_cupy,
gain_cupy, N_delays,
N_samples, N_filters),
stream=stream
)
# No return needed, y_cupy is modified in-place
# def calculate_peak_gain_estimate(
# head_position: torch.Tensor,
# speaker_position: torch.Tensor,
# absorption_db: float,
# # Engine parameters for accurate estimation:
# min_distance: float = 0.13, # 0.05 mic + 0.08 speaker
# late_reverb_mix: float = 0.9,
# num_early_reflections: int = 4, # 4 wall reflections
# avg_reflection_distance_ratio: float = 1.5, # Images are ~1.5x farther
# ) -> torch.Tensor:
# """
# Estimates peak gain of SpaceSimulationEngine output.
#
# Models three components:
# 1. Direct path: 1/distance with proximity boost
# 2. Early reflections: Attenuated by absorption and distance
# 3. Late reverb: Diffuse field energy, independent of source distance
#
# Args:
# head_position: [N, 3] or [3] position of listener
# speaker_position: [N, 3] or [3] position of source(s)
# absorption_db: Wall absorption coefficient in dB (negative = more absorption)
# min_distance: Minimum distance for gain clamping
# late_reverb_mix: Late reverb mixing coefficient (0-1)
# num_early_reflections: Number of first-order wall reflections
# avg_reflection_distance_ratio: Average distance multiplier for image sources
#
# Returns:
# Estimated peak amplitude gain [N] or scalar
# """
# # Direct path gain (1/r law with proximity effect)
# distance = torch.linalg.norm(speaker_position - head_position, dim=-1)
# distance_clamped = torch.clamp(distance, min=min_distance)
#
# # Direct gain with approximate proximity boost
# # Engine applies high-shelf filter near walls; approximate as ~1.2x boost at min distance
# proximity_boost = 1.0 + 0.2 * torch.exp(-distance_clamped / 0.3)
# direct_gain = proximity_boost / distance_clamped
#
# # Reflection/absorption coefficient
# reflection_coef = 10.0 ** (absorption_db / 20.0) # Linear amplitude coefficient
#
# # Early reflections contribution
# # Each reflection travels farther and is attenuated by one wall bounce
# avg_image_distance = distance_clamped * avg_reflection_distance_ratio
# early_reflection_gain = (reflection_coef / avg_image_distance) * num_early_reflections
#
# # Late reverb contribution (diffuse field)
# # Models the steady-state diffuse field energy in the room
# # Key insight: Late reverb is ~independent of source distance,
# # depends mainly on room size and absorption
#
# # Approximate RT60 (Sabine equation, simplified)
# # More absorption (lower reflection_coef) → shorter RT60 → less reverb energy
# # This is a heuristic approximation; actual engine calculates RT60 from room volume
# rt60_estimate = 0.161 * (6.0 / max(0.01, 1.0 - reflection_coef ** 2)) # Seconds, order of magnitude
#
# # Diffuse field energy is proportional to RT60 and (1 - absorption)
# # The factor of ~0.3 is empirically tuned to match engine output levels
# diffuse_field_gain = 0.3 * rt60_estimate * reflection_coef * late_reverb_mix
#
# # Total peak gain is the ADDITIVE combination (not multiplicative)
# # All three components sum in the time domain
# total_peak_gain = direct_gain + early_reflection_gain + diffuse_field_gain
#
# # Apply calibration factor to match engine
# # This accounts for HRIR convolution gain, filter coefficients, etc.
# calibration = 0.435 # Empirically tuned to match ~2.3x observed offset
#
# return total_peak_gain * calibration
#
def make_shape(x, out_buffer):
return out_buffer[:x.flatten().shape[0]].reshape(x.shape)
class SpaceSimulationEngine(LocalizationBlueprint):
def __init__(
self, num_speakers=1, sample_rate=44100, block_size=256, subject='018', device='cuda', dtype=torch.float32,
stream: torch.cuda.Stream = None, present='fast', speed_of_sound=343.0
):
super().__init__(device=device, dtype=dtype, num_speakers=num_speakers, speed_of_sound=speed_of_sound)
self.sample_rate = sample_rate
self.present = present
self.block_size = block_size
self.user_block_size = block_size
self.device = device
self.dtype = dtype
self.frame_counter = 0
self.crossfade_len = block_size
self.crossfade_linspace = torch.linspace(0, math.pi, self.crossfade_len, device=self.device, dtype=self.dtype)
self.reset_mask = torch.zeros(self.num_speakers, dtype=torch.bool, device=self.device)
# --- 3. Early Reflections (Energy Sum) ---
# --- GLOBAL (1 Head) ---
self.head = Head(
num_speakers=num_speakers, block_size=block_size, subject=subject, device=self.device, dtype=self.dtype
)
# We do this for efficient, head delta computation for sparse, speaker parameter updates
self.last_head_positions = torch.zeros((self.num_speakers, 3), device=device, dtype=dtype)
# Use self.num_speakers from base class
print(f"Initializing SpaceSimulationEngine for {self.num_speakers} speakers.")
# --- Physical Parameters (Global) ---
self.mic_radius = 0.05
self.speaker_radius = 0.08
self.min_distance = torch.tensor(self.mic_radius + self.speaker_radius, device=self.device, dtype=self.dtype)
self.num_precise_reflections = 4
# --- BATCHIFIED Early Reflections Setup ---
self.er_delay_line_size = 8192
is_power_of_two = (self.er_delay_line_size & (self.er_delay_line_size - 1) == 0) and self.er_delay_line_size > 0
assert is_power_of_two, "er_delay_line_size MUST be a power of 2 for fast bitwise masking."
self.er_size_mask = self.er_delay_line_size - 1
self.er_delay_line = torch.zeros((self.num_speakers, self.er_delay_line_size), device=self.device,
dtype=self.dtype)
self.er_write_head = 0 # Global write head, as all speakers are processed in sync
# --- BATCHIFIED Per-reflection parameters ---
self.reflection_delays = torch.zeros((self.num_speakers, self.num_er_sources), device=self.device,
dtype=torch.long)
self.reflection_gains = torch.zeros((self.num_speakers, self.num_er_sources), device=self.device,
dtype=self.dtype)
self.reflection_positions = torch.zeros((self.num_speakers, self.num_er_sources, 3), device=self.device,
dtype=self.dtype)
# --- NEW: State for parameter interpolation ---
self.prev_reflection_delays = torch.zeros_like(self.reflection_delays)
self.prev_reflection_gains = torch.zeros_like(self.reflection_gains)
# --- BATCHIFIED Proximity Filter (CUDA) ---
self.prox_filter_zi_torch = torch.zeros(self.num_speakers, device=self.device, dtype=self.dtype)
self.prox_filter_b0 = torch.ones(self.num_speakers, device=self.device, dtype=self.dtype)
self.prox_filter_b1 = torch.zeros(self.num_speakers, device=self.device, dtype=self.dtype)
self.prox_filter_a1 = torch.zeros(self.num_speakers, device=self.device, dtype=self.dtype)
self.prox_filter_output_buffer = torch.zeros((self.num_speakers, self.block_size), device=self.device,
dtype=self.dtype)
# Calculate delayed signal with CURRENT parameters
self.delayed_signal_out = {
0: torch.empty([self.num_speakers, self.block_size, self.num_precise_reflections], dtype=torch.float32,
device=self.device),
1: torch.empty([self.num_speakers, self.block_size, self.num_precise_reflections], dtype=torch.float32,
device=self.device),
2: torch.empty([self.num_speakers, self.block_size, self.num_er_sources - self.num_precise_reflections],
dtype=torch.float32, device=self.device),
3: torch.empty([self.num_speakers, self.block_size, self.num_er_sources - self.num_precise_reflections],
dtype=torch.float32, device=self.device),
}
self.read_indices_intermediate = {
0: torch.empty([self.num_speakers, self.block_size, self.num_precise_reflections], dtype=torch.long,
device=self.device),
1: torch.empty([self.num_speakers, self.block_size, self.num_precise_reflections], dtype=torch.long,