dyn.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. """Dynamics measurements (static curves, step responses) on any hosted effect. numpy only."""
  2. import sys; sys.path.insert(0, '.')
  3. from sig import *
  4. SR = 48000
  5. F0 = 1000.0
  6. def analytic(x):
  7. n = len(x); X = np.fft.fft(x); h = np.zeros(n); h[0] = 1
  8. h[1:(n + 1) // 2] = 2
  9. if n % 2 == 0: h[n // 2] = 1
  10. return np.fft.ifft(X * h)
  11. def stair(levels_db, hold=0.5, f=F0, sr=SR):
  12. """sine stair: one level per `hold` seconds (phase continuous)"""
  13. n = int(hold * sr)
  14. t = np.arange(n * len(levels_db)) / sr
  15. env = np.repeat(10 ** (np.array(levels_db) / 20), n)
  16. return np.sin(2 * np.pi * f * t) * env, n
  17. def stair_read(y, x, n, latency=0, tail=0.3, sr=SR):
  18. """output level (dB, sine amplitude) at the end of each stair step, and input level"""
  19. y = y[latency:]; m = len(y) // n
  20. outs, ins = [], []
  21. k = int(tail * sr) if tail < 1 else int(tail)
  22. for i in range(m):
  23. seg = y[i * n + n - k:(i + 1) * n]; sx = x[i * n + n - k:(i + 1) * n]
  24. outs.append(20 * np.log10(np.sqrt(2 * np.mean(seg ** 2)) + 1e-12))
  25. ins.append(20 * np.log10(np.sqrt(2 * np.mean(sx ** 2)) + 1e-12))
  26. return np.array(ins), np.array(outs)
  27. def burst(lo_db, hi_db, t_lo=1.0, t_hi=1.0, t_after=2.0, f=F0, sr=SR):
  28. a = np.concatenate([np.full(int(t_lo * sr), lo_db), np.full(int(t_hi * sr), hi_db), np.full(int(t_after * sr), lo_db)])
  29. t = np.arange(len(a)) / sr
  30. return np.sin(2 * np.pi * f * t) * 10 ** (a / 20)
  31. def gain_env(y, x, latency=0, smooth=48):
  32. """gain (dB) over time: |analytic(out)| / |analytic(in)|, both smoothed over `smooth` samples"""
  33. if latency: y = np.concatenate([y[latency:], np.zeros(latency)])
  34. ay = np.abs(analytic(y)); ax = np.abs(analytic(x))
  35. k = np.ones(smooth) / smooth
  36. ay = np.convolve(ay, k, 'same'); ax = np.convolve(ax, k, 'same')
  37. return 20 * np.log10((ay + 1e-12) / (ax + 1e-12))
  38. def time_to(g, start, frac, sr=SR):
  39. """time (ms) after `start` until g has covered `frac` of its change (start value -> final value of the segment)"""
  40. g0 = g[start - 10]; gend = g[min(len(g) - 1, start + int(0.9 * sr))]
  41. target = g0 + frac * (gend - g0)
  42. seg = g[start:start + int(0.95 * sr)]
  43. if gend < g0:
  44. idx = np.argmax(seg <= target)
  45. else:
  46. idx = np.argmax(seg >= target)
  47. return idx / sr * 1000, g0, gend