# 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="= 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)