merge ws/audio
This commit is contained in:
commit
fa98dd77c2
43 files changed
+8963
-19
No files matched your search
@@ -90,6 +90,16 @@ for _, c in { { "celt 128k", OpusCelt }, { "silk wb", OpusSilk }, { "hybrid", Op
|
||||
Opus.decode(Bytes.reader(b))
|
||||
end)
|
||||
end
|
||||
-- vorbis (ws-audio): 10 s of 44.1 kHz stereo music at oggenc -q 5 (tools/fixtures/vorbis.py)
|
||||
do
|
||||
local Vorbis = require("@formats/audio/vorbis")
|
||||
local VB = require("@tests/gen/vorbis_bench")
|
||||
local b = buffer.fromstring(VB.data)
|
||||
local dt = bench("vorbis decode q5 (10 s st)", 3, VB.frames * VB.channels * 4, function()
|
||||
Vorbis.decode(Bytes.reader(b))
|
||||
end)
|
||||
print(string.format("%-8s %-30s %8.0fx real time", runtime, "", VB.frames / VB.rate / dt))
|
||||
end
|
||||
for _, name in { "s16_long", "s24_96k" } do
|
||||
for _, c in FC do
|
||||
if c.name == name then
|
||||
@@ -116,6 +126,55 @@ do
|
||||
Wav.decode(Bytes.reader(file))
|
||||
end)
|
||||
end
|
||||
-- flac encode (ws-audio): 10 s of 44.1 kHz stereo 16-bit (a synthetic two-tone signal with noise)
|
||||
do
|
||||
local Fl = require("@formats/audio/flac")
|
||||
local n = 441000
|
||||
local a = Types.Audio.new(44100, 2, n)
|
||||
local seed = 1
|
||||
for i = 0, n - 1 do
|
||||
seed = (seed * 1103515245 + 12345) % 2147483648
|
||||
local noise = (seed / 2147483648 - 0.5) * 0.01
|
||||
buffer.writef32(a.samples, i * 8, math.floor((math.sin(i * 0.031) * 0.4 + math.sin(i * 0.21) * 0.1 + noise) * 32768) / 32768)
|
||||
buffer.writef32(a.samples, i * 8 + 4, math.floor((math.sin(i * 0.017) * 0.3 + noise) * 32768) / 32768)
|
||||
end
|
||||
for _, level in { 0, 5, 8 } do
|
||||
local dt = bench("flac encode -" .. level .. " (10 s st 16)", 2, n * 4, function()
|
||||
Fl.encode(a, { level = level })
|
||||
end)
|
||||
print(string.format("%-8s %-30s %8.0fx real time", runtime, "", 10 / dt))
|
||||
end
|
||||
end
|
||||
-- mp3 / mp2 encode (ws-audio): 10 s of 44.1 kHz stereo tones
|
||||
do
|
||||
local M3 = require("@formats/audio/mp3")
|
||||
local n = 441000
|
||||
local a = Types.Audio.new(44100, 2, n)
|
||||
for i = 0, n - 1 do
|
||||
buffer.writef32(a.samples, i * 8, math.sin(i * 0.031) * 0.4 + math.sin(i * 0.21) * 0.1)
|
||||
buffer.writef32(a.samples, i * 8 + 4, math.sin(i * 0.017) * 0.3)
|
||||
end
|
||||
for _, cfg in { { layer = 3, bitrate = 128 }, { layer = 2, bitrate = 192 } } do
|
||||
local dt = bench(string.format("mp%d encode %d kbps (10 s st)", cfg.layer, cfg.bitrate), 2, n * 8, function()
|
||||
M3.encode(a, cfg)
|
||||
end)
|
||||
print(string.format("%-8s %-30s %8.1fx real time", runtime, "", 10 / dt))
|
||||
end
|
||||
end
|
||||
-- vorbis encode (ws-audio): 10 s of 44.1 kHz stereo tones at quality 3
|
||||
do
|
||||
local Vb = require("@formats/audio/vorbis")
|
||||
local n = 441000
|
||||
local a = Types.Audio.new(44100, 2, n)
|
||||
for i = 0, n - 1 do
|
||||
buffer.writef32(a.samples, i * 8, math.sin(i * 0.031) * 0.4 + math.sin(i * 0.21) * 0.1)
|
||||
buffer.writef32(a.samples, i * 8 + 4, math.sin(i * 0.017) * 0.3)
|
||||
end
|
||||
local dt = bench("vorbis encode q3 (10 s st)", 2, n * 8, function()
|
||||
Vb.encode(a, { quality = 3 })
|
||||
end)
|
||||
print(string.format("%-8s %-30s %8.1fx real time", runtime, "", 10 / dt))
|
||||
end
|
||||
do
|
||||
local Json = require("@formats/codecs/Json")
|
||||
local JB = require("@tests/gen/json_bench")
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
# Shared helpers for the audio fixture generators (aiff, au, voc, vorbis, flac encoder, mp3 / mp2 encoders):
|
||||
# A = _audio.load() in a generator: import this file (generators are loaded by path, not as a package)
|
||||
# A.signal(kind, rate, ch, frames) deterministic test signals -> list of float frames-interleaved samples
|
||||
# A.f32le(samples) / A.from_f32le(b) float list <-> raw little-endian f32 bytes
|
||||
# A.wav(samples, rate, ch, bits=16) a WAV file (PCM 8/16/24/32 or float 32) for reference tools to read
|
||||
# A.ffdecode(ctx, data, fmt=None) decode any file with ffmpeg -> (rate, ch, floats)
|
||||
# A.tool(ctx, pkg, argv, data, ext) run a nix reference tool on a temp input file, return its stdout
|
||||
# A.snr(ref, test, ch, max_lag=0) SNR in dB of test against ref (searching an alignment lag up to max_lag frames,
|
||||
# either direction), and the lag found
|
||||
# A.luau(ctx, code) run Luau code (luau --codegen -O2 from the repo root, the .luaurc aliases
|
||||
# apply) and return its stdout bytes. Encoder fixtures use it to encode with our
|
||||
# encoder in the fixture step, then decode the output with the reference tool:
|
||||
# print(buffer.tostring(buf)) writes the raw bytes (plus one newline, stripped).
|
||||
import array, math, os, random, shutil, struct, subprocess, sys, tempfile, importlib.util
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
|
||||
def load():
|
||||
return sys.modules[__name__]
|
||||
|
||||
|
||||
def signal(kind, rate, ch, frames, seed=1):
|
||||
"""kinds: sine (440 Hz + 1 kHz per channel), sweep (50 Hz .. rate/2.2 log sweep), noise (white, -12 dBFS),
|
||||
music (a few harmonic notes with an envelope + a little noise), silence, square (aliased square, a stress test),
|
||||
loud (a full-scale sine near clipping)."""
|
||||
rng = random.Random(seed)
|
||||
out = [0.0] * (frames * ch)
|
||||
for c in range(ch):
|
||||
ph = 0.0
|
||||
notes = [(220.0 * 2 ** (rng.randrange(0, 24) / 12.0), rng.random() * 0.25 + 0.05) for _ in range(4)]
|
||||
for i in range(frames):
|
||||
t = i / rate
|
||||
if kind == "sine":
|
||||
v = 0.5 * math.sin(2 * math.pi * (440 + 110 * c) * t) + 0.2 * math.sin(2 * math.pi * 1000 * t + c)
|
||||
elif kind == "sweep":
|
||||
f0, f1 = 50.0, rate / 2.2
|
||||
dur = frames / rate
|
||||
f = f0 * (f1 / f0) ** (t / dur)
|
||||
ph += 2 * math.pi * f / rate
|
||||
v = 0.6 * math.sin(ph + c)
|
||||
elif kind == "noise":
|
||||
v = (rng.random() * 2 - 1) * 0.25
|
||||
elif kind == "music":
|
||||
v = 0.0
|
||||
for k, (f, a) in enumerate(notes):
|
||||
seg = (i // max(1, rate // 4) + k) % 4
|
||||
env = math.exp(-3.0 * ((i % max(1, rate // 4)) / rate))
|
||||
if seg != 3:
|
||||
v += a * env * (math.sin(2 * math.pi * f * t) + 0.3 * math.sin(4 * math.pi * f * t) + 0.1 * math.sin(6 * math.pi * f * t))
|
||||
v += (rng.random() * 2 - 1) * 0.01
|
||||
elif kind == "silence":
|
||||
v = 0.0
|
||||
elif kind == "square":
|
||||
v = 0.4 if math.sin(2 * math.pi * (300 + 50 * c) * t) >= 0 else -0.4
|
||||
elif kind == "loud":
|
||||
v = 0.98 * math.sin(2 * math.pi * 330 * t + c)
|
||||
else:
|
||||
raise ValueError(kind)
|
||||
out[i * ch + c] = v
|
||||
return out
|
||||
|
||||
|
||||
def quantize(samples, bits):
|
||||
s = 2 ** (bits - 1)
|
||||
return [max(-s, min(s - 1, int(math.floor(v * s + 0.5)))) / s for v in samples]
|
||||
|
||||
|
||||
def f32le(samples):
|
||||
a = array.array("f", samples)
|
||||
if sys.byteorder != "little":
|
||||
a.byteswap()
|
||||
return a.tobytes()
|
||||
|
||||
|
||||
def from_f32le(b):
|
||||
a = array.array("f")
|
||||
a.frombytes(b[: len(b) // 4 * 4])
|
||||
if sys.byteorder != "little":
|
||||
a.byteswap()
|
||||
return a.tolist()
|
||||
|
||||
|
||||
def wav(samples, rate, ch, bits=16, float_=False):
|
||||
n = len(samples) // ch
|
||||
if float_:
|
||||
data = f32le(samples)
|
||||
fmt = struct.pack("<HHIIHH", 3, ch, rate, rate * ch * 4, ch * 4, 32)
|
||||
else:
|
||||
bps = bits // 8
|
||||
s = 2 ** (bits - 1)
|
||||
out = bytearray()
|
||||
for v in samples:
|
||||
q = max(-s, min(s - 1, int(math.floor(v * s + 0.5))))
|
||||
if bits == 8:
|
||||
out.append(q + 128)
|
||||
else:
|
||||
out += (q & ((1 << bits) - 1)).to_bytes(bps, "little")
|
||||
data = bytes(out)
|
||||
fmt = struct.pack("<HHIIHH", 1, ch, rate, rate * ch * bps, ch * bps, bits)
|
||||
body = b"WAVE" + b"fmt " + struct.pack("<I", len(fmt)) + fmt + b"data" + struct.pack("<I", len(data)) + data
|
||||
if len(data) % 2:
|
||||
body += b"\0"
|
||||
return b"RIFF" + struct.pack("<I", len(body)) + body
|
||||
|
||||
|
||||
def tool(ctx, packages, argv, data=None, ext="bin", outext=None):
|
||||
"""run argv (a list; "{in}" / "{out}" are replaced by temp paths) under nix; returns stdout, or the {out} file"""
|
||||
d = tempfile.mkdtemp(prefix="fmt-audio-")
|
||||
try:
|
||||
inp = os.path.join(d, "in." + ext)
|
||||
out = os.path.join(d, "out." + (outext or "bin"))
|
||||
if data is not None:
|
||||
with open(inp, "wb") as f:
|
||||
f.write(data)
|
||||
args = [a.replace("{in}", inp).replace("{out}", out) for a in argv]
|
||||
stdout = ctx.nix(packages, args)
|
||||
if outext:
|
||||
with open(out, "rb") as f:
|
||||
return f.read()
|
||||
return stdout
|
||||
finally:
|
||||
shutil.rmtree(d, ignore_errors=True)
|
||||
|
||||
|
||||
def ffdecode(ctx, data, fmt=None, ext="bin", extra=None):
|
||||
"""(rate, channels, floats) of any file ffmpeg reads"""
|
||||
probe = tool(ctx, "ffmpeg", ["ffprobe", "-v", "error", "-show_entries", "stream=sample_rate,channels", "-of", "csv=p=0"]
|
||||
+ (["-f", fmt] if fmt else []) + ["{in}"], data, ext).decode().strip().split("\n")[0].split(",")
|
||||
rate, ch = int(probe[0]), int(probe[1])
|
||||
raw = tool(ctx, "ffmpeg", ["ffmpeg", "-v", "error"] + (["-f", fmt] if fmt else []) + ["-i", "{in}"] + (extra or [])
|
||||
+ ["-f", "f32le", "-acodec", "pcm_f32le", "-"], data, ext)
|
||||
return rate, ch, from_f32le(raw)
|
||||
|
||||
|
||||
def snr(ref, test, ch, max_lag=0, skip=0, hints=None):
|
||||
"""SNR (dB) of test vs ref over their common frames (after `skip` frames), best lag in [-max_lag, max_lag]
|
||||
(test[i + lag] ~ ref[i]). hints: lags tried first; the search runs only when none gives 10 dB. Returns (snr, lag)."""
|
||||
if hints:
|
||||
got = max(snr(ref, test, ch, 0, skip, None) if h == 0 else _snr_at(ref, test, ch, h, skip) for h in hints)
|
||||
if got[0] >= 10:
|
||||
return got
|
||||
best = (-1e9, 0)
|
||||
nref, ntest = len(ref) // ch, len(test) // ch
|
||||
lags = range(-max_lag, max_lag + 1) if max_lag else [0]
|
||||
if max_lag > 64:
|
||||
# coarse cross-correlation on the first channel to find candidate lags, then refine
|
||||
cands = []
|
||||
m = min(nref, 1 << 15)
|
||||
seg = [ref[i * ch] for i in range(skip, min(nref, skip + m))]
|
||||
for lag in range(-max_lag, max_lag + 1):
|
||||
acc = 0.0
|
||||
for i in range(0, len(seg), 7):
|
||||
j = skip + i + lag
|
||||
if 0 <= j < ntest:
|
||||
acc += seg[i] * test[j * ch]
|
||||
cands.append((acc, lag))
|
||||
cands.sort(reverse=True)
|
||||
lags = sorted(set(l for _, l in cands[:3]))
|
||||
for lag in lags:
|
||||
sig = err = 0.0
|
||||
for i in range(skip, nref):
|
||||
j = i + lag
|
||||
if j < 0 or j >= ntest:
|
||||
continue
|
||||
for c in range(ch):
|
||||
a = ref[i * ch + c]
|
||||
e = a - test[j * ch + c]
|
||||
sig += a * a
|
||||
err += e * e
|
||||
s = 200.0 if err == 0 else (10 * math.log10(sig / err) if sig > 0 else -200.0)
|
||||
if s > best[0]:
|
||||
best = (s, lag)
|
||||
return best
|
||||
|
||||
|
||||
def _snr_at(ref, test, ch, lag, skip):
|
||||
sig = err = 0.0
|
||||
nref, ntest = len(ref) // ch, len(test) // ch
|
||||
for i in range(skip, nref):
|
||||
j = i + lag
|
||||
if 0 <= j < ntest:
|
||||
for c in range(ch):
|
||||
a = ref[i * ch + c]
|
||||
e = a - test[j * ch + c]
|
||||
sig += a * a
|
||||
err += e * e
|
||||
return (200.0 if err == 0 else (10 * math.log10(sig / err) if sig > 0 else -200.0), lag)
|
||||
|
||||
|
||||
def luau_bin():
|
||||
p = shutil.which("luau")
|
||||
if p:
|
||||
return p
|
||||
return subprocess.run(["nix", "shell", "nixpkgs#luau", "-c", "sh", "-c", "command -v luau"], capture_output=True, check=True,
|
||||
text=True).stdout.strip()
|
||||
|
||||
|
||||
def luau(ctx, code):
|
||||
d = os.path.join(ROOT, "tests", "gen")
|
||||
os.makedirs(d, exist_ok=True)
|
||||
fd, path = tempfile.mkstemp(prefix="_run_", suffix=".luau", dir=d)
|
||||
try:
|
||||
with os.fdopen(fd, "w") as f:
|
||||
f.write(code)
|
||||
r = subprocess.run([luau_bin(), "--codegen", "-O2", path], cwd=ROOT, capture_output=True)
|
||||
if r.returncode != 0:
|
||||
raise RuntimeError("luau failed:\n" + r.stderr.decode(errors="replace") + r.stdout.decode(errors="replace")[-2000:])
|
||||
out = r.stdout
|
||||
return out[:-1] if out.endswith(b"\n") else out
|
||||
finally:
|
||||
os.unlink(path)
|
||||
|
||||
|
||||
def emit_signal(ctx, name, samples, rate, ch):
|
||||
"""emit tests/gen/<name>.luau = { rate, channels, frames, data = f32le bytes } (the input encoders are tested on)"""
|
||||
ctx.emit(name, {"rate": rate, "channels": ch, "frames": len(samples) // ch, "data": f32le(samples)})
|
||||
|
||||
|
||||
def encode_luau(ctx, module, sigmod, opts_lua="nil", source="audio"):
|
||||
"""encode the emitted signal module `sigmod` with require("@formats/<module>").encode(audio, opts) in Luau; returns
|
||||
the encoded bytes. source = "decoder" feeds a streaming Decoder (codecs/Pcm.audioDecoder) instead of the Audio."""
|
||||
code = """
|
||||
local S = require("@tests/gen/%s")
|
||||
local Types = require("@formats/Types")
|
||||
local Pcm = require("@formats/codecs/Pcm")
|
||||
local M = require("@formats/%s")
|
||||
local a = Types.Audio.new(S.rate, S.channels, S.frames)
|
||||
buffer.writestring(a.samples, 0, S.data)
|
||||
local src: any = a
|
||||
if "%s" == "decoder" then src = Pcm.audioDecoder(a) end
|
||||
local out, err = M.encode(src, %s)
|
||||
if not out then error("encode failed: " .. tostring(err)) end
|
||||
print(buffer.tostring(out))
|
||||
""" % (sigmod, module, source, opts_lua)
|
||||
return luau(ctx, code)
|
||||
|
||||
|
||||
def max_diff(a, b):
|
||||
if len(a) != len(b):
|
||||
return float("inf")
|
||||
return max((abs(x - y) for x, y in zip(a, b)), default=0.0)
|
||||
|
||||
|
||||
def pcm_fixtures(ctx, fmt, made, encodes, sig_rate=22050, sig_frames=3000):
|
||||
"""The fixtures of an uncompressed container (aiff, au, voc):
|
||||
made = [(name, packages, argv)]: reference tools write files from {in} (a stereo / mono 16-bit or float WAV of
|
||||
the test signal; argv may use {in_mono}, {in_float}) into {out}; each file is decoded by ffmpeg as the
|
||||
reference (f32le)
|
||||
encodes = [(name, opts_lua, channels)]: our encoder's output (in the fixture step) decoded by ffmpeg, compared
|
||||
against the f32 input (max abs difference, which the test bounds by the format's quantization step)
|
||||
Emits <fmt>_cases (files + references), <fmt>_sig / <fmt>_sig1 (the inputs, stereo / mono) and <fmt>_enc."""
|
||||
stereo = signal("music", sig_rate, 2, sig_frames, seed=3)
|
||||
mono = signal("sweep", sig_rate, 1, sig_frames, seed=4)
|
||||
emit_signal(ctx, fmt + "_sig", stereo, sig_rate, 2)
|
||||
emit_signal(ctx, fmt + "_sig1", mono, sig_rate, 1)
|
||||
inputs = {"{in}": wav(stereo, sig_rate, 2, 16), "{in_mono}": wav(mono, sig_rate, 1, 16),
|
||||
"{in_float}": wav(stereo, sig_rate, 2, float_=True)}
|
||||
cases = []
|
||||
for name, packages, argv in made:
|
||||
d = tempfile.mkdtemp(prefix="fmt-audio-")
|
||||
try:
|
||||
paths = {}
|
||||
for key, data in inputs.items():
|
||||
paths[key] = os.path.join(d, key.strip("{}") + ".wav")
|
||||
with open(paths[key], "wb") as f:
|
||||
f.write(data)
|
||||
out = os.path.join(d, "out." + fmt)
|
||||
args = []
|
||||
for a in argv:
|
||||
for key, p in paths.items():
|
||||
a = a.replace(key, p)
|
||||
args.append(a.replace("{out}", out))
|
||||
ctx.nix(packages, args)
|
||||
with open(out, "rb") as f:
|
||||
data = f.read()
|
||||
finally:
|
||||
shutil.rmtree(d, ignore_errors=True)
|
||||
rate, ch, ref = ffdecode(ctx, data, ext=fmt)
|
||||
cases.append({"name": name, "data": data, "rate": rate, "channels": ch, "frames": len(ref) // ch, "ref": f32le(ref)})
|
||||
ctx.emit(fmt + "_cases", cases)
|
||||
results = []
|
||||
for name, opts_lua, ch in encodes:
|
||||
sig = stereo if ch == 2 else mono
|
||||
out = encode_luau(ctx, "audio/" + fmt, fmt + ("_sig" if ch == 2 else "_sig1"), opts_lua)
|
||||
streamed = encode_luau(ctx, "audio/" + fmt, fmt + ("_sig" if ch == 2 else "_sig1"), opts_lua, source="decoder")
|
||||
rate, dch, dec = ffdecode(ctx, out, ext=fmt)
|
||||
errs = tool(ctx, "ffmpeg", ["ffmpeg", "-v", "error", "-i", "{in}", "-f", "null", "-"], out, fmt)
|
||||
results.append({"name": name, "opts": opts_lua, "channels": dch, "rate": rate, "frames": len(dec) // max(1, dch),
|
||||
"maxDiff": max_diff(sig, dec) if dch == ch else 99.0, "ffmpegErrors": errs.decode(errors="replace"),
|
||||
"bytes": len(out), "sameStreamed": out == streamed, "data": out})
|
||||
ctx.emit(fmt + "_enc", results)
|
||||
|
||||
|
||||
def encode_luau_many(ctx, module, jobs, sigmod):
|
||||
"""jobs = [(signal name, opts_lua)] over the emitted module sigmod = { [name] = { rate, channels, frames, data } }
|
||||
-> [bytes]: one Luau run encodes them all (length-prefixed on stdout)"""
|
||||
body = ['job("%s", %s)' % (name, opts) for name, opts in jobs]
|
||||
code = """
|
||||
local Types = require("@formats/Types")
|
||||
local M = require("@formats/%s")
|
||||
local S = require("@tests/gen/%s")
|
||||
local outs = {}
|
||||
local function job(name, opts)
|
||||
local s = S[name]
|
||||
local a = Types.Audio.new(s.rate, s.channels, s.frames)
|
||||
buffer.writestring(a.samples, 0, s.data)
|
||||
local out, err = M.encode(a, opts)
|
||||
if not out then error("encode failed: " .. tostring(err)) end
|
||||
local n = buffer.len(out)
|
||||
table.insert(outs, string.format("%%012d", n) .. buffer.tostring(out))
|
||||
end
|
||||
%s
|
||||
print(table.concat(outs))
|
||||
""" % (module, sigmod, "\n".join(body))
|
||||
raw = luau(ctx, code)
|
||||
res, p = [], 0
|
||||
while p < len(raw):
|
||||
n = int(raw[p:p + 12])
|
||||
res.append(raw[p + 12:p + 12 + n])
|
||||
p += 12 + n
|
||||
return res
|
||||
|
||||
|
||||
def shell_many(ctx, packages, files, script):
|
||||
"""write files {name: bytes} into a temp dir and run `sh -c script` there under nix; returns stdout"""
|
||||
d = tempfile.mkdtemp(prefix="fmt-audio-")
|
||||
try:
|
||||
for name, data in files.items():
|
||||
with open(os.path.join(d, name), "wb") as f:
|
||||
f.write(data)
|
||||
return ctx.nix(packages, ["sh", "-c", "cd '%s' && %s" % (d, script)])
|
||||
finally:
|
||||
shutil.rmtree(d, ignore_errors=True)
|
||||
@@ -0,0 +1,51 @@
|
||||
# AIFF / AIFF-C fixtures (tools/fixtures.py): files written by ffmpeg and sox in every sample format we read, each
|
||||
# with ffmpeg's f32 decode as the reference; our encoder's output for every sample format, decoded by ffmpeg in the
|
||||
# fixture step (tools/fixtures/_audio.py pcm_fixtures).
|
||||
# tests/gen/aiff_cases.luau { name, data, rate, channels, frames, ref (f32le) }
|
||||
# tests/gen/aiff_enc.luau { name, opts, channels, rate, frames, maxDiff, ffmpegErrors, bytes, sameStreamed, data }
|
||||
# tests/gen/aiff_sig*.luau the encoder inputs
|
||||
import importlib.util, os
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py"))
|
||||
A = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(A)
|
||||
|
||||
INPUTS = ["src/Formats/audio/aiff", "src/Formats/codecs/Pcm"]
|
||||
|
||||
|
||||
def ff(codec, src="{in}", extra=()):
|
||||
return ["ffmpeg", "-v", "error", "-i", src] + list(extra) + ["-c:a", codec, "-f", "aiff", "-y", "{out}"]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
made = [
|
||||
("ffmpeg-s16be", "ffmpeg", ff("pcm_s16be")),
|
||||
("ffmpeg-s16be-mono", "ffmpeg", ff("pcm_s16be", "{in_mono}")),
|
||||
("ffmpeg-s8", "ffmpeg", ff("pcm_s8")),
|
||||
("ffmpeg-s24be", "ffmpeg", ff("pcm_s24be", "{in_float}")),
|
||||
("ffmpeg-s32be", "ffmpeg", ff("pcm_s32be", "{in_float}")),
|
||||
("ffmpeg-sowt", "ffmpeg", ff("pcm_s16le")),
|
||||
("ffmpeg-fl32", "ffmpeg", ff("pcm_f32be", "{in_float}")),
|
||||
("ffmpeg-fl64", "ffmpeg", ff("pcm_f64be", "{in_float}")),
|
||||
("ffmpeg-ulaw", "ffmpeg", ff("pcm_mulaw")),
|
||||
("ffmpeg-alaw", "ffmpeg", ff("pcm_alaw")),
|
||||
("ffmpeg-48k-6ch", "ffmpeg", ["ffmpeg", "-v", "error", "-i", "{in}", "-af", "aresample=48000,pan=5.1|c0=c0|c1=c1|c2=c0|c3=c1|c4=c0|c5=c1", "-c:a", "pcm_s16be", "-f", "aiff", "-y", "{out}"]),
|
||||
("ffmpeg-tags", "ffmpeg", ff("pcm_s16be", extra=("-metadata", "title=Song Name", "-metadata", "author=Some One", "-metadata", "comment=hello"))),
|
||||
("sox-aiff-s16", "sox", ["sox", "{in}", "-t", "aiff", "{out}"]),
|
||||
("sox-aiff-s24-mono", "sox", ["sox", "{in_mono}", "-b", "24", "-t", "aiff", "{out}"]),
|
||||
("sox-aifc-s16", "sox", ["sox", "{in}", "-t", "aifc", "{out}"]),
|
||||
]
|
||||
encodes = [
|
||||
("s16", "nil", 2),
|
||||
("s16-mono", "nil", 1),
|
||||
("s8", '{ sampleFormat = "s8" }', 2),
|
||||
("s24", '{ sampleFormat = "s24" }', 2),
|
||||
("s32", '{ sampleFormat = "s32" }', 1),
|
||||
("f32", '{ sampleFormat = "f32" }', 2),
|
||||
("f64", '{ sampleFormat = "f64" }', 2),
|
||||
("ulaw", '{ sampleFormat = "ulaw" }', 2),
|
||||
("alaw", '{ sampleFormat = "alaw" }', 1),
|
||||
("sowt16", '{ littleEndian = true }', 2),
|
||||
("aifc-s16", '{ aifc = true }', 2),
|
||||
]
|
||||
A.pcm_fixtures(ctx, "aiff", made, encodes)
|
||||
@@ -0,0 +1,47 @@
|
||||
# Sun AU fixtures (tools/fixtures.py): files written by ffmpeg and sox in every encoding we read, each with ffmpeg's
|
||||
# f32 decode as the reference; our encoder's output for every encoding, decoded by ffmpeg in the fixture step
|
||||
# (tools/fixtures/_audio.py pcm_fixtures).
|
||||
# tests/gen/au_cases.luau { name, data, rate, channels, frames, ref (f32le) }
|
||||
# tests/gen/au_enc.luau { name, opts, channels, rate, frames, maxDiff, ffmpegErrors, bytes, sameStreamed, data }
|
||||
# tests/gen/au_sig*.luau the encoder inputs
|
||||
import importlib.util, os
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py"))
|
||||
A = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(A)
|
||||
|
||||
INPUTS = ["src/Formats/audio/au", "src/Formats/codecs/Pcm"]
|
||||
|
||||
|
||||
def ff(codec, src="{in}", extra=()):
|
||||
return ["ffmpeg", "-v", "error", "-i", src] + list(extra) + ["-c:a", codec, "-f", "au", "-y", "{out}"]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
made = [
|
||||
("ffmpeg-s16be", "ffmpeg", ff("pcm_s16be")),
|
||||
("ffmpeg-s16be-mono", "ffmpeg", ff("pcm_s16be", "{in_mono}")),
|
||||
("ffmpeg-s8", "ffmpeg", ff("pcm_s8")),
|
||||
("ffmpeg-s24be", "ffmpeg", ff("pcm_s24be", "{in_float}")),
|
||||
("ffmpeg-s32be", "ffmpeg", ff("pcm_s32be", "{in_float}")),
|
||||
("ffmpeg-f32be", "ffmpeg", ff("pcm_f32be", "{in_float}")),
|
||||
("ffmpeg-f64be", "ffmpeg", ff("pcm_f64be", "{in_float}")),
|
||||
("ffmpeg-ulaw", "ffmpeg", ff("pcm_mulaw")),
|
||||
("ffmpeg-alaw", "ffmpeg", ff("pcm_alaw")),
|
||||
("sox-comment", "sox", ["sox", "{in}", "--comment", "hello sun", "-t", "au", "{out}"]),
|
||||
("sox-ulaw-8k", "sox", ["sox", "{in_mono}", "-r", "8000", "-e", "mu-law", "-t", "au", "{out}"]),
|
||||
("sox-s16", "sox", ["sox", "{in}", "-t", "au", "{out}"]),
|
||||
("sox-f32", "sox", ["sox", "{in_float}", "-e", "floating-point", "-b", "32", "-t", "au", "{out}"]),
|
||||
]
|
||||
encodes = [
|
||||
("s16", "nil", 2),
|
||||
("s16-mono", "nil", 1),
|
||||
("s8", '{ sampleFormat = "s8" }', 2),
|
||||
("s24", '{ sampleFormat = "s24" }', 2),
|
||||
("s32", '{ sampleFormat = "s32" }', 1),
|
||||
("f32", '{ sampleFormat = "f32" }', 2),
|
||||
("f64", '{ sampleFormat = "f64" }', 2),
|
||||
("ulaw", '{ sampleFormat = "ulaw" }', 2),
|
||||
("alaw", '{ sampleFormat = "alaw" }', 1),
|
||||
]
|
||||
A.pcm_fixtures(ctx, "au", made, encodes)
|
||||
@@ -0,0 +1,89 @@
|
||||
# FLAC encoder fixtures (tools/fixtures.py): our encoder runs in the fixture step (tools/fixtures/_audio.py
|
||||
# encode_luau_many) on test signals; every output must pass `flac -t` (which also checks the decoded PCM against the
|
||||
# STREAMINFO MD5), and that MD5 must equal the MD5 of the input quantized here, so the stream is bit-exact. The level
|
||||
# sweep is compared in size with `flac -<level>` (libFLAC 1.5, --no-padding --no-seektable).
|
||||
# tests/gen/flac_enc.luau { name, sig, opts, bits, channels, frames, flacTest, md5, wantMd5, size, refSize?, data }
|
||||
# tests/gen/flac_enc_sigs.luau { [sig] = { rate, channels, frames, data (f32le) } }: the inputs
|
||||
import hashlib, importlib.util, os
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py"))
|
||||
A = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(A)
|
||||
|
||||
INPUTS = ["src/Formats/audio/flac", "src/Formats/codecs/Pcm", "src/Formats/core/Md5.luau"]
|
||||
|
||||
|
||||
def pcm_bytes(samples, bits):
|
||||
s = 2 ** (bits - 1)
|
||||
nb = (bits + 7) // 8
|
||||
out = bytearray()
|
||||
for v in samples:
|
||||
q = max(-s, min(s - 1, int(__import__("math").floor(v * s + 0.5))))
|
||||
out += (q & ((1 << (8 * nb)) - 1)).to_bytes(nb, "little")
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
sigs = {}
|
||||
|
||||
def sig(kind, ch, frames, rate=44100):
|
||||
name = "flacsig_%s_%d_%d_%d" % (kind, ch, frames, rate)
|
||||
if name not in sigs:
|
||||
samples = A.from_f32le(A.f32le(A.signal(kind, rate, ch, frames, seed=frames + ch))) # f32-rounded
|
||||
sigs[name] = (samples, rate, ch)
|
||||
return name
|
||||
|
||||
cases = [] # (name, sigmod, bits, opts_lua, ref_level)
|
||||
for level in range(9):
|
||||
cases.append(("L%d-music-st16" % level, sig("music", 2, 20000), 16, "{ level = %d, bits = 16 }" % level, level))
|
||||
cases.append(("L%d-noise-mono24" % level, sig("noise", 1, 9000), 24, "{ level = %d, bits = 24 }" % level, level))
|
||||
cases.append(("L%d-sweep-6ch8" % level, sig("sweep", 6, 5000, 48000), 8, "{ level = %d, bits = 8 }" % level, level))
|
||||
for kind in ("sine", "silence", "loud", "square"):
|
||||
for ch in (1, 2):
|
||||
for bits in (8, 16, 24):
|
||||
cases.append(("%s-%dch-%d" % (kind, ch, bits), sig(kind, ch, 4500), bits, "{ bits = %d }" % bits, None))
|
||||
for level in (0, 5, 8):
|
||||
for n in (1, 15, 100, 1153, 4097):
|
||||
cases.append(("L%d-len%d" % (level, n), sig("music", 2, n), 16, "{ level = %d }" % level, None))
|
||||
for bs in (192, 576, 1000, 4608, 16):
|
||||
cases.append(("bs%d" % bs, sig("music", 2, 7000), 16, "{ blockSize = %d }" % bs, None))
|
||||
cases.append(("bits12-22k", sig("music", 1, 6000, 22050), 12, "{ bits = 12 }", None))
|
||||
cases.append(("bits20-96k", sig("sweep", 2, 6000, 96000), 20, "{ bits = 20, level = 8 }", None))
|
||||
cases.append(("rate-11111", sig("sine", 2, 3000, 11111), 16, "nil", None))
|
||||
cases.append(("seek-1s", sig("music", 2, 30000), 16, "{ seekInterval = 0.25 }", None))
|
||||
cases.append(("padding", sig("sine", 1, 1000), 16, "{ padding = 100 }", None))
|
||||
|
||||
ctx.emit("flac_enc_sigs", {n: {"rate": r, "channels": c, "frames": len(x) // c, "data": A.f32le(x)} for n, (x, r, c) in sigs.items()})
|
||||
outs = A.encode_luau_many(ctx, "audio/flac", [(c[1], c[3]) for c in cases], "flac_enc_sigs")
|
||||
files = {"c%03d.flac" % i: o for i, o in enumerate(outs)}
|
||||
script = 'for f in c*.flac; do r=$(flac -s -t "$f" 2>&1); echo "$f|$?|$(metaflac --show-md5sum "$f")|$(echo $r | tr "\\n" " ")"; done'
|
||||
report = A.shell_many(ctx, "flac", files, script).decode(errors="replace")
|
||||
rows = {}
|
||||
for line in report.strip().split("\n"):
|
||||
f, rc, md5, msg = line.split("|", 3)
|
||||
rows[f] = (int(rc), md5.strip(), msg.strip())
|
||||
# libFLAC reference sizes for the level sweep
|
||||
refs = {}
|
||||
wavs = {}
|
||||
for i, c in enumerate(cases):
|
||||
if c[4] is not None:
|
||||
samples, rate, ch = sigs[c[1]]
|
||||
wavs["r%03d.raw" % i] = pcm_bytes(samples, c[2])
|
||||
wavs["r%03d.arg" % i] = ("-%d --channels=%d --bps=%d --sample-rate=%d" % (c[4], ch, c[2], rate)).encode()
|
||||
script = ('for i in r*.raw; do rm -f out.flac; flac -s $(cat "${i%.raw}.arg") --force-raw-format --endian=little --sign=signed '
|
||||
'--no-padding --no-seektable -f -o out.flac "$i"; echo "$i $(stat -c %s out.flac)"; done')
|
||||
for line in A.shell_many(ctx, "flac", wavs, script).decode().strip().split("\n"):
|
||||
f, size = line.split()
|
||||
refs[int(f[1:4])] = int(size)
|
||||
emitted = []
|
||||
for i, (name, sigmod, bits, opts, lvl) in enumerate(cases):
|
||||
samples, rate, ch = sigs[sigmod]
|
||||
rc, md5, msg = rows["c%03d.flac" % i]
|
||||
want = hashlib.md5(pcm_bytes(samples, bits)).hexdigest()
|
||||
e = {"name": name, "sig": sigmod, "opts": opts, "bits": bits, "channels": ch, "frames": len(samples) // ch,
|
||||
"flacTest": "" if rc == 0 else (msg or "rc %d" % rc), "md5": md5, "wantMd5": want, "size": len(outs[i]),
|
||||
"data": outs[i]}
|
||||
if i in refs:
|
||||
e["refSize"] = refs[i]
|
||||
emitted.append(e)
|
||||
ctx.emit("flac_enc", emitted)
|
||||
@@ -0,0 +1,80 @@
|
||||
# MP3 / MP2 encoder fixtures (tools/fixtures.py): our layer III and layer II encoders run in the fixture step
|
||||
# (tools/fixtures/_audio.py encode_luau_many) on test signals at every MPEG sample rate group, several bit rates and
|
||||
# modes; ffmpeg (mp3float / mp2float) and LAME (`lame --decode`, layer III) decode the files. Recorded per file: ffmpeg's
|
||||
# error output (must be empty), the decoded frame counts, and the SNR against the input after aligning the decoder delay.
|
||||
# tests/gen/mp3_enc.luau { name, sig, layer, bitrate, mode, rate, channels, frames, ffErrors, ffFrames, ffSnr,
|
||||
# ffLag, lameFrames?, lameSnr?, size, data }
|
||||
# tests/gen/mp3_enc_sigs.luau { [sig] = { rate, channels, frames, data (f32le) } }
|
||||
import importlib.util, io, os, wave
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py"))
|
||||
A = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(A)
|
||||
|
||||
INPUTS = ["src/Formats/audio/mp3", "src/Formats/codecs/Pcm"]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
sigs = {}
|
||||
|
||||
def sig(kind, ch, secs, rate):
|
||||
name = "%s_%d_%d" % (kind, ch, rate)
|
||||
if name not in sigs:
|
||||
frames = int(secs * rate)
|
||||
sigs[name] = (A.from_f32le(A.f32le(A.signal(kind, rate, ch, frames, seed=ch * 7 + rate % 97))), rate, ch)
|
||||
return name
|
||||
|
||||
cases = [] # name, sig, layer, bitrate, mode
|
||||
for kind in ("music", "sine", "sweep"):
|
||||
for br in (64, 128, 192, 320):
|
||||
cases.append(("l3-%s-44k-%d-joint" % (kind, br), sig(kind, 2, 1.0, 44100), 3, br, "joint"))
|
||||
cases.append(("l3-music-44k-128-stereo", sig("music", 2, 1.0, 44100), 3, 128, "stereo"))
|
||||
cases.append(("l3-music-48k-160-joint", sig("music", 2, 1.0, 48000), 3, 160, "joint"))
|
||||
cases.append(("l3-music-32k-96-mono", sig("music", 1, 1.0, 32000), 3, 96, "mono"))
|
||||
cases.append(("l3-noise-44k-128-mono", sig("noise", 1, 0.6, 44100), 3, 128, "mono"))
|
||||
cases.append(("l3-music-22k-64-joint", sig("music", 2, 1.0, 22050), 3, 64, "joint"))
|
||||
cases.append(("l3-music-24k-96-stereo", sig("music", 2, 1.0, 24000), 3, 96, "stereo"))
|
||||
cases.append(("l3-sweep-16k-48-mono", sig("sweep", 1, 1.0, 16000), 3, 48, "mono"))
|
||||
cases.append(("l3-music-11k-32-mono", sig("music", 1, 1.0, 11025), 3, 32, "mono"))
|
||||
cases.append(("l3-music-8k-24-joint", sig("music", 2, 1.0, 8000), 3, 24, "joint"))
|
||||
cases.append(("l3-music-12k-64-stereo", sig("music", 2, 1.0, 12000), 3, 64, "stereo"))
|
||||
cases.append(("l3-silence-44k-128", sig("silence", 2, 0.3, 44100), 3, 128, "joint"))
|
||||
cases.append(("l3-loud-44k-128", sig("loud", 2, 0.5, 44100), 3, 128, "joint"))
|
||||
for kind in ("music", "sine", "sweep"):
|
||||
for br in (128, 192, 256, 384):
|
||||
cases.append(("l2-%s-44k-%d" % (kind, br), sig(kind, 2, 1.0, 44100), 2, br, "stereo"))
|
||||
cases.append(("l2-music-48k-192", sig("music", 2, 1.0, 48000), 2, 192, "stereo"))
|
||||
cases.append(("l2-music-32k-mono-96", sig("music", 1, 1.0, 32000), 2, 96, "mono"))
|
||||
cases.append(("l2-music-44k-mono-64", sig("music", 1, 1.0, 44100), 2, 64, "mono"))
|
||||
cases.append(("l2-music-24k-96", sig("music", 2, 1.0, 24000), 2, 96, "stereo"))
|
||||
cases.append(("l2-sweep-16k-mono-48", sig("sweep", 1, 1.0, 16000), 2, 48, "mono"))
|
||||
cases.append(("l2-loud-44k-192", sig("loud", 2, 0.5, 44100), 2, 192, "stereo"))
|
||||
|
||||
ctx.emit("mp3_enc_sigs", {n: {"rate": r, "channels": c, "frames": len(x) // c, "data": A.f32le(x)} for n, (x, r, c) in sigs.items()})
|
||||
jobs = [(c[1], '{ layer = %d, bitrate = %d, mode = "%s" }' % (c[2], c[3], c[4])) for c in cases]
|
||||
outs = A.encode_luau_many(ctx, "audio/mp3", jobs, "mp3_enc_sigs")
|
||||
emitted = []
|
||||
for (name, sigmod, layer, br, mode), data in zip(cases, outs):
|
||||
samples, rate, ch = sigs[sigmod]
|
||||
ext = "mp3" if layer == 3 else "mp2"
|
||||
errs = A.tool(ctx, "ffmpeg", ["ffmpeg", "-v", "error", "-i", "{in}", "-f", "null", "-"], data, ext).decode(errors="replace")
|
||||
frate, fch, dec = A.ffdecode(ctx, data, ext=ext)
|
||||
dch = fch
|
||||
ref = samples if dch == ch else [samples[i // dch] for i in range(len(samples) // ch * dch)]
|
||||
snr, lag = A.snr(ref, dec, dch, max_lag=1600, skip=200, hints=[1057 if layer == 3 else 481]) if dch == ch else (-99.0, 0)
|
||||
e = {"name": name, "sig": sigmod, "layer": layer, "bitrate": br, "mode": mode, "rate": rate, "channels": ch,
|
||||
"frames": len(samples) // ch, "ffErrors": errs, "ffFrames": len(dec) // max(1, fch), "ffRate": frate,
|
||||
"ffChannels": fch, "ffSnr": snr, "ffLag": lag, "size": len(data), "data": data}
|
||||
if layer == 3:
|
||||
wavb = A.tool(ctx, "lame", ["lame", "--quiet", "--decode", "{in}", "{out}"], data, "mp3", "wav")
|
||||
with wave.open(io.BytesIO(wavb)) as wf:
|
||||
lch, raw = wf.getnchannels(), wf.readframes(wf.getnframes())
|
||||
lame = [int.from_bytes(raw[i:i + 2], "little", signed=True) / 32768 for i in range(0, len(raw), 2)]
|
||||
if lch == ch:
|
||||
ls, ll = A.snr(samples, lame, ch, max_lag=1600, skip=200, hints=[1057, 528, 529])
|
||||
e["lameSnr"], e["lameLag"] = ls, ll
|
||||
e["lameFrames"] = len(lame) // lch
|
||||
emitted.append(e)
|
||||
print(" mp3_enc: %-28s %5d bytes ffmpeg %.1f dB (lag %d)%s%s" % (name, len(data), snr, lag,
|
||||
(" lame %.1f dB" % e["lameSnr"]) if "lameSnr" in e else "", (" ERR " + errs.strip()[:60]) if errs.strip() else ""))
|
||||
ctx.emit("mp3_enc", emitted)
|
||||
@@ -0,0 +1,39 @@
|
||||
# Creative VOC fixtures (tools/fixtures.py): files written by ffmpeg (type 1 + type 8 blocks for 8-bit, type 9 for the
|
||||
# rest) and sox, each with ffmpeg's f32 decode as the reference; our encoder's output for every sample format, decoded
|
||||
# by ffmpeg in the fixture step (tools/fixtures/_audio.py pcm_fixtures).
|
||||
# tests/gen/voc_cases.luau { name, data, rate, channels, frames, ref (f32le) }
|
||||
# tests/gen/voc_enc.luau { name, opts, channels, rate, frames, maxDiff, ffmpegErrors, bytes, sameStreamed, data }
|
||||
# tests/gen/voc_sig*.luau the encoder inputs
|
||||
import importlib.util, os
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py"))
|
||||
A = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(A)
|
||||
|
||||
INPUTS = ["src/Formats/audio/voc", "src/Formats/codecs/Pcm"]
|
||||
|
||||
|
||||
def ff(codec, src="{in}", extra=()):
|
||||
return ["ffmpeg", "-v", "error", "-i", src] + list(extra) + ["-c:a", codec, "-f", "voc", "-y", "{out}"]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
made = [
|
||||
("ffmpeg-u8-stereo", "ffmpeg", ff("pcm_u8")),
|
||||
("ffmpeg-u8-mono", "ffmpeg", ff("pcm_u8", "{in_mono}")),
|
||||
("ffmpeg-s16", "ffmpeg", ff("pcm_s16le")),
|
||||
("ffmpeg-s16-mono-44k", "ffmpeg", ff("pcm_s16le", "{in_mono}", ("-ar", "44100"))),
|
||||
("ffmpeg-alaw", "ffmpeg", ff("pcm_alaw")),
|
||||
("ffmpeg-ulaw", "ffmpeg", ff("pcm_mulaw", "{in_mono}")),
|
||||
("sox-u8-mono-11k", "sox", ["sox", "{in_mono}", "-r", "11025", "-b", "8", "-t", "voc", "{out}"]),
|
||||
("sox-u8-stereo", "sox", ["sox", "{in}", "-b", "8", "-t", "voc", "{out}"]),
|
||||
("sox-s16-stereo", "sox", ["sox", "{in}", "-b", "16", "-t", "voc", "{out}"]),
|
||||
]
|
||||
encodes = [
|
||||
("s16", "nil", 2),
|
||||
("s16-mono", "nil", 1),
|
||||
("u8", '{ sampleFormat = "u8" }', 2),
|
||||
("alaw", '{ sampleFormat = "alaw" }', 2),
|
||||
("ulaw", '{ sampleFormat = "ulaw" }', 1),
|
||||
]
|
||||
A.pcm_fixtures(ctx, "voc", made, encodes)
|
||||
@@ -0,0 +1,57 @@
|
||||
# Ogg Vorbis fixtures (tools/fixtures.py): files made by oggenc (libvorbis, vorbis-tools) and ffmpeg (libvorbis) from
|
||||
# the test signals in tools/fixtures/_audio.py: qualities -1 .. 10, managed bitrate, 8 .. 96 kHz, mono / stereo / 5.1,
|
||||
# transients (block switching), silence, tags, a stream shorter than one block. References: oggdec (libvorbisfile:
|
||||
# the authority on start / end trimming) as 16-bit samples, and ffmpeg's f32 decode (more precise, but its Ogg demuxer
|
||||
# trims some streams differently: the test uses it only when its frame count agrees with oggdec).
|
||||
# tests/gen/vorbis_cases.luau { name, data, rate, channels, frames (oggdec), ref16 (s16le, oggdec), ffFrames,
|
||||
# ffRef (f32le, ffmpeg), inputFrames }
|
||||
import importlib.util, os
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py"))
|
||||
A = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(A)
|
||||
|
||||
CASES = [
|
||||
# name, signal, rate, channels, seconds, tool, args
|
||||
("q5-stereo-44k-music", "music", 44100, 2, 1.5, "oggenc", ["-q", "5"]),
|
||||
("q-1-mono-8k-music", "music", 8000, 1, 1.0, "oggenc", ["-q", "-1"]),
|
||||
("q10-stereo-48k-sweep", "sweep", 48000, 2, 1.0, "oggenc", ["-q", "10"]),
|
||||
("q3-mono-22k-noise", "noise", 22050, 1, 0.7, "oggenc", ["-q", "3"]),
|
||||
("q0-stereo-44k-square", "square", 44100, 2, 1.0, "oggenc", ["-q", "0"]),
|
||||
("q2-stereo-32k-tags", "sine", 32000, 2, 0.6, "oggenc", ["-q", "2", "-t", "A Title", "-a", "An Artist", "-l", "The Album", "-N", "7", "-c", "comment=hello vorbis"]),
|
||||
("managed-64k-stereo", "music", 44100, 2, 1.0, "oggenc", ["--managed", "-b", "64"]),
|
||||
("silence-stereo", "silence", 44100, 2, 0.5, "oggenc", ["-q", "4"]),
|
||||
("short-100", "sine", 44100, 2, 100 / 44100, "oggenc", ["-q", "4"]),
|
||||
("short-3000-mono", "music", 44100, 1, 3000 / 44100, "oggenc", ["-q", "4"]),
|
||||
("q6-stereo-96k", "music", 96000, 2, 0.4, "oggenc", ["-q", "6"]),
|
||||
("ffmpeg-5.1-48k", "music", 48000, 6, 0.6, "ffmpeg", ["-c:a", "libvorbis", "-q:a", "4"]),
|
||||
("ffmpeg-mono-16k", "sweep", 16000, 1, 0.8, "ffmpeg", ["-c:a", "libvorbis", "-q:a", "1"]),
|
||||
("loud-stereo", "loud", 44100, 2, 0.5, "oggenc", ["-q", "8"]),
|
||||
]
|
||||
|
||||
INPUTS = []
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
cases = []
|
||||
bench = None
|
||||
for name, kind, rate, ch, secs, tool, args in CASES:
|
||||
frames = max(1, int(round(secs * rate)))
|
||||
sig = A.signal(kind, rate, ch, frames, seed=len(name))
|
||||
wav = A.wav(sig, rate, ch, float_=True) if tool == "ffmpeg" else A.wav(sig, rate, ch, 16)
|
||||
if tool == "oggenc":
|
||||
data = A.tool(ctx, "vorbis-tools", ["oggenc", "-Q", "--serial", "1234"] + args + ["-o", "{out}", "{in}"], wav, "wav", "ogg")
|
||||
else:
|
||||
data = A.tool(ctx, "ffmpeg", ["ffmpeg", "-v", "error", "-i", "{in}"] + args + ["-f", "ogg", "-y", "{out}"], wav, "wav", "ogg")
|
||||
rrate, rch, ref = A.ffdecode(ctx, data, ext="ogg")
|
||||
raw = A.tool(ctx, "vorbis-tools", ["oggdec", "-Q", "-R", "-o", "{out}", "{in}"], data, "ogg", "raw")
|
||||
case = {"name": name, "data": data, "rate": rrate, "channels": rch, "frames": len(raw) // (2 * rch), "ref16": raw,
|
||||
"ffFrames": len(ref) // rch, "inputFrames": frames}
|
||||
if len(ref) // rch == len(raw) // (2 * rch):
|
||||
case["ffRef"] = A.f32le(ref)
|
||||
cases.append(case)
|
||||
ctx.emit("vorbis_cases", cases)
|
||||
# bench: 10 s of stereo music at q5
|
||||
sig = A.signal("music", 44100, 2, 441000, seed=9)
|
||||
data = A.tool(ctx, "vorbis-tools", ["oggenc", "-Q", "-q", "5", "-o", "{out}", "{in}"], A.wav(sig, 44100, 2, 16), "wav", "ogg")
|
||||
ctx.emit("vorbis_bench", {"data": data, "frames": 441000, "rate": 44100, "channels": 2})
|
||||
@@ -0,0 +1,74 @@
|
||||
# Vorbis encoder fixtures (tools/fixtures.py): our encoder runs in the fixture step (tools/fixtures/_audio.py
|
||||
# encode_luau_many) on test signals (qualities -1 .. 10, mono / stereo / 5.1, 8 .. 96 kHz, odd lengths, silence);
|
||||
# oggdec (libvorbisfile) and ffmpeg decode every file, ogginfo checks the stream. Recorded per file: ogginfo's warnings
|
||||
# and errors, oggdec's frame count, the SNR of oggdec's and ffmpeg's decodes against the input (no delay: the
|
||||
# granules are exact).
|
||||
# tests/gen/vorbis_enc.luau { name, sig, quality, rate, channels, frames, ogginfo, oggdecFrames, oggdecSnr,
|
||||
# ffFrames, ffSnr, ffErrors, kbps, data }
|
||||
# tests/gen/vorbis_enc_sigs.luau { [sig] = { rate, channels, frames, data (f32le) } }
|
||||
import importlib.util, os, re
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py"))
|
||||
A = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(A)
|
||||
|
||||
INPUTS = ["src/Formats/audio/vorbis", "src/Formats/codecs", "src/Formats/containers/Ogg"]
|
||||
|
||||
|
||||
WAVE_FROM_VORBIS6 = [0, 2, 1, 4, 5, 3] # vorbis channel k is WAVE channel WAVE_FROM_VORBIS6[k]
|
||||
|
||||
|
||||
def reorder(x):
|
||||
out = [0.0] * len(x)
|
||||
for i in range(0, len(x) - 5, 6):
|
||||
for k in range(6):
|
||||
out[i + k] = x[i + WAVE_FROM_VORBIS6[k]]
|
||||
return out
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
sigs = {}
|
||||
|
||||
def sig(kind, ch, frames, rate):
|
||||
name = "%s_%d_%d_%d" % (kind, ch, frames, rate)
|
||||
if name not in sigs:
|
||||
sigs[name] = (A.from_f32le(A.f32le(A.signal(kind, rate, ch, frames, seed=frames % 1000 + ch))), rate, ch)
|
||||
return name
|
||||
|
||||
cases = []
|
||||
for q in (-1, 0, 3, 6, 10):
|
||||
cases.append(("music-st-44k-q%d" % q, sig("music", 2, 44100, 44100), q))
|
||||
cases.append(("sine-st-44k-q3", sig("sine", 2, 30000, 44100), 3))
|
||||
cases.append(("sweep-mono-48k-q3", sig("sweep", 1, 40000, 48000), 3))
|
||||
cases.append(("noise-mono-22k-q5", sig("noise", 1, 15000, 22050), 5))
|
||||
cases.append(("music-mono-8k-q2", sig("music", 1, 9000, 8000), 2))
|
||||
cases.append(("music-st-96k-q4", sig("music", 2, 30000, 96000), 4))
|
||||
cases.append(("music-6ch-48k-q3", sig("music", 6, 20000, 48000), 3))
|
||||
cases.append(("square-st-32k-q5", sig("square", 2, 20000, 32000), 5))
|
||||
cases.append(("loud-st-44k-q8", sig("loud", 2, 20000, 44100), 8))
|
||||
cases.append(("silence-st-44k", sig("silence", 2, 10000, 44100), 3))
|
||||
for n in (1, 100, 1024, 1025, 3000):
|
||||
cases.append(("len-%d" % n, sig("music", 2, n, 44100), 3))
|
||||
ctx.emit("vorbis_enc_sigs", {n: {"rate": r, "channels": c, "frames": len(x) // c, "data": A.f32le(x)} for n, (x, r, c) in sigs.items()})
|
||||
outs = A.encode_luau_many(ctx, "audio/vorbis", [(c[1], "{ quality = %d }" % c[2]) for c in cases], "vorbis_enc_sigs")
|
||||
emitted = []
|
||||
for (name, sigmod, q), data in zip(cases, outs):
|
||||
samples, rate, ch = sigs[sigmod]
|
||||
frames = len(samples) // ch
|
||||
info = A.tool(ctx, "vorbis-tools", ["sh", "-c", "ogginfo {in} 2>&1; true"], data, "ogg").decode(errors="replace")
|
||||
problems = "\n".join(l for l in info.split("\n") if re.search(r"(?i)warning|error", l))
|
||||
raw = A.tool(ctx, "vorbis-tools", ["oggdec", "-Q", "-R", "-o", "{out}", "{in}"], data, "ogg", "raw")
|
||||
od = [int.from_bytes(raw[i:i + 2], "little", signed=True) / 32768 for i in range(0, len(raw) - 1, 2)]
|
||||
osnr, _ = A.snr(samples, od, ch) # (oggdec -R keeps the Vorbis channel order)
|
||||
ffe = A.tool(ctx, "ffmpeg", ["ffmpeg", "-v", "error", "-i", "{in}", "-f", "null", "-"], data, "ogg").decode(errors="replace")
|
||||
_, fch, ff = A.ffdecode(ctx, data, ext="ogg")
|
||||
if ch == 6: # ffmpeg reorders to WAVE order (FL FR FC LFE RL RR); Vorbis order is FL FC FR RL RR LFE
|
||||
ff = reorder(ff)
|
||||
fsnr, _ = A.snr(samples, ff, ch) if fch == ch else (-99.0, 0)
|
||||
e = {"name": name, "sig": sigmod, "quality": q, "rate": rate, "channels": ch, "frames": frames, "ogginfo": problems,
|
||||
"oggdecFrames": len(od) // ch, "oggdecSnr": osnr, "ffFrames": len(ff) // max(1, fch), "ffSnr": fsnr,
|
||||
"ffErrors": ffe, "kbps": len(data) * 8 / (frames / rate) / 1000, "data": data}
|
||||
emitted.append(e)
|
||||
print(" vorbis_enc: %-22s %7.1f kbps oggdec %d/%d frames %.1f dB ffmpeg %.1f dB%s" % (name, e["kbps"], e["oggdecFrames"], frames,
|
||||
osnr, fsnr, (" OGGINFO " + problems[:80]) if problems else ""))
|
||||
ctx.emit("vorbis_enc", emitted)
|
||||
Reference in new issue
Block a user