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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import pyroomacoustics as pra
import numpy as np
import random
import json
import os, glob
import sofa
import torch
import torchaudio.transforms as AT
from data.utils import read_audio_file

from scipy.signal import convolve
from scipy.ndimage import convolve1d


import time

class BaseSimulator(object):
    def __init__(self):    
        pass
    
    def preprocess(self, audio):
        return audio
        
    def postprocess(self, audio):
        return audio
            
    def randomize_sources(self, num_sources):
        pass
    
    def get_metadata(self):
        metadata = {}
        
        metadata['duration'] = self.D
        metadata['sofa'] = self.sofa
        
        metadata['mic_positions'] = self.mic_positions

        metadata['sources'] = []
        for i, source_id in enumerate(self.source_order):
            source = {'position':self.source_positions[i], 
                      'order':source_id,
                      'hrtf_index':self.hrtf_indices[i],
                      'label':self.source_labels[i]}
            metadata['sources'].append(source)

        metadata['num_background'] = self.num_background_sources
        
        return metadata

    def save(self, path):
        metadata = self.get_metadata()
        
        with open(path, 'w') as f:
            json.dump(metadata, f, indent=4)

    def simulate(self, audio: np.ndarray) -> np.ndarray:
        """
        Simulates RIR
        audio: (C x T)
        """
        num_sources = audio.shape[0]
       
        #t1 = time.time()

        rirs = self.get_rirs()

        #t2 = time.time()

        #t_rir = t2 - t1
        
        #t1 = time.time()
        x = self.preprocess(audio)

        output = []
        for i in range(num_sources):
            rir = rirs[i]
            waveform = x[i]
            
            left = convolve(waveform, rir[0])
            left = self.postprocess(left)
            
            right = convolve(waveform, rir[1])
            right = self.postprocess(right)
            
            binaural = np.stack([left, right])
            # Clean and renormalize so downstream sox int32 cast stays safe
            binaural = np.nan_to_num(binaural, nan=0.0, posinf=0.0, neginf=0.0)
            peak = np.max(np.abs(binaural))
            if peak >= 1.0:
                binaural = binaural / (peak + 1e-8)
            binaural = np.clip(binaural, -0.9999999, 0.9999999)
            output.append(binaural)

        output = np.array(output, dtype=np.float32)
        #t2 = time.time()

        #t_convolve = t2 - t1

        #print('RIR time:', t_rir)
        #print('Convolution time:', t_convolve)

        return output
    
    def initialize_room_with_random_params(self,
                                           num_sources: int,
                                           duration: float,
                                           ann_list: list, 
                                           nbackground_sources: int = 1):
        self.D = duration

        self.source_labels = []
        for i in range(num_sources):
            self.source_labels.append(ann_list[i])

        # Randomize source choose order
        # First k sources correspond to background sources
        # Next n - k sources are foreground sources
        n = num_sources
        k = nbackground_sources
        self.source_order = [i for i in range(n - k)]
        np.random.shuffle(self.source_order)
        self.source_order = [i for i in range(n - k, n)] + self.source_order

        self.num_background_sources = k

        return self

    def seed(self, seed_value):
        np.random.seed(seed_value)
        random.seed(seed_value)
        
class CATTRIR_Simulator(BaseSimulator):
    def __init__(self, dset_text_file, **kwargs) -> None:
        super().__init__()
        
        dset_dir = os.path.dirname(dset_text_file)
        with open(dset_text_file, 'r') as f:
            self.rt60_list = f.read().split('\n')
            self.rt60_dirs = [os.path.join(dset_dir, x) for x in self.rt60_list]

    def randomize_sources(self, num_sources):
        source_positions = []
        hrtf_indices = []
        rirs = sorted(os.listdir(self.room_dir))
        random_source_rir_wavs = random.sample(rirs, num_sources)
        
        angles = []
        for f in random_source_rir_wavs:
            angle = int(f[f.rfind('_')+1:-4])
            angles.append(angle)
        
        for i in range(num_sources):
            pos = [np.cos(np.deg2rad(angle)), np.sin(np.deg2rad(angle))]
            source_positions.append(pos)
            hrtf_indices.append(angle)

        return source_positions, hrtf_indices
    
    def get_rirs(self):
        num_sources = len(self.source_positions)
        rt60 = os.path.basename(self.room_dir)
        
        rirs = []
        for i in range(num_sources):
            path = os.path.join(self.room_dir, f'CATT_{rt60}_{self.hrtf_indices[i]}.wav')
            rir = read_audio_file(path, 44100)
            rirs.append(rir.astype(np.float32))
        
        return rirs
            
    def initialize_room_with_random_params(self,
                                           num_sources: int,
                                           duration: float,
                                           ann_list: list, 
                                           nbackground_sources: int = 1):
        
        self.room_dir = self.rt60_dirs[np.random.randint(len(self.rt60_dirs))]
        self.sofa = self.room_dir # TODO: Implement this better
        
        self.mic_positions = [[0, 0.9, 0], [0, -0.9, 0]]
        self.source_positions, self.hrtf_indices = self.randomize_sources(num_sources) 
        
        return super().initialize_room_with_random_params(num_sources, 
                                                       duration,
                                                       ann_list,
                                                       nbackground_sources)
        
