merge ws/m4a
This commit is contained in:
commit
e1ffb21494
42 files changed
+10353
-8
No files matched your search
@@ -535,3 +535,67 @@ do
|
||||
Webp.encode(img, { effort = 1 })
|
||||
end)
|
||||
end
|
||||
do
|
||||
local Xml = require("@formats/codecs/Xml")
|
||||
local XB = require("@tests/gen/xml_bench")
|
||||
local doc = assert(Xml.decode(XB.text))
|
||||
bench("xml decode (DOM)", 5, #XB.text, function()
|
||||
Xml.decode(XB.text)
|
||||
end)
|
||||
bench("xml events", 5, #XB.text, function()
|
||||
for _ in Xml.events(XB.text) do
|
||||
end
|
||||
end)
|
||||
bench("xml encode", 5, #XB.text, function()
|
||||
Xml.encode(doc)
|
||||
end)
|
||||
end
|
||||
|
||||
-- ws-m4a: AAC-LC / ALAC decode and ALAC encode (MB/s of 16-bit PCM equivalent: frames * channels * 2), MDCT
|
||||
do
|
||||
local M4a = require("@formats/audio/m4a")
|
||||
local Alac = require("@formats/codecs/Alac")
|
||||
local Mdct = require("@formats/codecs/Mdct")
|
||||
local MA = require("@tests/gen/m4a_aac")
|
||||
local ML = require("@tests/gen/m4a_alac")
|
||||
local aac = buffer.fromstring(MA[1].data)
|
||||
local a = assert(M4a.decode(Bytes.reader(aac)))
|
||||
bench("aac-lc decode (m4a, stereo)", 3, a.frames * a.channels * 2, function()
|
||||
M4a.decode(Bytes.reader(aac))
|
||||
end)
|
||||
local alac = buffer.fromstring(ML[1].data)
|
||||
local l = assert(M4a.decode(Bytes.reader(alac)))
|
||||
bench("alac decode (m4a, stereo 16)", 3, l.frames * l.channels * 2, function()
|
||||
M4a.decode(Bytes.reader(alac))
|
||||
end)
|
||||
local enc = assert(Alac.encoder({ sampleRate = 44100, channels = 2, bitDepth = 16 }))
|
||||
local ints = table.create(a.frames * 2, 0)
|
||||
for i = 1, a.frames * 2 do
|
||||
ints[i] = math.floor(buffer.readf32(a.samples, (i - 1) * 4) * 32767)
|
||||
end
|
||||
bench("alac encode (stereo 16)", 2, a.frames * 2 * 2, function()
|
||||
local f = 0
|
||||
while f < a.frames do
|
||||
local n = math.min(4096, a.frames - f)
|
||||
enc:encode(ints, f * 2 + 1, n)
|
||||
f += n
|
||||
end
|
||||
end)
|
||||
local plan = assert(Mdct.new(2048))
|
||||
local x, X = table.create(2048, 0.5), table.create(1024, 0)
|
||||
bench("mdct 2048 x 1000 (forward)", 3, 1000 * 2048 * 4, function()
|
||||
for _ = 1, 1000 do
|
||||
Mdct.forward(plan, x, 1, X, 1)
|
||||
end
|
||||
end)
|
||||
end
|
||||
do
|
||||
local Opus = require("@formats/audio/opus")
|
||||
local Cases = require("@tests/audio/_opus_cases")
|
||||
local c = Cases.list[2]
|
||||
local a = Cases.signal(c)
|
||||
local dt = bench("opus celt encode 128k (1.5 s st)", 2, a.frames * a.channels * 2, function()
|
||||
Opus.encode(a, { bitrate = 128000 })
|
||||
end)
|
||||
local _ = dt
|
||||
end
|
||||
@@ -0,0 +1,31 @@
|
||||
-- tools/fixtures/_m4a_encode: run by tools/fixtures/m4a.py (luau, from the repo root) so the reference tools can check
|
||||
-- our writers: encodes the test signal (tests/audio/_signal) to ALAC M4A (audio/m4a) and ALAC / PCM CAF (audio/caf)
|
||||
-- and prints "<name> <hex>" lines. The tests re-encode and compare the CRC with the file ffmpeg validated.
|
||||
local Signal = require("@tests/audio/_signal")
|
||||
local M4a = require("@formats/audio/m4a")
|
||||
local Caf = require("@formats/audio/caf")
|
||||
|
||||
local function hex(b: buffer): string
|
||||
local t = table.create(buffer.len(b))
|
||||
for i = 0, buffer.len(b) - 1 do
|
||||
t[i + 1] = string.format("%02x", buffer.readu8(b, i))
|
||||
end
|
||||
return table.concat(t)
|
||||
end
|
||||
|
||||
local Cases = require("@tests/audio/_encode_cases")
|
||||
for _, c in Cases do
|
||||
local a = Signal.audio(c.rate, c.frames, c.channels, c.bits, c.seed)
|
||||
a.tags = c.tags or {}
|
||||
local out, err
|
||||
if c.container == "caf" then
|
||||
out, err = Caf.encode(a, { codec = c.codec, bitDepth = c.bits })
|
||||
else
|
||||
out, err = M4a.encode(a, { bitDepth = c.bits })
|
||||
end
|
||||
if not out then
|
||||
print(c.name .. " ERROR " .. tostring(err))
|
||||
else
|
||||
print(c.name .. " " .. hex(out))
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,41 @@
|
||||
# The deterministic integer test signal shared by tools/fixtures/m4a.py, tools/fixtures/caf.py and the Luau side
|
||||
# (tests/audio/_signal.luau computes the same numbers): triangle + square + MINSTD noise (exact in doubles) + clicks, per channel.
|
||||
import struct
|
||||
|
||||
|
||||
def signal(frames, channels, bits, seed):
|
||||
s = seed
|
||||
peak = 2 ** (bits - 1) - 1
|
||||
out = []
|
||||
for i in range(frames):
|
||||
for c in range(channels):
|
||||
s = (s * 48271) % 2147483647
|
||||
p1 = 97 + 31 * c
|
||||
tri = abs((i % p1) * 2 - p1) * 2 - p1
|
||||
v = tri * (peak // (4 * p1))
|
||||
p2 = 1500 + 200 * c
|
||||
v += (peak // 6) if (i // p2) % 2 == 0 else -(peak // 6)
|
||||
v += ((s // 65536) % 4096 - 2048) * (peak // 65536 + 1)
|
||||
if i % 7001 < 3:
|
||||
v += peak // 2
|
||||
out.append(max(-peak - 1, min(peak, v)))
|
||||
return out
|
||||
|
||||
|
||||
def pack(samples, bits, big=False):
|
||||
e = ">" if big else "<"
|
||||
if bits == 16:
|
||||
return struct.pack(e + "%dh" % len(samples), *samples)
|
||||
if bits == 24:
|
||||
b = bytearray()
|
||||
for v in samples:
|
||||
x = struct.pack("<i", v)[:3]
|
||||
b += x[::-1] if big else x
|
||||
return bytes(b)
|
||||
return struct.pack(e + "%di" % len(samples), *samples)
|
||||
|
||||
|
||||
def wav(samples, channels, rate, bits):
|
||||
data = pack(samples, bits)
|
||||
fmt = struct.pack("<HHIIHH", 1, channels, rate, rate * channels * bits // 8, channels * bits // 8, bits)
|
||||
return b"RIFF" + struct.pack("<I", 36 + len(data)) + b"WAVEfmt " + struct.pack("<I", 16) + fmt + b"data" + struct.pack("<I", len(data)) + data
|
||||
@@ -0,0 +1,17 @@
|
||||
-- tools/fixtures/_opus_encode: run by tools/fixtures/opus_celt.py (luau, from the repo root): encodes
|
||||
-- tests/audio/_opus_cases with audio/opus's CELT encoder and prints "<name> <hex>" lines for opusdec / ffmpeg.
|
||||
local Opus = require("@formats/audio/opus")
|
||||
local Cases = require("@tests/audio/_opus_cases")
|
||||
|
||||
for _, c in Cases.list do
|
||||
local out, err = Opus.encode(Cases.signal(c), { bitrate = c.bitrate })
|
||||
if not out then
|
||||
print(c.name .. " ERROR " .. tostring(err))
|
||||
else
|
||||
local t = table.create(buffer.len(out))
|
||||
for i = 0, buffer.len(out) - 1 do
|
||||
t[i + 1] = string.format("%02x", buffer.readu8(out, i))
|
||||
end
|
||||
print(c.name .. " " .. table.concat(t))
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,89 @@
|
||||
# containers/IsoBmff fixtures (tools/fixtures.py): small files from ffmpeg / MP4Box / avifenc (nix) with ffprobe's
|
||||
# packet lists as the reference.
|
||||
# tests/gen/isobmff.luau { cases = { { name, data, streams = { { codec, kind, timescale, width?, height?,
|
||||
# sampleRate?, channels?, extradata }, ... }, packets = { { stream, pos, size, dts, pts, key },
|
||||
# ... } } }, tagged = { data, tags, cover }, avif = { { name, data, width, height, alpha } } }
|
||||
import json, os, shutil, subprocess, tempfile
|
||||
|
||||
PKGS = ["ffmpeg", "gpac", "libavif"]
|
||||
|
||||
|
||||
def sh(ctx, script, cwd):
|
||||
return ctx.nix(PKGS, ["sh", "-c", "cd '%s' && %s" % (cwd, script)])
|
||||
|
||||
|
||||
def probe(ctx, path, cwd):
|
||||
out = sh(ctx, "ffprobe -v error -ignore_editlist 1 -show_streams -show_packets -of json '%s'" % path, cwd)
|
||||
j = json.loads(out)
|
||||
streams = []
|
||||
for s in j["streams"]:
|
||||
kind = s["codec_type"]
|
||||
if kind == "video" and s.get("disposition", {}).get("attached_pic"):
|
||||
continue
|
||||
tb = s["time_base"].split("/")
|
||||
e = {"codec": s["codec_name"], "kind": kind, "timescale": int(tb[1]), "index": s["index"],
|
||||
"extradata": int(s.get("extradata_size", 0))}
|
||||
if kind == "video":
|
||||
e["width"], e["height"] = s["width"], s["height"]
|
||||
if kind == "audio":
|
||||
e["sampleRate"], e["channels"] = int(s["sample_rate"]), s["channels"]
|
||||
streams.append(e)
|
||||
index = {s["index"]: i + 1 for i, s in enumerate(streams)}
|
||||
packets = []
|
||||
for p in j["packets"]:
|
||||
if p["stream_index"] not in index:
|
||||
continue
|
||||
packets.append({"stream": index[p["stream_index"]], "pos": int(p["pos"]), "size": int(p["size"]),
|
||||
"dts": int(p["dts"]), "pts": int(p["pts"]), "key": "K" in p["flags"]})
|
||||
for s in streams:
|
||||
del s["index"]
|
||||
return streams, packets
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
d = tempfile.mkdtemp(prefix="isobmff-fx-")
|
||||
try:
|
||||
src_v = "-f lavfi -i testsrc=size=64x48:rate=10 -t 1.2"
|
||||
src_a = "-f lavfi -i sine=frequency=440:sample_rate=44100 -t 1.0"
|
||||
steps = [
|
||||
("h264_aac.mp4", "ffmpeg -v error %s %s -c:v libx264 -bf 2 -g 5 -pix_fmt yuv420p -c:a aac -b:a 64k -ac 2 h264_aac.mp4" % (src_v, src_a)),
|
||||
("faststart.mp4", "ffmpeg -v error -i h264_aac.mp4 -c copy -movflags +faststart faststart.mp4"),
|
||||
("mjpeg_pcm.mov", "ffmpeg -v error %s %s -c:v mjpeg -c:a pcm_s16be mjpeg_pcm.mov" % (src_v, src_a)),
|
||||
("hevc.mp4", "ffmpeg -v error %s -c:v libx265 -x265-params log-level=none -tag:v hvc1 hevc.mp4" % src_v),
|
||||
("frag.mp4", "ffmpeg -v error -i h264_aac.mp4 -c copy -movflags frag_keyframe+empty_moov+default_base_moof frag.mp4"),
|
||||
("mp4box_frag.mp4", "MP4Box -quiet -frag 300 -out mp4box_frag.mp4 h264_aac.mp4 >/dev/null 2>&1"),
|
||||
("stz2_co64.mp4", "MP4Box -quiet -add h264_aac.mp4#video -add h264_aac.mp4#audio:stz2 -co64 -new stz2_co64.mp4 >/dev/null 2>&1"),
|
||||
("alac.m4a", "ffmpeg -v error %s -c:a alac alac.m4a" % src_a),
|
||||
]
|
||||
cases = []
|
||||
for name, cmd in steps:
|
||||
sh(ctx, cmd, d)
|
||||
streams, packets = probe(ctx, name, d)
|
||||
with open(os.path.join(d, name), "rb") as f:
|
||||
data = f.read()
|
||||
cases.append({"name": name, "data": data, "streams": streams, "packets": packets})
|
||||
# tags + cover
|
||||
sh(ctx, "ffmpeg -v error -f lavfi -i color=red:size=8x8 -frames:v 1 -update 1 cover.png", d)
|
||||
tags = {"title": "Test Title", "artist": "Some Artist", "album": "An Album", "date": "2024",
|
||||
"genre": "Electronic", "comment": "a comment", "composer": "Composer X", "album_artist": "AA"}
|
||||
meta = " ".join("-metadata %s='%s'" % (k, v) for k, v in tags.items())
|
||||
sh(ctx, "ffmpeg -v error %s -i cover.png -map 0 -map 1 -c:a aac -b:a 48k -c:v png -disposition:v attached_pic -t 1 %s -metadata track=3/12 -metadata disc=1/2 tagged.m4a" % (src_a, meta), d)
|
||||
with open(os.path.join(d, "tagged.m4a"), "rb") as f:
|
||||
tagged = f.read()
|
||||
with open(os.path.join(d, "cover.png"), "rb") as f:
|
||||
cover = f.read()
|
||||
want = {"title": "Test Title", "artist": "Some Artist", "album": "An Album", "date": "2024",
|
||||
"genre": "Electronic", "comment": "a comment", "composer": "Composer X", "albumartist": "AA",
|
||||
"track": "3", "tracktotal": "12", "disc": "1", "disctotal": "2"}
|
||||
# AVIF stills (libavif): plain and with alpha
|
||||
avif = []
|
||||
sh(ctx, "ffmpeg -v error -f lavfi -i testsrc=size=40x24 -frames:v 1 still.png && "
|
||||
"ffmpeg -v error -f lavfi -i 'testsrc=size=40x24,format=rgba,geq=r=r(X\\,Y):a=X*6' -frames:v 1 alpha.png", d)
|
||||
for name, png, alpha in (("still.avif", "still.png", False), ("alpha.avif", "alpha.png", True)):
|
||||
sh(ctx, "avifenc -q 60 -s 10 %s %s >/dev/null" % (png, name), d)
|
||||
with open(os.path.join(d, name), "rb") as f:
|
||||
avif.append({"name": name, "data": f.read(), "width": 40, "height": 24, "alpha": alpha})
|
||||
ctx.emit("isobmff", {"cases": cases, "tagged": {"data": tagged, "tags": want, "cover": len(cover)},
|
||||
"avif": avif})
|
||||
finally:
|
||||
shutil.rmtree(d, ignore_errors=True)
|
||||
@@ -0,0 +1,198 @@
|
||||
# M4A / AAC / ALAC / CAF fixtures (tools/fixtures.py). Reference tools through nix: ffmpeg (AAC + ALAC encoders and
|
||||
# decoders, the CAF muxer), fdkaac (Fraunhofer's encoder: plain and HE-AAC), MP4Box (-info on our files).
|
||||
# tests/gen/m4a_alac.luau ALAC in M4A / CAF from ffmpeg: { name, data, container, channels, rate, bits, frames,
|
||||
# crc } where crc is the CRC-32 of the source integers as little-endian int32
|
||||
# tests/gen/m4a_aac.luau AAC from ffmpeg / faac (M4A, ADTS, CAF): { name, data, container, channels, rate, frames,
|
||||
# ref } with ref = ffmpeg's float decode (f32le) of the file
|
||||
# tests/gen/m4a_he.luau HE-AAC / HE-AACv2 from fdkaac: { name, data, rate (the SBR output rate), ps }
|
||||
# tests/gen/m4a_ours.luau our writers' files (tools/fixtures/_m4a_encode.luau over tests/audio/_encode_cases.luau)
|
||||
# checked by ffmpeg: { name, crc (of our bytes), ffmpeg (decodes bit-exactly), frames,
|
||||
# tags (ffprobe's view), mp4box (MP4Box -info exit status 0) }
|
||||
import importlib.util, json, math, os, shutil, struct, subprocess, tempfile, zlib
|
||||
|
||||
# the shared signal module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml)
|
||||
_spec = importlib.util.spec_from_file_location("_m4a_signal", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_m4a_signal.py"))
|
||||
_sig = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(_sig)
|
||||
signal, pack, wav = _sig.signal, _sig.pack, _sig.wav
|
||||
|
||||
INPUTS = ["src/Formats/audio/m4a", "src/Formats/audio/caf", "src/Formats/codecs/Alac", "src/Formats/containers/IsoBmff",
|
||||
"tests/audio/_signal.luau", "tests/audio/_encode_cases.luau", "tools/fixtures/_m4a_encode.luau",
|
||||
"tools/fixtures/_m4a_signal.py"]
|
||||
PKGS = ["ffmpeg", "fdk-aac-encoder", "gpac"]
|
||||
|
||||
|
||||
def run(ctx, cmd, cwd):
|
||||
return ctx.nix(PKGS, ["sh", "-c", "cd '%s' && %s" % (cwd, cmd)])
|
||||
|
||||
|
||||
def crc_ints(ints):
|
||||
return zlib.crc32(struct.pack("<%di" % len(ints), *ints))
|
||||
|
||||
|
||||
def music(frames, channels, rate, seed):
|
||||
"""a float test signal for the lossy codecs: tones with vibrato, a chord, noise bursts and clicks (transients)"""
|
||||
rng = __import__("random").Random(seed)
|
||||
out = []
|
||||
for i in range(frames):
|
||||
t = i / rate
|
||||
for c in range(channels):
|
||||
v = 0.25 * math.sin(2 * math.pi * (220 * (c + 1)) * t + 3 * math.sin(2 * math.pi * 5 * t))
|
||||
v += 0.12 * math.sin(2 * math.pi * 660 * t) + 0.08 * math.sin(2 * math.pi * 1320.5 * t + c)
|
||||
v += 0.05 * math.sin(2 * math.pi * (5000 + 300 * c) * t)
|
||||
if (i // (rate // 8)) % 3 == 1:
|
||||
v += 0.15 * (rng.random() * 2 - 1)
|
||||
if i % (rate // 3) < 40:
|
||||
v += 0.6 * (1 - (i % (rate // 3)) / 40) * (1 if (i // 7) % 2 else -1)
|
||||
out.append(max(-32768, min(32767, int(round(v * 20000)))))
|
||||
return out
|
||||
|
||||
|
||||
def adts_to_caf(adts):
|
||||
frames, p = [], 0
|
||||
while p + 7 <= len(adts):
|
||||
b1, b2, b3, b4, b5 = adts[p + 1], adts[p + 2], adts[p + 3], adts[p + 4], adts[p + 5]
|
||||
hs = 7 if b1 & 1 else 9
|
||||
size = ((b3 & 3) << 11) | (b4 << 3) | (b5 >> 5)
|
||||
frames.append(adts[p + hs:p + size])
|
||||
sfi, ch, aot = (b2 >> 2) & 15, ((b2 & 1) << 2) | (b3 >> 6), (b2 >> 6) + 1
|
||||
p += size
|
||||
rate = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350][sfi]
|
||||
asc = struct.pack(">H", (aot << 11) | (sfi << 7) | (ch << 3))
|
||||
dsi = b"\x05" + bytes([len(asc)]) + asc
|
||||
dcd = b"\x04" + bytes([13 + len(dsi)]) + bytes([0x40, 0x15, 0, 0, 0]) + struct.pack(">II", 0, 0) + dsi
|
||||
esd = b"\x03" + bytes([3 + len(dcd) + 3]) + b"\x00\x00\x00" + dcd + b"\x06\x01\x02"
|
||||
|
||||
def ber(n):
|
||||
out = [n & 127]
|
||||
n >>= 7
|
||||
while n:
|
||||
out.insert(0, 128 | (n & 127))
|
||||
n >>= 7
|
||||
return bytes(out)
|
||||
|
||||
def chunk(t, body):
|
||||
return t + struct.pack(">q", len(body)) + body
|
||||
|
||||
desc = struct.pack(">d4sIIIII", rate, b"aac ", 2, 0, 1024, ch, 0)
|
||||
pakt = struct.pack(">qqii", len(frames), len(frames) * 1024, 0, 0) + b"".join(ber(len(f)) for f in frames)
|
||||
data = b"\x00\x00\x00\x00" + b"".join(frames)
|
||||
return b"caff\x00\x01\x00\x00" + chunk(b"desc", desc) + chunk(b"kuki", b"\x00\x00\x00\x00" + esd) + chunk(b"pakt", pakt) + chunk(b"data", data)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
d = tempfile.mkdtemp(prefix="m4a-fx-")
|
||||
try:
|
||||
# --- ALAC from ffmpeg: lossless, the decode must equal the source integers
|
||||
alac = []
|
||||
for name, frames, ch, rate, bits, container in (
|
||||
("alac16_stereo.m4a", 10000, 2, 44100, 16, "m4a"),
|
||||
("alac16_mono.m4a", 4097, 1, 8000, 16, "m4a"),
|
||||
("alac24_stereo.m4a", 6000, 2, 96000, 24, "m4a"),
|
||||
("alac16_6ch.m4a", 5000, 6, 48000, 16, "m4a"),
|
||||
("alac16_stereo.caf", 9000, 2, 44100, 16, "caf"),
|
||||
):
|
||||
ints = signal(frames, ch, bits, 11 + frames)
|
||||
with open(os.path.join(d, "in.wav"), "wb") as f:
|
||||
f.write(wav(ints, ch, rate, bits))
|
||||
fmt = "-sample_fmt s32p" if bits == 24 else ""
|
||||
run(ctx, "ffmpeg -v error -y -i in.wav -c:a alac %s %s" % (fmt, name), d)
|
||||
with open(os.path.join(d, name), "rb") as f:
|
||||
data = f.read()
|
||||
alac.append({"name": name, "data": data, "container": container, "channels": ch, "rate": rate,
|
||||
"bits": bits, "frames": frames, "crc": crc_ints(ints)})
|
||||
ctx.emit("m4a_alac", alac)
|
||||
|
||||
# --- AAC from ffmpeg / faac: our decode against ffmpeg's float decode
|
||||
aac = []
|
||||
specs = (
|
||||
# name, frames, channels, rate, encoder command (in.wav -> name)
|
||||
("aac_stereo_128k.m4a", 60000, 2, 44100, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 128k -aac_pns 0 %s"),
|
||||
("aac_mono_22k.m4a", 30000, 1, 22050, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 48k %s"),
|
||||
("aac_51_48k.m4a", 30000, 6, 48000, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 256k %s"),
|
||||
("aac_tools_40k.m4a", 50000, 2, 44100, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 40k -aac_pns 1 -aac_is 1 -aac_ms 1 -aac_tns 1 %s"),
|
||||
("aac_8k_mono.m4a", 12000, 1, 8000, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 16k %s"),
|
||||
("aac_96k.m4a", 30000, 2, 96000, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 192k %s"),
|
||||
("aac_stereo.aac", 40000, 2, 44100, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 96k -aac_pns 0 -f adts %s"),
|
||||
("fdk_stereo.aac", 40000, 2, 44100, "fdkaac -S -b 96000 -f 2 -o %s in.wav"),
|
||||
("fdk_mono_32k.aac", 20000, 1, 32000, "fdkaac -S -b 48000 -f 2 -o %s in.wav"),
|
||||
("fdk_stereo.m4a", 40000, 2, 48000, "fdkaac -S -b 128000 -o %s in.wav"),
|
||||
("aac_stereo.caf", 30000, 2, 44100, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 96k -f adts %s.adts"),
|
||||
)
|
||||
for name, frames, ch, rate, cmd in specs:
|
||||
ints = music(frames, ch, rate, frames + ch)
|
||||
with open(os.path.join(d, "in.wav"), "wb") as f:
|
||||
f.write(wav(ints, ch, rate, 16))
|
||||
run(ctx, cmd % name, d)
|
||||
if name.endswith(".caf"):
|
||||
# ffmpeg cannot write AAC in CAF: wrap its ADTS frames ourselves (desc, kuki esds, pakt, data)
|
||||
with open(os.path.join(d, name + ".adts"), "rb") as f:
|
||||
adts = f.read()
|
||||
with open(os.path.join(d, name), "wb") as f:
|
||||
f.write(adts_to_caf(adts))
|
||||
with open(os.path.join(d, name), "rb") as f:
|
||||
data = f.read()
|
||||
ref = run(ctx, "ffmpeg -v error -i %s -f f32le -c:a pcm_f32le -" % name, d)
|
||||
container = "caf" if name.endswith(".caf") else ("adts" if name.endswith(".aac") else "m4a")
|
||||
aac.append({"name": name, "data": data, "container": container, "channels": ch, "rate": rate,
|
||||
"frames": len(ref) // (4 * ch), "ref": ref})
|
||||
ctx.emit("m4a_aac", aac)
|
||||
# HE-AAC (SBR) and HE-AACv2 (SBR + PS) from fdkaac: we decode the AAC-LC core at the core rate
|
||||
he = []
|
||||
for name, frames, ch, rate, prof, br in (("he_aac.m4a", 48000, 2, 44100, 5, 48000), ("he_aac_v2.m4a", 48000, 2, 44100, 29, 32000), ("he_aac.aac", 48000, 2, 44100, 5, 48000)):
|
||||
ints = music(frames, ch, rate, 99)
|
||||
with open(os.path.join(d, "in.wav"), "wb") as f:
|
||||
f.write(wav(ints, ch, rate, 16))
|
||||
run(ctx, "fdkaac -S -p %d -b %d %s -o %s in.wav" % (prof, br, "-f 2" if name.endswith(".aac") else "", name), d)
|
||||
with open(os.path.join(d, name), "rb") as f:
|
||||
he.append({"name": name, "data": f.read(), "rate": rate, "ps": prof == 29})
|
||||
ctx.emit("m4a_he", he)
|
||||
|
||||
# --- our writers, checked by ffmpeg / ffprobe / MP4Box
|
||||
luau = os.environ.get("LUAU") or shutil.which("luau")
|
||||
if luau:
|
||||
out = subprocess.run([luau, "tools/fixtures/_m4a_encode.luau"], capture_output=True, check=True, cwd=ctx.root).stdout
|
||||
else:
|
||||
out = ctx.nix("luau", ["luau", os.path.join(ctx.root, "tools/fixtures/_m4a_encode.luau")])
|
||||
ours = []
|
||||
meta = {
|
||||
# name -> frames, channels, bits, seed (tests/audio/_encode_cases.luau)
|
||||
"ours_alac16_stereo": (4096 * 3 + 1234, 2, 16, 1), "ours_alac16_mono": (5000, 1, 16, 2),
|
||||
"ours_alac24_stereo": (9000, 2, 24, 3), "ours_alac16_6ch": (4500, 6, 16, 4),
|
||||
"ours_alac20_stereo": (3000, 2, 20, 5), "ours_caf_alac16": (7000, 2, 16, 6),
|
||||
"ours_caf_pcm16": (3000, 2, 16, 7), "ours_caf_pcm24": (2000, 1, 24, 8),
|
||||
}
|
||||
for line in out.decode().split("\n"):
|
||||
if not line.strip():
|
||||
continue
|
||||
name, hx = line.split(" ", 1)
|
||||
if hx.startswith("ERROR"):
|
||||
raise RuntimeError("m4a fixtures: our encoder failed on %s: %s" % (name, hx))
|
||||
data = bytes.fromhex(hx)
|
||||
ext = "caf" if "caf" in name else "m4a"
|
||||
path = name + "." + ext
|
||||
with open(os.path.join(d, path), "wb") as f:
|
||||
f.write(data)
|
||||
frames, ch, bits, seed = meta[name]
|
||||
ints = signal(frames, ch, bits, seed)
|
||||
wide = bits > 16
|
||||
want = pack([v << (32 - bits) for v in ints] if wide else ints, 32 if wide else 16)
|
||||
got = run(ctx, "ffmpeg -v error -i %s -f %s -" % (path, "s32le" if wide else "s16le"), d)
|
||||
fbytes = (4 if wide else 2) * ch
|
||||
# ffmpeg's CAF reader drops the pakt remainder from a partial last ALAC packet (also on its own files):
|
||||
# accept its output when it is an exact prefix of ours
|
||||
ok = got == want or (ext == "caf" and len(got) > 0 and want.startswith(got))
|
||||
probe = json.loads(run(ctx, "ffprobe -v error -show_format -show_streams -of json %s" % path, d))
|
||||
tags = {k.lower(): v for k, v in probe["format"].get("tags", {}).items()}
|
||||
mp4box = True
|
||||
if ext == "m4a":
|
||||
try:
|
||||
run(ctx, "MP4Box -info %s >/dev/null 2>&1" % path, d)
|
||||
except subprocess.CalledProcessError:
|
||||
mp4box = False
|
||||
ours.append({"name": name, "crc": zlib.crc32(data), "ffmpeg": ok, "frames": len(got) // fbytes,
|
||||
"tags": tags, "mp4box": mp4box,
|
||||
"codec": probe["streams"][0]["codec_name"]})
|
||||
ctx.emit("m4a_ours", ours)
|
||||
finally:
|
||||
shutil.rmtree(d, ignore_errors=True)
|
||||
@@ -0,0 +1,48 @@
|
||||
# The CELT encoder reference check (tools/fixtures.py): runs tools/fixtures/_opus_encode.luau (our encoder over
|
||||
# tests/audio/_opus_cases.luau), then the reference tools through nix: opusdec --float (libopus), opusinfo (stream
|
||||
# structure), ffmpeg (an independent Ogg / Opus reader).
|
||||
# tests/gen/opus_celt.luau { { name, crc (of our bytes), opusdec (f32le 48 kHz decode), opusinfo (exit 0),
|
||||
# ffmpeg (decoded), ffmpegFrames, comments (opusinfo's user comments) } }
|
||||
import os, re, shutil, subprocess, tempfile, zlib
|
||||
|
||||
INPUTS = ["src/Formats/audio/opus", "src/Formats/codecs/Mdct", "src/Formats/containers/Ogg",
|
||||
"tests/audio/_opus_cases.luau", "tools/fixtures/_opus_encode.luau"]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
luau = os.environ.get("LUAU") or shutil.which("luau")
|
||||
script = os.path.join(ctx.root, "tools/fixtures/_opus_encode.luau")
|
||||
if luau:
|
||||
out = subprocess.run([luau, script], capture_output=True, check=True, cwd=ctx.root).stdout
|
||||
else:
|
||||
out = ctx.nix("luau", ["luau", script])
|
||||
d = tempfile.mkdtemp(prefix="opus-celt-fx-")
|
||||
try:
|
||||
cases = []
|
||||
for line in out.decode().split("\n"):
|
||||
if not line.strip():
|
||||
continue
|
||||
name, hx = line.split(" ", 1)
|
||||
if hx.startswith("ERROR"):
|
||||
raise RuntimeError("opus_celt fixtures: our encoder failed on %s: %s" % (name, hx))
|
||||
data = bytes.fromhex(hx)
|
||||
path = os.path.join(d, name + ".opus")
|
||||
with open(path, "wb") as f:
|
||||
f.write(data)
|
||||
raw = os.path.join(d, name + ".f32")
|
||||
ctx.nix("opus-tools", ["opusdec", "--quiet", "--float", "--rate", "48000", path, raw])
|
||||
with open(raw, "rb") as f:
|
||||
pcm = f.read()
|
||||
info = subprocess.run(["nix", "shell", "nixpkgs#opus-tools", "-c", "opusinfo", path], capture_output=True)
|
||||
text = info.stdout.decode(errors="replace")
|
||||
comments = {}
|
||||
for m in re.finditer(r"^\s*([A-Za-z]+)=(.*)$", text, re.M):
|
||||
comments[m.group(1).lower()] = m.group(2)
|
||||
ok = info.returncode == 0 and "WARNING" not in text and "ERROR" not in text.upper().replace("ERRORS", "")
|
||||
ff = subprocess.run(["nix", "shell", "nixpkgs#ffmpeg", "-c", "ffmpeg", "-v", "error", "-i", path, "-f", "f32le", "-ac", "1", "-"], capture_output=True)
|
||||
cases.append({"name": name, "crc": zlib.crc32(data), "opusdec": pcm, "opusinfo": ok,
|
||||
"ffmpeg": ff.returncode == 0 and len(ff.stderr) == 0, "ffmpegFrames": len(ff.stdout) // 4,
|
||||
"comments": comments})
|
||||
ctx.emit("opus_celt", cases)
|
||||
finally:
|
||||
shutil.rmtree(d, ignore_errors=True)
|
||||
Reference in new issue
Block a user