taillab.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. #!/usr/bin/env python3
  2. """taillab.py — reverb / modulation measurement lab and the TAIL SCORE (round 190bp).
  3. The waveform score (scripts/fxparity.py score(), untouched) needs a waveform null, which a recirculating or
  4. modulated effect cannot give: two correct renders of the same reverb do not null against each other. This lab
  5. measures what a tail *is* — decay per octave band, early decay, echo-density build-up, spectral balance over time,
  6. stereo correlation over time, time variance (modulation) — and scores two renders on those, blind to phase and to
  7. the modulators' phase. Both scores are always reported side by side; the tail score never replaces the old one.
  8. Black box only: the inputs are WAV renders (tools/fxrender for LYNX, recorded host renders for references).
  9. taillab.py pair <ref.wav> <lynx.wav> [--stim <stimulus.wav>] [--kind verb|delay|mod] [--dry <gL>,<gR>,<latency>]
  10. one pair: the measurements, the sub-scores and the tail score of that file (JSON)
  11. taillab.py dir <ref-dir> <lynx-dir> --stim <stim-dir> [--kind verb|delay|mod] [--json out.json]
  12. every <setting>_<signal>.wav present in both: wave score (fxparity) and tail score per file, per setting
  13. and for the row. A setting's dry gain is read off its impulse render and removed from all its files.
  14. taillab.py stats <render.wav> [--stim <stimulus.wav>] measurements of one impulse render (JSON)
  15. taillab.py pilot <render.wav> <hz> [t0 t1] modulation rate / depth seen on a steady pilot tone
  16. taillab.py probes <out-dir> [rate] writes the lab's stimuli (impulses at three levels each
  17. followed by a noise burst, pilot tones, pink noise)
  18. taillab.py engine <fxrender> <effect> <probe-dir> <out-dir> [fxrender options...]
  19. renders the probes through one LYNX effect and prints its decay / density / stereo / modulation table
  20. taillab.py selftest unit tests of the metric code (synthetic signals)
  21. Impulse stimulus layout (tp172b/c/d `impulse.wav` and `probes`): one sample impulse, silence, then a noise burst.
  22. The stretch after the impulse is the impulse response; the burst is used for the time-variance index: a linear
  23. time-invariant effect answers the burst with (impulse response * burst), any modulation makes it differ.
  24. Tail score, per setting: mean of the impulse half and the programme half. Every part is 10 at a match and falls
  25. linearly to 0 at the distance `FULL[part]`; a half is 10 minus the quadratic mean of what its parts miss (agg):
  26. impulse half
  27. decay |log2 ratio| of T20 and T30 per octave band (late-slope RT where the range is too short)
  28. early EDT per octave band (|log2|), clarity C80 (dB) and pre-delay (ms)
  29. relief energy decay relief: |dB| between the per-band Schroeder curves on a 20 ms grid, level removed
  30. density echo density (Abel & Huang NED): time to 0.5 and 0.9, and the late value
  31. balance octave-band spectrum of four time slices of the response (shape only)
  32. stereo L/R correlation per octave band in the same time slices
  33. mod time-variance index per octave band (burst answer vs. the answer predicted from the impulse response)
  34. level energy of the wet response
  35. dry (only where a dry path is present) its gain; its latency is taken as the effect's time zero
  36. programme half (drums, music, ...: the wet part of each render)
  37. kind verb (diffuse tails):
  38. spec long-term third-octave spectrum of the wet part, level removed
  39. env level over time of the wet part in three wide bands (below 300 Hz, to 3 kHz, above), 160 ms
  40. level mean third-octave level difference
  41. stereo L/R correlation per octave band 500 Hz - 8 kHz
  42. kind delay / mod (deterministic effects; mod compares the whole output, the others the wet part):
  43. spec third-octave x 20 ms energy map, level removed (frames smoothed until each cell holds enough samples)
  44. level energy
  45. stereo L/R correlation per octave band x 200 ms (delay) / per octave band over the file (mod: a flanger's
  46. correlation moves with its LFO phase)
  47. motion (kind mod only) modulation spectrum 0.25-16 Hz of the band transfer and of the L/R level difference
  48. Every distance of the diffuse-tail parts first loses its dead zone (DZ): the amount two phase-realisations of one
  49. reverb differ by on that estimator, so that a dense reverb scores >= 9.5 against its own second render (measured:
  50. LYNX against itself at another modulator phase 9.6 ... 10; sparse cloud modes, whose response is a handful of
  51. echoes rather than a diffuse field, repeat only to 7.7 ... 9.1 - on the reference as well).
  52. """
  53. import json
  54. import os
  55. import sys
  56. import numpy as np
  57. sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
  58. import fxparity # noqa: E402
  59. OCT = (63, 125, 250, 500, 1000, 2000, 4000, 8000)
  60. THIRDS = tuple(50.0 * 2 ** (k / 3.0) for k in range(26)) # 50 Hz ... 16 kHz
  61. SLICES = ((0.0, 0.08), (0.08, 0.3), (0.3, 1.0), (1.0, 3.0)) # seconds after the onset
  62. GRID = 0.02 # s, relief / programme map frame
  63. # distance at which a part scores 0 (see the module text). Changing one changes every tail score: bump VERSION.
  64. FULL = {'decay': 0.5, 'edt': 1.0, 'c80': 6.0, 'predelay': 30.0, 'relief': 6.0, 'ned_t': 2.0, 'ned_late': 0.5,
  65. 'balance': 6.0, 'stereo': 0.5, 'mod': 0.5, 'level': 6.0, 'spec': 6.0, 'motion': 10.0}
  66. # Dead zones: what two phase-realisations of one and the same reverb differ by on these estimators (sampling noise of
  67. # a band of width B over a time T goes with 1/sqrt(B T); the programme constants are the largest distance between two
  68. # recordings of one reference state on the banks' drums / music, see the anchors in docs/PARITY.md). A distance inside its dead zone is no evidence.
  69. DZ = {'t20': 1.0, 't30': 0.6, 'edt': 2.0, 'balance': 4.0, 'corr': 1.13, 'relief': 3.5, 'level': 0.2, 'c80': 0.2,
  70. 'p_spec': 0.4, 'p_env': 0.65, 'p_level': 0.15, 'p_stereo': 0.03}
  71. P_FULL = 4.0 # dB of long-term spectrum / envelope difference that costs all points (kind verb)
  72. VERSION = 1
  73. BW = tuple(c * (2 ** 0.5 - 2 ** -0.5) for c in OCT) # octave bandwidths, Hz
  74. NED_GAUSS = 0.3173105078629141 # erfc(1 / sqrt(2))
  75. def lin(d, full):
  76. return float(max(0.0, 10.0 * (1.0 - d / full)))
  77. def db(x):
  78. return 10.0 * np.log10(np.maximum(x, 1e-30))
  79. def agg(parts):
  80. """A half's score from its parts: 10 minus the quadratic mean of what each part misses. One part that is plainly
  81. wrong (a decay time off by a factor) therefore weighs more than the same points spread thinly over all parts."""
  82. v = np.array(list(parts.values()), float)
  83. return round(float(10.0 - np.sqrt(np.mean((10.0 - v) ** 2))), 3) if len(v) else None
  84. # ------------------------------------------------------------------------------------------------ filters
  85. def band_signals(x, sr, centers=OCT):
  86. """Zero-phase octave bands of a mono signal (FFT masks with raised edges a third of an octave wide that sum
  87. to one between neighbours). Returns [len(centers), len(x)]."""
  88. n = 1 << int(np.ceil(np.log2(len(x) + sr // 4)))
  89. X = np.fft.rfft(x, n)
  90. lf = np.log2(np.maximum(np.fft.rfftfreq(n, 1.0 / sr), 1e-9))
  91. out = np.empty((len(centers), len(x)))
  92. for k, c in enumerate(centers):
  93. lo, hi = c / 2 ** 0.5, min(c * 2 ** 0.5, sr * 0.47)
  94. w = np.clip((lf - np.log2(lo)) * 3 + 0.5, 0, 1) * np.clip((np.log2(hi) - lf) * 3 + 0.5, 0, 1)
  95. out[k] = np.fft.irfft(X * w, n)[:len(x)]
  96. return out
  97. def frames(p, hop):
  98. n = len(p) // hop
  99. return p[:n * hop].reshape(n, hop).sum(1)
  100. # ------------------------------------------------------------------------------------------------ decay
  101. def decay_curve(p, sr, hop_s=0.005):
  102. """Schroeder decay of an energy signal p (per sample, starting at the onset). The integration stops where the
  103. response meets its floor (or the end of the capture) and the missing rest is added as the integral of the
  104. late exponential, so a capture shorter than the tail does not bend the curve. Returns (edc dB per 5 ms frame,
  105. late-slope RT60 or None, usable frames)."""
  106. hop = max(1, int(hop_s * sr))
  107. e = frames(p, hop)
  108. if len(e) < 12 or e.max() <= 0:
  109. return np.zeros(1), None, 0
  110. sm = np.convolve(e, np.ones(5) / 5.0, 'same')
  111. pk = int(np.argmax(sm))
  112. noise = float(np.mean(e[-max(4, len(e) // 20):]))
  113. above = np.flatnonzero(sm > noise * 4.0)
  114. end = int(above[-1]) + 1 if len(above) else len(e)
  115. low = np.flatnonzero(sm[pk:] < sm[pk] * 1e-6) # below -60 dB the band filters' own skirts take over
  116. if len(low):
  117. end = min(end, pk + int(low[0]))
  118. end = max(end, min(len(e), pk + 10))
  119. rt_late, comp = None, 0.0
  120. a = pk + int((end - pk) * 0.4)
  121. if end - a >= 8:
  122. seg = np.log(np.maximum(sm[a:end], 1e-300))
  123. k, c = np.polyfit(np.arange(a, end), seg, 1)
  124. if k < -1e-9:
  125. rt_late = float(-np.log(1e6) / k * hop / sr)
  126. comp = float(np.exp(c + k * end) / (1.0 - np.exp(k)))
  127. tail = np.cumsum(e[:end][::-1])[::-1] + comp
  128. return db(tail / tail[0]), rt_late, end
  129. def rt_from(edc, hop_s, hi, lo):
  130. """RT60 from the regression of a decay curve between hi and lo dB (None if the curve does not get there)."""
  131. i0, i1 = int(np.argmax(edc <= hi)), int(np.argmax(edc <= lo))
  132. if edc.min() > lo or i1 <= i0 + 3:
  133. return None
  134. k = np.polyfit(np.arange(i0, i1) * hop_s, edc[i0:i1], 1)[0]
  135. return float(-60.0 / k) if k < 0 else None
  136. # ------------------------------------------------------------------------------------------------ echo density
  137. def ned_curve(x, sr, win_s=0.025, hop_s=0.005):
  138. """Normalised echo density (Abel & Huang 2006): share of samples outside one standard deviation in a sliding
  139. Hann-weighted window, over the Gaussian share. ~0 for a few isolated echoes, ~1 for a dense (Gaussian) tail."""
  140. w, hop = int(win_s * sr), int(hop_s * sr)
  141. n = (len(x) - w) // hop + 1
  142. if n < 1:
  143. return np.zeros(0), np.zeros(0)
  144. idx = np.arange(w)[None, :] + hop * np.arange(n)[:, None]
  145. fr = x[idx]
  146. wt = np.hanning(w)
  147. wt /= wt.sum()
  148. var = (fr ** 2 * wt).sum(1)
  149. out = ((np.abs(fr) > np.sqrt(var)[:, None]) * wt).sum(1) / NED_GAUSS
  150. return out, var
  151. def ned_stats(x, sr):
  152. """Time (s, window centre from the start of x) at which the NED first stays above 0.5 / 0.9, the late NED
  153. (0.15 - 0.6 s) and the curve."""
  154. ned, var = ned_curve(x, sr)
  155. if len(ned) < 8:
  156. return {'t50': None, 't90': None, 'late': None}
  157. sm = np.convolve(np.pad(ned, 1, 'edge'), np.ones(3) / 3.0, 'valid')
  158. live = var > var.max() * 1e-7
  159. t = (np.arange(len(ned)) * 0.005) + 0.0125
  160. def first(th):
  161. ok = (sm >= th) & live
  162. return float(t[int(np.argmax(ok))]) if ok.any() else None
  163. late = (t >= 0.15) & (t <= 0.6) & live
  164. return {'t50': first(0.5), 't90': first(0.9), 'late': float(ned[late].mean()) if late.sum() >= 4 else None}
  165. # ------------------------------------------------------------------------------------------------ probe layout
  166. def find_probe(stim, sr):
  167. """Impulse index, its amplitude and the noise burst's sample range in an impulse stimulus (None if it is not one)."""
  168. idx = np.flatnonzero(np.abs(stim[:, 0]) > 1e-9)
  169. if len(idx) == 0 or (len(idx) > 1 and idx[1] - idx[0] < int(0.05 * sr)):
  170. return None
  171. later = idx[1:]
  172. burst = (int(later[0]), int(later[-1]) + 1) if len(later) > 100 else None
  173. return {'imp': int(idx[0]), 'amp': float(stim[idx[0], 0]), 'burst': burst}
  174. def dry_path(out, stim, sr=48000, maxlag=256):
  175. """Dry path of an impulse render: (gain left, gain right, latency in samples). The render deconvolved by its
  176. stimulus (impulse + noise burst) is the response itself; a dry path is one isolated positive spike within the
  177. first `maxlag` samples (a plug-in latency), the same on both channels, at least 0.1 and twice anything else
  178. there. Its gain is then read exactly at the impulse sample. (0, 0, 0) if there is none."""
  179. probe = find_probe(stim, sr)
  180. n = min(len(out), len(stim))
  181. nf = 1 << int(np.ceil(np.log2(n + maxlag + 1)))
  182. m = np.zeros(maxlag + 1)
  183. for c in (0, 1):
  184. S = np.fft.rfft(stim[:n, c], nf)
  185. p = np.abs(S) ** 2
  186. m += np.abs(np.fft.irfft(np.fft.rfft(out[:n, c], nf) * np.conj(S) / (p + 1e-4 * p.max() + 1e-30), nf)[:maxlag + 1])
  187. k = int(np.argmax(m))
  188. rest = m.copy()
  189. rest[max(0, k - 3):k + 4] = 0.0
  190. if probe is None or probe['imp'] + k >= len(out) or m[k] < 2.0 * rest.max():
  191. return (0.0, 0.0, 0)
  192. i = probe['imp']
  193. g = [float(out[i + k, c] / stim[i, c]) if abs(stim[i, c]) > 1e-9 else 0.0 for c in (0, 1)]
  194. if min(g) < 0.1 or abs(g[0] - g[1]) > 0.03 * max(g): # positive, and the same on both sides
  195. return (0.0, 0.0, 0)
  196. return (g[0], g[1], k)
  197. def wet_of(out, stim, g):
  198. """The render minus its dry path g = (gain left, gain right, latency)."""
  199. w = out.copy()
  200. lag = int(g[2]) if len(g) > 2 else 0
  201. n = min(len(out) - lag, len(stim))
  202. if n > 0:
  203. w[lag:lag + n, 0] -= g[0] * stim[:n, 0]
  204. w[lag:lag + n, 1] -= g[1] * stim[:n, 1]
  205. return w
  206. # ------------------------------------------------------------------------------------------------ impulse stats
  207. def impulse_stats(out, stim, sr, g=None):
  208. """Measurements of an impulse render (see the module text). `out`, `stim`: [n, 2]."""
  209. probe = find_probe(stim, sr)
  210. if probe is None:
  211. raise ValueError('stimulus is not an impulse probe')
  212. if g is None:
  213. g = dry_path(out, stim, sr)
  214. wet = wet_of(out, stim, g)
  215. lag = int(g[2]) if len(g) > 2 else 0 # the effect's latency: its time zero
  216. i0 = probe['imp'] + lag
  217. i1 = probe['burst'][0] + lag if probe['burst'] else len(wet)
  218. h = wet[i0:min(i1, len(wet))]
  219. st = {'sr': sr, 'dry': [round(float(g[0]), 4), round(float(g[1]), 4)], 'latency': lag}
  220. p = (h ** 2).sum(1)
  221. tot = float(p.sum())
  222. st['energy_db'] = float(db(tot / (probe['amp'] ** 2)))
  223. if tot <= 1e-20:
  224. st['silent'] = True
  225. return st
  226. cum = np.cumsum(p)
  227. on = int(np.argmax(cum >= tot * 1e-3))
  228. st['predelay_ms'] = on / sr * 1000.0
  229. n80 = on + int(0.08 * sr)
  230. st['c80_db'] = float(db(cum[min(n80, len(cum) - 1)] / max(tot - cum[min(n80, len(cum) - 1)], 1e-30)))
  231. st['centre_ms'] = float((p[on:] * np.arange(len(p) - on)).sum() / max(p[on:].sum(), 1e-30) / sr * 1000.0)
  232. bl, br = band_signals(h[:, 0], sr), band_signals(h[:, 1], sr)
  233. pb = bl ** 2 + br ** 2 # [band, n]
  234. bt = pb.sum(1)
  235. st['band_db'] = [float(v) for v in db(bt / tot)]
  236. valid = bt > bt.max() * 1e-5
  237. t20, t30, edt, late, relief = [], [], [], [], []
  238. ng = max(1, int(GRID / 0.005))
  239. for k in range(len(OCT)):
  240. edc, rl, _ = decay_curve(pb[k, on:], sr)
  241. ok = bool(valid[k])
  242. t20.append(rt_from(edc, 0.005, -5.0, -25.0) if ok else None)
  243. t30.append(rt_from(edc, 0.005, -5.0, -35.0) if ok else None)
  244. edt.append(rt_from(edc, 0.005, 0.0, -10.0) if ok else None)
  245. late.append(rl if ok else None)
  246. # relief relative to the impulse time, in dB re the response's total energy
  247. full, _, _ = decay_curve(np.concatenate([np.zeros(on), pb[k, on:]]), sr) if on else (edc, None, 0)
  248. relief.append((full + db(bt[k] / tot))[::ng])
  249. n = min(len(r) for r in relief)
  250. st['relief'] = np.array([r[:n] for r in relief])
  251. st['t20'], st['t30'], st['edt'], st['rt_late'] = t20, t30, edt, late
  252. bb, _, _ = decay_curve(p[on:], sr)
  253. st['t30_bb'] = rt_from(bb, 0.005, -5.0, -35.0)
  254. st['edc_bb'] = bb[::ng]
  255. # echo density on each channel, averaged
  256. nl, nr = ned_stats(h[on:, 0], sr), ned_stats(h[on:, 1], sr)
  257. st['ned'] = {k: (None if nl[k] is None or nr[k] is None else 0.5 * (nl[k] + nr[k])) for k in nl}
  258. # time slices: band balance and L/R correlation
  259. bal, cor, wid = [], [], []
  260. for a, b in SLICES:
  261. s0, s1 = on + int(a * sr), min(on + int(b * sr), len(h))
  262. if s1 - s0 < int(0.03 * sr) or pb[:, s0:s1].sum() < tot * 1e-6:
  263. bal.append(None), cor.append(None), wid.append(None)
  264. continue
  265. e = pb[:, s0:s1].sum(1)
  266. bal.append([float(v) for v in db(e / e.sum())])
  267. ll, rr = (bl[:, s0:s1] ** 2).sum(1), (br[:, s0:s1] ** 2).sum(1)
  268. lr = (bl[:, s0:s1] * br[:, s0:s1]).sum(1)
  269. cor.append([float(v) if e[k] > e.max() * 1e-4 else None for k, v in enumerate(lr / np.sqrt(ll * rr + 1e-300))])
  270. wid.append(float(db((ll + rr - 2 * lr).sum() / max((ll + rr + 2 * lr).sum(), 1e-30))))
  271. st['balance'], st['corr'], st['width_db'] = bal, cor, wid
  272. # time-variance index: the burst's answer against the one a time-invariant system would give
  273. st['tvi'] = None
  274. if probe['burst'] and probe['burst'][0] < len(wet):
  275. b0, b1 = probe['burst']
  276. m = int(min(1.3 * sr, len(wet) - b0 - lag, len(h)))
  277. if m > (b1 - b0):
  278. nf = 1 << int(np.ceil(np.log2(m + (b1 - b0) + 8)))
  279. tv_e, tv_l = [], []
  280. pred, act = [], []
  281. for c in (0, 1):
  282. pr = np.fft.irfft(np.fft.rfft(h[:m, c] / probe['amp'], nf) * np.fft.rfft(stim[b0:b1, c], nf), nf)[:m]
  283. pred.append(band_signals(pr, sr))
  284. act.append(band_signals(wet[b0 + lag:b0 + lag + m, c], sr))
  285. split = b1 - b0
  286. for k in range(len(OCT)):
  287. for lst, (s0, s1) in ((tv_e, (0, split)), (tv_l, (split, m))):
  288. num = sum(((act[c][k, s0:s1] - pred[c][k, s0:s1]) ** 2).sum() for c in (0, 1))
  289. den = sum((act[c][k, s0:s1] ** 2).sum() + (pred[c][k, s0:s1] ** 2).sum() for c in (0, 1))
  290. lst.append(float(min(1.0, num / den)) if den > 0 and valid[k] else None)
  291. st['tvi'] = {'during': tv_e, 'after': tv_l}
  292. return st
  293. def _pairs(a, b):
  294. return [(x, y) for x, y in zip(a, b) if x is not None and y is not None]
  295. def impulse_score(A, B):
  296. """Sub-scores and their mean for LYNX's impulse stats B against the reference's A."""
  297. if A.get('silent') or B.get('silent'):
  298. return {'score': 0.0 if B.get('silent') and not A.get('silent') else None, 'parts': {}}
  299. d = {}
  300. # decay: T20 and T30 where both have them, the late-slope RT otherwise
  301. ds = []
  302. def rtd(x, y, k, key):
  303. return max(0.0, abs(np.log2(y / x)) - DZ[key] / np.sqrt(BW[k] * x))
  304. for k in range(len(OCT)):
  305. got = False
  306. for key in ('t20', 't30'):
  307. x, y = A[key][k], B[key][k]
  308. if x and y:
  309. ds.append(rtd(x, y, k, key))
  310. got = True
  311. elif (x is None) != (y is None) and A['rt_late'][k] and B['rt_late'][k]:
  312. ds.append(rtd(A['rt_late'][k], B['rt_late'][k], k, 't20'))
  313. got = True
  314. if not got and A['rt_late'][k] and B['rt_late'][k]:
  315. ds.append(rtd(A['rt_late'][k], B['rt_late'][k], k, 't20'))
  316. d['decay'] = float(np.mean(ds)) if ds else FULL['decay']
  317. parts = {'decay': lin(d['decay'], FULL['decay'])}
  318. pe = [rtd(x, y, k, 'edt') for k, (x, y) in enumerate(zip(A['edt'], B['edt'])) if x and y]
  319. d['edt'] = float(np.mean(pe)) if pe else FULL['edt']
  320. d['c80'] = max(0.0, abs(A['c80_db'] - B['c80_db']) - DZ['c80'])
  321. d['predelay'] = abs(A['predelay_ms'] - B['predelay_ms'])
  322. parts['early'] = float(np.mean([lin(d['edt'], FULL['edt']), lin(min(d['c80'], 12.0), FULL['c80']),
  323. lin(d['predelay'], FULL['predelay'])]))
  324. # relief: cells of the reference within 45 dB of its strongest, until its broadband curve is 40 dB down
  325. ra, rb = A['relief'], B['relief']
  326. n = min(ra.shape[1], rb.shape[1])
  327. stop = int(np.argmax(A['edc_bb'] <= -40.0)) or len(A['edc_bb'])
  328. n = max(min(n, stop + int(A['predelay_ms'] / 1000.0 / GRID) + 1), min(n, 10))
  329. ra, rb = ra[:, :n], rb[:, :n]
  330. floor = ra.max() - 45.0
  331. use = (ra > floor) | (rb > floor)
  332. dz = np.array([DZ['relief'] / np.sqrt(bw * 0.1) + 0.15 for bw in BW])[:, None]
  333. diff = np.maximum(np.abs(np.maximum(ra, floor) - np.maximum(rb, floor)) - dz, 0.0)
  334. d['relief'] = float(np.minimum(diff[use], 20.0).mean()) if use.any() else FULL['relief']
  335. parts['relief'] = lin(d['relief'], FULL['relief'])
  336. # echo density
  337. nd = []
  338. for key in ('t50', 't90'):
  339. x, y = A['ned'][key], B['ned'][key]
  340. if x is None and y is None:
  341. continue
  342. x, y = (4.0 if x is None else x), (4.0 if y is None else y)
  343. nd.append(lin(abs(np.log2((y + 0.005) / (x + 0.005))), FULL['ned_t']))
  344. if A['ned']['late'] is not None and B['ned']['late'] is not None:
  345. nd.append(lin(abs(A['ned']['late'] - B['ned']['late']), FULL['ned_late']))
  346. parts['density'] = float(np.mean(nd)) if nd else 10.0
  347. d['ned'] = [A['ned'], B['ned']]
  348. # balance and stereo per time slice
  349. bd, sd = [], []
  350. for (t0, t1), sa, sb, ca, cb in zip(SLICES, A['balance'], B['balance'], A['corr'], B['corr']):
  351. if sa is None:
  352. continue
  353. if sb is None:
  354. bd.append(FULL['balance']), sd.append(FULL['stereo'])
  355. continue
  356. nn = np.array(BW) * min(t1 - t0, 0.15) # independent samples per cell
  357. sa_, sb_ = np.array(sa), np.array(sb)
  358. use = sa_ > sa_.max() - 40.0
  359. bd.append(float(np.minimum(np.maximum(np.abs(sa_ - sb_) - DZ['balance'] / np.sqrt(nn), 0.0)[use], 20.0).mean()))
  360. pc = [max(0.0, abs(x - y) - DZ['corr'] / np.sqrt(nn[k])) for k, (x, y) in enumerate(zip(ca, cb))
  361. if x is not None and y is not None and nn[k] >= 6.0]
  362. if pc:
  363. sd.append(float(np.mean(pc)))
  364. d['balance'] = float(np.mean(bd)) if bd else 0.0
  365. d['stereo'] = float(np.mean(sd)) if sd else 0.0
  366. parts['balance'] = lin(d['balance'], FULL['balance'])
  367. parts['stereo'] = lin(d['stereo'], FULL['stereo'])
  368. if A.get('tvi') and B.get('tvi'):
  369. pm = _pairs(A['tvi']['during'] + A['tvi']['after'], B['tvi']['during'] + B['tvi']['after'])
  370. d['mod'] = float(np.mean([abs(x - y) for x, y in pm])) if pm else 0.0
  371. parts['mod'] = lin(d['mod'], FULL['mod'])
  372. d['level'] = max(0.0, abs(A['energy_db'] - B['energy_db']) - DZ['level'])
  373. parts['level'] = lin(d['level'], FULL['level'])
  374. ga, gb = max(abs(A['dry'][0]), abs(A['dry'][1])), max(abs(B['dry'][0]), abs(B['dry'][1]))
  375. if ga > 0 or gb > 0: # the dry path (a Mix law) where there is one
  376. d['dry'] = abs(20.0 * np.log10(gb / ga)) if ga > 0 and gb > 0 else FULL['level']
  377. parts['dry'] = lin(max(0.0, d['dry'] - 0.1), FULL['level'])
  378. return {'score': agg(parts), 'parts': {k: round(v, 2) for k, v in parts.items()},
  379. 'dist': {k: (round(v, 3) if isinstance(v, float) else v) for k, v in d.items()}}
  380. # ------------------------------------------------------------------------------------------------ programme maps
  381. def _stft_pow(x, win, hop):
  382. n = (len(x) - win) // hop + 1
  383. if n < 1:
  384. return np.zeros((0, win // 2 + 1), complex)
  385. idx = np.arange(win)[None, :] + hop * np.arange(n)[:, None]
  386. return np.fft.rfft(x[idx] * np.hanning(win), axis=1)
  387. def third_map(x, sr, smooth=True, bands=THIRDS):
  388. """Third-octave energy map of a stereo signal on a 20 ms grid: [frames, bands] (L + R power). Low bands come
  389. from a long window, high bands from a short one; with `smooth` each band is averaged over enough frames to
  390. hold about four independent samples (0.04 ... 0.2 s), which is what makes the map blind to phase."""
  391. g = int(GRID * sr)
  392. nfr = len(x) // g
  393. out = np.zeros((nfr, len(bands)))
  394. edges = [(b / 2 ** (1 / 6.0), b * 2 ** (1 / 6.0)) for b in bands]
  395. for win, hop, lo, hi in ((4096, g, 0.0, 400.0), (1024, g // 2, 400.0, 3000.0), (256, g // 8, 3000.0, 1e9)):
  396. sel = [k for k, b in enumerate(bands) if lo <= b < hi]
  397. if not sel:
  398. continue
  399. f = np.fft.rfftfreq(win, 1.0 / sr)
  400. acc = None
  401. for c in (0, 1):
  402. xp = np.concatenate([np.zeros(win // 2), x[:, c], np.zeros(win)])
  403. pw = np.abs(_stft_pow(xp, win, hop)) ** 2
  404. acc = pw if acc is None else acc + pw
  405. per = g // hop
  406. m = min(nfr, len(acc) // per)
  407. acc = acc[:m * per].reshape(m, per, -1).mean(1)
  408. for k in sel:
  409. w = (f >= edges[k][0]) & (f < edges[k][1])
  410. if not w.any():
  411. w = np.zeros(len(f), bool)
  412. w[int(np.argmin(np.abs(f - bands[k])))] = True
  413. out[:m, k] = acc[:, w].sum(1) / (win * win)
  414. if smooth:
  415. for k, b in enumerate(bands):
  416. n = int(min(10, max(2, np.ceil(4.0 / (0.2316 * b * GRID)))))
  417. out[:, k] = np.convolve(out[:, k], np.ones(n) / n, 'same')
  418. return out
  419. def corr_map(x, sr, bin_s=0.2):
  420. """L/R correlation per octave band (125 Hz - 8 kHz) in 200 ms bins, and the band energy: ([bins, bands], same)."""
  421. win, hop = 1024, 480
  422. L = _stft_pow(np.concatenate([x[:, 0], np.zeros(win)]), win, hop)
  423. R = _stft_pow(np.concatenate([x[:, 1], np.zeros(win)]), win, hop)
  424. f = np.fft.rfftfreq(win, 1.0 / sr)
  425. per = max(1, int(bin_s * sr / hop))
  426. m = len(L) // per
  427. rho, en = np.zeros((m, len(OCT) - 1)), np.zeros((m, len(OCT) - 1))
  428. for k, c in enumerate(OCT[1:]):
  429. w = (f >= c / 2 ** 0.5) & (f < c * 2 ** 0.5)
  430. ll = (np.abs(L[:m * per, w]) ** 2).sum(1).reshape(m, per).sum(1)
  431. rr = (np.abs(R[:m * per, w]) ** 2).sum(1).reshape(m, per).sum(1)
  432. lr = (L[:m * per, w] * np.conj(R[:m * per, w])).real.sum(1).reshape(m, per).sum(1)
  433. rho[:, k] = lr / np.sqrt(ll * rr + 1e-300)
  434. en[:, k] = ll + rr
  435. return rho, en
  436. def mod_spectrum(series, ok, hop_s=GRID):
  437. """Mean power of the fluctuation of each column of `series` ([frames, bands]; `ok` marks usable cells) in
  438. octave bins of modulation frequency 0.25 ... 16 Hz. Phase-blind by construction."""
  439. edges = [0.25 * 2 ** k for k in range(7)]
  440. acc, cnt = np.zeros(6), 0
  441. n = series.shape[0]
  442. if n < 64:
  443. return None
  444. fr = np.fft.rfftfreq(n, hop_s)
  445. for k in range(series.shape[1]):
  446. good = ok[:, k]
  447. if good.sum() < n * 0.5:
  448. continue
  449. s = np.interp(np.arange(n), np.flatnonzero(good), series[good, k])
  450. s = (s - s.mean()) * np.hanning(n)
  451. sp = np.abs(np.fft.rfft(s)) ** 2 / (np.hanning(n) ** 2).sum()
  452. acc += np.array([sp[(fr >= edges[i]) & (fr < edges[i + 1])].sum() for i in range(6)])
  453. cnt += 1
  454. return acc / cnt if cnt else None
  455. def programme_stats(out, stim, sr, g=(0.0, 0.0, 0), kind='verb'):
  456. """Measurements of a programme render. kind verb: the wet part's long-term third-octave spectrum, its level
  457. over time in three wide bands and the L/R correlation per octave band - statistics that hold for any phase
  458. of a diffuse tail (a fine time-frequency map does not: a held note through a reverb lands on a different mode
  459. gain in every realisation). kind delay / mod: the fine third-octave x 20 ms map, the effect being deterministic."""
  460. wet = wet_of(out, stim, g) if kind != 'mod' else out
  461. raw = third_map(wet, sr, smooth=False)
  462. st = {'energy_db': float(db((wet ** 2).sum())), 'lt': db(raw.sum(0))}
  463. wide = np.stack([raw[:, :8].sum(1), raw[:, 8:18].sum(1), raw[:, 18:].sum(1)], 1) # < 300 Hz, - 3 kHz, above
  464. st['wide'] = db(np.apply_along_axis(lambda v: np.convolve(v, np.ones(8) / 8.0, 'same'), 0, wide))
  465. rho, en = corr_map(wet, sr)
  466. st['rho_band'] = (rho * en).sum(0) / np.maximum(en.sum(0), 1e-300)
  467. st['en_band'] = en.sum(0)
  468. if kind != 'verb':
  469. st['map'] = third_map(wet, sr)
  470. if kind == 'delay':
  471. st['rho'], st['rho_en'] = rho, en
  472. if kind == 'mod':
  473. sel = [k for k, b in enumerate(THIRDS) if 400.0 <= b <= 8000.0]
  474. raw = raw[:, sel]
  475. n = min(len(raw), len(stim) // int(GRID * sr))
  476. src = third_map(stim[:n * int(GRID * sr)], sr, smooth=False)[:n, sel]
  477. raw = raw[:n]
  478. k2 = np.ones(2) / 2.0
  479. sm = lambda m: np.apply_along_axis(lambda v: np.convolve(v, k2, 'same'), 0, m)
  480. raw, src = sm(raw), sm(src)
  481. ok = src > src.max() * 1e-4
  482. st['motion_t'] = mod_spectrum(db(raw) - db(src), ok)
  483. chan = []
  484. for c in (0, 1):
  485. one = np.stack([out[:, c], out[:, c]], 1)
  486. chan.append(sm(third_map(one, sr, smooth=False)[:n, sel]))
  487. okp = (chan[0] + chan[1]) > (chan[0] + chan[1]).max() * 1e-4
  488. st['motion_p'] = mod_spectrum(db(chan[0]) - db(chan[1]), okp)
  489. return st
  490. def programme_score(A, B, kind='verb'):
  491. parts, d = {}, {}
  492. if kind == 'verb':
  493. use = A['lt'] > A['lt'].max() - 40.0
  494. dl = float((B['lt'] - A['lt'])[use].mean()) # level: mean of the band differences
  495. d['spec'] = max(0.0, float(np.abs(B['lt'] - dl - A['lt'])[use].mean()) - DZ['p_spec'])
  496. n = min(len(A['wide']), len(B['wide']))
  497. wa, wb = A['wide'][:n], B['wide'][:n] - dl
  498. floor = wa.max() - 40.0
  499. u = (wa > floor) | (wb > floor)
  500. diff = np.minimum(np.abs(np.maximum(wa, floor) - np.maximum(wb, floor)), 20.0)
  501. d['env'] = max(0.0, float(diff[u].mean()) - DZ['p_env']) if u.any() else 0.0
  502. d['level'] = max(0.0, abs(dl) - DZ['p_level'])
  503. ub = A['en_band'] > A['en_band'].max() * 1e-4
  504. ub[:2] = False # 125 / 250 Hz: too few partials in programme
  505. d['stereo'] = max(0.0, float(np.abs(A['rho_band'] - B['rho_band'])[ub].mean()) - DZ['p_stereo']) if ub.any() else 0.0
  506. parts = {'spec': lin(d['spec'], P_FULL), 'env': lin(d['env'], P_FULL), 'level': lin(d['level'], FULL['level']),
  507. 'stereo': lin(d['stereo'], FULL['stereo'])}
  508. else:
  509. ma, mb = db(A['map']), db(B['map'])
  510. n = min(len(ma), len(mb))
  511. ma, mb = ma[:n], mb[:n]
  512. dl = B['energy_db'] - A['energy_db']
  513. floor = ma.max() - 50.0
  514. mb2 = mb - dl
  515. use = (ma > floor) | (mb2 > floor)
  516. diff = np.abs(np.maximum(ma, floor) - np.maximum(mb2, floor))
  517. d['spec'] = float(np.minimum(diff[use], 20.0).mean()) if use.any() else 0.0
  518. d['level'] = abs(dl)
  519. parts['spec'] = lin(d['spec'], FULL['spec'])
  520. parts['level'] = lin(d['level'], FULL['level'])
  521. if kind == 'delay':
  522. m = min(len(A['rho']), len(B['rho']))
  523. use = A['rho_en'][:m] > A['rho_en'].max() * 1e-4
  524. d['stereo'] = float(np.abs(A['rho'][:m] - B['rho'][:m])[use].mean()) if use.any() else 0.0
  525. else: # mod: per band over the whole file
  526. ub = A['en_band'] > A['en_band'].max() * 1e-4
  527. d['stereo'] = float(np.abs(A['rho_band'] - B['rho_band'])[ub].mean()) if ub.any() else 0.0
  528. parts['stereo'] = lin(d['stereo'], FULL['stereo'])
  529. if kind == 'mod':
  530. ms = []
  531. for key in ('motion_t', 'motion_p'):
  532. x, y = A.get(key), B.get(key)
  533. if x is None or y is None:
  534. continue
  535. # dB^2 power of the fluctuation per modulation octave; below 0.01 dB^2 both count as still
  536. ms.append(float(np.abs(db(x + 0.01) - db(y + 0.01)).mean()))
  537. if ms:
  538. d['motion'] = float(np.mean(ms))
  539. parts['motion'] = lin(d['motion'], FULL['motion'])
  540. return {'score': agg(parts), 'parts': {k: round(v, 2) for k, v in parts.items()},
  541. 'dist': {k: round(v, 3) for k, v in d.items()}}
  542. # ------------------------------------------------------------------------------------------------ pilot tone
  543. def pilot_stats(x, sr, hz, t0=1.0, t1=None):
  544. """Modulation seen on a steady pilot tone of `hz` (mono mix of x between t0 and t1 s): the tone is brought to
  545. 0 Hz and low-passed at 60 Hz; the phase gives the instantaneous frequency. Returns the rate (Hz, strongest
  546. line 0.1-30 Hz of the frequency deviation, or of the level if the frequency is still), depth (cents, peak:
  547. 1.414 x rms), level wobble (dB rms). A time-invariant effect gives depth 0 and wobble 0."""
  548. m = x.mean(1) if x.ndim == 2 else x
  549. a, b = int(t0 * sr), int((t1 if t1 else len(m) / sr - 0.5) * sr)
  550. seg = m[a:b]
  551. n = len(seg)
  552. z = seg * np.exp(-2j * np.pi * hz * (np.arange(n) / sr))
  553. Z = np.fft.fft(z)
  554. f = np.fft.fftfreq(n, 1.0 / sr)
  555. Z[np.abs(f) > 60.0] = 0
  556. z = np.fft.ifft(Z)
  557. dec = max(1, sr // 400)
  558. z = z[sr // 4:n - sr // 4:dec]
  559. fs = sr / dec
  560. amp = np.abs(z)
  561. if amp.max() <= 1e-12:
  562. return {'rate_hz': None, 'depth_cents': 0.0, 'am_db': 0.0}
  563. dev = np.diff(np.unwrap(np.angle(z))) * fs / (2 * np.pi)
  564. dev = dev - dev.mean()
  565. cents = 1200.0 * np.log2(np.maximum(1.0 + dev / hz, 1e-6))
  566. lvl = 20 * np.log10(np.maximum(amp / amp.mean(), 1e-9))
  567. use = cents if np.sqrt(np.mean(cents ** 2)) > 0.02 else lvl - lvl.mean()
  568. sp = np.abs(np.fft.rfft(use * np.hanning(len(use))))
  569. fr = np.fft.rfftfreq(len(use), 1.0 / fs)
  570. band = (fr >= 0.1) & (fr <= 30.0)
  571. rate = float(fr[band][int(np.argmax(sp[band]))]) if band.any() and sp[band].max() > 1e-9 else None
  572. return {'rate_hz': rate, 'depth_cents': float(np.sqrt(2.0 * np.mean(cents ** 2))), 'am_db': float(np.std(lvl))}
  573. # ------------------------------------------------------------------------------------------------ files
  574. def write_wav(path, x, sr):
  575. import struct
  576. y = np.asarray(x, np.float32)
  577. if y.ndim == 1:
  578. y = np.stack([y, y], 1)
  579. dd = y.tobytes()
  580. h = b'RIFF' + struct.pack('<I', 36 + len(dd)) + b'WAVE' + b'fmt ' + struct.pack('<IHHIIHH', 16, 3, 2, sr, sr * 8, 8, 32) + \
  581. b'data' + struct.pack('<I', len(dd))
  582. open(path, 'wb').write(h + dd)
  583. def _clean(o):
  584. if isinstance(o, dict):
  585. return {k: _clean(v) for k, v in o.items() if not isinstance(v, np.ndarray)}
  586. if isinstance(o, (list, tuple)):
  587. return [_clean(v) for v in o]
  588. if isinstance(o, (np.floating, np.integer)):
  589. return float(o)
  590. return o
  591. def pair(ref, lynx, stim, kind='verb', g_ref=None, g_lynx=None):
  592. """Tail score of one file pair. An impulse stimulus gives the impulse half, anything else a programme file."""
  593. a, sr = fxparity.read_wav(ref)
  594. b, _ = fxparity.read_wav(lynx)
  595. s, _ = fxparity.read_wav(stim)
  596. probe = find_probe(s, sr)
  597. if probe is not None:
  598. A, B = impulse_stats(a, s, sr, g_ref), impulse_stats(b, s, sr, g_lynx)
  599. r = impulse_score(A, B)
  600. r['type'] = 'impulse'
  601. r['ref'], r['lynx'] = _clean(A), _clean(B)
  602. else:
  603. A = programme_stats(a, s, sr, g_ref or (0.0, 0.0, 0), kind)
  604. B = programme_stats(b, s, sr, g_lynx or (0.0, 0.0, 0), kind)
  605. r = programme_score(A, B, kind)
  606. r['type'] = 'programme'
  607. return r
  608. def score_dir(refdir, lynxdir, stimdir, kind='verb', wave=True):
  609. """Every <setting>_<signal>.wav of both folders. Returns {'files': {...}, 'settings': {...}, 'tail', 'wave',
  610. 'parts': mean sub-scores, 'loss': points each part costs on the row's tail score}."""
  611. names = sorted(f[:-4] for f in os.listdir(refdir) if f.endswith('.wav') and os.path.exists(os.path.join(lynxdir, f)))
  612. sets = {}
  613. for nm in names:
  614. s, _, sig = nm.partition('_')
  615. if os.path.exists(os.path.join(stimdir, sig + '.wav')):
  616. sets.setdefault(s, []).append(sig)
  617. res = {'files': {}, 'settings': {}}
  618. for s, sigs in sets.items():
  619. gr = gl = None
  620. imp = [x for x in sigs if find_probe(*fxparity.read_wav(os.path.join(stimdir, x + ".wav"))) is not None]
  621. if imp and kind != 'mod':
  622. st, sr = fxparity.read_wav(os.path.join(stimdir, imp[0] + '.wav'))
  623. gr = dry_path(fxparity.read_wav(os.path.join(refdir, f'{s}_{imp[0]}.wav'))[0], st, sr)
  624. gl = dry_path(fxparity.read_wav(os.path.join(lynxdir, f'{s}_{imp[0]}.wav'))[0], st, sr)
  625. half = {'impulse': [], 'programme': []}
  626. for sig in sigs:
  627. a, b = os.path.join(refdir, f'{s}_{sig}.wav'), os.path.join(lynxdir, f'{s}_{sig}.wav')
  628. r = pair(a, b, os.path.join(stimdir, sig + '.wav'), kind, gr, gl)
  629. if wave:
  630. w = fxparity.pair(a, b)
  631. r['wave'] = w['score']
  632. r['wave_detail'] = {k: (round(w[k], 2) if w.get(k) is not None else None) for k in ('esr_db', 'rms_db', 'spec_db', 'env_corr')}
  633. res['files'][f'{s}_{sig}'] = r
  634. if r['score'] is not None:
  635. half[r['type']].append(r['score'])
  636. hs = [float(np.mean(v)) for v in half.values() if v]
  637. res['settings'][s] = {'tail': round(float(np.mean(hs)), 3) if hs else None,
  638. 'impulse': round(float(np.mean(half['impulse'])), 3) if half['impulse'] else None,
  639. 'programme': round(float(np.mean(half['programme'])), 3) if half['programme'] else None,
  640. 'dry_ref': gr, 'dry_lynx': gl}
  641. ts = [v['tail'] for v in res['settings'].values() if v['tail'] is not None]
  642. res['tail'] = round(float(np.mean(ts)), 2) if ts else None
  643. ws = [r['wave'] for r in res['files'].values() if r.get('wave') is not None]
  644. res['wave'] = round(float(np.mean(ws)), 2) if ws else None
  645. # mean sub-score per part, and the points each part costs on the row's tail score: a file's loss (10 - score)
  646. # split over its parts in proportion to their squared deficits, averaged like the score itself
  647. parts, loss = {}, {}
  648. for s, sigs in sets.items():
  649. fs = [res['files'][f'{s}_{sig}'] for sig in sigs]
  650. types = {r['type'] for r in fs if r['score'] is not None}
  651. for typ in types:
  652. grp = [r for r in fs if r['type'] == typ and r['score'] is not None]
  653. for r in grp:
  654. df = {k: (10.0 - v) ** 2 for k, v in r['parts'].items()}
  655. tot = sum(df.values())
  656. for k, v in df.items():
  657. share = (10.0 - r['score']) * (v / tot if tot > 0 else 0.0)
  658. loss[f'{typ[:3]}.{k}'] = loss.get(f'{typ[:3]}.{k}', 0.0) + share / len(grp) / len(types) / max(1, len(ts))
  659. for typ in ('impulse', 'programme'):
  660. fs = [r for r in res['files'].values() if r['type'] == typ and r['score'] is not None]
  661. for k in sorted({k for r in fs for k in r['parts']}):
  662. parts[f'{typ[:3]}.{k}'] = round(float(np.mean([r['parts'][k] for r in fs if k in r['parts']])), 2)
  663. res['parts'] = parts
  664. res['loss'] = {k: round(v, 3) for k, v in sorted(loss.items(), key=lambda kv: -kv[1])}
  665. res['version'] = VERSION
  666. return res
  667. # ------------------------------------------------------------------------------------------------ probes / engine
  668. def make_probes(outdir, sr=48000):
  669. os.makedirs(outdir, exist_ok=True)
  670. rng = np.random.default_rng(190)
  671. burst = rng.standard_normal(int(0.3 * sr)) * 0.25
  672. for name, amp in (('imp06', 0.5), ('imp20', 0.1), ('imp40', 0.01)):
  673. x = np.zeros(8 * sr)
  674. x[int(0.1 * sr)] = amp
  675. x[4 * sr:4 * sr + len(burst)] = burst * (amp / 0.5)
  676. write_wav(os.path.join(outdir, name + '.wav'), x, sr)
  677. t = np.arange(10 * sr) / sr
  678. fade = np.clip(t / 0.05, 0, 1) * np.clip((10 - t) / 0.05, 0, 1)
  679. for hz in (1000, 5000):
  680. write_wav(os.path.join(outdir, f'pilot{hz}.wav'), 0.25 * np.sin(2 * np.pi * hz * t) * fade, sr)
  681. w = rng.standard_normal(6 * sr)
  682. W = np.fft.rfft(w)
  683. W[1:] /= np.sqrt(np.arange(1, len(W)))
  684. pk = np.fft.irfft(W, len(w))
  685. pk = np.concatenate([pk / np.abs(pk).max() * 0.5, np.zeros(4 * sr)])
  686. write_wav(os.path.join(outdir, 'pink.wav'), pk, sr)
  687. def engine_table(fxr, effect, probedir, outdir, opts):
  688. """Renders the probes through one LYNX effect (tools/fxrender) and returns its lab measurements."""
  689. import subprocess
  690. os.makedirs(outdir, exist_ok=True)
  691. names = ['imp06', 'imp20', 'imp40', 'pilot1000', 'pilot5000', 'pink']
  692. files = []
  693. for n in names:
  694. files += [os.path.join(probedir, n + '.wav'), os.path.join(outdir, n + '.wav')]
  695. r = subprocess.run([fxr, effect] + list(opts) + files, capture_output=True, text=True)
  696. if r.returncode:
  697. raise RuntimeError(r.stdout[-300:] + r.stderr[-300:])
  698. res = {}
  699. for n in ('imp06', 'imp20', 'imp40'):
  700. s, sr = fxparity.read_wav(os.path.join(probedir, n + '.wav'))
  701. o, _ = fxparity.read_wav(os.path.join(outdir, n + '.wav'))
  702. res[n] = _clean(impulse_stats(o, s, sr))
  703. for hz in (1000, 5000):
  704. o, sr = fxparity.read_wav(os.path.join(outdir, f'pilot{hz}.wav'))
  705. res[f'pilot{hz}'] = pilot_stats(o, sr, hz, 2.0, 9.0)
  706. return res
  707. def _fmt(v, f='%.2f'):
  708. return '-' if v is None else f % v
  709. def print_engine(res):
  710. a = res['imp06']
  711. if a.get('silent'):
  712. print('silent')
  713. return
  714. print('band ' + ' '.join(f'{c:>7d}' for c in OCT))
  715. for key in ('t20', 't30', 'edt', 'rt_late'):
  716. print(f'{key:7s}' + ' '.join(f'{_fmt(v):>7s}' for v in a[key]))
  717. print('level ' + ' '.join(f'{v:7.1f}' for v in a['band_db']))
  718. if a.get('tvi'):
  719. print('tvi dur' + ' '.join(f'{_fmt(v):>7s}' for v in a['tvi']['during']))
  720. print('tvi aft' + ' '.join(f'{_fmt(v):>7s}' for v in a['tvi']['after']))
  721. for i, sl in enumerate(SLICES):
  722. if a['corr'][i]:
  723. print(f'corr {sl[0]:.2f}-{sl[1]:.1f}s ' + ' '.join(f'{_fmt(v):>6s}' for v in a['corr'][i]) + f' width {a["width_db"][i]:+.1f} dB')
  724. print(f"pre-delay {a['predelay_ms']:.1f} ms C80 {a['c80_db']:+.1f} dB centre {a['centre_ms']:.0f} ms energy {a['energy_db']:+.1f} dB "
  725. f"NED t50 {_fmt(a['ned']['t50'], '%.3f')} t90 {_fmt(a['ned']['t90'], '%.3f')} late {_fmt(a['ned']['late'])}")
  726. for n in ('imp20', 'imp40'):
  727. b = res[n]
  728. if not b.get('silent'):
  729. print(f"{n}: energy {b['energy_db']:+.1f} dB (re its impulse) T30 broadband {_fmt(b['t30_bb'])} s (imp06 {_fmt(a['t30_bb'])} s)")
  730. for hz in (1000, 5000):
  731. p = res[f'pilot{hz}']
  732. print(f"pilot {hz} Hz: rate {_fmt(p['rate_hz'])} Hz depth {p['depth_cents']:.2f} cents level wobble {p['am_db']:.2f} dB")
  733. def main(argv):
  734. def opt(name, default=None):
  735. if name in argv:
  736. i = argv.index(name)
  737. v = argv[i + 1]
  738. del argv[i:i + 2]
  739. return v
  740. return default
  741. if len(argv) < 2:
  742. print(__doc__)
  743. return 2
  744. cmd = argv[1]
  745. if cmd == 'selftest':
  746. import taillab_test
  747. return taillab_test.run()
  748. kind, stim, js = opt('--kind', 'verb'), opt('--stim'), opt('--json')
  749. if cmd == 'pair' and len(argv) >= 4 and stim:
  750. dry = opt('--dry')
  751. g = tuple(float(v) for v in dry.split(',')) if dry else None
  752. print(json.dumps(_clean(pair(argv[2], argv[3], stim, kind, g, g))))
  753. elif cmd == 'dir' and len(argv) >= 4 and stim:
  754. res = score_dir(argv[2], argv[3], stim, kind)
  755. for nm, r in res['files'].items():
  756. print(f"{nm:22s} wave {r.get('wave')} tail {r['score']} " + ' '.join(f'{k}={v}' for k, v in r['parts'].items()))
  757. for s, v in res['settings'].items():
  758. print(f"setting {s}: tail {v['tail']} (impulse {v['impulse']}, programme {v['programme']})")
  759. print(f"ROW wave {res['wave']} tail {res['tail']} loss " + ' '.join(f'{k}={v}' for k, v in res['loss'].items()))
  760. if js:
  761. json.dump(_clean(res), open(js, 'w'))
  762. elif cmd == 'stats' and len(argv) >= 3 and stim:
  763. o, sr = fxparity.read_wav(argv[2])
  764. s, _ = fxparity.read_wav(stim)
  765. print(json.dumps(_clean(impulse_stats(o, s, sr))))
  766. elif cmd == 'pilot' and len(argv) >= 4:
  767. o, sr = fxparity.read_wav(argv[2])
  768. print(json.dumps(pilot_stats(o, sr, float(argv[3]), *(float(v) for v in argv[4:6]))))
  769. elif cmd == 'probes' and len(argv) >= 3:
  770. make_probes(argv[2], int(argv[3]) if len(argv) > 3 else 48000)
  771. elif cmd == 'engine' and len(argv) >= 6:
  772. res = engine_table(argv[2], argv[3], argv[4], argv[5], argv[6:])
  773. print_engine(res)
  774. if js:
  775. json.dump(res, open(js, 'w'))
  776. else:
  777. print(__doc__)
  778. return 2
  779. return 0
  780. if __name__ == '__main__':
  781. sys.exit(main(sys.argv))