class SOFASimulator(BaseSimulator):
    def __init__(self, sofa_text_file, **kwargs) -> None:
        super().__init__()
        self.hrtf_cache = {}
        self.sofa_dict = {}
        sofa_dir = os.path.dirname(sofa_text_file)
        with open(sofa_text_file, 'r') as f:
            raw_lines = f.read().splitlines()

        # Sanitize list: trim whitespace/CRLF, drop blanks and comments
        self.subject_sofa_list = [
            line.strip() for line in raw_lines
            if line.strip() and not line.strip().startswith('#')
        ]

        # Resolve paths relative to list file directory; normalize and validate
        self.sofa_files = []
        for entry in self.subject_sofa_list:
            path = entry if os.path.isabs(entry) else os.path.join(sofa_dir, entry)
            path = os.path.normpath(path)
            if not os.path.exists(path):
                raise FileNotFoundError(
                    f"SOFA file listed in {sofa_text_file} not found: {repr(path)}"
                )
            self.sofa_files.append(path)

        for fpath in self.sofa_files:
            self.sofa_dict[fpath] = sofa.Database.open(fpath)
        
        self.kwargs = kwargs

    def initialize_room_with_random_params(self,
                                           num_sources: int,
                                           duration: float,
                                           ann_list: list, 
                                           nbackground_sources: int = 1):
        
        self.sofa = self.sofa_files[np.random.randint(len(self.sofa_files))]
        self.HRTF = self.sofa_dict[self.sofa]#sofa.Database.open(self.sofa)
        mic_positions = self.HRTF.Receiver.Position.get_values(system="cartesian")[..., 0]
        self.mic_positions = mic_positions.tolist()
        self.source_positions, self.hrtf_indices = self.randomize_sources(num_sources) 
        
        return super().initialize_room_with_random_params(num_sources, 
                                                       duration,
                                                       ann_list,
                                                       nbackground_sources)
    def get_rirs(self):
        num_sources = len(self.source_positions)
        rirs = []
        for i in range(num_sources):
            key = self.sofa + str(sorted(list(self.hrtf_indices[i].items())))
            #print('KEY', key)
            if key in self.hrtf_cache:
                rir = self.hrtf_cache[key]
            else:
                rir = self.HRTF.Data.IR.get_values(indices=self.hrtf_indices[i]).astype(np.float32)
                self.hrtf_cache[key] = rir.copy()
            rirs.append(rir)
        return rirs
    
class CIPIC_Simulator(SOFASimulator):
    def randomize_sources(self, num_sources):
        source_positions = []
        hrtf_indices = []
        random_source_positions = random.sample(range(self.HRTF.Dimensions.M), num_sources)
        for i in range(num_sources):
            sofa_indices = {"M":random_source_positions[i]}
            pos = self.HRTF.Source.Position.get_values(system="cartesian", indices=sofa_indices).tolist()
            source_positions.append(pos)
            hrtf_indices.append(sofa_indices)

        return source_positions, hrtf_indices

    
class CIPIC_HRTF_Simulator(CIPIC_Simulator): pass

class BRIR48kHz_Simulator(CIPIC_HRTF_Simulator):
    def __init__(self, sofa_text_file, **kwargs):
        super().__init__(sofa_text_file, **kwargs)
        self.presampler = AT.Resample(self.kwargs['sr'], 48000)
        self.postsampler = AT.Resample(48000, self.kwargs['sr'])
    
    def preprocess(self, audio: np.ndarray) -> np.ndarray:
        audio = self.presampler(torch.from_numpy(audio))
        return audio.numpy()
    
    def postprocess(self, audio: np.ndarray) -> np.ndarray:
        audio = self.postsampler(torch.from_numpy(audio))
        return audio.numpy()

    
