fxparity.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. #!/usr/bin/env python3
  2. """fxparity.py — sound parity of LYNX's effects against the third-party originals they are inspired by (round tp172b).
  3. The originals are rendered black-box by tools/fxmeasure (a host, public parameter API only) and LYNX by
  4. tools/fxrender, on the same stimuli at matched settings. Each pair of renders is compared exactly like FL's own render
  5. tests (scripts/flref_compare.py: alignment, ESR, level, third-octave spectrum, 50 ms envelope) and scored 0-10 with
  6. the same scale as the FL-native parity tracker (round 170i).
  7. Usage:
  8. fxparity.py pair <original.wav> <lynx.wav> metrics + score as JSON
  9. fxparity.py dir <original-dir> <lynx-dir> every <name>.wav present in both, one JSON line each
  10. (round 190mm) a reference with a sidecar <name>.mask.json has those spans (Waves demo-mode mutes) left out of
  11. every metric; references without one score exactly as before
  12. fxparity.py verb <original.wav> <lynx.wav> [t0] reverb score of two impulse renders (impulse at t0 s, default
  13. 0.1): the mean of seven 0-10 sub-scores (see verb_score)
  14. """
  15. import json
  16. import os
  17. import sys
  18. sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
  19. import flref_compare as fc # noqa: E402
  20. def score(r):
  21. """0-10 sound score (the FL parity tracker's scale, round 170i)."""
  22. if not r or r.get('missing'):
  23. return None
  24. s = r.get('silent')
  25. if s == 'fl':
  26. return None
  27. if s == 'lynx':
  28. return 0
  29. e = r['esr_db']
  30. spec = r.get('spec_db') or 0
  31. env = r.get('env_corr') or 0
  32. rms = abs(r.get('rms_db') or 0)
  33. if e <= -70:
  34. return 10
  35. if e <= -55:
  36. return 9
  37. if e <= -40:
  38. return 8
  39. if spec <= 0.15 and rms <= 0.2 and env >= 0.995:
  40. return 8 if e <= -20 else 7
  41. if e <= -25:
  42. return 7
  43. if spec <= 0.6 and rms <= 0.5 and env >= 0.98:
  44. return 6
  45. if e <= -12:
  46. return 5
  47. if spec <= 2.5 and rms <= 1.5:
  48. return 4
  49. if spec <= 4 and rms <= 3:
  50. return 3
  51. if rms <= 5:
  52. return 2
  53. return 1
  54. def read_wav(path):
  55. """Stereo float64 frames and the rate of a PCM 16 / 24 / 32-bit or float 32 WAV (fxmeasure and fxrender write float)."""
  56. import struct
  57. import numpy as np
  58. d = open(path, 'rb').read()
  59. i, fmt = 12, None
  60. while i + 8 <= len(d):
  61. cid, size = d[i:i + 4], struct.unpack('<I', d[i + 4:i + 8])[0]
  62. if cid == b'fmt ':
  63. fmt = struct.unpack('<HHIIHH', d[i + 8:i + 24])
  64. elif cid == b'data' and fmt:
  65. tag, ch, rate, _, _, bits = fmt
  66. raw = d[i + 8:i + 8 + size]
  67. if bits == 32 and tag in (3, 0xFFFE):
  68. x = np.frombuffer(raw[:len(raw) // 4 * 4], '<f4').astype(np.float64)
  69. elif bits == 16:
  70. x = np.frombuffer(raw[:len(raw) // 2 * 2], '<i2').astype(np.float64) / 32768.0
  71. elif bits == 24:
  72. a = np.frombuffer(raw[:len(raw) // 3 * 3], np.uint8).reshape(-1, 3).astype(np.int32)
  73. x = ((a[:, 0] | (a[:, 1] << 8) | (a[:, 2] << 16)) << 8 >> 8) / 8388608.0
  74. else:
  75. x = np.frombuffer(raw[:len(raw) // 4 * 4], '<i4').astype(np.float64) / 2147483648.0
  76. x = x[:len(x) // ch * ch].reshape(-1, ch)
  77. if ch == 1:
  78. x = np.repeat(x, 2, axis=1)
  79. return x[:, :2], rate
  80. i += 8 + size + (size & 1)
  81. raise ValueError('not a WAV: ' + path)
  82. fc.read_fl = lambda p: read_wav(p)[0]
  83. fc.read_lynx = lambda p: read_wav(p)[0]
  84. def rate_of(path):
  85. return read_wav(path)[1]
  86. def demo_mask(ref):
  87. """Round 190mm: the demo-mode mute spans of a reference, from its sidecar `<ref>.mask.json` ({"spans": [[start, end],
  88. ...]} in reference samples; written by the capture, which finds each mute as a digital-silence run in take A that a
  89. second take B, started 7.5 s later, plays, widened over the fades where the takes differ). None without a sidecar:
  90. every older reference scores exactly as before."""
  91. p = ref[:-4] + '.mask.json'
  92. if not os.path.exists(p):
  93. return None
  94. return [tuple(x) for x in json.load(open(p)).get('spans', [])]
  95. def pair(a, b):
  96. fc.SR = rate_of(a)
  97. r = fc.compare(a, b, mask=demo_mask(a))
  98. r['score'] = score(r)
  99. return r
  100. # ------------------------------------------------------------------ reverbs (rounds 172b/c/d share this definition)
  101. OCTAVES = (125, 250, 500, 1000, 2000, 4000, 8000)
  102. def _band(x, lo, hi, sr):
  103. """Zero-phase FFT band pass with raised-cosine edges a third of an octave wide."""
  104. import numpy as np
  105. n = 1 << int(np.ceil(np.log2(len(x))))
  106. f = np.fft.rfftfreq(n, 1 / sr)
  107. lf = np.log2(np.maximum(f, 1e-9))
  108. w = np.clip((lf - np.log2(lo)) * 3 + .5, 0, 1) * np.clip((np.log2(hi) - lf) * 3 + .5, 0, 1)
  109. return np.fft.irfft(np.fft.rfft(x, n) * w, n)[:len(x)]
  110. def _edc(h):
  111. import numpy as np
  112. e = np.cumsum((h ** 2)[::-1])[::-1]
  113. return 10 * np.log10(np.maximum(e / max(e[0], 1e-30), 1e-30))
  114. def _t60(edc, sr, hi=-5.0, lo=-25.0):
  115. import numpy as np
  116. i0, i1 = int(np.argmax(edc <= hi)), int(np.argmax(edc <= lo))
  117. if i1 <= i0 + 10:
  118. return None
  119. k = np.polyfit(np.arange(i0, i1) / sr, edc[i0:i1], 1)[0]
  120. return float(-60.0 / k) if k < 0 else None
  121. def verb_stats(path, t0=0.1):
  122. """Black-box reverb measurements of an impulse render (the impulse at t0 s): RT60 per octave (Schroeder EDC,
  123. T20 x 3), the broadband EDC, pre-delay, early energy (first 80 ms after the first arrival), the tail's
  124. third-octave balance, the tail's L/R correlation, its spectral-centroid fluctuation (modulation) and the energy."""
  125. import numpy as np
  126. x, sr = read_wav(path)
  127. x = x[int(t0 * sr):]
  128. m = x.mean(1)
  129. a = np.abs(m)
  130. first = int(np.argmax(a > a.max() * 0.05)) if a.max() > 0 else 0
  131. h, hm = x[first:], m[first:]
  132. st = {'sr': sr, 'predelay_ms': first / sr * 1000, 'energy_db': 10 * np.log10(np.sum(h ** 2) + 1e-30)}
  133. st['rt60'] = [_t60(_edc(_band(hm, f / 2 ** .5, min(f * 2 ** .5, sr * 0.475), sr)), sr) for f in OCTAVES]
  134. st['edc'] = _edc(hm)
  135. e80 = np.sum(h[:int(0.08 * sr)] ** 2)
  136. st['early_db'] = 10 * np.log10(e80 / max(np.sum(h ** 2), 1e-30) + 1e-30)
  137. tail = hm[int(0.1 * sr):]
  138. sp = np.abs(np.fft.rfft(tail)) ** 2 if len(tail) > 64 else np.zeros(2)
  139. fr = np.fft.rfftfreq(len(tail), 1 / sr) if len(tail) > 64 else np.zeros(2)
  140. bands = [np.sum(sp[(fr >= 25 * 2 ** (k / 3)) & (fr < 25 * 2 ** ((k + 1) / 3))]) for k in range(29)]
  141. b = 10 * np.log10(np.array(bands) + 1e-30)
  142. st['tail_spec'] = b - b.max()
  143. l, r = h[int(.05 * sr):int(1.0 * sr), 0], h[int(.05 * sr):int(1.0 * sr), 1]
  144. st['lr_corr'] = float(np.dot(l, r) / (np.linalg.norm(l) * np.linalg.norm(r) + 1e-30))
  145. w = int(0.02 * sr)
  146. seg = tail[:len(tail) // w * w].reshape(-1, w)
  147. keep = np.sqrt(np.mean(seg ** 2, 1)) > 1e-5
  148. cents = []
  149. ff = np.fft.rfftfreq(w, 1 / sr)
  150. for fr_ in seg[keep][:200]:
  151. s_ = np.abs(np.fft.rfft(fr_ * np.hanning(w)))
  152. cents.append(np.sum(s_ * ff) / max(np.sum(s_), 1e-30))
  153. st['centroid_fluct'] = float(np.std(np.diff(cents)) if len(cents) > 3 else 0.0)
  154. return st
  155. def verb_score(a, b, t0=0.1):
  156. """Reverb score 0-10 of LYNX's impulse render `b` against the original's `a`: the mean of seven sub-scores, each
  157. 10 at a perfect match and 0 at the given distance (linear in between):
  158. rt60 mean |log2 ratio| of the RT60 per octave 125 Hz - 8 kHz 0 at 1 octave
  159. edc mean |dB| between the broadband EDCs over 0 … −40 dB of the original, time scaled 0..1 0 at 10 dB
  160. early |early-energy dB difference| / 10 + |pre-delay ms difference| / 50 (the larger) 0 at 1
  161. balance mean |dB| between the tails' normalised third-octave spectra (bands within 40 dB) 0 at 10 dB
  162. stereo |difference of the tails' L/R correlation| 0 at 1
  163. mod |log ratio| of the tails' spectral-centroid fluctuation (20 ms frames) 0 at 1
  164. level |energy dB difference| 0 at 10 dB"""
  165. import numpy as np
  166. A, B = verb_stats(a, t0), verb_stats(b, t0)
  167. lin = lambda d, full: max(0.0, 10.0 * (1.0 - d / full))
  168. pairs = [(x, y) for x, y in zip(A['rt60'], B['rt60']) if x and y]
  169. d_rt = float(np.mean([abs(np.log2(y / x)) for x, y in pairs])) if pairs else 1.0
  170. ea, eb = A['edc'], B['edc']
  171. na = int(np.argmax(ea <= -40)) or len(ea)
  172. nb = int(np.argmax(eb <= -40)) or len(eb)
  173. u = np.linspace(0, 1, 200)
  174. d_edc = float(np.mean(np.abs(np.interp(u * na, np.arange(len(ea)), ea) - np.interp(u * na, np.arange(len(eb)), eb))))
  175. d_early = max(abs(A['early_db'] - B['early_db']) / 10.0, abs(A['predelay_ms'] - B['predelay_ms']) / 50.0)
  176. use = A['tail_spec'] > -40
  177. d_bal = float(np.mean(np.abs(A['tail_spec'][use] - B['tail_spec'][use]))) if use.any() else 10.0
  178. d_st = abs(A['lr_corr'] - B['lr_corr'])
  179. d_mod = abs(np.log((B['centroid_fluct'] + 1.0) / (A['centroid_fluct'] + 1.0)))
  180. d_lvl = abs(A['energy_db'] - B['energy_db'])
  181. sub = {'rt60': lin(d_rt, 1.0), 'edc': lin(d_edc, 10.0), 'early': lin(d_early, 1.0), 'balance': lin(d_bal, 10.0),
  182. 'stereo': lin(d_st, 1.0), 'mod': lin(d_mod, 1.0), 'level': lin(d_lvl, 10.0)}
  183. out = {k: round(v, 2) for k, v in sub.items()}
  184. out['score'] = round(float(np.mean(list(sub.values()))), 2)
  185. out['rt60_orig'] = [x and round(x, 3) for x in A['rt60']]
  186. out['rt60_lynx'] = [x and round(x, 3) for x in B['rt60']]
  187. out['detail'] = {'d_rt60_oct': round(d_rt, 3), 'd_edc_db': round(d_edc, 2), 'd_early_db': round(A['early_db'] - B['early_db'], 2),
  188. 'd_predelay_ms': round(B['predelay_ms'] - A['predelay_ms'], 2), 'd_balance_db': round(d_bal, 2),
  189. 'lr': [round(A['lr_corr'], 3), round(B['lr_corr'], 3)],
  190. 'mod': [round(A['centroid_fluct'], 1), round(B['centroid_fluct'], 1)], 'd_level_db': round(B['energy_db'] - A['energy_db'], 2)}
  191. return out
  192. def main():
  193. if len(sys.argv) >= 4 and sys.argv[1] == 'pair':
  194. print(json.dumps(pair(sys.argv[2], sys.argv[3])))
  195. elif len(sys.argv) >= 4 and sys.argv[1] == 'verb':
  196. print(json.dumps(verb_score(sys.argv[2], sys.argv[3], float(sys.argv[4]) if len(sys.argv) > 4 else 0.1)))
  197. elif len(sys.argv) >= 4 and sys.argv[1] == 'dir':
  198. for f in sorted(os.listdir(sys.argv[2])):
  199. b = os.path.join(sys.argv[3], f)
  200. if f.endswith('.wav') and os.path.exists(b):
  201. r = pair(os.path.join(sys.argv[2], f), b)
  202. r['name'] = f[:-4]
  203. print(json.dumps(r))
  204. else:
  205. print(__doc__)
  206. return 2
  207. return 0
  208. if __name__ == '__main__':
  209. sys.exit(main())