ws-audio2: merge master (c5f2777)

This commit is contained in:
4DBug committed 2026-10-31 15:37:55 -05:00
commit d7697a8688
126 files changed
+25832 -1541

No files matched your search

+282 -1
View File
@@ -1,7 +1,7 @@
-- Throughput (bash tools/bench.sh): codec MB/s under both runtimes. MB/s are of decompressed output, best of n runs.
-- Fixtures: tools/fixtures/deflate.py (a 6 MB corpus), tools/fixtures/png.py (1024 x 768 images), tools/fixtures/mp3.py,
-- tools/fixtures/opus.py (3 s stereo files; MB/s of f32 output, 48 kHz stereo f32 is 0.384 MB/s of real time),
-- tools/fixtures/flac.py; wav encodes / decodes a generated tone; zstd / brotli / bzip2 / lzma (*_bench corpora), fonts
-- tools/fixtures/flac.py; wav encodes / decodes a generated tone; zstd / brotli / bzip2 / lzma / lz4 (*_bench corpora), fonts
-- (glyphs per second), json / xml / yaml, jpeg / gif / tiff / qoi / tga / pnm / hdr and ImageOps.
local Deflate = require("@formats/codecs/compress/Deflate")
local Crc32 = require("@formats/core/Crc32")
@@ -236,6 +236,53 @@ do
Zstd.decompress(z19, nil, nil, { verify = false })
end)
end
do
local Lz4 = require("@formats/codecs/compress/Lz4")
local LB = require("@tests/gen/lz4_bench")
local lz = buffer.fromstring(LB.data)
local raw = assert(Lz4.decompress(lz, nil, nil, LB.size))
assert(Crc32.of(raw) == LB.crc, "lz4 bench corpus mismatch")
bench("lz4 block decompress (hc9)", 5, LB.size, function()
Lz4.decompress(lz, nil, nil, LB.size)
end)
bench("lz4 block compress", 3, LB.size, function()
Lz4.compress(raw)
end)
end
-- ws-roblox: a model of 20000 parts (built here) through model/rbxm and model/rbxmx, and a .mesh decode
do
local Rbx = require("@formats/codecs/model/Rbx")
local Rbxm = require("@formats/model/rbxm")
local Rbxmx = require("@formats/model/rbxmx")
local RobloxMesh = require("@formats/model/robloxmesh")
local tree = Rbx.tree()
local folder = Rbx.add(tree, Rbx.instance("Folder", "Parts"))
for i = 1, 20000 do
local p = Rbx.add(folder, Rbx.instance("Part", "P" .. i))
Rbx.set(p, "CFrame", "CFrame", { i, i % 7, -i, 1, 0, 0, 0, 1, 0, 0, 0, 1 })
Rbx.set(p, "size", "Vector3", { 4, 1, 2 + i % 3 })
Rbx.set(p, "Color3uint8", "Color3uint8", { i % 256, 128, 255 - i % 256 })
Rbx.set(p, "Anchored", "Bool", i % 2 == 0)
Rbx.set(p, "Transparency", "Float32", (i % 4) / 4)
Rbx.set(p, "Material", "Enum", 256)
end
local bin = Rbxm.encode(tree) :: buffer
local xml = Rbxmx.encode(tree) :: buffer
bench("rbxm decode (20k parts)", 3, buffer.len(bin), function()
Rbxm.decode(Bytes.reader(bin))
end)
bench("rbxm encode (20k parts)", 3, buffer.len(bin), function()
Rbxm.encode(tree)
end)
bench("rbxmx decode (20k parts)", 3, buffer.len(xml), function()
Rbxmx.decode(Bytes.reader(xml))
end)
local M = require("@tests/gen/robloxmesh")
local mesh = buffer.fromstring(M.cases[#M.cases - 1].data)
bench("robloxmesh decode (v7, skinned)", 20, buffer.len(mesh), function()
RobloxMesh.decode(Bytes.reader(mesh))
end)
end
do
local Brotli = require("@formats/codecs/compress/Brotli")
local BB = require("@tests/gen/brotli_bench")
@@ -1078,6 +1125,240 @@ do
jitTune(false)
end
end
do
-- NBT / voxels (ws-voxel): a chunk-like NBT tree (24 sections with packed long arrays, 4000 entity-like compounds)
-- through codecs/text/Nbt (binary and SNBT), 1M packed 5-bit indices, a 64^3 Sponge schematic and Qubicle file
local Nbt = require("@formats/codecs/text/Nbt")
local Mc = require("@formats/codecs/model/Minecraft")
local Schematic = require("@formats/model/schematic")
local Qb = require("@formats/model/qb")
local sections = Nbt.list("compound")
for s = 1, 24 do
local pal = Nbt.list("compound")
for p = 1, 16 do
table.insert(pal, Nbt.compound({ Name = "minecraft:block_" .. p, Properties = Nbt.compound({ axis = "y" }, { "axis" }) }, { "Name", "Properties" }))
end
local longs = buffer.create(256 * 8)
for i = 0, 511 do
buffer.writeu32(longs, i * 4, (i * 2654435761) % 4294967296)
end
table.insert(sections, Nbt.compound({ Y = Nbt.byte(s - 5), block_states = Nbt.compound({ palette = pal, data = Nbt.longArray(longs) }, { "palette", "data" }) }, { "Y", "block_states" }))
end
local ents = Nbt.list("compound")
for i = 1, 4000 do
table.insert(ents, Nbt.compound({
id = "minecraft:thing",
Pos = Nbt.list("double", { Nbt.double(i * 0.5), Nbt.double(64), Nbt.double(-i * 0.25) }),
Health = Nbt.float(20),
UUID = Nbt.intArray({ i, -i, i * 3, 7 }),
Tags = Nbt.list("string", { "a", "b" }),
Age = Nbt.short(i % 1000),
Seed = Nbt.long(i * 1234567),
}, { "id", "Pos", "Health", "UUID", "Tags", "Age", "Seed" }))
end
local root = Nbt.compound({ DataVersion = 3953, sections = sections, entities = ents }, { "DataVersion", "sections", "entities" })
local raw = assert(Nbt.encode(root, { compression = "none" }))
bench("nbt decode (" .. buffer.len(raw) // 1000 .. " KB)", 5, buffer.len(raw), function()
Nbt.decode(raw)
end)
bench("nbt encode", 5, buffer.len(raw), function()
Nbt.encode(root, { compression = "none" })
end)
local text = assert(Nbt.print(root))
bench("snbt parse (" .. #text // 1000 .. " KB)", 3, #text, function()
Nbt.parse(text)
end)
bench("snbt print", 3, #text, function()
Nbt.print(root)
end)
local n = 1048576
local idx = buffer.create(n * 2)
for i = 0, n - 1 do
buffer.writeu16(idx, i * 2, (i * 7) % 32)
end
local packed = Mc.Packed.pack(idx, n, 5, false)
local out = buffer.create(n * 2)
bench("packed unpack 1M x 5 bits (MB out)", 5, n * 2, function()
Mc.Packed.unpack(packed, 5, n, false, out, 32)
end)
local V = 64
local states = { "minecraft:air" }
for i = 1, 40 do
table.insert(states, "minecraft:block_" .. i)
end
local cells = buffer.create(V * V * V * 2)
for i = 0, V * V * V - 1 do
buffer.writeu16(cells, i * 2, if (i // V) % 3 == 0 then 0 else 1 + (i // 97) % 40)
end
local grid = Mc.voxels(V, V, V, states, cells)
local schem = assert(Schematic.encode(grid, { compression = "none" }))
bench("schem decode 64^3 (MB of cells)", 3, V * V * V, function()
Schematic.decode(Bytes.reader(schem))
end)
bench("schem encode 64^3", 3, V * V * V, function()
Schematic.encode(grid, { compression = "none" })
end)
local qb = assert(Qb.encode(grid))
bench("qb decode 64^3 rle (MB of cells)", 3, V * V * V, function()
Qb.decode(Bytes.reader(qb))
end)
end
-- ------------------------------------------------------------------------------------------- ws-video-codecs: fps
do
local Jpeg = require("@formats/codecs/image/Jpeg")
local Mpeg1 = require("@formats/codecs/video/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
-- (LuaJIT also with the trace limits the api sets, host/init.luau: the default 1000 traces thrash on MPEG-1)
local function mpeg1(tag: string)
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%s", if rgba then "rgba" else "yuv", s.width, s.height, tag), 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
-- MPEG-2: 720x576 interlaced (field prediction / field DCT, B-frames), as on a DVD (ws-video2)
local M2 = require("@tests/gen/mpeg2_bench")
local function mpeg2(tag: string)
for _, s in M2 do
local file = Base64.decode(s.file) :: buffer
fps(string.format("mpeg2 decode yuv %dx%d interlaced%s", s.width, s.height, tag), 3, #s.units, function()
local dec = Mpeg1.new({ reorder = true, rgba = false })
for i, u in s.units do
dec:decode(file, u[1], u[2], i)
end
while dec:flush() do
end
end)
end
end
jitTune(false)
mpeg1("")
mpeg2("")
if runtime == "luajit" then
jitTune(true)
mpeg1(" (jit tuned)")
mpeg2(" (jit tuned)")
jitTune(false)
end
end
do
-- ------------------------------------------------------------------------------------- ws-video2-theora: fps
-- Theora (codecs/video/Theora): 320x240 clips, 50 frames, keyframe every 25: testsrc2 at 600 kbit/s (mostly static:
-- few coded blocks) and a mandelbrot zoom at 1200 kbit/s (every block coded, moving); decode alone and decode +
-- image() (the yuv420p copy every VideoDecoder frame makes)
local Theora = require("@formats/codecs/video/Theora")
local Ogg = require("@formats/containers/Ogg")
local Base64 = require("@formats/core/Base64")
local TB = require("@tests/gen/theora_bench")
local function run(tag: string)
for _, c in TB do
local d = Ogg.open(Base64.decode(c.file) :: buffer)
local hdrs, data = {}, {}
for p in d:packets(d:find("theora")) do
table.insert(if #hdrs < 3 then hdrs else data, Ogg.copy(p))
end
for _, image in { false, true } do
local n = c.width * c.height * 3 // 2 * #data
local dt = bench(string.format("theora %s %dx%d%s%s", c.name, c.width, c.height, if image then " +img" else "", tag), 3, n, function()
local dec = Theora.new(hdrs) :: any
for _, p in data do
dec:decode(p)
if image then
dec:image()
end
end
end)
print(string.format("%-8s %-30s %8.1f fps", runtime, " (" .. #data .. " frames)", #data / dt))
end
end
end
jitTune(false)
run("")
if runtime == "luajit" then
jitTune(true)
run(" (jit tuned)")
jitTune(false)
end
end
-- ------------------------------------------------------------------------------------------- ws-video2-legacy: fps
do
-- the legacy codecs (codecs/video/Legacy) through F.video.open, rgba8 frames out: ffmpeg's encoders at 320x240
-- (tools/fixtures/legacy.py), a 320x200 FLC (fli.py) and a 320x200 SMK4 (smk.py, textured: mostly FULL blocks);
-- frames per second of the whole decode (and the Smacker audio track, seconds of audio per second)
local F = require("@formats")
local LB = require("@tests/gen/legacy_bench")
local cases = table.clone(LB)
table.insert(cases, { name = "fli.flc", data = require("@tests/gen/fli_bench").data, width = 320, height = 200 })
table.insert(cases, { name = "smk4.smk", data = require("@tests/gen/smk_bench").data, width = 320, height = 200 })
for _, c in cases do
local data = buffer.fromstring(c.data)
local frames = 0
local dt = math.huge
for _ = 1, 3 do
local t0 = os.clock()
local v = assert(F.video.open(data, { audio = false }))
frames = 0
while v:nextFrame() do
frames += 1
end
dt = math.min(dt, os.clock() - t0)
end
print(string.format("%-8s %-30s %8.2f ms %7.1f fps", runtime, string.format("legacy %s %dx%d", c.name, c.width, c.height), dt * 1000 / frames, frames / dt))
end
local v = assert(F.video.open(buffer.fromstring(require("@tests/gen/smk_bench").data)))
local a = assert(v.audio)
local t0 = os.clock()
local n = 0
while true do
local _, got = a:read(4096)
if got == 0 then
break
end
n += got
end
local dt = os.clock() - t0
print(string.format("%-8s %-30s %8.2f ms %7.1fx real time", runtime, "smacker audio 22 kHz stereo", dt * 1000, n / a.sampleRate / dt))
end
-- ws-audio2: chip/midi
do
-- AHX / HVL (codecs/audio/Hively): a whole song rendered at 44.1 kHz (tools/fixtures/ahx.py karma.ahx, 3 s; hvl.py
+375
View File
@@ -0,0 +1,375 @@
# Shared helpers for the legacy video fixture generators (legacy.py), loaded by path: tiny AVI and QuickTime MOV
# writers (one video track, constant frame rate) for streams encoded here, and small encoders for what ffmpeg cannot
# encode: QuickTime RLE at depths 1 / 2 / 4 / 8, Microsoft Video 1 at 8 bits, Cinepak at 8 bits (palettised).
import struct
def le16(v):
return struct.pack("<H", v & 0xFFFF)
def le32(v):
return struct.pack("<I", v & 0xFFFFFFFF)
def be16(v):
return struct.pack(">H", v & 0xFFFF)
def be32(v):
return struct.pack(">I", v & 0xFFFFFFFF)
# ---------------------------------------------------------------------------------------------------- AVI
def _ck(cid, body):
return cid + le32(len(body)) + body + (b"\0" if len(body) & 1 else b"")
def _lst(kind, body):
return b"LIST" + le32(len(body) + 4) + kind + body
def bitmapinfo(w, h, bits, fourcc, palette=None):
"""BITMAPINFOHEADER (+ palette: a list of (r, g, b) stored as B, G, R, 0)"""
n = len(palette) if palette else 0
out = le32(40) + le32(w) + le32(h) + le16(1) + le16(bits) + fourcc + le32(w * h * max(1, bits // 8)) + \
le32(0) + le32(0) + le32(n) + le32(0)
for r, g, b in palette or []:
out += bytes([b, g, r, 0])
return out
def avi(w, h, fourcc, strf, frames, keys, fps=10):
"""an AVI file: one video stream, frames = [bytes], keys = [bool]"""
n = len(frames)
avih = le32(1000000 // fps) + le32(0) + le32(0) + le32(0x10) + le32(n) + le32(0) + le32(1) + \
le32(max(len(f) for f in frames)) + le32(w) + le32(h) + bytes(16)
strh = b"vids" + fourcc + le32(0) + le16(0) + le16(0) + le32(0) + le32(1) + le32(fps) + le32(0) + le32(n) + \
le32(max(len(f) for f in frames)) + struct.pack("<i", -1) + le32(0) + struct.pack("<hhhh", 0, 0, w, h)
hdrl = _lst(b"hdrl", _ck(b"avih", avih) + _lst(b"strl", _ck(b"strh", strh) + _ck(b"strf", strf)))
movi = b""
idx = b""
for f, k in zip(frames, keys):
idx += b"00dc" + le32(0x10 if k else 0) + le32(4 + len(movi)) + le32(len(f))
movi += _ck(b"00dc", f)
body = b"AVI " + hdrl + _lst(b"movi", movi) + _ck(b"idx1", idx)
return b"RIFF" + le32(len(body)) + body
# ---------------------------------------------------------------------------------------------------- MOV
def _box(t, body):
return be32(8 + len(body)) + t + body
def qt_entry(fourcc, w, h, depth, ctab_id=0xFFFF, colors=None):
"""a QuickTime video sample description; colors = [(r, g, b)] makes a colour table (ctab_id 0)"""
body = bytes(6) + be16(1) + be16(0) + be16(0) + b"appl" + be32(0) + be32(512) + be16(w) + be16(h) + \
be32(72 << 16) + be32(72 << 16) + be32(0) + be16(1) + bytes([4]) + b"test" + bytes(27) + be16(depth)
if colors is not None:
body += be16(0) + be32(0) + be16(0x8000) + be16(len(colors) - 1)
for i, (r, g, b) in enumerate(colors):
body += be16(i) + bytes([r, r, g, g, b, b])
else:
body += be16(ctab_id)
return _box(fourcc, body)
def mov(w, h, entry, frames, keys, fps=10):
"""a QuickTime file: one video track with the sample description `entry`"""
scale, delta = fps * 100, 100
n = len(frames)
ftyp = _box(b"ftyp", b"qt " + be32(0x200) + b"qt ")
mdat_off = len(ftyp) + 8
offs, pos = [], mdat_off
for f in frames:
offs.append(pos)
pos += len(f)
mdat = _box(b"mdat", b"".join(frames))
matrix = be32(0x10000) + be32(0) + be32(0) + be32(0) + be32(0x10000) + be32(0) + be32(0) + be32(0) + be32(0x40000000)
dur = n * delta
mvhd = _box(b"mvhd", be32(0) + be32(0) + be32(0) + be32(scale) + be32(dur) + be32(0x10000) + be16(0x100) +
bytes(10) + matrix + bytes(24) + be32(2))
tkhd = _box(b"tkhd", be32(3) + be32(0) + be32(0) + be32(1) + be32(0) + be32(dur) + bytes(8) + be16(0) + be16(0) +
be16(0) + be16(0) + matrix + be32(w << 16) + be32(h << 16))
mdhd = _box(b"mdhd", be32(0) + be32(0) + be32(0) + be32(scale) + be32(dur) + be16(0) + be16(0))
hdlr = _box(b"hdlr", be32(0) + b"mhlr" + b"vide" + bytes(12) + b"\x05Video")
vmhd = _box(b"vmhd", be32(1) + bytes(8))
dinf = _box(b"dinf", _box(b"dref", be32(0) + be32(1) + _box(b"alis", be32(1))))
stsd = _box(b"stsd", be32(0) + be32(1) + entry)
stts = _box(b"stts", be32(0) + be32(1) + be32(n) + be32(delta))
sync = [i + 1 for i, k in enumerate(keys) if k]
stss = _box(b"stss", be32(0) + be32(len(sync)) + b"".join(be32(i) for i in sync))
stsc = _box(b"stsc", be32(0) + be32(1) + be32(1) + be32(1) + be32(1))
stsz = _box(b"stsz", be32(0) + be32(0) + be32(n) + b"".join(be32(len(f)) for f in frames))
stco = _box(b"stco", be32(0) + be32(n) + b"".join(be32(o) for o in offs))
stbl = _box(b"stbl", stsd + stts + stss + stsc + stsz + stco)
minf = _box(b"minf", vmhd + dinf + stbl)
mdia = _box(b"mdia", mdhd + hdlr + minf)
trak = _box(b"trak", tkhd + mdia)
moov = _box(b"moov", mvhd + trak)
return ftyp + mdat + moov
# ---------------------------------------------------------------------------------------------------- pictures
def index_frames(w, h, n, colors, seed=1):
"""n palettised pictures (rows of indexes < colors): bands, a moving square, a noisy patch; most of each frame
stays the same as the previous one (inter-frame codecs get skips)"""
import random
rnd = random.Random(seed)
out = []
for t in range(n):
img = [[((x // 7 + y // 5) % colors) for x in range(w)] for y in range(h)]
sx, sy = (t * 5) % max(1, w - 12), (t * 3) % max(1, h - 10)
for y in range(sy, min(h, sy + 10)):
for x in range(sx, min(w, sx + 12)):
img[y][x] = (t + 1) % colors
for y in range(h // 2, min(h, h // 2 + 6)):
for x in range(w // 3, min(w, w // 3 + 9)):
img[y][x] = rnd.randrange(colors)
out.append(img)
return out
def palette(n, seed=7):
import random
rnd = random.Random(seed)
return [(rnd.randrange(256), rnd.randrange(256), rnd.randrange(256)) for _ in range(n)]
# ---------------------------------------------------------------------------------------------------- QuickTime RLE
def _groups(row, per):
return [tuple(row[i:i + per]) for i in range(0, len(row), per)]
def _pack(group, bits):
out = bytearray()
per = 8 // bits
for i in range(0, len(group), per):
v = 0
for k in range(per):
v = (v << bits) | group[i + k]
out.append(v)
return bytes(out)
def qtrle_frame(img, prev, bits):
"""one 'rle ' frame at 1 / 2 / 4 / 8 bits (prev = the previous picture or None: changed line range only, with
skip codes inside lines)"""
h, w = len(img), len(img[0])
per = 16 if bits == 1 else 32 // bits # pixels per group
pw = (w + per - 1) // per * per
rows = [r + [0] * (pw - w) for r in img]
prow = [r + [0] * (pw - w) for r in prev] if prev else None
changed = [y for y in range(h) if not prow or rows[y] != prow[y]]
if not changed:
return be32(6) + be16(0)
y0, y1 = changed[0], changed[-1] + 1
body = bytearray()
for y in range(y0, y1):
g = _groups(rows[y], per)
pg = _groups(prow[y], per) if prow else None
if bits == 1:
# (skip, code) pairs: the first of a line has bit 7 set
first = True
i = 0
while i < len(g):
skip = 0
while pg and i < len(g) and g[i] == pg[i] and skip < 127:
skip += 1
i += 1
if i >= len(g):
if first:
body += bytes([0x80 | skip, 0xFF])
first = False
break
j = i
while j + 1 < len(g) and g[j + 1] == g[i] and j - i < 126:
j += 1
sb = (0x80 if first else 0) | skip
first = False
if j > i:
body += bytes([sb, 256 - (j - i + 1)]) + _pack(g[i], 1)
i = j + 1
else:
k = i
while k < len(g) and k - i < 63 and not (pg and g[k] == pg[k]) and not (k + 1 < len(g) and g[k + 1] == g[k]):
k += 1
k = max(k, i + 1)
body += bytes([sb, k - i]) + b"".join(_pack(x, 1) for x in g[i:k])
i = k
if first:
body += bytes([0x80, 0xFF])
continue
line = bytearray([1])
i = 0
while i < len(g):
skip = 0
while pg and i < len(g) and g[i] == pg[i] and skip < 250:
skip += 1
i += 1
if i >= len(g):
break
if skip:
line += bytes([0, skip + 1])
j = i
while j + 1 < len(g) and g[j + 1] == g[i] and j - i < 126:
j += 1
if j > i:
line += bytes([256 - (j - i + 1)]) + _pack(g[i], bits)
i = j + 1
else:
k = i
while k < len(g) and k - i < 127 and not (pg and g[k] == pg[k]) and not (k + 1 < len(g) and g[k + 1] == g[k]):
k += 1
k = max(k, i + 1)
line += bytes([k - i]) + b"".join(_pack(x, bits) for x in g[i:k])
i = k
line += b"\xff"
body += line
if bits == 1:
body += b"\x00\x00"
else:
body += b"\x00"
head = be16(8) + be16(y0) + be16(0) + be16(y1 - y0) + be16(0)
return be32(4 + len(head) + len(body)) + head + bytes(body)
# ---------------------------------------------------------------------------------------------------- MS Video 1
def _block(img, bx, by):
"""the 16 pixels of a block, MS Video 1 order: bottom row first, left to right"""
return [img[by * 4 + 3 - y][bx * 4 + x] for y in range(4) for x in range(4)]
def msvc8_frame(img, prev):
"""one 8-bit CRAM frame: skips for unchanged blocks, 1-colour, 2-colour or 8-colour blocks"""
h, w = len(img), len(img[0])
bw, bh = w // 4, h // 4
out = bytearray()
skip = 0
def flush():
nonlocal skip
while skip:
k = min(skip, 1023)
out.extend([k & 0xFF, 0x84 + (k >> 8)])
skip -= k
for by in range(bh - 1, -1, -1):
for bx in range(bw):
px = _block(img, bx, by)
if prev and px == _block(prev, bx, by):
skip += 1
continue
flush()
cols = sorted(set(px), key=lambda c: (-px.count(c), c))
if len(cols) == 1:
out.extend([px[0], 0x80])
elif len(cols) == 2:
c0 = px[15] # pixel 15's flag bit is 0: it takes colours[1]
c1 = cols[0] if cols[0] != c0 else cols[1]
flags = sum(1 << i for i in range(16) if px[i] == c1)
out.extend([flags & 0xFF, flags >> 8, c1, c0])
else:
# 8-colour: a pair per quadrant; pixel 12 and 15 take the first colour of their quadrant (flags >= 0x9000)
colours = [0] * 8
flags = 0
for q, (qx, qy) in enumerate([(0, 0), (2, 0), (0, 2), (2, 2)]):
ids = [(qy + y) * 4 + qx + x for y in range(2) for x in range(2)]
vals = [px[i] for i in ids]
key = {2: 12, 3: 15}.get(q)
a = px[key] if key is not None else sorted(set(vals), key=lambda c: (-vals.count(c), c))[0]
rest = [v for v in vals if v != a]
b = rest[0] if rest else a
base = ((qy & 2) << 1) + (qx & 2)
colours[base], colours[base + 1] = a, b
for i in ids:
if px[i] == a:
flags |= 1 << i
else:
px[i] = b
out.extend([flags & 0xFF, flags >> 8] + colours)
flush()
return bytes(out)
# ---------------------------------------------------------------------------------------------------- Cinepak (8-bit)
def cvid8_frame(img, prev, first):
"""one palettised Cinepak frame: one strip, a V1 codebook of 4-index entries (each a 2x2 square of one colour per
entry quarter) and a V4 codebook; blocks are V1 when their four 2x2 squares are uniform, else V4 (from the
codebook of 2x2 squares); inter frames skip unchanged blocks"""
h, w = len(img), len(img[0])
blocks = [(x, y) for y in range(0, h, 4) for x in range(0, w, 4)]
v1, v4 = {}, {}
def sq(x, y):
return (img[y][x], img[y][x + 1], img[y + 1][x], img[y + 1][x + 1])
plan = []
for (x, y) in blocks:
if prev is not None and all(img[y + j][x + i] == prev[y + j][x + i] for j in range(4) for i in range(4)):
plan.append(None)
continue
q = [sq(x, y), sq(x + 2, y), sq(x, y + 2), sq(x + 2, y + 2)]
if all(len(set(s)) == 1 for s in q) and len(v1) < 256:
e = (q[0][0], q[1][0], q[2][0], q[3][0])
v1.setdefault(e, len(v1))
plan.append(("v1", v1[e]))
else:
ids = []
for s in q:
if s not in v4 and len(v4) < 256:
v4[s] = len(v4)
ids.append(v4.get(s, 0))
plan.append(("v4", ids))
def book(cid, entries):
data = b"".join(bytes(e) for e, _ in sorted(entries.items(), key=lambda kv: kv[1]))
return bytes([cid]) + (4 + len(data)).to_bytes(3, "big") + data
chunks = b""
if v4:
chunks += book(0x24, v4)
if v1:
chunks += book(0x26, v1)
bits, data = [], bytearray()
inter = prev is not None
# flags (MSB first, 32 per word) are interleaved with the indexes in decode order
words = bytearray()
flagbuf = []
def flag(b):
flagbuf.append(b)
if len(flagbuf) == 1:
words.extend(b"FLAG") # placeholder, patched below
pos_stack.append(len(words) - 4)
if len(flagbuf) == 32:
patch()
pos_stack = []
def patch():
v = 0
for i, b in enumerate(flagbuf):
v |= b << (31 - i)
p = pos_stack.pop()
words[p:p + 4] = v.to_bytes(4, "big")
flagbuf.clear()
for item in plan:
if inter:
flag(0 if item is None else 1)
if item is None:
continue
flag(1 if item[0] == "v4" else 0)
if item[0] == "v1":
words.append(item[1])
else:
words.extend(item[1])
if flagbuf:
patch()
vid = (0x31 if inter else 0x30)
chunks += bytes([vid]) + (4 + len(words)).to_bytes(3, "big") + bytes(words)
strip = bytes([0x10 if first else 0x11]) + (12 + len(chunks)).to_bytes(3, "big") + be16(0) + be16(0) + be16(h) + \
be16(w) + chunks
size = 10 + len(strip)
return bytes([0]) + size.to_bytes(3, "big") + be16(w) + be16(h) + be16(1) + strip
+13
View File
@@ -0,0 +1,13 @@
-- tools/fixtures/_lz4_encode.luau: run by tools/fixtures/lz4.py under the luau CLI: compresses every corpus of
-- tests/gen/lz4_corpora with codecs/compress/Lz4 and prints "<name> <hex>" lines for the reference to decompress.
local Lz4 = require("@formats/codecs/compress/Lz4")
local C = require("@tests/gen/lz4_corpora")
for name, data in C do
local b = assert(Lz4.compress(data))
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
print(name .. " " .. table.concat(t))
end
+34
View File
@@ -0,0 +1,34 @@
-- tools/fixtures/qb.py helper: our model/qb encoder's output for the reference reader there. Prints "<name>\t<hex>".
local Qb = require("@formats/model/qb")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Fx = require("@tests/gen/qb")
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 emit(name: string, b: buffer?, e: any)
if not b then
error(name .. ": " .. tostring(e))
end
print(name .. "\t" .. hex(b))
end
for _, c in Fx.cases do
local s = assert(Qb.decode(Bytes.reader(buffer.fromstring(c.data))))
emit(c.name .. "_same", Qb.encode(s))
emit(c.name .. "_flip", Qb.encode(s, { rightHanded = not c.rightHanded, compressed = not c.compressed, colorFormat = if c.colorFormat == "rgba" then "bgra" else "rgba" }))
end
-- a palette grid (no true colours) with a visibility mask computed by the encoder
local v = Types.Voxels.new(3, 3, 3)
v.palette[1] = { 200, 10, 10, 255 }
v.palette[2] = { 10, 200, 10, 255 }
for i = 0, 26 do
buffer.writeu8(v.data, i, if i == 13 then 2 elseif i % 2 == 0 then 1 else 0)
end
emit("palette_mask", Qb.encode(v, { visibilityMask = true }))
emit("palette_plain", Qb.encode(v))
+27
View File
@@ -0,0 +1,27 @@
-- tools/fixtures/_rbx_encode.luau: run by tools/fixtures/rbxmx.py under the luau CLI: decodes every file of
-- tests/gen/rbx_files (model/rbxm or model/rbxmx) and writes it back with both encoders; prints
-- "<file>/rbxm <hex>" and "<file>/rbxmx <hex>" lines for lune to read.
local Rbxm = require("@formats/model/rbxm")
local Rbxmx = require("@formats/model/rbxmx")
local Bytes = require("@formats/core/Bytes")
local Fx = require("@tests/gen/rbx_files")
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
for _, f in Fx.files do
local fmt: any = if f.xml then Rbxmx else Rbxm
local tree, err = fmt.decode(Bytes.reader(buffer.fromstring(f.data)))
if not tree then
error(f.name .. ": " .. tostring(err))
end
local a = assert(Rbxm.encode(tree))
print(f.name .. "/rbxm " .. hex(a))
local b = assert(Rbxmx.encode(tree))
print(f.name .. "/rbxmx " .. hex(b))
end
+30
View File
@@ -0,0 +1,30 @@
-- tools/fixtures/_robloxmesh_encode.luau: run by tools/fixtures/robloxmesh.py under the luau CLI: decodes every case of
-- tests/gen/robloxmesh and writes it back as versions 2.00 and 4.00; prints "<case>/<version> <hex>" lines for the
-- fixture's own reader.
local RobloxMesh = require("@formats/model/robloxmesh")
local Bytes = require("@formats/core/Bytes")
local Fx = require("@tests/gen/robloxmesh")
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
for _, c in Fx.cases do
if not c.unsupported then
local scene, err = RobloxMesh.decode(Bytes.reader(buffer.fromstring(c.data)))
if not scene then
error(c.name .. ": " .. tostring(err))
end
for _, v in { "2.00", "4.00" } do
local out, e = RobloxMesh.encode(scene, { version = v } :: any)
if not out then
error(c.name .. "/" .. v .. ": " .. tostring(e))
end
print(c.name .. "/" .. v .. " " .. hex(out))
end
end
end
+49
View File
@@ -0,0 +1,49 @@
-- tools/fixtures/schematic.py helper: our model/schematic encoder's output for the reference readers (litemapy,
-- nbtlib). Prints "<name>\t<hex>" lines. Inputs: the decoded fixtures of tests/gen/schematic, plus grids built here.
local Schematic = require("@formats/model/schematic")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Fx = require("@tests/gen/schematic")
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 emit(name: string, b: buffer?, e: any)
if not b then
error(name .. ": " .. tostring(e))
end
print(name .. "\t" .. hex(b))
end
local byName = {}
for _, c in Fx.cases do
byName[c.name] = assert(Schematic.decode(Bytes.reader(buffer.fromstring(c.data))))
end
-- same variant (fields kept), and across variants
emit("litemapy.litematic", Schematic.encode(byName.litemapy))
emit("litemapy.schem", Schematic.encode(byName.litemapy, { variant = "schem", version = 2 }))
emit("sponge2.schem", Schematic.encode(byName.sponge2))
emit("sponge2.litematic", Schematic.encode(byName.sponge2, { variant = "litematic" }))
emit("sponge3.schem", Schematic.encode(byName.sponge3))
emit("sponge3v2.schem", Schematic.encode(byName.sponge3, { version = 2 }))
emit("sponge1.schem", Schematic.encode(byName.sponge1))
emit("mcedit.schematic", Schematic.encode(byName.mcedit))
emit("worldedit_add.schematic", Schematic.encode(byName.worldedit_add))
emit("sponge2.schematic", Schematic.encode(byName.sponge2, { variant = "schematic" }))
emit("mcedit.schem", Schematic.encode(byName.mcedit, { variant = "schem" }))
-- a colour grid (no block states): each palette colour becomes the block nearest in colour
local v = Types.Voxels.new(4, 3, 2)
v.palette[1] = { 160, 40, 35, 255 }
v.palette[2] = { 125, 125, 125, 255 }
v.palette[3] = { 60, 110, 230, 120 }
for i = 0, 4 * 3 * 2 - 1 do
buffer.writeu8(v.data, i, i % 4)
end
emit("colors.schem", Schematic.encode(v))
emit("colors.litematic", Schematic.encode(v, { variant = "litematic" }))
emit("colors.schematic", Schematic.encode(v, { variant = "schematic" }))
+8 -3
View File
@@ -1,8 +1,9 @@
# Docs inputs for the audio / music / video / subtitle guide pages (tools/fixtures.py; tools/docs_check.py reads them):
# tiny ffmpeg test clips (testsrc 64x48, 10 frames at 10 fps, with a sine track): MP4 (H.264 + AAC), AVI (MJPEG +
# PCM), WebM (VP8 + Vorbis); a MIDI file written here (SMF 1: a tempo track and a melody), the SoundFont of
# tools/fixtures/sf2.py (build_sf2), a ProTracker module from tools/fixtures/mod.py (song_basic), MultiTracker / MED
# modules and an Unreal package (tools/fixtures/mtm.py, med.py, s3m.py), and SRT / WebVTT / ASS subtitles.
# PCM), WebM (VP8 + Vorbis), MPEG-TS (interlaced MPEG-2 + MP2); a MIDI file written here (SMF 1: a tempo track and a
# melody), the SoundFont of tools/fixtures/sf2.py (build_sf2), a ProTracker module from tools/fixtures/mod.py
# (song_basic), MultiTracker / MED modules and an Unreal package (tools/fixtures/mtm.py, med.py, s3m.py), and SRT /
# WebVTT / ASS subtitles.
# tests/gen/docs_av.luau { files = { [name] = bytes }, vars = { mp4Bytes = "clip.mp4", ... } }
import importlib.util, os, struct, tempfile
@@ -92,6 +93,9 @@ def generate(ctx):
"-c:a", "aac", "-b:a", "64k"]),
("clip.avi", ["-c:v", "mjpeg", "-q:v", "4", "-pix_fmt", "yuvj420p", "-c:a", "pcm_s16le"]),
("clip.webm", ["-c:v", "libvpx", "-b:v", "200k", "-g", "5", "-c:a", "libvorbis", "-q:a", "2"]),
("clip.ts", ["-c:v", "mpeg2video", "-b:v", "300k", "-g", "5", "-bf", "2", "-vf", "setfield=tff",
"-flags", "+ilme+ildct",
"-c:a", "mp2", "-b:a", "64k"]),
):
out = os.path.join(d, name)
ctx.nix("ffmpeg", ["ffmpeg", "-v", "error", "-y"] + src + codec + ["-shortest", out])
@@ -113,6 +117,7 @@ def generate(ctx):
"mp4Bytes": "clip.mp4",
"aviBytes": "clip.avi",
"webmBytes": "clip.webm",
"tsBytes": "clip.ts",
"midiBytes": "tune.mid",
"sf2Bytes": "bank.sf2",
"modBytes": "song.mod",
+33
View File
@@ -0,0 +1,33 @@
# Docs inputs for the legacy video sections of docs/guide/video.md (tools/fixtures.py; tools/docs_check.py reads them):
# a 64x48 FLC (tools/fixtures/fli.py's encoder), a 64x48 SMK4 with a packed stereo and a raw mono audio track
# (tools/fixtures/smk.py's encoder) and a 64x48 Cinepak MOV from ffmpeg.
# tests/gen/docs_legacy.luau { files = { [name] = bytes }, vars = { flcBytes = "anim.flc", ... } }
import importlib.util, os, tempfile
INPUTS = ["tools/docs_check.py", "tools/fixtures/fli.py", "tools/fixtures/smk.py", "tools/fixtures/_video.py"]
def load(ctx, name):
spec = importlib.util.spec_from_file_location("docs_legacy_" + name.replace("/", "_"), os.path.join(ctx.root, "tools", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def generate(ctx):
dc = load(ctx, "docs_check")
fli = load(ctx, "fixtures/fli")
smk = load(ctx, "fixtures/smk")
v = load(ctx, "fixtures/_video")
files = {}
w, h, n = 64, 48, 10
imgs = fli.idx_frames(w, h, n, 256, 5)
frames = [fli.frame([fli.color([(0, fli.pal(256, 5, False))], False), fli.brun([[bytes([x]) for x in r] for r in imgs[0]], 1, True)])]
frames += [fli.frame([fli.ss2(imgs[t], imgs[t - 1])]) for t in range(1, n)]
files["anim.flc"] = fli.file(0xAF12, w, h, 8, 100, frames)
files["intro.smk"] = smk.smk_file(4, 64, 48, 10, 100, [("packed", 22050, 2, 16), ("raw", 11025, 1, 8)], False, 7)
with tempfile.TemporaryDirectory() as d:
out = os.path.join(d, "cinepak.mov")
v.ffmpeg(["-f", "lavfi", "-i", "testsrc=size=64x48:rate=10:duration=1", "-c:v", "cinepak", out])
files["cinepak.mov"] = open(out, "rb").read()
dc.emit_inputs(ctx, files, {"flcBytes": "anim.flc", "smkBytes": "intro.smk", "cinepakBytes": "cinepak.mov"})
+49
View File
@@ -0,0 +1,49 @@
# Docs inputs for the Roblox guide page (tools/fixtures.py, tools/docs_check.py): a small place built by rojo 7.7 as
# .rbxl (binary) and .rbxlx (XML), and a skinned version 4.00 .mesh written by tools/fixtures/robloxmesh.py's spec
# writer.
# tests/gen/docs_roblox.luau { files = { [name] = bytes }, vars = { placeBytes, placeText, meshBytes } }
import importlib.util, json, os, random, shutil, tempfile
INPUTS = ["tools/docs_check.py", "tools/fixtures/robloxmesh.py"]
PLACE = {"name": "Obby", "tree": {
"$className": "DataModel",
"Workspace": {"$className": "Workspace",
"Spawn": {"$className": "SpawnLocation", "$properties": {"Size": [6, 1, 6], "Anchored": True}},
"Course": {"$className": "Model",
"Step1": {"$className": "Part", "$properties": {"Size": [4, 1, 4], "Position": [0, 4, 10], "Anchored": True, "Color": [1, 0, 0]}},
"Step2": {"$className": "Part", "$properties": {"Size": [4, 1, 4], "Position": [0, 8, 20], "Anchored": True, "Color": [0, 1, 0]}}}},
"Lighting": {"$className": "Lighting", "$properties": {"ClockTime": 14}},
"ServerScriptService": {"$className": "ServerScriptService",
"Main": {"$className": "Script", "$properties": {"Source": "print(\"hello from the obby\")\n"}}},
}}
def load(ctx, name):
spec = importlib.util.spec_from_file_location("docs_roblox_" + name, os.path.join(ctx.root, "tools", *name.split("/")))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def generate(ctx):
dc = load(ctx, "docs_check.py")
mesh = load(ctx, "fixtures/robloxmesh.py")
tmp = tempfile.mkdtemp(prefix="formats-docs-roblox-")
try:
proj = os.path.join(tmp, "place.project.json")
with open(proj, "w") as f:
json.dump(PLACE, f)
files = {}
for out in ("obby.rbxl", "obby.rbxlx"):
ctx.nix("rojo", ["rojo", "build", proj, "-o", os.path.join(tmp, out)])
with open(os.path.join(tmp, out), "rb") as f:
files[out] = f.read()
finally:
shutil.rmtree(tmp, ignore_errors=True)
rng = random.Random(5)
sv, sf = mesh.sphere(rng, 6, 10)
bones = mesh.make_bones(rng, 4)
nv, nf, subs, env, _, _ = mesh.make_skin(rng, sv, sf, bones, segs=10)
files["blob.mesh"], _ = mesh.write_v45("4.00", nv, nf, [0, len(nf)], bones, subs, env)
dc.emit_inputs(ctx, files, {"placeBytes": "obby.rbxl", "placeText": "obby.rbxlx", "meshBytes": "blob.mesh"})
+20
View File
@@ -0,0 +1,20 @@
# Docs inputs for the Ogg Theora section of docs/guide/video.md (tools/fixtures.py; tools/docs_check.py reads them): a
# tiny ffmpeg clip (testsrc 64x48, 10 frames at 10 fps, libtheora + a libvorbis sine track) as Ogg video.
# tests/gen/docs_theora.luau { files = { ["clip.ogv"] = bytes }, vars = { ogvBytes = "clip.ogv" } }
import importlib.util, os, shutil, subprocess, tempfile
INPUTS = ["tools/docs_check.py"]
def generate(ctx):
spec = importlib.util.spec_from_file_location("docs_theora_check", os.path.join(ctx.root, "tools", "docs_check.py"))
dc = importlib.util.module_from_spec(spec)
spec.loader.exec_module(dc)
ffmpeg = shutil.which("ffmpeg") or ctx.nix("ffmpeg-full", ["sh", "-c", "command -v ffmpeg"]).decode().strip()
with tempfile.TemporaryDirectory() as d:
out = os.path.join(d, "clip.ogv")
subprocess.run([ffmpeg, "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=64x48:rate=10:duration=1",
"-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100:duration=1", "-c:v", "libtheora",
"-q:v", "6", "-g", "5", "-c:a", "libvorbis", "-q:a", "2", out], check=True, capture_output=True)
files = {"clip.ogv": open(out, "rb").read()}
dc.emit_inputs(ctx, files, {"ogvBytes": "clip.ogv"})
+84
View File
@@ -0,0 +1,84 @@
# Docs inputs for the voxel guide page (docs/guide/voxel.md): a level.dat-like gzip NBT file and a Sponge v3 .schem
# (nbtlib), a two-region .litematic (litemapy), a small Anvil region from tools/fixtures/mca.py and a Qubicle file
# from tools/fixtures/qb.py's writer.
# tests/gen/docs_voxel.luau { files = { [name] = bytes }, vars = { levelDatBytes = ..., ... } }
import importlib.util, os, pickle, subprocess
INPUTS = ["tools/docs_check.py", "tools/fixtures/mca.py", "tools/fixtures/qb.py"]
BODY = r'''
import nbtlib, pickle, sys, io, gzip, os, tempfile
from nbtlib import Byte, Short, Int, Long, Float, Double, String, List, Compound, IntArray, ByteArray
import numpy as np
from litemapy import Schematic, Region, BlockState
files = {}
level = Compound({"Data": Compound({"LevelName": String("My World"), "DataVersion": Int(3953), "Difficulty": Byte(2),
"RandomSeed": Long(-4011880356862312345), "SpawnX": Int(16), "SpawnY": Int(64), "SpawnZ": Int(-8),
"GameRules": Compound({"doDaylightCycle": String("true")}),
"Player": Compound({"Pos": List[Double]([Double(16.5), Double(64.0), Double(-7.5)]), "Health": Float(20.0)})})})
f = nbtlib.File(level, root_name="")
buf = io.BytesIO()
f.write(buf)
files["level.dat"] = gzip.compress(buf.getvalue(), mtime=0)
# a 5 x 4 x 3 Sponge v3 schematic: a stone floor, oak planks walls, one glass block
w, h, l = 5, 4, 3
states = ["minecraft:air", "minecraft:stone", "minecraft:oak_planks", "minecraft:glass"]
idx = []
for y in range(h):
for z in range(l):
for x in range(w):
idx.append(1 if y == 0 else (3 if (x, y, z) == (2, 2, 0) else (2 if x in (0, w - 1) else 0)))
s = Compound({"Version": Int(3), "DataVersion": Int(3953), "Width": Short(w), "Height": Short(h), "Length": Short(l),
"Offset": IntArray([0, 0, 0]), "Metadata": Compound({"Name": String("hut")}),
"Blocks": Compound({"Palette": Compound({st: Int(i) for i, st in enumerate(states)}),
"Data": ByteArray(idx), "BlockEntities": List[Compound]([])})})
buf = io.BytesIO()
nbtlib.File({"Schematic": s}, root_name="").write(buf)
files["hut.schem"] = gzip.compress(buf.getvalue(), mtime=0)
a = Region(0, 0, 0, 3, 2, 3)
for x in range(3):
for z in range(3):
a[x, 0, z] = BlockState("minecraft:cobblestone")
b = Region(5, 0, 0, 2, 3, 1)
for y in range(3):
b[0, y, 0] = BlockState("minecraft:oak_log", axis="y")
tmp = tempfile.mkdtemp()
p = os.path.join(tmp, "build.litematic")
Schematic(name="build", author="docs", regions={"floor": a, "pillar": b}).save(p)
files["build.litematic"] = open(p, "rb").read()
sys.stdout.buffer.write(pickle.dumps(files, protocol=4))
'''
def load(ctx, name):
spec = importlib.util.spec_from_file_location("docs_voxel_" + name, os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def docs_check(ctx):
spec = importlib.util.spec_from_file_location("docs_check", os.path.join(ctx.root, "tools", "docs_check.py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def generate(ctx):
try:
files = pickle.loads(ctx.python(["nbtlib", "litemapy", "numpy"], BODY))
except subprocess.CalledProcessError as e:
raise RuntimeError("fixture python failed:\n" + e.stderr.decode(errors="replace")[-3000:])
mca = load(ctx, "mca")
regions = pickle.loads(ctx.python(["nbtlib", "numpy", "lz4", "xxhash"], mca.BODY))["regions"]
files["r.0.0.mca"] = regions[0]["data"] # 1.18+ chunks, every compression type
qb = load(ctx, "qb")
cells = {(x, y, z): ((200, 40, 40, 255) if y == 0 else (240, 240, 240, 255)) for x in range(3) for y in range(2) for z in range(3)}
files["box.qb"] = qb.write_qb([("box", (3, 2, 3), (0, 0, 0), cells)], False, True, True, False)
docs_check(ctx).emit_inputs(ctx, files, {
"levelDatBytes": "level.dat",
"schemBytes": "hut.schem",
"litematicBytes": "build.litematic",
"regionBytes": "r.0.0.mca",
"qbBytes": "box.qb",
})
+401
View File
@@ -0,0 +1,401 @@
# FLI / FLC fixtures (tools/fixtures.py): ffmpeg cannot write FLICs, so this encodes them (every chunk type: COLOR_64,
# COLOR_256, BRUN, LC / DELTA_FLI, SS2 / DELTA_FLC with line skips and the last-byte opcode, BLACK, COPY, PSTAMP; a
# prefix chunk and a ring frame; 15-bit FLC, 16-bit DTA and 24-bit FLC with BRUN / DTA_BRUN / DELTA / DTA_LC / COPY /
# DTA_COPY) and uses ffmpeg's decode as the reference (CRC-32 of each frame as rgba).
# tests/gen/fli_cases.luau { { name, data, width, height, depth, rate, frames = { crc } } }
import importlib.util, os, random, struct, tempfile, zlib
_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 le16(v):
return struct.pack("<H", v & 0xFFFF)
def le32(v):
return struct.pack("<I", v & 0xFFFFFFFF)
def s8(v):
return v & 0xFF
def chunk(typ, body):
if len(body) & 1:
body += b"\0"
return le32(6 + len(body)) + le16(typ) + body
def frame(chunks, magic=0xF1FA):
body = b"".join(chunks)
return le32(16 + len(body)) + le16(magic) + le16(len(chunks)) + bytes(8) + body
# ---------------------------------------------------------------------------------------------------- chunks
def color(entries, six):
"""COLOR_64 / COLOR_256: entries = [(skip, [(r, g, b), ...])]"""
out = le16(len(entries))
for skip, cols in entries:
out += bytes([skip, len(cols) & 0xFF])
for c in cols:
out += bytes(c)
return chunk(11 if six else 4, out)
def runs(seq, maxrun=127):
"""split a sequence into ('rep', value, n) and ('lit', [values]) pieces"""
out, i = [], 0
while i < len(seq):
j = i
while j + 1 < len(seq) and seq[j + 1] == seq[i] and j - i + 1 < maxrun:
j += 1
if j - i >= 2:
out.append(("rep", seq[i], j - i + 1))
i = j + 1
else:
k = i
while k < len(seq) and k - i < maxrun and not (k + 2 < len(seq) and seq[k] == seq[k + 1] == seq[k + 2]):
k += 1
k = max(k, i + 1)
out.append(("lit", seq[i:k]))
i = k
return out
def brun_line(units, unit_bytes):
"""BRUN line body: > 0 repeat, < 0 literal (units are byte strings of unit_bytes each)"""
out = bytes([0])
for p in runs(units):
if p[0] == "rep":
out += bytes([p[2]]) + p[1]
else:
out += bytes([s8(-len(p[1]))]) + b"".join(p[1])
return out
def brun(img, bpp, pixel_runs, typ=15):
lines = b""
for row in img:
if pixel_runs:
units = [row[x] for x in range(len(row))]
else:
flat = b"".join(row)
units = [flat[i:i + 1] for i in range(len(flat))]
lines += brun_line(units, bpp)
return chunk(typ, lines)
def lc(img, prev):
"""DELTA_FLI (LC): first changed line, line count, per line (skip, run) packets on bytes"""
h, w = len(img), len(img[0])
ch = [y for y in range(h) if img[y] != prev[y]]
if not ch:
return chunk(12, le16(0) + le16(0))
y0, y1 = ch[0], ch[-1] + 1
out = le16(y0) + le16(y1 - y0)
for y in range(y0, y1):
row, prow = img[y], prev[y]
packets = []
x = 0
while x < w:
skip = 0
while x < w and row[x] == prow[x] and skip < 255:
skip += 1
x += 1
if x >= w:
break
e = x
while e < w and row[e] != prow[e] and e - x < 127:
e += 1
seg = [bytes([v]) for v in row[x:e]]
pieces = runs(seg)
first = True
for p in pieces:
sk = skip if first else 0
first = False
if p[0] == "rep":
packets.append(bytes([sk, s8(-p[2])]) + p[1])
else:
packets.append(bytes([sk, len(p[1])]) + b"".join(p[1]))
x = e
out += bytes([len(packets)]) + b"".join(packets)
return chunk(12, out)
def ss2(img, prev, last_byte=False):
"""DELTA_FLC (SS2) on 8-bit pixels: word packets, line-skip words, the last-byte opcode on odd lines"""
h, w = len(img), len(img[0])
out = b""
count = 0
skip_lines = 0
for y in range(h):
row, prow = img[y], prev[y]
if row == prow:
skip_lines += 1
continue
if skip_lines:
out += le16(-skip_lines)
skip_lines = 0
body = b""
packets = 0
lastop = last_byte and y % 2 == 1 and row[w - 1] != prow[w - 1]
ww = w - (1 if lastop else 0)
words = [bytes(row[x:x + 2]) for x in range(0, ww - ww % 2, 2)]
pwords = [bytes(prow[x:x + 2]) for x in range(0, ww - ww % 2, 2)]
i = 0
while i < len(words):
skip = 0
while i < len(words) and words[i] == pwords[i] and skip < 127:
skip += 1
i += 1
if i >= len(words):
break
e = i
while e < len(words) and words[e] != pwords[e] and e - i < 127:
e += 1
first = True
for p in runs(words[i:e]):
sk = skip * 2 if first else 0
first = False
if p[0] == "rep":
body += bytes([sk, s8(-p[2])]) + p[1]
else:
body += bytes([sk, len(p[1])]) + b"".join(p[1])
packets += 1
i = e
if lastop:
out += le16(0x8000 | row[w - 1])
out += le16(packets) + body
count += 1
return chunk(7, le16(count) + out)
def delta_deep(img, prev, bpp, typ=7):
"""DELTA / DTA_LC on 15/16/24-bit pixels: negative words skip lines, packets (skip pixels, run)"""
h, w = len(img), len(img[0])
out, count, skip_lines = b"", 0, 0
for y in range(h):
row, prow = img[y], prev[y]
if row == prow:
skip_lines += 1
continue
if skip_lines:
out += le16(-skip_lines)
skip_lines = 0
body, packets, x = b"", 0, 0
while x < w:
skip = 0
while x < w and row[x] == prow[x] and skip < 255:
skip += 1
x += 1
if x >= w:
break
e = x
while e < w and row[e] != prow[e] and e - x < 127:
e += 1
first = True
for p in runs(row[x:e]):
sk = skip if first else 0
first = False
if p[0] == "rep":
body += bytes([sk, s8(-p[2])]) + p[1]
else:
body += bytes([sk, len(p[1])]) + b"".join(p[1])
packets += 1
x = e
out += le16(packets) + body
count += 1
return chunk(typ, le16(count) + out)
def copy8(img):
w = len(img[0])
pad = (w + 3) // 4 * 4 - w
return le32(6 + len(img) * (w + pad)) + le16(16) + b"".join(bytes(r) + bytes(pad) for r in img)
def copy_deep(img, bpp, typ=16):
w = len(img[0])
body = b"".join(b"".join(r) + (bytes(bpp) if w % 2 else b"") for r in img)
return le32(6 + len(body)) + le16(typ) + body
# ---------------------------------------------------------------------------------------------------- pictures
def idx_frames(w, h, n, colors, seed):
rnd = random.Random(seed)
out = []
for t in range(n):
img = [[(x // 6 + y // 4 + (t // 4)) % colors for x in range(w)] for y in range(h)]
sx, sy = (t * 7) % (w - 16), (t * 3) % (h - 12)
for y in range(sy, sy + 12):
for x in range(sx, sx + 16):
img[y][x] = (200 + t) % colors
for y in range(h // 2, h // 2 + 4):
for x in range(w // 2, w // 2 + 10):
img[y][x] = rnd.randrange(colors)
out.append(img)
return out
def deep_frames(w, h, n, bpp, seed):
rnd = random.Random(seed)
out = []
for t in range(n):
img = []
for y in range(h):
row = []
for x in range(w):
v = ((x * 37 + y * 11 + t * 3) // 8) & 0x7FFF if bpp == 2 else ((x * 4) & 255, (y * 5) & 255, (t * 20) & 255)
if 10 + t <= x < 26 + t and 8 <= y < 20:
v = 0x7C00 if bpp == 2 else (250, 10, 10)
if bpp == 2 and h // 2 <= y < h // 2 + 3 and w // 2 <= x < w // 2 + 7:
v = rnd.randrange(65536)
row.append(struct.pack("<H", v) if bpp == 2 else bytes([v[2], v[1], v[0]]))
img.append(row)
out.append(img)
return out
def header(typ, frames, w, h, depth, speed, oframes=(0, 0)):
hd = bytearray(128)
hd[4:6] = le16(typ)
hd[6:8] = le16(frames)
hd[8:10] = le16(w)
hd[10:12] = le16(h)
hd[12:14] = le16(depth)
hd[14:16] = le16(3)
if typ == 0xAF11:
hd[16:18] = le16(speed)
else:
hd[16:20] = le32(speed)
hd[80:84] = le32(oframes[0])
hd[84:88] = le32(oframes[1])
return hd
def file(typ, w, h, depth, speed, frames, prefix=b"", nframes=None):
hd = header(typ, nframes if nframes is not None else len(frames), w, h, depth, speed)
body = prefix + b"".join(frames)
hd[0:4] = le32(128 + len(body))
if typ != 0xAF11 and frames:
hd[80:84] = le32(128 + len(prefix))
hd[84:88] = le32(128 + len(prefix) + len(frames[0]))
return bytes(hd) + body
def pal(n, seed, six):
rnd = random.Random(seed)
m = 64 if six else 256
return [(rnd.randrange(m), rnd.randrange(m), rnd.randrange(m)) for _ in range(n)]
# ---------------------------------------------------------------------------------------------------- files
def fli_8():
"""FLI (AF11), 70 Hz jiffies: COLOR_64 + BRUN, LC deltas, a BLACK frame, a COPY frame, a palette change, PSTAMP"""
w, h, n = 80, 50, 10
imgs = idx_frames(w, h, n, 256, 1)
frames = [frame([color([(0, pal(256, 1, True))], True), brun([[bytes([v]) for v in r] for r in imgs[0]], 1, True)])]
for t in range(1, n):
if t == 4:
imgs[t] = [[0] * w for _ in range(h)]
frames.append(frame([chunk(13, b"")]))
elif t == 5:
frames.append(frame([copy8(imgs[t]), chunk(18, le16(10) + le16(6) + bytes(20))]))
elif t == 7:
frames.append(frame([color([(10, pal(20, 9, True)), (30, pal(5, 10, True))], True), lc(imgs[t], imgs[t - 1])]))
else:
frames.append(frame([lc(imgs[t], imgs[t - 1])]))
frames.append(frame([lc(imgs[0], imgs[-1])])) # the ring frame
return file(0xAF11, w, h, 8, 5, frames, nframes=n)
def flc_8():
"""FLC (AF12), ms: a prefix chunk, COLOR_256 + BRUN, SS2 deltas (line skips, last-byte opcode), COPY, BLACK, an
empty frame, COLOR_256 updates"""
w, h, n = 128, 64, 12
imgs = idx_frames(w, h, n, 256, 2)
frames = [frame([color([(0, pal(256, 2, False))], False), brun([[bytes([v]) for v in r] for r in imgs[0]], 1, True)])]
for t in range(1, n):
if t == 3:
imgs[t] = imgs[t - 1]
frames.append(frame([]))
elif t == 6:
frames.append(frame([copy8(imgs[t])]))
elif t == 8:
imgs[t] = [[0] * w for _ in range(h)]
frames.append(frame([chunk(13, b""), color([(0, pal(16, 3, False)), (100, pal(50, 4, False))], False)]))
else:
frames.append(frame([ss2(imgs[t], imgs[t - 1], last_byte=True)]))
prefix = le32(16) + le16(0xF100) + le16(0) + bytes(8)
return file(0xAF12, w, h, 8, 66, frames, prefix=prefix)
def flc_8_odd():
"""FLC 8-bit at an odd size: BRUN, LC, SS2 without the last-byte opcode, COPY with padded rows"""
w, h, n = 61, 37, 6
imgs = idx_frames(w, h, n, 256, 3)
frames = [frame([color([(0, pal(256, 5, False))], False), brun([[bytes([v]) for v in r] for r in imgs[0]], 1, True)])]
for t in range(1, n):
if t == 2:
frames.append(frame([lc(imgs[t], imgs[t - 1])]))
elif t == 4:
frames.append(frame([copy8(imgs[t])]))
else:
frames.append(frame([ss2(imgs[t], imgs[t - 1])]))
return file(0xAF12, w, h, 8, 100, frames)
def flc_deep(typ, depth, bpp, w, h):
"""15 / 16 / 24-bit: BRUN (bytes) or DTA_BRUN (pixels), DELTA / DTA_LC, BLACK, COPY / DTA_COPY"""
n = 7
imgs = deep_frames(w, h, n, bpp, depth)
frames = [frame([brun(imgs[0], bpp, False)])]
for t in range(1, n):
if t == 2:
frames.append(frame([copy_deep(imgs[t], bpp, 16)]))
elif t == 3:
frames.append(frame([brun(imgs[t], bpp, True, 25)]))
elif t == 4:
imgs[t] = [[bytes(bpp)] * w for _ in range(h)]
frames.append(frame([chunk(13, b"")]))
elif t == 5:
frames.append(frame([copy_deep(imgs[t], bpp, 26)]))
else:
frames.append(frame([delta_deep(imgs[t], imgs[t - 1], bpp, 7 if t % 2 else 27)]))
return file(typ, w, h, depth, 50, frames)
def rgba_crcs(path, w, h):
raw = V.ffmpeg(["-i", path, "-map", "0:v:0", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "rgba", "-"])
n = w * h * 4
return [zlib.crc32(raw[i:i + n]) & 0xffffffff for i in range(0, len(raw) - n + 1, n)]
def generate(ctx):
tmp = tempfile.mkdtemp(prefix="flifx_")
files = [
("anim.fli", fli_8(), 80, 50, 8, 70 / 5),
("anim.flc", flc_8(), 128, 64, 8, 1000 / 66),
("odd.flc", flc_8_odd(), 61, 37, 8, 10),
("rgb15.flc", flc_deep(0xAF12, 16, 2, 63, 40), 63, 40, 15, 20),
("rgb565.flc", flc_deep(0xAF44, 16, 2, 48, 30), 48, 30, 16, 20),
("bgr24.flc", flc_deep(0xAF12, 24, 3, 41, 30), 41, 30, 24, 20),
]
cases = []
for name, data, w, h, depth, rate in files:
path = os.path.join(tmp, name)
open(path, "wb").write(data)
crcs = rgba_crcs(path, w, h)
assert crcs, name
cases.append({"name": name, "data": data, "width": w, "height": h, "depth": depth, "rate": rate, "frames": crcs})
ctx.emit("fli_cases", cases)
# tools/bench.luau: a 320x200 FLC, 10 frames (BRUN then SS2 deltas)
w, h, n = 320, 200, 10
imgs = idx_frames(w, h, n, 256, 9)
frames = [frame([color([(0, pal(256, 9, False))], False), brun([[bytes([v]) for v in r] for r in imgs[0]], 1, True)])]
frames += [frame([ss2(imgs[t], imgs[t - 1])]) for t in range(1, n)]
ctx.emit("fli_bench", {"data": file(0xAF12, w, h, 8, 66, frames), "width": w, "height": h, "frames": n})
+108
View File
@@ -0,0 +1,108 @@
# Legacy video codec fixtures (tools/fixtures.py): Cinepak, Microsoft Video 1, QuickTime RLE and QuickTime SMC
# streams in AVI, MOV and MKV. ffmpeg encodes what it can (cinepak rgb24 / gray, msvideo1 rgb555, qtrle rgb24 /
# rgb555 / argb / gray, smc pal8); tools/fixtures/_legacy_mux.py encodes the rest (QuickTime RLE at 1 / 2 / 4 / 8 bits
# with colour tables and the default Macintosh palettes, 8-bit Microsoft Video 1 and Cinepak with AVI palettes). The
# reference is ffmpeg's decode of every file: the CRC-32 of each frame as rgba.
# tests/gen/legacy_cases.luau { { name, data, codec, width, height, frames = { crc } } }
import importlib.util, os, tempfile, zlib
_here = os.path.dirname(os.path.abspath(__file__))
def _load(name):
spec = importlib.util.spec_from_file_location(name, os.path.join(_here, name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
V = _load("_video")
M = _load("_legacy_mux")
INPUTS = ["tools/fixtures/_video.py", "tools/fixtures/_legacy_mux.py"]
W, H = 128, 96
SRC = ["-f", "lavfi", "-i", "testsrc2=size=%dx%d:rate=10" % (W, H), "-t", "1"]
def rgba_crcs(path, w, h):
raw = V.ffmpeg(["-i", path, "-map", "0:v:0", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "rgba", "-"])
n = w * h * 4
return [zlib.crc32(raw[i:i + n]) & 0xffffffff for i in range(0, len(raw) - n + 1, n)]
def case(tmp, name, codec, w=W, h=H):
path = os.path.join(tmp, name)
return {"name": name, "data": open(path, "rb").read(), "codec": codec, "width": w, "height": h,
"frames": rgba_crcs(path, w, h)}
def generate(ctx):
tmp = tempfile.mkdtemp(prefix="legacyfx_")
ff = lambda *a: V.ffmpeg(list(a), cwd=tmp)
cases = []
# ffmpeg's encoders
for ext in ("avi", "mov", "mkv"):
ff(*SRC, "-c:v", "cinepak", "cinepak." + ext)
cases.append(case(tmp, "cinepak." + ext, "cinepak"))
ff(*SRC, "-c:v", "cinepak", "-pix_fmt", "gray", "cinepak_gray.avi")
cases.append(case(tmp, "cinepak_gray.avi", "cinepak"))
ff("-f", "lavfi", "-i", "testsrc2=size=92x68:rate=10", "-t", "0.5", "-c:v", "cinepak", "cinepak_odd.mov")
cases.append(case(tmp, "cinepak_odd.mov", "cinepak", 92, 68))
ff(*SRC, "-c:v", "cinepak", "-min_strips", "3", "-max_strips", "3", "-skip_empty_cb", "1", "cinepak_strips.avi")
cases.append(case(tmp, "cinepak_strips.avi", "cinepak"))
for ext in ("avi", "mov", "mkv"):
ff(*SRC, "-c:v", "msvideo1", "msvideo1." + ext)
cases.append(case(tmp, "msvideo1." + ext, "msvideo1"))
for pf in ("rgb24", "rgb555be", "argb", "gray"):
ff(*SRC, "-c:v", "qtrle", "-pix_fmt", pf, "qtrle_%s.mov" % pf)
cases.append(case(tmp, "qtrle_%s.mov" % pf, "qtrle"))
ff("-f", "lavfi", "-i", "testsrc2=size=100x60:rate=10", "-t", "0.5", "-c:v", "qtrle", "-pix_fmt", "argb", "qtrle_odd.mov")
cases.append(case(tmp, "qtrle_odd.mov", "qtrle", 100, 60))
for ext in ("mov", "mkv"): # (ffmpeg's AVI muxer has no tag for smc: it writes raw pal8)
ff(*SRC, "-c:v", "smc", "smc." + ext)
cases.append(case(tmp, "smc." + ext, "smc"))
# streams encoded here
w, h, n = 64, 48, 8
for bits in (1, 2, 4, 8):
imgs = M.index_frames(w, h, n, 1 << bits, seed=bits)
frames = [M.qtrle_frame(img, imgs[i - 1] if i else None, bits) for i, img in enumerate(imgs)]
keys = [i == 0 for i in range(n)]
# a colour table in the sample description, and the Macintosh default table
pal = M.palette(1 << bits, seed=bits)
name = "qtrle_%d_ctab.mov" % bits
open(os.path.join(tmp, name), "wb").write(M.mov(w, h, M.qt_entry(b"rle ", w, h, bits, colors=pal), frames, keys))
cases.append(case(tmp, name, "qtrle", w, h))
name = "qtrle_%d_default.mov" % bits
open(os.path.join(tmp, name), "wb").write(M.mov(w, h, M.qt_entry(b"rle ", w, h, bits), frames, keys))
cases.append(case(tmp, name, "qtrle", w, h))
# grey depths (0x20 + bits) with the default table id: grey ramps
for bits in (2, 4):
imgs = M.index_frames(w, h, 4, 1 << bits, seed=10 + bits)
frames = [M.qtrle_frame(img, imgs[i - 1] if i else None, bits) for i, img in enumerate(imgs)]
name = "qtrle_%d_grey.mov" % bits
open(os.path.join(tmp, name), "wb").write(M.mov(w, h, M.qt_entry(b"rle ", w, h, 32 + bits), frames, [True] + [False] * 3))
cases.append(case(tmp, name, "qtrle", w, h))
# 8-bit Microsoft Video 1 and Cinepak with an AVI palette
pal = M.palette(256, seed=3)
imgs = M.index_frames(w, h, n, 256, seed=5)
frames = [M.msvc8_frame(img, imgs[i - 1] if i else None) for i, img in enumerate(imgs)]
open(os.path.join(tmp, "msvideo1_8.avi"), "wb").write(
M.avi(w, h, b"CRAM", M.bitmapinfo(w, h, 8, b"CRAM", pal), frames, [i == 0 for i in range(n)]))
cases.append(case(tmp, "msvideo1_8.avi", "msvideo1", w, h))
imgs = M.index_frames(w, h, n, 200, seed=6)
frames = [M.cvid8_frame(img, imgs[i - 1] if i else None, i == 0) for i, img in enumerate(imgs)]
open(os.path.join(tmp, "cinepak_8.avi"), "wb").write(
M.avi(w, h, b"cvid", M.bitmapinfo(w, h, 8, b"cvid", pal), frames, [i == 0 for i in range(n)]))
cases.append(case(tmp, "cinepak_8.avi", "cinepak", w, h))
for c in cases:
assert c["frames"], c["name"] + ": ffmpeg decoded no frame"
ctx.emit("legacy_cases", cases)
# tools/bench.luau: 320x240, 10 frames of each codec
bench = []
big = ["-f", "lavfi", "-i", "testsrc2=size=320x240:rate=10", "-t", "1"]
for name, args in [("cinepak.avi", ["-c:v", "cinepak"]), ("msvideo1.avi", ["-c:v", "msvideo1"]),
("qtrle.mov", ["-c:v", "qtrle", "-pix_fmt", "rgb24"]), ("smc.mov", ["-c:v", "smc"])]:
ff(*big, *args, "bench_" + name)
bench.append({"name": name, "data": open(os.path.join(tmp, "bench_" + name), "rb").read(), "width": 320, "height": 240})
ctx.emit("legacy_bench", bench)
+90
View File
@@ -0,0 +1,90 @@
# LZ4 block fixtures (tools/fixtures.py): deterministic corpora compressed by the reference (python-lz4, the lz4
# library: fast mode at several accelerations, and HC at levels 4 / 9 / 12), plus our own encoder's blocks
# (tools/fixtures/_lz4_encode.luau under the luau CLI) decompressed by the reference, as verdicts.
# tests/gen/lz4.luau { corpora = { [name] = bytes }, cases = { { name, corpus, data } }, ours = { { name, ok } } }
# tests/gen/lz4_bench.luau { size, crc, data (lz4 HC 9 block), raw }
import json, os, random, shutil, subprocess, zlib
INPUTS = ["src/Formats/codecs/compress/Lz4.luau", "tools/fixtures/_lz4_encode.luau"]
REF = r"""
import json, sys, lz4.block
req = json.load(sys.stdin)
out = {}
if req["op"] == "compress":
for name, hexdata in req["corpora"].items():
data = bytes.fromhex(hexdata)
res = {}
for acc in (1, 4, 16):
res["fast%d" % acc] = lz4.block.compress(data, mode="fast", acceleration=acc, store_size=False).hex()
for lv in (4, 9, 12):
res["hc%d" % lv] = lz4.block.compress(data, mode="high_compression", compression=lv, store_size=False).hex()
out[name] = res
else:
for name, item in req["blocks"].items():
try:
got = lz4.block.decompress(bytes.fromhex(item["data"]), uncompressed_size=item["size"])
out[name] = got.hex() == item["want"]
except Exception as e:
out[name] = False
print(json.dumps(out))
"""
def corpora(rng):
base = os.path.dirname(os.__file__)
text = bytearray()
for name in sorted(os.listdir(base)):
if name.endswith(".py"):
with open(os.path.join(base, name), "rb") as f:
text += f.read()
if len(text) >= 300000:
break
text = bytes(text[:300000])
far = rng.randbytes(9000)
return {
"empty": b"",
"one": b"a",
"twelve": b"abcabcabcabc",
"thirteen": b"abcabcabcabca",
"short": b"hello, hello, hello lz4 world\n",
"text": text[:150000],
"random": rng.randbytes(20000),
"runs": b"abc" * 4000 + b"\0" * 70000 + bytes(range(256)) * 40 + b"z" * 300,
"zeros": b"\0" * 100000,
"far": far + rng.randbytes(60000) + far,
"binary": bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(60000)),
"longlit": rng.randbytes(1000) + b"q" * 1000 + rng.randbytes(300),
}
def luau_cmd():
exe = shutil.which("luau")
return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
def generate(ctx):
rng = random.Random(41)
cs = corpora(rng)
ref = json.loads(ctx.python(["lz4"], REF, input=json.dumps({"op": "compress", "corpora": {k: v.hex() for k, v in cs.items()}}).encode()))
cases = []
for name, res in ref.items():
for mode, hexdata in res.items():
cases.append({"name": "%s/%s" % (name, mode), "corpus": name, "data": bytes.fromhex(hexdata)})
# our encoder's blocks, read back by the reference
ctx.emit("lz4_corpora", cs)
enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_lz4_encode.luau")], capture_output=True, check=True, cwd=ctx.root).stdout.decode()
blocks = {}
for line in enc.split("\n"):
if line.strip():
name, hexdata = line.split(" ", 1)
blocks[name] = {"data": hexdata.strip(), "size": len(cs[name]), "want": cs[name].hex()}
verdict = json.loads(ctx.python(["lz4"], REF, input=json.dumps({"op": "decompress", "blocks": blocks}).encode()))
ours = [{"name": n, "ok": bool(verdict.get(n)), "size": len(bytes.fromhex(blocks[n]["data"]))} for n in sorted(blocks)]
ctx.emit("lz4", {"cases": cases, "ours": ours})
bench = bytearray()
while len(bench) < 6_000_000:
bench += cs["text"] + bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(100000)) + rng.randbytes(20000)
bench = bytes(bench[:6_000_000])
code = "import sys, lz4.block; sys.stdout.buffer.write(lz4.block.compress(sys.stdin.buffer.read(), mode='high_compression', compression=9, store_size=False))"
ctx.emit("lz4_bench", {"size": len(bench), "crc": zlib.crc32(bench), "data": ctx.python(["lz4"], code, input=bench)})
+218
View File
@@ -0,0 +1,218 @@
# model/mca fixtures: Anvil region files assembled here by the Minecraft wiki's "Region file format" / "Chunk format"
# pages (nbtlib writes the chunk NBT; zlib, gzip, python-lz4 + xxhash for lz4-java's LZ4Block stream compress it):
# 1.18+ chunks (sections with palettes, non-spanning packed longs, single-state sections without data, block
# entities), 1.16 and 1.13 chunks (Level.Sections, non-spanning / spanning BlockStates), 1.12 chunks (Blocks / Add /
# Data nibbles), every compression type, and an external .mcc chunk.
# tests/gen/mca.luau { regions = { { name, data, files? = { [name] = bytes }, min = {x,y,z}, size = {x,y,z},
# crc (CRC-32 of the expected cell texts joined by "\n" in Voxels order: the state, or
# "legacy:<id>:<data>" for pre-1.13 cells), chunks = { { x, z, timestamp, compression,
# dataVersion } }, blockEntities } } }
import pickle, subprocess
BODY = r'''
import nbtlib, pickle, random, struct, sys, io, gzip, zlib
import lz4.block, xxhash
from nbtlib import Byte, Short, Int, Long, String, List, Compound, ByteArray, IntArray, LongArray
import numpy as np
rng = random.Random(9)
MODERN = [("minecraft:stone", {}), ("minecraft:dirt", {}), ("minecraft:grass_block", {"snowy": "false"}),
("minecraft:oak_log", {"axis": "y"}), ("minecraft:water", {"level": "0"}), ("minecraft:red_wool", {}),
("minecraft:deepslate", {"axis": "y"}), ("minecraft:oak_stairs", {"facing": "east", "half": "bottom", "shape": "straight", "waterlogged": "false"})]
MODERN += [("minecraft:%s_concrete" % c, {}) for c in ["white", "orange", "magenta", "lime", "pink", "gray", "cyan", "blue", "green", "black"]]
def sname(name, props):
return name + ("[" + ",".join("%s=%s" % kv for kv in props.items()) + "]" if props else "")
def signed(v):
return v - (1 << 64) if v >= (1 << 63) else v
def pack(idx, bits, spanning):
if spanning:
total = (len(idx) * bits + 63) // 64
acc = 0
for i, v in enumerate(idx):
acc |= v << (i * bits)
return [signed((acc >> (64 * k)) & ((1 << 64) - 1)) for k in range(total)]
per = 64 // bits
out = []
for k in range(0, len(idx), per):
acc = 0
for j, v in enumerate(idx[k:k + per]):
acc |= v << (j * bits)
out.append(signed(acc))
return out
def bits_for(n, minimum):
b = minimum
while (1 << b) < n: b += 1
return b
def section_states(fill):
# fill: "air", "solid", "mixed": a palette and 4096 indices (x + 16 z + 256 y)
if fill == "air":
return [("minecraft:air", {})], [0] * 4096
pool = MODERN[:2] if fill == "solid" else [("minecraft:air", {})] + rng.sample(MODERN, rng.choice([3, 9, 17]))
pal = list(pool)
idx = [rng.randrange(len(pal)) for _ in range(4096)]
used = sorted(set(idx))
remap = {o: i for i, o in enumerate(used)}
return [pal[u] for u in used], [remap[i] for i in idx]
def pal_nbt(pal):
out = []
for name, props in pal:
c = Compound({"Name": String(name)})
if props:
c["Properties"] = Compound({k: String(v) for k, v in props.items()})
out.append(c)
return List[Compound](out)
cells = {} # world (x, y, z) -> expected text
def record(cx, cz, sy, pal, idx, legacy=None):
for i in range(4096):
x, z, y = i % 16, (i // 16) % 16, i // 256
key = (cx * 16 + x, sy * 16 + y, cz * 16 + z)
if legacy is not None:
cells[key] = "legacy:%d:%d" % legacy[i]
else:
name, props = pal[idx[i]]
cells[key] = sname(name, props)
def modern_chunk(cx, cz, fills):
secs = []
for sy in range(-4, 20):
fill = fills.get(sy, "air")
pal, idx = section_states(fill)
s = Compound({"Y": Byte(sy), "block_states": Compound({"palette": pal_nbt(pal)}),
"biomes": Compound({"palette": List[String]([String("minecraft:plains")])})})
if len(pal) > 1:
s["block_states"]["data"] = LongArray(pack(idx, bits_for(len(pal), 4), False))
secs.append(s)
if fill != "air":
record(cx, cz, sy, pal, idx)
root = Compound({"DataVersion": Int(3953), "xPos": Int(cx), "yPos": Int(-4), "zPos": Int(cz),
"Status": String("minecraft:full"), "LastUpdate": Long(12345), "sections": List[Compound](secs),
"block_entities": List[Compound]([Compound({"id": String("minecraft:chest"), "x": Int(cx * 16 + 1),
"y": Int(-60), "z": Int(cz * 16 + 2), "keepPacked": Byte(0), "Items": List[Compound]([])})]),
"Heightmaps": Compound({})})
return root
def old_chunk(cx, cz, dv, spanning, fills):
secs = []
for sy, fill in fills.items():
pal, idx = section_states(fill)
bits = bits_for(len(pal), 4)
secs.append(Compound({"Y": Byte(sy), "Palette": pal_nbt(pal), "BlockStates": LongArray(pack(idx, bits, spanning)),
"BlockLight": ByteArray([0] * 2048), "SkyLight": ByteArray([0] * 2048)}))
record(cx, cz, sy, pal, idx)
return Compound({"DataVersion": Int(dv), "Level": Compound({"xPos": Int(cx), "zPos": Int(cz), "Status": String("full"),
"Sections": List[Compound](secs), "TileEntities": List[Compound]([]), "Entities": List[Compound]([])})})
def legacy_chunk(cx, cz, fills, with_add):
secs = []
ids = [(1, 0), (2, 0), (3, 0), (35, 14), (5, 2), (17, 5), (53, 3), (0, 0), (9, 0), (251, 4)]
if with_add:
ids += [(300, 1), (1000, 7)]
for sy in fills:
cellsl = [rng.choice(ids) for _ in range(4096)]
blocks = bytes(c[0] & 0xff for c in cellsl)
data = bytearray(2048); add = bytearray(2048)
for i, (bid, d) in enumerate(cellsl):
sh = 0 if i % 2 == 0 else 4 # Minecraft nibble arrays: low nibble first
data[i >> 1] |= d << sh
add[i >> 1] |= (bid >> 8) << sh
s = Compound({"Y": Byte(sy), "Blocks": ByteArray(np.frombuffer(blocks, dtype=np.int8)),
"Data": ByteArray(np.frombuffer(bytes(data), dtype=np.int8)),
"BlockLight": ByteArray([0] * 2048), "SkyLight": ByteArray([0] * 2048)})
if with_add:
s["Add"] = ByteArray(np.frombuffer(bytes(add), dtype=np.int8))
secs.append(s)
record(cx, cz, sy, None, None, legacy=cellsl)
return Compound({"Level": Compound({"xPos": Int(cx), "zPos": Int(cz), "Sections": List[Compound](secs),
"TileEntities": List[Compound]([Compound({"id": String("Chest"), "x": Int(cx * 16), "y": Int(fills[0] * 16), "z": Int(cz * 16)})]),
"Entities": List[Compound]([Compound({"id": String("Pig"), "Pos": List[nbtlib.Double]([nbtlib.Double(0.5), nbtlib.Double(1.0), nbtlib.Double(0.5)])})])})})
def nbt_bytes(root):
f = io.BytesIO()
f.write(b"\x0a"); nbtlib.tag.write_string("", f, "big"); root.write(f, byteorder="big")
return f.getvalue()
def lz4block(raw):
out = bytearray()
for k in range(0, len(raw), 65536):
blk = raw[k:k + 65536]
comp = lz4.block.compress(blk, store_size=False)
chk = xxhash.xxh32(blk, seed=0x9747b28c).intdigest() & 0x0fffffff
out += b"LZ4Block" + bytes([0x26]) + struct.pack("<iii", len(comp), len(blk), chk) + comp
out += b"LZ4Block" + bytes([0x16]) + struct.pack("<iii", 0, 0, 0)
return bytes(out)
CTYPE = {"gzip": 1, "zlib": 2, "none": 3, "lz4": 4}
def compress(raw, kind):
if kind == "gzip": return gzip.compress(raw, mtime=0)
if kind == "zlib": return zlib.compress(raw)
if kind == "none": return raw
return lz4block(raw)
def region(chunks):
# chunks: [(lx, lz, root, kind, external)] -> file bytes, external files
header = bytearray(8192)
body = bytearray()
files = {}
sector = 2
for lx, lz, root, kind, ext in chunks:
payload = compress(nbt_bytes(root), kind)
ctype = CTYPE[kind]
if ext:
files[ext] = payload
payload = b""
ctype |= 0x80
blob = struct.pack(">IB", len(payload) + 1, ctype) + payload
blob += b"\0" * ((-len(blob)) % 4096)
n = len(blob) // 4096
i = lx + 32 * lz
struct.pack_into(">I", header, i * 4, (sector << 8) | n)
struct.pack_into(">I", header, 4096 + i * 4, 1700000000 + i)
body += blob
sector += n
return bytes(header + body), files
def expected(name, data, files, chunks, nbes, dvs):
xs = [k[0] for k in cells]; ys = [k[1] for k in cells]; zs = [k[2] for k in cells]
lo = (min(xs), min(ys), min(zs)); hi = (max(xs), max(ys), max(zs))
# x / z cover whole chunks; y the sections holding blocks
lo = (min(c[2]["cx"] for c in chunks) * 16, lo[1], min(c[2]["cz"] for c in chunks) * 16)
hi = (max(c[2]["cx"] for c in chunks) * 16 + 15, hi[1], max(c[2]["cz"] for c in chunks) * 16 + 15)
size = [hi[0] - lo[0] + 1, hi[1] - lo[1] + 1, hi[2] - lo[2] + 1]
out = []
for z in range(lo[2], hi[2] + 1):
for y in range(lo[1], hi[1] + 1):
for x in range(lo[0], hi[0] + 1):
out.append(cells.get((x, y, z), "minecraft:air"))
text = "\n".join(out).encode()
return {"name": name, "data": data, "files": files, "min": list(lo), "size": size, "crc": zlib.crc32(text),
"chunks": [{"x": c[0], "z": c[1], "timestamp": 1700000000 + c[0] + 32 * c[1], "compression": c[3],
"dataVersion": dvs[k]} for k, c in enumerate(chunks)], "blockEntities": nbes}
regions = []
# 1. 1.18+ chunks, one per compression type
cells.clear()
spec = [(0, 0, "zlib"), (1, 0, "gzip"), (0, 1, "none"), (3, 2, "lz4")]
chunks = []
for lx, lz, kind in spec:
root = modern_chunk(lx, lz, {-4: "solid", -3: "mixed", -2: "mixed"})
chunks.append((lx, lz, {"root": root, "cx": lx, "cz": lz}, kind, None))
data, files = region([(c[0], c[1], c[2]["root"], c[3], c[4]) for c in chunks])
regions.append(expected("modern", data, files, chunks, 4, [3953] * 4))
# 2. older layouts: 1.12 (with Add), 1.13 (spanning), 1.16 (not spanning)
cells.clear()
chunks = [(0, 0, {"root": legacy_chunk(0, 0, [0, 1], True), "cx": 0, "cz": 0}, "zlib", None),
(1, 0, {"root": old_chunk(1, 0, 1631, True, {0: "mixed", 1: "mixed"}), "cx": 1, "cz": 0}, "zlib", None),
(2, 0, {"root": old_chunk(2, 0, 2586, False, {0: "mixed", 1: "solid"}), "cx": 2, "cz": 0}, "gzip", None)]
data, files = region([(c[0], c[1], c[2]["root"], c[3], c[4]) for c in chunks])
regions.append(expected("old", data, files, chunks, 1, [0, 1631, 2586]))
# 3. an external chunk (c.<x>.<z>.mcc) in region r.-1.2: local (3, 4) = world chunk (-29, 68)
cells.clear()
chunks = [(3, 4, {"root": modern_chunk(-29, 68, {0: "mixed"}), "cx": -29, "cz": 68}, "zlib", "c.-29.68.mcc")]
data, files = region([(c[0], c[1], c[2]["root"], c[3], c[4]) for c in chunks])
regions.append(expected("r.-1.2.mca", data, files, chunks, 0, [3953])) # its chest (y -60) is below the grid
sys.stdout.buffer.write(pickle.dumps({"regions": regions}, protocol=4))
'''
def generate(ctx):
try:
out = pickle.loads(ctx.python(["nbtlib", "numpy", "lz4", "xxhash"], BODY))
except subprocess.CalledProcessError as e:
raise RuntimeError("fixture python failed:\n" + e.stderr.decode(errors="replace")[-3000:])
for r in out["regions"]:
if not r["files"]:
del r["files"]
for c in r["chunks"]:
if not c["dataVersion"]:
del c["dataVersion"]
ctx.emit("mca", out)
+11 -4
View File
@@ -4,7 +4,9 @@
# 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) }
# yuv = { { index, planes } } (three whole frames as ffmpeg -pix_fmt yuv420p, base64 zlib),
# exact = { { y, u, v } } (CRC-32 of every frame's planes from `ffmpeg -idct int`, the IDCT
# codecs/video/Dsp reproduces: the decode must equal it) }
# 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
@@ -122,9 +124,9 @@ def generate(ctx):
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])
def reference(path, fmt, idct=None):
out = path + "." + fmt + (idct or "")
ff((["-idct", idct] if idct else []) + ["-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])
@@ -134,10 +136,13 @@ def generate(ctx):
es, path = encode(name, args, size)
rgba, w, h = reference(path, "rgba")
yuv, _, _ = reference(path, "yuv420p")
exact, _, _ = reference(path, "yuv420p", "int")
if size:
rgba, yuv = crop(rgba, w, h, size[0], size[1], 4), crop_yuv(yuv, w, h, size[0], size[1])
exact = crop_yuv(exact, w, h, size[0], size[1])
w, h = size
fs, ys = w * h * 4, w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2)
c = ((w + 1) // 2) * ((h + 1) // 2)
n = len(rgba) // fs
means = []
for k in range(n):
@@ -151,6 +156,8 @@ def generate(ctx):
"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],
"exact": [[zlib.crc32(f[:w * h]), zlib.crc32(f[w * h:w * h + c]), zlib.crc32(f[w * h + c:ys])]
for f in (exact[k * ys:(k + 1) * ys] for k in range(n))],
})
# a size change mid-stream: 176x144 then 320x180 (each part decoded by ffmpeg on its own)
+424
View File
@@ -0,0 +1,424 @@
# MPEG-2 video fixtures for codecs/video/Mpeg2 (tools/fixtures.py): elementary streams from ffmpeg's mpeg2video encoder
# (progressive and interlaced frame pictures with field prediction / field DCT, top and bottom field first, 4:2:2, the
# alternate scan, Table B-15 intra VLCs, the non-linear quantiser scale, intra DC precision 9..11, custom luma and
# chroma matrices, large motion (f_code > 1), odd sizes, B-frames), from mjpegtools' mpeg2enc (dual-prime
# prediction in interlaced frame pictures) and from field_stream below (field pictures: I / P / B fields, the second
# field predicted from the first, field / 16x8 / dual-prime prediction, skipped macroblocks; concealment vectors),
# each with `ffmpeg -idct int` decoding as the reference: the IJG integer IDCT that codecs/video/Dsp reproduces, so
# the planes must match exactly.
# tests/gen/mpeg2_<name>.luau { name, width, height, chroma (1 4:2:0 / 2 4:2:2), frames, file (base64),
# units = { { offset, length } } (one per picture), crcs = { { y, u, v } } (CRC-32 of
# every frame's cropped planes, display order), bands = { { crc } } (per frame, of
# each 16-line luma band), first / last = the yuv frame (base64 zlib) }
# tests/gen/mpeg2_containers.luau the prog stream in MPEG-TS (stream type 0x02, and patched to 0x80), MPEG-PS,
# Matroska and AVI, base64, with the stream's crcs
# tests/gen/mpeg2_bench.luau { { width, height, file, units } }: 720x576 interlaced (DVD-like) for tools/bench.luau
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", "mpeg2video", "-f", "mpeg2video"]
ILACE = ["-flags", "+ilme+ildct"]
CHROMA_INTRA = ",".join(str(8 + (i // 8) * 2 + (i % 8)) for i in range(64))
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, t, rate=25, vf=None):
s = "%s=size=%dx%d:rate=%d" % (kind, w, h, rate)
if vf:
s += "," + vf
return ["-f", "lavfi", "-i", s, "-t", str(t)]
# name: (ffmpeg input + encoder args, chroma)
CASES = {
"prog": (src("testsrc2", 352, 288, 0.8) + ["-b:v", "2M", "-bf", "2", "-g", "12"], 1),
"tff": (src("mandelbrot", 352, 288, 0.8, vf="setfield=tff") + ILACE + ["-b:v", "2M", "-bf", "2", "-g", "12"], 1),
"bff_alt": (src("testsrc2", 352, 288, 0.6, vf="scroll=h=0.01:v=0.02,setfield=bff") + ILACE + ["-alternate_scan", "1",
"-b:v", "1500k", "-bf", "1", "-g", "9"], 1),
"tools": (src("mandelbrot", 320, 240, 0.6) + ["-intra_vlc", "1", "-non_linear_quant", "1", "-qmax", "28", "-dc", "10", "-b:v", "1500k",
"-bf", "2", "-g", "8"], 1),
"dc9_matrix": (src("testsrc2", 176, 144, 0.6) + ["-dc", "9", "-intra_matrix", INTRA, "-inter_matrix", INTER,
"-b:v", "800k", "-bf", "1", "-g", "6"], 1),
"dc11_q1": (src("mandelbrot", 176, 144, 0.32) + ["-dc", "11", "-q:v", "1", "-qmin", "1", "-bf", "0", "-g", "4"], 1),
"motion": (src("testsrc2", 352, 288, 0.6, vf="scroll=h=0.04:v=0.03") + ["-b:v", "3M", "-bf", "3", "-g", "15"], 1),
"odd_ilace": (src("testsrc2", 346, 258, 0.48) + ILACE + ["-b:v", "1500k", "-bf", "2", "-g", "6"], 1),
"c422": (src("mandelbrot", 352, 288, 0.48) + ["-pix_fmt", "yuv422p", "-b:v", "3M", "-bf", "2", "-g", "6",
"-chroma_intra_matrix", CHROMA_INTRA], 2),
"c422_ilace": (src("testsrc2", 320, 240, 0.48, vf="scroll=h=0.02,setfield=tff") + ["-pix_fmt", "yuv422p"] + ILACE +
["-alternate_scan", "1", "-b:v", "3M", "-bf", "1", "-g", "6"], 2),
}
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 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)
def size(path):
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)
return tuple(int(x) for x in r.stdout.decode().strip().split(",")[:2])
def reference(path, chroma):
out = path + ".yuv"
ff(["-idct", "int", "-i", path, "-fps_mode", "passthrough", "-f", "rawvideo",
"-pix_fmt", "yuv422p" if chroma == 2 else "yuv420p", out])
return open(out, "rb").read()
def emit(name, es, path, chroma):
w, h = size(path)
yuv = reference(path, chroma)
cw, ch = (w + 1) // 2, (h if chroma == 2 else (h + 1) // 2)
fs = w * h + 2 * cw * ch
n = len(yuv) // fs
crcs, bands = [], []
for k in range(n):
f = yuv[k * fs:(k + 1) * fs]
crcs.append([zlib.crc32(f[:w * h]), zlib.crc32(f[w * h:w * h + cw * ch]), zlib.crc32(f[w * h + cw * ch:])])
bands.append([zlib.crc32(f[y * w:min(h, y + 16) * w]) for y in range(0, h, 16)])
ctx.emit("mpeg2_" + name, {
"name": name, "width": w, "height": h, "chroma": chroma, "frames": n, "file": b64(es),
"units": access_units(es), "crcs": crcs, "bands": bands, "first": z64(yuv[:fs]), "last": z64(yuv[(n - 1) * fs:n * fs]),
})
return crcs
with tempfile.TemporaryDirectory(prefix="formats-mpeg2-") as tmp:
crcs = {}
for name, (args, chroma) in CASES.items():
path = os.path.join(tmp, name + ".m2v")
ff(args + ENC + [path])
crcs[name] = emit(name, open(path, "rb").read(), path, chroma)
# mjpegtools' mpeg2enc: interlaced frame pictures with dual-prime prediction (P only, as dual prime requires)
y4m = os.path.join(tmp, "src.y4m")
ff(src("mandelbrot", 352, 288, 0.6) + ["-vf", "setfield=tff", "-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", y4m])
dp = os.path.join(tmp, "dualprime.m2v")
ctx.nix("mjpegtools", ["sh", "-c", "mpeg2enc -v 0 -f 3 -I 1 --dualprime-mpeg2 -R 0 -b 2500 -g 9 -G 9 -o '%s' < '%s'"
% (dp, y4m)])
emit("dualprime", open(dp, "rb").read(), dp, 1)
# field pictures and concealment vectors (field_stream below: no encoder at hand writes them)
seq = [("I", "P"), ("P", "P"), ("B", "B"), ("P", "P"), ("B", "B"), ("P", "P"), ("B", "B")]
for name, seed, dims, conceal in (("fields", 5, (320, 240), False), ("fields_conceal", 6, (176, 144), True)):
path = os.path.join(tmp, name + ".m2v")
es = field_stream(ctx.rng(seed), dims[0], dims[1], seq, conceal)
open(path, "wb").write(es)
emit(name, es, path, 1)
# the prog stream in the containers (stream copy)
prog = os.path.join(tmp, "prog.m2v")
cont = {"crcs": crcs["prog"]}
for fmt, ext in (("mpegts", "ts"), ("vob", "mpg"), ("matroska", "mkv"), ("avi", "avi")):
out = os.path.join(tmp, "prog." + ext)
ff(["-fflags", "+genpts", "-r", "25", "-i", prog, "-c", "copy", "-f", fmt, out])
cont[ext] = b64(open(out, "rb").read())
# stream type 0x80 (private / DigiCipher II video): the PMT's 0x02 entry patched, its CRC redone
ts = bytearray(base64.b64decode(cont["ts"]))
patched = False
for p in range(0, len(ts), 188):
pkt = ts[p:p + 188]
if pkt[0] != 0x47 or not (pkt[1] & 0x40):
continue
pid = ((pkt[1] & 0x1F) << 8) | pkt[2]
if pid == 0 or pid == 0x11 or pkt[3] & 0x20:
continue
o = p + 5 + pkt[4]
if ts[o] != 0x02: # table_id of a PMT
continue
slen = ((ts[o + 1] & 0x0F) << 8) | ts[o + 2]
pinfo = ((ts[o + 10] & 0x0F) << 8) | ts[o + 11]
e = o + 12 + pinfo
while e < o + 3 + slen - 4:
if ts[e] == 0x02:
ts[e] = 0x80
patched = True
e += 5 + (((ts[e + 3] & 0x0F) << 8) | ts[e + 4])
crc = zlib_crc32_mpeg(bytes(ts[o:o + 3 + slen - 4]))
ts[o + 3 + slen - 4:o + 3 + slen] = crc.to_bytes(4, "big")
assert patched, "mpeg2: no PMT entry patched"
cont["ts80"] = b64(bytes(ts))
ctx.emit("mpeg2_containers", cont)
bench = []
path = os.path.join(tmp, "bench.m2v")
ff(src("mandelbrot", 720, 576, 1.0) + ILACE + ["-b:v", "6M", "-bf", "2", "-g", "12"] + ENC + [path])
es = open(path, "rb").read()
bench.append({"width": 720, "height": 576, "file": b64(es), "units": access_units(es)})
ctx.emit("mpeg2_bench", bench)
def zlib_crc32_mpeg(data):
# CRC-32/MPEG-2: poly 0x04C11DB7, init 0xFFFFFFFF, MSB first, no final xor
crc = 0xFFFFFFFF
for b in data:
crc ^= b << 24
for _ in range(8):
crc = ((crc << 1) ^ 0x04C11DB7) & 0xFFFFFFFF if crc & 0x80000000 else (crc << 1) & 0xFFFFFFFF
return crc
# ---------------------------------------------------------------------------------------------------------------------
# A syntax-level MPEG-2 writer for what no encoder at hand produces: field pictures (I + P fields, the P field
# predicted from the first field of its own frame, P / B field pictures, field and 16x8 prediction, dual prime in
# field pictures, skipped macroblocks) and concealment motion vectors. The content is random (DC levels, sparse
# escape-coded coefficients, motion vectors kept inside the picture): any valid stream will do, ffmpeg's decode is
# the reference. The tables are those of ISO/IEC 13818-2 annex B (only the entries used here).
MBAI = {1: "1", 2: "011", 3: "010"}
DC_LUMA = ["100", "00", "01", "101", "110", "1110", "11110", "111110", "1111110"]
DC_CHROMA = ["00", "01", "10", "110", "1110", "11110", "111110", "1111110", "11111110"]
# |motion_code| 0..16 (Table B-10), then the sign bit
MOTION = ["1", "01", "001", "0001", "000011", "0000101", "0000100", "0000011", "000001011", "000001010", "000001001",
"0000010001", "0000010000", "0000001111", "0000001110", "0000001101", "0000001100"]
CBP = {60: "111", 4: "1101", 8: "1100", 16: "1011", 32: "1010"}
MBTYPE_P = {"mc_coded": "1", "nomc_coded": "01", "mc": "001", "intra": "00011"}
MBTYPE_B = {"interp": "10", "interp_coded": "11", "bwd": "010", "bwd_coded": "011", "fwd": "0010", "fwd_coded": "0011",
"intra": "00011"}
class Bits:
def __init__(self):
self.s = []
def put(self, v, n):
self.s.append(format(v & ((1 << n) - 1), "0%db" % n) if n else "")
def code(self, c):
self.s.append(c)
def start(self, code):
# next_start_code: zero stuffing to a byte boundary, then 00 00 01 code
n = len("".join(self.s))
if n % 8:
self.s.append("0" * (8 - n % 8))
self.put(0x000001, 24)
self.put(code, 8)
def bytes(self):
s = "".join(self.s)
s += "0" * (-len(s) % 8)
return bytes(int(s[i:i + 8], 2) for i in range(0, len(s), 8))
def field_stream(rng, w, h, frames, conceal=False):
"""frames: [(picture type per field, ...)] in decode order, e.g. [("I", "P"), ("P", "P"), ("B", "B")]"""
b = Bits()
mbw, mbh = (w + 15) // 16, 2 * ((h + 31) // 32)
fh = mbh * 8 # field height in lines (coded)
b.start(0xB3)
b.put(w, 12), b.put(h, 12), b.put(1, 4), b.put(3, 4), b.put(5000, 18), b.put(1, 1), b.put(112, 10), b.put(0, 1)
b.put(0, 1), b.put(0, 1)
b.start(0xB5)
b.put(1, 4), b.put(0x48, 8), b.put(0, 1), b.put(1, 2), b.put(0, 2), b.put(0, 2), b.put(0, 12), b.put(1, 1)
b.put(0, 8), b.put(0, 1), b.put(0, 2), b.put(0, 5)
b.start(0xB8)
b.put(0, 25), b.put(1, 1), b.put(0, 1)
# temporal references: decode order I P B P B ... is display order I B P B P (each B before the reference decoded
# just before it)
tr, d, last_ref = {}, 0, None
for k, f in enumerate(frames):
if f[0] != "B":
if last_ref is not None:
tr[last_ref] = d
d += 1
last_ref = k
else:
tr[k] = d
d += 1
tr[last_ref] = d
for k, (t0, t1) in enumerate(frames):
for fi, ptype in enumerate((t0, t1)):
parity = fi # top field first
pt = {"I": 1, "P": 2, "B": 3}[ptype]
b.start(0x00)
b.put(tr[k], 10), b.put(pt, 3), b.put(0xFFFF, 16)
if pt >= 2:
b.put(0, 1), b.put(7, 3)
if pt == 3:
b.put(0, 1), b.put(7, 3)
b.put(0, 1)
b.start(0xB5)
fc = (1, 1, 15, 15) if pt == 2 else (1, 1, 1, 1) if pt == 3 else (15, 15, 15, 15)
if pt == 1 and conceal:
fc = (1, 1, 15, 15)
b.put(8, 4)
for f in fc:
b.put(f, 4)
b.put(0, 2), b.put(1 + parity, 2), b.put(0, 1), b.put(0, 1), b.put(1 if conceal else 0, 1), b.put(0, 1)
b.put(0, 1), b.put(0, 1), b.put(0, 1), b.put(0, 1), b.put(0, 1), b.put(0, 1)
# the second field of the first frame has one reference: the first field (no skips, zero-vector or
# dual-prime prediction from its own parity)
only_first = k == 0 and fi == 1
for row in range(mbh // 2):
b.start(row + 1)
b.put(rng.choice((2, 4, 8)), 5), b.put(0, 1)
pmv = [[0, 0, 0, 0], [0, 0, 0, 0]] # [dir][r * 2 + c]
dc = [128, 128, 128]
col = 0
prev_dirs = None
while col < mbw:
# B skips repeat the previous vectors: only after zero ones (they stay inside the picture)
skip = (pt != 1 and not only_first and col > 0 and col < mbw - 1 and rng.random() < 0.15 and
prev_dirs is not None and (pt == 2 or not any(pmv[0] + pmv[1])))
if skip:
b.code(MBAI[2])
col += 1 # the skipped one
dc = [128, 128, 128]
if pt == 2:
pmv = [[0, 0, 0, 0], [0, 0, 0, 0]]
else:
b.code(MBAI[1])
if pt == 1 or rng.random() < 0.08:
b.code("1" if pt == 1 else (MBTYPE_P if pt == 2 else MBTYPE_B)["intra"])
if conceal:
# field_select, a concealment vector (the predictor again: motion codes 0), marker
b.put(0, 1), b.code(MOTION[0]), b.code(MOTION[0]), b.put(1, 1)
pmv[0][2:] = pmv[0][:2]
else:
pmv = [[0, 0, 0, 0], [0, 0, 0, 0]]
for blk in range(6):
comp = 0 if blk < 4 else blk - 3
target = rng.randrange(40, 216)
diff = target - dc[comp]
dc[comp] = target
size = abs(diff).bit_length()
b.code((DC_LUMA if comp == 0 else DC_CHROMA)[size])
if size:
b.put(diff if diff > 0 else diff + (1 << size) - 1, size)
ac_block(b, rng, 1, 0.5)
prev_dirs = None
col += 1
continue
dc = [128, 128, 128]
if pt == 2:
kind = rng.choice(("mc", "mc_coded", "mc_coded", "mc") if only_first else
("mc", "mc_coded", "mc_coded", "nomc_coded", "mc"))
dirs = (0,) if kind != "nomc_coded" else ()
b.code(MBTYPE_P[kind])
coded = kind != "mc"
else:
kind = rng.choice(("interp", "interp_coded", "bwd", "bwd_coded", "fwd", "fwd_coded"))
dirs = (0, 1) if kind.startswith("interp") else (1,) if kind.startswith("bwd") else (0,)
b.code(MBTYPE_B[kind])
coded = kind.endswith("coded")
if dirs:
choices = ["field", "16x8"] + (["dmv"] if pt == 2 and not only_first else [])
mt = rng.choice(choices)
b.put({"field": 1, "16x8": 2, "dmv": 3}[mt], 2)
for d in dirs:
motion(b, rng, pmv[d], mt, col, row, mbw, fh, parity, 0 if only_first else None)
else:
pmv = [[0, 0, 0, 0], [0, 0, 0, 0]]
if coded:
cbp = rng.choice(list(CBP))
b.code(CBP[cbp])
for blk in range(6):
if cbp & (32 >> blk):
ac_block(b, rng, 0, 0.6)
prev_dirs = dirs
col += 1
b.start(0xB7)
return b.bytes()
def ac_block(b, rng, first, more):
# escape-coded coefficients (6-bit run, 12-bit level), then end_of_block ("10"); a non-intra block needs one
n = first
count = 0
while n < 64 and (count == 0 and first == 0 or rng.random() < more):
run = rng.randrange(0, 6)
if n + run > 63:
break
level = rng.choice((-1, 1)) * rng.randrange(1, 24)
b.code("000001"), b.put(run, 6), b.put(level, 12)
n += run + 1
count += 1
b.code("10")
def put_motion(b, delta):
b.code(MOTION[abs(delta)])
if delta:
b.put(1 if delta < 0 else 0, 1)
def wrap(v):
return (v + 16) % 32 - 16
def motion(b, rng, pmv, mt, col, row, mbw, fh, parity, force_sel):
"""one direction's vectors for a field-picture macroblock, kept inside the reference field"""
def ok(mx, my, rows, y0):
sx, sy = col * 16 + (mx >> 1), y0 + (my >> 1)
return sx >= 0 and sx + 16 + (mx & 1) <= mbw * 16 and sy >= 0 and sy + rows + (my & 1) <= fh
def pick(px, py, rows, y0, extra=None):
for _ in range(50):
mx, my = rng.randrange(-12, 13), rng.randrange(-10, 11)
dx, dy = wrap(mx - px), wrap(my - py)
if ok(mx, my, rows, y0) and (extra is None or extra(mx, my)):
return dx, dy, mx, my
return None
if mt == "field":
sel = rng.randrange(2) if force_sel is None else force_sel
r = pick(pmv[0], pmv[1], 16, row * 16) or (wrap(-pmv[0]), wrap(-pmv[1]), 0, 0)
b.put(sel, 1)
put_motion(b, r[0]), put_motion(b, r[1])
mx, my = wrap(pmv[0] + r[0]), wrap(pmv[1] + r[1])
pmv[:] = [mx, my, mx, my]
elif mt == "16x8":
for half in range(2):
sel = rng.randrange(2) if force_sel is None else force_sel
px, py = pmv[half * 2], pmv[half * 2 + 1]
r = pick(px, py, 8, row * 16 + half * 8) or (wrap(-px), wrap(-py), 0, 0)
b.put(sel, 1)
put_motion(b, r[0]), put_motion(b, r[1])
pmv[half * 2], pmv[half * 2 + 1] = wrap(px + r[0]), wrap(py + r[1])
else:
# dual prime: the vector, its differential (0, +1, -1) and the derived opposite-parity vector
def dmv_ok(dmx, dmy):
def f(mx, my):
ox = ((mx + (mx > 0)) >> 1) + dmx
oy = ((my + (my > 0)) >> 1) + dmy + (-1 if parity == 0 else 1)
return ok(ox, oy, 16, row * 16)
return f
for dmx, dmy in rng.sample([(0, 0), (1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, -1)], 7):
r = pick(pmv[0], pmv[1], 16, row * 16, dmv_ok(dmx, dmy))
if r:
break
assert r, "dual prime: no vector fits"
put_motion(b, r[0]), b.code({0: "0", 1: "10", -1: "11"}[dmx])
put_motion(b, r[1]), b.code({0: "0", 1: "10", -1: "11"}[dmy])
mx, my = wrap(pmv[0] + r[0]), wrap(pmv[1] + r[1])
pmv[:] = [mx, my, mx, my]
+152
View File
@@ -0,0 +1,152 @@
# codecs/text/Nbt + data/nbt + data/snbt fixtures: random NBT trees (every tag type, nested lists / compounds, long
# extremes, BMP strings) written by Python's nbtlib (through nix) in Java big-endian and Bedrock little-endian, raw /
# gzip / zlib / with the Bedrock level.dat header, with nbtlib's SNBT text (indented and compact) and a canonical
# dump of the typed values; plus Bedrock network (varint) NBT from a small encoder here (nbtlib has none).
# tests/gen/nbt.luau { cases = { { name, raw, little, gzip, zlib, header, canon, snbt, compact, root } },
# net = { { data, canon } } }
# canon: b<n> s<n> i<n> l<n> f<hex f32 BE> d<hex f64 BE> S<len>:<utf8> B<hex> I[a,b] L[a,b]
# [<elemtype>|a,b] {<len>:<key>=<v>;...} (tests/codecs/nbt.luau computes the same text)
BODY = r'''
import nbtlib, pickle, random, struct, sys, io, gzip, zlib
from nbtlib import Byte, Short, Int, Long, Float, Double, String, List, Compound, ByteArray, IntArray, LongArray
import numpy as np
rng = random.Random(7)
NAMES = {"Byte": "byte", "Short": "short", "Int": "int", "Long": "long", "Float": "float", "Double": "double",
"ByteArray": "byteArray", "String": "string", "List": "list", "Compound": "compound", "IntArray": "intArray",
"LongArray": "longArray", "End": "end"}
ALPH = "abcXYZ019_-.+ :\"'\\\n\t{}[],;é中ü"
def rstr(n=None):
n = rng.choice([0, 1, 4, 12, 40]) if n is None else n
return "".join(rng.choice(ALPH) for _ in range(n))
def rkey():
return rng.choice(["", "a", "Name", "x y", "id", "Data", rstr(rng.randrange(1, 8))])
def scalar(kind):
if kind == "byte": return Byte(rng.choice([-128, -1, 0, 1, 127, rng.randrange(-128, 128)]))
if kind == "short": return Short(rng.choice([-32768, 32767, rng.randrange(-32768, 32768)]))
if kind == "int": return Int(rng.choice([-2**31, 2**31 - 1, 0, rng.randrange(-2**31, 2**31)]))
if kind == "long": return Long(rng.choice([-2**63, 2**63 - 1, 2**53, -2**53 - 1, 1, rng.randrange(-2**63, 2**63), rng.randrange(-2**40, 2**40)]))
if kind == "float": return Float(struct.unpack(">f", struct.pack(">f", rng.choice([0.0, -0.0, 1.5, 0.1, 3.4e38, 1e-40, rng.uniform(-1e6, 1e6)])))[0])
if kind == "double": return Double(rng.choice([0.0, 1.0, -2.5, 0.1, 1e300, 5e-324, 1e15, 1e16, 123456789.123, rng.uniform(-1e9, 1e9)]))
if kind == "string": return String(rstr())
if kind == "byteArray": return ByteArray([rng.randrange(-128, 128) for _ in range(rng.choice([0, 1, 5, 300]))])
if kind == "intArray": return IntArray([rng.randrange(-2**31, 2**31) for _ in range(rng.choice([0, 1, 4, 50]))])
if kind == "longArray": return LongArray([rng.choice([-2**63, 2**63 - 1, rng.randrange(-2**63, 2**63), rng.randrange(-100, 100)]) for _ in range(rng.choice([0, 1, 3, 40]))])
KINDS = ["byte", "short", "int", "long", "float", "double", "string", "byteArray", "intArray", "longArray"]
CLS = {"byte": Byte, "short": Short, "int": Int, "long": Long, "float": Float, "double": Double, "string": String,
"byteArray": ByteArray, "intArray": IntArray, "longArray": LongArray}
def value(d):
r = rng.random()
if d >= 4 or r < 0.55:
return scalar(rng.choice(KINDS))
if r < 0.8:
k = rng.choice(KINDS + ["compound", "list"])
n = rng.choice([0, 1, 3, 8])
if k == "compound":
return List[Compound]([compound(d + 1) for _ in range(n)])
if k == "list":
return List[List]([List[Int]([Int(i) for i in range(rng.randrange(3))]) for _ in range(n)])
return List[CLS[k]]([scalar(k) for _ in range(n)])
return compound(d + 1)
def compound(d):
c = Compound()
for _ in range(rng.choice([0, 1, 3, 6, 10])):
c[rkey()] = value(d)
return c
def canon(t):
n = type(t).__name__
if n.startswith("List"): n = "List"
if n == "Byte": return "b%d" % int(t)
if n == "Short": return "s%d" % int(t)
if n == "Int": return "i%d" % int(t)
if n == "Long": return "l%d" % int(t)
if n == "Float": return "f" + struct.pack(">f", float(t)).hex()
if n == "Double": return "d" + struct.pack(">d", float(t)).hex()
if n == "String":
b = str(t).encode("utf-8")
return "S%d:%s" % (len(b), str(t))
if n == "ByteArray": return "B" + np.asarray(t, dtype=np.int8).tobytes().hex()
if n == "IntArray": return "I[" + ",".join(str(int(x)) for x in t) + "]"
if n == "LongArray": return "L[" + ",".join(str(int(x)) for x in t) + "]"
if n == "List":
return "[" + NAMES[t.subtype.__name__] + "|" + ",".join(canon(x) for x in t) + "]"
if n in ("Compound", "File"):
return "{" + ";".join("%d:%s=%s" % (len(k.encode()), k, canon(v)) for k, v in t.items()) + "}"
raise TypeError(n)
def raw(root, name, order):
f = io.BytesIO()
f.write(b"\x0a")
nbtlib.tag.write_string(name, f, order)
root.write(f, byteorder=order)
return f.getvalue()
cases = []
for i in range(60):
root = compound(0)
if i == 0:
root = Compound()
name = rng.choice(["", "", "Schematic", "root", "é"])
big, little = raw(root, name, "big"), raw(root, name, "little")
# nbtlib's own file loader must read back what we hand it (a sanity check of the writer here)
back = nbtlib.File.parse(io.BytesIO(big))
assert canon(back) == canon(root)
header = struct.pack("<II", 9 + i % 3, len(little)) + little
cases.append({
"name": "tree%d" % i, "raw": big, "little": little, "gzip": gzip.compress(big, mtime=0),
"zlib": zlib.compress(big), "header": header, "version": 9 + i % 3, "root": name, "canon": canon(root),
"snbt": nbtlib.serialize_tag(root), "compact": nbtlib.serialize_tag(root, compact=True),
})
# Bedrock network NBT: an encoder from the wiki.vg description (zigzag varints for int / long / lengths)
def uvar(n):
out = bytearray()
while True:
b = n & 0x7f
n >>= 7
if n: out.append(b | 0x80)
else:
out.append(b); return bytes(out)
def zz32(v): return uvar(((v << 1) ^ (v >> 31)) & 0xffffffff)
def zz64(v): return uvar(((v << 1) ^ (v >> 63)) & 0xffffffffffffffff)
def nstr(s):
b = s.encode(); return uvar(len(b)) + b
IDS = {"end": 0, "byte": 1, "short": 2, "int": 3, "long": 4, "float": 5, "double": 6, "byteArray": 7, "string": 8,
"list": 9, "compound": 10, "intArray": 11, "longArray": 12}
def kind(t):
n = type(t).__name__
if n.startswith("List"): n = "List"
return NAMES[n]
def net(t):
k = kind(t)
if k == "byte": return struct.pack("<b", int(t))
if k == "short": return struct.pack("<h", int(t))
if k == "int": return zz32(int(t))
if k == "long": return zz64(int(t))
if k == "float": return struct.pack("<f", float(t))
if k == "double": return struct.pack("<d", float(t))
if k == "string": return nstr(str(t))
if k == "byteArray": return zz32(len(t)) + np.asarray(t, dtype=np.int8).tobytes()
if k == "intArray": return zz32(len(t)) + b"".join(zz32(int(x)) for x in t)
if k == "longArray": return zz32(len(t)) + b"".join(zz64(int(x)) for x in t)
if k == "list": return bytes([IDS[NAMES[t.subtype.__name__]]]) + zz32(len(t)) + b"".join(net(x) for x in t)
if k == "compound":
return b"".join(bytes([IDS[kind(v)]]) + nstr(key) + net(v) for key, v in t.items()) + b"\x00"
nets = []
for i in range(20):
root = compound(0)
nets.append({"data": b"\x0a" + nstr("") + net(root), "canon": canon(root)})
sys.stdout.buffer.write(pickle.dumps({"cases": cases, "net": nets}, protocol=4))
'''
def run(ctx, packages, body):
"""ctx.python with the script's stderr in the error"""
import subprocess
try:
return ctx.python(packages, body)
except subprocess.CalledProcessError as e:
raise RuntimeError("fixture python failed:\n" + e.stderr.decode(errors="replace")[-3000:])
def generate(ctx):
import pickle
out = pickle.loads(run(ctx, ["nbtlib", "numpy"], BODY))
ctx.emit("nbt", out)
+156
View File
@@ -0,0 +1,156 @@
# model/qb fixtures: Qubicle Binary files from a reader / writer written here from the format description in the
# Qubicle documentation (no Qubicle tool runs under nix), with every option: RGBA / BGRA, left- / right-handed,
# uncompressed / RLE, visibility masks; plus our encoder's output (tools/fixtures/_qb_encode.luau) read back by it.
# tests/gen/qb.luau { cases = { { name, data, colorFormat, rightHanded, compressed, visibilityMask,
# matrices = { { name, size, pos (scene coordinates: left-handed files mirrored on z), crc
# (CRC-32 of the r, g, b, a bytes of every cell in Voxels order), filled } } } },
# ours = { [name] = { same fields as cases } } }
import importlib.util, os, pickle, struct, subprocess, zlib, random
INPUTS = ["src/Formats/model/qb", "tools/fixtures/_qb_encode.luau"]
_spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_model_ref.py"))
R = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(R)
CODEFLAG, NEXTSLICEFLAG = 2, 6
def write_qb(matrices, bgra, right, compressed, mask):
"""matrices: [(name, (sx, sy, sz), (px, py, pz), {(x, y, z): (r, g, b, a)})] in file coordinates"""
out = bytearray(b"\x01\x01\x00\x00")
out += struct.pack("<IIIII", 1 if bgra else 0, 1 if right else 0, 1 if compressed else 0, 1 if mask else 0, len(matrices))
for name, (sx, sy, sz), (px, py, pz), cells in matrices:
nb = name.encode()
out += bytes([len(nb)]) + nb + struct.pack("<IIIiii", sx, sy, sz, px, py, pz)
def val(x, y, z):
c = cells.get((x, y, z))
if not c:
return 0
r, g, b, a = c
if bgra:
r, b = b, r
return r | g << 8 | b << 16 | a << 24
for z in range(sz):
vals = [val(x, y, z) for y in range(sy) for x in range(sx)]
if not compressed:
out += b"".join(struct.pack("<I", v) for v in vals)
continue
i = 0
while i < len(vals):
run = 1
while i + run < len(vals) and vals[i + run] == vals[i]:
run += 1
if run > 2:
out += struct.pack("<III", CODEFLAG, run, vals[i])
else:
out += b"".join(struct.pack("<I", vals[i]) for _ in range(run))
i += run
out += struct.pack("<I", NEXTSLICEFLAG)
return bytes(out)
def read_qb(data):
"""-> settings, [(name, size, pos, {(x, y, z): (r, g, b, a)})] in file coordinates"""
assert data[:4] == b"\x01\x01\x00\x00"
fmt, zaxis, comp, mask, n = struct.unpack_from("<IIIII", data, 4)
p = 24
mats = []
for _ in range(n):
ln = data[p]; p += 1
name = data[p:p + ln].decode(); p += ln
sx, sy, sz, px, py, pz = struct.unpack_from("<IIIiii", data, p); p += 24
cells = {}
def put(x, y, z, v):
if v >> 24 == 0:
return
r, g, b, a = v & 255, v >> 8 & 255, v >> 16 & 255, v >> 24
if fmt == 1:
r, b = b, r
cells[(x, y, z)] = (r, g, b, a)
for z in range(sz):
if not comp:
for y in range(sy):
for x in range(sx):
put(x, y, z, struct.unpack_from("<I", data, p)[0]); p += 4
continue
i = 0
while True:
d = struct.unpack_from("<I", data, p)[0]; p += 4
if d == NEXTSLICEFLAG:
break
if d == CODEFLAG:
run, v = struct.unpack_from("<II", data, p); p += 8
for _ in range(run):
put(i % sx, i // sx, z, v); i += 1
else:
put(i % sx, i // sx, z, d); i += 1
mats.append((name, (sx, sy, sz), (px, py, pz), cells))
return {"colorFormat": "bgra" if fmt else "rgba", "rightHanded": zaxis == 1, "compressed": comp == 1, "visibilityMask": mask == 1}, mats
def describe(settings, mats):
out = []
for name, (sx, sy, sz), (px, py, pz), cells in mats:
right = settings["rightHanded"]
buf = bytearray()
for z in range(sz):
for y in range(sy):
for x in range(sx):
fz = z if right else sz - 1 - z
buf += bytes(cells.get((x, y, fz), (0, 0, 0, 0)))
out.append({"name": name, "size": [sx, sy, sz], "pos": [px, py, pz if right else -(pz + sz)],
"crc": zlib.crc32(bytes(buf)), "filled": len(cells)})
d = dict(settings)
d["matrices"] = out
return d
def mask_of(cells, x, y, z):
a = 1
for (dx, dy, dz), bit in (((-1, 0, 0), 2), ((1, 0, 0), 4), ((0, 1, 0), 8), ((0, -1, 0), 16), ((0, 0, 1), 32), ((0, 0, -1), 64)):
if (x + dx, y + dy, z + dz) not in cells:
a += bit
return a
def generate(ctx):
rng = random.Random(4)
cases = []
for k, (bgra, right, comp, mask) in enumerate([(False, True, True, False), (True, False, False, False), (False, False, True, True),
(True, True, False, True), (False, True, False, False), (False, True, True, False)]):
mats = []
for m in range(1 + k % 3):
size = (rng.randrange(1, 9), rng.randrange(1, 7), rng.randrange(1, 6))
many = k == 5 # more than 255 colours
pal = [(rng.randrange(256), rng.randrange(256), rng.randrange(256)) for _ in range(400 if many else 6)]
cells = {}
for x in range(size[0]):
for y in range(size[1]):
for z in range(size[2]):
if rng.random() < 0.6:
cells[(x, y, z)] = pal[rng.randrange(len(pal))] + (255,)
if k == 5:
size = (20, 20, 3)
cells = {(x, y, z): pal[(x + 20 * y + z) % 400] + (255,) for x in range(20) for y in range(20) for z in range(3)}
if mask:
cells = {p: c[:3] + (mask_of(cells, *p),) for p, c in cells.items()}
mats.append(("m%d_%d" % (k, m), size, (rng.randrange(-20, 20), rng.randrange(-5, 5), rng.randrange(-20, 20)), cells))
data = write_qb(mats, bgra, right, comp, mask)
settings, back = read_qb(data)
d = describe(settings, back)
d["name"] = "case%d" % k
d["data"] = data
cases.append(d)
ctx.emit("qb", {"cases": cases})
try:
files = R.luau_encode(ctx, "tools/fixtures/_qb_encode.luau")
except subprocess.CalledProcessError as e:
raise RuntimeError("our encoder failed:\n" + (e.stderr or b"").decode(errors="replace")[-3000:])
ours = {}
for name, data in files.items():
settings, mats = read_qb(data)
ours[name] = describe(settings, mats)
ctx.emit("qb", {"cases": cases, "ours": ours})
+492
View File
@@ -0,0 +1,492 @@
# Roblox model / place fixtures (tools/fixtures.py) for model/rbxm (binary) and model/rbxmx (XML); one generator for
# both (named rbxmx so that both test filters, "rbxm" and "rbxmx", run it).
# Reference files: rojo 7.7 builds of a model project (a Folder with an explicitly typed property of every type, real
# instances with Refs / SharedStrings / attributes / tags, 120 parts with random and axis-aligned CFrames) and of a
# place project (DataModel services) to .rbxm / .rbxmx / .rbxl / .rbxlx; lune 0.11 (rbx-dom) builds a model of real
# properties of every type lune can set to .rbxm / .rbxmx; variants of the binary model with Zstandard chunks (zstd),
# raw chunks, and an unknown chunk + an unknown property type (python-lz4 / python-zstandard re-pack the chunks).
# Dumps: lune reads every reference file and prints each property the file holds (the names come from the XML twin)
# in a canonical form; the tests compare our decode against it.
# Ours: tools/fixtures/_rbx_encode.luau (luau CLI) decodes every file and writes it back as rbxm and rbxmx; lune
# reads our files and the dumps must equal the reference dumps (verdicts).
# tests/gen/rbx_files.luau { files = { { name, data, xml, place, dump = JSON text of { [path] = { class, props =
# { [name] = canon }, attrs, tags } } } } }
# tests/gen/rbx_ours.luau { { name, ok, detail } }
import json, math, os, random, shutil, struct, subprocess, tempfile
import xml.etree.ElementTree as ET
INPUTS = ["src/Formats/model/rbxm", "src/Formats/model/rbxmx", "src/Formats/codecs/model/Rbx", "tools/fixtures/_rbx_encode.luau"]
# ---------------------------------------------------------------------------------------------------- rojo projects
def cframe(pos, rows):
return {"CFrame": {"position": pos, "orientation": rows}}
def random_rotation(rng):
q = [rng.gauss(0, 1) for _ in range(4)]
n = math.sqrt(sum(c * c for c in q))
x, y, z, w = (c / n for c in q)
return [[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
[2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
[2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]]
AXES = [(1, 0, 0), (0, 1, 0), (0, 0, 1), (-1, 0, 0), (0, -1, 0), (0, 0, -1)]
def axis_rotation(rng):
while True:
r, u = rng.choice(AXES), rng.choice(AXES)
if any(a * b for a, b in zip(r, u)) == 0 and r != u and tuple(-c for c in r) != u:
break
k = (r[1] * u[2] - r[2] * u[1], r[2] * u[0] - r[0] * u[2], r[0] * u[1] - r[1] * u[0])
return [[r[0], u[0], k[0]], [r[1], u[1], k[1]], [r[2], u[2], k[2]]]
TYPES_FOLDER = {
"PString": {"String": "hello <world> & \"quotes\" é日"},
"PBinary": {"BinaryString": "AAECAwT/"},
"PBool": {"Bool": True},
"PInt32": {"Int32": -123},
"PInt64": {"Int64": -1234567890123},
"PFloat32": {"Float32": 1.5},
"PFloat64": {"Float64": 3.141592653589793},
"PUDim": {"UDim": [0.5, 10]},
"PUDim2": {"UDim2": [[0.5, 10], [0.25, -3]]},
"PRay": {"Ray": {"origin": [1, 2, 3], "direction": [4, 5, 6]}},
"PFaces": {"Faces": ["Right", "Top", "Front"]},
"PAxes": {"Axes": ["X", "Z"]},
"PBrickColor": {"BrickColor": 21},
"PColor3": {"Color3": [0.25, 0.5, 1]},
"PVector2": {"Vector2": [1.5, -2]},
"PVector3": {"Vector3": [1, -2, 3.25]},
"PVector3int16": {"Vector3int16": [-1, 2, 300]},
"PCFrame": cframe([1, 2, 3], [[0, 0, 1], [0, 1, 0], [-1, 0, 0]]),
"PCFrame2": cframe([4, 5, 6], [[0.36, 0.48, -0.8], [-0.8, 0.6, 0], [0.48, 0.64, 0.6]]),
"POptCFrame": {"OptionalCFrame": {"position": [1, 2, 3], "orientation": [[1, 0, 0], [0, 1, 0], [0, 0, 1]]}},
"POptNone": {"OptionalCFrame": None},
"PEnum": {"Enum": 3},
"PNumberSequence": {"NumberSequence": {"keypoints": [{"time": 0, "value": 1, "envelope": 0.5}, {"time": 0.5, "value": -3, "envelope": 0}, {"time": 1, "value": 2, "envelope": 0}]}},
"PColorSequence": {"ColorSequence": {"keypoints": [{"time": 0, "color": [1, 0, 0]}, {"time": 1, "color": [0, 0.5, 1]}]}},
"PNumberRange": {"NumberRange": [1, 5]},
"PRect": {"Rect": [[1, 2], [3, 4]]},
"PPhys": {"PhysicalProperties": {"density": 1, "friction": 0.5, "elasticity": 0.25, "frictionWeight": 2, "elasticityWeight": 3, "acousticAbsorption": 0.75}},
"PPhysDefault": {"PhysicalProperties": "Default"},
"PFont": {"Font": {"family": "rbxasset://fonts/families/Arial.json", "weight": "Bold", "style": "Italic"}},
"PUniqueId": {"UniqueId": "44b188dace632b4702e9c68d004815fc"},
"PUniqueId2": {"UniqueId": "7fb188dace632b4702e9c68d004815fd"},
"PSecurity": {"SecurityCapabilities": 12345},
"PContent": {"Content": {"Uri": "rbxassetid://1234"}},
"PContentNone": {"Content": "None"},
"PContentId": {"ContentId": "rbxassetid://99"},
"PShared": {"SharedString": "AAECAw=="},
}
def model_project(rng):
parts = {}
for i in range(120):
rows = axis_rotation(rng) if i % 3 else random_rotation(rng)
pos = [round(rng.uniform(-500, 500), 3) for _ in range(3)]
parts["P%03d" % i] = {"$className": "Part", "$properties": {
"CFrame": cframe(pos, rows),
"Size": [rng.choice([1, 2, 4, 0.5]), rng.uniform(0.2, 20), 2],
"Color": [rng.random(), rng.random(), rng.random()],
"Anchored": rng.random() < 0.5,
"Transparency": rng.choice([0, 0.25, 0.5]),
}}
tree = {
"$className": "Model",
"Types": {"$className": "Folder", "$properties": TYPES_FOLDER, "$attributes": {"Num": 5, "Str": "x", "Flag": True}},
"Types2": {"$className": "Folder", "$properties": {"PString": {"String": ""}, "PShared": {"SharedString": "AAECAw=="}, "PInt32": {"Int32": 2147483647}}},
"Base": {"$className": "Part", "$properties": {
"Size": [4, 1, 2], "CFrame": cframe([1, 2, 3], [[1, 0, 0], [0, 1, 0], [0, 0, 1]]), "Color": [0.2, 0.4, 0.6],
"Anchored": True, "Material": {"Enum": 288},
"CustomPhysicalProperties": {"PhysicalProperties": {"density": 1, "friction": 0.5, "elasticity": 0.25, "frictionWeight": 2, "elasticityWeight": 3, "acousticAbsorption": 1}},
"UniqueId": {"UniqueId": "0123456789abcdef0011223344556677"},
"Capabilities": {"SecurityCapabilities": 12345},
"Tags": ["Enemy", "Boss"],
}, "$attributes": {"Rojo_Id": "base", "Hp": 100}},
"Pointer": {"$className": "ObjectValue", "$attributes": {"Rojo_Target_Value": "base"}},
"Empty": {"$className": "ObjectValue"},
"Code": {"$className": "Script", "$properties": {"Source": "print('hi')\n-- <xml> & \"quotes\" ]]>\n"}},
"Emitter": {"$className": "ParticleEmitter", "$properties": {
"Size": {"NumberSequence": {"keypoints": [{"time": 0, "value": 1, "envelope": 0}, {"time": 1, "value": 3, "envelope": 0}]}},
"Color": {"ColorSequence": {"keypoints": [{"time": 0, "color": [1, 1, 0]}, {"time": 1, "color": [0, 1, 1]}]}},
"Lifetime": {"NumberRange": [1, 2]}}},
"Gui": {"$className": "ScreenGui", "Frame": {"$className": "Frame", "$properties": {"Size": {"UDim2": [[0.5, 10], [0.25, -3]]}, "BackgroundColor3": [1, 0.5, 0]},
"Label": {"$className": "TextLabel", "$properties": {"Text": "label", "FontFace": {"Font": {"family": "rbxasset://fonts/families/Ubuntu.json", "weight": "Light", "style": "Normal"}}}}}},
"Mesh": {"$className": "MeshPart", "$properties": {"MeshContent": {"Content": {"Uri": "rbxassetid://777"}}}},
"Same": {"$className": "Folder"},
"Same2": {"$className": "Folder", "$properties": {"Name": {"String": "Same"}}},
"Parts": dict({"$className": "Folder"}, **parts),
}
return {"name": "Kit", "tree": tree}
def place_project():
return {"name": "Place", "tree": {
"$className": "DataModel",
"Workspace": {"$className": "Workspace", "$properties": {"Gravity": 100},
"Floor": {"$className": "Part", "$properties": {"Size": [64, 1, 64], "Anchored": True, "Color": [0.3, 0.6, 0.3]}}},
"Lighting": {"$className": "Lighting", "$properties": {"Ambient": [0.1, 0.2, 0.3], "ClockTime": 12.5, "Brightness": 2}},
"ReplicatedStorage": {"$className": "ReplicatedStorage", "Lib": {"$className": "ModuleScript", "$properties": {"Source": "return { answer = 42 }\n"}}},
"ServerScriptService": {"$className": "ServerScriptService", "Main": {"$className": "Script", "$properties": {"Source": "print(require(game.ReplicatedStorage.Lib).answer)\n"}}},
"StarterGui": {"$className": "StarterGui"},
}}
# ---------------------------------------------------------------------------------------------------- lune scripts
LUNE_GEN = r"""
local roblox = require("@lune/roblox")
local fs = require("@lune/fs")
local process = require("@lune/process")
local I = roblox.Instance.new
local V3, CF = roblox.Vector3.new, roblox.CFrame.new
local m = I("Model"); m.Name = "Kit"
local p = I("Part"); p.Name = "Base"; p.Parent = m
p.CFrame = CF(1, 2, 3) * roblox.CFrame.Angles(0.3, 0.2, 0.1)
p.Size = V3(4, 1, 2)
p.Color = roblox.Color3.fromRGB(10, 20, 255)
p.Anchored = true
p.Transparency = 0.25
p.Material = roblox.Enum.Material.Neon
p.CustomPhysicalProperties = roblox.PhysicalProperties.new(1, 0.5, 0.25, 2, 3)
p:SetAttribute("Hp", 5); p:SetAttribute("Label", "x"); p:SetAttribute("Pos", V3(1, 2, 3))
p:AddTag("Enemy"); p:AddTag("Boss")
m.PrimaryPart = p
local function add(cls, name, f) local i = I(cls); i.Name = name; i.Parent = m; f(i); return i end
add("StringValue", "Str", function(i) i.Value = "hello\nworld <&>" end)
add("IntValue", "Int", function(i) i.Value = -1234567890123 end)
add("NumberValue", "Num", function(i) i.Value = math.pi end)
add("ObjectValue", "Obj", function(i) i.Value = p end)
add("ObjectValue", "ObjNil", function(i) end)
add("RayValue", "Ray", function(i) i.Value = roblox.Ray.new(V3(1, 2, 3), V3(4, 5, 6)) end)
add("BrickColorValue", "Brick", function(i) i.Value = roblox.BrickColor.new(21) end)
add("Color3Value", "Col", function(i) i.Value = roblox.Color3.new(0.25, 0.5, 1) end)
add("CFrameValue", "Cf", function(i) i.Value = CF(5, 6, 7) * roblox.CFrame.Angles(0, math.pi / 2, 0) end)
add("Vector3Value", "Vec", function(i) i.Value = V3(1, -2, 3.25) end)
add("Sky", "Sky", function(i) i.StarCount = 1234 end)
add("Handles", "Handles", function(i) i.Faces = roblox.Faces.new(roblox.Enum.NormalId.Top, roblox.Enum.NormalId.Front) end)
add("ArcHandles", "Arcs", function(i) i.Axes = roblox.Axes.new(roblox.Enum.Axis.X, roblox.Enum.Axis.Z) end)
add("TerrainRegion", "Region", function(i) i.ExtentsMax = roblox.Vector3int16.new(-1, 2, 300) end)
add("Script", "Code", function(i) i.Source = "print('hi')\n" end)
add("Decal", "Decal", function(i) i.Texture = "rbxassetid://55" end)
local pe = I("ParticleEmitter"); pe.Parent = p
pe.Size = roblox.NumberSequence.new({roblox.NumberSequenceKeypoint.new(0, 1, 0.5), roblox.NumberSequenceKeypoint.new(1, 2)})
pe.Color = roblox.ColorSequence.new(roblox.Color3.new(1, 0, 0), roblox.Color3.new(0, 0, 1))
pe.Lifetime = roblox.NumberRange.new(1, 5)
local sg = I("ScreenGui"); sg.Parent = m
local fr = I("Frame"); fr.Parent = sg; fr.Size = roblox.UDim2.new(0.5, 10, 0.25, -3)
local ul = I("UIListLayout"); ul.Parent = fr; ul.Padding = roblox.UDim.new(0.1, 4)
local il = I("ImageLabel"); il.Parent = fr; il.SliceCenter = roblox.Rect.new(1, 2, 3, 4); il.ImageRectOffset = roblox.Vector2.new(1.5, -2)
local tl = I("TextLabel"); tl.Parent = fr; tl.FontFace = roblox.Font.new("rbxasset://fonts/families/Arial.json", roblox.Enum.FontWeight.Bold, roblox.Enum.FontStyle.Italic)
local sm = I("SpecialMesh"); sm.Parent = p; sm.MeshContent = roblox.Content.fromUri("rbxassetid://1234")
m.ModelMeshData = "\0\1\2\3"
local folder = I("Folder"); folder.Name = "Many"; folder.Parent = m
local seed = 12345
local function rnd() seed = (seed * 1103515245 + 12345) % 2147483648; return seed / 2147483648 end
for k = 1, 150 do
local q = I("Part"); q.Name = "Q" .. k; q.Parent = folder
local rot = if k % 2 == 0 then roblox.CFrame.Angles(0, math.pi / 2 * (k % 4), 0) else roblox.CFrame.Angles(rnd() * 6, rnd() * 6, rnd() * 6)
q.CFrame = CF(rnd() * 1000 - 500, rnd() * 100, rnd() * 1000 - 500) * rot
q.Size = V3(1 + rnd() * 10, 1, 1 + rnd() * 3)
q.Color = roblox.Color3.new(rnd(), rnd(), rnd())
q.Anchored = k % 3 == 0
if k % 5 == 0 then q.Transparency = rnd() end
end
local dir = process.args[1]
fs.writeFile(dir .. "/lune.rbxm", roblox.serializeModel({m}))
fs.writeFile(dir .. "/lune.rbxmx", roblox.serializeModel({m}, true))
"""
LUNE_DUMP = r"""
local roblox = require("@lune/roblox")
local fs = require("@lune/fs")
local serde = require("@lune/serde")
local process = require("@lune/process")
local req = serde.decode("json", fs.readFile(process.args[1]))
local ALIAS = { size = "Size", Color3uint8 = "Color", shape = "Shape", formFactorRaw = "FormFactor", MaxPlayersInternal = "MaxPlayers" }
local function hex(s)
return (string.gsub(s, ".", function(c) return string.format("%02x", string.byte(c)) end))
end
local paths = {}
local function walk(list, prefix)
local seen = {}
for _, inst in list do
local n = inst.Name
seen[n] = (seen[n] or 0) + 1
local p = prefix .. (if prefix == "" then "" else "/") .. n .. (if seen[n] > 1 then "#" .. seen[n] else "")
paths[inst] = p
walk(inst:GetChildren(), p)
end
end
local function bits(v, names)
local b, k = 0, 1
for _, n in names do
if v[n] then b += k end
k *= 2
end
return b
end
local function canon(v)
local t = typeof(v)
if v == nil then return { t = "nil" } end
if t == "string" then return { t = "string", s = hex(v) } end
if t == "boolean" then return { t = "bool", b = v } end
if t == "number" then return { t = "number", n = { v } } end
if t == "Vector3" or t == "Vector3int16" then return { t = t, n = { v.X, v.Y, v.Z } } end
if t == "Vector2" or t == "Vector2int16" then return { t = t, n = { v.X, v.Y } } end
if t == "CFrame" then return { t = t, n = { v:GetComponents() } } end
if t == "Color3" then return { t = t, n = { v.R, v.G, v.B } } end
if t == "UDim" then return { t = t, n = { v.Scale, v.Offset } } end
if t == "UDim2" then return { t = t, n = { v.X.Scale, v.X.Offset, v.Y.Scale, v.Y.Offset } } end
if t == "Rect" then return { t = t, n = { v.Min.X, v.Min.Y, v.Max.X, v.Max.Y } } end
if t == "NumberRange" then return { t = t, n = { v.Min, v.Max } } end
if t == "Ray" then return { t = t, n = { v.Origin.X, v.Origin.Y, v.Origin.Z, v.Direction.X, v.Direction.Y, v.Direction.Z } } end
if t == "NumberSequence" then
local n = {}
for _, k in v.Keypoints do table.insert(n, k.Time); table.insert(n, k.Value); table.insert(n, k.Envelope) end
return { t = t, n = n }
end
if t == "ColorSequence" then
local n = {}
for _, k in v.Keypoints do table.insert(n, k.Time); table.insert(n, k.Value.R); table.insert(n, k.Value.G); table.insert(n, k.Value.B) end
return { t = t, n = n }
end
if t == "PhysicalProperties" then return { t = t, n = { v.Density, v.Friction, v.Elasticity, v.FrictionWeight, v.ElasticityWeight, v.AcousticAbsorption } } end
if t == "BrickColor" then return { t = t, n = { v.Number } } end
if t == "EnumItem" then return { t = t, n = { v.Value } } end
if t == "Faces" then return { t = t, n = { bits(v, { "Right", "Top", "Back", "Left", "Bottom", "Front" }) } } end
if t == "Axes" then return { t = t, n = { bits(v, { "X", "Y", "Z" }) } } end
if t == "Font" then return { t = t, s = v.Family, n = { v.Weight.Value }, style = v.Style.Name } end
if t == "Instance" then return { t = t, s = paths[v] or "?" } end
if t == "Content" then
local st = v.SourceType.Name
return { t = t, kind = st, s = if st == "Uri" then v.Uri elseif st == "Object" then (paths[v.Object] or "?") else "" }
end
if t == "UniqueId" then return { t = t, s = string.lower((string.gsub(tostring(v), "[^%x]", ""))) } end
return { t = t, s = tostring(v) }
end
local out = {}
for _, f in req.files do
local data = fs.readFile(f.path)
paths = {}
local roots
local ok, err = pcall(function()
if f.place then roots = roblox.deserializePlace(data):GetChildren() else roots = roblox.deserializeModel(data) end
end)
if not ok then
out[f.key] = { error = tostring(err) }
else
walk(roots, "")
local d = {}
for inst, p in paths do
local want = f.names[p]
local e = { class = inst.ClassName, props = {} }
if want then
for _, name in want do
local okv, v = pcall(function() return inst[ALIAS[name] or name] end)
if okv then e.props[name] = canon(v) end
end
end
local attrs = {}
for k, v in inst:GetAttributes() do attrs[k] = canon(v) end
e.attrs = attrs
e.tags = inst:GetTags()
d[p] = e
end
out[f.key] = d
end
end
print(serde.encode("json", out))
"""
# ---------------------------------------------------------------------------------------------------- chunk re-packing
REPACK = r"""
import json, struct, sys, lz4.block, zstandard
req = json.load(sys.stdin)
data = bytes.fromhex(req["data"])
mode = req["mode"]
out = bytearray(data[:32])
p = 32
while p < len(data):
name = data[p:p + 4]
cl, ul, res = struct.unpack_from("<III", data, p + 4)
p += 16
if cl == 0:
body = data[p:p + ul]; p += ul
else:
body = lz4.block.decompress(data[p:p + cl], uncompressed_size=ul); p += cl
if mode == "unknown" and name == b"END\0":
# an unknown chunk, and a PROP of an unknown type (0x7f) for class 0 (n instances, 3 bytes each)
extra = b"just some bytes the format does not know"
out += b"ZZZZ" + struct.pack("<III", 0, len(extra), 0) + extra
n = req["class0"]
prop = struct.pack("<i", 0) + struct.pack("<I", 7) + b"Mystery" + bytes([0x7f]) + bytes((i * 7 + k) % 256 for i in range(n) for k in range(3))
out += b"PROP" + struct.pack("<III", 0, len(prop), 0) + prop
if name == b"END\0" or mode in ("raw", "unknown"):
out += name + struct.pack("<III", 0, len(body), 0) + body
else:
z = zstandard.ZstdCompressor(level=3, write_content_size=True).compress(body)
out += name + struct.pack("<III", len(z), len(body), 0) + z
sys.stdout.write(out.hex())
"""
# ---------------------------------------------------------------------------------------------------- names from XML
def xml_names(xml_bytes):
"""{ path: [property names] } from an rbxmx / rbxlx (the same path scheme as the lune dump)"""
root = ET.fromstring(xml_bytes)
names = {}
def walk(items, prefix):
seen = {}
for it in items:
props = it.find("Properties")
nm = None
plist = []
if props is not None:
for pr in props:
pn = pr.get("name")
if pn == "Name":
nm = pr.text or ""
elif pn is not None:
plist.append(pn)
nm = nm if nm is not None else it.get("class")
seen[nm] = seen.get(nm, 0) + 1
path = prefix + ("" if prefix == "" else "/") + nm + ("#%d" % seen[nm] if seen[nm] > 1 else "")
names[path] = ["Name"] + [n for n in plist if n not in ("AttributesSerialize", "Tags")]
walk(it.findall("Item"), path)
walk(root.findall("Item"), "")
return names
def luau_cmd():
exe = shutil.which("luau")
return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
def generate(ctx):
tmp = tempfile.mkdtemp(prefix="formats-rbx-")
try:
_generate(ctx, tmp)
finally:
shutil.rmtree(tmp, ignore_errors=True)
def lune(ctx, script, args, tmp):
path = os.path.join(tmp, "script_%d.luau" % abs(hash(script)))
with open(path, "w") as f:
f.write(script)
try:
return subprocess.run(["nix", "shell", "nixpkgs#lune", "-c", "lune", "run", path] + args, capture_output=True, check=True, cwd=tmp).stdout
except subprocess.CalledProcessError as e:
raise RuntimeError("lune: " + e.stderr.decode(errors="replace")[-3000:])
def _generate(ctx, tmp):
rng = random.Random(77)
with open(os.path.join(tmp, "model.project.json"), "w") as f:
json.dump(model_project(rng), f)
with open(os.path.join(tmp, "place.project.json"), "w") as f:
json.dump(place_project(), f)
for proj, outs in (("model", ("model.rbxm", "model.rbxmx")), ("place", ("place.rbxl", "place.rbxlx"))):
for o in outs:
ctx.nix("rojo", ["rojo", "build", os.path.join(tmp, proj + ".project.json"), "-o", os.path.join(tmp, o)])
lune(ctx, LUNE_GEN, [tmp], tmp)
def read(n):
with open(os.path.join(tmp, n), "rb") as f:
return f.read()
files = []
for name, twin, place in (("model.rbxm", "model.rbxmx", False), ("model.rbxmx", "model.rbxmx", False),
("place.rbxl", "place.rbxlx", True), ("place.rbxlx", "place.rbxlx", True),
("lune.rbxm", "lune.rbxmx", False), ("lune.rbxmx", "lune.rbxmx", False)):
files.append({"name": name, "data": read(name), "xml": name.endswith("x"), "place": place, "names": xml_names(read(twin))})
# re-packed variants of the binary model
model = read("model.rbxm")
n0 = None
for mode in ("zstd", "raw", "unknown"):
req = {"data": model.hex(), "mode": mode, "class0": n0 or 0}
if mode == "unknown":
# class 0's instance count: from the raw variant's first INST chunk
raw = bytes.fromhex(ctx.python(["lz4", "zstandard"], REPACK, input=json.dumps({"data": model.hex(), "mode": "raw", "class0": 0}).encode()).decode())
p = 32
while True:
size = struct.unpack_from("<I", raw, p + 8)[0]
if raw[p:p + 4] == b"INST":
body = raw[p + 16:p + 16 + size]
cid, nl = struct.unpack_from("<iI", body, 0)
if cid == 0:
n0 = struct.unpack_from("<I", body, 8 + nl + 1)[0]
break
p += 16 + size
req["class0"] = n0
data = bytes.fromhex(ctx.python(["lz4", "zstandard"], REPACK, input=json.dumps(req).encode()).decode())
fn = "model-%s.rbxm" % mode
with open(os.path.join(tmp, fn), "wb") as f:
f.write(data)
files.append({"name": fn, "data": data, "xml": False, "place": False, "names": files[0]["names"]})
for f in files:
f["path"] = os.path.join(tmp, f["name"])
f["key"] = f["name"]
req = {"files": [{"key": f["key"], "path": f["path"], "place": f["place"], "names": f["names"]} for f in files]}
with open(os.path.join(tmp, "dump.json"), "w") as fh:
json.dump(req, fh)
dumps = json.loads(lune(ctx, LUNE_DUMP, [os.path.join(tmp, "dump.json")], tmp))
for f in files:
d = dumps[f["key"]]
assert "error" not in d, (f["name"], d)
f["dump"] = d
# the dumps as JSON text (a deep Luau table literal is too complex for luau-analyze)
ctx.emit("rbx_files", {"files": [dict({k: f[k] for k in ("name", "data", "xml", "place")}, dump=json.dumps(f["dump"], sort_keys=True)) for f in files]})
# ours: every file decoded and written back as rbxm and rbxmx, read by lune
enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_rbx_encode.luau")], capture_output=True, cwd=ctx.root)
if enc.returncode != 0:
raise RuntimeError("_rbx_encode: " + enc.stderr.decode(errors="replace")[-3000:])
ours = []
byname = {f["name"]: f for f in files}
for line in enc.stdout.decode().split("\n"):
if not line.strip():
continue
label, hexdata = line.split(" ", 1)
src, fmt = label.split("/")
fn = "ours-%s.%s" % (src.replace(".", "_"), ("rbxl" if byname[src]["place"] else "rbxm") + ("x" if fmt == "rbxmx" else ""))
with open(os.path.join(tmp, fn), "wb") as fh:
fh.write(bytes.fromhex(hexdata.strip()))
ours.append((label, fn, byname[src]))
req = {"files": [{"key": label, "path": os.path.join(tmp, fn), "place": f["place"], "names": f["names"]} for label, fn, f in ours]}
with open(os.path.join(tmp, "dump2.json"), "w") as fh:
json.dump(req, fh)
got = json.loads(lune(ctx, LUNE_DUMP, [os.path.join(tmp, "dump2.json")], tmp))
verdicts = []
for label, fn, f in ours:
d = got[label]
ok, detail = True, "%d instances" % len(d)
if "error" in d:
ok, detail = False, "lune: " + d["error"][:300]
else:
want = f["dump"]
if set(d) != set(want):
ok, detail = False, "instance paths differ: %s" % sorted(set(d) ^ set(want))[:5]
else:
for path in sorted(want):
a, b = want[path], d[path]
if a["class"] != b["class"]:
ok, detail = False, "%s: class %s, want %s" % (path, b["class"], a["class"])
break
diff = [k for k in a["props"] if a["props"][k] != b["props"].get(k)]
if diff:
k = diff[0]
ok, detail = False, "%s.%s: %s, want %s" % (path, k, json.dumps(b["props"].get(k))[:200], json.dumps(a["props"][k])[:200])
break
if a["attrs"] != b["attrs"] or sorted(a["tags"]) != sorted(b["tags"]):
ok, detail = False, "%s: attributes / tags differ" % path
break
verdicts.append({"name": label, "ok": ok, "detail": detail})
ctx.emit("rbx_ours", verdicts)
+461
View File
@@ -0,0 +1,461 @@
# Roblox FileMesh fixtures (tools/fixtures.py) for model/robloxmesh. No reference tool reads .mesh files, so this
# generator is an independent writer + reader written from the spec (MaximumADHD's "Roblox Mesh Format" notes,
# devforum 326114): it writes meshes of every version (1.00 / 1.01 ASCII, 2.00 with 36- and 40-byte vertices, 3.00 /
# 3.01 with LODs, 4.00 / 4.01 with bones, skinning and several subsets, 5.00 with a FACS blob, 6.00 / 7.00 chunked
# with LODS, SKINNING, FACS and HSRAVIS chunks, a 7.00 Draco COREMESH) with the values they hold, and reads our
# encoder's output (tools/fixtures/_robloxmesh_encode.luau under the luau CLI) back, as verdicts.
# tests/gen/robloxmesh.luau { cases = { { name, data, version, vertices, faces, pos, nrm, uv, tan?, col?, lods =
# { idx crc ... }, joints?, weights?, bones? = { { name, parent, cf } }, facs?, chunks?,
# unsupported? } }, ours = { { name, ok, detail } } }
import json, math, os, random, shutil, struct, subprocess, zlib
INPUTS = ["src/Formats/model/robloxmesh", "tools/fixtures/_robloxmesh_encode.luau"]
def f32(x):
return struct.unpack("<f", struct.pack("<f", x))[0]
def pk(fmt, vals):
return struct.pack("<%d%s" % (len(vals), fmt), *vals)
def crc(b):
return zlib.crc32(b)
def sbyte(v):
return v - 256 if v >= 128 else v
# ---------------------------------------------------------------------------------------------------- geometry
def sphere(rng, rings, segs, radius=2.0):
verts, faces = [], []
for i in range(rings + 1):
th = math.pi * i / rings
for j in range(segs + 1):
ph = 2 * math.pi * j / segs
n = [math.sin(th) * math.cos(ph), math.cos(th), math.sin(th) * math.sin(ph)]
verts.append({
"pos": [f32(c * radius + rng.uniform(-0.01, 0.01)) for c in n],
"nrm": [f32(c) for c in n],
"uv": [f32(j / segs), f32(i / rings)],
"tan": [rng.randrange(-127, 128) for _ in range(3)] + [rng.choice((-127, 127))],
"col": [rng.randrange(256) for _ in range(4)],
})
for i in range(rings):
for j in range(segs):
a = i * (segs + 1) + j
b = a + segs + 1
faces += [(a, b, a + 1), (a + 1, b, b + 1)]
return verts, faces
def vbytes(v, size):
out = pk("f", v["pos"] + v["nrm"] + v["uv"]) + bytes(t & 255 for t in v["tan"])
if size >= 40:
out += bytes(v["col"])
return out
def fbytes(faces):
return b"".join(pk("I", list(f)) for f in faces)
def tangent_f32(t):
return [f32(max(-1.0, min(1.0, c / 127))) for c in t]
def expect_core(verts, faces, lods, colors, tangents=True):
exp = {
"vertices": len(verts), "faces": len(faces),
"pos": crc(b"".join(pk("f", v["pos"]) for v in verts)),
"nrm": crc(b"".join(pk("f", v["nrm"]) for v in verts)),
"uv": crc(b"".join(pk("f", v["uv"]) for v in verts)),
"lods": [crc(fbytes(faces[lods[k]:lods[k + 1]])) for k in range(len(lods) - 1)],
}
if tangents:
exp["tan"] = crc(b"".join(pk("f", tangent_f32(v["tan"])) for v in verts))
if colors:
exp["col"] = crc(b"".join(bytes(v["col"]) for v in verts))
return exp
# ---------------------------------------------------------------------------------------------------- bones / skinning
def rot_y(a):
c, s = math.cos(a), math.sin(a)
return [c, 0, s, 0, 1, 0, -s, 0, c]
def make_bones(rng, n):
bones = []
for i in range(n):
parent = None if i == 0 else rng.randrange(i)
r = rot_y(rng.uniform(-3, 3))
cf = [f32(x) for x in r + [rng.uniform(-2, 2), rng.uniform(-2, 2), rng.uniform(-2, 2)]]
bones.append({"name": "Bone%02d" % i if i else "Root", "parent": parent, "cf": cf, "culling": f32(rng.uniform(0, 5)), "lodParent": 0xFFFF})
return bones
def make_skin(rng, verts, faces, bones, segs=12):
"""influences per vertex (1..4 bones from a window that moves with the sphere ring, so a third of the faces needs
at most ~20 bones), then subsets by face thirds; vertices are duplicated per subset (the format needs contiguous
vertex ranges). Returns new verts, faces, subsets, envelopes, the expected global joints / weights"""
nb = len(bones)
infl = []
for v in range(len(verts)):
ring = v // (segs + 1)
window = [(ring * 4 + k) % nb for k in range(min(8, nb))]
k = rng.randrange(1, 5)
bs = rng.sample(window, min(k, len(window)))
w = [rng.randrange(1, 100) for _ in bs]
tot = sum(w)
wb = [x * 255 // tot for x in w]
wb[0] += 255 - sum(wb)
infl.append(list(zip(bs, wb)))
nverts, nfaces, subsets, env, joints, weights = [], [], [], [], [], []
chunk = max(1, len(faces) // 3)
for s0 in range(0, len(faces), chunk):
sub_faces = faces[s0:s0 + chunk]
used = []
for f in sub_faces:
for v in f:
if v not in used:
used.append(v)
sub_bones = sorted({b for v in used for b, _ in infl[v]})
assert len(sub_bones) <= 26
loc = {b: i for i, b in enumerate(sub_bones)}
remap = {}
vb = len(nverts)
for v in used:
remap[v] = len(nverts)
nverts.append(verts[v])
pairs = infl[v] + [(None, 0)] * (4 - len(infl[v]))
env.append(bytes(loc[b] if b is not None else 0 for b, _ in pairs) + bytes(w for _, w in pairs))
joints.append([b if b is not None else 0 for b, _ in pairs])
weights.append([w for _, w in pairs])
for f in sub_faces:
nfaces.append(tuple(remap[v] for v in f))
subsets.append({"facesBegin": s0, "facesLength": len(sub_faces), "vertsBegin": vb, "vertsLength": len(nverts) - vb, "bones": sub_bones})
return nverts, nfaces, subsets, env, joints, weights
def bone_bytes(bones):
names = b""
out = b""
for b in bones:
idx = len(names)
names += b["name"].encode() + b"\0"
out += struct.pack("<IHHf", idx, 0xFFFF if b["parent"] is None else b["parent"], b["lodParent"], b["culling"]) + pk("f", b["cf"])
return out, names
def subset_bytes(subsets):
out = b""
for s in subsets:
ids = s["bones"] + [0xFFFF] * (26 - len(s["bones"]))
out += struct.pack("<IIIII", s["facesBegin"], s["facesLength"], s["vertsBegin"], s["vertsLength"], len(s["bones"])) + pk("H", ids)
return out
# ---------------------------------------------------------------------------------------------------- writers
def write_v1(version, verts, faces):
scale = 2.0 if version == "1.00" else 1.0
parts = []
exp_verts = []
for f in faces:
for vi in f:
v = verts[vi]
fp = [c * scale for c in v["pos"]]
fv = 1 - v["uv"][1]
parts.append("[%r,%r,%r][%r,%r,%r][%r,%r,0]" % tuple(fp + v["nrm"] + [v["uv"][0], fv]))
exp_verts.append({"pos": [f32(c * (0.5 if version == "1.00" else 1)) for c in fp], "nrm": v["nrm"], "uv": [v["uv"][0], f32(1 - fv)], "tan": [0, 0, 0, 0], "col": [255] * 4})
data = ("version %s\n%d\n" % (version, len(faces)) + "".join(parts)).encode()
exp_faces = [(3 * i, 3 * i + 1, 3 * i + 2) for i in range(len(faces))]
return data, expect_core(exp_verts, exp_faces, [0, len(faces)], False, tangents=False)
def write_v2(verts, faces, colors):
vs = 40 if colors else 36
data = b"version 2.00\n" + struct.pack("<HBBII", 12, vs, 12, len(verts), len(faces)) + b"".join(vbytes(v, vs) for v in verts) + fbytes(faces)
return data, expect_core(verts, faces, [0, len(faces)], colors)
def write_v3(version, verts, faces, lods):
data = (("version %s\n" % version).encode() + struct.pack("<HBBHHII", 16, 40, 12, 4, len(lods), len(verts), len(faces))
+ b"".join(vbytes(v, 40) for v in verts) + fbytes(faces) + pk("I", lods))
return data, expect_core(verts, faces, lods, True)
def write_v45(version, verts, faces, lods, bones, subsets, env, facs=None):
bb, names = bone_bytes(bones)
head = struct.pack("<HHIIHHIHBB", 32 if version == "5.00" else 24, 3, len(verts), len(faces), len(lods), len(bones), len(names), len(subsets), 1, 0)
if version == "5.00":
head += struct.pack("<II", 1 if facs else 0, len(facs or b""))
data = (("version %s\n" % version).encode() + head + b"".join(vbytes(v, 40) for v in verts) + (b"".join(env) if bones else b"")
+ fbytes(faces) + pk("I", lods) + bb + names + subset_bytes(subsets) + (facs or b""))
return data, expect_core(verts, faces, lods, True)
def chunk(name, version, body):
return name.ljust(8, b"\0") + struct.pack("<II", version, len(body)) + body
def write_v67(version, verts, faces, lods, bones, subsets, env, facs, hsr, draco=False):
if draco:
core = chunk(b"COREMESH", 2, struct.pack("<I", 16) + bytes(range(16)))
else:
core = chunk(b"COREMESH", 1, struct.pack("<I", len(verts)) + b"".join(vbytes(v, 40) for v in verts) + struct.pack("<I", len(faces)) + fbytes(faces))
lodc = chunk(b"LODS", 1, struct.pack("<HBI", 3, 1, len(lods)) + pk("I", lods))
bb, names = bone_bytes(bones)
skin = chunk(b"SKINNING", 1, struct.pack("<I", len(verts)) + b"".join(env) + struct.pack("<I", len(bones)) + bb + struct.pack("<I", len(names)) + names
+ struct.pack("<I", len(subsets)) + subset_bytes(subsets))
out = ("version %s\n" % version).encode() + core + lodc + skin
if facs:
out += chunk(b"FACS", 1, struct.pack("<I", len(facs)) + facs)
if hsr:
out += chunk(b"HSRAVIS", 1, struct.pack("<I", 10) + b"\x55\x01")
return out, expect_core(verts, faces, lods, True)
def skin_expect(exp, bones, joints, weights):
exp["joints"] = crc(b"".join(pk("H", j) for j in joints))
exp["weights"] = crc(b"".join(bytes(w) for w in weights))
exp["bones"] = [dict({"name": b["name"], "cf": b["cf"], "culling": b["culling"]}, **({"parent": b["parent"]} if b["parent"] is not None else {})) for b in bones]
return exp
# ---------------------------------------------------------------------------------------------------- reader (for our output)
def read_mesh(data):
line, rest = data.split(b"\n", 1)
version = line.decode().split()[1]
if version == "2.00":
hs, vs, fs, nv, nf = struct.unpack_from("<HBBII", rest, 0)
p = hs
nb = nsub = names_size = 0
lods = [0, nf]
elif version == "4.00":
hs, lod_type, nv, nf, nl, nb, names_size, nsub, hq, _ = struct.unpack_from("<HHIIHHIHBB", rest, 0)
vs, fs, p = 40, 12, hs
else:
raise ValueError("version " + version)
verts = []
for i in range(nv):
q = p + i * vs
v = struct.unpack_from("<8f", rest, q)
t = [sbyte(c) for c in rest[q + 32:q + 36]]
col = list(rest[q + 36:q + 40]) if vs >= 40 else [255] * 4
verts.append({"pos": list(v[:3]), "nrm": list(v[3:6]), "uv": list(v[6:8]), "tan": t, "col": col})
p += nv * vs
env = []
if version == "4.00" and nb > 0:
env = [rest[p + 8 * i:p + 8 * i + 8] for i in range(nv)]
p += 8 * nv
faces = [struct.unpack_from("<3I", rest, p + 12 * i) for i in range(nf)]
p += 12 * nf
if version == "4.00":
lods = list(struct.unpack_from("<%dI" % nl, rest, p))
p += 4 * nl
bones = []
for i in range(nb):
ni, par, lp, cull = struct.unpack_from("<IHHf", rest, p + 60 * i)
bones.append({"ni": ni, "parent": None if par == 0xFFFF else par, "cf": list(struct.unpack_from("<12f", rest, p + 60 * i + 12))})
p += 60 * nb
names = rest[p:p + names_size]
for b in bones:
b["name"] = names[b["ni"]:].split(b"\0", 1)[0].decode()
p += names_size
subsets = []
for i in range(nsub):
fb, fl, vb, vl, n = struct.unpack_from("<5I", rest, p + 72 * i)
ids = list(struct.unpack_from("<26H", rest, p + 72 * i + 20))[:n]
subsets.append({"facesBegin": fb, "facesLength": fl, "vertsBegin": vb, "vertsLength": vl, "bones": ids})
p += 72 * nsub
assert p == len(rest), "trailing bytes: %d of %d" % (p, len(rest))
return {"version": version, "verts": verts, "faces": faces, "lods": lods, "bones": bones, "subsets": subsets, "env": env}
def corners(m, lod=0):
"""the LOD's triangles as tuples of vertex values (position, uv) - comparable across vertex duplication"""
out = []
for f in m["faces"][m["lods"][lod]:m["lods"][lod + 1]]:
out.append(tuple(tuple(m["verts"][v]["pos"] + m["verts"][v]["uv"]) for v in f))
return out
def vertex_influences(m):
"""per vertex: { global bone: weight byte } through the subsets"""
infl = [None] * len(m["verts"])
for s in m["subsets"]:
assert len(s["bones"]) <= 26
for v in range(s["vertsBegin"], s["vertsBegin"] + s["vertsLength"]):
e = m["env"][v]
d = {}
for k in range(4):
if e[4 + k]:
d[s["bones"][e[k]]] = d.get(s["bones"][e[k]], 0) + e[4 + k]
assert sum(e[4:8]) == 255, "weights sum to %d" % sum(e[4:8])
infl[v] = d
return infl
def check_ours(src, out):
"""our re-encoding of a fixture (src: the original read as a v4-style record) -> ok, detail"""
a, b = src, out
if len(b["verts"]) < 1:
return False, "no vertices"
if sorted(corners(a)) != sorted(corners(b)):
return False, "LOD 0 triangles differ"
if b["version"] == "4.00":
if len(a["lods"]) != len(b["lods"]) and not b["bones"]:
return False, "LOD count %d, want %d" % (len(b["lods"]), len(a["lods"]))
if not b["bones"]:
for k in range(len(a["lods"]) - 1):
if sorted(corners(a, k)) != sorted(corners(b, k)):
return False, "LOD %d differs" % k
if a["bones"]:
if [x["name"] for x in a["bones"]] != [x["name"] for x in b["bones"]] or [x["parent"] for x in a["bones"]] != [x["parent"] for x in b["bones"]]:
return False, "bones differ"
for x, y in zip(a["bones"], b["bones"]):
if any(abs(p - q) > 1e-4 for p, q in zip(x["cf"], y["cf"])):
return False, "bone %s transform differs" % x["name"]
ia, ib = vertex_influences(a), vertex_influences(b)
key = lambda m, i: tuple(m["verts"][i]["pos"] + m["verts"][i]["uv"])
want = {key(a, i): ia[i] for i in range(len(a["verts"]))}
for i in range(len(b["verts"])):
w = want.get(key(b, i))
if w is None or ib[i] is None:
return False, "vertex %d has no influences" % i
if set(w) != set(ib[i]) or any(abs(w[j] - ib[i][j]) > 1 for j in w):
return False, "vertex %d influences %r, want %r" % (i, ib[i], w)
return True, "%d vertices, %d faces, %d bones, %d subsets" % (len(b["verts"]), len(b["faces"]), len(b["bones"]), len(b["subsets"]))
def luau_cmd():
exe = shutil.which("luau")
return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
def generate(ctx):
rng = random.Random(1337)
cases = []
sv, sf = sphere(rng, 8, 12)
for version in ("1.00", "1.01"):
data, exp = write_v1(version, sv, sf[:60])
cases.append(dict(exp, name="v" + version, data=data, version=version))
for colors in (False, True):
data, exp = write_v2(sv, sf, colors)
cases.append(dict(exp, name="v2.00-%d" % (40 if colors else 36), data=data, version="2.00"))
lods = [0, len(sf) // 2, len(sf) * 3 // 4, len(sf)]
for version in ("3.00", "3.01"):
data, exp = write_v3(version, sv, sf, lods)
cases.append(dict(exp, name="v" + version, data=data, version=version))
# skinned: 6 bones (one subset of all of them) and 40 bones (several subsets of up to 26)
bones6 = make_bones(rng, 6)
bones40 = make_bones(rng, 40)
for version in ("4.00", "4.01", "5.00"):
for bones in (bones6, bones40):
nv, nf, subs, env, joints, weights = make_skin(rng, sv, sf, bones)
lods2 = [0, len(nf)]
facs = bytes(rng.randrange(256) for _ in range(77)) if version == "5.00" else None
data, exp = write_v45(version, nv, nf, lods2, bones, subs, env, facs)
exp = skin_expect(exp, bones, joints, weights)
if facs:
exp["facs"] = crc(facs)
cases.append(dict(exp, name="v%s-%dbones" % (version, len(bones)), data=data, version=version))
# unskinned 4.00 with LODs
data, exp = write_v45("4.00", sv, sf, lods, [], [], [])
cases.append(dict(exp, name="v4.00-lods", data=data, version="4.00"))
for version in ("6.00", "7.00"):
nv, nf, subs, env, joints, weights = make_skin(rng, sv, sf, bones40)
facs = bytes(rng.randrange(256) for _ in range(40))
data, exp = write_v67(version, nv, nf, [0, len(nf) // 2, len(nf)], bones40, subs, env, facs, hsr=True)
exp = skin_expect(exp, bones40, joints, weights)
exp["facs"] = crc(facs)
exp["chunks"] = ["HSRAVIS"]
cases.append(dict(exp, name="v" + version, data=data, version=version))
data, _ = write_v67("7.00", sv, sf, [0, len(sf)], [], [], [], None, hsr=False, draco=True)
cases.append({"name": "v7.00-draco", "data": data, "version": "7.00", "unsupported": True})
ctx.emit("robloxmesh", {"cases": cases})
# ours: every decodable case re-encoded as 2.00 and 4.00, read back here
enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_robloxmesh_encode.luau")], capture_output=True, cwd=ctx.root)
if enc.returncode != 0:
raise RuntimeError("_robloxmesh_encode: " + enc.stderr.decode(errors="replace")[-3000:])
originals = {}
byname = {c["name"]: c for c in cases}
ours = []
for line in enc.stdout.decode().split("\n"):
if not line.strip():
continue
label, hexdata = line.split(" ", 1)
name, version = label.rsplit("/", 1)
try:
out = read_mesh(bytes.fromhex(hexdata.strip()))
if name not in originals:
originals[name] = read_original(byname[name])
ok, detail = check_ours(originals[name], out)
except Exception as e: # a reader failure is a verdict, not a fixture error
ok, detail = False, "read: %r" % e
ours.append({"name": label, "ok": ok, "detail": detail})
ctx.emit("robloxmesh", {"cases": cases, "ours": ours})
def read_original(case):
"""a fixture case as the record read_mesh gives (version 1 / 3 / 5 / 6 / 7 are rewritten through the 4.00 shape)"""
data = case["data"]
line, rest = data.split(b"\n", 1)
version = line.decode().split()[1]
if version in ("1.00", "1.01"):
text = rest.decode().split("\n", 1)[1]
vals = [float(x) for x in text.replace("][", ",").strip("[]").split(",")]
scale = 0.5 if version == "1.00" else 1
verts = []
for i in range(0, len(vals), 9):
verts.append({"pos": [f32(c * scale) for c in vals[i:i + 3]], "nrm": [f32(c) for c in vals[i + 3:i + 6]], "uv": [f32(vals[i + 6]), f32(1 - vals[i + 7])]})
nf = len(verts) // 3
return {"version": version, "verts": verts, "faces": [(3 * i, 3 * i + 1, 3 * i + 2) for i in range(nf)], "lods": [0, nf], "bones": [], "subsets": [], "env": []}
if version == "2.00":
return read_mesh(data)
if version in ("3.00", "3.01"):
hs, vs, fs, ls, nl, nv, nf = struct.unpack_from("<HBBHHII", rest, 0)
head = struct.pack("<HHIIHHIHBB", 24, 0, nv, nf, nl, 0, 0, 0, 0, 0)
return read_mesh(b"version 4.00\n" + head + rest[hs:])
if version in ("4.00", "4.01", "5.00"):
hs = struct.unpack_from("<H", rest, 0)[0]
fields = list(struct.unpack_from("<HHIIHHIHBB", rest, 0))
fields[0] = 24
body = rest[hs:]
if version == "5.00":
body = body[:len(body) - struct.unpack_from("<I", rest, 28)[0]]
return read_mesh(b"version 4.00\n" + struct.pack("<HHIIHHIHBB", *fields) + body)
# 6.00 / 7.00: chunks to the 4.00 layout
p, parts = 0, {}
while p < len(rest):
name = rest[p:p + 8].rstrip(b"\0").decode()
cv, size = struct.unpack_from("<II", rest, p + 8)
parts[name] = rest[p + 16:p + 16 + size]
p += 16 + size
core = parts["COREMESH"]
nv = struct.unpack_from("<I", core, 0)[0]
verts = core[4:4 + 40 * nv]
nf = struct.unpack_from("<I", core, 4 + 40 * nv)[0]
faces = core[8 + 40 * nv:8 + 40 * nv + 12 * nf]
lc = parts["LODS"]
nl = struct.unpack_from("<I", lc, 3)[0]
lods = lc[7:7 + 4 * nl]
sk = parts["SKINNING"]
q = 4
env = sk[q:q + 8 * nv]
q += 8 * nv
nb = struct.unpack_from("<I", sk, q)[0]
q += 4
bones = sk[q:q + 60 * nb]
q += 60 * nb
ns = struct.unpack_from("<I", sk, q)[0]
names = sk[q + 4:q + 4 + ns]
q += 4 + ns
nsub = struct.unpack_from("<I", sk, q)[0]
subs = sk[q + 4:q + 4 + 72 * nsub]
head = struct.pack("<HHIIHHIHBB", 24, 3, nv, nf, nl, nb, ns, nsub, 1, 0)
return read_mesh(b"version 4.00\n" + head + verts + env + faces + lods + bones + names + subs)
+244
View File
@@ -0,0 +1,244 @@
# model/schematic fixtures: schematics written by reference code through nix, with every cell's block state, and our
# encoder's output read back by the same reference code.
# .litematic: Python's litemapy (several regions, a negative size, a 40-state palette), a tile entity added with
# nbtlib; .schem v2: litemapy's Region.to_sponge_nbt (+ a block entity); .schem v1 / v3 and the legacy
# MCEdit .schematic (ids + data, WorldEdit AddBlocks, a SchematicaMapping table): nbtlib, by the specs.
# tests/gen/schematic.luau { cases = { { name, data, variant, version, regions = { { name, min = {x,y,z},
# size = {x,y,z}, cells = "state\n..." (Voxels order: x, then y, then z) or legacy =
# { id*16+data per cell } } }, blockEntities = n, ... } } }
# tests/gen/schematic_ours.luau { [name] = { regions = { { name, min, size, cells } } } }: our encodings
# (tools/fixtures/_schematic_encode.luau) read back by litemapy / nbtlib
import importlib.util, os, pickle, subprocess, sys
INPUTS = ["src/Formats/model/schematic", "src/Formats/codecs/model/Minecraft", "src/Formats/codecs/text/Nbt", "tools/fixtures/_schematic_encode.luau"]
_spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_model_ref.py"))
R = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(R)
COMMON = r'''
import nbtlib, pickle, random, struct, sys, io, gzip, os, tempfile
from nbtlib import Byte, Short, Int, Long, Float, Double, String, List, Compound, ByteArray, IntArray, LongArray
import numpy as np
from litemapy import Schematic, Region, BlockState
def state_of(bs):
# a litemapy BlockState as the state string, properties in the NBT order
t = bs.to_nbt()
props = t.get("Properties")
if props:
return str(t["Name"]) + "[" + ",".join("%s=%s" % (k, str(v)) for k, v in props.items()) + "]"
return str(t["Name"])
def region_cells(reg):
xs, ys, zs = list(reg.range_x()), list(reg.range_y()), list(reg.range_z())
out = []
for z in zs:
for y in ys:
for x in xs:
out.append(state_of(reg[x, y, z]))
return out
def region_info(name, reg):
return {"name": name, "min": [reg.min_schem_x(), reg.min_schem_y(), reg.min_schem_z()],
"size": [abs(reg.width), abs(reg.height), abs(reg.length)], "cells": "\n".join(region_cells(reg))}
def sponge_cells(s):
# Sponge v1 / v2 / v3 compound -> min, size, cells
v = int(s.get("Version", 1))
w, h, l = int(s["Width"]) & 0xffff, int(s["Height"]) & 0xffff, int(s["Length"]) & 0xffff
blocks = s["Blocks"] if v >= 3 else s
pal = blocks["Palette"]
data = bytes(np.asarray(blocks["Data"] if v >= 3 else blocks["BlockData"], dtype=np.int8).tobytes())
names = {int(i): k for k, i in pal.items()}
idx, p = [], 0
while len(idx) < w * h * l:
val, sh = 0, 0
while True:
c = data[p]; p += 1
val |= (c & 0x7f) << sh
sh += 7
if c < 128: break
idx.append(val)
cells = []
for z in range(l):
for y in range(h):
for x in range(w):
cells.append(names[idx[x + z * w + y * w * l]])
off = list(s["Offset"]) if "Offset" in s else [0, 0, 0]
return {"name": "", "min": [int(o) for o in off], "size": [w, h, l], "cells": "\n".join(cells)}
'''
BODY = COMMON + r'''
rng = random.Random(11)
STATES = ["minecraft:air", "minecraft:stone", "minecraft:red_wool", "minecraft:glass", "minecraft:oak_planks",
"minecraft:water[level=0]", "minecraft:grass_block[snowy=false]", "minecraft:oak_log[axis=y]",
"minecraft:oak_stairs[facing=east,half=bottom,shape=straight,waterlogged=false]",
"minecraft:chest[facing=north,type=single,waterlogged=false]", "minecraft:spruce_slab[type=top,waterlogged=false]",
"minecraft:lantern[hanging=true,waterlogged=false]"]
COLOURS = ["white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan",
"purple", "blue", "brown", "green", "red", "black"]
BIG = ["minecraft:%s_%s" % (c, k) for c in COLOURS for k in ("wool", "concrete", "terracotta")]
def bs(s):
if "[" in s:
name, rest = s.split("[", 1)
props = dict(kv.split("=") for kv in rest[:-1].split(","))
return BlockState(name, **props)
return BlockState(s)
def fill(reg, states):
for x in reg.range_x():
for y in reg.range_y():
for z in reg.range_z():
reg[x, y, z] = bs(rng.choice(states))
cases = []
tmp = tempfile.mkdtemp()
# 1. litematic: three regions (one with negative sizes, one with a 40-state palette)
main = Region(0, 0, 0, 6, 5, 4); fill(main, STATES)
neg = Region(10, 2, -3, -4, 3, -5); fill(neg, STATES[:6])
big = Region(-20, 0, 0, 7, 3, 5); fill(big, BIG)
sch = Schematic(name="Test", author="formats-luau", description="fixture", regions={"main": main, "neg": neg, "big": big})
path = os.path.join(tmp, "t.litematic")
sch.save(path)
f = nbtlib.load(path)
# a tile entity, as Litematica stores them (relative to the region's minimum corner)
f["Regions"]["main"]["TileEntities"].append(Compound({"x": Int(1), "y": Int(0), "z": Int(2), "id": String("minecraft:chest"), "Items": List[Compound]([])}))
f.save(path)
data = open(path, "rb").read()
cases.append({"name": "litemapy", "variant": "litematic", "version": 6, "data": data, "blockEntities": 1,
"regions": [region_info(n, r) for n, r in Schematic.load(path).regions.items()]})
# 2. schem v2 from litemapy (+ a block entity)
reg = Region(0, 0, 0, 5, 4, 6); fill(reg, STATES)
sp = reg.to_sponge_nbt(mc_version=3465)
sp["BlockEntities"].append(Compound({"Pos": IntArray([1, 2, 3]), "Id": String("minecraft:chest"), "Items": List[Compound]([])}))
path = os.path.join(tmp, "v2.schem")
sp.save(path, gzipped=True)
data = open(path, "rb").read()
cases.append({"name": "sponge2", "variant": "schem", "version": 2, "data": data, "blockEntities": 1, "regions": [sponge_cells(nbtlib.load(path))]})
# 3. schem v3 / v1 by the spec (nbtlib), a palette past 128 states (two-byte varints)
def varints(idx):
out = bytearray()
for v in idx:
while v >= 128:
out.append((v & 0x7f) | 0x80); v >>= 7
out.append(v)
return bytes(out)
def sponge(version, w, h, l, states, offset):
states = list(dict.fromkeys(states))
pal = {s: i for i, s in enumerate(states)}
idx = [rng.randrange(len(states)) for _ in range(w * h * l)]
data = ByteArray(np.frombuffer(varints(idx), dtype=np.int8))
palc = Compound({s: Int(i) for s, i in pal.items()})
if version >= 3:
s = Compound({"Version": Int(3), "DataVersion": Int(3953), "Width": Short(w), "Height": Short(h), "Length": Short(l),
"Offset": IntArray(offset), "Metadata": Compound({"Name": String("v3"), "Date": Long(1700000000000)}),
"Blocks": Compound({"Palette": palc, "Data": data, "BlockEntities": List[Compound]([
Compound({"Pos": IntArray([0, 1, 2]), "Id": String("minecraft:chest"), "Data": Compound({"Items": List[Compound]([])})})])}),
"Biomes": Compound({"Palette": Compound({"minecraft:plains": Int(0)}), "Data": ByteArray([0] * (w * h * l))}),
"Entities": List[Compound]([Compound({"Pos": List[Double]([Double(1.5), Double(0.0), Double(2.5)]), "Id": String("minecraft:pig"), "Data": Compound({})})])})
return nbtlib.File({"Schematic": s}, root_name=""), s
s = Compound({"Version": Int(1), "Width": Short(w), "Height": Short(h), "Length": Short(l), "Offset": IntArray(offset),
"PaletteMax": Int(len(states)), "Palette": palc, "BlockData": data,
"TileEntities": List[Compound]([Compound({"Pos": IntArray([0, 0, 0]), "Id": String("minecraft:chest"), "Items": List[Compound]([])})])})
return nbtlib.File(s, root_name="Schematic"), s
stairs = ["minecraft:oak_stairs[facing=%s,half=%s,shape=%s,waterlogged=false]" % (f_, h_, s_)
for f_ in ("north", "south", "east", "west") for h_ in ("top", "bottom")
for s_ in ("straight", "inner_left", "inner_right", "outer_left", "outer_right")]
for name, version, states, size, off in [("sponge3", 3, ["minecraft:air"] + BIG + stairs + STATES[1:], (9, 7, 8), [-4, 1, 7]),
("sponge1", 1, STATES, (4, 3, 5), [0, 0, 0])]:
f, s = sponge(version, size[0], size[1], size[2], states, off)
path = os.path.join(tmp, name + ".schem")
f.save(path, gzipped=True)
data = open(path, "rb").read()
cases.append({"name": name, "variant": "schem", "version": version, "data": data, "blockEntities": 1, "regions": [sponge_cells(s)]})
# 4. MCEdit .schematic: legacy ids and data values (WorldEdit AddBlocks; a Schematica name table)
LEGACY = [(0, 0), (1, 0), (1, 3), (35, 14), (35, 0), (5, 2), (17, 5), (53, 3), (20, 0), (98, 1), (159, 11), (251, 4), (44, 9), (2, 0)]
for name, ids, add, mapping in [("mcedit", LEGACY, False, False), ("worldedit_add", LEGACY + [(300, 2), (4000, 0)], True, False),
("schematica", LEGACY, False, True)]:
w, h, l = 5, 4, 3
n = w * h * l
cells = [rng.choice(ids) for _ in range(n)] # in file order (x + z*w + y*w*l)
blocks = bytes(c[0] & 0xff for c in cells)
datas = bytes(c[1] for c in cells)
root = Compound({"Width": Short(w), "Height": Short(h), "Length": Short(l), "Materials": String("Alpha"),
"Blocks": ByteArray(np.frombuffer(blocks, dtype=np.int8)), "Data": ByteArray(np.frombuffer(datas, dtype=np.int8)),
"Entities": List[Compound]([]),
"TileEntities": List[Compound]([Compound({"x": Int(1), "y": Int(1), "z": Int(1), "id": String("Chest"), "Items": List[Compound]([])})]),
"WEOffsetX": Int(-2), "WEOffsetY": Int(0), "WEOffsetZ": Int(3)})
if add:
nib = bytearray((n + 1) // 2)
for i, c in enumerate(cells):
hi = c[0] >> 8
nib[i >> 1] |= (hi << 4) if i % 2 == 0 else hi # high nibble first (WorldEdit)
root["AddBlocks"] = ByteArray(np.frombuffer(bytes(nib), dtype=np.int8))
if mapping:
root["SchematicaMapping"] = Compound({"minecraft:stone": Short(1), "minecraft:wool": Short(35), "minecraft:planks": Short(5),
"minecraft:log": Short(17), "minecraft:oak_stairs": Short(53), "minecraft:air": Short(0),
"minecraft:glass": Short(20), "minecraft:stonebrick": Short(98),
"minecraft:stained_hardened_clay": Short(159), "minecraft:concrete": Short(251),
"minecraft:stone_slab": Short(44), "minecraft:grass": Short(2)})
path = os.path.join(tmp, name + ".schematic")
nbtlib.File(root, root_name="Schematic").save(path, gzipped=True)
legacy = []
for z in range(l):
for y in range(h):
for x in range(w):
c = cells[x + z * w + y * w * l]
legacy.append(c[0] * 16 + c[1])
cases.append({"name": name, "variant": "schematic", "version": 0, "data": open(path, "rb").read(), "blockEntities": 1,
"regions": [{"name": "", "min": [-2, 0, 3], "size": [w, h, l], "legacy": legacy}]})
sys.stdout.buffer.write(pickle.dumps(cases, protocol=4))
'''
# our encodings read back: litematic by litemapy, schem v2 by litemapy's from_sponge_nbt, every Sponge version and
# the MCEdit layout by nbtlib
READ_BACK = COMMON + r'''
files = pickle.loads(sys.stdin.buffer.read())
tmp = tempfile.mkdtemp()
out = {}
for name, data in files.items():
path = os.path.join(tmp, name)
open(path, "wb").write(data)
f = nbtlib.load(path)
if name.endswith(".litematic"):
s = Schematic.load(path)
out[name] = {"regions": [region_info(n, r) for n, r in s.regions.items()], "author": s.author, "name": s.name}
elif name.endswith(".schem"):
s = f["Schematic"] if "Schematic" in f and "Version" not in f else f
regs = [sponge_cells(s)]
res = {"regions": regs, "version": int(s["Version"])}
if int(s["Version"]) == 2:
reg, mc = Region.from_sponge_nbt(nbtlib.load(path))
cells = region_cells(reg)
res["litemapy"] = "\n".join(cells)
out[name] = res
else:
w, h, l = int(f["Width"]), int(f["Height"]), int(f["Length"])
blocks = np.asarray(f["Blocks"], dtype=np.uint8)
datas = np.asarray(f["Data"], dtype=np.uint8)
add = np.asarray(f["AddBlocks"], dtype=np.uint8) if "AddBlocks" in f else None
legacy = []
for z in range(l):
for y in range(h):
for x in range(w):
i = x + z * w + y * w * l
bid = int(blocks[i])
if add is not None:
bid |= ((int(add[i >> 1]) >> (4 if i % 2 == 0 else 0)) & 15) << 8
legacy.append(bid * 16 + int(datas[i]))
out[name] = {"regions": [{"name": "", "min": [int(f.get("WEOffsetX", 0)), int(f.get("WEOffsetY", 0)), int(f.get("WEOffsetZ", 0))], "size": [w, h, l], "legacy": legacy}]}
sys.stdout.buffer.write(pickle.dumps(out, protocol=4))
'''
def run(ctx, packages, body, input=None):
try:
return ctx.python(packages, body, input=input)
except subprocess.CalledProcessError as e:
raise RuntimeError("fixture python failed:\n" + e.stderr.decode(errors="replace")[-3000:])
def generate(ctx):
cases = pickle.loads(run(ctx, ["nbtlib", "litemapy", "numpy"], BODY))
ctx.emit("schematic", {"cases": cases})
try:
files = R.luau_encode(ctx, "tools/fixtures/_schematic_encode.luau")
except subprocess.CalledProcessError as e:
raise RuntimeError("our encoder failed:\n" + (e.stderr or b"").decode(errors="replace")[-3000:] + (e.stdout or b"").decode(errors="replace")[-2000:])
ours = pickle.loads(run(ctx, ["nbtlib", "litemapy", "numpy"], READ_BACK, input=pickle.dumps(files)))
ctx.emit("schematic_ours", ours)
+499
View File
@@ -0,0 +1,499 @@
# Smacker fixtures (tools/fixtures.py): ffmpeg cannot write Smacker, so this encodes SMK2 / SMK4 files: the four
# header trees (8-bit low / high byte trees, escape leaves used through the recent-value cache, absent trees), every
# block type (MONO, FULL with the SMK4 doubled modes, SKIP, FILL) with block runs, palette updates (new entries, skips,
# copies from the old palette), a ring frame, both frame-time units, and audio tracks: packed DPCM 16-bit stereo and
# 8-bit mono, raw s16le and u8. The reference is ffmpeg's decode: the CRC-32 of each video frame as rgba and of each
# audio track as f32le.
# tests/gen/smk_cases.luau { { name, data, width, height, rate, frames = { crc }, audio = { { rate, channels,
# bits, codec, frames, crc } } } }
import heapq, importlib.util, math, os, random, struct, tempfile, zlib
_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"]
RUNS = list(range(1, 60)) + [128, 256, 512, 1024, 2048]
# ---------------------------------------------------------------------------------------------------- bits / trees
class Bits:
def __init__(self):
self.bits = []
def put(self, v, n):
for i in range(n):
self.bits.append((v >> i) & 1)
def code(self, c):
self.bits.extend(c)
def bytes(self):
out = bytearray((len(self.bits) + 7) // 8)
for i, b in enumerate(self.bits):
out[i >> 3] |= b << (i & 7)
return bytes(out)
def huffman(freqs, maxdepth):
"""a Huffman tree over freqs {value: count}: nested (left, right) tuples / ('leaf', value)"""
f = dict(freqs)
while True:
heap = [(c, i, ("leaf", v)) for i, (v, c) in enumerate(sorted(f.items()))]
heapq.heapify(heap)
k = len(heap)
while len(heap) > 1:
a = heapq.heappop(heap)
b = heapq.heappop(heap)
heapq.heappush(heap, (a[0] + b[0], k, (a[2], b[2])))
k += 1
tree = heap[0][2]
if depth(tree) <= maxdepth:
return tree
f = {v: c // 2 + 1 for v, c in f.items()}
def depth(t):
return 0 if t[0] == "leaf" else 1 + max(depth(t[0]), depth(t[1]))
def codes(t, prefix=(), out=None):
out = {} if out is None else out
if t[0] == "leaf":
out[t[1]] = list(prefix)
else:
codes(t[0], prefix + (0,), out)
codes(t[1], prefix + (1,), out)
return out
def write_tree8(bw, t):
if t[0] == "leaf":
bw.put(0, 1)
bw.put(t[1], 8)
else:
bw.put(1, 1)
write_tree8(bw, t[0])
write_tree8(bw, t[1])
class BigTree:
"""a header tree: values (16-bit) with three escape leaves for the recent-value cache"""
def __init__(self, freqs, rnd, absent_ok=True):
self.absent = not freqs
if self.absent:
return
lo = {}
hi = {}
for v, c in freqs.items():
lo[v & 255] = lo.get(v & 255, 0) + c
hi[v >> 8] = hi.get(v >> 8, 0) + c
# three escape values made of bytes the byte trees have, not used as values (a high-byte tree of only 0 is
# left out: absent byte trees decode as 0)
esc = []
for l in sorted(lo):
for h in sorted(hi):
v = l | h << 8
if v not in freqs and len(esc) < 3:
esc.append(v)
while len(esc) < 3: # every combination used: widen the low byte tree
nl = next(x for x in range(256) if x not in lo)
lo[nl] = 1
esc.append(nl | sorted(hi)[0] << 8)
self.esc = esc
self.lo = huffman(lo, 27)
self.hi = huffman(hi, 27)
allv = dict(freqs)
for i, e in enumerate(esc):
allv[e] = max(1, sum(freqs.values()) // (8 + i))
self.tree = huffman(allv, 200)
self.lcodes, self.hcodes, self.vcodes = codes(self.lo), codes(self.hi), codes(self.tree)
self.entries = count_entries(self.tree)
self.hi_absent = len(hi) == 1 and 0 in hi
self.rnd = rnd
def write(self, bw):
if self.absent:
bw.put(0, 1)
return
bw.put(1, 1)
bw.put(1, 1)
write_tree8(bw, self.lo)
bw.put(0, 1)
if self.hi_absent:
bw.put(0, 1)
else:
bw.put(1, 1)
write_tree8(bw, self.hi)
bw.put(0, 1)
for e in self.esc:
bw.put(e, 16)
self._write_big(bw, self.tree)
bw.put(0, 1)
def _write_big(self, bw, t):
if t[0] == "leaf":
bw.put(0, 1)
v = t[1]
bw.code(self.lcodes[v & 255])
if not self.hi_absent:
bw.code(self.hcodes[v >> 8])
else:
bw.put(1, 1)
self._write_big(bw, t[0])
self._write_big(bw, t[1])
def size(self):
return 0 if self.absent else (self.entries + 3) * 4
def reset(self):
self.cache = [0, 0, 0]
def emit(self, bw, v):
if self.absent:
assert v == 0
return
hit = [k for k in range(3) if self.cache[k] == v]
if hit and self.rnd.random() < 0.7:
bw.code(self.vcodes[self.esc[hit[0]]])
else:
bw.code(self.vcodes[v])
if v != self.cache[0]:
self.cache[2] = self.cache[1]
self.cache[1] = self.cache[0]
self.cache[0] = v
def count_entries(t):
return 1 if t[0] == "leaf" else 1 + count_entries(t[0]) + count_entries(t[1])
# ---------------------------------------------------------------------------------------------------- video
def blocks_of(img, w, h):
return [[[img[by * 4 + r][bx * 4 + x] for x in range(4)] for r in range(4)] for by in range(h // 4) for bx in range(w // 4)]
def classify(b, prev, v4):
if prev is not None and b == prev:
return ("skip",)
flat = [p for r in b for p in r]
cols = sorted(set(flat))
if len(cols) == 1:
return ("fill", cols[0])
if len(cols) == 2:
lo, hi = cols
m = 0
for i, p in enumerate(flat):
if p == hi:
m |= 1 << i
return ("mono", hi << 8 | lo, m)
if v4 and b[0] == b[1] and b[2] == b[3] and b[0][0] == b[0][1] and b[0][2] == b[0][3] and b[2][0] == b[2][1] and b[2][2] == b[2][3]:
return ("full", 1)
if v4 and b[0] == b[1] and b[2] == b[3]:
return ("full", 2)
return ("full", 0)
def full_codes(b, mode):
if mode == 0:
out = []
for r in b:
out += [r[2] | r[3] << 8, r[0] | r[1] << 8]
return out
if mode == 1:
return [b[0][0] | b[0][2] << 8, b[2][0] | b[2][2] << 8]
return [b[0][2] | b[0][3] << 8, b[0][0] | b[0][1] << 8, b[2][2] | b[2][3] << 8, b[2][0] | b[2][1] << 8]
def plan(frames, w, h, v4):
"""per frame the list of runs: (kind, extra, [blocks])"""
out = []
prev = None
for img in frames:
bl = blocks_of(img, w, h)
cls = [classify(b, prev[i] if prev else None, v4) for i, b in enumerate(bl)]
runs = []
i = 0
while i < len(bl):
c = cls[i]
key = c[:2] if c[0] in ("fill", "full") else c[:1]
j = i
while j + 1 < len(bl) and (cls[j + 1][:2] if cls[j + 1][0] in ("fill", "full") else cls[j + 1][:1]) == key:
j += 1
n = j - i + 1
# the largest run length of the table that fits
k = max(r for r in RUNS if r <= n)
runs.append((c, [bl[x] for x in range(i, i + k)], [cls[x] for x in range(i, i + k)], RUNS.index(k)))
i += k
out.append(runs)
prev = bl
return out
def type_value(c, ri):
kind = {"mono": 0, "full": 1, "skip": 2, "fill": 3}[c[0]]
v = kind | ri << 2
if c[0] == "fill":
v |= c[1] << 8
return v
def stats(plans, v4):
f = {"type": {}, "mclr": {}, "mmap": {}, "full": {}}
def add(t, v):
f[t][v] = f[t].get(v, 0) + 1
for runs in plans:
for c, bl, cl, ri in runs:
add("type", type_value(c, ri))
if c[0] == "mono":
for x in cl:
add("mclr", x[1])
add("mmap", x[2])
elif c[0] == "full":
for b in bl:
for v in full_codes(b, c[1]):
add("full", v)
return f
def encode_video(frames, w, h, v4, rnd):
plans = plan(frames, w, h, v4)
f = stats(plans, v4)
trees = {k: BigTree(f[k], rnd) for k in ("mmap", "mclr", "full", "type")}
tb = Bits()
for k in ("mmap", "mclr", "full", "type"):
trees[k].write(tb)
treebytes = tb.bytes()
out = []
for runs in plans:
for t in trees.values():
t.reset()
bw = Bits()
for c, bl, cl, ri in runs:
trees["type"].emit(bw, type_value(c, ri))
if c[0] == "mono":
for x in cl:
trees["mclr"].emit(bw, x[1])
trees["mmap"].emit(bw, x[2])
elif c[0] == "full":
if v4:
bw.code([1] if c[1] == 1 else [0, 1] if c[1] == 2 else [0, 0])
for b in bl:
for v in full_codes(b, c[1]):
trees["full"].emit(bw, v)
out.append(bw.bytes() or b"\0")
return treebytes, [trees[k].size() for k in ("mmap", "mclr", "full", "type")], out
# ---------------------------------------------------------------------------------------------------- palettes
def pal_chunk(new, old, first):
"""a palette update: new / old are lists of 256 6-bit (r, g, b)"""
body = bytearray()
i = 0
while i < 256:
if not first and new[i] == old[i]:
j = i
while j < 256 and j - i < 128 and new[j] == old[j]:
j += 1
body.append(0x80 | (j - i - 1))
i = j
continue
# a copy from the old palette when the next entries appear there in a row
if not first:
for off in range(256):
n = 0
while i + n < 256 and off + n < 256 and n < 64 and new[i + n] == old[off + n]:
n += 1
if n >= 2:
body += bytes([0x40 | (n - 1), off])
i += n
break
else:
off = None
if off is not None:
continue
body += bytes(new[i])
i += 1
size = 1 + len(body)
size = (size + 3) // 4 * 4
return bytes([size // 4]) + bytes(body) + bytes(size - 1 - len(body))
# ---------------------------------------------------------------------------------------------------- audio
def pack_audio(samples, ch, bits):
"""one packed (SMKA) chunk body: samples interleaved (s16 or u8)"""
nb = bits // 8
bw = Bits()
bw.put(1, 1)
bw.put(1 if ch == 2 else 0, 1)
bw.put(1 if bits == 16 else 0, 1)
mod = 65536 if bits == 16 else 256
pred = list(samples[:ch])
deltas = []
for i in range(ch, len(samples)):
c = i % ch
d = (samples[i] - pred[c]) % mod
pred[c] = samples[i]
deltas.append((c, d))
ntrees = (2 if bits == 16 else 1) * ch
freqs = [dict() for _ in range(ntrees)]
for c, d in deltas:
if bits == 16:
freqs[2 * c][d & 255] = freqs[2 * c].get(d & 255, 0) + 1
freqs[2 * c + 1][d >> 8] = freqs[2 * c + 1].get(d >> 8, 0) + 1
else:
freqs[c][d] = freqs[c].get(d, 0) + 1
trees = [huffman(f or {0: 1}, 27) for f in freqs]
cds = [codes(t) for t in trees]
for t in trees:
bw.put(1, 1)
write_tree8(bw, t)
bw.put(0, 1)
for c in range(ch - 1, -1, -1):
v = samples[c] % mod
if bits == 16:
v = ((v & 255) << 8) | (v >> 8) # stored byte-swapped
bw.put(v, bits)
for c, d in deltas:
if bits == 16:
bw.code(cds[2 * c][d & 255])
bw.code(cds[2 * c + 1][d >> 8])
else:
bw.code(cds[c][d])
return struct.pack("<I", len(samples) * nb) + bw.bytes()
def tone(n, ch, bits, rate, seed, f0):
rnd = random.Random(seed)
out = []
for i in range(n):
for c in range(ch):
v = 0.5 * math.sin(2 * math.pi * f0 * (c + 1) * i / rate) + 0.05 * (rnd.random() - 0.5)
if bits == 16:
out.append(int(v * 30000))
else:
out.append(int(128 + v * 120))
return out
# ---------------------------------------------------------------------------------------------------- files
def idx_frames(w, h, n, seed, busy=False):
rnd = random.Random(seed)
out = []
for t in range(n):
if busy: # textured, moving: mostly FULL blocks (the bench)
img = [[(x * 3 + y * 5 + ((x + t * 4) * (y + t)) // 7) % 251 for x in range(w)] for y in range(h)]
else:
img = [[(x // 8 + y // 8 * 3) % 40 for x in range(w)] for y in range(h)]
for y in range(8, 24):
for x in range(8 + t * 4, 24 + t * 4):
img[y][x] = 100 + (x + y) % 2 # two colours: MONO blocks
for y in range(h - 16, h - 8):
for x in range(0, w):
img[y][x] = 50 + ((x // 2) % 5) if (t % 2 == 0) else 60 # doubled pixels: SMK4 modes
for y in range(28, 36):
for x in range(w // 2, w // 2 + 12):
img[y][x] = rnd.randrange(256)
out.append(img)
return out
def smk_file(version, w, h, nframes, pts_inc, tracks, ring, seed, busy=False):
"""version 2 / 4; tracks = [(kind, rate, ch, bits)] kind "packed" / "raw"; returns bytes, track info"""
rnd = random.Random(seed)
frames = idx_frames(w, h, nframes, seed, busy)
if ring:
frames = frames + [frames[0]]
treebytes, sizes, video = encode_video(frames, w, h, version == 4, rnd)
total = len(frames)
# palettes (6-bit), changing on some frames
pals = []
cur = [(rnd.randrange(64), rnd.randrange(64), rnd.randrange(64)) for _ in range(256)]
for t in range(total):
if t in (3, 5):
cur = list(cur)
for k in range(20 + t, 40 + t):
cur[k] = (rnd.randrange(64), rnd.randrange(64), rnd.randrange(64))
cur[200:210] = pals[0][10:20] # a copy from the old palette
pals.append(list(cur))
# audio per frame
seconds = (pts_inc / 1000.0 if pts_inc > 0 else -pts_inc / 100000.0)
achunks = []
for ti, (kind, rate, ch, bits) in enumerate(tracks):
per = []
done = 0
for t in range(total):
n = int(round((t + 1) * seconds * rate)) - done
done += n
s = tone(n, ch, bits, rate, seed * 10 + ti * 100 + t, 440 + 110 * ti)
if kind == "packed":
per.append(pack_audio(s, ch, bits))
else:
per.append(b"".join(struct.pack("<h", v) if bits == 16 else bytes([v]) for v in s))
achunks.append(per)
data = []
flags = []
for t in range(total):
body = b""
fl = 0
if t == 0 or pals[t] != pals[t - 1]:
body += pal_chunk(pals[t], pals[t - 1] if t else None, t == 0)
fl |= 1
for ti in range(len(tracks)):
a = achunks[ti][t]
body += struct.pack("<I", 4 + len(a)) + a
fl |= 2 << ti
body += video[t]
body += bytes((-len(body)) % 4)
data.append(body)
flags.append(fl)
hd = b"SMK%d" % version + struct.pack("<IIIiI", w, h, nframes, pts_inc, 1 if ring else 0)
hd += struct.pack("<7I", *[max(len(a) for a in achunks[i]) if i < len(tracks) else 0 for i in range(7)])
hd += struct.pack("<I", len(treebytes)) + struct.pack("<4I", *sizes)
for i in range(7):
if i < len(tracks):
kind, rate, ch, bits = tracks[i]
f = 0x40 | (0x80 if kind == "packed" else 0) | (0x20 if bits == 16 else 0) | (0x10 if ch == 2 else 0)
hd += struct.pack("<I", rate | f << 24)
else:
hd += struct.pack("<I", 0)
hd += struct.pack("<I", 0)
hd += b"".join(struct.pack("<I", len(d) | (1 if t == 0 else 0)) for t, d in enumerate(data))
hd += bytes(flags)
return hd + treebytes + b"".join(data)
def generate(ctx):
tmp = tempfile.mkdtemp(prefix="smkfx_")
specs = [
("smk2_audio.smk", 2, 64, 48, 8, 100, [("packed", 22050, 2, 16), ("packed", 11025, 1, 8)], False, 1),
("smk4_ring.smk", 4, 96, 64, 9, -6667, [("raw", 16000, 1, 16), ("raw", 8000, 2, 8)], True, 2),
("smk4_mono.smk", 4, 64, 48, 6, 80, [("packed", 22050, 1, 16), ("packed", 11025, 2, 8)], False, 3),
("smk2_silent.smk", 2, 128, 64, 5, 66, [], False, 4),
]
cases = []
for name, ver, w, h, n, pts, tracks, ring, seed in specs:
data = smk_file(ver, w, h, n, pts, tracks, ring, seed)
path = os.path.join(tmp, name)
open(path, "wb").write(data)
raw = V.ffmpeg(["-i", path, "-map", "0:v:0", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "rgba", "-"])
sz = w * h * 4
crcs = [zlib.crc32(raw[i:i + sz]) & 0xffffffff for i in range(0, len(raw) - sz + 1, sz)]
assert len(crcs) == n + (1 if ring else 0), (name, len(crcs))
audio = []
for i, (kind, rate, ch, bits) in enumerate(tracks):
pcm = V.ffmpeg(["-i", path, "-map", "0:a:%d" % i, "-f", "f32le", "-"])
audio.append({"rate": rate, "channels": ch, "bits": bits,
"codec": "smackaudio" if kind == "packed" else ("pcm_s16le" if bits == 16 else "pcm_u8"),
"frames": len(pcm) // (4 * ch), "crc": zlib.crc32(pcm) & 0xffffffff})
rate = 1000 / pts if pts > 0 else 100000 / -pts
cases.append({"name": name, "data": data, "width": w, "height": h, "rate": rate, "frames": crcs, "audio": audio,
"ring": ring})
ctx.emit("smk_cases", cases)
# tools/bench.luau: a 320x200 SMK4 with 22.05 kHz packed stereo audio, 10 frames
ctx.emit("smk_bench", {"data": smk_file(4, 320, 200, 10, 100, [("packed", 22050, 2, 16)], False, 9, True), "width": 320,
"height": 200, "frames": 10})
+208
View File
@@ -0,0 +1,208 @@
# Theora fixtures for codecs/video/Theora and video/ogv (tools/fixtures.py): Ogg Theora files made by ffmpeg's
# libtheora encoder (testsrc2 / mandelbrot / static bars, several qualities and bit rates, odd sizes = picture regions
# smaller than the coded frame (the encoder keeps even sizes; two cases patch odd ones at offsets), 4:2:2 and 4:4:4, short and long keyframe intervals), one with an empty packet (a
# repeated frame) spliced in, an Ogg with Vorbis audio, and Theora in Matroska. The reference is ffmpeg's own decode
# (its vp3 decoder, bit-exact with libtheora): `-f framecrc` in the stream's native pixel format, one Adler-32 per
# frame over the packed planes of the picture region, with the frame's pts.
# tests/gen/theora_<name>.luau { name, width, height, pixfmt, file (base64 .ogv), frames = { { pts, adler } } }
# tests/gen/theora_dupe.luau the same, file with an empty packet after the 5th frame (frames: of the original)
# tests/gen/theora_av.luau { file (base64 .ogv with Vorbis), frames, pcm (f32le of ffmpeg's audio decode, base64),
# rate, channels }
# tests/gen/theora_opus.luau, theora_flac.luau the same with mono Opus / FLAC audio
# tests/gen/theora_mkv.luau { file (base64 .mkv), frames }
# tests/gen/theora_bench.luau { { name, file (base64 .ogv, 320x240), width, height } } for tools/bench.luau
import base64, os, shutil, struct, subprocess, tempfile, zlib
FF = ["-hide_banner", "-loglevel", "error", "-y"]
def b64(b):
return base64.b64encode(b).decode()
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: (input args, encoder args, pixel format)
CASES = {
"q6": (src("testsrc2", 320, 240, 25, 1.2), ["-q:v", "6", "-g", "12"], "yuv420p"),
"q0": (src("testsrc2", 176, 144, 25, 1), ["-q:v", "0", "-g", "30"], "yuv420p"),
"q10": (src("mandelbrot", 176, 144, 25, 0.6), ["-q:v", "10", "-g", "8"], "yuv420p"),
"motion": (src("mandelbrot", 240, 160, 30, 1.5), ["-b:v", "300k", "-g", "64"], "yuv420p"),
"odd": (src("testsrc2", 174, 98, 25, 1), ["-q:v", "5", "-g", "10"], "yuv420p"),
"static": (src("smptebars", 160, 120, 25, 1.2), ["-q:v", "4", "-g", "100"], "yuv420p"),
"yuv422": (src("testsrc2", 176, 144, 25, 1), ["-q:v", "6", "-g", "12"], "yuv422p"),
"yuv444": (src("mandelbrot", 144, 112, 25, 1), ["-q:v", "6", "-g", "12"], "yuv444p"),
"odd444": (src("testsrc2", 98, 62, 25, 0.6), ["-q:v", "7", "-g", "6"], "yuv444p"),
}
# ffmpeg's encoder writes even picture sizes at offset 0: these cases patch the identification header to an odd
# picture region at an offset (width, height, x, y from the bottom); the reference is ffmpeg's decode of the patched
# file (-flags unaligned: the exact crop)
PATCH = {
"crop": (src("testsrc2", 176, 112, 25, 0.6), ["-q:v", "6", "-g", "8"], "yuv420p", (171, 97, 3, 5)),
"crop422": (src("mandelbrot", 128, 96, 25, 0.6), ["-q:v", "6", "-g", "8"], "yuv422p", (117, 81, 5, 2)),
}
def crc32(b):
return zlib.crc32(b) & 0xFFFFFFFF
def ogg_pages(data):
"""yield (header fields, segment table, body) of each Ogg page"""
i = 0
while i + 27 <= len(data):
assert data[i:i + 4] == b"OggS"
flags, granule, serial, seq = data[i + 5], struct.unpack_from("<q", data, i + 6)[0], \
struct.unpack_from("<I", data, i + 14)[0], struct.unpack_from("<I", data, i + 18)[0]
n = data[i + 26]
segs = list(data[i + 27:i + 27 + n])
body = data[i + 27 + n:i + 27 + n + sum(segs)]
yield flags, granule, serial, seq, segs, body
i += 27 + n + sum(segs)
OGG_CRC = []
for _i in range(256):
r = _i << 24
for _ in range(8):
r = ((r << 1) ^ 0x04C11DB7) if r & 0x80000000 else (r << 1)
OGG_CRC.append(r & 0xFFFFFFFF)
def ogg_crc(b):
c = 0
for x in b:
c = ((c << 8) ^ OGG_CRC[((c >> 24) ^ x) & 0xFF]) & 0xFFFFFFFF
return c
def page(flags, granule, serial, seq, packets_segs, body):
head = b"OggS" + bytes([0, flags]) + struct.pack("<qII", granule, serial, seq) + b"\0\0\0\0" + \
bytes([len(packets_segs)]) + bytes(packets_segs)
p = bytearray(head + body)
struct.pack_into("<I", p, 22, ogg_crc(p))
return bytes(p)
def splice_empty(data, after):
"""rewrite a single-stream Ogg Theora file with one page per packet and an empty packet after data packet
`after` (1-based); granules are recomputed as frame counts since the last keyframe (bitstream 3.2.1 numbering)"""
packets, cur = [], b""
shift = None
for flags, granule, serial, seq, segs, body in ogg_pages(data):
o = 0
for s in segs:
cur += body[o:o + s]
o += s
if s < 255:
packets.append(cur)
cur = b""
sid = serial
shift = (packets[0][40] & 0x03) << 3 | packets[0][41] >> 5
out = []
seq = 0
frames = []
data_packets = packets[3:]
data_packets = data_packets[:after] + [b""] + data_packets[after:]
key = 0
for k, p in enumerate(packets[:3]):
segs = [255] * (len(p) // 255) + [len(p) % 255]
out.append(page(2 if k == 0 else 0, 0, sid, seq, segs, p))
seq += 1
for k, p in enumerate(data_packets):
n = k + 1
if len(p) > 0 and not (p[0] & 0x40):
key = n
segs = [255] * (len(p) // 255) + [len(p) % 255]
g = (key << shift) | (n - key)
out.append(page(4 if k == len(data_packets) - 1 else 0, g, sid, seq, segs, p))
seq += 1
return b"".join(out)
def patch_picture(data, w, h, x, y):
"""rewrite the first page (the identification header) with another picture region"""
out = bytearray(data)
n = out[26]
o = 27 + n # the packet starts here
assert out[o:o + 7] == b"\x80theora"
out[o + 14:o + 17] = w.to_bytes(3, "big")
out[o + 17:o + 20] = h.to_bytes(3, "big")
out[o + 20] = x
out[o + 21] = y
plen = 27 + n + sum(out[27:27 + n])
out[22:26] = b"\0\0\0\0"
struct.pack_into("<I", out, 22, ogg_crc(bytes(out[:plen])))
return bytes(out)
def generate(ctx):
ffmpeg = shutil.which("ffmpeg") or ctx.nix("ffmpeg-full", ["sh", "-c", "command -v ffmpeg"]).decode().strip()
def ff(args):
return subprocess.run([ffmpeg] + FF + args, check=True, capture_output=True).stdout
def framecrc(path, pixfmt, extra=None):
out = ff(["-flags", "unaligned", "-i", path] + (extra or []) + ["-map", "0:v", "-fps_mode", "passthrough", "-pix_fmt", pixfmt,
"-f", "framecrc", "-"]).decode()
frames = []
for line in out.splitlines():
if line.startswith("#"):
continue
parts = [x.strip() for x in line.split(",")]
frames.append([int(parts[1]), int(parts[5], 16)])
return frames
with tempfile.TemporaryDirectory(prefix="formats-theora-") as tmp:
for name, (inp, enc, pixfmt) in CASES.items():
path = os.path.join(tmp, name + ".ogv")
ff(inp + ["-pix_fmt", pixfmt, "-c:v", "libtheora"] + enc + [path])
data = open(path, "rb").read()
w, h = [int(x) for x in inp[3].split("=")[2].split(":")[0].split("x")]
ctx.emit("theora_" + name, {"name": name, "width": w, "height": h, "pixfmt": pixfmt, "file": b64(data),
"frames": framecrc(path, pixfmt)})
if name == "q6":
# an empty packet (a dropped / repeated frame) after the 5th frame
dupe = splice_empty(data, 5)
dpath = os.path.join(tmp, "dupe.ogv")
open(dpath, "wb").write(dupe)
ctx.emit("theora_dupe", {"name": "dupe", "width": w, "height": h, "pixfmt": pixfmt, "file": b64(dupe),
"frames": framecrc(path, pixfmt)})
for name, (inp, enc, pixfmt, (pw, ph, px, py)) in PATCH.items():
path = os.path.join(tmp, name + ".ogv")
ff(inp + ["-pix_fmt", pixfmt, "-c:v", "libtheora"] + enc + [path])
data = patch_picture(open(path, "rb").read(), pw, ph, px, py)
open(path, "wb").write(data)
ctx.emit("theora_" + name, {"name": name, "width": pw, "height": ph, "pixfmt": pixfmt, "file": b64(data),
"frames": framecrc(path, pixfmt)})
# Theora + Vorbis (stereo 44.1 kHz)
av = os.path.join(tmp, "av.ogv")
ff(src("testsrc2", 160, 120, 25, 1) + ["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100", "-t", "1",
"-ac", "2", "-c:v", "libtheora", "-q:v", "5", "-c:a", "libvorbis",
"-q:a", "3", "-shortest", av])
pcm = ff(["-i", av, "-map", "0:a", "-f", "f32le", "-"])
ctx.emit("theora_av", {"file": b64(open(av, "rb").read()), "frames": framecrc(av, "yuv420p"),
"width": 160, "height": 120, "pcm": b64(pcm), "rate": 44100, "channels": 2})
# Theora + Opus, Theora + FLAC (mono, 0.5 s)
for name, aenc, rate in (("opus", ["-c:a", "libopus", "-b:a", "48k"], 48000), ("flac", ["-c:a", "flac"], 22050)):
path = os.path.join(tmp, "a_" + name + ".ogv")
ff(src("testsrc2", 96, 64, 25, 0.5) + ["-f", "lavfi", "-i", "sine=frequency=330:sample_rate=%d" % rate,
"-t", "0.5", "-ac", "1", "-c:v", "libtheora", "-q:v", "4"] + aenc +
["-shortest", path])
pcm = ff(["-i", path, "-map", "0:a", "-f", "f32le", "-"])
ctx.emit("theora_" + name, {"file": b64(open(path, "rb").read()), "frames": framecrc(path, "yuv420p"),
"width": 96, "height": 64, "pcm": b64(pcm), "rate": rate, "channels": 1})
# Theora in Matroska (CodecPrivate: the three headers, Xiph-laced)
mkv = os.path.join(tmp, "t.mkv")
ff(["-i", os.path.join(tmp, "odd.ogv"), "-c", "copy", mkv])
ctx.emit("theora_mkv", {"file": b64(open(mkv, "rb").read()), "frames": framecrc(mkv, "yuv420p"),
"width": 174, "height": 98})
# the bench streams: an easy clip (testsrc2, mostly static) and a hard one (a mandelbrot zoom: every block moves)
bench = []
for kind, rate in (("testsrc2", "600k"), ("mandelbrot", "1200k")):
path = os.path.join(tmp, "bench_" + kind + ".ogv")
ff(src(kind, 320, 240, 25, 2) + ["-c:v", "libtheora", "-b:v", rate, "-g", "25", path])
bench.append({"name": kind, "file": b64(open(path, "rb").read()), "width": 320, "height": 240})
ctx.emit("theora_bench", bench)