# Salford-BBC Spatially-sampled Binaural Room Impulse Responses
# https://usir.salford.ac.uk/id/eprint/30868/
class SBSBRIR_Simulator(BRIR48kHz_Simulator):    
    def randomize_sources(self, num_sources):
        source_positions = []
        hrtf_indices = []
        
        random_source_positions = random.sample(range(self.HRTF.Dimensions.E), num_sources)
        random_measurement_rotation = np.random.randint(self.HRTF.Dimensions.M)
        for i in range(num_sources):
            #sofa_indices = {"M":0, "E":0}
            sofa_indices = {"M":random_measurement_rotation, "E":random_source_positions[i]}
            pos = self.HRTF.Emitter.Position.get_values(system="cartesian", indices=sofa_indices).tolist()
            source_positions.append(pos)
            hrtf_indices.append(sofa_indices)

        return source_positions, hrtf_indices
    
    def preprocess(self, audio: np.ndarray) -> np.ndarray:
        audio = super().preprocess(audio)
        audio = audio * 15

        return audio # Gain because RIRs are very low for some reason
    
# Real Room BRIRs
# https://github.com/IoSR-Surrey/RealRoomBRIRs
class RRBRIR_Simulator(BRIR48kHz_Simulator): pass
    
class Multi_Ch_Simulator(BaseSimulator):
    # simulators = [CIPIC_Simulator]
    # simulators = [ CATTRIR_Simulator]
    # simulators = [ SBSBRIR_Simulator]
    # simulators = [RRBRIR_Simulator]
    # simulators = [SBSBRIR_Simulator, RRBRIR_Simulator, CATTRIR_Simulator] # UNCOMMENT FOR REVERBED HRTF ONLY
    def __init__(self, hrtf_dir, dset_type: str, sr: int, reverb: bool = True) -> None:
        self.hrtf_dir = hrtf_dir
        self.dset = dset_type
        self.sr = sr
        
        if reverb:
            simulators = [CIPIC_Simulator, SBSBRIR_Simulator, RRBRIR_Simulator, CATTRIR_Simulator] 
        else:
            simulators = [CIPIC_Simulator]
        
        #simulators = [SBSBRIR_Simulator]
        self.simulators = [sim(os.path.join(self.hrtf_dir, sim.__name__[:-len("_Simulator")], self.dset + '_hrtf.txt'), sr=self.sr) for sim in simulators]

    def get_random_simulator(self) -> BaseSimulator:
        sim = random.choice(self.simulators)
        #print("Using simulator", type(sim))
        return sim#(os.path.join(self.hrtf_dir, sim.__name__[:-len("_Simulator")], self.dset + '_hrtf.txt'),sr=self.sr)

