File size: 16,966 Bytes
347d9a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Per-hall-family FOA rendering on a selected allocated GPU.

RLR acoustic propagation remains the pinned SoundSpaces native implementation.
GPU selection is explicit; sources/receivers use their actual scene positions.
Only temporary kernels are discarded. Metadata, SIR/SNR and acceptance reports
are retained. Noise emission gains are calibrated by the static job and shared
unchanged by the dynamic job.
"""
from __future__ import annotations

import argparse
import fcntl
import gzip
import json
import math
import os
from pathlib import Path
import shutil
import tempfile
import time

import numpy as np
import soundfile as sf

from dynamic_demo.render import Renderer, make_dry, two_time_convolution
from dynamic_dataset.runtime import ensure_compute
from .common import *
from .noise import waveform as noise_waveform
from .plan import audit_geometry


class NativeRenderer(Renderer):
    """Use the existing audited kernel conversion with explicit GPU selection."""
    def __init__(self, root, recipe, cache, gpu):
        import quaternion
        import habitat_sim
        self.hs, self.root, self.recipe, self.cache, self.position = habitat_sim, root, recipe, cache, position
        cache.mkdir(parents=True, exist_ok=True)
        self.records = {}
        context = dict(renderer=recipe['renderer'], foa_mapping=recipe['foa_mapping'],
                       room_assets_sha256=recipe['room_assets_sha256'])
        path = cache/'cache_context.json'
        if path.exists() and read(path) != context:
            raise ValueError('Recovery cache belongs to another acoustic recipe')
        write(path, context)
        folder = root/'assets/room'
        for name, digest in recipe['room_assets_sha256'].items():
            if sha(folder/name) != digest:
                raise ValueError('Frozen room asset checksum mismatch')
        config = habitat_sim.SimulatorConfiguration()
        config.scene_id = str(folder/'stage.stage_config.json')
        config.scene_dataset_config_file = str(folder/'dataset.scene_dataset_config.json')
        config.load_semantic_mesh = True
        config.enable_physics = False
        config.gpu_device_id = gpu
        if hasattr(config, 'random_seed'):
            config.random_seed = 20260826
        self.sim = habitat_sim.Simulator(habitat_sim.Configuration(config, [habitat_sim.agent.AgentConfiguration()]))
        if not self.sim.semantic_scene:
            raise ValueError('Acoustic semantic scene was not loaded')
        spec = habitat_sim.AudioSensorSpec()
        spec.uuid = 'audio_sensor'
        spec.channelLayout.channelType = habitat_sim.sensor.RLRAudioPropagationChannelLayoutType.Ambisonics
        spec.channelLayout.channelCount = 4
        spec.position = [0., 0., 0.]
        for key, value in recipe['renderer'].items():
            if hasattr(spec.acousticsConfig, key):
                setattr(spec.acousticsConfig, key, value)
        self.sim.add_sensor(spec)
        self.sensor = self.sim.get_agent(0)._sensors['audio_sensor']
        self.sensor.setAudioMaterialsJSON(str(folder/'materials.json'))

    def kernel(self, source, receiver, te, tr):
        h = super().kernel(source, receiver, te, tr)
        # Peak-packet DRR is a stated approximation, and only labelled for LOS.
        a, b = position(source, te), position(receiver, tr)
        key = __import__('dynamic_demo.common', fromlist=['uid']).uid(
            self.recipe['room_assets_sha256'], *[round(float(x), 7) for x in np.r_[a, b, receiver['yaw_deg']]])
        record = self.records[key]
        if 'early_to_late_energy_ratio_db' not in record:
            energy = h[:, 0].astype(float)**2
            peak = round(record['direct_delay_s']*SR)
            left, right = max(0, peak-8), min(len(h), peak+40)
            early = float(energy[left:right].sum())
            late = max(float(energy.sum())-early, 1e-30)
            record.update(early_to_late_energy_ratio_db=10*math.log10(max(early, 1e-30)/late),
                          drr_proxy_valid=record['los'], drr_proxy_window_s=[-.0005, .0025])
        return h


def source_mask(source, samples):
    mask = np.zeros(samples, bool)
    for event in source['events']:
        for a, b in event['activity_samples']:
            mask[max(0, a):min(samples, b)] = True
    return mask


def fixed_source(spec, ordinal=0):
    return dict(entity_id='N'+str(ordinal+1).zfill(2), entity_type='noise',
                initial_xyz_m=spec['source_positions_world_m'][ordinal], displacement_m=[0., 0., 0.],
                motion_start_s=0., motion_duration_s=1., yaw_deg=0)


def noise_component(root, episode, receiver, engine):
    spec = episode['noise']
    count = episode['duration_samples']
    # Supply a prehistory so steady noise is already reverberant at scene zero.
    pre = math.ceil(engine.recipe['renderer']['irTime']*SR)
    dry = noise_waveform(spec, count+pre, root)
    dry = np.r_[dry, np.zeros(pre+1, np.float32)]
    rn = sorted(set([0., pre/SR] + [round(t+pre/SR, 9) for t in rir_nodes(receiver)]))
    result = np.zeros((count, 4), np.float64)
    for ordinal in range(len(spec['source_positions_world_m'])):
        source = fixed_source(spec, ordinal)
        rendered = two_time_convolution(dry, [0.], rn,
            lambda te, tr: engine.kernel(source, receiver, 0., max(0., tr-pre/SR)),
            max_tail_s=engine.recipe['renderer']['irTime']+.001)
        result += rendered[pre:pre+count]
    return result.astype(np.float32)


def calibration(root, group, engine, dry_cache):
    path = root/'private/noise_calibration'/(group['group_id']+'.json')
    if path.exists():
        return read(path)
    baseline = group['static_episodes'][0]
    source, receiver = baseline['humans'][0], baseline['robots'][0]
    dry = make_dry(root, baseline)[0][source['entity_id']]
    target = two_time_convolution(dry, [0.], [0.], lambda te, tr: engine.kernel(source, receiver, te, tr),
                                  max_tail_s=group['renderer']['irTime']+.001)
    noise = noise_component(root, baseline, receiver, engine)
    mask = source_mask(source, len(dry))
    signal_power = float(np.mean(target[mask, 0].astype(float)**2))
    noise_power = float(np.mean(noise[mask, 0].astype(float)**2))
    if signal_power <= 0 or noise_power <= 0:
        raise ValueError('Invalid anchor signal/noise power')
    result = dict(group_id=group['group_id'], reference_mode='static', reference_robot_id='R01',
                  reference_source_id='H01', channel='W', mask='target emitted-speech activity intervals',
                  signal_power=signal_power, unit_noise_power=noise_power,
                  gains={str(int(level)): math.sqrt(signal_power/(noise_power*10**(level/10))) for level in [20., 10., 0.]},
                  shared_across_all_robots_and_modes=True)
    write(path, result)
    return result


def render_group(root, group, mode, gpu, cache_dir):
    # Shared-filesystem advisory locks prevent duplicate writers when a second
    # allocated node helps an existing queue. The lock inode stays in place;
    # the OS releases ownership if a stalled native process is killed.
    root,cache_dir=Path(root),Path(cache_dir)
    lock_path=root/mode/'reports/locks'/(group['group_id']+'.lock')
    lock_path.parent.mkdir(parents=True,exist_ok=True)
    cache_dir.mkdir(parents=True,exist_ok=True)
    with lock_path.open('a+') as lock:
        while True:
            try:
                fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
                break
            except BlockingIOError:
                write(cache_dir/'progress.json',dict(wall_time=time.time(),waiting_for='group_render_lock'))
                time.sleep(5)
        try:
            return _render_group(root,group,mode,gpu,cache_dir)
        finally:
            fcntl.flock(lock,fcntl.LOCK_UN)


def _render_group(root, group, mode, gpu, cache_dir):
    result_path = root/mode/'reports/groups'/(group['group_id']+'.json')
    if result_path.exists():
        result = read(result_path)
        if not result['passed']:
            raise ValueError('Previous group report did not pass')
        for recording in result['recordings']:
            if sha(root/mode/recording['path']) != recording['sha256']:
                raise ValueError('Completed audio changed; cannot silently resume')
        return result
    ensure_compute()
    started = time.monotonic()
    cache_dir = Path(cache_dir)
    engine_root = cache_dir/'engine'
    (engine_root/'assets').mkdir(parents=True, exist_ok=True)
    link = engine_root/'assets/room'
    if not link.exists():
        link.symlink_to(root/'shared/rooms'/group['room_id']/'assets/room', target_is_directory=True)
    engine = NativeRenderer(engine_root, group, cache_dir/'rirs', gpu)
    original_kernel = engine.kernel
    def progress_kernel(source, receiver, te, tr):
        write(cache_dir/'progress.json', dict(wall_time=time.time(), source_id=source['entity_id'],
              receiver_id=receiver['entity_id'], source_time_s=te, receiver_time_s=tr))
        return original_kernel(source, receiver, te, tr)
    engine.kernel = progress_kernel
    components = {}
    dry_cache = {}
    records, measurements, checks = [], [], []
    try:
        calibration_result = None
        if group['family_type'] == 'noise':
            if mode == 'static':
                calibration_result = calibration(root, group, engine, dry_cache)
            else:
                path = root/'private/noise_calibration'/(group['group_id']+'.json')
                for _ in range(360):
                    if path.exists():
                        break
                    write(cache_dir/'progress.json',dict(wall_time=time.time(),waiting_for='static_noise_calibration'))
                    time.sleep(5)
                if not path.exists():
                    raise TimeoutError('Static-job shared noise calibration is missing')
                calibration_result = read(path)
        for episode in group[mode+'_episodes']:
            if audit_geometry(episode, group['room'], group['family_type'] == 'count') is None:
                raise ValueError('Frozen episode failed independent geometry validation')
            dry, _ = make_dry(root, episode)
            for receiver in episode['robots']:
                rid = receiver['entity_id']
                stems = {}
                for source in episode['humans'] + episode['playback_sources']:
                    sid = source['entity_id']
                    if sid == rid:
                        continue
                    fingerprint = uid('stem', source, receiver, episode['duration_samples'])
                    if fingerprint not in components:
                        components[fingerprint] = two_time_convolution(dry[sid], rir_nodes(source), rir_nodes(receiver),
                            lambda te, tr, source=source: engine.kernel(source, receiver, te, tr),
                            max_tail_s=group['renderer']['irTime']+.001)
                    stems[sid] = components[fingerprint]
                noise = np.zeros((episode['duration_samples'], 4), np.float32)
                if episode['noise']['enabled']:
                    noise_key = uid('noise', episode['noise']['seed'], episode['noise'].get('recording'),
                                    receiver, episode['duration_samples'])
                    if noise_key not in components:
                        components[noise_key] = noise_component(root, episode, receiver, engine)
                    gain = calibration_result['gains'][str(int(episode['noise']['nominal_snr_db']))]
                    noise = components[noise_key]*gain
                speech = sum((w.astype(np.float64) for w in stems.values()), np.zeros_like(noise, dtype=np.float64))
                wave = (speech+noise).astype(np.float32)
                if not np.isfinite(wave).all() or not np.any(wave):
                    raise ValueError('Non-finite or silent FOA recording')
                path = root/mode/'public/audio/test'/episode['episode_id']/(rid+'_foa.wav')
                path.parent.mkdir(parents=True, exist_ok=True)
                temporary = path.with_suffix('.tmp.wav')
                sf.write(temporary, wave, SR, subtype='FLOAT')
                temporary.replace(path)
                readback, rate = sf.read(path, dtype='float32')
                np.testing.assert_array_equal(readback, wave)
                if rate != SR:
                    raise ValueError('Stored FOA sample-rate mismatch')
                record = dict(recording_id=uid(episode['episode_id'], rid, 'recording'),
                    episode_id=episode['episode_id'], scene_id=episode['scene_id'], episode_group_id=group['group_id'],
                    receiver_robot_id=rid, path=str(path.relative_to(root/mode)), sha256=sha(path),
                    num_samples=len(wave), sample_rate_hz=SR, num_channels=4, channels=['W','Y','Z','X'],
                    ordering='ACN', normalization='SN3D', subtype='FLOAT', global_start_sample=0,
                    common_final_gain=1., raw_peak=float(np.max(np.abs(wave))))
                records.append(record)
                checks.append(dict(episode_id=episode['episode_id'], receiver_id=rid,
                    own_playback_excluded=True, source_ids=list(stems), noise_included=episode['noise']['enabled'],
                    all_finite=True, source_stem_reconstruction_max_error=float(np.max(np.abs(wave.astype(float)-(speech+noise)))),
                    tail_energy_fraction=float(np.sum(wave[-8000:].astype(float)**2)/np.sum(wave.astype(float)**2))))
                for human in episode['humans']:
                    mask = source_mask(human, len(wave))
                    target = stems[human['entity_id']][:, 0].astype(float)
                    interference = speech[:, 0]-target
                    sp = float(np.mean(target[mask]**2))
                    ip = float(np.mean(interference[mask]**2))
                    npower = float(np.mean(noise[mask, 0].astype(float)**2))
                    ratio = lambda denominator: 10*math.log10(sp/denominator) if sp > 0 and denominator > 1e-30 else None
                    visibility = [dict(time_s=s/SR, visible=__import__('dynamic_demo.render', fromlist=['visible']).visible(
                        position(human, s/SR), position(receiver, s/SR), group['room'])) for s in grid(episode)]
                    measurements.append(dict(episode_id=episode['episode_id'], receiver_id=rid, source_id=human['entity_id'],
                        mask='target emitted-speech activity intervals; W-channel received energy',
                        target_power=sp, competing_speech_power=ip, environmental_noise_power=npower,
                        sir_db=ratio(ip), snr_db=ratio(npower), sinr_db=ratio(ip+npower),
                        visibility=visibility, nominal_snr_db=episode['noise'].get('nominal_snr_db')))
            print('EPISODE RENDERED', mode, group['index'], episode['branch'], len(engine.records), 'RIRs', flush=True)
        rir_log = root/mode/'private/rir_audits'/(group['group_id']+'.jsonl.gz')
        rir_log.parent.mkdir(parents=True, exist_ok=True)
        with gzip.open(rir_log, 'wt') as output:
            for record in sorted(engine.records.values(), key=lambda r:r['rir_id']):
                output.write(json.dumps(record, separators=(',', ':'), allow_nan=False)+'\n')
        result = dict(passed=True, group_id=group['group_id'], index=group['index'], mode=mode,
            scene_id=group['scene_id'], room_id=group['room_id'], family_type=group['family_type'],
            episode_ids=[e['episode_id'] for e in group[mode+'_episodes']], recordings=records,
            acoustic_measurements=measurements, audio_checks=checks, rir_audit_path=str(rir_log.relative_to(root/mode)),
            rir_audit_sha256=sha(rir_log), rir_count=len(engine.records), raw_peak=max(r['raw_peak'] for r in records),
            final_normalization_applied=False, gpu_device_id=gpu, wall_seconds=time.monotonic()-started,
            label_step_s=.5, source_rir_step_s=.2, receiver_rir_step_s=.2,
            human_listening_audit_completed=False, model_inference_performed=False)
        write(result_path, result)
        print('GROUP COMPLETE', mode, group['index'], len(records), 'FOA', round(result['wall_seconds'], 1), 's', flush=True)
        return result
    finally:
        engine.close()


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--root', type=Path, required=True)
    parser.add_argument('--mode', choices=['static','dynamic'], required=True)
    parser.add_argument('--index', type=int, required=True)
    parser.add_argument('--gpu', type=int, required=True)
    parser.add_argument('--cache-dir', type=Path, required=True)
    a = parser.parse_args()
    group = read(a.root/'private/plans'/f'{a.index:04d}.json')
    render_group(a.root.resolve(), group, a.mode, a.gpu, a.cache_dir)