From 1ed25296ba4741af475b9bbd74e36ae7f263fdce Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 13:53:23 -0500 Subject: [PATCH 01/27] ws-roblox: codecs/compress/Lz4 (LZ4 block decode + encode, decodeInto with history for linked blocks), tests vs python-lz4 both ways, bench line --- docs/FORMATS.md | 1 + src/Formats/codecs/compress/Lz4.luau | 291 +++++++++++++++++++++++++++ tests/codecs/lz4.luau | 101 ++++++++++ tools/bench.luau | 15 +- tools/fixtures/_lz4_encode.luau | 13 ++ tools/fixtures/lz4.py | 90 +++++++++ 6 files changed, 510 insertions(+), 1 deletion(-) create mode 100644 src/Formats/codecs/compress/Lz4.luau create mode 100644 tests/codecs/lz4.luau create mode 100644 tools/fixtures/_lz4_encode.luau create mode 100644 tools/fixtures/lz4.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0a41a66..2fe168c 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -103,6 +103,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/compress/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written - codecs/compress/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec - codecs/compress/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. + - codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md): decode and a greedy hash-chain-free encoder - codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3): - codecs/compress/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and - codecs/compress/PackBits: the Apple PackBits run-length code (TIFF compression 32773, PSD / PSB RLE channels, IFF diff --git a/src/Formats/codecs/compress/Lz4.luau b/src/Formats/codecs/compress/Lz4.luau new file mode 100644 index 0000000..80bc4b4 --- /dev/null +++ b/src/Formats/codecs/compress/Lz4.luau @@ -0,0 +1,291 @@ +--!strict +--!native +--!optimize 2 +-- codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md): decode and a greedy hash-chain-free encoder +-- (the reference "fast" strategy: one 4-byte hash table, 64 KB window). A codec (layer 3): model/rbxm chunk bodies, +-- and the LZ4 frame format (archive) builds on it. New code, written from the specification. Never throws. +-- +-- local out, err = Lz4.decompress(src, offset?, length?, outSize?, opts?) -- a block -> buffer | nil, Err +-- local packed = Lz4.compress(src, offset?, length?) -- -> buffer (a block) | nil, Err +-- local dEnd, msg = Lz4.decodeInto(src, p, limit, dst, d, dstLimit, histStart?) -- low level (linked blocks) +-- local n = Lz4.encodeInto(src, p, n, dst, d) -- low level; dst has bound(n) room +-- Lz4.bound(n) -- worst-case block size for n bytes +-- +-- decodeInto decodes one block from src[p, limit) to dst[d, dstLimit): matches may reach back to histStart (default +-- d), so a frame decoder with linked blocks keeps the previous output in front of d. It returns the output end, or +-- nil and a message ("truncated", "corrupt: ...", "limit: output ...") for the caller's Err.from. +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") + +local Lz4 = {} + +export type Options = { + maxBytes: number?, -- refuse output larger than this when outSize is not given (default 2^28) +} + +local readu8, writeu8, readu16, writeu16, readu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32 +local bcopy, bcreate, blen = buffer.copy, buffer.create, buffer.len +local band, rshift = bit32.band, bit32.rshift + +local MINMATCH = 4 +local LASTLITERALS = 5 -- the last 5 bytes are always literals +local MFLIMIT = 12 -- the last match starts at least 12 bytes before the end +local MAX_OFFSET = 65535 +local HASH_BITS = 13 +local HASH_SIZE = 2 ^ HASH_BITS + +-- ------------------------------------------------------------------------------------------------ decode +function Lz4.decodeInto(src: buffer, p: number, limit: number, dst: buffer, d: number, dstLimit: number, histStart: number?): (number?, string?) + local lo = histStart or d + if limit > blen(src) or dstLimit > blen(dst) or p < 0 or d < 0 or lo < 0 or lo > d then + return nil, "corrupt: bad ranges" + end + if p >= limit then + return nil, "truncated: empty block" + end + while true do + if p >= limit then + return nil, "truncated" + end + local token = readu8(src, p) + p += 1 + local lit = rshift(token, 4) + if lit == 15 then + local b = 255 + while b == 255 do + if p >= limit then + return nil, "truncated" + end + b = readu8(src, p) + p += 1 + lit += b + end + end + if lit > 0 then + if p + lit > limit then + return nil, "truncated: literals past the end" + end + if d + lit > dstLimit then + return nil, "limit: output larger than expected" + end + bcopy(dst, d, src, p, lit) + p += lit + d += lit + end + if p >= limit then + return d, nil -- the last sequence has no match + end + if p + 2 > limit then + return nil, "truncated" + end + local off = readu16(src, p) + p += 2 + if off == 0 or d - off < lo then + return nil, "corrupt: bad match offset" + end + local ml = band(token, 15) + if ml == 15 then + local b = 255 + while b == 255 do + if p >= limit then + return nil, "truncated" + end + b = readu8(src, p) + p += 1 + ml += b + end + end + ml += MINMATCH + if d + ml > dstLimit then + return nil, "limit: output larger than expected" + end + local s = d - off + if off >= ml then + bcopy(dst, d, dst, s, ml) + d += ml + elseif off == 1 then + buffer.fill(dst, d, readu8(dst, s), ml) + d += ml + else + -- an overlapping match repeats the off-byte pattern: copy what is already there, doubling each time + local n = ml + while n > 0 do + local c = d - s + if c > n then + c = n + end + bcopy(dst, d, dst, s, c) + d += c + n -= c + end + end + end +end + +-- decompress(src, offset?, length?, outSize?, opts?) -> buffer | nil, Err: one block. With outSize the output must be +-- exactly that long (CORRUPT otherwise); without it the output grows up to opts.maxBytes. +function Lz4.decompress(src: buffer | string, offset: number?, length: number?, outSize: number?, opts: Options?): (buffer?, Err.Err?) + local b, o, l, aerr = Bytes.span("Lz4.decompress", src, offset, length) + if not b then + return nil, aerr + end + if outSize ~= nil then + if type(outSize) ~= "number" or outSize < 0 or outSize % 1 ~= 0 then + return nil, Err.new(Err.ARG, "Lz4.decompress: bad outSize") + end + local out = bcreate(outSize) + local e, msg = Lz4.decodeInto(b, o, o + l, out, 0, outSize) + if not e then + return nil, Err.from(msg, o) + end + if e ~= outSize then + return nil, Err.new(Err.CORRUPT, string.format("block decodes to %d bytes, expected %d", e, outSize), o) + end + return out, nil + end + local max = (opts and opts.maxBytes) or 2 ^ 28 + local size = math.min(math.max(l * 4, 256), max) + while true do + local out = bcreate(size) + local e, msg = Lz4.decodeInto(b, o, o + l, out, 0, size) + if e then + local res = bcreate(e) + bcopy(res, 0, out, 0, e) + return res, nil + end + if not (msg and string.sub(msg, 1, 6) == "limit:") then + return nil, Err.from(msg, o) + end + if size >= max then + return nil, Err.new(Err.LIMIT, "output over " .. max .. " bytes", o) + end + size = math.min(size * 4, max) + end +end + +-- ------------------------------------------------------------------------------------------------ encode +-- bound(n) -> the largest block n input bytes can produce +function Lz4.bound(n: number): number + return n + n // 255 + 16 +end + +-- writes a length's 255-run extension at o; returns the next offset +local function extend(dst: buffer, o: number, n: number): number + while n >= 255 do + writeu8(dst, o, 255) + o += 1 + n -= 255 + end + writeu8(dst, o, n) + return o + 1 +end + +-- hash(v) -> 1 .. HASH_SIZE: Knuth's multiplicative hash (v * 2654435761 mod 2^32, top bits), exact in doubles +local function hash(v: number): number + local vl, vh = band(v, 0xFFFF), rshift(v, 16) + local mid = (vh * 0x79B1 + vl * 0x9E37) % 65536 + return ((vl * 0x79B1 + mid * 65536) % 4294967296) // (2 ^ (32 - HASH_BITS)) + 1 +end + +local hashTable: { number } = table.create(HASH_SIZE, -1e9) + +-- encodeInto(src, p, n, dst, d) -> the block's length: src[p, p + n) compressed to dst[d ..] (room for bound(n)) +function Lz4.encodeInto(src: buffer, p: number, n: number, dst: buffer, d: number): number + local op = d + local anchor = p + local iend = p + n + local ht = hashTable + for i = 1, HASH_SIZE do + ht[i] = -1e9 + end + if n >= MFLIMIT + 1 then + local mflimit = iend - MFLIMIT -- a match starts before this + local matchEnd = iend - LASTLITERALS -- and ends at or before this + local ip = p + local skip = 64 + while ip < mflimit do + local v = readu32(src, ip) + local h = hash(v) + local ref = ht[h] + ht[h] = ip + if ref >= p and ip - ref <= MAX_OFFSET and readu32(src, ref) == v then + -- back over equal bytes before the match (into the pending literals) + while ip > anchor and ref > p and readu8(src, ip - 1) == readu8(src, ref - 1) do + ip -= 1 + ref -= 1 + end + local a = ip + MINMATCH + local bpos = ref + MINMATCH + while a + 4 <= matchEnd and readu32(src, a) == readu32(src, bpos) do + a += 4 + bpos += 4 + end + while a < matchEnd and readu8(src, a) == readu8(src, bpos) do + a += 1 + bpos += 1 + end + local ml = a - ip + local lit = ip - anchor + local tok = op + op += 1 + local tl = if lit >= 15 then 15 else lit + if lit >= 15 then + op = extend(dst, op, lit - 15) + end + if lit > 0 then + bcopy(dst, op, src, anchor, lit) + op += lit + end + writeu16(dst, op, ip - ref) + op += 2 + local m = ml - MINMATCH + local tm = if m >= 15 then 15 else m + if m >= 15 then + op = extend(dst, op, m - 15) + end + writeu8(dst, tok, tl * 16 + tm) + ip = a + anchor = ip + skip = 64 + -- index the position just before the next one (better ratio at no cost) + if ip - 2 >= p and ip - 2 < mflimit then + local w = readu32(src, ip - 2) + ht[hash(w)] = ip - 2 + end + else + ip += rshift(skip, 6) -- step up over incompressible data (the reference's acceleration) + skip += 1 + end + end + end + -- the last literals + local lit = iend - anchor + local tok = op + op += 1 + if lit >= 15 then + op = extend(dst, op, lit - 15) + writeu8(dst, tok, 0xF0) + else + writeu8(dst, tok, lit * 16) + end + if lit > 0 then + bcopy(dst, op, src, anchor, lit) + op += lit + end + return op - d +end + +-- compress(src, offset?, length?) -> buffer (one block) | nil, Err +function Lz4.compress(src: buffer | string, offset: number?, length: number?): (buffer?, Err.Err?) + local b, o, l, aerr = Bytes.span("Lz4.compress", src, offset, length) + if not b then + return nil, aerr + end + local tmp = bcreate(Lz4.bound(l)) + local n = Lz4.encodeInto(b, o, l, tmp, 0) + local out = bcreate(n) + bcopy(out, 0, tmp, 0, n) + return out, nil +end + +return Lz4 diff --git a/tests/codecs/lz4.luau b/tests/codecs/lz4.luau new file mode 100644 index 0000000..3d5f859 --- /dev/null +++ b/tests/codecs/lz4.luau @@ -0,0 +1,101 @@ +-- codecs/compress/Lz4 tests: every reference block (python-lz4 fast at accelerations 1 / 4 / 16, HC 4 / 9 / 12) +-- decodes to its corpus, with and without the size; our encoder's blocks decode with the reference (fixture verdicts) +-- and round trip here; linked blocks through decodeInto's history; error codes; truncated / mutated / random blocks +-- never throw. Fixtures: tools/fixtures/lz4.py. +local T = require("@tests/T") +local Lz4 = require("@formats/codecs/compress/Lz4") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/lz4") +local C = require("@tests/gen/lz4_corpora") + +local t = T.suite("lz4") + +local nbytes = 0 +for _, c in Fx.cases do + local want = C[c.corpus] + local out, err = Lz4.decompress(c.data, nil, nil, #want) + t:check(out ~= nil and buffer.tostring(out) == want, c.name .. ": " .. tostring(err)) + if #want > 0 then + local grown = Lz4.decompress(c.data) + t:check(grown ~= nil and buffer.tostring(grown) == want, c.name .. ": without the size") + end + nbytes += #want +end +t:note("%d reference blocks, %.1f MB decoded", #Fx.cases, nbytes / 1e6) + +for _, v in Fx.ours do + t:check(v.ok, v.name .. ": the reference decodes our block") +end +for name, data in C do + local b = Lz4.compress(data) :: buffer + local back = Lz4.decompress(b, nil, nil, #data) + t:check(back ~= nil and buffer.tostring(back) == data, name .. ": round trip") + if name == "text" or name == "zeros" or name == "runs" then + t:check(buffer.len(b) < #data / 2, name .. ": compresses") + end + t:check(buffer.len(b) <= Lz4.bound(#data), name .. ": within bound") +end + +-- at an offset, and linked blocks: the second block refers into the first one's output +do + local text = C.text + local a, b2 = string.sub(text, 1, 70000), string.sub(text, 70001, 140000) + local pa = Lz4.compress(a) :: buffer + -- a block of b2 that copies the first 40 bytes of b2's region from a (a match reaching back across blocks) + local big = buffer.create(buffer.len(pa) + 20) + buffer.copy(big, 9, pa) + local out = Lz4.decompress(big, 9, buffer.len(pa), #a) + t:check(out ~= nil and buffer.tostring(out) == a, "at an offset") + local hand = buffer.create(3 + 1 + 2 + 1) + -- token: 0 literals, match length 15 + ext; offset = 100 back into the previous block + buffer.writeu8(hand, 0, 0x0F) + buffer.writeu16(hand, 1, 100) + buffer.writeu8(hand, 3, 20) -- match length 4 + 15 + 20 = 39 + buffer.writeu8(hand, 4, 0x10) -- the last sequence: one literal + buffer.writeu8(hand, 5, 33) + local dst = buffer.create(#a + 40) + buffer.writestring(dst, 0, a) + local e, msg = Lz4.decodeInto(hand, 0, 6, dst, #a, #a + 40, 0) + t:check(e == #a + 40, "linked block: " .. tostring(msg)) + t:eq(buffer.readstring(dst, #a, 39), string.sub(a, #a - 99, #a - 61), "linked block: match from the history") + local e2, msg2 = Lz4.decodeInto(hand, 0, 6, dst, #a, #a + 40) + t:check(e2 == nil and string.find(msg2 or "", "offset") ~= nil, "without history the match is corrupt") + t:check(b2 ~= nil, "second half") +end + +-- errors +do + local _, e1 = Lz4.decompress("") + t:check(e1 and e1.code == Err.TRUNCATED, "empty: " .. tostring(e1)) + local _, e2 = Lz4.decompress("\x50ab") + t:check(e2 and e2.code == Err.TRUNCATED, "literals past the end: " .. tostring(e2)) + local _, e3 = Lz4.decompress("\x14abcd\x09\x00\x10z") + t:check(e3 and e3.code == Err.CORRUPT, "offset before the start: " .. tostring(e3)) + local _, e4 = Lz4.decompress("\x10a", nil, nil, 5) + t:check(e4 and e4.code == Err.CORRUPT, "shorter than outSize: " .. tostring(e4)) + local _, e5 = Lz4.decompress("\x50abcde", nil, nil, 2) + t:check(e5 and e5.code == Err.LIMIT, "longer than outSize: " .. tostring(e5)) + local _, e6 = Lz4.decompress(C.zeros and (Lz4.compress(C.zeros) :: buffer), nil, nil, nil, { maxBytes = 1000 }) + t:check(e6 and e6.code == Err.LIMIT, "maxBytes: " .. tostring(e6)) + local ok, r1, r2 = pcall(Lz4.decompress, 5 :: any) + t:check(ok and r1 == nil and r2.code == Err.ARG, "a non-buffer argument returns Err.ARG") + local _, e7 = Lz4.decompress("\x10a", nil, nil, -1) + t:check(e7 and e7.code == Err.ARG, "bad outSize") +end + +do + local samples = {} + for i, c in Fx.cases do + if i % 4 == 0 and #c.data > 8 and #c.data < 30000 then + table.insert(samples, c.data) + end + end + t:fuzz("decompress", function(b: buffer) + return Lz4.decompress(b, nil, nil, nil, { maxBytes = 1e6 }) + end, samples, { mutations = 30, garbage = 2000 }) + t:fuzz("decompress (sized)", function(b: buffer) + return Lz4.decompress(b, nil, nil, 70000) + end, samples, { mutations = 30, garbage = 500, seed = 5 }) +end + +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index b32ee01..e7d1364 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -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,19 @@ 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 do local Brotli = require("@formats/codecs/compress/Brotli") local BB = require("@tests/gen/brotli_bench") diff --git a/tools/fixtures/_lz4_encode.luau b/tools/fixtures/_lz4_encode.luau new file mode 100644 index 0000000..7f1febb --- /dev/null +++ b/tools/fixtures/_lz4_encode.luau @@ -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 " " 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 diff --git a/tools/fixtures/lz4.py b/tools/fixtures/lz4.py new file mode 100644 index 0000000..b60ba53 --- /dev/null +++ b/tools/fixtures/lz4.py @@ -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)}) From 7b4bf1ee4345365560598c0c67df86cb4595a383 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:02:01 -0500 Subject: [PATCH 02/27] containers: video track palettes and depths for the legacy codecs Small backward-compatible additions so palettised codecs find their colour table on the Track: - containers/Avi: Avi.bitmapInfo(strf) (BITMAPINFOHEADER facts + palette as 256 RGBA u32); video/avi sets track.palette for 1..8-bit streams. - containers/IsoBmff/QtPalette (new): QuickTime sample description depth + colour table (stsd table, Mac default tables, grey ramps); IsoBmff Demux sets track.bitsPerPixel / track.palette, video/mp4 copies them. - video/mkv: V_MS/VFW/FOURCC (BITMAPINFOHEADER) and V_QUICKTIME (sample description) CodecPrivate map to the FourCC's codec with depth / palette. --- src/Formats/Registry.luau | 2 +- src/Formats/containers/Avi/init.luau | 47 ++++++++ src/Formats/containers/IsoBmff/Demux.luau | 14 +++ src/Formats/containers/IsoBmff/QtPalette.luau | 113 ++++++++++++++++++ src/Formats/video/avi/init.luau | 4 + src/Formats/video/mkv/Parse.luau | 38 ++++++ src/Formats/video/mkv/init.luau | 2 +- src/Formats/video/mp4/init.luau | 2 + 8 files changed, 220 insertions(+), 2 deletions(-) create mode 100644 src/Formats/containers/IsoBmff/QtPalette.luau diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6c0344c..288846f 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -308,7 +308,7 @@ local list: { Entry } = { path = "video/mkv", extensions = { "mkv", "webm", "mka", "mk3d" }, mime = { "video/x-matroska", "video/webm", "audio/x-matroska", "audio/webm" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "containers/Avi", "containers/IsoBmff/QtPalette", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" }, caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "rawvideo" }, audio = true, subtitles = true }, load = function() return require("@formats/video/mkv") diff --git a/src/Formats/containers/Avi/init.luau b/src/Formats/containers/Avi/init.luau index 081e9b9..9d89f18 100644 --- a/src/Formats/containers/Avi/init.luau +++ b/src/Formats/containers/Avi/init.luau @@ -9,6 +9,7 @@ -- avi.streams[i] = { type = "vids" | "auds" | ..., handler, scale, rate, start, length, sampleSize, strf -- (buffer), name, chunks = { { offset, size, key } } } -- offsets of the chunk data, absolute -- local w = Avi.writer({ streams = {...}, avih = {...} }); w:chunk(streamIndex, data, key); local file = w:finish() +-- local bi = Avi.bitmapInfo(strf) -- a BITMAPINFOHEADER: size, depth, FourCC, palette (also Matroska VFW) -- -- Never throws: malformed data returns nil, Err (a damaged index falls back to scanning). local Err = require("@formats/core/Err") @@ -520,4 +521,50 @@ function Avi.write(opts: WOptions, chunks: { { any } }): buffer return w:finish() end +-- ------------------------------------------------------------------------------------------------ BITMAPINFO +export type BitmapInfo = { + width: number, + height: number, -- signed: > 0 = bottom-up rows + bits: number, -- biBitCount + compression: string, -- biCompression as a FourCC ("\0\0\0\0" = BI_RGB) + palette: buffer?, -- bits <= 8: 256 u32 entries, bytes R, G, B, 0xFF (codecs/image/Pixels layout); unused ones 0 + extra: buffer?, -- the bytes after the 40-byte header (palette included), nil when none +} + +-- bitmapInfo(f) -> the BITMAPINFOHEADER facts of an AVI video strf (or a Matroska V_MS/VFW/FOURCC CodecPrivate) | +-- nil when shorter than 40 bytes. The palette is the last (2^bits) * 4 bytes after the header (B, G, R, x entries; +-- a trailing "BottomUp" tag is skipped), as the VfW codecs store it. +function Avi.bitmapInfo(f: buffer): BitmapInfo? + local n = buffer.len(f) + if n < 40 then + return nil + end + local bits = readu16(f, 14) + local info: BitmapInfo = { + width = buffer.readi32(f, 4), + height = buffer.readi32(f, 8), + bits = bits, + compression = readstring(f, 16, 4), + } + if n > 40 then + local e = buffer.create(n - 40) + buffer.copy(e, 0, f, 40) + info.extra = e + if bits >= 1 and bits <= 8 then + local count = math.min(2 ^ bits, (n - 40) // 4) + local at = n - count * 4 + if at - 40 >= 9 and readstring(f, n - 9, 9) == "BottomUp\0" then + at -= 9 + end + local pal = buffer.create(1024) + for i = 0, count - 1 do + local o = at + i * 4 + buffer.writeu32(pal, i * 4, readu8(f, o + 2) + readu8(f, o + 1) * 256 + readu8(f, o) * 65536 + 0xFF000000) + end + info.palette = pal + end + end + return info +end + return Avi diff --git a/src/Formats/containers/IsoBmff/Demux.luau b/src/Formats/containers/IsoBmff/Demux.luau index 7f8689d..d44c566 100644 --- a/src/Formats/containers/IsoBmff/Demux.luau +++ b/src/Formats/containers/IsoBmff/Demux.luau @@ -8,9 +8,14 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Box = require("@formats/containers/IsoBmff/Box") +local QtPalette = require("@formats/containers/IsoBmff/QtPalette") local readstring = buffer.readstring +local function readu16be(b: buffer, o: number): number + return buffer.readu8(b, o) * 256 + buffer.readu8(b, o + 1) +end + local Demux = {} export type Edit = { duration: number, mediaTime: number, rate: number } -- duration in movie ticks, mediaTime in media ticks (-1 = empty) @@ -33,6 +38,8 @@ export type Track = { channels: number?, bitsPerSample: number?, config: buffer?, -- codec configuration (AudioSpecificConfig, ALAC cookie, dOps, avcC, ...) + bitsPerPixel: number?, -- video: the sample description's depth (24, 32, 40 = 8-bit grey, ...) + palette: buffer?, -- video, 1..8-bit depths: 256 u32 entries (bytes R, G, B, 0xFF) objectType: number?, -- esds objectTypeIndication pcm: { bits: number, float: boolean, little: boolean }?, entryBoxes: { Box.Box }, -- the sample entry's child boxes (esds, btrt, colr, pasp, ...) @@ -194,6 +201,13 @@ local function sampleEntry(b: buffer, e: Box.Box, handler: string, t: Track) t.height = r:u16be() r:skip(4 + 4 + 4 + 2 + 32 + 2 + 2) childStart = r.pos + -- QuickTime depth and colour table (palettised codecs: QuickTime RLE / SMC, Cinepak, ...) + local depth, pal = QtPalette.read(b, e.start, e.stop, if typ == "cvid" then "cinepak" else typ) + t.bitsPerPixel = depth + t.palette = pal + if pal and not r.err and readu16be(b, childStart - 2) == 0 and childStart + 8 <= e.stop then + childStart = math.min(e.stop, childStart + 8 + (readu16be(b, childStart + 6) + 1) * 8) + end else childStart = r.pos end diff --git a/src/Formats/containers/IsoBmff/QtPalette.luau b/src/Formats/containers/IsoBmff/QtPalette.luau new file mode 100644 index 0000000..2034dc3 --- /dev/null +++ b/src/Formats/containers/IsoBmff/QtPalette.luau @@ -0,0 +1,113 @@ +--!strict +-- containers/IsoBmff/QtPalette: the depth and colour table of a QuickTime video sample description (Apple QuickTime +-- File Format, "Video sample description": depth at byte 82, color table ID at 84, then the table when the ID is 0). +-- Used by the MOV demuxer and by Matroska's V_QUICKTIME tracks (whose CodecPrivate is the same description). Depths 1, +-- 2, 4 and 8 are palettised: the colour table from the description, the Macintosh default table (ID -1), or a grey +-- ramp (depths 33..40: the 0x20 bit marks grey). Written from the QuickTime documentation; the default tables are the +-- Macintosh system palettes (white first, a 6x6x6 cube, then red / green / blue / grey ramps). +-- +-- local depth, palette = QtPalette.read(buf, entryStart, entryStop, codec) +-- -- depth: the stored depth (24, 32, 40, ...), palette: 256 u32 entries (bytes R, G, B, 0xFF) | nil +-- +-- Never throws. +local readu8, readu16, readu32, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32 + +local QtPalette = {} + +local function rgb(r: number, g: number, b: number): number + return r + g * 256 + b * 65536 + 0xFF000000 +end + +-- the Macintosh default colour tables: 2 / 4 / 16 entries (System 7 control panel), 256 (the system palette) +local SMALL: { [number]: { number } } = { + [1] = { 0xFFFFFF, 0x000000 }, + [2] = { 0xFFFFFF, 0xACACAC, 0x555555, 0x000000 }, + [4] = { + 0xFFFFFF, 0xFCF305, 0xFF6402, 0xDD0806, 0xF20884, 0x4600A5, 0x0000D4, 0x02ABEA, + 0x1FB714, 0x006411, 0x562C05, 0x90713A, 0xC0C0C0, 0x808080, 0x404040, 0x000000, + }, +} + +local function defaultTable(bits: number): buffer + local pal = buffer.create(1024) + local small = SMALL[bits] + if small then + for i, c in small do + writeu32(pal, (i - 1) * 4, rgb(c // 65536, (c // 256) % 256, c % 256)) + end + return pal + end + local i = 0 + for r = 5, 0, -1 do + for g = 5, 0, -1 do + for b = 5, 0, -1 do + if i < 215 then + writeu32(pal, i * 4, rgb(r * 51, g * 51, b * 51)) + end + i += 1 + end + end + end + -- ramps without the cube's multiples of 0x33: red, green, blue, grey; then black + local RAMP = { 0xEE, 0xDD, 0xBB, 0xAA, 0x88, 0x77, 0x55, 0x44, 0x22, 0x11 } + i = 215 + for ch = 0, 3 do + for _, v in RAMP do + local r = if ch == 0 or ch == 3 then v else 0 + local g = if ch == 1 or ch == 3 then v else 0 + local b = if ch == 2 or ch == 3 then v else 0 + writeu32(pal, i * 4, rgb(r, g, b)) + i += 1 + end + end + writeu32(pal, 255 * 4, rgb(0, 0, 0)) + return pal +end + +-- read(buf, start, stop, codec?) -> depth, palette | nil: start = the offset of the sample description (its size +-- field), stop = its end. Cinepak's grey flag selects its own grey mode, so no grey palette is made for it. +function QtPalette.read(b: buffer, start: number, stop: number, codec: string?): (number?, buffer?) + if start + 86 > stop or stop > buffer.len(b) then + return nil, nil + end + local raw = readu16(b, start + 82) + local id = readu16(b, start + 84) + local bits = raw % 32 + local grey = raw >= 32 and (raw // 32) % 2 == 1 + if bits ~= 1 and bits ~= 2 and bits ~= 4 and bits ~= 8 then + return raw, nil + end + if grey and codec == "cinepak" then + return raw, nil + end + if grey and bits > 1 and id ~= 0 then + local pal = buffer.create(1024) + local count = 2 ^ bits + local step = 256 // (count - 1) + local v = 255 + for i = 0, count - 1 do + writeu32(pal, i * 4, rgb(v, v, v)) + v = math.max(0, v - step) + end + return bits, pal + elseif id ~= 0 then + return bits, defaultTable(bits) + end + local pal = buffer.create(1024) + if start + 94 <= stop then + local first = readu32(b, start + 86) + local last = readu16(b, start + 92) + if first <= 255 and last <= 255 then + for i = first, last do + local o = start + 94 + (i - first) * 8 + if o + 8 > stop then + break + end + writeu32(pal, i * 4, rgb(readu8(b, o + 2), readu8(b, o + 4), readu8(b, o + 6))) + end + end + end + return bits, pal +end + +return QtPalette diff --git a/src/Formats/video/avi/init.luau b/src/Formats/video/avi/init.luau index fc46a32..3c5d919 100644 --- a/src/Formats/video/avi/init.luau +++ b/src/Formats/video/avi/init.luau @@ -110,6 +110,10 @@ local function videoTrack(s: Avi.Stream, id: number): Types.Track t.pixelFormat = "yuv420p" end end + local bi = Avi.bitmapInfo(f) + if bi and bi.palette then + t.palette = bi.palette -- 1..8-bit codecs (Microsoft Video 1, Cinepak, QuickTime RLE / SMC in AVI, ...) + end local size = buffer.readu32(f, 0) if size > 40 and buffer.len(f) > 40 then local c = buffer.create(buffer.len(f) - 40) diff --git a/src/Formats/video/mkv/Parse.luau b/src/Formats/video/mkv/Parse.luau index fd07900..252a004 100644 --- a/src/Formats/video/mkv/Parse.luau +++ b/src/Formats/video/mkv/Parse.luau @@ -9,6 +9,8 @@ local Types = require("@formats/Types") local Ebml = require("@formats/containers/Ebml") local Demux = require("@formats/containers/Demux") local Video = require("@formats/codecs/video/Video") +local Avi = require("@formats/containers/Avi") +local QtPalette = require("@formats/containers/IsoBmff/QtPalette") local Deflate = require("@formats/codecs/compress/Deflate") local Parse = {} @@ -152,6 +154,39 @@ local function codecFor(id: string, kind: string, bits: number?): string end Parse.codecFor = codecFor +-- V_MS/VFW/FOURCC (CodecPrivate = a BITMAPINFOHEADER) and V_QUICKTIME (CodecPrivate = a QuickTime sample +-- description, sometimes without its size field): the codec from the FourCC, the depth and palette, the extradata +local function vfwOrQuickTime(t: any, codecId: string, priv: buffer) + local n = buffer.len(priv) + if codecId == "V_MS/VFW/FOURCC" then + local bi = Avi.bitmapInfo(priv) + if bi then + t.codec = Video.fromFourcc(bi.compression) or t.codec + t.codecTag = bi.compression + t.bitsPerPixel = bi.bits + t.palette = bi.palette + t.config = bi.extra + end + elseif codecId == "V_QUICKTIME" and n >= 21 then + local desc = priv + if Video.fromFourcc(buffer.readstring(priv, 0, 4)) then + desc = buffer.create(n + 4) + local size = n + 4 + buffer.writeu8(desc, 0, size // 16777216 % 256) + buffer.writeu8(desc, 1, size // 65536 % 256) + buffer.writeu8(desc, 2, size // 256 % 256) + buffer.writeu8(desc, 3, size % 256) + buffer.copy(desc, 4, priv, 0, n) + end + local fcc = buffer.readstring(desc, 4, 4) + t.codec = Video.fromFourcc(fcc) or t.codec + t.codecTag = fcc + local depth, pal = QtPalette.read(desc, 0, buffer.len(desc), t.codec) + t.bitsPerPixel = depth + t.palette = pal + end +end + type TrackInfo = Types.Track & { strip: buffer?, lacing: boolean?, defaultDurationNs: number? } local function parseVideo(buf: buffer, off: number, len: number, t: any) @@ -278,6 +313,9 @@ local function parseTracks(buf: buffer, off: number, len: number, scaleNs: numbe t.kind = if ttype == 1 then "video" elseif ttype == 2 then "audio" elseif ttype == 17 then "subtitle" else "data" t.codecTag = codecId t.codec = codecFor(codecId, t.kind, t.bitsPerSample) + if t.kind == "video" and t.config then + vfwOrQuickTime(t, codecId, t.config) + end if t.kind == "audio" then t.sampleRate = t.sampleRate or 8000 t.channels = t.channels or 1 diff --git a/src/Formats/video/mkv/init.luau b/src/Formats/video/mkv/init.luau index 1a94272..b8a22a5 100644 --- a/src/Formats/video/mkv/init.luau +++ b/src/Formats/video/mkv/init.luau @@ -27,7 +27,7 @@ local Mkv = { category = "video", extensions = { "mkv", "webm", "mka", "mk3d" }, mime = { "video/x-matroska", "video/webm", "audio/x-matroska", "audio/webm" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "containers/Avi", "containers/IsoBmff/QtPalette", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" }, caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "rawvideo" }, audio = true, subtitles = true }, } diff --git a/src/Formats/video/mp4/init.luau b/src/Formats/video/mp4/init.luau index 0dcf3e8..f4d8217 100644 --- a/src/Formats/video/mp4/init.luau +++ b/src/Formats/video/mp4/init.luau @@ -133,6 +133,8 @@ function Mp4.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) bitsPerSample = it.bitsPerSample, config = it.config, default = true, + bitsPerPixel = it.bitsPerPixel, + palette = it.palette, } if it.kind == "video" then if not Video.entry(t.codec) then From 998177e5ab7f83d97ac9fb37f452e4a01d37f7b1 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:12:46 -0500 Subject: [PATCH 03/27] ws-voxel: codecs/text/Nbt (NBT Java / Bedrock / network varint, SNBT parse + print, typed values), data/nbt, data/snbt Shared change: codecs/compress/Deflate gains Deflate.peek(buf, off, len, n) (the first n inflated bytes of a gzip / zlib / raw stream, for sniffing gzip-wrapped NBT) through a backward-compatible prefix flag on Inflate.raw; gunzip's header parsing moved into a local helper both use. --- docs/FORMATS.md | 3 + src/Formats/Registry.luau | 24 + .../codecs/compress/Deflate/Inflate.luau | 14 +- src/Formats/codecs/compress/Deflate/init.luau | 90 ++- src/Formats/codecs/text/Nbt/Binary.luau | 698 ++++++++++++++++++ src/Formats/codecs/text/Nbt/Snbt.luau | 649 ++++++++++++++++ src/Formats/codecs/text/Nbt/Value.luau | 256 +++++++ src/Formats/codecs/text/Nbt/init.luau | 380 ++++++++++ src/Formats/data/nbt/init.luau | 60 ++ src/Formats/data/snbt/init.luau | 63 ++ tests/codecs/deflate.luau | 19 + tests/codecs/nbt.luau | 256 +++++++ tests/data/nbt.luau | 60 ++ tests/data/snbt.luau | 47 ++ tools/fixtures/nbt.py | 152 ++++ 15 files changed, 2745 insertions(+), 26 deletions(-) create mode 100644 src/Formats/codecs/text/Nbt/Binary.luau create mode 100644 src/Formats/codecs/text/Nbt/Snbt.luau create mode 100644 src/Formats/codecs/text/Nbt/Value.luau create mode 100644 src/Formats/codecs/text/Nbt/init.luau create mode 100644 src/Formats/data/nbt/init.luau create mode 100644 src/Formats/data/snbt/init.luau create mode 100644 tests/codecs/nbt.luau create mode 100644 tests/data/nbt.luau create mode 100644 tests/data/snbt.luau create mode 100644 tools/fixtures/nbt.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0a41a66..51b3d3b 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -62,7 +62,9 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | data | ini | .ini .cfg .conf .inf .desktop | yes | yes | ordered: true | `tests/data/ini.luau` | | data | json | .json .jsonl .ndjson .geojson | yes | yes | ordered: true, streaming: true | `tests/data/json.luau` | | data | msgpack | .msgpack .mpk | yes | yes | binary: true, ordered: true | `tests/data/msgpack.luau` | +| data | nbt | .nbt .dat .mcstructure .dat_old | yes | yes | binary: true, ordered: true, typed: true | `tests/data/nbt.luau` | | data | plist | .plist | yes | yes | binary: "read", ordered: true | `tests/data/plist.luau` | +| data | snbt | .snbt | yes | yes | ordered: true, typed: true | `tests/data/snbt.luau` | | data | toml | .toml | yes | yes | ordered: true, dates: true | `tests/data/toml.luau` | | data | xml | .xml .xsd .xsl .xslt .rss .atom .xhtml | yes | yes | namespaces: true, streaming: true | `tests/data/xml.luau` | | data | yaml | .yaml .yml | yes | yes | ordered: true, multiDocument: true, anchors: true | `tests/data/yaml.luau` | @@ -128,6 +130,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks - **text** - codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. + - codecs/text/Nbt: Minecraft's Named Binary Tag format and its text form SNBT, the engine data/nbt, data/snbt, - codecs/text/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is - codecs/text/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL, - codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ... diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6c0344c..b7c814e 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -698,6 +698,18 @@ local list: { Entry } = { return require("@formats/data/msgpack") end, }, + { + name = "nbt", + category = "data", + path = "data/nbt", + extensions = { "nbt", "dat", "mcstructure", "dat_old" }, + mime = { "application/x-minecraft-nbt" }, + deps = { "core/Err", "core/Bytes", "codecs/text/Nbt" }, + caps = { decode = true, encode = true, binary = true, ordered = true, typed = true }, + load = function() + return require("@formats/data/nbt") + end, + }, { name = "plist", category = "data", @@ -710,6 +722,18 @@ local list: { Entry } = { return require("@formats/data/plist") end, }, + { + name = "snbt", + category = "data", + path = "data/snbt", + extensions = { "snbt" }, + mime = { "text/x-minecraft-snbt" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "codecs/text/Nbt" }, + caps = { decode = true, encode = true, ordered = true, typed = true }, + load = function() + return require("@formats/data/snbt") + end, + }, { name = "toml", category = "data", diff --git a/src/Formats/codecs/compress/Deflate/Inflate.luau b/src/Formats/codecs/compress/Deflate/Inflate.luau index 449e1db..456464f 100644 --- a/src/Formats/codecs/compress/Deflate/Inflate.luau +++ b/src/Formats/codecs/compress/Deflate/Inflate.luau @@ -62,9 +62,10 @@ local function grow(out: buffer, op: number, need: number): (buffer, number) end -- Inflate src[start, endpos) into a buffer. cap: initial output capacity; exact: true = the output must fit in --- cap bytes (an error otherwise), false = grow as needed. +-- cap bytes (an error otherwise), false = grow as needed. prefix (with exact): stop at cap instead of failing and +-- return what was inflated so far (at most cap bytes; Deflate.peek, for sniffing). -- Returns out, outLen, consumedEnd (the input offset just past the final block) or nil, message. -function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean): (buffer?, any, number?) +function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean, prefix: boolean?): (buffer?, any, number?) local out = bcreate(cap) local op = 0 local pos = start @@ -123,6 +124,9 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex end if op + n > cap then if exact then + if prefix then + return out, op, pos + end return nil, "output larger than expected" end out, cap = grow(out, op, op + n) @@ -295,6 +299,9 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex if sym < 256 then if op >= cap then if exact then + if prefix then + return out, op, pos + end return nil, "output larger than expected" end out, cap = grow(out, op, op + 1) @@ -388,6 +395,9 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex end if op + len > cap then if exact then + if prefix then + return out, op, pos + end return nil, "output larger than expected" end out, cap = grow(out, op, op + len) diff --git a/src/Formats/codecs/compress/Deflate/init.luau b/src/Formats/codecs/compress/Deflate/init.luau index 37a529b..fd25c71 100644 --- a/src/Formats/codecs/compress/Deflate/init.luau +++ b/src/Formats/codecs/compress/Deflate/init.luau @@ -9,6 +9,7 @@ -- local out, err = Deflate.zlib(buf) -- checks the Adler-32 -- local out, err = Deflate.gunzip(buf) -- checks CRC-32 + ISIZE, concatenates members -- local z = Deflate.compress(buf, { level = 6 }) -- raw deflate; also zlibCompress / gzip +-- local head = Deflate.peek(buf, nil, nil, 512) -- the first 512 inflated bytes of gzip / zlib / raw -- -- Never throws: bad data and bad arguments return nil, Err (core/Err codes TRUNCATED / CORRUPT / CHECKSUM / ARG). local Err = require("@formats/core/Err") @@ -101,6 +102,36 @@ function Deflate.zlib(buf: buffer | string, offset: number?, length: number?, ex return out, consumed + 4 end +-- gzipBody(b, p, e) -> the offset of a gzip member's deflate data (past FEXTRA / FNAME / FCOMMENT / FHCRC) | nil, Err +local function gzipBody(b: buffer, p: number, e: number): (number?, Err.Err?) + local flg = buffer.readu8(b, p + 3) + if flg >= 0x20 then + return nil, Err.new(Err.CORRUPT, "gzip: reserved flags set", p + 3) + end + local q = p + 10 + if bit32.band(flg, 4) ~= 0 then -- FEXTRA + if q + 2 > e then + return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q) + end + q += 2 + buffer.readu16(b, q) + end + for _, bit in { 8, 16 } do -- FNAME, FCOMMENT: zero-terminated + if bit32.band(flg, bit) ~= 0 then + while q < e and buffer.readu8(b, q) ~= 0 do + q += 1 + end + q += 1 + end + end + if bit32.band(flg, 2) ~= 0 then -- FHCRC + q += 2 + end + if q >= e then + return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q) + end + return q, nil +end + -- gunzip(buf, offset?, length?) -> buffer | nil, Err. Members are concatenated; trailing data after a member that is -- not another gzip member (zero padding, garbage) is ignored, as gzip -d does. function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?): (buffer?, Err.Err?) @@ -127,30 +158,9 @@ function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?): if buffer.readu8(b, p + 2) ~= 8 then return nil, Err.new(Err.UNSUPPORTED, "gzip: unknown compression method", p + 2) end - local flg = buffer.readu8(b, p + 3) - if flg >= 0x20 then - return nil, Err.new(Err.CORRUPT, "gzip: reserved flags set", p + 3) - end - local q = p + 10 - if bit32.band(flg, 4) ~= 0 then -- FEXTRA - if q + 2 > e then - return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q) - end - q += 2 + buffer.readu16(b, q) - end - for _, bit in { 8, 16 } do -- FNAME, FCOMMENT: zero-terminated - if bit32.band(flg, bit) ~= 0 then - while q < e and buffer.readu8(b, q) ~= 0 do - q += 1 - end - q += 1 - end - end - if bit32.band(flg, 2) ~= 0 then -- FHCRC - q += 2 - end - if q >= e then - return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q) + local q, herr = gzipBody(b, p, e) + if not q then + return nil, herr end local out, consumed = Deflate.inflate(b, q, e - q) if not out then @@ -191,6 +201,38 @@ function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?): return res, nil end +-- peek(buf, offset?, length?, n) -> buffer | nil, Err: the first n bytes (fewer when the stream is shorter, or up to +-- 258 fewer at a match boundary) a gzip member, zlib stream or raw deflate stream inflates to, without inflating +-- the rest or checking checksums: for sniffing compressed files cheaply. +function Deflate.peek(buf: buffer | string, offset: number?, length: number?, n: number): (buffer?, Err.Err?) + local b, o, l, aerr = args("Deflate.peek", buf, offset, length) + if not b then + return nil, aerr + end + if type(n) ~= "number" or n < 1 then + return nil, Err.new(Err.ARG, "Deflate.peek: bad size " .. tostring(n)) + end + local e = o + l + local q = o + if l >= 18 and buffer.readu8(b, o) == 0x1f and buffer.readu8(b, o + 1) == 0x8b and buffer.readu8(b, o + 2) == 8 then + local herr + q, herr = gzipBody(b, o, e) + if not q then + return nil, herr + end + elseif l >= 6 then + local cmf, flg = buffer.readu8(b, o), buffer.readu8(b, o + 1) + if cmf % 16 == 8 and cmf // 16 <= 7 and (cmf * 256 + flg) % 31 == 0 and bit32.band(flg, 0x20) == 0 then + q = o + 2 + end + end + local out, k = Inflate.raw(b, q :: number, e, n, true, true) + if not out then + return nil, inflateErr(tostring(k), q) + end + return shrink(out, k), nil +end + export type CompressOptions = { level: number?, -- 0 (stored) .. 9 (best); default 6 } diff --git a/src/Formats/codecs/text/Nbt/Binary.luau b/src/Formats/codecs/text/Nbt/Binary.luau new file mode 100644 index 0000000..0ecbfd2 --- /dev/null +++ b/src/Formats/codecs/text/Nbt/Binary.luau @@ -0,0 +1,698 @@ +--!strict +-- codecs/text/Nbt/Binary: binary NBT read and write, from the Minecraft wiki "NBT format" page and wiki.vg "NBT". +-- New code. Three encodings: big-endian (Java Edition files; strings in Java's modified UTF-8, converted to and from +-- UTF-8), little-endian (Bedrock files; UTF-8) and Bedrock's network form (little-endian with zigzag varints for int / +-- long and varint lengths). All thirteen tag types; values per codecs/text/Nbt/Value. Lengths are checked against +-- the bytes left before anything is allocated, and nesting is limited (opts.maxDepth, default 512 like Minecraft). +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Value = require("@formats/codecs/text/Nbt/Value") + +local Binary = {} + +export type Options = { + endian: ("big" | "little")?, -- default "big" (Java) + varint: boolean?, -- Bedrock network NBT (little-endian, varint ints / lengths); implies endian = "little" + nameless: boolean?, -- the root tag has no name (Java network NBT since 1.20.2) + maxDepth: number?, -- nesting limit (default 512) + name: string?, -- write: the root name (default "") +} + +local readu8, readi8, readu32, readi16 = buffer.readu8, buffer.readi8, buffer.readu32, buffer.readi16 +local readf32, readf64, writeu32, readstring = buffer.readf32, buffer.readf64, buffer.writeu32, buffer.readstring +local byteswap = bit32.byteswap +local TWO32 = 4294967296 +local NAMES, IDS = Value.NAMES, Value.IDS +local newTag = Value.TagMeta + +type State = { b: buffer, p: number, e: number, le: boolean, net: boolean, java: boolean, depth: number, maxDepth: number, err: string?, scratch: buffer } + +-- ------------------------------------------------------------------------------------------------ modified UTF-8 +-- Java's DataOutput strings: U+0000 as C0 80, supplementary characters as two 3-byte surrogates (CESU-8) +local function fromModified(s: string): string + if not string.find(s, "[\192\237]") then + return s + end + local out = {} + local i, n = 1, #s + while i <= n do + local c = string.byte(s, i) + if c == 0xC0 and string.byte(s, i + 1) == 0x80 then + table.insert(out, "\0") + i += 2 + elseif c == 0xED and i + 5 <= n then + local b2, b3, c4, b5, b6 = string.byte(s, i + 1, i + 5) + if b2 >= 0xA0 and b2 <= 0xAF and c4 == 0xED and b5 >= 0xB0 and b5 <= 0xBF then + local hiS = 0xD000 + (b2 - 0x80) * 64 + (b3 - 0x80) + local loS = 0xD000 + (b5 - 0x80) * 64 + (b6 - 0x80) + table.insert(out, utf8.char(0x10000 + (hiS - 0xD800) * 1024 + (loS - 0xDC00))) + i += 6 + else + table.insert(out, string.char(c)) + i += 1 + end + else + local j = string.find(s, "[\192\237]", i + 1) or n + 1 + table.insert(out, string.sub(s, i, j - 1)) + i = j + end + end + return table.concat(out) +end + +local function toModified(s: string): string + if not string.find(s, "[%z\240-\244]") then + return s + end + local out = {} + local i, n = 1, #s + while i <= n do + local c = string.byte(s, i) + if c == 0 then + table.insert(out, "\192\128") + i += 1 + elseif c >= 0xF0 and c <= 0xF4 and i + 3 <= n then + local b2, b3, b4 = string.byte(s, i + 1, i + 3) + local cp = (c - 0xF0) * 262144 + (b2 - 0x80) * 4096 + (b3 - 0x80) * 64 + (b4 - 0x80) - 0x10000 + local hiS, loS = 0xD800 + cp // 1024, 0xDC00 + cp % 1024 + table.insert(out, string.char(0xED, 0x80 + (hiS - 0xD000) // 64, 0x80 + hiS % 64)) + table.insert(out, string.char(0xED, 0x80 + (loS - 0xD000) // 64, 0x80 + loS % 64)) + i += 4 + else + local j = string.find(s, "[%z\240-\244]", i + 1) or n + 1 + table.insert(out, string.sub(s, i, j - 1)) + i = j + end + end + return table.concat(out) +end +Binary.fromModified = fromModified +Binary.toModified = toModified + +-- ------------------------------------------------------------------------------------------------ read +local function fail(s: State, msg: string): nil + if not s.err then + s.err = msg + end + s.p = s.e + return nil +end + +local function need(s: State, n: number): boolean + if s.p + n > s.e then + fail(s, "truncated") + return false + end + return true +end + +local function u8(s: State): number + if not need(s, 1) then + return 0 + end + local v = readu8(s.b, s.p) + s.p += 1 + return v +end + +local function varuint(s: State): number -- up to 32 bits (5 bytes) + local v, mul = 0, 1 + for _ = 1, 5 do + if not need(s, 1) then + return 0 + end + local c = readu8(s.b, s.p) + s.p += 1 + v += (c % 128) * mul + if c < 128 then + return v % TWO32 + end + mul *= 128 + end + fail(s, "varint too long") + return 0 +end + +local function i16(s: State): number + if not need(s, 2) then + return 0 + end + local p = s.p + s.p = p + 2 + if s.le then + return readi16(s.b, p) + end + local v = readu8(s.b, p) * 256 + readu8(s.b, p + 1) + return if v >= 32768 then v - 65536 else v +end + +local function u32raw(s: State): number + if not need(s, 4) then + return 0 + end + local p = s.p + s.p = p + 4 + local v = readu32(s.b, p) + return if s.le then v else byteswap(v) +end + +local function i32(s: State): number + if s.net then + local n = varuint(s) + return if n % 2 == 0 then n // 2 else -(n + 1) // 2 + end + local v = u32raw(s) + return if v >= 0x80000000 then v - TWO32 else v +end + +-- a length: i32 (zigzag varint in network NBT) +local function len(s: State): number + return i32(s) +end + +local function i64(s: State): (number, number) -- hi, lo + if s.net then + local lo, hi, sh = 0, 0, 0 + while true do + if sh >= 70 or not need(s, 1) then + fail(s, "varint too long") + return 0, 0 + end + local c = readu8(s.b, s.p) + s.p += 1 + local d = c % 128 + if sh < 32 then + local x = d * 2 ^ sh + lo += x % TWO32 + hi = (hi + x // TWO32) % TWO32 + else + hi = (hi + d * 2 ^ (sh - 32)) % TWO32 + end + sh += 7 + if c < 128 then + break + end + end + local odd = lo % 2 == 1 + lo = lo // 2 + (hi % 2) * 0x80000000 + hi = hi // 2 + if odd then + hi, lo = TWO32 - 1 - hi, TWO32 - 1 - lo + end + return hi, lo + end + if s.le then + local lo = u32raw(s) + return u32raw(s), lo + end + local hi = u32raw(s) + return hi, u32raw(s) +end + +local function f32(s: State): number + local v = u32raw(s) + writeu32(s.scratch, 0, v) + return readf32(s.scratch, 0) +end + +local function f64(s: State): number + local hi, lo + if s.le then + lo = u32raw(s) + hi = u32raw(s) + else + hi = u32raw(s) + lo = u32raw(s) + end + writeu32(s.scratch, 0, lo) + writeu32(s.scratch, 4, hi) + return readf64(s.scratch, 0) +end + +local function str(s: State): string + local n + if s.net then + n = varuint(s) + else + n = i16(s) % 65536 + end + if not need(s, n) then + return "" + end + local v = readstring(s.b, s.p, n) + s.p += n + return if s.java then fromModified(v) else v +end + +local function tag(name: string, v: any): any + return setmetatable({ type = name, value = v }, newTag) +end + +-- the smallest encoded size of one element, to bound list lengths before allocating +local MIN = { [0] = 0, 1, 2, 4, 8, 4, 8, 4, 2, 5, 1, 4, 4 } +local MIN_NET = { [0] = 0, 1, 2, 1, 1, 4, 8, 1, 1, 2, 1, 1, 1 } + +local payload: (State, number) -> any + +local function count(s: State, n: number, size: number): boolean + if n < 0 then + fail(s, "negative length " .. n) + return false + end + if n * size > s.e - s.p then + fail(s, "truncated: " .. n .. " elements past the end") + return false + end + return true +end + +payload = function(s: State, id: number): any + if id == 3 then + return i32(s) + elseif id == 8 then + return str(s) + elseif id == 10 then + s.depth += 1 + if s.depth > s.maxDepth then + return fail(s, "limit: nested deeper than " .. s.maxDepth) + end + local o, keys = {}, {} + while true do + local t = u8(s) + if s.err then + return nil + end + if t == 0 then + break + end + if t > 12 then + return fail(s, "bad tag type " .. t) + end + local k = str(s) + local v = payload(s, t) + if s.err then + return nil + end + if o[k] == nil then + table.insert(keys, k) + end + o[k] = v + end + s.depth -= 1 + return Types.object(o, keys) + elseif id == 1 then + if not need(s, 1) then + return nil + end + s.p += 1 + return tag("byte", readi8(s.b, s.p - 1)) + elseif id == 2 then + return tag("short", i16(s)) + elseif id == 4 then + local hi, lo = i64(s) + return tag("long", Value.fromHiLo(hi, lo)) + elseif id == 5 then + return tag("float", f32(s)) + elseif id == 6 then + return tag("double", f64(s)) + elseif id == 7 then + local n = len(s) + if not count(s, n, 1) then + return nil + end + local out = buffer.create(n) + buffer.copy(out, 0, s.b, s.p, n) + s.p += n + return out + elseif id == 9 then + local et = u8(s) + local n = len(s) + if s.err then + return nil + end + if et > 12 then + return fail(s, "bad list element type " .. et) + end + if et == 0 and n > 0 then + return fail(s, "list of end tags with " .. n .. " elements") + end + if not count(s, n, (if s.net then MIN_NET else MIN)[et]) then + return nil + end + s.depth += 1 + if s.depth > s.maxDepth then + return fail(s, "limit: nested deeper than " .. s.maxDepth) + end + local out = table.create(n) + for i = 1, n do + local v = payload(s, et) + if s.err then + return nil + end + out[i] = v + end + s.depth -= 1 + Value.setListType(out, NAMES[et]) + return out + elseif id == 11 then + local n = len(s) + if not count(s, n, if s.net then 1 else 4) then + return nil + end + local out = table.create(n) + for i = 1, n do + out[i] = i32(s) + end + return tag("intArray", out) + elseif id == 12 then + local n = len(s) + if not count(s, n, if s.net then 1 else 8) then + return nil + end + local out = buffer.create(n * 8) + if s.net then + for i = 0, n - 1 do + local hi, lo = i64(s) + writeu32(out, i * 8, lo) + writeu32(out, i * 8 + 4, hi) + end + elseif s.le then + buffer.copy(out, 0, s.b, s.p, n * 8) + s.p += n * 8 + else + local b, p = s.b, s.p + for i = 0, n - 1 do + local q = p + i * 8 + writeu32(out, i * 8 + 4, byteswap(readu32(b, q))) + writeu32(out, i * 8, byteswap(readu32(b, q + 4))) + end + s.p = p + n * 8 + end + return tag("longArray", out) + end + return fail(s, "bad tag type " .. id) +end + +-- read(buf, pos, limit, opts?) -> value, rootName, endPos | nil, message, at +function Binary.read(b: buffer, pos: number, limit: number, opts: Options?): (any, any, number?) + local o: Options = opts or {} + local net = o.varint == true + local le = net or o.endian == "little" + local s: State = { + b = b, + p = pos, + e = limit, + le = le, + net = net, + java = not le, + depth = 0, + maxDepth = o.maxDepth or 512, + err = nil, + scratch = buffer.create(8), + } + local id = u8(s) + if s.err then + return nil, s.err, pos + end + if id == 0 or id > 12 then + return nil, "bad root tag type " .. id, pos + end + local name = if o.nameless then "" else str(s) + local v = payload(s, id) + if s.err then + return nil, s.err, s.p + end + return v, name, s.p +end + +-- ------------------------------------------------------------------------------------------------ write +type WState = { w: Bytes.Writer, le: boolean, net: boolean, java: boolean, depth: number, maxDepth: number } + +local function wvaruint(w: Bytes.Writer, v: number) + v %= TWO32 + while v >= 128 do + w:u8(v % 128 + 128) + v //= 128 + end + w:u8(v) +end + +local function wi32(ws: WState, v: number) + v %= TWO32 -- two's complement + if ws.net then + local sv = if v >= 0x80000000 then v - TWO32 else v + wvaruint(ws.w, if sv >= 0 then sv * 2 else -sv * 2 - 1) + elseif ws.le then + ws.w:u32le(v) + else + ws.w:u32be(v) + end +end + +local function wi16(ws: WState, v: number) + v %= 65536 + if ws.le then + ws.w:u16le(v) + else + ws.w:u16be(v) + end +end + +local function wi64(ws: WState, hi: number, lo: number) + if ws.net then + -- zigzag: (n << 1) ^ (n >> 63) + local neg = hi >= 0x80000000 + local zh = (hi * 2) % TWO32 + (if lo >= 0x80000000 then 1 else 0) + local zl = (lo * 2) % TWO32 + if neg then + zh, zl = TWO32 - 1 - zh, TWO32 - 1 - zl + end + while zh > 0 or zl >= 128 do + ws.w:u8(zl % 128 + 128) + zl = zl // 128 + (zh % 128) * 0x2000000 + zh //= 128 + end + ws.w:u8(zl) + elseif ws.le then + ws.w:u32le(lo) + ws.w:u32le(hi) + else + ws.w:u32be(hi) + ws.w:u32be(lo) + end +end + +local function wstr(ws: WState, s: string): string? + local v = if ws.java then toModified(s) else s + if ws.net then + wvaruint(ws.w, #v) + else + if #v > 65535 then + return "string longer than 65535 bytes" + end + wi16(ws, #v) + end + ws.w:string(v) + return nil +end + +local function integer(v: any, lo: number, hi: number, what: string): (number?, string?) + local n = if type(v) == "boolean" then (if v then 1 else 0) else v + if type(n) ~= "number" or n % 1 ~= 0 or n < lo or n > hi then + return nil, "bad " .. what .. " value " .. tostring(n) + end + return n, nil +end + +local wpayload: (WState, string, any) -> string? + +local function wlist(ws: WState, v: { any }): string? + local lt = Value.listType(v) + local n = #v + local wrap = false + if not lt then + if n == 0 then + lt = "end" + else + local t1, e1 = Value.typeOf(v[1]) + if not t1 then + return e1 + end + lt = t1 + end + end + for i = 1, n do + local t, e = Value.typeOf(v[i]) + if not t then + return e + end + if t ~= lt then + wrap = true -- mixed element types: every element becomes a compound { [""] = value }, as Minecraft does + end + end + if wrap then + lt = "compound" + end + if lt == "end" and n > 0 then + return "a list of end tags cannot hold elements" + end + ws.w:u8(IDS[lt :: string]) + wi32(ws, n) + for i = 1, n do + local x = v[i] + if wrap and Value.typeOf(x) ~= "compound" then + x = Types.object({ [""] = x }, { "" }) + end + local e = wpayload(ws, lt :: string, x) + if e then + return e + end + end + return nil +end + +wpayload = function(ws: WState, t: string, v: any): string? + local w = ws.w + local x = if Value.isTag(v) then v.value else v + if t == "int" then + local n, e = integer(x, -2147483648, 4294967295, "int") + if not n then + return e + end + wi32(ws, n) + elseif t == "string" then + if type(x) ~= "string" then + return "bad string value" + end + return wstr(ws, x) + elseif t == "compound" then + ws.depth += 1 + if ws.depth > ws.maxDepth then + return "nested deeper than " .. ws.maxDepth .. " (a cycle?)" + end + for _, k in Types.keys(v) do + if type(k) ~= "string" then + return "compound key " .. tostring(k) .. " is not a string" + end + local c = v[k] + local ct, e = Value.typeOf(c) + if not ct then + return e .. " (key " .. k .. ")" + end + w:u8(IDS[ct :: string]) + e = wstr(ws, k) + if e then + return e + end + e = wpayload(ws, ct :: string, c) + if e then + return e + end + end + w:u8(0) + ws.depth -= 1 + elseif t == "list" then + ws.depth += 1 + if ws.depth > ws.maxDepth then + return "nested deeper than " .. ws.maxDepth .. " (a cycle?)" + end + local e = wlist(ws, v) + if e then + return e + end + ws.depth -= 1 + elseif t == "byte" then + local n, e = integer(x, -128, 255, "byte") + if not n then + return e + end + w:u8(n % 256) + elseif t == "short" then + local n, e = integer(x, -32768, 65535, "short") + if not n then + return e + end + wi16(ws, n) + elseif t == "long" then + local hi, lo = Value.toHiLo(x) + if not hi then + return "bad long value " .. tostring(x) + end + wi64(ws, hi, lo :: number) + elseif t == "float" or t == "double" then + if type(x) ~= "number" then + return "bad " .. t .. " value " .. tostring(x) + end + if t == "float" then + if ws.le then + w:f32le(x) + else + w:f32be(x) + end + elseif ws.le then + w:f64le(x) + else + w:f64be(x) + end + elseif t == "byteArray" then + if type(x) ~= "buffer" then + return "bad byteArray value" + end + wi32(ws, buffer.len(x)) + w:bytes(x) + elseif t == "intArray" then + if type(x) ~= "table" then + return "bad intArray value" + end + wi32(ws, #x) + for i = 1, #x do + local n, e = integer(x[i], -2147483648, 4294967295, "intArray element") + if not n then + return e + end + wi32(ws, n) + end + elseif t == "longArray" then + if type(x) ~= "buffer" or buffer.len(x) % 8 ~= 0 then + return "bad longArray value (a buffer of 8-byte little-endian longs)" + end + local n = buffer.len(x) // 8 + wi32(ws, n) + if ws.le and not ws.net then + w:bytes(x) + else + for i = 0, n - 1 do + wi64(ws, buffer.readu32(x, i * 8 + 4), buffer.readu32(x, i * 8)) + end + end + else + return "cannot write tag type " .. t + end + return nil +end + +-- write(value, opts?) -> buffer | nil, message +function Binary.write(v: any, opts: Options?): (buffer?, string?) + local o: Options = opts or {} + local net = o.varint == true + local le = net or o.endian == "little" + local t, e = Value.typeOf(v) + if not t then + return nil, e + end + local ws: WState = { w = Bytes.writer(1024), le = le, net = net, java = not le, depth = 0, maxDepth = o.maxDepth or 512 } + ws.w:u8(IDS[t :: string]) + if not o.nameless then + e = wstr(ws, o.name or "") + if e then + return nil, e + end + end + e = wpayload(ws, t :: string, v) + if e then + return nil, e + end + return ws.w:finish(), nil +end + +return Binary diff --git a/src/Formats/codecs/text/Nbt/Snbt.luau b/src/Formats/codecs/text/Nbt/Snbt.luau new file mode 100644 index 0000000..7dcc0f3 --- /dev/null +++ b/src/Formats/codecs/text/Nbt/Snbt.luau @@ -0,0 +1,649 @@ +--!strict +-- codecs/text/Nbt/Snbt: stringified NBT (the text form of /data and /give), parse and print. New code, from the +-- Minecraft wiki "NBT format" SNBT section (Java 1.21.5 grammar). Parses: compounds, lists, [B; ...] [I; ...] [L; ...] +-- arrays, quoted strings ('...' / "..." with \\ \' \" \n \t \r \b \f \s \xNN \uNNNN \UNNNNNNNN escapes) and unquoted +-- strings, numbers with b / s / i / l / f / d suffixes (any case, signed / unsigned s / u prefix), underscores, hex +-- 0x and binary 0b integers, exponents, true / false (bytes 1 / 0), NaN / Infinity with a float suffix, trailing +-- commas. Not supported: the 1.21.5 operations bool(...) / uuid(...) and \N{name} escapes. Prints Minecraft's +-- compact form (or indented); floats print as the shortest text that reads back to the same value. +local Types = require("@formats/Types") +local Value = require("@formats/codecs/text/Nbt/Value") + +local Snbt = {} + +export type ParseOptions = { maxDepth: number? } +export type PrintOptions = { + indent: (number | string)?, -- pretty print: spaces per level or the indent string (default: compact) + quote: string?, -- the string quote, '"' (default) or "'"; the other one is used when it needs fewer escapes +} + +local byte, sub, find = string.byte, string.sub, string.find +local TWO32 = 4294967296 + +local function tag(name: string, v: any): any + return setmetatable({ type = name, value = v }, Value.TagMeta) +end + +-- ------------------------------------------------------------------------------------------------ parse +type P = { s: string, i: number, n: number, err: string?, at: number, depth: number, maxDepth: number } + +local function fail(p: P, msg: string): nil + if not p.err then + p.err, p.at = msg, p.i + end + p.i = p.n + 1 + return nil +end + +local function ws(p: P) + local _, e = find(p.s, "^%s*", p.i) + p.i = (e :: number) + 1 +end + +local function isUnquoted(c: number): boolean + return (c >= 48 and c <= 57) or (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 or c == 45 or c == 46 or c == 43 +end + +local ESC: { [string]: string } = { ["\\"] = "\\", ["'"] = "'", ['"'] = '"', n = "\n", t = "\t", r = "\r", b = "\b", f = "\f", s = " " } + +local function quoted(p: P): string? + local q = sub(p.s, p.i, p.i) + p.i += 1 + local out = {} + while true do + local j = find(p.s, if q == '"' then '["\\]' else "['\\]", p.i) + if not j then + return fail(p, "unterminated string") + end + table.insert(out, sub(p.s, p.i, j - 1)) + if sub(p.s, j, j) == q then + p.i = j + 1 + return table.concat(out) + end + local c = sub(p.s, j + 1, j + 1) + if ESC[c] then + table.insert(out, ESC[c]) + p.i = j + 2 + elseif c == "x" or c == "u" or c == "U" then + local nd = if c == "x" then 2 elseif c == "u" then 4 else 8 + local hex = sub(p.s, j + 2, j + 1 + nd) + if #hex ~= nd or find(hex, "[^%x]") then + p.i = j + return fail(p, "bad \\" .. c .. " escape") + end + local cp = tonumber(hex, 16) :: number + if cp > 0x10FFFF or (cp >= 0xD800 and cp <= 0xDFFF) then + p.i = j + return fail(p, "bad code point in \\" .. c .. " escape") + end + table.insert(out, utf8.char(cp)) + p.i = j + 2 + nd + else + p.i = j + return fail(p, "bad escape \\" .. c) + end + end +end + +-- number text -> a value, or nil when it is not a number (then it is an unquoted string) +local INT_RANGE: { [string]: { number } } = { + b = { -128, 127, 255 }, + s = { -32768, 32767, 65535 }, + i = { -2147483648, 2147483647, 4294967295 }, +} +local INT_NAME = { b = "byte", s = "short", i = "int", l = "long" } + +local function integer(t: string): any + local sign, body = string.match(t, "^([+-]?)(.+)$") + body = string.gsub(body :: string, "_", "") :: string + local radix, digits, suffix = 10, body, "" + local low = string.lower(body) + local m, sfx + if sub(low, 1, 2) == "0x" then + -- b and s are hex digits: a byte / short suffix needs its signedness (0x7Fsb, 0xFFub) + m, sfx = string.match(sub(body, 3), "^(%x+)([sSuU][bBsSiIlL])$") + if not m then + m, sfx = string.match(sub(body, 3), "^(%x+)([iIlL]?)$") + end + if not m then + return nil + end + radix = 16 + elseif sub(low, 1, 2) == "0b" then + m, sfx = string.match(sub(body, 3), "^([01]+)([sSuU]?[bBsSiIlL]?)$") + if m then + radix = 2 + end + end + if not m then + m, sfx = string.match(body, "^(%d+)([sSuU]?[bBsSiIlL]?)$") + if not m then + return nil + end + end + digits, suffix = m :: string, string.lower(sfx :: string) + local unsigned = false + if #suffix == 2 then + unsigned = sub(suffix, 1, 1) == "u" + suffix = sub(suffix, 2) + elseif suffix == "u" then + return nil + end + if suffix == "" then + suffix = "i" + end + if unsigned and sign == "-" then + return nil + end + -- the magnitude as (hi, lo) + local hi, lo = 0, 0 + for k = 1, #digits do + local c = byte(digits, k) + local d = if c <= 57 then c - 48 elseif c >= 97 then c - 87 else c - 55 + local x = lo * radix + d + local carry = x // TWO32 + lo = x - carry * TWO32 + hi = hi * radix + carry + if hi >= TWO32 then + return nil + end + end + if suffix == "l" then + local neg = sign == "-" + if radix == 10 then + if hi > 0x80000000 or (hi == 0x80000000 and (lo > 0 or not neg)) then + return nil + end + end + if neg and (hi > 0 or lo > 0) then + lo = (TWO32 - lo) % TWO32 + hi = (TWO32 - 1 - hi + (if lo == 0 then 1 else 0)) % TWO32 + end + return tag("long", Value.fromHiLo(hi, lo)) + end + if hi > 0 then + return nil + end + local r = INT_RANGE[suffix] + local v = lo + if sign == "-" then + v = -v + end + if radix ~= 10 and not unsigned and sign ~= "-" and v > r[2] and v <= r[3] then + v -= r[3] + 1 -- hex / binary literals wrap into the signed range (0xFFb = -1b) + elseif unsigned then + if v > r[3] then + return nil + end + if v > r[2] then + v -= r[3] + 1 + end + end + if v < r[1] or v > r[2] then + return nil + end + if suffix == "i" then + return v + end + return tag(INT_NAME[suffix], v) +end + +local function number(t: string): any + local low = string.lower(t) + if low == "true" then + return tag("byte", 1) + elseif low == "false" then + return tag("byte", 0) + end + local sfx = sub(low, -1) + local special = string.match(low, "^([+-]?)infinity[fd]$") + if special then + return tag(if sfx == "f" then "float" else "double", if special == "-" then -math.huge else math.huge) + elseif low == "nanf" or low == "nand" then + return tag(if sfx == "f" then "float" else "double", 0 / 0) + end + local iv = integer(t) + if iv ~= nil then + return iv + end + local body = string.gsub(t, "_", "") + local m, fs = string.match(body, "^([+-]?[%d%.]+[eE]?[+-]?%d*)([fFdD]?)$") + if not m then + return nil + end + -- mantissa digits[.digits] or .digits, an optional exponent; without a fraction or an exponent a suffix is needed + local mant, ex = string.match(m :: string, "^(.-)([eE][+-]?%d+)$") + if not mant then + mant = m + end + if not (string.match(mant :: string, "^[+-]?%d+%.?%d*$") or string.match(mant :: string, "^[+-]?%.%d+$")) then + return nil + end + if fs == "" and not ex and not find(mant :: string, ".", 1, true) then + return nil + end + local v = tonumber(m) + if not v then + return nil + end + if string.lower(fs :: string) == "f" then + local b = buffer.create(4) + buffer.writef32(b, 0, v) + return tag("float", buffer.readf32(b, 0)) + end + return tag("double", v) +end + +local parseValue: (P) -> any + +local function token(p: P): string + local j = p.i + while j <= p.n and isUnquoted(byte(p.s, j)) do + j += 1 + end + local t = sub(p.s, p.i, j - 1) + p.i = j + return t +end + +local function key(p: P): string? + ws(p) + local c = sub(p.s, p.i, p.i) + if c == '"' or c == "'" then + return quoted(p) + end + local t = token(p) + if t == "" then + return fail(p, "expected a key") + end + return t +end + +local ARRAY = { B = "byte", I = "int", L = "long" } + +local function array(p: P, kind: string): any + local items = {} + ws(p) + if sub(p.s, p.i, p.i) ~= "]" then + while true do + ws(p) + local at = p.i + local t = token(p) + local v = if t ~= "" then number(t) else nil + local vt = Value.typeOf(v) + if v == nil or (vt ~= "byte" and vt ~= "short" and vt ~= "int" and vt ~= "long") then + p.i = at + return fail(p, "expected an integer in a " .. kind .. " array") + end + local x: any = if Value.isTag(v) then (v :: any).value else v + if kind == "byte" and (x < -128 or x > 127) or kind == "int" and vt == "long" then + p.i = at + return fail(p, "value out of range in a " .. kind .. " array") + end + table.insert(items, x) + ws(p) + local c = sub(p.s, p.i, p.i) + p.i += 1 + if c == "]" then + break + elseif c ~= "," then + p.i -= 1 + return fail(p, "expected , or ]") + end + ws(p) + if sub(p.s, p.i, p.i) == "]" then + p.i += 1 + break + end + end + else + p.i += 1 + end + if kind == "byte" then + local b = buffer.create(#items) + for i, x in items do + buffer.writei8(b, i - 1, x) + end + return b + elseif kind == "int" then + return tag("intArray", items) + end + return Value.longArray(items) +end + +parseValue = function(p: P): any + ws(p) + if p.i > p.n then + return fail(p, "expected a value") + end + local c = sub(p.s, p.i, p.i) + if c == "{" then + p.depth += 1 + if p.depth > p.maxDepth then + return fail(p, "limit: nested deeper than " .. p.maxDepth) + end + p.i += 1 + local o, keys = {}, {} + ws(p) + if sub(p.s, p.i, p.i) == "}" then + p.i += 1 + else + while true do + local k = key(p) + if p.err then + return nil + end + ws(p) + if sub(p.s, p.i, p.i) ~= ":" then + return fail(p, "expected :") + end + p.i += 1 + local v = parseValue(p) + if p.err then + return nil + end + if o[k :: string] == nil then + table.insert(keys, k) + end + o[k :: string] = v + ws(p) + local d = sub(p.s, p.i, p.i) + p.i += 1 + if d == "}" then + break + elseif d ~= "," then + p.i -= 1 + return fail(p, "expected , or }") + end + ws(p) + if sub(p.s, p.i, p.i) == "}" then + p.i += 1 + break + end + end + end + p.depth -= 1 + return Types.object(o, keys) + elseif c == "[" then + p.depth += 1 + if p.depth > p.maxDepth then + return fail(p, "limit: nested deeper than " .. p.maxDepth) + end + p.i += 1 + local kind = string.match(p.s, "^%s*([BIL])%s*;", p.i) + if kind then + local _, e = find(p.s, "^%s*[BIL]%s*;", p.i) + p.i = (e :: number) + 1 + local v = array(p, ARRAY[kind]) + p.depth -= 1 + return v + end + local items = {} + local lt: string? = nil + local mixed = false + ws(p) + if sub(p.s, p.i, p.i) == "]" then + p.i += 1 + else + while true do + local v = parseValue(p) + if p.err then + return nil + end + local t = Value.typeOf(v) + if lt == nil then + lt = t + elseif t ~= lt then + mixed = true + end + table.insert(items, v) + ws(p) + local d = sub(p.s, p.i, p.i) + p.i += 1 + if d == "]" then + break + elseif d ~= "," then + p.i -= 1 + return fail(p, "expected , or ]") + end + ws(p) + if sub(p.s, p.i, p.i) == "]" then + p.i += 1 + break + end + end + end + p.depth -= 1 + if not mixed then + Value.setListType(items, lt or "end") + end + return items + elseif c == '"' or c == "'" then + return quoted(p) + end + local at = p.i + local t = token(p) + if t == "" then + return fail(p, "unexpected character " .. string.format("%q", c)) + end + local v = number(t) + if v == nil then + if string.match(t, "^[+-]?%d[%d_]*[sSuU]?[bBsSiIlL]$") then + p.i = at + return fail(p, "number out of range: " .. t) + end + return t + end + return v +end + +-- parse(text, opts?) -> value | nil, message, position (1-based) +function Snbt.parse(s: string, opts: ParseOptions?): (any, string?, number?) + local p: P = { s = s, i = 1, n = #s, err = nil, at = 1, depth = 0, maxDepth = (opts and opts.maxDepth) or 512 } + local v = parseValue(p) + if p.err then + return nil, p.err, p.at + end + ws(p) + if p.i <= p.n then + return nil, "trailing characters after the value", p.i + end + return v, nil, nil +end + +-- ------------------------------------------------------------------------------------------------ print +local function shortest(v: number, single: boolean): string + if v ~= v then + return "NaN" + elseif v == math.huge then + return "Infinity" + elseif v == -math.huge then + return "-Infinity" + end + local b = buffer.create(4) + if single then + buffer.writef32(b, 0, v) + v = buffer.readf32(b, 0) + end + local s = "" + for digits = if single then 6 else 15, 17 do + s = string.format("%." .. digits .. "g", v) + local back = tonumber(s) :: number + if single then + buffer.writef32(b, 0, back) + back = buffer.readf32(b, 0) + end + if back == v then + break + end + end + if not find(s, "[%.eEn]") then + s ..= ".0" + end + return s +end +Snbt.shortest = shortest + +local function quote(s: string, q: string): string + local other = if q == '"' then "'" else '"' + local _, nq = string.gsub(s, q, "") + local _, no = string.gsub(s, other, "") + if nq > no then + q = other + end + local e = string.gsub(s, "[\\" .. q .. "%c]", function(c: string): string + if c == "\\" or c == q then + return "\\" .. c + elseif c == "\n" then + return "\\n" + elseif c == "\t" then + return "\\t" + elseif c == "\r" then + return "\\r" + end + return string.format("\\x%02x", byte(c)) + end) + return q .. e .. q +end + +local function keyText(k: string, q: string): string + if k ~= "" and not find(k, "[^%w_%-%.%+]") then + return k + end + return quote(k, q) +end + +type Pr = { out: { string }, indent: string?, q: string, depth: number } + +local printValue: (Pr, any, number) -> string? + +local function scalar(v: any, q: string): string? + local tv = type(v) + if tv == "number" then + if v % 1 == 0 and v >= -2147483648 and v <= 2147483647 then + return string.format("%d", v) + end + return shortest(v, false) .. "d" + elseif tv == "string" then + return quote(v, q) + elseif tv == "boolean" then + return if v then "1b" else "0b" + elseif Value.isTag(v) then + local t, x = v.type, v.value + if t == "byte" then + return string.format("%db", x) + elseif t == "short" then + return string.format("%ds", x) + elseif t == "int" then + return string.format("%d", x) + elseif t == "long" then + return (if type(x) == "string" then x else string.format("%d", x)) .. "L" + elseif t == "float" then + return shortest(x, true) .. "f" + elseif t == "double" then + return shortest(x, false) .. "d" + elseif t == "string" then + return quote(x, q) + end + end + return nil +end + +local function seq(pr: Pr, head: string, items: { string }, close: string) + if pr.indent and #items > 0 then + local pad = string.rep(pr.indent, pr.depth) + table.insert(pr.out, head .. "\n" .. pad .. pr.indent .. table.concat(items, ",\n" .. pad .. pr.indent) .. "\n" .. pad .. close) + else + table.insert(pr.out, head .. table.concat(items, if pr.indent then ", " else ",") .. close) + end +end + +local function sub1(pr: Pr, v: any): (string?, string?) + local inner: Pr = { out = {}, indent = pr.indent, q = pr.q, depth = pr.depth + 1 } + local e = printValue(inner, v, inner.depth) + if e then + return nil, e + end + return table.concat(inner.out), nil +end + +printValue = function(pr: Pr, v: any, depth: number): string? + if depth > 512 then + return "nested deeper than 512 (a cycle?)" + end + local s = scalar(v, pr.q) + if s then + table.insert(pr.out, s) + return nil + end + local t, terr = Value.typeOf(v) + if not t then + return terr + end + if t == "byteArray" then + local items = table.create(buffer.len(v)) :: { string } + for i = 0, buffer.len(v) - 1 do + items[i + 1] = buffer.readi8(v, i) .. "b" + end + seq(pr, "[B;", items, "]") + elseif t == "intArray" then + local items = {} + for i, x in v.value do + items[i] = string.format("%d", x) + end + seq(pr, "[I;", items, "]") + elseif t == "longArray" then + local items = {} + for i, x in Value.longs(v) do + items[i] = (if type(x) == "string" then x else string.format("%d", x)) .. "L" + end + seq(pr, "[L;", items, "]") + elseif t == "list" then + local items: { string } = {} + for i = 1, #v do + local x, e = sub1(pr, v[i]) + if e then + return e + end + items[i] = x :: string + end + seq(pr, "[", items, "]") + else + local items = {} + for _, k in Types.keys(v) do + if type(k) ~= "string" then + return "compound key " .. tostring(k) .. " is not a string" + end + local x, e = sub1(pr, v[k]) + if e then + return e + end + table.insert(items, keyText(k, pr.q) .. (if pr.indent then ": " else ":") .. (x :: string)) + end + seq(pr, "{", items, "}") + end + return nil +end + +-- print(value, opts?) -> text | nil, message +function Snbt.print(v: any, opts: PrintOptions?): (string?, string?) + local o: PrintOptions = opts or {} + local ind = o.indent + local pr: Pr = { + out = {}, + indent = if type(ind) == "number" then string.rep(" ", ind) elseif type(ind) == "string" then ind else nil, + q = if o.quote == "'" then "'" else '"', + depth = 0, + } + local e = printValue(pr, v, 0) + if e then + return nil, e + end + return table.concat(pr.out), nil +end + +Value.print = function(v: any): string + return Snbt.print(v) or "?" +end + +return Snbt diff --git a/src/Formats/codecs/text/Nbt/Value.luau b/src/Formats/codecs/text/Nbt/Value.luau new file mode 100644 index 0000000..2c0bb17 --- /dev/null +++ b/src/Formats/codecs/text/Nbt/Value.luau @@ -0,0 +1,256 @@ +--!strict +-- codecs/text/Nbt/Value: the NBT value model shared by the binary and SNBT codecs. New code. +-- Plain Luau values with typed numbers, so a decode / encode round trip is exact: +-- int -> number string -> string byteArray -> buffer +-- compound -> Types.object (key order kept) list -> array (element type in Value.listType) +-- byte / short / long / float / double / intArray / longArray -> a tag { type = "", value = ... } with a +-- metatable (tostring gives SNBT): long values are numbers when exact (|v| <= 2^53), else their exact decimal +-- text; intArray value = { numbers }; longArray value = a buffer of little-endian two's complement int64s. +-- Inputs are lenient: a plain number writes as int when integral and in int range, else double; true / false as +-- byte 1 / 0; a plain table with string keys as a compound. +local Types = require("@formats/Types") + +local Value = {} + +-- tag ids (the binary format) <-> names +Value.NAMES = { + [0] = "end", + "byte", + "short", + "int", + "long", + "float", + "double", + "byteArray", + "string", + "list", + "compound", + "intArray", + "longArray", +} :: { [number]: string } +Value.IDS = {} :: { [string]: number } +for id = 0, 12 do + Value.IDS[Value.NAMES[id]] = id +end + +export type Tag = { type: string, value: any } + +local TagMeta: { [string]: any } = {} +Value.TagMeta = TagMeta +-- the SNBT printer, filled in by codecs/text/Nbt (Value is below the printer) +Value.print = function(v: any): string + return tostring(v.value) +end +TagMeta.__tostring = function(v: any): string + return Value.print(v) +end +TagMeta.__eq = function(a: any, b: any): boolean + if a.type ~= b.type then + return false + end + local x, y = a.value, b.value + if type(x) == "buffer" and type(y) == "buffer" then + return buffer.tostring(x) == buffer.tostring(y) + elseif type(x) == "table" and type(y) == "table" then + if #x ~= #y then + return false + end + for i = 1, #x do + if x[i] ~= y[i] then + return false + end + end + return true + end + return x == y +end + +local listTypes: { [any]: string } = setmetatable({}, { __mode = "k" }) :: any + +-- ------------------------------------------------------------------------------------------------ 64-bit integers +local TWO32 = 4294967296 + +-- fromHiLo(hi, lo) -> a long value: a number when exact, else the exact decimal text (hi, lo: u32 halves of the +-- two's complement int64) +function Value.fromHiLo(hi: number, lo: number): number | string + local s = if hi >= 0x80000000 then hi - TWO32 else hi + if s >= -0x200000 and s < 0x200000 then + return s * TWO32 + lo + end + local neg = s < 0 + if neg then -- magnitude = 2^64 - v + lo = (TWO32 - lo) % TWO32 + hi = (TWO32 - 1 - hi + (if lo == 0 then 1 else 0)) % TWO32 + end + local parts = {} + while hi > 0 or lo > 0 do -- divide (hi, lo) by 10^4: r * 2^32 + lo < 10^4 * 2^32 stays exact, ql < 2^32 + local qh = hi // 10000 + local x = (hi - qh * 10000) * TWO32 + lo + local ql = x // 10000 + local d = x - ql * 10000 + hi, lo = qh, ql + table.insert(parts, 1, string.format(if hi > 0 or lo > 0 then "%04d" else "%d", d)) + end + return (if neg then "-" else "") .. table.concat(parts) +end + +-- toHiLo(v) -> hi, lo (u32 halves) | nil: v a whole number in int64 range or its decimal text +function Value.toHiLo(v: any): (number?, number?) + if type(v) == "number" then + if v % 1 ~= 0 or v < -9223372036854775808 or v >= 9223372036854775808 then + return nil, nil + end + local hi = v // TWO32 + local lo = v - hi * TWO32 + return hi % TWO32, lo + elseif type(v) == "string" then + local neg, digits = string.match(v, "^(%-?)(%d+)$") + if not digits or #digits > 19 then + return nil, nil + end + local hi, lo = 0, 0 + for i = 1, #digits do + local x = lo * 10 + (string.byte(digits, i) - 48) + local carry = x // TWO32 + lo = x - carry * TWO32 + hi = hi * 10 + carry + end + if hi > 0x80000000 or (hi == 0x80000000 and (lo > 0 or neg == "")) then + return nil, nil + end + if neg == "-" and (hi > 0 or lo > 0) then + lo = (TWO32 - lo) % TWO32 + hi = (TWO32 - 1 - hi + (if lo == 0 then 1 else 0)) % TWO32 + end + return hi, lo + end + return nil, nil +end + +-- ------------------------------------------------------------------------------------------------ constructors +local function tag(name: string, v: any): Tag + return setmetatable({ type = name, value = v }, TagMeta) :: any +end +function Value.byte(n: number): Tag + return tag("byte", n) +end +function Value.short(n: number): Tag + return tag("short", n) +end +function Value.int(n: number): number + return n +end +-- long(n | "decimal") -> a long tag (decimal text within 2^53 becomes a number) +function Value.long(v: number | string): Tag + if type(v) == "string" then + local hi, lo = Value.toHiLo(v) + if hi then + v = Value.fromHiLo(hi, lo :: number) + end + end + return tag("long", v) +end +local f32 = buffer.create(4) +-- float(n) -> a float tag holding n rounded to single precision +function Value.float(n: number): Tag + buffer.writef32(f32, 0, n) + return tag("float", buffer.readf32(f32, 0)) +end +function Value.double(n: number): Tag + return tag("double", n) +end +function Value.intArray(t: { number }?): Tag + return tag("intArray", t or {}) +end +-- longArray(values | buffer) -> a longArray tag (values: numbers / decimal texts; a buffer: 8 bytes each, LE) +function Value.longArray(t: { any } | buffer | nil): Tag + if type(t) == "buffer" then + return tag("longArray", t) + end + local list: { any } = (t or {}) :: any + local b = buffer.create(#list * 8) + for i, x in list do + local hi, lo = Value.toHiLo(x) + buffer.writeu32(b, (i - 1) * 8, lo or 0) + buffer.writeu32(b, (i - 1) * 8 + 4, hi or 0) + end + return tag("longArray", b) +end +-- longs(longArray) -> { number | string }: the elements as long values +function Value.longs(a: Tag): { number | string } + local b: buffer = a.value + local out = table.create(buffer.len(b) // 8) :: { number | string } + for i = 0, buffer.len(b) // 8 - 1 do + out[i + 1] = Value.fromHiLo(buffer.readu32(b, i * 8 + 4), buffer.readu32(b, i * 8)) + end + return out +end +-- list(typeName, items?) -> items marked as a list of that element type (an empty list keeps its type) +function Value.list(name: string, items: { any }?): { any } + local t = items or {} + listTypes[t] = name + return t +end +function Value.compound(t: { [string]: any }?, keys: { string }?): { [string]: any } + return Types.object(t, keys) +end +-- listType(t) -> the element type name recorded for a list (decoded, or made by Value.list) +function Value.listType(t: any): string? + return listTypes[t] +end +function Value.setListType(t: any, name: string) + listTypes[t] = name +end +function Value.isTag(v: any): boolean + return type(v) == "table" and getmetatable(v) == TagMeta +end + +-- typeOf(v) -> the tag name v writes as, or nil + why +function Value.typeOf(v: any): (string?, string?) + local tv = type(v) + if tv == "number" then + return if v % 1 == 0 and v >= -2147483648 and v <= 2147483647 then "int" else "double", nil + elseif tv == "string" then + return "string", nil + elseif tv == "boolean" then + return "byte", nil + elseif tv == "buffer" then + return "byteArray", nil + elseif tv == "table" then + if getmetatable(v) == TagMeta then + local n = v.type + if Value.IDS[n] == nil or n == "end" or n == "list" or n == "compound" or n == "string" or n == "int" or n == "byteArray" then + if n == "int" or n == "string" or n == "byteArray" then + return n, nil + end + return nil, "bad tag type " .. tostring(n) + end + return n, nil + elseif Types.isObject(v) then + return "compound", nil + elseif listTypes[v] or v[1] ~= nil or next(v) == nil then + return "list", nil + end + return "compound", nil + end + return nil, "cannot write a " .. tv .. " as NBT" +end + +-- number(v) -> the numeric value of a number or numeric tag (long texts through tonumber: approximate) +function Value.number(v: any): number? + if type(v) == "number" then + return v + elseif type(v) == "boolean" then + return if v then 1 else 0 + elseif Value.isTag(v) then + local x = v.value + if type(x) == "number" then + return x + elseif type(x) == "string" then + return tonumber(x) + end + end + return nil +end + +return Value diff --git a/src/Formats/codecs/text/Nbt/init.luau b/src/Formats/codecs/text/Nbt/init.luau new file mode 100644 index 0000000..3245410 --- /dev/null +++ b/src/Formats/codecs/text/Nbt/init.luau @@ -0,0 +1,380 @@ +--!strict +-- codecs/text/Nbt: Minecraft's Named Binary Tag format and its text form SNBT, the engine data/nbt, data/snbt, +-- model/schematic and model/mca use. New code (Minecraft wiki "NBT format", wiki.vg "NBT"). +-- Binary: Java big-endian (modified UTF-8 strings), Bedrock little-endian (with or without the 8-byte level.dat +-- header) and Bedrock network NBT (varints), every tag type; files may be gzip or zlib compressed (codecs/compress/ +-- Deflate). SNBT: parse and print (codecs/text/Nbt/Snbt). Values are plain Luau with typed numbers +-- (codecs/text/Nbt/Value): int -> number, string -> string, byteArray -> buffer, compound -> Types.object (key order +-- kept), list -> array, the other numeric and array tags -> { type, value } tags, so round trips are exact. +-- +-- local Nbt = require("@formats/codecs/text/Nbt") +-- local v, info = Nbt.decode(buf) -- a file: compression and edition detected; info = how it was stored +-- print(v.Data.LevelName, v.Data.Time.value) -- int / string plain; long / byte / ... tags have .value +-- v.Data.Difficulty = Nbt.byte(2) +-- local out = Nbt.encode(v) -- written the way it was read (Nbt.info(v)), or opts +-- local text = Nbt.print(v) -- SNBT: {Data:{Difficulty:2b,...}} +-- local w = Nbt.parse('{pos:[I;1,2,3],name:"x"}') +-- local raw, name, endPos = Nbt.read(buf, 0, nil, { endian = "little" }) -- one uncompressed tag +-- +-- Never throws: bad data and bad values return nil, Err. +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Deflate = require("@formats/codecs/compress/Deflate") +local Value = require("@formats/codecs/text/Nbt/Value") +local Binary = require("@formats/codecs/text/Nbt/Binary") +local Snbt = require("@formats/codecs/text/Nbt/Snbt") + +local Nbt = {} + +export type Tag = Value.Tag +export type Info = { + name: string, -- the root tag's name + endian: "big" | "little", + varint: boolean?, -- Bedrock network NBT + compression: "gzip" | "zlib" | "none", + header: number?, -- Bedrock level.dat: the storage version from the 8-byte header +} +export type DecodeOptions = { + endian: ("big" | "little")?, -- default: detected (Java big-endian first) + varint: boolean?, -- Bedrock network NBT + nameless: boolean?, -- no root name (Java network NBT since 1.20.2) + maxDepth: number?, -- nesting limit (default 512) + maxBytes: number?, -- refuse compressed data that inflates past this (default 2^28) +} +export type EncodeOptions = { + endian: ("big" | "little")?, -- default: Nbt.info(value).endian, else "big" + varint: boolean?, + nameless: boolean?, + name: string?, -- the root name (default: Nbt.info(value).name, else "") + compression: ("gzip" | "zlib" | "none")?, -- default: Nbt.info(value).compression, else gzip for big-endian + header: number?, -- write the Bedrock level.dat header with this version + level: number?, -- deflate level 0..9 (default 6) +} + +Nbt.TAG = Value.IDS -- name -> id +Nbt.TAG_NAMES = Value.NAMES -- id -> name +Nbt.byte = Value.byte +Nbt.short = Value.short +Nbt.int = Value.int +Nbt.long = Value.long +Nbt.float = Value.float +Nbt.double = Value.double +Nbt.intArray = Value.intArray +Nbt.longArray = Value.longArray +Nbt.longs = Value.longs +Nbt.list = Value.list +Nbt.listType = Value.listType +Nbt.compound = Value.compound +Nbt.typeOf = Value.typeOf +Nbt.isTag = Value.isTag +Nbt.number = Value.number +Nbt.fromHiLo = Value.fromHiLo +Nbt.toHiLo = Value.toHiLo + +local infos: { [any]: Info } = setmetatable({}, { __mode = "k" }) :: any + +-- info(value) -> how a decoded root was stored (nil for values not from decode) +function Nbt.info(v: any): Info? + return if type(v) == "table" then infos[v] else nil +end +-- setInfo(value, info): what encode uses as defaults +function Nbt.setInfo(v: any, info: Info) + if type(v) == "table" then + infos[v] = info + end +end + +-- read(buf, offset?, length?, opts?) -> value, rootName, endOffset | nil, Err: one uncompressed root tag +function Nbt.read(buf: buffer | string, offset: number?, length: number?, opts: DecodeOptions?): (any, any, number?) + local b, o, l, aerr = Bytes.span("Nbt.read", buf, offset, length) + if not b then + return nil, aerr + end + local v, name, at = Binary.read(b, o, o + l, opts :: any) + if v == nil then + return nil, Err.from(name, (at or o) - o) + end + return v, name, at +end + +-- write(value, opts?) -> buffer | nil, Err: one uncompressed root tag +function Nbt.write(v: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local out, e = Binary.write(v, opts :: any) + if not out then + return nil, Err.new(Err.ARG, tostring(e)) + end + return out, nil +end + +-- unwrap(buf, offset?, length?, maxBytes?) -> data, start, end, compression | nil, Err: gzip / zlib detected by magic +function Nbt.unwrap(buf: buffer | string, offset: number?, length: number?, maxBytes: number?): (buffer?, any, number?, string?) + local b, o, l, aerr = Bytes.span("Nbt.unwrap", buf, offset, length) + if not b then + return nil, aerr + end + local c0 = if l >= 2 then buffer.readu8(b, o) else 0 + local c1 = if l >= 2 then buffer.readu8(b, o + 1) else 0 + local out, err, comp + if c0 == 0x1f and c1 == 0x8b then + out, err = Deflate.gunzip(b, o, l) + comp = "gzip" + elseif c0 % 16 == 8 and c0 < 0x80 and (c0 * 256 + c1) % 31 == 0 then + out, err = Deflate.zlib(b, o, l) + comp = "zlib" + else + return b, o, o + l, "none" + end + if not out then + return nil, err + end + if buffer.len(out) > (maxBytes or 2 ^ 28) then + return nil, Err.new(Err.LIMIT, "inflates to " .. buffer.len(out) .. " bytes, over maxBytes") + end + return out, 0, buffer.len(out), comp +end + +export type Peek = { + compression: string, -- "gzip" | "zlib" | "none" + endian: "big" | "little", + header: boolean, -- a Bedrock level.dat header + rootType: string, -- "compound" (or "list") + name: string, -- the root name + firstType: string?, -- the first child of a root compound (type and name; "end" when empty), when peeked + firstName: string?, + head: buffer, -- the first (up to 1024) uncompressed bytes +} + +local function plausibleName(b: buffer, p: number, n: number): string? + if p + n > buffer.len(b) or n > 256 then + return nil + end + local s = buffer.readstring(b, p, n) + if string.find(s, "[%z\1-\31\127]") then + return nil + end + return s +end + +-- peek(buf, offset?, length?) -> Peek | nil: whether the bytes look like an NBT file (inflating at most 1 KiB of a +-- gzip / zlib stream), and its root's name and first child: what format sniffs look at. Never fails loudly. +function Nbt.peek(buf: buffer, offset: number?, length: number?): Peek? + local o = offset or 0 + local l = length or (buffer.len(buf) - o) + if l < 3 then + return nil + end + local c0, c1 = buffer.readu8(buf, o), buffer.readu8(buf, o + 1) + local head: buffer + local comp = "none" + if c0 == 0x1f and c1 == 0x8b or (c0 % 16 == 8 and c0 < 0x80 and (c0 * 256 + c1) % 31 == 0) then + local h = Deflate.peek(buf, o, l, 1024) + if not h then + return nil + end + head, comp = h, if c0 == 0x1f then "gzip" else "zlib" + else + local n = math.min(l, 1024) + head = buffer.create(n) + buffer.copy(head, 0, buf, o, n) + end + local hn = buffer.len(head) + local function at(p: number, endian: string, header: boolean): Peek? + if p + 3 > hn then + return nil + end + local t = buffer.readu8(head, p) + if t ~= 10 and t ~= 9 then + return nil + end + local function u16(q: number): number + local a, b = buffer.readu8(head, q), buffer.readu8(head, q + 1) + return if endian == "big" then a * 256 + b else b * 256 + a + end + local nl = u16(p + 1) + local name = plausibleName(head, p + 3, nl) + if not name then + return nil + end + local res: Peek = { compression = comp, endian = endian :: any, header = header, rootType = Value.NAMES[t], name = name, head = head } + local q = p + 3 + nl + if t == 10 and q < hn then + local ft = buffer.readu8(head, q) + if ft > 12 then + return nil + end + if ft == 0 then + res.firstType = "end" -- an empty root compound + elseif q + 3 <= hn then + local fname = plausibleName(head, q + 3, u16(q + 1)) + if fname == nil and q + 3 + u16(q + 1) <= hn then + return nil + end + res.firstType, res.firstName = Value.NAMES[ft], fname + end + end + return res + end + if hn >= 12 and buffer.readu32(head, 4) == (if comp == "none" then l else -1) - 8 then + local r = at(8, "little", true) + if r then + return r + end + end + return at(0, "big", false) or at(0, "little", false) +end + +-- decode(buf | string, opts?, offset?, length?) -> value, Info | nil, Err: a whole NBT file (gzip / zlib / raw; Java +-- or Bedrock) +function Nbt.decode(buf: buffer | string, opts: DecodeOptions?, offset: number?, length: number?): (any, any) + local o: DecodeOptions = opts or {} + local b, s, e, comp = Nbt.unwrap(buf, offset, length, o.maxBytes) + if not b then + return nil, s + end + local data: buffer, start: number, stop: number = b, s, e :: number + local function try(endian: string, from: number, varint: boolean?): (any, any, number?) + return Binary.read(data, from, stop, { endian = endian :: any, varint = varint, nameless = o.nameless, maxDepth = o.maxDepth }) + end + local header: number? = nil + local v, name, at + if o.varint then + v, name, at = try("little", start, true) + elseif o.endian then + local from = start + if o.endian == "little" and stop - start >= 8 and buffer.readu32(data, start + 4) == stop - start - 8 then + header, from = buffer.readu32(data, start), start + 8 + end + v, name, at = try(o.endian, from) + else + -- Bedrock level.dat: version, length (u32le), then little-endian NBT + if stop - start >= 9 and buffer.readu32(data, start + 4) == stop - start - 8 and buffer.readu8(data, start + 8) == 10 then + v, name, at = try("little", start + 8) + if v ~= nil then + header = buffer.readu32(data, start) + o = table.clone(o) + o.endian = "little" + end + end + if v == nil then + local bv, bn, ba = try("big", start) + if bv ~= nil and ba == stop then + v, name, at, o = bv, bn, ba, table.clone(o) + o.endian = "big" + else + local lv, ln, la = try("little", start) + if lv ~= nil and (la == stop or bv == nil) then + v, name, at, o = lv, ln, la, table.clone(o) + o.endian = "little" + elseif bv ~= nil then + v, name, at, o = bv, bn, ba, table.clone(o) + o.endian = "big" + else + v, name, at = nil, bn, ba + end + end + end + end + if v == nil then + return nil, Err.from(name, (at or start) - start) + end + local info: Info = { + name = name, + endian = if o.varint or o.endian == "little" then "little" else "big", + varint = if o.varint then true else nil, + compression = comp :: any, + header = header, + } + if type(v) == "table" then + infos[v] = info + end + return v, info +end + +-- encode(value, opts?) -> buffer | nil, Err: a whole NBT file +function Nbt.encode(v: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local info = Nbt.info(v) + local endian = o.endian or (info and info.endian) or "big" + local varint = if o.varint ~= nil then o.varint else (info and info.varint) + local raw, e = Binary.write(v, { + endian = endian, + varint = varint, + nameless = o.nameless, + name = o.name or (info and info.name) or "", + }) + if not raw then + return nil, Err.new(Err.ARG, tostring(e)) + end + local header = if o.header ~= nil then o.header else (info and info.header) + if header then + local h = buffer.create(buffer.len(raw) + 8) + buffer.writeu32(h, 0, header) + buffer.writeu32(h, 4, buffer.len(raw)) + buffer.copy(h, 8, raw) + raw = h + end + local comp = o.compression or (info and info.compression) or (if endian == "big" then "gzip" else "none") + if comp == "gzip" then + return Deflate.gzip(raw, { level = o.level }) + elseif comp == "zlib" then + return Deflate.zlibCompress(raw, { level = o.level }) + elseif comp ~= "none" then + return nil, Err.new(Err.ARG, "unknown compression " .. tostring(comp)) + end + return raw, nil +end + +-- parse(text, opts?) -> value | nil, Err: SNBT +function Nbt.parse(text: string | buffer, opts: Snbt.ParseOptions?): (any, Err.Err?) + local s = if type(text) == "buffer" then buffer.tostring(text) else text + if type(s) ~= "string" then + return nil, Err.new(Err.ARG, "Nbt.parse: text must be a string") + end + local v, e, at = Snbt.parse(s, opts) + if v == nil then + return nil, Err.from(e, (at or 1) - 1) + end + return v, nil +end + +-- print(value, opts?) -> text | nil, Err: SNBT (compact, or opts.indent) +function Nbt.print(v: any, opts: Snbt.PrintOptions?): (string?, Err.Err?) + local s, e = Snbt.print(v, opts) + if not s then + return nil, Err.new(Err.ARG, tostring(e)) + end + return s, nil +end + +-- get(value, path) -> the value at a dotted path ("Data.Player.Pos[1]"; list indices 0-based like Minecraft's) +function Nbt.get(v: any, path: string): any + local cur = v + for part in string.gmatch(path, "[^%.]+") do + local k, rest = string.match(part, "^([^%[]*)(.*)$") + if k ~= "" then + if type(cur) ~= "table" or Value.isTag(cur) then + return nil + end + cur = cur[k] + end + for idx in string.gmatch(rest :: string, "%[(%-?%d+)%]") do + local i = tonumber(idx) :: number + if type(cur) == "table" and not Value.isTag(cur) then + cur = cur[i + 1] + elseif Value.isTag(cur) and type(cur.value) == "table" then + cur = cur.value[i + 1] + elseif type(cur) == "buffer" and i >= 0 and i < buffer.len(cur) then + cur = buffer.readi8(cur, i) + else + return nil + end + end + end + return cur +end + +Nbt.object = Types.object +Nbt.shortest = Snbt.shortest + +return Nbt diff --git a/src/Formats/data/nbt/init.luau b/src/Formats/data/nbt/init.luau new file mode 100644 index 0000000..407aed8 --- /dev/null +++ b/src/Formats/data/nbt/init.luau @@ -0,0 +1,60 @@ +--!strict +-- data/nbt: Minecraft NBT files (.nbt structures, level.dat / playerdata .dat, servers.dat, Bedrock .mcstructure and +-- level.dat), a thin format over codecs/text/Nbt (which see for the value mapping). Supports: Java big-endian and +-- Bedrock little-endian NBT (the level.dat 8-byte header too; network varint NBT with opts.varint), gzip / zlib / +-- uncompressed, every tag type, exact round trips (Nbt.info(value) remembers the root name, edition, compression +-- and header; encode writes it back the same way unless opts say otherwise). Text SNBT: data/snbt. +-- Not supported: nothing in the format. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Nbt = require("@formats/codecs/text/Nbt") + +-- ------------------------------------------------------------------------------------------------ contract +local NbtFormat = { + name = "nbt", + category = "data", + extensions = { "nbt", "dat", "mcstructure", "dat_old" }, + mime = { "application/x-minecraft-nbt" }, + deps = { "core/Err", "core/Bytes", "codecs/text/Nbt" }, + caps = { decode = true, encode = true, binary = true, ordered = true, typed = true }, +} + +export type DecodeOptions = Nbt.DecodeOptions +export type EncodeOptions = Nbt.EncodeOptions + +-- ------------------------------------------------------------------------------------------------ sniff +function NbtFormat.sniff(r: Bytes.Reader): number + local p = Nbt.peek(r.buf, r.base, r.limit - r.base) + if not p or p.rootType ~= "compound" then + return 0 + end + if p.compression ~= "none" then + return if p.firstType then 1 else 0.5 -- gzip wrapped NBT: ties with archive/gzip go to the extension + end + return if p.firstType and p.firstName then 0.6 else 0.2 +end + +-- ------------------------------------------------------------------------------------------------ decode +function NbtFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local v, info = Nbt.decode(r.buf, opts, r.base, r.limit - r.base) + if v == nil then + return nil, info + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function NbtFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + if value == nil then + return nil, Err.new(Err.ARG, "nothing to encode") + end + return Nbt.encode(value, opts) +end + +-- ------------------------------------------------------------------------------------------------ extras +NbtFormat.info = Nbt.info -- how a decoded value was stored: { name, endian, compression, header?, varint? } +NbtFormat.Nbt = Nbt + +return NbtFormat diff --git a/src/Formats/data/snbt/init.luau b/src/Formats/data/snbt/init.luau new file mode 100644 index 0000000..a128f3e --- /dev/null +++ b/src/Formats/data/snbt/init.luau @@ -0,0 +1,63 @@ +--!strict +-- data/snbt: stringified NBT text (Minecraft commands, datapacks, .snbt structure files), a thin format over +-- codecs/text/Nbt (which see for the value mapping and grammar). Supports: parse to the same typed values data/nbt +-- gives (convert between the two freely), print compact (Minecraft's form) or indented (opts.indent). +-- Not supported: the 1.21.5 bool(...) / uuid(...) operations. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Sniff = require("@formats/core/Sniff") +local Nbt = require("@formats/codecs/text/Nbt") + +-- ------------------------------------------------------------------------------------------------ contract +local SnbtFormat = { + name = "snbt", + category = "data", + extensions = { "snbt" }, + mime = { "text/x-minecraft-snbt" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "codecs/text/Nbt" }, + caps = { decode = true, encode = true, ordered = true, typed = true }, +} + +export type DecodeOptions = { maxDepth: number? } +export type EncodeOptions = { + indent: (number | string)?, -- pretty print: spaces per level or the indent string (default: compact) + quote: string?, -- '"' (default) or "'" +} + +-- ------------------------------------------------------------------------------------------------ sniff +function SnbtFormat.sniff(r: Bytes.Reader): number + -- SNBT has what JSON never has: unquoted keys, typed numbers (1b, 2.5f), [I; arrays, single-quoted strings + local head = Sniff.text(r, 512, true) + local first = string.sub(head, 1, 1) + if first ~= "{" and first ~= "[" then + return 0 + end + if string.find(head, "[{,]%s*[%a_][%w_%-%.%+]*%s*:") or string.find(head, "%d[bBsSlLfFdD]%s*[,}%]]") + or string.find(head, "%[[BIL]%s*;") or string.find(head, "[:,%[]%s*'") + then + return 0.7 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function SnbtFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local text = Sniff.dropBom(buffer.readstring(r.buf, r.base, r.limit - r.base)) + return Nbt.parse(text, opts) +end + +-- ------------------------------------------------------------------------------------------------ encode +function SnbtFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + if value == nil then + return nil, Err.new(Err.ARG, "nothing to encode") + end + local s, e = Nbt.print(value, opts) + if not s then + return nil, e + end + return buffer.fromstring(s), nil +end + +return SnbtFormat diff --git a/tests/codecs/deflate.luau b/tests/codecs/deflate.luau index d9ee80a..319dfdc 100644 --- a/tests/codecs/deflate.luau +++ b/tests/codecs/deflate.luau @@ -169,4 +169,23 @@ do end, samples, { mutations = 3, garbage = 300 }) end +-- peek: the first bytes of a gzip / zlib / raw stream without inflating the rest +do + local src = buffer.create(100000) + for i = 0, 99999 do + buffer.writeu8(src, i, (i * 7 + (i // 97)) % 251) + end + local want = buffer.readstring(src, 0, 1000) + for _, kind in { "gzip", "zlibCompress", "compress" } do + local z = assert((Deflate :: any)[kind](src)) :: buffer + local head = assert(Deflate.peek(z, nil, nil, 1000)) + t:check(buffer.len(head) <= 1000 and buffer.len(head) >= 1000 - 258, "peek " .. kind .. " size") + t:eq(buffer.tostring(head), string.sub(want, 1, buffer.len(head)), "peek " .. kind .. " bytes") + end + local small = assert(Deflate.peek(assert(Deflate.gzip(buffer.fromstring("hello"))), nil, nil, 1000)) + t:eq(buffer.tostring(small), "hello", "peek a short stream") + local _, e = Deflate.peek(buffer.fromstring("\31\139\8\0\0\0\0\0\0\3\255\255\255\255\255\255\255\255"), nil, nil, 10) + t:check(e ~= nil, "peek bad data") +end + t:done() diff --git a/tests/codecs/nbt.luau b/tests/codecs/nbt.luau new file mode 100644 index 0000000..ba602a3 --- /dev/null +++ b/tests/codecs/nbt.luau @@ -0,0 +1,256 @@ +-- codecs/text/Nbt tests: random trees written by Python's nbtlib (Java big-endian, Bedrock little-endian, gzip, zlib, +-- the level.dat header) decode to nbtlib's typed values (a canonical dump), re-encode to nbtlib's exact bytes in both +-- byte orders, nbtlib's SNBT (indented and compact) parses to the same values and our SNBT reads back exactly; +-- Bedrock network varint NBT; modified UTF-8; long extremes; SNBT grammar details; peek; errors; the fuzz pass. +-- Fixtures: tools/fixtures/nbt.py. +local T = require("@tests/T") +local Nbt = require("@formats/codecs/text/Nbt") +local Types = require("@formats/Types") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/nbt") + +local t = T.suite("nbt") + +local function hexOf(b: buffer, o: number, n: number, rev: boolean): string + local parts = {} + for i = 0, n - 1 do + parts[i + 1] = string.format("%02x", buffer.readu8(b, if rev then o + n - 1 - i else o + i)) + end + return table.concat(parts) +end + +-- the canonical dump tools/fixtures/nbt.py writes +local function canon(v: any): string + local ty = Nbt.typeOf(v) + local x = if Nbt.isTag(v) then v.value else v + if ty == "byte" or ty == "short" or ty == "int" or ty == "long" then + local n = if type(x) == "boolean" then (if x then 1 else 0) else x + return string.sub(ty :: string, 1, 1) .. (if type(n) == "string" then n else string.format("%d", n)) + elseif ty == "float" then + local b = buffer.create(4) + buffer.writef32(b, 0, x) + return "f" .. hexOf(b, 0, 4, true) + elseif ty == "double" then + local b = buffer.create(8) + buffer.writef64(b, 0, x) + return "d" .. hexOf(b, 0, 8, true) + elseif ty == "string" then + return "S" .. #x .. ":" .. x + elseif ty == "byteArray" then + return "B" .. hexOf(x, 0, buffer.len(x), false) + elseif ty == "intArray" then + local p = {} + for i, n in x do + p[i] = string.format("%d", n) + end + return "I[" .. table.concat(p, ",") .. "]" + elseif ty == "longArray" then + local p = {} + for i, n in Nbt.longs(v) do + p[i] = if type(n) == "string" then n else string.format("%d", n) + end + return "L[" .. table.concat(p, ",") .. "]" + elseif ty == "list" then + local p = {} + for i, e in v do + p[i] = canon(e) + end + return "[" .. (Nbt.listType(v) or "?") .. "|" .. table.concat(p, ",") .. "]" + end + local p = {} + for _, k in Types.keys(v) do + table.insert(p, #k .. ":" .. k .. "=" .. canon(v[k])) + end + return "{" .. table.concat(p, ";") .. "}" +end + +local function same(a: buffer, b: string): boolean + return buffer.tostring(a) == b +end + +-- 1. nbtlib trees +for _, c in Fx.cases do + local v, info = Nbt.decode(c.raw) + t:check(v ~= nil, c.name .. ": decode " .. tostring(info)) + t:eq(canon(v), c.canon, c.name .. ": value") + t:eq(info.name, c.root, c.name .. ": root name") + t:check(info.endian == "big" and info.compression == "none", c.name .. ": info") + local out = Nbt.encode(v) :: buffer + t:check(out and same(out, c.raw), c.name .. ": same bytes (big-endian)") + local le = Nbt.encode(v, { endian = "little" }) :: buffer + t:check(le and same(le, c.little), c.name .. ": same bytes (little-endian)") + for _, k in { "little", "gzip", "zlib", "header" } do + local w, wi = Nbt.decode(c[k]) + t:check(w ~= nil, c.name .. ": decode " .. k .. " " .. tostring(wi)) + t:eq(canon(w), c.canon, c.name .. ": " .. k .. " value") + if #c.raw > 4 then -- an empty compound with an empty name reads the same either way + t:eq(wi.endian, if k == "little" or k == "header" then "little" else "big", c.name .. ": " .. k .. " endian") + end + t:eq(wi.compression, if k == "gzip" or k == "zlib" then k else "none", c.name .. ": " .. k .. " compression") + -- written back the same way it was read + local again = Nbt.encode(w) :: buffer + local w2, wi2 = Nbt.decode(again) + t:eq(canon(w2), c.canon, c.name .. ": " .. k .. " round trip") + t:eq(wi2.compression, wi.compression, c.name .. ": " .. k .. " keeps compression") + t:eq(wi2.header, wi.header, c.name .. ": " .. k .. " keeps the header") + if k == "header" then + t:eq(wi.header, c.version, c.name .. ": header version") + t:check(same(again, c.header), c.name .. ": header same bytes") + end + end + -- SNBT: nbtlib's text parses to the same values (an empty list's type is not in the text); ours reads back + -- exactly (both forms) + local function untyped(s: string): string + return (string.gsub(s, "%[%a+|%]", "[|]")) + end + for _, k in { "snbt", "compact" } do + local s, e = Nbt.parse(c[k]) + t:check(s ~= nil, c.name .. ": parse " .. k .. " " .. tostring(e)) + t:eq(untyped(canon(s)), untyped(c.canon), c.name .. ": " .. k .. " value") + end + for _, o in { {}, { indent = 2 }, { quote = "'" } } do + local text = Nbt.print(v, o) :: string + local back, e = Nbt.parse(text) + t:check(back ~= nil, c.name .. ": our SNBT parses " .. tostring(e)) + t:eq(untyped(canon(back)), untyped(c.canon), c.name .. ": our SNBT round trip") + end +end + +-- 2. Bedrock network NBT +for i, c in Fx.net do + local v, info = Nbt.decode(c.data, { varint = true }) + t:check(v ~= nil, "net " .. i .. ": " .. tostring(info)) + t:eq(canon(v), c.canon, "net " .. i .. ": value") + t:check(same(Nbt.encode(v, { varint = true }) :: buffer, c.data), "net " .. i .. ": same bytes") +end + +-- 3. details +do + -- longs: exact past 2^53, both directions + for _, s in { "9223372036854775807", "-9223372036854775808", "9007199254740993", "-9007199254740993", "4294967296", "-1" } do + local hi, lo = Nbt.toHiLo(s) + t:check(hi ~= nil, "toHiLo " .. s) + t:eq(tostring(Nbt.fromHiLo(hi :: number, lo :: number)), s, "long text " .. s) + end + t:eq(Nbt.toHiLo("9223372036854775808"), nil, "long overflow") + t:eq(Nbt.long("12").value, 12, "small long text becomes a number") + -- modified UTF-8: NUL as C0 80 and U+1F600 as a surrogate pair in Java files, plain UTF-8 in Bedrock ones + local v = Nbt.compound({ s = "a\0b\u{1F600}" }, { "s" }) + local big = Nbt.write(v) :: buffer + t:check(string.find(buffer.tostring(big), "a\192\128b\237\160\189\237\184\128", 1, true) ~= nil, "modified UTF-8 out") + t:eq((Nbt.read(big)).s, "a\0b\u{1F600}", "modified UTF-8 in") + local little = Nbt.write(v, { endian = "little" }) :: buffer + t:check(string.find(buffer.tostring(little), "a\0b\u{1F600}", 1, true) ~= nil, "Bedrock strings are UTF-8") + -- lenient inputs: plain numbers, booleans, plain tables + local p = Nbt.read(Nbt.write({ a = 1.5, b = true, c = { 1, 2 }, d = {}, e = 2 ^ 40 }) :: buffer) + t:check(p.a.type == "double" and p.b.type == "byte" and p.b.value == 1, "plain number / boolean") + t:check(Nbt.listType(p.c) == "int" and Nbt.listType(p.d) == "end" and p.e.type == "double", "plain lists") + -- mixed lists are wrapped in compounds, as Minecraft 1.21.5 does + local m = Nbt.read(Nbt.write({ l = { 1, "x" } }) :: buffer) + t:check(Nbt.listType(m.l) == "compound" and m.l[1][""] == 1 and m.l[2][""] == "x", "heterogeneous list") + -- empty typed list keeps its type + local et = Nbt.read(Nbt.write({ l = Nbt.list("compound") }) :: buffer) + t:eq(Nbt.listType(et.l), "compound", "empty typed list") + -- tostring of tags is SNBT; == compares type and value + t:eq(tostring(Nbt.byte(3)), "3b", "tostring byte") + t:eq(tostring(Nbt.float(0.1)), "0.1f", "tostring float (shortest)") + t:check(Nbt.short(5) == Nbt.short(5) and Nbt.short(5) ~= Nbt.int(5) :: any, "tag equality") + -- get + local g = assert(Nbt.parse("{Data:{Pos:[1.0d,2.5d,3.0d],Inv:[{id:\"x\"}]}}")) + t:eq(Nbt.get(g, "Data.Pos[1]").value, 2.5, "get list element") + t:eq(Nbt.get(g, "Data.Inv[0].id"), "x", "get nested") + t:eq(Nbt.get(g, "Data.Missing.x"), nil, "get missing") +end + +-- 4. SNBT grammar +do + local cases: { { string } } = { + { "1b", "byte:1" }, { "-5S", "short:-5" }, { "7", "int:7" }, { "7i", "int:7" }, { "1_000", "int:1000" }, + { "123L", "long:123" }, { "0x1F", "int:31" }, { "0xFFub", "byte:-1" }, { "0x7Fsb", "byte:127" }, + { "0b101", "int:5" }, { "0b", "byte:0" }, { "200ub", "byte:-56" }, { "1.5", "double:1.5" }, { ".5f", "float:0.5" }, + { "2e3", "double:2000" }, { "3f", "float:3" }, { "4D", "double:4" }, { "true", "byte:1" }, { "false", "byte:0" }, + { "abc", "string:abc" }, { "1.2.3", "string:1.2.3" }, { "'it''", "" }, { "'a\\'b'", "string:a'b" }, + { '"\\u00e9\\x41\\n"', "string:\u{e9}A\n" }, { "-Infinityd", "double:-inf" }, + } + for _, c in cases do + local v = Nbt.parse(c[1]) + if c[2] == "" then + t:eq(v, nil, "snbt " .. c[1] .. " fails") + else + local ty = Nbt.typeOf(v) :: string + local x = Nbt.number(v) + local got = ty .. ":" .. (if ty == "string" then v elseif x == -math.huge then "-inf" else string.format("%.17g", x :: number)) + t:eq(got, c[2], "snbt " .. c[1]) + end + end + local a = assert(Nbt.parse("[B; 1b, -2b, 3]")) + t:check(typeof(a) == "buffer" and buffer.len(a) == 3 and buffer.readi8(a, 1) == -2, "byte array") + local ia = assert(Nbt.parse("[I;]")) + t:check(ia.type == "intArray" and #ia.value == 0, "empty int array") + local la = assert(Nbt.parse("[L; -9223372036854775808L, 5L]")) + t:eq(Nbt.longs(la)[1], "-9223372036854775808", "long array extreme") + local tc = assert(Nbt.parse("{a:1,b:[1,2,],}")) + t:check(tc.a == 1 and #tc.b == 2, "trailing commas") + t:eq(Nbt.print(assert(Nbt.parse('{"a b":1,c:"say \\"hi\\""}'))), "{\"a b\":1,c:'say \"hi\"'}", "quoting") + local _, e1 = Nbt.parse("{a:1") + t:check(e1 and e1.code == Err.CORRUPT, "unterminated compound") + local _, e2 = Nbt.parse("{a:300b}") + t:check(e2 and e2.code == Err.CORRUPT, "byte out of range") + local _, e3 = Nbt.parse(string.rep("[", 600) .. string.rep("]", 600)) + t:check(e3 and e3.code == Err.LIMIT, "depth limit") +end + +-- 5. peek +do + local c = Fx.cases[2] + for _, k in { "raw", "gzip", "zlib", "header" } do + local p = Nbt.peek(buffer.fromstring(c[k])) + t:check(p ~= nil and p.name == c.root and p.rootType == "compound", "peek " .. k) + end + t:eq(Nbt.peek(buffer.fromstring("hello world")), nil, "peek text") +end + +-- 6. errors +do + local _, e = Nbt.decode("\10\0\0\1\0\1a") + t:check(e and e.code == Err.TRUNCATED, "truncated") + local _, e2 = Nbt.decode("\13\0\0") + t:check(e2 and e2.code == Err.CORRUPT, "bad root type") + local _, e3 = Nbt.decode("\10\0\0\9\0\1l\1\127\255\255\255") + t:check(e3 and e3.code == Err.TRUNCATED, "huge list length") + local deep = {} + local cur = deep + for _ = 1, 600 do + local n = {} + cur.x = n + cur = n + end + local _, e4 = Nbt.encode(deep) + t:check(e4 and e4.code == Err.ARG, "encode depth") + local _, e5 = Nbt.encode({ a = Nbt.byte(300) }) + t:check(e5 and e5.code == Err.ARG, "encode byte range") + local _, e6 = Nbt.encode({ a = function() end }) + t:check(e6 and e6.code == Err.ARG, "encode function") +end + +-- 7. fuzz +local samples = {} +for i = 1, 8 do + table.insert(samples, Fx.cases[i].raw) + table.insert(samples, Fx.cases[i].little) +end +table.insert(samples, Fx.cases[3].gzip) +t:fuzz("decode", function(b: buffer) + return Nbt.decode(b) +end, samples) +t:fuzz("decode varint", function(b: buffer) + return Nbt.decode(b, { varint = true }) +end, { Fx.net[1].data, Fx.net[2].data }) +local texts = {} +for i = 1, 6 do + table.insert(texts, Fx.cases[i].compact) +end +t:fuzz("parse", function(b: buffer) + return Nbt.parse(buffer.tostring(b)) +end, texts) +t:done() diff --git a/tests/data/nbt.luau b/tests/data/nbt.luau new file mode 100644 index 0000000..3268473 --- /dev/null +++ b/tests/data/nbt.luau @@ -0,0 +1,60 @@ +-- data/nbt tests: the contract, nbtlib files through the api (F.load / F.save, NBT -> SNBT -> NBT), detection by +-- content and extension, exact round trips (root name, edition, compression and the Bedrock header kept), error +-- codes, and the fuzz pass. The engine itself: tests/codecs/nbt.luau; SNBT files: tests/data/snbt.luau. +-- Fixtures: tools/fixtures/nbt.py. +local T = require("@tests/T") +local F = require("@formats") +local NbtF = require("@formats/data/nbt") +local SnbtF = require("@formats/data/snbt") +local Nbt = require("@formats/codecs/text/Nbt") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/nbt") + +local t = T.suite("data/nbt") + +t:eq(NbtF.name, "nbt", "name") +t:eq(SnbtF.name, "snbt", "snbt name") +t:check(NbtF.caps.decode and NbtF.caps.encode and SnbtF.caps.decode and SnbtF.caps.encode, "caps") + +for i = 1, 12 do + local c = Fx.cases[i] + local v = F.load(c.gzip, { name = "level.dat" }) + t:check(v ~= nil, c.name .. ": F.load gzip") + local text = assert(F.saveString(v, { format = "snbt" })) + local back = assert(F.load(text, { format = "snbt" })) + t:eq(Nbt.print(back), Nbt.print(v), c.name .. ": NBT -> SNBT -> value") + local again = assert(F.save(v, nil, { format = "nbt" })) :: buffer + t:eq(buffer.readu8(again, 0), 0x1f, c.name .. ": saved gzip like the source") + t:eq(Nbt.print(F.load(again, { format = "nbt" })), Nbt.print(v), c.name .. ": saved file reads back") + t:eq(Nbt.info(F.load(again, { format = "nbt" })).name, c.root, c.name .. ": root name kept") + local raw = assert(F.save(v, nil, { format = "nbt", compression = "none" })) :: buffer + t:eq(buffer.tostring(raw), c.raw, c.name .. ": uncompressed = nbtlib's bytes") + local le = assert(F.load(c.header, { format = "nbt" })) + t:eq(buffer.tostring(assert(F.save(le, nil, { format = "nbt" })) :: buffer), c.header, c.name .. ": Bedrock level.dat same bytes") +end + +-- detection +do + local c = Fx.cases[3] + t:eq(F.detect(c.gzip, { name = "level.dat" }), "nbt", "detect gzip .dat") + t:eq(F.detect(c.raw, { name = "x.nbt" }), "nbt", "detect raw .nbt") +end + +-- errors +do + local _, e = NbtF.decode(Bytes.reader(buffer.fromstring("\10\0\0\1"))) + t:check(e and e.code == Err.TRUNCATED, "truncated") + local _, e3 = NbtF.encode(nil :: any) + t:check(e3 and e3.code == Err.ARG, "encode nil") +end + +local samples = {} +for i = 1, 6 do + table.insert(samples, Fx.cases[i].raw) + table.insert(samples, Fx.cases[i].header) +end +t:fuzz("decode", function(b: buffer) + return NbtF.decode(Bytes.reader(b)) +end, samples) +t:done() diff --git a/tests/data/snbt.luau b/tests/data/snbt.luau new file mode 100644 index 0000000..9b88fee --- /dev/null +++ b/tests/data/snbt.luau @@ -0,0 +1,47 @@ +-- data/snbt tests: the contract, nbtlib's SNBT text (indented and compact) through the api, conversion to and from +-- binary NBT (F.convert), detection against JSON, options (indent, quote), error codes, and the fuzz pass. The +-- grammar itself: tests/codecs/nbt.luau. Fixtures: tools/fixtures/nbt.py. +local T = require("@tests/T") +local F = require("@formats") +local SnbtF = require("@formats/data/snbt") +local Nbt = require("@formats/codecs/text/Nbt") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/nbt") + +local t = T.suite("data/snbt") + +t:eq(SnbtF.name, "snbt", "name") +t:check(SnbtF.caps.decode and SnbtF.caps.encode, "caps") + +for i = 1, 12 do + local c = Fx.cases[i] + local v = assert(F.load(c.snbt, { format = "snbt" })) + local bin = assert(F.convert(c.compact, "nbt", { format = "snbt", compression = "none" })) :: buffer + t:eq(Nbt.print(assert(Nbt.decode(bin))), Nbt.print(v), c.name .. ": SNBT -> NBT") + local text = assert(F.convert(c.raw, "snbt", { format = "nbt" })) :: buffer + t:eq(Nbt.print(assert(Nbt.parse(text))), Nbt.print(v), c.name .. ": NBT -> SNBT") + local pretty = assert(F.saveString(v, { format = "snbt", indent = "\t" })) + t:eq(Nbt.print(assert(F.load(pretty, { format = "snbt" }))), Nbt.print(v), c.name .. ": indented") +end + +do + t:eq(F.detect("{DataVersion:3465,size:[I;1,2,3]}"), "snbt", "detect snbt") + t:eq(F.detect('{"a": 1}'), "json", "json is not snbt") + t:eq(F.detect('{"a": 1b}'), "snbt", "typed number") + t:eq(F.detect(Fx.cases[3].compact, { name = "x.snbt" }), "snbt", "detect .snbt") + t:eq(F.saveString(Nbt.parse("{a:'x'}"), { format = "snbt", quote = "'" }), "{a:'x'}", "quote option") + local _, e = SnbtF.decode(Bytes.reader(buffer.fromstring("{a:"))) + t:check(e and e.code == Err.CORRUPT, "corrupt") + local _, e2 = SnbtF.encode({ a = function() end } :: any) + t:check(e2 and e2.code == Err.ARG, "encode a function") +end + +local texts = {} +for i = 1, 6 do + table.insert(texts, Fx.cases[i].snbt) +end +t:fuzz("decode", function(b: buffer) + return SnbtF.decode(Bytes.reader(b)) +end, texts) +t:done() diff --git a/tools/fixtures/nbt.py b/tools/fixtures/nbt.py new file mode 100644 index 0000000..4bb2364 --- /dev/null +++ b/tools/fixtures/nbt.py @@ -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 s i l f d S: B I[a,b] L[a,b] +# [|a,b] {:=;...} (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(">= 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(" Date: Sat, 31 Oct 2026 14:16:35 -0500 Subject: [PATCH 04/27] ws-video2-theora: codecs/video/Theora, a Theora decoder (port of libtheora 1.2.0, BSD) Headers (identification, comment via VorbisComment, setup: loop-filter limits, quant ranges -> dequant tables, the 80 Huffman trees as collapsed lookup tables), intra / inter frames, coded SB / block flags, MB modes (8 alphabets), MVs (VLC / CLC, last / prior, 4MV with per-format chroma averages, half / quarter-pel), block qi, DCT tokens with EOB runs, DC prediction, the spec IDCT, loop filter, golden / previous refs, 4:2:0 / 4:2:2 / 4:4:4, picture-region crop, empty-packet dupes. Bit-exact with ffmpeg on every frame of 12 fixtures (tests/codecs/theora). Outside the folder: codecs/video/Video BUILTIN entry theora gets a decoder (track.config = Xiph-laced headers, as Matroska's CodecPrivate); licenses/libtheora-BSD.txt + NOTICE row. --- docs/FORMATS.md | 1 + licenses/NOTICE.md | 1 + licenses/libtheora-BSD.txt | 28 + src/Formats/codecs/video/Theora/Decoder.luau | 1254 ++++++++++++++++++ src/Formats/codecs/video/Theora/Header.luau | 370 ++++++ src/Formats/codecs/video/Theora/init.luau | 270 ++++ src/Formats/codecs/video/Video/init.luau | 9 +- tests/codecs/theora.luau | 285 ++++ tools/fixtures/theora.py | 195 +++ 9 files changed, 2412 insertions(+), 1 deletion(-) create mode 100644 licenses/libtheora-BSD.txt create mode 100644 src/Formats/codecs/video/Theora/Decoder.luau create mode 100644 src/Formats/codecs/video/Theora/Header.luau create mode 100644 src/Formats/codecs/video/Theora/init.luau create mode 100644 tests/codecs/theora.luau create mode 100644 tools/fixtures/theora.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0a41a66..5f34e95 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -134,4 +134,5 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - **video** - codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the - codecs/video/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from + - codecs/video/Theora: a Theora video decoder (the Theora I specification, Xiph.Org), for Ogg (video/ogv) and Matroska - codecs/video/Video: the video codec registry and the generic VideoDecoder. New in formats-luau. diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index d61e1b4..ef688ee 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -38,6 +38,7 @@ | `tests/fixtures/vp8video/vp80-*.ivf` | the VP8 test vectors of the libvpx test data (vp80-00-comprehensive-001..018 and others) | WebM Project, BSD-3-Clause + patent grant: [libvpx-LICENSE.txt](libvpx-LICENSE.txt) | | `src/Formats/codecs/H264/` (Tables: CAVLC / CABAC / deblocking / scaling constant tables of ITU-T H.264, extracted from openh264 sources; the decoder itself is written from the spec) | openh264 2.x (Cisco) | BSD-2-Clause: [openh264-LICENSE.txt](openh264-LICENSE.txt) | | `tests/gen/h264_jvt` (downloaded at fixture time, not committed) | ITU-T H.264.1 / JVT conformance bitstreams (itu.int) | ITU-T test data | +| `src/Formats/codecs/video/Theora/` (Header, Decoder) | a Luau port of the libtheora 1.2.0 decoder (Xiph.Org; decinfo.c, dequant.c, quant.c, huffdec.c, decode.c, state.c, idct.c, fragment.c) checked against the Theora I specification; the token storage is simplified (coefficients per fragment) and the post-processing is not ported | BSD 3-clause: [libtheora-BSD.txt](libtheora-BSD.txt) | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this folder (see docs/STYLE.md, "Absorbing an existing repo"). diff --git a/licenses/libtheora-BSD.txt b/licenses/libtheora-BSD.txt new file mode 100644 index 0000000..c8ccce4 --- /dev/null +++ b/licenses/libtheora-BSD.txt @@ -0,0 +1,28 @@ +Copyright (C) 2002-2009 Xiph.org Foundation + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +- Neither the name of the Xiph.org Foundation nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/src/Formats/codecs/video/Theora/Decoder.luau b/src/Formats/codecs/video/Theora/Decoder.luau new file mode 100644 index 0000000..d29b8cf --- /dev/null +++ b/src/Formats/codecs/video/Theora/Decoder.luau @@ -0,0 +1,1254 @@ +--!strict +--!native +--!optimize 2 +-- codecs/video/Theora/Decoder: the Theora frame decoder (Theora I specification, section 7; native, never throws). A +-- Luau port of libtheora 1.2.0's decoder (Xiph.Org, BSD 3-clause: licenses/libtheora-BSD.txt; decode.c, state.c, +-- idct.c, fragment.c) with the bit-exact reconstruction of the specification: +-- * frame header, coded super block / block flags (the run-length codes), macro block modes (the 8 mode +-- alphabets), motion vectors (VLC / fixed length, last / prior vectors, 4MV with the chroma averages of each pixel +-- format), per-block qi indices, DC / AC tokens with EOB runs across blocks, planes and coefficients; +-- * DC prediction, dequantisation, the spec's 16-bit integer IDCT (DC-only blocks as libtheora: (dc * q + 15) >> 5), +-- half-pel motion compensation (two-reference average toward zero), the loop filter, border extension for +-- unrestricted motion vectors, golden / previous reference frames; +-- * 4:2:0, 4:2:2 and 4:4:4; empty packets repeat the previous frame. +-- Differences from libtheora: coefficients are kept per fragment (64 i16 each) instead of libtheora's token lists, +-- the frame is reconstructed whole (no MCU pipelining, same result), there is no post-processing (libtheora's default), +-- and intermediate IDCT sums are not wrapped to 16 bits (only out-of-range streams differ). +-- +-- Planes are stored in Theora's own orientation (row 0 is the bottom of the picture) with 16 (luma) / 8 (subsampled +-- chroma) pixels of edge padding; output() turns the picture region into top-down planes. +local Header = require("@formats/codecs/video/Theora/Header") + +local readu8 = buffer.readu8 +local writeu8 = buffer.writeu8 +local readu16 = buffer.readu16 +local readi16 = buffer.readi16 +local writei16 = buffer.writei16 +local readi32 = buffer.readi32 +local writei32 = buffer.writei32 +local readu32 = buffer.readu32 +local bcopy = buffer.copy +local bfill = buffer.fill +local lshift = bit32.lshift +local rshift = bit32.rshift +local bswap = bit32.byteswap + +local D = {} + +-- macro block modes (libtheora's numbering) +local NOMV, INTRA, INTER_MV, MV_LAST, MV_LAST2, GOLD_NOMV, GOLD_MV, FOURMV = 0, 1, 2, 3, 4, 5, 6, 7 +-- reference frames of a fragment (refi) +local GOLD, PREV, SELF, NONE = 0, 1, 2, 3 +local FRAME_FOR_MODE = { [0] = PREV, SELF, PREV, PREV, PREV, GOLD, GOLD, PREV } + +-- the mode alphabets of schemes 1..7 (scheme 0 sends its own) +local ALPHABETS = { + { MV_LAST, MV_LAST2, INTER_MV, NOMV, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { MV_LAST, MV_LAST2, NOMV, INTER_MV, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { MV_LAST, INTER_MV, MV_LAST2, NOMV, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { MV_LAST, INTER_MV, NOMV, MV_LAST2, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { NOMV, MV_LAST, MV_LAST2, INTER_MV, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { NOMV, GOLD_NOMV, MV_LAST, MV_LAST2, INTER_MV, INTRA, GOLD_MV, FOURMV }, + { NOMV, INTRA, INTER_MV, MV_LAST, MV_LAST2, GOLD_NOMV, GOLD_MV, FOURMV }, +} + +-- the macro block mode VLC (0, 10, 110, ..., 1111110, 1111111): by the next 7 bits, index * 8 + length +local MODE_VLC = table.create(128, 0) +for w = 0, 127 do + local n = 0 + while n < 7 and bit32.extract(w, 6 - n, 1) == 1 do + n += 1 + end + MODE_VLC[w + 1] = n * 8 + (if n < 7 then n + 1 else 7) +end + +-- the motion vector component VLC (Theora spec table 7.23): by the next 8 bits, (value + 32) * 16 + length +local MV_VLC = table.create(256, 0) +do + local function put(code: number, len: number, v: number) + local sh = 8 - len + for i = 0, 2 ^ sh - 1 do + MV_VLC[code * 2 ^ sh + i + 1] = (v + 32) * 16 + len + end + end + put(0, 3, 0) + put(1, 3, 1) + put(2, 3, -1) + put(6, 4, 2) + put(7, 4, -2) + put(8, 4, 3) + put(9, 4, -3) + for m = 4, 7 do + put(0x28 + (m - 4) * 2, 6, m) + put(0x29 + (m - 4) * 2, 6, -m) + end + for m = 8, 15 do + put(0x60 + (m - 8) * 2, 7, m) + put(0x61 + (m - 8) * 2, 7, -m) + end + for m = 16, 31 do + put(0xE0 + (m - 16) * 2, 8, m) + put(0xE1 + (m - 16) * 2, 8, -m) + end +end + +-- DCT tokens: extra bits per token +local TOKEN_EXTRA = { + [0] = 0, 0, 0, 2, 3, 4, 12, 3, 6, 0, 0, 0, 0, 1, 1, 1, 1, 2, 3, 4, 5, 6, 10, 1, 1, 1, 1, 1, 3, 4, 2, 3, +} + +-- natural index of zig-zag position (1-based by position + 1) +local ZIGZAG = Header.ZIGZAG + +-- clamp to 0..255 by lookup: CLAMP[v + COFF], v in [-COFF, COFF + 255] +local COFF = 70000 +local CLAMP = buffer.create(2 * COFF + 512) +for i = 0, 2 * COFF + 511 do + buffer.writeu8(CLAMP, i, math.clamp(i - COFF, 0, 255)) +end + +local C1, C2, C3, C4, C5, C6, C7 = 64277, 60547, 54491, 46341, 36410, 25080, 12785 + +export type State = { + pf: number, + hdec: number, + vdec: number, + fw: number, + fh: number, + pw: { number }, -- plane sizes in pixels, [pli + 1] + ph: { number }, + nhf: { number }, -- plane sizes in fragments + nvf: { number }, + foff: { number }, -- first fragment id - 1 of each plane + stride: { number }, + padx: { number }, + pady: { number }, + origin: { number }, -- byte offset of pixel (0, 0) + planeSize: { number }, + nfrags: number, + nsbs: number, + sbPlane: { number }, -- [pli + 1]: the first super block (0-based) of each plane, and [4] = nsbs + sbFr: { number }, -- [sbi * 16 + quad * 4 + bi + 1]: fragment id (1-based) or 0 + sbQuadValid: { boolean }, -- [sbi * 4 + quad + 1] + nmbs: number, + mbMode: { number }, -- [mbi + 1]: -1 outside the frame + mbFr: { number }, -- [mbi * 12 + pli * 4 + bi + 1]: fragment id or 0 + mapIdx: { number }, -- the valid (pli * 4 + bi) slots of a macro block for this pixel format + -- per fragment [fi] + coded: { number }, + refi: { number }, + fmode: { number }, + mvx: { number }, + mvy: { number }, + qii: { number }, + dcv: { number }, + tis: { number }, + last: { number }, + fpos: { number }, -- byte offset of the fragment's first pixel in its plane + fpl: { number }, -- plane (0..2) + coef: buffer, -- i16 [(fi - 1) * 64 + zzi] + clist: { { number } }, -- coded fragments per plane, coded order + ncl: { number }, + act: { { number } }, + refs: { { buffer } }, -- [r][pli + 1] + gold: number, + prev: number, + shown: number, -- the reference holding the last decoded picture + dequant: buffer, + lflim: { number }, + huff: { number }, + roots: { number }, + blk: buffer, -- i32 x 64 work blocks + tmp: buffer, + res: buffer, + bv: { number }, -- the loop filter's bounding values for the frame, [(f + 4) >> 3 + 129] + keyframes: number, +} + +-- new(info, setup) -> State +function D.new(info: Header.Info, setup: Header.Setup): State + local pf = info.pixelFormat + local hdec = if pf % 2 == 0 then 1 else 0 + local vdec = if pf < 2 then 1 else 0 + local fw, fh = info.frameWidth, info.frameHeight + local st: any = { + pf = pf, + hdec = hdec, + vdec = vdec, + fw = fw, + fh = fh, + pw = {}, + ph = {}, + nhf = {}, + nvf = {}, + foff = {}, + stride = {}, + padx = {}, + pady = {}, + origin = {}, + planeSize = {}, + dequant = setup.dequant, + lflim = setup.lflim, + huff = setup.huff, + roots = setup.roots, + blk = buffer.create(256), + tmp = buffer.create(256), + res = buffer.create(256), + bv = table.create(257, 0), + keyframes = 0, + } + local nfr = 0 + for pli = 0, 2 do + local hd, vd = if pli > 0 then hdec else 0, if pli > 0 then vdec else 0 + local w, h = fw // 2 ^ hd, fh // 2 ^ vd + local px, py = 16 // 2 ^ hd, 16 // 2 ^ vd + st.pw[pli + 1], st.ph[pli + 1] = w, h + st.nhf[pli + 1], st.nvf[pli + 1] = w // 8, h // 8 + st.foff[pli + 1] = nfr + nfr += (w // 8) * (h // 8) + st.padx[pli + 1], st.pady[pli + 1] = px, py + local stride = w + 2 * px + st.stride[pli + 1] = stride + st.origin[pli + 1] = py * stride + px + st.planeSize[pli + 1] = stride * (h + 2 * py) + end + st.nfrags = nfr + st.coded = table.create(nfr, 0) + st.refi = table.create(nfr, NONE) + st.fmode = table.create(nfr, 0) + st.mvx = table.create(nfr, 0) + st.mvy = table.create(nfr, 0) + st.qii = table.create(nfr, 0) + st.dcv = table.create(nfr, 0) + st.tis = table.create(nfr, 0) + st.last = table.create(nfr, 0) + st.fpos = table.create(nfr, 0) + st.fpl = table.create(nfr, 0) + st.coef = buffer.create(nfr * 128) + for pli = 0, 2 do + local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] + local stride, origin = st.stride[pli + 1], st.origin[pli + 1] + for fy = 0, nv - 1 do + for fx = 0, nh - 1 do + local fi = st.foff[pli + 1] + fy * nh + fx + 1 + st.fpos[fi] = origin + fy * 8 * stride + fx * 8 + st.fpl[fi] = pli + end + end + end + -- super blocks: 4x4 fragments in Hilbert order (oc_sb_create_plane_mapping) + local SB_MAP = { + { { 0, 0 }, { 0, 1 }, { 3, 2 }, { 3, 3 } }, + { { 0, 3 }, { 0, 2 }, { 3, 1 }, { 3, 0 } }, + { { 1, 0 }, { 1, 3 }, { 2, 0 }, { 2, 3 } }, + { { 1, 1 }, { 1, 2 }, { 2, 1 }, { 2, 2 } }, + } + local sbFr: { number } = {} + local sbQuadValid: { boolean } = {} + local sbPlane: { number } = {} + local sbi = 0 + for pli = 0, 2 do + sbPlane[pli + 1] = sbi + local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] + for y = 0, nv - 1, 4 do + for x = 0, nh - 1, 4 do + for k = 1, 16 do + sbFr[sbi * 16 + k] = 0 + end + for i = 0, math.min(4, nv - y) - 1 do + for j = 0, math.min(4, nh - x) - 1 do + local m = SB_MAP[i + 1][j + 1] + sbFr[sbi * 16 + m[1] * 4 + m[2] + 1] = st.foff[pli + 1] + (y + i) * nh + x + j + 1 + end + end + for q = 0, 3 do + -- the upper left block of each quadrant: index 0, but 2 in quadrant 3 + local tl = if q == 3 then 2 else 0 + sbQuadValid[sbi * 4 + q + 1] = sbFr[sbi * 16 + q * 4 + tl + 1] ~= 0 + end + sbi += 1 + end + end + end + sbPlane[4] = sbi + st.nsbs = sbi + st.sbFr, st.sbQuadValid, st.sbPlane = sbFr, sbQuadValid, sbPlane + -- macro blocks: 4 per luma super block (oc_mb_create_mapping) + local nsbl = sbPlane[2] + local nmbs = nsbl * 4 + local mbMode = table.create(nmbs, 0) + local mbFr = table.create(nmbs * 12, 0) + local MB_MAP = { { 0, 3 }, { 1, 2 } } + local nhl, nvl = st.nhf[1], st.nvf[1] + local nhc = st.nhf[2] + sbi = 0 + for y = 0, nvl - 1, 4 do + for x = 0, nhl - 1, 4 do + for ymb = 0, 1 do + for xmb = 0, 1 do + local mbi = sbi * 4 + MB_MAP[ymb + 1][xmb + 1] + local mbx, mby = x + xmb * 2, y + ymb * 2 + if mbx >= nhl or mby >= nvl then + mbMode[mbi + 1] = -1 + else + local o = mbi * 12 + for i = 0, 1 do + for j = 0, 1 do + mbFr[o + i * 2 + j + 1] = (mby + i) * nhl + mbx + j + 1 + end + end + for pli = 1, 2 do + local base = st.foff[pli + 1] + 1 + if pf == 0 then + mbFr[o + pli * 4 + 1] = base + (mby // 2) * nhc + mbx // 2 + elseif pf == 2 then + for i = 0, 1 do + mbFr[o + pli * 4 + i * 2 + 1] = base + (mby + i) * nhc + mbx // 2 + end + else + for k = 0, 3 do + mbFr[o + pli * 4 + k + 1] = mbFr[o + k + 1] + st.foff[pli + 1] + end + end + end + end + end + end + sbi += 1 + end + end + st.nmbs, st.mbMode, st.mbFr = nmbs, mbMode, mbFr + st.mapIdx = if pf == 0 then { 0, 1, 2, 3, 4, 8 } elseif pf == 2 then { 0, 1, 2, 3, 4, 6, 8, 10 } else { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 } + st.clist = { table.create(st.nhf[1] * st.nvf[1], 0), table.create(st.nhf[2] * st.nvf[2], 0), table.create(st.nhf[3] * st.nvf[3], 0) } + st.act = { table.create(st.nhf[1] * st.nvf[1], 0), table.create(st.nhf[2] * st.nvf[2], 0), table.create(st.nhf[3] * st.nvf[3], 0) } + st.ncl = { 0, 0, 0 } + -- three reference frames, grey until the first keyframe + st.refs = {} + for r = 1, 3 do + local planes = {} + for pli = 1, 3 do + local b = buffer.create(st.planeSize[pli]) + bfill(b, 0, 128) + planes[pli] = b + end + st.refs[r] = planes + end + st.gold, st.prev, st.shown = 1, 1, 1 + return st :: State +end + +-- ------------------------------------------------------------------------------------------------ reconstruction +-- the 8-point IDCT of libtheora's idct8 (the spec's), on 8 values; returns the 8 outputs +local function idct8(x0: number, x1: number, x2: number, x3: number, x4: number, x5: number, x6: number, x7: number): (number, number, number, number, number, number, number, number) + local t0 = (C4 * (x0 + x4)) // 65536 + local t1 = (C4 * (x0 - x4)) // 65536 + local t2 = (C6 * x2) // 65536 - (C2 * x6) // 65536 + local t3 = (C2 * x2) // 65536 + (C6 * x6) // 65536 + local t4 = (C7 * x1) // 65536 - (C1 * x7) // 65536 + local t5 = (C3 * x5) // 65536 - (C5 * x3) // 65536 + local t6 = (C5 * x5) // 65536 + (C3 * x3) // 65536 + local t7 = (C1 * x1) // 65536 + (C7 * x7) // 65536 + local r = t4 + t5 + t5 = (C4 * (t4 - t5)) // 65536 + t4 = r + r = t7 + t6 + t6 = (C4 * (t7 - t6)) // 65536 + t7 = r + r = t0 + t3 + t3 = t0 - t3 + t0 = r + r = t1 + t2 + t2 = t1 - t2 + t1 = r + r = t6 + t5 + t5 = t6 - t5 + t6 = r + return t0 + t7, t1 + t6, t2 + t5, t3 + t4, t3 - t4, t2 - t5, t1 - t6, t0 - t7 +end + +-- 2-D IDCT of blk (i16, natural order) into res (i32 residuals). Like libtheora, the dequantised coefficients and +-- the first pass's outputs are 16-bit (the i16 buffers wrap them), which also bounds every residual to +-24000. +local function idct(blk: buffer, tmp: buffer, res: buffer) + for i = 0, 7 do + local o = i * 16 + local x0, x1, x2, x3 = readi16(blk, o), readi16(blk, o + 2), readi16(blk, o + 4), readi16(blk, o + 6) + local x4, x5, x6, x7 = readi16(blk, o + 8), readi16(blk, o + 10), readi16(blk, o + 12), readi16(blk, o + 14) + local c = i * 2 + if x0 == 0 and x1 == 0 and x2 == 0 and x3 == 0 and x4 == 0 and x5 == 0 and x6 == 0 and x7 == 0 then + writei16(tmp, c, 0) + writei16(tmp, c + 16, 0) + writei16(tmp, c + 32, 0) + writei16(tmp, c + 48, 0) + writei16(tmp, c + 64, 0) + writei16(tmp, c + 80, 0) + writei16(tmp, c + 96, 0) + writei16(tmp, c + 112, 0) + else + local y0, y1, y2, y3, y4, y5, y6, y7 = idct8(x0, x1, x2, x3, x4, x5, x6, x7) + writei16(tmp, c, y0) + writei16(tmp, c + 16, y1) + writei16(tmp, c + 32, y2) + writei16(tmp, c + 48, y3) + writei16(tmp, c + 64, y4) + writei16(tmp, c + 80, y5) + writei16(tmp, c + 96, y6) + writei16(tmp, c + 112, y7) + end + end + for i = 0, 7 do + local o = i * 16 + local x0, x1, x2, x3 = readi16(tmp, o), readi16(tmp, o + 2), readi16(tmp, o + 4), readi16(tmp, o + 6) + local x4, x5, x6, x7 = readi16(tmp, o + 8), readi16(tmp, o + 10), readi16(tmp, o + 12), readi16(tmp, o + 14) + local y0, y1, y2, y3, y4, y5, y6, y7 = idct8(x0, x1, x2, x3, x4, x5, x6, x7) + local c = i * 4 + writei32(res, c, (y0 + 8) // 16) + writei32(res, c + 32, (y1 + 8) // 16) + writei32(res, c + 64, (y2 + 8) // 16) + writei32(res, c + 96, (y3 + 8) // 16) + writei32(res, c + 128, (y4 + 8) // 16) + writei32(res, c + 160, (y5 + 8) // 16) + writei32(res, c + 192, (y6 + 8) // 16) + writei32(res, c + 224, (y7 + 8) // 16) + end +end + +local function wrap16(v: number): number + return (v + 32768) % 65536 - 32768 +end + +-- the motion vector offsets of one component: integer part (toward zero) and the second sample's extra step (away +-- from zero) when there is a fraction. q: quarter-pel (subsampled direction) or half-pel +local function mvSplit(d: number, q: boolean): (number, number) + local div = if q then 4 else 2 + local a = if d < 0 then -((-d) // div) else d // div + local frac = d - a * div + local b = if frac > 0 then 1 elseif frac < 0 then -1 else 0 + return a, b +end + +-- reconstruct one coded fragment into dst (the SELF reference planes) +local function reconFrag(st: State, fi: number, qis: { number }, dstPlanes: { buffer }) + local pli = st.fpl[fi] + local mode = st.fmode[fi] + local qti = if mode == INTRA then 0 else 1 + local dq = st.dequant + local dcq = readu16(dq, (((qis[1] * 3 + pli) * 2 + qti) * 64) * 2) + local dc = st.dcv[fi] + local last = st.last[fi] + local res = st.res + local flat = false + local fv = 0 + if last == 0 then + flat = true + fv = wrap16((dc * dcq + 15) // 32) + else + local blk = st.blk + bfill(blk, 0, 0, 128) + writei16(blk, 0, wrap16(dc * dcq)) + local coef = st.coef + local co = (fi - 1) * 128 + local ao = (((qis[st.qii[fi] + 1] * 3 + pli) * 2 + qti) * 64) * 2 + for z = 1, last do + local c = readi16(coef, co + z * 2) + if c ~= 0 then + writei16(coef, co + z * 2, 0) + writei16(blk, ZIGZAG[z + 1] * 2, wrap16(c * readu16(dq, ao + z * 2))) + end + end + st.last[fi] = 0 + idct(blk, st.tmp, res) + end + local stride = st.stride[pli + 1] + local dst = dstPlanes[pli + 1] + local pos = st.fpos[fi] + local ri = st.refi[fi] + if ri == SELF then + if flat then + local v = readu8(CLAMP, fv + 128 + COFF) + for y = 0, 7 do + bfill(dst, pos + y * stride, v, 8) + end + else + for y = 0, 7 do + local d, s = pos + y * stride, y * 32 + for x = 0, 7 do + writeu8(dst, d + x, readu8(CLAMP, readi32(res, s + x * 4) + 128 + COFF)) + end + end + end + return + end + local ref = st.refs[if ri == GOLD then st.gold else st.prev][pli + 1] + local qx = pli > 0 and st.hdec == 1 + local qy = pli > 0 and st.vdec == 1 + local mx, mx2 = mvSplit(st.mvx[fi], qx) + local my, my2 = mvSplit(st.mvy[fi], qy) + local s1 = pos + my * stride + mx + if mx2 ~= 0 or my2 ~= 0 then + local s2 = s1 + my2 * stride + mx2 + for y = 0, 7 do + local d, a, b, r = pos + y * stride, s1 + y * stride, s2 + y * stride, y * 32 + for x = 0, 7 do + local p = (readu8(ref, a + x) + readu8(ref, b + x)) // 2 + local v = if flat then fv else readi32(res, r + x * 4) + writeu8(dst, d + x, readu8(CLAMP, p + v + COFF)) + end + end + else + for y = 0, 7 do + local d, a, r = pos + y * stride, s1 + y * stride, y * 32 + for x = 0, 7 do + local v = if flat then fv else readi32(res, r + x * 4) + writeu8(dst, d + x, readu8(CLAMP, readu8(ref, a + x) + v + COFF)) + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ loop filter +local function filterH(b: buffer, p: number, stride: number, bv: { number }) + p -= 2 + for _ = 0, 7 do + local p0, p1, p2, p3 = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2), readu8(b, p + 3) + local f = bv[(p0 - p3 + 3 * (p2 - p1) + 4) // 8 + 129] + writeu8(b, p + 1, readu8(CLAMP, p1 + f + COFF)) + writeu8(b, p + 2, readu8(CLAMP, p2 - f + COFF)) + p += stride + end +end + +local function filterV(b: buffer, p: number, stride: number, bv: { number }) + local q0, q1, q2 = p - 2 * stride, p - stride, p + stride + for x = 0, 7 do + local p0, p1, p2, p3 = readu8(b, q0 + x), readu8(b, q1 + x), readu8(b, p + x), readu8(b, q2 + x) + local f = bv[(p0 - p3 + 3 * (p2 - p1) + 4) // 8 + 129] + writeu8(b, q1 + x, readu8(CLAMP, p1 + f + COFF)) + writeu8(b, p + x, readu8(CLAMP, p2 - f + COFF)) + end +end + +local function loopFilter(st: State, planes: { buffer }, flimit: number) + local bv = st.bv + for i = -128, 128 do + local a = math.abs(i) + local v = 0 + if a < flimit then + v = i + elseif a < 2 * flimit then + v = if i > 0 then 2 * flimit - a else a - 2 * flimit + end + -- libtheora's table stops at index -127 (127 - i - flimit >= 0) + if i < -127 then + v = 0 + end + bv[i + 129] = v + end + local coded = st.coded + for pli = 0, 2 do + local b = planes[pli + 1] + local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] + local stride = st.stride[pli + 1] + local base = st.foff[pli + 1] + local fpos = st.fpos + for fy = 0, nv - 1 do + local row = base + fy * nh + for fx = 0, nh - 1 do + local fi = row + fx + 1 + if coded[fi] ~= 0 then + local p = fpos[fi] + if fx > 0 then + filterH(b, p, stride, bv) + end + if fy > 0 then + filterV(b, p, stride, bv) + end + if fx + 1 < nh and coded[fi + 1] == 0 then + filterH(b, p + 8, stride, bv) + end + if fy + 1 < nv and coded[fi + nh] == 0 then + filterV(b, p + 8 * stride, stride, bv) + end + end + end + end + end +end + +-- extend each plane's edge pixels into its padding (for unrestricted motion vectors) +local function borders(st: State, planes: { buffer }) + for pli = 1, 3 do + local b = planes[pli] + local stride, px, py = st.stride[pli], st.padx[pli], st.pady[pli] + local w, h = st.pw[pli], st.ph[pli] + for y = 0, h - 1 do + local o = (y + py) * stride + bfill(b, o, readu8(b, o + px), px) + bfill(b, o + px + w, readu8(b, o + px + w - 1), px) + end + local top, bot = py * stride, (py + h - 1) * stride + for k = 1, py do + bcopy(b, top - k * stride, b, top, stride) + bcopy(b, bot + k * stride, b, bot, stride) + end + end +end + +-- ------------------------------------------------------------------------------------------------ frame decode +-- decode(st, data, off, len) -> kind ("key" | "inter" | "dup") | nil, message. The picture is then in +-- st.refs[st.shown]. +function D.decode(st: State, data: buffer, off: number, len: number): (string?, string?) + if len <= 0 then + return "dup", nil + end + -- a zero-padded copy: reads past the end give zero bits, every read site clamps pos to the end first + local bb = buffer.create(len + 24) + bcopy(bb, 0, data, off, len) + local maxp = len * 8 + local pos = 0 + local function bits(n: number): number + if pos > maxp then + pos = maxp + end + local w = rshift(lshift(bswap(readu32(bb, pos // 8)), pos % 8), 32 - n) + pos += n + return w + end + local huff = st.huff + local function token(root: number): number + if pos > maxp then + pos = maxp + end + local o = root + while true do + local n = huff[o] + local w = rshift(lshift(bswap(readu32(bb, pos // 8)), pos % 8), 32 - n) + local e = huff[o + 1 + w] + if e >= 0 then + pos += e // 64 + return e % 64 + end + pos += n + o = -e + if pos > maxp then + pos = maxp + end + end + end + local function sbRun(): number + if bits(1) == 0 then + return 1 + elseif bits(1) == 0 then + return 2 + bits(1) + elseif bits(1) == 0 then + return 4 + bits(1) + elseif bits(1) == 0 then + return 6 + bits(2) + elseif bits(1) == 0 then + return 10 + bits(3) + elseif bits(1) == 0 then + return 18 + bits(4) + end + return 34 + bits(12) + end + local function blockRun(): number + if bits(1) == 0 then + return 1 + bits(1) + elseif bits(1) == 0 then + return 3 + bits(1) + elseif bits(1) == 0 then + return 5 + bits(1) + elseif bits(1) == 0 then + return 7 + bits(2) + elseif bits(1) == 0 then + return 11 + bits(2) + end + return 15 + bits(4) + end + + -- frame header + if bits(1) ~= 0 then + return nil, "not a data packet" + end + local intra = bits(1) == 0 + local qis = { bits(6) } + if bits(1) == 1 then + table.insert(qis, bits(6)) + if bits(1) == 1 then + table.insert(qis, bits(6)) + end + end + if intra then + if bits(3) ~= 0 then + return nil, "unsupported: reserved keyframe bits set" + end + end + local coded, refi, fmode, dcv, tis, qii = st.coded, st.refi, st.fmode, st.dcv, st.tis, st.qii + local mvx, mvy = st.mvx, st.mvy + local sbFr, sbQuadValid, sbPlane = st.sbFr, st.sbQuadValid, st.sbPlane + local clist, ncl = st.clist, st.ncl + local mbMode = st.mbMode + local nsbs = st.nsbs + local total = 0 + if intra then + for pli = 0, 2 do + local list, n = clist[pli + 1], 0 + for sbi = sbPlane[pli + 1], sbPlane[pli + 2] - 1 do + for q = 0, 3 do + if sbQuadValid[sbi * 4 + q + 1] then + for bi = 0, 3 do + local fi = sbFr[sbi * 16 + q * 4 + bi + 1] + if fi ~= 0 then + coded[fi] = 1 + refi[fi] = SELF + fmode[fi] = INTRA + n += 1 + list[n] = fi + end + end + end + end + end + ncl[pli + 1] = n + total += n + end + else + -- partially coded super blocks, then fully coded ones among the rest + local partial, full = table.create(nsbs, false), table.create(nsbs, false) + local npartial = 0 + local flag = bits(1) + local sbi = 0 + while sbi < nsbs do + local run = sbRun() + local fullRun = run >= 4129 + repeat + partial[sbi + 1] = flag == 1 + npartial += flag + sbi += 1 + run -= 1 + until run <= 0 or sbi >= nsbs + if fullRun and sbi < nsbs then + flag = bits(1) + else + flag = 1 - flag + end + end + if npartial < nsbs then + sbi = 0 + while partial[sbi + 1] do + sbi += 1 + end + flag = bits(1) + repeat + local run = sbRun() + local fullRun = run >= 4129 + while sbi < nsbs do + if not partial[sbi + 1] then + if run <= 0 then + break + end + run -= 1 + full[sbi + 1] = flag == 1 + end + sbi += 1 + end + if fullRun and sbi < nsbs then + flag = bits(1) + else + flag = 1 - flag + end + until sbi >= nsbs + end + -- block flags + local bflag = 0 + if npartial > 0 then + bflag = 1 - bits(1) + end + local run = 0 + for pli = 0, 2 do + local list, n = clist[pli + 1], 0 + for s = sbPlane[pli + 1], sbPlane[pli + 2] - 1 do + local isFull, isPartial = full[s + 1], partial[s + 1] + for q = 0, 3 do + if sbQuadValid[s * 4 + q + 1] then + local quadCoded = 0 + for bi = 0, 3 do + local fi = sbFr[s * 16 + q * 4 + bi + 1] + if fi ~= 0 then + local c = 0 + if isFull then + c = 1 + elseif isPartial then + if run <= 0 then + run = blockRun() + bflag = 1 - bflag + end + run -= 1 + c = bflag + end + coded[fi] = c + refi[fi] = NONE + if c == 1 then + n += 1 + list[n] = fi + quadCoded = 1 + end + end + end + if pli == 0 then + mbMode[s * 4 + q + 1] = quadCoded + end + end + end + end + ncl[pli + 1] = n + total += n + end + if total == 0 then + return "dup", nil + end + -- macro block modes + local scheme = bits(3) + local alphabet: { number } + if scheme == 0 then + alphabet = table.create(8, NOMV) + for mi = 1, 8 do + alphabet[bits(3) + 1] = ALPHABETS[7][mi] + end + else + alphabet = ALPHABETS[scheme] + end + for mbi = 1, st.nmbs do + if mbMode[mbi] > 0 then + local idx: number + if scheme == 7 then + idx = bits(3) + else + local e = MODE_VLC[bits(7) + 1] + pos -= 7 - e % 8 + idx = e // 8 + end + mbMode[mbi] = alphabet[idx + 1] + end + end + -- motion vectors + local clc = bits(1) == 1 + local function mv(): number + if clc then + local v = bits(6) + return if v % 2 == 1 then -(v // 2) else v // 2 + end + local e = MV_VLC[bits(8) + 1] + pos -= 8 - e % 16 + return e // 16 - 32 + end + local mbFr, mapIdx = st.mbFr, st.mapIdx + local nmap = #mapIdx + local lastX, lastY, priorX, priorY = 0, 0, 0, 0 + local lx, ly = { 0, 0, 0, 0 }, { 0, 0, 0, 0 } + local cx, cy = { 0, 0, 0, 0 }, { 0, 0, 0, 0 } + local pf = st.pf + for mbi = 0, st.nmbs - 1 do + local mode = mbMode[mbi + 1] + if mode >= 0 then + local o = mbi * 12 + if mode == FOURMV then + priorX, priorY = lastX, lastY + for bi = 1, 4 do + local fi = mbFr[o + bi] + if coded[fi] ~= 0 then + refi[fi] = PREV + fmode[fi] = FOURMV + local x = mv() + local y = mv() + lx[bi], ly[bi] = x, y + lastX, lastY = x, y + mvx[fi], mvy[fi] = x, y + else + lx[bi], ly[bi] = 0, 0 + end + end + if pf == 0 then + local sx, sy = lx[1] + lx[2] + lx[3] + lx[4], ly[1] + ly[2] + ly[3] + ly[4] + cx[1] = (sx + 2 - (if sx < 0 then 1 else 0)) // 4 + cy[1] = (sy + 2 - (if sy < 0 then 1 else 0)) // 4 + elseif pf == 2 then + local sx, sy = lx[1] + lx[2], ly[1] + ly[2] + cx[1] = (sx + 1 - (if sx < 0 then 1 else 0)) // 2 + cy[1] = (sy + 1 - (if sy < 0 then 1 else 0)) // 2 + sx, sy = lx[3] + lx[4], ly[3] + ly[4] + cx[3] = (sx + 1 - (if sx < 0 then 1 else 0)) // 2 + cy[3] = (sy + 1 - (if sy < 0 then 1 else 0)) // 2 + else + for k = 1, 4 do + cx[k], cy[k] = lx[k], ly[k] + end + end + for m = 5, nmap do + local mi = mapIdx[m] + local fi = mbFr[o + mi + 1] + if coded[fi] ~= 0 then + local bi = mi % 4 + 1 + refi[fi] = PREV + fmode[fi] = FOURMV + mvx[fi], mvy[fi] = cx[bi], cy[bi] + end + end + else + local x, y = 0, 0 + if mode == INTER_MV then + priorX, priorY = lastX, lastY + x = mv() + y = mv() + lastX, lastY = x, y + elseif mode == MV_LAST then + x, y = lastX, lastY + elseif mode == MV_LAST2 then + x, y = priorX, priorY + priorX, priorY = lastX, lastY + lastX, lastY = x, y + elseif mode == GOLD_MV then + x = mv() + y = mv() + end + local r = FRAME_FOR_MODE[mode] + for m = 1, nmap do + local fi = mbFr[o + mapIdx[m] + 1] + if coded[fi] ~= 0 then + refi[fi] = r + fmode[fi] = mode + mvx[fi], mvy[fi] = x, y + end + end + end + end + end + end + + -- block qi indices (over every coded fragment, planes in order) + local nqis = #qis + for pli = 1, 3 do + local list = clist[pli] + for k = 1, ncl[pli] do + local fi = list[k] + qii[fi] = 0 + dcv[fi] = 0 + tis[fi] = 0 + end + end + if nqis > 1 then + local all = table.create(total, 0) + local n = 0 + for pli = 1, 3 do + local list = clist[pli] + for k = 1, ncl[pli] do + n += 1 + all[n] = list[k] + end + end + local flag = bits(1) + local nqi1 = 0 + local k = 1 + while k <= total do + local run = sbRun() + local fullRun = run >= 4129 + repeat + qii[all[k]] = flag + nqi1 += flag + k += 1 + run -= 1 + until run <= 0 or k > total + if fullRun and k <= total then + flag = bits(1) + else + flag = 1 - flag + end + end + if nqis == 3 and nqi1 > 0 then + k = 1 + while qii[all[k]] == 0 do + k += 1 + end + flag = bits(1) + repeat + local run = sbRun() + local fullRun = run >= 4129 + while k <= total do + local fi = all[k] + if qii[fi] ~= 0 then + if run <= 0 then + break + end + run -= 1 + qii[fi] += flag + end + k += 1 + end + if fullRun and k <= total then + flag = bits(1) + else + flag = 1 - flag + end + until k > total + end + end + + -- DCT tokens: coefficient by coefficient, plane by plane, block by block in coded order; an EOB run ends the + -- next blocks that still wait for a token at their position + local coef, last = st.coef, st.last + local act = st.act + local nact = { 0, 0, 0 } + for pli = 1, 3 do + local src, dstl = clist[pli], act[pli] + for k = 1, ncl[pli] do + dstl[k] = src[k] + end + nact[pli] = ncl[pli] + end + local roots = st.roots + local hy: number = bits(4) + local hc: number = bits(4) + local eobs = 0 + for zzi = 0, 63 do + if zzi == 1 then + hy = bits(4) + hc = bits(4) + end + local grp: number = if zzi == 0 then 0 elseif zzi < 6 then 16 elseif zzi < 15 then 32 elseif zzi < 28 then 48 else 64 + for pli = 1, 3 do + local sel: number = if pli == 1 then hy else hc + local root = roots[sel + grp + 1] + local list = act[pli] + local n = nact[pli] + local w = 0 + for k = 1, n do + local fi = list[k] + local t = tis[fi] + if t == zzi then + if eobs > 0 then + eobs -= 1 + t = 64 + else + local tok = token(root) + local ex = TOKEN_EXTRA[tok] + local eb = if ex > 0 then bits(ex) else 0 + if tok < 7 then + local run: number + if tok < 3 then + run = tok + 1 + elseif tok == 3 then + run = 4 + eb + elseif tok == 4 then + run = 8 + eb + elseif tok == 5 then + run = 16 + eb + else + run = if eb == 0 then 2 ^ 31 else eb + end + eobs = run - 1 + t = 64 + elseif tok < 9 then + t = zzi + eb + 1 + else + local v, r = 0, 0 + if tok < 13 then + v = if tok == 9 then 1 elseif tok == 10 then -1 elseif tok == 11 then 2 else -2 + elseif tok < 17 then + v = if eb == 1 then -(tok - 10) else tok - 10 + elseif tok < 23 then + local half = 2 ^ (ex - 1) + local base = if tok == 17 then 7 elseif tok == 18 then 9 elseif tok == 19 then 13 elseif tok == 20 then 21 elseif tok == 21 then 37 else 69 + v = base + eb % half + if eb >= half then + v = -v + end + elseif tok < 28 then + r = tok - 22 + v = if eb == 1 then -1 else 1 + elseif tok == 28 then + r = 6 + eb % 4 + v = if eb >= 4 then -1 else 1 + elseif tok == 29 then + r = 10 + eb % 8 + v = if eb >= 8 then -1 else 1 + elseif tok == 30 then + r = 1 + v = 2 + eb % 2 + if eb >= 2 then + v = -v + end + else + r = 2 + eb % 2 + v = 2 + (eb // 2) % 2 + if eb >= 4 then + v = -v + end + end + local p = zzi + r + if p == 0 then + dcv[fi] = v + elseif p < 64 then + writei16(coef, (fi - 1) * 128 + p * 2, v) + last[fi] = p + end + t = p + 1 + end + end + tis[fi] = t + end + if t < 64 then + w += 1 + list[w] = fi + end + end + nact[pli] = w + end + end + + -- DC prediction (raster order per plane) + for pli = 0, 2 do + local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] + local base = st.foff[pli + 1] + local pl0, pl1, pl2 = 0, 0, 0 -- the last DC of each reference frame (GOLD, PREV, SELF) + for fy = 0, nv - 1 do + local row = base + fy * nh + local lref, ulref, uref = -1, -1, -1 + if fy > 0 then + uref = refi[row - nh + 1] + end + for fx = 0, nh - 1 do + local fi = row + fx + 1 + local urref = -1 + if fy > 0 and fx + 1 < nh then + urref = refi[fi - nh + 1] + end + if coded[fi] ~= 0 then + local r = refi[fi] + local pred: number + if fy == 0 then + pred = if r == 0 then pl0 elseif r == 1 then pl1 else pl2 + else + local m = (if lref == r then 1 else 0) + (if ulref == r then 2 else 0) + (if uref == r then 4 else 0) + (if urref == r then 8 else 0) + if m == 0 then + pred = if r == 0 then pl0 elseif r == 1 then pl1 else pl2 + elseif m == 1 or m == 3 then + pred = dcv[fi - 1] + elseif m == 2 then + pred = dcv[fi - nh - 1] + elseif m == 4 or m == 6 or m == 12 then + pred = dcv[fi - nh] + elseif m == 5 then + local s = dcv[fi - 1] + dcv[fi - nh] + pred = if s < 0 then -((-s) // 2) else s // 2 + elseif m == 8 then + pred = dcv[fi - nh + 1] + elseif m == 9 or m == 11 or m == 13 then + local s = 75 * dcv[fi - 1] + 53 * dcv[fi - nh + 1] + pred = if s < 0 then -((-s) // 128) else s // 128 + elseif m == 10 then + local s = dcv[fi - nh - 1] + dcv[fi - nh + 1] + pred = if s < 0 then -((-s) // 2) else s // 2 + elseif m == 14 then + local s = 3 * (dcv[fi - nh - 1] + dcv[fi - nh + 1]) + 10 * dcv[fi - nh] + pred = if s < 0 then -((-s) // 16) else s // 16 + else + local p0, p1, p2 = dcv[fi - 1], dcv[fi - nh - 1], dcv[fi - nh] + local s = 29 * (p0 + p2) - 26 * p1 + pred = if s < 0 then -((-s) // 32) else s // 32 + if math.abs(pred - p2) > 128 then + pred = p2 + elseif math.abs(pred - p0) > 128 then + pred = p0 + elseif math.abs(pred - p1) > 128 then + pred = p1 + end + end + end + local v = wrap16(dcv[fi] + pred) + dcv[fi] = v + if r == 0 then + pl0 = v + elseif r == 1 then + pl1 = v + else + pl2 = v + end + lref = r + else + lref = -1 + end + ulref = uref + uref = urref + end + end + end + + -- reconstruction into a free reference buffer + local self = 1 + while self == st.gold or self == st.prev do + self += 1 + end + local dst = st.refs[self] + if not intra then + local src = st.refs[st.prev] + for pli = 1, 3 do + bcopy(dst[pli], 0, src[pli], 0, st.planeSize[pli]) + end + end + for pli = 1, 3 do + local list = clist[pli] + for k = 1, ncl[pli] do + reconFrag(st, list[k], qis, dst) + end + end + local flimit = st.lflim[qis[1] + 1] + if flimit ~= 0 then + loopFilter(st, dst, flimit) + end + borders(st, dst) + if intra then + st.gold, st.prev = self, self + st.keyframes += 1 + else + st.prev = self + end + st.shown = self + return if intra then "key" else "inter", nil +end + +-- ------------------------------------------------------------------------------------------------ output +-- the picture region of the shown frame as top-down planes: plane(st, pli, x0, y0, w, h) copies a w x h window whose +-- top-left corner is (x0, y0) counted from the top of the plane +function D.plane(st: State, pli: number, x0: number, y0: number, w: number, h: number): buffer + local src = st.refs[st.shown][pli + 1] + local stride, origin, ph = st.stride[pli + 1], st.origin[pli + 1], st.ph[pli + 1] + local out = buffer.create(w * h) + for y = 0, h - 1 do + local row = ph - 1 - (y0 + y) -- Theora rows count from the bottom + bcopy(out, y * w, src, origin + row * stride + x0, w) + end + return out +end + +-- downsample(src, cw, ch, hdec, dst, off, ow, oh): 4:2:2 (hdec 1: rows averaged in pairs) or 4:4:4 (hdec 0: 2x2 +-- averages) chroma of cw x ch into ow x oh 4:2:0 chroma at dst[off] +function D.downsample(src: buffer, cw: number, ch: number, hdec: number, dst: buffer, off: number, ow: number, oh: number) + for r = 0, oh - 1 do + local r0 = math.min(2 * r, ch - 1) + local r1 = math.min(2 * r + 1, ch - 1) + local a, b = r0 * cw, r1 * cw + local o = off + r * ow + if hdec == 1 then + for c = 0, math.min(ow, cw) - 1 do + writeu8(dst, o + c, (readu8(src, a + c) + readu8(src, b + c) + 1) // 2) + end + else + for c = 0, ow - 1 do + local c0 = math.min(2 * c, cw - 1) + local c1 = math.min(2 * c + 1, cw - 1) + writeu8(dst, o + c, (readu8(src, a + c0) + readu8(src, a + c1) + readu8(src, b + c0) + readu8(src, b + c1) + 2) // 4) + end + end + end +end + +return D diff --git a/src/Formats/codecs/video/Theora/Header.luau b/src/Formats/codecs/video/Theora/Header.luau new file mode 100644 index 0000000..2d88abd --- /dev/null +++ b/src/Formats/codecs/video/Theora/Header.luau @@ -0,0 +1,370 @@ +--!strict +-- codecs/video/Theora/Header: the three Theora headers (Theora I specification, section 6): identification (frame / +-- picture size and offsets, frame rate, aspect, colour space, pixel format, keyframe granule shift), comment (Vorbis +-- comment layout) and setup (loop-filter limits, quantisation parameters, the 80 DCT token Huffman trees), and the +-- tables derived from them: the dequantisation matrices of every qi / plane / intra-inter and the collapsed Huffman +-- lookup tables the frame decoder walks. A Luau port of libtheora 1.2.0 (Xiph.Org, BSD 3-clause: +-- licenses/libtheora-BSD.txt): decinfo.c, dequant.c, quant.c (oc_dequant_tables_init), huffdec.c (the tree unpacking; +-- the table layout here is simpler). Never throws: bad headers return nil, message. +local Bits = require("@formats/core/Bits") + +local H = {} + +export type Info = { + versionMajor: number, + versionMinor: number, + versionSub: number, + frameWidth: number, -- coded frame size (multiples of 16) + frameHeight: number, + picWidth: number, -- the picture region (the displayed part) + picHeight: number, + picX: number, -- from the left + picY: number, -- from the bottom, as stored + fpsNum: number, + fpsDen: number, + aspectNum: number, + aspectDen: number, + colorspace: number, -- 0 unspecified, 1 Rec. 470M, 2 Rec. 470BG + bitrate: number, + quality: number, + granuleShift: number, + pixelFormat: number, -- 0 4:2:0, 2 4:2:2, 3 4:4:4 (1 is reserved) +} + +export type Setup = { + lflim: { number }, -- [qi + 1]: loop filter limit + dequant: buffer, -- u16 [((qi * 3 + pli) * 2 + qti) * 64 + zzi], zig-zag order, scaled by 4 like libtheora + huff: { number }, -- the 80 collapsed trees, one flat array (see buildTable) + roots: { number }, -- [table + 1]: the root node offset in huff +} + +-- the zig-zag scan: natural index of the coefficient at scan position zzi +H.ZIGZAG = { + 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, + 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, +} + +local function ilog(v: number): number + local n = 0 + while v > 0 do + n += 1 + v = v // 2 + end + return n +end + +-- ------------------------------------------------------------------------------------------------ identification +-- info(buf, off, len) -> Info | nil, message: the packet starting with 0x80 "theora" +function H.info(b: buffer, off: number, len: number): (Info?, string?) + if len < 42 or buffer.readu8(b, off) ~= 0x80 or buffer.readstring(b, off + 1, 6) ~= "theora" then + return nil, "not a Theora identification header" + end + local br = Bits.msbReader(b, off + 7, len - 7) + local info: Info = { + versionMajor = br:read(8), + versionMinor = br:read(8), + versionSub = br:read(8), + frameWidth = br:read(16) * 16, + frameHeight = br:read(16) * 16, + picWidth = br:read(24), + picHeight = br:read(24), + picX = br:read(8), + picY = br:read(8), + fpsNum = br:read(32), + fpsDen = br:read(32), + aspectNum = br:read(24), + aspectDen = br:read(24), + colorspace = br:read(8), + bitrate = br:read(24), + quality = br:read(6), + granuleShift = br:read(5), + pixelFormat = br:read(2), + } + local reserved = br:read(3) + if br.err then + return nil, "truncated identification header" + end + if info.versionMajor > 3 or (info.versionMajor == 3 and info.versionMinor > 2) then + return nil, "unsupported: Theora bitstream version " .. info.versionMajor .. "." .. info.versionMinor + end + if info.frameWidth == 0 or info.frameHeight == 0 or info.picWidth + info.picX > info.frameWidth or info.picHeight + info.picY > info.frameHeight then + return nil, "bad frame / picture size" + end + if info.fpsNum == 0 or info.fpsDen == 0 then + return nil, "bad frame rate" + end + if info.pixelFormat == 1 or reserved ~= 0 then + return nil, "reserved pixel format" + end + return info, nil +end + +-- ------------------------------------------------------------------------------------------------ comment +-- comment(buf, off, len) -> vendor, { "KEY=value" } | nil, message: the packet starting with 0x81 "theora" +function H.comment(b: buffer, off: number, len: number): (string?, { string }?, string?) + if len < 7 or buffer.readu8(b, off) ~= 0x81 or buffer.readstring(b, off + 1, 6) ~= "theora" then + return nil, nil, "not a Theora comment header" + end + local p, e = off + 7, off + len + local function str(): string? + if p + 4 > e then + return nil + end + local n = buffer.readu32(b, p) + p += 4 + if n > e - p then + return nil + end + local s = buffer.readstring(b, p, n) + p += n + return s + end + local vendor = str() + if not vendor or p + 4 > e then + return nil, nil, "truncated comment header" + end + local count = buffer.readu32(b, p) + p += 4 + if count * 4 > e - p then + return nil, nil, "bad comment count" + end + local list: { string } = {} + for _ = 1, count do + local s = str() + if not s then + return nil, nil, "truncated comment header" + end + table.insert(list, s) + end + return vendor, list, nil +end + +-- ------------------------------------------------------------------------------------------------ Huffman trees +-- A tree is read depth first (0: an internal node, 1 then 5 bits: a leaf with that token). It becomes lookup tables in +-- one flat array: a node is huff[o] = n (bits to peek) followed by 2^n entries, entry = length * 64 + token (a leaf +-- reached after `length` <= n of the peeked bits) or -offset (another node, after all n bits). +local MAXBITS = 8 + +local function readTree(br: any): ({ number }?, { number }?, { number }?) + -- the trie: kid0 / kid1 child ids (0 = none), tok = token or -1 (node 1 is the root) + local kid0, kid1, tok = { 0 }, { 0 }, { -1 } + -- as libtheora's oc_huff_tree_unpack: code is the current codeword left-aligned in 32 bits, len its length + local code, len, nleaves = 0, 0, 0 + while true do + local bit = br:read(1) + if br.err then + return nil, nil, nil + end + if bit == 0 then + len += 1 + if len > 32 then + return nil, nil, nil + end + else + nleaves += 1 + if nleaves > 32 then + return nil, nil, nil + end + local t = br:read(5) + -- insert the leaf + local n = 1 + for d = 1, len do + local k = (code // 2 ^ (32 - d)) % 2 + local kids = if k == 0 then kid0 else kid1 + local nx = kids[n] + if nx == 0 then + nx = #tok + 1 + kid0[nx], kid1[nx], tok[nx] = 0, 0, -1 + kids[n] = nx + end + n = nx + end + tok[n] = t + if len <= 0 then + break + end + -- the next codeword: clear the trailing 1 bits, then set the last 0 bit + local cb = 2 ^ (32 - len) + while len > 0 and (code // cb) % 2 == 1 do + code -= cb + cb *= 2 + len -= 1 + end + if len <= 0 then + break + end + code += cb + end + end + return kid0, kid1, tok +end + +local function buildTable(out: { number }, kid0: { number }, kid1: { number }, tok: { number }): number + local heights: { [number]: number } = {} + local function height(n: number): number + local h = heights[n] + if h then + return h + end + h = 0 + if tok[n] < 0 then + local a = if kid0[n] ~= 0 then height(kid0[n]) else 0 + local c = if kid1[n] ~= 0 then height(kid1[n]) else 0 + h = 1 + math.max(a, c) + end + heights[n] = h + return h + end + local function node(n: number): number + local nb = math.clamp(height(n), 1, MAXBITS) + local off = #out + 1 + out[off] = nb + local size = 2 ^ nb + for i = 1, size do + out[off + i] = 0 + end + for i = 0, size - 1 do + local cur, d = n, 0 + while d < nb and tok[cur] < 0 do + local bit = (i // 2 ^ (nb - 1 - d)) % 2 + local nx = if bit == 0 then kid0[cur] else kid1[cur] + d += 1 + cur = nx + if nx == 0 then + break + end + end + if cur == 0 then + out[off + 1 + i] = d * 64 -- no code here (a corrupt tree): token 0 + elseif tok[cur] >= 0 then + out[off + 1 + i] = d * 64 + tok[cur] + else + out[off + 1 + i] = -node(cur) + end + end + return off + end + return node(1) +end + +-- ------------------------------------------------------------------------------------------------ setup +local DC_MIN = { 16, 32 } +local AC_MIN = { 8, 16 } + +-- setup(buf, off, len) -> Setup | nil, message: the packet starting with 0x82 "theora" +function H.setup(b: buffer, off: number, len: number): (Setup?, string?) + if len < 7 or buffer.readu8(b, off) ~= 0x82 or buffer.readstring(b, off + 1, 6) ~= "theora" then + return nil, "not a Theora setup header" + end + local br = Bits.msbReader(b, off + 7, len - 7) + -- loop filter limits, AC / DC scales + local lflim, acScale, dcScale = table.create(64, 0), table.create(64, 0), table.create(64, 0) + local nb = br:read(3) + for qi = 1, 64 do + lflim[qi] = br:read(nb) + end + nb = br:read(4) + 1 + for qi = 1, 64 do + acScale[qi] = br:read(nb) + end + nb = br:read(4) + 1 + for qi = 1, 64 do + dcScale[qi] = br:read(nb) + end + local nbms = br:read(9) + 1 + local bms: { { number } } = {} + for m = 1, nbms do + local mat = table.create(64, 0) + for ci = 1, 64 do + mat[ci] = br:read(8) + end + bms[m] = mat + end + if br.err then + return nil, "truncated setup header" + end + -- the quant ranges of the 6 (qti, pli) pairs: sizes and base matrix indices (0-based) + local ranges: { { sizes: { number }, idx: { number } } } = {} + local mb = ilog(nbms - 1) + for i = 0, 5 do + local qti, pli = i // 3, i % 3 + local copy = false + if i > 0 and br:read(1) == 0 then + copy = true + local from = i - 1 + if qti > 0 and br:read(1) == 1 then + from = pli -- the same plane of the intra set + end + ranges[i + 1] = ranges[from + 1] + end + if not copy then + local sizes, idx = {}, { br:read(mb) } + local qi = 0 + while qi < 63 do + local s = br:read(ilog(62 - qi)) + 1 + table.insert(sizes, s) + qi += s + table.insert(idx, br:read(mb)) + end + if qi > 63 then + return nil, "bad quant ranges" + end + for _, m in idx do + if m >= nbms then + return nil, "bad base matrix index" + end + end + ranges[i + 1] = { sizes = sizes, idx = idx } + end + end + if br.err then + return nil, "truncated setup header" + end + -- the dequantisation tables (oc_dequant_tables_init) + local dequant = buffer.create(64 * 6 * 64 * 2) + local base = table.create(64, 0) + for qti = 0, 1 do + for pli = 0, 2 do + local r = ranges[qti * 3 + pli + 1] + local qi = 0 + for qri = 0, #r.sizes do + local m0 = bms[r.idx[qri + 1] + 1] + table.move(m0, 1, 64, 1, base) + local qiStart = qi + local qiEnd = if qri == #r.sizes then qi + 1 else qi + r.sizes[qri + 1] + while true do + local o = ((qi * 3 + pli) * 2 + qti) * 64 + local q = (dcScale[qi + 1] * base[1] // 100) * 4 + buffer.writeu16(dequant, o * 2, math.clamp(q, DC_MIN[qti + 1], 4096)) + for zzi = 1, 63 do + q = (acScale[qi + 1] * base[H.ZIGZAG[zzi + 1] + 1] // 100) * 4 + buffer.writeu16(dequant, (o + zzi) * 2, math.clamp(q, AC_MIN[qti + 1], 4096)) + end + qi += 1 + if qi >= qiEnd then + break + end + -- interpolate the next base matrix + local m1 = bms[r.idx[qri + 2] + 1] + local sz = r.sizes[qri + 1] + for ci = 1, 64 do + base[ci] = (2 * ((qiEnd - qi) * m0[ci] + (qi - qiStart) * m1[ci]) + sz) // (2 * sz) + end + end + end + end + end + -- the 80 Huffman trees + local huff: { number } = {} + local roots: { number } = {} + for t = 1, 80 do + local k0, k1, tk = readTree(br) + if not k0 or not k1 or not tk then + return nil, "bad Huffman tree " .. (t - 1) + end + roots[t] = buildTable(huff, k0, k1, tk) + end + return { lflim = lflim, dequant = dequant, huff = huff, roots = roots }, nil +end + +return H diff --git a/src/Formats/codecs/video/Theora/init.luau b/src/Formats/codecs/video/Theora/init.luau new file mode 100644 index 0000000..dd99346 --- /dev/null +++ b/src/Formats/codecs/video/Theora/init.luau @@ -0,0 +1,270 @@ +--!strict +-- codecs/video/Theora: a Theora video decoder (the Theora I specification, Xiph.Org), for Ogg (video/ogv) and Matroska +-- (V_THEORA). A Luau port of the libtheora 1.2.0 decoder (BSD 3-clause, licenses/libtheora-BSD.txt): Header.luau +-- (identification / comment / setup headers, dequantisation tables, Huffman trees) and Decoder.luau (native frames). +-- Supports: every Theora I stream (bitstream 3.2.x and older 3.x): intra and inter frames, golden frames, 4MV +-- macro blocks, all three pixel formats (4:2:0, 4:2:2, 4:4:4), picture regions smaller than the coded frame (odd sizes, +-- offsets), empty packets (a repeated frame). Output is bit-exact with libtheora / ffmpeg (tests/codecs/theora.luau); +-- yuv420p images average 4:2:2 / 4:4:4 chroma down (planes() keeps the native layout). +-- Not supported: libtheora's optional post-processing (deblocking / deringing, off by default there too). +-- +-- local dec = Theora.new({ idHeader, commentHeader, setupHeader }) -- or the Xiph-laced Matroska CodecPrivate +-- local kind = dec:decode(packet) -- "key" | "inter" | "dup" (empty packet / no coded blocks) | nil, Err +-- local img = dec:image() -- a fresh yuv420p Types.Image of the picture region +-- local y, u, v, cw, ch = dec:planes() -- native planes (chroma cw x ch), top-down +-- Theora.granuleFrame(dec.info, granulepos) -- the 0-based frame index of an Ogg granule position +-- +-- Never throws: bad headers / packets come back as nil, Err (a corrupt frame still updates the picture). +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local VorbisComment = require("@formats/codecs/audio/VorbisComment") +local Header = require("@formats/codecs/video/Theora/Header") +local Decoder = require("@formats/codecs/video/Theora/Decoder") + +local Theora = {} + +export type Options = { + maxPixels: number?, -- larger coded frames are refused (default 4096 * 2304) +} + +local PIXEL_FORMATS = { [0] = "yuv420p", "reserved", "yuv422p", "yuv444p" } + +-- isHeader(buf, off?, len?) -> 1 / 2 / 3 for the identification / comment / setup header, else nil +function Theora.isHeader(b: buffer, off: number?, len: number?): number? + local o = off or 0 + local n = len or (buffer.len(b) - o) + if n < 7 then + return nil + end + local t = buffer.readu8(b, o) + if t >= 0x80 and t <= 0x82 and buffer.readstring(b, o + 1, 6) == "theora" then + return t - 0x7F + end + return nil +end + +-- splitConfig(config) -> the three header packets from Matroska's Xiph-laced CodecPrivate (or nil) +function Theora.splitConfig(c: buffer): { buffer }? + local n = buffer.len(c) + if n < 3 or buffer.readu8(c, 0) ~= 2 then + return nil + end + local p, lens = 1, {} + for k = 1, 2 do + local size = 0 + repeat + if p >= n then + return nil + end + local b = buffer.readu8(c, p) + size += b + p += 1 + until b < 255 + lens[k] = size + end + lens[3] = n - p - lens[1] - lens[2] + if lens[3] < 0 then + return nil + end + local out = {} + for k = 1, 3 do + out[k] = buffer.create(lens[k]) + buffer.copy(out[k], 0, c, p, lens[k]) + p += lens[k] + end + return out +end + +-- granuleFrame(info, granulepos) -> the 0-based index of the frame a granule position ends on (-1 for none) +function Theora.granuleFrame(info: Header.Info, g: number): number + if g < 0 then + return -1 + end + local shift = 2 ^ info.granuleShift + local key = g // shift + local f = key + g % shift + -- since bitstream 3.2.1 the first frame is granule 1 + local v = info.versionMajor * 65536 + info.versionMinor * 256 + info.versionSub + if v >= 0x030201 then + f -= 1 + end + return f +end + +-- ------------------------------------------------------------------------------------------------ decoder +local Dec = {} +Dec.__index = Dec + +export type TheoraDecoder = typeof(setmetatable( + {} :: { + info: Header.Info, + vendor: string, + comments: { string }, + tags: { [string]: string }, + width: number, -- the picture region + height: number, + frameRate: number, + pixelFormat: string, -- "yuv420p" | "yuv422p" | "yuv444p" + aspect: number, -- pixel aspect ratio (1 when unknown) + frames: number, -- packets decoded (dupes included) + _st: Decoder.State, + _any: boolean, -- a frame was decoded + }, + Dec +)) + +-- new(headers, opts?) -> TheoraDecoder | nil, Err: headers = the three header packets, or the Xiph-laced config +function Theora.new(headers: { buffer } | buffer, opts: Options?): (TheoraDecoder?, Err.Err?) + local list: { buffer }? = nil + if type(headers) == "buffer" then + list = Theora.splitConfig(headers) + elseif type(headers) == "table" then + list = headers + end + if not list or #list < 3 or type(list[1]) ~= "buffer" or type(list[2]) ~= "buffer" or type(list[3]) ~= "buffer" then + return nil, Err.new(Err.CORRUPT, "missing Theora headers") + end + local ok, info, ierr = pcall(Header.info, list[1], 0, buffer.len(list[1])) + if not ok or not info then + return nil, Err.from(if ok then ierr else tostring(info)) + end + local maxPixels = opts and opts.maxPixels or 4096 * 2304 + if info.frameWidth * info.frameHeight > maxPixels then + return nil, Err.new(Err.LIMIT, "frame of " .. info.frameWidth .. "x" .. info.frameHeight .. " is over maxPixels") + end + local ok2, vendor, comments, cerr = pcall(Header.comment, list[2], 0, buffer.len(list[2])) + if not ok2 or not vendor or not comments then + return nil, Err.from(if ok2 then cerr else tostring(vendor)) + end + local ok3, setup, serr = pcall(Header.setup, list[3], 0, buffer.len(list[3])) + if not ok3 or not setup then + return nil, Err.from(if ok3 then serr else tostring(setup)) + end + local st = Decoder.new(info, setup) + local tags = VorbisComment.tags(comments) + return setmetatable({ + info = info, + vendor = vendor, + comments = comments, + tags = tags, + width = info.picWidth, + height = info.picHeight, + frameRate = info.fpsNum / info.fpsDen, + pixelFormat = PIXEL_FORMATS[info.pixelFormat], + aspect = if info.aspectNum > 0 and info.aspectDen > 0 then info.aspectNum / info.aspectDen else 1, + frames = 0, + _st = st, + _any = false, + }, Dec), nil +end + +-- decode(data, off?, len?) -> "key" | "inter" | "dup" | nil, Err. Header packets are skipped (nil, nil). +function Dec.decode(self: TheoraDecoder, data: buffer, off: number?, len: number?): (string?, Err.Err?) + local o = off or 0 + local n = len or (buffer.len(data) - o) + if o < 0 or n < 0 or o + n > buffer.len(data) then + return nil, Err.new(Err.ARG, "decode: range outside the buffer") + end + if n > 0 and buffer.readu8(data, o) >= 0x80 then + return nil, nil + end + local kind, msg = Decoder.decode(self._st, data, o, n) + if not kind then + return nil, Err.from(msg) + end + self.frames += 1 + if kind ~= "dup" then + self._any = true + end + return kind, nil +end + +-- reset(): after a seek (the next frame should be a keyframe; until then inter frames predict from grey / old data) +function Dec.reset(self: TheoraDecoder) + local st = self._st + st.shown = st.prev +end + +local function window(self: TheoraDecoder): (number, number, number, number) + local info = self.info + -- the picture's top-left corner counted from the top of the frame (the header counts y from the bottom) + return info.picX, info.frameHeight - info.picHeight - info.picY, info.picWidth, info.picHeight +end + +-- planes() -> y, u, v (fresh top-down buffers of the picture region, chroma in the native layout), chroma width, +-- chroma height +function Dec.planes(self: TheoraDecoder): (buffer, buffer, buffer, number, number) + local st = self._st + local x0, y0, w, h = window(self) + local hd, vd = st.hdec, st.vdec + local cx0, cy0 = x0 // 2 ^ hd, y0 // 2 ^ vd + local cw, ch = (w + hd) // 2 ^ hd, (h + vd) // 2 ^ vd + cw = math.min(cw, st.pw[2] - cx0) + ch = math.min(ch, st.ph[2] - cy0) + return Decoder.plane(st, 0, x0, y0, w, h), Decoder.plane(st, 1, cx0, cy0, cw, ch), Decoder.plane(st, 2, cx0, cy0, cw, ch), cw, ch +end + +-- image() -> a fresh yuv420p Types.Image of the picture (4:2:2 / 4:4:4 chroma averaged down) +function Dec.image(self: TheoraDecoder): Types.Image + local y, u, v, cw, ch = self:planes() + local w, h = self.width, self.height + local img = Types.Image.new(w, h, "yuv420p") + local px = img.pixels + local ow, oh = (w + 1) // 2, (h + 1) // 2 + buffer.copy(px, 0, y, 0, w * h) + local st = self._st + if st.hdec == 1 and st.vdec == 1 then + for r = 0, oh - 1 do + local sr = math.min(r, ch - 1) + buffer.copy(px, w * h + r * ow, u, sr * cw, math.min(ow, cw)) + buffer.copy(px, w * h + ow * oh + r * ow, v, sr * cw, math.min(ow, cw)) + end + else + Decoder.downsample(u, cw, ch, st.hdec, px, w * h, ow, oh) + Decoder.downsample(v, cw, ch, st.hdec, px, w * h + ow * oh, ow, oh) + end + img.meta.yuv = { range = "limited", matrix = "bt601" } + img.meta.source = { format = "theora", pixelFormat = self.pixelFormat, colorspace = self.info.colorspace } + return img +end + +-- ------------------------------------------------------------------------------------------------ registry +-- newVideoDecoder(track, opts?) -> a Types.VideoCodecDecoder (the codecs/video/Video entry "theora"): track.config +-- holds the three headers (Xiph-laced, as Matroska's CodecPrivate); one picture per packet, empty packets repeat +function Theora.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + if not track.config then + return nil, Err.new(Err.CORRUPT, "Theora track without its headers") + end + local dec, err = Theora.new(track.config :: buffer, { maxPixels = opts and opts.maxPixels }) + if not dec then + return nil, err + end + local d = dec :: TheoraDecoder + local pending: { any } = {} + local self: any = {} + function self.decode(_: any, packet: Types.Packet): Err.Err? + local kind, e = d:decode(packet.data) + if not kind then + return e + end + if d._any then + table.insert(pending, { d:image(), packet.pts, kind == "key" }) + end + return nil + end + function self.receive(_: any): (Types.Image?, number?, boolean?) + local p = table.remove(pending, 1) + if not p then + return nil, nil, nil + end + return p[1], p[2], p[3] + end + function self.flush(_: any) end + function self.reset(_: any) + table.clear(pending) + d:reset() + end + return self, nil +end + +return Theora diff --git a/src/Formats/codecs/video/Video/init.luau b/src/Formats/codecs/video/Video/init.luau index 0960b9b..d986129 100644 --- a/src/Formats/codecs/video/Video/init.luau +++ b/src/Formats/codecs/video/Video/init.luau @@ -294,6 +294,13 @@ local function h264Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDec return H264.newVideoDecoder(track, opts) end +-- Theora (codecs/video/Theora): track.config = the three headers, Xiph-laced (Matroska's CodecPrivate; video/ogv +-- builds the same); one picture per packet, empty packets repeat the previous one +local function theoraDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local Theora = require("@formats/codecs/video/Theora") + return Theora.newVideoDecoder(track, opts) +end + -- ------------------------------------------------------------------------------------------------ registry -- the codecs known by name (decoders where `new` is set). FourCCs compare case-sensitively first, then upper-cased. local BUILTIN: { Entry } = { @@ -307,7 +314,7 @@ local BUILTIN: { Entry } = { { id = "hevc", name = "H.265 / HEVC", fourcc = { "hvc1", "hev1", "HEVC", "H265" }, matroska = { "V_MPEGH/ISO/HEVC" } }, { id = "vp9", name = "VP9", fourcc = { "VP90", "vp09" }, matroska = { "V_VP9" } }, { id = "av1", name = "AV1", fourcc = { "AV01", "av01" }, matroska = { "V_AV1" } }, - { id = "theora", name = "Theora", matroska = { "V_THEORA" } }, + { id = "theora", name = "Theora", matroska = { "V_THEORA" }, new = theoraDecoder }, { id = "png", name = "PNG", fourcc = { "png ", "MPNG" }, matroska = { "V_PNG" } }, } diff --git a/tests/codecs/theora.luau b/tests/codecs/theora.luau new file mode 100644 index 0000000..f6dbbf9 --- /dev/null +++ b/tests/codecs/theora.luau @@ -0,0 +1,285 @@ +-- codecs/video/Theora tests. Against ffmpeg (tools/fixtures/theora.py, its vp3 decoder = libtheora's output): every +-- frame of every stream, bit-exact (Adler-32 of the native planes of the picture region, as ffmpeg's framecrc): 4:2:0 / +-- 4:2:2 / 4:4:4, qualities 0..10, a 300 kbit/s high-motion stream (4MV, golden frames, multiple qi), picture regions +-- smaller than the coded frame (even sizes from the encoder, odd sizes at offsets patched into the header), frames +-- the encoder dropped (empty packets: ffmpeg outputs nothing, we repeat the previous picture) and one spliced in; +-- image() as yuv420p (4:2:2 / 4:4:4 chroma averaged); Theora in Matroska through the codecs/video/Video registry. +-- Errors: missing / bad headers, maxPixels, header packets in the data, garbage packets; the fuzz no-throw passes +-- (headers, key and inter frames). +local T = require("@tests/T") +local Theora = require("@formats/codecs/video/Theora") +local Video = require("@formats/codecs/video/Video") +local Ogg = require("@formats/containers/Ogg") +local Mkv = require("@formats/video/mkv") +local Bytes = require("@formats/core/Bytes") +local Base64 = require("@formats/core/Base64") +local Adler32 = require("@formats/core/Adler32") +local Err = require("@formats/core/Err") + +local t = T.suite("theora") + +local CASES = { "q6", "q0", "q10", "motion", "odd", "static", "yuv422", "yuv444", "odd444", "crop", "crop422" } +local FIXTURES: { [string]: any } = { + q6 = require("@tests/gen/theora_q6"), + q0 = require("@tests/gen/theora_q0"), + q10 = require("@tests/gen/theora_q10"), + motion = require("@tests/gen/theora_motion"), + odd = require("@tests/gen/theora_odd"), + static = require("@tests/gen/theora_static"), + yuv422 = require("@tests/gen/theora_yuv422"), + yuv444 = require("@tests/gen/theora_yuv444"), + odd444 = require("@tests/gen/theora_odd444"), + crop = require("@tests/gen/theora_crop"), + crop422 = require("@tests/gen/theora_crop422"), +} + +-- the Theora packets of an Ogg file: headers, data packets +local function packets(file: buffer): ({ buffer }, { buffer }) + local d = Ogg.open(file) + local serial = d:find("theora") + local hdrs, data = {}, {} + for p in d:packets(serial) do + if #hdrs < 3 then + table.insert(hdrs, Ogg.copy(p)) + else + table.insert(data, Ogg.copy(p)) + end + end + return hdrs, data +end + +-- ffmpeg's framecrc: Adler-32 started at 0 over the packed planes +local function crc(y: buffer, u: buffer, v: buffer): number + local a = Adler32.of(y, nil, nil, 0) + a = Adler32.of(u, nil, nil, a) + return Adler32.of(v, nil, nil, a) +end + +local samples: { buffer } = {} +local headerSets: { { buffer } } = {} + +-- 1. every fixture, every frame +for _, name in CASES do + local fx = FIXTURES[name] + local hdrs, data = packets(Base64.decode(fx.file) :: buffer) + table.insert(headerSets, hdrs) + local dec, err = Theora.new(hdrs) + t:check(dec ~= nil, name .. ": headers: " .. tostring(err)) + if dec then + t:eq(dec.width, fx.width, name .. ": width") + t:eq(dec.height, fx.height, name .. ": height") + t:eq(dec.pixelFormat, fx.pixfmt, name .. ": pixel format") + local want: { [number]: number } = {} + for _, f in fx.frames do + want[f[1]] = f[2] + end + local bad, dupes, prev = 0, 0, nil :: number? + for k, p in data do + local kind, e = dec:decode(p) + if not kind then + bad += 1 + t:check(false, name .. ": frame " .. (k - 1) .. ": " .. tostring(e)) + continue + end + local y, u, v = dec:planes() + local c = crc(y, u, v) + local w = want[k - 1] + if kind == "dup" then + dupes += 1 + t:check(w == nil, name .. ": ffmpeg shows no frame for empty packet " .. (k - 1)) + if c ~= prev then + bad += 1 + end + elseif w ~= c then + bad += 1 + end + prev = c + end + t:eq(bad, 0, name .. ": frames different from ffmpeg's (of " .. #data .. ", " .. dupes .. " repeated)") + t:eq(#data - dupes, #fx.frames, name .. ": as many shown frames as ffmpeg") + table.insert(samples, data[1]) + if data[2] then + table.insert(samples, data[2]) + end + end +end + +-- 2. an empty packet spliced in after the 5th frame repeats it; the rest follows +do + local fx = require("@tests/gen/theora_dupe") :: any + local hdrs, data = packets(Base64.decode(fx.file) :: buffer) + local dec = Theora.new(hdrs) :: Theora.TheoraDecoder + local bad, prev = 0, nil :: number? + for k, p in data do + local kind = dec:decode(p) + local y, u, v = dec:planes() + local c = crc(y, u, v) + if k == 6 then + t:eq(kind, "dup", "dupe: the empty packet") + t:eq(buffer.len(p), 0, "dupe: it is empty") + t:eq(c, prev, "dupe: repeats the previous picture") + elseif c ~= fx.frames[if k > 6 then k - 1 else k][2] then + bad += 1 + end + prev = c + end + t:eq(bad, 0, "dupe: the other frames") +end + +-- 3. image(): yuv420p, the planes as they are (4:2:0) or averaged (4:2:2 / 4:4:4) +for _, name in { "q6", "crop", "yuv422", "crop422", "odd444" } do + local fx = FIXTURES[name] + local hdrs, data = packets(Base64.decode(fx.file) :: buffer) + local dec = Theora.new(hdrs) :: Theora.TheoraDecoder + dec:decode(data[1]) + dec:decode(data[2]) + local img = dec:image() + local y, u, v, cw, ch = dec:planes() + local w, h = dec.width, dec.height + local ow, oh = (w + 1) // 2, (h + 1) // 2 + t:eq(img.format, "yuv420p", name .. ": image format") + t:eq(img.width * 1000 + img.height, w * 1000 + h, name .. ": image size") + t:eq(buffer.len(img.pixels), w * h + 2 * ow * oh, name .. ": image bytes") + t:eq(Adler32.of(img.pixels, 0, w * h), Adler32.of(y), name .. ": luma") + local bad = 0 + for r = 0, oh - 1 do + for c = 0, ow - 1 do + local want + if fx.pixfmt == "yuv420p" then + want = buffer.readu8(u, math.min(r, ch - 1) * cw + c) + elseif fx.pixfmt == "yuv422p" then + want = (buffer.readu8(u, math.min(2 * r, ch - 1) * cw + c) + buffer.readu8(u, math.min(2 * r + 1, ch - 1) * cw + c) + 1) // 2 + else + local r0, r1 = math.min(2 * r, ch - 1), math.min(2 * r + 1, ch - 1) + local c0, c1 = math.min(2 * c, cw - 1), math.min(2 * c + 1, cw - 1) + want = (buffer.readu8(u, r0 * cw + c0) + buffer.readu8(u, r0 * cw + c1) + buffer.readu8(u, r1 * cw + c0) + buffer.readu8(u, r1 * cw + c1) + 2) // 4 + end + if buffer.readu8(img.pixels, w * h + r * ow + c) ~= want then + bad += 1 + end + end + end + t:eq(bad, 0, name .. ": U downsampled") + local _ = v + t:eq(img.meta.yuv and img.meta.yuv.matrix, "bt601", name .. ": colour matrix") +end + +-- 4. Theora in Matroska: the registry entry (V_THEORA, Xiph-laced CodecPrivate) through video/mkv +do + t:eq(Video.fromMatroska("V_THEORA"), "theora", "registry: V_THEORA") + t:check(Video.canDecode("theora"), "registry: theora decodes") + local fx = require("@tests/gen/theora_mkv") :: any + local v, err = Mkv.open(Bytes.reader(Base64.decode(fx.file) :: buffer)) + t:check(v ~= nil, "mkv: open: " .. tostring(err)) + if v then + t:eq(v.codec, "theora", "mkv: codec") + local n, bad, shown = 0, 0, 0 + local want: { [number]: number } = {} + for _, f in fx.frames do + want[f[1]] = f[2] + end + while true do + local f, e = v:nextFrame() + if not f then + t:check(e == nil, "mkv: frames: " .. tostring(e)) + break + end + local img = f.image + local w = want[math.floor(f.pts * 25 + 0.5)] + if w then + shown += 1 + if Adler32.of(img.pixels, nil, nil, 0) ~= w then + bad += 1 + end + end + n += 1 + end + t:eq(bad, 0, "mkv: frames as ffmpeg's") + t:eq(shown, #fx.frames, "mkv: every frame ffmpeg shows") + end +end + +-- 5. API details and errors +do + local fx = FIXTURES.q6 + local hdrs, data = packets(Base64.decode(fx.file) :: buffer) + local dec = Theora.new(hdrs) :: Theora.TheoraDecoder + t:eq(dec.frameRate, 25, "frame rate") + t:check(dec.vendor ~= "" and dec.tags.encoder ~= nil, "comment header: vendor and ENCODER tag") + t:eq(Theora.isHeader(hdrs[1]), 1, "isHeader: identification") + t:eq(Theora.isHeader(hdrs[3]), 3, "isHeader: setup") + t:eq(Theora.isHeader(data[1]), nil, "isHeader: data") + local kind, e = dec:decode(hdrs[2]) + t:check(kind == nil and e == nil, "a header packet in the data is skipped") + t:eq(Theora.granuleFrame(dec.info, 0), -1, "granule 0 (3.2.1 numbering)") + t:eq(Theora.granuleFrame(dec.info, 2 ^ dec.info.granuleShift * 12 + 3), 14, "granule: keyframe 12 + 3") + -- the Xiph-laced config Matroska uses + local lens = { buffer.len(hdrs[1]), buffer.len(hdrs[2]) } + local w = Bytes.writer(64) + w:u8(2) + for _, l in lens do + local x = l + while x >= 255 do + w:u8(255) + x -= 255 + end + w:u8(x) + end + for _, h in hdrs do + w:bytes(h) + end + local cfg = w:finish() + local parts = Theora.splitConfig(cfg) + t:check(parts ~= nil and #parts == 3 and buffer.len(parts[3]) == buffer.len(hdrs[3]), "splitConfig") + t:check(Theora.new(cfg) ~= nil, "new(config)") + local d2, e2 = Theora.new({ hdrs[1], hdrs[2] }) + t:check(d2 == nil and e2 ~= nil and e2.code == Err.CORRUPT, "missing setup header: CORRUPT") + local _, e3 = Theora.new({ hdrs[2], hdrs[1], hdrs[3] }) + t:check(e3 ~= nil and e3.code == Err.CORRUPT, "headers out of order: CORRUPT") + local cut = buffer.create(100) + buffer.copy(cut, 0, hdrs[3], 0, 100) + local _, e4 = Theora.new({ hdrs[1], hdrs[2], cut }) + t:check(e4 ~= nil, "truncated setup header: " .. tostring(e4)) + local _, e5 = Theora.new(hdrs, { maxPixels = 1000 }) + t:check(e5 ~= nil and e5.code == Err.LIMIT, "maxPixels: LIMIT") + local _, e6 = dec:decode(data[1], 5, buffer.len(data[1])) + t:check(e6 ~= nil and e6.code == Err.ARG, "decode: range outside the buffer") + -- an inter frame before any keyframe decodes over grey + local fresh = Theora.new(hdrs) :: Theora.TheoraDecoder + t:check(fresh:decode(data[2]) == "inter", "an inter frame first") + local track: any = { id = 1, kind = "video", codec = "theora", timescale = 25, config = cfg } + local vd = Theora.newVideoDecoder(track) + t:check(vd ~= nil, "newVideoDecoder") + if vd then + vd:decode({ track = 1, pts = 0, keyframe = true, data = data[1] }) + local img, pts, key = vd:receive() + t:check(img ~= nil and pts == 0 and key == true, "newVideoDecoder: a keyframe picture") + vd:reset() + t:check(vd:receive() == nil, "newVideoDecoder: reset drops pending pictures") + end + local nv, nerr = Theora.newVideoDecoder({ id = 1, kind = "video", codec = "theora", timescale = 25 } :: any) + t:check(nv == nil and nerr ~= nil, "newVideoDecoder without config") +end + +-- 6. fuzz: headers, keyframes and inter frames (a decoder primed with a keyframe, fed mutated packets) +do + local hdrs = headerSets[1] + t:fuzz("headers", function(b: buffer) + return Theora.new({ hdrs[1], hdrs[2], b }) + end, { hdrs[3] }, { mutations = 24, garbage = 50 }) + t:fuzz("identification", function(b: buffer) + return Theora.new({ b, hdrs[2], hdrs[3] }) + end, { hdrs[1] }, { mutations = 24, garbage = 20 }) + for i, h in headerSets do + local dec = Theora.new(h) :: Theora.TheoraDecoder + local s = { samples[2 * i - 1], samples[2 * i] } + dec:decode(s[1]) + t:fuzz("frames " .. CASES[i], function(b: buffer) + local kind = dec:decode(b) + dec:planes() + return kind + end, s, { mutations = 12, garbage = 20, seed = i }) + end +end + +t:done() diff --git a/tools/fixtures/theora.py b/tools/fixtures/theora.py new file mode 100644 index 0000000..4395444 --- /dev/null +++ b/tools/fixtures/theora.py @@ -0,0 +1,195 @@ +# 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_.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_mkv.luau { file (base64 .mkv), frames } +# tests/gen/theora_bench.luau { file (base64 .ogv, 320x240) } 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("> 24) ^ x) & 0xFF]) & 0xFFFFFFFF + return c + + +def page(flags, granule, serial, seq, packets_segs, body): + head = b"OggS" + bytes([0, flags]) + struct.pack("> 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(" Date: Sat, 31 Oct 2026 14:19:46 -0500 Subject: [PATCH 05/27] ws-roblox: codecs/model/Rbx (RbxTree, typed values, CFrame rotation ids, binary property columns), model/rbxm (binary rbxm / rbxl read + write; LZ4 / Zstd / raw chunks; unknown chunks and property types round trip raw), model/rbxmx (XML rbxmx / rbxlx read + write); tests vs rojo 7.7 + lune 0.11 both ways init.luau: KIND_CATEGORY gains rbxtree = model (F.save of an RbxTree finds the model category). --- docs/FORMATS.md | 3 + src/Formats/Registry.luau | 24 + src/Formats/codecs/model/Rbx/Binary.luau | 774 +++++++++++++++++++++++ src/Formats/codecs/model/Rbx/init.luau | 281 ++++++++ src/Formats/init.luau | 1 + src/Formats/model/rbxm/init.luau | 575 +++++++++++++++++ src/Formats/model/rbxmx/init.luau | 661 +++++++++++++++++++ tests/model/_rbx.luau | 286 +++++++++ tests/model/rbxm.luau | 251 ++++++++ tests/model/rbxmx.luau | 188 ++++++ tools/fixtures/_rbx_encode.luau | 27 + tools/fixtures/rbxmx.py | 492 ++++++++++++++ 12 files changed, 3563 insertions(+) create mode 100644 src/Formats/codecs/model/Rbx/Binary.luau create mode 100644 src/Formats/codecs/model/Rbx/init.luau create mode 100644 src/Formats/model/rbxm/init.luau create mode 100644 src/Formats/model/rbxmx/init.luau create mode 100644 tests/model/_rbx.luau create mode 100644 tests/model/rbxm.luau create mode 100644 tests/model/rbxmx.luau create mode 100644 tools/fixtures/_rbx_encode.luau create mode 100644 tools/fixtures/rbxmx.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 2fe168c..ed39b7b 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -41,6 +41,8 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` | | model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` | | model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` | +| model | rbxm | .rbxm .rbxl | yes | yes | tree: true, compression: "none", "lz4", "zstd" | `tests/model/rbxm.luau` | +| model | rbxmx | .rbxmx .rbxlx | yes | yes | tree: true | `tests/model/rbxmx.luau` | | model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` | | model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` | | model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` | @@ -127,6 +129,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - **model** - codecs/model/Mat4: 4x4 matrix and quaternion helpers for the model formats: column-major flat arrays of 16 - codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks + - codecs/model/Rbx: the Roblox instance tree every Roblox file format maps to (model/rbxm binary rbxm / rbxl, - **text** - codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. - codecs/text/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6c0344c..b959ea9 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -446,6 +446,30 @@ local list: { Entry } = { return require("@formats/model/ply") end, }, + { + name = "rbxm", + category = "model", + path = "model/rbxm", + extensions = { "rbxm", "rbxl" }, + mime = { "application/x-roblox-rbxm", "application/x-roblox-rbxl" }, + deps = { "core/Err", "core/Bytes", "core/Md5", "codecs/compress/Lz4", "codecs/compress/Zstd", "codecs/model/Rbx", "codecs/model/Rbx/Binary" }, + caps = { decode = true, encode = true, tree = true, compression = { "none", "lz4", "zstd" } }, + load = function() + return require("@formats/model/rbxm") + end, + }, + { + name = "rbxmx", + category = "model", + path = "model/rbxmx", + extensions = { "rbxmx", "rbxlx" }, + mime = { "application/x-roblox-rbxmx", "application/x-roblox-rbxlx" }, + deps = { "core/Err", "core/Bytes", "core/Base64", "core/Md5", "codecs/text/Xml", "codecs/model/Rbx" }, + caps = { decode = true, encode = true, tree = true }, + load = function() + return require("@formats/model/rbxmx") + end, + }, { name = "stl", category = "model", diff --git a/src/Formats/codecs/model/Rbx/Binary.luau b/src/Formats/codecs/model/Rbx/Binary.luau new file mode 100644 index 0000000..eb5636e --- /dev/null +++ b/src/Formats/codecs/model/Rbx/Binary.luau @@ -0,0 +1,774 @@ +--!strict +--!native +--!optimize 2 +-- codecs/model/Rbx/Binary: the property columns of the Roblox binary format (rbx-dom docs/binary.md): one PROP chunk +-- holds a property's values for every instance of a class, by type id, with the format's array transforms: byte +-- interleaving (all first bytes, then all second bytes, ...), big-endian integers, zigzag signed integers, "rotated" +-- floats (sign bit moved to bit 0), delta-coded referents, and CFrame rotation ids (codecs/model/Rbx). Never throws. +-- +-- local values, pEnd = Binary.decode(typeId, buf, p, limit, n, ctx) -- n plain values (codecs/model/Rbx forms) +-- local err = Binary.encode(typeId, values, n, writer, ctx) -- nil, or a message +-- Binary.readRefs(buf, p, limit, n) / Binary.writeRefs(writer, refs) -- referent arrays (INST, PRNT) +-- +-- ctx: { ref = function(referent) -> Instance? (decode), refOf = function(Instance?) -> referent (-1 = none), +-- shared = { string } (SSTR entries, 1-based, decode), sharedIndex = function(string) -> 0-based index (encode) }. +-- decode returns nil, message on bad data ("truncated", "corrupt: ...", "unknown" for a type id it does not know / +-- a layout it cannot read, which the format keeps raw). +local Rbx = require("@formats/codecs/model/Rbx") +local Bytes = require("@formats/core/Bytes") + +local Binary = {} + +local readu8, readu16, readi16, readu32, readf32, readf64 = + buffer.readu8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readf32, buffer.readf64 +local writeu32, readstring = buffer.writeu32, buffer.readstring +local writef32 = buffer.writef32 +local floor = math.floor + +local scratch = buffer.create(8) +local TWO32 = 4294967296 + +-- ------------------------------------------------------------------------------------------------ transforms +-- the rotated float encoding: bits rotated left by one (sign in bit 0) +local function unrotate(x: number): number + writeu32(scratch, 0, x // 2 + (x % 2) * 2147483648) + return readf32(scratch, 0) +end +local function rotate(v: number): number + writef32(scratch, 0, v) + local bits = readu32(scratch, 0) + return (bits * 2) % TWO32 + bits // 2147483648 +end +local function unzigzag(x: number): number + return if x % 2 == 0 then x // 2 else -(x + 1) // 2 +end +local function zigzag32(v: number): number + v = floor(v) + return (if v >= 0 then v * 2 else -v * 2 - 1) % TWO32 +end + +-- n big-endian u32 values interleaved at p (4n bytes) +local function u32s(b: buffer, p: number, n: number): { number } + local out = table.create(n, 0) + local n2, n3 = n * 2, n * 3 + for i = 0, n - 1 do + out[i + 1] = readu8(b, p + i) * 16777216 + readu8(b, p + n + i) * 65536 + readu8(b, p + n2 + i) * 256 + readu8(b, p + n3 + i) + end + return out +end +local function i32s(b: buffer, p: number, n: number): { number } + local out = u32s(b, p, n) + for i = 1, n do + out[i] = unzigzag(out[i]) + end + return out +end +local function f32s(b: buffer, p: number, n: number): { number } + local out = u32s(b, p, n) + for i = 1, n do + out[i] = unrotate(out[i]) + end + return out +end +-- n zigzag i64 values (8n interleaved bytes), as doubles +local function i64s(b: buffer, p: number, n: number): { number } + local out = table.create(n, 0) + for i = 0, n - 1 do + local hi = readu8(b, p + i) * 16777216 + readu8(b, p + n + i) * 65536 + readu8(b, p + 2 * n + i) * 256 + readu8(b, p + 3 * n + i) + local lo = readu8(b, p + 4 * n + i) * 16777216 + readu8(b, p + 5 * n + i) * 65536 + readu8(b, p + 6 * n + i) * 256 + readu8(b, p + 7 * n + i) + local half = hi * 2147483648 + lo // 2 + out[i + 1] = if lo % 2 == 0 then half else -half - 1 + end + return out +end + +-- writers: n values interleaved as big-endian u32 / zigzag i32 / rotated f32 / zigzag i64 +local function putU32s(w: Bytes.Writer, vals: { number }) + local n = #vals + local p = w:reserve(4 * n) + local b = w.buf + for i = 0, n - 1 do + local v = vals[i + 1] % TWO32 + buffer.writeu8(b, p + i, v // 16777216) + buffer.writeu8(b, p + n + i, (v // 65536) % 256) + buffer.writeu8(b, p + 2 * n + i, (v // 256) % 256) + buffer.writeu8(b, p + 3 * n + i, v % 256) + end + w.pos = p + 4 * n +end +local function putI32s(w: Bytes.Writer, vals: { number }) + local t = table.create(#vals, 0) + for i, v in vals do + t[i] = zigzag32(v) + end + putU32s(w, t) +end +local function putF32s(w: Bytes.Writer, vals: { number }) + local t = table.create(#vals, 0) + for i, v in vals do + t[i] = rotate(v) + end + putU32s(w, t) +end +local function putI64s(w: Bytes.Writer, vals: { number }) + local n = #vals + local p = w:reserve(8 * n) + local b = w.buf + for i = 0, n - 1 do + local v = floor(vals[i + 1]) + local z = if v >= 0 then v * 2 else -v * 2 - 1 + local hi, lo = (z // TWO32) % TWO32, z % TWO32 + buffer.writeu8(b, p + i, hi // 16777216) + buffer.writeu8(b, p + n + i, (hi // 65536) % 256) + buffer.writeu8(b, p + 2 * n + i, (hi // 256) % 256) + buffer.writeu8(b, p + 3 * n + i, hi % 256) + buffer.writeu8(b, p + 4 * n + i, lo // 16777216) + buffer.writeu8(b, p + 5 * n + i, (lo // 65536) % 256) + buffer.writeu8(b, p + 6 * n + i, (lo // 256) % 256) + buffer.writeu8(b, p + 7 * n + i, lo % 256) + end + w.pos = p + 8 * n +end + +-- referent arrays: zigzag i32, interleaved, each the difference from the previous one +function Binary.readRefs(b: buffer, p: number, limit: number, n: number): ({ number }?, number) + if n < 0 or p + 4 * n > limit then + return nil, p + end + local out = i32s(b, p, n) + local acc = 0 + for i = 1, n do + acc += out[i] + out[i] = acc + end + return out, p + 4 * n +end +function Binary.writeRefs(w: Bytes.Writer, refs: { number }) + local d = table.create(#refs, 0) + local prev = 0 + for i, r in refs do + d[i] = r - prev + prev = r + end + putI32s(w, d) +end + +-- ------------------------------------------------------------------------------------------------ decode +export type Ctx = { + ref: ((number) -> any)?, + refOf: ((any) -> number)?, + shared: { string }?, + sharedIndex: ((string) -> number)?, +} + +-- a length-prefixed string at p: string, next p (nil when it runs past limit) +local function str(b: buffer, p: number, limit: number): (string?, number) + if p + 4 > limit then + return nil, p + end + local len = readu32(b, p) + if p + 4 + len > limit then + return nil, p + end + return readstring(b, p + 4, len), p + 4 + len +end + +local function cframes(b: buffer, p: number, limit: number, n: number): ({ any }?, number) + local rots: { { number } } = table.create(n) :: any + for i = 1, n do + if p >= limit then + return nil, p + end + local id = readu8(b, p) + p += 1 + if id == 0 then + if p + 36 > limit then + return nil, p + end + local m = table.create(9, 0) + for k = 0, 8 do + m[k + 1] = readf32(b, p + 4 * k) + end + rots[i] = m + p += 36 + else + local m = Rbx.ROTATIONS[id] + if not m then + return nil, -1 + end + rots[i] = m + end + end + if p + 12 * n > limit then + return nil, p + end + local xs, ys, zs = f32s(b, p, n), f32s(b, p + 4 * n, n), f32s(b, p + 8 * n, n) + local out = table.create(n) + for i = 1, n do + local m = rots[i] + out[i] = { xs[i], ys[i], zs[i], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9] } + end + return out, p + 12 * n +end + +local FIXED: { [number]: number } = { -- bytes per value of the fixed-size types + [0x02] = 1, + [0x03] = 4, + [0x04] = 4, + [0x05] = 8, + [0x06] = 8, + [0x07] = 16, + [0x08] = 24, + [0x09] = 1, + [0x0A] = 1, + [0x0B] = 4, + [0x0C] = 12, + [0x0D] = 8, + [0x0E] = 12, + [0x0F] = 4, + [0x12] = 4, + [0x13] = 4, + [0x14] = 6, + [0x17] = 8, + [0x18] = 16, + [0x1A] = 3, + [0x1B] = 8, + [0x1C] = 4, + [0x1F] = 16, + [0x21] = 8, +} + +-- decode(typeId, b, p, limit, n, ctx) -> n values, the end offset | nil, message +function Binary.decode(t: number, b: buffer, p: number, limit: number, n: number, ctx: Ctx): ({ any }?, any) + if limit > buffer.len(b) or p < 0 or n < 0 then + return nil, "corrupt: bad ranges" + end + local size = FIXED[t] + if size and p + size * n > limit then + return nil, "truncated property values" + end + if t == 0x01 or t == 0x1D then + local out = table.create(n, "") + for i = 1, n do + local s, q = str(b, p, limit) + if not s then + return nil, "truncated string" + end + out[i] = s + p = q + end + return out, p + elseif t == 0x02 then + local out = table.create(n, false) + for i = 1, n do + out[i] = readu8(b, p + i - 1) ~= 0 + end + return out, p + n + elseif t == 0x03 then + return i32s(b, p, n), p + 4 * n + elseif t == 0x04 then + return f32s(b, p, n), p + 4 * n + elseif t == 0x05 then + local out = table.create(n, 0) + for i = 1, n do + out[i] = readf64(b, p + 8 * (i - 1)) + end + return out, p + 8 * n + elseif t == 0x06 then + local s, o = f32s(b, p, n), i32s(b, p + 4 * n, n) + local out = table.create(n) + for i = 1, n do + out[i] = { s[i], o[i] } + end + return out, p + 8 * n + elseif t == 0x07 then + local xs, ys, xo, yo = f32s(b, p, n), f32s(b, p + 4 * n, n), i32s(b, p + 8 * n, n), i32s(b, p + 12 * n, n) + local out = table.create(n) + for i = 1, n do + out[i] = { xs[i], xo[i], ys[i], yo[i] } + end + return out, p + 16 * n + elseif t == 0x08 then + local out = table.create(n) + for i = 1, n do + local q = p + 24 * (i - 1) + out[i] = { readf32(b, q), readf32(b, q + 4), readf32(b, q + 8), readf32(b, q + 12), readf32(b, q + 16), readf32(b, q + 20) } + end + return out, p + 24 * n + elseif t == 0x09 or t == 0x0A then + local out = table.create(n, 0) + for i = 1, n do + out[i] = readu8(b, p + i - 1) + end + return out, p + n + elseif t == 0x0B or t == 0x12 then + return u32s(b, p, n), p + 4 * n + elseif t == 0x0C or t == 0x0E or t == 0x0D or t == 0x18 then + local k = if t == 0x0D then 2 elseif t == 0x18 then 4 else 3 + local cols: { { number } } = table.create(k) :: any + for c = 1, k do + cols[c] = f32s(b, p + 4 * n * (c - 1), n) + end + local out = table.create(n) + for i = 1, n do + local v = table.create(k, 0) + for c = 1, k do + v[c] = cols[c][i] + end + out[i] = v + end + return out, p + 4 * k * n + elseif t == 0x0F or t == 0x14 then + local k = if t == 0x0F then 2 else 3 + local out = table.create(n) + for i = 1, n do + local q = p + 2 * k * (i - 1) + out[i] = if k == 2 then { readi16(b, q), readi16(b, q + 2) } else { readi16(b, q), readi16(b, q + 2), readi16(b, q + 4) } + end + return out, p + 2 * k * n + elseif t == 0x10 then + local out, q = cframes(b, p, limit, n) + if not out then + return nil, if q == -1 then "corrupt: bad CFrame rotation id" else "truncated CFrame values" + end + return out, q + elseif t == 0x13 then + local refs, q = Binary.readRefs(b, p, limit, n) + if not refs then + return nil, "truncated referents" + end + local out = table.create(n) + local ref = ctx.ref + for i = 1, n do + out[i] = if ref and refs[i] >= 0 then ref(refs[i]) else nil + end + return out, q + elseif t == 0x15 or t == 0x16 then + local k = if t == 0x15 then 3 else 5 + local out = table.create(n) + for i = 1, n do + if p + 4 > limit then + return nil, "truncated sequence" + end + local count = readu32(b, p) + p += 4 + if p + count * 4 * k > limit then + return nil, "truncated sequence" + end + local seq = table.create(count) + for j = 1, count do + local key = table.create(k, 0) + for c = 1, k do + key[c] = readf32(b, p + 4 * (c - 1)) + end + seq[j] = key + p += 4 * k + end + out[i] = seq + end + return out, p + elseif t == 0x17 then + local out = table.create(n) + for i = 1, n do + out[i] = { readf32(b, p + 8 * (i - 1)), readf32(b, p + 8 * (i - 1) + 4) } + end + return out, p + 8 * n + elseif t == 0x19 then + local out = table.create(n) + for i = 1, n do + if p >= limit then + return nil, "truncated physical properties" + end + local flag = readu8(b, p) + p += 1 + if flag % 2 == 1 then + local k = if flag // 2 % 2 == 1 then 6 else 5 + if p + 4 * k > limit then + return nil, "truncated physical properties" + end + local v = table.create(6, 1) -- acoustic absorption 1 when the file leaves it out + for c = 1, k do + v[c] = readf32(b, p + 4 * (c - 1)) + end + out[i] = v + p += 4 * k + elseif flag ~= 0 then + return nil, "unknown" + end + end + return out, p + elseif t == 0x1A then + local out = table.create(n) + for i = 1, n do + out[i] = { readu8(b, p + i - 1), readu8(b, p + n + i - 1), readu8(b, p + 2 * n + i - 1) } + end + return out, p + 3 * n + elseif t == 0x1B or t == 0x21 then + return i64s(b, p, n), p + 8 * n + elseif t == 0x1C then + local idx = u32s(b, p, n) + local shared: { string } = ctx.shared or {} + local out: { string } = table.create(n, "") + for i = 1, n do + local s = shared[idx[i] + 1] + if s == nil then + return nil, "corrupt: shared string index out of range" + end + out[i] = s + end + return out, p + 4 * n + elseif t == 0x1E then + if p >= limit or readu8(b, p) ~= 0x10 then + return nil, "unknown" + end + local cfs, q = cframes(b, p + 1, limit, n) + if not cfs then + return nil, if q == -1 then "corrupt: bad CFrame rotation id" else "truncated CFrame values" + end + if q + 1 + n > limit or readu8(b, q) ~= 0x02 then + return nil, "truncated optional CFrame flags" + end + local out = table.create(n) + for i = 1, n do + out[i] = if readu8(b, q + i) ~= 0 then cfs[i] else nil + end + return out, q + 1 + n + elseif t == 0x1F then + local out = table.create(n, "") + local hex = table.create(16, "") + for i = 0, n - 1 do + local by = table.create(16, 0) + for k = 0, 15 do + by[k + 1] = readu8(b, p + k * n + i) + end + -- bytes 8..15: the random part rotated left by one bit (as a 64-bit integer); undo it + local carry = by[16] % 2 + for k = 9, 16 do + local v = by[k] + by[k] = v // 2 + carry * 128 + carry = v % 2 + end + for k = 1, 8 do + hex[k] = string.format("%02x", by[8 + k]) + end + for k = 1, 8 do + hex[8 + k] = string.format("%02x", by[k + 4 - (if k > 4 then 8 else 0)]) + end + out[i + 1] = table.concat(hex) + end + return out, p + 16 * n + elseif t == 0x20 then + local out = table.create(n) + for i = 1, n do + local fam, q = str(b, p, limit) + if not fam or q + 3 > limit then + return nil, "truncated font" + end + local weight, style = readu16(b, q), readu8(b, q + 2) + local face, q2 = str(b, q + 3, limit) + if not face then + return nil, "truncated font" + end + out[i] = { family = fam, weight = weight, style = if style == 1 then "Italic" else "Normal", cachedFaceId = if face ~= "" then face else nil } + p = q2 + end + return out, p + elseif t == 0x22 then + if p + 4 * n > limit then + return nil, "truncated content" + end + local kinds = i32s(b, p, n) + p += 4 * n + if p + 4 > limit then + return nil, "truncated content" + end + local nu = readu32(b, p) + p += 4 + local uris = table.create(math.min(nu, n)) + for j = 1, nu do + local s, q = str(b, p, limit) + if not s then + return nil, "truncated content" + end + uris[j] = s + p = q + end + if p + 4 > limit then + return nil, "truncated content" + end + local no = readu32(b, p) + local objs, q = Binary.readRefs(b, p + 4, limit, no) + if not objs or q + 4 > limit then + return nil, "truncated content" + end + if readu32(b, q) ~= 0 then + return nil, "unknown" -- external objects: kept raw + end + p = q + 4 + local out = table.create(n) + local iu, io = 1, 1 + for i = 1, n do + local k = kinds[i] + if k == 1 then + if iu > nu then + return nil, "corrupt: content uri count" + end + out[i] = uris[iu] + iu += 1 + elseif k == 2 then + if io > no then + return nil, "corrupt: content object count" + end + local r = objs[io] + out[i] = if ctx.ref and r >= 0 then ctx.ref(r) else nil + io += 1 + elseif k ~= 0 then + return nil, "unknown" + end + end + return out, p + end + return nil, "unknown" +end + +-- ------------------------------------------------------------------------------------------------ encode +local function num(v: any): number + return if type(v) == "number" and v == v then v else 0 +end +-- column c of n array values (missing components 0) +local function column(vals: { any }, n: number, c: number): { number } + local out = table.create(n, 0) + for i = 1, n do + local v = vals[i] + out[i] = if type(v) == "table" then num(v[c]) else 0 + end + return out +end + +local function putString(w: Bytes.Writer, s: string) + w:u32le(#s) + w:string(s) +end + +local function putCFrames(w: Bytes.Writer, vals: { any }, n: number) + for i = 1, n do + local v = vals[i] + local cf = if type(v) == "table" then v else { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 } + local id = Rbx.rotationId(cf) + w:u8(id) + if id == 0 then + for k = 4, 12 do + w:f32le(num(cf[k])) + end + end + end + putF32s(w, column(vals, n, 1)) + putF32s(w, column(vals, n, 2)) + putF32s(w, column(vals, n, 3)) +end + +local function hexByte(s: string, i: number): number + return tonumber(string.sub(s, 2 * i - 1, 2 * i), 16) or 0 +end + +-- encode(typeId, values, n, w, ctx) -> nil | message: values[1 .. n] in the codecs/model/Rbx forms (nil entries are +-- the type's none / default) +function Binary.encode(t: number, vals: { any }, n: number, w: Bytes.Writer, ctx: Ctx): string? + if t == 0x01 or t == 0x1D then + for i = 1, n do + local v = vals[i] + putString(w, if type(v) == "string" then v else "") + end + elseif t == 0x02 then + for i = 1, n do + w:u8(if vals[i] then 1 else 0) + end + elseif t == 0x03 then + local c = table.create(n, 0) + for i = 1, n do + c[i] = num(vals[i]) + end + putI32s(w, c) + elseif t == 0x04 then + local c = table.create(n, 0) + for i = 1, n do + c[i] = num(vals[i]) + end + putF32s(w, c) + elseif t == 0x05 then + for i = 1, n do + w:f64le(num(vals[i])) + end + elseif t == 0x06 then + putF32s(w, column(vals, n, 1)) + putI32s(w, column(vals, n, 2)) + elseif t == 0x07 then + putF32s(w, column(vals, n, 1)) + putF32s(w, column(vals, n, 3)) + putI32s(w, column(vals, n, 2)) + putI32s(w, column(vals, n, 4)) + elseif t == 0x08 then + for i = 1, n do + local v = vals[i] + for c = 1, 6 do + w:f32le(if type(v) == "table" then num(v[c]) else 0) + end + end + elseif t == 0x09 or t == 0x0A then + for i = 1, n do + w:u8(num(vals[i]) % 256) + end + elseif t == 0x0B or t == 0x12 then + local c = table.create(n, 0) + for i = 1, n do + c[i] = floor(num(vals[i])) + end + putU32s(w, c) + elseif t == 0x0C or t == 0x0E or t == 0x0D or t == 0x18 then + local k = if t == 0x0D then 2 elseif t == 0x18 then 4 else 3 + for c = 1, k do + putF32s(w, column(vals, n, c)) + end + elseif t == 0x0F or t == 0x14 then + local k = if t == 0x0F then 2 else 3 + for i = 1, n do + local v = vals[i] + for c = 1, k do + local x = floor(if type(v) == "table" then num(v[c]) else 0) % 65536 + w:u16le(x) + end + end + elseif t == 0x10 then + putCFrames(w, vals, n) + elseif t == 0x13 then + local refs = table.create(n, -1) + local refOf = ctx.refOf + for i = 1, n do + refs[i] = if refOf and vals[i] ~= nil then refOf(vals[i]) else -1 + end + Binary.writeRefs(w, refs) + elseif t == 0x15 or t == 0x16 then + local k = if t == 0x15 then 3 else 5 + for i = 1, n do + local seq = vals[i] + if type(seq) ~= "table" then + seq = {} + end + w:u32le(#seq) + for _, key in seq do + for c = 1, k do + w:f32le(if type(key) == "table" then num(key[c]) else 0) + end + end + end + elseif t == 0x17 then + for i = 1, n do + local v = vals[i] + w:f32le(if type(v) == "table" then num(v[1]) else 0) + w:f32le(if type(v) == "table" then num(v[2]) else 0) + end + elseif t == 0x19 then + for i = 1, n do + local v = vals[i] + if type(v) ~= "table" then + w:u8(0) + else + local acoustic = v[6] ~= nil and v[6] ~= 1 -- (rbx-dom leaves the default out) + w:u8(if acoustic then 3 else 1) + for c = 1, if acoustic then 6 else 5 do + w:f32le(num(v[c])) + end + end + end + elseif t == 0x1A then + for c = 1, 3 do + for i = 1, n do + local v = vals[i] + w:u8(math.clamp(floor(if type(v) == "table" then num(v[c]) else 0), 0, 255)) + end + end + elseif t == 0x1B or t == 0x21 then + local c = table.create(n, 0) + for i = 1, n do + c[i] = num(vals[i]) + end + putI64s(w, c) + elseif t == 0x1C then + local idx = table.create(n, 0) + local si = ctx.sharedIndex + for i = 1, n do + local v = vals[i] + idx[i] = if si then si(if type(v) == "string" then v else "") else 0 + end + putU32s(w, idx) + elseif t == 0x1E then + w:u8(0x10) + putCFrames(w, vals, n) + w:u8(0x02) + for i = 1, n do + w:u8(if type(vals[i]) == "table" then 1 else 0) + end + elseif t == 0x1F then + local p = w:reserve(16 * n) + local b = w.buf + for i = 0, n - 1 do + local s = vals[i + 1] + if type(s) ~= "string" or #s ~= 32 or string.find(s, "[^%x]") then + return "a UniqueId is 32 hex digits" + end + -- index (hex 25..32) and time (17..24) first, then the random part (1..16) rotated left by one bit + local by = table.create(16, 0) + for k = 1, 4 do + by[k] = hexByte(s, 12 + k) + by[4 + k] = hexByte(s, 8 + k) + end + local top = hexByte(s, 1) // 128 + for k = 1, 8 do + local v = hexByte(s, k) + local nxt = if k < 8 then hexByte(s, k + 1) // 128 else top + by[8 + k] = (v * 2) % 256 + nxt + end + for k = 0, 15 do + buffer.writeu8(b, p + k * n + i, by[k + 1]) + end + end + w.pos = p + 16 * n + elseif t == 0x20 then + for i = 1, n do + local v = vals[i] + if type(v) ~= "table" then + v = Rbx.default("Font") + end + putString(w, if type(v.family) == "string" then v.family else "") + w:u16le(math.clamp(floor(num(v.weight)), 0, 65535)) + w:u8(if v.style == "Italic" then 1 else 0) + putString(w, if type(v.cachedFaceId) == "string" then v.cachedFaceId else "") + end + elseif t == 0x22 then + local kinds, uris, objs = table.create(n, 0), {}, {} + local refOf = ctx.refOf + for i = 1, n do + local v = vals[i] + if type(v) == "string" then + kinds[i] = 1 + table.insert(uris, v) + elseif type(v) == "table" then + kinds[i] = 2 + table.insert(objs, if refOf then refOf(v) else -1) + end + end + putI32s(w, kinds) + w:u32le(#uris) + for _, s in uris do + putString(w, s) + end + w:u32le(#objs) + Binary.writeRefs(w, objs) + w:u32le(0) + else + return "unknown type id " .. t + end + return nil +end + +return Binary diff --git a/src/Formats/codecs/model/Rbx/init.luau b/src/Formats/codecs/model/Rbx/init.luau new file mode 100644 index 0000000..ac3142c --- /dev/null +++ b/src/Formats/codecs/model/Rbx/init.luau @@ -0,0 +1,281 @@ +--!strict +-- codecs/model/Rbx: the Roblox instance tree every Roblox file format maps to (model/rbxm binary rbxm / rbxl, +-- model/rbxmx XML rbxmx / rbxlx), the typed property values, the CFrame rotation IDs, and (codecs/model/Rbx/Binary) the +-- binary format's property column codecs. Shared here because a format cannot require another one. Written from the +-- rbx-dom format notes (docs/binary.md, docs/xml.md) and checked against rbx-dom through rojo / lune. A file library, +-- not a Roblox runtime: nothing here creates Instances; a Roblox game reads the tree itself. +-- +-- local tree = Rbx.tree() -- { kind = "rbxtree", roots = {}, place = false, ... } +-- local part = Rbx.instance("Part", "Floor") -- { className, name, properties = {}, children = {} } +-- Rbx.set(part, "Size", "Vector3", { 64, 1, 64 }) -- properties.Size = { type = "Vector3", value = {...} } +-- Rbx.add(tree, part) -- a root; Rbx.add(parentInstance, child) nests +-- for inst, depth in Rbx.descendants(tree) do ... end +-- +-- Property values are { type = , value = } with these value forms (arrays follow the Roblox constructor +-- argument order, so Vector3.new(table.unpack(v.value)) / CFrame.new(table.unpack(v.value)) rebuild them in Roblox): +-- String, BinaryString, ProtectedString, ContentId, Bytecode string (bytes) +-- SharedString string (the content; writers deduplicate) +-- Bool boolean +-- Int32, Int64, Float32, Float64 number (Int64 exact to 2^53) +-- Enum, BrickColor, SecurityCapabilities number +-- Faces number: bits Right 1, Top 2, Back 4, Left 8, Bottom 16, Front 32 +-- Axes number: bits X 1, Y 2, Z 4 +-- UDim { scale, offset } UDim2 { xScale, xOffset, yScale, yOffset } NumberRange { min, max } +-- Vector2 / Vector2int16 { x, y } Vector3 / Vector3int16 { x, y, z } Color3 { r, g, b } (0..1) +-- Color3uint8 { r, g, b } (0..255) Rect { minX, minY, maxX, maxY } Ray { ox, oy, oz, dx, dy, dz } +-- CFrame { x, y, z, r00, r01, r02, r10, r11, r12, r20, r21, r22 } OptionalCFrame: the same, or nil (none) +-- NumberSequence { { time, value, envelope } ... } ColorSequence { { time, r, g, b, envelope } ... } +-- PhysicalProperties nil (default) | { density, friction, elasticity, frictionWeight, elasticityWeight, +-- acousticAbsorption } (decoders fill acousticAbsorption = 1 when the file leaves it out) +-- Ref an Instance of the tree, or nil +-- UniqueId 32 hex digits: random (16), time (8), index (8) +-- Font { family, weight (100..900), style ("Normal" | "Italic"), cachedFaceId? } +-- Content nil (none) | string (a URI) | an Instance (object) +-- Raw a binary property of a type this library does not know: { typeId, data (the class's whole column), +-- index, count }; written back verbatim while the class keeps the same instances in the same order +-- XmlRaw an XML property of an unknown type: value = the element (codecs/text/Xml node), written back as it is +-- Name is not a property here: it is inst.name. Never throws. + +local Rbx = {} + +export type Value = { type: string, value: any } +export type Instance = { + className: string, + name: string, + properties: { [string]: Value }, + children: { Instance }, + parent: Instance?, -- nil for roots + referent: string?, -- the file's referent (XML "RBX..." id, binary index) when read; writers make their own + service: boolean?, -- a service (binary INST object format 1; rbxl roots) +} +export type Tree = { + kind: "rbxtree", + roots: { Instance }, + place: boolean, -- a place (rbxl / rbxlx: the roots are services under the DataModel) or a model + metadata: { [string]: string }, -- binary META / XML entries (ExplicitAutoJoints, ...) + extra: { any }, -- unknown binary chunks { name, data } / unknown top-level XML elements, written back + meta: { source: { format: string, [string]: any }?, [string]: any }, +} + +-- ------------------------------------------------------------------------------------------------ tree +function Rbx.tree(place: boolean?): Tree + return { kind = "rbxtree", roots = {}, place = place == true, metadata = {}, extra = {}, meta = {} } +end + +function Rbx.instance(className: string, name: string?): Instance + return { className = className, name = name or className, properties = {}, children = {} } +end + +-- add(parent, child) -> child: parent is a Tree (child becomes a root) or an Instance +function Rbx.add(parent: any, child: Instance): Instance + if parent.kind == "rbxtree" then + child.parent = nil + table.insert(parent.roots, child) + else + child.parent = parent + table.insert(parent.children, child) + end + return child +end + +-- set(inst, name, type, value): a property (value nil = the type's nil form: Ref none, OptionalCFrame none, ...) +function Rbx.set(inst: Instance, name: string, typ: string, value: any) + inst.properties[name] = { type = typ, value = value } +end + +-- get(inst, name) -> the property's value (not the Value table), nil when absent +function Rbx.get(inst: Instance, name: string): any + local v = inst.properties[name] + return if v then v.value else nil +end + +-- descendants(treeOrInstance) -> iterator over (instance, depth) in depth-first order (roots / the instance's children +-- at depth 1) +function Rbx.descendants(root: any): () -> (Instance?, number?) + local stack: { any } = {} + local list = if root.kind == "rbxtree" then root.roots else root.children + for i = #list, 1, -1 do + table.insert(stack, { list[i], 1 }) + end + return function(): (Instance?, number?) + local top = table.remove(stack) + if not top then + return nil, nil + end + local inst, depth = top[1], top[2] + for i = #inst.children, 1, -1 do + table.insert(stack, { inst.children[i], depth + 1 }) + end + return inst, depth + end +end + +-- list(tree) -> every instance, depth first +function Rbx.list(tree: any): { Instance } + local out = {} + for inst in Rbx.descendants(tree) do + table.insert(out, inst :: Instance) + end + return out +end + +-- find(treeOrInstance, path) -> the instance at a "/"-separated path of names ("Workspace/Baseplate"), or nil +function Rbx.find(root: any, path: string): Instance? + local cur: any = root + for part in string.gmatch(path, "[^/]+") do + local list = if cur.kind == "rbxtree" then cur.roots else cur.children + local found = nil + for _, c in list do + if c.name == part then + found = c + break + end + end + if not found then + return nil + end + cur = found + end + return if cur.kind == "rbxtree" then nil else cur +end + +-- fullName(inst) -> "Workspace.Model.Part" (names joined up to the root) +function Rbx.fullName(inst: Instance): string + local parts = {} + local cur: Instance? = inst + while cur do + table.insert(parts, 1, cur.name) + cur = cur.parent + end + return table.concat(parts, ".") +end + +-- ------------------------------------------------------------------------------------------------ CFrame rotation ids +-- The binary format stores axis-aligned rotations as one byte: id = 6 * n(RightVector) + n(UpVector) + 1, where n is +-- the NormalId of a unit axis (+X 0, +Y 1, +Z 2, -X 3, -Y 4, -Z 5) and the third column is their cross product. +local AXES = { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 }, { -1, 0, 0 }, { 0, -1, 0 }, { 0, 0, -1 } } + +-- the rotation of an id as { r00 .. r22 } (row major), or nil for an id that is not a rotation +local ROTATIONS: { [number]: { number } } = {} +for a = 0, 5 do + for b = 0, 5 do + if a % 3 ~= b % 3 then + local r, u = AXES[a + 1], AXES[b + 1] + local k = { r[2] * u[3] - r[3] * u[2], r[3] * u[1] - r[1] * u[3], r[1] * u[2] - r[2] * u[1] } + -- columns: right, up, back (= right x up) + ROTATIONS[6 * a + b + 1] = { r[1], u[1], k[1] + 0, r[2], u[2], k[2] + 0, r[3], u[3], k[3] + 0 } + end + end +end +Rbx.ROTATIONS = ROTATIONS + +local function axisIndex(x: number, y: number, z: number): number? + for i, a in AXES do + if a[1] == x and a[2] == y and a[3] == z then + return i - 1 + end + end + return nil +end + +-- rotationId(cf) -> the id of the CFrame's rotation (cf = { x, y, z, r00 .. r22 }), or 0 when it is not axis aligned +function Rbx.rotationId(cf: { number }): number + local a = axisIndex(cf[4], cf[7], cf[10]) + local b = axisIndex(cf[5], cf[8], cf[11]) + if not a or not b then + return 0 + end + local id = 6 * a + b + 1 + local rot = ROTATIONS[id] + if not rot or rot[3] ~= cf[6] or rot[6] ~= cf[9] or rot[9] ~= cf[12] then + return 0 + end + return id +end + +-- ------------------------------------------------------------------------------------------------ values +-- binary type ids (rbx-dom docs/binary.md) by type name, and back +Rbx.TYPE_IDS = table.freeze({ + String = 0x01, + BinaryString = 0x01, + ProtectedString = 0x01, + ContentId = 0x01, + Bool = 0x02, + Int32 = 0x03, + Float32 = 0x04, + Float64 = 0x05, + UDim = 0x06, + UDim2 = 0x07, + Ray = 0x08, + Faces = 0x09, + Axes = 0x0A, + BrickColor = 0x0B, + Color3 = 0x0C, + Vector2 = 0x0D, + Vector3 = 0x0E, + Vector2int16 = 0x0F, + CFrame = 0x10, + Enum = 0x12, + Ref = 0x13, + Vector3int16 = 0x14, + NumberSequence = 0x15, + ColorSequence = 0x16, + NumberRange = 0x17, + Rect = 0x18, + PhysicalProperties = 0x19, + Color3uint8 = 0x1A, + Int64 = 0x1B, + SharedString = 0x1C, + Bytecode = 0x1D, + OptionalCFrame = 0x1E, + UniqueId = 0x1F, + Font = 0x20, + SecurityCapabilities = 0x21, + Content = 0x22, +} :: { [string]: number }) +local NAMES: { [number]: string } = {} +for name, id in Rbx.TYPE_IDS do + if NAMES[id] == nil or name == "String" then + NAMES[id] = name + end +end +Rbx.TYPE_NAMES = table.freeze(NAMES) + +-- the value a binary writer uses for an instance without the property (zero / empty / identity; BrickColor 194, the +-- Medium stone grey Roblox defaults to; sequences of two keypoints at times 0 and 1) +local IDENTITY_CF = { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 } +function Rbx.default(typ: string): any + if typ == "String" or typ == "BinaryString" or typ == "ProtectedString" or typ == "ContentId" or typ == "Bytecode" or typ == "SharedString" then + return "" + elseif typ == "Bool" then + return false + elseif typ == "BrickColor" then + return 194 + elseif typ == "UDim" or typ == "NumberRange" or typ == "Vector2" or typ == "Vector2int16" then + return { 0, 0 } + elseif typ == "UDim2" or typ == "Rect" then + return { 0, 0, 0, 0 } + elseif typ == "Vector3" or typ == "Vector3int16" or typ == "Color3" or typ == "Color3uint8" then + return { 0, 0, 0 } + elseif typ == "Ray" then + return { 0, 0, 0, 0, 0, 0 } + elseif typ == "CFrame" then + return table.clone(IDENTITY_CF) + elseif typ == "NumberSequence" then + return { { 0, 0, 0 }, { 1, 0, 0 } } + elseif typ == "ColorSequence" then + return { { 0, 0, 0, 0, 0 }, { 1, 0, 0, 0, 0 } } + elseif typ == "UniqueId" then + return string.rep("0", 32) + elseif typ == "Font" then + return { family = "rbxasset://fonts/families/SourceSansPro.json", weight = 400, style = "Normal" } + elseif typ == "PhysicalProperties" or typ == "Ref" or typ == "OptionalCFrame" or typ == "Content" then + return nil + end + return 0 +end + +-- STRINGS: the string-valued types (one binary type, several XML tags) +Rbx.STRINGS = table.freeze({ String = true, BinaryString = true, ProtectedString = true, ContentId = true, Bytecode = true } :: { [string]: boolean }) + +return Rbx diff --git a/src/Formats/init.luau b/src/Formats/init.luau index 4f90979..c8b1127 100644 --- a/src/Formats/init.luau +++ b/src/Formats/init.luau @@ -41,6 +41,7 @@ local KIND_CATEGORY: { [string]: string } = { audio = "audio", video = "video", scene = "model", + rbxtree = "model", -- codecs/model/Rbx trees (model/rbxm, model/rbxmx) cad = "cad", font = "font", archive = "archive", diff --git a/src/Formats/model/rbxm/init.luau b/src/Formats/model/rbxm/init.luau new file mode 100644 index 0000000..7fb49e7 --- /dev/null +++ b/src/Formats/model/rbxm/init.luau @@ -0,0 +1,575 @@ +--!strict +-- model/rbxm: the Roblox binary model / place format (.rbxm / .rbxl, " e then + return nil, p + end + local n = readu32(b, p) + if p + 4 + n > e then + return nil, p + end + return readstring(b, p + 4, n), p + 4 + n +end + +function Rbxm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Rbx.Tree?, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 28 + local maxInstances = opts and opts.maxInstances or 2 ^ 22 + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 32 then + return nil, Err.new(Err.TRUNCATED, "header", base) + end + if readstring(b, base, 14) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "bad signature", base) + end + local version = buffer.readu16(b, base + 14) + if version ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "format version " .. version, base + 14) + end + local nClasses, nInstances = readi32(b, base + 16), readi32(b, base + 20) + if nClasses < 0 or nInstances < 0 then + return nil, Err.new(Err.CORRUPT, "negative counts", base + 16) + end + if nInstances > maxInstances then + return nil, Err.new(Err.LIMIT, "limit: " .. nInstances .. " instances", base + 20) + end + local tree = Rbx.tree() + tree.meta.source = { format = "rbxm", version = version, classes = nClasses, instances = nInstances, compression = {} } + local classes: { [number]: Class } = {} + local byRef: { [number]: Rbx.Instance } = {} + local shared: { string } = {} + local parented: { [Rbx.Instance]: boolean } = {} + local order: { Rbx.Instance } = {} + local anyService = false + local comp: { [string]: boolean } = {} + local ctx: Binary.Ctx = { + ref = function(n: number): any + return byRef[n] + end, + shared = shared, + } + local p = base + 32 + local ended = false + while p < limit do + if p + 16 > limit then + return nil, Err.new(Err.TRUNCATED, "chunk header", p) + end + local name = readstring(b, p, 4) + local clen, ulen = readu32(b, p + 4), readu32(b, p + 8) + local at = p + p += 16 + if ulen > maxBytes then + return nil, Err.new(Err.LIMIT, "limit: chunk of " .. ulen .. " bytes", at) + end + local body: buffer, bo: number, be: number + if clen == 0 then + if p + ulen > limit then + return nil, Err.new(Err.TRUNCATED, "chunk " .. name .. " runs past the end", at) + end + body, bo, be = b, p, p + ulen + p += ulen + comp.none = true + else + if p + clen > limit then + return nil, Err.new(Err.TRUNCATED, "chunk " .. name .. " runs past the end", at) + end + local out, err + if Zstd.isFrame(b, p) then + out, err = Zstd.decompress(b, p, clen, { maxBytes = ulen }) + comp.zstd = true + else + out, err = Lz4.decompress(b, p, clen, ulen) + comp.lz4 = true + end + if not out then + return nil, err + end + if buffer.len(out) ~= ulen then + return nil, Err.new(Err.CORRUPT, "chunk " .. name .. " decompresses to the wrong size", at) + end + body, bo, be = out, 0, ulen + p += clen + end + if name == "END\0" then + ended = true + break + elseif name == "META" then + if bo + 4 > be then + return nil, Err.new(Err.TRUNCATED, "META", at) + end + local q = bo + 4 + for _ = 1, readu32(body, bo) do + local k, q1 = str(body, q, be) + local v, q2 = str(body, q1, be) + if not k or not v then + return nil, Err.new(Err.TRUNCATED, "META entry", at) + end + tree.metadata[k] = v + q = q2 + end + elseif name == "SSTR" then + if bo + 8 > be then + return nil, Err.new(Err.TRUNCATED, "SSTR", at) + end + local q = bo + 8 + for i = 1, readu32(body, bo + 4) do + local s, q2 = str(body, q + 16, be) + if not s then + return nil, Err.new(Err.TRUNCATED, "shared string", at) + end + shared[i] = s + q = q2 + end + elseif name == "INST" then + local id = if bo + 4 <= be then readi32(body, bo) else -1 + local cname, q = str(body, bo + 4, be) + if not cname or q + 5 > be then + return nil, Err.new(Err.TRUNCATED, "INST", at) + end + local fmt, count = readu8(body, q), readu32(body, q + 1) + if count > nInstances then + return nil, Err.new(Err.CORRUPT, "more instances than the header says", at) + end + local refs, q2 = Binary.readRefs(body, q + 5, be, count) + if not refs then + return nil, Err.new(Err.TRUNCATED, "INST referents", at) + end + if id < 0 or classes[id] then + return nil, Err.new(Err.CORRUPT, "bad class id " .. id, at) + end + local service = fmt == 1 + if service and q2 + count > be then + return nil, Err.new(Err.TRUNCATED, "INST service markers", at) + end + classes[id] = { id = id, name = cname, refs = refs, service = service } + for i, ref in refs do + if byRef[ref] then + return nil, Err.new(Err.CORRUPT, "referent " .. ref .. " used twice", at) + end + local inst = Rbx.instance(cname) + inst.referent = tostring(ref) + if service and readu8(body, q2 + i - 1) ~= 0 then + inst.service = true + anyService = true + end + byRef[ref] = inst + table.insert(order, inst) + end + elseif name == "PROP" then + local id = if bo + 4 <= be then readi32(body, bo) else -1 + local pname, q = str(body, bo + 4, be) + if not pname or q + 1 > be then + return nil, Err.new(Err.TRUNCATED, "PROP", at) + end + local cls = classes[id] + if not cls then + return nil, Err.new(Err.CORRUPT, "PROP for an unknown class " .. id, at) + end + local t = readu8(body, q) + local n = #cls.refs + local vals, msg = Binary.decode(t, body, q + 1, be, n, ctx) + if vals then + local tname = Rbx.TYPE_NAMES[t] + for i, ref in cls.refs do + local inst = byRef[ref] + if pname == "Name" and t == 0x01 then + inst.name = vals[i] + else + inst.properties[pname] = { type = tname, value = vals[i] } + end + end + elseif msg == "unknown" then + local data = buffer.create(be - q - 1) + buffer.copy(data, 0, body, q + 1, be - q - 1) + for i, ref in cls.refs do + byRef[ref].properties[pname] = { type = "Raw", value = { typeId = t, data = data, index = i, count = n } } + end + else + return nil, Err.from(msg, at) + end + elseif name == "PRNT" then + if bo + 5 > be then + return nil, Err.new(Err.TRUNCATED, "PRNT", at) + end + if readu8(body, bo) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "PRNT version " .. readu8(body, bo), at) + end + local count = readu32(body, bo + 1) + local kids, q = Binary.readRefs(body, bo + 5, be, count) + local parents = if kids then Binary.readRefs(body, q, be, count) else nil + if not kids or not parents then + return nil, Err.new(Err.TRUNCATED, "PRNT referents", at) + end + for i = 1, count do + local child, parent = byRef[kids[i]], parents[i] >= 0 and byRef[parents[i]] or nil + if not child or (parents[i] >= 0 and not parent) then + return nil, Err.new(Err.CORRUPT, "PRNT names an unknown referent", at) + end + if parented[child] then + return nil, Err.new(Err.CORRUPT, "an instance with two parents", at) + end + parented[child] = true + -- refuse cycles: the parent may not be a descendant of the child + local up: Rbx.Instance? = parent + while up do + if up == child then + return nil, Err.new(Err.CORRUPT, "a cycle in the hierarchy", at) + end + up = up.parent + end + Rbx.add(parent or tree, child) + end + else + local data = buffer.create(be - bo) + buffer.copy(data, 0, body, bo, be - bo) + table.insert(tree.extra, { name = name, data = data }) + end + end + if not ended then + return nil, Err.new(Err.TRUNCATED, "no END chunk", limit) + end + -- instances PRNT does not mention are roots + for _, inst in order do + if not parented[inst] then + table.insert(tree.roots, inst) + end + end + tree.place = anyService + local list = {} + for k in comp do + table.insert(list, k) + end + table.sort(list) + local src: any = tree.meta.source + src.compression = list + return tree, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- the binary type of a property over a class's instances: type id, type name | nil, message +local function columnType(insts: { Rbx.Instance }, pname: string): (number?, string?) + local id, tname = nil, nil + for _, inst in insts do + local v = inst.properties[pname] + if v then + if type(v) ~= "table" or type(v.type) ~= "string" then + return nil, "property " .. pname .. " of " .. inst.className .. " is not a { type, value } table" + end + local t = if v.type == "Raw" then -1 elseif v.type == "XmlRaw" then -2 else Rbx.TYPE_IDS[v.type] + if not t then + return nil, "property " .. pname .. ": unknown type " .. v.type + end + if id == nil then + id, tname = t, v.type + elseif id ~= t then + return nil, "property " .. pname .. " of " .. inst.className .. " has values of types " .. tostring(tname) .. " and " .. v.type + end + end + end + return id, tname +end + +local function chunk(w: Bytes.Writer, name: string, body: buffer, compress: boolean) + w:string(name) + local n = buffer.len(body) + if compress then + local z = Lz4.compress(body) :: buffer + w:u32le(buffer.len(z)) + w:u32le(n) + w:u32le(0) + w:bytes(z) + else + w:u32le(0) + w:u32le(n) + w:u32le(0) + w:bytes(body) + end +end + +local function putStr(w: Bytes.Writer, s: string) + w:u32le(#s) + w:string(s) +end + +function Rbxm.encode(tree: Rbx.Tree, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(tree) ~= "table" or tree.kind ~= "rbxtree" or type(tree.roots) ~= "table" then + return nil, Err.new(Err.ARG, "expected an RbxTree (codecs/model/Rbx)") + end + local o: any = opts or {} + local compress = o.compression ~= "none" + local place = if o.place ~= nil then o.place == true elseif o.format == "rbxl" then true else tree.place == true + -- every instance depth first; referents in that order + local insts: { Rbx.Instance } = {} + local refOf: { [any]: number } = {} + local parentOf: { [Rbx.Instance]: Rbx.Instance? } = {} + local function visit(inst: any, parent: Rbx.Instance?): Err.Err? + if type(inst) ~= "table" or type(inst.className) ~= "string" or type(inst.properties) ~= "table" then + return Err.new(Err.ARG, "an instance needs className and properties") + end + if refOf[inst] then + return Err.new(Err.ARG, "an instance appears twice in the tree") + end + refOf[inst] = #insts + table.insert(insts, inst) + parentOf[inst] = parent + for _, c in inst.children or {} do + local e = visit(c, inst) + if e then + return e + end + end + return nil + end + for _, root in tree.roots do + local e = visit(root, nil) + if e then + return nil, e + end + end + -- classes by name + local byClass: { [string]: { Rbx.Instance } } = {} + local names = {} + for _, inst in insts do + local list = byClass[inst.className] + if not list then + list = {} + byClass[inst.className] = list + table.insert(names, inst.className) + end + table.insert(list, inst) + end + table.sort(names) + -- shared strings, in order of first use + local sharedIdx: { [string]: number } = {} + local sharedList: { string } = {} + local ctx: Binary.Ctx = { + refOf = function(v: any): number + return refOf[v] or -1 + end, + sharedIndex = function(s: string): number + local i = sharedIdx[s] + if not i then + table.insert(sharedList, s) + i = #sharedList - 1 + sharedIdx[s] = i + end + return i + end, + } + local props: { buffer } = {} + local instChunks: { buffer } = {} + for classId, cname in names do + local list = byClass[cname] + local id = classId - 1 + -- INST + local w = Bytes.writer(64 + 5 * #list) + w:u32le(id) + putStr(w, cname) + local service = place and parentOf[list[1]] == nil + for _, inst in list do + if inst.service then + service = true + end + end + w:u8(if service then 1 else 0) + w:u32le(#list) + local refs = table.create(#list, 0) + for i, inst in list do + refs[i] = refOf[inst] + end + Binary.writeRefs(w, refs) + if service then + for _, inst in list do + w:u8(if inst.service or (place and parentOf[inst] == nil) then 1 else 0) + end + end + table.insert(instChunks, w:finish()) + -- PROP: Name, then every property any instance of the class has, sorted + local pnames: { string } = {} + local seen: { [string]: boolean } = {} + for _, inst in list do + for pn in inst.properties do + if not seen[pn] and pn ~= "Name" then + seen[pn] = true + table.insert(pnames, pn) + end + end + end + table.sort(pnames) + table.insert(pnames, 1, "Name") + for _, pn in pnames do + local t: number?, tname: string? + if pn == "Name" then + t, tname = 0x01, "String" + else + local e + t, e = columnType(list, pn) + if not t then + return nil, Err.new(Err.ARG, e or "bad property") + end + tname = e + end + local pw = Bytes.writer(64) + pw:u32le(id) + putStr(pw, pn) + local tid = t :: number + if tid == -1 then + -- Raw: the column read from a file, written back only when this class still has exactly its instances + local first = list[1].properties[pn] + local raw = first and first.value + local ok = type(raw) == "table" and raw.count == #list and type(raw.data) == "buffer" + if ok then + for i, inst in list do + local v = inst.properties[pn] + if not v or v.type ~= "Raw" or v.value.data ~= raw.data or v.value.index ~= i then + ok = false + break + end + end + end + if ok then + pw:u8(raw.typeId) + pw:bytes(raw.data) + table.insert(props, pw:finish()) + end + elseif tid ~= -2 then + pw:u8(tid) + local vals = table.create(#list) + for i, inst in list do + if pn == "Name" then + vals[i] = if type(inst.name) == "string" then inst.name else inst.className + else + local v = inst.properties[pn] + if v then + vals[i] = v.value + else + vals[i] = Rbx.default(tname :: string) + end + end + end + local e = Binary.encode(tid, vals, #list, pw, ctx) + if e then + return nil, Err.new(Err.ARG, "property " .. pn .. ": " .. e) + end + table.insert(props, pw:finish()) + end + end + end + -- PRNT + local pw = Bytes.writer(16 + 8 * #insts) + pw:u8(0) + pw:u32le(#insts) + local kids, parents = table.create(#insts, 0), table.create(#insts, 0) + for i, inst in insts do + kids[i] = i - 1 + local par = parentOf[inst] + parents[i] = if par then refOf[par] else -1 + end + Binary.writeRefs(pw, kids) + Binary.writeRefs(pw, parents) + + local out = Bytes.writer(1024) + out:string(MAGIC) + out:u16le(0) + out:u32le(#names) + out:u32le(#insts) + out:u32le(0) + out:u32le(0) + local metaKeys = {} + for k, v in tree.metadata or {} do + if type(k) == "string" and type(v) == "string" then + table.insert(metaKeys, k) + end + end + if #metaKeys > 0 then + table.sort(metaKeys) + local mw = Bytes.writer(64) + mw:u32le(#metaKeys) + for _, k in metaKeys do + putStr(mw, k) + putStr(mw, (tree.metadata :: any)[k]) + end + chunk(out, "META", mw:finish(), compress) + end + if #sharedList > 0 then + local sw = Bytes.writer(64) + sw:u32le(0) + sw:u32le(#sharedList) + for _, s in sharedList do + local h = Md5.new() + h:update(buffer.fromstring(s)) + sw:string(h:digest()) + putStr(sw, s) + end + chunk(out, "SSTR", sw:finish(), compress) + end + for _, c in instChunks do + chunk(out, "INST", c, compress) + end + for _, c in props do + chunk(out, "PROP", c, compress) + end + chunk(out, "PRNT", pw:finish(), compress) + for _, x in tree.extra or {} do + if type(x) == "table" and type(x.name) == "string" and #x.name == 4 and type(x.data) == "buffer" then + chunk(out, x.name, x.data, compress) + end + end + chunk(out, "END\0", buffer.fromstring(""), false) + return out:finish(), nil +end + +return Rbxm diff --git a/src/Formats/model/rbxmx/init.luau b/src/Formats/model/rbxmx/init.luau new file mode 100644 index 0000000..b2427ac --- /dev/null +++ b/src/Formats/model/rbxmx/init.luau @@ -0,0 +1,661 @@ +--!strict +-- model/rbxmx: the Roblox XML model / place format (.rbxmx / .rbxlx, ``), read + write, to and from +-- the instance tree of codecs/model/Rbx (an RbxTree, as model/rbxm: converting between the two is load + save). +-- Written from the rbx-dom format notes (docs/xml.md); checked against rojo 7.7 and lune 0.11 (rbx-dom) both ways. +-- Decode: , with of every type codecs/model/Rbx lists (string, BinaryString +-- (base64), ProtectedString, Content (url / uri / null), ContentId, bool, int, int64, float, double (INF / NAN), +-- token, BrickColor (as rbx-dom: an ; read back as BrickColor for the BrickColor properties of a short +-- built-in list), Color3 (components or packed ARGB), Color3uint8, Vector2 / 3 (int16), CoordinateFrame, +-- OptionalCoordinateFrame, UDim / UDim2, Rect2D, Ray, Faces, Axes, NumberSequence, ColorSequence, NumberRange, +-- PhysicalProperties, Ref, SharedString (+ ), UniqueId, Font, SecurityCapabilities); unknown property +-- tags are kept as "XmlRaw" values and written back as they are; unknown top-level elements go to tree.extra. +-- tree.place is true when a root is a Workspace (rbxlx). +-- Encode: rbx-dom's layout (version 4, referents "RBX" + 32 hex digits, properties sorted by name, two-space indent, +-- floats as the shortest text that reads back to the same f32 / f64). A String holding bytes XML cannot carry (control +-- characters, invalid UTF-8) is written as a BinaryString. "Raw" values (unknown binary types) are skipped. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Base64 = require("@formats/core/Base64") +local Md5 = require("@formats/core/Md5") +local Xml = require("@formats/codecs/text/Xml") +local Rbx = require("@formats/codecs/model/Rbx") + +-- ------------------------------------------------------------------------------------------------ contract +local Rbxmx = { + name = "rbxmx", + category = "model", + extensions = { "rbxmx", "rbxlx" }, + mime = { "application/x-roblox-rbxmx", "application/x-roblox-rbxlx" }, + deps = { "core/Err", "core/Bytes", "core/Base64", "core/Md5", "codecs/text/Xml", "codecs/model/Rbx" }, + caps = { decode = true, encode = true, tree = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxDepth: number?, -- XML nesting limit (default 10000) +} +export type EncodeOptions = { + indent: (number | string)?, -- default 2 spaces; 0 for none +} + +-- ------------------------------------------------------------------------------------------------ constants +local XmlNode = Xml.element +local find, format, match, gmatch = string.find, string.format, string.match, string.gmatch + +-- tag name -> type name for the simple (text) types +local SCALAR_TAGS: { [string]: string } = { + string = "String", + ProtectedString = "ProtectedString", + bool = "Bool", + int = "Int32", + int64 = "Int64", + float = "Float32", + double = "Float64", + token = "Enum", + BrickColor = "BrickColor", + SecurityCapabilities = "SecurityCapabilities", + UniqueId = "UniqueId", +} +-- BrickColor properties: XML writes them as (rbx-dom reads them through its reflection database); these known ones +-- read back as BrickColor (the rest of an stays Int32) +local BRICKCOLOR: { [string]: boolean } = { + ["BrickColorValue.Value"] = true, + ["SpawnLocation.TeamColor"] = true, + ["Team.TeamColor"] = true, + ["FlagStand.TeamColor"] = true, + ["Skin.SkinColor"] = true, +} +-- the strings rbx-dom writes as BinaryString (the rest decides by content) +local BINARY_NAMES: { [string]: boolean } = { AttributesSerialize = true, Tags = true, MaterialColors = true, SmoothGrid = true, PhysicsGrid = true } + +-- ------------------------------------------------------------------------------------------------ sniff +function Rbxmx.sniff(r: Bytes.Reader): number + local head = r:peek(256) + head = string.gsub(head, "^\239\187\191", "") + head = string.gsub(head, "^%s*<%?xml[^>]*%?>", "") + if match(head, "^%s*]") then + return if find(head, "version=", 1, true) then 1 else 0.8 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function num(s: string?): number + if s == nil then + return 0 + end + local t = string.lower((string.gsub(s, "^%s+", ""))) + t = string.gsub(t, "%s+$", "") + if t == "inf" or t == "+inf" or t == "infinity" then + return math.huge + elseif t == "-inf" or t == "-infinity" then + return -math.huge + elseif t == "nan" or t == "-nan" then + return 0 / 0 + end + return tonumber(t) or 0 +end + +local function childText(node: Xml.Node, name: string): string? + local c = Xml.child(node, name) + return if c then Xml.text(c) else nil +end +local function comps(node: Xml.Node?, names: { string }): { number } + local out = table.create(#names, 0) + if node then + for i, n in names do + out[i] = num(childText(node, n)) + end + end + return out +end +local function numbers(s: string): { number } + local out = {} + for w in gmatch(s, "%S+") do + table.insert(out, num(w)) + end + return out +end + +local CF_NAMES = { "X", "Y", "Z", "R00", "R01", "R02", "R10", "R11", "R12", "R20", "R21", "R22" } +local PHYS_NAMES = { "Density", "Friction", "Elasticity", "FrictionWeight", "ElasticityWeight" } + +-- a property element -> type name, value | nil (unknown: XmlRaw). refs: referent -> instance (filled later: Refs +-- come back as { pending = referent }) +local function readRaw(node: Xml.Node, shared: { [string]: string }, key: string): (string, any) + local tag = node.name + local scalar = SCALAR_TAGS[tag] + if tag == "int" and BRICKCOLOR[key] then + scalar = "BrickColor" + end + if scalar then + local s = Xml.text(node) + if scalar == "String" or scalar == "ProtectedString" then + return scalar, s + elseif scalar == "Bool" then + return scalar, match(s, "^%s*true%s*$") ~= nil + elseif scalar == "UniqueId" then + return scalar, string.lower((string.gsub(s, "%s", ""))) + end + return scalar, num(s) + elseif tag == "BinaryString" then + local data = Base64.decode((string.gsub(Xml.text(node), "%s", ""))) + return "BinaryString", if data then buffer.tostring(data) else "" + elseif tag == "Content" or tag == "ContentId" then + local url = Xml.child(node, "url") + if url then + return "ContentId", Xml.text(url) + end + local uri = Xml.child(node, "uri") + if uri then + return "Content", Xml.text(uri) + end + local obj = Xml.child(node, "Object") or Xml.child(node, "Ref") + if obj then + return "Content", { pending = Xml.text(obj) } + end + if Xml.child(node, "null") then + return (if tag == "ContentId" then "ContentId" else "Content"), (if tag == "ContentId" then "" else nil) + end + return "ContentId", Xml.text(node) + elseif tag == "Vector2" or tag == "Vector2int16" then + return tag, comps(node, { "X", "Y" }) + elseif tag == "Vector3" or tag == "Vector3int16" then + return tag, comps(node, { "X", "Y", "Z" }) + elseif tag == "Color3" then + if Xml.child(node, "R") then + return tag, comps(node, { "R", "G", "B" }) + end + local v = num(Xml.text(node)) % 4294967296 + return tag, { (v // 65536) % 256 / 255, (v // 256) % 256 / 255, v % 256 / 255 } + elseif tag == "Color3uint8" then + local v = num(Xml.text(node)) % 4294967296 + return tag, { (v // 65536) % 256, (v // 256) % 256, v % 256 } + elseif tag == "CoordinateFrame" or tag == "CFrame" then + return "CFrame", comps(node, CF_NAMES) + elseif tag == "OptionalCoordinateFrame" then + local cf = Xml.child(node, "CFrame") + return "OptionalCFrame", if cf then comps(cf, CF_NAMES) else nil + elseif tag == "UDim" then + return tag, comps(node, { "S", "O" }) + elseif tag == "UDim2" then + return tag, comps(node, { "XS", "XO", "YS", "YO" }) + elseif tag == "Rect2D" then + local a, b = comps(Xml.child(node, "min"), { "X", "Y" }), comps(Xml.child(node, "max"), { "X", "Y" }) + return "Rect", { a[1], a[2], b[1], b[2] } + elseif tag == "Ray" then + local a, b = comps(Xml.child(node, "origin"), { "X", "Y", "Z" }), comps(Xml.child(node, "direction"), { "X", "Y", "Z" }) + return tag, { a[1], a[2], a[3], b[1], b[2], b[3] } + elseif tag == "Faces" or tag == "Axes" then + local t = childText(node, string.lower(tag)) + return tag, num(t or Xml.text(node)) + elseif tag == "NumberRange" then + local v = numbers(Xml.text(node)) + return tag, { v[1] or 0, v[2] or 0 } + elseif tag == "NumberSequence" or tag == "ColorSequence" then + local k = if tag == "NumberSequence" then 3 else 5 + local v = numbers(Xml.text(node)) + local seq = {} + for i = 1, #v - k + 1, k do + table.insert(seq, table.move(v, i, i + k - 1, 1, table.create(k, 0))) + end + return tag, seq + elseif tag == "PhysicalProperties" then + local custom = childText(node, "CustomPhysics") + if not custom or not match(custom, "^%s*true%s*$") then + return tag, nil + end + local v = comps(node, PHYS_NAMES) + local a = childText(node, "AcousticAbsorption") + v[6] = if a then num(a) else 1 + return tag, v + elseif tag == "Ref" then + local s = string.gsub(Xml.text(node), "%s", "") + return tag, if s == "" or s == "null" then nil else { pending = s } + elseif tag == "SharedString" then + local key = string.gsub(Xml.text(node), "%s", "") + return tag, shared[key] or "" + elseif tag == "Font" then + local fam = Xml.child(node, "Family") + local face = Xml.child(node, "CachedFaceId") + local f = { + family = if fam then childText(fam, "url") or Xml.text(fam) else "", + weight = num(childText(node, "Weight") or "400"), + style = if match(childText(node, "Style") or "", "Italic") then "Italic" else "Normal", + cachedFaceId = if face then childText(face, "url") or nil else nil, + } + if f.cachedFaceId == "" then + f.cachedFaceId = nil + end + return tag, f + end + return "XmlRaw", node +end + +-- single-precision types: their components rounded to f32 (as a binary file stores them), so XML and binary +-- decodes of the same data are equal. Which components are floats, by type (true = all) +local F32: { [string]: any } = { + Float32 = true, + Vector2 = true, + Vector3 = true, + Color3 = true, + CFrame = true, + OptionalCFrame = true, + Rect = true, + Ray = true, + NumberRange = true, + NumberSequence = true, + ColorSequence = true, + PhysicalProperties = true, + UDim = { true, false }, + UDim2 = { true, false, true, false }, +} +local f32buf = buffer.create(4) +local function f32(v: number): number + buffer.writef32(f32buf, 0, v) + return buffer.readf32(f32buf, 0) +end +local function round32(v: any, which: any): any + if type(v) == "number" then + return f32(v) + elseif type(v) == "table" then + for i, x in v do + if type(x) == "table" then + round32(x, true) + elseif type(x) == "number" and (which == true or which[i]) then + v[i] = f32(x) + end + end + end + return v +end +local function readValue(node: Xml.Node, shared: { [string]: string }, key: string): (string, any) + local t, v = readRaw(node, shared, key) + local which = F32[t] + if which then + v = round32(v, which) + end + return t, v +end + +function Rbxmx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Rbx.Tree?, Err.Err?) + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local doc, err = Xml.decode(text, { maxDepth = opts and opts.maxDepth } :: any) + if not doc then + return nil, err + end + local root = (doc :: any).root + if not root or root.name ~= "roblox" then + return nil, Err.new(Err.CORRUPT, "the root element is not ") + end + local tree = Rbx.tree() + tree.meta.source = { format = "rbxmx", version = root.attrs.version } + -- shared strings first (properties name them by key) + local shared: { [string]: string } = {} + for _, ss in Xml.children(root, "SharedStrings") do + for _, s in Xml.children(ss, "SharedString") do + local key = s.attrs.md5 + local data = Base64.decode((string.gsub(Xml.text(s), "%s", ""))) + if key and data then + shared[key] = buffer.tostring(data) + end + end + end + local byRef: { [string]: Rbx.Instance } = {} + local pending: { { any } } = {} -- { value table, field, referent } + local function item(node: Xml.Node, parent: any): Err.Err? + local cls = node.attrs.class + if type(cls) ~= "string" then + return Err.new(Err.CORRUPT, "an without a class") + end + local inst = Rbx.instance(cls) + local ref = node.attrs.referent + if type(ref) == "string" then + inst.referent = ref + byRef[ref] = inst + end + Rbx.add(parent, inst) + for _, c in node.children do + if type(c) == "table" then + if c.name == "Properties" then + for _, pnode in c.children do + if type(pnode) == "table" and string.sub(pnode.name, 1, 1) ~= "#" then + local pname = pnode.attrs.name + if type(pname) == "string" then + local t, v = readValue(pnode, shared, cls .. "." .. pname) + if pname == "Name" and (t == "String" or t == "ProtectedString") then + inst.name = v + else + local val = { type = t, value = v } + inst.properties[pname] = val + if type(v) == "table" and v.pending then + table.insert(pending, { val, v.pending }) + end + end + end + end + end + elseif c.name == "Item" then + local e = item(c, inst) + if e then + return e + end + end + end + end + return nil + end + for _, c in root.children do + if type(c) == "table" then + if c.name == "Item" then + local e = item(c, tree) + if e then + return nil, e + end + elseif c.name == "Meta" then + if type(c.attrs.name) == "string" then + tree.metadata[c.attrs.name] = Xml.text(c) + end + elseif c.name ~= "SharedStrings" and string.sub(c.name, 1, 1) ~= "#" then + table.insert(tree.extra, c) + end + end + end + for _, p in pending do + p[1].value = byRef[p[2]] + end + for _, rt in tree.roots do + if rt.className == "Workspace" then + tree.place = true + end + end + return tree, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- the shortest text that reads back as the same float (single: f32 values; else f64) +local function fmt(v: any, single: boolean?): string + if type(v) ~= "number" then + v = 0 + end + if v ~= v then + return "NAN" + elseif v == math.huge then + return "INF" + elseif v == -math.huge then + return "-INF" + end + if single then + v = f32(v) + end + if v == math.floor(v) and math.abs(v) < 2 ^ 53 then + return format("%.0f", v) + end + for d = if single then 6 else 15, if single then 9 else 17 do + local s = format("%." .. d .. "g", v) + local back = tonumber(s) or 0 + if (if single then f32(back) else back) == v then + return s + end + end + return format("%.17g", v) +end +local function int(v: any): string + return format("%.0f", math.floor(if type(v) == "number" and v == v and math.abs(v) ~= math.huge then v else 0)) +end + +local function textEl(tag: string, text: string): Xml.Node + return XmlNode(tag, nil, { text }) +end +local function compsEl(tag: string, attrs: { [string]: string }?, names: { string }, v: any, single: boolean?, ints: boolean?): Xml.Node + local kids = {} + for i, n in names do + local x = if type(v) == "table" then v[i] else 0 + table.insert(kids, textEl(n, if ints then int(x) else fmt(x, single))) + end + return XmlNode(tag, attrs, kids) +end + +local function hexDigits(i: number): string + return format("%032X", i) +end + +local function xmlSafe(s: string): boolean + if find(s, "[%z\1-\8\11\12\14-\31\127]") then + return false + end + return utf8.len(s) ~= nil +end + +-- a property -> its element, or nil to skip +local function writeValue(name: string, v: any, refOf: (any) -> string, sharedKey: (string) -> string): Xml.Node? + local t, x = v.type, v.value + local a = { name = name } + if t == "String" or t == "ProtectedString" or t == "BinaryString" or t == "Bytecode" then + local s = if type(x) == "string" then x else "" + if t == "BinaryString" or t == "Bytecode" or BINARY_NAMES[name] or not xmlSafe(s) then + return XmlNode("BinaryString", a, { Base64.encode(s) }) + end + return XmlNode(if t == "ProtectedString" then "ProtectedString" else "string", a, { s }) + elseif t == "ContentId" then + local s = if type(x) == "string" then x else "" + return XmlNode("ContentId", a, { if s == "" then XmlNode("null") else textEl("url", s) }) + elseif t == "Content" then + if type(x) == "string" then + return XmlNode("Content", a, { textEl("uri", x) }) + elseif type(x) == "table" then + return XmlNode("Content", a, { textEl("Object", refOf(x)) }) + end + return XmlNode("Content", a, { XmlNode("null") }) + elseif t == "Bool" then + return XmlNode("bool", a, { if x then "true" else "false" }) + elseif t == "Int32" then + return XmlNode("int", a, { int(x) }) + elseif t == "Int64" then + return XmlNode("int64", a, { int(x) }) + elseif t == "Float32" then + return XmlNode("float", a, { fmt(x, true) }) + elseif t == "Float64" then + return XmlNode("double", a, { fmt(x) }) + elseif t == "Enum" then + return XmlNode("token", a, { int(x) }) + elseif t == "BrickColor" then + return XmlNode("int", a, { int(x) }) + elseif t == "SecurityCapabilities" then + return XmlNode("SecurityCapabilities", a, { int(x) }) + elseif t == "UniqueId" then + return XmlNode("UniqueId", a, { if type(x) == "string" then string.lower(x) else string.rep("0", 32) }) + elseif t == "Vector2" then + return compsEl(t, a, { "X", "Y" }, x, true) + elseif t == "Vector3" then + return compsEl(t, a, { "X", "Y", "Z" }, x, true) + elseif t == "Vector2int16" then + return compsEl(t, a, { "X", "Y" }, x, false, true) + elseif t == "Vector3int16" then + return compsEl(t, a, { "X", "Y", "Z" }, x, false, true) + elseif t == "Color3" then + return compsEl(t, a, { "R", "G", "B" }, x, true) + elseif t == "Color3uint8" then + local c = if type(x) == "table" then x else { 0, 0, 0 } + local function b(i: number): number + return math.clamp(math.floor(tonumber(c[i]) or 0), 0, 255) + end + return XmlNode(t, a, { int(b(1) * 65536 + b(2) * 256 + b(3)) }) + elseif t == "CFrame" then + return compsEl("CoordinateFrame", a, CF_NAMES, x, true) + elseif t == "OptionalCFrame" then + return XmlNode("OptionalCoordinateFrame", a, if type(x) == "table" then { compsEl("CFrame", nil, CF_NAMES, x, true) } else {}) + elseif t == "UDim" then + local u = if type(x) == "table" then x else { 0, 0 } + return XmlNode(t, a, { textEl("S", fmt(u[1], true)), textEl("O", int(u[2])) }) + elseif t == "UDim2" then + local u = if type(x) == "table" then x else { 0, 0, 0, 0 } + return XmlNode(t, a, { textEl("XS", fmt(u[1], true)), textEl("XO", int(u[2])), textEl("YS", fmt(u[3], true)), textEl("YO", int(u[4])) }) + elseif t == "Rect" then + local u = if type(x) == "table" then x else { 0, 0, 0, 0 } + return XmlNode("Rect2D", a, { compsEl("min", nil, { "X", "Y" }, { u[1], u[2] }, true), compsEl("max", nil, { "X", "Y" }, { u[3], u[4] }, true) }) + elseif t == "Ray" then + local u = if type(x) == "table" then x else { 0, 0, 0, 0, 0, 0 } + return XmlNode(t, a, { compsEl("origin", nil, { "X", "Y", "Z" }, { u[1], u[2], u[3] }, true), compsEl("direction", nil, { "X", "Y", "Z" }, { u[4], u[5], u[6] }, true) }) + elseif t == "Faces" or t == "Axes" then + return XmlNode(t, a, { textEl(string.lower(t), int(x)) }) + elseif t == "NumberRange" or t == "NumberSequence" or t == "ColorSequence" then + local parts = {} + local list = if type(x) ~= "table" then {} elseif t == "NumberRange" then { x } else x + for _, key in list do + for _, c in key do + table.insert(parts, fmt(c, true) .. " ") + end + end + return XmlNode(t, a, { table.concat(parts) }) + elseif t == "PhysicalProperties" then + if type(x) ~= "table" then + return XmlNode(t, a, { textEl("CustomPhysics", "false") }) + end + local kids = { textEl("CustomPhysics", "true") } + for i, n in PHYS_NAMES do + table.insert(kids, textEl(n, fmt(x[i], true))) + end + table.insert(kids, textEl("AcousticAbsorption", fmt(if x[6] ~= nil then x[6] else 1, true))) + return XmlNode(t, a, kids) + elseif t == "Ref" then + return XmlNode("Ref", a, { if x ~= nil then refOf(x) else "null" }) + elseif t == "SharedString" then + return XmlNode("SharedString", a, { sharedKey(if type(x) == "string" then x else "") }) + elseif t == "Font" then + local f = if type(x) == "table" then x else Rbx.default("Font") + local kids = { + XmlNode("Family", nil, { textEl("url", if type(f.family) == "string" then f.family else "") }), + textEl("Weight", int(f.weight or 400)), + textEl("Style", if f.style == "Italic" then "Italic" else "Normal"), + } + if type(f.cachedFaceId) == "string" and f.cachedFaceId ~= "" then + table.insert(kids, XmlNode("CachedFaceId", nil, { textEl("url", f.cachedFaceId) })) + end + return XmlNode("Font", a, kids) + elseif t == "XmlRaw" then + if type(x) == "table" and type(x.name) == "string" then + local copy = XmlNode(x.name, nil, x.children) + for k, val in x.attrs do + Xml.setAttr(copy, k, val) + end + Xml.setAttr(copy, "name", name) + return copy + end + end + return nil +end + +function Rbxmx.encode(tree: Rbx.Tree, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(tree) ~= "table" or tree.kind ~= "rbxtree" or type(tree.roots) ~= "table" then + return nil, Err.new(Err.ARG, "expected an RbxTree (codecs/model/Rbx)") + end + local refs: { [any]: string } = {} + local count = 0 + local function assign(inst: any): Err.Err? + if type(inst) ~= "table" or type(inst.className) ~= "string" or type(inst.properties) ~= "table" then + return Err.new(Err.ARG, "an instance needs className and properties") + end + if refs[inst] then + return Err.new(Err.ARG, "an instance appears twice in the tree") + end + refs[inst] = "RBX" .. hexDigits(count) + count += 1 + for _, c in inst.children or {} do + local e = assign(c) + if e then + return e + end + end + return nil + end + for _, rt in tree.roots do + local e = assign(rt) + if e then + return nil, e + end + end + local function refOf(x: any): string + return refs[x] or "null" + end + local sharedKeys: { [string]: string } = {} + local sharedList: { string } = {} + local function sharedKey(s: string): string + local k = sharedKeys[s] + if not k then + local h = Md5.new() + h:update(buffer.fromstring(s)) + k = Base64.encode(h:digest()) + sharedKeys[s] = k + table.insert(sharedList, s) + end + return k + end + local function item(inst: Rbx.Instance): Xml.Node + local props = { textEl("string", inst.name or inst.className) } + props[1].attrs.name = "Name" + local names: { string } = {} + for k in inst.properties do + if k ~= "Name" then + table.insert(names, k) + end + end + table.sort(names) + for _, k in names do + local v = inst.properties[k] + if type(v) == "table" then + local el = writeValue(k, v, refOf, sharedKey) + if el then + table.insert(props, el) + end + end + end + local kids = { XmlNode("Properties", nil, props) } + for _, c in inst.children or {} do + table.insert(kids, item(c)) + end + local el = XmlNode("Item", nil, kids) + Xml.setAttr(el, "class", inst.className) + Xml.setAttr(el, "referent", refs[inst]) + return el + end + local root = XmlNode("roblox", nil, {}) + Xml.setAttr(root, "version", "4") + local metaKeys = {} + for k in tree.metadata or {} do + table.insert(metaKeys, k) + end + table.sort(metaKeys) + for _, k in metaKeys do + local m = textEl("Meta", tostring((tree.metadata :: any)[k])) + m.attrs.name = k + Xml.append(root, m) + end + for _, rt in tree.roots do + Xml.append(root, item(rt)) + end + for _, x in tree.extra or {} do + if type(x) == "table" and type(x.name) == "string" and type(x.children) == "table" then + Xml.append(root, x) + end + end + if #sharedList > 0 then + local ss = XmlNode("SharedStrings", nil, {}) + for _, s in sharedList do + local el = XmlNode("SharedString", nil, { Base64.encode(s) }) + Xml.setAttr(el, "md5", sharedKeys[s]) + Xml.append(ss, el) + end + Xml.append(root, ss) + end + local indent = if opts and opts.indent ~= nil then opts.indent else 2 + local s, err = Xml.encode(root, { indent = indent, declaration = false, selfClose = false }) + if not s then + return nil, err + end + return buffer.fromstring(s), nil +end + +return Rbxmx diff --git a/tests/model/_rbx.luau b/tests/model/_rbx.luau new file mode 100644 index 0000000..40adb77 --- /dev/null +++ b/tests/model/_rbx.luau @@ -0,0 +1,286 @@ +-- tests/model/_rbx: helpers shared by the model/rbxm and model/rbxmx tests: instance paths (the scheme of the lune dump +-- in tools/fixtures/rbxmx.py), our property values in lune's canonical form, a dump comparison, a deep tree comparison, +-- and a tree with a value of every type built from scratch. +local Rbx = require("@formats/codecs/model/Rbx") + +local H = {} + +local f32buf = buffer.create(4) +local function f32(v: number): number + buffer.writef32(f32buf, 0, v) + return buffer.readf32(f32buf, 0) +end + +local function hex(s: string): string + return (string.gsub(s, ".", function(c: string): string + return string.format("%02x", string.byte(c)) + end)) +end + +-- paths(tree) -> { [path] = instance }, { [instance] = path }: names joined with "/", "#k" for the k-th sibling of a name +function H.paths(tree: any): ({ [string]: any }, { [any]: string }) + local byPath, ofInst = {}, {} + local function walk(list: { any }, prefix: string) + local seen: { [string]: number } = {} + 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 "") + byPath[p] = inst + ofInst[inst] = p + walk(inst.children, p) + end + end + walk(tree.roots, "") + return byPath, ofInst +end + +local function numbers(t: string, v: any): { number }? + if type(v) == "number" then + return { v } + elseif type(v) ~= "table" then + return nil + end + if t == "NumberSequence" or t == "ColorSequence" then + local out = {} + for _, k in v do + local n = if t == "ColorSequence" then 4 else 3 -- lune has no ColorSequence envelope + for c = 1, n do + table.insert(out, k[c]) + end + end + return out + end + return v +end + +-- same(ours: Value, want: lune canon, pathOf, propName) -> ok, detail +function H.same(v: any, want: any, pathOf: { [any]: string }, pname: string): (boolean, string) + local t = if v then v.type else "nil" + local x = if v then v.value else nil + local wt = want.t + if wt == "nil" then + return x == nil, "want nil, got " .. t + elseif wt == "string" then + return type(x) == "string" and hex(x) == want.s, "string differs (" .. t .. ")" + elseif wt == "bool" then + return x == want.b, "bool differs" + elseif wt == "Instance" then + return type(x) == "table" and pathOf[x] == want.s, "ref differs: " .. tostring(x and pathOf[x]) .. " vs " .. tostring(want.s) + elseif wt == "Content" then + if want.kind == "None" then + return x == nil, "content not none" + elseif want.kind == "Uri" then + return x == want.s, "content uri " .. tostring(x) + end + return type(x) == "table" and pathOf[x] == want.s, "content object" + elseif wt == "UniqueId" then + return x == want.s, "uniqueid " .. tostring(x) .. " vs " .. tostring(want.s) + elseif wt == "Font" then + return type(x) == "table" and x.family == want.s and x.weight == want.n[1] and x.style == want.style, "font differs" + end + local got = numbers(t, x) + if t == "Color3uint8" and got then + got = { f32(got[1] / 255), f32(got[2] / 255), f32(got[3] / 255) } + end + local n = want.n + if not got or not n then + return false, "no numbers: " .. t .. " vs " .. tostring(wt) + end + local count = #n + if t == "PhysicalProperties" then + count = math.min(#got, #n) + elseif #got ~= #n then + return false, string.format("%d numbers, want %d (%s / %s)", #got, #n, t, wt) + end + for i = 1, count do + if got[i] ~= n[i] then + return false, string.format("%s[%d] = %.9g, want %.9g", t, i, got[i], n[i]) + end + end + return true, "" +end + +-- compare(t, tree, dump, label) -> properties compared: every instance / property of a lune dump against our tree +function H.compare(t: any, tree: any, dump: any, label: string): number + local byPath, pathOf = H.paths(tree) + local n = 0 + for path, e in dump do + local inst = byPath[path] + t:check(inst ~= nil, label .. ": instance " .. path) + if inst then + t:check(inst.className == e.class, label .. ": " .. path .. " class " .. inst.className .. ", want " .. e.class) + for pname, want in e.props do + local v = if pname == "Name" then { type = "String", value = inst.name } else inst.properties[pname] + local ok, detail = H.same(v, want, pathOf, pname) + t:check(ok, label .. ": " .. path .. "." .. pname .. ": " .. detail) + n += 1 + end + end + end + return n +end + +-- the type family a value compares under (a binary file has one string type; XML writes BrickColor as an int) +local FAMILY: { [string]: string } = { + String = "string", + BinaryString = "string", + ProtectedString = "string", + ContentId = "string", + Bytecode = "string", + BrickColor = "int", + Int32 = "int", +} +local function family(t: string): string + return FAMILY[t] or t +end + +-- equal(a, b, pathA, pathB) -> ok, where: values compared deeply (Refs / Content objects by path) +local function equal(a: any, b: any, pa: { [any]: string }, pb: { [any]: string }): boolean + if type(a) ~= type(b) then + return false + end + if type(a) == "buffer" then + return buffer.tostring(a) == buffer.tostring(b) + elseif type(a) ~= "table" then + return a == b or (a ~= a and b ~= b) + end + if a.className and b.className then + return pa[a] == pb[b] + end + for k, v in a do + if not equal(v, b[k], pa, pb) then + return false + end + end + for k in b do + if a[k] == nil then + return false + end + end + return true +end + +-- sameTree(t, a, b, label, opts?) -> instances compared: class, name, children and every property (opts.loose: +-- string / int families compare as one type, properties only b has are allowed when another instance of the class has them in a; opts.skipRaw: Raw values are not compared) +function H.sameTree(t: any, a: any, b: any, label: string, opts: any?): number + local o = opts or {} + local pa = select(2, H.paths(a)) + local pb = select(2, H.paths(b)) + local n = 0 + local bad = 0 + local classProps: { [string]: { [string]: boolean } } = {} + for inst in Rbx.descendants(a) do + local i = inst :: any + classProps[i.className] = classProps[i.className] or {} + for k in i.properties do + classProps[i.className][k] = true + end + end + local function walk(la: { any }, lb: { any }, where: string) + if #la ~= #lb then + t:check(false, string.format("%s: %s has %d children, want %d", label, where, #lb, #la)) + return + end + for i, x in la do + local y = lb[i] + n += 1 + local w = where .. "/" .. x.name + if x.className ~= y.className or x.name ~= y.name then + t:check(false, label .. ": " .. w .. ": " .. y.className .. " " .. y.name) + else + for k, v in x.properties do + local u = y.properties[k] + local skip = o.skipRaw and v.type == "Raw" + if not skip then + local tt = if o.loose then family(v.type) == family(u and u.type or "") else u and u.type == v.type + if not tt or not equal(v.value, u.value, pa, pb) then + bad += 1 + if bad < 10 then + t:check(false, label .. ": " .. w .. "." .. k .. " (" .. v.type .. " / " .. tostring(u and u.type) .. ")") + end + end + end + end + for k, u in y.properties do + -- a binary file stores a value for every instance of a class: the writer fills in the ones the XML + -- twin leaves out (when another instance of the class has the property) + local filled = o.loose and classProps[y.className] and classProps[y.className][k] + if x.properties[k] == nil and not (o.skipRaw and u.type == "Raw") and not filled then + bad += 1 + if bad < 10 then + t:check(false, label .. ": " .. w .. "." .. k .. " is extra") + end + end + end + walk(x.children, y.children, w) + end + end + end + walk(a.roots, b.roots, "") + t:check(bad == 0, label .. ": " .. bad .. " property differences") + return n +end + +-- everything() -> a model with one value of every type (and several instances per class) +function H.everything(): any + local tree = Rbx.tree() + local root = Rbx.add(tree, Rbx.instance("Model", "Everything")) + local a = Rbx.add(root, Rbx.instance("Folder", "A")) + local b = Rbx.add(root, Rbx.instance("Folder", "B")) + local c = Rbx.add(a, Rbx.instance("Part", "C")) + local S = Rbx.set + S(a, "Str", "String", "plain") + S(a, "Bin", "BinaryString", "\0\1\2\255") + S(a, "Prot", "ProtectedString", "print('x')") + S(a, "Cid", "ContentId", "rbxassetid://1") + S(a, "Flag", "Bool", true) + S(a, "I32", "Int32", -2147483648) + S(a, "I64", "Int64", 2 ^ 52 + 1) + S(a, "F32", "Float32", f32(0.1)) + S(a, "F64", "Float64", 0.1) + S(a, "En", "Enum", 7) + S(a, "Brick", "BrickColor", 1004) + S(a, "Sec", "SecurityCapabilities", 2 ^ 40) + S(a, "Fc", "Faces", 63) + S(a, "Ax", "Axes", 7) + S(a, "Ud", "UDim", { 0.5, -7 }) + S(a, "Ud2", "UDim2", { 0.25, 1, -0.5, 1000 }) + S(a, "Nr", "NumberRange", { -1, 1 }) + S(a, "V2", "Vector2", { 1.5, -2.5 }) + S(a, "V2i", "Vector2int16", { -32768, 32767 }) + S(a, "V3", "Vector3", { 1, 2, 3 }) + S(a, "V3i", "Vector3int16", { -5, 0, 5 }) + S(a, "C3", "Color3", { 0.5, 0.25, 1 }) + S(a, "C3u", "Color3uint8", { 0, 128, 255 }) + S(a, "Rc", "Rect", { 1, 2, 3, 4 }) + S(a, "Ry", "Ray", { 1, 2, 3, 0, 0, -1 }) + S(a, "Cf", "CFrame", { 1, 2, 3, 0, -1, 0, 1, 0, 0, 0, 0, 1 }) + S(a, "Cf2", "CFrame", { 1, 2, 3, f32(0.36), f32(0.48), f32(-0.8), f32(-0.8), f32(0.6), 0, f32(0.48), f32(0.64), f32(0.6) }) + S(a, "Ocf", "OptionalCFrame", { 4, 5, 6, 1, 0, 0, 0, 1, 0, 0, 0, 1 }) + S(b, "Ocf", "OptionalCFrame", nil) + S(a, "Ns", "NumberSequence", { { 0, 1, 0 }, { 0.5, 2, 0.25 }, { 1, 3, 0 } }) + S(a, "Cs", "ColorSequence", { { 0, 1, 0, 0, 0 }, { 1, 0, 0, 1, 0 } }) + S(a, "Phys", "PhysicalProperties", { 1, 0.5, 0.25, 2, 3, 1 }) + S(b, "Phys", "PhysicalProperties", { 1, 0.5, 0.25, 2, 3, 0.75 }) + S(c, "Phys", "PhysicalProperties", nil) + S(a, "Ref", "Ref", c) + S(b, "Ref", "Ref", nil) + S(a, "Sh", "SharedString", "shared\0bytes") + S(b, "Sh", "SharedString", "shared\0bytes") + S(a, "Uid", "UniqueId", "7fb188dace632b4702e9c68d004815fd") + S(b, "Uid", "UniqueId", "00000000000000010000000200000003") + S(a, "Font", "Font", { family = "rbxasset://fonts/families/Arial.json", weight = 700, style = "Italic", cachedFaceId = "rbxasset://fonts/arialbd.ttf" }) + S(a, "Ct", "Content", "rbxassetid://5") + S(b, "Ct", "Content", c) + S(c, "Ct", "Content", nil) + -- the same properties on B (columns of two values), so every type is also written for a second instance + for k, v in a.properties do + if b.properties[k] == nil then + b.properties[k] = v + end + end + return tree +end + +return H diff --git a/tests/model/rbxm.luau b/tests/model/rbxm.luau new file mode 100644 index 0000000..70276df --- /dev/null +++ b/tests/model/rbxm.luau @@ -0,0 +1,251 @@ +-- model/rbxm tests: binary models and places built by rojo 7.7 and lune 0.11 (rbx-dom) decode to the values lune reads +-- from them (every property the files hold); the binary decode equals the decode of the XML twin; Zstandard and raw +-- chunk variants; an unknown chunk and an unknown property type round trip raw; our rbxm output read back by lune +-- equals the original (fixture verdicts); round trips of a tree with every type; options, errors and the fuzz pass. +-- Fixtures: tools/fixtures/rbxmx.py. +local T = require("@tests/T") +local Rbxm = require("@formats/model/rbxm") +local Rbxmx = require("@formats/model/rbxmx") +local Rbx = require("@formats/codecs/model/Rbx") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local H = require("@tests/model/_rbx") +local Fx = require("@tests/gen/rbx_files") +local Json = require("@formats/codecs/text/Json") +local Ours = require("@tests/gen/rbx_ours") + +local t = T.suite("rbxm") + +t:eq(Rbxm.name, "rbxm", "name") +t:eq(Rbxm.category, "model", "category") +t:check(table.find(Rbxm.extensions, "rbxl") ~= nil, "extensions") +t:check(Rbxm.caps.decode and Rbxm.caps.encode, "caps") + +local function decode(data: any, opts: any?): (any, any) + return Rbxm.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts) +end +local function file(name: string): any + for _, f in Fx.files do + if f.name == name then + return f + end + end + error("no fixture " .. name) +end + +-- every binary reference file against lune's reading of it, and against the decode of its XML twin +local nprops = 0 +local trees: { [string]: any } = {} +for _, f in Fx.files do + if not f.xml then + local tree, err = decode(f.data) + t:check(tree ~= nil, f.name .. ": " .. tostring(err)) + if tree then + trees[f.name] = tree + t:check(tree.kind == "rbxtree" and tree.meta.source.format == "rbxm", f.name .. ": an RbxTree") + t:eq(tree.place, f.place, f.name .. ": place") + nprops += H.compare(t, tree, Json.decode(f.dump), f.name) + end + end +end +t:note("%d binary files, %d property values match lune", #Fx.files - 3, nprops) +for _, pair in { { "model.rbxm", "model.rbxmx" }, { "place.rbxl", "place.rbxlx" }, { "lune.rbxm", "lune.rbxmx" } } do + local xt = Rbxmx.decode(Bytes.reader(buffer.fromstring(file(pair[2]).data))) + local n = H.sameTree(t, xt, trees[pair[1]], pair[1] .. " vs " .. pair[2], { loose = true }) + t:check(n > 5, pair[1] .. ": instances compared") +end + +-- the typed property folder (tools/fixtures/rbxmx.py TYPES_FOLDER), value by value +do + local tree = trees["model.rbxm"] + local f = Rbx.find(tree, "Kit/Types") :: any + t:check(f ~= nil, "Kit/Types") + local P = f.properties + local function v(name: string, typ: string): any + local x = P[name] + t:check(x ~= nil and x.type == typ, name .. " is " .. typ .. " (" .. tostring(x and x.type) .. ")") + return x and x.value + end + t:eq(v("PString", "String"), "hello & \"quotes\" \u{e9}\u{65e5}", "String") + t:eq(v("PBinary", "String"), "\0\1\2\3\4\255", "BinaryString bytes") + t:eq(v("PBool", "Bool"), true, "Bool") + t:eq(v("PInt32", "Int32"), -123, "Int32") + t:eq(v("PInt64", "Int64"), -1234567890123, "Int64") + t:eq(v("PFloat32", "Float32"), 1.5, "Float32") + t:eq(v("PFloat64", "Float64"), 3.141592653589793, "Float64") + t:eq(table.concat(v("PUDim2", "UDim2"), ","), "0.5,10,0.25,-3", "UDim2") + t:eq(table.concat(v("PRay", "Ray"), ","), "1,2,3,4,5,6", "Ray") + t:eq(v("PFaces", "Faces"), 1 + 2 + 32, "Faces") + t:eq(v("PAxes", "Axes"), 1 + 4, "Axes") + t:eq(v("PBrickColor", "BrickColor"), 21, "BrickColor") + t:eq(table.concat(v("PVector3int16", "Vector3int16"), ","), "-1,2,300", "Vector3int16") + t:eq(table.concat(v("PCFrame", "CFrame"), ","), "1,2,3,0,0,1,0,1,0,-1,0,0", "CFrame (rotation id)") + t:check(v("POptCFrame", "OptionalCFrame")[1] == 1, "OptionalCFrame") + t:check(P.POptNone and P.POptNone.type == "OptionalCFrame" and P.POptNone.value == nil, "OptionalCFrame none") + t:eq(v("PEnum", "Enum"), 3, "Enum") + t:eq(#v("PNumberSequence", "NumberSequence"), 3, "NumberSequence keypoints") + t:eq(v("PNumberSequence", "NumberSequence")[2][2], -3, "NumberSequence value") + t:eq(v("PColorSequence", "ColorSequence")[2][4], 1, "ColorSequence") + t:eq(table.concat(v("PNumberRange", "NumberRange"), ","), "1,5", "NumberRange") + t:eq(table.concat(v("PRect", "Rect"), ","), "1,2,3,4", "Rect") + t:eq(table.concat(v("PPhys", "PhysicalProperties"), ","), "1,0.5,0.25,2,3,0.75", "PhysicalProperties") + t:check(P.PPhysDefault and P.PPhysDefault.value == nil, "PhysicalProperties default") + local font = v("PFont", "Font") + t:check(font.family == "rbxasset://fonts/families/Arial.json" and font.weight == 700 and font.style == "Italic", "Font") + t:eq(v("PUniqueId", "UniqueId"), "44b188dace632b4702e9c68d004815fc", "UniqueId") + t:eq(v("PUniqueId2", "UniqueId"), "7fb188dace632b4702e9c68d004815fd", "UniqueId (top bits)") + t:eq(v("PSecurity", "SecurityCapabilities"), 12345, "SecurityCapabilities") + t:eq(v("PContent", "Content"), "rbxassetid://1234", "Content uri") + t:check(P.PContentNone and P.PContentNone.value == nil, "Content none") + t:eq(v("PContentId", "String"), "rbxassetid://99", "ContentId") + t:eq(v("PShared", "SharedString"), "\0\1\2\3", "SharedString") + local types2 = Rbx.find(tree, "Kit/Types2") :: any + t:eq(types2.properties.PShared.value, "\0\1\2\3", "SharedString shared by two instances") + local ptr = Rbx.find(tree, "Kit/Pointer") :: any + t:check(ptr.properties.Value.type == "Ref" and ptr.properties.Value.value == Rbx.find(tree, "Kit/Base"), "Ref") + t:check(string.find(Rbx.get(Rbx.find(tree, "Kit/Code") :: any, "Source"), "]]>", 1, true) ~= nil, "Source") + t:eq(Rbx.fullName(Rbx.find(tree, "Kit/Gui/Frame/Label") :: any), "Kit.Gui.Frame.Label", "fullName") + t:eq(#Rbx.find(tree, "Kit/Parts").children, 120, "120 parts") + t:eq(#Rbx.list(tree), 1 + 12 + 2 + 120, "every instance") +end + +-- chunk variants: Zstandard, raw, an unknown chunk and an unknown property type +do + local base = trees["model.rbxm"] + t:eq(table.concat(base.meta.source.compression, ","), "lz4,none", "rojo: lz4 chunks (END raw)") + for _, name in { "model-zstd.rbxm", "model-raw.rbxm" } do + local tree = trees[name] + H.sameTree(t, base, tree, name) + end + t:eq(table.concat(trees["model-zstd.rbxm"].meta.source.compression, ","), "none,zstd", "zstd chunks") + local u = trees["model-unknown.rbxm"] + H.sameTree(t, base, u, "model-unknown.rbxm", { skipRaw = true }) + t:check(#u.extra == 1 and u.extra[1].name == "ZZZZ", "the unknown chunk is kept") + local raws = 0 + for inst in Rbx.descendants(u) do + local m = (inst :: any).properties.Mystery + if m then + raws += 1 + t:check(m.type == "Raw" and m.value.typeId == 0x7f, "unknown property type kept raw") + end + end + t:check(raws > 0, "instances with the raw property: " .. raws) + local again = decode(Rbxm.encode(u) :: buffer) + t:check(again and #again.extra == 1 and buffer.tostring(again.extra[1].data) == buffer.tostring(u.extra[1].data), "unknown chunk round trip") + H.sameTree(t, u, again, "unknown round trip") + -- an edited class (an instance more) drops the raw column instead of writing it wrong + u = decode(file("model-unknown.rbxm").data) + local cls + for inst in Rbx.descendants(u) do + if (inst :: any).properties.Mystery then + cls = (inst :: any).className + break + end + end + Rbx.add(u.roots[1], Rbx.instance(cls, "Added")) + local edited = decode(Rbxm.encode(u) :: buffer) + local still = false + for inst in Rbx.descendants(edited) do + if (inst :: any).properties.Mystery then + still = true + end + end + t:check(edited and not still, "a raw column is dropped when its class changes") +end + +-- our encoder: lune reads our rbxm back to the same values (tools/fixtures/rbxmx.py) +local nours = 0 +for _, v in Ours do + if string.sub(v.name, -5) == "/rbxm" then + t:check(v.ok, v.name .. ": " .. v.detail) + nours += 1 + end +end +t:note("%d of our rbxm files read back by lune", nours) + +-- round trips: every reference file, and a tree with every type +for name, tree in trees do + local out, err = Rbxm.encode(tree) + t:check(out ~= nil, name .. ": encode " .. tostring(err)) + if out then + local back = decode(out) + H.sameTree(t, tree, back, name .. ": round trip") + t:eq(back.place, tree.place, name .. ": place round trip") + end +end +do + local tree = H.everything() + local out = Rbxm.encode(tree) :: buffer + local back = decode(out) + H.sameTree(t, tree, back, "every type", { loose = true }) + local raw = Rbxm.encode(tree, { compression = "none" }) :: buffer + local back2 = decode(raw) + H.sameTree(t, tree, back2, "every type, raw chunks", { loose = true }) + t:eq(table.concat(back2.meta.source.compression, ","), "none", "compression = none") + t:check(buffer.len(raw) > buffer.len(out), "lz4 chunks are smaller") + -- through XML and back + local viaXml = Rbxmx.decode(Bytes.reader(Rbxmx.encode(back) :: buffer)) + H.sameTree(t, tree, decode(Rbxm.encode(viaXml) :: buffer), "every type via rbxmx", { loose = true }) + -- a place: roots marked as services + local place = Rbx.tree(true) + Rbx.add(place, Rbx.instance("Workspace")) + Rbx.add(place, Rbx.instance("Lighting")) + local pb = decode(Rbxm.encode(place) :: buffer) + t:check(pb.place and pb.roots[1].service and pb.roots[2].service, "place services") + local pm = decode(Rbxm.encode(place, { place = false }) :: buffer) + t:check(not pm.place, "place = false") + tree.metadata.ExplicitAutoJoints = "true" + t:eq(decode(Rbxm.encode(tree) :: buffer).metadata.ExplicitAutoJoints, "true", "META") +end + +-- sniff, errors +do + local data = file("model.rbxm").data + t:eq(Rbxm.sniff(Bytes.reader(buffer.fromstring(data))), 1, "sniff") + t:eq(Rbxm.sniff(Bytes.reader(buffer.fromstring(file("model.rbxmx").data))), 0, "sniff XML") + local _, e1 = decode(" parents [1, 0] + local s = buffer.tostring(raw) + local at = string.find(s, "PRNT", 1, true) :: number + local body = at - 1 + 16 + -- parents are the second referent array: zigzag deltas (1, -1) = (2, 1), interleaved big-endian + buffer.writeu8(raw, body + 5 + 8 + 6, 2) + buffer.writeu8(raw, body + 5 + 8 + 7, 1) + local _, e8 = decode(raw) + t:check(e8 and e8.code == Err.CORRUPT, "a cycle: " .. tostring(e8)) +end + +-- fuzz +do + local samples = { file("model-raw.rbxm").data, Rbxm.encode(H.everything(), { compression = "none" }) :: buffer, Rbxm.encode(H.everything()) :: buffer } + t:fuzz("decode", function(b: buffer) + return Rbxm.decode(Bytes.reader(b)) + end, samples, { mutations = 150, garbage = 300, keepHeader = 32 }) +end + +t:done() diff --git a/tests/model/rbxmx.luau b/tests/model/rbxmx.luau new file mode 100644 index 0000000..e58db09 --- /dev/null +++ b/tests/model/rbxmx.luau @@ -0,0 +1,188 @@ +-- model/rbxmx tests: XML models and places built by rojo 7.7 and lune 0.11 (rbx-dom) decode to the values lune reads +-- from them; our rbxmx output read back by lune equals the original (fixture verdicts); round trips of every reference +-- file and of a tree with every type; XML specifics (BinaryString, CDATA, packed Color3, INF / NAN, unknown property +-- tags kept raw, referents, SharedStrings, floats written exactly); errors and the fuzz pass. +-- Fixtures: tools/fixtures/rbxmx.py. +local T = require("@tests/T") +local Rbxmx = require("@formats/model/rbxmx") +local Rbx = require("@formats/codecs/model/Rbx") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local H = require("@tests/model/_rbx") +local Fx = require("@tests/gen/rbx_files") +local Json = require("@formats/codecs/text/Json") +local Ours = require("@tests/gen/rbx_ours") + +local t = T.suite("rbxmx") + +t:eq(Rbxmx.name, "rbxmx", "name") +t:eq(Rbxmx.category, "model", "category") +t:check(table.find(Rbxmx.extensions, "rbxlx") ~= nil, "extensions") +t:check(Rbxmx.caps.decode and Rbxmx.caps.encode, "caps") + +local function decode(data: any, opts: any?): (any, any) + return Rbxmx.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts) +end +local function encode(tree: any, opts: any?): string + return buffer.tostring(Rbxmx.encode(tree, opts) :: buffer) +end + +local nprops = 0 +local trees: { [string]: any } = {} +for _, f in Fx.files do + if f.xml then + local tree, err = decode(f.data) + t:check(tree ~= nil, f.name .. ": " .. tostring(err)) + if tree then + trees[f.name] = tree + t:check(tree.kind == "rbxtree" and tree.meta.source.format == "rbxmx", f.name .. ": an RbxTree") + t:eq(tree.place, f.place, f.name .. ": place") + nprops += H.compare(t, tree, Json.decode(f.dump), f.name) + end + end +end +t:note("3 XML files, %d property values match lune", nprops) + +do + local tree = trees["model.rbxmx"] + local P = (Rbx.find(tree, "Kit/Types") :: any).properties + t:eq(P.PBinary.type, "BinaryString", "BinaryString (CDATA)") + t:eq(P.PBinary.value, "\0\1\2\3\4\255", "BinaryString bytes") + t:eq(P.PContentId.type, "ContentId", "ContentId") + t:eq(P.PFloat32.value, 1.5, "float") + t:eq(P.PUniqueId.value, "44b188dace632b4702e9c68d004815fc", "UniqueId") + t:eq(P.PShared.value, "\0\1\2\3", "SharedString") + t:eq(P.PBrickColor.type, "Int32", "a BrickColor of an unknown property reads as its ") + local base = (Rbx.find(tree, "Kit/Base") :: any).properties + t:eq(base.Tags.value, "Enemy\0Boss", "Tags") + t:check(#base.AttributesSerialize.value > 10, "AttributesSerialize") + local lune = trees["lune.rbxmx"] + t:eq((Rbx.find(lune, "Kit/Brick") :: any).properties.Value.type, "BrickColor", "BrickColorValue.Value is a BrickColor") +end + +local nours = 0 +for _, v in Ours do + if string.sub(v.name, -6) == "/rbxmx" then + t:check(v.ok, v.name .. ": " .. v.detail) + nours += 1 + end +end +t:note("%d of our rbxmx files read back by lune", nours) + +for name, tree in trees do + local back = decode(encode(tree)) + H.sameTree(t, tree, back, name .. ": round trip") + t:eq(back.place, tree.place, name .. ": place round trip") +end +do + local tree = H.everything() + local s = encode(tree) + H.sameTree(t, tree, decode(s), "every type", { loose = true }) + t:check(string.find(s, '', 1, true) == 1, "rbx-dom's root element") + t:check(string.find(s, "", 1, true) ~= nil, "SharedStrings") + local again = encode(decode(s)) + t:eq(again, s, "a second write is byte-identical") + local flat = encode(tree, { indent = 0 }) + t:check(not string.find(flat, "\n + + true + null + + + ]]> + 4294934528 + INF + -INF + NAN + RBXA + null + + AAEC + AwQ= + + rbxasset://textures/a.png + + 1 + true20.30.511 + + +]==] + local tree, err = decode(doc) + t:check(tree ~= nil, "a hand-written file: " .. tostring(err)) + local p = tree.roots[1] + t:eq(p.name, "Odd ", "CDATA name") + local c = p.properties.Color.value + t:check(c[1] == 1 and math.abs(c[2] - 0x80 / 255) < 1e-6 and c[3] == 0, "packed ARGB Color3") + t:eq(p.properties.Inf.value, math.huge, "INF") + t:eq(p.properties.NegInf.value, -math.huge, "-INF") + t:check(p.properties.Nan.value ~= p.properties.Nan.value, "NAN") + t:check(p.properties.Self.value == p, "Ref to itself") + t:check(p.properties.None.type == "Ref" and p.properties.None.value == nil, "Ref null") + t:eq(p.properties.Data.value, "\0\1\2\3\4", "BinaryString with whitespace") + t:eq(p.properties.Old.type, "ContentId", "legacy ") + t:eq(p.properties.Old.value, "rbxasset://textures/a.png", "url") + t:eq(p.properties.Mystery.type, "XmlRaw", "unknown tag kept") + t:eq(p.properties.Phys.value[6], 1, "acoustic absorption defaults to 1") + t:eq(tree.metadata.ExplicitAutoJoints, "true", "Meta") + t:eq(#tree.extra, 1, " kept") + local out = encode(tree) + t:check(string.find(out, '1', 1, true) ~= nil + or string.find(out, "true', 1, true) ~= nil, "Meta written") + -- a String with bytes XML cannot hold is written as a BinaryString + local raw = Rbx.tree() + local f = Rbx.add(raw, Rbx.instance("Folder")) + Rbx.set(f, "Blob", "String", "a\0b\255") + local rs = encode(raw) + t:check(string.find(rs, '', 1, true) ~= nil, "binary bytes as BinaryString") + t:eq(decode(rs).roots[1].properties.Blob.value, "a\0b\255", "binary bytes round trip") + -- floats: the shortest text that reads back exactly + local fl = Rbx.tree() + local g = Rbx.add(fl, Rbx.instance("Folder")) + Rbx.set(g, "A", "Float64", 0.1) + Rbx.set(g, "B", "Float32", 0.1) + Rbx.set(g, "C", "Vector3", { 1 / 3, 1e-30, -2 ^ 100 }) + local fs = encode(fl) + t:check(string.find(fs, '0.1', 1, true) ~= nil, "double 0.1") + t:check(string.find(fs, '0.1', 1, true) ~= nil, "float 0.1") + local fb = decode(fs).roots[1].properties + t:eq(fb.A.value, 0.1, "double exact") + local v = buffer.create(4) + buffer.writef32(v, 0, 1 / 3) + t:eq(fb.C.value[1], buffer.readf32(v, 0), "f32 exact") +end + +-- sniff, errors +do + local data = Fx.files[2].data + t:eq(Rbxmx.sniff(Bytes.reader(buffer.fromstring(data))), 1, "sniff") + t:eq(Rbxmx.sniff(Bytes.reader(buffer.fromstring("\n"))), 1, "sniff with a declaration") + t:eq(Rbxmx.sniff(Bytes.reader(buffer.fromstring(Fx.files[1].data))), 0, "sniff binary") + t:eq(Rbxmx.sniff(Bytes.reader(buffer.fromstring(""))), 0, "sniff other XML") + local _, e1 = decode("") + t:check(e1 and e1.code == Err.CORRUPT, "not : " .. tostring(e1)) + local _, e2 = decode("") + t:check(e2 and e2.code == Err.TRUNCATED, "truncated: " .. tostring(e2)) + local _, e3 = decode("") + t:check(e3 and e3.code == Err.CORRUPT, "an Item without a class: " .. tostring(e3)) + local _, e4 = Rbxmx.encode({ kind = "scene" } :: any) + t:check(e4 and e4.code == Err.ARG, "encode a non-tree") +end + +do + local samples = { Fx.files[2].data, encode(H.everything()) } + t:fuzz("decode", function(b: buffer) + return Rbxmx.decode(Bytes.reader(b)) + end, samples, { mutations = 80, garbage = 300 }) +end + +t:done() diff --git a/tools/fixtures/_rbx_encode.luau b/tools/fixtures/_rbx_encode.luau new file mode 100644 index 0000000..0b078b4 --- /dev/null +++ b/tools/fixtures/_rbx_encode.luau @@ -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 +-- "/rbxm " and "/rbxmx " 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 diff --git a/tools/fixtures/rbxmx.py b/tools/fixtures/rbxmx.py new file mode 100644 index 0000000..f399bf0 --- /dev/null +++ b/tools/fixtures/rbxmx.py @@ -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 & \"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-- & \"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(" 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(" Date: Sat, 31 Oct 2026 14:20:17 -0500 Subject: [PATCH 06/27] codecs/video/Legacy: Cinepak, Microsoft Video 1, QuickTime RLE / SMC and FLIC decoders Registry decoders (codecs/video/Video BUILTIN: cvid, CRAM / MSVC / WHAM, 'rle ', 'smc ', AFLC), rgba8 pictures painted over the previous picture, palettes from track.palette (or packet.palette). Bit-exact with ffmpeg on 28 AVI / MOV / MKV fixtures (tools/fixtures/legacy.py: ffmpeg's encoders plus encoders in _legacy_mux.py for QuickTime RLE 1/2/4/8-bit, 8-bit MS Video 1 and Cinepak). Also fixes QtPalette's big-endian reads. --- docs/FORMATS.md | 1 + src/Formats/codecs/video/Legacy/Cinepak.luau | 303 ++++++++++++++ src/Formats/codecs/video/Legacy/Flic.luau | 372 +++++++++++++++++ src/Formats/codecs/video/Legacy/Msvideo1.luau | 121 ++++++ src/Formats/codecs/video/Legacy/Picture.luau | 115 ++++++ src/Formats/codecs/video/Legacy/QtRle.luau | 276 +++++++++++++ src/Formats/codecs/video/Legacy/Smc.luau | 183 +++++++++ src/Formats/codecs/video/Legacy/init.luau | 187 +++++++++ src/Formats/codecs/video/Video/init.luau | 14 + src/Formats/containers/IsoBmff/QtPalette.luau | 9 +- src/Formats/video/mkv/Parse.luau | 5 +- tests/codecs/legacy.luau | 113 ++++++ tools/fixtures/_legacy_mux.py | 375 ++++++++++++++++++ tools/fixtures/legacy.py | 100 +++++ 14 files changed, 2171 insertions(+), 3 deletions(-) create mode 100644 src/Formats/codecs/video/Legacy/Cinepak.luau create mode 100644 src/Formats/codecs/video/Legacy/Flic.luau create mode 100644 src/Formats/codecs/video/Legacy/Msvideo1.luau create mode 100644 src/Formats/codecs/video/Legacy/Picture.luau create mode 100644 src/Formats/codecs/video/Legacy/QtRle.luau create mode 100644 src/Formats/codecs/video/Legacy/Smc.luau create mode 100644 src/Formats/codecs/video/Legacy/init.luau create mode 100644 tests/codecs/legacy.luau create mode 100644 tools/fixtures/_legacy_mux.py create mode 100644 tools/fixtures/legacy.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0a41a66..b7c26a7 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -133,5 +133,6 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ... - **video** - codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the + - codecs/video/Legacy: FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC and Smacker video decoders. - codecs/video/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from - codecs/video/Video: the video codec registry and the generic VideoDecoder. New in formats-luau. diff --git a/src/Formats/codecs/video/Legacy/Cinepak.luau b/src/Formats/codecs/video/Legacy/Cinepak.luau new file mode 100644 index 0000000..a7ed8d9 --- /dev/null +++ b/src/Formats/codecs/video/Legacy/Cinepak.luau @@ -0,0 +1,303 @@ +--!strict +--!native +--!optimize 2 +-- codecs/video/Legacy/Cinepak: Cinepak ('cvid') frames: 24-bit colour (codebook entries of 4 luma + 2 chroma, or 4 +-- luma for grey), and 8-bit palettised streams (entries are palette indexes). Written from the format description +-- (MultimediaWiki "Cinepak"): a frame header (flags, size, width, height, strip count), strips with their own V1 / V4 +-- codebooks (full or partial updates, kept per strip between frames, inherited from the strip above unless the frame +-- flags say otherwise) and the vector chunks (intra, inter with skip flags, V1-only). Colour codebook entries are +-- converted once with the Cinepak YUV formula (r = y + 2v, g = y - u/2 - v, b = y + 2u, clamped). Sega FILM's extra +-- header bytes are detected on the first frame. Paints over the previous picture. Bit-exact with ffmpeg's cinepak +-- decoder. Never throws: every read is range-checked against its chunk. +local Picture = require("@formats/codecs/video/Legacy/Picture") + +local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8 +local band = bit32.band + +local Cinepak = {} + +local MAX_STRIPS = 32 +-- a codebook: 256 entries of 4 u32 rgba pixels (16 bytes); palettised streams use the low byte (the index) +local ENTRY = 16 +local BOOK = 256 * ENTRY + +export type State = { + books: buffer, -- MAX_STRIPS * 2 codebooks (V4 then V1 per strip) + filmSkip: number, -- Sega FILM extra header bytes (-1 = not known yet) +} + +function Cinepak.state(): State + return { books = buffer.create(MAX_STRIPS * 2 * BOOK), filmSkip = -1 } +end + +local function be16(d: buffer, o: number): number + return readu8(d, o) * 256 + readu8(d, o + 1) +end +local function be24(d: buffer, o: number): number + return readu8(d, o) * 65536 + readu8(d, o + 1) * 256 + readu8(d, o + 2) +end +local function be32(d: buffer, o: number): number + return readu8(d, o) * 16777216 + readu8(d, o + 1) * 65536 + readu8(d, o + 2) * 256 + readu8(d, o + 3) +end + +local function clip(v: number): number + return if v < 0 then 0 elseif v > 255 then 255 else v +end + +-- a codebook chunk (ids 0x20..0x27): entries of 4 or 6 bytes, all of them or those whose flag bit is set +local function codebook(books: buffer, book: number, id: number, d: buffer, p: number, stop: number) + local six = band(id, 4) == 0 + local partial = band(id, 1) ~= 0 + local size = if six then 6 else 4 + local flag, mask = 0, 0 + for i = 0, 255 do + if partial then + mask //= 2 + if mask == 0 then + if p + 4 > stop then + return + end + flag = be32(d, p) + p += 4 + mask = 0x80000000 + end + end + if not partial or band(flag, mask) ~= 0 then + if p + size > stop then + return + end + local e = book + i * ENTRY + local y0, y1, y2, y3 = readu8(d, p), readu8(d, p + 1), readu8(d, p + 2), readu8(d, p + 3) + if six then + local u, v = readu8(d, p + 4), readu8(d, p + 5) + if u >= 128 then + u -= 256 + end + if v >= 128 then + v -= 256 + end + local uh = if u < 0 then -((-u) // 2) else u // 2 -- C division (towards zero) + local dr, dg, db = 2 * v, -uh - v, 2 * u + writeu32(books, e, clip(y0 + dr) + clip(y0 + dg) * 256 + clip(y0 + db) * 65536 + 0xFF000000) + writeu32(books, e + 4, clip(y1 + dr) + clip(y1 + dg) * 256 + clip(y1 + db) * 65536 + 0xFF000000) + writeu32(books, e + 8, clip(y2 + dr) + clip(y2 + dg) * 256 + clip(y2 + db) * 65536 + 0xFF000000) + writeu32(books, e + 12, clip(y3 + dr) + clip(y3 + dg) * 256 + clip(y3 + db) * 65536 + 0xFF000000) + else + writeu32(books, e, y0 * 0x10101 + 0xFF000000) + writeu32(books, e + 4, y1 * 0x10101 + 0xFF000000) + writeu32(books, e + 8, y2 * 0x10101 + 0xFF000000) + writeu32(books, e + 12, y3 * 0x10101 + 0xFF000000) + end + p += size + end + end +end + +-- the vectors of a strip (ids 0x30 intra, 0x31 inter with skip flags, 0x32 V1 only); false on truncated data +local function vectors(pic: Picture.Picture, books: buffer, v4: number, v1: number, id: number, d: buffer, p: number, + stop: number, x1: number, y1: number, x2: number, y2: number): boolean + local stride = pic.stride + local pal = pic.idx + local px = (pal or pic.rgba) :: buffer + local flag, mask = 0, 0 + local inter = band(id, 1) ~= 0 + local v1only = band(id, 2) ~= 0 + for y = y1, y2 - 1, 4 do + for x = x1, x2 - 1, 4 do + local paint = true + if inter then + mask //= 2 + if mask == 0 then + if p + 4 > stop then + return false + end + flag = be32(d, p) + p += 4 + mask = 0x80000000 + end + paint = band(flag, mask) ~= 0 + end + if paint then + local useV1 = v1only + if not v1only then + mask //= 2 + if mask == 0 then + if p + 4 > stop then + return false + end + flag = be32(d, p) + p += 4 + mask = 0x80000000 + end + useV1 = band(flag, mask) == 0 + end + local o = y * stride + x + if useV1 then + if p >= stop then + return false + end + local e = v1 + readu8(d, p) * ENTRY + p += 1 + -- each of the 4 entries fills a 2x2 square + local a, b, c, e4 = readu32(books, e), readu32(books, e + 4), readu32(books, e + 8), readu32(books, e + 12) + if pal then + a, b, c, e4 = a % 256, b % 256, c % 256, e4 % 256 + writeu32(px, o, a * 0x0101 + b * 0x01010000) + writeu32(px, o + stride, a * 0x0101 + b * 0x01010000) + writeu32(px, o + 2 * stride, c * 0x0101 + e4 * 0x01010000) + writeu32(px, o + 3 * stride, c * 0x0101 + e4 * 0x01010000) + else + for r = 0, 3 do + local q = (o + r * stride) * 4 + local l, rr = if r < 2 then a else c, if r < 2 then b else e4 + writeu32(px, q, l) + writeu32(px, q + 4, l) + writeu32(px, q + 8, rr) + writeu32(px, q + 12, rr) + end + end + else + if p + 4 > stop then + return false + end + local e0 = v4 + readu8(d, p) * ENTRY + local e1 = v4 + readu8(d, p + 1) * ENTRY + local e2 = v4 + readu8(d, p + 2) * ENTRY + local e3 = v4 + readu8(d, p + 3) * ENTRY + p += 4 + -- entry k covers the 2x2 square k (top-left, top-right, bottom-left, bottom-right) + if pal then + for r = 0, 3 do + local l, rr = if r < 2 then e0 else e2, if r < 2 then e1 else e3 + local off = (r % 2) * 8 + local q = o + r * stride + writeu8(px, q, readu8(books, l + off)) + writeu8(px, q + 1, readu8(books, l + off + 4)) + writeu8(px, q + 2, readu8(books, rr + off)) + writeu8(px, q + 3, readu8(books, rr + off + 4)) + end + else + for r = 0, 3 do + local l, rr = if r < 2 then e0 else e2, if r < 2 then e1 else e3 + local off = (r % 2) * 8 + local q = (o + r * stride) * 4 + writeu32(px, q, readu32(books, l + off)) + writeu32(px, q + 4, readu32(books, l + off + 4)) + writeu32(px, q + 8, readu32(books, rr + off)) + writeu32(px, q + 12, readu32(books, rr + off + 4)) + end + end + end + end + end + end + return true +end + +-- decode(pic, data, state, hasPalette) -> picture?, message: true = a picture; false + nil = no picture for this +-- packet (an empty frame); false + message = an error +function Cinepak.decode(pic: Picture.Picture, d: buffer, st: State, newPalette: boolean): (boolean, string?) + local n = buffer.len(d) + if n < 10 then + return false, "frame too short" + end + local strips = be16(d, 8) + if strips == 0 and not (pic.idx and newPalette) then + return false, nil + end + local size = be24(d, 1) + if n < size * 5 // 100 then + return false, "frame shorter than its header says" + end + if st.filmSkip < 0 then + if size == 0 then + return false, "unsupported: a zero frame size" + end + if size ~= n and n % size ~= 0 then + if n >= 16 and readu8(d, 10) == 0xFE and readu8(d, 11) == 0 and readu8(d, 12) == 0 and readu8(d, 13) == 6 + and readu8(d, 14) == 0 and readu8(d, 15) == 0 then + st.filmSkip = 6 + else + st.filmSkip = 2 + end + else + st.filmSkip = 0 + end + end + local skip = st.filmSkip + if n < 10 + skip + strips * 12 then + return false, "truncated strip headers" + end + if strips > 0 then + local ss = be24(d, 10 + skip + 1) + if ss < 12 or ss > size then + return false, "bad strip size" + end + end + local flags = readu8(d, 0) + local p = 10 + skip + strips = math.min(strips, MAX_STRIPS) + local books = st.books + -- the coded area: the size rounded up to whole blocks (the picture's plane) + local cw, ch = pic.stride, pic.rows + local y0 = 0 + for i = 0, strips - 1 do + if p + 12 > n then + return true, nil + end + local sy1 = be16(d, p + 4) + local sx1 = be16(d, p + 6) + local sy2, sx2 = be16(d, p + 8), be16(d, p + 10) + if sy1 == 0 then + sy1 = y0 + sy2 = y0 + sy2 + end + local ssize = be24(d, p + 1) - 12 + if ssize < 0 then + return true, nil + end + p += 12 + local stop = math.min(n, p + ssize) + local v4 = i * 2 * BOOK + local v1 = v4 + BOOK + if i > 0 and band(flags, 1) == 0 then + buffer.copy(books, v4, books, v4 - 2 * BOOK, 2 * BOOK) + end + -- the strip's chunks: codebooks, then one vector chunk + -- (strips start on block boundaries in every known stream: the plane holds whole blocks only) + if sx2 > cw or sy2 > ch or sx1 >= sx2 or sy1 >= sy2 or band(sx1, 3) ~= 0 or band(sy1, 3) ~= 0 then + return true, nil + end + local q = p + local done = false + while q + 4 <= stop do + local id = readu8(d, q) + local csize = be24(d, q + 1) - 4 + if csize < 0 then + return true, nil + end + q += 4 + local cstop = math.min(stop, q + csize) + if id == 0x20 or id == 0x21 or id == 0x24 or id == 0x25 then + codebook(books, v4, id, d, q, cstop) + elseif id == 0x22 or id == 0x23 or id == 0x26 or id == 0x27 then + codebook(books, v1, id, d, q, cstop) + elseif id == 0x30 or id == 0x31 or id == 0x32 then + if not vectors(pic, books, v4, v1, id, d, q, cstop, sx1, sy1, sx2, sy2) then + return true, nil + end + done = true + break + end + q = cstop + end + if not done then + return true, nil + end + p = stop + y0 = sy2 + end + return true, nil +end + +return Cinepak diff --git a/src/Formats/codecs/video/Legacy/Flic.luau b/src/Formats/codecs/video/Legacy/Flic.luau new file mode 100644 index 0000000..99c72f7 --- /dev/null +++ b/src/Formats/codecs/video/Legacy/Flic.luau @@ -0,0 +1,372 @@ +--!strict +--!native +--!optimize 2 +-- codecs/video/Legacy/Flic: Autodesk Animator FLI / FLC frames (the F1FA frame chunks; the file format is +-- video/fli). Written from the FLIC file format description (Jim Kent's "FLC - Animator Pro Flic Files", Dr. Dobb's +-- 1993; MultimediaWiki "Flic Video"). 8-bit palettised: COLOR_256 (4), COLOR_64 (11, 6-bit entries widened by bit +-- replication), DELTA_FLC / SS2 (7: word runs, line skips, last-byte opcode), DELTA_FLI / LC (12: byte runs), BLACK +-- (13), BYTE_RUN / BRUN (15), FLI_COPY (16, rows padded to 4), PSTAMP (18, skipped). 15 / 16 / 24-bit FLC and FLX +-- (DTA): DELTA / DTA_LC (pixel runs), BLACK, BRUN (byte runs), DTA_BRUN (25, pixel runs), COPY / DTA_COPY (16 / 26); +-- pixels are 5-5-5 / 5-6-5 little-endian words or B, G, R bytes. Not supported: 1-bit FLICs, the Magic Carpet +-- 6-bit COLOR_256 variant. Paints over the previous picture. Bit-exact with ffmpeg's flic decoder on valid frames. +-- Never throws: reads past the frame give zeros, every write is range-checked (a damaged frame gives no picture). +local Types = require("@formats/Types") +local Picture = require("@formats/codecs/video/Legacy/Picture") + +local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 +local bfill = buffer.fill + +local Flic = {} + +-- the decoding state of one stream: a byte plane (stride = width * bytes per pixel) and the palette +export type State = { + pic: Picture.Picture, + depth: number, -- 8, 15, 16, 24 + bpp: number, -- bytes per pixel +} + +-- state(w, h, depth) -> State | nil, message +function Flic.state(w: number, h: number, depth: number): (State?, string?) + local bpp = if depth == 8 then 1 elseif depth == 15 or depth == 16 then 2 elseif depth == 24 then 3 else 0 + if bpp == 0 then + return nil, "unsupported: " .. depth .. "-bit FLIC" + end + local pic = Picture.new(w * bpp, h, true) + pic.w = w + return { pic = pic, depth = depth, bpp = bpp }, nil +end + +local function s8(v: number): number + return if v >= 128 then v - 256 else v +end + +-- decode(st, data) -> true | false, message +function Flic.decode(st: State, d: buffer): (boolean, string?) + local pic = st.pic + local px = pic.idx :: buffer + local pal = pic.pal + local w, h = pic.w, pic.h + local bpp = st.bpp + local deep = bpp > 1 + local stride = pic.stride + local limit = stride * h + local n = buffer.len(d) + if n < 16 then + return false, "frame too short" + end + local p = 0 + local function u8(): number + local v = if p < n then readu8(d, p) else 0 + p += 1 + return v + end + local function u16(): number + local a = u8() + return a + u8() * 256 + end + local frameSize = math.min(readu32(d, 0), n) + local chunks = readu8(d, 6) + readu8(d, 7) * 256 + if frameSize < 16 then + return false, "bad frame size" + end + frameSize -= 16 + p = 16 + while frameSize >= 6 and chunks > 0 and n - p >= 4 do + local size = readu32(d, p) + if size > frameSize then + size = frameSize + end + local after = p + size + p += 4 + local typ = u16() + if typ == 4 or typ == 11 then + if not deep then + -- palette packets: skip count, change count (0 = 256), r g b + local shift = typ == 11 + local packets = u16() + local at = 0 + for _ = 1, packets do + at += u8() + local count = u8() + if count == 0 then + count = 256 + end + if p + count * 3 > after then + break + end + for _ = 1, count do + if at >= 256 then + at = 0 + end + local r, g, b = u8(), u8(), u8() + if shift then + -- 6-bit entries: v << 2 (kept to 8 bits), the top two bits repeated below + r, g, b = r * 4 % 256, g * 4 % 256, b * 4 % 256 + r, g, b = r + r // 64, g + g // 64, b + b // 64 + end + writeu32(pal, at * 4, r + g * 256 + b * 65536 + 0xFF000000) + at += 1 + end + end + end + elseif typ == 7 or (deep and typ == 27) then + -- word-oriented delta: per line a count of packets (or a line skip / last-byte opcode) + local y = 0 + local lines = u16() + while lines > 0 do + if p + 2 > after then + break + end + if y > limit then + return false, "delta past the picture" + end + local lp = u16() + if lp >= 0x8000 then + lp -= 0x10000 + end + if deep then + if lp < 0 then + if -lp > h then + return false, "bad line skip" + end + y += -lp * stride + continue + end + elseif lp < 0 and lp >= -0x4000 then + -- 0xC000 .. 0xFFFF: skip lines + if -lp > h then + return false, "bad line skip" + end + y += -lp * stride + continue + elseif lp < 0 then + -- 0x8000 .. 0xBFFF: the low byte goes into the line's last pixel (ffmpeg writes the last byte of its + -- padded row instead: the same pixel when rows are not padded) + local q = y + w - 1 + if q < 0 or q >= limit then + return false, "delta past the picture" + end + writeu8(px, q, lp % 256) + continue + elseif lp >= 0x4000 then + continue -- undefined opcode + end + lines -= 1 + local q = y + for _ = 1, lp do + if p + 2 > after then + break + end + q += u8() * bpp + local run = s8(u8()) + if deep then + local cnt = if run < 0 then -run else run + if q + cnt * bpp > limit then + return false, "delta past the picture" + end + if run < 0 then + local a, b, c = u8(), u8(), if bpp == 3 then u8() else 0 + for _ = 1, cnt do + writeu8(px, q, a) + writeu8(px, q + 1, b) + if bpp == 3 then + writeu8(px, q + 2, c) + end + q += bpp + end + else + if p + cnt * bpp > after then + break + end + buffer.copy(px, q, d, p, cnt * bpp) + p += cnt * bpp + q += cnt * bpp + end + elseif run < 0 then + local cnt = -run + local a, b = u8(), u8() + if q + cnt * 2 > limit then + return false, "delta past the picture" + end + for _ = 1, cnt do + writeu8(px, q, a) + writeu8(px, q + 1, b) + q += 2 + end + else + if q + run * 2 > limit then + return false, "delta past the picture" + end + if p + run * 2 > after then + break + end + buffer.copy(px, q, d, p, run * 2) + p += run * 2 + q += run * 2 + end + end + y += stride + end + elseif typ == 12 and not deep then + -- byte-oriented delta (LC): first line, line count, per line packets of (skip, run) + local first = u16() + if first >= h then + return false, "bad first line" + end + local y = first * stride + local lines = u16() + while lines > 0 do + local q = y + if q > limit then + return false, "delta past the picture" + end + if p + 1 > after then + break + end + local packets = u8() + for _ = 1, packets do + if p + 1 > after then + break + end + q += u8() + local run = s8(u8()) + if run > 0 then + if q + run > limit then + return false, "delta past the picture" + end + if p + run > after then + break + end + buffer.copy(px, q, d, p, run) + p += run + q += run + elseif run < 0 then + local v = u8() + if q - run > limit then + return false, "delta past the picture" + end + bfill(px, q, v, -run) + q -= run + end + end + y += stride + lines -= 1 + end + elseif typ == 13 then + bfill(px, 0, 0, limit) + elseif typ == 15 or (deep and typ == 25) then + -- byte run (BRUN: bytes; DTA_BRUN: pixels of a deep FLIC): > 0 a run of one value, < 0 literals + local unit = if typ == 25 then bpp else 1 + local y = 0 + for _ = 1, h do + local q = y + p += 1 -- the packet count (unused) + local left = if typ == 25 then w else w * bpp + while left > 0 do + if p + 1 > after then + break + end + local run = s8(u8()) + if run == 0 and not deep then + return false, "zero byte run" + end + if run > 0 then + if q + run * unit > limit then + return false, "run past the picture" + end + if unit == 1 then + bfill(px, q, u8(), run) + q += run + else + local a, b, c = u8(), u8(), if bpp == 3 then u8() else 0 + for _ = 1, run do + writeu8(px, q, a) + writeu8(px, q + 1, b) + if bpp == 3 then + writeu8(px, q + 2, c) + end + q += bpp + end + end + left -= run + else + local cnt = -run + if q + cnt * unit > limit then + return false, "run past the picture" + end + if p + cnt * unit > after then + break + end + buffer.copy(px, q, d, p, cnt * unit) + p += cnt * unit + q += cnt * unit + left -= cnt + end + end + y += stride + end + elseif typ == 16 or (deep and typ == 26) then + -- uncompressed rows (8-bit rows padded to 4 bytes; deep rows of an odd width carry one pixel more) + local row = w * bpp + local padded = if deep then row + (w % 2) * bpp else ((w + 3) // 4) * 4 + local ok = if deep then size - 6 <= ((w + 1) // 2) * 2 * h * bpp else size - 6 == padded * h + if ok then + if deep and n - p < row * h then + return false, "truncated copy chunk" + end + for y = 0, h - 1 do + local s = p + y * padded + local cnt = math.max(0, math.min(row, n - s)) + if cnt > 0 then + buffer.copy(px, y * stride, d, s, cnt) + end + end + p += padded * h + end + end + -- typ 18 (PSTAMP) and unknown chunks are skipped + if after - p >= 0 then + p = after + else + break + end + frameSize -= size + chunks -= 1 + end + return true, nil +end + +-- image(st) -> a fresh rgba8 Image +function Flic.image(st: State): Types.Image + local pic = st.pic + if st.bpp == 1 then + return Picture.image(pic) + end + local w, h = pic.w, pic.h + local img = Types.Image.new(w, h, "rgba8") + local out = img.pixels + local px = pic.idx :: buffer + local stride = pic.stride + if st.bpp == 3 then + for y = 0, h - 1 do + local s, o = y * stride, y * w * 4 + for x = 0, w - 1 do + local q = s + x * 3 + writeu32(out, o + x * 4, readu8(px, q + 2) + readu8(px, q + 1) * 256 + readu8(px, q) * 65536 + 0xFF000000) + end + end + else + local lut = if st.depth == 15 then Picture.rgb555() else Picture.rgb565() + local mask = if st.depth == 15 then 32768 else 65536 + for y = 0, h - 1 do + local s, o = y * stride, y * w * 4 + for x = 0, w - 1 do + local q = s + x * 2 + writeu32(out, o + x * 4, readu32(lut, ((readu8(px, q) + readu8(px, q + 1) * 256) % mask) * 4)) + end + end + end + return img +end + +return Flic diff --git a/src/Formats/codecs/video/Legacy/Msvideo1.luau b/src/Formats/codecs/video/Legacy/Msvideo1.luau new file mode 100644 index 0000000..417ad45 --- /dev/null +++ b/src/Formats/codecs/video/Legacy/Msvideo1.luau @@ -0,0 +1,121 @@ +--!strict +--!native +--!optimize 2 +-- codecs/video/Legacy/Msvideo1: Microsoft Video 1 (CRAM / MSVC / WHAM) frames, 8-bit palettised and 16-bit +-- X-R-G-B 1-5-5-5. Written from the format description (MultimediaWiki "Microsoft Video 1"): 4x4 blocks, block rows +-- bottom-up (rows of a block bottom-up too), each block a 16-bit code: a skip count (0x84xx - 0x87xx), a 2-colour +-- block (16 flag bits + 2 colours; at 16 bits a first colour with bit 15 set makes it an 8-colour block, one colour +-- pair per quadrant; at 8 bits codes >= 0x9000 are 8-colour), or a 1-colour block. Paints over the previous picture. +-- Bit-exact with ffmpeg's msvideo1 decoder. Never throws: every read is range-checked (a damaged frame stops there). +local Picture = require("@formats/codecs/video/Legacy/Picture") + +local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32 +local band = bit32.band + +local Msvideo1 = {} + +-- the colour of pixel (x, y) of a block (y = 0 is the block's bottom row) for flag bit f: 2-colour c0 / c1 +-- (bit set = c0), 8-colour: colours[quadrant * 2 + (bit clear)] +local function quadrant(x: number, y: number): number + return (if y >= 2 then 4 else 0) + (if x >= 2 then 2 else 0) +end + +-- decode(pic, data, bits) -> true | false, message (bits = 8: palettised, else 16-bit) +function Msvideo1.decode(pic: Picture.Picture, d: buffer, bits: number): (boolean, string?) + local n = buffer.len(d) + local bw, bh = pic.w // 4, pic.h // 4 + if n < bw * bh // 512 then + return false, "frame too small" + end + local stride = pic.stride + local total = bw * bh + local skip = 0 + local p = 0 + local wide = bits ~= 8 + local px = (if wide then pic.rgba else pic.idx) :: buffer + local lut = if wide then Picture.rgb555() else nil + local c = table.create(8, 0) + for by = bh - 1, 0, -1 do + for bx = 0, bw - 1 do + if skip ~= 0 then + skip -= 1 + total -= 1 + continue + end + if p + 2 > n then + return true, nil + end + local a, b = readu8(d, p), readu8(d, p + 1) + p += 2 + if a == 0 and b == 0 and total == 0 then + return true, nil + end + -- the block's bottom-left pixel; its rows go up + local o = (by * 4 + 3) * stride + bx * 4 + if band(b, 0xFC) == 0x84 then + skip = (b - 0x84) * 256 + a - 1 + elseif b < 0x80 or (not wide and b >= 0x90) then + local flags = b * 256 + a + local eight + if wide then + if p + 4 > n then + return true, nil + end + c[1], c[2] = readu16(d, p), readu16(d, p + 2) + p += 4 + eight = c[1] >= 0x8000 + if eight then + if p + 12 > n then + return true, nil + end + for k = 3, 8 do + c[k] = readu16(d, p) + p += 2 + end + end + else + eight = b >= 0x90 + local cnt = if eight then 8 else 2 + if p + cnt > n then + return true, nil + end + for k = 1, cnt do + c[k] = readu8(d, p) + p += 1 + end + end + for y = 0, 3 do + local row = o - y * stride + for x = 0, 3 do + local k = (if band(flags, 1) == 1 then 1 else 2) + if eight then + k += quadrant(x, y) + end + flags = flags // 2 + if lut then + writeu32(px, (row + x) * 4, readu32(lut, (c[k] % 32768) * 4)) + else + writeu8(px, row + x, c[k]) + end + end + end + else + local v = if wide then readu32(lut :: buffer, ((b * 256 + a) % 32768) * 4) else a + for y = 0, 3 do + local row = o - y * stride + if lut then + for x = 0, 3 do + writeu32(px, (row + x) * 4, v) + end + else + writeu32(px, row, v * 0x01010101) + end + end + end + total -= 1 + end + end + return true, nil +end + +return Msvideo1 diff --git a/src/Formats/codecs/video/Legacy/Picture.luau b/src/Formats/codecs/video/Legacy/Picture.luau new file mode 100644 index 0000000..e4080c6 --- /dev/null +++ b/src/Formats/codecs/video/Legacy/Picture.luau @@ -0,0 +1,115 @@ +--!strict +--!native +--!optimize 2 +-- codecs/video/Legacy/Picture: the picture every legacy decoder keeps between frames (they are all inter-frame +-- codecs: a packet paints over the previous picture). Palettised codecs keep a u8 index plane and a 256-entry palette, +-- direct-colour ones an rgba8 plane; both planes are padded (stride / rows) so the codecs' block and run writes past +-- the visible edge land in range. Also the 5-5-5 / 5-6-5 to 8-bit tables: channels are widened by bit replication +-- (c << 3 | c >> 2), as ffmpeg's swscale does, so the output equals ffmpeg's rgba conversion. New in formats-luau. +local Types = require("@formats/Types") +local Pixels = require("@formats/codecs/image/Pixels") + +local readu32, writeu32 = buffer.readu32, buffer.writeu32 + +local Picture = {} + +export type Picture = { + w: number, + h: number, + stride: number, -- index plane: bytes per row; rgba plane: pixels per row + rows: number, + idx: buffer?, -- u8 index plane, stride * rows bytes (palettised) + rgba: buffer?, -- u32 rgba8 plane, stride * rows * 4 bytes (direct colour) + pal: buffer, -- 256 u32 entries, bytes R, G, B, A +} + +-- new(w, h, palettised, padW?, padH?, palette?) -> a black picture; padW / padH round the plane up (blocks of 4, ...) +function Picture.new(w: number, h: number, palettised: boolean, padW: number?, padH: number?, palette: buffer?): Picture + local pw, ph = padW or 1, padH or 1 + local stride = ((w + pw - 1) // pw) * pw + local rows = ((h + ph - 1) // ph) * ph + local pal = buffer.create(1024) + if palette and buffer.len(palette) >= 1024 then + buffer.copy(pal, 0, palette, 0, 1024) + end + local p: Picture = { w = w, h = h, stride = stride, rows = rows, pal = pal } + if palettised then + p.idx = buffer.create(stride * rows) + else + p.rgba = buffer.create(stride * rows * 4) + end + return p +end + +-- image(p) -> a fresh rgba8 Image of the visible w x h +function Picture.image(p: Picture): Types.Image + local w, h = p.w, p.h + local img = Types.Image.new(w, h, "rgba8") + local idx, rgba = p.idx, p.rgba + if idx then + Pixels.indexed(idx, 0, p.stride, 8, img.pixels, w, h, true, p.pal) + elseif rgba then + if p.stride == w then + buffer.copy(img.pixels, 0, rgba, 0, w * h * 4) + else + for y = 0, h - 1 do + buffer.copy(img.pixels, y * w * 4, rgba, y * p.stride * 4, w * 4) + end + end + end + return img +end + +-- setPalette(p, src): a 1024-byte palette (u32 R, G, B, A entries) from a packet or the track +function Picture.setPalette(p: Picture, src: buffer) + if buffer.len(src) >= 1024 then + buffer.copy(p.pal, 0, src, 0, 1024) + end +end + +local lut555: buffer? = nil +local lut565: buffer? = nil + +-- rgb555() -> u32 table: X-R-G-B 1-5-5-5 value -> rgba8 pixel (opaque); 32768 entries +function Picture.rgb555(): buffer + local t = lut555 + if t then + return t + end + local b = buffer.create(32768 * 4) + for v = 0, 32767 do + local r, g, bl = v // 1024, (v // 32) % 32, v % 32 + r, g, bl = r * 8 + r // 4, g * 8 + g // 4, bl * 8 + bl // 4 + writeu32(b, v * 4, r + g * 256 + bl * 65536 + 0xFF000000) + end + lut555 = b + return b +end + +-- rgb565() -> u32 table: R-G-B 5-6-5 value -> rgba8 pixel; 65536 entries +function Picture.rgb565(): buffer + local t = lut565 + if t then + return t + end + local b = buffer.create(65536 * 4) + for v = 0, 65535 do + local r, g, bl = v // 2048, (v // 32) % 64, v % 32 + r, g, bl = r * 8 + r // 4, g * 4 + g // 16, bl * 8 + bl // 4 + writeu32(b, v * 4, r + g * 256 + bl * 65536 + 0xFF000000) + end + lut565 = b + return b +end + +-- copy of a picture's plane (for decoders that read the previous picture while writing the next) +function Picture.clonePlane(p: Picture): buffer + local src = (p.idx or p.rgba) :: buffer + local c = buffer.create(buffer.len(src)) + buffer.copy(c, 0, src, 0) + return c +end + +local _ = readu32 + +return Picture diff --git a/src/Formats/codecs/video/Legacy/QtRle.luau b/src/Formats/codecs/video/Legacy/QtRle.luau new file mode 100644 index 0000000..2c687e8 --- /dev/null +++ b/src/Formats/codecs/video/Legacy/QtRle.luau @@ -0,0 +1,276 @@ +--!strict +--!native +--!optimize 2 +-- codecs/video/Legacy/QtRle: QuickTime Animation ('rle ') frames, depths 1, 2, 4, 8 (palettised; 33..40 = grey) and +-- 16 (X-R-G-B 1-5-5-5), 24 (R, G, B), 32 (A, R, G, B). Written from the format description (Apple QuickTime File +-- Format; MultimediaWiki "Apple QuickTime RLE"): a chunk size, a header (0x0008: start line + line count), then per +-- line a skip byte and run codes until -1 (0: another skip; < 0: one pixel group repeated; > 0: literal groups). +-- Groups are 4 pixels at 8 bits, 8 at 4 bits, 16 at 2 bits, 1 pixel at 16 / 24 / 32 bits; the 1-bit layout has its +-- own (skip, code) pairs where a skip with bit 7 set moves to the next line. Paints over the previous picture; frames +-- shorter than 8 bytes repeat it. Bit-exact with ffmpeg's qtrle decoder on valid streams. Never throws: every read +-- and write is range-checked (a damaged frame stops where the damage is). +local Picture = require("@formats/codecs/video/Legacy/Picture") + +local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32 +local band, rshift = bit32.band, bit32.rshift + +local QtRle = {} + +local function s8(v: number): number + return if v >= 128 then v - 256 else v +end + +-- 1-bit: (skip, code) pairs; skip bit 7 = next line (the first one starts the first line) +local function decode1(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number) + row -= stride + local q = row + lines += 1 + while lines > 0 do + if p + 2 > n then + return + end + local skip = readu8(d, p) + local code = s8(readu8(d, p + 1)) + p += 2 + if code == 0 then + return + end + if skip >= 128 then + lines -= 1 + row += stride + q = row + 16 * (skip - 128) + else + q += 16 * skip + end + if q < 0 or q > limit then + return + end + if code ~= -1 then + if code < 0 then + local cnt = -code + if p + 2 > n or q + cnt * 16 > limit then + return + end + local a, b = readu8(d, p), readu8(d, p + 1) + p += 2 + for _ = 1, cnt do + for k = 7, 0, -1 do + writeu8(px, q, band(rshift(a, k), 1)) + q += 1 + end + for k = 7, 0, -1 do + writeu8(px, q, band(rshift(b, k), 1)) + q += 1 + end + end + else + local cnt = code * 2 + if p + cnt > n or q + cnt * 8 > limit then + return + end + for _ = 1, cnt do + local a = readu8(d, p) + p += 1 + for k = 7, 0, -1 do + writeu8(px, q, band(rshift(a, k), 1)) + q += 1 + end + end + end + end + end +end + +-- 2 / 4 / 8-bit: groups of 16 / 8 / 4 indexes (4 bytes); skips count groups +local function decodeIdx(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number, bpp: number) + local group = 32 // bpp -- pixels per 4 bytes + local per = 8 // bpp -- pixels per byte + local mask = 2 ^ bpp - 1 + for _ = 1, lines do + if p >= n then + return + end + local q = row + group * (readu8(d, p) - 1) + p += 1 + if q < 0 or q > limit then + return + end + while true do + if p >= n then + return + end + local code = s8(readu8(d, p)) + p += 1 + if code == -1 then + break + end + if p >= n then + return + end + if code == 0 then + q += group * (readu8(d, p) - 1) + p += 1 + if q < 0 or q > limit then + return + end + elseif code < 0 then + local cnt = -code + if p + 4 > n or q + cnt * group > limit then + return + end + if bpp == 8 then + local v = readu32(d, p) + for _ = 1, cnt do + writeu32(px, q, v) + q += 4 + end + else + local v0 = q + for b = 0, 3 do + local byte = readu8(d, p + b) + for k = per - 1, 0, -1 do + writeu8(px, q, band(rshift(byte, k * bpp), mask)) + q += 1 + end + end + for _ = 2, cnt do + buffer.copy(px, q, px, v0, group) + q += group + end + end + p += 4 + else + local bytes = code * 4 + if p + bytes > n or q + bytes * per > limit then + return + end + if bpp == 8 then + buffer.copy(px, q, d, p, bytes) + q += bytes + else + for b = 0, bytes - 1 do + local byte = readu8(d, p + b) + for k = per - 1, 0, -1 do + writeu8(px, q, band(rshift(byte, k * bpp), mask)) + q += 1 + end + end + end + p += bytes + end + end + row += stride + end +end + +-- 16 / 24 / 32-bit: one pixel per group, into the rgba8 plane (stride in pixels) +local function decodeRgb(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number, depth: number) + local bpp = depth // 8 + local lut = if depth == 16 then Picture.rgb555() else nil + for _ = 1, lines do + if p >= n then + return + end + local q = row + (readu8(d, p) - 1) + p += 1 + if q < 0 or q > limit then + return + end + while true do + if p >= n then + return + end + local code = s8(readu8(d, p)) + p += 1 + if code == -1 then + break + end + if p >= n then + return + end + if code == 0 then + q += readu8(d, p) - 1 + p += 1 + if q < 0 or q > limit then + return + end + else + local cnt = if code < 0 then -code else code + local need = if code < 0 then bpp else bpp * cnt + if p + need > n or q + cnt > limit then + return + end + for _ = 1, cnt do + local v + if lut then + v = readu32(lut, (readu8(d, p) * 256 + readu8(d, p + 1)) % 32768 * 4) + elseif bpp == 3 then + v = readu8(d, p) + readu8(d, p + 1) * 256 + readu8(d, p + 2) * 65536 + 0xFF000000 + else + v = readu8(d, p + 1) + readu8(d, p + 2) * 256 + readu8(d, p + 3) * 65536 + readu8(d, p) * 16777216 + end + writeu32(px, q * 4, v) + q += 1 + if code > 0 then + p += bpp + end + end + if code < 0 then + p += bpp + end + end + end + row += stride + end +end + +-- decode(pic, data, depth) -> true (a picture, possibly the previous one again) | false, message +function QtRle.decode(pic: Picture.Picture, d: buffer, depth: number): (boolean, string?) + local n = buffer.len(d) + if n < 8 then + return true, nil -- no change + end + local p = 4 + local header = readu8(d, p) * 256 + readu8(d, p + 1) + p += 2 + local h = pic.h + local start, lines = 0, h + if band(header, 8) ~= 0 then + if n < 14 then + return true, nil + end + start = readu8(d, p) * 256 + readu8(d, p + 1) + lines = readu8(d, p + 4) * 256 + readu8(d, p + 5) + p += 8 + if lines > h - start then + return true, nil + end + end + local stride = pic.stride + local bits = if depth > 32 then depth - 32 else depth + local idx, rgba = pic.idx, pic.rgba + if idx and bits <= 8 then + local limit = stride * h + if bits == 1 then + decode1(idx, stride, limit, d, p, n, start * stride, lines) + else + decodeIdx(idx, stride, limit, d, p, n, start * stride, lines, bits) + end + elseif rgba and (bits == 16 or bits == 24 or bits == 32) then + decodeRgb(rgba, stride, stride * h, d, p, n, start * stride, lines, bits) + else + return false, "unsupported: depth " .. depth + end + return true, nil +end + +-- palettised(depth) -> whether the depth uses a palette; pad(depth) -> the row padding the plane needs +function QtRle.palettised(depth: number): boolean + return depth <= 8 or depth > 32 +end +function QtRle.pad(depth: number): number + local bits = if depth > 32 then depth - 32 else depth + return if bits <= 8 then 32 // math.max(1, bits) else 1 +end + +return QtRle diff --git a/src/Formats/codecs/video/Legacy/Smc.luau b/src/Formats/codecs/video/Legacy/Smc.luau new file mode 100644 index 0000000..6ff9a60 --- /dev/null +++ b/src/Formats/codecs/video/Legacy/Smc.luau @@ -0,0 +1,183 @@ +--!strict +--!native +--!optimize 2 +-- codecs/video/Legacy/Smc: QuickTime Graphics ('smc ') frames, 8-bit palettised. Written from the format description +-- (MultimediaWiki "Apple SMC"): 4x4 blocks in raster order, opcodes in the high nibble with a block count (low nibble +-- + 1, or the next byte + 1 when bit 4 is set): skip, repeat the last block, repeat the last pair of blocks, 1-colour +-- fill, 2 / 4 / 8-colour blocks (the colour groups go into 256-entry rotating tables, or come from them by index: +-- the tables restart every frame) and 16-colour blocks. Paints over the previous picture. Bit-exact with ffmpeg's smc +-- decoder (for widths whose rows are not padded: the previous block of a row start is the last block of the row +-- above). Never throws: reads past the data give zeros, the block count bounds every write. +local Picture = require("@formats/codecs/video/Legacy/Picture") + +local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 +local band, rshift = bit32.band, bit32.rshift + +local Smc = {} + +-- decode(pic, data, tables) -> true | false, message. tables = Smc.tables() (scratch, reused between frames) +function Smc.decode(pic: Picture.Picture, d: buffer, tables: buffer): (boolean, string?) + local px = pic.idx :: buffer + local n = buffer.len(d) + local stride = pic.stride -- a multiple of 4: the plane holds whole blocks + local bh = pic.rows // 4 + local total = ((pic.w + 3) // 4) * ((pic.h + 3) // 4) + if total // 1024 > n then + return false, "frame too small" + end + local blocksWide = (pic.w + 3) // 4 + local p = 4 -- flags byte + 24-bit chunk size + -- block position: bx, by (blocks) + local bx, by = 0, 0 + local pairI, quadI, octI = 0, 0, 0 + -- tables: pairs at 0 (256 * 2), quads at 512 (256 * 4), octets at 1536 (256 * 8) + local function u8(): number + if p < n then + local v = readu8(d, p) + p += 1 + return v + end + return 0 + end + local function advance() + bx += 1 + if bx >= blocksWide then + bx = 0 + by += 1 + end + total -= 1 + end + while total > 0 do + if p >= n then + return false, "truncated" + end + local op = readu8(d, p) + p += 1 + local kind = rshift(op, 4) + local count: number + if kind < 8 then + count = if band(op, 0x10) ~= 0 then 1 + u8() else 1 + band(op, 15) + else + count = band(op, 15) + 1 + end + if kind <= 1 then + for _ = 1, count do + if total <= 0 then + break + end + advance() + end + elseif kind <= 5 then + -- repeat the last block (2, 3) or the last pair of blocks (4, 5) + local pair = kind >= 4 + local back = if pair then 2 else 1 + local pos = by * blocksWide + bx + if pos < back then + return false, "repeat before any block" + end + local reps = if pair then count * 2 else count + local srcA = pos - back + local srcB = pos - 1 + for k = 0, reps - 1 do + if total <= 0 or by >= bh then + break + end + local s = if pair and k % 2 == 1 then srcB else srcA + local sx, sy = (s % blocksWide) * 4, (s // blocksWide) * 4 + local o, so = by * 4 * stride + bx * 4, sy * stride + sx + for r = 0, 3 do + writeu32(px, o + r * stride, readu32(px, so + r * stride)) + end + advance() + end + elseif kind <= 7 then + local c = u8() + local v = c * 0x01010101 + for _ = 1, count do + if total <= 0 or by >= bh then + break + end + local o = by * 4 * stride + bx * 4 + for r = 0, 3 do + writeu32(px, o + r * stride, v) + end + advance() + end + elseif kind <= 13 then + -- 2 / 4 / 8-colour blocks: a new colour group (even kinds) or one from the table (odd kinds) + local size = if kind <= 9 then 2 elseif kind <= 11 then 4 else 8 + local base = if size == 2 then 0 elseif size == 4 then 512 else 1536 + local entry: number + if kind % 2 == 0 then + local i = if size == 2 then pairI elseif size == 4 then quadI else octI + for k = 0, size - 1 do + writeu8(tables, base + i * size + k, u8()) + end + entry = i + i = (i + 1) % 256 + if size == 2 then + pairI = i + elseif size == 4 then + quadI = i + else + octI = i + end + else + entry = u8() + end + local t = base + entry * size + for _ = 1, count do + if total <= 0 or by >= bh then + break + end + local o = by * 4 * stride + bx * 4 + if size == 2 then + local f = u8() * 256 + u8() + for k = 0, 15 do + local bit = band(rshift(f, 15 - k), 1) + writeu8(px, o + (k // 4) * stride + k % 4, readu8(tables, t + bit)) + end + elseif size == 4 then + local f = u8() * 16777216 + u8() * 65536 + u8() * 256 + u8() + for k = 0, 15 do + local i = band(rshift(f, 30 - 2 * k), 3) + writeu8(px, o + (k // 4) * stride + k % 4, readu8(tables, t + i)) + end + else + -- 6 bytes 01 23 45 67 89 AB -> rows 0-1 flags 012456, rows 2-3 flags 89A37B (3 bits per pixel) + local v1 = u8() * 256 + u8() + local v2 = u8() * 256 + u8() + local v3 = u8() * 256 + u8() + local fa = band(v1, 0xFFF0) * 256 + rshift(v2, 4) + local fb = band(v3, 0xFFF0) * 256 + band(v1, 15) * 256 + band(v2, 15) * 16 + band(v3, 15) + for k = 0, 15 do + local f = if k < 8 then fa else fb + local i = band(rshift(f, 21 - 3 * (k % 8)), 7) + writeu8(px, o + (k // 4) * stride + k % 4, readu8(tables, t + i)) + end + end + advance() + end + else + -- 16-colour blocks + for _ = 1, count do + if total <= 0 or by >= bh then + break + end + local o = by * 4 * stride + bx * 4 + for k = 0, 15 do + writeu8(px, o + (k // 4) * stride + k % 4, u8()) + end + advance() + end + end + end + return true, nil +end + +-- tables() -> the colour group scratch (pairs, quads, octets) +function Smc.tables(): buffer + return buffer.create(512 + 1024 + 2048) +end + +return Smc diff --git a/src/Formats/codecs/video/Legacy/init.luau b/src/Formats/codecs/video/Legacy/init.luau new file mode 100644 index 0000000..51729a4 --- /dev/null +++ b/src/Formats/codecs/video/Legacy/init.luau @@ -0,0 +1,187 @@ +--!strict +-- codecs/video/Legacy: FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC and Smacker video decoders. +-- The 1990s inter-frame codecs as codecs/video/Video registry decoders (rgba8 pictures, one per packet): Autodesk +-- FLI / FLC ("flic", the frames of video/fli), Cinepak ("cinepak", +-- 'cvid'), Microsoft Video 1 ("msvideo1": CRAM / MSVC / WHAM, 8-bit palettised and 16-bit), QuickTime Animation +-- ("qtrle", 'rle ': depths 1 / 2 / 4 / 8 / 16 / 24 / 32 and grey) and QuickTime Graphics ("smc", 'smc '). +-- New in formats-luau, written from the format descriptions (see each submodule); decoding is bit-exact with ffmpeg's +-- decoders (tests/codecs/legacy.luau). Every decoder keeps the previous picture (a packet paints over it) and returns +-- a fresh copy. +-- +-- Palettes come from the Track: track.palette (256 u32 entries, bytes R, G, B, A: the AVI BITMAPINFO palette, the +-- QuickTime sample description's colour table, ...) and a packet's own `palette` (same layout) replaces it from that +-- packet on. Depths come from track.bitsPerPixel (AVI biBitCount, the QuickTime depth). +-- +-- local dec, err = Legacy.newDecoder("cinepak", track, { maxPixels = 2^22 }) -- a Types.VideoCodecDecoder +-- Legacy.CODECS --> { "flic", "cinepak", "msvideo1", "qtrle", "smc" } +-- +-- Never throws: bad tracks return nil, Err; bad packets return Err from decode(). +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Picture = require("@formats/codecs/video/Legacy/Picture") +local Flic = require("@formats/codecs/video/Legacy/Flic") +local Cinepak = require("@formats/codecs/video/Legacy/Cinepak") +local Msvideo1 = require("@formats/codecs/video/Legacy/Msvideo1") +local QtRle = require("@formats/codecs/video/Legacy/QtRle") +local Smc = require("@formats/codecs/video/Legacy/Smc") + +local Legacy = {} + +Legacy.Picture = Picture +Legacy.Flic = Flic +Legacy.Cinepak = Cinepak +Legacy.Msvideo1 = Msvideo1 +Legacy.QtRle = QtRle +Legacy.Smc = Smc +Legacy.CODECS = { "flic", "cinepak", "msvideo1", "qtrle", "smc" } + +export type Options = { + maxPixels: number?, -- refuse bigger pictures (LIMIT; default 2^26) + [string]: any, +} + +-- the per-codec pieces: make(track) -> state, step(state, data, packet) -> image? | nil, Err? +type Codec = { + make: (track: Types.Track) -> (any, string?), + step: (st: any, data: buffer, packet: Types.Packet) -> (Types.Image?, Err.Err?), +} + +local function fail(msg: string?): Err.Err + return Err.from(msg or "corrupt frame") +end + +local function packetPalette(pic: Picture.Picture, packet: Types.Packet): boolean + local pal = (packet :: any).palette + if type(pal) == "buffer" then + Picture.setPalette(pic, pal) + return true + end + return false +end + +local CODECS: { [string]: Codec } = { + qtrle = { + make = function(t) + local depth = t.bitsPerPixel or 24 + local bits = if depth > 32 then depth - 32 else depth + if not (bits == 1 or bits == 2 or bits == 4 or bits == 8 or bits == 16 or bits == 24 or bits == 32) then + return nil, "unsupported: depth " .. depth + end + return { pic = Picture.new(t.width :: number, t.height :: number, QtRle.palettised(depth), QtRle.pad(depth), 1, t.palette), depth = depth }, nil + end, + step = function(st, data, packet) + packetPalette(st.pic, packet) + local ok, msg = QtRle.decode(st.pic, data, st.depth) + if not ok then + return nil, fail(msg) + end + return Picture.image(st.pic), nil + end, + }, + smc = { + make = function(t) + return { pic = Picture.new(t.width :: number, t.height :: number, true, 4, 4, t.palette), tables = Smc.tables() }, nil + end, + step = function(st, data, packet) + packetPalette(st.pic, packet) + local ok, msg = Smc.decode(st.pic, data, st.tables) + if not ok then + return nil, fail(msg) + end + return Picture.image(st.pic), nil + end, + }, + msvideo1 = { + make = function(t) + if (t.width :: number) < 4 or (t.height :: number) < 4 then + return nil, "smaller than one block" + end + local bits = if t.bitsPerPixel == 8 then 8 else 16 + return { pic = Picture.new(t.width :: number, t.height :: number, bits == 8, 4, 4, t.palette), bits = bits }, nil + end, + step = function(st, data, packet) + if st.bits == 8 then + packetPalette(st.pic, packet) + end + local ok, msg = Msvideo1.decode(st.pic, data, st.bits) + if not ok then + return nil, fail(msg) + end + return Picture.image(st.pic), nil + end, + }, + cinepak = { + make = function(t) + local pal = t.bitsPerPixel == 8 + return { pic = Picture.new(t.width :: number, t.height :: number, pal, 4, 4, t.palette), cp = Cinepak.state() }, nil + end, + step = function(st, data, packet) + local newPal = st.pic.idx ~= nil and packetPalette(st.pic, packet) + local ok, msg = Cinepak.decode(st.pic, data, st.cp, newPal) + if not ok then + return nil, if msg then fail(msg) else nil + end + return Picture.image(st.pic), nil + end, + }, + flic = { + make = function(t) + return Flic.state(t.width :: number, t.height :: number, t.bitsPerPixel or 8) + end, + step = function(st, data, _packet) + local ok, msg = Flic.decode(st, data) + if not ok then + return nil, fail(msg) + end + return Flic.image(st), nil + end, + }, +} + +-- newDecoder(id, track, opts?) -> a Types.VideoCodecDecoder | nil, Err +function Legacy.newDecoder(id: string, track: Types.Track, opts: Options?): (Types.VideoCodecDecoder?, Err.Err?) + local codec = CODECS[id] + if not codec then + return nil, Err.new(Err.UNSUPPORTED, "no legacy codec " .. tostring(id)) + end + local w, h = track.width or 0, track.height or 0 + if type(w) ~= "number" or type(h) ~= "number" or w <= 0 or h <= 0 or w ~= w // 1 or h ~= h // 1 then + return nil, Err.new(Err.CORRUPT, "video track without a valid size") + end + local max = (opts and opts.maxPixels) or 2 ^ 26 + if w * h > max or w > 32768 or h > 32768 then + return nil, Err.new(Err.LIMIT, "picture of " .. w .. " x " .. h .. " over the limit") + end + local st, msg = codec.make(track) + if not st then + return nil, fail(msg) + end + -- Video.simpleDecoder, without requiring the registry (which requires this module) + local queue: { any } = {} + local self = {} + function self.decode(_: any, packet: Types.Packet): Err.Err? + local ok, img, err = pcall(codec.step, st, packet.data, packet) + if not ok then + return Err.new(Err.CORRUPT, "decoder failed: " .. tostring(img)) + end + if img then + table.insert(queue, { img, packet.pts, packet.keyframe }) + end + return err + end + function self.receive(_: any): (Types.Image?, number?, boolean?) + local q = table.remove(queue, 1) + if q then + return q[1], q[2], q[3] + end + return nil, nil, nil + end + function self.flush(_: any) end + function self.reset(_: any) + table.clear(queue) + st = codec.make(track) or st -- back to a black picture with the track's palette (decoding restarts at a keyframe) + end + return self :: any, nil +end + +return Legacy diff --git a/src/Formats/codecs/video/Video/init.luau b/src/Formats/codecs/video/Video/init.luau index 0960b9b..1b7cde8 100644 --- a/src/Formats/codecs/video/Video/init.luau +++ b/src/Formats/codecs/video/Video/init.luau @@ -294,6 +294,13 @@ local function h264Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDec return H264.newVideoDecoder(track, opts) end +-- FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC, Smacker (codecs/video/Legacy) +local function legacyDecoder(id: string): (track: Types.Track, opts: any?) -> (Types.VideoCodecDecoder?, Err.Err?) + return function(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + return require("@formats/codecs/video/Legacy").newDecoder(id, track, opts) + end +end + -- ------------------------------------------------------------------------------------------------ registry -- the codecs known by name (decoders where `new` is set). FourCCs compare case-sensitively first, then upper-cased. local BUILTIN: { Entry } = { @@ -309,6 +316,13 @@ local BUILTIN: { Entry } = { { id = "av1", name = "AV1", fourcc = { "AV01", "av01" }, matroska = { "V_AV1" } }, { id = "theora", name = "Theora", matroska = { "V_THEORA" } }, { id = "png", name = "PNG", fourcc = { "png ", "MPNG" }, matroska = { "V_PNG" } }, + -- legacy inter-frame codecs (codecs/video/Legacy; rgba8 pictures, palettes from track.palette) + { id = "cinepak", name = "Cinepak", fourcc = { "cvid" }, new = legacyDecoder("cinepak") }, + { id = "msvideo1", name = "Microsoft Video 1", fourcc = { "CRAM", "MSVC", "WHAM" }, new = legacyDecoder("msvideo1") }, + { id = "qtrle", name = "QuickTime Animation (RLE)", fourcc = { "rle " }, new = legacyDecoder("qtrle") }, + { id = "smc", name = "QuickTime Graphics (SMC)", fourcc = { "smc " }, new = legacyDecoder("smc") }, + { id = "flic", name = "Autodesk Animator FLIC", fourcc = { "AFLC" }, new = legacyDecoder("flic") }, + { id = "smackvid", name = "Smacker video", fourcc = { "SMK2", "SMK4" }, new = legacyDecoder("smackvid") }, } local byId: { [string]: Entry } = {} diff --git a/src/Formats/containers/IsoBmff/QtPalette.luau b/src/Formats/containers/IsoBmff/QtPalette.luau index 2034dc3..91b4524 100644 --- a/src/Formats/containers/IsoBmff/QtPalette.luau +++ b/src/Formats/containers/IsoBmff/QtPalette.luau @@ -10,7 +10,14 @@ -- -- depth: the stored depth (24, 32, 40, ...), palette: 256 u32 entries (bytes R, G, B, 0xFF) | nil -- -- Never throws. -local readu8, readu16, readu32, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32 +local readu8, writeu32 = buffer.readu8, buffer.writeu32 + +local function readu16(b: buffer, o: number): number -- big-endian + return readu8(b, o) * 256 + readu8(b, o + 1) +end +local function readu32(b: buffer, o: number): number + return readu16(b, o) * 65536 + readu16(b, o + 2) +end local QtPalette = {} diff --git a/src/Formats/video/mkv/Parse.luau b/src/Formats/video/mkv/Parse.luau index 252a004..b4766d4 100644 --- a/src/Formats/video/mkv/Parse.luau +++ b/src/Formats/video/mkv/Parse.luau @@ -313,8 +313,9 @@ local function parseTracks(buf: buffer, off: number, len: number, scaleNs: numbe t.kind = if ttype == 1 then "video" elseif ttype == 2 then "audio" elseif ttype == 17 then "subtitle" else "data" t.codecTag = codecId t.codec = codecFor(codecId, t.kind, t.bitsPerSample) - if t.kind == "video" and t.config then - vfwOrQuickTime(t, codecId, t.config) + local cfg: buffer? = t.config + if t.kind == "video" and cfg then + vfwOrQuickTime(t, codecId, cfg) end if t.kind == "audio" then t.sampleRate = t.sampleRate or 8000 diff --git a/tests/codecs/legacy.luau b/tests/codecs/legacy.luau new file mode 100644 index 0000000..236f7d2 --- /dev/null +++ b/tests/codecs/legacy.luau @@ -0,0 +1,113 @@ +-- codecs/video/Legacy tests: Cinepak (24-bit, grey, 8-bit palettised, several strips, a 92x68 size), Microsoft Video 1 +-- (16-bit, 8-bit with an AVI palette), QuickTime RLE (depths 1 / 2 / 4 / 8 with colour tables, default Macintosh +-- tables and grey ramps; 16 / 24 / 32-bit and grey from ffmpeg) and QuickTime SMC, in AVI, MOV and MKV: every frame +-- equals ffmpeg's decode (CRC-32 of rgba); seeking; the registry entries; the fuzz pass on each codec's packet decoder. +-- Fixtures: tools/fixtures/legacy.py. +local T = require("@tests/T") +local F = require("@formats") +local Crc32 = require("@formats/core/Crc32") +local Video = require("@formats/codecs/video/Video") +local Legacy = require("@formats/codecs/video/Legacy") +local Fx = require("@tests/gen/legacy_cases") + +local t = T.suite("legacy") + +-- the registry +t:eq(Video.fromFourcc("cvid"), "cinepak", "cvid") +t:eq(Video.fromFourcc("CRAM"), "msvideo1", "CRAM") +t:eq(Video.fromFourcc("msvc"), "msvideo1", "msvc") +t:eq(Video.fromFourcc("rle "), "qtrle", "rle ") +t:eq(Video.fromFourcc("smc "), "smc", "smc ") +for _, id in Legacy.CODECS do + t:check(Video.canDecode(id), id .. ": decodable") +end + +local samples: { [string]: { any } } = {} + +for _, c in Fx do + local label = c.name + local v, err = F.video.open(c.data) + t:check(v ~= nil, label .. ": open: " .. tostring(err)) + if v then + t:eq(v.codec, c.codec, label .. ": codec") + t:eq(v.width, c.width, label .. ": width") + local n, bad, first = 0, 0, nil + while true do + local f, ferr = v:nextFrame() + if not f then + t:check(ferr == nil, label .. ": decode error " .. tostring(ferr)) + break + end + n += 1 + local img = f.image + if img.format ~= "rgba8" or img.width ~= c.width or Crc32.of(img.pixels) ~= c.frames[n] then + bad += 1 + first = first or n + end + end + t:check(n == #c.frames and bad == 0, string.format("%s: %d of %d frames equal ffmpeg's (%d differ, first %s)", label, n - bad, #c.frames, bad, tostring(first))) + -- seeking: back to the start, the first frame again + v:seek(0) + local f = v:nextFrame() + t:check(f ~= nil and Crc32.of(f.image.pixels) == c.frames[1], label .. ": seek(0)") + -- packets for the fuzz pass + local dmx = v.demuxer + local tr = dmx:track("video") + if not samples[c.codec] then + local list = {} + for k = 1, math.min(3, dmx:count(tr.id)) do + table.insert(list, dmx:get(tr.id, k).data) + end + samples[c.codec] = { track = tr, packets = list } + end + end +end + +-- the fuzz pass on the native packet decoders (no pcall in between) +local P = Legacy.Picture +local raw: { [string]: (tr: any) -> (buffer) -> any } = { + cinepak = function(tr) + return function(b) + local pic = P.new(tr.width, tr.height, tr.bitsPerPixel == 8, 4, 4, tr.palette) + return Legacy.Cinepak.decode(pic, b, Legacy.Cinepak.state(), false) + end + end, + msvideo1 = function(tr) + return function(b) + local bits = if tr.bitsPerPixel == 8 then 8 else 16 + return Legacy.Msvideo1.decode(P.new(tr.width, tr.height, bits == 8, 4, 4), b, bits) + end + end, + qtrle = function(tr) + return function(b) + local d = tr.bitsPerPixel or 24 + for _, depth in { d, 1, 2, 4, 8, 16, 32 } do + Legacy.QtRle.decode(P.new(tr.width, tr.height, Legacy.QtRle.palettised(depth), Legacy.QtRle.pad(depth), 1), b, depth) + end + return true + end + end, + smc = function(tr) + return function(b) + return Legacy.Smc.decode(P.new(tr.width, tr.height, true, 4, 4), b, Legacy.Smc.tables()) + end + end, +} +for id, s in samples do + local fn = raw[id] + if fn then + t:fuzz(id .. " packets", fn(s.track), s.packets, { mutations = 24, garbage = 60 }) + end +end +t:fuzz("open", function(b: buffer) + local v = F.video.open(b) + if v then + for _ = 1, 3 do + if not v:nextFrame() then + break + end + end + end + return v +end, { Fx[1].data, Fx[#Fx].data }, { mutations = 8, garbage = 20 }) +t:done() diff --git a/tools/fixtures/_legacy_mux.py b/tools/fixtures/_legacy_mux.py new file mode 100644 index 0000000..c00c674 --- /dev/null +++ b/tools/fixtures/_legacy_mux.py @@ -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 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("= 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 diff --git a/tools/fixtures/legacy.py b/tools/fixtures/legacy.py new file mode 100644 index 0000000..863b866 --- /dev/null +++ b/tools/fixtures/legacy.py @@ -0,0 +1,100 @@ +# 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) From 4dcb0051807c30ec6feb8894a8a6ff6600662a6e Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:22:39 -0500 Subject: [PATCH 07/27] ws-video2-theora: video/ogv, Ogg video (Theora + Vorbis / Opus / FLAC) Demuxes every logical stream of the first Ogg group into containers/Demux: Theora (frame times from granules, Xiph-laced headers as track.config, comment tags in meta.tags), Vorbis / Opus / FLAC audio (headers in track.config) for the api's openAudio hook; open = Video.open. Sniff claims only Ogg files with a Theora BOS page. encode remuxes Theora (+ Vorbis / Opus pages from AudioWrap, interleaved by time). codecs/video/Theora gains info / comment helpers. --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/codecs/video/Theora/init.luau | 33 +- src/Formats/video/ogv/init.luau | 407 ++++++++++++++++++++++ tests/video/ogv.luau | 211 +++++++++++ tools/fixtures/theora.py | 10 + 6 files changed, 667 insertions(+), 7 deletions(-) create mode 100644 src/Formats/video/ogv/init.luau create mode 100644 tests/video/ogv.luau diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 5f34e95..d1c5a0e 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -33,6 +33,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | video | mp4 | .mp4 .m4v .mov .qt .3gp .3g2 .mj2 | yes | yes | streaming: true, remux: true, video: "mjpeg", "mpeg1", "h264", audio: true, fragments: true | `tests/video/mp4.luau` | | video | mpegps | .mpg .mpeg .vob .m1v .mpv .dat | yes | - | streaming: true, video: "mpeg1", audio: true | `tests/video/mpegps.luau` | | video | mpegts | .ts .m2ts .mts .tsv | yes | - | streaming: true, video: "mpeg1", "h264", audio: true | `tests/video/mpegts.luau` | +| video | ogv | .ogv .ogg | yes | yes | streaming: true, remux: true, video: "theora", audio: true | `tests/video/ogv.luau` | | video | y4m | .y4m | yes | yes | streaming: true, video: "rawvideo", depths: 8, 10, 12, 16 | `tests/video/y4m.luau` | | model | 3mf | .3mf | yes | yes | materials: true, vertexColors: true, textures: true, units: true | `tests/model/3mf.luau` | | model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6c0344c..206913c 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -350,6 +350,18 @@ local list: { Entry } = { return require("@formats/video/mpegts") end, }, + { + name = "ogv", + category = "video", + path = "video/ogv", + extensions = { "ogv", "ogg" }, + mime = { "video/ogg" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "containers/Demux", "containers/AudioWrap", "codecs/video/Theora", "codecs/video/Video", "codecs/video/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "theora" }, audio = true }, + load = function() + return require("@formats/video/ogv") + end, + }, { name = "y4m", category = "video", diff --git a/src/Formats/codecs/video/Theora/init.luau b/src/Formats/codecs/video/Theora/init.luau index dd99346..c607c0e 100644 --- a/src/Formats/codecs/video/Theora/init.luau +++ b/src/Formats/codecs/video/Theora/init.luau @@ -23,6 +23,8 @@ local Decoder = require("@formats/codecs/video/Theora/Decoder") local Theora = {} +export type Info = Header.Info + export type Options = { maxPixels: number?, -- larger coded frames are refused (default 4096 * 2304) } @@ -75,6 +77,24 @@ function Theora.splitConfig(c: buffer): { buffer }? return out end +-- info(idHeader) -> Header.Info (frame / picture size, frame rate, granule shift, pixel format, ...) | nil, Err +function Theora.info(h: buffer): (Header.Info?, Err.Err?) + local ok, info, err = pcall(Header.info, h, 0, buffer.len(h)) + if not ok or not info then + return nil, Err.from(if ok then err else tostring(info)) + end + return info, nil +end + +-- comment(commentHeader) -> vendor, { "KEY=value" }, tags (lower-case keys) | nil, nil, nil, Err +function Theora.comment(h: buffer): (string?, { string }?, { [string]: string }?, Err.Err?) + local ok, vendor, list, err = pcall(Header.comment, h, 0, buffer.len(h)) + if not ok or not vendor or not list then + return nil, nil, nil, Err.from(if ok then err else tostring(vendor)) + end + return vendor, list, (VorbisComment.tags(list)), nil +end + -- granuleFrame(info, granulepos) -> the 0-based index of the frame a granule position ends on (-1 for none) function Theora.granuleFrame(info: Header.Info, g: number): number if g < 0 then @@ -124,24 +144,23 @@ function Theora.new(headers: { buffer } | buffer, opts: Options?): (TheoraDecode if not list or #list < 3 or type(list[1]) ~= "buffer" or type(list[2]) ~= "buffer" or type(list[3]) ~= "buffer" then return nil, Err.new(Err.CORRUPT, "missing Theora headers") end - local ok, info, ierr = pcall(Header.info, list[1], 0, buffer.len(list[1])) - if not ok or not info then - return nil, Err.from(if ok then ierr else tostring(info)) + local info, ierr = Theora.info(list[1]) + if not info then + return nil, ierr end local maxPixels = opts and opts.maxPixels or 4096 * 2304 if info.frameWidth * info.frameHeight > maxPixels then return nil, Err.new(Err.LIMIT, "frame of " .. info.frameWidth .. "x" .. info.frameHeight .. " is over maxPixels") end - local ok2, vendor, comments, cerr = pcall(Header.comment, list[2], 0, buffer.len(list[2])) - if not ok2 or not vendor or not comments then - return nil, Err.from(if ok2 then cerr else tostring(vendor)) + local vendor, comments, tags, cerr = Theora.comment(list[2]) + if not vendor or not comments or not tags then + return nil, cerr end local ok3, setup, serr = pcall(Header.setup, list[3], 0, buffer.len(list[3])) if not ok3 or not setup then return nil, Err.from(if ok3 then serr else tostring(setup)) end local st = Decoder.new(info, setup) - local tags = VorbisComment.tags(comments) return setmetatable({ info = info, vendor = vendor, diff --git a/src/Formats/video/ogv/init.luau b/src/Formats/video/ogv/init.luau new file mode 100644 index 0000000..0750440 --- /dev/null +++ b/src/Formats/video/ogv/init.luau @@ -0,0 +1,407 @@ +--!strict +-- video/ogv: Ogg video (.ogv, or .ogg with a Theora stream: the Ogg Theora mapping of the Theora I specification, +-- RFC 3533 / 5334). New in formats-luau, on containers/Ogg and containers/Demux. +-- Read: open() demuxes every logical stream of the first Ogg group into a packet index: Theora video (frame times from +-- the granule positions: keyframe number << shift | frames since it; the three headers become track.config, +-- Xiph-laced as in Matroska, so codecs/video/Theora decodes it through the codecs/video/Video registry), Vorbis / +-- Opus / FLAC audio (headers in track.config, times from the granules) reaching the audio formats through the api's +-- opts.openAudio hook; the Theora comment header's tags go to meta.tags. Ogv.demux(r) gives the Demuxer alone. +-- Write: remux (encode): a Theora video track copied from the source (ogv / mkv), plus its Vorbis / Opus audio copied +-- (the audio pages come from containers/AudioWrap and are interleaved by time). +-- Not supported: chained Ogg files (only the first group of streams), Skeleton / Kate / Speex streams (skipped), +-- encoding Theora (there is no encoder: other sources cannot be written). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Ogg = require("@formats/containers/Ogg") +local Demux = require("@formats/containers/Demux") +local AudioWrap = require("@formats/containers/AudioWrap") +local Theora = require("@formats/codecs/video/Theora") +local Video = require("@formats/codecs/video/Video") +local Source = require("@formats/codecs/video/Video/Source") + +-- ------------------------------------------------------------------------------------------------ contract +local Ogv = { + name = "ogv", + category = "video", + extensions = { "ogv", "ogg" }, + mime = { "video/ogg" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "containers/Demux", "containers/AudioWrap", "codecs/video/Theora", "codecs/video/Video", "codecs/video/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "theora" }, audio = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + rgba: boolean?, -- nextFrame returns rgba8 images (default false: yuv420p from the codec) + track: number?, -- the video track id to decode (default: the first video track) + audio: boolean?, -- false: do not open the audio track + maxPixels: number?, + verify: boolean?, -- false: skip the page CRC checks (default true) + openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder +} +export type EncodeOptions = { + audio: boolean?, -- false: no audio; true: fail when the audio cannot be copied (default: dropped) +} + +-- ------------------------------------------------------------------------------------------------ constants +local AUDIO = { vorbis = true, opus = true, flac = true } + +-- ------------------------------------------------------------------------------------------------ sniff +-- 1 when one of the beginning-of-stream pages at the start of an Ogg file is a Theora identification header (plain +-- Ogg Vorbis / Opus / FLAC files are left to the audio formats) +function Ogv.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "OggS" then + return 0 + end + local b, p, lim = r.buf, r.pos, r.limit + for _ = 1, 8 do + if p + 27 > lim or buffer.readstring(b, p, 4) ~= "OggS" or buffer.readu8(b, p + 5) % 4 < 2 then + return 0 + end + local nseg = buffer.readu8(b, p + 26) + local d = p + 27 + nseg + if d + 7 <= lim and buffer.readu8(b, d) == 0x80 and buffer.readstring(b, d + 1, 6) == "theora" then + return 1 + end + if d > lim then + return 0 + end + local size = 0 + for i = 0, nseg - 1 do + size += buffer.readu8(b, p + 27 + i) + end + p = d + size + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ encode +-- the pages of an Ogg buffer: { offset, size, serial, granule, bos } +local function pages(b: buffer): { { number } } + local out = {} + local pos = 0 + while true do + local p = Ogg.Page.find(b, pos, nil, false) + if not p then + break + end + table.insert(out, { p.offset, p.size, p.granule, if p.bos then 1 else 0, if p.continued then 1 else 0 }) + pos = p.offset + p.size + end + return out +end + +-- encode(video, opts?) -> an Ogg file | nil, Err: a VideoDecoder or Demuxer whose video track is Theora (ogv, mkv) +function Ogv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: any = opts or {} + local streams, err = Source.streams(value, o, { video = { copy = { theora = true } }, audio = { copy = { vorbis = true, opus = true } } }) + if not streams then + return nil, err + end + local vs: Source.Stream? = nil + local as: Source.Stream? = nil + for _, s in streams do + if s.kind == "video" and s.codec == "theora" and not vs then + vs = s + elseif s.kind == "audio" and s.copied and not as then + as = s + end + end + if not vs or not vs.config then + return nil, Err.new(Err.UNSUPPORTED, "only Theora video can be written (no Theora encoder)") + end + local v = vs :: Source.Stream + local headers = Theora.splitConfig(v.config :: buffer) + local info = headers and Theora.info(headers[1]) + if not headers or not info then + return nil, Err.new(Err.CORRUPT, "Theora track without its three headers") + end + local fps = info.fpsNum / info.fpsDen + local scale = 2 ^ info.granuleShift + local bias = if info.versionMajor * 65536 + info.versionMinor * 256 + info.versionSub >= 0x030201 then 1 else 0 + -- video pages (serial 0x7468656F), granules from the frame numbers + local mux = Ogg.muxer({ pageSize = 4096 }) + local s = mux:stream(0x7468656F) + s:packet(headers[1], 0, { flush = true }) + s:packet(headers[2], 0) + s:packet(headers[3], 0, { flush = true }) + local key = 0 + local start = if #v.packets > 0 then v.packets[1].pts else 0 + for i, p in v.packets do + local frame = math.floor((p.pts - start) * fps + 0.5) + if buffer.len(p.data) > 0 and buffer.readu8(p.data, 0) // 64 == 0 then + key = frame + bias + end + s:packet(p.data, key * scale + (frame + bias - key), { eos = i == #v.packets }) + end + local video = mux:finish() + -- audio pages: the audio track as its own Ogg stream (containers/AudioWrap), interleaved by time + local audio: buffer? = nil + local arate, askip = 1, 0 + if as and o.audio ~= false then + local a = as :: Source.Stream + local track: any = { id = 1, kind = "audio", codec = a.codec, timescale = 1, config = a.config, sampleRate = a.sampleRate, channels = a.channels } + local shim = { + count = function(_: any, _t: number): number + return #a.packets + end, + get = function(_: any, _t: number, k: number): any + local p = a.packets[k] + return p and { track = 1, pts = p.pts, duration = p.duration, keyframe = true, data = p.data } + end, + } + local buf, _, aerr = AudioWrap.wrap(shim, track) + if not buf and o.audio == true then + return nil, aerr + end + audio = buf + if a.codec == "opus" then + arate = 48000 + local c = a.config + askip = if c and buffer.len(c) >= 12 then buffer.readu16(c, 10) else 0 + else + arate = a.sampleRate or 44100 + end + elseif o.audio == true and not as then + return nil, Err.new(Err.UNSUPPORTED, "the audio track is not Vorbis / Opus") + end + local vp = pages(video) + local ap = if audio then pages(audio) else {} + local out = Bytes.writer(buffer.len(video) + (if audio then buffer.len(audio) else 0)) + local function put(b: buffer, pg: { number }) + out:bytes(b, pg[1], pg[2]) + end + -- bos pages first (video, then audio), then the other header pages, then data by time + put(video, vp[1]) + if audio and ap[1] then + put(audio :: buffer, ap[1]) + end + local vi, ai = 2, 2 + local function headerPage(list: { { number } }, i: number): boolean + local pg = list[i] + return pg ~= nil and pg[3] == 0 + end + while headerPage(vp, vi) do + put(video, vp[vi]) + vi += 1 + end + while audio and headerPage(ap, ai) do + put(audio :: buffer, ap[ai]) + ai += 1 + end + local vt, at = 0, 0 + while vi <= #vp or ai <= #ap do + local nv, na = vp[vi], ap[ai] + if nv and nv[3] >= 0 then + vt = Theora.granuleFrame(info, nv[3]) / fps + end + if na and na[3] >= 0 then + at = (na[3] - askip) / arate + end + if nv and (not na or vt <= at) then + put(video, nv) + vi += 1 + else + put(audio :: buffer, na) + ai += 1 + end + end + return out:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- Xiph lacing of header packets (Matroska's CodecPrivate layout): count - 1, the sizes but the last, the packets +local function xiphLace(list: { buffer }): buffer + local w = Bytes.writer(64) + w:u8(#list - 1) + for i = 1, #list - 1 do + local n = buffer.len(list[i]) + while n >= 255 do + w:u8(255) + n -= 255 + end + w:u8(n) + end + for _, h in list do + w:bytes(h) + end + return w:finish() +end + +type Pending = { track: number, pts: number, key: boolean, page: number, data: buffer, off: number, len: number, own: boolean } + +-- demux(r, opts?) -> the Demuxer (containers/Demux) | nil, Err +function Ogv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local ogg, err = Ogg.open(r, { verify = not (opts and opts.verify == false) }) + if not ogg then + return nil, err + end + local src: buffer = ogg.buf + local tracks: { Types.Track } = {} + local all: { Pending } = {} + local meta: { [string]: any } = {} + local function add(track: number, pts: number, key: boolean, p: any) + table.insert(all, { + track = track, + pts = pts, + key = key, + page = p.pageOffset, + data = p.data, + off = p.offset, + len = p.size, + own = p.data ~= src, + }) + end + for _, st in ogg:streams() do + local codec = st.codec + if codec ~= "theora" and not AUDIO[codec] then + continue + end + local rd = ogg:reader(st.serial) + local headers: { buffer } = {} + local nh = if codec == "theora" or codec == "vorbis" then 3 elseif codec == "opus" then 2 else 1 + while #headers < nh do + local p = rd:nextPacket() + if not p then + break + end + table.insert(headers, Ogg.copy(p)) + if codec == "flac" and #headers == 1 and p.size >= 9 then + nh = 1 + buffer.readu16(p.data, p.offset + 7) // 256 + (buffer.readu16(p.data, p.offset + 7) % 256) * 256 + if nh > 64 then + nh = 1 + end + end + end + if #headers < nh then + continue + end + local id = #tracks + 1 + local track: any = { id = id, kind = "audio", codec = codec, codecTag = codec, timescale = 1, default = true, serial = st.serial } + if codec == "theora" then + local info = Theora.info(headers[1]) + if not info then + continue + end + track.kind = "video" + track.width, track.height = info.picWidth, info.picHeight + track.timescale = info.fpsNum + track.frameRate = info.fpsNum / info.fpsDen + track.config = xiphLace(headers) + local _, _, tags = Theora.comment(headers[2]) + meta.tags = tags + -- frame k of the stream: granule = keyframe << shift | frames since; bitstream 3.2.1 counts from 1 + local packets = {} + local base: number? = nil + while true do + local p = rd:nextPacket() + if not p then + break + end + if p.size > 0 and buffer.readu8(p.data, p.offset) >= 0x80 then + continue -- a stray header + end + table.insert(packets, p) + if base == nil and p.granule >= 0 then + base = Theora.granuleFrame(info, p.granule) - (#packets - 1) + end + end + local b0 = base or 0 + for k, p in packets do + local key = p.size > 0 and buffer.readu8(p.data, p.offset) // 64 == 0 + add(id, (b0 + k - 1) * info.fpsDen, key, p) + end + track.duration = (b0 + #packets) / track.frameRate + else + local h = headers[1] + local rate, channels, skip = 0, 0, 0 + if codec == "vorbis" and buffer.len(h) >= 16 then + channels, rate = buffer.readu8(h, 11), buffer.readu32(h, 12) + track.config = xiphLace(headers) + elseif codec == "opus" and buffer.len(h) >= 19 then + channels, rate, skip = buffer.readu8(h, 9), 48000, buffer.readu16(h, 10) + track.config = h + track.codecDelay = skip / 48000 + elseif codec == "flac" and buffer.len(h) >= 9 + 4 + 4 + 18 then + local o = 9 + 4 + 4 + 10 -- "fLaC", the block header, STREAMINFO's sample rate field + rate = buffer.readu8(h, o) * 4096 + buffer.readu8(h, o + 1) * 16 + buffer.readu8(h, o + 2) // 16 + channels = (buffer.readu8(h, o + 2) // 2) % 8 + 1 + local parts = { buffer.create(buffer.len(h) - 9) } + buffer.copy(parts[1], 0, h, 9) + for i = 2, #headers do + table.insert(parts, headers[i]) + end + local total = 0 + for _, x in parts do + total += buffer.len(x) + end + local cfg = buffer.create(total) + local o2 = 0 + for _, x in parts do + buffer.copy(cfg, o2, x) + o2 += buffer.len(x) + end + track.config = cfg + end + if rate <= 0 or channels <= 0 then + continue + end + track.sampleRate, track.channels, track.timescale = rate, channels, rate + local last = 0 + while true do + local p = rd:nextPacket() + if not p then + break + end + add(id, math.max(0, last - skip), true, p) + if p.granule >= 0 then + last = p.granule + end + end + track.duration = math.max(0, last - skip) / rate + end + table.insert(tracks, track) + end + if #tracks == 0 then + return nil, Err.new(Err.UNSUPPORTED, "no Theora / Vorbis / Opus / FLAC stream") + end + -- the index in file order (by the page each packet ends on) + local order = table.create(#all, 0) + for i = 1, #all do + order[i] = i + end + table.sort(order, function(a: number, c: number): boolean + local pa, pc = all[a].page, all[c].page + if pa ~= pc then + return pa < pc + end + return a < c + end) + local dmx = Demux.new("ogv", tracks, src, meta) + for _, i in order do + local e = all[i] + if e.own then + dmx:addData(e.track, e.pts, e.pts, nil, e.key, e.data) + else + dmx:add(e.track, e.pts, e.pts, nil, e.key, e.off, e.len) + end + end + dmx:finish() + return dmx, nil +end + +-- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err +function Ogv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local ok, dmx, err = pcall(Ogv.demux, r, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(dmx)) + end + if not dmx then + return nil, err + end + return Video.open(dmx, opts :: Video.OpenOptions?) +end + +return Ogv diff --git a/tests/video/ogv.luau b/tests/video/ogv.luau new file mode 100644 index 0000000..d1e0093 --- /dev/null +++ b/tests/video/ogv.luau @@ -0,0 +1,211 @@ +-- video/ogv tests: Ogg Theora files from ffmpeg (libtheora + libvorbis; tools/fixtures/theora.py): sniffing (Theora +-- BOS pages, plain Ogg Vorbis left to the audio formats), tracks, granule times, every frame through F.video.open +-- bit-exact with ffmpeg's (Adler-32 of yuv420p, its framecrc), an empty packet (a repeated frame), the Vorbis track +-- through the api's audio hook against ffmpeg's decode, tags, seeking, remuxing (ogv -> ogv, mkv -> ogv, ogv -> mkv) +-- read back, errors and the fuzz no-throw pass. +local T = require("@tests/T") +local C = require("@tests/video/_common") +local F = require("@formats") +local Ogv = require("@formats/video/ogv") +local Theora = require("@formats/codecs/video/Theora") +local AudioWrap = require("@formats/containers/AudioWrap") +local Bytes = require("@formats/core/Bytes") +local Base64 = require("@formats/core/Base64") +local Adler32 = require("@formats/core/Adler32") +local Err = require("@formats/core/Err") + +local t = T.suite("ogv") + +local AV = require("@tests/gen/theora_av") :: any +local Q0 = require("@tests/gen/theora_q0") :: any +local DUPE = require("@tests/gen/theora_dupe") :: any +local MKV = require("@tests/gen/theora_mkv") :: any +local OPUS = require("@tests/gen/theora_opus") :: any +local FLAC = require("@tests/gen/theora_flac") :: any + +local function file(fx: any): buffer + return Base64.decode(fx.file) :: buffer +end + +-- every frame of a VideoDecoder against ffmpeg's framecrc (yuv420p, keyed by frame number); frames ffmpeg does not +-- show (empty packets) must repeat the previous one +local function frames(v: any, fx: any, label: string, fps: number) + local want: { [number]: number } = {} + for _, f in fx.frames do + want[f[1]] = f[2] + end + local n, bad, shown, prev = 0, 0, 0, nil :: number? + while true do + local f, err = v:nextFrame() + if not f then + t:check(err == nil, label .. ": decode error " .. tostring(err)) + break + end + n += 1 + local c = Adler32.of(f.image.pixels, nil, nil, 0) + local w = want[math.floor(f.pts * fps + 0.5)] + if w then + shown += 1 + if c ~= w then + bad += 1 + end + elseif c ~= prev then + bad += 1 + end + prev = c + end + t:eq(bad, 0, label .. ": frames equal to ffmpeg's (" .. n .. " frames)") + t:eq(shown, #fx.frames, label .. ": every frame ffmpeg shows") + return n +end + +-- 1. contract and sniffing +t:eq(Ogv.name, "ogv", "name") +t:eq(Ogv.category, "video", "category") +t:check(table.find(Ogv.extensions, "ogv") ~= nil, "ogv extension") +t:eq(Ogv.sniff(Bytes.reader(file(AV))), 1, "sniff: Theora + Vorbis") +t:eq(Ogv.sniff(Bytes.reader(file(Q0))), 1, "sniff: Theora") +t:eq(Ogv.sniff(Bytes.reader(buffer.fromstring("OggS\0\2" .. string.rep("\0", 40)))), 0, "sniff: an Ogg page without Theora") +t:eq(Ogv.sniff(Bytes.reader(buffer.fromstring("RIFF"))), 0, "sniff: not Ogg") + +-- 2. Theora + Vorbis through the api +local v, err = F.video.open(file(AV)) +t:check(v ~= nil, "open: " .. tostring(err)) +if v then + t:eq(v.format, "ogv", "format") + t:eq(v.codec, "theora", "codec") + t:eq(v.width * 1000 + v.height, 160120, "size") + t:eq(v.frameRate, 25, "frame rate") + local dmx = v.demuxer :: any + t:eq(#dmx.tracks, 2, "two tracks") + local vt, at = dmx:track("video"), dmx:track("audio") + t:check(vt and vt.codec == "theora" and vt.timescale == 25, "video track") + t:check(at and at.codec == "vorbis" and at.sampleRate == 44100 and at.channels == 2, "audio track") + t:check(vt and vt.config and #(Theora.splitConfig(vt.config) or {}) == 3, "video config: three Xiph-laced headers") + t:check(math.abs(v.duration - 1) < 0.05, "duration " .. v.duration) + t:check(v.meta.tags and v.meta.tags.encoder ~= nil, "tags from the comment header") + local first = dmx:get(vt.id, 1) + t:check(first and first.keyframe and first.pts == 0, "first packet: a keyframe at 0") + t:check(not dmx:get(vt.id, 2).keyframe, "second packet: an inter frame") + frames(v, AV, "av", 25) + local pcm = Base64.decode(AV.pcm) :: buffer + C.audio(t, v, { pcm = buffer.tostring(pcm) }, "av", false, 20) + -- seeking + v:seek(0.5) + local f = v:nextFrame() + t:check(f ~= nil and f.pts >= 0.5 - 1e-6 and f.pts < 0.6, "seek 0.5 -> " .. tostring(f and f.pts)) + if f then + local want = nil + for _, w in AV.frames do + if w[1] == math.floor(f.pts * 25 + 0.5) then + want = w[2] + end + end + t:eq(Adler32.of(f.image.pixels, nil, nil, 0), want, "the frame after seeking equals ffmpeg's") + end + -- remux ogv -> ogv + v:reset() + local out, rerr = F.save(v, nil, { format = "ogv" }) + t:check(out ~= nil, "remux: " .. tostring(rerr)) + if out then + t:eq(Ogv.sniff(Bytes.reader(out)), 1, "remux: sniff") + local v2 = F.video.open(out) :: any + t:check(v2 ~= nil and #v2.demuxer.tracks == 2, "remux: two tracks") + if v2 then + frames(v2, AV, "remux", 25) + C.audio(t, v2, { pcm = buffer.tostring(pcm) }, "remux", false, 20) + end + end + -- remux ogv -> mkv (V_THEORA) + v:reset() + local mk, merr = F.save(v, nil, { format = "mkv" }) + t:check(mk ~= nil, "to mkv: " .. tostring(merr)) + if mk then + local v3 = F.video.open(mk) :: any + t:check(v3 ~= nil and v3.codec == "theora", "to mkv: Theora track") + if v3 then + frames(v3, AV, "to mkv", 25) + end + end +end + +-- 3. Opus and FLAC audio tracks (FLAC: exact) +for _, c in { { OPUS, "opus", 48000 }, { FLAC, "flac", 22050 } } do + local fx, codec, rate = c[1], c[2], c[3] + local vd, e = F.video.open(file(fx)) + t:check(vd ~= nil, codec .. ": open: " .. tostring(e)) + if vd then + local at = (vd.demuxer :: any):track("audio") + t:check(at and at.codec == codec and at.sampleRate == rate and at.channels == 1, codec .. ": audio track") + frames(vd, fx, codec, 25) + C.audio(t, vd, { pcm = buffer.tostring(Base64.decode(fx.pcm) :: buffer) }, codec, codec == "flac", 20) + if codec == "opus" then + vd:reset() + local out = F.save(vd, nil, { format = "ogv" }) + local v2 = out and F.video.open(out) :: any + t:check(v2 ~= nil and v2.audio ~= nil, "opus: remux keeps the audio") + if v2 then + C.audio(t, v2, { pcm = buffer.tostring(Base64.decode(fx.pcm) :: buffer) }, "opus remux", false, 20) + end + end + end +end + +-- 4. an empty packet: a repeated frame with its own time +do + local vd = Ogv.open(Bytes.reader(file(DUPE))) :: any + local n = 0 + local prev, dupAt = nil, nil + while true do + local f = vd:nextFrame() + if not f then + break + end + n += 1 + local c = Adler32.of(f.image.pixels, nil, nil, 0) + if n == 6 then + dupAt = f.pts + t:eq(c, prev, "dupe: frame 6 repeats frame 5") + end + prev = c + end + t:eq(n, #DUPE.frames + 1, "dupe: one frame per packet") + t:check(dupAt ~= nil and math.abs((dupAt :: number) - 0.2) < 1e-6, "dupe: its time slot (0.2 s)") + t:check(vd.audio == nil and vd.audioError == nil, "no audio track, no audio error") +end + +-- 5. Theora in Matroska -> ogv +do + local mv = F.video.open(file(MKV)) :: any + local out, e = F.save(mv, nil, { format = "ogv" }) + t:check(out ~= nil, "mkv -> ogv: " .. tostring(e)) + if out then + local v2 = Ogv.open(Bytes.reader(out)) :: any + frames(v2, MKV, "mkv -> ogv", 25) + end +end + +-- 6. not Theora: plain Ogg Vorbis goes to the audio format, writing other codecs fails +do + local vd = Ogv.open(Bytes.reader(file(AV))) :: any + local at = vd.demuxer:track("audio") + local ogg = AudioWrap.wrap(vd.demuxer, at) :: buffer + t:eq(Ogv.sniff(Bytes.reader(ogg)), 0, "sniff: Ogg Vorbis is not ogv") + local a = F.load(ogg, { name = "x.ogg" }) + t:check(a ~= nil and a.kind == "audio", "F.load of Ogg Vorbis named .ogg: audio") + local v4, e4 = Ogv.open(Bytes.reader(ogg)) + t:check(v4 ~= nil and v4.decodeError ~= nil, "an Ogg without video: opens, frames UNSUPPORTED (" .. tostring(e4) .. ")") + local _, ee = Ogv.encode(Ogv.open(Bytes.reader(ogg)) :: any) + t:check(ee ~= nil and ee.code == Err.UNSUPPORTED, "encode without Theora: UNSUPPORTED") + local _, eg = Ogv.open(Bytes.reader(buffer.fromstring("OggS garbage"))) + t:check(eg ~= nil, "garbage: an error") + local cut = buffer.create(5000) + buffer.copy(cut, 0, file(Q0), 0, 5000) + local vc = Ogv.open(Bytes.reader(cut)) + t:check(vc ~= nil, "a truncated file opens") +end + +-- 7. fuzz +t:fuzz("open", C.fuzzOpen(Ogv), { buffer.tostring(file(Q0)) }, { mutations = 16, garbage = 50 }) + +t:done() diff --git a/tools/fixtures/theora.py b/tools/fixtures/theora.py index 4395444..7d05299 100644 --- a/tools/fixtures/theora.py +++ b/tools/fixtures/theora.py @@ -8,6 +8,7 @@ # 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 { file (base64 .ogv, 320x240) } for tools/bench.luau import base64, os, shutil, struct, subprocess, tempfile, zlib @@ -184,6 +185,15 @@ def generate(ctx): 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]) From a1d2e7218cd88f1a04f4b63e37502789ccabfb02 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:24:29 -0500 Subject: [PATCH 08/27] video/fli: FLI / FLC / FLX animations (read) Header (FLI 1/70 s, FLC ms, depths 8 / 15 / 16 / 24), frame chunks into containers/Demux, open() through the registry's flic decoder (codecs/video/Legacy/Flic); the ring frame is dropped unless opts.ringFrame. Fixtures encoded by tools/fixtures/fli.py (every chunk type) with ffmpeg's decode as the reference: bit-exact. --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/video/fli/init.luau | 157 +++++++++++++ tests/video/fli.luau | 105 +++++++++ tools/fixtures/fli.py | 395 ++++++++++++++++++++++++++++++++ 5 files changed, 670 insertions(+) create mode 100644 src/Formats/video/fli/init.luau create mode 100644 tests/video/fli.luau create mode 100644 tools/fixtures/fli.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index b7c26a7..13d1e91 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -28,6 +28,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | audio | vorbis | .ogg .oga | yes | yes | streaming: true, seek: true, lossy: true, channels: 255 | `tests/audio/vorbis.luau` | | audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` | | video | avi | .avi | yes | yes | streaming: true, video: "mjpeg", "mpeg1", "rawvideo", audio: true, odml: true | `tests/video/avi.luau` | +| video | fli | .fli .flc .flx | yes | - | streaming: true, video: "flic", depths: 8, 15, 16, 24 | `tests/video/fli.luau` | | video | h264 | .h264 .264 .avc .jsv .26l .jvt | yes | yes | streaming: true, video: "h264", depths: 8 | `tests/video/h264.luau` | | video | mkv | .mkv .webm .mka .mk3d | yes | yes | streaming: true, remux: true, video: "vp8", "mjpeg", "mpeg1", "rawvideo", audio: true, subtitles: true | `tests/video/mkv.luau` | | video | mp4 | .mp4 .m4v .mov .qt .3gp .3g2 .mj2 | yes | yes | streaming: true, remux: true, video: "mjpeg", "mpeg1", "h264", audio: true, fragments: true | `tests/video/mp4.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 288846f..d26e1e1 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -290,6 +290,18 @@ local list: { Entry } = { return require("@formats/video/avi") end, }, + { + name = "fli", + category = "video", + path = "video/fli", + extensions = { "fli", "flc", "flx" }, + mime = { "video/x-fli", "video/fli", "video/x-flc" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "flic" }, depths = { 8, 15, 16, 24 } }, + load = function() + return require("@formats/video/fli") + end, + }, { name = "h264", category = "video", diff --git a/src/Formats/video/fli/init.luau b/src/Formats/video/fli/init.luau new file mode 100644 index 0000000..8224d48 --- /dev/null +++ b/src/Formats/video/fli/init.luau @@ -0,0 +1,157 @@ +--!strict +-- video/fli: Autodesk Animator FLI / Animator Pro FLC / FLX animations. New in formats-luau, written from the FLIC +-- file format description (Jim Kent, "FLC - Animator Pro Flic Files"; MultimediaWiki "FLIC"). +-- Read: the 128-byte header (FLI 0xAF11: speed in 1/70 s; FLC 0xAF12 / DTA 0xAF44: speed in ms; depth 8, 15, 16, 24: +-- an FLC that says 16 bits holds 5-5-5 pixels, as Animator Pro wrote them), prefix and other non-frame chunks skipped, +-- every frame chunk (0xF1FA, and 0xF5FA) a packet of a Demuxer; open() returns a VideoDecoder whose frames are rgba8 +-- (codecs/video/Legacy: palette chunks, BRUN, LC, SS2, BLACK, COPY, the deep-colour DTA chunks). The ring frame (the +-- extra frame after `frames` that leads back to the first) is not shown. Fli.demux(r) gives the Demuxer. +-- Not supported: writing, 1-bit FLICs, the X-COM / Magic Carpet game variants (audio chunks, 6-bit COLOR_256). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Demux = require("@formats/containers/Demux") +local Video = require("@formats/codecs/video/Video") + +-- ------------------------------------------------------------------------------------------------ contract +local Fli = { + name = "fli", + category = "video", + extensions = { "fli", "flc", "flx" }, + mime = { "video/x-fli", "video/fli", "video/x-flc" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "flic" }, depths = { 8, 15, 16, 24 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + rgba: boolean?, -- (frames are rgba8 already) + maxPixels: number?, -- default 2^26 + ringFrame: boolean?, -- true: also show the ring frame at the end (as ffmpeg does) +} + +-- ------------------------------------------------------------------------------------------------ constants +local HEADER = 128 +local FLI, FLC, DTA = 0xAF11, 0xAF12, 0xAF44 +local FRAME, FRAME2 = 0xF1FA, 0xF5FA + +-- ------------------------------------------------------------------------------------------------ sniff +function Fli.sniff(r: Bytes.Reader): number + local s = r:peek(18) + if #s < 18 then + return 0 + end + local magic = string.byte(s, 5) + string.byte(s, 6) * 256 + if magic ~= FLI and magic ~= FLC and magic ~= DTA then + return 0 + end + local w = string.byte(s, 9) + string.byte(s, 10) * 256 + local h = string.byte(s, 11) + string.byte(s, 12) * 256 + if w > 4096 or h > 4096 then + return 0 + end + return 0.9 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- demux(r, opts?) -> the Demuxer | nil, Err +function Fli.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + local n = limit - base + if n < HEADER then + return nil, Err.new(Err.TRUNCATED, "file shorter than the 128-byte header") + end + local hr = Bytes.reader(b, base, HEADER) + hr:skip(4) + local magic = hr:u16le() + local frames = hr:u16le() + local w, h = hr:u16le(), hr:u16le() + local depth = hr:u16le() + hr:skip(2) + local speed = hr:u32le() + if hr.err then + return nil, hr.err + end + if magic ~= FLI and magic ~= FLC and magic ~= DTA then + return nil, Err.new(Err.CORRUPT, string.format("bad magic 0x%04x", magic), 4) + end + if magic == FLI then + speed = speed % 65536 + end + if w == 0 or h == 0 then + return nil, Err.new(Err.CORRUPT, "no picture size") + end + local max = (opts and opts.maxPixels) or 2 ^ 26 + if w * h > max then + return nil, Err.new(Err.LIMIT, w .. " x " .. h .. " over maxPixels") + end + if magic == FLI or depth == 0 then + depth = 8 + elseif magic == FLC and depth == 16 then + depth = 15 -- Animator Pro's 16-bit FLCs hold 5-5-5 pixels + end + if speed == 0 then + speed = 5 + end + local scale = if magic == FLI then 70 else 1000 + local track: Types.Track = { + id = 1, + kind = "video", + codec = "flic", + codecTag = string.format("0x%04X", magic), + timescale = scale, + width = w, + height = h, + frameRate = scale / speed, + default = true, + bitsPerPixel = depth, + } + -- the frame chunks + local offs, sizes = {}, {} + local p = base + HEADER + while p + 6 <= limit do + local size = buffer.readu32(b, p) + local cm = buffer.readu16(b, p + 4) + if size < 6 then + break + end + if (cm == FRAME or cm == FRAME2) and size > 6 then + if p + size > limit then + break -- a truncated last frame + end + table.insert(offs, p) + table.insert(sizes, size) + end + p += size + end + local count = #offs + if frames > 0 and count > frames and not (opts and opts.ringFrame) then + count = frames -- the ring frame is not a frame of the animation + end + local dmx = Demux.new("fli", { track }, b, { + type = magic, + frames = frames, + depth = depth, + speed = speed, + ringFrame = #offs > frames and frames > 0, + }) + for i = 1, count do + dmx:add(1, (i - 1) * speed, nil, speed, i == 1, offs[i], sizes[i]) + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> a VideoDecoder | nil, Err +function Fli.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Fli.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts :: Video.OpenOptions?) +end + +return Fli diff --git a/tests/video/fli.luau b/tests/video/fli.luau new file mode 100644 index 0000000..b163dc9 --- /dev/null +++ b/tests/video/fli.luau @@ -0,0 +1,105 @@ +-- video/fli tests: FLI (COLOR_64, BRUN, LC, BLACK, COPY, PSTAMP, a ring frame), FLC (prefix chunk, COLOR_256, SS2 with +-- line skips and the last-byte opcode, an empty frame), an odd-size FLC, and 15 / 16 / 24-bit FLCs (BRUN, DTA_BRUN, +-- DELTA, DTA_LC, COPY, DTA_COPY, BLACK), all encoded by the fixture script: every frame equals ffmpeg's decode +-- (CRC-32 of rgba), frame rates, the ring frame option, seeking, errors, the fuzz pass. Fixtures: tools/fixtures/fli.py. +local T = require("@tests/T") +local F = require("@formats") +local Fli = require("@formats/video/fli") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/fli_cases") + +local t = T.suite("fli") +t:eq(Fli.name, "fli", "name") +t:eq(Fli.category, "video", "category") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end + +for _, c in Fx do + local label = c.name + t:check(Fli.sniff(reader(c.data)) > 0, label .. ": sniff") + t:eq(F.detect(buffer.fromstring(c.data)), "fli", label .. ": detect") + local v, err = F.video.open(buffer.fromstring(c.data)) + t:check(v ~= nil, label .. ": open " .. tostring(err)) + if v then + t:eq(v.codec, "flic", label .. ": codec") + t:check(v.width == c.width and v.height == c.height, label .. ": size") + t:check(math.abs(v.frameRate - c.rate) < 1e-9, label .. ": frame rate " .. v.frameRate) + t:eq(v.track.bitsPerPixel, c.depth, label .. ": depth") + local ring = v.demuxer.meta.ringFrame + local want = if ring then #c.frames - 1 else #c.frames + local n, bad = 0, 0 + while true do + local f, ferr = v:nextFrame() + if not f then + t:check(ferr == nil, label .. ": " .. tostring(ferr)) + break + end + n += 1 + if f.image.format ~= "rgba8" or Crc32.of(f.image.pixels) ~= c.frames[n] then + bad += 1 + end + end + t:check(n == want and bad == 0, string.format("%s: %d of %d frames equal ffmpeg's (%d differ)", label, n - bad, want, bad)) + v:seek(0.25) + local f = v:nextFrame() + local k = math.floor(0.25 * c.rate + 1 - 1e-9) + 1 + t:check(f ~= nil and Crc32.of(f.image.pixels) == c.frames[k], label .. ": seek to frame " .. k) + if ring then + local v2 = Fli.open(reader(c.data), { ringFrame = true }) + local m = 0 + while v2 and v2:nextFrame() do + m += 1 + end + t:eq(m, #c.frames, label .. ": with the ring frame") + end + end +end + +-- errors +do + local _, e = Fli.open(reader(string.sub(Fx[1].data, 1, 100))) + t:check(e ~= nil and e.code == Err.TRUNCATED, "short header: TRUNCATED") + local bad = Fx[1].data + bad = string.sub(bad, 1, 4) .. "\0\0" .. string.sub(bad, 7) + t:eq(Fli.sniff(reader(bad)), 0, "bad magic: no sniff") + local _, e2 = Fli.open(reader(bad)) + t:check(e2 ~= nil and e2.code == Err.CORRUPT, "bad magic: CORRUPT") + local big = string.sub(Fx[1].data, 1, 8) .. "\255\15\255\15" .. string.sub(Fx[1].data, 13) + local _, e3 = Fli.open(reader(big), { maxPixels = 2 ^ 20 }) + t:check(e3 ~= nil and e3.code == Err.LIMIT, "maxPixels: LIMIT") +end + +local samples = {} +for _, c in Fx do + table.insert(samples, c.data) +end +t:fuzz("open", function(b: buffer) + local v = Fli.open(Bytes.reader(b)) + if v then + while v:nextFrame() do + end + end + return v +end, samples, { mutations = 12, garbage = 40, keepHeader = 16 }) +-- the frame decoder itself (codecs/video/Legacy/Flic, native: no pcall in between) +local Flic = require("@formats/codecs/video/Legacy").Flic +for _, c in { Fx[1], Fx[2], Fx[4], Fx[6] } do + local d = Fli.demux(reader(c.data)) + local packets = {} + for k = 1, math.min(4, d:count(1)) do + table.insert(packets, d:get(1, k).data) + end + t:fuzz(c.name .. " frames", function(b: buffer) + local st = Flic.state(c.width, c.height, c.depth) + if st then + Flic.decode(st, b) + return Flic.image(st) + end + return nil + end, packets, { mutations = 20, garbage = 30 }) +end +t:done() diff --git a/tools/fixtures/fli.py b/tools/fixtures/fli.py new file mode 100644 index 0000000..0428f02 --- /dev/null +++ b/tools/fixtures/fli.py @@ -0,0 +1,395 @@ +# 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("= 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(" Date: Sat, 31 Oct 2026 14:25:41 -0500 Subject: [PATCH 09/27] ws-voxel: wip: codecs/model/Minecraft, model/schematic, Types.Voxels blocks / colors --- src/Formats/Types.luau | 12 + .../codecs/model/Minecraft/Colors.luau | 81 +++ .../codecs/model/Minecraft/Legacy.luau | 111 ++++ .../codecs/model/Minecraft/Packed.luau | 220 ++++++++ src/Formats/codecs/model/Minecraft/init.luau | 500 ++++++++++++++++++ src/Formats/model/schematic/Common.luau | 202 +++++++ src/Formats/model/schematic/Litematic.luau | 215 ++++++++ src/Formats/model/schematic/Mcedit.luau | 213 ++++++++ src/Formats/model/schematic/Sponge.luau | 131 +++++ src/Formats/model/schematic/init.luau | 309 +++++++++++ tools/fixtures/schematic.py | 243 +++++++++ 11 files changed, 2237 insertions(+) create mode 100644 src/Formats/codecs/model/Minecraft/Colors.luau create mode 100644 src/Formats/codecs/model/Minecraft/Legacy.luau create mode 100644 src/Formats/codecs/model/Minecraft/Packed.luau create mode 100644 src/Formats/codecs/model/Minecraft/init.luau create mode 100644 src/Formats/model/schematic/Common.luau create mode 100644 src/Formats/model/schematic/Litematic.luau create mode 100644 src/Formats/model/schematic/Mcedit.luau create mode 100644 src/Formats/model/schematic/Sponge.luau create mode 100644 src/Formats/model/schematic/init.luau create mode 100644 tools/fixtures/schematic.py diff --git a/src/Formats/Types.luau b/src/Formats/Types.luau index 63e3d79..55b983e 100644 --- a/src/Formats/Types.luau +++ b/src/Formats/Types.luau @@ -360,6 +360,18 @@ export type Voxels = { data: buffer, -- size x * y * z bytes, cell (x, y, z) at x + sx * (y + sy * z) palette: { { number } }, -- palette[i] = { r, g, b, a } 0..255 (sRGB) for i = 1 .. 255 (shared between a file's models) materials: { [number]: VoxelMaterial }?, -- by palette index + -- block grids (Minecraft schematics / regions): the exact block state of every cell, data / palette being its + -- colour view (block colours from a default table) + blocks: VoxelBlocks?, + -- true-colour grids (Qubicle): the exact 32-bit colour of every cell as r, g, b, a bytes (u32 little-endian, + -- a = 0 empty), data / palette being an indexed view of it + colors: buffer?, +} +export type VoxelBlocks = { + palette: { string }, -- block states ("minecraft:oak_stairs[facing=east,half=bottom]"), palette[1] is index 0 + data: buffer, -- u16 little-endian per cell (same cell order as Voxels.data): 0-based index into palette + blockEntities: { any }?, -- the format's block entity records (NBT compounds; positions relative to the grid) + entities: { any }?, -- entity records (NBT compounds) } local Voxels = {} -- new(sx, sy, sz, palette?) -> an empty grid (the palette defaults to grey ramps: callers set their own) diff --git a/src/Formats/codecs/model/Minecraft/Colors.luau b/src/Formats/codecs/model/Minecraft/Colors.luau new file mode 100644 index 0000000..1d66576 --- /dev/null +++ b/src/Formats/codecs/model/Minecraft/Colors.luau @@ -0,0 +1,81 @@ +--!strict +-- codecs/model/Minecraft/Colors: the built-in default colour of Minecraft blocks, for showing block grids as coloured +-- voxels. Hand-made for this library (approximate average colours picked by eye; no game assets or wiki tables were +-- copied): exact block names, then families by dye colour and wood type; codecs/model/Minecraft resolves stairs / +-- slabs / walls / ... to their base block and falls back to keywords. Format: name=rrggbb or name=rrggbbaa. +local Colors = {} + +Colors.BLOCKS = [[ +stone=7d7d7d granite=956756 polished_granite=9a6a59 diorite=bcbcbc polished_diorite=c0c0c2 andesite=888889 +polished_andesite=848686 grass_block=6d9a3f dirt=866043 coarse_dirt=77553b podzol=5b3f18 rooted_dirt=90674c +mud=3c3a3d cobblestone=7a7a7a bedrock=555555 sand=dbcf9f red_sand=be6621 gravel=837f7e suspicious_sand=d6c996 +suspicious_gravel=817c7b sandstone=d8cb9b chiseled_sandstone=d8ca9b cut_sandstone=d9cd9e smooth_sandstone=dfd5a5 +red_sandstone=b5621f cut_red_sandstone=bc6620 chiseled_red_sandstone=b7601e smooth_red_sandstone=b5621f +sponge=c3c04a wet_sponge=aaab3c glass=c0f5fe50 tinted_glass=2c262ec0 lapis_block=1f438c gold_block=f6d03d +iron_block=dcdcdc diamond_block=62ede4 emerald_block=2acb57 redstone_block=af1805 coal_block=101010 +netherite_block=433e40 copper_block=c06c50 exposed_copper=a17e68 weathered_copper=6c9a6f oxidized_copper=52a284 +cut_copper=bf6b51 raw_iron_block=a6896b raw_gold_block=dda92e raw_copper_block=9a6a4e amethyst_block=8562b8 +budding_amethyst=84609f bricks=976253 bookshelf=75603d chiseled_bookshelf=b29159 mossy_cobblestone=6e7660 +obsidian=0f0a18 crying_obsidian=200a3c tnt=db4130 spawner=24364a chest=a0742d trapped_chest=a0742d +ender_chest=2a3b3c crafting_table=81633c furnace=6d6d6d snow=f9fefe snow_block=f9fefe powder_snow=f8fdfd +ice=92b8fec8 packed_ice=8db4fa blue_ice=74a7fd frosted_ice=8cb4fac8 clay=a0a6b3 pumpkin=c6761a +carved_pumpkin=c27118 jack_o_lantern=d79a32 netherrack=612626 soul_sand=513e32 soul_soil=4b3a2e basalt=505055 +polished_basalt=636367 smooth_basalt=48484e glowstone=ab8354 magma_block=8e3f1f nether_bricks=2c1518 +red_nether_bricks=450709 cracked_nether_bricks=281417 chiseled_nether_bricks=2f171c nether_wart_block=720202 +warped_wart_block=167879 end_stone=dbdea0 end_stone_bricks=dae0a2 purpur_block=a97ea9 purpur_pillar=ab81ab +prismarine=63a29a prismarine_bricks=63ab9e dark_prismarine=335b4b sea_lantern=acc7be hay_block=a68b0c +terracotta=985e43 quartz_block=ebe5de smooth_quartz=ece6df quartz_bricks=eae5dd quartz_pillar=ebe6e0 +chiseled_quartz_block=e7e2da smooth_stone=9e9e9e stone_bricks=7a7979 mossy_stone_bricks=737969 +cracked_stone_bricks=767676 chiseled_stone_bricks=777777 deepslate=505053 cobbled_deepslate=4d4d51 +polished_deepslate=484849 deepslate_bricks=474747 cracked_deepslate_bricks=414141 deepslate_tiles=373737 +cracked_deepslate_tiles=343434 chiseled_deepslate=363637 reinforced_deepslate=505350 tuff=6c6d67 +polished_tuff=626a63 tuff_bricks=626660 calcite=dfe0dc dripstone_block=866b5c pointed_dripstone=816757 +moss_block=596d2d moss_carpet=596d2d pale_moss_block=6b7069 melon=6f9118 cactus=587f28 sugar_cane=95c165 +bamboo=5d8f1e bamboo_block=7f9030 stripped_bamboo_block=c0ad50 water=3f76e4b4 bubble_column=3f76e4b4 +lava=cf5b14 short_grass=5b8a32 grass=5b8a32 tall_grass=5b8a32 fern=586e30 large_fern=586e30 dead_bush=6b4f29 +vine=3c6e18 glow_lichen=708079 lily_pad=208030 seagrass=307b16 tall_seagrass=307b16 kelp=3b7f22 +kelp_plant=3b7f22 dried_kelp_block=323b27 red_mushroom_block=c82e2d brown_mushroom_block=957051 +mushroom_stem=cbc4b9 red_mushroom=d84a3e brown_mushroom=9a7759 slime_block=6fc05bc8 honey_block=fba92fc8 +honeycomb_block=e5941e bone_block=e1ddc9 shroomlight=f19346 target=e2aa9e respawn_anchor=4b1e86 +lodestone=939599 blackstone=2a2328 polished_blackstone=35303b polished_blackstone_bricks=302a32 +cracked_polished_blackstone_bricks=2c2629 chiseled_polished_blackstone=35303b gilded_blackstone=382b26 +crimson_nylium=831f1f warped_nylium=2b7265 crimson_roots=7e0812 warped_roots=148a7c packed_mud=8e6b50 +mud_bricks=89684f sculk=0d1e24 sculk_catalyst=2d3a3b sculk_sensor=074654 sculk_shrieker=c6cdab +redstone_lamp=5f361e note_block=58392a jukebox=5d4030 beacon=75dcd7 observer=626262 piston=9a8d6c +sticky_piston=8b9c66 piston_head=9a8d6c dispenser=7a7a7a dropper=7a7a7a hopper=434343 anvil=444444 +chipped_anvil=444444 damaged_anvil=444444 cauldron=4a4a4a rail=7d6c4b powered_rail=8a6d3e detector_rail=7b6853 +activator_rail=74574b ladder=7c5f35 scaffolding=aa8449 lantern=6a5b54 soul_lantern=4a6366 campfire=6e5638 +soul_campfire=4e5d5d barrel=86643b smoker=5a5853 blast_furnace=6c6b6b cartography_table=685032 +fletching_table=c5b485 smithing_table=39394a loom=8e7965 stonecutter=7b7672 grindstone=8e8e8e composter=704a26 +beehive=b8945b bee_nest=c5964b farmland=8f6646 dirt_path=94793f mycelium=6f6365 torch=ffd80060 +wall_torch=ffd80060 soul_torch=6be1e360 redstone_torch=c0210f60 redstone_wire=9e0b0060 lever=6e6e6e60 +cobweb=e4e9ea80 iron_bars=8b8d8b90 chain=3a404e90 end_rod=e0d8d0 chorus_plant=5e395e chorus_flower=977a97 +dragon_egg=0c0910 end_portal_frame=5b7860 enchanting_table=813838 brewing_stand=7a654f flower_pot=7d4536 +cake=f8dede conduit=9f8b71 lectern=ad8a54 bell=fdd533 decorated_pot=8f4f35 crafter=7a6c64 +trial_spawner=3b4a55 vault=46545c heavy_core=4c5056 command_block=b5886c chain_command_block=829f8f +repeating_command_block=8370b0 structure_block=58475b jigsaw=50455a +dandelion=e0c41c poppy=c42b1a blue_orchid=2aa8d0 allium=b878e8 azure_bluet=dfe6d7 red_tulip=c43b1b +orange_tulip=e07e1b white_tulip=e0e8db pink_tulip=e8b8d8 oxeye_daisy=e8e8c8 cornflower=4f76d8 +lily_of_the_valley=e8e8e8 wither_rose=2a2c18 sunflower=f0c71d lilac=b88cb8 rose_bush=b02a1e peony=e8b8e0 +torchflower=d9b14e pitcher_plant=7a97c8 pink_petals=f0b8d0 spore_blossom=d066a8 azalea=5f7a2c +flowering_azalea=7c6b6e sweet_berry_bush=3f6a2f cocoa=8c5428 wheat=a99c30 carrots=4a9a1e potatoes=4c9a2a +beetroots=5a8a2a nether_wart=8a1818 crimson_fungus=8a2525 warped_fungus=2a7a6e twisting_vines=148a7c +weeping_vines=8a1414 hanging_roots=a17561 big_dripleaf=6b8f34 small_dripleaf=6b8f34 cave_vines=5a6d23 +frogspawn=66605ca0 sniffer_egg=8a5045 turtle_egg=dcd8b8 sea_pickle=6a7030 mangrove_roots=4b3c27 +muddy_mangrove_roots=46413a ochre_froglight=f6e8a6 verdant_froglight=dcf0d6 pearlescent_froglight=f1e1ea +creaking_heart=5a4a3c resin_block=d9661c resin_bricks=ce5a1a +]] + +-- wool-like colour of each dye, then concrete and terracotta (same order as Colors.DYES) +Colors.DYES = { "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black" } +Colors.WOOL = "e9ecec f07613 bd44b3 3aafd9 f8c527 70b919 ed8dac 3e4447 8e8e86 158991 792aac 35399d 724728 546d1b a12722 141519" +Colors.CONCRETE = "cfd5d6 e06100 a9309f 2389c6 f0af15 5ea818 d5658e 36393d 7d7d73 157788 64209c 2c2e8f 603b1f 495b24 8e2020 080a0f" +Colors.TERRACOTTA = "d1b2a1 a15325 95576c 716c89 ba8523 677534 a14e4e 392a23 876a61 575b5b 764656 4a3b5b 4d3323 4c532a 8f3d2e 251610" + +-- wood types: planks, bark (log / wood), leaves +Colors.WOODS = { "oak", "spruce", "birch", "jungle", "acacia", "dark_oak", "mangrove", "cherry", "pale_oak", "bamboo", "crimson", "warped" } +Colors.PLANKS = "a2834f 735531 c0af79 a07351 a85a32 432b14 763631 e3b3ad e4d9d3 c1ad50 653147 2b6963" +Colors.BARK = "6d5533 3a2510 d8d7d2 55441a 676157 3e2f17 543a26 371b22 524a46 7f9030 5c1919 3a3a4d" +Colors.LEAVES = "4a7a20 3d5d3d 5f8a3c 3f8a1c 4b7a1e 3c6a18 4b8a28 e5adc2 878d76 5d8f1e 831f1f 2b7265" + +return Colors diff --git a/src/Formats/codecs/model/Minecraft/Legacy.luau b/src/Formats/codecs/model/Minecraft/Legacy.luau new file mode 100644 index 0000000..9d1348e --- /dev/null +++ b/src/Formats/codecs/model/Minecraft/Legacy.luau @@ -0,0 +1,111 @@ +--!strict +-- codecs/model/Minecraft/Legacy: numeric block ids of Minecraft before 1.13 (the .schematic format, Anvil chunks with +-- Blocks / Data arrays), from the Minecraft wiki "Java Edition data values/Pre-flattening" page (facts, not code): +-- the 1.12 name of every id, and how the data value picks a variant for the blocks whose colour or wood depends on it +-- (the modern name of that variant: wool 14 -> red_wool, planks 2 -> birch_planks). +local Legacy = {} + +local function words(s: string): { string } + local out = {} + for w in string.gmatch(s, "%S+") do + table.insert(out, w) + end + return out +end + +-- ids 0 .. 255 (NAMES[id + 1]), "-" = unused +Legacy.NAMES = words([[air stone grass dirt cobblestone planks sapling bedrock flowing_water water flowing_lava +lava sand gravel gold_ore iron_ore coal_ore log leaves sponge glass lapis_ore lapis_block dispenser sandstone noteblock +bed golden_rail detector_rail sticky_piston web tallgrass deadbush piston piston_head wool piston_extension +yellow_flower red_flower brown_mushroom red_mushroom gold_block iron_block double_stone_slab stone_slab brick_block tnt +bookshelf mossy_cobblestone obsidian torch fire mob_spawner oak_stairs chest redstone_wire diamond_ore diamond_block +crafting_table wheat farmland furnace lit_furnace standing_sign wooden_door ladder rail stone_stairs wall_sign lever +stone_pressure_plate iron_door wooden_pressure_plate redstone_ore lit_redstone_ore unlit_redstone_torch redstone_torch +stone_button snow_layer ice snow cactus clay reeds jukebox fence pumpkin netherrack soul_sand glowstone portal +lit_pumpkin cake unpowered_repeater powered_repeater stained_glass trapdoor monster_egg stonebrick +brown_mushroom_block red_mushroom_block iron_bars glass_pane melon_block pumpkin_stem melon_stem vine fence_gate +brick_stairs stone_brick_stairs mycelium waterlily nether_brick nether_brick_fence nether_brick_stairs nether_wart +enchanting_table brewing_stand cauldron end_portal end_portal_frame end_stone dragon_egg redstone_lamp +lit_redstone_lamp double_wooden_slab wooden_slab cocoa sandstone_stairs emerald_ore ender_chest tripwire_hook tripwire +emerald_block spruce_stairs birch_stairs jungle_stairs command_block beacon cobblestone_wall flower_pot carrots +potatoes wooden_button skull anvil trapped_chest light_weighted_pressure_plate heavy_weighted_pressure_plate +unpowered_comparator powered_comparator daylight_detector redstone_block quartz_ore hopper quartz_block quartz_stairs +activator_rail dropper stained_hardened_clay stained_glass_pane leaves2 log2 acacia_stairs dark_oak_stairs slime +barrier iron_trapdoor prismarine sea_lantern hay_block carpet hardened_clay coal_block packed_ice double_plant +standing_banner wall_banner daylight_detector_inverted red_sandstone red_sandstone_stairs double_stone_slab2 +stone_slab2 spruce_fence_gate birch_fence_gate jungle_fence_gate dark_oak_fence_gate acacia_fence_gate spruce_fence +birch_fence jungle_fence dark_oak_fence acacia_fence spruce_door birch_door jungle_door acacia_door dark_oak_door +end_rod chorus_plant chorus_flower purpur_block purpur_pillar purpur_stairs purpur_double_slab purpur_slab end_bricks +beetroots grass_path end_gateway repeating_command_block chain_command_block frosted_ice magma nether_wart_block +red_nether_brick bone_block structure_void observer white_shulker_box orange_shulker_box magenta_shulker_box +light_blue_shulker_box yellow_shulker_box lime_shulker_box pink_shulker_box gray_shulker_box silver_shulker_box +cyan_shulker_box purple_shulker_box blue_shulker_box brown_shulker_box green_shulker_box red_shulker_box +black_shulker_box white_glazed_terracotta orange_glazed_terracotta magenta_glazed_terracotta +light_blue_glazed_terracotta yellow_glazed_terracotta lime_glazed_terracotta pink_glazed_terracotta +gray_glazed_terracotta silver_glazed_terracotta cyan_glazed_terracotta purple_glazed_terracotta +blue_glazed_terracotta brown_glazed_terracotta green_glazed_terracotta red_glazed_terracotta black_glazed_terracotta +concrete concrete_powder - - structure_block]]) + +-- legacy names whose modern name differs (data value not involved; only one-to-one renames, so the way back is exact: +-- lit_furnace, powered_repeater, ... keep their legacy names) +Legacy.RENAMED = { + grass = "grass_block", brick_block = "bricks", stonebrick = "stone_bricks", hardened_clay = "terracotta", + melon_block = "melon", lit_pumpkin = "jack_o_lantern", slime = "slime_block", magma = "magma_block", + red_nether_brick = "red_nether_bricks", nether_brick = "nether_bricks", end_bricks = "end_stone_bricks", + mob_spawner = "spawner", web = "cobweb", snow_layer = "snow", snow = "snow_block", noteblock = "note_block", + quartz_ore = "nether_quartz_ore", reeds = "sugar_cane", waterlily = "lily_pad", flowing_water = "water", + flowing_lava = "lava", tallgrass = "short_grass", grass_path = "dirt_path", double_stone_slab = "smooth_stone", + stone_slab = "smooth_stone_slab", deadbush = "dead_bush", yellow_flower = "dandelion", + + fence = "oak_fence", fence_gate = "oak_fence_gate", + wooden_door = "oak_door", trapdoor = "oak_trapdoor", wooden_pressure_plate = "oak_pressure_plate", + wooden_button = "oak_button", stone_stairs = "cobblestone_stairs", standing_sign = "oak_sign", + wall_sign = "oak_wall_sign", golden_rail = "powered_rail", portal = "nether_portal", piston_extension = "moving_piston", + + silver_shulker_box = "light_gray_shulker_box", silver_glazed_terracotta = "light_gray_glazed_terracotta", + + monster_egg = "infested_stone", + standing_banner = "white_banner", wall_banner = "white_wall_banner", skull = "skeleton_skull", + bed = "red_bed", +} + +-- legacy names whose data value selects the variant: the modern names by data value (0-based) +local DYED = "white orange magenta light_blue yellow lime pink gray light_gray cyan purple blue brown green red black" +local function dyed(suffix: string): { string } + local out = {} + for i, d in words(DYED) do + out[i] = d .. "_" .. suffix + end + return out +end +Legacy.VARIANTS = { + stone = { "stone", "granite", "polished_granite", "diorite", "polished_diorite", "andesite", "polished_andesite" }, + dirt = { "dirt", "coarse_dirt", "podzol" }, + planks = { "oak_planks", "spruce_planks", "birch_planks", "jungle_planks", "acacia_planks", "dark_oak_planks" }, + wooden_slab = { "oak_slab", "spruce_slab", "birch_slab", "jungle_slab", "acacia_slab", "dark_oak_slab" }, + sapling = { "oak_sapling", "spruce_sapling", "birch_sapling", "jungle_sapling", "acacia_sapling", "dark_oak_sapling" }, + sand = { "sand", "red_sand" }, + log = { "oak_log", "spruce_log", "birch_log", "jungle_log" }, -- data % 4 + log2 = { "acacia_log", "dark_oak_log" }, + leaves = { "oak_leaves", "spruce_leaves", "birch_leaves", "jungle_leaves" }, + leaves2 = { "acacia_leaves", "dark_oak_leaves" }, + sponge = { "sponge", "wet_sponge" }, + sandstone = { "sandstone", "chiseled_sandstone", "cut_sandstone" }, + red_sandstone = { "red_sandstone", "chiseled_red_sandstone", "cut_red_sandstone" }, + stonebrick = { "stone_bricks", "mossy_stone_bricks", "cracked_stone_bricks", "chiseled_stone_bricks" }, + quartz_block = { "quartz_block", "chiseled_quartz_block", "quartz_pillar" }, + prismarine = { "prismarine", "prismarine_bricks", "dark_prismarine" }, + cobblestone_wall = { "cobblestone_wall", "mossy_cobblestone_wall" }, + red_flower = { "poppy", "blue_orchid", "allium", "azure_bluet", "red_tulip", "orange_tulip", "white_tulip", "pink_tulip", "oxeye_daisy" }, + double_plant = { "sunflower", "lilac", "tall_grass", "large_fern", "rose_bush", "peony" }, + wool = dyed("wool"), + carpet = dyed("carpet"), + stained_glass = dyed("stained_glass"), + stained_glass_pane = dyed("stained_glass_pane"), + stained_hardened_clay = dyed("terracotta"), + concrete = dyed("concrete"), + concrete_powder = dyed("concrete_powder"), +} +Legacy.MASK = { log = 4, log2 = 4, leaves = 4, leaves2 = 4, sapling = 8, wooden_slab = 8, quartz_block = 8, double_plant = 8 } + +return Legacy diff --git a/src/Formats/codecs/model/Minecraft/Packed.luau b/src/Formats/codecs/model/Minecraft/Packed.luau new file mode 100644 index 0000000..75cbf83 --- /dev/null +++ b/src/Formats/codecs/model/Minecraft/Packed.luau @@ -0,0 +1,220 @@ +--!strict +--!native +--!optimize 2 +-- codecs/model/Minecraft/Packed: Minecraft's packed index arrays. New code, from the Minecraft wiki "Chunk format" and +-- the Sponge / Litematica schematic specs: long arrays (little-endian int64s as codecs/text/Nbt keeps them) holding +-- bits-wide indices either spanning long boundaries (Litematica, chunks before 1.16) or not (chunks since 1.16: +-- floor(64 / bits) per long, the rest padding), and the varint byte arrays of Sponge schematics. Indices are written +-- to / read from u16 little-endian buffers. Every access is bounds-checked first; never throws. +local Packed = {} + +local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 +local writeu8, writeu16 = buffer.writeu8, buffer.writeu16 +local extract, band, rshift, lshift, bor = bit32.extract, bit32.band, bit32.rshift, bit32.lshift, bit32.bor + +-- longsNeeded(count, bits, spanning) -> the number of longs a packed array of count indices takes +function Packed.longsNeeded(count: number, bits: number, spanning: boolean): number + if spanning then + return (count * bits + 63) // 64 + end + local per = 64 // bits + return (count + per - 1) // per +end + +-- unpack(longs, bits, count, spanning, out, max) -> true | false, message: count indices into out (u16 LE, from byte +-- 0); an index >= max is an error. bits 1 .. 16. +function Packed.unpack(longs: buffer, bits: number, count: number, spanning: boolean, out: buffer, max: number): (boolean, string?) + if bits < 1 or bits > 16 then + return false, "unsupported: " .. bits .. "-bit packed indices" + end + local need = Packed.longsNeeded(count, bits, spanning) + if buffer.len(longs) < need * 8 then + return false, "packed array too short (" .. buffer.len(longs) // 8 .. " longs, need " .. need .. ")" + end + if buffer.len(out) < count * 2 then + return false, "output too small" + end + -- a copy with 4 bytes of padding, so every 32-bit read stays in range + local n = need * 8 + local src = buffer.create(n + 4) + buffer.copy(src, 0, longs, 0, n) + if spanning then + local p = 0 + for i = 0, count - 1 do + local v = extract(readu32(src, rshift(p, 3)), band(p, 7), bits) + if v >= max then + return false, "index " .. v .. " past the palette (" .. max .. ")" + end + writeu16(out, i * 2, v) + p += bits + end + else + local per = 64 // bits + local i = 0 + local base = 0 + while i < count do + local p = 0 + for _ = 1, per do + if i >= count then + break + end + local v = extract(readu32(src, base + rshift(p, 3)), band(p, 7), bits) + if v >= max then + return false, "index " .. v .. " past the palette (" .. max .. ")" + end + writeu16(out, i * 2, v) + i += 1 + p += bits + end + base += 8 + end + end + return true, nil +end + +-- pack(indices, count, bits, spanning) -> longs buffer (little-endian int64s): the inverse of unpack +function Packed.pack(indices: buffer, count: number, bits: number, spanning: boolean): buffer + local need = Packed.longsNeeded(count, bits, spanning) + local out = buffer.create(need * 8 + 4) + local per = 64 // bits + for i = 0, count - 1 do + local v = readu16(indices, i * 2) + local p = if spanning then i * bits else (i // per) * 64 + (i % per) * bits + local at = rshift(p, 3) + local sh = band(p, 7) + -- OR the value in byte by byte (up to 3 bytes for 16 bits at a shift of 7) + local x = lshift(v, sh) + for k = 0, 2 do + local bits8 = band(rshift(x, k * 8), 0xff) + if bits8 ~= 0 then + writeu8(out, at + k, bor(readu8(out, at + k), bits8)) + end + end + end + local res = buffer.create(need * 8) + buffer.copy(res, 0, out, 0, need * 8) + return res +end + +-- bitsFor(n, min) -> bits for indices 0 .. n - 1 (at least min) +function Packed.bitsFor(n: number, min: number): number + local b = min + while lshift(1, b) < n and b < 31 do + b += 1 + end + return b +end + +-- varints(src, offset, length, count, out, max) -> true | false, message: count unsigned LEB128 varints (Sponge +-- BlockData) into out (u16 LE) +function Packed.varints(src: buffer, offset: number, length: number, count: number, out: buffer, max: number): (boolean, string?) + if buffer.len(out) < count * 2 or offset + length > buffer.len(src) then + return false, "bad varint array arguments" + end + local p, e = offset, offset + length + for i = 0, count - 1 do + local v, sh = 0, 0 + while true do + if p >= e then + return false, "truncated: block data ends after " .. i .. " of " .. count .. " entries" + end + local c = readu8(src, p) + p += 1 + v += band(c, 0x7f) * 2 ^ sh + if c < 128 then + break + end + sh += 7 + if sh > 28 then + return false, "varint too long" + end + end + if v >= max then + return false, "index " .. v .. " past the palette (" .. max .. ")" + end + writeu16(out, i * 2, v) + end + return true, nil +end + +-- toVarints(indices, count) -> buffer: count u16 indices as unsigned LEB128 varints +function Packed.toVarints(indices: buffer, count: number): buffer + local out = buffer.create(count * 3) + local p = 0 + for i = 0, count - 1 do + local v = readu16(indices, i * 2) + while v >= 128 do + writeu8(out, p, band(v, 0x7f) + 128) + p += 1 + v = rshift(v, 7) + end + writeu8(out, p, v) + p += 1 + end + local res = buffer.create(p) + buffer.copy(res, 0, out, 0, p) + return res +end + +-- nibble(src, offset, i, highFirst) -> the 4-bit value i of a nibble array (Minecraft: low nibble first; WorldEdit's +-- AddBlocks: high nibble first) +function Packed.nibble(src: buffer, offset: number, i: number, highFirst: boolean): number + local b = readu8(src, offset + rshift(i, 1)) + local odd = band(i, 1) == 1 + if odd == highFirst then + return band(b, 15) + end + return rshift(b, 4) +end + +-- setNibble(dst, offset, i, v, highFirst) +function Packed.setNibble(dst: buffer, offset: number, i: number, v: number, highFirst: boolean) + local at = offset + rshift(i, 1) + local b = readu8(dst, at) + local odd = band(i, 1) == 1 + if odd == highFirst then + writeu8(dst, at, bor(band(b, 0xf0), band(v, 15))) + else + writeu8(dst, at, bor(band(b, 0x0f), lshift(band(v, 15), 4))) + end +end + +-- fromYzx(src, sx, sy, sz, dst?, ox?, oy?, oz?, dsx?, dsy?) -> dst: u16 cells in Minecraft's order (x fastest, then +-- z, then y: schematics, chunk sections) to Types.Voxels order (x, then y, then z), into dst (default a new +-- sx * sy * sz grid) at cell offset (ox, oy, oz) of a dsx * dsy * ... grid. The caller checks the ranges. +function Packed.fromYzx(src: buffer, sx: number, sy: number, sz: number, dst: buffer?, ox: number?, oy: number?, oz: number?, dsx: number?, dsy: number?): buffer + local out = dst or buffer.create(sx * sy * sz * 2) + local bx, by, bz = ox or 0, oy or 0, oz or 0 + local wx, wy = dsx or sx, dsy or sy + local i = 0 + for y = 0, sy - 1 do + for z = 0, sz - 1 do + local d = (bx + wx * ((by + y) + wy * (bz + z))) * 2 + for _ = 0, sx - 1 do + writeu16(out, d, readu16(src, i)) + i += 2 + d += 2 + end + end + end + return out +end + +-- toYzx(src, sx, sy, sz) -> buffer: Types.Voxels order to Minecraft's (the inverse of fromYzx) +function Packed.toYzx(src: buffer, sx: number, sy: number, sz: number): buffer + local out = buffer.create(sx * sy * sz * 2) + local i = 0 + for y = 0, sy - 1 do + for z = 0, sz - 1 do + local s = (sx * (y + sy * z)) * 2 + for _ = 0, sx - 1 do + writeu16(out, i, readu16(src, s)) + i += 2 + s += 2 + end + end + end + return out +end + +return Packed diff --git a/src/Formats/codecs/model/Minecraft/init.luau b/src/Formats/codecs/model/Minecraft/init.luau new file mode 100644 index 0000000..ded3ef3 --- /dev/null +++ b/src/Formats/codecs/model/Minecraft/init.luau @@ -0,0 +1,500 @@ +--!strict +-- codecs/model/Minecraft: what Minecraft's voxel formats share (model/schematic, model/mca). New code. +-- Block states ("minecraft:oak_stairs[facing=east,half=bottom]": parse / format / NBT compound form), the default +-- block colour table (codecs/model/Minecraft/Colors, hand-made) with fallbacks by family, the pre-1.13 numeric ids +-- (codecs/model/Minecraft/Legacy), packed index arrays (codecs/model/Minecraft/Packed), and the bridge between block +-- grids and Types.Voxels: voxels.blocks holds the exact states (u16 indices into a state palette), voxels.data / +-- palette their colours; writing a grid without blocks picks the block nearest in colour for each palette colour. +-- +-- local Mc = require("@formats/codecs/model/Minecraft") +-- local name, props = Mc.parseState("minecraft:oak_log[axis=y]") -- "minecraft:oak_log", { { "axis", "y" } } +-- local rgba = Mc.color("minecraft:red_wool") -- { r, g, b, a } | nil for air +-- local v = Mc.voxels(sx, sy, sz, states, indices) -- a Types.Voxels with .blocks +-- local states, indices = Mc.blocksOf(v) -- back (or chosen by colour) +local Types = require("@formats/Types") +local Nbt = require("@formats/codecs/text/Nbt") +local Colors = require("@formats/codecs/model/Minecraft/Colors") +local Legacy = require("@formats/codecs/model/Minecraft/Legacy") +local Packed = require("@formats/codecs/model/Minecraft/Packed") + +local Minecraft = {} + +Minecraft.Packed = Packed +Minecraft.Legacy = Legacy + +-- ------------------------------------------------------------------------------------------------ block states +-- parseState(s) -> name (namespace added when missing), props { { key, value } } in their order +function Minecraft.parseState(s: string): (string, { { string } }) + local name, rest = string.match(s, "^%s*([^%[%s]*)%s*(.*)$") + local n = name or "" + if n ~= "" and not string.find(n, ":", 1, true) then + n = "minecraft:" .. n + end + local props = {} + local body = rest and string.match(rest :: string, "^%[(.*)%]%s*$") + if body then + for pair in string.gmatch(body, "[^,]+") do + local k, v = string.match(pair, "^%s*([^=%s]+)%s*=%s*(.-)%s*$") + if k then + table.insert(props, { k, v :: string }) + end + end + end + return n, props +end + +-- stateString(name, props?) -> "name[k=v,...]" (props { { k, v } } in order, or a map: keys sorted) +function Minecraft.stateString(name: string, props: { any }?): string + if not props or next(props) == nil then + return name + end + local parts = {} + if props[1] ~= nil then + for _, kv in props do + table.insert(parts, kv[1] .. "=" .. tostring(kv[2])) + end + else + for _, k in Types.keys(props) do + table.insert(parts, tostring(k) .. "=" .. tostring((props :: any)[k])) + end + end + return name .. "[" .. table.concat(parts, ",") .. "]" +end + +-- stateFromNbt(compound) -> the state string of a palette entry { Name, Properties? } (litematic, chunk sections) +function Minecraft.stateFromNbt(c: any): string? + if type(c) ~= "table" or type(c.Name) ~= "string" then + return nil + end + local props = {} + if type(c.Properties) == "table" then + for _, k in Types.keys(c.Properties) do + local v = c.Properties[k] + table.insert(props, { k, if type(v) == "string" then v else tostring(Nbt.number(v) or v) }) + end + end + return Minecraft.stateString(c.Name, props) +end + +-- stateToNbt(state) -> { Name, Properties? } (a Types.object; Properties in the state's order) +function Minecraft.stateToNbt(s: string): { [string]: any } + local name, props = Minecraft.parseState(s) + local c = Types.object({ Name = name }, { "Name" }) + if #props > 0 then + local p, keys = {}, {} + for _, kv in props do + p[kv[1]] = kv[2] + table.insert(keys, kv[1]) + end + Types.set(c, "Properties", Types.object(p, keys)) + end + return c +end + +-- baseName(state) -> the name without namespace and properties ("minecraft:oak_log[axis=y]" -> "oak_log") +function Minecraft.baseName(s: string): string + local name = string.match(s, "^%s*([^%[%s]*)") or "" + return string.match(name, ":(.*)$") or name +end + +local AIR = { air = true, cave_air = true, void_air = true, structure_void = true, light = true, barrier = true, moving_piston = true } +-- isAir(state) -> true for blocks that are not drawn (air, cave_air, void_air, structure_void, light, barrier) +function Minecraft.isAir(s: string): boolean + return AIR[Minecraft.baseName(s)] == true +end + +-- ------------------------------------------------------------------------------------------------ colours +local function hex(h: string): { number } + local c = { tonumber(string.sub(h, 1, 2), 16) or 0, tonumber(string.sub(h, 3, 4), 16) or 0, tonumber(string.sub(h, 5, 6), 16) or 0, 255 } + if #h >= 8 then + c[4] = tonumber(string.sub(h, 7, 8), 16) or 255 + end + return c +end +local function list(s: string): { { number } } + local out = {} + for h in string.gmatch(s, "%x+") do + table.insert(out, hex(h)) + end + return out +end + +local EXACT: { [string]: { number } } = {} +for name, h in string.gmatch(Colors.BLOCKS, "([%w_]+)=(%x+)") do + EXACT[name] = hex(h) +end +local WOOL, CONCRETE, TERRACOTTA = list(Colors.WOOL), list(Colors.CONCRETE), list(Colors.TERRACOTTA) +local PLANKS, BARK, LEAVES = list(Colors.PLANKS), list(Colors.BARK), list(Colors.LEAVES) +-- longest prefixes first, so light_blue wins over blue and dark_oak over oak +local function byLength(names: { string }): { { any } } + local out = {} + for i, n in names do + table.insert(out, { n, i }) + end + table.sort(out, function(a, b) + return #a[1] > #b[1] + end) + return out +end +local DYES, WOODS = byLength(Colors.DYES), byLength(Colors.WOODS) +local SUFFIXES = { + "_wall_hanging_sign", "_hanging_sign", "_wall_sign", "_sign", "_fence_gate", "_fence", "_pressure_plate", "_button", + "_trapdoor", "_door", "_stairs", "_slab", "_wall", "_pane", "_carpet", "_wall_banner", "_banner", "_bars", +} +local PREFIXES = { "waxed_", "potted_", "infested_", "lit_", "unlit_", "unpowered_", "powered_", "chipped_", "damaged_" } +local CORAL = { tube = hex("3157d0"), brain = hex("cf5b9f"), bubble = hex("a118a0"), fire = hex("a6252f"), horn = hex("d8c53e") } +local FALLBACK = hex("909090") + +local function mix(c: { number }, w: { number }, t: number): { number } + return { math.floor(c[1] + (w[1] - c[1]) * t + 0.5), math.floor(c[2] + (w[2] - c[2]) * t + 0.5), math.floor(c[3] + (w[3] - c[3]) * t + 0.5), c[4] } +end + +local resolve: (string, number) -> { number }? + +local function family(n: string): { number }? + for _, d in DYES do + local pre = d[1] .. "_" + if string.sub(n, 1, #pre) == pre then + local rest = string.sub(n, #pre + 1) + local i = d[2] + if rest == "concrete" then + return CONCRETE[i] + elseif rest == "concrete_powder" then + return mix(CONCRETE[i], { 255, 255, 255, 255 }, 0.2) + elseif rest == "terracotta" then + return TERRACOTTA[i] + elseif string.find(rest, "glass", 1, true) then + local c = table.clone(WOOL[i]) + c[4] = 0x80 + return c + end + return WOOL[i] + end + end + local stripped = string.match(n, "^stripped_(.*)$") + for _, w in WOODS do + local pre = w[1] .. "_" + local m = stripped or n + if string.sub(m, 1, #pre) == pre then + local rest = string.sub(m, #pre + 1) + local i = w[2] + if stripped then + return PLANKS[i] + elseif rest == "log" or rest == "wood" or rest == "stem" or rest == "hyphae" then + return BARK[i] + elseif rest == "leaves" or rest == "sapling" or rest == "propagule" then + return LEAVES[i] + elseif rest == "block" and w[1] == "bamboo" then + return EXACT.bamboo_block + end + return PLANKS[i] + end + end + return nil +end + +local function keywords(n: string): { number }? + if string.find(n, "copper", 1, true) then + return if string.find(n, "oxidized", 1, true) then EXACT.oxidized_copper + elseif string.find(n, "weathered", 1, true) then EXACT.weathered_copper + elseif string.find(n, "exposed", 1, true) then EXACT.exposed_copper + else EXACT.copper_block + elseif string.find(n, "coral", 1, true) then + if string.find(n, "dead", 1, true) then + return hex("857e79") + end + for k, c in CORAL do + if string.find(n, k, 1, true) then + return c + end + end + elseif string.find(n, "_ore$") then + return if string.find(n, "deepslate", 1, true) then EXACT.deepslate + elseif string.find(n, "nether", 1, true) then EXACT.netherrack + else EXACT.stone + end + for _, k in { "deepslate", "blackstone", "sandstone", "prismarine", "purpur", "quartz", "glass", "ice", "stone", "brick", "nether", "end", "mushroom", "grass", "candle", "head", "skull", "rail", "sign", "tulip", "orchid" } do + if string.find(n, k, 1, true) then + local alias = ({ glass = "glass", ice = "ice", stone = "stone", brick = "bricks", nether = "nether_bricks", ["end"] = "end_stone", mushroom = "mushroom_stem", grass = "short_grass", candle = "white_wool", head = "polished_andesite", skull = "bone_block", rail = "rail", sign = "oak_planks", tulip = "red_tulip", orchid = "blue_orchid", deepslate = "deepslate", blackstone = "blackstone", sandstone = "sandstone", prismarine = "prismarine", purpur = "purpur_block", quartz = "quartz_block" } :: any)[k] + return EXACT[alias] + end + end + return nil +end + +resolve = function(n: string, depth: number): { number }? + if depth > 4 then + return nil + end + local c = EXACT[n] + if c then + return c + end + local renamed = Legacy.RENAMED[n] + if renamed then + return resolve(renamed, depth + 1) + end + for _, p in PREFIXES do + if string.sub(n, 1, #p) == p then + return resolve(string.sub(n, #p + 1), depth + 1) + end + end + c = family(n) + if c then + return c + end + for _, sfx in SUFFIXES do + if #n > #sfx and string.sub(n, -#sfx) == sfx then + local base = string.sub(n, 1, #n - #sfx) + for _, form in { base, base .. "s", base .. "_block", base .. "_planks" } do + local fc = EXACT[form] or family(form) + if fc then + return fc + end + end + return resolve(base, depth + 1) + end + end + return keywords(n) +end + +local cache: { [string]: { number } | false } = {} +-- color(state) -> { r, g, b, a } (0..255) | nil for air-like blocks: the default colour table, families, keywords +function Minecraft.color(s: string): { number }? + local hit = cache[s] + if hit ~= nil then + return hit or nil + end + local name, props = Minecraft.parseState(s) + local n = string.match(name, ":(.*)$") or name + local res: { number }? = nil + if not AIR[n] then + -- pre-1.13 names whose data value picks the variant + local variants = Legacy.VARIANTS[n] or (if n == "double_wooden_slab" then Legacy.VARIANTS.planks else nil) + if variants then + local data = 0 + for _, kv in props do + if kv[1] == "data" then + data = tonumber(kv[2]) or 0 + end + end + local v = variants[data % (Legacy.MASK[n] or 16) + 1] or variants[1] + res = resolve(v, 0) + end + res = res or resolve(n, 0) or FALLBACK + end + cache[s] = res or false + return res +end + +-- ------------------------------------------------------------------------------------------------ legacy ids +local REVERSE: { [string]: { number } }? = nil +local function reverse(): { [string]: { number } } + if REVERSE then + return REVERSE + end + local r: { [string]: { number } } = {} + local byName: { [string]: number } = {} + for i, n in Legacy.NAMES do + if n ~= "-" then + byName[n] = i - 1 + end + end + for legacy, modern in Legacy.RENAMED do + r[modern] = { byName[legacy], 0 } + end + for legacy, variants in Legacy.VARIANTS do + for d, v in variants do + if r[v] == nil then + r[v] = { byName[legacy], d - 1 } + end + end + end + for n, id in byName do + if r[n] == nil then + r[n] = { id, 0 } + end + end + REVERSE = r + return r +end + +-- legacyState(id, data) -> the state string for a pre-1.13 block (variant names where the data value picks one, the +-- rest of the data value kept as [data=N] so legacyId gives it back exactly) +function Minecraft.legacyState(id: number, data: number): string + local n = Legacy.NAMES[id + 1] + if n == nil or n == "-" then + return "minecraft:legacy_" .. id .. (if data ~= 0 then "[data=" .. data .. "]" else "") + end + local variants = Legacy.VARIANTS[n] + if variants then + local idx = data % (Legacy.MASK[n] or 16) + local v = variants[idx + 1] + if v then + return "minecraft:" .. v .. (if data ~= idx then "[data=" .. data .. "]" else "") + end + end + return "minecraft:" .. (Legacy.RENAMED[n] or n) .. (if data ~= 0 then "[data=" .. data .. "]" else "") +end + +-- legacyId(state) -> id, data | nil: the inverse of legacyState (modern names that exist before 1.13 too; their +-- properties are not converted to data values) +function Minecraft.legacyId(s: string): (number?, number?) + local name, props = Minecraft.parseState(s) + local n = string.match(name, ":(.*)$") or name + local id: number?, data = nil, 0 + local lid = string.match(n, "^legacy_(%d+)$") + if lid then + id = tonumber(lid) + else + local e = reverse()[n] + if e then + id, data = e[1], e[2] + end + end + if id == nil then + return nil, nil + end + for _, kv in props do + if kv[1] == "data" then + data = (tonumber(kv[2]) or data) % 16 + end + end + return id, data +end + +-- ------------------------------------------------------------------------------------------------ voxels +-- voxels(sx, sy, sz, states, indices, opts?) -> Types.Voxels: indices (u16 LE per cell in Voxels order: x fastest, +-- then y, then z) into states; data / palette from the block colours (air -> 0; up to 255 colours, more merge into +-- the nearest one) +function Minecraft.voxels(sx: number, sy: number, sz: number, states: { string }, indices: buffer): Types.Voxels + local v = Types.Voxels.new(sx, sy, sz) + local lut = buffer.create(#states) + local slots: { [string]: number } = {} + local used = 0 + for i, s in states do + local c = Minecraft.color(s) + local slot = 0 + if c then + local key = string.format("%d,%d,%d,%d", c[1], c[2], c[3], c[4]) + slot = slots[key] + if not slot then + if used < 255 then + used += 1 + slot = used + v.palette[slot] = { c[1], c[2], c[3], c[4] } + else + local best, bd = 1, math.huge + for k = 1, 255 do + local p = v.palette[k] + local d = (p[1] - c[1]) ^ 2 + (p[2] - c[2]) ^ 2 + (p[3] - c[3]) ^ 2 + (p[4] - c[4]) ^ 2 + if d < bd then + best, bd = k, d + end + end + slot = best + end + slots[key] = slot + end + end + buffer.writeu8(lut, i - 1, slot) + end + local n = sx * sy * sz + local data, nstates = v.data, #states + for i = 0, n - 1 do + local s = buffer.readu16(indices, i * 2) + buffer.writeu8(data, i, if s < nstates then buffer.readu8(lut, s) else 0) + end + v.blocks = { palette = states, data = indices } + return v +end + +-- the blocks a colour grid is written with: full blocks of distinct colours (and stained glass for translucent ones) +local CANDIDATES: { { any } }? = nil +local function candidates(): { { any } } + if CANDIDATES then + return CANDIDATES + end + local out = {} + for _, d in Colors.DYES do + for _, kind in { "wool", "concrete", "terracotta" } do + local s = "minecraft:" .. d .. "_" .. kind + table.insert(out, { s, Minecraft.color(s) }) + end + end + for _, w in Colors.WOODS do + local s = "minecraft:" .. w .. "_planks" + table.insert(out, { s, Minecraft.color(s) }) + end + for _, n in { "stone", "cobblestone", "bricks", "sand", "red_sand", "dirt", "grass_block", "gravel", "deepslate", "sandstone", "quartz_block", "obsidian", "netherrack", "end_stone", "prismarine", "dark_prismarine", "snow_block", "gold_block", "iron_block", "diamond_block", "emerald_block", "lapis_block", "redstone_block", "coal_block", "glowstone", "sponge", "melon", "pumpkin", "hay_block", "bone_block", "clay", "packed_ice", "nether_bricks", "purpur_block", "andesite", "diorite", "granite", "calcite", "tuff", "blackstone", "mud", "moss_block", "amethyst_block", "copper_block", "oxidized_copper" } do + local s = "minecraft:" .. n + table.insert(out, { s, Minecraft.color(s) }) + end + CANDIDATES = out + return out +end + +-- nearestBlock(rgba) -> the block state whose default colour is nearest (translucent colours -> stained glass) +function Minecraft.nearestBlock(c: { number }): string + local a = c[4] or 255 + if a < 200 then + local best, bd = "minecraft:glass", math.huge + for i, d in Colors.DYES do + local w = WOOL[i] + local dist = (w[1] - c[1]) ^ 2 + (w[2] - c[2]) ^ 2 + (w[3] - c[3]) ^ 2 + if dist < bd then + best, bd = "minecraft:" .. d .. "_stained_glass", dist + end + end + return best + end + local best, bd = "minecraft:stone", math.huge + for _, cand in candidates() do + local k = cand[2] + local dist = (k[1] - c[1]) ^ 2 + (k[2] - c[2]) ^ 2 + (k[3] - c[3]) ^ 2 + if dist < bd then + best, bd = cand[1], dist + end + end + return best +end + +-- blocksOf(voxels) -> states, indices (u16 LE per cell): voxels.blocks when present (checked), else a block per +-- palette colour (nearestBlock; cell 0 -> "minecraft:air" at index 0) | nil, message +function Minecraft.blocksOf(v: Types.Voxels): ({ string }?, any) + local n = v.size[1] * v.size[2] * v.size[3] + local b = v.blocks + if b then + if type(b.palette) ~= "table" or type(b.data) ~= "buffer" or buffer.len(b.data) < n * 2 then + return nil, "voxels.blocks must hold a palette and a u16 per cell" + end + if #b.palette == 0 or #b.palette > 65536 then + return nil, "voxels.blocks.palette must have 1 .. 65536 states" + end + return b.palette, b.data + end + local states = { "minecraft:air" } + local slotOf: { [number]: number } = { [0] = 0 } + local byState: { [string]: number } = { ["minecraft:air"] = 0 } + local out = buffer.create(n * 2) + local data = v.data + for i = 0, n - 1 do + local p = buffer.readu8(data, i) + local s = slotOf[p] + if s == nil then + local col = v.palette[p] or { 128, 128, 128, 255 } + local st = Minecraft.nearestBlock(col) + s = byState[st] + if s == nil then + table.insert(states, st) + s = #states - 1 + byState[st] = s + end + slotOf[p] = s + end + buffer.writeu16(out, i * 2, s :: number) + end + return states, out +end + +return Minecraft diff --git a/src/Formats/model/schematic/Common.luau b/src/Formats/model/schematic/Common.luau new file mode 100644 index 0000000..e9f49c5 --- /dev/null +++ b/src/Formats/model/schematic/Common.luau @@ -0,0 +1,202 @@ +--!strict +-- model/schematic/Common: what the three schematic flavours share: the region record they read into and write from, +-- NBT field access with type checks, and block entities in one shape ({ pos = { x, y, z }, id, data }: Sponge v3's, +-- converted from / to MCEdit's and Litematica's flat { x, y, z, id, ... } and Sponge v2's { Pos, Id, ... }). +local Types = require("@formats/Types") +local Nbt = require("@formats/codecs/text/Nbt") + +local Common = {} + +-- a block region: indices are u16 per cell in Types.Voxels order (x fastest, then y, then z) into states +export type Region = { + name: string?, + size: { number }, -- x, y, z cells + position: { number }, -- the minimum corner relative to the schematic origin + states: { string }, + indices: buffer, + blockEntities: { any }, + entities: { any }, +} + +-- int(v) -> the integer value of an NBT number (byte / short / int / long tag or plain number) | nil +function Common.int(v: any): number? + local n = Nbt.number(v) + if n == nil or n ~= n or n % 1 ~= 0 then + return nil + end + return n +end + +-- dims(a, b, c, max) -> sx, sy, sz | nil, message: positive sizes whose product stays under max cells +function Common.dims(a: any, b: any, c: any, max: number): (number?, any, number?) + local x, y, z = Common.int(a), Common.int(b), Common.int(c) + if not x or not y or not z then + return nil, "missing or non-integer size", nil + end + if x < 0 or y < 0 or z < 0 then + return nil, "negative size", nil + end + if x * y * z > max then + return nil, "limit: " .. x .. " x " .. y .. " x " .. z .. " cells is over maxCells", nil + end + return x, y, z +end + +-- ints(v) -> the numbers of an intArray tag or a list of numbers | nil +function Common.ints(v: any): { number }? + if Nbt.isTag(v) and v.type == "intArray" then + return v.value + elseif type(v) == "table" and not Nbt.isTag(v) and v[1] ~= nil then + local out = {} + for i, x in v do + out[i] = Nbt.number(x) or 0 + end + return out + end + return nil +end + +local function rest(c: any, skip: { [string]: boolean }): { [string]: any } + local out, keys = {}, {} + for _, k in Types.keys(c) do + if not skip[k] then + out[k] = c[k] + table.insert(keys, k) + end + end + return Types.object(out, keys) +end + +local FLAT_SKIP = { x = true, y = true, z = true, id = true } +local POS_SKIP = { Pos = true, Id = true } + +-- blockEntity(c, style) -> the common shape of one record: style "flat" (MCEdit, Litematica), "pos" (Sponge v1 / v2), +-- "data" (Sponge v3) +function Common.blockEntity(c: any, style: string): any + if type(c) ~= "table" or Nbt.isTag(c) then + return nil + end + if style == "flat" then + return { pos = { Common.int(c.x) or 0, Common.int(c.y) or 0, Common.int(c.z) or 0 }, id = if type(c.id) == "string" then c.id else nil, data = rest(c, FLAT_SKIP) } + end + local p = Common.ints(c.Pos) or { 0, 0, 0 } + local data = if style == "data" then (if type(c.Data) == "table" then c.Data else Types.object()) else rest(c, POS_SKIP) + return { pos = { p[1] or 0, p[2] or 0, p[3] or 0 }, id = if type(c.Id) == "string" then c.Id else nil, data = data } +end + +-- flatBlockEntity(be, style) -> the record in a flavour's shape (the inverse of blockEntity) +function Common.flatBlockEntity(be: any, style: string): any + local o = Types.object() + local data = if type(be.data) == "table" then be.data else Types.object() + if style == "flat" then + Types.set(o, "x", be.pos[1]) + Types.set(o, "y", be.pos[2]) + Types.set(o, "z", be.pos[3]) + if be.id then + Types.set(o, "id", be.id) + end + for _, k in Types.keys(data) do + if not FLAT_SKIP[k] then + Types.set(o, k, data[k]) + end + end + return o + end + Types.set(o, "Pos", Nbt.intArray({ be.pos[1], be.pos[2], be.pos[3] })) + if be.id then + Types.set(o, "Id", be.id) + end + if style == "data" then + Types.set(o, "Data", data) + else + for _, k in Types.keys(data) do + if not POS_SKIP[k] then + Types.set(o, k, data[k]) + end + end + end + return o +end + +-- list(v) -> v when it is an NBT list (array), else an empty list +function Common.list(v: any): { any } + if type(v) == "table" and not Nbt.isTag(v) and not Types.isObject(v) then + return v + end + return {} +end + +-- compound({ { key, value } }) -> a Types.object with these keys in this order (nil values skipped) +function Common.compound(fields: { { any } }): { [string]: any } + local o, keys = {}, {} + for _, kv in fields do + if kv[2] ~= nil then + o[kv[1]] = kv[2] + table.insert(keys, kv[1]) + end + end + return Types.object(o, keys) +end + +-- merge(base, fields, drop?) -> a compound of fields ({ { key, value } }, nil values left out) laid out in base's key +-- order (a decoded source compound: its other keys are kept, except those in drop), new keys after +function Common.merge(base: any, fields: { { any } }, drop: { [string]: boolean }?): { [string]: any } + if type(base) ~= "table" or not Types.isObject(base) then + return Common.compound(fields) + end + local mine: { [string]: any } = {} + local present: { [string]: boolean } = {} + for _, kv in fields do + present[kv[1]] = true + mine[kv[1]] = kv[2] + end + local out = {} + for _, k in Types.keys(base) do + if present[k] then + if mine[k] ~= nil then + table.insert(out, { k, mine[k] }) + end + elseif not (drop and drop[k]) then + table.insert(out, { k, base[k] }) + end + end + local seen: { [string]: boolean } = {} + for _, kv in out do + seen[kv[1]] = true + end + for _, kv in fields do + if not seen[kv[1]] and kv[2] ~= nil then + table.insert(out, kv) + end + end + return Common.compound(out) +end + +-- dedupe(states, indices, n) -> states, indices with every state once (indices remapped when needed) +function Common.dedupe(states: { string }, indices: buffer, n: number): ({ string }, buffer) + local first: { [string]: number } = {} + local remap: { number } = {} + local out: { string } = {} + local dup = false + for i, s in states do + local at = first[s] + if at == nil then + table.insert(out, s) + at = #out - 1 + first[s] = at + else + dup = true + end + remap[i] = at + end + if not dup then + return states, indices + end + local res = buffer.create(n * 2) + for i = 0, n - 1 do + buffer.writeu16(res, i * 2, remap[buffer.readu16(indices, i * 2) + 1] or 0) + end + return out, res +end + +return Common diff --git a/src/Formats/model/schematic/Litematic.luau b/src/Formats/model/schematic/Litematic.luau new file mode 100644 index 0000000..f4ea4c5 --- /dev/null +++ b/src/Formats/model/schematic/Litematic.luau @@ -0,0 +1,215 @@ +--!strict +-- model/schematic/Litematic: Litematica's .litematic, from the mod's sources (LitematicaSchematic, +-- LitematicaBitArray) as documented by the litemapy project: Metadata (name, author, description, enclosing size, +-- counts, times, preview), several named Regions with a Position and a Size that may be negative, a block-state +-- palette (index 0 = air) and BlockStates packed spanning long boundaries (at least 2 bits), TileEntities (relative +-- to the region's minimum corner), Entities and pending ticks (kept as they are). +local Types = require("@formats/Types") +local Nbt = require("@formats/codecs/text/Nbt") +local Mc = require("@formats/codecs/model/Minecraft") +local Common = require("@formats/model/schematic/Common") + +local Litematic = {} + +local Packed = Mc.Packed + +local function xyz(c: any): { number }? + if type(c) ~= "table" then + return nil + end + local x, y, z = Common.int(c.x), Common.int(c.y), Common.int(c.z) + if not x or not y or not z then + return nil + end + return { x, y, z } +end + +local function vec(v: { number }): any + return Common.compound({ { "x", v[1] }, { "y", v[2] }, { "z", v[3] } }) +end + +-- read(root, maxCells) -> { Region }, extra | nil, message +function Litematic.read(root: any, maxCells: number): ({ Common.Region }?, any) + if not Types.isObject(root.Regions) then + return nil, "no Regions" + end + local out: { Common.Region } = {} + local total = 0 + local raw: { [string]: any } = {} + for _, name in Types.keys(root.Regions) do + local reg = root.Regions[name] + if type(reg) ~= "table" then + return nil, "region " .. name .. " is not a compound" + end + local pos, size = xyz(reg.Position), xyz(reg.Size) + if not pos or not size then + return nil, "region " .. name .. ": no Position / Size" + end + local ax, ay, az = math.abs(size[1]), math.abs(size[2]), math.abs(size[3]) + local sx, sy, sz = Common.dims(ax, ay, az, maxCells - total) + if not sx then + return nil, "region " .. name .. ": " .. tostring(sy) + end + total += ax * ay * az + local states: { string } = {} + for i, c in Common.list(reg.BlockStatePalette) do + local st = Mc.stateFromNbt(c) + if not st then + return nil, "region " .. name .. ": bad palette entry " .. i + end + states[i] = st + end + if #states == 0 then + states[1] = "minecraft:air" + end + local n = ax * ay * az + local yzx = buffer.create(n * 2) + local bs = reg.BlockStates + if n > 0 then + if not (Nbt.isTag(bs) and bs.type == "longArray") then + return nil, "region " .. name .. ": no BlockStates" + end + local bits = Packed.bitsFor(#states, 2) + local ok, e = Packed.unpack(bs.value, bits, n, true, yzx, #states) + if not ok then + return nil, "region " .. name .. ": " .. tostring(e) + end + end + local bes = {} + for _, c in Common.list(reg.TileEntities) do + local be = Common.blockEntity(c, "flat") + if be then + table.insert(bes, be) + end + end + table.insert(out, { + name = name, + size = { ax, ay, az }, + position = { + pos[1] + (if size[1] < 0 then size[1] + 1 else 0), + pos[2] + (if size[2] < 0 then size[2] + 1 else 0), + pos[3] + (if size[3] < 0 then size[3] + 1 else 0), + }, + states = states, + indices = Packed.fromYzx(yzx, ax, ay, az), + blockEntities = bes, + entities = Common.list(reg.Entities), + }) + raw[name] = reg + end + return out, { + version = Common.int(root.Version), + subVersion = Common.int(root.SubVersion), + dataVersion = Common.int(root.MinecraftDataVersion), + metadata = root.Metadata, + regions = raw, + } +end + +-- write(regions, version, dataVersion, base?, name?) -> the root compound | nil, message. base: the decoded root +-- (Metadata fields and each region's Position / Size signs and pending ticks are kept) +function Litematic.write(regions: { Common.Region }, version: number, dataVersion: number, base: any, title: string?): (any, string?) + local baseRegions = if type(base) == "table" and Types.isObject(base.Regions) then base.Regions else nil + local regs, order = {}, {} + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + local blocks, volume = 0, 0 + for i, r in regions do + local name = r.name or ("Region" .. (if i == 1 then "" else tostring(i))) + while regs[name] ~= nil do + name ..= "_" + end + local sx, sy, sz = r.size[1], r.size[2], r.size[3] + local n = sx * sy * sz + local states, indices = Common.dedupe(r.states, r.indices, n) + if states[1] ~= "minecraft:air" then + -- Litematica keeps air at index 0 + local at = table.find(states, "minecraft:air") + local shifted = buffer.create(n * 2) + local nst = table.clone(states) + if at then + nst[1], nst[at] = states[at], states[1] + else + table.insert(nst, 1, "minecraft:air") + end + for c = 0, n - 1 do + local v = buffer.readu16(indices, c * 2) + local w = if at then (if v == 0 then at - 1 elseif v == at - 1 then 0 else v) else v + 1 + buffer.writeu16(shifted, c * 2, w) + end + states, indices = nst, shifted + end + local palette = Nbt.list("compound") + for k, st in states do + palette[k] = Mc.stateToNbt(st) + end + local airLike: { [number]: boolean } = {} + for k, st in states do + airLike[k - 1] = Mc.isAir(st) + end + for c = 0, n - 1 do + if not airLike[buffer.readu16(indices, c * 2)] then + blocks += 1 + end + end + volume += n + local bits = Packed.bitsFor(#states, 2) + local longs = Packed.pack(Packed.toYzx(indices, sx, sy, sz), n, bits, true) + local tiles = Nbt.list("compound") + for _, be in r.blockEntities do + table.insert(tiles, Common.flatBlockEntity(be, "flat")) + end + local p = r.position + local pos, size = { p[1], p[2], p[3] }, { sx, sy, sz } + local b = if baseRegions then baseRegions[name] else nil + local bsize = if type(b) == "table" then xyz(b.Size) else nil + if bsize and math.abs(bsize[1]) == sx and math.abs(bsize[2]) == sy and math.abs(bsize[3]) == sz then + -- keep the source's corner and signs + for k = 1, 3 do + if bsize[k] < 0 then + size[k] = bsize[k] + pos[k] = p[k] - bsize[k] - 1 + end + end + end + for k = 1, 3 do + lo[k] = math.min(lo[k], p[k]) + hi[k] = math.max(hi[k], p[k] + r.size[k]) + end + regs[name] = Common.merge(b, { + { "BlockStatePalette", palette }, + { "BlockStates", Nbt.longArray(longs) }, + { "Entities", if #r.entities > 0 then r.entities else Nbt.list("compound") }, + { "PendingBlockTicks", if type(b) == "table" then b.PendingBlockTicks else Nbt.list("compound") }, + { "PendingFluidTicks", if type(b) == "table" then b.PendingFluidTicks else Nbt.list("compound") }, + { "Position", vec(pos) }, + { "Size", vec(size) }, + { "TileEntities", tiles }, + }) + table.insert(order, name) + end + if #order == 0 then + lo, hi = { 0, 0, 0 }, { 0, 0, 0 } + end + local bm = if type(base) == "table" and type(base.Metadata) == "table" then base.Metadata else nil + local metadata = Common.merge(bm, { + { "EnclosingSize", vec({ hi[1] - lo[1], hi[2] - lo[2], hi[3] - lo[3] }) }, + { "Author", if bm and bm.Author then bm.Author else "" }, + { "Description", if bm and bm.Description then bm.Description else "" }, + { "Name", title or (if bm and bm.Name then bm.Name else "Unnamed") }, + { "RegionCount", #order }, + { "TimeCreated", if bm and bm.TimeCreated then bm.TimeCreated else Nbt.long(0) }, + { "TimeModified", if bm and bm.TimeModified then bm.TimeModified else Nbt.long(0) }, + { "TotalBlocks", blocks }, + { "TotalVolume", volume }, + }) + local regions_ = Types.object(regs, order) + return Common.merge(base, { + { "MinecraftDataVersion", dataVersion }, + { "Version", version }, + { "SubVersion", if type(base) == "table" and base.SubVersion ~= nil then base.SubVersion elseif version >= 6 then 1 else nil }, + { "Metadata", metadata }, + { "Regions", regions_ }, + }), nil +end + +return Litematic diff --git a/src/Formats/model/schematic/Mcedit.luau b/src/Formats/model/schematic/Mcedit.luau new file mode 100644 index 0000000..d320037 --- /dev/null +++ b/src/Formats/model/schematic/Mcedit.luau @@ -0,0 +1,213 @@ +--!strict +-- model/schematic/Mcedit: the MCEdit / WorldEdit .schematic layout (Minecraft before 1.13), from the Minecraft wiki +-- "Schematic file format" page: Width / Height / Length, Blocks + Data (+ WorldEdit's AddBlocks high nibbles, high +-- nibble first), Materials = "Alpha", TileEntities, Entities, WEOffset*, and the SchematicaMapping / BlockIDs name +-- tables of Schematica and MCEdit-Unified. Block ids become state strings through codecs/model/Minecraft +-- (legacyState: wool 14 -> minecraft:red_wool) and back (legacyId; blocks unknown before 1.13 become the legacy block +-- nearest in colour). +local Types = require("@formats/Types") +local Nbt = require("@formats/codecs/text/Nbt") +local Mc = require("@formats/codecs/model/Minecraft") +local Common = require("@formats/model/schematic/Common") + +local Mcedit = {} + +local Packed = Mc.Packed + +-- read(root, maxCells) -> { Region }, extra | nil, message +function Mcedit.read(root: any, maxCells: number): ({ Common.Region }?, any) + local blocks = root.Blocks + if type(blocks) ~= "buffer" then + return nil, "no Blocks byte array" + end + local function u16(v: any): any + local n = Common.int(v) + return if n and n < 0 then n + 65536 else n + end + local sx, sy, sz = Common.dims(u16(root.Width), u16(root.Height), u16(root.Length), maxCells) + if not sx then + return nil, sy + end + local n = sx * sy :: number * (sz :: number) + if buffer.len(blocks) < n then + return nil, "truncated: Blocks has " .. buffer.len(blocks) .. " bytes for " .. n .. " cells" + end + local data = if type(root.Data) == "buffer" and buffer.len(root.Data) >= n then root.Data else nil + local add = if type(root.AddBlocks) == "buffer" and buffer.len(root.AddBlocks) >= (n + 1) // 2 then root.AddBlocks else nil + -- id -> name tables of Schematica (name -> id) and MCEdit-Unified (id text -> name) + local names: { [number]: string } = {} + if Types.isObject(root.SchematicaMapping) then + for _, k in Types.keys(root.SchematicaMapping) do + local id = Common.int(root.SchematicaMapping[k]) + if id then + names[id] = k + end + end + end + if Types.isObject(root.BlockIDs) then + for _, k in Types.keys(root.BlockIDs) do + local id = tonumber(k) + if id and type(root.BlockIDs[k]) == "string" then + names[id] = root.BlockIDs[k] + end + end + end + local function state(id: number, d: number): string + local name = names[id] + if name then + local base = string.match(name, "^minecraft:(.*)$") or (if string.find(name, ":", 1, true) then nil else name) + if base then + local std = table.find(Mc.Legacy.NAMES, base) + if std then + return Mc.legacyState(std - 1, d) + end + end + return Mc.stateString(if string.find(name, ":", 1, true) then name else "minecraft:" .. name, if d ~= 0 then { { "data", tostring(d) } } else nil) + end + return Mc.legacyState(id, d) + end + local slots: { [number]: number } = {} + local states: { string } = {} + local yzx = buffer.create(n * 2) + for i = 0, n - 1 do + local id = buffer.readu8(blocks, i) + if add then + id += Packed.nibble(add, 0, i, true) * 256 + end + local d = if data then buffer.readu8(data, i) % 16 else 0 + local key = id * 16 + d + local s = slots[key] + if not s then + table.insert(states, state(id, d)) + s = #states - 1 + slots[key] = s + end + buffer.writeu16(yzx, i * 2, s :: number) + end + local bes = {} + for _, c in Common.list(root.TileEntities) do + local be = Common.blockEntity(c, "flat") + if be then + table.insert(bes, be) + end + end + return { + { + name = nil, + size = { sx, sy, sz }, + position = { Common.int(root.WEOffsetX) or 0, Common.int(root.WEOffsetY) or 0, Common.int(root.WEOffsetZ) or 0 }, + states = states, + indices = Packed.fromYzx(yzx, sx, sy :: number, sz :: number), + blockEntities = bes, + entities = Common.list(root.Entities), + }, + }, + { materials = root.Materials } +end + +-- the legacy blocks a colour can become (full blocks of distinct colours) +local CANDIDATES: { { any } }? = nil +local function candidates(): { { any } } + if CANDIDATES then + return CANDIDATES + end + local out = {} + local function add(id: number, d: number) + local c = Mc.color(Mc.legacyState(id, d)) + if c then + table.insert(out, { id, d, c }) + end + end + for d = 0, 15 do + add(35, d) -- wool + add(159, d) -- stained clay + add(251, d) -- concrete + end + for d = 0, 5 do + add(5, d) -- planks + end + for _, id in { 1, 2, 3, 4, 7, 12, 13, 24, 41, 42, 45, 48, 49, 57, 80, 82, 87, 88, 89, 98, 121, 133, 152, 155, 168, 172, 173, 174, 179, 201, 216 } do + add(id, 0) + end + CANDIDATES = out + return out +end + +local function nearest(state: string): (number, number) + local c = Mc.color(state) + if not c then + return 0, 0 + end + if c[4] < 200 then + return 20, 0 -- glass + end + local bid, bd, best = 1, 0, math.huge + for _, k in candidates() do + local kc = k[3] + local dist = (kc[1] - c[1]) ^ 2 + (kc[2] - c[2]) ^ 2 + (kc[3] - c[3]) ^ 2 + if dist < best then + bid, bd, best = k[1], k[2], dist + end + end + return bid, bd +end + +-- write(region, base?) -> the root compound (named "Schematic") | nil, message. base: a decoded root whose other +-- fields are kept +function Mcedit.write(r: Common.Region, base: any): (any, string?) + local sx, sy, sz = r.size[1], r.size[2], r.size[3] + if sx > 65535 or sy > 65535 or sz > 65535 then + return nil, "a .schematic is at most 65535 cells on each axis" + end + local n = sx * sy * sz + local ids, datas = table.create(#r.states), table.create(#r.states) + local high = false + for i, s in r.states do + local id, d = Mc.legacyId(s) + if id == nil then + id, d = nearest(s) + end + ids[i], datas[i] = id, d + if (id :: number) > 255 then + high = true + end + end + local yzx = Packed.toYzx(r.indices, sx, sy, sz) + local blocks, data = buffer.create(n), buffer.create(n) + local add = if high then buffer.create((n + 1) // 2) else nil + for i = 0, n - 1 do + local s = buffer.readu16(yzx, i * 2) + 1 + local id = ids[s] or 0 + buffer.writeu8(blocks, i, id % 256) + buffer.writeu8(data, i, datas[s] or 0) + if add then + Packed.setNibble(add, 0, i, id // 256, true) + end + end + local tiles = Nbt.list("compound") + for _, be in r.blockEntities do + table.insert(tiles, Common.flatBlockEntity(be, "flat")) + end + local ents = if #r.entities > 0 then r.entities else Nbt.list("compound") + local fields = { + { "Width", Nbt.short(sx) }, + { "Height", Nbt.short(sy) }, + { "Length", Nbt.short(sz) }, + { "Materials", "Alpha" }, + { "Blocks", blocks }, + { "Data", data }, + { "AddBlocks", add }, + { "Entities", ents }, + { "TileEntities", tiles }, + } + local p = r.position + if p[1] ~= 0 or p[2] ~= 0 or p[3] ~= 0 or (type(base) == "table" and base.WEOffsetX ~= nil) then + table.insert(fields, { "WEOffsetX", p[1] }) + table.insert(fields, { "WEOffsetY", p[2] }) + table.insert(fields, { "WEOffsetZ", p[3] }) + end + local root = Common.merge(base, fields, { SchematicaMapping = true, BlockIDs = true, Add = true }) + return root, nil +end + +return Mcedit diff --git a/src/Formats/model/schematic/Sponge.luau b/src/Formats/model/schematic/Sponge.luau new file mode 100644 index 0000000..47f344f --- /dev/null +++ b/src/Formats/model/schematic/Sponge.luau @@ -0,0 +1,131 @@ +--!strict +-- model/schematic/Sponge: the Sponge schematic format (.schem: WorldEdit 7+, FAWE, Amulet), from the +-- SpongePowered/Schematic-Specification documents for versions 1, 2 and 3: Width / Height / Length, Offset, the +-- block-state Palette with varint BlockData (v1 / v2) or the Blocks container (v3), block entities (TileEntities / +-- BlockEntities, v3 with Data), Entities, Metadata, DataVersion; biomes are kept as they are. +local Types = require("@formats/Types") +local Nbt = require("@formats/codecs/text/Nbt") +local Mc = require("@formats/codecs/model/Minecraft") +local Common = require("@formats/model/schematic/Common") + +local Sponge = {} + +local Packed = Mc.Packed + +-- read(s, maxCells) -> { Region }, extra | nil, message. s: the Schematic compound (v3: the root's Schematic child) +function Sponge.read(s: any, maxCells: number): ({ Common.Region }?, any) + local version = Common.int(s.Version) or 1 + local function u16(v: any): any + local n = Common.int(v) + return if n and n < 0 then n + 65536 else n + end + local sx, sy, sz = Common.dims(u16(s.Width), u16(s.Height), u16(s.Length), maxCells) + if not sx then + return nil, sy + end + local container = if version >= 3 then s.Blocks else s + if version >= 3 and type(container) ~= "table" then + return nil, "no Blocks container" + end + local palette = if version >= 3 then container.Palette else s.Palette + local data = if version >= 3 then container.Data else s.BlockData + if not Types.isObject(palette) then + return nil, "no block palette" + end + if type(data) ~= "buffer" then + return nil, "no block data" + end + local states: { string } = {} + local max = -1 + for _, k in Types.keys(palette) do + local i = Common.int(palette[k]) + if i == nil or i < 0 or i > 65535 then + return nil, "bad palette index for " .. k + end + states[i + 1] = k + if i > max then + max = i + end + end + for i = 1, max + 1 do + if states[i] == nil then + states[i] = "minecraft:air" + end + end + local n = sx * sy :: number * (sz :: number) + local yzx = buffer.create(n * 2) + local ok, e = Packed.varints(data, 0, buffer.len(data), n, yzx, max + 1) + if not ok then + return nil, e + end + local bes = {} + local raw = if version >= 3 then container.BlockEntities elseif version == 2 then s.BlockEntities else s.TileEntities + for _, c in Common.list(raw) do + local be = Common.blockEntity(c, if version >= 3 then "data" else "pos") + if be then + table.insert(bes, be) + end + end + local off = Common.ints(s.Offset) or { 0, 0, 0 } + return { + { + name = nil, + size = { sx, sy, sz }, + position = { off[1] or 0, off[2] or 0, off[3] or 0 }, + states = states, + indices = Packed.fromYzx(yzx, sx, sy :: number, sz :: number), + blockEntities = bes, + entities = Common.list(s.Entities), + }, + }, + { version = version, dataVersion = Common.int(s.DataVersion), metadata = s.Metadata } +end + +-- write(region, version, dataVersion, base?) -> the Schematic compound (v3: the caller wraps it in the root) | nil, +-- message. base: the decoded Schematic compound whose other fields (Metadata, Biomes, ...) are kept +function Sponge.write(r: Common.Region, version: number, dataVersion: number, base: any): (any, string?) + local sx, sy, sz = r.size[1], r.size[2], r.size[3] + if sx > 65535 or sy > 65535 or sz > 65535 then + return nil, "a Sponge schematic is at most 65535 cells on each axis" + end + local n = sx * sy * sz + local states, indices = Common.dedupe(r.states, r.indices, n) + local palette, keys = {}, {} + for i, st in states do + palette[st] = i - 1 + keys[i] = st + end + local pal = Types.object(palette, keys) + local data = Packed.toVarints(Packed.toYzx(indices, sx, sy, sz), n) + local bes = Nbt.list("compound") + for _, be in r.blockEntities do + table.insert(bes, Common.flatBlockEntity(be, if version >= 3 then "data" else "pos")) + end + local ents = if #r.entities > 0 then r.entities else nil + local off = Nbt.intArray({ r.position[1], r.position[2], r.position[3] }) + local fields: { { any } } = { + { "Version", version }, + { "DataVersion", if version >= 2 then dataVersion else nil }, + { "Width", Nbt.short(sx) }, + { "Height", Nbt.short(sy) }, + { "Length", Nbt.short(sz) }, + { "Offset", off }, + } + if version >= 3 then + local blocksBase = if type(base) == "table" then base.Blocks else nil + table.insert(fields, { "Blocks", Common.merge(blocksBase, { { "Palette", pal }, { "Data", data }, { "BlockEntities", bes } }) }) + table.insert(fields, { "Entities", ents }) + else + table.insert(fields, { "PaletteMax", #states }) + table.insert(fields, { "Palette", pal }) + table.insert(fields, { "BlockData", data }) + table.insert(fields, { if version == 2 then "BlockEntities" else "TileEntities", bes }) + table.insert(fields, { "Entities", if version == 2 then ents else nil }) + end + -- the other version's block fields never carry over + local drop = if version >= 3 then { PaletteMax = true, Palette = true, BlockData = true, BlockEntities = true, TileEntities = true } + else { Blocks = true, Biomes = true, TileEntities = version ~= 1, BlockEntities = version == 1 } + return Common.merge(base, fields, drop :: any), nil +end + +return Sponge diff --git a/src/Formats/model/schematic/init.luau b/src/Formats/model/schematic/init.luau new file mode 100644 index 0000000..4d0db36 --- /dev/null +++ b/src/Formats/model/schematic/init.luau @@ -0,0 +1,309 @@ +--!strict +-- model/schematic: Minecraft schematics: MCEdit / WorldEdit .schematic (before 1.13), Sponge .schem (versions 1, 2, 3: +-- WorldEdit 7+) and Litematica .litematic, read and write. New code over codecs/text/Nbt (gzip NBT) and +-- codecs/model/Minecraft (block states, colours, legacy ids, packed arrays); the layouts: model/schematic/Mcedit, +-- Sponge, Litematic. +-- decode -> a Scene (meta.up = "y", one unit = one block): scene.voxels holds one Types.Voxels per region (a .litematic +-- has several), each with voxels.blocks (the exact block states, u16 per cell, plus block entities and entities as +-- NBT) and data / palette coloured from the default block colour table; a node per region places it (translation = +-- the region's minimum corner: Sponge Offset, WorldEdit WEOffset, Litematica Position). meta.source keeps the +-- variant, version, DataVersion, Metadata and the whole root NBT (source.nbt). +-- encode <- a Scene with voxels or one Types.Voxels: opts.variant (or the file name's extension, or the source's) +-- "schem" (default, version 3) / "schematic" / "litematic". Grids without blocks (a .vox) get, per palette colour, +-- the block nearest in colour. Several regions are merged into one grid for .schem / .schematic. Fields of the +-- source that are not blocks (Metadata, biomes, pending ticks, ...) are written back when the variant is the same. +-- Not supported: converting block properties to pre-1.13 data values (legacy writes keep the data a state came with +-- or 0), Sponge biome conversion between versions, rotated nodes (only translations place a grid). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Nbt = require("@formats/codecs/text/Nbt") +local Mc = require("@formats/codecs/model/Minecraft") +local Common = require("@formats/model/schematic/Common") +local Mcedit = require("@formats/model/schematic/Mcedit") +local Sponge = require("@formats/model/schematic/Sponge") +local Litematic = require("@formats/model/schematic/Litematic") + +-- ------------------------------------------------------------------------------------------------ contract +local Schematic = { + name = "schematic", + category = "model", + extensions = { "schem", "schematic", "litematic" }, + mime = { "application/x-minecraft-schematic" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Nbt", "codecs/model/Minecraft" }, + caps = { decode = true, encode = true, voxels = true, blocks = true, variants = { "schem", "schematic", "litematic" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxCells: number?, -- refuse schematics with more cells in total (default 2^26) + maxBytes: number?, -- refuse NBT that inflates past this (default 2^28) +} +export type EncodeOptions = { + variant: ("schem" | "schematic" | "litematic")?, -- default: the extension of opts.name, the source's, else "schem" + version: number?, -- Sponge 1 / 2 / 3 (default 3, or the source's), Litematica version (default 6, or the source's) + dataVersion: number?, -- Minecraft's DataVersion (default the source's, else 3953 = 1.21) + name: string?, -- the file name (its extension picks the variant); for .litematic also the default Metadata.Name + title: string?, -- .litematic Metadata.Name + compression: ("gzip" | "zlib" | "none")?, -- default gzip, as every tool writes them + level: number?, -- deflate level +} + +-- ------------------------------------------------------------------------------------------------ constants +local DEFAULT_DATA_VERSION = 3953 +local LITEMATIC_HINTS = { "Regions", "EnclosingSize", "RegionCount", "TotalVolume", "MinecraftDataVersion" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Schematic.sniff(r: Bytes.Reader): number + local p = Nbt.peek(r.buf, r.base, r.limit - r.base) + if not p or p.rootType ~= "compound" or p.endian ~= "big" then + return 0 + end + if p.name == "Schematic" or (p.firstName == "Schematic" and p.firstType == "compound") then + return 1 + end + local head = buffer.tostring(p.head) + for _, h in LITEMATIC_HINTS do + if string.find(head, string.char(0, #h) .. h, 1, true) then + return 1 + end + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- variantOf(root, name) -> "schem" | "schematic" | "litematic", the compound holding the Sponge fields | nil +local function variantOf(root: any): (string?, any) + if type(root) ~= "table" or not Types.isObject(root) then + return nil, nil + end + if Types.isObject(root.Regions) then + return "litematic", root + end + if Types.isObject(root.Schematic) and (Common.int(root.Schematic.Version) or 0) >= 3 then + return "schem", root.Schematic + end + if root.Version ~= nil and (root.Palette ~= nil or root.BlockData ~= nil) then + return "schem", root + end + if type(root.Blocks) == "buffer" then + return "schematic", root + end + return nil, nil +end + +function Schematic.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local o: DecodeOptions = opts or {} + local root, info = Nbt.decode(r.buf, { maxBytes = o.maxBytes, endian = "big" }, r.base, r.limit - r.base) + if root == nil then + return nil, info + end + local variant, s = variantOf(root) + if not variant then + return nil, Err.new(Err.CORRUPT, "not a schematic (no Regions, Schematic / Palette or Blocks)") + end + local maxCells = o.maxCells or 2 ^ 26 + local regions, extra + if variant == "litematic" then + regions, extra = Litematic.read(s, maxCells) + elseif variant == "schem" then + regions, extra = Sponge.read(s, maxCells) + else + regions, extra = Mcedit.read(s, maxCells) + end + if not regions then + return nil, Err.from(extra) + end + local scene = Types.Scene.new() + scene.voxels = {} + for i, reg in regions do + local v = Mc.voxels(reg.size[1], reg.size[2], reg.size[3], reg.states, reg.indices) + v.name = reg.name + local b = v.blocks :: Types.VoxelBlocks + b.blockEntities = reg.blockEntities + b.entities = reg.entities + table.insert(scene.voxels :: { Types.Voxels }, v) + table.insert(scene.nodes, { name = reg.name, children = {}, voxels = i, translation = { reg.position[1], reg.position[2], reg.position[3] } }) + table.insert(scene.roots, #scene.nodes) + end + scene.meta.up = "y" + scene.meta.unit = 1 + local src: { [string]: any } = { format = "schematic", variant = variant, nbt = root, rootName = info.name, compression = info.compression } + for k, v in extra do + src[k] = v + end + scene.meta.source = src :: any + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function regionsOf(value: any): ({ Common.Region }?, string?) + local out: { Common.Region } = {} + local function add(v: Types.Voxels, pos: { number }, name: string?): string? + if type(v) ~= "table" or type(v.size) ~= "table" or type(v.data) ~= "buffer" then + return "expected Types.Voxels grids" + end + local states, indices = Mc.blocksOf(v) + if not states then + return indices + end + local b = v.blocks + table.insert(out, { + name = name or v.name, + size = { v.size[1], v.size[2], v.size[3] }, + position = { math.floor(pos[1] + 0.5), math.floor(pos[2] + 0.5), math.floor(pos[3] + 0.5) }, + states = states, + indices = indices, + blockEntities = if b and b.blockEntities then b.blockEntities else {}, + entities = if b and b.entities then b.entities else {}, + }) + return nil + end + if type(value) == "table" and value.kind == "voxels" then + local e = add(value, { 0, 0, 0 }, nil) + return if e then nil else out, e + end + if type(value) ~= "table" or value.kind ~= "scene" or type(value.voxels) ~= "table" or #value.voxels == 0 then + return nil, "expected a Scene with voxels or a Types.Voxels" + end + local placed = false + local function walk(i: number, base: { number }, depth: number): string? + local node = value.nodes[i] + if type(node) ~= "table" or depth > 64 then + return nil + end + local t = node.translation or { 0, 0, 0 } + local p = { base[1] + (t[1] or 0), base[2] + (t[2] or 0), base[3] + (t[3] or 0) } + if node.voxels and value.voxels[node.voxels] then + placed = true + local e = add(value.voxels[node.voxels], p, node.name) + if e then + return e + end + end + for _, c in node.children or {} do + local e = walk(c, p, depth + 1) + if e then + return e + end + end + return nil + end + for _, root in value.roots or {} do + local e = walk(root, { 0, 0, 0 }, 0) + if e then + return nil, e + end + end + if not placed then + for _, v in value.voxels do + local e = add(v, { 0, 0, 0 }, nil) + if e then + return nil, e + end + end + end + return out, nil +end + +-- merge(regions) -> one region covering them all (air where none is) +local function merge(regions: { Common.Region }): Common.Region + if #regions == 1 then + return regions[1] + end + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + for _, r in regions do + for k = 1, 3 do + lo[k] = math.min(lo[k], r.position[k]) + hi[k] = math.max(hi[k], r.position[k] + r.size[k]) + end + end + local sx, sy, sz = hi[1] - lo[1], hi[2] - lo[2], hi[3] - lo[3] + local states = { "minecraft:air" } + local out = buffer.create(sx * sy * sz * 2) + local bes, ents = {}, {} + for _, r in regions do + local base = #states + for _, st in r.states do + table.insert(states, st) + end + local rx, ry, rz = r.size[1], r.size[2], r.size[3] + local ox, oy, oz = r.position[1] - lo[1], r.position[2] - lo[2], r.position[3] - lo[3] + for z = 0, rz - 1 do + for y = 0, ry - 1 do + local s = (rx * (y + ry * z)) * 2 + local d = (ox + sx * ((oy + y) + sy * (oz + z))) * 2 + for _ = 0, rx - 1 do + buffer.writeu16(out, d, buffer.readu16(r.indices, s) + base) + s += 2 + d += 2 + end + end + end + for _, be in r.blockEntities do + table.insert(bes, { pos = { be.pos[1] + ox, be.pos[2] + oy, be.pos[3] + oz }, id = be.id, data = be.data }) + end + for _, e in r.entities do + table.insert(ents, e) + end + end + local st, idx = Common.dedupe(states, out, sx * sy * sz) + return { name = regions[1].name, size = { sx, sy, sz }, position = lo, states = st, indices = idx, blockEntities = bes, entities = ents } +end + +function Schematic.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local regions, rerr = regionsOf(value) + if not regions then + return nil, Err.new(Err.ARG, tostring(rerr)) + end + local src = if type(value) == "table" and type(value.meta) == "table" and type(value.meta.source) == "table" and value.meta.source.format == "schematic" then value.meta.source else nil + local ext = if o.name then string.lower(string.match(o.name, "%.([%w]+)$") or "") else nil + local key = o.format and string.lower(o.format) + local variant = o.variant + or (if ext == "schem" or ext == "schematic" or ext == "litematic" then ext else nil) + or (if key == "schem" or key == "litematic" then key else nil) + or (src and src.variant) + or "schem" + if variant ~= "schem" and variant ~= "schematic" and variant ~= "litematic" then + return nil, Err.new(Err.ARG, "unknown variant " .. tostring(variant)) + end + local same = src ~= nil and src.variant == variant + local base = if same then (src :: any).nbt else nil + local dataVersion = o.dataVersion or (src and src.dataVersion) or DEFAULT_DATA_VERSION + local root, rootName, e + if variant == "litematic" then + local version = o.version or (if same then (src :: any).version else nil) or 6 + local title = o.title or (if o.name then string.match(o.name, "([^/\\]-)%.[%w]+$") else nil) + root, e = Litematic.write(regions, version, dataVersion, base, title) + rootName = "" + elseif variant == "schem" then + local version = o.version or (if same then (src :: any).version else nil) or 3 + if version ~= 1 and version ~= 2 and version ~= 3 then + return nil, Err.new(Err.ARG, "Sponge schematic version must be 1, 2 or 3") + end + local sameVersion = same and (src :: any).version == version + local inner = if sameVersion and base then (if version >= 3 then base.Schematic else base) else nil + local sch + sch, e = Sponge.write(merge(regions), version, dataVersion, inner) + if sch and version >= 3 then + root, rootName = Common.merge(if sameVersion then base else nil, { { "Schematic", sch } }), "" + else + root, rootName = sch, "Schematic" + end + else + root, e = Mcedit.write(merge(regions), base) + rootName = "Schematic" + end + if not root then + return nil, Err.new(Err.ARG, tostring(e)) + end + if same and (src :: any).rootName ~= nil then + rootName = (src :: any).rootName + end + return Nbt.encode(root, { name = rootName, endian = "big", compression = o.compression or "gzip", level = o.level }) +end + +return Schematic diff --git a/tools/fixtures/schematic.py b/tools/fixtures/schematic.py new file mode 100644 index 0000000..7996ad6 --- /dev/null +++ b/tools/fixtures/schematic.py @@ -0,0 +1,243 @@ +# 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): + 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) From 7fc5d3f5f0ffb40b84abcf7c97f1d7b6607222da Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:26:01 -0500 Subject: [PATCH 10/27] regenerate registry after merging master --- docs/FORMATS.md | 2 ++ src/Formats/Registry.luau | 12 ++++++++++++ 2 files changed, 14 insertions(+) diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 1a67408..9f9bed5 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -41,6 +41,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` | | model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` | | model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` | +| model | schematic | .schem .schematic .litematic | yes | yes | voxels: true, blocks: true, variants: "schem", "schematic", "litematic" | **missing** | | model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` | | model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` | | model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` | @@ -128,6 +129,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - **model** - codecs/model/Mat4: 4x4 matrix and quaternion helpers for the model formats: column-major flat arrays of 16 - codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks + - codecs/model/Minecraft: what Minecraft's voxel formats share (model/schematic, model/mca). New code. - **text** - codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. - codecs/text/Nbt: Minecraft's Named Binary Tag format and its text form SNBT, the engine data/nbt, data/snbt, diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 61a19b4..6e4d13f 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -446,6 +446,18 @@ local list: { Entry } = { return require("@formats/model/ply") end, }, + { + name = "schematic", + category = "model", + path = "model/schematic", + extensions = { "schem", "schematic", "litematic" }, + mime = { "application/x-minecraft-schematic" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Nbt", "codecs/model/Minecraft" }, + caps = { decode = true, encode = true, voxels = true, blocks = true, variants = { "schem", "schematic", "litematic" } }, + load = function() + return require("@formats/model/schematic") + end, + }, { name = "stl", category = "model", From 22db57f3489aa979f5419decff55ed24c5858c07 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:28:11 -0500 Subject: [PATCH 11/27] ws-video2: MPEG-2 in MPEG-TS (0x02 / private 0x80), MPEG-PS, MKV, AVI, MP4 caps; tests/video/mpeg2.luau --- docs/FORMATS.md | 10 ++-- src/Formats/Registry.luau | 10 ++-- src/Formats/video/avi/init.luau | 2 +- src/Formats/video/mkv/init.luau | 2 +- src/Formats/video/mp4/init.luau | 2 +- src/Formats/video/mpegps/init.luau | 11 ++-- src/Formats/video/mpegts/init.luau | 7 +-- tests/video/mpeg2.luau | 80 ++++++++++++++++++++++++++++++ 8 files changed, 103 insertions(+), 21 deletions(-) create mode 100644 tests/video/mpeg2.luau diff --git a/docs/FORMATS.md b/docs/FORMATS.md index d612dc3..c98a249 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -27,12 +27,12 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | audio | voc | .voc | yes | yes | streaming: true, depths: 8, 16, lossy: false | `tests/audio/voc.luau` | | audio | vorbis | .ogg .oga | yes | yes | streaming: true, seek: true, lossy: true, channels: 255 | `tests/audio/vorbis.luau` | | audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` | -| video | avi | .avi | yes | yes | streaming: true, video: "mjpeg", "mpeg1", "rawvideo", audio: true, odml: true | `tests/video/avi.luau` | +| video | avi | .avi | yes | yes | streaming: true, video: "mjpeg", "mpeg1", "mpeg2", "rawvideo", audio: true, odml: true | `tests/video/avi.luau` | | video | h264 | .h264 .264 .avc .jsv .26l .jvt | yes | yes | streaming: true, video: "h264", depths: 8 | `tests/video/h264.luau` | -| video | mkv | .mkv .webm .mka .mk3d | yes | yes | streaming: true, remux: true, video: "vp8", "mjpeg", "mpeg1", "rawvideo", audio: true, subtitles: true | `tests/video/mkv.luau` | -| video | mp4 | .mp4 .m4v .mov .qt .3gp .3g2 .mj2 | yes | yes | streaming: true, remux: true, video: "mjpeg", "mpeg1", "h264", audio: true, fragments: true | `tests/video/mp4.luau` | -| video | mpegps | .mpg .mpeg .vob .m1v .mpv .dat | yes | - | streaming: true, video: "mpeg1", audio: true | `tests/video/mpegps.luau` | -| video | mpegts | .ts .m2ts .mts .tsv | yes | - | streaming: true, video: "mpeg1", "h264", audio: true | `tests/video/mpegts.luau` | +| video | mkv | .mkv .webm .mka .mk3d | yes | yes | streaming: true, remux: true, video: "vp8", "mjpeg", "mpeg1", "mpeg2", "rawvideo", audio: true, subtitles: true | `tests/video/mkv.luau` | +| video | mp4 | .mp4 .m4v .mov .qt .3gp .3g2 .mj2 | yes | yes | streaming: true, remux: true, video: "mjpeg", "mpeg1", "mpeg2", "h264", audio: true, fragments: true | `tests/video/mp4.luau` | +| video | mpegps | .mpg .mpeg .vob .m1v .mpv .dat | yes | - | streaming: true, video: "mpeg1", "mpeg2", audio: true | `tests/video/mpegps.luau` | +| video | mpegts | .ts .m2ts .mts .tsv | yes | - | streaming: true, video: "mpeg1", "mpeg2", "h264", audio: true | `tests/video/mpegts.luau` | | video | y4m | .y4m | yes | yes | streaming: true, video: "rawvideo", depths: 8, 10, 12, 16 | `tests/video/y4m.luau` | | model | 3mf | .3mf | yes | yes | materials: true, vertexColors: true, textures: true, units: true | `tests/model/3mf.luau` | | model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 429bc2a..7dfc437 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -285,7 +285,7 @@ local list: { Entry } = { extensions = { "avi" }, mime = { "video/x-msvideo", "video/avi" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Avi", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source" }, - caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "rawvideo" }, audio = true, odml = true }, + caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "mpeg2", "rawvideo" }, audio = true, odml = true }, load = function() return require("@formats/video/avi") end, @@ -309,7 +309,7 @@ local list: { Entry } = { extensions = { "mkv", "webm", "mka", "mk3d" }, mime = { "video/x-matroska", "video/webm", "audio/x-matroska", "audio/webm" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" }, - caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "rawvideo" }, audio = true, subtitles = true }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "mpeg2", "rawvideo" }, audio = true, subtitles = true }, load = function() return require("@formats/video/mkv") end, @@ -321,7 +321,7 @@ local list: { Entry } = { extensions = { "mp4", "m4v", "mov", "qt", "3gp", "3g2", "mj2" }, mime = { "video/mp4", "video/quicktime", "video/3gpp" }, deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source" }, - caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "h264" }, audio = true, fragments = true }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "mpeg2", "h264" }, audio = true, fragments = true }, load = function() return require("@formats/video/mp4") end, @@ -333,7 +333,7 @@ local list: { Entry } = { extensions = { "mpg", "mpeg", "vob", "m1v", "mpv", "dat" }, mime = { "video/mpeg" }, deps = { "core/Err", "core/Bytes", "Types", "containers/MpegPs", "containers/MpegEs", "containers/Demux", "codecs/video/Video" }, - caps = { decode = true, encode = false, streaming = true, video = { "mpeg1" }, audio = true }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2" }, audio = true }, load = function() return require("@formats/video/mpegps") end, @@ -345,7 +345,7 @@ local list: { Entry } = { extensions = { "ts", "m2ts", "mts", "tsv" }, mime = { "video/mp2t" }, deps = { "core/Err", "core/Bytes", "Types", "containers/MpegTs", "containers/MpegEs", "containers/Demux", "codecs/video/Video" }, - caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "h264" }, audio = true }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2", "h264" }, audio = true }, load = function() return require("@formats/video/mpegts") end, diff --git a/src/Formats/video/avi/init.luau b/src/Formats/video/avi/init.luau index fc46a32..1f0fdf0 100644 --- a/src/Formats/video/avi/init.luau +++ b/src/Formats/video/avi/init.luau @@ -25,7 +25,7 @@ local AviFormat = { extensions = { "avi" }, mime = { "video/x-msvideo", "video/avi" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Avi", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source" }, - caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "rawvideo" }, audio = true, odml = true }, + caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "mpeg2", "rawvideo" }, audio = true, odml = true }, } -- ------------------------------------------------------------------------------------------------ types diff --git a/src/Formats/video/mkv/init.luau b/src/Formats/video/mkv/init.luau index 8e009e9..9e068c7 100644 --- a/src/Formats/video/mkv/init.luau +++ b/src/Formats/video/mkv/init.luau @@ -28,7 +28,7 @@ local Mkv = { extensions = { "mkv", "webm", "mka", "mk3d" }, mime = { "video/x-matroska", "video/webm", "audio/x-matroska", "audio/webm" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" }, - caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "rawvideo" }, audio = true, subtitles = true }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "mpeg2", "rawvideo" }, audio = true, subtitles = true }, } -- ------------------------------------------------------------------------------------------------ types diff --git a/src/Formats/video/mp4/init.luau b/src/Formats/video/mp4/init.luau index 48b57c7..eb643df 100644 --- a/src/Formats/video/mp4/init.luau +++ b/src/Formats/video/mp4/init.luau @@ -30,7 +30,7 @@ local Mp4 = { extensions = { "mp4", "m4v", "mov", "qt", "3gp", "3g2", "mj2" }, mime = { "video/mp4", "video/quicktime", "video/3gpp" }, deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source" }, - caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "h264" }, audio = true, fragments = true }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "mpeg2", "h264" }, audio = true, fragments = true }, } -- ------------------------------------------------------------------------------------------------ types diff --git a/src/Formats/video/mpegps/init.luau b/src/Formats/video/mpegps/init.luau index 8708894..91ef418 100644 --- a/src/Formats/video/mpegps/init.luau +++ b/src/Formats/video/mpegps/init.luau @@ -1,10 +1,11 @@ --!strict -- video/mpegps: MPEG program streams (ISO/IEC 11172-1 system streams and 13818-1 program streams: .mpg / .mpeg / -- .vob / VCD .dat). New in formats-luau, on containers/MpegPs. Video PES payloads are joined into the elementary --- stream and cut into pictures (containers/MpegEs: one packet per picture with its sequence / GOP headers); a --- picture takes the PTS of the PES it starts in, pictures without one get theirs from the GOP's temporal references. --- Audio packets are the PES payloads (MP1 / MP2 / MP3 frames, AC-3, LPCM). open() returns a VideoDecoder: MPEG-1 --- video through the codecs/video/Video registry (MPEG-2 detected and reported), audio through the api's opts.openAudio hook. +-- stream and cut into pictures (containers/MpegEs: one packet per picture with its sequence / GOP headers, both +-- fields of a field-coded frame in one); a picture takes the PTS of the PES it starts in, pictures without one get +-- theirs from the GOP's temporal references. Audio packets are the PES payloads (MP1 / MP2 / MP3 frames, AC-3, LPCM). +-- open() returns a VideoDecoder: MPEG-1 / MPEG-2 video through the codecs/video/Video registry (MPEG-2 told by its +-- sequence extension), audio through the api's opts.openAudio hook. -- Timescale 90 kHz. Not supported: writing, H.264 in PS (packets are whole PES payloads), DVD navigation packets. -- ------------------------------------------------------------------------------------------------ requires @@ -23,7 +24,7 @@ local Ps = { extensions = { "mpg", "mpeg", "vob", "m1v", "mpv", "dat" }, mime = { "video/mpeg" }, deps = { "core/Err", "core/Bytes", "Types", "containers/MpegPs", "containers/MpegEs", "containers/Demux", "codecs/video/Video" }, - caps = { decode = true, encode = false, streaming = true, video = { "mpeg1" }, audio = true }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2" }, audio = true }, } -- ------------------------------------------------------------------------------------------------ types diff --git a/src/Formats/video/mpegts/init.luau b/src/Formats/video/mpegts/init.luau index 1cac2a4..4213838 100644 --- a/src/Formats/video/mpegts/init.luau +++ b/src/Formats/video/mpegts/init.luau @@ -2,8 +2,9 @@ -- video/mpegts: MPEG transport streams (ISO/IEC 13818-1: .ts / .m2ts segments, HLS). The demuxer is containers/MpegTs, -- absorbed from mpegts-luau (resync, PAT / PMT with CRC, continuity checks, PES reassembly, 33-bit PTS / DTS -- unwrapped); this format turns its units into a Demuxer (timescale 90 kHz; one PES = one packet: a picture as --- muxed by ffmpeg, one or more audio frames) and returns a VideoDecoder: MPEG-1 video through the codecs/video/Video --- registry (stream type 0x02 checked for an MPEG-2 sequence extension), H.264 when registered, audio (MP1 / MP2 / +-- muxed by ffmpeg, one or more audio frames) and returns a VideoDecoder: MPEG-1 / MPEG-2 video through the +-- codecs/video/Video registry (stream types 0x01 / 0x02, and private ones such as 0x80 with a video PES stream id, +-- told apart by an MPEG-2 sequence extension), H.264 when registered, audio (MP1 / MP2 / -- MP3, AAC in ADTS) through the api's opts.openAudio hook. Keyframes: MPEG-1 / 2 I-pictures, H.264 IDR access units. -- M2TS (192-byte packets with a 4-byte timestamp prefix) is read too. Not supported: writing, scrambled streams, -- PES without PTS for video before the first one (dropped). @@ -24,7 +25,7 @@ local Ts = { extensions = { "ts", "m2ts", "mts", "tsv" }, mime = { "video/mp2t" }, deps = { "core/Err", "core/Bytes", "Types", "containers/MpegTs", "containers/MpegEs", "containers/Demux", "codecs/video/Video" }, - caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "h264" }, audio = true }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2", "h264" }, audio = true }, } -- ------------------------------------------------------------------------------------------------ types diff --git a/tests/video/mpeg2.luau b/tests/video/mpeg2.luau new file mode 100644 index 0000000..9fe1724 --- /dev/null +++ b/tests/video/mpeg2.luau @@ -0,0 +1,80 @@ +-- MPEG-2 video in the containers (tools/fixtures/mpeg2.py, "mpeg2_containers"): the same elementary stream copied by +-- ffmpeg into MPEG-TS (stream type 0x02, and the PMT patched to 0x80, private / DigiCipher II video), MPEG-PS (VOB), +-- Matroska (V_MPEG2) and AVI: each opens through F.video.open with codec "mpeg2", its frames equal ffmpeg's +-- `-idct int` decode (luma CRC per frame, display order), seeking lands on a frame; the raw .m2v opens too. +local T = require("@tests/T") +local F = require("@formats") +local Base64 = require("@formats/core/Base64") +local Crc32 = require("@formats/core/Crc32") +local Fx = require("@tests/gen/mpeg2_containers") +local Prog = require("@tests/gen/mpeg2_prog") + +local t = T.suite("video/mpeg2") + +local function lumaCrc(img: any): number + return Crc32.of(img.pixels, 0, img.width * img.height) +end + +local CASES = { + { "ts", "mpegts" }, + { "ts80", "mpegts" }, + { "mpg", "mpegps" }, + { "mkv", "mkv" }, + { "avi", "avi" }, +} +for _, c in CASES do + local key, format = c[1], c[2] + local data = Base64.decode(Fx[key]) :: buffer + local v, err = F.video.open(data) + t:check(v ~= nil, key .. ": opens: " .. tostring(err)) + if v then + t:eq(v.format, format, key .. ": format") + t:eq(v.codec, "mpeg2", key .. ": codec") + t:check(v.width == Prog.width and v.height == Prog.height, key .. ": size") + local frames, exact = 0, 0 + while true do + local f, ferr = v:nextFrame() + t:check(ferr == nil, key .. ": frame error " .. tostring(ferr)) + if not f then + break + end + frames += 1 + local ref = Fx.crcs[frames] + if ref and lumaCrc(f.image) == ref[1] then + exact += 1 + end + end + t:eq(frames, #Fx.crcs, key .. ": frame count") + -- the frames ffmpeg's encoder left with an uncoded macroblock are concealed differently (tests/codecs/mpeg2) + t:check(exact >= frames - 2, string.format("%s: %d of %d frames equal ffmpeg's", key, exact, frames)) + v:seek(0.4) + local f = v:nextFrame() + t:check(f ~= nil and math.abs(f.pts - 0.4) < 0.05, key .. ": seek") + t:note(" %-5s %-7s %d frames, %d bit-exact", key, format, frames, exact) + end +end + +-- the elementary stream itself +do + local v, err = F.video.open(Base64.decode(Prog.file) :: buffer) + t:check(v ~= nil and v.codec == "mpeg2", "m2v: opens as mpeg2: " .. tostring(err)) + if v then + local n = 0 + while v:nextFrame() do + n += 1 + end + t:eq(n, Prog.frames, "m2v: frame count") + end +end + +t:fuzz("open", function(b: buffer) + local v = F.video.open(b) + if v then + for _ = 1, 3 do + v:nextFrame() + end + end + return v +end, { Base64.decode(Fx.ts) :: buffer, Base64.decode(Fx.mpg) :: buffer }, { mutations = 30, garbage = 5 }) + +t:done() From 5585ce53cef2d020ecb364fb70ea00c261831c10 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:30:45 -0500 Subject: [PATCH 12/27] ws-video2: MPEG-1 tests bit-exact against ffmpeg -idct int (308 of 312 frames; 4 with concealed macroblocks) --- tests/codecs/mpeg1.luau | 27 +++++++++++++++++++++++++-- tools/fixtures/mpeg1.py | 15 +++++++++++---- 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/tests/codecs/mpeg1.luau b/tests/codecs/mpeg1.luau index 34cafb4..d5ca329 100644 --- a/tests/codecs/mpeg1.luau +++ b/tests/codecs/mpeg1.luau @@ -1,4 +1,5 @@ --- codecs/video/Mpeg1 tests, ported from mpeg1-luau tests/decode.luau and tests/robust.luau. Against ffmpeg +-- codecs/video/Mpeg1 tests, ported from mpeg1-luau tests/decode.luau and tests/robust.luau. Every frame bit-exact with +-- `ffmpeg -idct int` (the IDCT codecs/video/Dsp reproduces; frames with concealed macroblocks excepted). Against ffmpeg -- (tools/fixtures/mpeg1.py): every stream decodes, one access unit at a time, to as many frames as ffmpeg's decode, -- in display order; each frame's RGBA channel means within 1.5 of ffmpeg's; whole sampled frames within 2 MAE per -- channel (IDCT and colour rounding) and, as yuv420p (frameImage), within a PSNR floor of ffmpeg -pix_fmt yuv420p; @@ -11,6 +12,7 @@ local Mpeg1 = require("@formats/codecs/video/Mpeg1") local Base64 = require("@formats/core/Base64") local Deflate = require("@formats/codecs/compress/Deflate") local Types = require("@formats/Types") +local Crc32 = require("@formats/core/Crc32") local STREAMS = { require("@tests/gen/mpeg1_qcif_200k"), @@ -81,6 +83,7 @@ local function psnr(a: buffer, ao: number, b: buffer, bo: number, n: number): nu end local MAE_LIMIT = 2 +local totalExact, totalConcealed = 0, 0 local MEAN_LIMIT = 1.5 -- 1. every stream against ffmpeg @@ -101,6 +104,7 @@ for _, fx in STREAMS do local hasB = string.find(name, "bframes") ~= nil local dec = Mpeg1.new({ reorder = hasB }) local frames = 0 + local exact, concealed = 0, 0 local maxMae, maxMeanErr = 0, 0 local sums = {} local function onFrame(f: any) @@ -136,6 +140,21 @@ for _, fx in STREAMS do end t:check(buffer.readu8(px, 3) == 255 and buffer.readu8(px, n * 4 - 1) == 255, "alpha 255") sums[frames] = buffer.tostring(px) + -- bit-exact against ffmpeg -idct int (outside macroblocks the decoder had to conceal) + local ex = fx.exact[frames] + if ex then + local img = Mpeg1.frameImage(f) :: Types.Image + local yc = Crc32.of(img.pixels, 0, n) + local uc = Crc32.of(img.pixels, n, cw * ch) + local vc = Crc32.of(img.pixels, n + cw * ch, cw * ch) + if yc == ex[1] and uc == ex[2] and vc == ex[3] then + exact += 1 + elseif next(f.concealed) ~= nil then + concealed += 1 + else + t:check(false, string.format("%s frame %d (type %d): differs from ffmpeg -idct int", name, frames, f.pictureType)) + end + end end local t0 = os.clock() for _, u in fx.units do @@ -155,7 +174,10 @@ for _, fx in STREAMS do t:eq(frames, fx.frames, name .. ": frames (ffmpeg's count)") t:eq(dec.stats.errors, 0, name .. ": no bitstream errors") worst = math.max(worst, maxMae) - t:note("%-13s %4dx%-4d %3d frames worst MAE %.3f means err %.3f %6.1f fps (with the checks)", name, w, h, frames, maxMae, maxMeanErr, frames / dt) + t:note("%-13s %4dx%-4d %3d frames %3d bit-exact worst MAE %.3f means err %.3f %6.1f fps (with the checks)", name, w, h, frames, exact, maxMae, maxMeanErr, frames / dt) + t:eq(exact + concealed, frames, name .. ": frames equal to ffmpeg -idct int (or with concealed macroblocks)") + totalExact += exact + totalConcealed += concealed -- streamed: random pieces through write / decodeFrame, then flush local d2 = Mpeg1.new({ reorder = hasB }) @@ -187,6 +209,7 @@ for _, fx in STREAMS do t:eq(got, frames, name .. ": streamed frame count") end t:note("worst sampled-frame MAE %.3f (limit %d); worst yuv420p PSNR luma %.1f, chroma %.1f dB", worst, MAE_LIMIT, worstY, worstC) +t:note("%d frames bit-exact with ffmpeg -idct int, %d with concealed macroblocks (ffmpeg error concealment)", totalExact, totalConcealed) -- 2. a size change mid-stream do diff --git a/tools/fixtures/mpeg1.py b/tools/fixtures/mpeg1.py index 0400555..3b5dfd8 100644 --- a/tools/fixtures/mpeg1.py +++ b/tools/fixtures/mpeg1.py @@ -4,7 +4,9 @@ # tests/gen/mpeg1_.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) From 3a1965486f68cf7807f361346c9ebe94ae4a4b28 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:33:15 -0500 Subject: [PATCH 13/27] ws-roblox: model/robloxmesh (.mesh 1.00-5.00, 6.00/7.00 chunked with raw COREMESH read; Draco COREMESH UNSUPPORTED; 2.00 / 4.00 write with skinning subsets and LODs) mapped to Scene; rbxm / rbxmx variant() for F.detect (rbxl / rbxlx); api tests --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/model/rbxm/init.luau | 30 ++ src/Formats/model/rbxmx/init.luau | 6 + src/Formats/model/robloxmesh/Parse.luau | 440 ++++++++++++++++++ src/Formats/model/robloxmesh/Write.luau | 109 +++++ src/Formats/model/robloxmesh/init.luau | 578 ++++++++++++++++++++++++ tests/model/rbxm.luau | 17 + tests/model/robloxmesh.luau | 202 +++++++++ tools/fixtures/_robloxmesh_encode.luau | 30 ++ tools/fixtures/robloxmesh.py | 461 +++++++++++++++++++ 11 files changed, 1886 insertions(+) create mode 100644 src/Formats/model/robloxmesh/Parse.luau create mode 100644 src/Formats/model/robloxmesh/Write.luau create mode 100644 src/Formats/model/robloxmesh/init.luau create mode 100644 tests/model/robloxmesh.luau create mode 100644 tools/fixtures/_robloxmesh_encode.luau create mode 100644 tools/fixtures/robloxmesh.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0250ba7..ab1b266 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -43,6 +43,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` | | model | rbxm | .rbxm .rbxl | yes | yes | tree: true, compression: "none", "lz4", "zstd" | `tests/model/rbxm.luau` | | model | rbxmx | .rbxmx .rbxlx | yes | yes | tree: true | `tests/model/rbxmx.luau` | +| model | robloxmesh | .mesh | yes | yes | skinning: true, lods: true, versions: "1.00", "1.01", "2.00", "3.00", "3.01", "4.00", "4.01", "5.00", "6.00", "7.00" | `tests/model/robloxmesh.luau` | | model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` | | model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` | | model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 9d01ae2..10f00bd 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -470,6 +470,18 @@ local list: { Entry } = { return require("@formats/model/rbxmx") end, }, + { + name = "robloxmesh", + category = "model", + path = "model/robloxmesh", + extensions = { "mesh" }, + mime = { "application/x-roblox-mesh" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten" }, + caps = { decode = true, encode = true, skinning = true, lods = true, versions = { "1.00", "1.01", "2.00", "3.00", "3.01", "4.00", "4.01", "5.00", "6.00", "7.00" } }, + load = function() + return require("@formats/model/robloxmesh") + end, + }, { name = "stl", category = "model", diff --git a/src/Formats/model/rbxm/init.luau b/src/Formats/model/rbxm/init.luau index 7fb49e7..b903f92 100644 --- a/src/Formats/model/rbxm/init.luau +++ b/src/Formats/model/rbxm/init.luau @@ -50,6 +50,36 @@ function Rbxm.sniff(r: Bytes.Reader): number return if r:peek(14) == MAGIC then 1 else 0 end +-- variant(r) -> "rbxl" for a place (an INST chunk marks services), else "rbxm" (F.detect); reads only the INST chunks +function Rbxm.variant(r: Bytes.Reader): string? + local b, p, e = r.buf, r.base + 32, r.limit + if r:peek(14) ~= MAGIC then + return nil + end + while p + 16 <= e do + local name, clen, ulen = readstring(b, p, 4), readu32(b, p + 4), readu32(b, p + 8) + local size = if clen == 0 then ulen else clen + if p + 16 + size > e or name == "END\0" then + break + end + if name == "INST" then + local body: buffer?, o = b, p + 16 + if clen ~= 0 then + body = if Zstd.isFrame(b, p + 16) then Zstd.decompress(b, p + 16, clen, { maxBytes = ulen }) else Lz4.decompress(b, p + 16, clen, ulen) + o = 0 + end + if body and o + 8 <= buffer.len(body) then + local q = o + 8 + readu32(body, o + 4) + if q < buffer.len(body) and readu8(body, q) == 1 then + return "rbxl" + end + end + end + p += 16 + size + end + return "rbxm" +end + -- ------------------------------------------------------------------------------------------------ decode type Class = { id: number, name: string, refs: { number }, service: boolean } diff --git a/src/Formats/model/rbxmx/init.luau b/src/Formats/model/rbxmx/init.luau index b2427ac..91ec602 100644 --- a/src/Formats/model/rbxmx/init.luau +++ b/src/Formats/model/rbxmx/init.luau @@ -81,6 +81,12 @@ function Rbxmx.sniff(r: Bytes.Reader): number return 0 end +-- variant(r) -> "rbxlx" for a place (a Workspace item), else "rbxmx" (F.detect) +function Rbxmx.variant(r: Bytes.Reader): string? + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + return if find(text, ' lim.maxVertices or nf > lim.maxFaces then + return nil, "limit: " .. nf .. " faces" + end + local r = record(version) + local nv = nf * 3 + r.numVerts, r.numFaces = nv, nf + r.pos, r.nrm, r.uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8) + r.faces = buffer.create(nf * 12) + local scale = if version == "1.00" then 0.5 else 1 + local i = 0 + local vals = table.create(9, 0) + local k = 0 + local start = string.find(text, "[", 1, true) or (#text + 1) + for a, b, c in string.gmatch(string.sub(text, start), "%[%s*([^,%]]+)%s*,%s*([^,%]]+)%s*,%s*([^,%]]+)%s*%]") do + local x, y, z = tonumber(a), tonumber(b), tonumber(c) + if not x or not y or not z then + return nil, "corrupt: bad number in a vector" + end + vals[k * 3 + 1], vals[k * 3 + 2], vals[k * 3 + 3] = x, y, z + k += 1 + if k == 3 then + if i >= nv then + break + end + writef32(r.pos, i * 12, vals[1] * scale) + writef32(r.pos, i * 12 + 4, vals[2] * scale) + writef32(r.pos, i * 12 + 8, vals[3] * scale) + writef32(r.nrm, i * 12, vals[4]) + writef32(r.nrm, i * 12 + 4, vals[5]) + writef32(r.nrm, i * 12 + 8, vals[6]) + writef32(r.uv, i * 8, vals[7]) + writef32(r.uv, i * 8 + 4, 1 - vals[8]) -- version 1 stores V upside down + i += 1 + k = 0 + end + end + if i < nv then + return nil, "truncated: " .. i .. " of " .. nv .. " vertices" + end + for f = 0, nv - 1 do + writeu32(r.faces, f * 4, f) + end + r.lods = { 0, nf } + return r, nil +end + +-- ------------------------------------------------------------------------------------------------ binary parts +-- vertices of size vs (36 / 40) at p +local function vertices(b: buffer, p: number, n: number, vs: number, r: Record) + local pos, nrm, uv, tan = buffer.create(n * 12), buffer.create(n * 12), buffer.create(n * 8), buffer.create(n * 4) + local col = if vs >= 40 then buffer.create(n * 4) else nil + for i = 0, n - 1 do + local q = p + i * vs + buffer.copy(pos, i * 12, b, q, 12) + buffer.copy(nrm, i * 12, b, q + 12, 12) + buffer.copy(uv, i * 8, b, q + 24, 8) + buffer.copy(tan, i * 4, b, q + 32, 4) + if col then + buffer.copy(col, i * 4, b, q + 36, 4) + end + end + r.pos, r.nrm, r.uv, r.tan, r.col = pos, nrm, uv, tan, col + r.numVerts = n +end + +local function faces(b: buffer, p: number, n: number, fs: number, r: Record): string? + local out = buffer.create(n * 12) + local nv = r.numVerts + for i = 0, n - 1 do + for k = 0, 2 do + local v = readu32(b, p + i * fs + k * 4) + if v >= nv then + return "corrupt: face " .. i .. " uses vertex " .. v .. " of " .. nv + end + writeu32(out, i * 12 + k * 4, v) + end + end + r.faces, r.numFaces = out, n + return nil +end + +local function bones(b: buffer, p: number, n: number, names: string, r: Record) + for i = 0, n - 1 do + local q = p + i * 60 + local ni = readu32(b, q) + local name = string.match(string.sub(names, ni + 1), "^[^%z]*") or "" + local parent = readu16(b, q + 4) + local cf = table.create(12, 0) + for k = 0, 11 do + cf[k + 1] = readf32(b, q + 12 + 4 * k) + end + r.bones[i + 1] = { name = name, parent = if parent == 0xFFFF then nil else parent, lodParent = readu16(b, q + 6), culling = readf32(b, q + 8), cf = cf } + end +end + +local function subsets(b: buffer, p: number, n: number, r: Record) + for i = 0, n - 1 do + local q = p + i * 72 + local count = math.min(readu32(b, q + 16), 26) + local list = table.create(count, 0) + for k = 0, count - 1 do + list[k + 1] = readu16(b, q + 20 + 2 * k) + end + r.subsets[i + 1] = { facesBegin = readu32(b, q), facesLength = readu32(b, q + 4), vertsBegin = readu32(b, q + 8), vertsLength = readu32(b, q + 12), bones = list } + end +end + +local function lods(b: buffer, p: number, n: number, r: Record) + local out = table.create(n, 0) + for i = 0, n - 1 do + out[i + 1] = readu32(b, p + 4 * i) + end + r.lods = out +end + +-- ------------------------------------------------------------------------------------------------ versions 2 .. 5 +local function classic(b: buffer, p: number, e: number, version: string, lim: Limits): (Record?, string?) + local r = record(version) + local major = tonumber(string.sub(version, 1, 1)) or 0 + if p + 12 > e then + return nil, "truncated header" + end + local hs = readu16(b, p) + local nv: number, nf: number, vs: number, fs: number = 0, 0, 40, 12 + local nlod: number, nbones: number, namesSize: number, nsub: number = 0, 0, 0, 0 + if major == 2 or major == 3 then + vs = readu8(b, p + 2) + fs = readu8(b, p + 3) + if major == 2 then + nv = readu32(b, p + 4) + nf = readu32(b, p + 8) + else + if p + 16 > e then + return nil, "truncated header" + end + nlod = readu16(b, p + 6) + nv = readu32(b, p + 8) + nf = readu32(b, p + 12) + end + else + if p + 24 > e then + return nil, "truncated header" + end + r.lodType = readu16(b, p + 2) + nv = readu32(b, p + 4) + nf = readu32(b, p + 8) + nlod = readu16(b, p + 12) + nbones = readu16(b, p + 14) + namesSize = readu32(b, p + 16) + nsub = readu16(b, p + 20) + r.highQualityLods = readu8(b, p + 22) + if major >= 5 then + if p + 32 > e then + return nil, "truncated header" + end + r.facsFormat = readu32(b, p + 24) + end + end + if vs < 36 or fs < 12 then + return nil, "corrupt: vertex size " .. vs .. ", face size " .. fs + end + if nv > lim.maxVertices or nf > lim.maxFaces then + return nil, "limit: " .. nv .. " vertices, " .. nf .. " faces" + end + local q = p + hs + if q + nv * vs > e then + return nil, "truncated vertices" + end + vertices(b, q, nv, vs, r) + q += nv * vs + if nbones > 0 then + if q + nv * 8 > e then + return nil, "truncated skinning" + end + local env = buffer.create(nv * 8) + buffer.copy(env, 0, b, q, nv * 8) + r.env = env + q += nv * 8 + end + if q + nf * fs > e then + return nil, "truncated faces" + end + local ferr = faces(b, q, nf, fs, r) + if ferr then + return nil, ferr + end + q += nf * fs + if q + nlod * 4 > e then + return nil, "truncated LOD offsets" + end + lods(b, q, nlod, r) + q += nlod * 4 + if q + nbones * 60 + namesSize + nsub * 72 > e then + return nil, "truncated bones / subsets" + end + local names = readstring(b, q + nbones * 60, namesSize) + bones(b, q, nbones, names, r) + q += nbones * 60 + namesSize + subsets(b, q, nsub, r) + q += nsub * 72 + if major >= 5 then + local size = readu32(b, p + 28) + if size > 0 then + if q + size > e then + return nil, "truncated FACS data" + end + local facs = buffer.create(size) + buffer.copy(facs, 0, b, q, size) + r.facs = facs + end + end + if #r.lods == 0 then + r.lods = { 0, nf } + end + return r, nil +end + +-- ------------------------------------------------------------------------------------------------ versions 6 / 7 +local function chunked(b: buffer, p: number, e: number, version: string, lim: Limits): (Record?, string?) + local r = record(version) + local core = false + while p < e do + if p + 16 > e then + return nil, "truncated chunk header" + end + local name = string.gsub(readstring(b, p, 8), "%z+$", "") + local cv, size = readu32(b, p + 8), readu32(b, p + 12) + local q = p + 16 + local ce = q + size + if ce > e then + return nil, "truncated chunk " .. name + end + if name == "COREMESH" then + if cv == 2 then + return nil, "unsupported: Draco-compressed COREMESH (needs codecs/model/Draco)" + elseif cv ~= 1 then + return nil, "unsupported: COREMESH version " .. cv + end + if q + 4 > ce then + return nil, "truncated COREMESH" + end + local nv = readu32(b, q) + if nv > lim.maxVertices then + return nil, "limit: " .. nv .. " vertices" + end + if q + 4 + nv * 40 + 4 > ce then + return nil, "truncated COREMESH vertices" + end + vertices(b, q + 4, nv, 40, r) + local fq = q + 4 + nv * 40 + local nf = readu32(b, fq) + if nf > lim.maxFaces then + return nil, "limit: " .. nf .. " faces" + end + if fq + 4 + nf * 12 > ce then + return nil, "truncated COREMESH faces" + end + local ferr = faces(b, fq + 4, nf, 12, r) + if ferr then + return nil, ferr + end + core = true + elseif name == "LODS" and cv == 1 then + if q + 7 > ce then + return nil, "truncated LODS" + end + r.lodType = readu16(b, q) + r.highQualityLods = readu8(b, q + 2) + local n = readu32(b, q + 3) + if q + 7 + n * 4 > ce then + return nil, "truncated LODS" + end + lods(b, q + 7, n, r) + elseif name == "SKINNING" and cv == 1 then + if not core then + return nil, "corrupt: SKINNING before COREMESH" + end + if q + 4 > ce then + return nil, "truncated SKINNING" + end + local ns = readu32(b, q) + local s = q + 4 + if ns ~= r.numVerts or s + ns * 8 + 4 > ce then + return nil, "corrupt: SKINNING count" + end + local env = buffer.create(ns * 8) + buffer.copy(env, 0, b, s, ns * 8) + r.env = env + s += ns * 8 + local nb = readu32(b, s) + s += 4 + if s + nb * 60 + 4 > ce then + return nil, "truncated SKINNING bones" + end + local bq = s + s += nb * 60 + local namesSize = readu32(b, s) + s += 4 + if s + namesSize + 4 > ce then + return nil, "truncated SKINNING names" + end + bones(b, bq, nb, readstring(b, s, namesSize), r) + s += namesSize + local nsub = readu32(b, s) + s += 4 + if s + nsub * 72 > ce then + return nil, "truncated SKINNING subsets" + end + subsets(b, s, nsub, r) + if nb == 0 then + r.env = nil + end + elseif name == "FACS" and cv == 1 then + if q + 4 > ce then + return nil, "truncated FACS" + end + local size = readu32(b, q) + if q + 4 + size > ce then + return nil, "truncated FACS" + end + local facs = buffer.create(size) + buffer.copy(facs, 0, b, q + 4, size) + r.facs, r.facsFormat = facs, 1 + else + local data = buffer.create(size) + buffer.copy(data, 0, b, q, size) + table.insert(r.chunks, { name = name, version = cv, data = data }) + end + p = ce + end + if not core then + return nil, "corrupt: no COREMESH chunk" + end + if #r.lods == 0 then + r.lods = { 0, r.numFaces } + end + return r, nil +end + +-- parse(b, p, e, lim) -> Record | nil, message +function Parse.parse(b: buffer, p: number, e: number, lim: Limits): (Record?, string?) + if e - p < 13 then + return nil, "truncated: no version line" + end + local line = readstring(b, p, 12) + local version = string.match(line, "^version (%d%.%d%d)$") + if not version or readu8(b, p + 12) ~= 10 and readu8(b, p + 12) ~= 13 then + return nil, "corrupt: bad version line" + end + local q = p + 13 + if readu8(b, p + 12) == 13 and q < e and readu8(b, q) == 10 then + q += 1 + end + local major = string.sub(version, 1, 1) + if major == "1" then + return ascii(readstring(b, p, e - p), version, lim) + elseif major == "2" or major == "3" or major == "4" or major == "5" then + return classic(b, q, e, version, lim) + elseif major == "6" or major == "7" then + return chunked(b, q, e, version, lim) + end + return nil, "unsupported: version " .. version +end + +-- tangent(tan, i) -> x, y, z, w of vertex i's packed tangent (signed bytes / 127) +local function snorm(v: number): number + local x = if v >= 128 then v - 256 else v + return math.clamp(x / 127, -1, 1) +end +function Parse.tangent(tan: buffer, i: number): (number, number, number, number) + return snorm(readu8(tan, i * 4)), snorm(readu8(tan, i * 4 + 1)), snorm(readu8(tan, i * 4 + 2)), snorm(readu8(tan, i * 4 + 3)) +end + +return Parse diff --git a/src/Formats/model/robloxmesh/Write.luau b/src/Formats/model/robloxmesh/Write.luau new file mode 100644 index 0000000..7b54c03 --- /dev/null +++ b/src/Formats/model/robloxmesh/Write.luau @@ -0,0 +1,109 @@ +--!strict +--!native +--!optimize 2 +-- model/robloxmesh/Write: a flat record (model/robloxmesh/Parse's shape) to a version 2.00 or 4.00 FileMesh. 2.00: +-- header, 36- or 40-byte vertices (40 when col is set), faces. 4.00: the 24-byte header, 40-byte vertices, skinning +-- (when there are bones), faces, LOD offsets, bones, the bone name table, subsets. Never throws. +local Parse = require("@formats/model/robloxmesh/Parse") +local Bytes = require("@formats/core/Bytes") + +local Write = {} + +local function vertex(w: Bytes.Writer, r: Parse.Record, i: number, colors: boolean) + local p = w:reserve(if colors then 40 else 36) + local b = w.buf + buffer.copy(b, p, r.pos, i * 12, 12) + buffer.copy(b, p + 12, r.nrm, i * 12, 12) + buffer.copy(b, p + 24, r.uv, i * 8, 8) + if r.tan then + buffer.copy(b, p + 32, r.tan, i * 4, 4) + else + buffer.writeu32(b, p + 32, 0x7F810000) -- (0, 0, -1, 1) + end + if colors then + if r.col then + buffer.copy(b, p + 36, r.col, i * 4, 4) + else + buffer.writeu32(b, p + 36, 0xFFFFFFFF) + end + end + w.pos = p + (if colors then 40 else 36) +end + +-- write(r, version) -> buffer ("2.00" | "4.00") +function Write.write(r: Parse.Record, version: string): buffer + local nv, nf = r.numVerts, r.numFaces + local w = Bytes.writer(64 + nv * 48 + nf * 12) + w:string("version " .. version .. "\n") + if version == "2.00" then + local colors = r.col ~= nil + w:u16le(12) + w:u8(if colors then 40 else 36) + w:u8(12) + w:u32le(nv) + w:u32le(nf) + for i = 0, nv - 1 do + vertex(w, r, i, colors) + end + w:bytes(r.faces, 0, nf * 12) + return w:finish() + end + -- 4.00 + local names = {} + local nameAt = {} + local size = 0 + for i, bone in r.bones do + nameAt[i] = size + table.insert(names, bone.name .. "\0") + size += #bone.name + 1 + end + local nb = #r.bones + w:u16le(24) + w:u16le(r.lodType) + w:u32le(nv) + w:u32le(nf) + w:u16le(#r.lods) + w:u16le(nb) + w:u32le(size) + w:u16le(#r.subsets) + w:u8(r.highQualityLods) + w:u8(0) + for i = 0, nv - 1 do + vertex(w, r, i, true) + end + if nb > 0 then + local env = r.env + if env then + w:bytes(env, 0, nv * 8) + else + w:fill(0, nv * 8) + end + end + w:bytes(r.faces, 0, nf * 12) + for _, o in r.lods do + w:u32le(o) + end + for i, bone in r.bones do + w:u32le(nameAt[i]) + w:u16le(if bone.parent then bone.parent else 0xFFFF) + w:u16le(bone.lodParent) + w:f32le(bone.culling) + for k = 1, 12 do + w:f32le(bone.cf[k] or 0) + end + end + w:string(table.concat(names)) + for _, s in r.subsets do + w:u32le(s.facesBegin) + w:u32le(s.facesLength) + w:u32le(s.vertsBegin) + w:u32le(s.vertsLength) + w:u32le(#s.bones) + for k = 1, 26 do + w:u16le(s.bones[k] or 0xFFFF) + end + end + return w:finish() +end + +return Write diff --git a/src/Formats/model/robloxmesh/init.luau b/src/Formats/model/robloxmesh/init.luau new file mode 100644 index 0000000..b3e1b70 --- /dev/null +++ b/src/Formats/model/robloxmesh/init.luau @@ -0,0 +1,578 @@ +--!strict +-- model/robloxmesh: the Roblox FileMesh (.mesh), read + write, mapped to a Scene. Written from MaximumADHD's "Roblox Mesh +-- Format" notes (devforum.roblox.com/t/roblox-mesh-format/326114); no port. +-- Decode: 1.00 / 1.01 (ASCII; 1.00 positions halved, V flipped), 2.00, 3.00 / 3.01 (LOD offsets), 4.00 / 4.01 (bones, +-- skinning, subsets), 5.00 (+ FACS), 6.00 / 7.00 chunked (COREMESH v1, LODS, SKINNING, FACS; HSRAVIS and unknown +-- chunks kept raw in meta.source.chunks). A Draco-compressed COREMESH (v2) is Err.UNSUPPORTED until codecs/model/Draco +-- exists. One mesh, one triangle primitive (LOD 0): POSITION, NORMAL, TEXCOORD_0 (f32), TANGENT (f32 x4 from the signed +-- bytes), COLOR_0 (unorm8 x4, when the vertices carry colours), u32 indices; the other LODs as primitives in +-- mesh.extras.lods (same attributes, their own indices). Bones become joint nodes (local matrices from the files' +-- world-space CFrames; extras.culling / lodParent) under one skin with inverse bind matrices; skinning becomes +-- JOINTS_0 (u16, global joint indices through the subsets) and WEIGHTS_0 (unorm8). FACS data is kept raw +-- (meta.source.facs). meta.up = "y"; units are studs. +-- Encode: version 2.00 (default; 40-byte vertices when a COLOR_0 is not all white) or 4.00 (opts.version), from every +-- primitive of the scene in world space (codecs/model/MeshFlatten; polygons / strips fan-triangulated). 4.00 writes +-- the scene's first skin as bones + skinning (subsets of at most 26 bones, vertices duplicated across subsets, up to +-- 4 influences, weights to bytes summing to 255) and LOD offsets (mesh.extras.lods of a single unskinned primitive). +-- Missing normals are computed (area weighted), missing tangents written as (0, 0, -1, 1). Not supported: writing +-- 3.00 / 5.00+ / FACS. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") +local Flatten = require("@formats/codecs/model/MeshFlatten") +local Parse = require("@formats/model/robloxmesh/Parse") +local Write = require("@formats/model/robloxmesh/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local RobloxMesh = { + name = "robloxmesh", + category = "model", + extensions = { "mesh" }, + mime = { "application/x-roblox-mesh" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten" }, + caps = { decode = true, encode = true, skinning = true, lods = true, versions = { "1.00", "1.01", "2.00", "3.00", "3.01", "4.00", "4.01", "5.00", "6.00", "7.00" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxVertices: number?, -- default 2^24 + maxFaces: number?, -- default 2^25 +} +export type EncodeOptions = { + version: ("2.00" | "4.00")?, -- default "2.00" +} + +-- ------------------------------------------------------------------------------------------------ constants +local readf32, writef32, readu8, writeu8, writeu16 = buffer.readf32, buffer.writef32, buffer.readu8, buffer.writeu8, buffer.writeu16 +local accessor = Types.Scene.accessor + +-- ------------------------------------------------------------------------------------------------ sniff +function RobloxMesh.sniff(r: Bytes.Reader): number + return if string.match(r:peek(13), "^version [1-7]%.%d%d[\r\n]") then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a bone's world matrix (column major) from its CFrame (r00 .. r22, x, y, z) +local function boneMatrix(cf: { number }): { number } + return { cf[1], cf[4], cf[7], 0, cf[2], cf[5], cf[8], 0, cf[3], cf[6], cf[9], 0, cf[10], cf[11], cf[12], 1 } +end + +local function indices(r: Parse.Record, from: number, to: number): Types.Accessor + local n = math.max(0, to - from) + local d = buffer.create(n * 12) + buffer.copy(d, 0, r.faces, from * 12, n * 12) + return accessor(d, "u32", 1, n * 3) +end + +function RobloxMesh.decode(rd: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local lim = { maxVertices = opts and opts.maxVertices or 2 ^ 24, maxFaces = opts and opts.maxFaces or 2 ^ 25 } + local r, msg = Parse.parse(rd.buf, rd.base, rd.limit, lim) + if not r then + return nil, Err.from(msg, rd.base) + end + local nv, nf = r.numVerts, r.numFaces + local attrs: { [string]: Types.Accessor } = { + POSITION = accessor(r.pos, "f32", 3, nv), + NORMAL = accessor(r.nrm, "f32", 3, nv), + TEXCOORD_0 = accessor(r.uv, "f32", 2, nv), + } + local tan = r.tan + if tan then + local t = buffer.create(nv * 16) + for i = 0, nv - 1 do + local x, y, z, w = Parse.tangent(tan, i) + writef32(t, i * 16, x) + writef32(t, i * 16 + 4, y) + writef32(t, i * 16 + 8, z) + writef32(t, i * 16 + 12, w) + end + attrs.TANGENT = accessor(t, "f32", 4, nv) + end + if r.col then + attrs.COLOR_0 = accessor(r.col, "unorm8", 4, nv) + end + -- LOD ranges (offsets clamped to the faces) + local offs = {} + for _, o in r.lods do + table.insert(offs, math.clamp(o, 0, nf)) + end + if #offs < 2 then + offs = { 0, nf } + end + local scene = Types.Scene.new() + local prim: Types.Primitive = { attributes = attrs, indices = indices(r, offs[1], offs[2]), mode = "triangles" } + local lods = {} + for k = 2, #offs - 1 do + table.insert(lods, { attributes = attrs, indices = indices(r, offs[k], offs[k + 1]), mode = "triangles" }) + end + local mesh: Types.Mesh = { name = "Mesh", primitives = { prim } } + if #lods > 0 then + mesh.extras = { lods = lods } + end + scene.meshes[1] = mesh + scene.nodes[1] = { name = "Mesh", children = {}, mesh = 1 } + scene.roots[1] = 1 + -- bones and skinning + local nb = #r.bones + if nb > 0 then + local world: { { number } } = table.create(nb) :: any + for i, bone in r.bones do + world[i] = boneMatrix(bone.cf) + end + local joints = table.create(nb, 0) + local ibm = buffer.create(nb * 64) + for i, bone in r.bones do + local parent = if bone.parent and bone.parent < nb and bone.parent ~= i - 1 then bone.parent + 1 else nil + local m = world[i] + if parent then + local inv = Mat4.inverse(world[parent]) + if inv then + m = Mat4.mul(inv, m) + end + end + local node: Types.Node = { name = bone.name, children = {}, matrix = m, extras = { culling = bone.culling, lodParent = bone.lodParent } } + table.insert(scene.nodes, node) + joints[i] = #scene.nodes + local inv = Mat4.inverse(world[i]) or Mat4.identity() + for k = 1, 16 do + writef32(ibm, (i - 1) * 64 + (k - 1) * 4, inv[k]) + end + end + for i, bone in r.bones do + local parent = if bone.parent and bone.parent < nb and bone.parent ~= i - 1 then bone.parent + 1 else nil + if parent then + table.insert(scene.nodes[joints[parent]].children, joints[i]) + else + table.insert(scene.roots, joints[i]) + end + end + scene.skins[1] = { joints = joints, inverseBindMatrices = accessor(ibm, "f32", 16, nb) } + scene.nodes[1].skin = 1 + local env = r.env + if env then + local jb, wb = buffer.create(nv * 8), buffer.create(nv * 4) + for i = 0, nv - 1 do + for k = 0, 3 do + writeu8(wb, i * 4 + k, readu8(env, i * 8 + 4 + k)) + end + end + for _, s in r.subsets do + local last = math.min(s.vertsBegin + s.vertsLength, nv) - 1 + for v = s.vertsBegin, last do + for k = 0, 3 do + local li = readu8(env, v * 8 + k) + local g = s.bones[li + 1] + writeu16(jb, v * 8 + k * 2, if g and g < nb and readu8(wb, v * 4 + k) > 0 then g else 0) + end + end + end + attrs.JOINTS_0 = accessor(jb, "u16", 4, nv) + attrs.WEIGHTS_0 = accessor(wb, "unorm8", 4, nv) + end + end + local subsets = {} + for _, s in r.subsets do + table.insert(subsets, { facesBegin = s.facesBegin, facesLength = s.facesLength, vertsBegin = s.vertsBegin, vertsLength = s.vertsLength, bones = s.bones }) + end + scene.meta.up = "y" + scene.meta.source = { + format = "robloxmesh", + version = r.version, + lodType = r.lodType, + highQualityLods = r.highQualityLods, + lodOffsets = r.lods, + subsets = subsets, + facsFormat = r.facsFormat, + facs = r.facs, + chunks = r.chunks, + } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function num(attr: any, i: number, c: number, default: number): number + if not attr or c >= attr.components then + return default + end + return attr.values[i * attr.components + c + 1] +end + +-- area-weighted vertex normals +local function normals(pos: buffer, nv: number, corners: { number }): buffer + local acc = table.create(nv * 3, 0) + for f = 0, #corners // 3 - 1 do + local a, b, c = corners[f * 3 + 1], corners[f * 3 + 2], corners[f * 3 + 3] + local ax, ay, az = readf32(pos, a * 12), readf32(pos, a * 12 + 4), readf32(pos, a * 12 + 8) + local ux, uy, uz = readf32(pos, b * 12) - ax, readf32(pos, b * 12 + 4) - ay, readf32(pos, b * 12 + 8) - az + local vx, vy, vz = readf32(pos, c * 12) - ax, readf32(pos, c * 12 + 4) - ay, readf32(pos, c * 12 + 8) - az + local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + for _, v in { a, b, c } do + acc[v * 3 + 1] += nx + acc[v * 3 + 2] += ny + acc[v * 3 + 3] += nz + end + end + local out = buffer.create(nv * 12) + for v = 0, nv - 1 do + local x, y, z = acc[v * 3 + 1], acc[v * 3 + 2], acc[v * 3 + 3] + local l = math.sqrt(x * x + y * y + z * z) + if l > 0 then + writef32(out, v * 12, x / l) + writef32(out, v * 12 + 4, y / l) + writef32(out, v * 12 + 8, z / l) + else + writef32(out, v * 12 + 4, 1) + end + end + return out +end + +-- world matrices of every node (parents through children lists) +local function worlds(scene: any): { [number]: { number } } + local out: { [number]: { number } } = {} + local parent: { [number]: number } = {} + for i, n in scene.nodes do + for _, c in n.children or {} do + parent[c] = i + end + end + local function world(i: number, depth: number): { number } + if out[i] then + return out[i] + end + local m = Types.Scene.nodeMatrix(scene.nodes[i]) + local p = parent[i] + if p and depth < 256 then + m = Mat4.mul(world(p, depth + 1), m) + end + out[i] = m + return m + end + for i in scene.nodes do + world(i, 0) + end + return out +end + +-- the bones of a skin: Parse.Bone list, or nil, message +local function skinBones(scene: any, skin: any): ({ Parse.Bone }?, string?) + local joints = skin.joints + if type(joints) ~= "table" or #joints == 0 then + return nil, "a skin without joints" + end + if #joints > 65534 then + return nil, "too many joints" + end + local w = worlds(scene) + local index: { [number]: number } = {} + for i, j in joints do + index[j] = i - 1 + end + local parentOf: { [number]: number } = {} + for i, n in scene.nodes do + for _, c in n.children or {} do + parentOf[c] = i + end + end + local ibm = skin.inverseBindMatrices and Flatten.numbers(skin.inverseBindMatrices) + local out = {} + for i, j in joints do + local node = scene.nodes[j] + if not node then + return nil, "a joint names a missing node" + end + local m = w[j] + if ibm and #ibm >= i * 16 then + local inv = Mat4.inverse(table.move(ibm, (i - 1) * 16 + 1, i * 16, 1, table.create(16, 0))) + if inv then + m = inv + end + end + local ex = if type(node.extras) == "table" then node.extras else {} + local p = parentOf[j] + out[i] = { + name = if type(node.name) == "string" then node.name else "Bone" .. i, + parent = if p then index[p] else nil, + lodParent = if type(ex.lodParent) == "number" then ex.lodParent else 0xFFFF, + culling = if type(ex.culling) == "number" then ex.culling else 0, + cf = { m[1], m[5], m[9], m[2], m[6], m[10], m[3], m[7], m[11], m[13], m[14], m[15] }, + } + end + return out, nil +end + +-- the vertex arrays of the record from merged attributes, for the vertices `order` (new index -> merged index) +local function fill(r: Parse.Record, m: any, order: { number }, nrm: buffer?) + local nv = #order + local pos, nb, uv, tan = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(nv * 4) + local P, N, U, T, C = m.attrs.POSITION, m.attrs.NORMAL, m.attrs.TEXCOORD_0, m.attrs.TANGENT, m.attrs.COLOR_0 + local col = nil + if C then + local scale = if C.raw then 1 else 255 + local white = true + col = buffer.create(nv * 4) + for i, src in order do + for k = 0, 3 do + local v = math.clamp(math.floor(num(C, src, k, if C.raw then 255 else 1) * scale + 0.5), 0, 255) + writeu8(col, (i - 1) * 4 + k, v) + if v ~= 255 then + white = false + end + end + end + if white then + col = nil + end + end + for i, src in order do + local o = i - 1 + for k = 0, 2 do + writef32(pos, o * 12 + k * 4, num(P, src, k, 0)) + end + if N then + for k = 0, 2 do + writef32(nb, o * 12 + k * 4, num(N, src, k, 0)) + end + elseif nrm then + buffer.copy(nb, o * 12, nrm, src * 12, 12) + end + writef32(uv, o * 8, num(U, src, 0, 0)) + writef32(uv, o * 8 + 4, num(U, src, 1, 0)) + if T then + for k = 0, 3 do + local v = math.clamp(math.floor(num(T, src, k, if k == 3 then 1 else 0) * 127 + 0.5), -127, 127) + writeu8(tan, o * 4 + k, v % 256) + end + else + buffer.writeu32(tan, o * 4, 0x7F810000) + end + end + r.pos, r.nrm, r.uv, r.tan, r.col, r.numVerts = pos, nb, uv, tan, col, nv +end + +function RobloxMesh.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + local version = opts and opts.version or "2.00" + if version ~= "2.00" and version ~= "4.00" then + return nil, Err.new(Err.ARG, "version must be \"2.00\" or \"4.00\"") + end + if type(scene) ~= "table" or type(scene.meshes) ~= "table" then + return nil, Err.new(Err.ARG, "expected a Scene") + end + local keep = { NORMAL = true, TEXCOORD_0 = true, TANGENT = true, COLOR_0 = true, JOINTS_0 = true, WEIGHTS_0 = true } + local m, merr = Flatten.merge(scene, function(name: string): boolean + return keep[name] == true + end, { triangulate = true }) + if not m then + return nil, Err.new(Err.ARG, tostring(merr)) + end + local corners = m.corners + if not m.sizes or #corners == 0 then + return nil, Err.new(Err.ARG, "no triangles to write") + end + local nv0 = m.count + if nv0 > 2 ^ 32 - 1 then + return nil, Err.new(Err.LIMIT, "too many vertices") + end + local r: Parse.Record = { + version = version, + numVerts = 0, + numFaces = #corners // 3, + pos = buffer.create(0), + nrm = buffer.create(0), + uv = buffer.create(0), + faces = buffer.create(0), + lods = {}, + lodType = 0, + highQualityLods = 0, + bones = {}, + subsets = {}, + facsFormat = 0, + chunks = {}, + } + local src = if type(scene.meta) == "table" and type(scene.meta.source) == "table" and scene.meta.source.format == "robloxmesh" then scene.meta.source else nil + if src and type(src.lodType) == "number" then + r.lodType, r.highQualityLods = src.lodType, if type(src.highQualityLods) == "number" then src.highQualityLods else 0 + end + -- normals when the scene has none + local nrm: buffer? = nil + if not m.attrs.NORMAL then + local pb = buffer.create(nv0 * 12) + for i = 0, nv0 - 1 do + for k = 0, 2 do + writef32(pb, i * 12 + k * 4, num(m.attrs.POSITION, i, k, 0)) + end + end + nrm = normals(pb, nv0, corners) + end + -- the skin (4.00): the first node with a mesh and a skin + local skin = nil + if version == "4.00" and m.attrs.JOINTS_0 and m.attrs.WEIGHTS_0 then + for _, n in scene.nodes or {} do + if n.mesh and n.skin and scene.skins and scene.skins[n.skin] then + skin = scene.skins[n.skin] + break + end + end + end + local nf = #corners // 3 + if skin then + local bones, berr = skinBones(scene, skin) + if not bones then + return nil, Err.new(Err.ARG, berr or "bad skin") + end + r.bones = bones + local J, W = m.attrs.JOINTS_0, m.attrs.WEIGHTS_0 + local wscale = if W.raw then 1 / 255 else 1 + local nb = #bones + -- per vertex: up to 4 (joint, weight) pairs with weight > 0 + local influences: { { { number } } } = table.create(nv0) :: any + for v = 0, nv0 - 1 do + local list = {} + for k = 0, 3 do + local wt = num(W, v, k, 0) * wscale + local j = num(J, v, k, 0) + if wt > 0 and j >= 0 and j < nb then + table.insert(list, { j, wt }) + end + end + influences[v + 1] = list + end + -- subsets: faces in order, a new subset when a face's joints do not fit in 26 + local faceIdx = buffer.create(nf * 12) + local order: { number } = {} + local s: any = nil + local function close() + if s then + table.insert(r.subsets, { facesBegin = s.facesBegin, facesLength = s.faceCount, vertsBegin = s.vertsBegin, vertsLength = #order - s.vertsBegin, bones = s.bones }) + end + end + local function open(f: number) + s = { facesBegin = f, faceCount = 0, vertsBegin = #order, bones = {}, local_ = {}, remap = {} } + end + open(0) + for f = 0, nf - 1 do + local need = {} + local extra = 0 + for c = 1, 3 do + for _, inf in influences[corners[f * 3 + c] + 1] do + if s.local_[inf[1]] == nil and not need[inf[1]] then + need[inf[1]] = true + extra += 1 + end + end + end + if #s.bones + extra > 26 then + close() + open(f) + for c = 1, 3 do + for _, inf in influences[corners[f * 3 + c] + 1] do + need[inf[1]] = true + end + end + end + for j in need do + if s.local_[j] == nil then + table.insert(s.bones, j) + s.local_[j] = #s.bones - 1 + end + end + for c = 1, 3 do + local v = corners[f * 3 + c] + local nvx = s.remap[v] + if not nvx then + table.insert(order, v) + nvx = #order - 1 + s.remap[v] = nvx + end + buffer.writeu32(faceIdx, f * 12 + (c - 1) * 4, nvx) + end + s.faceCount += 1 + end + close() + r.faces = faceIdx + fill(r, m, order, nrm) + -- envelopes: subset-local bone indices, weights summing to 255 + local env = buffer.create(#order * 8) + for _, sub in r.subsets do + local loc: { [number]: number } = {} + for i, j in sub.bones do + loc[j] = i - 1 + end + for o = sub.vertsBegin, sub.vertsBegin + sub.vertsLength - 1 do + local list = influences[order[o + 1] + 1] + local total = 0 + for _, inf in list do + total += inf[2] + end + local bytes, sum, best = {}, 0, 1 + for k, inf in list do + local b = if total > 0 then math.floor(inf[2] / total * 255 + 0.5) else 0 + bytes[k] = b + sum += b + if inf[2] > list[best][2] then + best = k + end + end + if #list > 0 then + bytes[best] += 255 - sum + end + for k = 0, 3 do + local inf = list[k + 1] + writeu8(env, o * 8 + k, if inf then loc[inf[1]] or 0 else 0) + writeu8(env, o * 8 + 4 + k, if inf then math.clamp(bytes[k + 1], 0, 255) else 0) + end + end + end + r.env = env + r.lods = { 0, nf } + else + local order = table.create(nv0, 0) + for i = 1, nv0 do + order[i] = i - 1 + end + fill(r, m, order, nrm) + local faces = buffer.create(nf * 12) + for i, c in corners do + buffer.writeu32(faces, (i - 1) * 4, c) + end + r.faces = faces + r.lods = { 0, nf } + -- extra LODs of a single untransformed primitive + local part = m.parts[1] + local mesh = part and part.mesh + local lods = if #m.parts == 1 and part.identity and mesh and type(mesh.extras) == "table" then mesh.extras.lods else nil + if version == "4.00" and type(lods) == "table" and #lods > 0 then + local list = {} + for _, lp in lods do + local idx = if type(lp) == "table" and lp.indices then Flatten.numbers(lp.indices) else nil + if idx and #idx % 3 == 0 then + table.insert(list, idx) + end + end + local total = nf + for _, idx in list do + total += #idx // 3 + end + local all = buffer.create(total * 12) + buffer.copy(all, 0, faces, 0, nf * 12) + local at = nf + for _, idx in list do + for i, c in idx do + if c >= nv0 then + return nil, Err.new(Err.ARG, "a LOD index is out of range") + end + buffer.writeu32(all, at * 12 + (i - 1) * 4, c) + end + at += #idx // 3 + table.insert(r.lods, at) + end + r.faces, r.numFaces = all, total + end + end + return Write.write(r, version), nil +end + +return RobloxMesh diff --git a/tests/model/rbxm.luau b/tests/model/rbxm.luau index 70276df..e7deadc 100644 --- a/tests/model/rbxm.luau +++ b/tests/model/rbxm.luau @@ -240,6 +240,23 @@ do t:check(e8 and e8.code == Err.CORRUPT, "a cycle: " .. tostring(e8)) end +-- through the api: detection (variant: rbxl for places), load, save, convert +do + local F = require("@formats") + t:eq(F.detect(file("place.rbxl").data), "rbxl", "detect a place") + t:eq(F.detect(file("model.rbxm").data), "rbxm", "detect a model") + t:eq(F.detect(file("place.rbxlx").data), "rbxlx", "detect an XML place") + t:eq(F.detect(file("model.rbxmx").data), "rbxmx", "detect an XML model") + local tree = F.load(file("model.rbxm").data) + t:check(tree and tree.kind == "rbxtree", "F.load") + local again = F.save(tree) + t:check(type(again) == "buffer" and Rbxm.sniff(Bytes.reader(again)) == 1, "F.save keeps the source format") + local x = F.convert(file("model.rbxm").data, "rbxmx") + t:check(type(x) == "buffer" and Rbxmx.sniff(Bytes.reader(x)) == 1, "F.convert to rbxmx") + local l = F.save(tree, nil, { format = "rbxl" }) + t:eq(F.detect(l), "rbxl", "save as rbxl marks services") +end + -- fuzz do local samples = { file("model-raw.rbxm").data, Rbxm.encode(H.everything(), { compression = "none" }) :: buffer, Rbxm.encode(H.everything()) :: buffer } diff --git a/tests/model/robloxmesh.luau b/tests/model/robloxmesh.luau new file mode 100644 index 0000000..9d2da02 --- /dev/null +++ b/tests/model/robloxmesh.luau @@ -0,0 +1,202 @@ +-- model/robloxmesh tests: meshes of every version written by the fixture's spec writer (1.00 / 1.01 ASCII, 2.00 with +-- 36- and 40-byte vertices, 3.00 / 3.01 LODs, 4.00 / 4.01 / 5.00 skinned with one and several subsets, 5.00 FACS, +-- 6.00 / 7.00 chunked) decode to the values they were written from (attribute CRCs, LOD index CRCs, global joints and +-- weights, bone names / parents / world transforms, FACS, raw chunks); a Draco COREMESH is UNSUPPORTED; our 2.00 / +-- 4.00 output read back by the fixture's reader (verdicts); round trips; errors and the fuzz pass. +-- Fixtures: tools/fixtures/robloxmesh.py. +local T = require("@tests/T") +local RobloxMesh = require("@formats/model/robloxmesh") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") +local Fx = require("@tests/gen/robloxmesh") + +local t = T.suite("robloxmesh") + +t:eq(RobloxMesh.name, "robloxmesh", "name") +t:eq(RobloxMesh.category, "model", "category") +t:check(table.find(RobloxMesh.extensions, "mesh") ~= nil, "extensions") +t:check(RobloxMesh.caps.decode and RobloxMesh.caps.encode, "caps") + +local function decode(data: any, opts: any?): (any, any) + return RobloxMesh.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts) +end + +-- a world matrix of node i (parents through the children lists) +local function world(scene: any, i: number): { number } + local parent = {} + for k, n in scene.nodes do + for _, c in n.children do + parent[c] = k + end + end + local m = Types.Scene.nodeMatrix(scene.nodes[i]) + local p = parent[i] + while p do + m = Mat4.mul(Types.Scene.nodeMatrix(scene.nodes[p]), m) + p = parent[p] + end + return m +end + +local ncases = 0 +for _, c in Fx.cases do + local scene, err = decode(c.data) + if c.unsupported then + t:check(scene == nil and err and err.code == Err.UNSUPPORTED, c.name .. ": unsupported (" .. tostring(err) .. ")") + continue + end + t:check(scene ~= nil, c.name .. ": " .. tostring(err)) + if not scene then + continue + end + ncases += 1 + local prim = scene.meshes[1].primitives[1] + local a = prim.attributes + t:eq(scene.meta.source.version, c.version, c.name .. ": version") + t:eq(a.POSITION.count, c.vertices, c.name .. ": vertices") + t:eq(Crc32.of(a.POSITION.data), c.pos, c.name .. ": POSITION") + t:eq(Crc32.of(a.NORMAL.data), c.nrm, c.name .. ": NORMAL") + t:eq(Crc32.of(a.TEXCOORD_0.data), c.uv, c.name .. ": TEXCOORD_0") + if c.tan then + t:check(a.TANGENT and Crc32.of(a.TANGENT.data) == c.tan, c.name .. ": TANGENT") + end + if c.col then + t:check(a.COLOR_0 and a.COLOR_0.type == "unorm8" and Crc32.of(a.COLOR_0.data) == c.col, c.name .. ": COLOR_0") + else + t:check(a.COLOR_0 == nil, c.name .. ": no COLOR_0") + end + local lods = { prim } + for _, l in (scene.meshes[1].extras or {}).lods or {} do + table.insert(lods, l) + end + t:eq(#lods, #c.lods, c.name .. ": LODs") + for k, want in c.lods do + t:check(lods[k] and Crc32.of(lods[k].indices.data) == want, c.name .. ": LOD " .. (k - 1) .. " indices") + end + if c.joints then + t:check(a.JOINTS_0 and Crc32.of(a.JOINTS_0.data) == c.joints, c.name .. ": JOINTS_0") + t:check(a.WEIGHTS_0 and Crc32.of(a.WEIGHTS_0.data) == c.weights, c.name .. ": WEIGHTS_0") + local skin = scene.skins[1] + t:eq(#skin.joints, #c.bones, c.name .. ": joints") + t:eq(skin.inverseBindMatrices.count, #c.bones, c.name .. ": inverse bind matrices") + t:eq(scene.nodes[1].skin, 1, c.name .. ": the mesh node is skinned") + local worst = 0 + for i, b in c.bones do + local j = skin.joints[i] + local node = scene.nodes[j] + t:eq(node.name, b.name, c.name .. ": bone name") + t:eq(node.extras.culling, b.culling, c.name .. ": culling") + local isRoot = table.find(scene.roots, j) ~= nil + t:eq(isRoot, b.parent == nil, c.name .. ": " .. b.name .. " root") + if b.parent then + t:check(table.find(scene.nodes[skin.joints[b.parent + 1]].children, j) ~= nil, c.name .. ": " .. b.name .. " parent") + end + local m = world(scene, j) + local cf = b.cf + local want = { cf[1], cf[4], cf[7], 0, cf[2], cf[5], cf[8], 0, cf[3], cf[6], cf[9], 0, cf[10], cf[11], cf[12], 1 } + for k = 1, 16 do + worst = math.max(worst, math.abs(m[k] - want[k])) + end + end + t:check(worst < 1e-4, c.name .. ": bone world transforms (" .. worst .. ")") + end + if c.facs then + t:check(scene.meta.source.facs and Crc32.of(scene.meta.source.facs) == c.facs, c.name .. ": FACS kept raw") + end + if c.chunks then + t:eq(scene.meta.source.chunks[1].name, c.chunks[1], c.name .. ": raw chunk") + end + t:eq(scene.meta.up, "y", c.name .. ": up") +end +t:note("%d meshes match", ncases) + +for _, v in Fx.ours do + t:check(v.ok, v.name .. ": " .. v.detail) +end +t:note("%d of our files read back by the fixture's reader", #Fx.ours) + +-- round trips through our encoder +do + for _, name in { "v2.00-40", "v4.00-lods", "v4.00-40bones", "v6.00" } do + local c + for _, x in Fx.cases do + if x.name == name then + c = x + end + end + local s = decode(c.data) + local out = RobloxMesh.encode(s, { version = "4.00" }) :: buffer + local back = decode(out) + t:check(back ~= nil, name .. ": re-read") + local p0, p1 = s.meshes[1].primitives[1], back.meshes[1].primitives[1] + t:eq(p1.indices.count, p0.indices.count, name .. ": triangles") + if not c.joints then + t:eq(Crc32.of(p1.attributes.POSITION.data), Crc32.of(p0.attributes.POSITION.data), name .. ": positions") + t:eq(Crc32.of(p1.indices.data), Crc32.of(p0.indices.data), name .. ": indices") + t:eq(Crc32.of(p1.attributes.TANGENT.data), Crc32.of(p0.attributes.TANGENT.data), name .. ": tangents") + else + t:eq(#back.skins[1].joints, #s.skins[1].joints, name .. ": joints") + end + local v2 = decode(RobloxMesh.encode(s) :: buffer) + t:eq(v2.meta.source.version, "2.00", name .. ": 2.00 by default") + end + -- a glTF-style scene: a quad under a transformed node, no normals / colours + local s = Types.Scene.new() + local pos = buffer.create(48) + for i, v in { 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0 } do + buffer.writef32(pos, (i - 1) * 4, v) + end + local idx = buffer.create(24) + for i, v in { 0, 1, 2, 0, 2, 3 } do + buffer.writeu32(idx, (i - 1) * 4, v) + end + s.meshes[1] = { primitives = { { attributes = { POSITION = Types.Scene.accessor(pos, "f32", 3, 4) }, indices = Types.Scene.accessor(idx, "u32", 1, 6), mode = "triangles" } } } + s.nodes[1] = { children = {}, mesh = 1, translation = { 10, 0, 0 } } + s.roots[1] = 1 + local q = decode(RobloxMesh.encode(s) :: buffer) + local qa = q.meshes[1].primitives[1].attributes + t:eq(buffer.readf32(qa.POSITION.data, 12), 11, "node transform applied") + t:eq(buffer.readf32(qa.NORMAL.data, 8), 1, "computed normal +Z") + t:check(qa.COLOR_0 == nil, "white / no colours: 36-byte vertices") +end + +-- sniff, errors +do + local c = Fx.cases[3] + t:eq(RobloxMesh.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, "sniff") + t:eq(RobloxMesh.sniff(Bytes.reader(buffer.fromstring("version 1.0"))), 0, "sniff short") + t:eq(RobloxMesh.sniff(Bytes.reader(buffer.fromstring("solid cube\n"))), 0, "sniff STL") + local _, e1 = decode("version 9.00\n") + t:check(e1 and e1.code == Err.UNSUPPORTED, "version 9: " .. tostring(e1)) + local _, e2 = decode(string.sub(c.data, 1, 60)) + t:check(e2 and e2.code == Err.TRUNCATED, "truncated: " .. tostring(e2)) + local _, e3 = decode(c.data, { maxVertices = 10 }) + t:check(e3 and e3.code == Err.LIMIT, "maxVertices: " .. tostring(e3)) + local bad = buffer.fromstring(c.data) + buffer.writeu32(bad, buffer.len(bad) - 4, 99999) + local _, e4 = decode(bad) + t:check(e4 and e4.code == Err.CORRUPT, "face index out of range: " .. tostring(e4)) + local _, e5 = decode("hello there, a mesh") + t:check(e5 and e5.code == Err.CORRUPT, "no version line: " .. tostring(e5)) + local _, e6 = RobloxMesh.encode(Types.Scene.new()) + t:check(e6 and e6.code == Err.ARG, "an empty scene: " .. tostring(e6)) + local _, e7 = RobloxMesh.encode(decode(c.data), { version = "3.00" } :: any) + t:check(e7 and e7.code == Err.ARG, "version 3.00 is not written") +end + +do + local samples = {} + for _, c in Fx.cases do + if #c.data < 40000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + return RobloxMesh.decode(Bytes.reader(b)) + end, samples, { mutations = 30, garbage = 300, keepHeader = 13 }) +end + +t:done() diff --git a/tools/fixtures/_robloxmesh_encode.luau b/tools/fixtures/_robloxmesh_encode.luau new file mode 100644 index 0000000..99b4ae3 --- /dev/null +++ b/tools/fixtures/_robloxmesh_encode.luau @@ -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 "/ " 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 diff --git a/tools/fixtures/robloxmesh.py b/tools/fixtures/robloxmesh.py new file mode 100644 index 0000000..a404222 --- /dev/null +++ b/tools/fixtures/robloxmesh.py @@ -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("= 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("= 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(" 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(" Date: Sat, 31 Oct 2026 14:37:39 -0500 Subject: [PATCH 14/27] video/smk: Smacker (SMK2 / SMK4) with its video codec and audio containers into containers/Demux (palette updates ride on each video packet as packet.palette); the Smacker video codec (header Huffman trees with the escape cache, MONO / FULL (+ SMK4 doubled modes) / SKIP / FILL blocks) lives in codecs/video/Legacy/Smacker and registers as 'smackvid'; Smacker's packed DPCM-Huffman audio (8 / 16-bit, mono / stereo) and raw PCM tracks decode in video/smk/Audio, the Decoder built by the format over codecs/audio/Stream (Smk.openAudio; open() installs it as the openAudio hook). Fixtures encoded by tools/fixtures/smk.py: video and audio bit-exact with ffmpeg. --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/codecs/video/Legacy/Smacker.luau | 363 ++++++++++++++ src/Formats/codecs/video/Legacy/init.luau | 33 +- src/Formats/video/smk/Audio.luau | 123 +++++ src/Formats/video/smk/init.luau | 320 ++++++++++++ tests/video/smk.luau | 180 +++++++ tools/fixtures/smk.py | 493 +++++++++++++++++++ 8 files changed, 1522 insertions(+), 3 deletions(-) create mode 100644 src/Formats/codecs/video/Legacy/Smacker.luau create mode 100644 src/Formats/video/smk/Audio.luau create mode 100644 src/Formats/video/smk/init.luau create mode 100644 tests/video/smk.luau create mode 100644 tools/fixtures/smk.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 13d1e91..8b27918 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -34,6 +34,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | video | mp4 | .mp4 .m4v .mov .qt .3gp .3g2 .mj2 | yes | yes | streaming: true, remux: true, video: "mjpeg", "mpeg1", "h264", audio: true, fragments: true | `tests/video/mp4.luau` | | video | mpegps | .mpg .mpeg .vob .m1v .mpv .dat | yes | - | streaming: true, video: "mpeg1", audio: true | `tests/video/mpegps.luau` | | video | mpegts | .ts .m2ts .mts .tsv | yes | - | streaming: true, video: "mpeg1", "h264", audio: true | `tests/video/mpegts.luau` | +| video | smk | .smk | yes | - | streaming: true, video: "smackvid", audio: "smackaudio", "pcm_u8", "pcm_s16le" | `tests/video/smk.luau` | | video | y4m | .y4m | yes | yes | streaming: true, video: "rawvideo", depths: 8, 10, 12, 16 | `tests/video/y4m.luau` | | model | 3mf | .3mf | yes | yes | materials: true, vertexColors: true, textures: true, units: true | `tests/model/3mf.luau` | | model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index d26e1e1..ad48ba9 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -362,6 +362,18 @@ local list: { Entry } = { return require("@formats/video/mpegts") end, }, + { + name = "smk", + category = "video", + path = "video/smk", + extensions = { "smk" }, + mime = { "video/vnd.radgamettools.smacker" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/audio/Stream", "codecs/video/Legacy/Smacker" }, + caps = { decode = true, encode = false, streaming = true, video = { "smackvid" }, audio = { "smackaudio", "pcm_u8", "pcm_s16le" } }, + load = function() + return require("@formats/video/smk") + end, + }, { name = "y4m", category = "video", diff --git a/src/Formats/codecs/video/Legacy/Smacker.luau b/src/Formats/codecs/video/Legacy/Smacker.luau new file mode 100644 index 0000000..c5923ec --- /dev/null +++ b/src/Formats/codecs/video/Legacy/Smacker.luau @@ -0,0 +1,363 @@ +--!strict +--!native +--!optimize 2 +-- codecs/video/Legacy/Smacker: RAD Game Tools' Smacker video (SMK2 / SMK4 frames; the file format is video/smk) and +-- the Huffman trees Smacker audio shares. Written from the format description (MultimediaWiki "Smacker"). Bits are +-- read LSB first. A tree is a pre-order bit string (1 = node: left subtree then right; 0 = leaf with its value); +-- an 8-bit tree's leaves hold bytes, a "big" tree's leaves hold 16-bit values made of a low-byte and a high-byte +-- 8-bit tree, three of them being escape leaves that return the three most recently decoded values instead (a +-- per-frame cache, reset to 0 at each frame). The four big trees (MMAP, MCLR, FULL, TYPE) come from the file header; +-- a frame is 4x4 blocks in raster order, each TYPE code giving a block type and a run length: MONO (two colours and a +-- 16-bit mask), FULL (16 pixels as 8 codes; SMK4 adds a 2x2-doubled and a 2x1-doubled mode), SKIP, FILL (one colour). +-- Trees are flat arrays (a node stores the size of its left subtree, as a negative number) walked bit by bit. +-- Bit-exact with ffmpeg's smackvid decoder. Never throws: trees are bounded (depth, entries), reads past the data give +-- zero bits, a frame whose codes run out of bits gives no picture. +local Picture = require("@formats/codecs/video/Legacy/Picture") + +local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32 +local band, rshift = bit32.band, bit32.rshift + +local Smacker = {} + +local MAX_DEPTH8 = 27 -- 8-bit trees (3 x 9-bit lookups in the reference decoder) +local MAX_DEPTH16 = 500 + +-- block runs (TYPE code bits 2..7) +local RUNS = table.create(64, 0) +for i = 1, 59 do + RUNS[i] = i +end +RUNS[60], RUNS[61], RUNS[62], RUNS[63], RUNS[64] = 128, 256, 512, 1024, 2048 + +-- a bit position over buf[0, nbits / 8) +export type Bits = { buf: buffer, pos: number, nbits: number } + +function Smacker.bits(buf: buffer, offset: number, length: number): Bits + return { buf = buf, pos = offset * 8, nbits = (offset + length) * 8 } +end + +local function bit(br: Bits): number + local p = br.pos + br.pos = p + 1 + if p >= br.nbits then + return 0 + end + return band(rshift(readu8(br.buf, rshift(p, 3)), band(p, 7)), 1) +end +Smacker.bit = bit + +-- read(br, n) -> n bits (LSB first; zeros past the end) +function Smacker.read(br: Bits, n: number): number + local v, m = 0, 1 + for _ = 1, n do + v += bit(br) * m + m *= 2 + end + return v +end +local readBits = Smacker.read + +-- walk(tree, br) -> the leaf value (no end-of-data check: 8-bit trees, as the reference's table lookups) +local function walk(tree: { number }, br: Bits): number + local i = 1 + local e = tree[1] + while e < 0 do + if bit(br) == 1 then + i += -e - 1 + end + i += 1 + e = tree[i] + end + return e +end +Smacker.walk = walk + +-- the pre-order tree reader: leaf(index) -> value | nil, message; returns the flat tree (1-based) +local function build(br: Bits, maxDepth: number, maxEntries: number, leaf: (number) -> (number?, string?), bigChecks: boolean): ({ number }?, string?) + local vals: { number } = {} + local n = 0 + local stack: { number } = {} + local state: { number } = {} + local sp = 0 + while true do + if sp > maxDepth then + return nil, "tree too deep" + end + if n >= maxEntries then + return nil, "tree too big" + end + if bigChecks and br.pos >= br.nbits then + return nil, "truncated tree" + end + if bit(br) == 1 then + n += 1 + vals[n] = -1 + sp += 1 + stack[sp], state[sp] = n, 0 + else + local v, msg = leaf(n) + if not v then + return nil, msg + end + n += 1 + vals[n] = v + local more = false + while sp > 0 do + if state[sp] == 0 then + local at = stack[sp] + vals[at] = -(n - at) - 1 -- the left subtree holds n - at entries + state[sp] = 1 + more = true + break + end + sp -= 1 + end + if not more then + return vals, nil + end + end + end +end + +-- tree8(br) -> an 8-bit tree (leaves are bytes) | nil, message +function Smacker.tree8(br: Bits): ({ number }?, string?) + local leaves = 0 + return build(br, MAX_DEPTH8, 511, function(_: number): (number?, string?) + if leaves >= 256 then + return nil, "tree too big" + end + leaves += 1 + if br.nbits - br.pos < 8 then + return nil, "truncated tree" + end + return readBits(br, 8), nil + end, false) +end +local tree8 = Smacker.tree8 + +export type BigTree = { vals: { number }, last: { number } } -- last: the escape leaves' indexes (1-based) + +-- bigTree(br, size) -> one of the header's trees | nil, message (size = its byte size from the header: bounds entries) +local function bigTree(br: Bits, size: number): (BigTree?, string?) + if bit(br) == 0 then + return { vals = { 0, 0 }, last = { 2, 2, 2 } }, nil -- no tree: every code is 0 + end + local lohi: { { number } } = {} + for k = 1, 2 do + if bit(br) == 0 then + lohi[k] = { 0 } + else + local t, msg = tree8(br) + if not t then + return nil, msg + end + bit(br) + lohi[k] = t + end + end + local esc = { readBits(br, 16), readBits(br, 16), readBits(br, 16) } + local last = { -1, -1, -1 } + local lo, hi = lohi[1], lohi[2] + local vals, msg = build(br, MAX_DEPTH16, (size + 3) // 4, function(index: number): (number?, string?) + local v = walk(lo, br) + walk(hi, br) * 256 + for k = 1, 3 do + if v == esc[k] then + last[k] = index + 1 + return 0, nil + end + end + return v, nil + end, true) + if not vals then + return nil, msg + end + bit(br) + for k = 1, 3 do + if last[k] == -1 then + table.insert(vals, 0) + last[k] = #vals + end + end + return { vals = vals, last = last }, nil +end + +export type Trees = { mmap: BigTree, mclr: BigTree, full: BigTree, type: BigTree } + +-- trees(config) -> the four header trees | nil, message. config = the four u32 tree sizes then the tree bits +function Smacker.trees(config: buffer): (Trees?, string?) + local n = buffer.len(config) + if n <= 16 then + return nil, "no trees" + end + local br = Smacker.bits(config, 16, n - 16) + local out: { BigTree } = {} + local present = 0 + for k = 1, 4 do + local size = buffer.readu32(config, (k - 1) * 4) + if size >= 2 ^ 28 then + return nil, "tree size too large" + end + local here = br.pos < br.nbits and band(rshift(readu8(config, rshift(br.pos, 3)), band(br.pos, 7)), 1) == 1 + local t, msg = bigTree(br, size) + if not t then + return nil, msg + end + if here then + present += 1 + end + out[k] = t + end + if present == 0 or br.pos > br.nbits then + return nil, "bad trees" + end + return { mmap = out[1], mclr = out[2], full = out[3], type = out[4] }, nil +end + +-- code(tree, br) -> the next value (updating the recent-value cache) | nil when the bits run out inside the tree +local function code(t: BigTree, br: Bits): number? + local vals = t.vals + local i = 1 + local e = vals[1] + while e < 0 do + if br.pos >= br.nbits then + return nil + end + if bit(br) == 1 then + i += -e - 1 + end + i += 1 + e = vals[i] + end + local last = t.last + local l0, l1, l2 = last[1], last[2], last[3] + if e ~= vals[l0] then + vals[l2] = vals[l1] + vals[l1] = vals[l0] + vals[l0] = e + end + return e +end + +local function reset(t: BigTree) + local vals, last = t.vals, t.last + vals[last[1]], vals[last[2]], vals[last[3]] = 0, 0, 0 +end + +-- decode(pic, data, trees, v4) -> true | false, message. pic: palettised, padded to blocks of 4 +function Smacker.decode(pic: Picture.Picture, d: buffer, trees: Trees, v4: boolean): (boolean, string?) + local px = pic.idx :: buffer + local stride = pic.stride + local mmap, mclr, full, typ = trees.mmap, trees.mclr, trees.full, trees.type + reset(mmap) + reset(mclr) + reset(full) + reset(typ) + local br = Smacker.bits(d, 0, buffer.len(d)) + local bw, bh = pic.w // 4, pic.h // 4 + local blocks = bw * bh + local blk = 0 + while blk < blocks do + local ty = code(typ, br) + if not ty then + return false, "truncated frame" + end + local run = RUNS[band(rshift(ty, 2), 63) + 1] + local kind = band(ty, 3) + if kind == 2 then + blk = math.min(blocks, blk + run) + elseif kind == 3 then + local v = rshift(ty, 8) * 0x01010101 + for _ = 1, run do + if blk >= blocks then + break + end + local o = (blk // bw) * stride * 4 + (blk % bw) * 4 + writeu32(px, o, v) + writeu32(px, o + stride, v) + writeu32(px, o + 2 * stride, v) + writeu32(px, o + 3 * stride, v) + blk += 1 + end + elseif kind == 0 then + for _ = 1, run do + if blk >= blocks then + break + end + local clr = code(mclr, br) + local map = code(mmap, br) + if not clr or not map then + return false, "truncated frame" + end + local hi, lo = rshift(clr, 8), band(clr, 255) + local o = (blk // bw) * stride * 4 + (blk % bw) * 4 + for r = 0, 3 do + local q = o + r * stride + writeu8(px, q, if band(map, 1) ~= 0 then hi else lo) + writeu8(px, q + 1, if band(map, 2) ~= 0 then hi else lo) + writeu8(px, q + 2, if band(map, 4) ~= 0 then hi else lo) + writeu8(px, q + 3, if band(map, 8) ~= 0 then hi else lo) + map = rshift(map, 4) + end + blk += 1 + end + else + local mode = 0 + if v4 then + if br.pos >= br.nbits then + return false, "truncated frame" + end + if bit(br) == 1 then + mode = 1 + elseif bit(br) == 1 then + mode = 2 + end + end + for _ = 1, run do + if blk >= blocks then + break + end + local o = (blk // bw) * stride * 4 + (blk % bw) * 4 + if mode == 0 then + for r = 0, 3 do + local a = code(full, br) + local b = code(full, br) + if not a or not b then + return false, "truncated frame" + end + local q = o + r * stride + writeu8(px, q + 2, band(a, 255)) + writeu8(px, q + 3, rshift(a, 8)) + writeu8(px, q, band(b, 255)) + writeu8(px, q + 1, rshift(b, 8)) + end + elseif mode == 1 then + for half = 0, 1 do + local a = code(full, br) + if not a then + return false, "truncated frame" + end + local lo, hi = band(a, 255), rshift(a, 8) + local v = lo * 0x0101 + hi * 0x01010000 + writeu32(px, o + half * 2 * stride, v) + writeu32(px, o + (half * 2 + 1) * stride, v) + end + else + for half = 0, 1 do + local p2 = code(full, br) + local p1 = code(full, br) + if not p1 or not p2 then + return false, "truncated frame" + end + local v = p1 + p2 * 65536 + writeu32(px, o + half * 2 * stride, v) + writeu32(px, o + (half * 2 + 1) * stride, v) + end + end + blk += 1 + end + end + end + return true, nil +end + +return Smacker diff --git a/src/Formats/codecs/video/Legacy/init.luau b/src/Formats/codecs/video/Legacy/init.luau index 51729a4..f73885d 100644 --- a/src/Formats/codecs/video/Legacy/init.luau +++ b/src/Formats/codecs/video/Legacy/init.luau @@ -3,7 +3,8 @@ -- The 1990s inter-frame codecs as codecs/video/Video registry decoders (rgba8 pictures, one per packet): Autodesk -- FLI / FLC ("flic", the frames of video/fli), Cinepak ("cinepak", -- 'cvid'), Microsoft Video 1 ("msvideo1": CRAM / MSVC / WHAM, 8-bit palettised and 16-bit), QuickTime Animation --- ("qtrle", 'rle ': depths 1 / 2 / 4 / 8 / 16 / 24 / 32 and grey) and QuickTime Graphics ("smc", 'smc '). +-- ("qtrle", 'rle ': depths 1 / 2 / 4 / 8 / 16 / 24 / 32 and grey), QuickTime Graphics ("smc", 'smc ') and Smacker +-- video ("smackvid", the frames of video/smk: track.config = the header's tree sizes and trees, codecTag SMK2 / SMK4). -- New in formats-luau, written from the format descriptions (see each submodule); decoding is bit-exact with ffmpeg's -- decoders (tests/codecs/legacy.luau). Every decoder keeps the previous picture (a packet paints over it) and returns -- a fresh copy. @@ -13,7 +14,7 @@ -- packet on. Depths come from track.bitsPerPixel (AVI biBitCount, the QuickTime depth). -- -- local dec, err = Legacy.newDecoder("cinepak", track, { maxPixels = 2^22 }) -- a Types.VideoCodecDecoder --- Legacy.CODECS --> { "flic", "cinepak", "msvideo1", "qtrle", "smc" } +-- Legacy.CODECS --> { "flic", "cinepak", "msvideo1", "qtrle", "smc", "smackvid" } -- -- Never throws: bad tracks return nil, Err; bad packets return Err from decode(). local Err = require("@formats/core/Err") @@ -24,6 +25,7 @@ local Cinepak = require("@formats/codecs/video/Legacy/Cinepak") local Msvideo1 = require("@formats/codecs/video/Legacy/Msvideo1") local QtRle = require("@formats/codecs/video/Legacy/QtRle") local Smc = require("@formats/codecs/video/Legacy/Smc") +local Smacker = require("@formats/codecs/video/Legacy/Smacker") local Legacy = {} @@ -33,7 +35,8 @@ Legacy.Cinepak = Cinepak Legacy.Msvideo1 = Msvideo1 Legacy.QtRle = QtRle Legacy.Smc = Smc -Legacy.CODECS = { "flic", "cinepak", "msvideo1", "qtrle", "smc" } +Legacy.Smacker = Smacker +Legacy.CODECS = { "flic", "cinepak", "msvideo1", "qtrle", "smc", "smackvid" } export type Options = { maxPixels: number?, -- refuse bigger pictures (LIMIT; default 2^26) @@ -124,6 +127,30 @@ local CODECS: { [string]: Codec } = { return Picture.image(st.pic), nil end, }, + smackvid = { + make = function(t) + local cfg = t.config + if type(cfg) ~= "buffer" then + return nil, "no Smacker trees" + end + local trees, msg = Smacker.trees(cfg) + if not trees then + return nil, msg + end + return { pic = Picture.new(t.width :: number, t.height :: number, true, 4, 4, t.palette), trees = trees, v4 = t.codecTag == "SMK4" }, nil + end, + step = function(st, data, packet) + packetPalette(st.pic, packet) + if buffer.len(data) == 0 then + return nil, fail("empty frame") + end + local ok, msg = Smacker.decode(st.pic, data, st.trees, st.v4) + if not ok then + return nil, fail(msg) + end + return Picture.image(st.pic), nil + end, + }, flic = { make = function(t) return Flic.state(t.width :: number, t.height :: number, t.bitsPerPixel or 8) diff --git a/src/Formats/video/smk/Audio.luau b/src/Formats/video/smk/Audio.luau new file mode 100644 index 0000000..2da8993 --- /dev/null +++ b/src/Formats/video/smk/Audio.luau @@ -0,0 +1,123 @@ +--!strict +--!native +--!optimize 2 +-- video/smk/Audio: Smacker's packed audio (SMKA: DPCM with Huffman-coded deltas), the one audio codec only Smacker +-- files carry. Written from the format description (MultimediaWiki "Smacker"). A packet: the unpacked size (u32), +-- then LSB-first bits: data flag, stereo, 16-bit, one 8-bit Huffman tree per channel and byte (codecs/video/Legacy/ +-- Smacker trees: 1, 2 or 4), the first sample(s) raw (16-bit ones byte-swapped, the right channel first), then per +-- sample a delta added with wraparound (the low byte's tree, and the high byte's for 16 bits). Raw PCM tracks (u8 / +-- s16le) are converted here too. Output: interleaved floats (u8: (v - 128) / 128, s16: v / 32768), as ffmpeg gives +-- them. Never throws: trees are bounded and every read past the packet gives zero bits. +local Smacker = require("@formats/codecs/video/Legacy/Smacker") + +local readu8, readi16 = buffer.readu8, buffer.readi16 + +local Audio = {} + +-- decode(data, channels, bits, packed) -> frames, floats (1-based interleaved) | nil, message +function Audio.decode(d: buffer, channels: number, bits: number, packed: boolean): (number?, { number } | string) + local n = buffer.len(d) + if not packed then + local bps = bits // 8 + local frames = n // (bps * channels) + local count = frames * channels + local out = table.create(count, 0) + if bps == 1 then + for i = 0, count - 1 do + out[i + 1] = (readu8(d, i) - 128) / 128 + end + else + for i = 0, count - 1 do + out[i + 1] = readi16(d, i * 2) / 32768 + end + end + return frames, out + end + if n <= 4 then + return nil, "packet too small" + end + local size = buffer.readu32(d, 0) + if size > 2 ^ 24 then + return nil, "packet too big" + end + local br = Smacker.bits(d, 4, n - 4) + local bit, read, walk = Smacker.bit, Smacker.read, Smacker.walk + if bit(br) == 0 then + return 0, {} -- no data + end + local stereo = bit(br) + local wide = bit(br) + if (stereo == 1) ~= (channels == 2) or (wide == 1) ~= (bits == 16) then + return nil, "packet does not match the track's format" + end + local bytes = wide + 1 + local ch = stereo + 1 + if size % (ch * bytes) ~= 0 then + return nil, "unpacked size is not a whole number of samples" + end + local trees: { { number } } = {} + for k = 1, 2 ^ (wide + stereo) do + bit(br) + local t, msg = Smacker.tree8(br) + if not t then + return nil, msg or "bad tree" + end + bit(br) + trees[k] = t + end + if br.nbits - br.pos < ch * bytes * 8 then + return nil, "truncated packet" + end + -- whether any tree needs bits (else every delta is a constant and no end check applies) + local coded = false + for _, t in trees do + if #t > 1 then + coded = true + end + end + local frames = size // (ch * bytes) + local total = frames * ch + local out = table.create(total, 0) + if wide == 1 then + local pred = { 0, 0 } + for c = ch, 1, -1 do + local v = read(br, 16) + pred[c] = (v // 256) + (v % 256) * 256 + end + for c = 1, math.min(ch, total) do + local v = pred[c] + out[c] = (if v >= 32768 then v - 65536 else v) / 32768 + end + for i = ch, total - 1 do + local c = if ch == 2 then i % 2 else 0 + if coded and br.pos > br.nbits then + return nil, "truncated packet" + end + local lo = walk(trees[2 * c + 1], br) + local hi = walk(trees[2 * c + 2], br) + local v = (pred[c + 1] + lo + hi * 256) % 65536 + pred[c + 1] = v + out[i + 1] = (if v >= 32768 then v - 65536 else v) / 32768 + end + else + local pred = { 0, 0 } + for c = ch, 1, -1 do + pred[c] = read(br, 8) + end + for c = 1, math.min(ch, total) do + out[c] = (pred[c] - 128) / 128 + end + for i = ch, total - 1 do + local c = if ch == 2 then i % 2 else 0 + if br.pos > br.nbits then + return nil, "truncated packet" + end + local v = (pred[c + 1] + walk(trees[c + 1], br)) % 256 + pred[c + 1] = v + out[i + 1] = (v - 128) / 128 + end + end + return frames, out +end + +return Audio diff --git a/src/Formats/video/smk/init.luau b/src/Formats/video/smk/init.luau new file mode 100644 index 0000000..11c4c45 --- /dev/null +++ b/src/Formats/video/smk/init.luau @@ -0,0 +1,320 @@ +--!strict +-- video/smk: RAD Game Tools' Smacker video (SMK2 and SMK4). New in formats-luau, written from the format description +-- (MultimediaWiki "Smacker"). +-- Read: the header (size, frame count, frame time: > 0 ms, < 0 units of 10 us; the ring-frame flag), up to 7 audio +-- tracks (rate, packed / 16-bit / stereo flags), the frame sizes and flags, the four Huffman trees; per frame a palette +-- update (skip / copy-from-old / new 6-bit entries), the audio chunks and the video data, into a Demuxer. open() +-- returns a VideoDecoder: rgba8 frames from the Smacker video codec (codecs/video/Legacy/Smacker, through the +-- codecs/video/Video registry: the frame's palette rides on each packet as packet.palette), and the first audio +-- track as an audio Decoder built here (Smacker's packed DPCM audio has no audio format, so the format decodes it +-- itself: video/smk/Audio over codecs/audio/Stream; raw u8 / s16le tracks too). The ring frame (the extra frame that +-- leads back to the first) is not shown unless opts.ringFrame. Smk.demux(r) gives the Demuxer; Smk.openAudio(dmx, +-- track) the Decoder of any of its audio tracks. +-- Not supported: writing, Bink audio tracks (flags 0x08 / 0x04: reported as "binkaudio", no decoder). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Demux = require("@formats/containers/Demux") +local Video = require("@formats/codecs/video/Video") +local Stream = require("@formats/codecs/audio/Stream") +local Audio = require("@formats/video/smk/Audio") + +-- ------------------------------------------------------------------------------------------------ contract +local Smk = { + name = "smk", + category = "video", + extensions = { "smk" }, + mime = { "video/vnd.radgamettools.smacker" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/audio/Stream", "codecs/video/Legacy/Smacker" }, + caps = { decode = true, encode = false, streaming = true, video = { "smackvid" }, audio = { "smackaudio", "pcm_u8", "pcm_s16le" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + rgba: boolean?, -- (frames are rgba8 already) + maxPixels: number?, -- default 2^26 + audio: boolean?, -- false: do not open the audio track + ringFrame: boolean?, -- true: also show the ring frame at the end (as ffmpeg does) + openAudio: any?, -- the api's hook: used only for tracks this format cannot decode (Bink audio) +} + +-- ------------------------------------------------------------------------------------------------ constants +local HEADER = 104 +local RING = 1 +-- 6-bit palette components -> 8 bits (bit replication: v << 2 | v >> 4) +local PAL6 = table.create(64, 0) +for i = 0, 63 do + PAL6[i + 1] = i * 4 + i // 16 +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Smk.sniff(r: Bytes.Reader): number + local s = r:peek(4) + if s ~= "SMK2" and s ~= "SMK4" then + return 0 + end + return 1 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a frame's palette update over the previous palette (pal: 256 u32 R, G, B, A); false when malformed +local function palette(b: buffer, p: number, stop: number, old: buffer): (buffer?) + local pal = buffer.create(1024) + buffer.copy(pal, 0, old, 0, 1024) + local function u8(): number + local v = if p < stop then buffer.readu8(b, p) else 0 + p += 1 + return v + end + local sz = 0 + while sz < 256 do + local t = u8() + if t >= 0x80 then + sz += t - 0x80 + 1 + elseif t >= 0x40 then + local off = u8() + local j = t - 0x40 + 1 + if off + j > 256 then + return nil + end + while j > 0 and sz < 256 do + buffer.writeu32(pal, sz * 4, buffer.readu32(old, off * 4)) + sz += 1 + off += 1 + j -= 1 + end + else + local r = PAL6[t + 1] + local g = PAL6[u8() % 64 + 1] + local bl = PAL6[u8() % 64 + 1] + buffer.writeu32(pal, sz * 4, r + g * 256 + bl * 65536 + 0xFF000000) + sz += 1 + end + end + return pal +end + +-- demux(r, opts?) -> the Demuxer | nil, Err +function Smk.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + if limit - base < HEADER then + return nil, Err.new(Err.TRUNCATED, "file shorter than the header") + end + local hr = Bytes.reader(b, base, HEADER) + local magic = hr:string(4) + local w, h, frames = hr:u32le(), hr:u32le(), hr:u32le() + local ptsInc = hr:i32le() + local flags = hr:u32le() + hr:skip(28) + local treeSize = hr:u32le() + local sizes = { hr:u32le(), hr:u32le(), hr:u32le(), hr:u32le() } + local rates, aflags = {}, {} + for k = 1, 7 do + rates[k] = hr:u24le() + aflags[k] = hr:u8() + end + if hr.err then + return nil, hr.err + end + if magic ~= "SMK2" and magic ~= "SMK4" then + return nil, Err.new(Err.CORRUPT, "not a Smacker file") + end + if w == 0 or h == 0 or w > 32768 or h > 32768 then + return nil, Err.new(Err.CORRUPT, "bad picture size") + end + local max = (opts and opts.maxPixels) or 2 ^ 26 + if w * h > max then + return nil, Err.new(Err.LIMIT, w .. " x " .. h .. " over maxPixels") + end + local shown = frames + if bit32.band(flags, RING) ~= 0 then + frames += 1 + end + local p = base + HEADER + if frames > 0xFFFFFF or p + frames * 5 + treeSize > limit then + return nil, Err.new(Err.TRUNCATED, "frame tables or trees past the end of the file") + end + -- the trees (with the four sizes in front, as the video codec takes them) + local config = buffer.create(16 + treeSize) + for k = 1, 4 do + buffer.writeu32(config, (k - 1) * 4, sizes[k]) + end + buffer.copy(config, 16, b, p + frames * 5, treeSize) + -- frame time: > 0 ms, < 0 units of 10 us (ticks of 1/100000 s) + local tick = if ptsInc < 0 then -ptsInc elseif ptsInc > 0 then ptsInc * 100 else 10000 + local tracks: { Types.Track } = { + { + id = 1, + kind = "video", + codec = "smackvid", + codecTag = magic, + timescale = 100000, + width = w, + height = h, + frameRate = 100000 / tick, + default = true, + config = config, + flags = flags, + } :: Types.Track, + } + local audio: { [number]: Types.Track } = {} + for k = 1, 7 do + if rates[k] > 0 then + local f = aflags[k] + local bits = if bit32.band(f, 0x20) ~= 0 then 16 else 8 + local codec = if bit32.band(f, 0x0C) ~= 0 then "binkaudio" + elseif bit32.band(f, 0x80) ~= 0 then "smackaudio" + elseif bits == 16 then "pcm_s16le" + else "pcm_u8" + local t: Types.Track = { + id = k + 1, + kind = "audio", + codec = codec, + codecTag = string.format("0x%02X", f), + timescale = rates[k], + sampleRate = rates[k], + channels = if bit32.band(f, 0x10) ~= 0 then 2 else 1, + bitsPerSample = bits, + default = #tracks == 1, + } + audio[k] = t + table.insert(tracks, t) + end + end + local dmx = Demux.new("smk", tracks, b, { version = magic, flags = flags, frames = shown, ringFrame = frames > shown }) + local count = if opts and opts.ringFrame then frames else shown + local pal = buffer.create(1024) + local apts = { 0, 0, 0, 0, 0, 0, 0 } + local at = p + frames * 5 + treeSize + for i = 0, frames - 1 do + local fsize = buffer.readu32(b, p + i * 4) + local fflags = buffer.readu8(b, p + frames * 4 + i) + local size = fsize - fsize % 4 + local q, stop = at, math.min(limit, at + size) + at += size + local ok = true + if fflags % 2 == 1 and q < stop then + local psize = buffer.readu8(b, q) * 4 + if psize > size then + ok = false + else + local np = palette(b, q + 1, math.min(stop, q + psize), pal) + if np then + pal = np + else + ok = false + end + q += psize + end + end + for k = 1, 7 do + if not ok then + break + end + if bit32.band(fflags, 2 ^ k) ~= 0 then + if q + 4 > stop then + ok = false + break + end + local asize = buffer.readu32(b, q) + local t = audio[k] + local min = if t and t.codec ~= "pcm_s16le" then 8 else 4 + if asize < min or q + asize > stop then + ok = false + break + end + if t then + local len = asize - 4 + local frameBytes = (t.channels :: number) * (t.bitsPerSample :: number) // 8 + local n = if t.codec == "smackaudio" then buffer.readu32(b, q + 4) // frameBytes + elseif t.codec == "binkaudio" then 0 + else len // frameBytes + dmx:add(t.id, apts[k], nil, n, true, q + 4, len) + apts[k] += n + end + q += asize + end + end + if ok and i < count then + dmx:add(1, i * tick, nil, tick, i == 0 or fsize % 2 == 1, q, math.max(0, stop - q)) + dmx:setExtra("palette", pal) + end + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- openAudio(dmx, track) -> an audio Decoder for one of the demuxer's audio tracks | nil, Err +function Smk.openAudio(dmx: any, track: Types.Track): (Types.Decoder?, Err.Err?) + local codec = track.codec + if codec ~= "smackaudio" and codec ~= "pcm_u8" and codec ~= "pcm_s16le" then + return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. codec) + end + local id = track.id + local count = dmx:count(id) + local starts: { number } = {} + local total = 0 + for k = 1, count do + local pts, _, dur = dmx:info(id, k) + starts[k] = pts or total + total = (pts or total) + (dur or 0) + end + starts[count + 1] = total + local rate, ch, bits = track.sampleRate :: number, track.channels :: number, track.bitsPerSample :: number + local packed = codec == "smackaudio" + local floats: { number } = {} + local dec: any = { + sampleRate = rate, + channels = ch, + frames = total, + duration = total / rate, + bitrate = rate * ch * bits, + tags = {}, + } + return Stream.packets(dec, { + count = count, + start = function(i: number): number + return starts[math.clamp(i, 1, count + 1)] + end, + decode = function(i: number): (number?, Err.Err?) + local pkt = dmx:get(id, i) + if not pkt then + return nil, Err.new(Err.TRUNCATED, "no audio packet " .. i) + end + local n, out = Audio.decode(pkt.data, ch, bits, packed) + if not n then + return nil, Err.from(out :: string) + end + floats = out :: { number } + return n, nil + end, + pcm = function(): { number } + return floats + end, + reset = function() end, + cumulative = true, + }) +end + +-- open(r, opts?) -> a VideoDecoder | nil, Err +function Smk.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Smk.demux(r, opts) + if not dmx then + return nil, err + end + local o: any = table.clone(opts or {}) + type Hook = (any, Types.Track) -> (Types.Decoder?, Err.Err?) + local hook = o.openAudio :: Hook? + o.openAudio = function(d: any, track: Types.Track): (Types.Decoder?, Err.Err?) + if track.codec == "binkaudio" and hook then + return hook(d, track) + end + return Smk.openAudio(d, track) + end + return Video.open(dmx, o) +end + +return Smk diff --git a/tests/video/smk.luau b/tests/video/smk.luau new file mode 100644 index 0000000..6969cde --- /dev/null +++ b/tests/video/smk.luau @@ -0,0 +1,180 @@ +-- video/smk tests: Smacker files encoded by the fixture script (SMK2 and SMK4, every block type and run, the trees' +-- escape cache, palette updates, a ring frame, ms and 10 us frame times; packed 16-bit stereo / 8-bit mono / 16-bit +-- mono / 8-bit stereo audio and raw s16le / u8 tracks): every video frame and every audio track equal ffmpeg's +-- decode (CRC-32 of rgba / f32le), audio seeking, errors, and the fuzz pass on the container, the video codec and the +-- audio codec. Fixtures: tools/fixtures/smk.py. +local T = require("@tests/T") +local F = require("@formats") +local Smk = require("@formats/video/smk") +local SmkAudio = require("@formats/video/smk/Audio") +local Legacy = require("@formats/codecs/video/Legacy") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/smk_cases") + +local t = T.suite("smk") +t:eq(Smk.name, "smk", "name") +t:eq(Smk.category, "video", "category") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end + +-- every frame of an audio Decoder -> f32 buffer, frames +local function drain(dec: any): (buffer, number) + local chunks, total = {}, 0 + while true do + local b, n = dec:read(1000) + if n == 0 then + break + end + table.insert(chunks, { b, n }) + total += n + end + local out = buffer.create(total * dec.channels * 4) + local at = 0 + for _, c in chunks do + buffer.copy(out, at, c[1], 0, c[2] * dec.channels * 4) + at += c[2] * dec.channels * 4 + end + return out, total +end + +for _, c in Fx do + local label = c.name + t:check(Smk.sniff(reader(c.data)) == 1, label .. ": sniff") + t:eq(F.detect(buffer.fromstring(c.data)), "smk", label .. ": detect") + local v, err = F.video.open(buffer.fromstring(c.data)) + t:check(v ~= nil, label .. ": open " .. tostring(err)) + if v then + t:eq(v.codec, "smackvid", label .. ": codec") + t:check(v.width == c.width and v.height == c.height, label .. ": size") + t:check(math.abs(v.frameRate - c.rate) < 1e-6, label .. ": frame rate " .. v.frameRate) + local want = if c.ring then #c.frames - 1 else #c.frames + local n, bad = 0, 0 + while true do + local f, ferr = v:nextFrame() + if not f then + t:check(ferr == nil, label .. ": " .. tostring(ferr)) + break + end + n += 1 + if f.image.format ~= "rgba8" or Crc32.of(f.image.pixels) ~= c.frames[n] then + bad += 1 + end + end + t:check(n == want and bad == 0, string.format("%s: %d of %d frames equal ffmpeg's (%d differ)", label, n - bad, want, bad)) + v:seek(0.2) + local f = v:nextFrame() + local k = math.floor(0.2 * c.rate - 1e-9) + 2 + t:check(f ~= nil and Crc32.of(f.image.pixels) == c.frames[k], label .. ": seek to frame " .. k) + -- audio: the first track through the VideoDecoder, every track through Smk.openAudio + if #c.audio > 0 then + t:check(v.audio ~= nil, label .. ": audio " .. tostring(v.audioError)) + end + local tracks = {} + for _, tr in v.demuxer.tracks do + if tr.kind == "audio" then + table.insert(tracks, tr) + end + end + t:eq(#tracks, #c.audio, label .. ": audio tracks") + for i, a in c.audio do + local tr = tracks[i] + t:eq(tr.codec, a.codec, label .. ": audio " .. i .. " codec") + local dec, aerr = Smk.openAudio(v.demuxer, tr) + t:check(dec ~= nil, label .. ": audio " .. i .. ": " .. tostring(aerr)) + if dec then + t:check(dec.sampleRate == a.rate and dec.channels == a.channels, label .. ": audio " .. i .. " format") + local pcm, frames = drain(dec) + t:eq(frames, a.frames, label .. ": audio " .. i .. " frames") + t:eq(Crc32.of(pcm), a.crc, label .. ": audio " .. i .. " equals ffmpeg's") + dec:seek(0) + local again = drain(dec) + t:eq(Crc32.of(again), a.crc, label .. ": audio " .. i .. " after seek(0)") + dec:seek(0.3) + local tail, rest = drain(dec) + local skip = a.frames - rest + t:check(math.abs(skip - 0.3 * a.rate) <= 1, label .. ": audio " .. i .. " seek(0.3) at frame " .. skip) + local same = buffer.len(tail) > 0 + for q = 0, math.min(buffer.len(tail), 4000) - 4, 4 do + if buffer.readu32(tail, q) ~= buffer.readu32(pcm, skip * a.channels * 4 + q) then + same = false + break + end + end + t:check(same, label .. ": audio " .. i .. " seek(0.3) samples") + end + end + if c.ring then + local v2 = Smk.open(reader(c.data), { ringFrame = true }) + local m = 0 + while v2 and v2:nextFrame() do + m += 1 + end + t:eq(m, #c.frames, label .. ": with the ring frame") + end + end +end + +-- errors +do + local _, e = Smk.open(reader(string.sub(Fx[1].data, 1, 60))) + t:check(e ~= nil and e.code == Err.TRUNCATED, "short header: TRUNCATED") + local _, e2 = Smk.open(reader("SMK3" .. string.sub(Fx[1].data, 5))) + t:check(e2 ~= nil and e2.code == Err.CORRUPT, "bad magic: CORRUPT") + t:eq(Smk.sniff(reader("SMK3" .. string.sub(Fx[1].data, 5))), 0, "bad magic: no sniff") + local _, e3 = Smk.open(reader(Fx[1].data), { maxPixels = 100 }) + t:check(e3 ~= nil and e3.code == Err.LIMIT, "maxPixels: LIMIT") + local _, e4 = Smk.open(reader(string.sub(Fx[1].data, 1, 200))) + t:check(e4 ~= nil and e4.code == Err.TRUNCATED, "trees past the end: TRUNCATED") +end + +-- fuzz: the container, the video codec (native, no pcall in between) and the audio codec +local samples = {} +for _, c in Fx do + table.insert(samples, c.data) +end +t:fuzz("open", function(b: buffer) + local v = Smk.open(Bytes.reader(b)) + if v then + for _ = 1, 4 do + if not v:nextFrame() then + break + end + end + if v.audio then + v.audio:read(500) + end + end + return v +end, samples, { mutations = 16, garbage = 40, keepHeader = 4 }) +local S, P = Legacy.Smacker, Legacy.Picture +for _, c in { Fx[1], Fx[2] } do + local d = Smk.demux(reader(c.data)) + local tr = d.tracks[1] + local packets = {} + for k = 1, math.min(3, d:count(1)) do + table.insert(packets, d:get(1, k).data) + end + t:fuzz(c.name .. " trees", function(b: buffer) + return S.trees(b) + end, { tr.config }, { mutations = 30, garbage = 30, keepHeader = 16 }) + local trees = assert(S.trees(tr.config)) + t:fuzz(c.name .. " frames", function(b: buffer) + return S.decode(P.new(c.width, c.height, true, 4, 4), b, trees, tr.codecTag == "SMK4") + end, packets, { mutations = 30, garbage = 30 }) + for _, at in d.tracks do + if at.kind == "audio" then + local ap = {} + for k = 1, math.min(2, d:count(at.id)) do + table.insert(ap, d:get(at.id, k).data) + end + t:fuzz(c.name .. " audio " .. at.codec, function(b: buffer) + return SmkAudio.decode(b, at.channels, at.bitsPerSample, at.codec == "smackaudio") + end, ap, { mutations = 20, garbage = 20 }) + end + end +end +t:done() diff --git a/tools/fixtures/smk.py b/tools/fixtures/smk.py new file mode 100644 index 0000000..0d9ee5a --- /dev/null +++ b/tools/fixtures/smk.py @@ -0,0 +1,493 @@ +# 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(" 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(" 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) From fea56f4391449c67799d73b8c01b2d36a34f54c4 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:37:43 -0500 Subject: [PATCH 15/27] ws-voxel: model/schematic (.schem v1-3, .schematic, .litematic read + write), codecs/model/Minecraft (block states, default colours, legacy ids, packed arrays) Types change (backward compatible): Types.Voxels gains optional blocks (VoxelBlocks: exact block states as u16 indices into a state palette, block entities, entities) and colors (exact u32 RGBA per cell). --- docs/FORMATS.md | 2 +- .../codecs/model/Minecraft/Legacy.luau | 15 +- src/Formats/codecs/model/Minecraft/init.luau | 12 +- src/Formats/model/schematic/Common.luau | 6 +- src/Formats/model/schematic/Mcedit.luau | 56 ++++- src/Formats/model/schematic/Sponge.luau | 10 +- src/Formats/model/schematic/init.luau | 37 ++- tests/codecs/minecraft.luau | 155 ++++++++++++ tests/model/schematic.luau | 221 ++++++++++++++++++ tools/fixtures/_schematic_encode.luau | 49 ++++ tools/fixtures/schematic.py | 1 + 11 files changed, 524 insertions(+), 40 deletions(-) create mode 100644 tests/codecs/minecraft.luau create mode 100644 tests/model/schematic.luau create mode 100644 tools/fixtures/_schematic_encode.luau diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 9f9bed5..dedbd74 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -41,7 +41,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` | | model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` | | model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` | -| model | schematic | .schem .schematic .litematic | yes | yes | voxels: true, blocks: true, variants: "schem", "schematic", "litematic" | **missing** | +| model | schematic | .schem .schematic .litematic | yes | yes | voxels: true, blocks: true, variants: "schem", "schematic", "litematic" | `tests/model/schematic.luau` | | model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` | | model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` | | model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` | diff --git a/src/Formats/codecs/model/Minecraft/Legacy.luau b/src/Formats/codecs/model/Minecraft/Legacy.luau index 9d1348e..51f834d 100644 --- a/src/Formats/codecs/model/Minecraft/Legacy.luau +++ b/src/Formats/codecs/model/Minecraft/Legacy.luau @@ -53,21 +53,18 @@ Legacy.RENAMED = { melon_block = "melon", lit_pumpkin = "jack_o_lantern", slime = "slime_block", magma = "magma_block", red_nether_brick = "red_nether_bricks", nether_brick = "nether_bricks", end_bricks = "end_stone_bricks", mob_spawner = "spawner", web = "cobweb", snow_layer = "snow", snow = "snow_block", noteblock = "note_block", - quartz_ore = "nether_quartz_ore", reeds = "sugar_cane", waterlily = "lily_pad", flowing_water = "water", - flowing_lava = "lava", tallgrass = "short_grass", grass_path = "dirt_path", double_stone_slab = "smooth_stone", - stone_slab = "smooth_stone_slab", deadbush = "dead_bush", yellow_flower = "dandelion", - + quartz_ore = "nether_quartz_ore", reeds = "sugar_cane", waterlily = "lily_pad", + tallgrass = "short_grass", grass_path = "dirt_path", double_stone_slab = "smooth_stone", + stone_slab = "smooth_stone_slab", deadbush = "dead_bush", yellow_flower = "dandelion", fence = "oak_fence", fence_gate = "oak_fence_gate", wooden_door = "oak_door", trapdoor = "oak_trapdoor", wooden_pressure_plate = "oak_pressure_plate", wooden_button = "oak_button", stone_stairs = "cobblestone_stairs", standing_sign = "oak_sign", wall_sign = "oak_wall_sign", golden_rail = "powered_rail", portal = "nether_portal", piston_extension = "moving_piston", - silver_shulker_box = "light_gray_shulker_box", silver_glazed_terracotta = "light_gray_glazed_terracotta", - monster_egg = "infested_stone", standing_banner = "white_banner", wall_banner = "white_wall_banner", skull = "skeleton_skull", bed = "red_bed", -} +} :: { [string]: string } -- legacy names whose data value selects the variant: the modern names by data value (0-based) local DYED = "white orange magenta light_blue yellow lime pink gray light_gray cyan purple blue brown green red black" @@ -105,7 +102,7 @@ Legacy.VARIANTS = { stained_hardened_clay = dyed("terracotta"), concrete = dyed("concrete"), concrete_powder = dyed("concrete_powder"), -} -Legacy.MASK = { log = 4, log2 = 4, leaves = 4, leaves2 = 4, sapling = 8, wooden_slab = 8, quartz_block = 8, double_plant = 8 } +} :: { [string]: { string } } +Legacy.MASK = { log = 4, log2 = 4, leaves = 4, leaves2 = 4, sapling = 8, wooden_slab = 8, quartz_block = 8, double_plant = 8 } :: { [string]: number } return Legacy diff --git a/src/Formats/codecs/model/Minecraft/init.luau b/src/Formats/codecs/model/Minecraft/init.luau index ded3ef3..5e31c3b 100644 --- a/src/Formats/codecs/model/Minecraft/init.luau +++ b/src/Formats/codecs/model/Minecraft/init.luau @@ -121,18 +121,18 @@ end local EXACT: { [string]: { number } } = {} for name, h in string.gmatch(Colors.BLOCKS, "([%w_]+)=(%x+)") do - EXACT[name] = hex(h) + EXACT[name :: string] = hex(h :: string) end local WOOL, CONCRETE, TERRACOTTA = list(Colors.WOOL), list(Colors.CONCRETE), list(Colors.TERRACOTTA) local PLANKS, BARK, LEAVES = list(Colors.PLANKS), list(Colors.BARK), list(Colors.LEAVES) -- longest prefixes first, so light_blue wins over blue and dark_oak over oak local function byLength(names: { string }): { { any } } - local out = {} + local out: { { any } } = {} for i, n in names do table.insert(out, { n, i }) end - table.sort(out, function(a, b) - return #a[1] > #b[1] + table.sort(out, function(a: { any }, b: { any }): boolean + return #(a[1] :: string) > #(b[1] :: string) end) return out end @@ -141,8 +141,8 @@ local SUFFIXES = { "_wall_hanging_sign", "_hanging_sign", "_wall_sign", "_sign", "_fence_gate", "_fence", "_pressure_plate", "_button", "_trapdoor", "_door", "_stairs", "_slab", "_wall", "_pane", "_carpet", "_wall_banner", "_banner", "_bars", } -local PREFIXES = { "waxed_", "potted_", "infested_", "lit_", "unlit_", "unpowered_", "powered_", "chipped_", "damaged_" } -local CORAL = { tube = hex("3157d0"), brain = hex("cf5b9f"), bubble = hex("a118a0"), fire = hex("a6252f"), horn = hex("d8c53e") } +local PREFIXES = { "waxed_", "potted_", "flowing_", "infested_", "lit_", "unlit_", "unpowered_", "powered_", "chipped_", "damaged_" } +local CORAL: { [string]: { number } } = { tube = hex("3157d0"), brain = hex("cf5b9f"), bubble = hex("a118a0"), fire = hex("a6252f"), horn = hex("d8c53e") } local FALLBACK = hex("909090") local function mix(c: { number }, w: { number }, t: number): { number } diff --git a/src/Formats/model/schematic/Common.luau b/src/Formats/model/schematic/Common.luau index e9f49c5..ee1002a 100644 --- a/src/Formats/model/schematic/Common.luau +++ b/src/Formats/model/schematic/Common.luau @@ -46,9 +46,9 @@ end function Common.ints(v: any): { number }? if Nbt.isTag(v) and v.type == "intArray" then return v.value - elseif type(v) == "table" and not Nbt.isTag(v) and v[1] ~= nil then - local out = {} - for i, x in v do + elseif type(v) == "table" and not Nbt.isTag(v) and (v :: any)[1] ~= nil then + local out: { number } = {} + for i, x in v :: { any } do out[i] = Nbt.number(x) or 0 end return out diff --git a/src/Formats/model/schematic/Mcedit.luau b/src/Formats/model/schematic/Mcedit.luau index d320037..c9b5805 100644 --- a/src/Formats/model/schematic/Mcedit.luau +++ b/src/Formats/model/schematic/Mcedit.luau @@ -91,18 +91,18 @@ function Mcedit.read(root: any, maxCells: number): ({ Common.Region }?, any) table.insert(bes, be) end end - return { + local regions: { Common.Region } = { { name = nil, - size = { sx, sy, sz }, + size = { sx, sy :: number, sz :: number }, position = { Common.int(root.WEOffsetX) or 0, Common.int(root.WEOffsetY) or 0, Common.int(root.WEOffsetZ) or 0 }, states = states, indices = Packed.fromYzx(yzx, sx, sy :: number, sz :: number), blockEntities = bes, entities = Common.list(root.Entities), }, - }, - { materials = root.Materials } + } + return regions, { materials = root.Materials } end -- the legacy blocks a colour can become (full blocks of distinct colours) @@ -160,14 +160,50 @@ function Mcedit.write(r: Common.Region, base: any): (any, string?) return nil, "a .schematic is at most 65535 cells on each axis" end local n = sx * sy * sz - local ids, datas = table.create(#r.states), table.create(#r.states) + -- the source's name tables (Schematica / MCEdit-Unified) give the ids for the names they list + local map: { [string]: number } = {} + if type(base) == "table" then + if Types.isObject(base.SchematicaMapping) then + for _, k in Types.keys(base.SchematicaMapping) do + local id = Common.int(base.SchematicaMapping[k]) + if id then + map[k] = id + end + end + end + if Types.isObject(base.BlockIDs) then + for _, k in Types.keys(base.BlockIDs) do + local id = tonumber(k) + if id and type(base.BlockIDs[k]) == "string" then + map[base.BlockIDs[k]] = id + end + end + end + end + local ids, datas = table.create(#r.states) :: { number }, table.create(#r.states) :: { number } local high = false for i, s in r.states do local id, d = Mc.legacyId(s) - if id == nil then - id, d = nearest(s) + if id ~= nil then + local lname = Mc.Legacy.NAMES[id + 1] + local mapped = lname and map["minecraft:" .. lname] + if mapped then + id = mapped + end + else + local name, props = Mc.parseState(s) + if map[name] then + id, d = map[name], 0 + for _, kv in props do + if kv[1] == "data" then + d = (tonumber(kv[2]) or 0) % 16 + end + end + else + id, d = nearest(s) + end end - ids[i], datas[i] = id, d + ids[i], datas[i] = id :: number, d :: number if (id :: number) > 255 then high = true end @@ -189,7 +225,7 @@ function Mcedit.write(r: Common.Region, base: any): (any, string?) table.insert(tiles, Common.flatBlockEntity(be, "flat")) end local ents = if #r.entities > 0 then r.entities else Nbt.list("compound") - local fields = { + local fields: { { any } } = { { "Width", Nbt.short(sx) }, { "Height", Nbt.short(sy) }, { "Length", Nbt.short(sz) }, @@ -206,7 +242,7 @@ function Mcedit.write(r: Common.Region, base: any): (any, string?) table.insert(fields, { "WEOffsetY", p[2] }) table.insert(fields, { "WEOffsetZ", p[3] }) end - local root = Common.merge(base, fields, { SchematicaMapping = true, BlockIDs = true, Add = true }) + local root = Common.merge(base, fields, { Add = true }) return root, nil end diff --git a/src/Formats/model/schematic/Sponge.luau b/src/Formats/model/schematic/Sponge.luau index 47f344f..c939d1a 100644 --- a/src/Formats/model/schematic/Sponge.luau +++ b/src/Formats/model/schematic/Sponge.luau @@ -67,18 +67,18 @@ function Sponge.read(s: any, maxCells: number): ({ Common.Region }?, any) end end local off = Common.ints(s.Offset) or { 0, 0, 0 } - return { + local regions: { Common.Region } = { { name = nil, - size = { sx, sy, sz }, + size = { sx, sy :: number, sz :: number }, position = { off[1] or 0, off[2] or 0, off[3] or 0 }, states = states, indices = Packed.fromYzx(yzx, sx, sy :: number, sz :: number), blockEntities = bes, entities = Common.list(s.Entities), }, - }, - { version = version, dataVersion = Common.int(s.DataVersion), metadata = s.Metadata } + } + return regions, { version = version, dataVersion = Common.int(s.DataVersion), metadata = s.Metadata } end -- write(region, version, dataVersion, base?) -> the Schematic compound (v3: the caller wraps it in the root) | nil, @@ -101,7 +101,7 @@ function Sponge.write(r: Common.Region, version: number, dataVersion: number, ba for _, be in r.blockEntities do table.insert(bes, Common.flatBlockEntity(be, if version >= 3 then "data" else "pos")) end - local ents = if #r.entities > 0 then r.entities else nil + local ents = if #r.entities > 0 then r.entities else Nbt.list("compound") -- optional, but readers expect it local off = Nbt.intArray({ r.position[1], r.position[2], r.position[3] }) local fields: { { any } } = { { "Version", version }, diff --git a/src/Formats/model/schematic/init.luau b/src/Formats/model/schematic/init.luau index 4d0db36..b844efa 100644 --- a/src/Formats/model/schematic/init.luau +++ b/src/Formats/model/schematic/init.luau @@ -49,11 +49,22 @@ export type EncodeOptions = { title: string?, -- .litematic Metadata.Name compression: ("gzip" | "zlib" | "none")?, -- default gzip, as every tool writes them level: number?, -- deflate level + format: string?, -- set by the api: the format key the encoder was picked by ("schem", "litematic", ...) } -- ------------------------------------------------------------------------------------------------ constants local DEFAULT_DATA_VERSION = 3953 local LITEMATIC_HINTS = { "Regions", "EnclosingSize", "RegionCount", "TotalVolume", "MinecraftDataVersion" } +local SPONGE_HINTS = { "BlockData", "PaletteMax" } -- v1 / v2 fields (some writers leave the root unnamed) + +local function hinted(head: string, hints: { string }): boolean + for _, h in hints do + if string.find(head, string.char(0, #h) .. h, 1, true) then + return true + end + end + return false +end -- ------------------------------------------------------------------------------------------------ sniff function Schematic.sniff(r: Bytes.Reader): number @@ -65,12 +76,25 @@ function Schematic.sniff(r: Bytes.Reader): number return 1 end local head = buffer.tostring(p.head) - for _, h in LITEMATIC_HINTS do - if string.find(head, string.char(0, #h) .. h, 1, true) then - return 1 - end + return if hinted(head, LITEMATIC_HINTS) or hinted(head, SPONGE_HINTS) then 1 else 0 +end + +-- variant(r) -> "schem" | "litematic" | "schematic" | nil: the flavour, for F.detect (from the first inflated bytes) +function Schematic.variant(r: Bytes.Reader): string? + local p = Nbt.peek(r.buf, r.base, r.limit - r.base) + if not p then + return nil end - return 0 + if p.firstName == "Schematic" then + return "schem" + end + local head = buffer.tostring(p.head) + if hinted(head, LITEMATIC_HINTS) then + return "litematic" + elseif hinted(head, SPONGE_HINTS) or (p.name == "Schematic" and hinted(head, { "Palette", "Version" })) then + return "schem" + end + return if p.name == "Schematic" then "schematic" else nil end -- ------------------------------------------------------------------------------------------------ decode @@ -114,7 +138,8 @@ function Schematic.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, regions, extra = Mcedit.read(s, maxCells) end if not regions then - return nil, Err.from(extra) + local msg = tostring(extra) + return nil, Err.from(msg, nil, if string.find(msg, "limit: ", 1, true) then "limit" else nil) end local scene = Types.Scene.new() scene.voxels = {} diff --git a/tests/codecs/minecraft.luau b/tests/codecs/minecraft.luau new file mode 100644 index 0000000..e8afa7a --- /dev/null +++ b/tests/codecs/minecraft.luau @@ -0,0 +1,155 @@ +-- codecs/model/Minecraft tests: packed index arrays (spanning and not, 1..16 bits, against a bit-by-bit reference), +-- Sponge varints, nibble arrays, YZX reordering, block-state strings and their NBT form, every legacy id / data pair +-- through legacyState / legacyId, colours (air, families, fallbacks), voxels / blocksOf and nearest-colour blocks. +-- The formats using it: tests/model/schematic.luau, tests/model/mca.luau. +local T = require("@tests/T") +local Mc = require("@formats/codecs/model/Minecraft") +local Types = require("@formats/Types") + +local t = T.suite("minecraft") +local P = Mc.Packed +local rand = T.rng(3) + +-- 1. packed arrays against a reference that walks the bits one at a time +local function refBit(longs: buffer, p: number): number + return bit32.extract(buffer.readu8(longs, p // 8), p % 8, 1) +end +for bits = 1, 16 do + for _, spanning in { true, false } do + local count = 100 + rand(300) + local max = math.min(2 ^ bits, 70000) + local idx = buffer.create(count * 2) + for i = 0, count - 1 do + buffer.writeu16(idx, i * 2, rand(max)) + end + local longs = P.pack(idx, count, bits, spanning) + t:eq(buffer.len(longs), P.longsNeeded(count, bits, spanning) * 8, bits .. " bits: size") + local per = 64 // bits + local bad = 0 + for i = 0, count - 1 do + local p = if spanning then i * bits else (i // per) * 64 + (i % per) * bits + local v = 0 + for k = 0, bits - 1 do + v += refBit(longs, p + k) * 2 ^ k + end + if v ~= buffer.readu16(idx, i * 2) then + bad += 1 + end + end + t:eq(bad, 0, bits .. " bits " .. tostring(spanning) .. ": layout") + local back = buffer.create(count * 2) + local ok, e = P.unpack(longs, bits, count, spanning, back, max) + t:check(ok, tostring(e)) + t:eq(buffer.tostring(back), buffer.tostring(idx), bits .. " bits " .. tostring(spanning) .. ": round trip") + end +end +do + local out = buffer.create(40) + t:check(not P.unpack(buffer.create(8), 4, 20, false, out, 16), "too few longs") + local l = P.pack(buffer.fromstring("\5\0"), 1, 4, false) + t:check(not P.unpack(l, 4, 1, false, out, 3), "index past the palette") + t:eq(P.bitsFor(17, 4), 5, "bitsFor") + t:eq(P.bitsFor(1, 2), 2, "bitsFor minimum") +end + +-- 2. varints, nibbles, YZX +do + local idx = buffer.create(400) + for i = 0, 199 do + buffer.writeu16(idx, i * 2, (i * 997) % 20000) + end + local v = P.toVarints(idx, 200) + local back = buffer.create(400) + t:check(P.varints(v, 0, buffer.len(v), 200, back, 20000), "varints") + t:eq(buffer.tostring(back), buffer.tostring(idx), "varints round trip") + t:check(not P.varints(v, 0, buffer.len(v) - 1, 200, back, 20000), "varints truncated") + local nib = buffer.create(2) + P.setNibble(nib, 0, 0, 0xA, true) + P.setNibble(nib, 0, 1, 0x3, true) + P.setNibble(nib, 0, 2, 0x7, false) + t:eq(buffer.readu8(nib, 0), 0xA3, "high nibble first") + t:eq(buffer.readu8(nib, 1), 0x07, "low nibble first") + t:eq(P.nibble(nib, 0, 1, true), 3, "read nibble") + local sx, sy, sz = 3, 4, 5 + local yzx = buffer.create(sx * sy * sz * 2) + for y = 0, sy - 1 do + for z = 0, sz - 1 do + for x = 0, sx - 1 do + buffer.writeu16(yzx, (x + z * sx + y * sx * sz) * 2, x * 100 + y * 10 + z) + end + end + end + local vox = P.fromYzx(yzx, sx, sy, sz) + t:eq(buffer.readu16(vox, (2 + sx * (3 + sy * 4)) * 2), 234, "fromYzx") + t:eq(buffer.tostring(P.toYzx(vox, sx, sy, sz)), buffer.tostring(yzx), "toYzx") +end + +-- 3. states +do + local name, props = Mc.parseState("oak_log[axis=y, foo = bar]") + t:eq(name, "minecraft:oak_log", "namespace added") + t:eq(#props, 2, "props") + t:eq(Mc.stateString(name, props), "minecraft:oak_log[axis=y,foo=bar]", "stateString") + local c = Mc.stateToNbt("minecraft:chest[facing=north,type=single]") + t:eq(table.concat(Types.keys(c.Properties), ","), "facing,type", "NBT property order") + t:eq(Mc.stateFromNbt(c), "minecraft:chest[facing=north,type=single]", "stateFromNbt") + t:eq(Mc.baseName("minecraft:stone"), "stone", "baseName") + t:check(Mc.isAir("minecraft:cave_air") and not Mc.isAir("minecraft:stone"), "isAir") +end + +-- 4. legacy ids: every id / data pair reads back exactly +do + local bad = 0 + for id = 0, 255 do + for d = 0, 15 do + local s = Mc.legacyState(id, d) + local i2, d2 = Mc.legacyId(s) + if i2 ~= id or d2 ~= d then + bad += 1 + end + end + end + t:eq(bad, 0, "legacy round trip") + t:eq(Mc.legacyState(35, 14), "minecraft:red_wool", "wool 14") + t:eq(Mc.legacyState(5, 2), "minecraft:birch_planks", "planks 2") + t:eq(Mc.legacyState(17, 5), "minecraft:spruce_log[data=5]", "log axis bits kept") + t:eq(select(1, Mc.legacyId("minecraft:white_concrete")), 251, "modern name -> legacy id") +end + +-- 5. colours +do + t:eq(Mc.color("minecraft:air"), nil, "air") + local function hex(s: string): string + local c = Mc.color(s) :: { number } + return string.format("%02x%02x%02x%02x", c[1], c[2], c[3], c[4]) + end + t:eq(hex("minecraft:stone"), "7d7d7dff", "exact") + t:eq(hex("minecraft:stone_brick_stairs[facing=east]"), hex("minecraft:stone_bricks"), "stairs -> base") + t:eq(hex("minecraft:red_concrete"), "8e2020ff", "dye family") + t:eq(hex("minecraft:dark_oak_log"), "3e2f17ff", "wood bark") + t:eq(string.sub(hex("minecraft:red_stained_glass"), 7, 8), "80", "stained glass translucent") + t:eq(hex("minecraft:wool[data=14]"), hex("minecraft:red_wool"), "legacy data colour") + t:eq(hex("mod:something_odd"), "909090ff", "fallback") +end + +-- 6. voxels / blocksOf +do + local states = { "minecraft:air", "minecraft:stone", "minecraft:red_wool", "minecraft:stone" } + local idx = buffer.create(8 * 2) + for i = 0, 7 do + buffer.writeu16(idx, i * 2, i % 4) + end + local v = Mc.voxels(2, 2, 2, states, idx) + t:eq(buffer.readu8(v.data, 0), 0, "air -> 0") + t:eq(buffer.readu8(v.data, 1), buffer.readu8(v.data, 3), "same colour, same index") + t:check(buffer.readu8(v.data, 2) ~= buffer.readu8(v.data, 1), "different colours") + local s2, i2 = Mc.blocksOf(v) + t:check(s2 == states and i2 == idx, "blocksOf keeps the blocks") + local g = Types.Voxels.new(2, 1, 1) + g.palette[7] = { 240, 118, 19, 255 } + buffer.writeu8(g.data, 1, 7) + local s3, i3 = Mc.blocksOf(g) + t:eq((s3 :: { string })[buffer.readu16(i3, 2) + 1], "minecraft:orange_wool", "nearest block by colour") + t:eq((s3 :: { string })[buffer.readu16(i3, 0) + 1], "minecraft:air", "empty -> air") +end +t:done() diff --git a/tests/model/schematic.luau b/tests/model/schematic.luau new file mode 100644 index 0000000..8508c99 --- /dev/null +++ b/tests/model/schematic.luau @@ -0,0 +1,221 @@ +-- model/schematic tests: .litematic files written by litemapy (several regions, negative sizes, a 40-state palette, +-- tile entities), Sponge .schem v2 (litemapy) and v1 / v3 (nbtlib, by the spec; two-byte varints), MCEdit +-- .schematic (legacy ids + data, WorldEdit AddBlocks, a Schematica name table): every cell's block state, placement, +-- block entities; our re-encodings give the same NBT for the same variant, and the reference readers (litemapy / +-- nbtlib, in the fixture step) read our output, across variants and from colour-only grids, to the same cells; +-- detection, the api, error codes and the fuzz pass. Fixtures: tools/fixtures/schematic.py. +local T = require("@tests/T") +local F = require("@formats") +local Schematic = require("@formats/model/schematic") +local Mc = require("@formats/codecs/model/Minecraft") +local Nbt = require("@formats/codecs/text/Nbt") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/schematic") +local Ours = require("@tests/gen/schematic_ours") + +local t = T.suite("schematic") + +t:eq(Schematic.name, "schematic", "name") +t:check(Schematic.caps.decode and Schematic.caps.encode, "caps") + +local function dec(data: string | buffer, opts: any?): (Types.Scene?, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Schematic.decode(Bytes.reader(b), opts) +end + +-- the region record of node i: { name, min, size, cells (state per cell, "\n"-joined), legacy (id * 16 + data) } +local function regions(scene: Types.Scene): { any } + local out = {} + for _, node in scene.nodes do + local v = (scene.voxels :: { Types.Voxels })[node.voxels :: number] + local b = v.blocks :: Types.VoxelBlocks + local n = v.size[1] * v.size[2] * v.size[3] + local cells, legacy = table.create(n), table.create(n) + for i = 0, n - 1 do + local st = b.palette[buffer.readu16(b.data, i * 2) + 1] + cells[i + 1] = st + local id, d = Mc.legacyId(st) + legacy[i + 1] = if id then id * 16 + (d :: number) else -1 + end + local tr = node.translation :: { number } + table.insert(out, { name = node.name, min = tr, size = v.size, cells = table.concat(cells, "\n"), legacy = legacy, voxels = v, blockEntities = #(b.blockEntities or {}) }) + end + return out +end + +local function sameRegion(got: any, want: any, label: string) + t:eq(got.size[1] .. "," .. got.size[2] .. "," .. got.size[3], want.size[1] .. "," .. want.size[2] .. "," .. want.size[3], label .. ": size") + t:eq(got.min[1] .. "," .. got.min[2] .. "," .. got.min[3], want.min[1] .. "," .. want.min[2] .. "," .. want.min[3], label .. ": minimum corner") + if want.cells then + t:eq(got.cells, want.cells, label .. ": cells") + else + local bad = 0 + for i, x in want.legacy do + if got.legacy[i] ~= x then + bad += 1 + end + end + t:eq(bad, 0, label .. ": legacy ids") + end +end + +-- 1. reference files +local decoded: { [string]: Types.Scene } = {} +for _, c in Fx.cases do + local scene, err = dec(c.data) + t:check(scene ~= nil, c.name .. ": " .. tostring(err)) + local s = scene :: Types.Scene + decoded[c.name] = s + t:eq(s.meta.source.variant, c.variant, c.name .. ": variant") + if c.version > 0 then + t:eq(s.meta.source.version, c.version, c.name .. ": version") + end + local regs = regions(s) + t:eq(#regs, #c.regions, c.name .. ": regions") + local bes = 0 + for i, want in c.regions do + sameRegion(regs[i], want, c.name .. " region " .. i) + if want.name ~= "" then + t:eq(regs[i].name, want.name, c.name .. " region " .. i .. ": name") + end + bes += regs[i].blockEntities + end + t:eq(bes, c.blockEntities, c.name .. ": block entities") + -- colours: air is empty, the rest coloured from the default table + local v = regs[1].voxels + local b = v.blocks + for i = 0, v.size[1] * v.size[2] * v.size[3] - 1 do + local st = b.palette[buffer.readu16(b.data, i * 2) + 1] + local idx = buffer.readu8(v.data, i) + if Mc.isAir(st) ~= (idx == 0) then + t:check(false, c.name .. ": cell " .. i .. " colour index " .. idx .. " for " .. st) + end + if idx > 0 then + local col, p = Mc.color(st) :: { number }, v.palette[idx] + if col[1] ~= p[1] or col[2] ~= p[2] or col[3] ~= p[3] then + t:check(false, c.name .. ": cell " .. i .. " colour of " .. st) + end + end + end + -- the same variant again: the same NBT (every field), the same cells + local out, eerr = Schematic.encode(s) + t:check(out ~= nil, c.name .. ": encode " .. tostring(eerr)) + local again = assert(dec(out :: buffer)) + t:eq(Nbt.print(again.meta.source.nbt), Nbt.print(s.meta.source.nbt), c.name .. ": same NBT") + t:eq(again.meta.source.rootName, s.meta.source.rootName, c.name .. ": root name") + for i, r in regions(again) do + sameRegion(r, regs[i], c.name .. " again region " .. i) + end + -- api: detection by content (the flavour) and loading + t:eq(F.detect(c.data), c.variant, c.name .. ": F.detect") + local viaApi = F.load(c.data) + t:check(viaApi and viaApi.kind == "scene", c.name .. ": F.load") +end + +-- 2. our encodings read back by litemapy / nbtlib (fixture step) +local outputs: { [string]: () -> (buffer?, any) } = {} +local function colorGrid(): Types.Voxels + 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 + return v +end +outputs["litemapy.litematic"] = function() return Schematic.encode(decoded.litemapy) end +outputs["litemapy.schem"] = function() return Schematic.encode(decoded.litemapy, { variant = "schem", version = 2 }) end +outputs["sponge2.schem"] = function() return Schematic.encode(decoded.sponge2) end +outputs["sponge2.litematic"] = function() return Schematic.encode(decoded.sponge2, { variant = "litematic" }) end +outputs["sponge3.schem"] = function() return Schematic.encode(decoded.sponge3) end +outputs["sponge3v2.schem"] = function() return Schematic.encode(decoded.sponge3, { version = 2 }) end +outputs["sponge1.schem"] = function() return Schematic.encode(decoded.sponge1) end +outputs["mcedit.schematic"] = function() return Schematic.encode(decoded.mcedit) end +outputs["worldedit_add.schematic"] = function() return Schematic.encode(decoded.worldedit_add) end +outputs["sponge2.schematic"] = function() return Schematic.encode(decoded.sponge2, { variant = "schematic" }) end +outputs["mcedit.schem"] = function() return Schematic.encode(decoded.mcedit, { variant = "schem" }) end +outputs["colors.schem"] = function() return Schematic.encode(colorGrid()) end +outputs["colors.litematic"] = function() return Schematic.encode(colorGrid(), { variant = "litematic" }) end +outputs["colors.schematic"] = function() return Schematic.encode(colorGrid(), { variant = "schematic" }) end +local count = 0 +for name, ref in Ours do + local make = outputs[name] + t:check(make ~= nil, name .. ": known output") + local mine = assert(dec(assert(make()))) + local regs = regions(mine) + t:eq(#regs, #ref.regions, name .. ": regions read back") + for i, want in ref.regions do + sameRegion(regs[i], want, name .. " (reference) region " .. i) + end + if ref.litemapy then + t:eq(ref.litemapy, regs[1].cells, name .. ": litemapy's Sponge reader") + end + count += 1 +end +t:eq(count, 14, "every output checked") +-- the source cells survive the conversions +do + local function cellsVia(name: string): string + return regions(assert(dec(assert(outputs[name]()))))[1].cells + end + t:eq(cellsVia("sponge2.litematic"), regions(decoded.sponge2)[1].cells, "schem -> litematic cells") + t:eq(cellsVia("sponge3v2.schem"), regions(decoded.sponge3)[1].cells, "v3 -> v2 cells") + local legacy = regions(assert(dec(assert(outputs["mcedit.schem"]()))))[1].legacy + local src = regions(decoded.mcedit)[1].legacy + t:eq(table.concat(legacy, ","), table.concat(src, ","), "schematic -> schem keeps legacy states") + -- litematic -> schem merges the regions into one grid covering them all + local merged = regions(assert(dec(assert(outputs["litemapy.schem"]()))))[1] + t:eq(merged.size[1] .. "," .. merged.size[2] .. "," .. merged.size[3], "31,5,12", "merged size") + -- colour grid -> blocks by colour + local cg = regions(assert(dec(assert(outputs["colors.schem"]()))))[1] + local first = string.split(cg.cells, "\n") + t:eq(first[1], "minecraft:air", "empty cell -> air") + t:eq(first[2], "minecraft:red_wool", "red -> red wool") + t:eq(first[4], "minecraft:light_blue_stained_glass", "translucent blue -> stained glass") +end + +-- 3. through the api +do + local scene = assert(F.load(Fx.cases[1].data, { name = "x.litematic" })) + local schem = assert(F.save(scene, nil, { format = "schem" })) :: buffer + t:eq(F.detect(schem), "schem", "F.save format = schem") + local lite = assert(F.save(scene, nil, { format = "litematic" })) :: buffer + t:eq(F.detect(lite), "litematic", "F.save format = litematic") + local legacy = assert(F.save(scene, nil, { format = "schematic", variant = "schematic" })) :: buffer + t:eq(F.detect(legacy), "schematic", "variant schematic") + t:eq(F.detect(legacy, { name = "a.schematic" }), "schematic", "detect with a name") + -- a vox-like grid without blocks through F.save + local g = Types.Voxels.new(2, 2, 2) + buffer.writeu8(g.data, 0, 5) + t:check(F.save(g, nil, { format = "schem" }) ~= nil, "save a bare Voxels") +end + +-- 4. errors +do + local _, e1 = dec(assert(Nbt.encode(Nbt.compound({ a = 1 }, { "a" })))) + t:check(e1 and e1.code == Err.CORRUPT, "not a schematic") + local _, e2 = dec(Fx.cases[1].data, { maxCells = 10 }) + t:check(e2 and e2.code == Err.LIMIT, "maxCells") + local _, e3 = Schematic.encode({ kind = "scene" } :: any) + t:check(e3 and e3.code == Err.ARG, "encode without voxels") + local _, e4 = Schematic.encode(colorGrid(), { variant = "x" :: any }) + t:check(e4 and e4.code == Err.ARG, "unknown variant") + local bad = Nbt.compound({ Width = Nbt.short(4), Height = Nbt.short(4), Length = Nbt.short(4), Blocks = buffer.create(10) }, { "Width", "Height", "Length", "Blocks" }) + local _, e5 = dec(assert(Nbt.encode(bad, { name = "Schematic" }))) + t:check(e5 and e5.code == Err.TRUNCATED, "short Blocks") +end + +-- 5. fuzz (the uncompressed NBT too, so mutations reach the layouts, not just gzip's CRC) +local samples = {} +for _, c in Fx.cases do + local s = assert(dec(c.data)) + table.insert(samples, (assert(Nbt.encode(s.meta.source.nbt, { name = s.meta.source.rootName, compression = "none" })))) +end +table.insert(samples, Fx.cases[1].data) +t:fuzz("decode", function(b: buffer) + return Schematic.decode(Bytes.reader(b)) +end, samples) +t:done() diff --git a/tools/fixtures/_schematic_encode.luau b/tools/fixtures/_schematic_encode.luau new file mode 100644 index 0000000..1f09645 --- /dev/null +++ b/tools/fixtures/_schematic_encode.luau @@ -0,0 +1,49 @@ +-- tools/fixtures/schematic.py helper: our model/schematic encoder's output for the reference readers (litemapy, +-- nbtlib). Prints "\t" 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" })) diff --git a/tools/fixtures/schematic.py b/tools/fixtures/schematic.py index 7996ad6..e44d80c 100644 --- a/tools/fixtures/schematic.py +++ b/tools/fixtures/schematic.py @@ -119,6 +119,7 @@ def varints(idx): 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)) From d99b026b0711e60a59317e432a3703f74a8dbd9f Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:41:29 -0500 Subject: [PATCH 16/27] legacy video: bench lines (320x240 / 320x200 fixtures), Smacker frame decoder through 10-bit lookup tables --- src/Formats/codecs/video/Legacy/Smacker.luau | 146 ++++++++++++------- tools/bench.luau | 39 +++++ tools/fixtures/fli.py | 6 + tools/fixtures/legacy.py | 8 + tools/fixtures/smk.py | 14 +- 5 files changed, 157 insertions(+), 56 deletions(-) diff --git a/src/Formats/codecs/video/Legacy/Smacker.luau b/src/Formats/codecs/video/Legacy/Smacker.luau index c5923ec..eab6650 100644 --- a/src/Formats/codecs/video/Legacy/Smacker.luau +++ b/src/Formats/codecs/video/Legacy/Smacker.luau @@ -9,12 +9,13 @@ -- per-frame cache, reset to 0 at each frame). The four big trees (MMAP, MCLR, FULL, TYPE) come from the file header; -- a frame is 4x4 blocks in raster order, each TYPE code giving a block type and a run length: MONO (two colours and a -- 16-bit mask), FULL (16 pixels as 8 codes; SMK4 adds a 2x2-doubled and a 2x1-doubled mode), SKIP, FILL (one colour). --- Trees are flat arrays (a node stores the size of its left subtree, as a negative number) walked bit by bit. +-- Trees are flat arrays (a node stores the size of its left subtree, as a negative number); the frame decoder reads +-- 10 bits at a time through a lookup table into them. -- Bit-exact with ffmpeg's smackvid decoder. Never throws: trees are bounded (depth, entries), reads past the data give -- zero bits, a frame whose codes run out of bits gives no picture. local Picture = require("@formats/codecs/video/Legacy/Picture") -local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32 +local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32 local band, rshift = bit32.band, bit32.rshift local Smacker = {} @@ -135,7 +136,7 @@ function Smacker.tree8(br: Bits): ({ number }?, string?) end local tree8 = Smacker.tree8 -export type BigTree = { vals: { number }, last: { number } } -- last: the escape leaves' indexes (1-based) +export type BigTree = { vals: { number }, last: { number }, lut: buffer? } -- last: the escape leaves' indexes (1-based) -- bigTree(br, size) -> one of the header's trees | nil, message (size = its byte size from the header: bounds entries) local function bigTree(br: Bits, size: number): (BigTree?, string?) @@ -213,29 +214,26 @@ function Smacker.trees(config: buffer): (Trees?, string?) return { mmap = out[1], mclr = out[2], full = out[3], type = out[4] }, nil end --- code(tree, br) -> the next value (updating the recent-value cache) | nil when the bits run out inside the tree -local function code(t: BigTree, br: Bits): number? - local vals = t.vals - local i = 1 - local e = vals[1] - while e < 0 do - if br.pos >= br.nbits then - return nil +local LUT_BITS = 10 + +-- the first LUT_BITS bits of a code -> (entry index * 32 + bits used): a leaf, or the node reached after LUT_BITS bits +local function lut(vals: { number }): buffer + local size = 2 ^ LUT_BITS + local t = buffer.create(size * 4) + for pat = 0, size - 1 do + local i, len = 1, 0 + local e = vals[1] + while e < 0 and len < LUT_BITS do + if band(rshift(pat, len), 1) == 1 then + i += -e - 1 + end + i += 1 + len += 1 + e = vals[i] end - if bit(br) == 1 then - i += -e - 1 - end - i += 1 - e = vals[i] + writeu32(t, pat * 4, i * 32 + len) end - local last = t.last - local l0, l1, l2 = last[1], last[2], last[3] - if e ~= vals[l0] then - vals[l2] = vals[l1] - vals[l1] = vals[l0] - vals[l0] = e - end - return e + return t end local function reset(t: BigTree) @@ -248,17 +246,65 @@ function Smacker.decode(pic: Picture.Picture, d: buffer, trees: Trees, v4: boole local px = pic.idx :: buffer local stride = pic.stride local mmap, mclr, full, typ = trees.mmap, trees.mclr, trees.full, trees.type - reset(mmap) - reset(mclr) - reset(full) - reset(typ) - local br = Smacker.bits(d, 0, buffer.len(d)) + for _, t in { mmap, mclr, full, typ } do + reset(t) + if not t.lut then + t.lut = lut(t.vals) + end + end + local n = buffer.len(d) + local nbits = n * 8 + local pos = 0 + -- the next value of a tree (updating its recent-value cache) | -1 when the bits run out inside the tree + local function code(t: BigTree): number + local vals = t.vals + local i, p + local byte = rshift(pos, 3) + if byte + 3 <= n then + local v = band(rshift(readu8(d, byte) + readu8(d, byte + 1) * 256 + readu8(d, byte + 2) * 65536, band(pos, 7)), 1023) + local ent = readu32(t.lut :: buffer, v * 4) + i = rshift(ent, 5) + p = pos + band(ent, 31) + else + i, p = 1, pos + end + local e = vals[i] + while e < 0 do + if p >= nbits then + return -1 + end + if band(rshift(readu8(d, rshift(p, 3)), band(p, 7)), 1) == 1 then + i += -e - 1 + end + p += 1 + i += 1 + e = vals[i] + end + pos = p + local last = t.last + local l0 = last[1] + if e ~= vals[l0] then + local l1 = last[2] + vals[last[3]] = vals[l1] + vals[l1] = vals[l0] + vals[l0] = e + end + return e + end + local function bit(): number + local p = pos + pos = p + 1 + if p >= nbits then + return 0 + end + return band(rshift(readu8(d, rshift(p, 3)), band(p, 7)), 1) + end local bw, bh = pic.w // 4, pic.h // 4 local blocks = bw * bh local blk = 0 while blk < blocks do - local ty = code(typ, br) - if not ty then + local ty = code(typ) + if ty < 0 then return false, "truncated frame" end local run = RUNS[band(rshift(ty, 2), 63) + 1] @@ -283,9 +329,9 @@ function Smacker.decode(pic: Picture.Picture, d: buffer, trees: Trees, v4: boole if blk >= blocks then break end - local clr = code(mclr, br) - local map = code(mmap, br) - if not clr or not map then + local clr = code(mclr) + local map = code(mmap) + if clr < 0 or map < 0 then return false, "truncated frame" end local hi, lo = rshift(clr, 8), band(clr, 255) @@ -303,12 +349,12 @@ function Smacker.decode(pic: Picture.Picture, d: buffer, trees: Trees, v4: boole else local mode = 0 if v4 then - if br.pos >= br.nbits then + if pos >= nbits then return false, "truncated frame" end - if bit(br) == 1 then + if bit() == 1 then mode = 1 - elseif bit(br) == 1 then + elseif bit() == 1 then mode = 2 end end @@ -319,33 +365,29 @@ function Smacker.decode(pic: Picture.Picture, d: buffer, trees: Trees, v4: boole local o = (blk // bw) * stride * 4 + (blk % bw) * 4 if mode == 0 then for r = 0, 3 do - local a = code(full, br) - local b = code(full, br) - if not a or not b then + local a = code(full) + local b = code(full) + if a < 0 or b < 0 then return false, "truncated frame" end - local q = o + r * stride - writeu8(px, q + 2, band(a, 255)) - writeu8(px, q + 3, rshift(a, 8)) - writeu8(px, q, band(b, 255)) - writeu8(px, q + 1, rshift(b, 8)) + -- the first code is the right pixel pair, the second the left one + writeu32(px, o + r * stride, b + a * 65536) end elseif mode == 1 then for half = 0, 1 do - local a = code(full, br) - if not a then + local a = code(full) + if a < 0 then return false, "truncated frame" end - local lo, hi = band(a, 255), rshift(a, 8) - local v = lo * 0x0101 + hi * 0x01010000 + local v = band(a, 255) * 0x0101 + rshift(a, 8) * 0x01010000 writeu32(px, o + half * 2 * stride, v) writeu32(px, o + (half * 2 + 1) * stride, v) end else for half = 0, 1 do - local p2 = code(full, br) - local p1 = code(full, br) - if not p1 or not p2 then + local p2 = code(full) + local p1 = code(full) + if p1 < 0 or p2 < 0 then return false, "truncated frame" end local v = p1 + p2 * 65536 diff --git a/tools/bench.luau b/tools/bench.luau index b32ee01..f593634 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -1078,3 +1078,42 @@ do 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 diff --git a/tools/fixtures/fli.py b/tools/fixtures/fli.py index 0428f02..e7ad3d6 100644 --- a/tools/fixtures/fli.py +++ b/tools/fixtures/fli.py @@ -393,3 +393,9 @@ def generate(ctx): 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}) diff --git a/tools/fixtures/legacy.py b/tools/fixtures/legacy.py index 863b866..76353ce 100644 --- a/tools/fixtures/legacy.py +++ b/tools/fixtures/legacy.py @@ -98,3 +98,11 @@ def generate(ctx): 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) diff --git a/tools/fixtures/smk.py b/tools/fixtures/smk.py index 0d9ee5a..0bfba7a 100644 --- a/tools/fixtures/smk.py +++ b/tools/fixtures/smk.py @@ -381,11 +381,14 @@ def tone(n, ch, bits, rate, seed, f0): # ---------------------------------------------------------------------------------------------------- files -def idx_frames(w, h, n, seed): +def idx_frames(w, h, n, seed, busy=False): rnd = random.Random(seed) out = [] for t in range(n): - img = [[(x // 8 + y // 8 * 3) % 40 for x in range(w)] for y in range(h)] + 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 @@ -399,10 +402,10 @@ def idx_frames(w, h, n, seed): return out -def smk_file(version, w, h, nframes, pts_inc, tracks, ring, seed): +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) + 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) @@ -491,3 +494,6 @@ def generate(ctx): 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}) From 1013925a85fe3c3435cac17823f60a58e0907b1d Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:43:22 -0500 Subject: [PATCH 17/27] ws-video2-theora: Theora speed (fused prediction + IDCT add, inlined token decode, table-driven tokens), bench lines, guide section tools/bench.luau: a ws-video2-theora block (320x240 testsrc2 / mandelbrot, decode and decode + image()). docs/guide/video.md: an Ogg Theora section (tested snippet; inputs from the new tools/fixtures/docs_theora.py) and the formats / writers tables. --- docs/guide/video.md | 28 +- src/Formats/codecs/video/Theora/Decoder.luau | 462 ++++++++++--------- src/Formats/codecs/video/Theora/Header.luau | 2 +- tools/bench.luau | 39 ++ tools/fixtures/docs_theora.py | 20 + tools/fixtures/theora.py | 13 +- 6 files changed, 342 insertions(+), 222 deletions(-) create mode 100644 tools/fixtures/docs_theora.py diff --git a/docs/guide/video.md b/docs/guide/video.md index 99e0395..6d2ed39 100644 --- a/docs/guide/video.md +++ b/docs/guide/video.md @@ -179,6 +179,7 @@ Images and animated images save as videos too. | Destination | Video | Audio | |---|---|---| | webm | VP8 / VP9 / AV1 copied (VP8 is decode only, so the source must be WebM-compatible) | Opus / Vorbis copied | +| ogv | Theora copied (the source must be Theora: ogv or mkv) | Vorbis / Opus copied | | mkv | any codec copied, else MJPEG | copied, else PCM s16 | | mp4, mov | H.264 / HEVC / AV1 / MJPEG / MPEG-4 copied, else MJPEG | AAC / ALAC / Opus / FLAC / MP3 copied; PCM in MOV only | | avi | MJPEG copied, else MJPEG encoded (`quality`) | PCM s16 | @@ -235,6 +236,30 @@ assert(C.register({ assert(C.fromFourcc("SLID") == "solid" and C.canDecode("solid")) ``` +## Ogg Theora + +Ogg video (`.ogv`, or `.ogg` with a Theora stream) opens like any other container: the `ogv` format demuxes every +Ogg stream, Theora video decodes bit-exactly (as libtheora / ffmpeg) in all three pixel formats (4:2:2 and 4:4:4 +chroma is averaged down to yuv420p), and a Vorbis, Opus or FLAC track becomes `v.audio`. Plain Ogg Vorbis / Opus / +FLAC files stay audio. Theora in Matroska (`V_THEORA`) decodes too, and an Ogg Theora video remuxes to ogv or mkv +(there is no Theora encoder). + +```luau +local v = assert(F.video.open(ogvBytes)) -- Theora + Vorbis +assert(v.format == "ogv" and v.codec == "theora" and v.width == 64 and v.height == 48) +assert(v.frameRate == 10 and v.audio ~= nil) +local n = 0 +while v:nextFrame() do n += 1 end -- dropped frames repeat the previous picture +assert(n == 10) +local Theora = F.format("ogv") -- the format module: sniff / demux / open / encode +local d = assert(Theora.demux(F.Bytes.reader(ogvBytes))) +local vt = d:track("video") +assert(vt.codec == "theora" and vt.timescale == 10) -- packet times are frame numbers here +v:reset() +local mkv = assert(F.save(v, nil, { format = "mkv" })) -- Theora + Vorbis copied into Matroska +assert(F.video.open(mkv).codec == "theora") +``` + ## Playing in a game loop Decode only the frames that are due, and stop when this frame's time budget is used up; a slow frame then makes @@ -279,7 +304,8 @@ editable:WritePixelsBuffer(Vector2.zero, editable.Size, v:toRGBA(frame).pixels) | Format | Read | Write | Video codecs (decode) | |---|---|---|---| | mp4 / mov / m4v / 3gp | yes | yes | H.264, MJPEG, MPEG-1 | -| mkv / webm | yes | yes | VP8, MJPEG, MPEG-1, raw (+ H.264) | +| mkv / webm | yes | yes | VP8, MJPEG, MPEG-1, raw, Theora (+ H.264) | +| ogv (Ogg Theora) | yes | yes (Theora + Vorbis / Opus copied) | Theora | | avi | yes | yes | MJPEG, MPEG-1, raw (+ H.264) | | mpegts, mpegps | yes | - | MPEG-1, H.264 | | y4m | yes | yes | raw | diff --git a/src/Formats/codecs/video/Theora/Decoder.luau b/src/Formats/codecs/video/Theora/Decoder.luau index d29b8cf..aad8f1c 100644 --- a/src/Formats/codecs/video/Theora/Decoder.luau +++ b/src/Formats/codecs/video/Theora/Decoder.luau @@ -24,9 +24,10 @@ local writeu8 = buffer.writeu8 local readu16 = buffer.readu16 local readi16 = buffer.readi16 local writei16 = buffer.writei16 -local readi32 = buffer.readi32 -local writei32 = buffer.writei32 local readu32 = buffer.readu32 +local writeu32 = buffer.writeu32 +local band = bit32.band +local bxor = bit32.bxor local bcopy = buffer.copy local bfill = buffer.fill local lshift = bit32.lshift @@ -93,10 +94,56 @@ do end -- DCT tokens: extra bits per token -local TOKEN_EXTRA = { - [0] = 0, 0, 0, 2, 3, 4, 12, 3, 6, 0, 0, 0, 0, 1, 1, 1, 1, 2, 3, 4, 5, 6, 10, 1, 1, 1, 1, 1, 3, 4, 2, 3, +local TOKEN_EXTRA = { -- [token + 1] + 0, 0, 0, 2, 3, 4, 12, 3, 6, 0, 0, 0, 0, 1, 1, 1, 1, 2, 3, 4, 5, 6, 10, 1, 1, 1, 1, 1, 3, 4, 2, 3, } +-- the zero-run / coefficient tokens (7..31) by token * 1024 + extra bits + 1: run * 4096 + value + 2048, where run is +-- the zeros before the value (value 0: a pure zero run of run + 1) +local TOKEN_VALUE = table.create(32 * 1024, 2048) +for tok = 7, 31 do + local ex = TOKEN_EXTRA[tok + 1] + for eb = 0, 2 ^ ex - 1 do + local v, r = 0, 0 + if tok < 9 then + r = eb -- zero runs: eb + 1 zeros + elseif tok < 13 then + v = if tok == 9 then 1 elseif tok == 10 then -1 elseif tok == 11 then 2 else -2 + elseif tok < 17 then + v = if eb == 1 then -(tok - 10) else tok - 10 + elseif tok < 23 then + local half = 2 ^ (ex - 1) -- the top extra bit is the sign + local base = if tok == 17 then 7 elseif tok == 18 then 9 elseif tok == 19 then 13 elseif tok == 20 then 21 elseif tok == 21 then 37 else 69 + v = base + eb % half + if eb >= half then + v = -v + end + elseif tok < 28 then + r = tok - 22 + v = if eb == 1 then -1 else 1 + elseif tok == 28 then + r = 6 + eb % 4 + v = if eb >= 4 then -1 else 1 + elseif tok == 29 then + r = 10 + eb % 8 + v = if eb >= 8 then -1 else 1 + elseif tok == 30 then + r = 1 + v = 2 + eb % 2 + if eb >= 2 then + v = -v + end + else + r = 2 + eb % 2 + v = 2 + (eb // 2) % 2 + if eb >= 4 then + v = -v + end + end + TOKEN_VALUE[tok * 1024 + eb + 1] = r * 4096 + v + 2048 + end +end + -- natural index of zig-zag position (1-based by position + 1) local ZIGZAG = Header.ZIGZAG @@ -158,9 +205,8 @@ export type State = { lflim: { number }, huff: { number }, roots: { number }, - blk: buffer, -- i32 x 64 work blocks + blk: buffer, -- i16 x 64 work blocks tmp: buffer, - res: buffer, bv: { number }, -- the loop filter's bounding values for the frame, [(f + 4) >> 3 + 129] keyframes: number, } @@ -191,9 +237,8 @@ function D.new(info: Header.Info, setup: Header.Setup): State lflim = setup.lflim, huff = setup.huff, roots = setup.roots, - blk = buffer.create(256), - tmp = buffer.create(256), - res = buffer.create(256), + blk = buffer.create(128), + tmp = buffer.create(128), bv = table.create(257, 0), keyframes = 0, } @@ -366,23 +411,24 @@ local function idct8(x0: number, x1: number, x2: number, x3: number, x4: number, return t0 + t7, t1 + t6, t2 + t5, t3 + t4, t3 - t4, t2 - t5, t1 - t6, t0 - t7 end --- 2-D IDCT of blk (i16, natural order) into res (i32 residuals). Like libtheora, the dequantised coefficients and --- the first pass's outputs are 16-bit (the i16 buffers wrap them), which also bounds every residual to +-24000. -local function idct(blk: buffer, tmp: buffer, res: buffer) +-- the first IDCT pass: the rows of blk (i16, natural order) into the columns of tmp (i16: like libtheora, the +-- dequantised coefficients and these intermediate values are 16-bit, which also bounds every residual) +local function idctRows(blk: buffer, tmp: buffer) for i = 0, 7 do local o = i * 16 local x0, x1, x2, x3 = readi16(blk, o), readi16(blk, o + 2), readi16(blk, o + 4), readi16(blk, o + 6) local x4, x5, x6, x7 = readi16(blk, o + 8), readi16(blk, o + 10), readi16(blk, o + 12), readi16(blk, o + 14) local c = i * 2 - if x0 == 0 and x1 == 0 and x2 == 0 and x3 == 0 and x4 == 0 and x5 == 0 and x6 == 0 and x7 == 0 then - writei16(tmp, c, 0) - writei16(tmp, c + 16, 0) - writei16(tmp, c + 32, 0) - writei16(tmp, c + 48, 0) - writei16(tmp, c + 64, 0) - writei16(tmp, c + 80, 0) - writei16(tmp, c + 96, 0) - writei16(tmp, c + 112, 0) + if x1 == 0 and x2 == 0 and x3 == 0 and x4 == 0 and x5 == 0 and x6 == 0 and x7 == 0 then + local y = (C4 * x0) // 65536 + writei16(tmp, c, y) + writei16(tmp, c + 16, y) + writei16(tmp, c + 32, y) + writei16(tmp, c + 48, y) + writei16(tmp, c + 64, y) + writei16(tmp, c + 80, y) + writei16(tmp, c + 96, y) + writei16(tmp, c + 112, y) else local y0, y1, y2, y3, y4, y5, y6, y7 = idct8(x0, x1, x2, x3, x4, x5, x6, x7) writei16(tmp, c, y0) @@ -395,20 +441,29 @@ local function idct(blk: buffer, tmp: buffer, res: buffer) writei16(tmp, c + 112, y7) end end - for i = 0, 7 do - local o = i * 16 - local x0, x1, x2, x3 = readi16(tmp, o), readi16(tmp, o + 2), readi16(tmp, o + 4), readi16(tmp, o + 6) - local x4, x5, x6, x7 = readi16(tmp, o + 8), readi16(tmp, o + 10), readi16(tmp, o + 12), readi16(tmp, o + 14) - local y0, y1, y2, y3, y4, y5, y6, y7 = idct8(x0, x1, x2, x3, x4, x5, x6, x7) - local c = i * 4 - writei32(res, c, (y0 + 8) // 16) - writei32(res, c + 32, (y1 + 8) // 16) - writei32(res, c + 64, (y2 + 8) // 16) - writei32(res, c + 96, (y3 + 8) // 16) - writei32(res, c + 128, (y4 + 8) // 16) - writei32(res, c + 160, (y5 + 8) // 16) - writei32(res, c + 192, (y6 + 8) // 16) - writei32(res, c + 224, (y7 + 8) // 16) +end + +-- the second pass, added to the prediction already in dst: column c of the block is row c of tmp +local function idctAdd(tmp: buffer, dst: buffer, pos: number, stride: number) + for c = 0, 7 do + local o = c * 16 + local y0, y1, y2, y3, y4, y5, y6, y7 = idct8(readi16(tmp, o), readi16(tmp, o + 2), readi16(tmp, o + 4), readi16(tmp, o + 6), readi16(tmp, o + 8), readi16(tmp, o + 10), readi16(tmp, o + 12), readi16(tmp, o + 14)) + local p = pos + c + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y0 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y1 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y2 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y3 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y4 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y5 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y6 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y7 + 8) // 16 + COFF)) end end @@ -426,7 +481,8 @@ local function mvSplit(d: number, q: boolean): (number, number) return a, b end --- reconstruct one coded fragment into dst (the SELF reference planes) +-- reconstruct one coded fragment into dst (the SELF reference planes): the prediction (128 for intra blocks, the +-- reference block or the average of two for inter ones) goes to dst first, then the residual is added local function reconFrag(st: State, fi: number, qis: { number }, dstPlanes: { buffer }) local pli = st.fpl[fi] local mode = st.fmode[fi] @@ -435,12 +491,20 @@ local function reconFrag(st: State, fi: number, qis: { number }, dstPlanes: { bu local dcq = readu16(dq, (((qis[1] * 3 + pli) * 2 + qti) * 64) * 2) local dc = st.dcv[fi] local last = st.last[fi] - local res = st.res - local flat = false + local stride = st.stride[pli + 1] + local dst = dstPlanes[pli + 1] + local pos = st.fpos[fi] + local ri = st.refi[fi] local fv = 0 if last == 0 then - flat = true fv = wrap16((dc * dcq + 15) // 32) + if ri == SELF then + local v = readu8(CLAMP, fv + 128 + COFF) + for y = 0, 7 do + bfill(dst, pos + y * stride, v, 8) + end + return + end else local blk = st.blk bfill(blk, 0, 0, 128) @@ -456,50 +520,44 @@ local function reconFrag(st: State, fi: number, qis: { number }, dstPlanes: { bu end end st.last[fi] = 0 - idct(blk, st.tmp, res) + idctRows(blk, st.tmp) end - local stride = st.stride[pli + 1] - local dst = dstPlanes[pli + 1] - local pos = st.fpos[fi] - local ri = st.refi[fi] + -- the prediction if ri == SELF then - if flat then - local v = readu8(CLAMP, fv + 128 + COFF) + for y = 0, 7 do + bfill(dst, pos + y * stride, 128, 8) + end + else + local ref = st.refs[if ri == GOLD then st.gold else st.prev][pli + 1] + local mx, mx2 = mvSplit(st.mvx[fi], pli > 0 and st.hdec == 1) + local my, my2 = mvSplit(st.mvy[fi], pli > 0 and st.vdec == 1) + local s1 = pos + my * stride + mx + if mx2 ~= 0 or my2 ~= 0 then + -- (a + b) >> 1 per byte, four at a time + local s2 = s1 + my2 * stride + mx2 for y = 0, 7 do - bfill(dst, pos + y * stride, v, 8) + local d, a, b = pos + y * stride, s1 + y * stride, s2 + y * stride + local u, v = readu32(ref, a), readu32(ref, b) + writeu32(dst, d, band(u, v) + rshift(band(bxor(u, v), 0xFEFEFEFE), 1)) + u, v = readu32(ref, a + 4), readu32(ref, b + 4) + writeu32(dst, d + 4, band(u, v) + rshift(band(bxor(u, v), 0xFEFEFEFE), 1)) end else for y = 0, 7 do - local d, s = pos + y * stride, y * 32 - for x = 0, 7 do - writeu8(dst, d + x, readu8(CLAMP, readi32(res, s + x * 4) + 128 + COFF)) - end + local d, a = pos + y * stride, s1 + y * stride + writeu32(dst, d, readu32(ref, a)) + writeu32(dst, d + 4, readu32(ref, a + 4)) end end - return end - local ref = st.refs[if ri == GOLD then st.gold else st.prev][pli + 1] - local qx = pli > 0 and st.hdec == 1 - local qy = pli > 0 and st.vdec == 1 - local mx, mx2 = mvSplit(st.mvx[fi], qx) - local my, my2 = mvSplit(st.mvy[fi], qy) - local s1 = pos + my * stride + mx - if mx2 ~= 0 or my2 ~= 0 then - local s2 = s1 + my2 * stride + mx2 + -- the residual + if last ~= 0 then + idctAdd(st.tmp, dst, pos, stride) + elseif fv ~= 0 then for y = 0, 7 do - local d, a, b, r = pos + y * stride, s1 + y * stride, s2 + y * stride, y * 32 - for x = 0, 7 do - local p = (readu8(ref, a + x) + readu8(ref, b + x)) // 2 - local v = if flat then fv else readi32(res, r + x * 4) - writeu8(dst, d + x, readu8(CLAMP, p + v + COFF)) - end - end - else - for y = 0, 7 do - local d, a, r = pos + y * stride, s1 + y * stride, y * 32 - for x = 0, 7 do - local v = if flat then fv else readi32(res, r + x * 4) - writeu8(dst, d + x, readu8(CLAMP, readu8(ref, a + x) + v + COFF)) + local d = pos + y * stride + for x = d, d + 7 do + writeu8(dst, x, readu8(CLAMP, readu8(dst, x) + fv + COFF)) end end end @@ -593,6 +651,88 @@ local function borders(st: State, planes: { buffer }) end end +-- DC prediction (raster order per plane): each coded block's DC adds a prediction from its left / upper neighbours +-- coded from the same reference frame (or the last such DC in the plane) +local function dcPredict(st: State) + local coded, refi, dcv = st.coded, st.refi, st.dcv + for pli = 0, 2 do + local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] + local base = st.foff[pli + 1] + local pl0, pl1, pl2 = 0, 0, 0 -- the last DC of each reference frame (GOLD, PREV, SELF) + for fy = 0, nv - 1 do + local row = base + fy * nh + local lref, ulref, uref = -1, -1, -1 + if fy > 0 then + uref = refi[row - nh + 1] + end + for fx = 0, nh - 1 do + local fi = row + fx + 1 + local urref = -1 + if fy > 0 and fx + 1 < nh then + urref = refi[fi - nh + 1] + end + if coded[fi] ~= 0 then + local r = refi[fi] + local pred: number + if fy == 0 then + pred = if r == 0 then pl0 elseif r == 1 then pl1 else pl2 + else + local m = (if lref == r then 1 else 0) + (if ulref == r then 2 else 0) + (if uref == r then 4 else 0) + (if urref == r then 8 else 0) + if m == 0 then + pred = if r == 0 then pl0 elseif r == 1 then pl1 else pl2 + elseif m == 1 or m == 3 then + pred = dcv[fi - 1] + elseif m == 2 then + pred = dcv[fi - nh - 1] + elseif m == 4 or m == 6 or m == 12 then + pred = dcv[fi - nh] + elseif m == 5 then + local s = dcv[fi - 1] + dcv[fi - nh] + pred = if s < 0 then -((-s) // 2) else s // 2 + elseif m == 8 then + pred = dcv[fi - nh + 1] + elseif m == 9 or m == 11 or m == 13 then + local s = 75 * dcv[fi - 1] + 53 * dcv[fi - nh + 1] + pred = if s < 0 then -((-s) // 128) else s // 128 + elseif m == 10 then + local s = dcv[fi - nh - 1] + dcv[fi - nh + 1] + pred = if s < 0 then -((-s) // 2) else s // 2 + elseif m == 14 then + local s = 3 * (dcv[fi - nh - 1] + dcv[fi - nh + 1]) + 10 * dcv[fi - nh] + pred = if s < 0 then -((-s) // 16) else s // 16 + else + local p0, p1, p2 = dcv[fi - 1], dcv[fi - nh - 1], dcv[fi - nh] + local s = 29 * (p0 + p2) - 26 * p1 + pred = if s < 0 then -((-s) // 32) else s // 32 + if math.abs(pred - p2) > 128 then + pred = p2 + elseif math.abs(pred - p0) > 128 then + pred = p0 + elseif math.abs(pred - p1) > 128 then + pred = p1 + end + end + end + local v = wrap16(dcv[fi] + pred) + dcv[fi] = v + if r == 0 then + pl0 = v + elseif r == 1 then + pl1 = v + else + pl2 = v + end + lref = r + else + lref = -1 + end + ulref = uref + uref = urref + end + end + end +end + -- ------------------------------------------------------------------------------------------------ frame decode -- decode(st, data, off, len) -> kind ("key" | "inter" | "dup") | nil, message. The picture is then in -- st.refs[st.shown]. @@ -609,31 +749,11 @@ function D.decode(st: State, data: buffer, off: number, len: number): (string?, if pos > maxp then pos = maxp end - local w = rshift(lshift(bswap(readu32(bb, pos // 8)), pos % 8), 32 - n) + local w = rshift(lshift(bswap(readu32(bb, rshift(pos, 3))), band(pos, 7)), 32 - n) pos += n return w end local huff = st.huff - local function token(root: number): number - if pos > maxp then - pos = maxp - end - local o = root - while true do - local n = huff[o] - local w = rshift(lshift(bswap(readu32(bb, pos // 8)), pos % 8), 32 - n) - local e = huff[o + 1 + w] - if e >= 0 then - pos += e // 64 - return e % 64 - end - pos += n - o = -e - if pos > maxp then - pos = maxp - end - end - end local function sbRun(): number if bits(1) == 0 then return 1 @@ -1028,9 +1148,28 @@ function D.decode(st: State, data: buffer, off: number, len: number): (string?, eobs -= 1 t = 64 else - local tok = token(root) - local ex = TOKEN_EXTRA[tok] - local eb = if ex > 0 then bits(ex) else 0 + -- the token (inlined: the hottest loop), then its extra bits + if pos > maxp then + pos = maxp + end + local o, tok = root, 0 + while true do + local nb = huff[o] + local e = huff[o + 1 + rshift(lshift(bswap(readu32(bb, rshift(pos, 3))), band(pos, 7)), 32 - nb)] + if e >= 0 then + pos += rshift(e, 6) + tok = band(e, 63) + break + end + pos += nb + o = -e + end + local ex = TOKEN_EXTRA[tok + 1] + local eb = 0 + if ex > 0 then + eb = rshift(lshift(bswap(readu32(bb, rshift(pos, 3))), band(pos, 7)), 32 - ex) + pos += ex + end if tok < 7 then local run: number if tok < 3 then @@ -1046,49 +1185,18 @@ function D.decode(st: State, data: buffer, off: number, len: number): (string?, end eobs = run - 1 t = 64 - elseif tok < 9 then - t = zzi + eb + 1 else - local v, r = 0, 0 - if tok < 13 then - v = if tok == 9 then 1 elseif tok == 10 then -1 elseif tok == 11 then 2 else -2 - elseif tok < 17 then - v = if eb == 1 then -(tok - 10) else tok - 10 - elseif tok < 23 then - local half = 2 ^ (ex - 1) - local base = if tok == 17 then 7 elseif tok == 18 then 9 elseif tok == 19 then 13 elseif tok == 20 then 21 elseif tok == 21 then 37 else 69 - v = base + eb % half - if eb >= half then - v = -v + -- zero runs and coefficients: run * 4096 + value + 2048 (value 0: a zero run) + local e = TOKEN_VALUE[tok * 1024 + eb + 1] + local p = zzi + rshift(e, 12) + local v = band(e, 4095) - 2048 + if v ~= 0 then + if p == 0 then + dcv[fi] = v + elseif p < 64 then + writei16(coef, (fi - 1) * 128 + p * 2, v) + last[fi] = p end - elseif tok < 28 then - r = tok - 22 - v = if eb == 1 then -1 else 1 - elseif tok == 28 then - r = 6 + eb % 4 - v = if eb >= 4 then -1 else 1 - elseif tok == 29 then - r = 10 + eb % 8 - v = if eb >= 8 then -1 else 1 - elseif tok == 30 then - r = 1 - v = 2 + eb % 2 - if eb >= 2 then - v = -v - end - else - r = 2 + eb % 2 - v = 2 + (eb // 2) % 2 - if eb >= 4 then - v = -v - end - end - local p = zzi + r - if p == 0 then - dcv[fi] = v - elseif p < 64 then - writei16(coef, (fi - 1) * 128 + p * 2, v) - last[fi] = p end t = p + 1 end @@ -1104,83 +1212,7 @@ function D.decode(st: State, data: buffer, off: number, len: number): (string?, end end - -- DC prediction (raster order per plane) - for pli = 0, 2 do - local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] - local base = st.foff[pli + 1] - local pl0, pl1, pl2 = 0, 0, 0 -- the last DC of each reference frame (GOLD, PREV, SELF) - for fy = 0, nv - 1 do - local row = base + fy * nh - local lref, ulref, uref = -1, -1, -1 - if fy > 0 then - uref = refi[row - nh + 1] - end - for fx = 0, nh - 1 do - local fi = row + fx + 1 - local urref = -1 - if fy > 0 and fx + 1 < nh then - urref = refi[fi - nh + 1] - end - if coded[fi] ~= 0 then - local r = refi[fi] - local pred: number - if fy == 0 then - pred = if r == 0 then pl0 elseif r == 1 then pl1 else pl2 - else - local m = (if lref == r then 1 else 0) + (if ulref == r then 2 else 0) + (if uref == r then 4 else 0) + (if urref == r then 8 else 0) - if m == 0 then - pred = if r == 0 then pl0 elseif r == 1 then pl1 else pl2 - elseif m == 1 or m == 3 then - pred = dcv[fi - 1] - elseif m == 2 then - pred = dcv[fi - nh - 1] - elseif m == 4 or m == 6 or m == 12 then - pred = dcv[fi - nh] - elseif m == 5 then - local s = dcv[fi - 1] + dcv[fi - nh] - pred = if s < 0 then -((-s) // 2) else s // 2 - elseif m == 8 then - pred = dcv[fi - nh + 1] - elseif m == 9 or m == 11 or m == 13 then - local s = 75 * dcv[fi - 1] + 53 * dcv[fi - nh + 1] - pred = if s < 0 then -((-s) // 128) else s // 128 - elseif m == 10 then - local s = dcv[fi - nh - 1] + dcv[fi - nh + 1] - pred = if s < 0 then -((-s) // 2) else s // 2 - elseif m == 14 then - local s = 3 * (dcv[fi - nh - 1] + dcv[fi - nh + 1]) + 10 * dcv[fi - nh] - pred = if s < 0 then -((-s) // 16) else s // 16 - else - local p0, p1, p2 = dcv[fi - 1], dcv[fi - nh - 1], dcv[fi - nh] - local s = 29 * (p0 + p2) - 26 * p1 - pred = if s < 0 then -((-s) // 32) else s // 32 - if math.abs(pred - p2) > 128 then - pred = p2 - elseif math.abs(pred - p0) > 128 then - pred = p0 - elseif math.abs(pred - p1) > 128 then - pred = p1 - end - end - end - local v = wrap16(dcv[fi] + pred) - dcv[fi] = v - if r == 0 then - pl0 = v - elseif r == 1 then - pl1 = v - else - pl2 = v - end - lref = r - else - lref = -1 - end - ulref = uref - uref = urref - end - end - end + dcPredict(st) -- reconstruction into a free reference buffer local self = 1 diff --git a/src/Formats/codecs/video/Theora/Header.luau b/src/Formats/codecs/video/Theora/Header.luau index 2d88abd..2259c19 100644 --- a/src/Formats/codecs/video/Theora/Header.luau +++ b/src/Formats/codecs/video/Theora/Header.luau @@ -226,7 +226,7 @@ local function buildTable(out: { number }, kid0: { number }, kid1: { number }, t for i = 0, size - 1 do local cur, d = n, 0 while d < nb and tok[cur] < 0 do - local bit = (i // 2 ^ (nb - 1 - d)) % 2 + local bit = bit32.extract(i, nb - 1 - d, 1) local nx = if bit == 0 then kid0[cur] else kid1[cur] d += 1 cur = nx diff --git a/tools/bench.luau b/tools/bench.luau index b32ee01..afd0966 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -1078,3 +1078,42 @@ do 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 diff --git a/tools/fixtures/docs_theora.py b/tools/fixtures/docs_theora.py new file mode 100644 index 0000000..1b85b57 --- /dev/null +++ b/tools/fixtures/docs_theora.py @@ -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"}) diff --git a/tools/fixtures/theora.py b/tools/fixtures/theora.py index 7d05299..6bcfd6a 100644 --- a/tools/fixtures/theora.py +++ b/tools/fixtures/theora.py @@ -10,7 +10,7 @@ # 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 { file (base64 .ogv, 320x240) } for tools/bench.luau +# 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"] @@ -199,7 +199,10 @@ def generate(ctx): 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 stream - bench = os.path.join(tmp, "bench.ogv") - ff(src("testsrc2", 320, 240, 25, 2) + ["-c:v", "libtheora", "-b:v", "600k", "-g", "25", bench]) - ctx.emit("theora_bench", {"file": b64(open(bench, "rb").read()), "width": 320, "height": 240}) + # 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) From 3e336392728f51f6bd0856697405e648b4a3867b Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:43:48 -0500 Subject: [PATCH 18/27] docs: legacy video (guide section, formats table rows, docs/video.md layers row); docs_legacy inputs --- docs/guide/video.md | 71 +++++++++++++++++++++++++++++++++++ docs/video.md | 1 + tools/fixtures/docs_legacy.py | 33 ++++++++++++++++ 3 files changed, 105 insertions(+) create mode 100644 tools/fixtures/docs_legacy.py diff --git a/docs/guide/video.md b/docs/guide/video.md index 99e0395..28e87c7 100644 --- a/docs/guide/video.md +++ b/docs/guide/video.md @@ -288,6 +288,77 @@ editable:WritePixelsBuffer(Vector2.zero, editable.Size, v:toRGBA(frame).pixels) See [FORMATS.md](../FORMATS.md). Subtitle tracks of Matroska files are read as cues by `F.format("mkv").subtitles`. + +| fli / flc / flx | yes | - | FLIC (8-bit palettised, 15 / 16 / 24-bit) | +| smk | yes | - | Smacker video (SMK2 / SMK4) + Smacker audio / PCM | + +AVI, MOV / MP4 and MKV (V_MS/VFW/FOURCC, V_QUICKTIME) also decode the legacy codecs: Cinepak, Microsoft Video 1, +QuickTime Animation (RLE) and QuickTime Graphics (SMC). See [Legacy video](#legacy-video). + + +## Legacy video + +The 1990s formats and codecs decode to **rgba8** frames (they are palettised or RGB, not YUV), each frame painted +over the previous one, as the codecs define. Decoding is bit-exact with ffmpeg's. + +| Codec id | Name | Containers | Depths | +|---|---|---|---| +| `flic` | Autodesk FLI / FLC | fli | 8-bit palettised, 15 / 16 / 24-bit | +| `smackvid` | Smacker video | smk | 8-bit palettised | +| `cinepak` | Cinepak (`cvid`) | avi, mov, mkv | 24-bit, grey, 8-bit palettised | +| `msvideo1` | Microsoft Video 1 (`CRAM`, `MSVC`, `WHAM`) | avi, mov, mkv | 16-bit (5-5-5), 8-bit palettised | +| `qtrle` | QuickTime Animation (`rle `) | mov, mkv | 1, 2, 4, 8 (palettised or grey), 16, 24, 32 (alpha) | +| `smc` | QuickTime Graphics (`smc `) | mov, mkv | 8-bit palettised | + +Palettes come from the container: `track.palette` (256 entries, 4 bytes each: R, G, B, A) holds the AVI +BITMAPINFO palette or the QuickTime colour table (or the Macintosh default table it refers to); FLIC and Smacker +frames carry their own palette changes. + +```luau +local v = assert(F.video.open(cinepakBytes)) -- Cinepak in a QuickTime movie +assert(v.format == "mov" and v.codec == "cinepak") +local frames = 0 +while true do + local f = v:nextFrame() + if not f then break end + assert(f.image.format == "rgba8" and f.image.width == 64) + frames += 1 +end +assert(frames == v.frames) +``` + +FLIC files (`.fli` at 70 Hz ticks, `.flc` / `.flx` in milliseconds) open as videos; the ring frame (an extra frame +leading back to the first, for looping) is not shown unless you ask for it. + +```luau +local v = assert(F.video.open(flcBytes)) +print(v.format, v.codec, v.width, v.height, v.frameRate) -- fli flic 64 48 10 +assert(v.track.bitsPerPixel == 8 and v.frames == 10) +local f = assert(v:nextFrame()) +local r, g, b, a = F.ops.image.getPixel(f.image, 0, 0) -- palette colours, opaque +assert(r and g and b and a == 255) +local all = assert(F.format("fli").open(F.Bytes.reader(flcBytes), { ringFrame = true })) +assert(all.codec == "flic") +``` + +Smacker files carry up to seven audio tracks. The format decodes Smacker's packed audio (and raw PCM tracks) itself: +`v.audio` is the first track, `F.format("smk").openAudio(demuxer, track)` opens any of them. + +```luau +local v = assert(F.video.open(smkBytes)) +assert(v.format == "smk" and v.codec == "smackvid") +local a = assert(v.audio, tostring(v.audioError)) -- packed 16-bit stereo, 22050 Hz +assert(a.sampleRate == 22050 and a.channels == 2) +local Smk = F.format("smk") +for _, t in v.demuxer.tracks do + if t.kind == "audio" then + local dec = assert(Smk.openAudio(v.demuxer, t)) -- smackaudio, pcm_u8 or pcm_s16le + local pcm, n = dec:read(1000) + assert(n == 1000 and buffer.len(pcm) == n * dec.channels * 4) + end +end +``` + ## Gotchas - Pure-Luau decoding is CPU-bound: H.264 and VP8 are practical at low resolutions. Measure with `tools/bench.luau` diff --git a/docs/video.md b/docs/video.md index 184ca45..f2469d6 100644 --- a/docs/video.md +++ b/docs/video.md @@ -28,6 +28,7 @@ F.convert(gif, "avi") -- animated images become videos (un | `codecs/video/Video/Source` | what writers write: copied packets or frames encoded by a registry encoder, PCM from the audio | | `codecs/image/Yuv` | yuv420p <-> rgba8 (BT.601 / 709, limited / full range from `image.meta.yuv`), range remap | | `codecs/image/Vp8`, `Jpeg`, `Mpeg1` | the decoders (and the JPEG encoder) | +| `codecs/video/Legacy` | FLIC, Smacker, Cinepak, Microsoft Video 1, QuickTime RLE / SMC: rgba8, palettes from `track.palette` | | `video/` | the formats: demux into `containers/Demux`, `open` = `Video.open(demuxer, opts)`, `encode` via Source | Audio tracks reach the audio formats through the api hook `opts.openAudio(demuxer, track)` (a format never requires diff --git a/tools/fixtures/docs_legacy.py b/tools/fixtures/docs_legacy.py new file mode 100644 index 0000000..719f8fd --- /dev/null +++ b/tools/fixtures/docs_legacy.py @@ -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"}) From 286d193f144b4ad6b7b9530024f596665c169d6b Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:47:05 -0500 Subject: [PATCH 19/27] ws-voxel: model/mca (Anvil regions read-only: gzip / zlib / LZ4Block / stored / external .mcc chunks; 1.18+, 1.13-1.17 and pre-1.13 chunk layouts) into Voxels with exact block states; block entity shapes moved into codecs/model/Minecraft --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/codecs/model/Minecraft/init.luau | 87 +++++ src/Formats/model/mca/Chunk.luau | 135 +++++++ src/Formats/model/mca/Lz4Block.luau | 70 ++++ src/Formats/model/mca/init.luau | 355 +++++++++++++++++++ src/Formats/model/schematic/Common.luau | 86 +---- tests/model/mca.luau | 148 ++++++++ tools/fixtures/mca.py | 218 ++++++++++++ 9 files changed, 1032 insertions(+), 80 deletions(-) create mode 100644 src/Formats/model/mca/Chunk.luau create mode 100644 src/Formats/model/mca/Lz4Block.luau create mode 100644 src/Formats/model/mca/init.luau create mode 100644 tests/model/mca.luau create mode 100644 tools/fixtures/mca.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 3ffa1a8..702f9a2 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -38,6 +38,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | | model | fbx | .fbx | yes | yes | binary: true, ascii: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true | `tests/model/fbx.luau` | | model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true | `tests/model/gltf.luau` | +| model | mca | .mca .mcr | yes | - | voxels: true, blocks: true | `tests/model/mca.luau` | | model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` | | model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` | | model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 43dcd3c..ac05da1 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -410,6 +410,18 @@ local list: { Entry } = { return require("@formats/model/gltf") end, }, + { + name = "mca", + category = "model", + path = "model/mca", + extensions = { "mca", "mcr" }, + mime = { "application/x-minecraft-region" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/text/Nbt", "codecs/model/Minecraft", "codecs/compress/Lz4" }, + caps = { decode = true, encode = false, voxels = true, blocks = true }, + load = function() + return require("@formats/model/mca") + end, + }, { name = "obj", category = "model", diff --git a/src/Formats/codecs/model/Minecraft/init.luau b/src/Formats/codecs/model/Minecraft/init.luau index 5e31c3b..634757b 100644 --- a/src/Formats/codecs/model/Minecraft/init.luau +++ b/src/Formats/codecs/model/Minecraft/init.luau @@ -497,4 +497,91 @@ function Minecraft.blocksOf(v: Types.Voxels): ({ string }?, any) return states, out end +-- ------------------------------------------------------------------------------------------------ block entities +-- Block entity records in one shape, { pos = { x, y, z }, id, data } (Sponge v3's), from / to the flat +-- { x, y, z, id, ... } of MCEdit, Litematica and chunks, and Sponge v1 / v2's { Pos, Id, ... }. +local function int(v: any): number? + local n = Nbt.number(v) + if n == nil or n ~= n or n % 1 ~= 0 then + return nil + end + return n +end +local function ints(v: any): { number }? + if Nbt.isTag(v) and v.type == "intArray" then + return v.value + elseif type(v) == "table" and not Nbt.isTag(v) and (v :: any)[1] ~= nil then + local out: { number } = {} + for i, x in v :: { any } do + out[i] = Nbt.number(x) or 0 + end + return out + end + return nil +end +Minecraft.int = int -- the integer value of an NBT number | nil +Minecraft.ints = ints -- the numbers of an intArray or a list | nil + +local function rest(c: any, skip: { [string]: boolean }): { [string]: any } + local out, keys = {}, {} + for _, k in Types.keys(c) do + if not skip[k] then + out[k] = c[k] + table.insert(keys, k) + end + end + return Types.object(out, keys) +end + +local FLAT_SKIP = { x = true, y = true, z = true, id = true } +local POS_SKIP = { Pos = true, Id = true } + +-- blockEntity(c, style) -> the common shape of one record: style "flat" (MCEdit, Litematica), "pos" (Sponge v1 / v2), +-- "data" (Sponge v3) +function Minecraft.blockEntity(c: any, style: string): any + if type(c) ~= "table" or Nbt.isTag(c) then + return nil + end + if style == "flat" then + return { pos = { int(c.x) or 0, int(c.y) or 0, int(c.z) or 0 }, id = if type(c.id) == "string" then c.id else nil, data = rest(c, FLAT_SKIP) } + end + local p = ints(c.Pos) or { 0, 0, 0 } + local data = if style == "data" then (if type(c.Data) == "table" then c.Data else Types.object()) else rest(c, POS_SKIP) + return { pos = { p[1] or 0, p[2] or 0, p[3] or 0 }, id = if type(c.Id) == "string" then c.Id else nil, data = data } +end + +-- flatBlockEntity(be, style) -> the record in a flavour's shape (the inverse of blockEntity) +function Minecraft.flatBlockEntity(be: any, style: string): any + local o = Types.object() + local data = if type(be.data) == "table" then be.data else Types.object() + if style == "flat" then + Types.set(o, "x", be.pos[1]) + Types.set(o, "y", be.pos[2]) + Types.set(o, "z", be.pos[3]) + if be.id then + Types.set(o, "id", be.id) + end + for _, k in Types.keys(data) do + if not FLAT_SKIP[k] then + Types.set(o, k, data[k]) + end + end + return o + end + Types.set(o, "Pos", Nbt.intArray({ be.pos[1], be.pos[2], be.pos[3] })) + if be.id then + Types.set(o, "Id", be.id) + end + if style == "data" then + Types.set(o, "Data", data) + else + for _, k in Types.keys(data) do + if not POS_SKIP[k] then + Types.set(o, k, data[k]) + end + end + end + return o +end + return Minecraft diff --git a/src/Formats/model/mca/Chunk.luau b/src/Formats/model/mca/Chunk.luau new file mode 100644 index 0000000..75764a4 --- /dev/null +++ b/src/Formats/model/mca/Chunk.luau @@ -0,0 +1,135 @@ +--!strict +-- model/mca/Chunk: the blocks of one Anvil chunk's NBT, from the Minecraft wiki "Chunk format" page, in the three +-- layouts it has had: 1.18+ (root sections[] with block_states { palette, data }, non-spanning packing, at least +-- 4 bits, yPos), 1.13 - 1.17 (Level.Sections[] with Palette + BlockStates, spanning before DataVersion 2529 = +-- 20w17a), and before 1.13 (Level.Sections[] with Blocks / Add / Data nibble arrays, numeric ids through +-- codecs/model/Minecraft legacyState). Each section is 16 x 16 x 16 cells in Minecraft's order (x, then z, then y). +local Types = require("@formats/Types") +local Nbt = require("@formats/codecs/text/Nbt") +local Mc = require("@formats/codecs/model/Minecraft") + +local Chunk = {} + +local Packed = Mc.Packed + +export type Section = { y: number, states: { string }, cells: buffer } -- cells: u16 per cell, 4096, x-z-y order +export type Blocks = { + x: number, -- chunk coordinates (xPos / zPos) + z: number, + dataVersion: number?, + sections: { Section }, + blockEntities: { any }, -- the chunk's records as they are (absolute x, y, z) + entities: { any }, -- entities stored in the chunk (before 1.17) +} + +local function int(v: any): number? + local n = Nbt.number(v) + return if n and n == n and n % 1 == 0 then n else nil +end + +local function list(v: any): { any } + return if type(v) == "table" and not Nbt.isTag(v) and not Types.isObject(v) then v else {} +end + +-- a palette section (1.13+): states from the palette compounds, cells from the packed array +local function paletted(y: number, palette: { any }, data: any, minBits: number, spanning: boolean): (Section?, string?) + local states = table.create(#palette) :: { string } + for i, c in palette do + local s = Mc.stateFromNbt(c) + if not s then + return nil, "section " .. y .. ": bad palette entry " .. i + end + states[i] = s + end + if #states == 0 then + return nil, nil + end + local cells = buffer.create(8192) + if #states > 1 or data ~= nil then + if not (Nbt.isTag(data) and data.type == "longArray") then + return nil, "section " .. y .. ": no block state data" + end + local bits = Packed.bitsFor(#states, minBits) + local ok, e = Packed.unpack(data.value, bits, 4096, spanning, cells, #states) + if not ok then + return nil, "section " .. y .. ": " .. tostring(e) + end + end + return { y = y, states = states, cells = cells }, nil +end + +-- blocks(root) -> Blocks | nil, message: the sections of a decoded chunk +function Chunk.blocks(root: any): (Blocks?, string?) + if type(root) ~= "table" or not Types.isObject(root) then + return nil, "chunk NBT is not a compound" + end + local dv = int(root.DataVersion) + local level = if Types.isObject(root.Level) then root.Level else root + local x, z = int(level.xPos), int(level.zPos) + if not x or not z then + return nil, "chunk without xPos / zPos" + end + local out: Blocks = { x = x, z = z, dataVersion = dv, sections = {}, blockEntities = {}, entities = list(level.Entities) } + if root.sections ~= nil then + -- 1.18+ + for _, s in list(root.sections) do + local y = int(s.Y) + local bs = s.block_states + if y and type(bs) == "table" and not Nbt.isTag(bs) then + local sec, e = paletted(y, list(bs.palette), bs.data, 4, false) + if e then + return nil, e + end + if sec then + table.insert(out.sections, sec) + end + end + end + out.blockEntities = list(root.block_entities) + return out, nil + end + for _, s in list(level.Sections) do + local y = int(s.Y) + if y then + if s.Palette ~= nil then + local sec, e = paletted(y, list(s.Palette), s.BlockStates, 4, (dv or 0) < 2529) + if e then + return nil, e + end + if sec then + table.insert(out.sections, sec) + end + elseif type(s.Blocks) == "buffer" then + local blocks = s.Blocks :: buffer + if buffer.len(blocks) < 4096 then + return nil, "section " .. y .. ": short Blocks array" + end + local data = if type(s.Data) == "buffer" and buffer.len(s.Data) >= 2048 then s.Data else nil + local add = if type(s.Add) == "buffer" and buffer.len(s.Add) >= 2048 then s.Add else nil + local slots: { [number]: number } = {} + local states: { string } = {} + local cells = buffer.create(8192) + for i = 0, 4095 do + local id = buffer.readu8(blocks, i) + if add then + id += Packed.nibble(add, 0, i, false) * 256 + end + local d = if data then Packed.nibble(data, 0, i, false) else 0 + local key = id * 16 + d + local slot = slots[key] + if not slot then + table.insert(states, Mc.legacyState(id, d)) + slot = #states - 1 + slots[key] = slot + end + buffer.writeu16(cells, i * 2, slot :: number) + end + table.insert(out.sections, { y = y, states = states, cells = cells }) + end + end + end + out.blockEntities = list(level.TileEntities) + return out, nil +end + +return Chunk diff --git a/src/Formats/model/mca/Lz4Block.luau b/src/Formats/model/mca/Lz4Block.luau new file mode 100644 index 0000000..de5d700 --- /dev/null +++ b/src/Formats/model/mca/Lz4Block.luau @@ -0,0 +1,70 @@ +--!strict +-- model/mca/Lz4Block: the lz4-java LZ4BlockOutputStream framing Minecraft (24w04a+) uses for compression type 4 +-- chunks, from lz4-java's LZ4BlockOutputStream source: blocks of "LZ4Block", a token (method 0x10 raw / 0x20 LZ4 | +-- level), compressed and decompressed lengths and an XXH32 checksum (little-endian i32s; not verified), then the +-- block, each block independent; an empty block ends the stream. The blocks decode through codecs/compress/Lz4. +local Lz4 = require("@formats/codecs/compress/Lz4") + +local Lz4Block = {} + +local MAGIC = "LZ4Block" + +-- decode(buf, offset, length, maxBytes) -> buffer | nil, message +function Lz4Block.decode(b: buffer, offset: number, length: number, maxBytes: number): (buffer?, string?) + local p, e = offset, offset + length + local parts, total = {}, 0 + while true do + if p + 21 > e then + if #parts > 0 and p >= e then + break -- some writers stop without the empty end block + end + return nil, "truncated LZ4 block header" + end + if buffer.readstring(b, p, 8) ~= MAGIC then + return nil, "bad LZ4Block magic" + end + local token = buffer.readu8(b, p + 8) + local clen, dlen = buffer.readi32(b, p + 9), buffer.readi32(b, p + 13) + p += 21 + local method = token // 16 * 16 + if clen < 0 or dlen < 0 or p + clen > e then + return nil, "truncated LZ4 block" + end + if dlen == 0 and clen == 0 then + break + end + total += dlen + if total > maxBytes then + return nil, "limit: chunk inflates past maxBytes" + end + if method == 0x10 then + if clen ~= dlen then + return nil, "raw LZ4 block length mismatch" + end + local out = buffer.create(dlen) + buffer.copy(out, 0, b, p, clen) + table.insert(parts, out) + elseif method == 0x20 then + local out, err = Lz4.decompress(b, p, clen, dlen) + if not out then + return nil, "LZ4: " .. tostring(err and err.message) + end + table.insert(parts, out) + else + return nil, "unsupported: LZ4Block method " .. method + end + p += clen + end + if #parts == 1 then + return parts[1], nil + end + local res = buffer.create(total) + local w = 0 + for _, part in parts do + buffer.copy(res, w, part) + w += buffer.len(part) + end + return res, nil +end + +return Lz4Block diff --git a/src/Formats/model/mca/init.luau b/src/Formats/model/mca/init.luau new file mode 100644 index 0000000..c5d1558 --- /dev/null +++ b/src/Formats/model/mca/init.luau @@ -0,0 +1,355 @@ +--!strict +-- model/mca: Minecraft Anvil region files (r...mca: 32 x 32 chunks), read-only. New code, from the Minecraft +-- wiki "Region file format" and "Chunk format" pages. Supports: the location / timestamp header, chunk payloads +-- compressed with gzip, zlib (codecs/compress/Deflate), LZ4 (lz4-java block streams, 24w04a+: model/mca/Lz4Block over +-- codecs/compress/Lz4) or stored, external .mcc chunks through opts.resolve, and every chunk layout: 1.18+ sections, +-- 1.13 - 1.17 palettes (spanning and not) and pre-1.13 numeric ids (model/mca/Chunk). +-- decode -> a Scene (meta.up = "y", one unit = one block) with one Types.Voxels covering the chosen chunks +-- (opts.chunks, opts.area; by default every chunk, between the lowest and highest section holding blocks) with +-- voxels.blocks (exact states, block entities relative to the grid), placed by its node at the world position of its +-- minimum corner. meta.source.chunks lists every chunk read (local and world coordinates, timestamp, compression, +-- DataVersion) with its whole NBT (chunk.nbt; opts.keepNbt = false drops it). Mca.list / Mca.chunk read the header +-- and one chunk's NBT without building voxels. +-- Not supported: writing; custom (127) chunk compression; LZ4 checksums are not verified; entities stored in the +-- separate entities/ region files (1.17+) are another file (load it with Mca.chunk). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Deflate = require("@formats/codecs/compress/Deflate") +local Nbt = require("@formats/codecs/text/Nbt") +local Mc = require("@formats/codecs/model/Minecraft") +local Chunk = require("@formats/model/mca/Chunk") +local Lz4Block = require("@formats/model/mca/Lz4Block") + +-- ------------------------------------------------------------------------------------------------ contract +local Mca = { + name = "mca", + category = "model", + extensions = { "mca", "mcr" }, + mime = { "application/x-minecraft-region" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/text/Nbt", "codecs/model/Minecraft", "codecs/compress/Lz4" }, + caps = { decode = true, encode = false, voxels = true, blocks = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + chunks: { { number } }?, -- only these chunks: { { x, z } } local coordinates 0 .. 31 (default all) + area: { number }?, -- only blocks inside { minX, minY, minZ, maxX, maxY, maxZ } (world coordinates, inclusive) + maxCells: number?, -- refuse grids with more cells (default 2^25: pick chunks or an area for big regions) + maxBytes: number?, -- refuse a chunk that inflates past this (default 2^26) + keepNbt: boolean?, -- keep each chunk's NBT in meta.source.chunks[i].nbt (default true) + region: { number }?, -- the region's coordinates { x, z } (default: from opts.name "r...mca"), for .mcc files + name: string?, -- the file name (the api fills it in) + resolve: ((string) -> buffer?)?, -- reads a sibling file: external chunks c...mcc +} +export type Entry = { + x: number, -- local chunk coordinates 0 .. 31 + z: number, + sector: number, -- 4 KiB sector of the chunk + sectors: number, + timestamp: number, -- seconds since 1970 +} + +-- ------------------------------------------------------------------------------------------------ constants +local COMPRESSION = { [1] = "gzip", [2] = "zlib", [3] = "none", [4] = "lz4", [127] = "custom" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Mca.sniff(r: Bytes.Reader): number + local n = r.limit - r.base + if n < 8192 then + return 0 + end + local sectors = (n + 4095) // 4096 + local used, b = 0, r.buf + for i = 0, 1023 do + local e = bit32.byteswap(buffer.readu32(b, r.base + i * 4)) + if e ~= 0 then + local off, cnt = e // 256, e % 256 + if off < 2 or cnt == 0 or off + cnt > sectors then + return 0 + end + used += 1 + if used == 1 then + local p = r.base + off * 4096 + if p + 5 > r.limit then + return 0 + end + local c = buffer.readu8(b, p + 4) % 128 + if COMPRESSION[c] == nil then + return 0 + end + end + end + end + return if used > 0 then 0.8 else 0.2 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- list(r) -> { Entry } | nil, Err: the chunks present in the region (location and timestamp tables) +function Mca.list(r: Bytes.Reader): ({ Entry }?, Err.Err?) + local n = r.limit - r.base + if n < 8192 then + return nil, Err.new(Err.TRUNCATED, "region header is 8192 bytes, file has " .. n) + end + local out: { Entry } = {} + for i = 0, 1023 do + local e = bit32.byteswap(buffer.readu32(r.buf, r.base + i * 4)) + if e ~= 0 then + table.insert(out, { + x = i % 32, + z = i // 32, + sector = e // 256, + sectors = e % 256, + timestamp = bit32.byteswap(buffer.readu32(r.buf, r.base + 4096 + i * 4)), + }) + end + end + return out, nil +end + +local function regionCoords(o: DecodeOptions): (number?, number?) + if o.region then + return o.region[1], o.region[2] + end + if o.name then + local x, z = string.match(o.name, "r%.(%-?%d+)%.(%-?%d+)%.mc[ar]$") + if x then + return tonumber(x), tonumber(z) + end + end + return nil, nil +end + +-- payload(r, e, o) -> the chunk's uncompressed NBT bytes, compression name | nil, Err +local function payload(r: Bytes.Reader, e: Entry, o: DecodeOptions): (buffer?, any) + local p = r.base + e.sector * 4096 + if p + 5 > r.limit then + return nil, Err.new(Err.TRUNCATED, string.format("chunk %d,%d starts past the end", e.x, e.z), p - r.base) + end + local len = bit32.byteswap(buffer.readu32(r.buf, p)) + local ctype = buffer.readu8(r.buf, p + 4) + local data: buffer, start: number, size: number = r.buf, p + 5, len - 1 + if ctype >= 128 then + -- stored in c...mcc next to the region (whole file = the compressed payload) + local rx, rz = regionCoords(o) + if not o.resolve or rx == nil then + return nil, Err.new(Err.UNSUPPORTED, string.format("chunk %d,%d is in an external .mcc file (pass opts.resolve and the region coordinates)", e.x, e.z)) + end + local name = string.format("c.%d.%d.mcc", (rx :: number) * 32 + e.x, (rz :: number) * 32 + e.z) + local ext = o.resolve(name) + if type(ext) ~= "buffer" then + return nil, Err.new(Err.IO, "cannot read " .. name) + end + data, start, size = ext, 0, buffer.len(ext) + ctype -= 128 + elseif len < 1 or p + 4 + len > r.limit then + return nil, Err.new(Err.TRUNCATED, string.format("chunk %d,%d runs past the end", e.x, e.z), p - r.base) + end + local comp = COMPRESSION[ctype] + local maxBytes = o.maxBytes or 2 ^ 26 + local out, err + if comp == "gzip" then + out, err = Deflate.gunzip(data, start, size) + elseif comp == "zlib" then + out, err = Deflate.zlib(data, start, size) + elseif comp == "none" then + out = buffer.create(size :: number) + buffer.copy(out, 0, data, start, size) + elseif comp == "lz4" then + local msg + out, msg = Lz4Block.decode(data, start, size :: number, maxBytes) + if not out then + err = Err.from(msg, start - r.base) + end + else + return nil, Err.new(Err.UNSUPPORTED, string.format("chunk %d,%d: compression type %d", e.x, e.z, ctype)) + end + if not out then + return nil, err + end + if buffer.len(out) > maxBytes then + return nil, Err.new(Err.LIMIT, string.format("chunk %d,%d inflates past maxBytes", e.x, e.z)) + end + return out, comp +end + +-- chunk(r, x, z, opts?) -> the chunk's NBT root, compression | nil, Err (nil, nil when the chunk is absent) +function Mca.chunk(r: Bytes.Reader, x: number, z: number, opts: DecodeOptions?): (any, any) + local o: DecodeOptions = opts or {} + if x < 0 or x > 31 or z < 0 or z > 31 or x % 1 ~= 0 or z % 1 ~= 0 then + return nil, Err.new(Err.ARG, "chunk coordinates are 0 .. 31") + end + local entries, lerr = Mca.list(r) + if not entries then + return nil, lerr + end + for _, e in entries do + if e.x == x and e.z == z then + local raw, comp = payload(r, e, o) + if not raw then + return nil, comp + end + local v, info = Nbt.decode(raw, { endian = "big", maxBytes = o.maxBytes }) + if v == nil then + return nil, info + end + return v, comp + end + end + return nil, nil +end + +function Mca.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local o: DecodeOptions = opts or {} + local entries, lerr = Mca.list(r) + if not entries then + return nil, lerr + end + local want: { [number]: boolean }? = nil + if o.chunks then + local w: { [number]: boolean } = {} + for _, c in o.chunks do + w[(c[1] or 0) + 32 * (c[2] or 0)] = true + end + want = w + end + local area = o.area + if area and #area ~= 6 then + return nil, Err.new(Err.ARG, "area is { minX, minY, minZ, maxX, maxY, maxZ }") + end + local keep = o.keepNbt ~= false + local chunks: { Chunk.Blocks } = {} + local infos = {} + for _, e in entries do + if not want or want[e.x + 32 * e.z] then + local raw, comp = payload(r, e, o) + if not raw then + return nil, comp + end + local v, info = Nbt.decode(raw, { endian = "big", maxBytes = o.maxBytes }) + if v == nil then + return nil, Err.new(info.code, string.format("chunk %d,%d: %s", e.x, e.z, info.message)) + end + local blocks, berr = Chunk.blocks(v) + if not blocks then + return nil, Err.from(string.format("chunk %d,%d: %s", e.x, e.z, tostring(berr))) + end + local inArea = not area or (blocks.x * 16 <= area[4] and blocks.x * 16 + 15 >= area[1] and blocks.z * 16 <= area[6] and blocks.z * 16 + 15 >= area[3]) + if inArea then + table.insert(chunks, blocks) + table.insert(infos, { x = e.x, z = e.z, worldX = blocks.x, worldZ = blocks.z, timestamp = e.timestamp, compression = comp, dataVersion = blocks.dataVersion, nbt = if keep then v else nil }) + end + end + end + -- the bounds: chunks in x / z, sections holding anything but air in y, cut to the area + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + for _, c in chunks do + lo[1], hi[1] = math.min(lo[1], c.x * 16), math.max(hi[1], c.x * 16 + 15) + lo[3], hi[3] = math.min(lo[3], c.z * 16), math.max(hi[3], c.z * 16 + 15) + for _, s in c.sections do + local solid = false + for _, st in s.states do + if not Mc.isAir(st) then + solid = true + break + end + end + if solid then + lo[2], hi[2] = math.min(lo[2], s.y * 16), math.max(hi[2], s.y * 16 + 15) + end + end + end + if area then + for k = 1, 3 do + lo[k], hi[k] = math.max(lo[k], area[k]), math.min(hi[k], area[k + 3]) + if area[k] > area[k + 3] then + return nil, Err.new(Err.ARG, "area minimum past its maximum") + end + end + if lo[2] == math.huge then + lo[2], hi[2] = area[2], area[5] + end + end + if lo[2] == math.huge then + lo[2], hi[2] = 0, -1 -- no blocks at all + end + if #chunks == 0 then + lo, hi = { 0, 0, 0 }, { -1, -1, -1 } + end + local sx, sy, sz = math.max(0, hi[1] - lo[1] + 1), math.max(0, hi[2] - lo[2] + 1), math.max(0, hi[3] - lo[3] + 1) + local n = sx * sy * sz + if n > (o.maxCells or 2 ^ 25) then + return nil, Err.new(Err.LIMIT, string.format("%d x %d x %d cells is over maxCells: choose opts.chunks or opts.area", sx, sy, sz)) + end + -- one palette for the grid (air first), each section copied in through a remap table + local states = { "minecraft:air" } + local index: { [string]: number } = { ["minecraft:air"] = 0 } + local grid = buffer.create(n * 2) + local bes, ents = {}, {} + for _, c in chunks do + local cx, cz = c.x * 16 - lo[1], c.z * 16 - lo[3] + for _, s in c.sections do + local cy = s.y * 16 - lo[2] + if cy + 15 >= 0 and cy < sy and cx + 15 >= 0 and cx < sx and cz + 15 >= 0 and cz < sz then + local lut = table.create(#s.states) :: { number } + for i, st in s.states do + local g = index[st] + if g == nil then + table.insert(states, st) + g = #states - 1 + index[st] = g + end + lut[i] = g + end + if #states > 65536 then + return nil, Err.new(Err.LIMIT, "more than 65536 block states") + end + local cells = s.cells + local y0, y1 = math.max(0, -cy), math.min(15, sy - 1 - cy) + local z0, z1 = math.max(0, -cz), math.min(15, sz - 1 - cz) + local x0, x1 = math.max(0, -cx), math.min(15, sx - 1 - cx) + for y = y0, y1 do + for z = z0, z1 do + local src = ((y * 16 + z) * 16 + x0) * 2 + local dst = ((cx + x0) + sx * ((cy + y) + sy * (cz + z))) * 2 + for _ = x0, x1 do + buffer.writeu16(grid, dst, lut[buffer.readu16(cells, src) + 1] or 0) + src += 2 + dst += 2 + end + end + end + end + end + for _, rec in c.blockEntities do + local be = Mc.blockEntity(rec, "flat") + if be then + local px, py, pz = be.pos[1] - lo[1], be.pos[2] - lo[2], be.pos[3] - lo[3] + if px >= 0 and px < sx and py >= 0 and py < sy and pz >= 0 and pz < sz then + be.pos = { px, py, pz } + table.insert(bes, be) + end + end + end + for _, ent in c.entities do + table.insert(ents, ent) + end + end + local v = Mc.voxels(sx, sy, sz, states, grid) + local b = v.blocks :: Types.VoxelBlocks + b.blockEntities = bes + b.entities = ents + local scene = Types.Scene.new() + scene.voxels = { v } + scene.nodes = { { name = o.name, children = {}, voxels = 1, translation = { lo[1], lo[2], lo[3] } } } + scene.roots = { 1 } + scene.meta.up = "y" + scene.meta.unit = 1 + local rx, rz = regionCoords(o) + scene.meta.source = { format = "mca", region = if rx then { rx, rz } else nil, chunks = infos } + return scene, nil +end + +return Mca diff --git a/src/Formats/model/schematic/Common.luau b/src/Formats/model/schematic/Common.luau index ee1002a..3b3fd7b 100644 --- a/src/Formats/model/schematic/Common.luau +++ b/src/Formats/model/schematic/Common.luau @@ -4,6 +4,7 @@ -- converted from / to MCEdit's and Litematica's flat { x, y, z, id, ... } and Sponge v2's { Pos, Id, ... }). local Types = require("@formats/Types") local Nbt = require("@formats/codecs/text/Nbt") +local Mc = require("@formats/codecs/model/Minecraft") local Common = {} @@ -19,13 +20,7 @@ export type Region = { } -- int(v) -> the integer value of an NBT number (byte / short / int / long tag or plain number) | nil -function Common.int(v: any): number? - local n = Nbt.number(v) - if n == nil or n ~= n or n % 1 ~= 0 then - return nil - end - return n -end +Common.int = Mc.int -- dims(a, b, c, max) -> sx, sy, sz | nil, message: positive sizes whose product stays under max cells function Common.dims(a: any, b: any, c: any, max: number): (number?, any, number?) @@ -43,80 +38,11 @@ function Common.dims(a: any, b: any, c: any, max: number): (number?, any, number end -- ints(v) -> the numbers of an intArray tag or a list of numbers | nil -function Common.ints(v: any): { number }? - if Nbt.isTag(v) and v.type == "intArray" then - return v.value - elseif type(v) == "table" and not Nbt.isTag(v) and (v :: any)[1] ~= nil then - local out: { number } = {} - for i, x in v :: { any } do - out[i] = Nbt.number(x) or 0 - end - return out - end - return nil -end +Common.ints = Mc.ints -local function rest(c: any, skip: { [string]: boolean }): { [string]: any } - local out, keys = {}, {} - for _, k in Types.keys(c) do - if not skip[k] then - out[k] = c[k] - table.insert(keys, k) - end - end - return Types.object(out, keys) -end - -local FLAT_SKIP = { x = true, y = true, z = true, id = true } -local POS_SKIP = { Pos = true, Id = true } - --- blockEntity(c, style) -> the common shape of one record: style "flat" (MCEdit, Litematica), "pos" (Sponge v1 / v2), --- "data" (Sponge v3) -function Common.blockEntity(c: any, style: string): any - if type(c) ~= "table" or Nbt.isTag(c) then - return nil - end - if style == "flat" then - return { pos = { Common.int(c.x) or 0, Common.int(c.y) or 0, Common.int(c.z) or 0 }, id = if type(c.id) == "string" then c.id else nil, data = rest(c, FLAT_SKIP) } - end - local p = Common.ints(c.Pos) or { 0, 0, 0 } - local data = if style == "data" then (if type(c.Data) == "table" then c.Data else Types.object()) else rest(c, POS_SKIP) - return { pos = { p[1] or 0, p[2] or 0, p[3] or 0 }, id = if type(c.Id) == "string" then c.Id else nil, data = data } -end - --- flatBlockEntity(be, style) -> the record in a flavour's shape (the inverse of blockEntity) -function Common.flatBlockEntity(be: any, style: string): any - local o = Types.object() - local data = if type(be.data) == "table" then be.data else Types.object() - if style == "flat" then - Types.set(o, "x", be.pos[1]) - Types.set(o, "y", be.pos[2]) - Types.set(o, "z", be.pos[3]) - if be.id then - Types.set(o, "id", be.id) - end - for _, k in Types.keys(data) do - if not FLAT_SKIP[k] then - Types.set(o, k, data[k]) - end - end - return o - end - Types.set(o, "Pos", Nbt.intArray({ be.pos[1], be.pos[2], be.pos[3] })) - if be.id then - Types.set(o, "Id", be.id) - end - if style == "data" then - Types.set(o, "Data", data) - else - for _, k in Types.keys(data) do - if not POS_SKIP[k] then - Types.set(o, k, data[k]) - end - end - end - return o -end +-- blockEntity(c, style) / flatBlockEntity(be, style): codecs/model/Minecraft's (shared with model/mca) +Common.blockEntity = Mc.blockEntity +Common.flatBlockEntity = Mc.flatBlockEntity -- list(v) -> v when it is an NBT list (array), else an empty list function Common.list(v: any): { any } diff --git a/tests/model/mca.luau b/tests/model/mca.luau new file mode 100644 index 0000000..30ef1c7 --- /dev/null +++ b/tests/model/mca.luau @@ -0,0 +1,148 @@ +-- model/mca tests: region files with 1.18+ chunks (each compression: zlib, gzip, stored, LZ4 block streams), +-- 1.16 / 1.13 / 1.12 chunks (palettes non-spanning and spanning, numeric ids with Add nibbles) and an external .mcc +-- chunk: every cell of the assembled grid against the fixture (a CRC of the cell texts), placement, the chunk list, +-- block entities, opts.chunks / opts.area / maxCells, Mca.list / Mca.chunk, detection, errors and the fuzz pass. +-- Fixtures: tools/fixtures/mca.py. +local T = require("@tests/T") +local F = require("@formats") +local Mca = require("@formats/model/mca") +local Mc = require("@formats/codecs/model/Minecraft") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/mca") + +local t = T.suite("mca") + +t:eq(Mca.name, "mca", "name") +t:check(Mca.caps.decode and not Mca.caps.encode, "caps: read-only") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end + +-- the fixture's cell texts: the state, or "legacy::" inside chunks without a DataVersion +local function cellText(scene: Types.Scene): string + local v = (scene.voxels :: { Types.Voxels })[1] + local b = v.blocks :: Types.VoxelBlocks + local o = scene.nodes[1].translation :: { number } + local legacyChunk: { [string]: boolean } = {} + for _, c in scene.meta.source.chunks do + if c.dataVersion == nil then + legacyChunk[c.worldX .. "," .. c.worldZ] = true + end + end + local sx, sy, sz = v.size[1], v.size[2], v.size[3] + local parts = table.create(sx * sy * sz) + local i = 0 + for z = 0, sz - 1 do + for y = 0, sy - 1 do + for x = 0, sx - 1 do + local st = b.palette[buffer.readu16(b.data, i * 2) + 1] + local wx, wz = o[1] + x, o[3] + z + if legacyChunk[(wx // 16) .. "," .. (wz // 16)] then + local id, d = Mc.legacyId(st) + st = "legacy:" .. tostring(id) .. ":" .. tostring(d) + end + i += 1 + parts[i] = st + end + end + end + return table.concat(parts, "\n") +end + +for _, c in Fx.regions do + local opts = { name = c.name, resolve = function(name: string): buffer? + local f = c.files and c.files[name] + return if f then buffer.fromstring(f) else nil + end } + local scene, err = Mca.decode(reader(c.data), opts) + t:check(scene ~= nil, c.name .. ": " .. tostring(err)) + local s = scene :: Types.Scene + local v = (s.voxels :: { Types.Voxels })[1] + t:eq(table.concat(v.size, ","), table.concat(c.size, ","), c.name .. ": size") + t:eq(table.concat(s.nodes[1].translation :: { number }, ","), table.concat(c.min, ","), c.name .. ": minimum corner") + t:eq(Crc32.of(buffer.fromstring(cellText(s))), c.crc, c.name .. ": every cell") + t:eq(#s.meta.source.chunks, #c.chunks, c.name .. ": chunks") + for i, want in c.chunks do + local got = s.meta.source.chunks[i] + t:check(got.x == want.x and got.z == want.z, c.name .. ": chunk " .. i .. " position") + t:eq(got.timestamp, want.timestamp, c.name .. ": chunk " .. i .. " timestamp") + t:eq(got.compression, want.compression, c.name .. ": chunk " .. i .. " compression") + t:eq(got.dataVersion, want.dataVersion, c.name .. ": chunk " .. i .. " DataVersion") + t:check(got.nbt ~= nil, c.name .. ": chunk " .. i .. " NBT kept") + end + t:eq(#((v.blocks :: Types.VoxelBlocks).blockEntities :: { any }), c.blockEntities, c.name .. ": block entities") + -- colours follow the blocks + local air = 0 + for i = 0, buffer.len(v.data) - 1 do + if buffer.readu8(v.data, i) == 0 then + air += 1 + end + end + t:check(air > 0 and air < buffer.len(v.data), c.name .. ": colour grid") +end + +-- details on the 1.18+ region +do + local c = Fx.regions[1] + local list = assert(Mca.list(reader(c.data))) + t:eq(#list, 4, "list") + local nbt, comp = Mca.chunk(reader(c.data), 3, 2) + t:check(nbt and nbt.xPos == 3 and nbt.Status == "minecraft:full", "Mca.chunk") + t:eq(comp, "lz4", "Mca.chunk compression") + t:eq(Mca.chunk(reader(c.data), 9, 9), nil, "absent chunk") + -- only some chunks / an area + local one = assert(Mca.decode(reader(c.data), { chunks = { { 1, 0 } }, keepNbt = false })) + t:eq(table.concat((one.voxels :: { Types.Voxels })[1].size, ","), "16,48,16", "opts.chunks") + t:eq(one.meta.source.chunks[1].nbt, nil, "keepNbt = false") + local part = assert(Mca.decode(reader(c.data), { area = { 4, -64, 4, 19, -60, 9 } })) + local pv = (part.voxels :: { Types.Voxels })[1] + t:eq(table.concat(pv.size, ","), "16,5,6", "opts.area size") + t:eq(table.concat(part.nodes[1].translation :: { number }, ","), "4,-64,4", "opts.area corner") + -- the area's cells equal the same cells of the whole grid + local whole = assert(Mca.decode(reader(c.data))) + local wv = (whole.voxels :: { Types.Voxels })[1] + local wo = whole.nodes[1].translation :: { number } + local bad = 0 + for z = 0, 5 do + for y = 0, 4 do + for x = 0, 15 do + local a = pv.blocks.palette[buffer.readu16(pv.blocks.data, (x + 16 * (y + 5 * z)) * 2) + 1] + local gx, gy, gz = 4 + x - wo[1], -64 + y - wo[2], 4 + z - wo[3] + local w = wv.blocks.palette[buffer.readu16(wv.blocks.data, (gx + wv.size[1] * (gy + wv.size[2] * gz)) * 2) + 1] + if a ~= w then + bad += 1 + end + end + end + end + t:eq(bad, 0, "area cells") + local _, e = Mca.decode(reader(c.data), { maxCells = 1000 }) + t:check(e and e.code == Err.LIMIT, "maxCells") + t:eq(F.detect(c.data), "mca", "F.detect") + local viaApi = F.load(c.data, { name = "r.0.0.mca" }) + t:check(viaApi and viaApi.kind == "scene", "F.load") + t:check(F.save(viaApi, nil, { format = "schem" }) ~= nil, "region -> .schem") +end + +-- errors +do + local ext = Fx.regions[3] + local _, e1 = Mca.decode(reader(ext.data)) + t:check(e1 and e1.code == Err.UNSUPPORTED, "external chunk without resolve") + local _, e2 = Mca.decode(reader(string.sub(Fx.regions[1].data, 1, 9000))) + t:check(e2 and e2.code == Err.TRUNCATED, "truncated region") + local _, e3 = Mca.decode(reader(string.rep("\0", 100))) + t:check(e3 and e3.code == Err.TRUNCATED, "short header") + local _, e4 = Mca.chunk(reader(Fx.regions[1].data), 40, 0) + t:check(e4 and e4.code == Err.ARG, "bad chunk coordinates") +end + +local samples = { Fx.regions[2].data, string.sub(Fx.regions[1].data, 1, 20000) } +t:fuzz("decode", function(b: buffer) + return Mca.decode(Bytes.reader(b)) +end, samples, { keepHeader = 0 }) +t:done() diff --git a/tools/fixtures/mca.py b/tools/fixtures/mca.py new file mode 100644 index 0000000..ff2bbbe --- /dev/null +++ b/tools/fixtures/mca.py @@ -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::" 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(" 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...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) From d22c72c1bc967dc4ff2a0628e50c4298e40e91dd Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:50:27 -0500 Subject: [PATCH 20/27] ws-video2: MPEG-2 field-picture / concealment-vector fixtures (a syntax-level writer in tools/fixtures/mpeg2.py), bit-exact; LuaJIT-friendlier hot paths; mpeg2 bench line --- src/Formats/codecs/video/Mpeg2/Decoder.luau | 67 ++++-- tests/codecs/mpeg2.luau | 4 +- tools/bench.luau | 17 ++ tools/fixtures/mpeg2.py | 252 +++++++++++++++++++- 4 files changed, 322 insertions(+), 18 deletions(-) diff --git a/src/Formats/codecs/video/Mpeg2/Decoder.luau b/src/Formats/codecs/video/Mpeg2/Decoder.luau index 4cd982c..e25801d 100644 --- a/src/Formats/codecs/video/Mpeg2/Decoder.luau +++ b/src/Formats/codecs/video/Mpeg2/Decoder.luau @@ -31,6 +31,7 @@ local readi32 = buffer.readi32 local writei32 = buffer.writei32 local band = bit32.band local bor = bit32.bor +local bxor = bit32.bxor local lshift = bit32.lshift local rshift = bit32.rshift local bswap = bit32.byteswap @@ -549,12 +550,18 @@ function D.new(maxPixels: number?): Core mc(rY, stride, sb + sy * stride + sx, curY, stride, dOff, 16, h, hx, hy, avg) end -- chroma: horizontal vector / 2 truncated toward zero; vertical too in 4:2:0 - local mx = if mvx < 0 then -((-mvx) // 2) else mvx // 2 + local mx = mvx // 2 + if mvx < 0 then + mx = -((-mvx) // 2) + end local cx, cy, chh, cph, chx, chy chx = band(mx, 1) cx = mbCol * 8 + (mx - chx) // 2 if chroma == 1 then - local my = if mvy < 0 then -((-mvy) // 2) else mvy // 2 + local my = mvy // 2 + if mvy < 0 then + my = -((-mvy) // 2) + end chy = band(my, 1) cy = rowY // 2 + (my - chy) // 2 chh, cph = h // 2, ph // 2 @@ -563,7 +570,11 @@ function D.new(maxPixels: number?): Core cy = rowY + (mvy - chy) // 2 chh, cph = h, ph end - local cdOff = cdb + (if chroma == 1 then rowY // 2 else rowY) * cs + mbCol * 8 + local crow = rowY + if chroma == 1 then + crow = rowY // 2 + end + local cdOff = cdb + crow * cs + mbCol * 8 if cx < 0 or cy < 0 or cx + 8 + chx > chw or cy + chh + chy > cph then Dsp.edge(rCb, cs, csb, cx, cy, 8, chh, chw, cph, EDGE) mc(EDGE, 32, 0, curCb, cs, cdOff, 8, chh, chx, chy, avg) @@ -592,8 +603,15 @@ function D.new(maxPixels: number?): Core local function predictDir(d: number, avg: boolean) local o = d * 8 if not fieldPic then - local r = (if d == 0 then fwS else bwS) or cur :: Store - local ry, rcb, rcr = r.y, r.cb, r.cr + local r = bwS + if d == 0 then + r = fwS + end + if r == nil then + r = cur + end + local ref = r :: Store + local ry, rcb, rcr = ref.y, ref.cb, ref.cr if motionType == 1 then mcPart(ry, rcb, rcr, -1, -1, mbRow * 16, 16, MV[o + 1], MV[o + 2], avg) elseif motionType == 2 then @@ -736,7 +754,10 @@ function D.new(maxPixels: number?): Core dc = dcY else size = vlc(DC_CHROMA, DC_CHROMA_BITS) - dc = if b % 2 == 0 then dcCb else dcCr + dc = dcCr + if b % 2 == 0 then + dc = dcCb + end end if size > 0 then local diff = read(size) @@ -761,14 +782,24 @@ function D.new(maxPixels: number?): Core end local v = lshift(dc, 3 - dcPrec) writei32(blk, 0, v) - parityOdd = bit32.bxor(1, band(v, 1)) - q = if luma then intraQ else chromaIntraQ + parityOdd = bxor(1, band(v, 1)) + q = chromaIntraQ + if luma then + q = intraQ + end n = 1 else - q = if luma then nonIntraQ else chromaNonIntraQ + q = chromaNonIntraQ + if luma then + q = nonIntraQ + end + end + local lut, nextLut = DCT_NEXT, DCT_NEXT + if mbIntra and intraVlc then + lut, nextLut = DCT_B15, DCT_B15 + elseif n == 0 then + lut = DCT_FIRST end - local lut = if mbIntra and intraVlc then DCT_B15 elseif n == 0 then DCT_FIRST else DCT_NEXT - local nextLut = if mbIntra and intraVlc then DCT_B15 else DCT_NEXT local intra = mbIntra local qs = qscale local m2 = mpeg2 @@ -853,7 +884,9 @@ function D.new(maxPixels: number?): Core if neg then m = -m end - parityOdd = bit32.bxor(parityOdd, band(m, 1)) + if m2 then + parityOdd = bxor(parityOdd, band(m, 1)) + end -- saturate if m > 2047 then m = 2047 @@ -887,7 +920,10 @@ function D.new(maxPixels: number?): Core off = (mbRow * 16 + (if b >= 2 then 8 else 0)) * cw + mbCol * 16 + (if b % 2 == 1 then 8 else 0) end else - dst = if b % 2 == 0 then curCb else curCr + dst = curCr + if b % 2 == 0 then + dst = curCb + end local k = (b - 4) // 2 -- the vertical chroma block of a 4:2:2 macroblock if chroma == 1 then stride = cstride @@ -923,7 +959,10 @@ function D.new(maxPixels: number?): Core -- motion vectors of direction d (13818-2 7.6.3; MPEG-1: frame vectors, full_pel doubled) local function motionVectors(d: number) - local fh, fv = if d == 0 then fc00 else fc10, if d == 0 then fc01 else fc11 + local fh, fv = fc10, fc11 + if d == 0 then + fh, fv = fc00, fc01 + end local o, p, f = d * 8, d * 4, d * 2 if motionType == 1 and not fieldPic then local x = decodeMotion(fh, PMV[p + 1]) diff --git a/tests/codecs/mpeg2.luau b/tests/codecs/mpeg2.luau index fb3da3f..cd88a82 100644 --- a/tests/codecs/mpeg2.luau +++ b/tests/codecs/mpeg2.luau @@ -1,7 +1,7 @@ -- codecs/video/Mpeg2 tests. Against `ffmpeg -idct int` (tools/fixtures/mpeg2.py): every stream (progressive and -- interlaced frame pictures with field prediction and field DCT, top / bottom field first, 4:2:2, the alternate scan, -- Table B-15, the non-linear quantiser scale, DC precision 9..11, custom luma / chroma matrices, f_code > 1, an odd --- size, B-frames, dual prime) decodes one access unit at a time to exactly ffmpeg's planes, every frame, in display +-- size, B-frames, dual prime, field pictures, concealment vectors) decodes one access unit at a time to exactly ffmpeg's planes, every frame, in display -- order; the same stream written in random pieces gives the same frames; frame flags (mpeg2, chroma, progressive, -- topFieldFirst); frameImage (4:2:2 -> yuv420p, rgba8); the registry's VideoCodecDecoder; truncated and corrupted -- streams never throw; the fuzz no-throw pass. @@ -24,6 +24,8 @@ local STREAMS = { require("@tests/gen/mpeg2_c422"), require("@tests/gen/mpeg2_c422_ilace"), require("@tests/gen/mpeg2_dualprime"), + require("@tests/gen/mpeg2_fields"), + require("@tests/gen/mpeg2_fields_conceal"), } local t = T.suite("codecs/mpeg2") diff --git a/tools/bench.luau b/tools/bench.luau index b32ee01..4712a7c 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -964,11 +964,28 @@ do 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 diff --git a/tools/fixtures/mpeg2.py b/tools/fixtures/mpeg2.py index b9e1f00..17a931b 100644 --- a/tools/fixtures/mpeg2.py +++ b/tools/fixtures/mpeg2.py @@ -1,9 +1,11 @@ # 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) and from mjpegtools' mpeg2enc (dual-prime -# prediction in interlaced frame pictures), each with `ffmpeg -idct int` decoding as the reference: the IJG integer -# IDCT that codecs/video/Dsp reproduces, so the planes must match exactly. +# 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_.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 @@ -126,6 +128,14 @@ def generate(ctx): % (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"]} @@ -176,3 +186,239 @@ def zlib_crc32_mpeg(data): 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] From 6e0b80a7f2078685e0e64466659799b203e75451 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:51:14 -0500 Subject: [PATCH 21/27] ws-video2: MpegEs Picture type annotation (type baseline) --- src/Formats/containers/MpegEs.luau | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Formats/containers/MpegEs.luau b/src/Formats/containers/MpegEs.luau index 704db06..77be2ef 100644 --- a/src/Formats/containers/MpegEs.luau +++ b/src/Formats/containers/MpegEs.luau @@ -134,7 +134,7 @@ function MpegEs.pictures(b: buffer, off: number, limit: number): { Picture } local x = readu8(b, p + 4) * 256 + readu8(b, p + 5) t, tr = (x // 8) % 8, x // 64 end - cur = { offset = unitStart or p, size = 0, type = t, temporal = tr, gop = gop, sequence = seq, structure = st } + cur = { offset = unitStart or p, size = 0, type = t, temporal = tr, gop = gop, sequence = seq, structure = st } :: Picture unitStart, seq, gop = nil, false, false elseif code == 0xB7 and cur then cur.size = p + 4 - cur.offset From f86e12f051c5edb9185126288515c67020daba35 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:52:15 -0500 Subject: [PATCH 22/27] ws-voxel: model/qb (Qubicle Binary read + write: RGBA / BGRA, z orientation, RLE, visibility masks; exact colours in Voxels.colors) --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/model/qb/init.luau | 401 +++++++++++++++++++++++++++++++++ tests/model/qb.luau | 130 +++++++++++ tools/fixtures/_qb_encode.luau | 34 +++ tools/fixtures/qb.py | 156 +++++++++++++ 6 files changed, 734 insertions(+) create mode 100644 src/Formats/model/qb/init.luau create mode 100644 tests/model/qb.luau create mode 100644 tools/fixtures/_qb_encode.luau create mode 100644 tools/fixtures/qb.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 702f9a2..43bbcdf 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -42,6 +42,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` | | model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` | | model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` | +| model | qb | .qb | yes | yes | voxels: true, truecolor: true | `tests/model/qb.luau` | | model | rbxm | .rbxm .rbxl | yes | yes | tree: true, compression: "none", "lz4", "zstd" | `tests/model/rbxm.luau` | | model | rbxmx | .rbxmx .rbxlx | yes | yes | tree: true | `tests/model/rbxmx.luau` | | model | robloxmesh | .mesh | yes | yes | skinning: true, lods: true, versions: "1.00", "1.01", "2.00", "3.00", "3.01", "4.00", "4.01", "5.00", "6.00", "7.00" | `tests/model/robloxmesh.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index ac05da1..8369b75 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -458,6 +458,18 @@ local list: { Entry } = { return require("@formats/model/ply") end, }, + { + name = "qb", + category = "model", + path = "model/qb", + extensions = { "qb" }, + mime = { "model/x-qubicle" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, voxels = true, truecolor = true }, + load = function() + return require("@formats/model/qb") + end, + }, { name = "rbxm", category = "model", diff --git a/src/Formats/model/qb/init.luau b/src/Formats/model/qb/init.luau new file mode 100644 index 0000000..2c8ce33 --- /dev/null +++ b/src/Formats/model/qb/init.luau @@ -0,0 +1,401 @@ +--!strict +-- model/qb: Qubicle Binary (.qb, Qubicle 1.x "Qubicle Binary" exchange format), read and write. New code, from the +-- format description in the Qubicle documentation (minddesk.com "Qubicle Binary"): version 1.1.0.0, RGBA or BGRA +-- colours, left- or right-handed z axis, uncompressed or run-length compressed matrices (CODEFLAG 2 / NEXTSLICEFLAG 6 +-- per z slice), the visibility mask encoding in the alpha byte, named matrices with a position. +-- decode -> a Scene (meta.up = "y"): one Types.Voxels per matrix with voxels.colors (each cell's exact colour as +-- r, g, b, a bytes; a = the visibility mask when the file encodes one, 0 = empty) and data / palette as an indexed view +-- (up to 255 colours exact, more mapped to the nearest of the 255 most used); a node per matrix with its name and +-- position. Left-handed files are mirrored on z into the scene's right-handed axes (and back on write). +-- encode <- a Scene with voxels or one Types.Voxels: voxels.colors when present (exact), else palette colours; +-- options default to the source file's settings. +-- Not supported: the Qubicle Exchange (.qbt / .qbcl) formats. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") + +-- ------------------------------------------------------------------------------------------------ contract +local Qb = { + name = "qb", + category = "model", + extensions = { "qb" }, + mime = { "model/x-qubicle" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, voxels = true, truecolor = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxCells: number?, -- refuse files whose matrices hold more cells in total (default 2^27) +} +export type EncodeOptions = { + compressed: boolean?, -- run-length compress the matrices (default: the source's, else true) + colorFormat: ("rgba" | "bgra")?, -- default: the source's, else "rgba" + rightHanded: boolean?, -- the z axis orientation (default: the source's, else true) + visibilityMask: boolean?, -- encode the visible sides in the alpha byte (default: the source's, else false) +} + +-- ------------------------------------------------------------------------------------------------ constants +local CODEFLAG, NEXTSLICEFLAG = 2, 6 +-- visibility mask bits (alpha): 1 = filled, then the sides that are not hidden by a neighbour +local LEFT, RIGHT, TOP, BOTTOM, FRONT, BACK = 2, 4, 8, 16, 32, 64 + +-- ------------------------------------------------------------------------------------------------ sniff +function Qb.sniff(r: Bytes.Reader): number + if r:remaining() < 24 or r:peek(4) ~= "\1\1\0\0" then + return 0 + end + local b, p = r.buf, r.pos + local fmt, z, comp, mask = buffer.readu32(b, p + 4), buffer.readu32(b, p + 8), buffer.readu32(b, p + 12), buffer.readu32(b, p + 16) + if fmt > 1 or z > 1 or comp > 1 or mask > 1 then + return 0 + end + return 0.9 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the indexed view of a true-colour grid: exact for up to 255 colours, else the 255 most used and the nearest of them +local function indexed(v: Types.Voxels, colors: buffer, n: number) + local count: { [number]: number } = {} + for i = 0, n - 1 do + local c = buffer.readu32(colors, i * 4) + if c >= 0x1000000 then -- alpha > 0: filled + local rgb = c % 0x1000000 + local k = count[rgb] + if k == nil then + count[rgb] = 1 + else + count[rgb] = k + 1 + end + end + end + local order = {} + for rgb in count do + table.insert(order, rgb) + end + table.sort(order, function(a: number, b: number): boolean + if count[a] ~= count[b] then + return count[a] > count[b] + end + return a < b + end) + local slot: { [number]: number } = {} + for i = 1, math.min(255, #order) do + local rgb = order[i] + slot[rgb] = i + v.palette[i] = { rgb % 256, (rgb // 256) % 256, rgb // 65536, 255 } + end + for i = 256, #order do + local rgb = order[i] + local r, g, b = rgb % 256, (rgb // 256) % 256, rgb // 65536 + local best, bd = 1, math.huge + for k = 1, 255 do + local p = v.palette[k] + local d = (p[1] - r) ^ 2 + (p[2] - g) ^ 2 + (p[3] - b) ^ 2 + if d < bd then + best, bd = k, d + end + end + slot[rgb] = best + end + for i = 0, n - 1 do + local c = buffer.readu32(colors, i * 4) + buffer.writeu8(v.data, i, if c >= 0x1000000 then slot[c % 0x1000000] else 0) + end +end + +function Qb.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local o: DecodeOptions = opts or {} + local maxCells = o.maxCells or 2 ^ 27 + local ver = r:string(4) + local fmt, zAxis, compressed, mask, count = r:u32le(), r:u32le(), r:u32le(), r:u32le(), r:u32le() + if r.err then + return nil, r.err + end + if ver ~= "\1\1\0\0" then + return nil, Err.new(Err.CORRUPT, "not a Qubicle Binary file (version 1.1.0.0)", 0) + end + if fmt > 1 or zAxis > 1 or compressed > 1 or mask > 1 then + return nil, Err.new(Err.CORRUPT, "bad header flags", 4) + end + if count > r:remaining() // 25 then + return nil, Err.new(Err.TRUNCATED, count .. " matrices cannot fit", 20) + end + local scene = Types.Scene.new() + local grids: { Types.Voxels } = {} + scene.voxels = grids + local total = 0 + local bgra = fmt == 1 + for m = 1, count do + local at = r:tell() + local nameLen = r:u8() + local name = r:string(nameLen) + local sx, sy, sz = r:u32le(), r:u32le(), r:u32le() + local px, py, pz = r:i32le(), r:i32le(), r:i32le() + if r.err then + return nil, r.err + end + if sx * sy * sz + total > maxCells then + return nil, Err.new(Err.LIMIT, string.format("matrix %d: %d x %d x %d cells is over maxCells", m, sx, sy, sz), at) + end + local n = sx * sy * sz + total += n + local colors = buffer.create(n * 4) + local b = r.buf + local function put(x: number, y: number, z: number, c: number) + if bgra then -- b, g, r, a -> r, g, b, a + c = (c // 65536) % 256 + (c // 256) % 256 * 256 + c % 256 * 65536 + (c // 16777216) * 16777216 + end + if c < 0x1000000 then + c = 0 -- alpha 0: empty + end + local zz = if zAxis == 0 then sz - 1 - z else z + buffer.writeu32(colors, (x + sx * (y + sy * zz)) * 4, c) + end + if compressed == 0 then + if not r:need(n * 4) then + return nil, r.err + end + local p = r.pos + for z = 0, sz - 1 do + for y = 0, sy - 1 do + for x = 0, sx - 1 do + put(x, y, z, buffer.readu32(b, p)) + p += 4 + end + end + end + r.pos = p + else + local slice = sx * sy + for z = 0, sz - 1 do + local index = 0 + while true do + local d = r:u32le() + if r.err then + return nil, r.err + end + if d == NEXTSLICEFLAG then + break + elseif d == CODEFLAG then + local run, c = r:u32le(), r:u32le() + if r.err then + return nil, r.err + end + if index + run > slice then + return nil, Err.new(Err.CORRUPT, string.format("matrix %d: run past the slice", m), r:tell() - 8) + end + for _ = 1, run do + put(index % sx, index // sx, z, c) + index += 1 + end + else + if index >= slice then + return nil, Err.new(Err.CORRUPT, string.format("matrix %d: slice %d overflows", m, z), r:tell() - 4) + end + put(index % sx, index // sx, z, d) + index += 1 + end + end + end + end + local v = Types.Voxels.new(sx, sy, sz) + v.name = name + v.colors = colors + indexed(v, colors, n) + table.insert(grids, v) + local tz = if zAxis == 0 then 0 - (pz + sz) else pz + table.insert(scene.nodes, { name = name, children = {}, voxels = m, translation = { px, py, tz } }) + table.insert(scene.roots, #scene.nodes) + end + scene.meta.up = "y" + scene.meta.source = { + format = "qb", + colorFormat = if bgra then "bgra" else "rgba", + rightHanded = zAxis == 1, + compressed = compressed == 1, + visibilityMask = mask == 1, + } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function cellColor(v: Types.Voxels, i: number): number + if v.colors then + return buffer.readu32(v.colors, i * 4) + end + local idx = buffer.readu8(v.data, i) + if idx == 0 then + return 0 + end + local p = v.palette[idx] or { 0, 0, 0, 255 } + return p[1] + p[2] * 256 + p[3] * 65536 + 255 * 16777216 +end + +function Qb.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local grids: { { v: Types.Voxels, name: string, pos: { number } } } = {} + local function add(v: any, name: string?, pos: { number }): string? + if type(v) ~= "table" or type(v.size) ~= "table" or type(v.data) ~= "buffer" then + return "expected Types.Voxels grids" + end + local n = v.size[1] * v.size[2] * v.size[3] + if buffer.len(v.data) < n or (v.colors and buffer.len(v.colors) < n * 4) then + return "voxel data shorter than its size" + end + local nm = name or v.name or ("matrix" .. (#grids + 1)) + if #nm > 255 then + return "matrix name longer than 255 bytes" + end + table.insert(grids, { v = v, name = nm, pos = pos }) + return nil + end + local src = if type(value) == "table" and type(value.meta) == "table" and type(value.meta.source) == "table" and value.meta.source.format == "qb" then value.meta.source else nil + if type(value) == "table" and value.kind == "voxels" then + local e = add(value, nil, { 0, 0, 0 }) + if e then + return nil, Err.new(Err.ARG, e) + end + elseif type(value) == "table" and value.kind == "scene" and type(value.voxels) == "table" then + local used: { [number]: boolean } = {} + local function walk(i: number, base: { number }, depth: number): string? + local node = value.nodes[i] + if type(node) ~= "table" or depth > 64 then + return nil + end + local t = node.translation or { 0, 0, 0 } + local p = { base[1] + (t[1] or 0), base[2] + (t[2] or 0), base[3] + (t[3] or 0) } + if node.voxels and value.voxels[node.voxels] then + used[node.voxels] = true + local e = add(value.voxels[node.voxels], node.name, p) + if e then + return e + end + end + for _, c in node.children or {} do + local e = walk(c, p, depth + 1) + if e then + return e + end + end + return nil + end + for _, root in value.roots or {} do + local e = walk(root, { 0, 0, 0 }, 0) + if e then + return nil, Err.new(Err.ARG, e) + end + end + for i, v in value.voxels do + if not used[i] then + local e = add(v, nil, { 0, 0, 0 }) + if e then + return nil, Err.new(Err.ARG, e) + end + end + end + else + return nil, Err.new(Err.ARG, "expected a Scene with voxels or a Types.Voxels") + end + local function pick(opt: any, key: string, default: any): any + if opt ~= nil then + return opt + elseif src and src[key] ~= nil then + return src[key] + end + return default + end + local compressed = pick(o.compressed, "compressed", true) + local bgra = pick(o.colorFormat, "colorFormat", "rgba") == "bgra" + local right = pick(o.rightHanded, "rightHanded", true) + local mask = pick(o.visibilityMask, "visibilityMask", false) + local keepMask = mask and src ~= nil and src.visibilityMask == true -- the source's alpha bytes already are masks + local w = Bytes.writer(1024) + w:string("\1\1\0\0") + w:u32le(if bgra then 1 else 0) + w:u32le(if right then 1 else 0) + w:u32le(if compressed then 1 else 0) + w:u32le(if mask then 1 else 0) + w:u32le(#grids) + for _, g in grids do + local v = g.v + local sx, sy, sz = v.size[1], v.size[2], v.size[3] + w:u8(#g.name) + w:string(g.name) + w:u32le(sx) + w:u32le(sy) + w:u32le(sz) + local px, py, pz = math.floor(g.pos[1] + 0.5), math.floor(g.pos[2] + 0.5), math.floor(g.pos[3] + 0.5) + w:u32le(px % 4294967296) + w:u32le(py % 4294967296) + w:u32le((if right then pz else -pz - sz) % 4294967296) + local function filled(x: number, y: number, z: number): boolean + if x < 0 or y < 0 or z < 0 or x >= sx or y >= sy or z >= sz then + return false + end + return cellColor(v, x + sx * (y + sy * z)) >= 0x1000000 + end + -- the value of file cell (x, y, z): colour bytes in the file's order, the alpha a mask when asked + local function value(x: number, y: number, z: number): number + local zz = if right then z else sz - 1 - z + local c = cellColor(v, x + sx * (y + sy * zz)) + if c < 0x1000000 then + return 0 + end + local a = c // 16777216 + if mask and not keepMask then + a = 1 + if not filled(x - 1, y, zz) then a += LEFT end + if not filled(x + 1, y, zz) then a += RIGHT end + if not filled(x, y + 1, zz) then a += TOP end + if not filled(x, y - 1, zz) then a += BOTTOM end + if not filled(x, y, zz + 1) then a += FRONT end + if not filled(x, y, zz - 1) then a += BACK end + elseif not mask and src and src.visibilityMask then + a = 255 -- masks are not colours + end + local r, gg, b = c % 256, (c // 256) % 256, (c // 65536) % 256 + if bgra then + r, b = b, r + end + return r + gg * 256 + b * 65536 + a * 16777216 + end + for z = 0, sz - 1 do + if compressed then + local x, y = 0, 0 + local slice = sx * sy + local i = 0 + while i < slice do + x, y = i % sx, i // sx + local c = value(x, y, z) + local run = 1 + while i + run < slice and value((i + run) % sx, (i + run) // sx, z) == c do + run += 1 + end + if run > 2 then + w:u32le(CODEFLAG) + w:u32le(run) + w:u32le(c) + else + for _ = 1, run do + w:u32le(c) + end + end + i += run + end + w:u32le(NEXTSLICEFLAG) + else + for y = 0, sy - 1 do + for x = 0, sx - 1 do + w:u32le(value(x, y, z)) + end + end + end + end + end + return w:finish(), nil +end + +return Qb diff --git a/tests/model/qb.luau b/tests/model/qb.luau new file mode 100644 index 0000000..2aca062 --- /dev/null +++ b/tests/model/qb.luau @@ -0,0 +1,130 @@ +-- model/qb tests: Qubicle Binary files with every option (RGBA / BGRA, left- / right-handed, RLE or not, visibility +-- masks, more than 255 colours) against the reference reader / writer of the fixture (exact colours of every cell, +-- names, positions), the indexed palette view, our encodings read back by the reference (same settings, flipped +-- settings, palette grids with computed masks), the api, error codes and the fuzz pass. Fixtures: tools/fixtures/qb.py. +local T = require("@tests/T") +local F = require("@formats") +local Qb = require("@formats/model/qb") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/qb") + +local t = T.suite("qb") + +t:eq(Qb.name, "qb", "name") +t:check(Qb.caps.decode and Qb.caps.encode, "caps") + +local function dec(data: string | buffer): (Types.Scene?, any) + return Qb.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data)) +end + +local function check(scene: Types.Scene, want: any, label: string) + t:eq(#scene.nodes, #want.matrices, label .. ": matrices") + for i, m in want.matrices do + local node = scene.nodes[i] + local v = (scene.voxels :: { Types.Voxels })[node.voxels :: number] + t:eq(node.name, m.name, label .. " " .. i .. ": name") + t:eq(table.concat(v.size, ","), table.concat(m.size, ","), label .. " " .. i .. ": size") + t:eq(table.concat(node.translation :: { number }, ","), table.concat(m.pos, ","), label .. " " .. i .. ": position") + t:eq(Crc32.of(v.colors :: buffer), m.crc, label .. " " .. i .. ": colours") + local filled = 0 + for k = 0, buffer.len(v.data) - 1 do + if buffer.readu8(v.data, k) ~= 0 then + filled += 1 + end + end + t:eq(filled, m.filled, label .. " " .. i .. ": filled cells") + end +end + +for _, c in Fx.cases do + local s, err = dec(c.data) + t:check(s ~= nil, c.name .. ": " .. tostring(err)) + check(s :: Types.Scene, c, c.name) + local src = (s :: Types.Scene).meta.source + t:check(src.colorFormat == c.colorFormat and src.rightHanded == c.rightHanded and src.compressed == c.compressed and src.visibilityMask == c.visibilityMask, c.name .. ": settings") + t:check(buffer.tostring(Qb.encode(s) :: buffer) == c.data, c.name .. ": same bytes again") + -- the palette view: exact colours when there are up to 255 + local v = ((s :: Types.Scene).voxels :: { Types.Voxels })[1] + local exact = true + for k = 0, buffer.len(v.data) - 1 do + local idx = buffer.readu8(v.data, k) + if idx > 0 then + local p, col = v.palette[idx], buffer.readu32(v.colors :: buffer, k * 4) + if p[1] + p[2] * 256 + p[3] * 65536 ~= col % 16777216 then + exact = false + end + end + end + t:eq(exact, c.name ~= "case5", c.name .. ": palette exact up to 255 colours") + t:eq(F.detect(c.data), "qb", c.name .. ": detect") +end + +-- our encodings, read by the reference +for name, want in Fx.ours do + local base = string.match(name, "^(case%d)_") + if base then + local c + for _, x in Fx.cases do + if x.name == base then + c = x + end + end + t:check(c ~= nil, name .. ": source") + -- the same cells whatever the settings (scene coordinates) + for i, m in want.matrices do + t:eq(m.crc, c.matrices[i].crc, name .. " " .. i .. ": colours read back") + t:eq(table.concat(m.pos, ","), table.concat(c.matrices[i].pos, ","), name .. " " .. i .. ": position read back") + end + if string.find(name, "_flip") then + t:check(want.rightHanded ~= c.rightHanded and want.compressed ~= c.compressed, name .. ": flipped settings") + end + end +end +do + local m = Fx.ours.palette_mask + t:check(m.visibilityMask and m.matrices[1].filled == 15, "palette grid with a mask") + local plain = Fx.ours.palette_plain + t:check(not plain.visibilityMask and plain.rightHanded and plain.compressed, "defaults") + -- our decode of the masked file: the centre cell (hidden on every side) has mask 1 + local v = Types.Voxels.new(3, 3, 3) + v.palette[1] = { 200, 10, 10, 255 } + for i = 0, 26 do + buffer.writeu8(v.data, i, 1) + end + local s = assert(dec(assert(Qb.encode(v, { visibilityMask = true })))) + local colors = ((s.voxels :: { Types.Voxels })[1]).colors :: buffer + t:eq(buffer.readu8(colors, 13 * 4 + 3), 1, "hidden cell mask") + t:eq(buffer.readu8(colors, 0 * 4 + 3), 1 + 2 + 16 + 64, "corner cell mask (left, bottom, back)") +end + +-- api and conversion to .vox +do + local s = assert(F.load(Fx.cases[1].data)) + t:check(s.kind == "scene", "F.load") + t:check(F.save(s, nil, { format = "vox" }) ~= nil, "qb -> vox") + t:check(F.save(s, nil, { format = "schem" }) ~= nil, "qb -> schem") +end + +-- errors +do + local _, e1 = dec("\1\1\0\0") + t:check(e1 and e1.code == Err.TRUNCATED, "truncated header") + local _, e2 = dec("\2\1\0\0" .. string.rep("\0", 20)) + t:check(e2 and e2.code == Err.CORRUPT, "bad version") + local _, e3 = dec(string.sub(Fx.cases[1].data, 1, 60)) + t:check(e3 and e3.code == Err.TRUNCATED, "truncated matrix") + local _, e4 = Qb.encode({} :: any) + t:check(e4 and e4.code == Err.ARG, "encode nothing") +end + +local samples = {} +for _, c in Fx.cases do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + return Qb.decode(Bytes.reader(b)) +end, samples) +t:done() diff --git a/tools/fixtures/_qb_encode.luau b/tools/fixtures/_qb_encode.luau new file mode 100644 index 0000000..2a157dc --- /dev/null +++ b/tools/fixtures/_qb_encode.luau @@ -0,0 +1,34 @@ +-- tools/fixtures/qb.py helper: our model/qb encoder's output for the reference reader there. Prints "\t". +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)) diff --git a/tools/fixtures/qb.py b/tools/fixtures/qb.py new file mode 100644 index 0000000..5539500 --- /dev/null +++ b/tools/fixtures/qb.py @@ -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(" 2: + out += struct.pack(" 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("> 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(" Date: Sat, 31 Oct 2026 14:53:04 -0500 Subject: [PATCH 23/27] ws-video2: docs/guide/video.md MPEG-2 section (tested snippet, tsBytes clip), formats table; docs/video.md layers --- docs/guide/video.md | 34 +++++++++++++++++++++++++++++----- docs/video.md | 2 ++ tools/fixtures/docs_av.py | 10 +++++++--- 3 files changed, 38 insertions(+), 8 deletions(-) diff --git a/docs/guide/video.md b/docs/guide/video.md index cbabe27..996da6f 100644 --- a/docs/guide/video.md +++ b/docs/guide/video.md @@ -2,7 +2,7 @@ A video file opens as a **VideoDecoder**: frames come out one at a time, as Images, with their presentation time. Underneath sits a **Demuxer**: the container's tracks and their compressed packets. Video tracks decode through a -codec registry (H.264, VP8, MPEG-1, Motion-JPEG, raw), and the first audio track opens as an audio +codec registry (H.264, VP8, MPEG-1, MPEG-2, Motion-JPEG, raw), and the first audio track opens as an audio [Decoder](audio.md#decoder). Animated GIF, APNG and WebP open as videos too. [docs/video.md](../video.md) covers the internals and how to add a codec. @@ -263,6 +263,30 @@ assert(C.register({ assert(C.fromFourcc("SLID") == "solid" and C.canDecode("solid")) ``` +## MPEG-2 (DVD, broadcast TS) + +MPEG-1 and MPEG-2 video decode through one decoder (`codecs/video/Mpeg2`; `codecs/video/Mpeg1` is the same module): +Main profile, progressive and interlaced, frame and field pictures, 4:2:0 and 4:2:2. It reads `.mpg` / `.vob` +program streams, transport streams (stream type 0x02, or a private type such as 0x80 carrying a video PES), raw +`.m2v` elementary streams, and MPEG-2 tracks of MP4 / MOV, Matroska and AVI. The output equals `ffmpeg -idct int` +sample for sample (the integer IDCT of the IJG; ffmpeg's default IDCT differs from it by at most a level or two). + +```luau +local v = assert(F.video.open(tsBytes)) -- MPEG-TS: interlaced MPEG-2 + MP2 +assert(v.format == "mpegts" and v.codec == "mpeg2") +local f = assert(v:nextFrame()) +local src = f.image.meta.source +assert(src.format == "mpeg2" and src.interlaced and src.topFieldFirst) +assert(f.image.format == "yuv420p") -- both fields woven: the top field on the even lines +local a = assert(v.audio, tostring(v.audioError)) -- the MP2 track through the audio hook +assert(a.sampleRate == 44100) +``` + +Interlaced frames come out woven, as they were coded: deinterlace them yourself if needed (`src.interlaced`, +`src.topFieldFirst`). 4:2:2 streams (studio / XDCAM) are converted to 4:2:0 for the frame Image, averaging chroma +lines of the same field. A 720x576 interlaced stream decodes at about 130 frames per second in Luau on one desktop +core (`tools/bench.luau`): real time with room to spare on a PC, less so on phones. + ## Playing in a game loop Decode only the frames that are due, and stop when this frame's time budget is used up; a slow frame then makes @@ -306,10 +330,10 @@ editable:WritePixelsBuffer(Vector2.zero, editable.Size, v:toRGBA(frame).pixels) | Format | Read | Write | Video codecs (decode) | |---|---|---|---| -| mp4 / mov / m4v / 3gp | yes | yes | H.264, MJPEG, MPEG-1 | -| mkv / webm | yes | yes | VP8, MJPEG, MPEG-1, raw (+ H.264) | -| avi | yes | yes | MJPEG, MPEG-1, raw (+ H.264) | -| mpegts, mpegps | yes | - | MPEG-1, H.264 | +| mp4 / mov / m4v / 3gp | yes | yes | H.264, MJPEG, MPEG-1, MPEG-2 | +| mkv / webm | yes | yes | VP8, MJPEG, MPEG-1, MPEG-2, raw (+ H.264) | +| avi | yes | yes | MJPEG, MPEG-1, MPEG-2, raw (+ H.264) | +| mpegts, mpegps | yes | - | MPEG-1, MPEG-2, H.264 | | y4m | yes | yes | raw | | h264 (Annex B) | yes | yes (copy) | H.264 | | gif, png (APNG), webp | as video | as video via the image writers | frames | diff --git a/docs/video.md b/docs/video.md index 184ca45..8f5b6f5 100644 --- a/docs/video.md +++ b/docs/video.md @@ -28,6 +28,8 @@ F.convert(gif, "avi") -- animated images become videos (un | `codecs/video/Video/Source` | what writers write: copied packets or frames encoded by a registry encoder, PCM from the audio | | `codecs/image/Yuv` | yuv420p <-> rgba8 (BT.601 / 709, limited / full range from `image.meta.yuv`), range remap | | `codecs/image/Vp8`, `Jpeg`, `Mpeg1` | the decoders (and the JPEG encoder) | +| `codecs/video/Mpeg2` (`Mpeg1` is the same module), `H264` | MPEG-1 / MPEG-2 and H.264 video decoders | +| `codecs/video/Dsp` | 8x8 IDCT (bit-exact with `ffmpeg -idct int`) and half-pel motion compensation for the MPEG-style codecs | | `video/` | the formats: demux into `containers/Demux`, `open` = `Video.open(demuxer, opts)`, `encode` via Source | Audio tracks reach the audio formats through the api hook `opts.openAudio(demuxer, track)` (a format never requires diff --git a/tools/fixtures/docs_av.py b/tools/fixtures/docs_av.py index 8019408..9beb3a2 100644 --- a/tools/fixtures/docs_av.py +++ b/tools/fixtures/docs_av.py @@ -1,8 +1,8 @@ # 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), 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), and SRT / WebVTT / ASS subtitles. # tests/gen/docs_av.luau { files = { [name] = bytes }, vars = { mp4Bytes = "clip.mp4", ... } } import importlib.util, os, struct, tempfile @@ -91,6 +91,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]) @@ -107,6 +110,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", From 48c0366528e67854d8b7c1e6549513f6bc5483e4 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:54:03 -0500 Subject: [PATCH 24/27] ws-video2: mpeg2 test: field pictures written in random pieces --- tests/codecs/mpeg2.luau | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/codecs/mpeg2.luau b/tests/codecs/mpeg2.luau index cd88a82..b111d68 100644 --- a/tests/codecs/mpeg2.luau +++ b/tests/codecs/mpeg2.luau @@ -165,7 +165,7 @@ do end -- 3. the same stream written in random pieces (decodeFrame) gives the same frames as unit by unit -for _, idx in { 2, 9 } do +for _, idx in { 2, 9, 12 } do local fx = STREAMS[idx] local file = b64(fx.file) local want = decodeUnits(fx, file) From 2be536bd98801296f0b9045d66a8ad943d08661a Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:56:33 -0500 Subject: [PATCH 25/27] ws-voxel: docs/guide/voxel.md (NBT / SNBT, schematics, regions, Qubicle; tested snippets) + inputs generator; bench lines for NBT, SNBT, packed arrays, schem, qb --- docs/guide/README.md | 1 + docs/guide/data.md | 3 +- docs/guide/scene.md | 5 ++ docs/guide/voxel.md | 145 +++++++++++++++++++++++++++++++++++ tools/bench.luau | 78 +++++++++++++++++++ tools/fixtures/docs_voxel.py | 84 ++++++++++++++++++++ 6 files changed, 315 insertions(+), 1 deletion(-) create mode 100644 docs/guide/voxel.md create mode 100644 tools/fixtures/docs_voxel.py diff --git a/docs/guide/README.md b/docs/guide/README.md index d1fff6c..b9c2a72 100644 --- a/docs/guide/README.md +++ b/docs/guide/README.md @@ -18,6 +18,7 @@ and the host notes. Each standard type has its own page: | [Fonts](font.md) | `Font` | TTF / OTF, WOFF, WOFF2, BMFont | | [Archives](archive.md) | `Archive` | zip, tar, gzip, 7z, xz, zstd, Brotli, bzip2 | | [Data](data.md) | plain values, `XmlNode`, `Date` | JSON, XML, YAML, TOML, CSV, INI, MessagePack, CBOR, plist | +| [Minecraft and voxels](voxel.md) | typed values, `Scene` + `Voxels` | NBT, SNBT, `.schem` / `.schematic` / `.litematic`, Anvil `.mca`, Qubicle `.qb` | | [Vector](vector.md) | `Vector` | SVG | | [Layered images](layered.md) | `Layered` | PSD, Aseprite | | [Tile maps](tilemap.md) | `TileMap` | Tiled TMX / TMJ | diff --git a/docs/guide/data.md b/docs/guide/data.md index 3b40019..46a6d52 100644 --- a/docs/guide/data.md +++ b/docs/guide/data.md @@ -3,7 +3,8 @@ The data formats (JSON, XML, YAML, TOML, CSV, INI, MessagePack, CBOR, plist) decode to plain Luau values: tables, strings, numbers, booleans. Three helpers fill the gaps Luau tables leave: `F.data.null` (a null that can sit in a table), ordered objects (`F.Types.object`: key order, and `{}` that stays an object), and `F.Types.Date` (TOML, -YAML, plist, CBOR and MessagePack dates). XML decodes to a tree of `XmlNode`s. +YAML, plist, CBOR and MessagePack dates). XML decodes to a tree of `XmlNode`s. Minecraft's NBT and SNBT (typed +numbers kept) are on the [Minecraft and voxels](voxel.md) page. ```luau local v = assert(F.data.load('{"name": "ada", "tags": ["x", "y"], "boss": null}')) diff --git a/docs/guide/scene.md b/docs/guide/scene.md index 525643e..659ecd4 100644 --- a/docs/guide/scene.md +++ b/docs/guide/scene.md @@ -329,6 +329,8 @@ node that shows a model has `node.voxels` (an index into `scene.voxels`) and no | `data` | `buffer` | one byte per cell, `0` = empty, `1..255` = palette index; cell `(x, y, z)` (0-based) at byte `x + sx * (y + sy * z)` | | `palette` | `{ { r, g, b, a } }` | 255 entries, 0..255 **sRGB**, `palette[i]` for index `i`, shared by a file's models | | `materials` | `{ [index]: { type, ... } }?` | MATL: `"diffuse"`, `"metal"`, `"glass"`, `"emit"`, ... with their properties | +| `blocks` | `{ palette, data, blockEntities?, entities? }?` | Minecraft grids: the exact block state of every cell ([voxel.md](voxel.md)) | +| `colors` | `buffer?` | true-colour grids (Qubicle): r, g, b, a bytes per cell | ```luau local V = F.Types.Voxels @@ -392,6 +394,9 @@ assert(F.load(vox).voxels[1].size[1] == 4) | 3MF | yes | yes | | | USDA (+ USDZ read) | yes | yes | | | VOX | yes | yes | voxel grids, scene graph, materials | +| Minecraft `.schem` / `.schematic` / `.litematic` | yes | yes | block grids, see [voxel.md](voxel.md) | +| Minecraft region `.mca` | yes | | block grids of chosen chunks, see [voxel.md](voxel.md) | +| Qubicle `.qb` | yes | yes | true-colour grids, see [voxel.md](voxel.md) | | STEP | via the CAD plug-in | | see [cad.md](cad.md) | Capabilities per format: [FORMATS.md](../FORMATS.md). diff --git a/docs/guide/voxel.md b/docs/guide/voxel.md new file mode 100644 index 0000000..5371656 --- /dev/null +++ b/docs/guide/voxel.md @@ -0,0 +1,145 @@ +# Minecraft and voxel files + +Minecraft's NBT data, its schematics (`.schem`, `.schematic`, `.litematic`) and region files (`.mca`), and Qubicle +`.qb` models. NBT and SNBT load as plain values (the [Data](data.md) category); schematics, regions and Qubicle files +load as a `Scene` whose `scene.voxels` holds `Voxels` grids (see [3D scenes](scene.md#voxels)), so they mesh and save +like a `.vox`. + +| Format | Read | Write | Value | +|---|---|---|---| +| NBT (`.nbt`, `.dat`, `.mcstructure`) | yes | yes | typed plain values; Java big-endian, Bedrock little-endian, gzip / zlib / raw | +| SNBT (`.snbt`) | yes | yes | the same values as text | +| Sponge `.schem` v1 / v2 / v3 | yes | yes | Scene, one grid with block states | +| MCEdit / WorldEdit `.schematic` | yes | yes | Scene; pre-1.13 numeric ids | +| Litematica `.litematic` | yes | yes | Scene, one grid per region | +| Anvil region `.mca` | yes | | Scene, the chosen chunks as one grid, plus each chunk's NBT | +| Qubicle `.qb` | yes | yes | Scene, one grid per matrix, exact colours | + +## NBT and SNBT + +NBT values are plain Luau with their tag type kept, so what you load saves back the same: + +| NBT tag | Luau value | +|---|---| +| int | number | +| string | string | +| byte array | buffer | +| compound | ordered table (`F.Types.object`, keys in file order) | +| list | array (its element type: `Nbt.listType(list)`) | +| byte, short, long, float, double | a tag `{ type = "byte", value = 1 }` (`tostring` gives SNBT: `1b`); longs past 2^53 hold their exact decimal text | +| int array, long array | a tag with `value` = numbers / a buffer of 8-byte little-endian longs | + +```luau +local level = assert(F.load(levelDatBytes, { name = "level.dat" })) -- gzip NBT +local data = level.Data +assert(data.LevelName == "My World" and data.SpawnY == 64) -- ints and strings are plain +assert(data.Difficulty.type == "byte" and data.Difficulty.value == 2) +assert(data.RandomSeed.value == "-4011880356862312345") -- past 2^53: exact text +assert(tostring(data.Player.Health) == "20.0f") + +local Nbt = F.format("nbt").Nbt -- the engine: codecs/text/Nbt +data.Difficulty = Nbt.byte(3) +data.Tags = Nbt.list("string", { "a", "b" }) +local saved = assert(F.save(level, nil, { format = "nbt" })) -- gzip again, like the source +assert(F.load(saved, { format = "nbt" }).Data.Difficulty.value == 3) +local info = F.format("nbt").info(level) -- how it was stored +assert(info.compression == "gzip" and info.endian == "big" and info.name == "") +``` + +Plain inputs work too: a whole number writes as an int, other numbers as a double, `true` / `false` as bytes, a table +with string keys as a compound and an array as a list. Bedrock files (little-endian, with or without the `level.dat` +header) are detected; `endian = "little"`, `varint = true` (network NBT) and `compression` force a layout when saving. + +```luau +local text = assert(F.convert(levelDatBytes, "snbt", { format = "nbt" })) -- NBT -> SNBT text +assert(string.find(buffer.tostring(text), 'LevelName:"My World"', 1, true)) +local v = assert(F.load("{pos:[I;1,2,3],name:'x',scale:1.5f,big:9007199254740993L}", { format = "snbt" })) +assert(v.pos.value[2] == 2 and v.scale.type == "float" and v.big.value == "9007199254740993") +assert(F.saveString(v, { format = "snbt" }) == '{pos:[I;1,2,3],name:"x",scale:1.5f,big:9007199254740993L}') +local pretty = assert(F.saveString(v, { format = "snbt", indent = 2 })) +local bedrock = assert(F.save(v, nil, { format = "nbt", endian = "little", compression = "none" })) +``` + +## Schematics + +A schematic loads as a Scene with `meta.up = "y"` and one unit per block. Each grid has its usual colour view +(`data` / `palette`, from a built-in table of block colours) and `voxels.blocks` with the exact blocks: + +| `voxels.blocks` field | Meaning | +|---|---| +| `palette` | block states (`"minecraft:oak_log[axis=y]"`), entry 1 is index 0 | +| `data` | a buffer, one u16 per cell (same cell order as `voxels.data`): the 0-based palette index | +| `blockEntities` | `{ { pos = { x, y, z }, id, data } }`: chests, signs, ... (`data` is their NBT) | +| `entities` | entity NBT records | + +```luau +local scene = assert(F.load(schemBytes)) -- detected by content: F.detect gives "schem" +local grid = scene.voxels[1] +assert(grid.size[1] == 5 and grid.size[2] == 4) -- x, y (up), z +local blocks = grid.blocks +local function blockAt(x: number, y: number, z: number): string + local i = x + grid.size[1] * (y + grid.size[2] * z) + return blocks.palette[buffer.readu16(blocks.data, i * 2) + 1] +end +assert(blockAt(0, 0, 0) == "minecraft:stone" and blockAt(2, 2, 0) == "minecraft:glass") +assert(F.Types.Voxels.get(grid, 1, 1, 1) == 0) -- air is empty in the colour view + +local lite = assert(F.load(litematicBytes)) +assert(#lite.voxels == 2 and lite.nodes[2].name == "pillar") -- a node per region, placed by translation +local legacy = assert(F.save(lite, nil, { format = "schematic", variant = "schematic" })) -- regions merged +local schem = assert(F.save(lite, nil, { format = "schem" })) -- Sponge v3 +assert(F.detect(schem) == "schem") +``` + +`F.save` picks the flavour from `variant`, the destination's extension (`"out.litematic"`), `format = "schem"` / +`"litematic"`, or the loaded file's. A grid without `blocks` (a `.vox`, a `.qb`) gets the block nearest in colour for +each palette colour, so converting voxel art works: + +```luau +local vox = assert(F.load(voxBytes)) +local schem = assert(F.save(vox, nil, { format = "schem" })) +local back = assert(F.load(schem)) +assert(back.voxels[1].blocks.palette[1] == "minecraft:air") +``` + +## Region files + +An Anvil region holds 32 x 32 chunks. Loading it builds one grid over the chunks you pick (`chunks = { { x, z } }`, +local 0..31), or the blocks inside `area = { minX, minY, minZ, maxX, maxY, maxZ }` (world coordinates), between the +lowest and highest sections holding blocks; `maxCells` (default 2^25) guards against loading a whole world. + +```luau +local Mca = F.format("mca") +local region = assert(F.load(regionBytes, { name = "r.0.0.mca", chunks = { { 0, 0 }, { 1, 0 } } })) +local grid = region.voxels[1] +assert(grid.size[1] == 32 and grid.size[3] == 16) +local corner = region.nodes[1].translation -- the grid's world position +assert(corner[1] == 0 and corner[2] == -64) +local chunk = region.meta.source.chunks[1] +assert(chunk.dataVersion == 3953 and chunk.nbt.Status == "minecraft:full") -- the chunk's whole NBT + +local list = assert(Mca.list(F.Bytes.reader(regionBytes))) -- the chunks present, with timestamps +local nbt = assert(Mca.chunk(F.Bytes.reader(regionBytes), 3, 2)) +assert(nbt.xPos == 3) +``` + +All chunk layouts read: 1.18+ sections, 1.13 - 1.17 palettes and pre-1.13 numeric ids (as state names such as +`minecraft:red_wool`, with `[data=N]` for the rest of a data value). Chunk payloads may be gzip, zlib, LZ4 or stored; +chunks in external `.mcc` files load through `opts.resolve` (filled in when loading by path). Regions are read-only. + +## Qubicle + +Each matrix becomes a grid with `voxels.colors`, the exact colour of every cell (`r, g, b, a` bytes; `a = 0` is +empty), next to the indexed `data` / `palette` view. Left-handed files are mirrored into the scene's right-handed +axes; saving writes the source's settings unless `compressed`, `colorFormat` (`"rgba"` / `"bgra"`), `rightHanded` or +`visibilityMask` say otherwise. + +```luau +local box = assert(F.load(qbBytes)) +local grid = box.voxels[1] +local first = buffer.readu32(grid.colors, 0) -- r + g * 256 + b * 65536 + a * 2^24 +assert(first % 256 == 200 and first // 16777216 == 255) +assert(box.nodes[1].name == "box") +local again = assert(F.save(box, nil, { format = "qb", compressed = false })) +local vox = assert(F.save(box, nil, { format = "vox" })) -- or .schem, .glb after F.ops.mesh.meshVoxels +``` diff --git a/tools/bench.luau b/tools/bench.luau index e7d1364..59a36c4 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -1091,3 +1091,81 @@ 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 diff --git a/tools/fixtures/docs_voxel.py b/tools/fixtures/docs_voxel.py new file mode 100644 index 0000000..5e3ff9f --- /dev/null +++ b/tools/fixtures/docs_voxel.py @@ -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", + }) From 88d5fe7d2f05379a4e297fd3f36311026d145d37 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 15:01:19 -0500 Subject: [PATCH 26/27] ws-video2-theora: Theora MC average without type diagnostics (lint TYPES back to the baseline) --- src/Formats/codecs/video/Theora/Decoder.luau | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/Formats/codecs/video/Theora/Decoder.luau b/src/Formats/codecs/video/Theora/Decoder.luau index aad8f1c..d7a7afc 100644 --- a/src/Formats/codecs/video/Theora/Decoder.luau +++ b/src/Formats/codecs/video/Theora/Decoder.luau @@ -537,10 +537,12 @@ local function reconFrag(st: State, fi: number, qis: { number }, dstPlanes: { bu local s2 = s1 + my2 * stride + mx2 for y = 0, 7 do local d, a, b = pos + y * stride, s1 + y * stride, s2 + y * stride - local u, v = readu32(ref, a), readu32(ref, b) + local u: number = readu32(ref, a) + local v: number = readu32(ref, b) writeu32(dst, d, band(u, v) + rshift(band(bxor(u, v), 0xFEFEFEFE), 1)) - u, v = readu32(ref, a + 4), readu32(ref, b + 4) - writeu32(dst, d + 4, band(u, v) + rshift(band(bxor(u, v), 0xFEFEFEFE), 1)) + local u2: number = readu32(ref, a + 4) + local v2: number = readu32(ref, b + 4) + writeu32(dst, d + 4, band(u2, v2) + rshift(band(bxor(u2, v2), 0xFEFEFEFE), 1)) end else for y = 0, 7 do From 9fe5f8d658cdfd98b4fdbb937ea250374873519a Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 15:06:55 -0500 Subject: [PATCH 27/27] ws-roblox: docs/guide/roblox.md (tested snippets: places, building trees, meshes) + docs_roblox inputs; F.Rbx (codecs/model/Rbx) exported by the api; bench lines (rbxm / rbxmx / robloxmesh); STYLE.md codec list gains Lz4 and Rbx --- docs/API.md | 2 +- docs/STYLE.md | 4 +- docs/guide/README.md | 1 + docs/guide/roblox.md | 94 +++++++++++++++++++++++++++++++++++ src/Formats/init.luau | 2 + tools/bench.luau | 34 +++++++++++++ tools/fixtures/docs_roblox.py | 49 ++++++++++++++++++ 7 files changed, 183 insertions(+), 3 deletions(-) create mode 100644 docs/guide/roblox.md create mode 100644 tools/fixtures/docs_roblox.py diff --git a/docs/API.md b/docs/API.md index 7077b3d..f47905e 100644 --- a/docs/API.md +++ b/docs/API.md @@ -104,4 +104,4 @@ decoders (CELT, VP8, H.264, MPEG-1) outgrow the defaults and fall back to the in ## Also exported `F.Err` (codes `TRUNCATED`, `CORRUPT`, `CHECKSUM`, `UNSUPPORTED`, `LIMIT`, `ARG`, `IO`, `UNKNOWN_FORMAT`), `F.Types` -(the standard types and their constructors), `F.Bytes` (`core/Bytes` Reader / Writer), `F.null`, `F.version`. +(the standard types and their constructors), `F.Bytes` (`core/Bytes` Reader / Writer), `F.Rbx` (the Roblox instance tree of `rbxm` / `rbxmx`: `codecs/model/Rbx`), `F.null`, `F.version`. diff --git a/docs/STYLE.md b/docs/STYLE.md index 46ba287..f720a56 100644 --- a/docs/STYLE.md +++ b/docs/STYLE.md @@ -25,11 +25,11 @@ src/Formats/ vector layered subtitle music playlist containers/ containers (layer 4) Chunks, Riff, IsoBmff, Ebml, Ogg, Zip, Tar, ... codecs// codecs (layer 3) generic algorithms, by domain: - compress/ Deflate Lzma Zstd Brotli Bzip2 Lzw entropy/ Huffman RangeCoder + compress/ Deflate Lzma Zstd Brotli Bzip2 Lzw Lz4 entropy/ Huffman RangeCoder image/ Jpeg Dct Vp8 Vp8L Pixels Yuv Quantize Raster Blend audio/ Opus Vorbis Flac Mpa Aac Alac Mdct Pcm Stream Resample VorbisComment Tracker SoundFont video/ H264 Mpeg1 Video (the video codec registry) text/ Json Xml Text Url - font/ TrueType Cff model/ Mat4 MeshFlatten + font/ TrueType Cff model/ Mat4 MeshFlatten Rbx host/ host (layer 2) runtime adapters; only the api uses them Types.luau types (layer 1) standard types + constructors core/ core (layer 0) Bytes, Bits, Err, Crc32, Adler32, Base64, Md5, diff --git a/docs/guide/README.md b/docs/guide/README.md index d1fff6c..d36c603 100644 --- a/docs/guide/README.md +++ b/docs/guide/README.md @@ -14,6 +14,7 @@ and the host notes. Each standard type has its own page: | [Music](music.md) | `Module`, `Midi` | MOD, S3M, XM, IT, MIDI, SoundFont 2 | | [Video](video.md) | `VideoDecoder`, `Demuxer`, `Track`, `Packet` | MP4 / MOV, MKV / WebM, AVI, MPEG-TS / PS, Y4M, H.264 | | [3D scenes](scene.md) | `Scene`, `Voxels` | glTF / GLB, OBJ, STL, PLY, FBX, Collada, 3MF, USDA, OFF, VOX | +| [Roblox](roblox.md) | `RbxTree` (`F.Rbx`), `Scene` | rbxm / rbxl, rbxmx / rbxlx, Roblox .mesh | | [CAD](cad.md) | `Cad` (STEP) | STEP (B-rep through a plug-in) | | [Fonts](font.md) | `Font` | TTF / OTF, WOFF, WOFF2, BMFont | | [Archives](archive.md) | `Archive` | zip, tar, gzip, 7z, xz, zstd, Brotli, bzip2 | diff --git a/docs/guide/roblox.md b/docs/guide/roblox.md new file mode 100644 index 0000000..3b1fc85 --- /dev/null +++ b/docs/guide/roblox.md @@ -0,0 +1,94 @@ +# Roblox files + +Roblox models and places (`.rbxm` / `.rbxl` binary, `.rbxmx` / `.rbxlx` XML) load as an **`RbxTree`**: instances +with a class name, a name, typed properties and children. Roblox meshes (`.mesh`) load as an ordinary +[`Scene`](scene.md). This is a file library, not a Roblox runtime. It never creates Instances. A Roblox game that +wants Instances walks the tree itself, and the tree works the same under LuaJIT and the luau CLI. + +```luau +local place = assert(F.load(placeBytes)) -- binary .rbxl -> RbxTree +assert(place.kind == "rbxtree" and place.place) -- a place: the roots are services +for inst, depth in F.Rbx.descendants(place) do + print(string.rep(" ", depth - 1) .. inst.className .. " " .. inst.name) +end +local step = assert(F.Rbx.find(place, "Workspace/Course/Step2")) +local size = F.Rbx.get(step, "size") -- { 4, 1, 4 } (the binary name of Part.Size) +assert(size[1] == 4 and size[2] == 1) +local xml = assert(F.convert(placeBytes, "rbxlx")) -- binary -> XML: both read and write the same tree +assert(F.detect(xml) == "rbxlx" and F.detect(placeBytes) == "rbxl") +``` + +## The tree + +`F.Rbx` (`codecs/model/Rbx`) holds the type and its helpers: + +| Field / call | Meaning | +|---|---| +| `tree.roots` | the top-level instances (the services of a place) | +| `tree.place` | true for `.rbxl` / `.rbxlx` (services); saving to `rbxl` sets it | +| `tree.metadata` | the file's META entries (`ExplicitAutoJoints`, ...) | +| `inst.className`, `inst.name`, `inst.children`, `inst.parent` | the hierarchy. `Name` is `inst.name`, not a property | +| `inst.properties[name]` | `{ type = "Vector3", value = { x, y, z } }` | +| `F.Rbx.tree()`, `instance(class, name)`, `add(parent, child)` | build trees | +| `set(inst, name, type, value)`, `get(inst, name)` | properties | +| `find(root, "A/B/C")`, `descendants(root)`, `list(tree)`, `fullName(inst)` | lookups | + +Property values keep the file's type, because a number alone could be an `Int32`, a `Float32` or an `Enum`. Arrays +follow the argument order of the Roblox constructors, so `Vector3.new(table.unpack(v.value))` and +`CFrame.new(table.unpack(v.value))` rebuild them in a game. The full list is in the header of +`src/Formats/codecs/model/Rbx/init.luau`: + +- **Text and numbers:** `String`, `BinaryString`, `ProtectedString`, `ContentId`, `SharedString` are strings. + `Bool`, `Int32`, `Int64`, `Float32`, `Float64`, `Enum`, `BrickColor`, `Faces` and `Axes` are numbers and booleans. +- **Arrays:** `Vector2`, `Vector3` and `Color3` (0..1) are arrays. `CFrame` is 12 numbers: the position, then the + rotation row by row. +- **References:** `Ref` and the object form of `Content` hold the instance itself. `Content` is otherwise a URI string, + or nil. +- **Unknown data** is kept, not dropped: properties of unknown types (`Raw` in binary files, `XmlRaw` in XML) and unknown + chunks are written back unchanged. + +Property names are the ones the file stores. Binary files use a few serialized names, for example `size` for +`Part.Size` and `Color3uint8` for `Part.Color`. Without Roblox's reflection database, the library does not rename +them. + +```luau +local tree = F.Rbx.tree() +local model = F.Rbx.add(tree, F.Rbx.instance("Model", "Tower")) +for i = 1, 3 do + local part = F.Rbx.add(model, F.Rbx.instance("Part", "Floor" .. i)) + F.Rbx.set(part, "size", "Vector3", { 8, 1, 8 }) + F.Rbx.set(part, "CFrame", "CFrame", { 0, i * 4, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 }) + F.Rbx.set(part, "Anchored", "Bool", true) +end +F.Rbx.set(model, "PrimaryPart", "Ref", model.children[1]) +local rbxm = assert(F.save(tree, nil, { format = "rbxm" })) -- LZ4 chunks; { compression = "none" } writes them raw +local back = assert(F.load(rbxm)) +assert(F.Rbx.get(back.roots[1], "PrimaryPart") == back.roots[1].children[1]) +local text = buffer.tostring(assert(F.save(back, nil, { format = "rbxmx" }))) +assert(string.find(text, '