fxparity.py 9.9 KB

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