ws-h264: merge ws/video; codecs/Video registers h264 (avc1/avc3/H264/... FourCCs, V_MPEG4/ISO/AVC) via H264.newVideoDecoder; video/h264 raw Annex B format (demux by access unit, copy-writer from MP4/MKV samples); MMCO 5 resets frame_num (JVT MR2/MR4/MR5); meta.yuv from the VUI
This commit is contained in:
commit
d4486dccce
211 files changed
+43039
-552
No files matched your search
+387
-7
@@ -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")
|
||||
@@ -536,14 +595,335 @@ do
|
||||
end)
|
||||
end
|
||||
do
|
||||
-- H.264: frames per second over whole streams (decode + output copies); MB/s of yuv420p output
|
||||
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
|
||||
|
||||
-- MIDI through the SoundFont synth (tools/fixtures/sf2.py's test song; tools/fixtures/midi.py's "song" through the
|
||||
-- built-in waveform set): seconds of stereo 44.1 kHz audio rendered per second of CPU
|
||||
do
|
||||
local Midi = require("@formats/music/midi")
|
||||
local Sf2 = require("@formats/music/sf2")
|
||||
local SF = require("@tests/gen/sf2_cases")
|
||||
local MC = require("@tests/gen/midi_cases")
|
||||
local sf = assert(Sf2.decode(Bytes.reader(buffer.fromstring(SF.sf2))))
|
||||
local function realtime(label: string, data: string, font: any)
|
||||
local song = assert(Midi.decode(Bytes.reader(buffer.fromstring(data))))
|
||||
local best = math.huge
|
||||
local frames = 0
|
||||
for _ = 1, 3 do
|
||||
local dec = assert(Midi.render(song, { soundfont = font, tail = 0 }))
|
||||
local out = buffer.create(4096 * 8)
|
||||
local t0 = os.clock()
|
||||
frames = 0
|
||||
while true do
|
||||
local _, n = dec:read(4096, out)
|
||||
if n == 0 then
|
||||
break
|
||||
end
|
||||
frames += n
|
||||
end
|
||||
best = math.min(best, os.clock() - t0)
|
||||
end
|
||||
print(string.format("%-8s %-30s %8.2f ms %7.1f x realtime", runtime, label, best * 1000, frames / 44100 / best))
|
||||
end
|
||||
realtime("midi render sf2 (test song)", SF.song, sf)
|
||||
for _, c in MC do
|
||||
if c.name == "song" then
|
||||
realtime("midi render fallback", c.data, nil)
|
||||
end
|
||||
end
|
||||
end
|
||||
-- the synth's per-voice cost: 32 sustained, filtered, looped voices (sf2 saw preset with a mod env) for 2 s
|
||||
do
|
||||
local SoundFont = require("@formats/codecs/SoundFont")
|
||||
local Sf2 = require("@formats/music/sf2")
|
||||
local SF = require("@tests/gen/sf2_cases")
|
||||
local sf = assert(Sf2.decode(Bytes.reader(buffer.fromstring(SF.sf2))))
|
||||
local frames = 88200
|
||||
local out = buffer.create(frames * 8)
|
||||
local best = math.huge
|
||||
for _ = 1, 3 do
|
||||
local s = SoundFont.synth(sf, 44100)
|
||||
SoundFont.Synth.midi(s, 0xC0, 1, 0)
|
||||
for k = 0, 31 do
|
||||
SoundFont.Synth.midi(s, 0x90, 40 + k, 100)
|
||||
end
|
||||
buffer.fill(out, 0, 0)
|
||||
local t0 = os.clock()
|
||||
for f = 0, frames - 1, 1024 do
|
||||
SoundFont.Synth.render(s, out, f, 1024)
|
||||
end
|
||||
best = math.min(best, os.clock() - t0)
|
||||
end
|
||||
print(string.format("%-8s %-30s %8.2f ms %7.1f M voice-samples/s", runtime, "synth 32 voices x 2 s", best * 1000, 32 * frames / best / 1e6))
|
||||
end
|
||||
-- the tracker engine: 32 channels of looped samples (one note each, linear interpolation, volume ramps), and an
|
||||
-- IT-style module with background voices (NNA continue) and resonant filters on every channel
|
||||
do
|
||||
local Tracker = require("@formats/codecs/Tracker")
|
||||
local function song(format: string, filter: boolean): any
|
||||
local m = Tracker.newModule(format, 32)
|
||||
m.order = { 0 }
|
||||
m.patterns[1] = Tracker.newPattern(64, 32)
|
||||
local s = Tracker.newSample("saw")
|
||||
s.length = 1000
|
||||
s.data = buffer.create(4000)
|
||||
for i = 0, 999 do
|
||||
buffer.writef32(s.data, i * 4, (i % 100) / 50 - 1)
|
||||
end
|
||||
s.loopStart, s.loopEnd, s.loopType = 0, 1000, 1
|
||||
m.samples[1] = s
|
||||
if format == "it" then
|
||||
local ins = Tracker.newInstrument("nna")
|
||||
for n = 1, 120 do
|
||||
ins.sampleMap[n] = 1
|
||||
end
|
||||
ins.nna = 1
|
||||
ins.fadeout = 64
|
||||
if filter then
|
||||
ins.cutoff, ins.resonance = 60, 40
|
||||
end
|
||||
m.instruments[1] = ins
|
||||
end
|
||||
for ch = 1, 32 do
|
||||
for row = 0, 63, 16 do
|
||||
Tracker.setCell(m, 0, row, ch, 37 + ch + row // 16, 1, 0, 0, 0)
|
||||
end
|
||||
end
|
||||
return m
|
||||
end
|
||||
local function realtime(label: string, m: any, voices: number)
|
||||
local best, frames = math.huge, 0
|
||||
local out = buffer.create(4096 * 8)
|
||||
for _ = 1, 3 do
|
||||
local dec = Tracker.render(m) :: any
|
||||
frames = 0
|
||||
local t0 = os.clock()
|
||||
while true do
|
||||
local _, n = dec:read(4096, out)
|
||||
if n == 0 then
|
||||
break
|
||||
end
|
||||
frames += n
|
||||
end
|
||||
best = math.min(best, os.clock() - t0)
|
||||
end
|
||||
print(string.format("%-8s %-30s %8.2f ms %7.1f x realtime %5.1f M voice-samples/s", runtime, label, best * 1000, frames / 44100 / best, voices * frames / best / 1e6))
|
||||
end
|
||||
realtime("tracker 32 ch (mod)", song("mod", false), 32)
|
||||
realtime("tracker 32 ch + NNA, filters", song("it", true), 64)
|
||||
end
|
||||
-- ------------------------------------------------------------------------------------------- ws-video-codecs: fps
|
||||
do
|
||||
local Jpeg = require("@formats/codecs/Jpeg")
|
||||
local Mpeg1 = require("@formats/codecs/Mpeg1")
|
||||
local Base64 = require("@formats/core/Base64")
|
||||
local Types = require("@formats/Types")
|
||||
local MB = require("@tests/gen/mjpeg_bench")
|
||||
local M1 = require("@tests/gen/mpeg1_bench")
|
||||
-- best of n runs of f (which handles `frames` frames): ms per frame and frames per second
|
||||
local function fps(label: string, n: number, frames: number, f: () -> ())
|
||||
f()
|
||||
local dt = math.huge
|
||||
for _ = 1, n do
|
||||
local t0 = os.clock()
|
||||
f()
|
||||
dt = math.min(dt, os.clock() - t0)
|
||||
end
|
||||
print(string.format("%-8s %-30s %8.2f ms %7.1f fps", runtime, label, dt * 1000 / frames, frames / dt))
|
||||
end
|
||||
for _, c in MB.frames do
|
||||
local b = Base64.decode(c.data) :: buffer
|
||||
local img = assert(Jpeg.decode(b, 0, nil, { yuv = true }))
|
||||
assert(Crc32.of(img.pixels) == c.yuv, "mjpeg bench: " .. c.name .. " does not match TurboJPEG")
|
||||
fps("mjpeg decode yuv " .. c.name, 10, 1, function()
|
||||
Jpeg.decode(b, 0, nil, { yuv = true })
|
||||
end)
|
||||
fps("mjpeg decode rgba " .. c.name, 10, 1, function()
|
||||
Jpeg.decode(b)
|
||||
end)
|
||||
end
|
||||
for _, s in MB.sources do
|
||||
local img = Types.Image.new(s.width, s.height, "yuv420p")
|
||||
img.pixels = assert(Deflate.zlib(Base64.decode(s.yuv) :: buffer))
|
||||
fps(string.format("mjpeg encode yuv %dx%d q85", s.width, s.height), 5, 1, function()
|
||||
Jpeg.encode(img, { quality = 85 })
|
||||
end)
|
||||
end
|
||||
for _, s in M1 do
|
||||
local file = Base64.decode(s.file) :: buffer
|
||||
for _, rgba in { false, true } do
|
||||
fps(string.format("mpeg1 decode %s %dx%d", if rgba then "rgba" else "yuv", s.width, s.height), 3, #s.units, function()
|
||||
local dec = Mpeg1.new({ reorder = true, rgba = rgba })
|
||||
for i, u in s.units do
|
||||
dec:decode(file, u[1], u[2], i)
|
||||
end
|
||||
while dec:flush() do
|
||||
end
|
||||
end)
|
||||
end
|
||||
end
|
||||
end
|
||||
-- ------------------------------------------------------------------------------------------- ws-video: containers
|
||||
do
|
||||
local F = require("@formats")
|
||||
local VB = require("@tests/gen/videobench")
|
||||
local function clock(n: number, f: () -> number): (number, number)
|
||||
local frames = f()
|
||||
local dt = math.huge
|
||||
for _ = 1, n do
|
||||
local t0 = os.clock()
|
||||
frames = f()
|
||||
dt = math.min(dt, os.clock() - t0)
|
||||
end
|
||||
return dt, frames
|
||||
end
|
||||
for _, c in VB do
|
||||
local data = buffer.fromstring(c.data)
|
||||
local dtOpen = clock(3, function(): number
|
||||
F.video.open(data, { audio = false })
|
||||
return 1
|
||||
end)
|
||||
for _, rgba in { false, true } do
|
||||
local ok, dt, frames = pcall(clock, 2, function(): number
|
||||
local v = assert(F.video.open(data, { audio = false, rgba = rgba }))
|
||||
local n = 0
|
||||
while true do
|
||||
local f, err = v:nextFrame()
|
||||
if not f then
|
||||
assert(err == nil, tostring(err))
|
||||
break
|
||||
end
|
||||
n += 1
|
||||
end
|
||||
return n
|
||||
end)
|
||||
if ok then
|
||||
print(string.format("%-8s %-30s %8.2f ms %7.1f fps (open %.1f ms)", runtime, string.format("video %s %s %s", c.size, c.name, if rgba then "rgba" else "yuv"), dt * 1000 / frames, frames / dt, dtOpen * 1000))
|
||||
else
|
||||
print(string.format("%-8s %-30s %s", runtime, "video " .. c.size .. " " .. c.name, tostring(dt)))
|
||||
end
|
||||
end
|
||||
if c.name == "raw.y4m" then
|
||||
local dt, frames = clock(2, function(): number
|
||||
assert(F.convert(data, "avi", { quality = 85 }))
|
||||
return 8
|
||||
end)
|
||||
print(string.format("%-8s %-30s %8.2f ms %7.1f fps", runtime, "video " .. c.size .. " y4m -> mjpeg avi", dt * 1000 / frames, frames / dt))
|
||||
end
|
||||
end
|
||||
end
|
||||
-- ------------------------------------------------------------------------------------------- ws-video-vp8: fps
|
||||
do
|
||||
-- VP8 video (codecs/Vp8, tools/fixtures/vp8video.py): whole IVF streams (libvpx, panning testsrc2) through one
|
||||
-- decoder object; frames per second. On LuaJIT the library's host module raises the trace limits (maxtrace=8000,
|
||||
-- see src/Formats/host/init.luau): the second pair of lines runs with them, as the api does.
|
||||
local Vp8 = require("@formats/codecs/Vp8")
|
||||
local VB = require("@tests/gen/vp8video_bench")
|
||||
local function run(tag: string)
|
||||
for _, c in VB do
|
||||
local b = buffer.fromstring(c.ivf)
|
||||
local frames = {}
|
||||
local p = 32
|
||||
while p + 12 <= buffer.len(b) do
|
||||
local n = buffer.readu32(b, p)
|
||||
table.insert(frames, { p + 12, n })
|
||||
p += 12 + n
|
||||
end
|
||||
local dt = bench(string.format("vp8 decode %dx%d%s", c.width, c.height, tag), 3, c.width * c.height * 1.5 * #frames, function()
|
||||
local dec = Vp8.newDecoder()
|
||||
for _, f in frames do
|
||||
dec:decodeFrame(b, f[1], f[2])
|
||||
end
|
||||
end)
|
||||
print(string.format("%-8s %-30s %8.1f fps", runtime, " (" .. #frames .. " frames)", #frames / dt))
|
||||
end
|
||||
end
|
||||
run("")
|
||||
if runtime == "luajit" then
|
||||
require("@formats/host")
|
||||
run(" (jit tuned)")
|
||||
end
|
||||
end
|
||||
do
|
||||
-- H.264 (codecs/H264): whole Annex B streams, frames per second (decode + the cropped yuv420p output copies). The
|
||||
-- testsrc2 clips are easy (mostly static); the mandelbrot zooms move everywhere. LuaJIT runs twice: with its default
|
||||
-- trace limits and with the ones host/init.luau sets (maxtrace=8000, maxmcode=65536).
|
||||
local H264 = require("@formats/codecs/H264")
|
||||
local HB = require("@tests/gen/h264_bench")
|
||||
for _, c in HB do
|
||||
local n = c.width * c.height * 3 // 2 * #c.frames
|
||||
local dt = bench("h264 " .. c.name .. " " .. #c.frames .. "f", 2, n, function()
|
||||
H264.decodeAll(c.data)
|
||||
end)
|
||||
print(string.format("%-8s h264 %s: %.1f fps at %dx%d", runtime, c.name, #c.frames / dt, c.width, c.height))
|
||||
local function run(tag: string)
|
||||
for _, c in HB do
|
||||
local n = c.width * c.height * 3 // 2 * #c.frames
|
||||
local dt = bench(string.format("h264 %s %dx%d%s", c.name, c.width, c.height, tag), 3, n, function()
|
||||
H264.decodeAll(c.data)
|
||||
end)
|
||||
print(string.format("%-8s %-30s %8.1f fps", runtime, " (" .. #c.frames .. " frames)", #c.frames / dt))
|
||||
end
|
||||
end
|
||||
run("")
|
||||
if runtime == "luajit" then
|
||||
require("@formats/host")
|
||||
run(" (jit tuned)")
|
||||
end
|
||||
end
|
||||
@@ -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,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,183 @@
|
||||
# MIDI reference cases (run by tools/fixtures/midi.py through ctx.python(["mido"], ...); not a generator itself).
|
||||
# Builds Standard MIDI Files with python mido (formats 0 / 1 / 2, tempo changes, time / key signatures, running
|
||||
# status, sysex, pitch bend, every channel message, a random stress file), saves them with mido, and prints JSON:
|
||||
# per file the bytes, mido's parse in formats-luau's event shape and mido's lengths / message times.
|
||||
import io, json, random, sys
|
||||
import mido
|
||||
from mido import Message, MetaMessage, MidiFile, MidiTrack
|
||||
|
||||
|
||||
def ours(msg):
|
||||
"""a mido message -> [type, channel, data, meta] in formats-luau's shape (data = raw bytes)"""
|
||||
t = msg.type
|
||||
if msg.is_meta:
|
||||
b = msg.bytes()
|
||||
i = 2
|
||||
while b[i] & 0x80:
|
||||
i += 1
|
||||
return ["meta", -1, list(b[i + 1:]), b[1]]
|
||||
if t == "sysex":
|
||||
return ["sysex", -1, list(msg.data) + [0xF7], -1]
|
||||
if t == "note_on":
|
||||
return ["noteOn", msg.channel, [msg.note, msg.velocity], -1]
|
||||
if t == "note_off":
|
||||
return ["noteOff", msg.channel, [msg.note, msg.velocity], -1]
|
||||
if t == "polytouch":
|
||||
return ["aftertouch", msg.channel, [msg.note, msg.value], -1]
|
||||
if t == "control_change":
|
||||
return ["controller", msg.channel, [msg.control, msg.value], -1]
|
||||
if t == "program_change":
|
||||
return ["program", msg.channel, [msg.program], -1]
|
||||
if t == "aftertouch":
|
||||
return ["channelPressure", msg.channel, [msg.value], -1]
|
||||
if t == "pitchwheel":
|
||||
v = msg.pitch + 8192
|
||||
return ["pitchBend", msg.channel, [v & 127, v >> 7], -1]
|
||||
raise ValueError(t)
|
||||
|
||||
|
||||
def describe(name, mid):
|
||||
buf = io.BytesIO()
|
||||
mid.save(file=buf)
|
||||
data = buf.getvalue()
|
||||
back = MidiFile(file=io.BytesIO(data))
|
||||
tracks = []
|
||||
for tr in back.tracks:
|
||||
tick, evs = 0, []
|
||||
for msg in tr:
|
||||
tick += msg.time
|
||||
evs.append([tick] + ours(msg))
|
||||
tracks.append(evs)
|
||||
case = {"name": name, "hex": data.hex(), "type": back.type, "division": back.ticks_per_beat, "tracks": tracks}
|
||||
if back.type != 2 and back.ticks_per_beat > 0:
|
||||
case["length"] = back.length
|
||||
t, times = 0.0, []
|
||||
for msg in back:
|
||||
t += msg.time
|
||||
times.append(t)
|
||||
case["times"] = times
|
||||
return case
|
||||
|
||||
|
||||
def notes(track, ch, rng, n, prog=None, start=0):
|
||||
if prog is not None:
|
||||
track.append(Message("program_change", channel=ch, program=prog, time=start))
|
||||
start = 0
|
||||
for i in range(n):
|
||||
note = rng.randint(30, 90)
|
||||
track.append(Message("note_on", channel=ch, note=note, velocity=rng.randint(1, 127), time=start if i == 0 else rng.randint(0, 120)))
|
||||
track.append(Message("note_off", channel=ch, note=note, velocity=rng.randint(0, 127), time=rng.randint(1, 480)))
|
||||
|
||||
|
||||
cases = []
|
||||
rng = random.Random(7)
|
||||
|
||||
# format 0: one track with everything
|
||||
mid = MidiFile(type=0, ticks_per_beat=480)
|
||||
t = MidiTrack()
|
||||
mid.tracks.append(t)
|
||||
t.append(MetaMessage("track_name", name="format zero"))
|
||||
t.append(MetaMessage("set_tempo", tempo=500000))
|
||||
t.append(MetaMessage("time_signature", numerator=3, denominator=4, clocks_per_click=24, notated_32nd_notes_per_beat=8))
|
||||
t.append(MetaMessage("key_signature", key="Eb"))
|
||||
t.append(MetaMessage("text", text="hello"))
|
||||
t.append(Message("program_change", channel=0, program=5))
|
||||
t.append(Message("control_change", channel=0, control=7, value=100))
|
||||
t.append(Message("control_change", channel=0, control=10, value=20))
|
||||
t.append(Message("note_on", channel=0, note=60, velocity=100, time=0))
|
||||
t.append(Message("note_on", channel=0, note=64, velocity=90, time=10)) # running status
|
||||
t.append(Message("note_on", channel=0, note=67, velocity=80, time=10))
|
||||
t.append(Message("pitchwheel", channel=0, pitch=-8192, time=100))
|
||||
t.append(Message("pitchwheel", channel=0, pitch=8191, time=100))
|
||||
t.append(Message("pitchwheel", channel=0, pitch=0, time=100))
|
||||
t.append(Message("polytouch", channel=0, note=60, value=33, time=5))
|
||||
t.append(Message("aftertouch", channel=0, value=44, time=5))
|
||||
t.append(Message("sysex", data=[0x7E, 0x7F, 0x09, 0x01], time=0))
|
||||
t.append(MetaMessage("set_tempo", tempo=300000, time=240))
|
||||
t.append(Message("note_off", channel=0, note=60, velocity=0, time=480))
|
||||
t.append(Message("note_on", channel=0, note=64, velocity=0, time=0)) # note on, velocity 0
|
||||
t.append(Message("note_off", channel=0, note=67, velocity=64, time=0))
|
||||
t.append(Message("note_on", channel=9, note=36, velocity=127, time=100))
|
||||
t.append(Message("note_off", channel=9, note=36, velocity=0, time=100))
|
||||
t.append(MetaMessage("time_signature", numerator=6, denominator=8, time=0))
|
||||
t.append(MetaMessage("set_tempo", tempo=1000000, time=10))
|
||||
t.append(Message("note_on", channel=1, note=72, velocity=50, time=0))
|
||||
t.append(Message("note_off", channel=1, note=72, velocity=50, time=960))
|
||||
cases.append(describe("format0", mid))
|
||||
|
||||
# format 1: a conductor track + 3 instrument tracks, tempo changes in the conductor
|
||||
mid = MidiFile(type=1, ticks_per_beat=96)
|
||||
cond = MidiTrack()
|
||||
mid.tracks.append(cond)
|
||||
cond.append(MetaMessage("track_name", name="conductor"))
|
||||
cond.append(MetaMessage("time_signature", numerator=4, denominator=4))
|
||||
for i, tempo in enumerate([500000, 400000, 600000, 250000, 750000]):
|
||||
cond.append(MetaMessage("set_tempo", tempo=tempo, time=0 if i == 0 else 384))
|
||||
for ch in range(3):
|
||||
tr = MidiTrack()
|
||||
mid.tracks.append(tr)
|
||||
tr.append(MetaMessage("track_name", name="part %d" % ch))
|
||||
notes(tr, ch, rng, 40, prog=ch * 10)
|
||||
cases.append(describe("format1", mid))
|
||||
|
||||
# format 2: independent patterns, each with its own tempo
|
||||
mid = MidiFile(type=2, ticks_per_beat=240)
|
||||
for k in range(3):
|
||||
tr = MidiTrack()
|
||||
mid.tracks.append(tr)
|
||||
tr.append(MetaMessage("set_tempo", tempo=400000 + 100000 * k))
|
||||
notes(tr, k, rng, 10)
|
||||
cases.append(describe("format2", mid))
|
||||
|
||||
# a random stress file: many tracks / channels / controller streams (long running-status runs)
|
||||
mid = MidiFile(type=1, ticks_per_beat=480)
|
||||
for k in range(6):
|
||||
tr = MidiTrack()
|
||||
mid.tracks.append(tr)
|
||||
if k == 0:
|
||||
for j in range(20):
|
||||
tr.append(MetaMessage("set_tempo", tempo=rng.randint(200000, 1500000), time=rng.randint(0, 2000)))
|
||||
continue
|
||||
ch = rng.randint(0, 15)
|
||||
for j in range(400):
|
||||
r = rng.random()
|
||||
dt = rng.choice([0, 0, 1, 7, 120, 480, 20000])
|
||||
if r < 0.4:
|
||||
tr.append(Message("note_on", channel=ch, note=rng.randint(0, 127), velocity=rng.randint(0, 127), time=dt))
|
||||
elif r < 0.6:
|
||||
tr.append(Message("note_off", channel=ch, note=rng.randint(0, 127), velocity=rng.randint(0, 127), time=dt))
|
||||
elif r < 0.8:
|
||||
tr.append(Message("control_change", channel=ch, control=rng.randint(0, 127), value=rng.randint(0, 127), time=dt))
|
||||
elif r < 0.9:
|
||||
tr.append(Message("pitchwheel", channel=ch, pitch=rng.randint(-8192, 8191), time=dt))
|
||||
elif r < 0.95:
|
||||
tr.append(Message("program_change", channel=ch, program=rng.randint(0, 127), time=dt))
|
||||
else:
|
||||
tr.append(Message("sysex", data=[rng.randint(0, 127) for _ in range(rng.randint(0, 200))], time=dt))
|
||||
cases.append(describe("random", mid))
|
||||
|
||||
# SMPTE time (25 fps, 40 ticks per frame): division = -(25 << 8) + 40 as a signed 16-bit value
|
||||
mid = MidiFile(type=0, ticks_per_beat=-6360)
|
||||
t = MidiTrack()
|
||||
mid.tracks.append(t)
|
||||
t.append(Message("note_on", note=60, velocity=64, time=0))
|
||||
t.append(Message("note_off", note=60, velocity=64, time=1000))
|
||||
cases.append(describe("smpte", mid))
|
||||
|
||||
# the song the fallback / SoundFont render tests play (tools/fixtures/sf2.py has its own); its mido length
|
||||
mid = MidiFile(type=1, ticks_per_beat=480)
|
||||
cond = MidiTrack()
|
||||
mid.tracks.append(cond)
|
||||
cond.append(MetaMessage("set_tempo", tempo=500000))
|
||||
cond.append(MetaMessage("set_tempo", tempo=250000, time=1920))
|
||||
tr = MidiTrack()
|
||||
mid.tracks.append(tr)
|
||||
notes(tr, 0, rng, 12, prog=0)
|
||||
dr = MidiTrack()
|
||||
mid.tracks.append(dr)
|
||||
for k in range(16):
|
||||
dr.append(Message("note_on", channel=9, note=[36, 38, 42, 46][k % 4], velocity=110, time=0 if k == 0 else 120))
|
||||
dr.append(Message("note_off", channel=9, note=[36, 38, 42, 46][k % 4], velocity=0, time=120))
|
||||
cases.append(describe("song", mid))
|
||||
|
||||
json.dump(cases, sys.stdout)
|
||||
@@ -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,61 @@
|
||||
# Audio features of a WAV on stdin (run by tools/fixtures/sf2.py through ctx.python(["numpy"], ...); not a generator).
|
||||
# tests/music/sf2.luau computes the same features from formats-luau's render and compares them:
|
||||
# env RMS of the mono mix per 50 ms window (2205 frames)
|
||||
# bands per 2 s segment: mean power in 24 log-spaced bands (60 Hz .. 16 kHz) of 2048-point Hann frames (hop 1024),
|
||||
# in dB
|
||||
# peaks the strongest frequency (parabolic interpolation) of the mean 8192-point Hann spectrum in a few windows
|
||||
import io, json, sys, wave
|
||||
import numpy as np
|
||||
|
||||
w = wave.open(io.BytesIO(sys.stdin.buffer.read()))
|
||||
rate, ch, width, n = w.getframerate(), w.getnchannels(), w.getsampwidth(), w.getnframes()
|
||||
raw = w.readframes(n)
|
||||
assert width == 2, width
|
||||
x = np.frombuffer(raw, dtype="<i2").astype(np.float64).reshape(-1, ch) / 32768.0
|
||||
mono = x.mean(axis=1)
|
||||
|
||||
ENV = 2205
|
||||
env = [float(np.sqrt(np.mean(mono[i:i + ENV] ** 2))) for i in range(0, len(mono) - ENV + 1, ENV)]
|
||||
|
||||
N, HOP = 2048, 1024
|
||||
edges = [float(e) for e in np.geomspace(60, 16000, 25)]
|
||||
freqs = np.arange(N // 2 + 1) * rate / N
|
||||
han = 0.5 - 0.5 * np.cos(2 * np.pi * np.arange(N) / N)
|
||||
SEGMENTS = [(0, 2), (2, 4), (4, 6), (6, 8), (8, 10), (10, 12)]
|
||||
|
||||
|
||||
def bands(a, b):
|
||||
acc, frames = np.zeros(24), 0
|
||||
for s in range(int(a * rate), int(b * rate) - N + 1, HOP):
|
||||
p = np.abs(np.fft.rfft(mono[s:s + N] * han)) ** 2
|
||||
for k in range(24):
|
||||
acc[k] += p[(freqs >= edges[k]) & (freqs < edges[k + 1])].sum()
|
||||
frames += 1
|
||||
return [float(10 * np.log10(v / max(frames, 1) + 1e-12)) for v in acc]
|
||||
|
||||
|
||||
PN = 8192
|
||||
phan = 0.5 - 0.5 * np.cos(2 * np.pi * np.arange(PN) / PN)
|
||||
WINDOWS = [(4.2, 5.4), (8.05, 8.45), (8.55, 8.95), (2.02, 2.33)]
|
||||
|
||||
|
||||
def peak(a, b):
|
||||
acc = np.zeros(PN // 2 + 1)
|
||||
for s in range(int(a * rate), int(b * rate) - PN + 1, PN // 4):
|
||||
acc += np.abs(np.fft.rfft(mono[s:s + PN] * phan)) ** 2
|
||||
k = int(np.argmax(acc[1:-1])) + 1
|
||||
y0, y1, y2 = np.log(acc[k - 1] + 1e-30), np.log(acc[k] + 1e-30), np.log(acc[k + 1] + 1e-30)
|
||||
d = 0.5 * (y0 - y2) / (y0 - 2 * y1 + y2)
|
||||
return float((k + d) * rate / PN)
|
||||
|
||||
|
||||
json.dump({
|
||||
"rate": rate,
|
||||
"frames": len(mono),
|
||||
"env": env,
|
||||
"edges": edges,
|
||||
"segments": [list(s) for s in SEGMENTS],
|
||||
"bands": [bands(a, b) for a, b in SEGMENTS],
|
||||
"windows": [list(wd) for wd in WINDOWS],
|
||||
"peaks": [peak(a, b) for a, b in WINDOWS],
|
||||
}, sys.stdout)
|
||||
@@ -0,0 +1,495 @@
|
||||
# Tracker fixture helpers (used by tools/fixtures/{mod,s3m,xm,it}.py): small writers for MOD, S3M, XM and IT
|
||||
# (including IT 2.14 / 2.15 sample compression), synthesized samples, reference renders through openmpt123 (nix
|
||||
# libopenmpt) and the comparison features (per 2048-frame block: RMS of left / right / mid and 40 log-spaced band
|
||||
# magnitudes of the mid signal), computed the same way in tests/music/_similar.luau. Every module is generated here
|
||||
# (no third-party files), so the fixtures carry no licence.
|
||||
import json, math, os, struct, subprocess, tempfile
|
||||
|
||||
SR = 44100
|
||||
HOP = 2048
|
||||
BANDS = 40
|
||||
F_LO, F_HI = 150.0, 16000.0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- samples
|
||||
def synth(kind, n, period, amp=0.9, seed=1, decay=None):
|
||||
"""float samples in [-1, 1]: sine / square / saw / tri / noise / pluck"""
|
||||
out = []
|
||||
s = seed
|
||||
for i in range(n):
|
||||
ph = (i % period) / period
|
||||
if kind == "sine":
|
||||
v = math.sin(2 * math.pi * ph)
|
||||
elif kind == "square":
|
||||
v = 1.0 if ph < 0.5 else -1.0
|
||||
elif kind == "saw":
|
||||
v = 2 * ph - 1
|
||||
elif kind == "tri":
|
||||
v = 4 * ph - 1 if ph < 0.5 else 3 - 4 * ph
|
||||
else: # noise
|
||||
s = (s * 1103515245 + 12345) % 2147483648
|
||||
v = (s / 2147483648) * 2 - 1
|
||||
if decay:
|
||||
v *= math.exp(-i / decay)
|
||||
out.append(v * amp)
|
||||
return out
|
||||
|
||||
|
||||
def s8(xs):
|
||||
return bytes((max(-128, min(127, int(round(x * 127)))) & 255) for x in xs)
|
||||
|
||||
|
||||
def u8(xs):
|
||||
return bytes(max(0, min(255, int(round(x * 127)) + 128)) for x in xs)
|
||||
|
||||
|
||||
def s16(xs):
|
||||
return b"".join(struct.pack("<h", max(-32768, min(32767, int(round(x * 32767))))) for x in xs)
|
||||
|
||||
|
||||
def delta8(raw):
|
||||
out, prev = bytearray(), 0
|
||||
for b in raw:
|
||||
v = b - 256 if b >= 128 else b
|
||||
out.append((v - prev) & 255)
|
||||
prev = v
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def delta16(raw):
|
||||
out, prev = bytearray(), 0
|
||||
for i in range(0, len(raw), 2):
|
||||
v = struct.unpack_from("<h", raw, i)[0]
|
||||
out += struct.pack("<H", (v - prev) & 0xFFFF)
|
||||
prev = v
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def name(s, n):
|
||||
b = s.encode()[:n]
|
||||
return b + b"\0" * (n - len(b))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- MOD
|
||||
PERIODS = [1712, 1616, 1524, 1440, 1356, 1280, 1208, 1140, 1076, 1016, 960, 906,
|
||||
856, 808, 762, 720, 678, 640, 604, 570, 538, 508, 480, 453,
|
||||
428, 404, 381, 360, 339, 320, 302, 285, 269, 254, 240, 226,
|
||||
214, 202, 190, 180, 170, 160, 151, 143, 135, 127, 120, 113]
|
||||
|
||||
|
||||
def mod_period(note): # note 1 = C-0; 49 = ProTracker C-2 (428)
|
||||
return PERIODS[note - 25] if note else 0
|
||||
|
||||
|
||||
def write_mod(title, samples, orders, patterns, channels=4, restart=127):
|
||||
"""samples: [{name, data (s8 bytes, even length), volume, finetune (-8..7), loop: (start, length) | None}];
|
||||
patterns: [[row: [(note, ins, fx, param)] * channels] * 64]"""
|
||||
out = bytearray(name(title, 20))
|
||||
for i in range(31):
|
||||
if i < len(samples):
|
||||
s = samples[i]
|
||||
ls, ll = s.get("loop") or (0, 2)
|
||||
out += name(s.get("name", ""), 22) + struct.pack(">HBBHH", len(s["data"]) // 2, s.get("finetune", 0) & 15,
|
||||
s.get("volume", 64), ls // 2, ll // 2)
|
||||
else:
|
||||
out += b"\0" * 22 + struct.pack(">HBBHH", 0, 0, 0, 0, 1)
|
||||
out += bytes([len(orders), restart]) + bytes(orders) + b"\0" * (128 - len(orders))
|
||||
out += b"M.K." if channels == 4 else (b"%dCHN" % channels if channels < 10 else b"%dCH" % channels)
|
||||
for pat in patterns:
|
||||
for row in pat:
|
||||
for (note, ins, fx, param) in row:
|
||||
p = mod_period(note)
|
||||
out += bytes([(ins & 0xF0) | (p >> 8), p & 255, ((ins & 15) << 4) | fx, param])
|
||||
for s in samples:
|
||||
out += s["data"]
|
||||
return bytes(out)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- S3M
|
||||
def write_s3m(title, samples, orders, patterns, channels, speed=6, tempo=125, gvol=64, mvol=48 | 128, pans=None,
|
||||
flags=0, cwt=0x1320, chanset=None):
|
||||
"""samples: [{name, data (u8 bytes), volume, c2spd, loop: (start, end) | None}];
|
||||
patterns: [[row: [(note, ins, vol, cmd, info)] * channels] * 64] with note 0 = none, 254 = cut, else S3M byte
|
||||
(octave << 4 | semitone); vol None = none; cmd 0 = none (A = 1)."""
|
||||
ordn = list(orders) + [255]
|
||||
if len(ordn) % 2:
|
||||
ordn.append(255)
|
||||
nins, npat = len(samples), len(patterns)
|
||||
head = bytearray(name(title, 28) + bytes([0x1A, 16, 0, 0]))
|
||||
head += struct.pack("<HHHHHH", len(ordn), nins, npat, flags, cwt, 2) + b"SCRM"
|
||||
head += bytes([gvol, speed, tempo, mvol, 16, 252 if pans else 0]) + b"\0" * 8 + struct.pack("<H", 0)
|
||||
cs = chanset or [(i % 2) * 8 + i // 2 if i < channels else 255 for i in range(32)]
|
||||
head += bytes(cs[:32] + [255] * (32 - len(cs)))
|
||||
head += bytes(ordn)
|
||||
ptr_at = len(head)
|
||||
head += b"\0" * (2 * (nins + npat))
|
||||
if pans:
|
||||
head += bytes([(0x20 | (p & 15)) for p in pans] + [0] * (32 - len(pans)))
|
||||
body = bytearray(head)
|
||||
|
||||
def align():
|
||||
while len(body) % 16:
|
||||
body.append(0)
|
||||
|
||||
ins_ptrs, pat_ptrs, ins_at = [], [], []
|
||||
for s in samples:
|
||||
align()
|
||||
ins_ptrs.append(len(body) // 16)
|
||||
ins_at.append(len(body))
|
||||
body += b"\0" * 80
|
||||
for pat in patterns:
|
||||
align()
|
||||
pat_ptrs.append(len(body) // 16)
|
||||
pk = bytearray()
|
||||
for row in pat:
|
||||
for ch, (note, ins, vol, cmd, info) in enumerate(row):
|
||||
what = 0
|
||||
if note or ins:
|
||||
what |= 0x20
|
||||
if vol is not None:
|
||||
what |= 0x40
|
||||
if cmd:
|
||||
what |= 0x80
|
||||
if what:
|
||||
pk.append(what | ch)
|
||||
if what & 0x20:
|
||||
pk += bytes([note if note else 255, ins])
|
||||
if what & 0x40:
|
||||
pk.append(vol)
|
||||
if what & 0x80:
|
||||
pk += bytes([cmd, info])
|
||||
pk.append(0)
|
||||
body += struct.pack("<H", len(pk) + 2) + pk
|
||||
for i, s in enumerate(samples):
|
||||
align()
|
||||
seg = len(body) // 16
|
||||
body += s["data"]
|
||||
ls, le = s.get("loop") or (0, 0)
|
||||
h = bytearray(80)
|
||||
h[0] = 1
|
||||
h[1:13] = name(s.get("name", "") + ".smp", 12)
|
||||
h[13] = seg >> 16
|
||||
struct.pack_into("<H", h, 14, seg & 0xFFFF)
|
||||
struct.pack_into("<IIIBBBB", h, 16, len(s["data"]), ls, le, s.get("volume", 64), 0, 0, 1 if s.get("loop") else 0)
|
||||
struct.pack_into("<I", h, 32, s.get("c2spd", 8363))
|
||||
h[48:76] = name(s.get("name", ""), 28)
|
||||
h[76:80] = b"SCRS"
|
||||
body[ins_at[i]:ins_at[i] + 80] = h
|
||||
for k, p in enumerate(ins_ptrs + pat_ptrs):
|
||||
struct.pack_into("<H", body, ptr_at + 2 * k, p)
|
||||
return bytes(body)
|
||||
|
||||
|
||||
def s3m_note(note):
|
||||
"""our note number (1 = C-0, 61 = C-5 IT = S3M C-4) -> the S3M note byte"""
|
||||
n = note - 13
|
||||
return (n // 12) << 4 | (n % 12)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- XM
|
||||
def env_bytes(points):
|
||||
b = bytearray()
|
||||
for (x, y) in points[:12]:
|
||||
b += struct.pack("<HH", x, y)
|
||||
return bytes(b + b"\0" * (48 - len(b)))
|
||||
|
||||
|
||||
def write_xm(title, instruments, orders, patterns, channels, speed=6, tempo=125, linear=True, restart=0):
|
||||
"""instruments: [{name, samples: [{name, data (raw bytes, not delta), bits 8|16, volume, finetune, pan, relnote,
|
||||
loop: (start, length, type 1|2) | None}], keymap: [96 sample indexes] | None, volenv: {points, sustain, loop:
|
||||
(s, e)} | None, panenv: ..., fadeout, vib: (type, sweep, depth, rate)}];
|
||||
patterns: [[row: [(note, ins, vol, fx, param)] * channels]] (note 97 = key off; vol = raw volume byte)"""
|
||||
out = bytearray(b"Extended Module: " + name(title, 20) + b"\x1a" + name("formats-luau fixtures", 20))
|
||||
out += struct.pack("<HIHHHHHHHH", 0x0104, 276, len(orders), restart, channels, len(patterns), len(instruments),
|
||||
1 if linear else 0, speed, tempo)
|
||||
out += bytes(orders) + b"\0" * (256 - len(orders))
|
||||
for pat in patterns:
|
||||
pk = bytearray()
|
||||
for row in pat:
|
||||
for (note, ins, vol, fx, param) in row:
|
||||
flags = 0x80 | (1 if note else 0) | (2 if ins else 0) | (4 if vol else 0) | (8 if fx else 0) | (16 if param else 0)
|
||||
pk.append(flags)
|
||||
for bit, v in ((1, note), (2, ins), (4, vol), (8, fx), (16, param)):
|
||||
if flags & bit:
|
||||
pk.append(v)
|
||||
out += struct.pack("<IBHH", 9, 0, len(pat), len(pk)) + pk
|
||||
for ins in instruments:
|
||||
smps = ins.get("samples", [])
|
||||
if not smps:
|
||||
out += struct.pack("<I", 29) + name(ins.get("name", ""), 22) + struct.pack("<BH", 0, 0)
|
||||
continue
|
||||
h = bytearray(struct.pack("<I", 263) + name(ins.get("name", ""), 22) + struct.pack("<BHI", 0, len(smps), 40))
|
||||
h += bytes(ins.get("keymap") or [0] * 96)
|
||||
ve, pe = ins.get("volenv"), ins.get("panenv")
|
||||
h += env_bytes(ve["points"] if ve else []) + env_bytes(pe["points"] if pe else [])
|
||||
h += bytes([len(ve["points"]) if ve else 0, len(pe["points"]) if pe else 0])
|
||||
for e in (ve, pe):
|
||||
if e:
|
||||
ls, le = e.get("loop") or (0, 0)
|
||||
h += bytes([e.get("sustain", 0) or 0, ls, le])
|
||||
else:
|
||||
h += b"\0\0\0"
|
||||
for e in (ve, pe):
|
||||
t = 0
|
||||
if e:
|
||||
t = 1 | (2 if e.get("sustain") is not None else 0) | (4 if e.get("loop") else 0)
|
||||
h.append(t)
|
||||
vt, vs, vd, vr = ins.get("vib", (0, 0, 0, 0))
|
||||
h += bytes([vt, vs, vd, vr]) + struct.pack("<H", ins.get("fadeout", 0)) + b"\0" * 22
|
||||
out += h
|
||||
for s in smps:
|
||||
bpsm = 2 if s.get("bits", 8) == 16 else 1
|
||||
ls, ll, lt = s.get("loop") or (0, 0, 0)
|
||||
t = lt | (16 if bpsm == 2 else 0)
|
||||
out += struct.pack("<IIIBbBBbB", len(s["data"]), ls * bpsm, ll * bpsm, s.get("volume", 64), s.get("finetune", 0),
|
||||
t, s.get("pan", 128), s.get("relnote", 0), 0) + name(s.get("name", ""), 22)
|
||||
for s in smps:
|
||||
out += delta16(s["data"]) if s.get("bits", 8) == 16 else delta8(s["data"])
|
||||
return bytes(out)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- IT
|
||||
def it_compress(raw, bits, it215):
|
||||
"""IT 2.14 / 2.15 compression with a constant bit width (9 for 8-bit, 17 for 16-bit): valid for every decoder,
|
||||
no width changes"""
|
||||
width = 9 if bits == 8 else 17
|
||||
block = 0x8000 if bits == 8 else 0x4000
|
||||
if bits == 8:
|
||||
vals = [b - 256 if b >= 128 else b for b in raw]
|
||||
else:
|
||||
vals = [struct.unpack_from("<h", raw, i)[0] for i in range(0, len(raw), 2)]
|
||||
mask = (1 << (bits)) - 1
|
||||
out = bytearray()
|
||||
for start in range(0, len(vals), block):
|
||||
chunk = vals[start:start + block]
|
||||
acc, nbits, data = 0, 0, bytearray()
|
||||
d1 = d2 = 0
|
||||
for v in chunk:
|
||||
if it215:
|
||||
nd1 = v - d2 # second-order: the decoder does d1 += x; d2 += d1; out d2
|
||||
x = nd1 - d1
|
||||
d1, d2 = nd1, v
|
||||
else:
|
||||
x = v - d1
|
||||
d1 = v
|
||||
acc |= (x & mask) << nbits
|
||||
nbits += width
|
||||
while nbits >= 8:
|
||||
data.append(acc & 255)
|
||||
acc >>= 8
|
||||
nbits -= 8
|
||||
if nbits:
|
||||
data.append(acc & 255)
|
||||
out += struct.pack("<H", len(data)) + data
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def it_env(e):
|
||||
b = bytearray(82)
|
||||
if e:
|
||||
flags = 1 | (2 if e.get("loop") else 0) | (4 if e.get("sustain") else 0) | (128 if e.get("filter") else 0)
|
||||
b[0] = flags
|
||||
b[1] = len(e["points"])
|
||||
ls, le = e.get("loop") or (0, 0)
|
||||
ss, se = e.get("sustain") or (0, 0)
|
||||
b[2], b[3], b[4], b[5] = ls, le, ss, se
|
||||
for i, (x, y) in enumerate(e["points"][:25]):
|
||||
struct.pack_into("<bH", b, 6 + i * 3, y, x)
|
||||
return bytes(b)
|
||||
|
||||
|
||||
def write_it(title, samples, instruments, orders, patterns, channels, speed=6, tempo=125, gv=128, mv=48, linear=True,
|
||||
old=False, compat=False, pans=None, vols=None, msg=None):
|
||||
"""samples: [{name, data (raw signed bytes), bits, stereo, volume, gv, pan (0..64) | None, c5, loop: (s, e, ping),
|
||||
sus: (s, e, ping), compress: None | 214 | 215, vib: (speed, depth, rate, type)}];
|
||||
instruments: None (sample mode) or [{name, nna, dct, dca, fadeout, gbv, pan | None, pps, ppc, ifc, ifr,
|
||||
keymap: [(note, sample)] * 120, volenv / panenv / pitchenv: {points [(tick, value)], loop, sustain, filter}}];
|
||||
patterns: [[row: [(note, ins, vol, cmd, param)] * channels]] with note 0 = none else IT note + 1 (1 = C-0) or
|
||||
255 off / 254 cut / 253 fade (stored as 246, like IT); vol None or the raw volume byte; cmd 0 = none (A = 1)."""
|
||||
ins_list = instruments or []
|
||||
ordn = list(orders) + [255]
|
||||
flags = 1 | (4 if instruments else 0) | (8 if linear else 0) | (16 if old else 0) | (32 if compat else 0)
|
||||
head = bytearray(b"IMPM" + name(title, 26) + struct.pack("<H", 0x1004))
|
||||
head += struct.pack("<HHHHHHHH", len(ordn), len(ins_list), len(samples), len(patterns), 0x0214, 0x0214, flags, 0)
|
||||
head += bytes([gv, mv, speed, tempo, 128, 0]) + struct.pack("<HII", 0, 0, 0)
|
||||
cp = [(pans[i] if pans and i < len(pans) else 32) if i < channels else 32 + 128 for i in range(64)]
|
||||
head += bytes(cp) + bytes([(vols[i] if vols and i < len(vols) else 64) for i in range(64)])
|
||||
head += bytes(ordn)
|
||||
ptr_at = len(head)
|
||||
head += b"\0" * (4 * (len(ins_list) + len(samples) + len(patterns)))
|
||||
body = bytearray(head)
|
||||
ptrs = []
|
||||
for ins in ins_list:
|
||||
ptrs.append(len(body))
|
||||
b = bytearray(554)
|
||||
b[0:4] = b"IMPI"
|
||||
b[17], b[18], b[19] = ins.get("nna", 0), ins.get("dct", 0), ins.get("dca", 0)
|
||||
struct.pack_into("<H", b, 20, ins.get("fadeout", 0))
|
||||
struct.pack_into("<bB", b, 22, ins.get("pps", 0), ins.get("ppc", 60))
|
||||
b[24] = ins.get("gbv", 128)
|
||||
b[25] = ins["pan"] if ins.get("pan") is not None else 128 + 32
|
||||
b[32:58] = name(ins.get("name", ""), 26)
|
||||
b[58] = ins.get("ifc", 0)
|
||||
b[59] = ins.get("ifr", 0)
|
||||
km = ins["keymap"]
|
||||
for n in range(120):
|
||||
b[64 + 2 * n], b[65 + 2 * n] = km[n]
|
||||
for k, key in enumerate(("volenv", "panenv", "pitchenv")):
|
||||
b[304 + 82 * k:386 + 82 * k] = it_env(ins.get(key))
|
||||
body += b
|
||||
smp_at = []
|
||||
for s in samples:
|
||||
ptrs.append(len(body))
|
||||
smp_at.append(len(body))
|
||||
body += b"\0" * 80
|
||||
for pat in patterns:
|
||||
ptrs.append(len(body))
|
||||
pk = bytearray()
|
||||
for row in pat:
|
||||
for ch, (note, ins, vol, cmd, param) in enumerate(row):
|
||||
mask = (1 if note else 0) | (2 if ins else 0) | (4 if vol is not None else 0) | (8 if cmd else 0)
|
||||
if mask:
|
||||
pk += bytes([(ch + 1) | 128, mask])
|
||||
if note:
|
||||
pk.append(note - 1 if note < 253 else (246 if note == 253 else note))
|
||||
if ins:
|
||||
pk.append(ins)
|
||||
if vol is not None:
|
||||
pk.append(vol)
|
||||
if cmd:
|
||||
pk += bytes([cmd, param])
|
||||
pk.append(0)
|
||||
body += struct.pack("<HHI", len(pk), len(pat), 0) + pk
|
||||
for i, s in enumerate(samples):
|
||||
raw = s["data"]
|
||||
stereo = s.get("stereo", False)
|
||||
bps = 2 if s.get("bits", 8) == 16 else 1
|
||||
frames = len(raw) // bps // (2 if stereo else 1)
|
||||
comp = s.get("compress")
|
||||
if comp:
|
||||
if stereo:
|
||||
half = len(raw) // 2
|
||||
data = it_compress(raw[:half], s.get("bits", 8), comp == 215) + it_compress(raw[half:], s.get("bits", 8), comp == 215)
|
||||
else:
|
||||
data = it_compress(raw, s.get("bits", 8), comp == 215)
|
||||
else:
|
||||
data = raw
|
||||
ptr = len(body)
|
||||
body += data
|
||||
h = bytearray(80)
|
||||
h[0:4] = b"IMPS"
|
||||
fl = 1 | (2 if bps == 2 else 0) | (4 if stereo else 0) | (8 if comp else 0)
|
||||
lp, sp = s.get("loop"), s.get("sus")
|
||||
if lp:
|
||||
fl |= 16 | (64 if lp[2] else 0)
|
||||
if sp:
|
||||
fl |= 32 | (128 if sp[2] else 0)
|
||||
h[17], h[18], h[19] = s.get("gv", 64), fl, s.get("volume", 64)
|
||||
h[20:46] = name(s.get("name", ""), 26)
|
||||
h[46] = 1 | (4 if comp == 215 else 0)
|
||||
h[47] = (s["pan"] | 128) if s.get("pan") is not None else 32
|
||||
struct.pack_into("<IIIIIII", h, 48, frames, lp[0] if lp else 0, lp[1] if lp else 0, s.get("c5", 8363),
|
||||
sp[0] if sp else 0, sp[1] if sp else 0, ptr)
|
||||
vs, vd, vr, vt = s.get("vib", (0, 0, 0, 0))
|
||||
h[76], h[77], h[78], h[79] = vs, vd, vr, vt
|
||||
body[smp_at[i]:smp_at[i] + 80] = h
|
||||
for k, p in enumerate(ptrs):
|
||||
struct.pack_into("<I", body, ptr_at + 4 * k, p)
|
||||
return bytes(body)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- reference render
|
||||
def openmpt(ctx, data, ext, extra=()):
|
||||
"""the module rendered by openmpt123 (linear interpolation, no Amiga resampler): (left, right) float lists"""
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
p = os.path.join(d, "song." + ext)
|
||||
with open(p, "wb") as f:
|
||||
f.write(data)
|
||||
raw = ctx.nix("libopenmpt", ["openmpt123", "--batch", "--quiet", "--stdout", "--samplerate", str(SR),
|
||||
"--channels", "2", "--float", "--filter", "2", "--stereo", "100",
|
||||
"--ctl", "render.resampler.emulate_amiga=0", *extra, p])
|
||||
import array
|
||||
a = array.array("f")
|
||||
a.frombytes(raw[: len(raw) // 8 * 8])
|
||||
return a[0::2], a[1::2]
|
||||
|
||||
|
||||
def fft(re, im):
|
||||
n = len(re)
|
||||
j = 0
|
||||
for i in range(1, n):
|
||||
bit = n >> 1
|
||||
while j & bit:
|
||||
j ^= bit
|
||||
bit >>= 1
|
||||
j |= bit
|
||||
if i < j:
|
||||
re[i], re[j] = re[j], re[i]
|
||||
im[i], im[j] = im[j], im[i]
|
||||
size = 2
|
||||
while size <= n:
|
||||
ang = -2 * math.pi / size
|
||||
wr, wi = math.cos(ang), math.sin(ang)
|
||||
for start in range(0, n, size):
|
||||
cr, ci = 1.0, 0.0
|
||||
half = size // 2
|
||||
for k in range(half):
|
||||
a, b = start + k, start + k + half
|
||||
tr = re[b] * cr - im[b] * ci
|
||||
ti = re[b] * ci + im[b] * cr
|
||||
re[b], im[b] = re[a] - tr, im[a] - ti
|
||||
re[a], im[a] = re[a] + tr, im[a] + ti
|
||||
cr, ci = cr * wr - ci * wi, cr * wi + ci * wr
|
||||
size *= 2
|
||||
|
||||
|
||||
EDGES = [F_LO * (F_HI / F_LO) ** (j / BANDS) for j in range(BANDS + 1)]
|
||||
WINDOW = [0.5 - 0.5 * math.cos(2 * math.pi * i / HOP) for i in range(HOP)]
|
||||
|
||||
|
||||
def features(left, right):
|
||||
"""{frames, rmsL, rmsR, rmsM, bands (frames * BANDS magnitudes)} of a stereo signal"""
|
||||
n = len(left) // HOP
|
||||
out = {"frames": n, "rmsL": [], "rmsR": [], "rmsM": [], "bands": []}
|
||||
for k in range(n):
|
||||
o = k * HOP
|
||||
L, R = left[o:o + HOP], right[o:o + HOP]
|
||||
M = [(a + b) / 2 for a, b in zip(L, R)]
|
||||
out["rmsL"].append(math.sqrt(sum(x * x for x in L) / HOP))
|
||||
out["rmsR"].append(math.sqrt(sum(x * x for x in R) / HOP))
|
||||
out["rmsM"].append(math.sqrt(sum(x * x for x in M) / HOP))
|
||||
re = [M[i] * WINDOW[i] for i in range(HOP)]
|
||||
im = [0.0] * HOP
|
||||
fft(re, im)
|
||||
e = [0.0] * BANDS
|
||||
for b in range(1, HOP // 2):
|
||||
f = b * SR / HOP
|
||||
if f < F_LO or f >= F_HI:
|
||||
continue
|
||||
j = min(BANDS - 1, int(math.log(f / F_LO) / math.log(F_HI / F_LO) * BANDS))
|
||||
e[j] += re[b] * re[b] + im[b] * im[b]
|
||||
out["bands"] += [math.sqrt(x) for x in e]
|
||||
return out
|
||||
|
||||
|
||||
def duration(ctx, data, ext):
|
||||
"""openmpt123 --info's song length in seconds"""
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
p = os.path.join(d, "song." + ext)
|
||||
with open(p, "wb") as f:
|
||||
f.write(data)
|
||||
info = ctx.nix("libopenmpt", ["openmpt123", "--info", p]).decode(errors="replace")
|
||||
for line in info.splitlines():
|
||||
if line.startswith("Duration"):
|
||||
secs = 0.0
|
||||
for part in line.split(":", 1)[1].strip().split(":"):
|
||||
secs = secs * 60 + float(part)
|
||||
return secs
|
||||
raise RuntimeError("openmpt123 --info: no duration")
|
||||
|
||||
|
||||
def reference(ctx, data, ext, extra=()):
|
||||
left, right = openmpt(ctx, data, ext, extra)
|
||||
f = features(left, right)
|
||||
f["duration"] = duration(ctx, data, ext)
|
||||
return f
|
||||
@@ -0,0 +1,122 @@
|
||||
# Shared helpers for the video fixture generators (mkv.py, avi.py, y4m.py, mpegts.py, videoapi.py), loaded by path.
|
||||
# ffmpeg / ffprobe come from PATH when present (a build with libvpx / libopus / libvorbis), else nix (ffmpeg-full).
|
||||
import json, os, shutil, subprocess, zlib
|
||||
|
||||
_FF = None
|
||||
|
||||
|
||||
def ff_prefix():
|
||||
global _FF
|
||||
if _FF is None:
|
||||
if shutil.which("ffmpeg") and shutil.which("ffprobe"):
|
||||
_FF = []
|
||||
else:
|
||||
_FF = ["nix", "shell", "nixpkgs#ffmpeg-full", "-c"]
|
||||
return _FF
|
||||
|
||||
|
||||
def ffmpeg(args, cwd=None, input=None):
|
||||
return subprocess.run(ff_prefix() + ["ffmpeg", "-v", "error", "-y"] + args, cwd=cwd, input=input,
|
||||
capture_output=True, check=True).stdout
|
||||
|
||||
|
||||
def ffprobe_json(path, extra):
|
||||
out = subprocess.run(ff_prefix() + ["ffprobe", "-v", "error", "-of", "json"] + extra + [path],
|
||||
capture_output=True, check=True).stdout
|
||||
return json.loads(out)
|
||||
|
||||
|
||||
def streams(path):
|
||||
"""ffprobe streams: [{index, kind, codec, width, height, rate, channels, time_base}]"""
|
||||
d = ffprobe_json(path, ["-show_streams"])
|
||||
out = []
|
||||
for s in d.get("streams", []):
|
||||
e = {"index": s["index"], "kind": s.get("codec_type", ""), "codec": s.get("codec_name", "")}
|
||||
if "width" in s:
|
||||
e["width"], e["height"] = s["width"], s["height"]
|
||||
if "sample_rate" in s:
|
||||
e["rate"] = int(s["sample_rate"])
|
||||
e["channels"] = s.get("channels", 0)
|
||||
tb = s.get("time_base", "1/1").split("/")
|
||||
e["tbn"], e["tbd"] = int(tb[0]), int(tb[1])
|
||||
out.append(e)
|
||||
return out
|
||||
|
||||
|
||||
def packets(path):
|
||||
"""ffprobe packets in file order: [{stream, pts, dur, key, size, crc}] (pts / dur in the stream time base)"""
|
||||
d = ffprobe_json(path, ["-show_packets", "-show_data_hash", "crc32"])
|
||||
out = []
|
||||
for p in d.get("packets", []):
|
||||
e = {"stream": p["stream_index"], "key": "K" in p.get("flags", ""), "size": int(p["size"]),
|
||||
"crc": int(p["data_hash"].split(":")[1], 16)}
|
||||
if p.get("pts") not in (None, "N/A"):
|
||||
e["pts"] = int(p["pts"])
|
||||
if p.get("duration") not in (None, "N/A"):
|
||||
e["dur"] = int(p["duration"])
|
||||
out.append(e)
|
||||
return out
|
||||
|
||||
|
||||
def yuv_frames(path, w, h, extra=None, codec=None):
|
||||
"""the first video stream decoded by ffmpeg to yuv420p (yuvj420p for MJPEG: full range, no conversion): a list of
|
||||
frame bytes"""
|
||||
pix = "yuvj420p" if codec == "mjpeg" else "yuv420p"
|
||||
raw = ffmpeg(["-i", path] + (extra or []) + ["-map", "0:v:0", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", pix, "-"])
|
||||
n = w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2)
|
||||
return [raw[i:i + n] for i in range(0, len(raw) - n + 1, n)]
|
||||
|
||||
|
||||
def pcm_f32(path, extra=None):
|
||||
"""the first audio stream decoded by ffmpeg to interleaved f32le"""
|
||||
return ffmpeg(["-i", path] + (extra or []) + ["-map", "0:a:0", "-f", "f32le", "-"])
|
||||
|
||||
|
||||
def crc(b):
|
||||
return zlib.crc32(b) & 0xffffffff
|
||||
|
||||
|
||||
def ebml_vint(b, p):
|
||||
"""(value, length) of an EBML vint (marker removed; all ones -> -1)"""
|
||||
first = b[p]
|
||||
n = 1
|
||||
mask = 0x80
|
||||
while n <= 8 and not first & mask:
|
||||
n += 1
|
||||
mask >>= 1
|
||||
v = first & (mask - 1)
|
||||
ones = v == mask - 1
|
||||
for i in range(1, n):
|
||||
v = (v << 8) | b[p + i]
|
||||
ones = ones and b[p + i] == 255
|
||||
return (-1 if ones else v), n
|
||||
|
||||
|
||||
def ebml_id(b, p):
|
||||
first = b[p]
|
||||
n = 1 if first >= 0x80 else 2 if first >= 0x40 else 3 if first >= 0x20 else 4
|
||||
return int.from_bytes(b[p:p + n], "big"), n
|
||||
|
||||
|
||||
def mkv_unknown_clusters(data):
|
||||
"""the same Matroska file with every Cluster's size field rewritten to 'unknown' (same length)"""
|
||||
b = bytearray(data)
|
||||
p = 0
|
||||
# EBML header
|
||||
i, n = ebml_id(b, p)
|
||||
s, m = ebml_vint(b, p + n)
|
||||
p += n + m + s
|
||||
i, n = ebml_id(b, p) # Segment
|
||||
s, m = ebml_vint(b, p + n)
|
||||
p += n + m
|
||||
while p < len(b):
|
||||
i, n = ebml_id(b, p)
|
||||
s, m = ebml_vint(b, p + n)
|
||||
if i == 0x1F43B675:
|
||||
b[p + n] = (0xFF >> (m - 1)) if m < 8 else 0x01
|
||||
for k in range(1, m):
|
||||
b[p + n + k] = 0xFF
|
||||
if m == 1:
|
||||
b[p + n] = 0xFF
|
||||
p += n + m + s
|
||||
return bytes(b)
|
||||
@@ -0,0 +1,53 @@
|
||||
-- tools/fixtures/_video_encode: run by tools/fixtures/videoenc.py (luau, from the repo root) so ffprobe / ffmpeg can
|
||||
-- check our video writers: remuxes and re-encodes the container fixtures (tests/gen/mkv_cases, avi_cases, mp4_cases) and the
|
||||
-- animated GIF of tests/gen/videoenc_src, and prints "<name> <hex>" lines (or "<name> ERR <message>").
|
||||
local F = require("@formats")
|
||||
local Mkv = require("@tests/gen/mkv_cases")
|
||||
local Avi = require("@tests/gen/avi_cases")
|
||||
local Mp4 = require("@tests/gen/mp4_cases")
|
||||
local Src = require("@tests/gen/videoenc_src")
|
||||
|
||||
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 function find(list: any, name: string): string
|
||||
for _, c in list do
|
||||
if c.name == name then
|
||||
return c.data
|
||||
end
|
||||
end
|
||||
error("no fixture " .. name)
|
||||
end
|
||||
|
||||
local JOBS = {
|
||||
{ "remux.webm", find(Mkv, "vp8_opus.webm"), "webm", {} },
|
||||
{ "copy.mkv", find(Mkv, "mjpeg_pcm.mkv"), "mkv", {} },
|
||||
{ "vp8_mjpeg.mkv", find(Mkv, "vp8_opus.webm"), "mkv", { reencode = true, quality = 92 } },
|
||||
{ "copy.avi", find(Avi, "mjpeg_pcm.avi"), "avi", {} },
|
||||
{ "vp8_mjpeg.avi", find(Mkv, "vp8_opus.webm"), "avi", { quality = 92 } },
|
||||
{ "mpeg1_mjpeg.avi", find(Mkv, "mpeg1_mp2.mkv"), "avi", { quality = 92 } },
|
||||
{ "gif.avi", Src.gif, "avi", { quality = 95 } },
|
||||
{ "gif.mkv", Src.gif, "mkv", { quality = 95 } },
|
||||
{ "gif.y4m", Src.gif, "y4m", {} },
|
||||
{ "webm.y4m", find(Mkv, "vp8_opus.webm"), "y4m", {} },
|
||||
{ "gif.mp4", Src.gif, "mp4", { quality = 95 } },
|
||||
{ "pcm.mov", find(Mkv, "mjpeg_pcm.mkv"), "mov", {} },
|
||||
{ "h264_aac.mov", find(Mp4, "h264_aac.mp4"), "mov", {} },
|
||||
{ "h264_aac.mkv", find(Mp4, "h264_aac.mp4"), "mkv", {} },
|
||||
{ "vp8_mjpeg.mp4", find(Mkv, "vp8_opus.webm"), "mp4", { quality = 92 } },
|
||||
{ "flac.mp4", find(Mp4, "mjpeg_flac.mp4"), "mp4", {} },
|
||||
}
|
||||
for _, j in JOBS do
|
||||
local name, data, fmt, opts = j[1], j[2], j[3], j[4]
|
||||
local out, err = F.convert(buffer.fromstring(data), fmt, opts)
|
||||
if out then
|
||||
print(name .. " " .. hex(out))
|
||||
else
|
||||
print(name .. " ERR " .. string.gsub(tostring(err), "%s", "_"))
|
||||
end
|
||||
end
|
||||
@@ -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,152 @@
|
||||
# AVI fixtures (tools/fixtures.py): files made by ffmpeg (MJPEG + PCM with idx1, the same with OpenDML indexes added
|
||||
# here, MJPEG + IMA
|
||||
# ADPCM, MPEG-1 + MP2, uncompressed BGR24 / BGRA / I420 video) and edits made here (the OpenDML indexes renamed to
|
||||
# JUNK so idx1 is used; idx1 renamed too so the movi list is scanned; a truncated file). For each file: ffprobe's
|
||||
# streams and packets, ffmpeg's frames (CRC-32 of yuv420p, or of rgba for uncompressed RGB; the first frames raw for
|
||||
# PSNR checks) and ffmpeg's decoded audio (f32).
|
||||
# tests/gen/avi_cases.luau { { name, data, streams, packets, frames, yuv, rgba, pcm, ... } }
|
||||
import importlib.util, os, tempfile
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("_video_helpers", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_video.py"))
|
||||
V = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(V)
|
||||
|
||||
INPUTS = ["tools/fixtures/_video.py"]
|
||||
|
||||
W, H = 160, 120
|
||||
SRC = ["-f", "lavfi", "-i", "testsrc2=size=%dx%d:rate=10" % (W, H)]
|
||||
|
||||
|
||||
def sine(rate, ch=1):
|
||||
return ["-f", "lavfi", "-i", "sine=frequency=330:sample_rate=%d" % rate, "-ac", str(ch)]
|
||||
|
||||
|
||||
def rename(data, old, new):
|
||||
"""every chunk id `old` renamed to `new` (same length), found by walking the RIFF lists"""
|
||||
b = bytearray(data)
|
||||
|
||||
def walk(p, end):
|
||||
while p + 8 <= end:
|
||||
cid = bytes(b[p:p + 4])
|
||||
size = int.from_bytes(b[p + 4:p + 8], "little")
|
||||
if cid in (b"RIFF", b"LIST"):
|
||||
walk(p + 12, min(end, p + 8 + size))
|
||||
elif cid == old:
|
||||
b[p:p + 4] = new
|
||||
p += 8 + size + (size & 1)
|
||||
walk(0, len(b))
|
||||
return bytes(b)
|
||||
|
||||
|
||||
def chunks(b, p, end):
|
||||
out = []
|
||||
while p + 8 <= end:
|
||||
cid = b[p:p + 4]
|
||||
size = int.from_bytes(b[p + 4:p + 8], "little")
|
||||
out.append((cid, p, size))
|
||||
p += 8 + size + (size & 1)
|
||||
return out
|
||||
|
||||
|
||||
def ck(cid, body):
|
||||
return cid + len(body).to_bytes(4, "little") + body + (b"\0" if len(body) & 1 else b"")
|
||||
|
||||
|
||||
def add_odml(data):
|
||||
"""the same AVI with OpenDML indexes: an indx super index in every strl pointing at an ix## standard index
|
||||
appended to the movi list (built from idx1, which is kept)"""
|
||||
b = data
|
||||
top = chunks(b, 12, len(b))
|
||||
hdrl = next(c for c in top if c[0] == b"LIST" and b[c[1] + 8:c[1] + 12] == b"hdrl")
|
||||
movi = next(c for c in top if c[0] == b"LIST" and b[c[1] + 8:c[1] + 12] == b"movi")
|
||||
idx1 = next(c for c in top if c[0] == b"idx1")
|
||||
movi_base = movi[1] + 8 # the 'movi' fourcc
|
||||
streams = {}
|
||||
for k in range(idx1[2] // 16):
|
||||
e = idx1[1] + 8 + k * 16
|
||||
cid = b[e:e + 4]
|
||||
flags, off, size = (int.from_bytes(b[e + 4 + 4 * i:e + 8 + 4 * i], "little") for i in range(3))
|
||||
sn = int(cid[:2])
|
||||
streams.setdefault(sn, (cid, []))[1].append((movi_base + off + 8, size, bool(flags & 0x10)))
|
||||
n = len([c for c in chunks(b, hdrl[1] + 12, hdrl[1] + 8 + hdrl[2]) if c[0] == b"LIST" and b[c[1] + 8:c[1] + 12] == b"strl"])
|
||||
INDX = 8 + 24 + 16 # one super index entry
|
||||
delta = n * INDX
|
||||
# the ix## chunks at the end of the movi list
|
||||
ixs = []
|
||||
pos = movi[1] + 8 + movi[2] + delta # where the first ix chunk starts (movi grows by them)
|
||||
for sn in range(n):
|
||||
cid, ents = streams.get(sn, (b"%02dwb" % sn, []))
|
||||
body = (2).to_bytes(2, "little") + bytes([0, 1]) + len(ents).to_bytes(4, "little") + cid + \
|
||||
(0).to_bytes(8, "little") + bytes(4)
|
||||
for off, size, key in ents:
|
||||
body += (off + delta).to_bytes(4, "little") + (size | (0 if key else 0x80000000)).to_bytes(4, "little")
|
||||
chunk = ck(b"ix%02d" % sn, body)
|
||||
ixs.append((pos, len(chunk), len(ents), cid, chunk))
|
||||
pos += len(chunk)
|
||||
# hdrl with an indx in every strl
|
||||
out_h = b""
|
||||
si = 0
|
||||
for c in chunks(b, hdrl[1] + 12, hdrl[1] + 8 + hdrl[2]):
|
||||
raw = b[c[1]:c[1] + 8 + c[2] + (c[2] & 1)]
|
||||
if c[0] == b"LIST" and b[c[1] + 8:c[1] + 12] == b"strl":
|
||||
p, ln, cnt, cid, _ = ixs[si]
|
||||
indx = (4).to_bytes(2, "little") + bytes([0, 0]) + (1).to_bytes(4, "little") + cid + bytes(12) + \
|
||||
p.to_bytes(8, "little") + ln.to_bytes(4, "little") + cnt.to_bytes(4, "little")
|
||||
raw = ck(b"LIST", b[c[1] + 8:c[1] + 8 + c[2]] + ck(b"indx", indx))
|
||||
si += 1
|
||||
out_h += raw
|
||||
out = b""
|
||||
for c in top:
|
||||
if c is hdrl:
|
||||
out += ck(b"LIST", b"hdrl" + out_h)
|
||||
elif c is movi:
|
||||
out += ck(b"LIST", b[c[1] + 8:c[1] + 8 + c[2]] + b"".join(x[4] for x in ixs))
|
||||
else:
|
||||
out += b[c[1]:c[1] + 8 + c[2] + (c[2] & 1)]
|
||||
res = b"RIFF" + (len(out) + 4).to_bytes(4, "little") + b"AVI " + out
|
||||
assert res[ixs[0][0]:ixs[0][0] + 2] == b"ix", "odml layout"
|
||||
return res
|
||||
|
||||
|
||||
def case(tmp, name, rgba=False, raw_frames=2, pcm_frames=8192):
|
||||
path = os.path.join(tmp, name)
|
||||
c = {"name": name, "data": open(path, "rb").read(), "streams": V.streams(path), "packets": V.packets(path)}
|
||||
vs = [s for s in c["streams"] if s["kind"] == "video"]
|
||||
if vs:
|
||||
w, h = vs[0]["width"], vs[0]["height"]
|
||||
if rgba:
|
||||
raw = V.ffmpeg(["-i", path, "-map", "0:v:0", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "rgba", "-"])
|
||||
n = w * h * 4
|
||||
c["rgba"] = [V.crc(raw[i:i + n]) for i in range(0, len(raw) - n + 1, n)]
|
||||
else:
|
||||
frames = V.yuv_frames(path, w, h, codec=vs[0]["codec"])
|
||||
c["frames"] = [V.crc(f) for f in frames]
|
||||
c["yuv"] = frames[:raw_frames]
|
||||
if any(s["kind"] == "audio" for s in c["streams"]):
|
||||
pcm = V.pcm_f32(path)
|
||||
c["pcm"] = pcm[:pcm_frames * 4]
|
||||
c["pcmBytes"] = len(pcm)
|
||||
return c
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
tmp = tempfile.mkdtemp(prefix="avifx_")
|
||||
ff = lambda *a: V.ffmpeg(list(a), cwd=tmp)
|
||||
ff(*SRC, *sine(44100, 2), "-t", "1", "-c:v", "mjpeg", "-q:v", "3", "-c:a", "pcm_s16le", "mjpeg_pcm.avi")
|
||||
ff(*SRC, *sine(22050), "-t", "1", "-c:v", "mjpeg", "-q:v", "5", "-c:a", "adpcm_ima_wav", "mjpeg_ima.avi")
|
||||
ff(*SRC, *sine(44100), "-t", "1", "-r", "25", "-c:v", "mpeg1video", "-b:v", "500k", "-c:a", "mp2", "mpeg1_mp2.avi")
|
||||
ff(*SRC, "-t", "0.5", "-c:v", "rawvideo", "-pix_fmt", "bgr24", "bgr24.avi")
|
||||
ff(*SRC, "-t", "0.5", "-c:v", "rawvideo", "-pix_fmt", "bgra", "bgra.avi")
|
||||
ff(*SRC, "-t", "0.5", "-c:v", "rawvideo", "-pix_fmt", "yuv420p", "i420.avi")
|
||||
ff(*SRC, *sine(8000), "-t", "1", "-c:v", "mjpeg", "-c:a", "pcm_u8", "pcm_u8.avi")
|
||||
full = open(os.path.join(tmp, "mjpeg_pcm.avi"), "rb").read()
|
||||
idx1 = rename(full, b"indx", b"JUNK")
|
||||
open(os.path.join(tmp, "idx1_only.avi"), "wb").write(idx1)
|
||||
open(os.path.join(tmp, "no_index.avi"), "wb").write(rename(idx1, b"idx1", b"JUNK"))
|
||||
open(os.path.join(tmp, "odml.avi"), "wb").write(add_odml(full))
|
||||
cases = [case(tmp, "mjpeg_pcm.avi"), case(tmp, "mjpeg_ima.avi"), case(tmp, "mpeg1_mp2.avi"),
|
||||
case(tmp, "bgr24.avi", rgba=True), case(tmp, "bgra.avi", rgba=True), case(tmp, "i420.avi"),
|
||||
case(tmp, "pcm_u8.avi"), case(tmp, "idx1_only.avi"), case(tmp, "no_index.avi"),
|
||||
case(tmp, "odml.avi")]
|
||||
cases.append({"name": "truncated.avi", "data": full[: len(full) * 6 // 10], "truncated": True})
|
||||
ctx.emit("avi_cases", cases)
|
||||
@@ -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,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,192 @@
|
||||
# IT fixtures (tools/fixtures.py): generated Impulse Tracker modules exercising instruments (new note actions,
|
||||
# duplicate checks, envelopes, filters, sustain loops, auto-vibrato, keymaps), sample mode with the IT effects, Amiga
|
||||
# slides with old effects, and IT 2.14 / 2.15 compressed, 16-bit and stereo samples, rendered by openmpt123.
|
||||
# tests/gen/it_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py),
|
||||
# duration (openmpt's song length), plain (for "compressed": the same song uncompressed) }
|
||||
import os, sys
|
||||
|
||||
# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml)
|
||||
T = sys.modules.get("_tracker")
|
||||
if T is None:
|
||||
import importlib.util
|
||||
_spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py"))
|
||||
T = importlib.util.module_from_spec(_spec)
|
||||
sys.modules["_tracker"] = T
|
||||
_spec.loader.exec_module(T)
|
||||
|
||||
INPUTS = ["tools/fixtures/_tracker.py"]
|
||||
|
||||
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, Tt, U, V, W, X, Y, Z = range(1, 27)
|
||||
OFF, CUT, FADE = 255, 254, 253
|
||||
|
||||
|
||||
def empty(ch, rows=64):
|
||||
return [[(0, 0, None, 0, 0) for _ in range(ch)] for _ in range(rows)]
|
||||
|
||||
|
||||
def put(p, row, ch, note=0, ins=0, vol=None, cmd=0, param=0):
|
||||
p[row][ch] = (note, ins, vol, cmd, param)
|
||||
|
||||
|
||||
def samples(compress=None):
|
||||
return [
|
||||
{"name": "sine", "data": T.s8(T.synth("sine", 64, 64)), "volume": 64, "c5": 8363, "loop": (0, 64, False), "compress": compress},
|
||||
{"name": "square", "data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 48, "c5": 16726, "loop": (0, 64, False), "gv": 48},
|
||||
{"name": "saw16", "data": T.s16(T.synth("saw", 128, 64, 0.6)), "bits": 16, "volume": 64, "c5": 11025, "loop": (0, 128, False),
|
||||
"compress": compress},
|
||||
{"name": "noise", "data": T.s8(T.synth("noise", 6000, 1, 0.7, decay=1500)), "volume": 60, "c5": 8363, "pan": 16},
|
||||
{"name": "ping sus", "data": T.s8(T.synth("tri", 400, 50, 0.8)), "volume": 64, "c5": 9000, "sus": (100, 300, True),
|
||||
"loop": (0, 400, False), "vib": (8, 16, 4, 0)},
|
||||
{"name": "stereo", "data": T.s16(T.synth("sine", 256, 32, 0.6) + T.synth("saw", 256, 64, 0.5)), "bits": 16, "stereo": True,
|
||||
"volume": 56, "c5": 8363, "loop": (0, 256, True), "compress": compress},
|
||||
{"name": "pluck", "data": T.s8(T.synth("saw", 3000, 40, 0.8, decay=900)), "volume": 64, "c5": 8363},
|
||||
]
|
||||
|
||||
|
||||
def keymap(sample, transpose=0, split=None):
|
||||
km = []
|
||||
for n in range(120):
|
||||
smp = sample if split is None or n < split[0] else split[1]
|
||||
km.append((max(0, min(119, n + transpose)), smp))
|
||||
return km
|
||||
|
||||
|
||||
def instruments():
|
||||
return [
|
||||
{"name": "nna cont", "nna": 1, "fadeout": 256, "keymap": keymap(7),
|
||||
"volenv": {"points": [(0, 64), (10, 48), (40, 0)]}},
|
||||
{"name": "nna off", "nna": 2, "fadeout": 128, "keymap": keymap(1),
|
||||
"volenv": {"points": [(0, 0), (3, 64), (8, 40), (20, 30)], "sustain": (2, 3)}},
|
||||
{"name": "nna fade dct", "nna": 3, "dct": 1, "dca": 0, "fadeout": 64, "keymap": keymap(2)},
|
||||
{"name": "pan pitch", "fadeout": 512, "keymap": keymap(3, 12), "pan": 48, "pps": 16, "ppc": 60,
|
||||
"panenv": {"points": [(0, -32), (16, 32), (32, -32)], "loop": (0, 2)},
|
||||
"pitchenv": {"points": [(0, 0), (10, 12), (20, -12), (30, 0)], "loop": (1, 2)}},
|
||||
{"name": "filter", "keymap": keymap(3), "ifc": 128 + 40, "ifr": 128 + 64, "fadeout": 300,
|
||||
"pitchenv": {"points": [(0, -32), (30, 32), (60, -32)], "loop": (0, 2), "filter": True}},
|
||||
{"name": "sus loop", "keymap": keymap(5), "fadeout": 400, "gbv": 96},
|
||||
{"name": "split stereo", "keymap": keymap(6, 0, (60, 1)), "fadeout": 200,
|
||||
"volenv": {"points": [(0, 64), (5, 32), (10, 64), (15, 32)], "sustain": (0, 3), "loop": (1, 2)}},
|
||||
]
|
||||
|
||||
|
||||
def song_instruments(compress=None):
|
||||
a, b = empty(5), empty(5)
|
||||
# new note actions: continue / note off / fade, with the duplicate check cutting same-note repeats
|
||||
for i, n in enumerate((61, 64, 68, 73)):
|
||||
put(a, i * 4, 0, n, 1)
|
||||
put(a, i * 4, 1, n - 12, 2)
|
||||
put(a, 16, 1, 0, 0, None, S, 0x71)
|
||||
put(a, 20, 1, 49, 2)
|
||||
put(a, 22, 1, 0, 0, None, S, 0x73)
|
||||
put(a, 24, 1, 56, 2)
|
||||
put(a, 28, 1, OFF)
|
||||
for r in (0, 4, 8, 9, 12, 16):
|
||||
put(a, r, 2, 61 if r != 12 else 64, 3)
|
||||
put(a, 20, 2, 0, 0, None, S, 0x70)
|
||||
put(a, 24, 2, 61, 3, None, S, 0x75)
|
||||
put(a, 26, 2, 66, 3)
|
||||
put(a, 30, 2, FADE)
|
||||
# panning / pitch envelopes, pitch-pan separation, instrument pan
|
||||
put(a, 32, 0, 37, 4)
|
||||
put(a, 32, 1, 61, 4)
|
||||
put(a, 40, 1, 73, 4, None, S, 0x7B)
|
||||
put(a, 44, 1, 0, 0, None, S, 0x7C)
|
||||
put(a, 48, 0, OFF)
|
||||
put(a, 56, 1, CUT)
|
||||
# filters: instrument cutoff + resonance, filter envelope, Zxx
|
||||
put(a, 36, 3, 49, 5)
|
||||
put(a, 44, 3, 0, 0, None, Z, 0x20)
|
||||
put(a, 48, 3, 0, 0, None, Z, 0x60)
|
||||
put(a, 52, 3, 0, 0, None, Z, 0x88)
|
||||
put(a, 60, 3, OFF)
|
||||
# sustain loop + ping-pong, auto-vibrato, instrument global volume, a stereo / mono key split
|
||||
put(b, 0, 0, 61, 6)
|
||||
put(b, 16, 0, OFF)
|
||||
put(b, 0, 1, 49, 7)
|
||||
put(b, 8, 1, 73, 7)
|
||||
put(b, 16, 1, 49, 7, 32)
|
||||
put(b, 24, 1, OFF)
|
||||
put(b, 32, 1, 85, 7)
|
||||
put(b, 8, 4, 61, 1, None, H, 0x44)
|
||||
put(b, 12, 4, 61, 1, None, S, 0x77)
|
||||
put(b, 20, 4, 0, 0, None, S, 0x78)
|
||||
put(b, 40, 4, 61, 3, 0, M, 0x20)
|
||||
put(b, 44, 4, 0, 0, None, N, 0x04)
|
||||
put(b, 48, 4, 0, 0, None, N, 0x30)
|
||||
return T.write_it("instruments", samples(compress), instruments(), [0, 1], [a, b], 5, speed=5, tempo=135,
|
||||
pans=[16, 48, 32, 32, 40], mv=64)
|
||||
|
||||
|
||||
def song_effects(linear=True, old=False, compat=False):
|
||||
a, b = empty(4), empty(4)
|
||||
put(a, 0, 0, 61, 1, 48, D, 0x00)
|
||||
put(a, 4, 0, 0, 0, 70)
|
||||
put(a, 5, 0, 0, 0, 80)
|
||||
put(a, 8, 0, 0, 0, 88)
|
||||
put(a, 12, 0, 0, 0, 99)
|
||||
put(a, 16, 0, 0, 0, 110)
|
||||
put(a, 20, 0, 0, 0, 120)
|
||||
put(a, 24, 0, 49, 0, 196)
|
||||
put(a, 28, 0, 0, 0, 205, H, 0x46)
|
||||
put(a, 32, 0, 0, 0, 160)
|
||||
put(a, 36, 0, 0, 0, None, Y, 0x48)
|
||||
put(a, 44, 0, 0, 0, None, P, 0x08)
|
||||
put(a, 48, 0, 0, 0, None, P, 0x30)
|
||||
put(a, 52, 0, 0, 0, None, P, 0xF4)
|
||||
put(a, 56, 0, 0, 0, None, X, 0xC0)
|
||||
put(a, 0, 1, 49, 2, None, E, 0x04)
|
||||
put(a, 4, 1, 0, 0, None, F, 0x10)
|
||||
put(a, 8, 1, 0, 0, None, E, 0xF8)
|
||||
put(a, 9, 1, 0, 0, None, F, 0xE8)
|
||||
put(a, 12, 1, 49, 2, None, G, 0x08)
|
||||
put(a, 13, 1, 61, 0, None, G, 0x00)
|
||||
put(a, 16, 1, 0, 0, None, E, 0x00)
|
||||
put(a, 20, 1, 56, 2, None, J, 0x37)
|
||||
put(a, 24, 1, 0, 0, None, U, 0x88)
|
||||
put(a, 28, 1, 0, 0, None, R, 0x46)
|
||||
put(a, 32, 1, 0, 0, None, I, 0x31)
|
||||
put(a, 36, 1, 0, 0, None, Q, 0x84)
|
||||
put(a, 40, 1, 0, 0, None, K, 0x02)
|
||||
put(a, 44, 1, 49, 2, None, L, 0x20)
|
||||
put(a, 48, 1, 0, 0, None, O, 0x00)
|
||||
put(a, 52, 1, 61, 4, None, O, 0x04)
|
||||
put(a, 56, 1, 61, 4, None, S, 0xD3)
|
||||
put(a, 60, 1, 61, 4, None, S, 0xC2)
|
||||
put(a, 0, 2, 37, 3, None, V, 0x60)
|
||||
put(a, 8, 2, 0, 0, None, W, 0x04)
|
||||
put(a, 16, 2, 0, 0, None, W, 0x60)
|
||||
put(a, 24, 2, 0, 0, None, Tt, 0x10 + 0x06)
|
||||
put(a, 28, 2, 0, 0, None, Tt, 0x04)
|
||||
put(a, 32, 2, 0, 0, None, Tt, 0x90)
|
||||
put(a, 36, 2, 0, 0, None, S, 0xB0)
|
||||
put(a, 38, 2, 0, 0, None, S, 0xB1)
|
||||
put(a, 40, 2, 0, 0, None, S, 0xE2)
|
||||
put(a, 44, 2, 0, 0, None, S, 0x63)
|
||||
put(a, 48, 2, 0, 0, None, A, 0x04)
|
||||
put(a, 52, 2, 0, 0, None, M, 0x30)
|
||||
put(a, 56, 2, 0, 0, None, N, 0x02)
|
||||
put(a, 0, 3, 73, 7, None, S, 0x91)
|
||||
put(a, 16, 3, 73, 7, None, X, 0x40)
|
||||
put(a, 32, 3, 61, 3, None, S, 0x8C)
|
||||
put(b, 0, 0, 61, 1)
|
||||
put(b, 0, 1, 64, 2)
|
||||
put(b, 0, 2, 68, 3)
|
||||
put(b, 8, 0, CUT)
|
||||
put(b, 12, 1, OFF)
|
||||
put(b, 16, 2, FADE)
|
||||
put(b, 20, 3, 61, 7, None, B, 0x01)
|
||||
return T.write_it("effects", samples(), None, [0, 1], [a, b], 4, speed=4, tempo=140, linear=linear, old=old,
|
||||
compat=compat, pans=[0, 64, 20, 44], vols=[64, 48, 64, 56], gv=112, mv=80)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
cases = []
|
||||
plain = song_instruments()
|
||||
for nm, data in (("instruments", plain), ("effects", song_effects()), ("amiga old", song_effects(False, True, True)),
|
||||
("compressed 2.14", song_instruments(214)), ("compressed 2.15", song_instruments(215))):
|
||||
ref = T.reference(ctx, data, "it")
|
||||
c = {"name": nm, "data": data, "ref": ref, "duration": ref["duration"]}
|
||||
if nm.startswith("compressed"):
|
||||
c["plain"] = plain
|
||||
cases.append(c)
|
||||
ctx.emit("it_cases", cases)
|
||||
@@ -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,72 @@
|
||||
# MIDI fixtures (tools/fixtures.py). Reference parses from python mido (tools/fixtures/_midi_ref.py, run in a nix
|
||||
# python with mido) plus hand-made byte strings for what mido does not write.
|
||||
# tests/gen/midi_cases.luau { { name, data, type, division, tracks = { { {tick, type, channel, data, meta} } },
|
||||
# length?, times?, exact? } }: channel / meta = -1 when absent; exact = the bytes are
|
||||
# what an encoder with running status writes (mido's own output)
|
||||
# tests/gen/midi_bad.luau { { name, data, code } }: crafted bad files and the Err code expected
|
||||
# tests/gen/midi_trunc.luau { name, data }: a mido file cut short (lenient decode keeps the events, strict fails)
|
||||
import json, struct
|
||||
|
||||
INPUTS = ["tools/fixtures/_midi_ref.py"]
|
||||
|
||||
|
||||
def vlq(v):
|
||||
out = [v & 127]
|
||||
v >>= 7
|
||||
while v:
|
||||
out.insert(0, (v & 127) | 128)
|
||||
v >>= 7
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def smf(tracks, fmt=0, division=96, extra=b""):
|
||||
out = b"MThd" + struct.pack(">IHHh", 6, fmt, len(tracks), division) + extra
|
||||
for body in tracks:
|
||||
out += b"MTrk" + struct.pack(">I", len(body)) + body
|
||||
return out
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
ref = json.loads(ctx.python(["mido"], ctx.read("tools/fixtures/_midi_ref.py").decode()))
|
||||
cases = []
|
||||
by_name = {}
|
||||
for c in ref:
|
||||
case = {"name": c["name"], "data": bytes.fromhex(c["hex"]), "type": c["type"], "division": c["division"],
|
||||
"tracks": c["tracks"], "exact": True}
|
||||
if "length" in c:
|
||||
case["length"] = c["length"]
|
||||
case["times"] = c["times"]
|
||||
cases.append(case)
|
||||
by_name[c["name"]] = case
|
||||
|
||||
# running status across meta and escape events (mido's writer never relies on it), and an F7 escape
|
||||
body = (b"\x00\x90\x3c\x40" + b"\x00\xff\x01\x01\x41" + b"\x10\x3c\x00" + b"\x00\xf7\x02\xf3\x01" + b"\x05\x3e\x7f"
|
||||
+ b"\x00\xff\x2f\x00")
|
||||
cases.append({"name": "running-after-meta", "data": smf([body]), "type": 0, "division": 96, "exact": False, "tracks": [[
|
||||
[0, "noteOn", 0, [60, 64], -1], [0, "meta", -1, [0x41], 1], [16, "noteOn", 0, [60, 0], -1],
|
||||
[16, "escape", -1, [0xF3, 0x01], -1], [21, "noteOn", 0, [62, 127], -1], [21, "meta", -1, [], 0x2F]]]})
|
||||
# an unknown chunk between MThd and MTrk, a longer MThd, and an RMID wrapper
|
||||
f0 = by_name["format0"]
|
||||
raw = f0["data"]
|
||||
hdr, rest = raw[:14], raw[14:]
|
||||
cases.append(dict(f0, name="unknown-chunk", exact=False, data=hdr + b"XFIH" + struct.pack(">I", 5) + b"abcde" + rest))
|
||||
long_hdr = b"MThd" + struct.pack(">I", 8) + raw[8:14] + b"\x00\x00" + rest
|
||||
cases.append(dict(f0, name="long-mthd", exact=False, data=long_hdr))
|
||||
riff = b"RMID" + b"data" + struct.pack("<I", len(raw)) + raw + (b"\x00" if len(raw) % 2 else b"")
|
||||
cases.append(dict(f0, name="rmid", exact=False, data=b"RIFF" + struct.pack("<I", len(riff)) + riff))
|
||||
ctx.emit("midi_cases", cases)
|
||||
|
||||
bad = [
|
||||
{"name": "not-midi", "data": b"MTrk\x00\x00\x00\x00", "code": "CORRUPT"},
|
||||
{"name": "data-over-127", "data": smf([b"\x00\x90\x3c\x80\x00\xff\x2f\x00"]), "code": "CORRUPT"},
|
||||
{"name": "running-without-status", "data": smf([b"\x00\x3c\x40\x00\xff\x2f\x00"]), "code": "CORRUPT"},
|
||||
{"name": "long-delta", "data": smf([b"\x81\x81\x81\x81\x01\x90\x3c\x40"]), "code": "CORRUPT"},
|
||||
{"name": "format-3", "data": b"MThd" + struct.pack(">IHHh", 6, 3, 0, 96), "code": "UNSUPPORTED"},
|
||||
{"name": "zero-division", "data": b"MThd" + struct.pack(">IHHh", 6, 0, 0, 0), "code": "CORRUPT"},
|
||||
{"name": "short-header", "data": b"MThd\x00\x00\x00\x06\x00", "code": "TRUNCATED"},
|
||||
{"name": "system-common", "data": smf([b"\x00\xf2\x01\x02"]), "code": "CORRUPT"},
|
||||
{"name": "rmid-without-data", "data": b"RIFF\x0c\x00\x00\x00RMIDLIST\x00\x00\x00\x00", "code": "CORRUPT"},
|
||||
]
|
||||
ctx.emit("midi_bad", bad)
|
||||
f1 = by_name["format1"]["data"]
|
||||
ctx.emit("midi_trunc", {"name": "format1-cut", "data": f1[: len(f1) * 3 // 5]})
|
||||
@@ -0,0 +1,317 @@
|
||||
# Motion-JPEG fixtures for codecs/Jpeg (tools/fixtures.py): ffmpeg's mjpeg encoder (testsrc2 / mandelbrot sources,
|
||||
# yuvj420p / yuvj422p / yuvj444p, odd sizes) split into its JPEG frames, and references for each frame:
|
||||
# yuv CRC-32 of the yuv420p planes codecs/Jpeg must produce with { yuv = true }: libjpeg-turbo's own IDCT planes
|
||||
# (TurboJPEG tj3DecompressToYUV8 through ctypes, the islow IDCT), cropped, 4:2:2 chroma row pairs averaged
|
||||
# ((a + b + 1) >> 1), 4:4:4 chroma 2 x 2 averaged ((a + b + c + d + 2) >> 2): bit-exact
|
||||
# rgba CRC-32 of djpeg -dct int (bit-exact)
|
||||
# ff for the first frame of each stream: ffmpeg's own decode as yuvj420p and rgba (PSNR thresholds: ffmpeg's
|
||||
# IDCT and its swscale conversions differ from libjpeg's; rgba for the small streams and one 320x240)
|
||||
# Variants: frames written with ffmpeg's default (annex K) Huffman tables and their DHT segments stripped, as
|
||||
# Motion-JPEG in AVI leaves them out; an AVI1 APP0 segment and junk after EOI; an interlaced frame (two fields,
|
||||
# each its own half-height JPEG with an AVI1 segment of polarity 1, back to back).
|
||||
# tests/gen/mjpeg_cases.luau { streams = { { name, width, height, sampling, frames = { { data, yuv, rgba } },
|
||||
# ff = { yuv, rgba? } } }, fields = { data, width, height, yuv, rgba, src } }
|
||||
# tests/gen/mjpeg_enc.luau yuv420p sources and what tj3CompressFromYUV8 writes for them at a quality (our
|
||||
# encoder must write the same bytes), with djpeg's CRC and ffmpeg's PSNR of that file
|
||||
# tests/gen/mjpeg_bench.luau 320x240 and 640x480 frames (4:2:0, 4:2:2) and yuv420p sources
|
||||
# Binary fields are base64 (JPEG data) or base64 of zlib data (raw planes / pixels, inflated with codecs/Deflate):
|
||||
# Luau string literals of binary data cost ~3.7 bytes per byte, base64 1.33.
|
||||
import base64, ctypes, math, os, shutil, subprocess, tempfile, zlib
|
||||
|
||||
FF = ["-hide_banner", "-loglevel", "error", "-y"]
|
||||
|
||||
|
||||
def b64(b):
|
||||
return base64.b64encode(b).decode()
|
||||
|
||||
|
||||
def z64(b):
|
||||
return base64.b64encode(zlib.compress(b, 9)).decode()
|
||||
|
||||
|
||||
def tool(ctx, pkg, name):
|
||||
p = shutil.which(name)
|
||||
if p:
|
||||
return p
|
||||
return ctx.nix(pkg, ["sh", "-c", "command -v " + name]).decode().strip()
|
||||
|
||||
|
||||
def store(attr):
|
||||
return subprocess.run(["nix", "build", "nixpkgs#" + attr, "--no-link", "--print-out-paths"], check=True,
|
||||
capture_output=True, text=True).stdout.strip().split("\n")[0]
|
||||
|
||||
|
||||
class TurboJpeg:
|
||||
"""the TurboJPEG 3 API (libjpeg-turbo) through ctypes: raw YUV planes in and out"""
|
||||
|
||||
def __init__(self):
|
||||
lib = ctypes.CDLL(os.path.join(store("libjpeg_turbo.out"), "lib", "libturbojpeg.so"))
|
||||
lib.tj3Init.restype = ctypes.c_void_p
|
||||
lib.tj3Init.argtypes = [ctypes.c_int]
|
||||
lib.tj3Set.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int]
|
||||
lib.tj3Get.argtypes = [ctypes.c_void_p, ctypes.c_int]
|
||||
lib.tj3DecompressHeader.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t]
|
||||
lib.tj3DecompressToYUV8.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t, ctypes.c_char_p, ctypes.c_int]
|
||||
lib.tj3CompressFromYUV8.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int, ctypes.c_int, ctypes.c_int,
|
||||
ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(ctypes.c_size_t)]
|
||||
lib.tj3Free.argtypes = [ctypes.c_void_p]
|
||||
self.lib = lib
|
||||
self.dec = lib.tj3Init(1)
|
||||
self.enc = lib.tj3Init(0)
|
||||
|
||||
def planes(self, jpeg):
|
||||
"""-> w, h, subsamp (0 444, 1 422, 2 420), Y, Cb, Cr (TurboJPEG's unpadded-alignment plane layout)"""
|
||||
L = self.lib
|
||||
assert L.tj3DecompressHeader(self.dec, jpeg, len(jpeg)) == 0
|
||||
w, h, ss = L.tj3Get(self.dec, 5), L.tj3Get(self.dec, 6), L.tj3Get(self.dec, 4)
|
||||
mw, mh = {0: (1, 1), 1: (2, 1), 2: (2, 2)}[ss]
|
||||
pw, ph = -(-w // mw) * mw, -(-h // mh) * mh
|
||||
cw, ch = pw // mw, ph // mh
|
||||
out = ctypes.create_string_buffer(pw * ph + 2 * cw * ch)
|
||||
assert L.tj3DecompressToYUV8(self.dec, jpeg, len(jpeg), out, 1) == 0
|
||||
raw = out.raw
|
||||
return w, h, ss, (raw[:pw * ph], pw), (raw[pw * ph:pw * ph + cw * ch], cw, ch), (raw[pw * ph + cw * ch:], cw, ch)
|
||||
|
||||
def yuv420(self, jpeg):
|
||||
"""what codecs/Jpeg { yuv = true } must produce for this frame"""
|
||||
w, h, ss, (Y, pw), cb, cr = self.planes(jpeg)
|
||||
out = bytearray()
|
||||
for y in range(h):
|
||||
out += Y[y * pw:y * pw + w]
|
||||
ow, oh = (w + 1) // 2, (h + 1) // 2
|
||||
for P, cw, ch in (cb, cr):
|
||||
for y in range(oh):
|
||||
if ss == 2:
|
||||
out += P[y * cw:y * cw + ow]
|
||||
elif ss == 1:
|
||||
a = P[2 * y * cw:2 * y * cw + ow]
|
||||
b = P[(2 * y + 1) * cw:(2 * y + 1) * cw + ow] if 2 * y + 1 < ch else a
|
||||
out += bytes((p + q + 1) >> 1 for p, q in zip(a, b))
|
||||
else:
|
||||
r0 = P[2 * y * cw:2 * y * cw + cw]
|
||||
r1 = P[(2 * y + 1) * cw:(2 * y + 1) * cw + cw] if 2 * y + 1 < ch else r0
|
||||
row = bytearray()
|
||||
for x in range(ow):
|
||||
x1 = min(2 * x + 1, w - 1)
|
||||
row.append((r0[2 * x] + r0[x1] + r1[2 * x] + r1[x1] + 2) >> 2)
|
||||
out += row
|
||||
return bytes(out)
|
||||
|
||||
def compress420(self, yuv, w, h, quality):
|
||||
"""yuv420p (w x h luma) -> tj3CompressFromYUV8's JPEG; TurboJPEG wants the luma plane padded to even sizes"""
|
||||
pw, ph = w + (w & 1), h + (h & 1)
|
||||
Y = yuv[:w * h]
|
||||
buf = bytearray()
|
||||
for y in range(ph):
|
||||
r = Y[min(y, h - 1) * w:min(y, h - 1) * w + w]
|
||||
buf += r + r[-1:] * (pw - w)
|
||||
buf += yuv[w * h:]
|
||||
L = self.lib
|
||||
L.tj3Set(self.enc, 3, quality)
|
||||
L.tj3Set(self.enc, 4, 2)
|
||||
p, n = ctypes.c_void_p(), ctypes.c_size_t(0)
|
||||
assert L.tj3CompressFromYUV8(self.enc, bytes(buf), w, 1, h, ctypes.byref(p), ctypes.byref(n)) == 0
|
||||
data = ctypes.string_at(p, n.value)
|
||||
L.tj3Free(p)
|
||||
return data
|
||||
|
||||
|
||||
def split(stream):
|
||||
"""a Motion-JPEG elementary stream -> its JPEG frames (SOI .. EOI)"""
|
||||
frames, pos = [], 0
|
||||
while True:
|
||||
s = stream.find(b"\xff\xd8", pos)
|
||||
if s < 0:
|
||||
return frames
|
||||
p = s + 2
|
||||
while True:
|
||||
m = stream[p + 1]
|
||||
if m == 0xD9:
|
||||
p += 2
|
||||
break
|
||||
ln = (stream[p + 2] << 8) | stream[p + 3]
|
||||
p += 2 + ln
|
||||
if m == 0xDA:
|
||||
while not (stream[p] == 0xFF and stream[p + 1] not in (0,) and not 0xD0 <= stream[p + 1] <= 0xD7):
|
||||
p += 1
|
||||
frames.append(stream[s:p])
|
||||
pos = p
|
||||
|
||||
|
||||
def strip_dht(jpeg):
|
||||
out, pos = bytearray(jpeg[:2]), 2
|
||||
while pos < len(jpeg):
|
||||
m = jpeg[pos + 1]
|
||||
if m == 0xDA:
|
||||
out += jpeg[pos:]
|
||||
break
|
||||
ln = (jpeg[pos + 2] << 8) | jpeg[pos + 3]
|
||||
if m != 0xC4:
|
||||
out += jpeg[pos:pos + 2 + ln]
|
||||
pos += 2 + ln
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def avi1(jpeg, polarity):
|
||||
"""an AVI1 APP0 segment right after SOI (polarity, 0, field size, field size less padding)"""
|
||||
n = len(jpeg) + 18
|
||||
body = b"AVI1" + bytes([polarity, 0]) + n.to_bytes(4, "big") + n.to_bytes(4, "big")
|
||||
return jpeg[:2] + b"\xff\xe0" + (len(body) + 2).to_bytes(2, "big") + body + jpeg[2:]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
work = tempfile.mkdtemp(prefix="formats-mjpeg-")
|
||||
try:
|
||||
_generate(ctx, work)
|
||||
finally:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
|
||||
|
||||
def _generate(ctx, work):
|
||||
ffmpeg = tool(ctx, "ffmpeg", "ffmpeg")
|
||||
djpeg = os.path.join(os.path.dirname(ctx.nix("libjpeg_turbo", ["sh", "-c", "command -v djpeg"]).decode().strip()), "djpeg")
|
||||
tj = TurboJpeg()
|
||||
W = lambda n: os.path.join(work, n)
|
||||
|
||||
def ff(*args):
|
||||
subprocess.run([ffmpeg] + FF + list(args), check=True, capture_output=True)
|
||||
|
||||
def source(src, w, h, frames, extra=()):
|
||||
# a raw yuv420p / yuv444p source scaled to w x h (ffmpeg's lavfi sources only make even sizes)
|
||||
sw, sh = w + (w & 1), h + (h & 1)
|
||||
return ["-f", "lavfi", "-i", "%s=size=%dx%d:rate=25" % (src, sw, sh), "-frames:v", str(frames),
|
||||
"-vf", "scale=%d:%d" % (w, h)] + list(extra)
|
||||
|
||||
def rgba_crc(jpeg):
|
||||
p = W("f.jpg")
|
||||
open(p, "wb").write(jpeg)
|
||||
r = subprocess.run([djpeg, "-dct", "int", "-pnm", p], check=True, capture_output=True).stdout
|
||||
return zlib.crc32(rgba_of_pnm(r))
|
||||
|
||||
def rgba_of_pnm(d):
|
||||
# djpeg's "P6\n<w> <h>\n255\n" + RGB -> RGBA
|
||||
parts = d.split(maxsplit=3)
|
||||
w, h = int(parts[1]), int(parts[2])
|
||||
rgb = d[len(d) - w * h * 3:]
|
||||
out = bytearray(w * h * 4)
|
||||
out[0::4], out[1::4], out[2::4] = rgb[0::3], rgb[1::3], rgb[2::3]
|
||||
out[3::4] = b"\xff" * (w * h)
|
||||
return bytes(out)
|
||||
|
||||
def ffdecode(jpeg, fmt):
|
||||
p = W("ff.jpg")
|
||||
open(p, "wb").write(jpeg)
|
||||
o = W("ff.raw")
|
||||
ff("-f", "mjpeg", "-i", p, "-f", "rawvideo", "-pix_fmt", fmt, o)
|
||||
return open(o, "rb").read()
|
||||
|
||||
streams = []
|
||||
|
||||
def stream(name, src, w, h, pix, nframes, encargs=(), mutate=None):
|
||||
out = W(name + ".mjpeg")
|
||||
ff(*source(src, w, h, nframes), "-pix_fmt", pix, "-c:v", "mjpeg", *encargs, "-f", "mjpeg", out)
|
||||
frames = split(open(out, "rb").read())
|
||||
assert len(frames) == nframes, (name, len(frames))
|
||||
entries = []
|
||||
for fr in frames:
|
||||
ref = fr
|
||||
data = mutate(fr) if mutate else fr
|
||||
entries.append({"data": b64(data), "yuv": zlib.crc32(tj.yuv420(ref)), "rgba": rgba_crc(ref)})
|
||||
ref = {"yuv": z64(ffdecode(frames[0], "yuvj420p"))}
|
||||
if w * h <= 30000 or name == "testsrc_420": # keep tests/gen small: rgba for the small ones and one 320x240
|
||||
ref["rgba"] = z64(ffdecode(frames[0], "rgba"))
|
||||
streams.append({"name": name, "width": w, "height": h, "sampling": pix[4:7], "frames": entries, "ff": ref})
|
||||
|
||||
stream("testsrc_420", "testsrc2", 320, 240, "yuvj420p", 4, ("-q:v", "3"))
|
||||
stream("testsrc_422", "testsrc2", 320, 240, "yuvj422p", 4, ("-q:v", "3"))
|
||||
stream("mandel_444", "mandelbrot", 176, 144, "yuvj444p", 2, ("-q:v", "4"))
|
||||
stream("odd_420", "mandelbrot", 173, 97, "yuvj420p", 3, ("-q:v", "6"))
|
||||
stream("odd_422", "testsrc2", 97, 61, "yuvj422p", 3, ("-q:v", "2"))
|
||||
stream("odd_444", "testsrc2", 33, 17, "yuvj444p", 2, ("-q:v", "2"))
|
||||
stream("q31_420", "testsrc2", 160, 120, "yuvj420p", 2, ("-q:v", "31"))
|
||||
# Motion-JPEG as AVI stores it: the annex K tables left out
|
||||
stream("nodht_420", "mandelbrot", 320, 240, "yuvj420p", 3, ("-q:v", "4", "-huffman", "default"), strip_dht)
|
||||
stream("nodht_422", "testsrc2", 176, 144, "yuvj422p", 3, ("-q:v", "4", "-huffman", "default"), strip_dht)
|
||||
# an AVI1 segment (progressive, polarity 0) and padding / junk after EOI
|
||||
stream("avi1_junk", "testsrc2", 160, 120, "yuvj420p", 2, ("-q:v", "5"),
|
||||
lambda f: avi1(f, 0) + b"\0\0\0\0\xff\xd9junk after the image\xff\xd8")
|
||||
|
||||
# an interlaced frame: two fields of 320 x 120, each its own JPEG with AVI1 polarity 1, back to back
|
||||
full = W("full.yuv")
|
||||
ff(*source("testsrc2", 320, 240, 1), "-pix_fmt", "yuv420p", "-f", "rawvideo", full)
|
||||
fy = open(full, "rb").read()
|
||||
fw, fh = 320, 240
|
||||
fields, fsrc = [], []
|
||||
for k in range(2):
|
||||
rows = b"".join(fy[y * fw:(y + 1) * fw] for y in range(k, fh, 2))
|
||||
cw = fw // 2
|
||||
chroma = b""
|
||||
for pl in range(2):
|
||||
base = fw * fh + pl * cw * (fh // 2)
|
||||
chroma += b"".join(fy[base + y * cw:base + (y + 1) * cw] for y in range(k, fh // 2, 2))
|
||||
p = W("field%d.yuv" % k)
|
||||
open(p, "wb").write(rows + chroma)
|
||||
o = W("field%d.jpg" % k)
|
||||
ff("-f", "rawvideo", "-pix_fmt", "yuvj420p", "-s", "%dx%d" % (fw, fh // 2), "-i", p, "-pix_fmt", "yuvj420p",
|
||||
"-c:v", "mjpeg", "-q:v", "3", "-f", "mjpeg", o)
|
||||
fields.append(open(o, "rb").read())
|
||||
data = avi1(fields[0], 1) + b"\0" * 7 + avi1(fields[1], 1)
|
||||
|
||||
def weave(a, b, w, hf, bpp):
|
||||
out = bytearray()
|
||||
for y in range(2 * hf):
|
||||
src, k = (a, y // 2) if y % 2 == 0 else (b, y // 2)
|
||||
out += src[k * w * bpp:(k + 1) * w * bpp]
|
||||
return bytes(out)
|
||||
|
||||
ya, yb = tj.yuv420(fields[0]), tj.yuv420(fields[1])
|
||||
hf, cw, chf = fh // 2, fw // 2, fh // 4
|
||||
wy = weave(ya[:fw * hf], yb[:fw * hf], fw, hf, 1)
|
||||
for pl in range(2):
|
||||
o = fw * hf + pl * cw * chf
|
||||
wy += weave(ya[o:o + cw * chf], yb[o:o + cw * chf], cw, chf, 1)
|
||||
|
||||
def rgba_raw(jpeg):
|
||||
p = W("f.jpg")
|
||||
open(p, "wb").write(jpeg)
|
||||
return rgba_of_pnm(subprocess.run([djpeg, "-dct", "int", "-pnm", p], check=True, capture_output=True).stdout)
|
||||
|
||||
wr = weave(rgba_raw(fields[0]), rgba_raw(fields[1]), fw, hf, 4)
|
||||
ctx.emit("mjpeg_cases", {"streams": streams, "fields": {"data": b64(data), "width": fw, "height": fh,
|
||||
"yuv": zlib.crc32(wy), "rgba": zlib.crc32(wr), "src": z64(fy)}})
|
||||
|
||||
# the encoder: yuv420p sources, byte-identical with tj3CompressFromYUV8
|
||||
enc = []
|
||||
for name, src, w, h, qs in (("testsrc_320x240", "testsrc2", 320, 240, (50, 75, 90)),
|
||||
("mandel_176x144", "mandelbrot", 176, 144, (30, 95)),
|
||||
("odd_97x61", "testsrc2", 97, 61, (75,)), ("tiny_7x5", "mandelbrot", 7, 5, (90,)),
|
||||
("one_1x1", "testsrc2", 1, 1, (90,))):
|
||||
p = W(name + ".yuv")
|
||||
ff(*source(src, max(w, 2), max(h, 2), 1), "-pix_fmt", "yuv420p", "-f", "rawvideo", W("s.yuv"))
|
||||
raw = open(W("s.yuv"), "rb").read()
|
||||
if (w, h) == (1, 1):
|
||||
raw = raw[:1] + raw[4:5] + raw[5:6] # the top-left luma and chroma samples of a 2x2 source
|
||||
open(p, "wb").write(raw)
|
||||
for q in qs:
|
||||
want = tj.compress420(raw, w, h, q)
|
||||
got = ffdecode(want, "yuvj420p") if w > 1 else None
|
||||
psnr = 99.0
|
||||
if got:
|
||||
se = sum((a - b) ** 2 for a, b in zip(got[:w * h], raw[:w * h]))
|
||||
psnr = 99.0 if se == 0 else 10 * math.log10(255 * 255 * w * h / se)
|
||||
enc.append({"name": "%s_q%d" % (name, q), "width": w, "height": h, "quality": q, "yuv": z64(raw),
|
||||
"want": b64(want), "rgba": rgba_crc(want), "ffpsnr": round(psnr, 3)})
|
||||
ctx.emit("mjpeg_enc", enc)
|
||||
|
||||
bench = []
|
||||
for name, w, h, pix in (("320x240 4:2:0", 320, 240, "yuvj420p"), ("640x480 4:2:0", 640, 480, "yuvj420p"),
|
||||
("640x480 4:2:2", 640, 480, "yuvj422p")):
|
||||
o = W("bench.mjpeg")
|
||||
ff(*source("testsrc2", w, h, 1), "-pix_fmt", pix, "-c:v", "mjpeg", "-q:v", "3", "-f", "mjpeg", o)
|
||||
fr = split(open(o, "rb").read())[0]
|
||||
bench.append({"name": name, "width": w, "height": h, "data": b64(fr), "yuv": zlib.crc32(tj.yuv420(fr))})
|
||||
srcs = []
|
||||
for w, h in ((320, 240), (640, 480)):
|
||||
ff(*source("testsrc2", w, h, 1), "-pix_fmt", "yuv420p", "-f", "rawvideo", W("b.yuv"))
|
||||
srcs.append({"width": w, "height": h, "yuv": z64(open(W("b.yuv"), "rb").read())})
|
||||
ctx.emit("mjpeg_bench", {"frames": bench, "sources": srcs})
|
||||
@@ -0,0 +1,131 @@
|
||||
# Matroska / WebM fixtures (tools/fixtures.py): files made by ffmpeg (libvpx VP8 + Opus / Vorbis WebM, MJPEG + PCM,
|
||||
# MPEG-1 + MP3, srt subtitles) and mkvmerge (Xiph / EBML / fixed lacing, header-removal compression), plus edits made
|
||||
# here (every cluster rewritten to an unknown size, a truncated file). For each file: ffprobe's streams and packets
|
||||
# (pts, duration, keyframe flag, size, CRC-32 of the data), ffmpeg's yuv420p frames (CRC-32 each; the first frames
|
||||
# raw for PSNR checks) and ffmpeg's decoded audio (f32).
|
||||
# tests/gen/mkv_cases.luau { { name, data, streams, packets, frames = { crc }, yuv = { raw frame }, pcm, ... } }
|
||||
import importlib.util, os, subprocess, tempfile
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("_video_helpers", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_video.py"))
|
||||
V = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(V)
|
||||
|
||||
INPUTS = ["tools/fixtures/_video.py"]
|
||||
|
||||
W, H = 160, 120
|
||||
SRC = ["-f", "lavfi", "-i", "testsrc2=size=%dx%d:rate=15" % (W, H)]
|
||||
MOVE = ["-f", "lavfi", "-i", "mandelbrot=size=%dx%d:rate=15" % (W, H)]
|
||||
|
||||
|
||||
def sine(rate, ch=1):
|
||||
if ch == 1:
|
||||
return ["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=%d" % rate]
|
||||
return ["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=%d" % rate, "-ac", str(ch)]
|
||||
|
||||
|
||||
def case(ctx, tmp, name, raw_frames=2, audio=True, video=True, pcm_frames=8192):
|
||||
path = os.path.join(tmp, name)
|
||||
data = open(path, "rb").read()
|
||||
c = {"name": name, "data": data, "streams": V.streams(path), "packets": V.packets(path)}
|
||||
vs = [s for s in c["streams"] if s["kind"] == "video"]
|
||||
if video and vs:
|
||||
frames = V.yuv_frames(path, vs[0]["width"], vs[0]["height"], codec=vs[0]["codec"])
|
||||
c["frames"] = [V.crc(f) for f in frames]
|
||||
c["yuv"] = frames[:raw_frames]
|
||||
if audio and any(s["kind"] == "audio" for s in c["streams"]):
|
||||
pcm = V.pcm_f32(path)
|
||||
c["pcm"] = pcm if pcm_frames is None else pcm[:pcm_frames * 4]
|
||||
c["pcmBytes"] = len(pcm)
|
||||
return c
|
||||
|
||||
|
||||
def el(i, payload):
|
||||
"""an EBML element: id (int), payload bytes"""
|
||||
n = len(payload)
|
||||
size = bytes([0x01]) + n.to_bytes(7, "big")
|
||||
return i.to_bytes((i.bit_length() + 7) // 8, "big") + size + payload
|
||||
|
||||
|
||||
def uint(v):
|
||||
return v.to_bytes(max(1, (v.bit_length() + 7) // 8), "big")
|
||||
|
||||
|
||||
def lacing_file(ctx):
|
||||
"""A_PCM/INT/LIT mono 8 kHz s16 in three SimpleBlocks, Xiph-, EBML- and fixed-laced (DefaultDuration 10 ms)"""
|
||||
rng = ctx.rng(7)
|
||||
frames = [bytes(rng.randrange(256) for _ in range(2 * n)) for n in (80, 40, 120, 80, 80, 80, 80, 80, 80, 80)]
|
||||
head = el(0x1A45DFA3, el(0x4282, b"matroska") + el(0x4287, uint(4)) + el(0x4285, uint(2)))
|
||||
info = el(0x1549A966, el(0x2AD7B1, uint(1000000)) + el(0x4D80, b"fixture") + el(0x5741, b"fixture"))
|
||||
track = el(0xAE, el(0xD7, uint(1)) + el(0x73C5, uint(1)) + el(0x83, uint(2)) + el(0x86, b"A_PCM/INT/LIT") +
|
||||
el(0x23E383, uint(10000000)) + el(0xE1, el(0xB5, __import__("struct").pack(">d", 8000.0)) +
|
||||
el(0x9F, uint(1)) + el(0x6264, uint(16))))
|
||||
tracks = el(0x1654AE6B, track)
|
||||
|
||||
def xiph(sizes):
|
||||
out = b""
|
||||
for s in sizes:
|
||||
out += b"\xff" * (s // 255) + bytes([s % 255])
|
||||
return out
|
||||
|
||||
def ebmlnum(v):
|
||||
n = 1
|
||||
while v >= (1 << (7 * n)) - 1:
|
||||
n += 1
|
||||
return ((1 << (7 * n)) | v).to_bytes(n, "big")
|
||||
|
||||
def sebml(v, n=2):
|
||||
return ((1 << (7 * n)) | (v + (1 << (7 * n - 1)) - 1)).to_bytes(n, "big")
|
||||
|
||||
def block(rel, flags, body):
|
||||
return el(0xA3, b"\x81" + rel.to_bytes(2, "big") + bytes([flags]) + body)
|
||||
|
||||
f = frames
|
||||
b1 = block(0, 0x80 | 0x02, bytes([2]) + xiph([len(f[0]), len(f[1])]) + f[0] + f[1] + f[2])
|
||||
sizes = [len(f[3]), len(f[4]), len(f[5])]
|
||||
b2 = block(40, 0x80 | 0x06, bytes([2]) + ebmlnum(sizes[0]) + sebml(sizes[1] - sizes[0]) + f[3] + f[4] + f[5])
|
||||
b3 = block(70, 0x80 | 0x04, bytes([3]) + f[6] + f[7] + f[8] + f[9])
|
||||
cluster = el(0x1F43B675, el(0xE7, uint(0)) + b1 + b2 + b3)
|
||||
return head + el(0x18538067, info + tracks + cluster)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
tmp = tempfile.mkdtemp(prefix="mkvfx_")
|
||||
ff = lambda *a: V.ffmpeg(list(a), cwd=tmp)
|
||||
ff(*SRC, *sine(48000), "-t", "1", "-c:v", "libvpx", "-g", "8", "-auto-alt-ref", "1", "-lag-in-frames", "8",
|
||||
"-b:v", "300k", "-c:a", "libopus", "-b:a", "48k", "vp8_opus.webm")
|
||||
ff(*MOVE, *sine(44100, 2), "-t", "1", "-c:v", "libvpx", "-g", "30", "-b:v", "200k", "-c:a", "libvorbis",
|
||||
"vp8_vorbis.webm")
|
||||
ff(*SRC, *sine(44100, 2), "-t", "1", "-c:v", "mjpeg", "-q:v", "3", "-c:a", "pcm_s16le", "mjpeg_pcm.mkv")
|
||||
ff(*MOVE, *sine(44100), "-t", "1", "-r", "25", "-c:v", "mpeg1video", "-b:v", "400k", "-c:a", "mp2", "-b:a", "64k",
|
||||
"mpeg1_mp2.mkv")
|
||||
ff(*SRC, *sine(48000, 2), "-t", "1", "-c:v", "libvpx", "-g", "15", "-c:a", "flac", "vp8_flac.mkv")
|
||||
open(os.path.join(tmp, "subs.srt"), "w").write(
|
||||
"1\n00:00:00,100 --> 00:00:00,500\nHello\n\n2\n00:00:00,600 --> 00:00:00,900\nWorld <b>bold</b>\n\n")
|
||||
ff(*SRC, "-i", "subs.srt", "-t", "1", "-c:v", "mjpeg", "-c:s", "srt", "subs.mkv")
|
||||
# mkvmerge: Xiph lacing (Vorbis) and zlib content compression; a file crafted here with all three lacings
|
||||
mk = lambda *a: subprocess.run(["nix", "shell", "nixpkgs#mkvtoolnix-cli", "-c", "mkvmerge", "-q"] + list(a),
|
||||
cwd=tmp, check=False, capture_output=True)
|
||||
mk("-o", "laced_vorbis.mkv", "vp8_vorbis.webm")
|
||||
ff(*sine(44100), "-t", "1", "-c:a", "libvorbis", "v.ogg")
|
||||
mk("-o", "zlib_vorbis.mka", "--compression", "0:zlib", "v.ogg")
|
||||
open(os.path.join(tmp, "lacing.mka"), "wb").write(lacing_file(ctx))
|
||||
# unknown-size clusters, a truncated file
|
||||
open(os.path.join(tmp, "unknown_clusters.webm"), "wb").write(
|
||||
V.mkv_unknown_clusters(open(os.path.join(tmp, "vp8_opus.webm"), "rb").read()))
|
||||
full = open(os.path.join(tmp, "mjpeg_pcm.mkv"), "rb").read()
|
||||
|
||||
cases = [
|
||||
case(ctx, tmp, "vp8_opus.webm"),
|
||||
case(ctx, tmp, "vp8_vorbis.webm"),
|
||||
case(ctx, tmp, "mjpeg_pcm.mkv"),
|
||||
case(ctx, tmp, "mpeg1_mp2.mkv"),
|
||||
case(ctx, tmp, "vp8_flac.mkv"),
|
||||
case(ctx, tmp, "subs.mkv", audio=False),
|
||||
case(ctx, tmp, "unknown_clusters.webm"),
|
||||
]
|
||||
for name in ("laced_vorbis.mkv", "zlib_vorbis.mka", "lacing.mka"):
|
||||
if os.path.exists(os.path.join(tmp, name)):
|
||||
cases.append(case(ctx, tmp, name))
|
||||
cut = full[: len(full) * 7 // 10]
|
||||
cases.append({"name": "truncated.mkv", "data": cut, "truncated": True})
|
||||
ctx.emit("mkv_cases", cases)
|
||||
@@ -0,0 +1,110 @@
|
||||
# MOD fixtures (tools/fixtures.py): generated ProTracker modules exercising the effects, rendered by openmpt123.
|
||||
# tests/gen/mod_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py),
|
||||
# duration (openmpt's song length) }
|
||||
import os, sys
|
||||
|
||||
# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml)
|
||||
T = sys.modules.get("_tracker")
|
||||
if T is None:
|
||||
import importlib.util
|
||||
_spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py"))
|
||||
T = importlib.util.module_from_spec(_spec)
|
||||
sys.modules["_tracker"] = T
|
||||
_spec.loader.exec_module(T)
|
||||
|
||||
INPUTS = ["tools/fixtures/_tracker.py"]
|
||||
|
||||
|
||||
def empty(ch):
|
||||
return [[(0, 0, 0, 0) for _ in range(ch)] for _ in range(64)]
|
||||
|
||||
|
||||
def put(p, row, ch, note=0, ins=0, fx=0, param=0):
|
||||
p[row][ch] = (note, ins, fx, param)
|
||||
|
||||
|
||||
def samples():
|
||||
return [
|
||||
{"name": "sine", "data": T.s8(T.synth("sine", 64, 64)), "volume": 64, "loop": (0, 64)},
|
||||
{"name": "square", "data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 48, "loop": (0, 64)},
|
||||
{"name": "saw", "data": T.s8(T.synth("saw", 128, 64, 0.6)), "volume": 64, "loop": (64, 64)},
|
||||
{"name": "noise", "data": T.s8(T.synth("noise", 4000, 1, 0.7, decay=1200)), "volume": 64},
|
||||
{"name": "tri ft", "data": T.s8(T.synth("tri", 32, 32, 0.8)), "volume": 56, "finetune": 3, "loop": (0, 32)},
|
||||
]
|
||||
|
||||
|
||||
def song_basic():
|
||||
a, b = empty(4), empty(4)
|
||||
mel = [49, 53, 56, 61, 56, 53, 51, 49]
|
||||
for i in range(16):
|
||||
put(a, i * 4, 0, mel[i % 8], 1)
|
||||
put(a, i * 4, 1, 37 + (i % 4) * 2, 2, 0x0, 0x37 if i % 2 else 0)
|
||||
put(a, 0, 2, 49, 3, 0x1, 0x02)
|
||||
put(a, 16, 2, 0, 0, 0x2, 0x03)
|
||||
put(a, 32, 2, 61, 3, 0xC, 0x30)
|
||||
put(a, 33, 2, 0, 0, 0xA, 0x02)
|
||||
put(a, 48, 2, 0, 0, 0xA, 0x40)
|
||||
for r in range(0, 64, 8):
|
||||
put(a, r, 3, 61, 4, 0xC, 0x40 - r // 2)
|
||||
put(a, 60, 3, 61, 4, 0xE, 0xC2)
|
||||
# pattern b: portamento, vibrato, tremolo, offsets, retrig, delay, fine slides, speed change, break
|
||||
put(b, 0, 0, 49, 1)
|
||||
put(b, 4, 0, 61, 0, 0x3, 0x08)
|
||||
put(b, 8, 0, 0, 0, 0x3, 0x00)
|
||||
put(b, 12, 0, 49, 0, 0x5, 0x02)
|
||||
put(b, 16, 0, 56, 5, 0x4, 0x46)
|
||||
put(b, 20, 0, 0, 0, 0x6, 0x01)
|
||||
put(b, 24, 0, 0, 0, 0x4, 0x8F)
|
||||
put(b, 0, 1, 37, 2, 0x7, 0x48)
|
||||
put(b, 8, 1, 0, 0, 0x7, 0x00)
|
||||
put(b, 16, 1, 44, 2, 0xE, 0x12)
|
||||
put(b, 17, 1, 0, 0, 0xE, 0x12)
|
||||
put(b, 20, 1, 0, 0, 0xE, 0x24)
|
||||
put(b, 24, 1, 0, 0, 0xE, 0xB8)
|
||||
put(b, 28, 1, 0, 0, 0xE, 0xA4)
|
||||
put(b, 0, 3, 49, 4, 0x9, 0x08)
|
||||
put(b, 8, 3, 49, 4, 0xE, 0x93)
|
||||
put(b, 16, 3, 56, 4, 0xE, 0xD3)
|
||||
put(b, 24, 2, 49, 3, 0xF, 0x03)
|
||||
put(b, 32, 2, 51, 3, 0xF, 0x90)
|
||||
put(b, 40, 2, 53, 3, 0xF, 0x06)
|
||||
put(b, 40, 3, 61, 4, 0x9, 0x04)
|
||||
put(b, 44, 0, 49, 5, 0xE, 0x53)
|
||||
put(b, 48, 0, 0, 0, 0xD, 0x00)
|
||||
return T.write_mod("basic", samples(), [0, 1], [a, b])
|
||||
|
||||
|
||||
def song_loops():
|
||||
a, b, c = empty(4), empty(4), empty(4)
|
||||
put(a, 0, 0, 49, 1, 0xF, 0x04)
|
||||
put(a, 4, 0, 0, 0, 0xE, 0x60)
|
||||
put(a, 5, 1, 61, 2)
|
||||
put(a, 8, 0, 53, 1, 0xE, 0x62)
|
||||
put(a, 16, 0, 56, 1, 0xE, 0xE3)
|
||||
put(a, 17, 2, 37, 3, 0xA, 0x01)
|
||||
put(a, 32, 0, 0, 0, 0xD, 0x16)
|
||||
put(b, 16, 0, 61, 1)
|
||||
put(b, 20, 3, 49, 4, 0xF, 0x70)
|
||||
put(b, 24, 0, 0, 0, 0xB, 0x02)
|
||||
put(c, 0, 1, 50, 5)
|
||||
put(c, 4, 1, 0, 0, 0xB, 0x01)
|
||||
return T.write_mod("loops", samples(), [0, 1, 2], [a, b, c])
|
||||
|
||||
|
||||
def song_8ch():
|
||||
a = empty(8)
|
||||
for ch in range(8):
|
||||
put(a, ch * 2, ch, 37 + ch * 5, 1 + ch % 3, 0x8, ch * 32)
|
||||
put(a, 32, 0, 61, 5, 0xE, 0x84)
|
||||
put(a, 32, 7, 49, 4, 0x8, 0xFF)
|
||||
put(a, 63, 0, 0, 0, 0xF, 0x00)
|
||||
return T.write_mod("eight", samples(), [0], [a], channels=8)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
cases = []
|
||||
for nm, data in (("basic", song_basic()), ("loops", song_loops()), ("8ch", song_8ch())):
|
||||
ref = T.reference(ctx, data, "mod")
|
||||
cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]})
|
||||
ctx.emit("mod_cases", cases)
|
||||
|
||||
@@ -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,50 @@
|
||||
# MP4 / MOV fixtures (tools/fixtures.py): files made by ffmpeg (MJPEG + AAC MP4, MJPEG + PCM MOV, H.264 with B-frames
|
||||
# + AAC (edit lists), fragmented MP4, MPEG-1 + Opus, MJPEG + FLAC, MJPEG + MP2 MOV) with ffprobe's streams and packets,
|
||||
# ffmpeg's frames (CRC-32; the first raw) and audio (f32). Our MP4 / MOV writer's files are checked in
|
||||
# tools/fixtures/videoenc.py.
|
||||
# tests/gen/mp4_cases.luau { { name, data, streams, packets, frames, yuv, pcm, pcmBytes } }
|
||||
import importlib.util, os, tempfile
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("_video_helpers", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_video.py"))
|
||||
V = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(V)
|
||||
|
||||
INPUTS = ["tools/fixtures/_video.py"]
|
||||
|
||||
SRC = ["-f", "lavfi", "-i", "testsrc2=size=160x120:rate=12"]
|
||||
|
||||
|
||||
def aud(rate, ch=1):
|
||||
return ["-f", "lavfi", "-i", "sine=frequency=550:sample_rate=%d" % rate, "-ac", str(ch)]
|
||||
|
||||
|
||||
def case(tmp, name):
|
||||
path = os.path.join(tmp, name)
|
||||
c = {"name": name, "data": open(path, "rb").read(), "streams": V.streams(path), "packets": V.packets(path)}
|
||||
vs = [s for s in c["streams"] if s["kind"] == "video"]
|
||||
if vs:
|
||||
frames = V.yuv_frames(path, vs[0]["width"], vs[0]["height"], codec=vs[0]["codec"])
|
||||
c["frames"] = [V.crc(f) for f in frames]
|
||||
c["yuv"] = frames[:2]
|
||||
if any(s["kind"] == "audio" for s in c["streams"]):
|
||||
pcm = V.pcm_f32(path)
|
||||
c["pcm"] = pcm[:8192 * 4]
|
||||
c["pcmBytes"] = len(pcm)
|
||||
return c
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
tmp = tempfile.mkdtemp(prefix="mp4fx_")
|
||||
ff = lambda *a: V.ffmpeg(list(a), cwd=tmp)
|
||||
ff(*SRC, *aud(44100), "-t", "1", "-c:v", "mjpeg", "-q:v", "4", "-c:a", "aac", "-b:a", "96k", "mjpeg_aac.mp4")
|
||||
ff(*SRC, *aud(48000, 2), "-t", "1", "-c:v", "mjpeg", "-c:a", "pcm_s16le", "mjpeg_pcm.mov")
|
||||
ff(*SRC, *aud(44100), "-t", "1", "-c:v", "libx264", "-preset", "veryfast", "-bf", "2", "-g", "6", "-c:a", "aac",
|
||||
"h264_aac.mp4")
|
||||
ff(*SRC, *aud(48000), "-t", "1", "-c:v", "mjpeg", "-c:a", "aac", "-movflags", "frag_keyframe+empty_moov",
|
||||
"fragmented.mp4")
|
||||
ff(*SRC, *aud(48000), "-t", "1", "-r", "25", "-c:v", "mpeg1video", "-c:a", "libopus", "mpeg1_opus.mp4")
|
||||
ff(*SRC, *aud(44100, 2), "-t", "1", "-c:v", "mjpeg", "-c:a", "flac", "mjpeg_flac.mp4")
|
||||
ff(*SRC, *aud(44100), "-t", "1", "-c:v", "mjpeg", "-c:a", "mp2", "mjpeg_mp2.mov")
|
||||
cases = [case(tmp, n) for n in ("mjpeg_aac.mp4", "mjpeg_pcm.mov", "h264_aac.mp4", "fragmented.mp4",
|
||||
"mpeg1_opus.mp4", "mjpeg_flac.mp4", "mjpeg_mp2.mov")]
|
||||
ctx.emit("mp4_cases", cases)
|
||||
@@ -0,0 +1,170 @@
|
||||
# MPEG-1 video fixtures for codecs/Mpeg1 (tools/fixtures.py), ported from mpeg1-luau tools/fixtures.py: elementary
|
||||
# streams made by ffmpeg's mpeg1video encoder (testsrc2 / mandelbrot, several bit rates, odd sizes, custom matrices,
|
||||
# B-frames, a size change), their access units, and ffmpeg's own decode of each as references:
|
||||
# tests/gen/mpeg1_<name>.luau { name, width, height, frames, file (base64), units = { { offset, length } },
|
||||
# means = { { r, g, b } } (every frame, display order, ffmpeg's RGBA),
|
||||
# rgba = { { index, pixels } } (two whole RGBA frames, base64 zlib),
|
||||
# yuv = { { index, planes } } (three whole frames as ffmpeg -pix_fmt yuv420p, base64 zlib) }
|
||||
# tests/gen/mpeg1_sizechange.luau { file (base64), parts = { { width, height, frames, last (RGBA, base64 zlib) } } }
|
||||
# tests/gen/mpeg1_bench.luau { { width, height, file (base64), units } }: 320x240 and 640x480 streams (with
|
||||
# B-frames) for tools/bench.luau
|
||||
# Binary fields are base64 (file, units' data) or base64 of zlib data (frames: the test inflates them with
|
||||
# codecs/Deflate): Luau string literals of binary data cost ~3.7 bytes per byte, base64 1.33. With short streams and
|
||||
# few whole frames the set stays near 10 MB.
|
||||
import base64, os, shutil, subprocess, tempfile, zlib
|
||||
|
||||
def b64(b):
|
||||
return base64.b64encode(b).decode()
|
||||
|
||||
|
||||
def z64(b):
|
||||
return base64.b64encode(zlib.compress(b, 9)).decode()
|
||||
|
||||
|
||||
FF = ["-hide_banner", "-loglevel", "error", "-y"]
|
||||
ENC = ["-c:v", "mpeg1video", "-f", "mpeg1video"]
|
||||
# a non-default intra matrix (steeper) and inter matrix (rising), 64 values in natural order
|
||||
INTRA = ",".join(str(8 + (i // 8 + i % 8) * 3) for i in range(64))
|
||||
INTER = ",".join(str(16 + (i // 8 + i % 8)) for i in range(64))
|
||||
|
||||
|
||||
def src(kind, w, h, rate, t):
|
||||
return ["-f", "lavfi", "-i", "%s=size=%dx%d:rate=%s" % (kind, w, h, rate), "-t", str(t)]
|
||||
|
||||
|
||||
# name: (ffmpeg input + encoder args, size patched into the sequence headers or None, rgba sample picks, yuv picks)
|
||||
CASES = {
|
||||
"qcif_200k": (src("testsrc2", 176, 144, 25, 1.2) + ["-b:v", "200k", "-bf", "0", "-g", "50"], None),
|
||||
"main_450k": (src("testsrc2", 320, 180, 24, 1.5) + ["-b:v", "450k", "-bf", "0", "-g", "48"], None),
|
||||
"zoom_150k": (src("mandelbrot", 320, 180, 24, 1.5) + ["-b:v", "150k", "-bf", "0", "-g", "48"], None),
|
||||
"zoom_1500k": (src("mandelbrot", 320, 180, 24, 1) + ["-b:v", "1500k", "-bf", "0", "-g", "48"], None),
|
||||
"big_1000k": (src("testsrc2", 640, 360, 24, 0.5) + ["-b:v", "1000k", "-bf", "0", "-g", "36"], None),
|
||||
# odd sizes: ffmpeg's encoder only writes even ones, so the size in the sequence headers is patched; the
|
||||
# reference is ffmpeg's decode of the unpatched stream, cropped (swscale's odd-size RGBA path interpolates
|
||||
# chroma differently from its even-size one, which is what the decoder matches)
|
||||
"odd_173x95": (src("mandelbrot", 174, 96, 24, 1) + ["-b:v", "300k", "-bf", "0", "-g", "24"], (173, 95)),
|
||||
"bframes": (src("testsrc2", 320, 180, 24, 1) + ["-b:v", "600k", "-bf", "2", "-g", "24"], None),
|
||||
"bframes_zoom": (src("mandelbrot", 176, 144, 24, 1.5) + ["-b:v", "250k", "-bf", "3", "-g", "16"], None),
|
||||
"matrix": (src("testsrc2", 176, 144, 25, 1) + ["-b:v", "300k", "-bf", "0", "-g", "12",
|
||||
"-intra_matrix", INTRA, "-inter_matrix", INTER], None),
|
||||
"q1": (src("mandelbrot", 176, 144, 25, 0.6) + ["-q:v", "1", "-bf", "0", "-g", "8"], None),
|
||||
"q31": (src("testsrc2", 176, 144, 25, 1) + ["-q:v", "31", "-bf", "0", "-g", "25"], None),
|
||||
"zeromv": (src("mandelbrot", 176, 144, 25, 1) + ["-b:v", "300k", "-bf", "0", "-g", "25", "-me_method", "zero"], None),
|
||||
}
|
||||
|
||||
|
||||
def patch_size(es, w, h):
|
||||
# every sequence header (00 00 01 B3): 12-bit width, 12-bit height
|
||||
b = bytearray(es)
|
||||
i = 0
|
||||
while True:
|
||||
i = b.find(b"\x00\x00\x01\xb3", i)
|
||||
if i < 0:
|
||||
return bytes(b)
|
||||
b[i + 4] = w >> 4
|
||||
b[i + 5] = ((w & 15) << 4) | (h >> 8)
|
||||
b[i + 6] = h & 255
|
||||
i += 4
|
||||
|
||||
|
||||
def access_units(es):
|
||||
# one unit per picture: from the first header byte before it (sequence / GOP) to the next unit start
|
||||
starts = []
|
||||
i = 0
|
||||
pending = None
|
||||
while True:
|
||||
i = es.find(b"\x00\x00\x01", i)
|
||||
if i < 0 or i + 3 >= len(es):
|
||||
break
|
||||
code = es[i + 3]
|
||||
if code in (0xB3, 0xB8) and pending is None:
|
||||
pending = i
|
||||
elif code == 0x00:
|
||||
starts.append(pending if pending is not None else i)
|
||||
pending = None
|
||||
i += 3
|
||||
return [[s, (starts[k + 1] if k + 1 < len(starts) else len(es)) - s] for k, s in enumerate(starts)]
|
||||
|
||||
|
||||
def crop(frames, w, h, cw, ch, bpp):
|
||||
fs = w * h * bpp
|
||||
out = bytearray()
|
||||
for k in range(len(frames) // fs):
|
||||
for y in range(ch):
|
||||
o = k * fs + y * w * bpp
|
||||
out += frames[o:o + cw * bpp]
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def crop_yuv(frames, w, h, cw, ch):
|
||||
fs = w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2)
|
||||
out = bytearray()
|
||||
for k in range(len(frames) // fs):
|
||||
f = frames[k * fs:(k + 1) * fs]
|
||||
out += crop(f[:w * h], w, h, cw, ch, 1)
|
||||
c = ((w + 1) // 2) * ((h + 1) // 2)
|
||||
for pl in range(2):
|
||||
out += crop(f[w * h + pl * c:w * h + (pl + 1) * c], (w + 1) // 2, (h + 1) // 2, (cw + 1) // 2, (ch + 1) // 2, 1)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
ffmpeg = shutil.which("ffmpeg") or ctx.nix("ffmpeg", ["sh", "-c", "command -v ffmpeg"]).decode().strip()
|
||||
ffprobe = shutil.which("ffprobe") or os.path.join(os.path.dirname(ffmpeg), "ffprobe")
|
||||
|
||||
def ff(args):
|
||||
subprocess.run([ffmpeg] + FF + args, check=True, capture_output=True)
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="formats-mpeg1-") as tmp:
|
||||
def encode(name, args, size):
|
||||
path = os.path.join(tmp, name + ".m1v")
|
||||
ff(args + ENC + [path])
|
||||
es = open(path, "rb").read()
|
||||
return (patch_size(es, *size) if size else es), path
|
||||
|
||||
def reference(path, fmt):
|
||||
out = path + "." + fmt
|
||||
ff(["-i", path, "-f", "rawvideo", "-pix_fmt", fmt, out])
|
||||
r = subprocess.run([ffprobe, "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height",
|
||||
"-of", "csv=p=0", path], check=True, capture_output=True)
|
||||
w, h = (int(x) for x in r.stdout.decode().strip().split(",")[:2])
|
||||
return open(out, "rb").read(), w, h
|
||||
|
||||
for name, (args, size) in CASES.items():
|
||||
es, path = encode(name, args, size)
|
||||
rgba, w, h = reference(path, "rgba")
|
||||
yuv, _, _ = reference(path, "yuv420p")
|
||||
if size:
|
||||
rgba, yuv = crop(rgba, w, h, size[0], size[1], 4), crop_yuv(yuv, w, h, size[0], size[1])
|
||||
w, h = size
|
||||
fs, ys = w * h * 4, w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2)
|
||||
n = len(rgba) // fs
|
||||
means = []
|
||||
for k in range(n):
|
||||
fr = rgba[k * fs:(k + 1) * fs]
|
||||
means.append([round(sum(fr[c::4]) / (w * h), 4) for c in range(3)])
|
||||
# whole frames: the first P-picture and the last one (the most drift) as RGBA, three as yuv420p
|
||||
picks = sorted({1, n - 1}) if n > 2 else list(range(n))
|
||||
ypicks = sorted({0, n // 2, n - 1})
|
||||
ctx.emit("mpeg1_" + name, {
|
||||
"name": name, "width": w, "height": h, "frames": n, "file": b64(es), "units": access_units(es),
|
||||
"means": means,
|
||||
"rgba": [{"index": k + 1, "pixels": z64(rgba[k * fs:(k + 1) * fs])} for k in picks],
|
||||
"yuv": [{"index": k + 1, "planes": z64(yuv[k * ys:(k + 1) * ys])} for k in ypicks],
|
||||
})
|
||||
|
||||
# a size change mid-stream: 176x144 then 320x180 (each part decoded by ffmpeg on its own)
|
||||
a, pa = encode("sc_a", src("testsrc2", 176, 144, 24, 0.5) + ["-b:v", "200k", "-bf", "0", "-g", "6"], None)
|
||||
b, pb = encode("sc_b", src("mandelbrot", 320, 180, 24, 0.5) + ["-b:v", "400k", "-bf", "0", "-g", "6"], None)
|
||||
parts = []
|
||||
for path in (pa, pb):
|
||||
rg, w, h = reference(path, "rgba")
|
||||
n = len(rg) // (w * h * 4)
|
||||
parts.append({"width": w, "height": h, "frames": n, "last": z64(rg[(n - 1) * w * h * 4:])})
|
||||
ctx.emit("mpeg1_sizechange", {"file": b64(a + b), "parts": parts})
|
||||
|
||||
bench = []
|
||||
for w, h, rate in ((320, 240, "600k"), (640, 480, "1500k")):
|
||||
es, _ = encode("bench", src("testsrc2", w, h, 25, 2) + ["-b:v", rate, "-bf", "2", "-g", "25"], None)
|
||||
bench.append({"width": w, "height": h, "file": b64(es), "units": access_units(es)})
|
||||
ctx.emit("mpeg1_bench", bench)
|
||||
@@ -0,0 +1,59 @@
|
||||
# MPEG-TS / PS fixtures (tools/fixtures.py): transport streams (MPEG-1 + MP2 as bugtv plays them, with B-frames,
|
||||
# H.264 + AAC, M2TS 192-byte packets, garbage before the first packet) and program streams (MPEG-1 system stream,
|
||||
# MPEG-2 PS / VOB layout, B-frames, a raw .m1v elementary stream), made by ffmpeg. For each file: ffprobe's streams
|
||||
# and packets, ffmpeg's frames (CRC-32 of yuv420p; the first frames raw) and audio (f32).
|
||||
# tests/gen/mpegts_cases.luau, tests/gen/mpegps_cases.luau
|
||||
import importlib.util, os, tempfile
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("_video_helpers", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_video.py"))
|
||||
V = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(V)
|
||||
|
||||
INPUTS = ["tools/fixtures/_video.py"]
|
||||
|
||||
SRC = ["-f", "lavfi", "-i", "testsrc2=size=160x120:rate=25"]
|
||||
AUD = ["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100"]
|
||||
|
||||
|
||||
def case(tmp, name, raw_frames=3, pcm_frames=8192, packets=True):
|
||||
path = os.path.join(tmp, name)
|
||||
c = {"name": name, "data": open(path, "rb").read(), "streams": V.streams(path)}
|
||||
if packets:
|
||||
c["packets"] = V.packets(path)
|
||||
vs = [s for s in c["streams"] if s["kind"] == "video"]
|
||||
if vs:
|
||||
frames = V.yuv_frames(path, vs[0]["width"], vs[0]["height"])
|
||||
c["frames"] = [V.crc(f) for f in frames]
|
||||
c["yuv"] = frames[:raw_frames]
|
||||
if any(s["kind"] == "audio" for s in c["streams"]):
|
||||
pcm = V.pcm_f32(path)
|
||||
c["pcm"] = pcm[:pcm_frames * 4]
|
||||
c["pcmBytes"] = len(pcm)
|
||||
return c
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
tmp = tempfile.mkdtemp(prefix="mpegfx_")
|
||||
ff = lambda *a: V.ffmpeg(list(a), cwd=tmp)
|
||||
ff(*SRC, *AUD, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-bf", "0", "-c:a", "mp2", "-b:a", "128k",
|
||||
"-f", "mpegts", "mpeg1_mp2.ts")
|
||||
ff(*SRC, *AUD, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-bf", "2", "-c:a", "mp2", "-f", "mpegts",
|
||||
"bframes.ts")
|
||||
ff(*SRC, *AUD, "-t", "1", "-c:v", "libx264", "-preset", "veryfast", "-g", "10", "-c:a", "aac", "-b:a", "96k",
|
||||
"-f", "mpegts", "h264_aac.ts")
|
||||
ff(*SRC, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-f", "mpegts", "-mpegts_m2ts_mode", "1", "m2ts.m2ts")
|
||||
open(os.path.join(tmp, "garbage.ts"), "wb").write(bytes(ctx.rng(3).randrange(256) for _ in range(333)).replace(b"G", b"g") +
|
||||
open(os.path.join(tmp, "mpeg1_mp2.ts"), "rb").read())
|
||||
ts = [case(tmp, "mpeg1_mp2.ts"), case(tmp, "bframes.ts"), case(tmp, "h264_aac.ts"), case(tmp, "m2ts.m2ts"),
|
||||
case(tmp, "garbage.ts", packets=False)]
|
||||
full = ts[0]["data"]
|
||||
ts.append({"name": "truncated.ts", "data": full[: len(full) // 2 + 77], "truncated": True})
|
||||
ctx.emit("mpegts_cases", ts)
|
||||
|
||||
ff(*SRC, *AUD, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-bf", "0", "-c:a", "mp2", "-f", "mpeg", "system.mpg")
|
||||
ff(*SRC, *AUD, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-bf", "2", "-c:a", "mp2", "-f", "mpeg",
|
||||
"bframes.mpg")
|
||||
ff(*SRC, *AUD, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-c:a", "mp2", "-f", "vob", "mpeg2ps.vob")
|
||||
ff(*SRC, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-bf", "2", "-f", "mpeg1video", "es.m1v")
|
||||
ps = [case(tmp, n, packets=False) for n in ("system.mpg", "bframes.mpg", "mpeg2ps.vob", "es.m1v")]
|
||||
ctx.emit("mpegps_cases", ps)
|
||||
@@ -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)
|
||||
@@ -0,0 +1,130 @@
|
||||
# S3M fixtures (tools/fixtures.py): generated Scream Tracker 3 modules exercising the effects, rendered by openmpt123.
|
||||
# tests/gen/s3m_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py),
|
||||
# duration (openmpt's song length) }
|
||||
import os, sys
|
||||
|
||||
# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml)
|
||||
T = sys.modules.get("_tracker")
|
||||
if T is None:
|
||||
import importlib.util
|
||||
_spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py"))
|
||||
T = importlib.util.module_from_spec(_spec)
|
||||
sys.modules["_tracker"] = T
|
||||
_spec.loader.exec_module(T)
|
||||
|
||||
INPUTS = ["tools/fixtures/_tracker.py"]
|
||||
|
||||
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, Tt, U, V, W, X, Y, Z = range(1, 27)
|
||||
|
||||
|
||||
def empty(ch, rows=64):
|
||||
return [[(0, 0, None, 0, 0) for _ in range(ch)] for _ in range(rows)]
|
||||
|
||||
|
||||
def put(p, row, ch, note=0, ins=0, vol=None, cmd=0, info=0):
|
||||
p[row][ch] = (T.s3m_note(note) if 0 < note < 254 else note, ins, vol, cmd, info)
|
||||
|
||||
|
||||
def samples():
|
||||
return [
|
||||
{"name": "sine", "data": T.u8(T.synth("sine", 64, 64)), "volume": 64, "c2spd": 8363, "loop": (0, 64)},
|
||||
{"name": "square", "data": T.u8(T.synth("square", 64, 64, 0.5)), "volume": 40, "c2spd": 16726, "loop": (0, 64)},
|
||||
{"name": "saw", "data": T.u8(T.synth("saw", 100, 100, 0.6)), "volume": 64, "c2spd": 13000, "loop": (0, 100)},
|
||||
{"name": "noise", "data": T.u8(T.synth("noise", 6000, 1, 0.7, decay=1500)), "volume": 60, "c2spd": 8363},
|
||||
{"name": "tri", "data": T.u8(T.synth("tri", 50, 50, 0.8)), "volume": 50, "c2spd": 10000, "loop": (0, 50)},
|
||||
]
|
||||
|
||||
|
||||
def song_effects(keep=None):
|
||||
"""keep: debugging aid, a set of channels to keep (the others keep only their global effects)"""
|
||||
a, b, c = empty(4), empty(4), empty(4)
|
||||
mel = [61, 65, 68, 73, 68, 65, 63, 61]
|
||||
for i in range(16):
|
||||
put(a, i * 4, 0, mel[i % 8], 1, None, J if i % 4 == 1 else 0, 0x47 if i % 4 == 1 else 0)
|
||||
put(a, 0, 1, 49, 2, 48)
|
||||
put(a, 4, 1, 0, 0, None, D, 0x04)
|
||||
put(a, 8, 1, 0, 0, None, D, 0x20)
|
||||
put(a, 12, 1, 0, 0, None, D, 0xF2)
|
||||
put(a, 13, 1, 0, 0, None, D, 0x3F)
|
||||
put(a, 14, 1, 0, 0, None, D, 0x00)
|
||||
put(a, 16, 1, 51, 2, None, E, 0x03)
|
||||
put(a, 20, 1, 0, 0, None, F, 0x06)
|
||||
put(a, 24, 1, 0, 0, None, E, 0xF4)
|
||||
put(a, 25, 1, 0, 0, None, F, 0xE8)
|
||||
put(a, 28, 1, 56, 2, None, H, 0x46)
|
||||
put(a, 32, 1, 0, 0, None, U, 0x48)
|
||||
put(a, 36, 1, 0, 0, None, K, 0x02)
|
||||
put(a, 40, 1, 49, 2, None, G, 0x00)
|
||||
put(a, 41, 1, 61, 0, None, G, 0x10)
|
||||
put(a, 44, 1, 0, 0, None, L, 0x01)
|
||||
put(a, 48, 1, 54, 2, None, R, 0x58)
|
||||
put(a, 52, 1, 0, 0, None, I, 0x21)
|
||||
put(a, 56, 1, 0, 0, None, X, 0x20)
|
||||
put(a, 60, 1, 0, 0, None, S, 0x8C)
|
||||
for r in range(0, 64, 8):
|
||||
put(a, r, 3, 61, 4, 64 - r // 2)
|
||||
put(a, 20, 3, 0, 0, None, O, 0x08)
|
||||
put(a, 24, 3, 61, 4, None, Q, 0x83)
|
||||
put(a, 32, 3, 61, 4, None, S, 0xC3)
|
||||
put(a, 40, 3, 61, 4, None, S, 0xD2)
|
||||
put(a, 48, 2, 37, 3, None, V, 0x30)
|
||||
put(a, 56, 2, 0, 0, None, V, 0x40)
|
||||
put(b, 0, 2, 49, 3, None, A, 0x04)
|
||||
put(b, 4, 2, 0, 0, None, Tt, 0x90)
|
||||
put(b, 8, 2, 52, 5, None, S, 0xB0)
|
||||
put(b, 10, 0, 64, 1)
|
||||
put(b, 12, 2, 0, 0, None, S, 0xB2)
|
||||
put(b, 16, 2, 56, 5, None, S, 0xE2)
|
||||
put(b, 20, 0, 61, 1, None, O, 0x00)
|
||||
put(b, 24, 0, 254)
|
||||
put(b, 28, 2, 0, 0, None, C, 0x08)
|
||||
put(c, 8, 0, 49, 1, 32)
|
||||
put(c, 12, 1, 61, 2, None, X, 0x80)
|
||||
put(c, 16, 1, 0, 0, None, S, 0x82)
|
||||
put(c, 20, 0, 0, 0, None, B, 0x05)
|
||||
if keep is not None: # debugging: only some channels
|
||||
for p in (a, b, c):
|
||||
for row in p:
|
||||
for ch in range(4):
|
||||
if ch not in keep and row[ch][3] not in (A, B, C, Tt, V):
|
||||
row[ch] = (0, 0, None, 0, 0)
|
||||
return T.write_s3m("effects", samples(), [0, 1, 254, 2], [a, b, c], 4)
|
||||
|
||||
|
||||
def song_memory():
|
||||
"""ST3's shared effect memory, fast slides (ST3.00), the panning table, global volume, an order loop"""
|
||||
a = empty(6)
|
||||
put(a, 0, 0, 61, 1, None, D, 0x08)
|
||||
put(a, 4, 0, 0, 0, None, E, 0x02)
|
||||
put(a, 8, 0, 0, 0, None, D, 0x00)
|
||||
put(a, 12, 0, 0, 0, None, F, 0x00)
|
||||
put(a, 0, 1, 49, 3, None, D, 0x80)
|
||||
put(a, 2, 1, 0, 0, None, D, 0x00)
|
||||
put(a, 16, 2, 73, 5)
|
||||
put(a, 20, 2, 0, 0, None, Q, 0x02)
|
||||
put(a, 24, 2, 0, 0, None, Q, 0x00)
|
||||
put(a, 28, 3, 56, 2, 20)
|
||||
put(a, 28, 4, 63, 1, 30)
|
||||
put(a, 32, 5, 37, 3, None, X, 0x00)
|
||||
put(a, 40, 5, 0, 0, None, S, 0xE3)
|
||||
put(a, 48, 0, 0, 0, None, V, 0x20)
|
||||
put(a, 63, 0, 0, 0, None, B, 0x00)
|
||||
return T.write_s3m("memory", samples(), [0], [a], 6, speed=5, tempo=140, cwt=0x1300,
|
||||
pans=[2, 13, 5, 10, 7, 15], mvol=64 | 128, gvol=48)
|
||||
|
||||
|
||||
def song_mono():
|
||||
a = empty(2)
|
||||
put(a, 0, 0, 61, 1)
|
||||
put(a, 8, 1, 68, 2)
|
||||
put(a, 16, 0, 0, 0, None, H, 0x28)
|
||||
put(a, 32, 1, 0, 0, None, F, 0x10)
|
||||
return T.write_s3m("mono", samples(), [0], [a], 2, mvol=32)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
cases = []
|
||||
for nm, data in (("effects", song_effects()), ("memory", song_memory()), ("mono", song_mono())):
|
||||
ref = T.reference(ctx, data, "s3m")
|
||||
cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]})
|
||||
ctx.emit("s3m_cases", cases)
|
||||
@@ -0,0 +1,227 @@
|
||||
# SoundFont fixtures (tools/fixtures.py): a small self-made SF2 (band-limited sine / saw / square loops + a noise
|
||||
# burst; melodic presets with envelopes, a filter + mod envelope, vibrato, a preset global zone, an instrument global
|
||||
# zone, a drum kit on bank 128 with exclusive classes), a 12.5 s test song (SMF written here) that plays each preset in
|
||||
# its own 2 s segment (chords, pitch bend with an RPN 0 range of 12, sustain pedal, CC7 / CC11), the song rendered by
|
||||
# FluidSynth (nixpkgs#fluidsynth, reverb and chorus off) and analysed with numpy (tools/fixtures/_sf2_features.py):
|
||||
# tests/gen/sf2_cases.luau { sf2, sf2_24 (the same with an sm24 chunk), song, fluid = { env, bands, peaks },
|
||||
# expect = { presets, samples, instruments, info, values } }
|
||||
import json, math, os, random, struct, subprocess, tempfile
|
||||
|
||||
INPUTS = ["tools/fixtures/_sf2_features.py"]
|
||||
RATE = 44100
|
||||
PERIOD = 100 # 441 Hz loops
|
||||
CYCLES = 50
|
||||
|
||||
|
||||
def tc(sec):
|
||||
return int(round(1200 * math.log2(sec)))
|
||||
|
||||
|
||||
def hz_cents(hz):
|
||||
return int(round(1200 * math.log2(hz / 8.176)))
|
||||
|
||||
|
||||
def wave(kind, rng):
|
||||
n = PERIOD * CYCLES
|
||||
out = []
|
||||
for i in range(n):
|
||||
ph = 2 * math.pi * i / PERIOD
|
||||
if kind == "sine":
|
||||
v = math.sin(ph) * 0.8
|
||||
elif kind == "saw":
|
||||
v = sum(math.sin(k * ph) / k for k in range(1, 50)) * 0.45
|
||||
else:
|
||||
v = sum(math.sin(k * ph) / k for k in range(1, 50, 2)) * 0.6
|
||||
out.append(v)
|
||||
return out
|
||||
|
||||
|
||||
def chunk(cid, data):
|
||||
pad = b"\x00" if len(data) % 2 else b""
|
||||
return cid + struct.pack("<I", len(data)) + data + pad
|
||||
|
||||
|
||||
def lst(kind, chunks):
|
||||
body = kind + b"".join(chunks)
|
||||
return b"LIST" + struct.pack("<I", len(body)) + body
|
||||
|
||||
|
||||
def zstr(s):
|
||||
b = s.encode() + b"\x00"
|
||||
return b + (b"\x00" if len(b) % 2 else b"")
|
||||
|
||||
|
||||
def name20(s):
|
||||
return s.encode()[:19].ljust(20, b"\x00")
|
||||
|
||||
|
||||
def build_sf2(with24):
|
||||
rng = random.Random(3)
|
||||
waves = [("sine", wave("sine", rng)), ("saw", wave("saw", rng)), ("square", wave("square", rng)),
|
||||
("noise", [rng.uniform(-0.7, 0.7) for _ in range(RATE // 2)])]
|
||||
pcm, pcm24, headers = bytearray(), bytearray(), []
|
||||
pos = 0
|
||||
for name, w in waves:
|
||||
start = pos
|
||||
for v in w:
|
||||
x = int(round(v * 8388607))
|
||||
hi, lo = x >> 8, x & 255
|
||||
pcm += struct.pack("<h", hi)
|
||||
pcm24.append(lo)
|
||||
pos += len(w)
|
||||
end = pos
|
||||
pcm += b"\x00\x00" * 46
|
||||
pcm24 += b"\x00" * 46
|
||||
pos += 46
|
||||
# sine: 441 Hz = A4 + 3.93 cents -> root 69, correction -4 makes it play 440 Hz-ish at key 69
|
||||
headers.append((name, start, end, start, end, RATE, 69, -4, 0, 1))
|
||||
if len(pcm24) % 2:
|
||||
pcm24 += b"\x00"
|
||||
info = lst(b"INFO", [chunk(b"ifil", struct.pack("<HH", 2, 4)), chunk(b"isng", zstr("EMU8000")),
|
||||
chunk(b"INAM", zstr("formats-luau test bank")), chunk(b"ICMT", zstr("generated by tools/fixtures/sf2.py"))])
|
||||
sd = [chunk(b"smpl", bytes(pcm))] + ([chunk(b"sm24", bytes(pcm24))] if with24 else [])
|
||||
sdta = lst(b"sdta", sd)
|
||||
|
||||
# instruments: lists of zones, a zone = [(op, amount)], amounts as signed 16 (key ranges: lo | hi << 8)
|
||||
def rng_(lo, hi):
|
||||
return lo | (hi << 8)
|
||||
insts = [
|
||||
("sine inst", [[(34, tc(0.01)), (36, tc(0.5)), (37, 60), (38, tc(0.2)), (54, 1), (53, 0)]]),
|
||||
("saw inst", [[(8, hz_cents(2500))], # the instrument global zone: a low-pass
|
||||
[(34, tc(0.005)), (38, tc(0.15)), (28, tc(0.4)), (29, 1000), (11, 2400), (54, 1), (53, 1)]]),
|
||||
("square inst", [[(34, tc(0.02)), (38, tc(0.1)), (6, 50), (24, hz_cents(5)), (54, 1), (53, 2)]]),
|
||||
("drum inst", [[(38, tc(0.05))],
|
||||
[(43, rng_(35, 36)), (36, tc(0.3)), (37, 1440), (54, 1), (53, 0)],
|
||||
[(43, rng_(38, 38)), (8, hz_cents(5000)), (36, tc(0.15)), (37, 1440), (53, 3)],
|
||||
[(43, rng_(42, 42)), (36, tc(0.06)), (37, 1440), (57, 1), (58, 81), (53, 3)],
|
||||
[(43, rng_(46, 46)), (36, tc(0.6)), (37, 1440), (57, 1), (58, 81), (53, 3)]]),
|
||||
]
|
||||
presets = [
|
||||
("Sine", 0, 0, [[(48, 30)], [(41, 0)]]), # a preset global zone (attenuation), then the instrument
|
||||
("Saw", 1, 0, [[(41, 1)]]),
|
||||
("Square", 2, 0, [[(41, 2)]]),
|
||||
("Drums", 0, 128, [[(41, 3)]]),
|
||||
]
|
||||
phdr, pbag, pgen = bytearray(), bytearray(), bytearray()
|
||||
bag = gen = 0
|
||||
for name, prog, bank, zones in presets:
|
||||
phdr += name20(name) + struct.pack("<HHHIII", prog, bank, bag, 0, 0, 0)
|
||||
for z in zones:
|
||||
pbag += struct.pack("<HH", gen, 0)
|
||||
bag += 1
|
||||
for op, amt in z:
|
||||
pgen += struct.pack("<Hh" if op != 43 else "<HH", op, amt)
|
||||
gen += 1
|
||||
phdr += name20("EOP") + struct.pack("<HHHIII", 0, 0, bag, 0, 0, 0)
|
||||
pbag += struct.pack("<HH", gen, 0)
|
||||
pgen += struct.pack("<HH", 0, 0)
|
||||
inst, ibag, igen = bytearray(), bytearray(), bytearray()
|
||||
bag = gen = 0
|
||||
for name, zones in insts:
|
||||
inst += name20(name) + struct.pack("<H", bag)
|
||||
for z in zones:
|
||||
ibag += struct.pack("<HH", gen, 0)
|
||||
bag += 1
|
||||
for op, amt in z:
|
||||
igen += struct.pack("<Hh" if op != 43 else "<HH", op, amt)
|
||||
gen += 1
|
||||
inst += name20("EOI") + struct.pack("<H", bag)
|
||||
ibag += struct.pack("<HH", gen, 0)
|
||||
igen += struct.pack("<HH", 0, 0)
|
||||
shdr = bytearray()
|
||||
for (name, s, e, ls, le, rate, pitch, corr, link, typ) in headers:
|
||||
shdr += name20(name) + struct.pack("<IIIIIBbHH", s, e, ls, le, rate, pitch, corr, link, typ)
|
||||
shdr += name20("EOS") + b"\x00" * 26
|
||||
pmod = b"\x00" * 10
|
||||
pdta = lst(b"pdta", [chunk(b"phdr", bytes(phdr)), chunk(b"pbag", bytes(pbag)), chunk(b"pmod", pmod),
|
||||
chunk(b"pgen", bytes(pgen)), chunk(b"inst", bytes(inst)), chunk(b"ibag", bytes(ibag)),
|
||||
chunk(b"imod", pmod), chunk(b"igen", bytes(igen)), chunk(b"shdr", bytes(shdr))])
|
||||
body = b"sfbk" + info + sdta + pdta
|
||||
data = b"RIFF" + struct.pack("<I", len(body)) + body
|
||||
expect = {
|
||||
"presets": [{"name": n, "preset": p, "bank": b} for n, p, b, _ in sorted(presets, key=lambda x: (x[2], x[1]))],
|
||||
"samples": [{"name": h[0], "start": h[1], "stop": h[2], "loopStart": h[3], "loopEnd": h[4], "sampleRate": h[5],
|
||||
"originalPitch": h[6], "pitchCorrection": h[7]} for h in headers],
|
||||
"instruments": [n for n, _ in insts],
|
||||
"info": {"name": "formats-luau test bank", "engine": "EMU8000", "version": "2.04"},
|
||||
# a few raw sample values (16-bit and 24-bit) for the sample decoding check
|
||||
"values": [[i, struct.unpack_from("<h", pcm, i * 2)[0], pcm24[i]] for i in (0, 1, 25, 77, 5000 + 46 + 13, 20000)],
|
||||
}
|
||||
return data, expect
|
||||
|
||||
|
||||
def vlq(v):
|
||||
out = [v & 127]
|
||||
v >>= 7
|
||||
while v:
|
||||
out.insert(0, (v & 127) | 128)
|
||||
v >>= 7
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def song():
|
||||
tpq, us = 480, 500000 # 1 beat = 0.5 s
|
||||
ev = [] # (seconds, bytes)
|
||||
|
||||
def at(sec, *b):
|
||||
ev.append((sec, bytes(b)))
|
||||
at(0, 0xC0, 0)
|
||||
at(0, 0xC1, 1)
|
||||
at(0, 0xC2, 2)
|
||||
# seg 0: a sine chord
|
||||
for n in (60, 64, 67):
|
||||
at(0.0, 0x90, n, 127)
|
||||
at(1.5, 0x80, n, 0)
|
||||
# seg 1: a saw melody (filter + mod env)
|
||||
for k, n in enumerate((48, 52, 55, 60)):
|
||||
at(2.0 + 0.4 * k, 0x91, n, 127)
|
||||
at(2.35 + 0.4 * k, 0x81, n, 0)
|
||||
# seg 2: a square with vibrato
|
||||
at(4.0, 0x92, 69, 127)
|
||||
at(5.5, 0x82, 69, 0)
|
||||
# seg 3: drums (hats cut each other: exclusive class)
|
||||
for sec, n in ((6.0, 36), (6.25, 42), (6.5, 38), (6.75, 42), (7.0, 46), (7.25, 42), (7.5, 36)):
|
||||
at(sec, 0x99, n, 127)
|
||||
at(sec + 0.1, 0x89, n, 0)
|
||||
# seg 4: sine with a pitch-bend range of 12 (RPN 0), a bend up an octave, the sustain pedal
|
||||
at(7.9, 0xB0, 101, 0)
|
||||
at(7.9, 0xB0, 100, 0)
|
||||
at(7.9, 0xB0, 6, 12)
|
||||
at(8.0, 0x90, 72, 127)
|
||||
at(8.5, 0xE0, 0x7F, 0x7F)
|
||||
at(9.0, 0xE0, 0x00, 0x40)
|
||||
at(9.1, 0xB0, 64, 127)
|
||||
at(9.2, 0x80, 72, 0)
|
||||
at(9.6, 0xB0, 64, 0)
|
||||
# seg 5: saw with volume and expression changes
|
||||
at(10.0, 0x91, 57, 127)
|
||||
at(10.75, 0xB1, 7, 60)
|
||||
at(11.25, 0xB1, 11, 64)
|
||||
at(11.6, 0x81, 57, 0)
|
||||
ev.sort(key=lambda e: e[0])
|
||||
body, last = bytearray(), 0
|
||||
body += b"\x00\xff\x51\x03" + struct.pack(">I", us)[1:]
|
||||
for sec, b in ev:
|
||||
tick = int(round(sec * tpq * 1e6 / us))
|
||||
body += vlq(tick - last) + b
|
||||
last = tick
|
||||
end = int(round(12.5 * tpq * 1e6 / us))
|
||||
body += vlq(end - last) + b"\xff\x2f\x00"
|
||||
return b"MThd" + struct.pack(">IHHH", 6, 0, 1, tpq) + b"MTrk" + struct.pack(">I", len(body)) + bytes(body)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
sf2, expect = build_sf2(False)
|
||||
sf2_24, _ = build_sf2(True)
|
||||
mid = song()
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
fp, mp, wp = os.path.join(d, "t.sf2"), os.path.join(d, "t.mid"), os.path.join(d, "t.wav")
|
||||
with open(fp, "wb") as f:
|
||||
f.write(sf2)
|
||||
with open(mp, "wb") as f:
|
||||
f.write(mid)
|
||||
ctx.nix("fluidsynth", ["fluidsynth", "-ni", "-q", "-R", "0", "-C", "0", "-g", "0.5", "-r", "44100", "-F", wp, fp, mp])
|
||||
with open(wp, "rb") as f:
|
||||
wav = f.read()
|
||||
fluid = json.loads(ctx.python(["numpy"], ctx.read("tools/fixtures/_sf2_features.py").decode(), input=wav))
|
||||
ctx.emit("sf2_cases", {"sf2": sf2, "sf2_24": sf2_24, "song": mid, "fluid": fluid, "expect": expect})
|
||||
@@ -0,0 +1,27 @@
|
||||
# Video bench inputs (tools/fixtures.py, for tools/bench.luau): 1 s of testsrc2 at 320x240 and 640x480, 25 fps, as
|
||||
# MJPEG AVI, MPEG-1 TS, VP8 WebM (libvpx) and 8 frames of 320x240 Y4M.
|
||||
# tests/gen/videobench.luau { { name, size, data } }
|
||||
import importlib.util, os, tempfile
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("_video_helpers", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_video.py"))
|
||||
V = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(V)
|
||||
|
||||
INPUTS = ["tools/fixtures/_video.py"]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
tmp = tempfile.mkdtemp(prefix="videobench_")
|
||||
out = []
|
||||
for size in ("320x240", "640x480"):
|
||||
src = ["-f", "lavfi", "-i", "testsrc2=size=%s:rate=25" % size, "-t", "1"]
|
||||
for name, args in (("mjpeg.avi", ["-c:v", "mjpeg", "-q:v", "4"]),
|
||||
("mpeg1.ts", ["-c:v", "mpeg1video", "-b:v", "2M", "-bf", "2", "-f", "mpegts"]),
|
||||
("vp8.webm", ["-c:v", "libvpx", "-b:v", "1M", "-g", "50"]),
|
||||
("raw.y4m", ["-pix_fmt", "yuv420p", "-frames:v", "8"])):
|
||||
if name == "raw.y4m" and size == "640x480":
|
||||
continue
|
||||
path = os.path.join(tmp, size + "_" + name)
|
||||
V.ffmpeg(src + args + [path])
|
||||
out.append({"name": name, "size": size, "data": open(path, "rb").read()})
|
||||
ctx.emit("videobench", out)
|
||||
@@ -0,0 +1,63 @@
|
||||
# Our video writers checked by ffprobe / ffmpeg (tools/fixtures.py): tools/fixtures/_video_encode.luau remuxes /
|
||||
# re-encodes the container fixtures (WebM remux, MJPEG Matroska / AVI / MP4 from VP8 and MPEG-1, MJPEG copies, H.264 +
|
||||
# AAC MP4 to MOV / Matroska, PCM MOV, FLAC MP4, an animated GIF with uneven delays to AVI / Matroska / Y4M / MP4, WebM
|
||||
# to Y4M); each output must probe in ffprobe and decode in
|
||||
# ffmpeg. Emitted per file: our bytes, ffprobe's streams and packets, ffmpeg's frames (CRC-32; the first raw) and
|
||||
# audio, so the test can decode our file with our decoders and compare.
|
||||
# tests/gen/videoenc_src.luau { gif = <animated GIF made by Pillow: 4 frames, 100 / 50 / 200 / 100 ms> }
|
||||
# tests/gen/videoenc_cases.luau { { name, data, streams, packets, frames, yuv, pcm, pcmBytes } | { name, err } }
|
||||
import importlib.util, os, shutil, subprocess, tempfile
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("_video_helpers", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_video.py"))
|
||||
V = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(V)
|
||||
|
||||
INPUTS = ["tools/fixtures/_video.py", "tools/fixtures/_video_encode.luau", "tools/fixtures/mkv.py", "tools/fixtures/avi.py", "tools/fixtures/mp4.py",
|
||||
"src/Formats/video", "src/Formats/codecs/Video", "src/Formats/containers/Ebml", "src/Formats/containers/Avi", "src/Formats/containers/IsoBmff",
|
||||
"src/Formats/codecs/Jpeg", "src/Formats/codecs/Vp8"]
|
||||
|
||||
GIF = r"""
|
||||
import io, sys
|
||||
from PIL import Image, ImageDraw
|
||||
frames = []
|
||||
for i, c in enumerate([(255, 0, 0), (0, 160, 0), (0, 0, 255), (240, 200, 0)]):
|
||||
im = Image.new("RGB", (64, 48), (20, 20, 20))
|
||||
d = ImageDraw.Draw(im)
|
||||
d.rectangle([4 + i * 10, 8, 24 + i * 10, 40], fill=c)
|
||||
d.ellipse([40, 4 + i * 6, 60, 20 + i * 6], fill=(255, 255, 255))
|
||||
frames.append(im)
|
||||
b = io.BytesIO()
|
||||
frames[0].save(b, "GIF", save_all=True, append_images=frames[1:], duration=[100, 50, 200, 100], loop=0)
|
||||
sys.stdout.buffer.write(b.getvalue())
|
||||
"""
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
tmp = tempfile.mkdtemp(prefix="videoenc_")
|
||||
gif = ctx.python(["pillow"], GIF)
|
||||
ctx.emit("videoenc_src", {"gif": gif})
|
||||
luau = os.environ.get("LUAU") or shutil.which("luau")
|
||||
cmd = [luau, "tools/fixtures/_video_encode.luau"] if luau else ["nix", "shell", "nixpkgs#luau", "-c", "luau", "tools/fixtures/_video_encode.luau"]
|
||||
out = subprocess.run(cmd, capture_output=True, check=True, cwd=ctx.root).stdout.decode()
|
||||
cases = []
|
||||
for line in out.split("\n"):
|
||||
if not line.strip():
|
||||
continue
|
||||
name, rest = line.split(" ", 1)
|
||||
if rest.startswith("ERR "):
|
||||
cases.append({"name": name, "err": rest[4:]})
|
||||
continue
|
||||
path = os.path.join(tmp, name)
|
||||
open(path, "wb").write(bytes.fromhex(rest))
|
||||
c = {"name": name, "data": open(path, "rb").read(), "streams": V.streams(path), "packets": V.packets(path)}
|
||||
vs = [s for s in c["streams"] if s["kind"] == "video"]
|
||||
if vs:
|
||||
frames = V.yuv_frames(path, vs[0]["width"], vs[0]["height"], codec=vs[0]["codec"])
|
||||
c["frames"] = [V.crc(f) for f in frames]
|
||||
c["yuv"] = frames[:3]
|
||||
if any(s["kind"] == "audio" for s in c["streams"]):
|
||||
pcm = V.pcm_f32(path)
|
||||
c["pcm"] = pcm[:8192 * 4]
|
||||
c["pcmBytes"] = len(pcm)
|
||||
cases.append(c)
|
||||
ctx.emit("videoenc_cases", cases)
|
||||
@@ -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)
|
||||
@@ -0,0 +1,133 @@
|
||||
# VP8 video fixtures (tools/fixtures.py) for tests/codecs/vp8video.luau and tools/bench.luau. Clips are encoded by
|
||||
# ffmpeg's libvpx into IVF (many encoder settings: alt-ref / hidden frames, golden refreshes, token partitions, error
|
||||
# resilience, profiles 1-3, sharpness, segmentation, q extremes, short key frame intervals, motion off the frame edges),
|
||||
# plus the official VP8 test vectors (tests/fixtures/vp8video/vp80-*.ivf, from the libvpx test data, BSD:
|
||||
# licenses/libvpx-LICENSE.txt). The reference output is ffmpeg's native vp8 decoder (bit-exact with libvpx):
|
||||
# `ffmpeg -c:v vp8 -i x.ivf -noautoscale -fps_mode passthrough -f framehash -hash crc32 -`: the CRC32 of every
|
||||
# shown yuv420p frame (and its size: key frames may change it).
|
||||
# tests/gen/vp8video_cases.luau { name, ivf, width, height (of the first frame), crcs, sizes (bytes) }
|
||||
# tests/gen/vp8video_bench.luau { { name, ivf, width, height, frames, crcs, sizes } } for tools/bench.luau
|
||||
import os, shutil, subprocess, tempfile, zlib
|
||||
|
||||
INPUTS = ["tests/fixtures/vp8video"]
|
||||
|
||||
VECTORS = "tests/fixtures/vp8video"
|
||||
|
||||
|
||||
def ffmpeg(ctx, args):
|
||||
"""runs ffmpeg (the one on PATH when it has libvpx, else nixpkgs#ffmpeg) and returns stdout"""
|
||||
exe = shutil.which("ffmpeg")
|
||||
if exe:
|
||||
enc = subprocess.run([exe, "-hide_banner", "-encoders"], capture_output=True).stdout
|
||||
if b"libvpx " in enc:
|
||||
return subprocess.run([exe, "-hide_banner", "-loglevel", "error"] + args, capture_output=True, check=True).stdout
|
||||
return ctx.nix("ffmpeg", ["ffmpeg", "-hide_banner", "-loglevel", "error"] + args)
|
||||
|
||||
|
||||
def ivf_size(data):
|
||||
return data[12] | data[13] << 8, data[14] | data[15] << 8
|
||||
|
||||
|
||||
def reference(ctx, path):
|
||||
"""ffmpeg's decode: (crc32, byte size) of each shown yuv420p frame (sizes may change at key frames)"""
|
||||
out = ffmpeg(ctx, ["-c:v", "vp8", "-i", path, "-noautoscale", "-fps_mode", "passthrough", "-f", "framehash",
|
||||
"-hash", "crc32", "-"])
|
||||
frames = []
|
||||
for line in out.decode().splitlines():
|
||||
if line and not line.startswith("#"):
|
||||
f = [x.strip() for x in line.split(",")]
|
||||
frames.append((int(f[5], 16), int(f[4])))
|
||||
return frames
|
||||
|
||||
|
||||
# (name, lavfi source, frames, encoder options)
|
||||
SRC_320 = "testsrc2=s=320x240:r=25"
|
||||
PAN = "testsrc2=s=480x360:r=25,crop=w=320:h=240:x='80+70*sin(t*3)':y='60+50*cos(t*2)'"
|
||||
CLIPS = [
|
||||
("default_320x240", SRC_320, 20, ["-b:v", "400k"]),
|
||||
("odd_173x95", "mandelbrot=s=173x95:r=25", 16, ["-b:v", "200k"]),
|
||||
("pan_320x240", PAN, 24, ["-b:v", "300k", "-g", "100"]),
|
||||
("altref_352x288", "testsrc2=s=352x288:r=25", 30,
|
||||
["-b:v", "300k", "-auto-alt-ref", "1", "-lag-in-frames", "16", "-arnr-maxframes", "7", "-arnr-strength", "5",
|
||||
"-arnr-type", "3", "2pass"]),
|
||||
("altref_pan", PAN, 30, ["-b:v", "250k", "-auto-alt-ref", "1", "-lag-in-frames", "25", "-g", "200", "2pass"]),
|
||||
("tokenparts3", SRC_320, 12, ["-b:v", "500k", "-slices", "8"]),
|
||||
("tokenparts1_odd", "mandelbrot=s=201x77:r=25", 12, ["-b:v", "300k", "-slices", "2"]),
|
||||
("error_resilient", PAN, 16, ["-b:v", "300k", "-error-resilient", "1"]),
|
||||
("profile1", PAN, 16, ["-b:v", "300k", "-profile:v", "1"]),
|
||||
("profile2", PAN, 16, ["-b:v", "300k", "-profile:v", "2"]),
|
||||
("profile3", PAN, 16, ["-b:v", "300k", "-profile:v", "3"]),
|
||||
("sharpness7", PAN, 12, ["-b:v", "200k", "-sharpness", "7"]),
|
||||
("sharpness3", "mandelbrot=s=160x120:r=25", 12, ["-b:v", "150k", "-sharpness", "3"]),
|
||||
("realtime_cyclic", PAN, 24,
|
||||
["-deadline", "realtime", "-cpu-used", "8", "-b:v", "200k", "-static-thresh", "100", "-screen-content-mode", "1"]),
|
||||
("realtime_noise", "testsrc2=s=320x240:r=25,noise=alls=30:allf=t", 16,
|
||||
["-deadline", "realtime", "-cpu-used", "4", "-b:v", "400k"]),
|
||||
("best_split", "testsrc2=s=176x144:r=25,rotate=a='t*0.4':c=black", 16, ["-deadline", "best", "-b:v", "250k"]),
|
||||
("cellauto_split", "cellauto=s=176x144:rule=110:r=25,scale=176:144", 16, ["-b:v", "300k", "-cpu-used", "0"]),
|
||||
("q_high", PAN, 10, ["-qmin", "0", "-qmax", "2", "-b:v", "20M"]),
|
||||
("q_low", PAN, 16, ["-qmin", "60", "-qmax", "63", "-b:v", "20k"]),
|
||||
("keyint5", PAN, 16, ["-b:v", "300k", "-g", "5"]),
|
||||
("golden", "testsrc2=s=240x160:r=25", 40, ["-b:v", "150k", "-g", "300", "-auto-alt-ref", "0"]),
|
||||
("big_motion", "testsrc2=s=640x480:r=25,crop=w=192:h=144:x='224+200*sin(t*9)':y='168+150*cos(t*7)'", 16,
|
||||
["-b:v", "300k"]),
|
||||
("tiny_24x18", "testsrc2=s=24x18:r=25", 12, ["-b:v", "50k"]),
|
||||
("temporal_layers", PAN, 16,
|
||||
["-deadline", "realtime", "-b:v", "300k", "-ts-parameters",
|
||||
"ts_number_layers=2:ts_target_bitrate=150,300:ts_rate_decimator=2,1:ts_periodicity=2:ts_layer_id=0,1"]),
|
||||
]
|
||||
|
||||
BENCH = [
|
||||
("bench_320x240", "testsrc2=s=480x360:r=25,crop=w=320:h=240:x='80+70*sin(t*3)':y='60+50*cos(t*2)'", 40,
|
||||
["-b:v", "500k"]),
|
||||
("bench_640x480", "testsrc2=s=960x720:r=25,crop=w=640:h=480:x='160+150*sin(t*3)':y='120+100*cos(t*2)'", 30,
|
||||
["-b:v", "1200k"]),
|
||||
]
|
||||
|
||||
|
||||
def encode(ctx, tmp, name, src, frames, opts):
|
||||
path = os.path.join(tmp, name + ".ivf")
|
||||
base = ["-f", "lavfi", "-i", src, "-frames:v", str(frames), "-pix_fmt", "yuv420p", "-c:v", "libvpx"]
|
||||
try:
|
||||
if "2pass" in opts: # alt-ref frames need the two-pass encoder
|
||||
opts = [o for o in opts if o != "2pass"]
|
||||
log = os.path.join(tmp, name + "-pass")
|
||||
ffmpeg(ctx, base + opts + ["-pass", "1", "-passlogfile", log, "-f", "null", "-"])
|
||||
opts = opts + ["-pass", "2", "-passlogfile", log]
|
||||
ffmpeg(ctx, base + opts + ["-f", "ivf", "-y", path])
|
||||
except subprocess.CalledProcessError as e:
|
||||
if name == "temporal_layers": # optional: depends on the libvpx wrapper's options
|
||||
return None
|
||||
raise RuntimeError("vp8video: %s: %s" % (name, e.stderr.decode(errors="replace")))
|
||||
return path
|
||||
|
||||
|
||||
def case(ctx, name, path):
|
||||
with open(path, "rb") as f:
|
||||
data = f.read()
|
||||
w, h = ivf_size(data)
|
||||
ref = reference(ctx, path)
|
||||
return {"name": name, "ivf": data, "width": w, "height": h, "crcs": [r[0] for r in ref], "sizes": [r[1] for r in ref]}
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
tmp = tempfile.mkdtemp(prefix="vp8video")
|
||||
try:
|
||||
cases = []
|
||||
vec = os.path.join(ctx.root, VECTORS)
|
||||
for f in sorted(os.listdir(vec)):
|
||||
if f.endswith(".ivf"):
|
||||
cases.append(case(ctx, f[:-4], os.path.join(vec, f)))
|
||||
for name, src, frames, opts in CLIPS:
|
||||
path = encode(ctx, tmp, name, src, frames, opts)
|
||||
if path:
|
||||
cases.append(case(ctx, name, path))
|
||||
ctx.emit("vp8video_cases", cases)
|
||||
bench = []
|
||||
for name, src, frames, opts in BENCH:
|
||||
c = case(ctx, name, encode(ctx, tmp, name, src, frames, opts))
|
||||
c["frames"] = len(c["crcs"])
|
||||
bench.append(c)
|
||||
ctx.emit("vp8video_bench", bench)
|
||||
finally:
|
||||
shutil.rmtree(tmp)
|
||||
@@ -0,0 +1,167 @@
|
||||
# XM fixtures (tools/fixtures.py): generated FastTracker 2 modules exercising instruments (envelopes, fadeout,
|
||||
# auto-vibrato, keymaps, 16-bit and ping-pong samples) and the effects, rendered by openmpt123.
|
||||
# tests/gen/xm_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py),
|
||||
# duration (openmpt's song length) }
|
||||
import os, sys
|
||||
|
||||
# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml)
|
||||
T = sys.modules.get("_tracker")
|
||||
if T is None:
|
||||
import importlib.util
|
||||
_spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py"))
|
||||
T = importlib.util.module_from_spec(_spec)
|
||||
sys.modules["_tracker"] = T
|
||||
_spec.loader.exec_module(T)
|
||||
|
||||
INPUTS = ["tools/fixtures/_tracker.py"]
|
||||
|
||||
OFF = 97
|
||||
Gx, Hx, Kx, Lx, Px, Rx, Tx, Xx = 16, 17, 20, 21, 25, 27, 29, 33
|
||||
|
||||
|
||||
def empty(ch, rows=64):
|
||||
return [[(0, 0, 0, 0, 0) for _ in range(ch)] for _ in range(rows)]
|
||||
|
||||
|
||||
def put(p, row, ch, note=0, ins=0, vol=0, fx=0, param=0):
|
||||
p[row][ch] = (note, ins, vol, fx, param)
|
||||
|
||||
|
||||
def instruments():
|
||||
sine = {"name": "sine", "data": T.s8(T.synth("sine", 64, 64)), "volume": 64, "pan": 128, "loop": (0, 64, 1)}
|
||||
tri = {"name": "tri", "data": T.s8(T.synth("tri", 32, 32, 0.8)), "volume": 48, "pan": 96, "relnote": 12, "finetune": -20,
|
||||
"loop": (0, 32, 1)}
|
||||
saw16 = {"name": "saw16", "data": T.s16(T.synth("saw", 128, 64, 0.6)), "bits": 16, "volume": 56, "pan": 160,
|
||||
"loop": (0, 128, 1)}
|
||||
ping = {"name": "ping", "data": T.s8(T.synth("saw", 200, 200, 0.7)), "volume": 64, "pan": 128, "finetune": 30,
|
||||
"loop": (20, 150, 2)}
|
||||
noise = {"name": "noise", "data": T.s8(T.synth("noise", 5000, 1, 0.7, decay=1500)), "volume": 60, "pan": 128}
|
||||
square = {"name": "square", "data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 64, "pan": 128, "loop": (0, 64, 1)}
|
||||
return [
|
||||
{"name": "env", "samples": [sine], "volenv": {"points": [(0, 0), (4, 64), (10, 40), (30, 20), (40, 0)], "sustain": 2},
|
||||
"fadeout": 1024},
|
||||
{"name": "panloop", "samples": [square], "panenv": {"points": [(0, 0), (8, 64), (16, 0)], "loop": (0, 2)},
|
||||
"volenv": {"points": [(0, 64), (20, 48), (60, 32)], "loop": (1, 2)}, "fadeout": 512},
|
||||
{"name": "autovib", "samples": [saw16], "vib": (0, 10, 8, 6)},
|
||||
{"name": "multi", "samples": [sine, tri], "keymap": [0] * 48 + [1] * 48},
|
||||
{"name": "ping", "samples": [ping]},
|
||||
{"name": "noise", "samples": [noise]},
|
||||
{"name": "sq vib", "samples": [square], "vib": (1, 0, 4, 20)},
|
||||
{"name": "empty"},
|
||||
]
|
||||
|
||||
|
||||
def song_instruments():
|
||||
a, b = empty(4), empty(4)
|
||||
put(a, 0, 0, 49, 1)
|
||||
put(a, 12, 0, OFF)
|
||||
put(a, 20, 0, 56, 1)
|
||||
put(a, 24, 0, 0, 0, 0, Kx, 3)
|
||||
put(a, 32, 0, 61, 1)
|
||||
put(a, 33, 0, 0, 0, 0, Lx, 20)
|
||||
put(a, 40, 0, 63)
|
||||
put(a, 44, 0, OFF)
|
||||
put(a, 48, 0, 0, 1)
|
||||
put(a, 0, 1, 37, 2)
|
||||
put(a, 30, 1, OFF)
|
||||
put(a, 40, 1, 44, 2)
|
||||
put(a, 0, 2, 49, 3)
|
||||
put(a, 32, 2, 56, 3)
|
||||
put(a, 8, 3, 37, 4)
|
||||
put(a, 16, 3, 61, 4)
|
||||
put(a, 24, 3, 73, 4)
|
||||
put(a, 32, 3, 85, 4)
|
||||
put(a, 40, 3, 49, 5)
|
||||
put(a, 52, 3, 61, 5)
|
||||
put(a, 60, 3, 61, 8)
|
||||
put(b, 0, 0, 49, 7)
|
||||
put(b, 0, 1, 56, 3, 0x30)
|
||||
put(b, 8, 1, 0, 3)
|
||||
put(b, 16, 2, 61, 6, 0x40)
|
||||
put(b, 20, 2, 61, 6, 0, 0x9, 0x08)
|
||||
put(b, 24, 2, 61, 6, 0, 0xE, 0x93)
|
||||
put(b, 32, 3, 49, 1)
|
||||
put(b, 36, 3, 61)
|
||||
put(b, 40, 3, OFF)
|
||||
put(b, 44, 3, 63)
|
||||
put(b, 48, 0, 0, 0, 0, 0xD, 0x00)
|
||||
return T.write_xm("instruments", instruments(), [0, 1], [a, b], 4)
|
||||
|
||||
|
||||
def song_effects(linear=True):
|
||||
a, b = empty(6), empty(6, 48)
|
||||
put(a, 0, 0, 49, 7, 0, 0x1, 0x04)
|
||||
put(a, 4, 0, 0, 0, 0, 0x1, 0x00)
|
||||
put(a, 8, 0, 0, 0, 0, 0x2, 0x08)
|
||||
put(a, 12, 0, 0, 0, 0, 0xE, 0x18)
|
||||
put(a, 13, 0, 0, 0, 0, 0xE, 0x10)
|
||||
put(a, 14, 0, 0, 0, 0, 0xE, 0x2F)
|
||||
put(a, 16, 0, 0, 0, 0, Xx, 0x1F)
|
||||
put(a, 17, 0, 0, 0, 0, Xx, 0x10)
|
||||
put(a, 18, 0, 0, 0, 0, Xx, 0x28)
|
||||
put(a, 20, 0, 49, 7, 0, 0x3, 0x10)
|
||||
put(a, 21, 0, 61, 0, 0, 0x3, 0x00)
|
||||
put(a, 24, 0, 0, 0, 0, 0x5, 0x02)
|
||||
put(a, 28, 0, 56, 0, 0, 0x4, 0x48)
|
||||
put(a, 32, 0, 0, 0, 0, 0x6, 0x20)
|
||||
put(a, 36, 0, 0, 0, 0, 0x7, 0x6F)
|
||||
put(a, 40, 0, 0, 0, 0, Tx, 0x21)
|
||||
put(a, 44, 0, 0, 0, 0, 0xA, 0x0F)
|
||||
put(a, 46, 0, 0, 0, 0, 0xE, 0xA8)
|
||||
put(a, 48, 0, 61, 7, 0, 0x0, 0x37)
|
||||
put(a, 52, 0, 0, 0, 0, 0xE, 0xC3)
|
||||
# channel 1: the volume column
|
||||
put(a, 0, 1, 56, 6, 0x30)
|
||||
put(a, 4, 1, 0, 0, 0x64)
|
||||
put(a, 8, 1, 0, 0, 0x73)
|
||||
put(a, 12, 1, 0, 0, 0x85)
|
||||
put(a, 13, 1, 0, 0, 0x9A)
|
||||
put(a, 16, 1, 0, 0, 0xA6)
|
||||
put(a, 17, 1, 0, 0, 0xB8)
|
||||
put(a, 24, 1, 0, 0, 0xC2)
|
||||
put(a, 28, 1, 0, 0, 0xE4)
|
||||
put(a, 32, 1, 0, 0, 0xD6)
|
||||
put(a, 36, 1, 61, 0, 0xF8)
|
||||
put(a, 40, 1, 49, 0, 0xF0)
|
||||
# channel 2: panning, retrig, offset, delay
|
||||
put(a, 0, 2, 61, 2, 0, 0x8, 0x20)
|
||||
put(a, 8, 2, 0, 0, 0, Px, 0x30)
|
||||
put(a, 16, 2, 0, 0, 0, Px, 0x06)
|
||||
put(a, 24, 2, 61, 6, 0, Rx, 0x83)
|
||||
put(a, 32, 2, 61, 6, 0, Rx, 0x32)
|
||||
put(a, 40, 2, 61, 6, 0, 0x9, 0x06)
|
||||
put(a, 48, 2, 61, 6, 0, 0xE, 0xD3)
|
||||
put(a, 56, 2, 61, 6, 0x20, 0xE, 0xC2)
|
||||
# channel 3: global volume, pattern loop, pattern delay, speed / tempo
|
||||
put(a, 0, 3, 37, 3, 0, Gx, 0x30)
|
||||
put(a, 8, 3, 0, 0, 0, Hx, 0x02)
|
||||
put(a, 16, 3, 0, 0, 0, Hx, 0x40)
|
||||
put(a, 24, 3, 0, 0, 0, 0xE, 0x60)
|
||||
put(a, 26, 3, 0, 0, 0, 0xE, 0x62)
|
||||
put(a, 32, 3, 0, 0, 0, 0xE, 0xE2)
|
||||
put(a, 40, 3, 0, 0, 0, 0xF, 0x05)
|
||||
put(a, 48, 3, 0, 0, 0, 0xF, 0x96)
|
||||
# channel 4 / 5: an instrument change without a note, an empty instrument, a note after key off
|
||||
put(a, 0, 4, 49, 1)
|
||||
put(a, 8, 4, 0, 2)
|
||||
put(a, 16, 4, OFF)
|
||||
put(a, 24, 4, 51)
|
||||
put(a, 32, 4, 51, 8)
|
||||
put(a, 40, 4, 53, 1)
|
||||
put(a, 4, 5, 73, 5, 0, 0xE, 0x80)
|
||||
put(a, 20, 5, 0, 0, 0, 0x8, 0xC0)
|
||||
# pattern b (48 rows): portamento in the other direction, arpeggio, a break and a jump back (song loop)
|
||||
put(b, 0, 0, 73, 7, 0, 0x4, 0x00)
|
||||
put(b, 0, 1, 61, 4)
|
||||
put(b, 4, 1, 0, 0, 0, 0x0, 0x47)
|
||||
put(b, 16, 1, 25, 4, 0, 0x2, 0x10)
|
||||
put(b, 32, 0, 0, 0, 0, 0xB, 0x01)
|
||||
return T.write_xm("effects", instruments(), [0, 1], [a, b], 6, speed=5, tempo=130, linear=linear, restart=1)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
cases = []
|
||||
for nm, data in (("instruments", song_instruments()), ("effects", song_effects()), ("amiga", song_effects(False))):
|
||||
ref = T.reference(ctx, data, "xm")
|
||||
cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]})
|
||||
ctx.emit("xm_cases", cases)
|
||||
@@ -0,0 +1,34 @@
|
||||
# YUV4MPEG2 fixtures (tools/fixtures.py): streams written by ffmpeg in C420jpeg (odd size 173x95), C420mpeg2, C422,
|
||||
# C444, Cmono and C420p10 (10-bit) with ffmpeg's yuv420p decode of each (CRC-32 per frame; the first frames raw for
|
||||
# the converted layouts, which are compared by PSNR).
|
||||
# tests/gen/y4m_cases.luau { { name, data, width, height, rate = { num, den }, frames = { crc }, yuv = { raw } } }
|
||||
import importlib.util, os, tempfile
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("_video_helpers", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_video.py"))
|
||||
V = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(V)
|
||||
|
||||
INPUTS = ["tools/fixtures/_video.py"]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
tmp = tempfile.mkdtemp(prefix="y4mfx_")
|
||||
cases = []
|
||||
for name, size, rate, pix, extra in [
|
||||
("c420jpeg.y4m", "173x95", "30000/1001", "yuv420p", []),
|
||||
("c420mpeg2.y4m", "160x120", "25", "yuv420p", ["-chroma_sample_location", "left"]),
|
||||
("c422.y4m", "160x120", "24", "yuv422p", []),
|
||||
("c444.y4m", "160x120", "10", "yuv444p", []),
|
||||
("cmono.y4m", "160x120", "10", "gray", []),
|
||||
("c420p10.y4m", "96x64", "10", "yuv420p10le", ["-strict", "-1"]),
|
||||
]:
|
||||
path = os.path.join(tmp, name)
|
||||
w, h = (int(x) for x in size.split("x"))
|
||||
V.ffmpeg(["-f", "lavfi", "-i", "testsrc2=size=%s:rate=%s" % (size, rate), "-frames:v", "6", "-vf",
|
||||
"pad=%d:%d" % (w + 1, h + 1) if w % 2 else "null", "-s", size, "-pix_fmt", pix] + extra + [path])
|
||||
frames = V.yuv_frames(path, w, h)
|
||||
num, den = (rate.split("/") + ["1"])[:2]
|
||||
cases.append({"name": name, "data": open(path, "rb").read(), "width": w, "height": h,
|
||||
"rate": [int(num), int(den)], "frames": [V.crc(f) for f in frames], "yuv": frames[:2],
|
||||
"exact": pix == "yuv420p"})
|
||||
ctx.emit("y4m_cases", cases)
|
||||
+1
-1
@@ -14,7 +14,7 @@ python3 -I tools/fixtures.py $1 || { echo "FAILED: fixtures"; exit 1; }
|
||||
python3 -I tools/gen_registry.py > /dev/null || { echo "FAILED: gen_registry"; exit 1; }
|
||||
python3 -I tools/build.py || { echo "FAILED: build"; exit 1; }
|
||||
passed=0
|
||||
for t in $(find tests -name '*.luau' -not -path 'tests/gen/*' -not -path 'tests/fixtures/*' -not -name 'T.luau' | sort); do
|
||||
for t in $(find tests -name '*.luau' -not -path 'tests/gen/*' -not -path 'tests/fixtures/*' -not -name 'T.luau' -not -name '_*' | sort); do
|
||||
[ -n "$1" ] && [[ "$t" != *$1* ]] && continue
|
||||
for rt in $RUNTIMES; do
|
||||
echo "== $t ($rt)"
|
||||
|
||||
Reference in new issue
Block a user