ws-audio2: merge ws/audio2-lossy (Musepack SV7/SV8, AC-3, AudioWrap AC-3 hook)
This commit is contained in:
commit
39da2f6648
25 files changed
+4196
-4
No files matched your search
@@ -1099,3 +1099,31 @@ do
|
||||
end
|
||||
end
|
||||
end
|
||||
-- ws-audio2: lossy
|
||||
do
|
||||
-- Musepack (codecs/audio/Musepack) SV8 / SV7 and AC-3 5.1 (codecs/audio/Ac3): whole-file decodes, MB/s of f32 output
|
||||
-- (tools/fixtures/mpc.py: 1.2 s of 44.1 kHz stereo at quality 5; tools/fixtures/ac3.py: 0.16 s of 48 kHz 5.1 at
|
||||
-- 448 kbps, decoded 4 times per run)
|
||||
local Mpc = require("@formats/audio/mpc")
|
||||
local MpcFx = require("@tests/gen/mpc_cases")
|
||||
local Ac3F = require("@formats/audio/ac3")
|
||||
local Ac3Fx = require("@tests/gen/ac3_cases")
|
||||
for _, c in MpcFx do
|
||||
if c.name == "sv8_q5_stereo" or c.name == "sv7_q5_stereo" then
|
||||
local b = buffer.fromstring(c.data)
|
||||
bench("mpc " .. c.name, 5, c.frames * c.channels * 4, function()
|
||||
assert(Mpc.decode(Bytes.reader(b)))
|
||||
end)
|
||||
end
|
||||
end
|
||||
for _, c in Ac3Fx do
|
||||
if c.name == "5.1_448" then
|
||||
local b = buffer.fromstring(c.data)
|
||||
bench("ac3 5.1 448 kbps", 5, c.frames * c.channels * 4 * 4, function()
|
||||
for _ = 1, 4 do
|
||||
assert(Ac3F.decode(Bytes.reader(b)))
|
||||
end
|
||||
end)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,229 @@
|
||||
# AC-3 fixtures (tools/fixtures.py). Encoders: ffmpeg (every channel layout, coupling, rematrixing, 32 / 44.1 /
|
||||
# 48 kHz) and aften (block switching, dual mono 1+1, dynamic range profiles, the alternate bit stream syntax).
|
||||
# References: ffmpeg's float decode with -drc_scale 0 (dynamic range off, our default), except for block-switched
|
||||
# streams: ffmpeg (as packaged) mis-decodes the first of the two short transforms, so those use liba52's a52dec
|
||||
# (-r -a: no dynamic range, no level adjustment; float for stereo, 16-bit wav6 for more channels), which agrees with
|
||||
# the A/52 transform equations. AC-3 tracks in Matroska / MP4 / MPEG-TS / AVI (remuxed by ffmpeg) for the api's audio hook.
|
||||
#
|
||||
# Both encoders set dithflag, and decoders draw their own random dither for the zero-bit mantissas, so two correct
|
||||
# decoders differ by about the coding noise. The reference streams therefore have their dithflags cleared (the bit
|
||||
# positions come from our decoder's dec.blocks, the CRCs are recomputed): the reference and we decode the same
|
||||
# numbers. `dithered` keeps the encoder's original stream for a few cases.
|
||||
# tests/gen/ac3_cases.luau { name, data, channels, rate, frames, ref (f32le, WAVE order), refTool, refDrc?,
|
||||
# dithered? }
|
||||
# tests/gen/ac3_tracks.luau { name, data (the container), channels, rate, ref (ffmpeg's decode of the AC-3) }
|
||||
import importlib.util, math, os, random, shutil, struct, tempfile
|
||||
|
||||
_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 = ["tools/fixtures/_audio.py", "src/Formats/codecs/audio/Ac3"]
|
||||
SECONDS = 0.15
|
||||
DITHERED = ("stereo_44k", "aften_5.1_blksw")
|
||||
NFCHANS = [2, 1, 2, 3, 3, 4, 4, 5]
|
||||
|
||||
|
||||
def _lit(b):
|
||||
return '"' + "".join("\\x%02x" % x for x in b) + '"'
|
||||
|
||||
|
||||
def crc16(data, crc=0):
|
||||
"""A/52 section 7.10.1: x^16 + x^15 + x^2 + 1, MSB first, zero start"""
|
||||
for b in data:
|
||||
crc ^= b << 8
|
||||
for _ in range(8):
|
||||
crc = ((crc << 1) ^ 0x8005) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
|
||||
return crc
|
||||
|
||||
|
||||
def fix_crcs(f):
|
||||
"""recompute crc1 (the CRC of the first 5/8 of the frame after the sync word is 0) and crc2 (all of it)"""
|
||||
words = len(f) // 2
|
||||
n58 = ((words >> 1) + (words >> 3)) * 2
|
||||
# crc1 is the first word of the span: solve the linear map W -> crc(W || 0...) for crc(W || rest) == 0
|
||||
rest = crc16(bytes(2) + bytes(f[4:n58]))
|
||||
basis = [crc16(bytes([(1 << i) >> 8, (1 << i) & 255]) + bytes(n58 - 4)) for i in range(16)]
|
||||
rows = [(basis[i], 1 << i) for i in range(16)]
|
||||
pivots = {}
|
||||
for v, m in rows:
|
||||
for bit in range(15, -1, -1):
|
||||
if not v >> bit & 1:
|
||||
continue
|
||||
if bit in pivots:
|
||||
pv, pm = pivots[bit]
|
||||
v, m = v ^ pv, m ^ pm
|
||||
else:
|
||||
pivots[bit] = (v, m)
|
||||
break
|
||||
w, target = 0, rest
|
||||
for bit in range(15, -1, -1):
|
||||
if target >> bit & 1:
|
||||
pv, pm = pivots[bit]
|
||||
target ^= pv
|
||||
w ^= pm
|
||||
f[2], f[3] = w >> 8, w & 255
|
||||
assert crc16(bytes(f[2:n58])) == 0
|
||||
c2 = crc16(bytes(f[2:-2]))
|
||||
f[-2], f[-1] = c2 >> 8, c2 & 255
|
||||
assert crc16(bytes(f[2:])) == 0
|
||||
|
||||
|
||||
def undither(ctx, data):
|
||||
"""clear every dithflag (after the blksw flags at each audio block's start) and fix the CRCs"""
|
||||
code = """
|
||||
local Ac3 = require("@formats/codecs/audio/Ac3")
|
||||
local b = buffer.fromstring(%s)
|
||||
local dec = Ac3.decoder()
|
||||
local o, n = 0, buffer.len(b)
|
||||
while o + 8 <= n do
|
||||
local h = Ac3.header(b, o, n)
|
||||
if not h then break end
|
||||
assert(dec:decode(b, o, h.frameSize))
|
||||
print(o, h.frameSize, h.acmod, table.concat(dec.blocks, " "))
|
||||
o += h.frameSize
|
||||
end
|
||||
""" % _lit(data)
|
||||
out = bytearray(data)
|
||||
for line in A.luau(ctx, code).decode().strip().split("\n"):
|
||||
v = [int(x) for x in line.split()]
|
||||
o, size, acmod, blocks = v[0], v[1], v[2], v[3:]
|
||||
nf = NFCHANS[acmod]
|
||||
f = out[o:o + size]
|
||||
for p in blocks:
|
||||
for k in range(nf):
|
||||
bit = p + nf + k
|
||||
f[bit >> 3] &= ~(0x80 >> (bit & 7)) & 255
|
||||
fix_crcs(f)
|
||||
out[o:o + size] = f
|
||||
return bytes(out)
|
||||
|
||||
|
||||
# name, encoder, layout (ffmpeg) or (acmod, lfe) (aften), rate, kbps, extra options
|
||||
CASES = [
|
||||
("mono_48k", "ffmpeg", "mono", 48000, 96, []),
|
||||
("stereo_44k", "ffmpeg", "stereo", 44100, 192, []),
|
||||
("stereo_cpl_48k", "ffmpeg", "stereo", 48000, 96, ["-channel_coupling", "1", "-cpl_start_band", "1"]),
|
||||
("stereo_cpl0_48k", "ffmpeg", "stereo", 48000, 64, ["-channel_coupling", "1", "-cpl_start_band", "0"]),
|
||||
("stereo_32k", "ffmpeg", "stereo", 32000, 64, []),
|
||||
("3.0_48k", "ffmpeg", "3.0", 48000, 256, []),
|
||||
("2.1_48k", "ffmpeg", "2.1", 48000, 192, []),
|
||||
("3.0back_48k", "ffmpeg", "3.0(back)", 48000, 192, []),
|
||||
("4.0_48k", "ffmpeg", "4.0", 48000, 256, []),
|
||||
("4.1_44k", "ffmpeg", "4.1", 44100, 320, []),
|
||||
("quad_side_48k", "ffmpeg", "quad(side)", 48000, 256, []),
|
||||
("5.0_side_32k", "ffmpeg", "5.0(side)", 32000, 320, []),
|
||||
("5.1_448", "ffmpeg", "5.1(side)", 48000, 448, []),
|
||||
("5.1_cpl_256", "ffmpeg", "5.1(side)", 48000, 256, ["-channel_coupling", "1"]),
|
||||
("aften_blksw_stereo", "aften", (2, 0), 48000, 192, ["-s", "1"]),
|
||||
("aften_dualmono", "aften", (0, 0), 48000, 128, []),
|
||||
("aften_5.1_blksw", "aften", (7, 1), 48000, 384, ["-s", "1"]),
|
||||
("aften_5.1_drc", "aften", (7, 1), 48000, 384, ["-dynrng", "1"]),
|
||||
("aften_xbsi_2.2", "aften", (6, 0), 44100, 256, ["-xbsi1", "1", "-xbsi2", "1", "-s", "1"]),
|
||||
]
|
||||
CHANNELS = {"mono": 1, "stereo": 2, "3.0": 3, "2.1": 3, "3.0(back)": 3, "4.0": 4, "4.1": 5, "quad(side)": 4,
|
||||
"5.0(side)": 5, "5.1(side)": 6}
|
||||
ACMOD_CH = {0: 2, 1: 1, 2: 2, 3: 3, 4: 3, 5: 4, 6: 4, 7: 5}
|
||||
|
||||
|
||||
def signal(frames, ch, rate, seed):
|
||||
"""per-channel tones with vibrato, noise bursts and clicks (transients for block switching)"""
|
||||
rng = random.Random(seed)
|
||||
out = [0.0] * (frames * ch)
|
||||
for c in range(ch):
|
||||
f = 110.0 * (c + 2) * (1.0 + 0.07 * c)
|
||||
for i in range(frames):
|
||||
t = i / rate
|
||||
v = 0.2 * math.sin(2 * math.pi * f * t + 2 * math.sin(2 * math.pi * 4 * t))
|
||||
v += 0.06 * math.sin(2 * math.pi * (2500 + 700 * c) * t)
|
||||
if (i // (rate // 10) + c) % 4 == 1:
|
||||
v += 0.12 * (rng.random() * 2 - 1)
|
||||
k = i % (rate // 7)
|
||||
if k < 60:
|
||||
v += 0.5 * (1 - k / 60) * (1 if (i // 5) % 2 else -1)
|
||||
out[i * ch + c] = v
|
||||
return out
|
||||
|
||||
|
||||
def raw(samples):
|
||||
return struct.pack("<%df" % len(samples), *samples)
|
||||
|
||||
|
||||
def a52dec(run, d, name, ch):
|
||||
"""liba52's decode: float (planar per 256-sample block) for stereo, 16-bit wav6 otherwise -> f32le, WAVE order"""
|
||||
flags = "-a -r"
|
||||
if ch == 2:
|
||||
raw_ = run("a52dec -o float %s %s 2>/dev/null" % (flags, name))
|
||||
v = struct.unpack("<%df" % (len(raw_) // 4), raw_)
|
||||
out = [0.0] * len(v)
|
||||
for b in range(len(v) // 512):
|
||||
for i in range(256):
|
||||
out[(b * 256 + i) * 2] = v[b * 512 + i]
|
||||
out[(b * 256 + i) * 2 + 1] = v[b * 512 + 256 + i]
|
||||
return raw(out)
|
||||
wav = run("a52dec -o wav6 %s %s 2>/dev/null" % (flags, name))
|
||||
p = wav.index(b"data") + 8
|
||||
pcm = struct.unpack("<%dh" % ((len(wav) - p) // 2), wav[p:p + (len(wav) - p) // 2 * 2])
|
||||
return raw([x / 32768 for x in pcm])
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
d = tempfile.mkdtemp(prefix="fmt-ac3-")
|
||||
cases, tracks = [], []
|
||||
try:
|
||||
def run(cmd):
|
||||
return ctx.nix(["ffmpeg", "aften", "a52dec"], ["sh", "-c", "cd '%s' && %s" % (d, cmd)])
|
||||
|
||||
for name, enc, layout, rate, kbps, extra in CASES:
|
||||
ch = CHANNELS[layout] if enc == "ffmpeg" else ACMOD_CH[layout[0]] + layout[1]
|
||||
frames = int(rate * SECONDS)
|
||||
sig = signal(frames, ch, rate, len(name))
|
||||
with open(os.path.join(d, name + ".raw"), "wb") as f:
|
||||
f.write(raw(sig))
|
||||
out = name + ".ac3"
|
||||
if enc == "ffmpeg":
|
||||
run("ffmpeg -v error -y -f f32le -ar %d -ch_layout '%s' -i %s.raw -c:a ac3 -b:a %dk %s %s"
|
||||
% (rate, layout, name, kbps, " ".join(extra), out))
|
||||
else:
|
||||
with open(os.path.join(d, name + ".wav"), "wb") as f:
|
||||
f.write(A.wav(sig, rate, ch))
|
||||
run("aften -v 0 -threads 1 -b %d -acmod %d -lfe %d %s %s.wav %s" % (kbps, layout[0], layout[1], " ".join(extra), name, out))
|
||||
with open(os.path.join(d, out), "rb") as f:
|
||||
orig = f.read()
|
||||
data = undither(ctx, orig)
|
||||
with open(os.path.join(d, "u_" + out), "wb") as f:
|
||||
f.write(data)
|
||||
c = {"name": name, "data": data, "channels": ch, "rate": rate}
|
||||
if "-s" in extra:
|
||||
c["ref"], c["refTool"] = a52dec(run, d, "u_" + out, ch), "a52dec"
|
||||
else:
|
||||
c["ref"], c["refTool"] = run("ffmpeg -v error -drc_scale 0 -i u_%s -f f32le -" % out), "ffmpeg"
|
||||
if "-dynrng" in extra:
|
||||
c["refDrc"] = run("ffmpeg -v error -drc_scale 1 -i u_%s -f f32le -" % out)
|
||||
c["frames"] = len(c["ref"]) // (4 * ch)
|
||||
if name in DITHERED:
|
||||
c["dithered"] = orig
|
||||
cases.append(c)
|
||||
# AC-3 tracks in containers: the (undithered) AC-3 remuxed with a tiny Motion-JPEG / MPEG-1 picture track
|
||||
sig = signal(int(48000 * 0.3), 6, 48000, 7)
|
||||
with open(os.path.join(d, "t.raw"), "wb") as f:
|
||||
f.write(raw(sig))
|
||||
for name, video, layout in (("ac3.mkv", "-c:v mjpeg -pix_fmt yuvj420p", "5.1(side)"),
|
||||
("ac3.mp4", "-c:v mjpeg -pix_fmt yuvj420p", "stereo"), ("ac3.ts", "-c:v mpeg1video", "stereo"),
|
||||
("ac3.avi", "-c:v mjpeg -pix_fmt yuvj420p", "stereo")):
|
||||
run("ffmpeg -v error -y -f f32le -ar 48000 -ch_layout '5.1(side)' -i t.raw -af aformat=channel_layouts='%s' "
|
||||
"-c:a ac3 -b:a 192k t.ac3" % layout)
|
||||
with open(os.path.join(d, "t.ac3"), "rb") as f:
|
||||
es = undither(ctx, f.read())
|
||||
with open(os.path.join(d, "u.ac3"), "wb") as f:
|
||||
f.write(es)
|
||||
run("ffmpeg -v error -y -f lavfi -i testsrc=size=64x48:rate=25:duration=0.3 -i u.ac3 %s -c:a copy -shortest %s"
|
||||
% (video, name))
|
||||
with open(os.path.join(d, name), "rb") as f:
|
||||
data = f.read()
|
||||
ref = run("ffmpeg -v error -drc_scale 0 -i u.ac3 -f f32le -")
|
||||
tracks.append({"name": name, "data": data, "channels": CHANNELS[layout], "rate": 48000, "ref": ref})
|
||||
finally:
|
||||
shutil.rmtree(d, ignore_errors=True)
|
||||
ctx.emit("ac3_cases", cases)
|
||||
ctx.emit("ac3_tracks", tracks)
|
||||
@@ -0,0 +1,39 @@
|
||||
# Docs inputs for the Musepack / AC-3 section of docs/guide/audio.md (tools/docs_check.py): a tagged stereo tone as
|
||||
# Musepack SV8 (mpcenc, built by tools/fixtures/mpc.py's nix expression) and a 5.1 tone as AC-3 (ffmpeg).
|
||||
# tests/gen/docs_lossy.luau { files = { [name] = bytes }, vars = { mpcBytes = "tone.mpc", ac3Bytes = "tone.ac3" } }
|
||||
import importlib.util, math, os, shutil, struct, subprocess, tempfile
|
||||
|
||||
INPUTS = ["tools/docs_check.py", "tools/fixtures/mpc.py"]
|
||||
|
||||
|
||||
def load(ctx, rel, name):
|
||||
spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, rel))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
dc = load(ctx, "tools/docs_check.py", "docs_check")
|
||||
mpc = load(ctx, "tools/fixtures/mpc.py", "docs_lossy_mpc")
|
||||
d = tempfile.mkdtemp(prefix="fmt-docs-lossy-")
|
||||
try:
|
||||
rate, n = 44100, 44100
|
||||
st = [0.3 * math.sin(2 * math.pi * f * i / rate) for i in range(n) for f in (440, 660)]
|
||||
with open(os.path.join(d, "tone.wav"), "wb") as f:
|
||||
f.write(mpc.A.wav(st, rate, 2))
|
||||
subprocess.run([os.path.join(mpc.tools(), "mpcenc"), "--silent", "--overwrite", "--quality", "4",
|
||||
"--tag", "Title=Docs Tone", "--artist", "formats-luau", os.path.join(d, "tone.wav"),
|
||||
os.path.join(d, "tone.mpc")], capture_output=True, check=True)
|
||||
six = [0.2 * math.sin(2 * math.pi * (200 + 100 * c) * i / 48000) for i in range(24000) for c in range(6)]
|
||||
with open(os.path.join(d, "six.raw"), "wb") as f:
|
||||
f.write(struct.pack("<%df" % len(six), *six))
|
||||
ctx.nix("ffmpeg", ["sh", "-c", "cd '%s' && ffmpeg -v error -y -f f32le -ar 48000 -ch_layout '5.1(side)' -i six.raw "
|
||||
"-c:a ac3 -b:a 384k tone.ac3" % d])
|
||||
files = {}
|
||||
for name in ("tone.mpc", "tone.ac3"):
|
||||
with open(os.path.join(d, name), "rb") as f:
|
||||
files[name] = f.read()
|
||||
finally:
|
||||
shutil.rmtree(d, ignore_errors=True)
|
||||
dc.emit_inputs(ctx, files, {"mpcBytes": "tone.mpc", "ac3Bytes": "tone.ac3"})
|
||||
@@ -0,0 +1,130 @@
|
||||
# Musepack fixtures (tools/fixtures.py). There is no Musepack encoder in nixpkgs, so the reference tools are built
|
||||
# here from the official sources through nix (fetchurl with pinned hashes): mpcenc / libmpcdec from musepack_src_r475
|
||||
# (SV8, BSD / LGPL tools), mppenc 1.16 (SV7), and `mpcf32`, a 20-line C program linked against r475's libmpcdec that
|
||||
# writes its float output (gapless, the reference) as f32le, optionally after mpc_demux_seek_sample.
|
||||
# tests/gen/mpc_cases.luau { name, data, version, channels, rate, frames, exact (frames that match libmpcdec
|
||||
# exactly), ref (mpcf32's f32le, the first REF frames), ff? (ffmpeg's s16 decode as f32le,
|
||||
# aligned: ffmpeg is not gapless), tags? }
|
||||
# tests/gen/mpc_seek.luau { name (a case), at (sample), ref (mpcf32 after seeking to `at`, SEEK_REF stereo frames) }
|
||||
import importlib.util, os, subprocess, tempfile, shutil
|
||||
|
||||
_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 = ["tools/fixtures/_audio.py"]
|
||||
|
||||
NIX = r'''
|
||||
with import <nixpkgs> {};
|
||||
let
|
||||
flags = "-fcommon -Wno-error -Wno-implicit-function-declaration -Wno-incompatible-pointer-types -Wno-int-conversion";
|
||||
f32 = writeText "mpcf32.c" ''
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <mpc/mpcdec.h>
|
||||
int main(int argc, char **argv) {
|
||||
mpc_reader r; mpc_streaminfo si; MPC_SAMPLE_FORMAT b[MPC_DECODER_BUFFER_LENGTH];
|
||||
if (argc < 2 || mpc_reader_init_stdio(&r, argv[1]) < 0) return 1;
|
||||
mpc_demux *d = mpc_demux_init(&r); if (!d) return 2;
|
||||
mpc_demux_get_info(d, &si);
|
||||
if (argc > 2) mpc_demux_seek_sample(d, (mpc_uint64_t) atoll(argv[2]));
|
||||
for (;;) { mpc_frame_info f; f.buffer = b;
|
||||
if (mpc_demux_decode(d, &f) != MPC_STATUS_OK) { fprintf(stderr, "error\n"); return 3; }
|
||||
if (f.bits == -1) break;
|
||||
fwrite(b, sizeof(float), f.samples * si.channels, stdout); }
|
||||
return 0; }
|
||||
'';
|
||||
in symlinkJoin { name = "musepack-tools"; paths = [
|
||||
(stdenv.mkDerivation {
|
||||
pname = "musepack"; version = "r475";
|
||||
src = fetchurl { url = "https://files.musepack.net/source/musepack_src_r475.tar.gz"; sha256 = "a4b1742f997f83e1056142d556a8c20845ba764b70365ff9ccf2e3f81c427b2b"; };
|
||||
nativeBuildInputs = [ cmake ];
|
||||
NIX_CFLAGS_COMPILE = flags;
|
||||
postPatch = "sed -i -e /mpcgain/d -e /mpcchap/d -e /wavcmp/d -e /mpccut/d CMakeLists.txt";
|
||||
cmakeFlags = [ "-DCMAKE_POLICY_VERSION_MINIMUM=3.5" "-DSHARED=OFF" ];
|
||||
postBuild = "$CC -O2 -I../include ${f32} libmpcdec/libmpcdec_static.a -lm -o mpcf32";
|
||||
installPhase = "mkdir -p $out/bin; cp mpcenc/mpcenc mpcdec/mpcdec mpcf32 $out/bin/";
|
||||
})
|
||||
(stdenv.mkDerivation {
|
||||
pname = "mppenc"; version = "1.16";
|
||||
src = fetchurl { url = "https://files.musepack.net/source/mppenc-1.16.tar.bz2"; sha256 = "f90781856ca7b6ce1ec7033321fadbcd04fe264d0349c20b49ad05f7cb2655ad"; };
|
||||
nativeBuildInputs = [ cmake ];
|
||||
NIX_CFLAGS_COMPILE = flags;
|
||||
cmakeFlags = [ "-DCMAKE_POLICY_VERSION_MINIMUM=3.5" ];
|
||||
installPhase = "mkdir -p $out/bin; cp src/mppenc $out/bin/";
|
||||
})
|
||||
]; }
|
||||
'''
|
||||
|
||||
# name, encoder (mpcenc = SV8, mppenc = SV7), signal, rate, channels, seconds, extra options
|
||||
CASES = [
|
||||
("sv8_q5_stereo", "mpcenc", "music", 44100, 2, 1.2, ["--quality", "5", "--num_frames", "1"]),
|
||||
("sv8_q3_mono32k", "mpcenc", "sweep", 32000, 1, 0.5, ["--quality", "3"]),
|
||||
("sv8_q9_noise48k", "mpcenc", "noise", 48000, 2, 0.4, ["--quality", "9", "--num_frames", "2"]),
|
||||
("sv8_q1_sine", "mpcenc", "sine", 44100, 2, 0.3, ["--quality", "1", "--num_frames", "0",
|
||||
"--artist", "Some One", "--tag", "Title=Mpc Tone", "--tag", "Year=2026"]),
|
||||
("sv7_q5_stereo", "mppenc", "music", 44100, 2, 1.2, ["--quality", "5"]),
|
||||
("sv7_q8_noise", "mppenc", "noise", 44100, 2, 0.3, ["--quality", "8"]),
|
||||
("sv7_q2_sweep", "mppenc", "sweep", 48000, 2, 0.5, ["--quality", "2"]),
|
||||
]
|
||||
REF = 22050 # frames of reference output kept per case (the fixture module stays small)
|
||||
FF = ("sv8_q5_stereo", "sv7_q5_stereo") # cases also compared with ffmpeg
|
||||
SEEKS = [("sv8_q5_stereo", 30000), ("sv8_q9_noise48k", 9000), ("sv7_q5_stereo", 40000)]
|
||||
SEEK_REF = 4096
|
||||
|
||||
|
||||
def tools():
|
||||
out = subprocess.run(["nix", "build", "--impure", "--no-link", "--print-out-paths", "--expr", NIX],
|
||||
capture_output=True, check=True).stdout.decode().strip().split("\n")[-1]
|
||||
return os.path.join(out, "bin")
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
bin_ = tools()
|
||||
d = tempfile.mkdtemp(prefix="fmt-mpc-")
|
||||
cases, seeks, files = [], [], {}
|
||||
try:
|
||||
for name, enc, kind, rate, ch, secs, extra in CASES:
|
||||
frames = int(rate * secs)
|
||||
sig = A.signal(kind, rate, ch, frames, seed=len(name))
|
||||
wav = os.path.join(d, name + ".wav")
|
||||
mpc = os.path.join(d, name + ".mpc")
|
||||
with open(wav, "wb") as f:
|
||||
f.write(A.wav(sig, rate, ch))
|
||||
subprocess.run([os.path.join(bin_, enc)] + extra + ["--silent", "--overwrite", wav, mpc], capture_output=True, check=True)
|
||||
with open(mpc, "rb") as f:
|
||||
data = f.read()
|
||||
files[name] = mpc
|
||||
ref = subprocess.run([os.path.join(bin_, "mpcf32"), mpc], capture_output=True, check=True).stdout
|
||||
got = len(ref) // (4 * ch)
|
||||
assert got == frames, (name, got, frames)
|
||||
# SV7: libmpcdec decodes the zero-filled data past the last frame for the synthesis tail (reading past
|
||||
# its tables); we decode silence there, so only the frames before it compare exactly
|
||||
exact = frames
|
||||
if enc == "mppenc":
|
||||
exact = min(frames, int.from_bytes(data[4:8], "little") * 1152 - 481)
|
||||
c = {"name": name, "data": data, "version": 8 if enc == "mpcenc" else 7, "channels": ch, "rate": rate,
|
||||
"frames": frames, "exact": exact, "ref": ref[:REF * ch * 4]}
|
||||
if name in FF:
|
||||
_, _, ff = A.ffdecode(ctx, data, ext="mpc")
|
||||
# ffmpeg decodes without the gapless trimming: find the lag of the reference inside its output
|
||||
refl = A.from_f32le(ref)
|
||||
best = None
|
||||
for lag in range(0, 2400):
|
||||
if (lag + 200) * ch > len(ff):
|
||||
break
|
||||
e = sum((ff[(lag + i) * ch] - refl[i * ch]) ** 2 for i in range(100, 200))
|
||||
if best is None or e < best[0]:
|
||||
best = (e, lag)
|
||||
c["ff"] = A.f32le(ff[best[1] * ch:(best[1] + REF) * ch])
|
||||
if "--artist" in extra:
|
||||
c["tags"] = {"artist": "Some One", "title": "Mpc Tone", "date": "2026"}
|
||||
cases.append(c)
|
||||
for name, at in SEEKS:
|
||||
ref = subprocess.run([os.path.join(bin_, "mpcf32"), files[name], str(at)], capture_output=True, check=True).stdout
|
||||
data = next(c["data"] for c in cases if c["name"] == name)
|
||||
seeks.append({"name": name, "at": at, "ref": ref[:SEEK_REF * 8]})
|
||||
finally:
|
||||
shutil.rmtree(d, ignore_errors=True)
|
||||
ctx.emit("mpc_cases", cases)
|
||||
ctx.emit("mpc_seek", seeks)
|
||||
Reference in new issue
Block a user