File size: 15,549 Bytes
2e20433
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Two-time RIR interpolation for moving sources AND moving receivers.

y[r] = sum_i,j receiver_basis_j(r) * conv(source_basis_i * x, h_ij)[r]

h_ij is actually rendered in the same room at source position i and receiver
position j. Source weights use emission time; receiver weights use reception
time, including the entire reverberant tail. This is a quasi-static numerical
approximation, not an exact wave-equation or exact Doppler simulator.
"""
from __future__ import annotations

import argparse
import math
import os
from pathlib import Path
import socket
import time

import numpy as np
import soundfile as sf
from scipy.signal import fftconvolve, resample_poly

from .common import SR, position, read, sha, uid, write


def nodes(entity, step):
    if not np.any(entity['displacement_m']):
        return [0.]
    end = entity['motion_duration_s']
    return sorted(set([round(float(t), 9) for t in np.arange(0., end, step)]+[end]))


def basis(knots, i, samples):
    t = np.asarray(samples, dtype=float)/SR
    if len(knots)==1:
        return np.ones_like(t)
    center=knots[i];w=np.ones_like(t)
    if i:
        w=np.where(t<center,(t-knots[i-1])/(center-knots[i-1]),w)
    if i+1<len(knots):
        w=np.where(t>=center,(knots[i+1]-t)/(knots[i+1]-center),w)
    return np.clip(w,0.,1.)


def two_time_convolution(dry, source_nodes, receiver_nodes, kernel, max_tail_s=3.5):
    n=len(dry);out=np.zeros((n,4),np.float64)
    samples=np.arange(n)
    for i,te in enumerate(source_nodes):
        piece=dry*basis(source_nodes,i,samples)
        nz=np.flatnonzero(piece)
        if not len(nz):continue
        lo,hi=int(nz[0]),int(nz[-1])+1
        for j,tr in enumerate(receiver_nodes):
            rw=basis(receiver_nodes,j,samples)
            nzr=np.flatnonzero(rw[lo:min(n,hi+math.ceil(max_tail_s*SR))])
            if not len(nzr):continue
            h=kernel(te,tr)
            if len(h)>math.ceil(max_tail_s*SR):
                raise ValueError('RIR support exceeds declared interpolation horizon')
            y=fftconvolve(piece[lo:hi,None],h,axes=0)
            end=min(n,lo+len(y))
            if end-lo<len(y):
                total=float(np.sum(y*y));tail=float(np.sum(y[end-lo:]**2))
                if tail>max(total,1e-30)*1e-7:
                    raise ValueError('Significant output reverberation tail would be truncated')
            out[lo:end]+=y[:end-lo]*rw[lo:end,None]
    return out.astype(np.float32)


def visible(a,b,room):
    a,b=np.asarray(a),np.asarray(b)
    for box in room['surfaces'][6:]:
        low,high=0.,1.;lo=np.asarray(box['location'])-np.asarray(box['size'])/2
        hi=np.asarray(box['location'])+np.asarray(box['size'])/2
        for axis in range(3):
            d=b[axis]-a[axis]
            if abs(d)<1e-12:
                if not lo[axis]<=a[axis]<=hi[axis]:low=2.;break
            else:
                x,z=sorted(((lo[axis]-a[axis])/d,(hi[axis]-a[axis])/d))
                low=max(low,x);high=min(high,z)
        if low<=high and high>1e-4 and low<1-1e-4:return False
    return True


def validate_geometry(recipe):
    room=recipe['room'];width,height,depth=room['room_size_m']
    constraints=recipe.get('motion_constraints',{})
    clearance=constraints.get('wall_and_furniture_clearance_m',.25)
    audit=[]
    for scene in recipe['scenes']:
        entities=scene['humans']+scene['robots'];t=np.arange(0.,scene['duration_samples']/SR,.025)
        minimum=float('inf')
        for e in entities:
            p=position(e,t)
            if not (np.all(np.abs(p[:,0])<width/2-clearance) and np.all(np.abs(p[:,2])<depth/2-clearance)):
                raise ValueError('Trajectory crosses a wall: '+e['entity_id'])
            for box in room['surfaces'][6:]:
                size=np.asarray(box['size'])[[0,2]]/2+clearance
                if np.any(np.all(np.abs(p[:,[0,2]]-np.asarray(box['location'])[[0,2]])<size,axis=1)):
                    raise ValueError('Body footprint crosses furniture: '+e['entity_id'])
            speed=1.875*np.linalg.norm(e['displacement_m'])/e['motion_duration_s']
            distance=float(np.linalg.norm(e['displacement_m']))
            if distance and distance<=constraints.get('minimum_moving_displacement_m',0.):
                raise ValueError('Moving entity displacement is too short: '+e['entity_id'])
            if e['motion_duration_s']>scene['duration_samples']/SR:
                raise ValueError('Motion endpoint is outside the recorded clip')
            limit=constraints.get('maximum_human_speed_mps',.8) if e['entity_type']=='human' else constraints.get('maximum_robot_speed_mps',.45)
            if speed>limit:raise ValueError('Trajectory speed above frozen limit')
        for i,e in enumerate(entities):
            for f in entities[i+1:]:
                distance=np.linalg.norm((position(e,t)-position(f,t))[:,[0,2]],axis=1)
                minimum=min(minimum,float(distance.min()))
        if minimum<constraints.get('minimum_entity_clearance_m',.6):raise ValueError('Human/robot collision clearance failed')
        audit.append(dict(scene_id=scene['scene_id'],minimum_horizontal_clearance_m=minimum,
            entity_displacements_m={e['entity_id']:float(np.linalg.norm(e['displacement_m'])) for e in entities},
            maximum_human_speed_mps=max(1.875*np.linalg.norm(e['displacement_m'])/e['motion_duration_s'] for e in scene['humans']),
            maximum_robot_speed_mps=max(1.875*np.linalg.norm(e['displacement_m'])/e['motion_duration_s'] for e in scene['robots'])))
    return audit


class Renderer:
    def __init__(self,root,recipe,cache,position_fn=position):
        # quaternion must precede habitat_sim on this pinned native runtime.
        import quaternion
        import habitat_sim
        self.hs=habitat_sim;self.root=root;self.recipe=recipe;self.cache=cache;self.position=position_fn
        self.cache.mkdir(parents=True,exist_ok=True);self.records={}
        context_path=self.cache/'cache_context.json'
        context=dict(renderer=recipe['renderer'],foa_mapping=recipe['foa_mapping'],
            room_assets_sha256=recipe['room_assets_sha256'])
        if context_path.exists() and read(context_path)!=context:
            raise ValueError('RIR cache belongs to a different renderer, mapping or room')
        write(context_path,context)
        folder=root/'assets/room'
        for name,h in recipe['room_assets_sha256'].items():
            if sha(folder/name)!=h:raise ValueError('Room asset changed: '+name)
        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
        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 k,v in recipe['renderer'].items():
            if hasattr(spec.acousticsConfig,k):setattr(spec.acousticsConfig,k,v)
        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):
        a=self.position(source,te);b=self.position(receiver,tr);yaw=receiver['yaw_deg']
        key=uid(self.recipe['room_assets_sha256'],*[round(float(x),7) for x in np.r_[a,b,yaw]])
        path=self.cache/(key+'.npy');meta=self.cache/(key+'.json')
        if path.exists() and meta.exists():
            record=read(meta)
            if sha(path)!=record['sha256']:raise ValueError('Cached RIR hash mismatch')
            self.records[key]=record
            return np.load(path,allow_pickle=False)
        agent=self.sim.get_agent(0);state=agent.get_state()
        state.position=np.asarray(b,np.float32);state.rotation=np.quaternion(1.,0.,0.,0.)
        state.sensor_states={};agent.set_state(state,True)
        self.sensor.setAudioSourceTransform(np.asarray(a,np.float32))
        native=np.asarray(self.sim.get_sensor_observations()['audio_sensor'],np.float32)
        if native.shape[0]!=4:native=native.T
        m=self.recipe['foa_mapping'];w=m['w_polarity']*native[m['w_channel']]
        axes={axis:item['polarity']*native[item['channel']]/math.sqrt(3.) for axis,item in m['world_axis_mapping'].items()}
        q=math.radians(yaw);right=math.cos(q)*axes['world_x']+math.sin(q)*axes['world_z']
        front=math.sin(q)*axes['world_x']-math.cos(q)*axes['world_z']
        h=np.stack([w,-right,axes['world_y'],front])
        energy=np.sum(h.astype(float)**2,axis=0);total=float(energy.sum())
        if not np.isfinite(h).all() or total<=0:raise ValueError('Invalid native RIR')
        first=int(np.flatnonzero(energy>energy.max()*1e-5)[0])
        peak=first+int(np.argmax(energy[first:first+17]))
        v=h[:,peak];actual=np.array([-v[1],v[2],-v[3]])*np.sign(v[0]);actual/=np.linalg.norm(actual)
        d=a-b;local=np.array([math.cos(q)*d[0]+math.sin(q)*d[2],d[1],-math.sin(q)*d[0]+math.cos(q)*d[2]])
        distance=float(np.linalg.norm(d));expected=local/distance
        error=float(np.degrees(np.arccos(np.clip(np.dot(actual,expected),-1,1))))
        los=visible(a,b,self.recipe['room']);delay=peak/32000.
        if los and (error>3. or abs(delay-distance/343.)>.003):
            raise ValueError('Native direct path direction/delay failed: '+str((error,delay,distance)))
        tail=float(energy[-1600:].sum()/total)
        if tail>1e-7:raise ValueError('Native RIR has significant truncated tail')
        # Retain energy to 1e-11, stricter than the output-tail acceptance test.
        remaining=np.cumsum(energy[::-1])[::-1]/total
        end=int(np.flatnonzero(remaining>1e-11)[-1])+1
        h=resample_poly(h[:,:end],1,2,axis=1).T.astype(np.float32)
        np.save(path,h,allow_pickle=False)
        record=dict(rir_id=key,sha256=sha(path),source_xyz_m=a.tolist(),receiver_xyz_m=b.tolist(),
            receiver_yaw_deg=yaw,los=los,direct_angle_error_deg=error,direct_delay_s=delay,
            geometric_delay_s=distance/343.,native_final_50ms_energy_fraction=tail,
            retained_samples=len(h),sample_rate_hz=SR)
        write(meta,record);self.records[key]=record
        print('RIR',len(self.records),key,round(error,3),'deg',flush=True)
        return h

    def close(self):self.sim.close()


def make_dry(root,scene):
    dry={};gains=[]
    for s in scene['humans']+scene['playback_sources']:
        x=np.zeros(scene['duration_samples'],np.float32)
        for e in s['events']:
            p=root/e['audio_asset']
            if sha(p)!=e['original_source_sha256']:raise ValueError('Source checksum changed')
            full,sr=sf.read(p,dtype='float32');a,b=e['crop_samples'];wave=full[a:b].copy()
            if sr!=SR:raise ValueError('Source sample rate changed')
            fade=min(128,len(wave)//2);wave[:fade]*=np.linspace(0,1,fade);wave[-fade:]*=np.linspace(1,0,fade)
            mask=np.zeros(len(wave),bool)
            for lo,hi in e['activity_samples']:
                mask[max(0,lo-e['start_sample']):min(len(wave),hi-e['start_sample'])]=True
            gain=10**(s['emitted_rms_dbfs']/20)/max(np.sqrt(np.mean(wave[mask].astype(float)**2)),1e-12)
            x[e['start_sample']:e['end_sample']]+=wave*gain
            gains.append(dict(event_id=e['event_id'],dry_gain=float(gain)))
        dry[s['entity_id']]=x
    return dry,gains


def render_all(root,work):
    if 'debug' in socket.gethostname().lower() and not os.environ.get('DISH_ALLOW_LOCAL_RENDER'):
        raise RuntimeError('Use an allocated CPU job here, or explicitly allow a local reproduction machine')
    recipe=read(root/'data/recipe.json');geometry_audit=validate_geometry(recipe)
    engine=Renderer(root,recipe,work/'rirs');mixes={};stems={};gains=None
    start=time.monotonic()
    try:
        for scene in recipe['scenes']:
            dry,gains=make_dry(root,scene)
            for receiver in scene['robots']:
                rid=receiver['entity_id'];key=(scene['branch'],rid)
                signal=np.zeros((scene['duration_samples'],4),np.float64)
                rn=nodes(receiver,recipe['receiver_node_step_s'])
                for source in scene['humans']+scene['playback_sources']:
                    sid=source['entity_id']
                    if sid==rid:continue
                    print('STEM',scene['branch'],rid,sid,flush=True)
                    sn=nodes(source,recipe['source_node_step_s'])
                    stem=two_time_convolution(dry[sid],sn,rn,lambda te,tr:engine.kernel(source,receiver,te,tr))
                    stems[(scene['branch'],rid,sid)]=stem;signal+=stem
                mixes[key]=signal.astype(np.float32)
        peak=max(float(np.max(np.abs(x))) for x in mixes.values());gain=.9/peak
        records=[];stem_records=[];scene_ids={s['branch']:s['scene_id'] for s in recipe['scenes']}
        for (branch,rid),wave in mixes.items():
            folder=root/'audio'/branch;folder.mkdir(parents=True,exist_ok=True)
            wave=(wave*gain).astype(np.float32)
            path=folder/(rid+'_foa.wav');sf.write(path,wave,SR,subtype='FLOAT')
            # Two symmetric virtual cardioid microphones: a stereo audition,
            # not an HRTF/binaural measurement, and never the model input.
            stereo=np.column_stack([.5*wave[:,0]+.5*wave[:,1],.5*wave[:,0]-.5*wave[:,1]])
            preview=folder/(rid+'_preview.wav');sf.write(preview,stereo,SR,subtype='PCM_16')
            records.append(dict(branch=branch,receiver_id=rid,path=str(path.relative_to(root)),
                preview_path=str(preview.relative_to(root)),sha256=sha(path),preview_sha256=sha(preview),
                sample_rate_hz=SR,channels=['W','Y','Z','X'],normalization='SN3D',ordering='ACN',
                samples=len(wave),recording_id=uid(scene_ids[branch],rid,'recording'),global_start_sample=0))
        stemdir=work/'stems';stemdir.mkdir(parents=True,exist_ok=True)
        for (branch,rid,sid),wave in stems.items():
            p=stemdir/(branch+'_'+rid+'_'+sid+'.npy');np.save(p,(wave*gain).astype(np.float32))
            stem_records.append(dict(branch=branch,receiver_id=rid,source_id=sid,path=str(p),sha256=sha(p)))
        result=dict(passed=True,rendering_method=recipe['rendering_method'],
            common_final_gain=gain,original_peak=peak,dry_gains=gains,recordings=records,
            geometry_audit=geometry_audit,rir_records=list(engine.records.values()),
            stem_records=stem_records,wall_seconds=time.monotonic()-start,
            human_listening_audit_completed=False,model_inference_performed=False)
        write(work/'render.complete.json',result)
        public=dict(result);public.pop('stem_records')
        write(root/'data/rendering.json',public)
        print('RENDER COMPLETE',len(records),'recordings',len(engine.records),'RIRs',flush=True)
    finally:engine.close()


if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('--root',type=Path,required=True);p.add_argument('--work',type=Path,required=True)
    a=p.parse_args();render_all(a.root.resolve(),a.work.resolve())