"""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,(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-lomax(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])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 minimumenergy.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())