62 lines
2.3 KiB
Python
62 lines
2.3 KiB
Python
# Audio features of a WAV on stdin (run by tools/fixtures/sf2.py through ctx.python(["numpy"], ...); not a generator).
|
|
# tests/music/sf2.luau computes the same features from rosetta's render and compares them:
|
|
# env RMS of the mono mix per 50 ms window (2205 frames)
|
|
# bands per 2 s segment: mean power in 24 log-spaced bands (60 Hz .. 16 kHz) of 2048-point Hann frames (hop 1024),
|
|
# in dB
|
|
# peaks the strongest frequency (parabolic interpolation) of the mean 8192-point Hann spectrum in a few windows
|
|
import io, json, sys, wave
|
|
import numpy as np
|
|
|
|
w = wave.open(io.BytesIO(sys.stdin.buffer.read()))
|
|
rate, ch, width, n = w.getframerate(), w.getnchannels(), w.getsampwidth(), w.getnframes()
|
|
raw = w.readframes(n)
|
|
assert width == 2, width
|
|
x = np.frombuffer(raw, dtype="<i2").astype(np.float64).reshape(-1, ch) / 32768.0
|
|
mono = x.mean(axis=1)
|
|
|
|
ENV = 2205
|
|
env = [float(np.sqrt(np.mean(mono[i:i + ENV] ** 2))) for i in range(0, len(mono) - ENV + 1, ENV)]
|
|
|
|
N, HOP = 2048, 1024
|
|
edges = [float(e) for e in np.geomspace(60, 16000, 25)]
|
|
freqs = np.arange(N // 2 + 1) * rate / N
|
|
han = 0.5 - 0.5 * np.cos(2 * np.pi * np.arange(N) / N)
|
|
SEGMENTS = [(0, 2), (2, 4), (4, 6), (6, 8), (8, 10), (10, 12)]
|
|
|
|
|
|
def bands(a, b):
|
|
acc, frames = np.zeros(24), 0
|
|
for s in range(int(a * rate), int(b * rate) - N + 1, HOP):
|
|
p = np.abs(np.fft.rfft(mono[s:s + N] * han)) ** 2
|
|
for k in range(24):
|
|
acc[k] += p[(freqs >= edges[k]) & (freqs < edges[k + 1])].sum()
|
|
frames += 1
|
|
return [float(10 * np.log10(v / max(frames, 1) + 1e-12)) for v in acc]
|
|
|
|
|
|
PN = 8192
|
|
phan = 0.5 - 0.5 * np.cos(2 * np.pi * np.arange(PN) / PN)
|
|
WINDOWS = [(4.2, 5.4), (8.05, 8.45), (8.55, 8.95), (2.02, 2.33)]
|
|
|
|
|
|
def peak(a, b):
|
|
acc = np.zeros(PN // 2 + 1)
|
|
for s in range(int(a * rate), int(b * rate) - PN + 1, PN // 4):
|
|
acc += np.abs(np.fft.rfft(mono[s:s + PN] * phan)) ** 2
|
|
k = int(np.argmax(acc[1:-1])) + 1
|
|
y0, y1, y2 = np.log(acc[k - 1] + 1e-30), np.log(acc[k] + 1e-30), np.log(acc[k + 1] + 1e-30)
|
|
d = 0.5 * (y0 - y2) / (y0 - 2 * y1 + y2)
|
|
return float((k + d) * rate / PN)
|
|
|
|
|
|
json.dump({
|
|
"rate": rate,
|
|
"frames": len(mono),
|
|
"env": env,
|
|
"edges": edges,
|
|
"segments": [list(s) for s in SEGMENTS],
|
|
"bands": [bands(a, b) for a, b in SEGMENTS],
|
|
"windows": [list(wd) for wd in WINDOWS],
|
|
"peaks": [peak(a, b) for a, b in WINDOWS],
|
|
}, sys.stdout)
|