class PRASimulator(object):
    def __init__(self,
                 n_mics = 2,
                 min_absorption=0.6,
                 max_absorption=1,
                 fs=44100,
                 max_order=15,
                 mean_mic_distance=13.9,
                 mic_distance_var=0.7,
                 mic_array_keepout=0.5,
                 min_room_length=6,
                 max_room_length=8,
                 min_room_width=6,
                 max_room_width=8) -> None:
        """
        Mic distance is by default the average of the
        median Bitragion Breadth for men and women
        """
        # Constant across samples
        self.M = n_mics
        self.fs = fs
        self.K = mic_array_keepout
        self.max_order = max_order
        self.min_absorption = min_absorption
        self.max_absorption = max_absorption
        self.R = mean_mic_distance
        self.V = mic_distance_var

        self.min_room_length = min_room_length
        self.max_room_length = max_room_length
        self.min_room_width = min_room_width
        self.max_room_width = max_room_width

    def initialize_room_with_random_params(self, num_sources: int, duration: float):
        self.D = duration
        self.mic_distance = np.random.normal(self.R, scale=self.V ** 0.5) * 1e-2
        self.mic_positions = [[-self.mic_distance/2, 0], [self.mic_distance/2, 0]]
        self.absorption = np.random.uniform(self.min_absorption, self.max_absorption)
        
        self.L = np.random.uniform(self.min_room_length, self.max_room_length)
        self.W = np.random.uniform(self.min_room_width, self.max_room_width)

        self.left_wall = -self.L / 2
        self.right_wall = self.L / 2
        
        self.bottom_wall = -self.W / 2
        self.top_wall = self.W / 2
        
        self.source_positions = []
        for i in range(num_sources):
            source_pos = self._get_random_source_pos(self.left_wall,
                                                    self.right_wall,
                                                    self.bottom_wall,
                                                    self.top_wall,
                                                    self.K)
            self.source_positions.append(source_pos)

        # Randomize source choose order
        self.source_order = [i for i in range(num_sources - 1)]
        np.random.shuffle(self.source_order)
        self.source_order = [num_sources-1] + self.source_order # Background is always last

        return self

    def intialize_from_metadata(self, metadata_path):
        with open(metadata_path, 'r') as f:
            metadata = json.load(f)

        self.D = metadata['duration']
        self.M = metadata['n_mics']
        self.fs = metadata['sampling_rate']
        self.max_order = metadata['max_order']
        self.absorption = metadata['absorption']
        self.mic_distance = metadata['mic_distance']
        self.mic_positions = metadata['mic_positions']

        room_desc = metadata['room']
        self.L = room_desc['length']
        self.W = room_desc['width']

        self.left_wall = -self.L / 2
        self.right_wall = self.L / 2
        
        self.bottom_wall = -self.W / 2
        self.top_wall = self.W / 2

        self.source_order = []
        self.source_positions = []

        source_list = metadata['sources']
        for source in source_list:
            source_id = source['order']
            source_position = source['position']
            
            self.source_order.append(source_id)
            self.source_positions.append(source_position)

        return self

    def get_metadata(self):
        metadata = {}
        
        metadata['duration'] = self.D
        metadata['sampling_rate'] = self.fs
        metadata['max_order'] = self.max_order
        
        metadata['n_mics'] = self.M
        metadata['absorption'] = self.absorption
        metadata['mic_distance'] = self.mic_distance
        metadata['mic_positions'] = self.mic_positions
        
        room_desc = {}
        room_desc['length'] = self.L
        room_desc['width'] = self.W
        metadata['room'] = room_desc

        metadata['sources'] = []
        for i, source_id in enumerate(self.source_order):
            source = {'position':self.source_positions[i], 'order':source_id}
            metadata['sources'].append(source)
        
        return metadata

    def save(self, path):
        metadata = self.get_metadata()
        
        with open(path, 'w') as f:
            json.dump(metadata, f, indent=4)

    def simulate(self,
                 source_audio):
        """
        Input: list of source_audio (T,)
        returns y (M, T)
        """
        
        corners = np.array([[self.left_wall, self.bottom_wall],
                            [self.right_wall, self.bottom_wall],
                            [self.right_wall, self.top_wall],
                            [self.left_wall, self.top_wall]]).T

        room = pra.room.Room.from_corners(corners,
                              absorption=self.absorption,
                              fs=self.fs,
                              max_order=self.max_order)

        mic_array = np.array(self.mic_positions).T#pra.circular_2D_array(center=[0., 0.], M=self.M, phi0=180, radius=self.mic_distance * 0.5 * 1e-2)
        room.add_microphone_array(mic_array)

        for i, source_pos in enumerate(self.source_positions):
            room.add_source(source_pos, signal=source_audio[i])

        y = room.simulate(return_premix=True)

        total_samples = int(round(self.D * self.fs))
        return y[..., :total_samples]

    def _get_random_source_pos(self, L, R, B, T, K):
        pos = [0, 0]

        while np.linalg.norm(pos) < K:
            x = np.random.uniform(L, R)
            y = np.random.uniform(B, T)

            pos = [x, y]

        return pos


def test():
    n_sources = 5
    duration = 1
    save_path = 'mymetadata.json'
    
    simulator = PRASimulator().initialize_room_with_random_params(n_sources, duration)
    simulator.save(save_path)

    simulator2 = PRASimulator().intialize_from_metadata(save_path)
    
    x = [np.random.random(44100) for i in range(n_sources)]
    # x = [np.sin(2 * np.pi * 440 * np.arange(0, 1, 1/44100)) for i in range(n_sources)]
    y = simulator2.simulate(x) * 1e3

    import soundfile as sf
    sf.write('audio.wav', y[0].T, 44100)


if __name__ == "__main__":
    test()