ws-audio: merge ws/absorb (Ogg + muxer, Riff, wav, mp3, opus, apng)
This commit is contained in:
commit
aee2d3257e
72 files changed
+14343
-56
No files matched your search
+29
-1
@@ -1,11 +1,18 @@
|
||||
-- Throughput (bash tools/bench.sh): codec MB/s under both runtimes. MB/s are of decompressed output, best of n runs.
|
||||
-- Fixtures: tools/fixtures/deflate.py (a 6 MB corpus) and tools/fixtures/png.py (1024 x 768 images).
|
||||
-- Fixtures: tools/fixtures/deflate.py (a 6 MB corpus), tools/fixtures/png.py (1024 x 768 images), tools/fixtures/mp3.py,
|
||||
-- tools/fixtures/opus.py (3 s stereo files; MB/s of f32 output, 48 kHz stereo f32 is 0.384 MB/s of real time).
|
||||
local Deflate = require("@formats/codecs/Deflate")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Png = require("@formats/image/png")
|
||||
local B = require("@tests/gen/deflate_bench")
|
||||
local PB = require("@tests/gen/png_bench")
|
||||
local Mp3 = require("@formats/audio/mp3")
|
||||
local MC = require("@tests/gen/mp3_cases")
|
||||
local Opus = require("@formats/audio/opus")
|
||||
local OpusCelt = require("@tests/gen/opus_celt_st_128")
|
||||
local OpusSilk = require("@tests/gen/opus_silk_wb_st")
|
||||
local OpusHybrid = require("@tests/gen/opus_hybrid_st")
|
||||
|
||||
local runtime = if (_G :: any).jit ~= nil then "luajit" else "luau"
|
||||
|
||||
@@ -18,6 +25,7 @@ local function bench(label: string, n: number, bytes: number, f: () -> ())
|
||||
dt = math.min(dt, os.clock() - t0)
|
||||
end
|
||||
print(string.format("%-8s %-30s %8.2f ms %7.1f MB/s", runtime, label, dt * 1000, bytes / dt / 1e6))
|
||||
return dt
|
||||
end
|
||||
|
||||
local z = buffer.fromstring(B.zlib)
|
||||
@@ -56,3 +64,23 @@ do
|
||||
Png.encode(img)
|
||||
end)
|
||||
end
|
||||
for _, name in { "l3_cbr128_js", "l3_vbr_v2_48k", "l2_192_st" } do
|
||||
for _, c in MC do
|
||||
if c.name == name then
|
||||
local b = buffer.fromstring(c.data)
|
||||
local dec = assert(Mp3.open(Bytes.reader(b)))
|
||||
local secs = dec.duration
|
||||
local dt = bench("mp3 decode " .. name, 5, dec.frames * dec.channels * 4, function()
|
||||
local d = assert(Mp3.open(Bytes.reader(b)))
|
||||
d:readAll()
|
||||
end)
|
||||
print(string.format("%-8s %-30s %8.0fx real time", runtime, "", secs / dt))
|
||||
end
|
||||
end
|
||||
end
|
||||
for _, c in { { "celt 128k", OpusCelt }, { "silk wb", OpusSilk }, { "hybrid", OpusHybrid } } do
|
||||
local b = buffer.fromstring(c[2].data)
|
||||
bench("opus decode " .. c[1] .. " (3 s st)", 3, #c[2].ref, function()
|
||||
Opus.decode(Bytes.reader(b))
|
||||
end)
|
||||
end
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
cd "$(dirname "$0")/.." || exit 1
|
||||
LUAU=${LUAU:-$(command -v luau || nix shell nixpkgs#luau -c sh -c 'command -v luau')}
|
||||
LUAJIT=${LUAJIT:-$(command -v luajit || nix shell nixpkgs#luajit -c sh -c 'command -v luajit')}
|
||||
python3 -I tools/fixtures.py deflate png > /dev/null || exit 1
|
||||
python3 -I tools/fixtures.py deflate png mp3 opus > /dev/null || exit 1
|
||||
python3 -I tools/build.py luajit > /dev/null || exit 1
|
||||
"$LUAU" --codegen -O2 tools/bench.luau
|
||||
"$LUAJIT" -e 'package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path' build/luajit/tools/bench.lua
|
||||
@@ -0,0 +1,220 @@
|
||||
# APNG fixtures (tools/fixtures.py).
|
||||
# tests/gen/apng_cases.luau animated PNGs with the reference composited canvases (CRC-32 of each full rgba8 frame)
|
||||
# - made by ffmpeg's apng encoder (sub-rectangles, dispose / blend chosen by ffmpeg, -plays)
|
||||
# - written here by hand: every dispose op (none / background / previous) and blend op (source / over) on
|
||||
# sub-rectangles with partial alpha, a hidden default image (IDAT not part of the animation), palette + tRNS,
|
||||
# grey, RGB, a first frame with dispose previous, split fdATs
|
||||
# The reference canvases come from ffmpeg (`-f apng -i x -f rawvideo -pix_fmt rgba`); a small compositor here
|
||||
# (the same integer blend as ffmpeg's pngdec.c) must agree with ffmpeg, so a broken reference is caught too.
|
||||
# Files ffmpeg cannot represent (the hidden default image) use the compositor here alone.
|
||||
import os, random, struct, subprocess, tempfile, zlib
|
||||
|
||||
|
||||
def chunk(t, d):
|
||||
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d))
|
||||
|
||||
|
||||
CH = {0: 1, 2: 3, 3: 1, 6: 4}
|
||||
|
||||
|
||||
def raw_rows(px, w, h, ct, rng):
|
||||
"""px: list of h rows of w sample tuples -> filtered (random filter per row) scanlines"""
|
||||
ch = CH[ct]
|
||||
out = bytearray()
|
||||
prev = None
|
||||
for y in range(h):
|
||||
row = bytes(s for p in px[y] for s in p)
|
||||
ft = rng.randrange(5)
|
||||
out.append(ft)
|
||||
for i, x in enumerate(row):
|
||||
a = row[i - ch] if i >= ch else 0
|
||||
b = prev[i] if prev else 0
|
||||
c = prev[i - ch] if prev and i >= ch else 0
|
||||
if ft == 4:
|
||||
p = a + b - c
|
||||
pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
|
||||
pred = a if pa <= pb and pa <= pc else (b if pb <= pc else c)
|
||||
else:
|
||||
pred = (0, a, b, (a + b) // 2)[ft]
|
||||
out.append((x - pred) & 255)
|
||||
prev = row
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def to_rgba(ct, s, plte=None, trns=None):
|
||||
if ct == 6:
|
||||
return tuple(s)
|
||||
if ct == 2:
|
||||
return (s[0], s[1], s[2], 255)
|
||||
if ct == 0:
|
||||
return (s[0], s[0], s[0], 255)
|
||||
c = plte[s[0]]
|
||||
a = trns[s[0]] if trns and s[0] < len(trns) else 255
|
||||
return (c[0], c[1], c[2], a)
|
||||
|
||||
|
||||
def apng(w, h, ct, frames, plays=0, default=None, plte=None, trns=None, rng=None, split=1):
|
||||
"""frames: list of dict(x, y, w, h, px, num, den, dispose, blend); default: px of a hidden default image"""
|
||||
rng = rng or random.Random(1)
|
||||
out = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, ct, 0, 0, 0))
|
||||
out += chunk(b"acTL", struct.pack(">II", len(frames), plays))
|
||||
if plte:
|
||||
out += chunk(b"PLTE", b"".join(bytes(c) for c in plte))
|
||||
if trns:
|
||||
out += chunk(b"tRNS", bytes(trns))
|
||||
seq = 0
|
||||
if default is not None:
|
||||
out += chunk(b"IDAT", zlib.compress(raw_rows(default, w, h, ct, rng)))
|
||||
for i, f in enumerate(frames):
|
||||
out += chunk(b"fcTL", struct.pack(">IIIIIHHBB", seq, f["w"], f["h"], f["x"], f["y"], f["num"], f["den"], f["dispose"], f["blend"]))
|
||||
seq += 1
|
||||
z = zlib.compress(raw_rows(f["px"], f["w"], f["h"], ct, rng))
|
||||
step = max(1, -(-len(z) // split))
|
||||
for k in range(0, len(z), step):
|
||||
if i == 0 and default is None:
|
||||
out += chunk(b"IDAT", z[k:k + step])
|
||||
else:
|
||||
out += chunk(b"fdAT", struct.pack(">I", seq) + z[k:k + step])
|
||||
seq += 1
|
||||
return out + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def div255(x):
|
||||
return ((x + 128) * 257) >> 16
|
||||
|
||||
|
||||
def composite(w, h, ct, frames, plte=None, trns=None):
|
||||
"""full rgba8 canvases (bytes), blending like ffmpeg's pngdec.c (APNG spec semantics)"""
|
||||
canvas = [(0, 0, 0, 0)] * (w * h)
|
||||
outs = []
|
||||
for i, f in enumerate(frames):
|
||||
dispose, blend = f["dispose"], f["blend"]
|
||||
if i == 0:
|
||||
blend = 0
|
||||
if dispose == 2:
|
||||
dispose = 1
|
||||
saved = list(canvas)
|
||||
for yy in range(f["h"]):
|
||||
for xx in range(f["w"]):
|
||||
src = to_rgba(ct, f["px"][yy][xx], plte, trns)
|
||||
k = (f["y"] + yy) * w + f["x"] + xx
|
||||
if blend == 0 or src[3] == 255:
|
||||
canvas[k] = src
|
||||
elif src[3] == 0:
|
||||
pass
|
||||
else:
|
||||
fa, bg = src[3], canvas[k]
|
||||
ba = bg[3]
|
||||
oa = fa + div255((255 - fa) * ba)
|
||||
if ba == 255:
|
||||
canvas[k] = tuple(div255(fa * src[c] + (255 - fa) * bg[c]) for c in range(3)) + (oa,)
|
||||
else:
|
||||
canvas[k] = tuple((255 * fa * src[c] + (255 - fa) * ba * bg[c]) // (255 * oa) for c in range(3)) + (oa,)
|
||||
outs.append(b"".join(bytes(p) for p in canvas))
|
||||
if dispose == 1:
|
||||
for yy in range(f["h"]):
|
||||
for xx in range(f["w"]):
|
||||
canvas[(f["y"] + yy) * w + f["x"] + xx] = (0, 0, 0, 0)
|
||||
elif dispose == 2:
|
||||
canvas = saved
|
||||
return outs
|
||||
|
||||
|
||||
def ffmpeg_frames(ctx, data, w, h):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
p = os.path.join(tmp, "in.png")
|
||||
with open(p, "wb") as f:
|
||||
f.write(data)
|
||||
raw = subprocess.run(["ffmpeg", "-v", "error", "-f", "apng", "-i", p, "-f", "rawvideo", "-pix_fmt", "rgba", "-fps_mode", "passthrough", "-"],
|
||||
capture_output=True, check=True).stdout
|
||||
n = w * h * 4
|
||||
return [raw[i:i + n] for i in range(0, len(raw), n)]
|
||||
|
||||
|
||||
def sprite(rng, w, h, ct, alpha=True, ncolors=None):
|
||||
px = []
|
||||
for y in range(h):
|
||||
row = []
|
||||
for x in range(w):
|
||||
if ct == 3:
|
||||
row.append((rng.randrange(ncolors),))
|
||||
elif ct == 0:
|
||||
row.append(((x * 17 + y * 5 + rng.randrange(8)) & 255,))
|
||||
elif ct == 2:
|
||||
row.append((rng.randrange(256), (x * 9) & 255, (y * 13) & 255))
|
||||
else:
|
||||
a = rng.choice((0, 255, 255, rng.randrange(256))) if alpha else 255
|
||||
row.append((rng.randrange(256), (x * 9) & 255, (y * 13) & 255, a))
|
||||
px.append(row)
|
||||
return px
|
||||
|
||||
|
||||
def frame(rng, ct, x, y, w, h, dispose, blend, num=1, den=10, **kw):
|
||||
return {"x": x, "y": y, "w": w, "h": h, "px": sprite(rng, w, h, ct, **kw), "num": num, "den": den, "dispose": dispose, "blend": blend}
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = random.Random(77)
|
||||
cases = []
|
||||
|
||||
def add(name, data, w, h, frames_meta, refs, default_crc=None, plays=0, ffmpeg=True, opaque=False):
|
||||
c = {"name": name, "data": data, "width": w, "height": h, "plays": plays,
|
||||
"frames": [{"x": f["x"], "y": f["y"], "w": f["w"], "h": f["h"], "num": f["num"], "den": f["den"], "dispose": f["dispose"], "blend": f["blend"]} for f in frames_meta],
|
||||
"crcs": [zlib.crc32(r) for r in refs], "ffmpeg": ffmpeg, "opaque": opaque}
|
||||
if default_crc is not None:
|
||||
c["defaultCrc"] = default_crc
|
||||
cases.append(c)
|
||||
|
||||
def hand(name, w, h, ct, frames, plays=0, plte=None, trns=None, split=1):
|
||||
data = apng(w, h, ct, frames, plays=plays, plte=plte, trns=trns, rng=rng, split=split)
|
||||
mine = composite(w, h, ct, frames, plte, trns)
|
||||
ref = ffmpeg_frames(ctx, data, w, h)
|
||||
if ct in (0, 2): # ffmpeg decodes to an opaque pixel format: disposed pixels come out opaque black
|
||||
mine = [bytes(v if i % 4 != 3 else 255 for i, v in enumerate(m)) for m in mine]
|
||||
if ref != mine:
|
||||
for fi, (a, b) in enumerate(zip(ref, mine)):
|
||||
if a != b:
|
||||
k = next(j for j in range(len(a)) if a[j] != b[j])
|
||||
print("apng fixture mismatch:", name, fi, k // 4 % w, k // 4 // w, a[k - k % 4:k - k % 4 + 4], b[k - k % 4:k - k % 4 + 4], frames[fi]["dispose"], frames[fi]["blend"], frames[fi - 1]["dispose"] if fi else None, sum(1 for j in range(0, len(a), 4) if a[j:j + 4] != b[j:j + 4]))
|
||||
raise RuntimeError("apng fixture %s: ffmpeg and the reference compositor disagree (%d vs %d frames)" % (name, len(ref), len(mine)))
|
||||
add(name, data, w, h, frames, ref, plays=plays, opaque=ct in (0, 2))
|
||||
|
||||
# every dispose x blend on sub-rectangles over a semi-transparent background
|
||||
W, H = 20, 16
|
||||
fr = [frame(rng, 6, 0, 0, W, H, 0, 0)]
|
||||
for d in (0, 1, 2):
|
||||
for b in (0, 1):
|
||||
fr.append(frame(rng, 6, rng.randrange(8), rng.randrange(6), 1 + rng.randrange(12), 1 + rng.randrange(10), d, b, num=rng.randrange(1, 200), den=rng.choice((0, 100, 1000))))
|
||||
fr.append(frame(rng, 6, 3, 2, 9, 7, 2, 1))
|
||||
fr.append(frame(rng, 6, 0, 0, W, H, 0, 1))
|
||||
hand("rgba-dispose-blend", W, H, 6, fr, plays=3, split=2)
|
||||
# first frame dispose previous (= background), then over
|
||||
hand("first-previous", 12, 9, 6, [frame(rng, 6, 0, 0, 12, 9, 2, 1), frame(rng, 6, 2, 2, 5, 4, 0, 1), frame(rng, 6, 0, 0, 3, 3, 1, 0)])
|
||||
# palette + tRNS, over
|
||||
pal = [(rng.randrange(256), rng.randrange(256), rng.randrange(256)) for _ in range(40)]
|
||||
trns = [rng.choice((0, 128, 255, rng.randrange(256))) for _ in range(30)]
|
||||
hand("palette-trns", 17, 13, 3, [frame(rng, 3, 0, 0, 17, 13, 1, 0, ncolors=40)] + [frame(rng, 3, rng.randrange(5), rng.randrange(5), 1 + rng.randrange(12), 1 + rng.randrange(8), rng.randrange(3), rng.randrange(2), ncolors=40) for _ in range(5)], plte=pal, trns=trns)
|
||||
# grey and RGB (no alpha: over = source)
|
||||
hand("gray", 15, 11, 0, [frame(rng, 0, 0, 0, 15, 11, 0, 0)] + [frame(rng, 0, rng.randrange(5), rng.randrange(5), 1 + rng.randrange(10), 1 + rng.randrange(6), rng.randrange(3), rng.randrange(2)) for _ in range(4)], plays=1)
|
||||
hand("rgb", 15, 11, 2, [frame(rng, 2, 0, 0, 15, 11, 1, 0)] + [frame(rng, 2, rng.randrange(5), rng.randrange(5), 1 + rng.randrange(10), 1 + rng.randrange(6), rng.randrange(3), rng.randrange(2)) for _ in range(4)])
|
||||
# a single-frame APNG
|
||||
hand("one-frame", 7, 5, 6, [frame(rng, 6, 0, 0, 7, 5, 0, 0)])
|
||||
|
||||
# hidden default image (not part of the animation): ffmpeg's demuxer cannot express it, so the compositor here
|
||||
dpx = sprite(rng, 10, 8, 6)
|
||||
fr = [frame(rng, 6, 0, 0, 10, 8, 0, 0), frame(rng, 6, 2, 1, 4, 5, 1, 1), frame(rng, 6, 5, 3, 5, 5, 0, 1)]
|
||||
data = apng(10, 8, 6, fr, default=dpx, rng=rng)
|
||||
add("hidden-default", data, 10, 8, fr, composite(10, 8, 6, fr), default_crc=zlib.crc32(b"".join(bytes(p) for row in dpx for p in row)), ffmpeg=False)
|
||||
|
||||
# ffmpeg's own encoder (it picks sub-rectangles, dispose and blend ops)
|
||||
for name, src, pix, plays in (
|
||||
("ffmpeg-testsrc", "testsrc=size=40x30:rate=10", "rgb24", 0),
|
||||
("ffmpeg-rgba", "testsrc2=size=36x28:rate=8,format=rgba,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='if(lt(mod(X+T*40,20),10),255,90)'", "rgba", 2),
|
||||
):
|
||||
data = subprocess.run(["ffmpeg", "-v", "error", "-f", "lavfi", "-i", src, "-frames:v", "7", "-pix_fmt", pix, "-plays", str(plays), "-f", "apng", "-"],
|
||||
capture_output=True, check=True).stdout
|
||||
w, h = struct.unpack(">II", data[16:24])
|
||||
ref = ffmpeg_frames(ctx, data, w, h)
|
||||
cases.append({"name": name, "data": data, "width": w, "height": h, "plays": plays, "crcs": [zlib.crc32(r) for r in ref], "ffmpeg": True, "opaque": pix == "rgb24"})
|
||||
|
||||
ctx.emit("apng_cases", cases)
|
||||
@@ -0,0 +1,75 @@
|
||||
# MP3 fixtures (tools/fixtures.py). Ported from mp3-luau tools/make_fixtures.sh + make_refs.py.
|
||||
# tests/gen/mp3_cases.luau the committed streams in tests/fixtures/mp3/ (made by ffmpeg's libmp3lame / mp2 encoders
|
||||
# from a synthetic test signal: tones, a chirp, noise, clicks) with their minimp3 reference
|
||||
# decodes (*.ref, from the minimp3 C harness: see the format below), plus streams lame
|
||||
# encodes here; each with ffmpeg's decode of three windows and its length.
|
||||
# .ref layout (little-endian): "MP3REF1\0", u32 hz, channels, frames, window frames W, window count N, then
|
||||
# N x (u32 start frame, W x channels f32), then u32 block size B, u32 block count, f64 sum of squares per block.
|
||||
import math, os, random, struct, tempfile
|
||||
|
||||
INPUTS = ["tests/fixtures/mp3"]
|
||||
DIR = os.path.join("tests", "fixtures", "mp3")
|
||||
|
||||
|
||||
def ffmpeg_windows(ctx, data, ch, starts, W):
|
||||
with tempfile.TemporaryDirectory() as tmp: # a file, not a pipe: ffmpeg applies the LAME gapless info only when it can seek
|
||||
path = os.path.join(tmp, "in.mp3")
|
||||
with open(path, "wb") as f:
|
||||
f.write(data)
|
||||
out = ctx.nix("ffmpeg", ["ffmpeg", "-v", "error", "-i", path, "-f", "f32le", "-ac", str(ch), "pipe:1"])
|
||||
frames = len(out) // (4 * ch)
|
||||
wins = []
|
||||
for s in starts:
|
||||
s = max(0, min(frames - W, s))
|
||||
wins.append({"start": s, "pcm": out[s * ch * 4:(s + W) * ch * 4]})
|
||||
return frames, wins
|
||||
|
||||
|
||||
def ref_windows(ref):
|
||||
hz, ch, frames, W, N = struct.unpack_from("<5I", ref, 8)
|
||||
p, starts = 28, []
|
||||
for _ in range(N):
|
||||
starts.append(struct.unpack_from("<I", ref, p)[0])
|
||||
p += 4 + W * ch * 4
|
||||
return ch, W, starts
|
||||
|
||||
|
||||
def wav(rate, ch, secs, seed):
|
||||
rnd = random.Random(seed)
|
||||
fr = bytearray()
|
||||
for i in range(int(secs * rate)):
|
||||
t = i / rate
|
||||
for c in range(ch):
|
||||
v = 0.25 * math.sin(2 * math.pi * (330 * (c + 1) + 200 * t) * t) + 0.04 * (rnd.random() - 0.5)
|
||||
if (i // 2000) % 7 == 3:
|
||||
v += 0.3 * math.sin(2 * math.pi * 4000 * t) * (1 - (i % 2000) / 2000)
|
||||
fr += struct.pack("<h", int(max(-1, min(1, v)) * 32767))
|
||||
hdr = b"RIFF" + struct.pack("<I", 36 + len(fr)) + b"WAVEfmt " + struct.pack("<IHHIIHH", 16, 1, ch, rate, rate * ch * 2, ch * 2, 16)
|
||||
return hdr + b"data" + struct.pack("<I", len(fr)) + bytes(fr)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
cases = []
|
||||
for fn in sorted(os.listdir(os.path.join(ctx.root, DIR))):
|
||||
if not fn.endswith((".mp3", ".mp2")):
|
||||
continue
|
||||
name = fn[:-4]
|
||||
data = ctx.read(os.path.join(DIR, fn))
|
||||
ref = ctx.read(os.path.join(DIR, name + ".ref"))
|
||||
ch, W, starts = ref_windows(ref)
|
||||
frames, wins = ffmpeg_windows(ctx, data, ch, starts, W)
|
||||
cases.append({"name": name, "data": data, "ref": ref, "ffFrames": frames, "ff": wins})
|
||||
# streams the lame CLI writes here (no minimp3 reference: ffmpeg only)
|
||||
for name, rate, ch, args in (("lame_v5_st", 44100, 2, ["-V", "5"]), ("lame_cbr64_mono_22k", 22050, 1, ["-b", "64", "-m", "m"]),
|
||||
("lame_abr96_48k", 48000, 2, ["--abr", "96"])):
|
||||
src = wav(rate, ch, 1.2, len(name))
|
||||
with tempfile.TemporaryDirectory() as tmp: # a file: lame writes the LAME (gapless) tag only when it can seek
|
||||
path = os.path.join(tmp, "out.mp3")
|
||||
ctx.nix("lame", ["lame", "--quiet", "--resample", str(rate / 1000)] + args + ["-", path], input=src)
|
||||
with open(path, "rb") as f:
|
||||
data = f.read()
|
||||
W = 1152
|
||||
frames, wins = ffmpeg_windows(ctx, data, ch, [0, 20000, 10 ** 9], W)
|
||||
cases.append({"name": name, "data": data, "ffFrames": frames, "ff": wins, "channels": ch, "rate": rate,
|
||||
"srcFrames": int(1.2 * rate)})
|
||||
ctx.emit("mp3_cases", cases)
|
||||
@@ -0,0 +1,209 @@
|
||||
# Ogg fixtures (tools/fixtures.py): containers/Ogg. Ported from ogg-luau tools/gen_fixtures.py.
|
||||
# tests/gen/ogg_cases.luau real encoder files (opusenc, flac --ogg, ffmpeg vorbis) and hand-made multiplexed files
|
||||
# (lacing edge cases, junk, a corrupt page copy, a lost page), each with the packet list
|
||||
# from the small independent parser below: { size, crc32, granule, bos, eos }
|
||||
import math, os, random, struct, tempfile, wave, zlib
|
||||
|
||||
# --- CRC + writer -----------------------------------------------------------------------------------------
|
||||
def _crc_table():
|
||||
t = []
|
||||
for i in range(256):
|
||||
r = i << 24
|
||||
for _ in range(8):
|
||||
r = ((r << 1) ^ 0x04C11DB7) if r & 0x80000000 else (r << 1)
|
||||
r &= 0xFFFFFFFF
|
||||
t.append(r)
|
||||
return t
|
||||
|
||||
|
||||
CRC = _crc_table()
|
||||
|
||||
|
||||
def ogg_crc(data):
|
||||
c = 0
|
||||
for x in data:
|
||||
c = ((c << 8) & 0xFFFFFFFF) ^ CRC[(c >> 24) ^ x]
|
||||
return c
|
||||
|
||||
|
||||
def page(serial, seq, granule, flags, segs, data):
|
||||
h = struct.pack("<4sBBqIIIB", b"OggS", 0, flags, granule, serial, seq, 0, len(segs)) + bytes(segs)
|
||||
p = bytearray(h + data)
|
||||
struct.pack_into("<I", p, 22, ogg_crc(p))
|
||||
return bytes(p)
|
||||
|
||||
|
||||
def mux_stream(serial, packets, max_segs=255, granule_of=None):
|
||||
"""Pages for one stream; packets = list of (bytes, granule). Pages break after max_segs lacing values."""
|
||||
pages = []
|
||||
segs, data, seq, cont, gran = [], b"", 0, False, -1
|
||||
first = True
|
||||
|
||||
def flush(eos=False, next_cont=False):
|
||||
nonlocal segs, data, seq, cont, gran, first
|
||||
flags = (1 if cont else 0) | (2 if first else 0) | (4 if eos else 0)
|
||||
pages.append(page(serial, seq, gran, flags, segs, data))
|
||||
seq += 1
|
||||
first = False
|
||||
segs, data, gran = [], b"", -1
|
||||
cont = next_cont
|
||||
|
||||
for i, (pkt, g) in enumerate(packets):
|
||||
n = len(pkt)
|
||||
lac = [255] * (n // 255) + [n % 255]
|
||||
pos = 0
|
||||
for j, l in enumerate(lac):
|
||||
if len(segs) == max_segs:
|
||||
flush(next_cont=j > 0)
|
||||
segs.append(l)
|
||||
data += pkt[pos:pos + l]
|
||||
pos += l
|
||||
gran = g
|
||||
if i == 0 or (i % 7 == 3): # bos page holds only the first packet; break pages now and then
|
||||
flush()
|
||||
flush(eos=True)
|
||||
return pages
|
||||
|
||||
|
||||
# --- reference parser ---------------------------------------------------------------------------------------
|
||||
def parse(data):
|
||||
"""{serial: [ (bytes, granule, bos, eos) ]} with resync + CRC check, like the library."""
|
||||
out, partial, order, seqs = {}, {}, [], {}
|
||||
pos = 0
|
||||
while True:
|
||||
i = data.find(b"OggS", pos)
|
||||
if i < 0 or i + 27 > len(data):
|
||||
break
|
||||
nseg = data[i + 26]
|
||||
segs = data[i + 27:i + 27 + nseg]
|
||||
total = 27 + nseg + sum(segs)
|
||||
if len(segs) < nseg or i + total > len(data):
|
||||
pos = i + 1
|
||||
continue
|
||||
p = bytearray(data[i:i + total])
|
||||
crc = struct.unpack_from("<I", p, 22)[0]
|
||||
p[22:26] = b"\0\0\0\0"
|
||||
if ogg_crc(p) != crc:
|
||||
pos = i + 1
|
||||
continue
|
||||
flags, gran, serial = p[5], struct.unpack_from("<q", p, 6)[0], struct.unpack_from("<I", p, 14)[0]
|
||||
if serial not in out:
|
||||
out[serial] = []
|
||||
order.append(serial)
|
||||
partial[serial] = None
|
||||
seq = struct.unpack_from("<I", p, 18)[0]
|
||||
if serial in seqs and seq != seqs[serial] + 1:
|
||||
partial[serial] = None
|
||||
seqs[serial] = seq
|
||||
body = 27 + nseg
|
||||
last_complete = max([k for k, l in enumerate(segs) if l < 255], default=-1)
|
||||
cur = partial[serial] if (flags & 1) else None
|
||||
if not (flags & 1):
|
||||
cur = None
|
||||
skip = (flags & 1) and partial[serial] is None
|
||||
first_on_page = True
|
||||
for k, l in enumerate(segs):
|
||||
chunk = bytes(p[body:body + l])
|
||||
body += l
|
||||
if skip:
|
||||
if l < 255:
|
||||
skip = False
|
||||
first_on_page = False
|
||||
continue
|
||||
cur = (cur or b"") + chunk
|
||||
if l < 255:
|
||||
last = k == last_complete
|
||||
out[serial].append((cur, gran if last else -1, bool(flags & 2) and first_on_page,
|
||||
bool(flags & 4) and last))
|
||||
first_on_page = False
|
||||
cur = None
|
||||
partial[serial] = cur
|
||||
pos = i + total
|
||||
return order, out
|
||||
|
||||
|
||||
def codec(pkt):
|
||||
if pkt.startswith(b"OpusHead"):
|
||||
return "opus"
|
||||
if pkt[:5] == b"\x7fFLAC":
|
||||
return "flac"
|
||||
if pkt[:7] == b"\x01vorbis":
|
||||
return "vorbis"
|
||||
return "unknown"
|
||||
|
||||
|
||||
|
||||
def case(name, data, note):
|
||||
order, streams = parse(data)
|
||||
ss = []
|
||||
for s in order:
|
||||
pk = streams[s]
|
||||
gs = [g for _, g, _, _ in pk if g != -1]
|
||||
ss.append({"serial": s, "codec": codec(pk[0][0]), "lastGranule": gs[-1] if gs else -1,
|
||||
"packets": [[len(b), zlib.crc32(b), g, bos, eos] for b, g, bos, eos in pk]})
|
||||
return {"name": name, "note": note, "data": data, "streams": ss}
|
||||
|
||||
|
||||
def tone_wav(path, secs, rate=48000, ch=2):
|
||||
rnd = random.Random(1)
|
||||
with wave.open(path, "wb") as w:
|
||||
w.setnchannels(ch)
|
||||
w.setsampwidth(2)
|
||||
w.setframerate(rate)
|
||||
fr = bytearray()
|
||||
for i in range(int(secs * rate)):
|
||||
t = i / rate
|
||||
for c in range(ch):
|
||||
v = 0.3 * math.sin(2 * math.pi * (220 * (c + 1) + 40 * math.sin(t)) * t) + 0.05 * (rnd.random() - 0.5)
|
||||
fr += struct.pack("<h", int(v * 32767))
|
||||
w.writeframes(bytes(fr))
|
||||
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
tmp = tempfile.mkdtemp()
|
||||
cases = []
|
||||
wav = os.path.join(tmp, "a.wav")
|
||||
tone_wav(wav, 12)
|
||||
opus = os.path.join(tmp, "a.opus")
|
||||
ctx.nix("opus-tools", ["opusenc", "--quiet", "--bitrate", "48", wav, opus])
|
||||
cases.append(case("opus_stereo", open(opus, "rb").read(), "opusenc 48 kb/s, 12 s stereo"))
|
||||
wav2 = os.path.join(tmp, "b.wav")
|
||||
tone_wav(wav2, 1.5, 44100, 1)
|
||||
oflac = os.path.join(tmp, "b.oga")
|
||||
ctx.nix("flac", ["flac", "-s", "--ogg", "-5", "-o", oflac, wav2])
|
||||
cases.append(case("flac_ogg", open(oflac, "rb").read(), "flac --ogg -5, 1.5 s mono"))
|
||||
vorb = os.path.join(tmp, "c.ogg")
|
||||
ctx.nix("ffmpeg", ["ffmpeg", "-v", "error", "-y", "-i", wav2, "-ac", "2", "-c:a", "vorbis", "-strict", "-2", vorb])
|
||||
cases.append(case("vorbis_ffmpeg", open(vorb, "rb").read(), "ffmpeg native vorbis, 1.5 s stereo"))
|
||||
|
||||
# two interleaved streams, lacing edge cases, junk, a corrupt page, a dropped page
|
||||
rnd = random.Random(7)
|
||||
sizes = [0, 1, 254, 255, 256, 509, 510, 511, 765, 4000, 70000, 0, 0, 3, 65025, 255 * 255 + 1]
|
||||
a = [(b"OpusHead" + bytes(11), 0)] + [(bytes(rnd.randrange(256) for _ in range(n)), 100 * (i + 1))
|
||||
for i, n in enumerate(sizes)]
|
||||
b = [(b"\x7fFLAC" + bytes(40), 0)] + [(bytes(rnd.randrange(256) for _ in range(rnd.randrange(1, 900))), 50 * (i + 1))
|
||||
for i in range(60)]
|
||||
pa = mux_stream(0x1234ABCD, a, max_segs=255)
|
||||
pb = mux_stream(7, b, max_segs=17)
|
||||
out = pa[:1] + pb[:1] # bos pages first
|
||||
ra, rb = pa[1:], pb[1:]
|
||||
while ra or rb:
|
||||
if rb and (not ra or rnd.random() < 0.5):
|
||||
out.append(rb.pop(0))
|
||||
else:
|
||||
out.append(ra.pop(0))
|
||||
blob = bytearray()
|
||||
for k, pg in enumerate(out):
|
||||
if k == 5:
|
||||
blob += b"junkOggSjunk" + bytes(40)
|
||||
if k == 9: # a corrupt copy before the real page
|
||||
bad = bytearray(pg)
|
||||
bad[len(bad) // 2] ^= 0xFF
|
||||
blob += bad
|
||||
blob += pg
|
||||
blob += b"OggS\0trailing-truncated"
|
||||
cases.append(case("mux_edge", bytes(blob), "2 streams, lacing edges, junk, a corrupt page copy, truncated tail"))
|
||||
lost = [pg for pg in out if not (struct.unpack_from("<I", pg, 14)[0] == 7 and struct.unpack_from("<I", pg, 18)[0] == 5)]
|
||||
cases.append(case("mux_lost", b"".join(lost), "mux_edge without page 5 of serial 7"))
|
||||
ctx.emit("ogg_cases", cases)
|
||||
@@ -0,0 +1,66 @@
|
||||
# Opus fixtures (tools/fixtures.py): audio/opus. Ported from opus-luau tools/fixtures.sh.
|
||||
# tests/gen/opus_<name>.luau { name, data = the .opus file, ref = opusdec --float output (f32 LE interleaved) }
|
||||
# Sources: 48 kHz signals synthesised by ffmpeg (aevalsrc: tones, vibrato, chirps, noise bursts, clicks, a speech-like
|
||||
# harmonic source with moving formants), encoded by opusenc (CELT-only frame sizes / bitrates, forced SILK NB / MB /
|
||||
# WB, hybrid SWB / FB, a 5.1 mapping-family-1 stream, a long tagged file) and ffmpeg libopus (CBR, voip, lowdelay).
|
||||
import os, tempfile
|
||||
|
||||
MUSIC = ("0.25*sin(2*PI*(220+30*sin(2*PI*5*t))*t)+0.15*sin(2*PI*(100*t+700*t*t))+0.3*exp(-25*mod(t,0.375))*(random(0)-0.5)"
|
||||
"+0.4*lt(mod(t,0.5),0.0006)")
|
||||
MUSIC2 = ("0.2*sin(2*PI*330*t)+0.1*sin(2*PI*1320*t)*lt(mod(t,0.25),0.125)+0.25*exp(-40*mod(t+0.1,0.375))*(random(1)-0.5)"
|
||||
"+0.12*sin(2*PI*(3000-2500*t/3)*t)")
|
||||
F0 = "(120+40*sin(2*PI*0.7*t))"
|
||||
FM = "(600+300*sin(2*PI*1.3*t))"
|
||||
SPEECH = ("(0.5+0.5*sin(2*PI*2.1*t))*(sin(2*PI*{f0}*t)*0.3+sin(2*PI*2*{f0}*t)*0.25+sin(2*PI*3*{f0}*t)*0.2*exp(-abs(3*{f0}-{fm})/400)"
|
||||
"+sin(2*PI*5*{f0}*t)*0.15*exp(-abs(5*{f0}-{fm}*2)/400)+sin(2*PI*8*{f0}*t)*0.08+0.02*(random(2)-0.5))").format(f0=F0, fm=FM)
|
||||
SOURCES = {
|
||||
"music": (MUSIC + "|" + MUSIC2, 3),
|
||||
"mono": (MUSIC + "+0.5*" + SPEECH, 3),
|
||||
"speech": (SPEECH, 3),
|
||||
"speechst": (SPEECH + "|0.7*" + SPEECH + "+0.1*sin(2*PI*440*t)", 3),
|
||||
"mixst": (MUSIC + "+" + SPEECH + "|" + MUSIC2 + "+0.6*" + SPEECH, 3),
|
||||
"surround": (MUSIC + "|" + MUSIC2 + "|" + SPEECH + "|0.3*sin(2*PI*55*t)|0.5*" + MUSIC2 + "|0.5*" + MUSIC, 2),
|
||||
"long": (MUSIC + "+0.3*" + SPEECH + "|" + MUSIC2 + "+0.3*" + SPEECH, 12),
|
||||
}
|
||||
# name, source, encoder ("enc" = opusenc, "ff" = ffmpeg libopus), arguments
|
||||
CASES = [
|
||||
("celt_st_128", "music", "enc", ["--music", "--bitrate", "128"]),
|
||||
("celt_st_32", "music", "enc", ["--music", "--bitrate", "32"]),
|
||||
("celt_st_64", "mixst", "enc", ["--music", "--bitrate", "64"]),
|
||||
("celt_st_256", "music", "enc", ["--music", "--bitrate", "256"]),
|
||||
("celt_mono_64", "mono", "enc", ["--music", "--bitrate", "64"]),
|
||||
("celt_fs2_5", "music", "enc", ["--music", "--bitrate", "96", "--framesize", "2.5"]),
|
||||
("celt_fs5", "music", "enc", ["--music", "--bitrate", "96", "--framesize", "5"]),
|
||||
("celt_fs10", "mixst", "enc", ["--music", "--bitrate", "96", "--framesize", "10"]),
|
||||
("celt_fs40", "music", "enc", ["--music", "--bitrate", "96", "--framesize", "40"]),
|
||||
("celt_fs60", "mixst", "enc", ["--music", "--bitrate", "160", "--framesize", "60"]),
|
||||
("silk_nb", "speech", "enc", ["--speech", "--bitrate", "8", "--max-delay", "0"]),
|
||||
("silk_mb", "speech", "enc", ["--speech", "--bitrate", "12", "--set-ctl-int", "4008=1102"]),
|
||||
("silk_wb", "speech", "enc", ["--speech", "--bitrate", "20", "--framesize", "40", "--set-ctl-int", "4008=1103"]),
|
||||
("silk_wb_st", "speechst", "enc", ["--speech", "--bitrate", "28", "--framesize", "60", "--set-ctl-int", "4008=1103"]),
|
||||
("silk_nb_st", "speechst", "enc", ["--speech", "--bitrate", "12", "--framesize", "10", "--set-ctl-int", "4008=1101"]),
|
||||
("hybrid_swb", "speech", "enc", ["--speech", "--bitrate", "24"]),
|
||||
("hybrid_fb", "speech", "enc", ["--speech", "--bitrate", "36", "--framesize", "10"]),
|
||||
("hybrid_st", "speechst", "enc", ["--speech", "--bitrate", "40"]),
|
||||
("mix_st_24", "mixst", "enc", ["--bitrate", "24"]),
|
||||
("surround51", "surround", "enc", ["--bitrate", "192"]),
|
||||
("long_128", "long", "enc", ["--bitrate", "128", "--comment", "TITLE=Long Test", "--artist", "opus-luau"]),
|
||||
("ff_cbr", "mixst", "ff", ["-b:a", "96k", "-vbr", "off"]),
|
||||
("ff_voip", "speechst", "ff", ["-b:a", "32k", "-application", "voip"]),
|
||||
("ff_lowdelay", "music", "ff", ["-b:a", "128k", "-application", "lowdelay", "-frame_duration", "5"]),
|
||||
]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
tmp = tempfile.mkdtemp()
|
||||
for name, (expr, secs) in SOURCES.items():
|
||||
ctx.nix("ffmpeg", ["ffmpeg", "-loglevel", "error", "-y", "-f", "lavfi", "-i", "aevalsrc='%s':s=48000:d=%d" % (expr, secs),
|
||||
"-c:a", "pcm_s16le", os.path.join(tmp, name + ".wav")])
|
||||
for name, src, enc, args in CASES:
|
||||
wav, opus, ref = (os.path.join(tmp, x) for x in (src + ".wav", name + ".opus", name + ".f32"))
|
||||
if enc == "enc":
|
||||
ctx.nix("opus-tools", ["opusenc", "--quiet"] + args + [wav, opus])
|
||||
else:
|
||||
ctx.nix("ffmpeg", ["ffmpeg", "-loglevel", "error", "-y", "-i", wav, "-c:a", "libopus"] + args + [opus])
|
||||
ctx.nix("opus-tools", ["opusdec", "--quiet", "--float", opus, ref])
|
||||
ctx.emit("opus_" + name, {"name": name, "data": open(opus, "rb").read(), "ref": open(ref, "rb").read()})
|
||||
@@ -0,0 +1,199 @@
|
||||
# WAV fixtures (tools/fixtures.py): audio/wav. Ported from wav-luau tools/mkfixtures.py.
|
||||
# tests/gen/wav_cases.luau a short synthetic stereo signal in every supported format and container (ffmpeg / sox),
|
||||
# plus hand-patched variants (data size 0 / 0xFFFFFFFF, truncation, odd chunks with and
|
||||
# without the pad byte, tags after the data), with ffmpeg's (or sox's) f32le decode
|
||||
# tests/gen/wav_enc.luau encoder references: random samples at each depth, written by ffmpeg with -bitexact
|
||||
# (PCM u8 / s16 / s24 / s32 / f32, 1-8 channels, > 48 kHz, RF64); our encoder must
|
||||
# produce the same bytes
|
||||
import os, random, struct, tempfile
|
||||
|
||||
CTX = None
|
||||
|
||||
|
||||
def build_cases():
|
||||
work = tempfile.mkdtemp()
|
||||
RATE, DUR = 16000, 0.2
|
||||
SRC = "aevalsrc=0.6*sin(2*PI*440*t)+0.25*sin(2*PI*3100*t*t*10)|0.5*sin(2*PI*660*t)+0.2*(random(1)*2-1):s=%d:d=%g" % (RATE, DUR)
|
||||
|
||||
def run(*args):
|
||||
CTX.nix(["ffmpeg", "sox"], list(args))
|
||||
|
||||
def path(n):
|
||||
return os.path.join(work, n)
|
||||
|
||||
def ffenc(name, *args, ac=2):
|
||||
run("ffmpeg", "-v", "error", "-y", "-f", "lavfi", "-i", SRC, "-ac", str(ac), *args, path(name))
|
||||
return path(name)
|
||||
|
||||
def ref(p):
|
||||
return CTX.nix("ffmpeg", ["ffmpeg", "-v", "error", "-i", p, "-f", "f32le", "-c:a", "pcm_f32le", "-"])
|
||||
|
||||
def soxref(p):
|
||||
# ffmpeg cannot read every RIFX file: sox decodes those (through its 32-bit integer pipeline)
|
||||
return CTX.nix("sox", ["sox", p, "-t", "raw", "-e", "floating-point", "-b", "32", "-L", "-"])
|
||||
|
||||
def chunks(d):
|
||||
be = d[:4] == b"RIFX"
|
||||
p, out = 12, []
|
||||
while p + 8 <= len(d):
|
||||
cid = d[p:p + 4]
|
||||
size = struct.unpack_from(">I" if be else "<I", d, p + 4)[0]
|
||||
out.append((cid, p, size))
|
||||
if size == 0xFFFFFFFF:
|
||||
break
|
||||
p += 8 + size + (size & 1)
|
||||
return out
|
||||
|
||||
def find(d, cid):
|
||||
for c, p, s in chunks(d):
|
||||
if c == cid:
|
||||
return p, s
|
||||
raise KeyError(cid)
|
||||
|
||||
entries = []
|
||||
|
||||
def add(name, data, refdata, channels, fmt, container="RIFF", tags=None):
|
||||
frames = len(refdata) // (4 * channels)
|
||||
# ADPCM: ffmpeg decodes the padding of the last block too; the fact chunk holds the true length
|
||||
if b"fact" in data[:200]:
|
||||
fp, _ = find(data, b"fact")
|
||||
frames = min(frames, struct.unpack_from("<I", data, fp + 8)[0])
|
||||
entries.append(dict(name=name, file=data, ref=refdata, channels=channels, rate=RATE, frames=frames,
|
||||
format=fmt, container=container, tags=tags))
|
||||
|
||||
def plain(name, fmt, *args, ac=2, tags=None):
|
||||
p = ffenc(name + ".wav", *args, ac=ac)
|
||||
d = open(p, "rb").read()
|
||||
add(name, d, ref(p), ac, fmt, tags=tags)
|
||||
return p, d
|
||||
|
||||
# formats
|
||||
plain("u8", "pcm", "-c:a", "pcm_u8")
|
||||
p16, d16 = plain("s16", "pcm", "-c:a", "pcm_s16le")
|
||||
plain("s16_mono_tags", "pcm", "-c:a", "pcm_s16le", "-metadata", "title=Hello Title", "-metadata", "artist=Some Artist",
|
||||
"-metadata", "album=An Album", "-metadata", "genre=Test", ac=1,
|
||||
tags={"title": "Hello Title", "artist": "Some Artist", "album": "An Album", "genre": "Test"})
|
||||
plain("s24_ext", "pcm", "-c:a", "pcm_s24le")
|
||||
plain("s32_ext", "pcm", "-c:a", "pcm_s32le")
|
||||
plain("f32", "float", "-c:a", "pcm_f32le")
|
||||
plain("f64", "float", "-c:a", "pcm_f64le")
|
||||
plain("alaw", "alaw", "-c:a", "pcm_alaw")
|
||||
plain("mulaw_mono", "mulaw", "-c:a", "pcm_mulaw", ac=1)
|
||||
plain("ima", "ima_adpcm", "-c:a", "adpcm_ima_wav")
|
||||
plain("ima_mono", "ima_adpcm", "-c:a", "adpcm_ima_wav", ac=1)
|
||||
plain("ms", "ms_adpcm", "-c:a", "adpcm_ms")
|
||||
plain("ms_mono", "ms_adpcm", "-c:a", "adpcm_ms", ac=1)
|
||||
plain("s16_6ch_ext", "pcm", "-c:a", "pcm_s16le", ac=6)
|
||||
|
||||
# containers
|
||||
p = ffenc("rf64.wav", "-c:a", "pcm_s16le", "-rf64", "always")
|
||||
add("rf64", open(p, "rb").read(), ref(p), 2, "pcm", container="RF64")
|
||||
for name, args in (("rifx_s16", ["-b", "16"]), ("rifx_s24", ["-b", "24"]), ("rifx_f32", ["-e", "floating-point", "-b", "32"])):
|
||||
p = path(name + ".wav")
|
||||
run("sox", path("s24_ext.wav"), "-B", *args, p)
|
||||
add(name, open(p, "rb").read(), soxref(p), 2, "float" if "f32" in name else "pcm", container="RIFX")
|
||||
|
||||
# streamed output: data size 0xFFFFFFFF
|
||||
p = path("pipe.wav")
|
||||
with open(p, "wb") as f:
|
||||
f.write(CTX.nix("ffmpeg", ["ffmpeg", "-v", "error", "-f", "lavfi", "-i", SRC, "-c:a", "pcm_s16le", "-f", "wav", "pipe:1"]))
|
||||
d = open(p, "rb").read()
|
||||
assert find(d, b"data")[1] == 0xFFFFFFFF
|
||||
add("streamed_ffffffff", d, ref(p16), 2, "pcm")
|
||||
|
||||
# data size 0
|
||||
r16 = ref(p16)
|
||||
dp, _ = find(d16, b"data")
|
||||
d = bytearray(d16)
|
||||
struct.pack_into("<I", d, dp + 4, 0)
|
||||
add("datasize_0", bytes(d), r16, 2, "pcm")
|
||||
|
||||
# truncated mid-frame: 1000 whole frames + 3 bytes
|
||||
add("truncated_s16", d16[:dp + 8 + 1000 * 4 + 3], r16[:1000 * 2 * 4], 2, "pcm")
|
||||
|
||||
# truncated IMA ADPCM: one whole block, then a partial block with its headers + 3 whole groups + 5 bytes
|
||||
pima = path("ima.wav")
|
||||
dima = open(pima, "rb").read()
|
||||
fp, _ = find(dima, b"fmt ")
|
||||
ba = struct.unpack_from("<H", dima, fp + 8 + 12)[0]
|
||||
spb = (ba - 8) * 2 // 2 + 1
|
||||
dp, _ = find(dima, b"data")
|
||||
cut = dp + 8 + ba + 8 + 3 * 8 + 5
|
||||
frames = spb + 1 + 3 * 8
|
||||
rima = ref(pima)
|
||||
assert len(rima) >= frames * 8
|
||||
add("truncated_ima", dima[:cut], rima[:frames * 2 * 4], 2, "ima_adpcm")
|
||||
|
||||
# odd-sized chunks before the data, padded and unpadded
|
||||
fp, fs = find(d16, b"fmt ")
|
||||
head, rest = d16[:fp + 8 + fs], d16[fp + 8 + fs:]
|
||||
def riff(body):
|
||||
return b"RIFF" + struct.pack("<I", len(body) + 4) + b"WAVE" + body
|
||||
odd_padded = riff(head[12:] + b"junk" + struct.pack("<I", 3) + b"abc\0" + rest)
|
||||
add("odd_chunk_padded", odd_padded, r16, 2, "pcm")
|
||||
odd_unpadded = riff(head[12:] + b"abcd" + struct.pack("<I", 5) + b"12345" + rest)
|
||||
add("odd_chunk_unpadded", odd_unpadded, r16, 2, "pcm")
|
||||
|
||||
# 8-bit mono, odd frame count (odd data size, pad byte), LIST/INFO after the data
|
||||
p = path("u8odd.wav")
|
||||
run("ffmpeg", "-v", "error", "-y", "-f", "lavfi", "-i", SRC, "-ac", "1", "-af", "atrim=end_sample=3199",
|
||||
"-c:a", "pcm_u8", "-map_metadata", "-1", "-fflags", "+bitexact", p)
|
||||
d = open(p, "rb").read()
|
||||
dp, ds = find(d, b"data")
|
||||
assert ds % 2 == 1, ds
|
||||
info = b"INFO" + b"INAM" + struct.pack("<I", 5) + b"Odd!\0\0" + b"IART" + struct.pack("<I", 4) + b"Me\0\0"
|
||||
body = d[12:dp + 8 + ds] + b"\0" + b"LIST" + struct.pack("<I", len(info)) + info
|
||||
add("u8_odd_list_after", riff(body), ref(p), 1, "pcm", tags={"title": "Odd!", "artist": "Me"})
|
||||
|
||||
|
||||
return entries
|
||||
|
||||
|
||||
def raw_samples(rng, kind, n):
|
||||
"""n random samples as (raw little-endian bytes, the same values as f32 little-endian)"""
|
||||
raw, f32 = bytearray(), bytearray()
|
||||
for i in range(n):
|
||||
if kind == "u8":
|
||||
v = rng.randrange(256); raw.append(v); x = (v - 128) / 128
|
||||
elif kind == "s16":
|
||||
v = rng.randrange(-32768, 32768); raw += struct.pack("<h", v); x = v / 32768
|
||||
elif kind == "s24":
|
||||
v = rng.randrange(-8388608, 8388608); raw += struct.pack("<i", v)[:3]; x = v / 8388608
|
||||
elif kind == "s32":
|
||||
v = rng.randrange(-8388608, 8388608) * 256; raw += struct.pack("<i", v); x = v / 2147483648
|
||||
else:
|
||||
x = struct.unpack("<f", struct.pack("<f", rng.uniform(-1, 1)))[0]; raw += struct.pack("<f", x)
|
||||
f32 += struct.pack("<f", x)
|
||||
if kind in ("s16", "s24", "s32", "u8"):
|
||||
# the extremes too
|
||||
pass
|
||||
return bytes(raw), bytes(f32)
|
||||
|
||||
|
||||
FF = {"u8": ("u8", "pcm_u8"), "s16": ("s16le", "pcm_s16le"), "s24": ("s24le", "pcm_s24le"), "s32": ("s32le", "pcm_s32le"),
|
||||
"f32": ("f32le", "pcm_f32le")}
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
global CTX
|
||||
CTX = ctx
|
||||
ctx.emit("wav_cases", [{k: v for k, v in e.items() if v is not None} for e in build_cases()])
|
||||
rng = random.Random(3)
|
||||
tmp = tempfile.mkdtemp()
|
||||
enc = []
|
||||
for kind, ch, rate, frames, extra in (("s16", 2, 44100, 1001, []), ("s24", 2, 44100, 777, []), ("s32", 2, 44100, 500, []),
|
||||
("f32", 2, 44100, 640, []), ("u8", 1, 8000, 999, []), ("s16", 6, 48000, 300, []),
|
||||
("f32", 6, 8000, 120, []), ("s16", 1, 96000, 256, []), ("s16", 3, 8000, 50, []),
|
||||
("s16", 4, 8000, 50, []), ("s16", 5, 8000, 50, []), ("s16", 7, 8000, 50, []),
|
||||
("s16", 8, 8000, 50, []), ("s24", 1, 22050, 333, []),
|
||||
("s16", 2, 44100, 441, ["-rf64", "always"]), ("f32", 1, 44100, 100, ["-rf64", "always"])):
|
||||
raw, f32 = raw_samples(rng, kind, frames * ch)
|
||||
src = os.path.join(tmp, "in.raw")
|
||||
open(src, "wb").write(raw)
|
||||
out = os.path.join(tmp, "out.wav")
|
||||
fmt, codec = FF[kind]
|
||||
ctx.nix("ffmpeg", ["ffmpeg", "-v", "error", "-y", "-f", fmt, "-ar", str(rate), "-ac", str(ch), "-i", src,
|
||||
"-c:a", codec] + extra + ["-fflags", "+bitexact", "-flags:a", "+bitexact", "-map_metadata", "-1", out])
|
||||
enc.append({"name": "%s-%dch-%d%s" % (kind, ch, rate, "-rf64" if extra else ""), "kind": kind, "channels": ch,
|
||||
"rate": rate, "frames": frames, "rf64": bool(extra), "samples": f32, "file": open(out, "rb").read()})
|
||||
ctx.emit("wav_enc", enc)
|
||||
Reference in new issue
Block a user