ws-audio: merge master (ws/m4a codecs/Mdct already in use since 6535a3c; audio/opus encoder, data, vec, 3d, webp)

This commit is contained in:
4DBug committed 2026-10-31 09:29:36 -05:00
commit 43b8f4b4f5
400 files changed
+82546 -38

No files matched your search

+485 -1
View File
@@ -1,7 +1,8 @@
-- 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.
-- tools/fixtures/flac.py; wav encodes / decodes a generated tone; zstd / brotli / bzip2 / lzma (*_bench corpora), fonts
-- (glyphs per second), json / xml / yaml, jpeg / gif / tiff / qoi / tga / pnm / hdr and ImageOps.
local Deflate = require("@formats/codecs/Deflate")
local Crc32 = require("@formats/core/Crc32")
local Bytes = require("@formats/core/Bytes")
@@ -174,3 +175,486 @@ do
end)
print(string.format("%-8s %-30s %8.1fx real time", runtime, "", 10 / dt))
end
do
local Json = require("@formats/codecs/Json")
local JB = require("@tests/gen/json_bench")
local v = assert(Json.decode(JB.text))
assert(Json.encode(v) == JB.compact, "json bench mismatch")
bench("json decode (indented)", 5, #JB.text, function()
Json.decode(JB.text)
end)
bench("json decode (compact)", 5, #JB.compact, function()
Json.decode(JB.compact)
end)
bench("json encode (compact, sorted)", 5, #JB.compact, function()
Json.encode(v)
end)
end
do
local Xml = require("@formats/codecs/Xml")
local XB = require("@tests/gen/xml_bench")
local doc = assert(Xml.decode(XB.text))
bench("xml decode (DOM)", 5, #XB.text, function()
Xml.decode(XB.text)
end)
bench("xml events", 5, #XB.text, function()
for _ in Xml.events(XB.text) do
end
end)
bench("xml encode", 5, #XB.text, function()
Xml.encode(doc)
end)
end
-- ws-arch codecs: zstd, brotli, bzip2, xz / lzma
do
local Zstd = require("@formats/codecs/Zstd")
local ZB = require("@tests/gen/zstd_bench")
local z3, z19 = buffer.fromstring(ZB.data3), buffer.fromstring(ZB.data19)
local zo = assert(Zstd.decompress(z3))
assert(buffer.len(zo) == ZB.size and Crc32.of(zo) == ZB.crc, "zstd bench corpus mismatch")
bench("zstd -3 (+ xxh64)", 3, ZB.size, function()
Zstd.decompress(z3)
end)
bench("zstd -3 (no checksum)", 3, ZB.size, function()
Zstd.decompress(z3, nil, nil, { verify = false })
end)
bench("zstd -19 (no checksum)", 3, ZB.size, function()
Zstd.decompress(z19, nil, nil, { verify = false })
end)
end
do
local Brotli = require("@formats/codecs/Brotli")
local BB = require("@tests/gen/brotli_bench")
local bz = buffer.fromstring(BB.data)
local bout = assert(Brotli.decompress(bz))
assert(buffer.len(bout) == BB.size and Crc32.of(bout) == BB.crc, "brotli bench corpus mismatch")
bench("brotli decompress (q9 w22)", 5, BB.size, function()
Brotli.decompress(bz)
end)
end
do
local Bzip2 = require("@formats/codecs/Bzip2")
local BZ = require("@tests/gen/bzip2_bench")
local bz = buffer.fromstring(BZ.data)
bench("bzip2 decompress -9", 3, BZ.size, function()
Bzip2.decompress(bz)
end)
end
do
local Lzma = require("@formats/codecs/Lzma")
local LB = require("@tests/gen/lzma_bench")
local lx, la = buffer.fromstring(LB.xz), buffer.fromstring(LB.alone)
local lo = assert(Lzma.xz(lx))
assert(buffer.len(lo) == LB.size and Crc32.of(lo) == LB.crc, "lzma bench corpus mismatch")
bench("xz -6 (lzma2 + crc64)", 3, LB.size, function()
Lzma.xz(lx)
end)
bench("lzma alone -6", 3, LB.size, function()
Lzma.alone(la)
end)
end
-- fonts: outlines and rasterization (MB/s here = thousands of glyphs per second)
do
local Ttf = require("@formats/font/ttf")
local FX = require("@tests/gen/fonts")
for _, c in FX.fonts do
if c.name == "Roboto-Medium" or c.name == "SourceSans3-Regular" then
local f = assert(Ttf.decode(Bytes.reader(buffer.fromstring(c.data))))
local gl = {}
for cp = 33, 126 do
table.insert(gl, f:glyphIndex(cp))
end
bench(c.name .. " outlines (kglyph/s)", 3, #gl * 1000, function()
for _, g in gl do
f:outline(g)
end
end)
bench(c.name .. " rasterize 32 px (kglyph/s)", 3, #gl * 1000, function()
for _, g in gl do
f:rasterize(g, 32)
end
end)
end
end
end
do
local Yaml = require("@formats/data/yaml")
local YB = require("@tests/gen/yaml_bench")
local yb = buffer.fromstring(YB.text)
local v = assert(Yaml.decode(Bytes.reader(yb)))
bench("yaml decode (block)", 3, #YB.text, function()
Yaml.decode(Bytes.reader(yb))
end)
bench("yaml encode", 3, #YB.text, function()
Yaml.encode(v)
end)
end
-- ------------------------------------------------------------------------------------------------ jpeg (ws-imgA)
do
local Jpeg = require("@formats/image/jpeg")
local Types = require("@formats/Types")
local JB = require("@tests/gen/jpeg_bench")
for _, c in JB.files do
local b = buffer.fromstring(c.data)
local img = Jpeg.decode(Bytes.reader(b))
assert(img and Crc32.of(img.pixels) == c.crc, "jpeg bench: " .. c.name .. " does not match djpeg")
bench("jpeg decode " .. c.name, 3, c.width * c.height * 4, function()
Jpeg.decode(Bytes.reader(b))
end)
end
local b0 = buffer.fromstring(JB.files[1].data)
bench("jpeg decode 1/8 (DC only)", 3, JB.width * JB.height * 4, function()
Jpeg.decode(Bytes.reader(b0), { scale = 8 })
end)
local src = Types.Image.new(JB.width, JB.height, "rgb8")
buffer.writestring(src.pixels, 0, JB.rgb)
for _, o in { { label = "baseline 4:2:0 q85", quality = 85 }, { label = "progressive 4:2:0 q85", quality = 85, progressive = true }, { label = "baseline 4:4:4 q85 optimized", quality = 85, subsampling = "444", optimize = true } } do
bench("jpeg encode " .. o.label, 2, JB.width * JB.height * 3, function()
Jpeg.encode(src, o :: any)
end)
end
end
-- ---------------------------------------------------------------------------------------- ws-imgA: gif + quantize
do
local Gif = require("@formats/image/gif")
local Quantize = require("@formats/codecs/Quantize")
local Types = require("@formats/Types")
local GB = require("@tests/gen/gif_bench")
local still = buffer.fromstring(GB.still)
local anim = buffer.fromstring(GB.anim)
local simg = assert(Gif.decode(Bytes.reader(still)))
local aimg = assert(Gif.decode(Bytes.reader(anim)))
local sw, sh = simg.width, simg.height
bench("gif decode 512x384", 5, sw * sh * 4, function()
Gif.decode(Bytes.reader(still))
end)
bench("gif decode 40 x 128x128 anim", 3, #(aimg.frames :: any) * 128 * 128 * 4, function()
Gif.decode(Bytes.reader(anim))
end)
bench("gif encode 512x384 (exact pal)", 3, sw * sh * 4, function()
Gif.encode(simg)
end)
local photo = Types.Image.new(sw, sh)
for i = 0, sw * sh - 1 do
local x, y = i % sw, i // sw
buffer.writeu32(photo.pixels, i * 4, (x % 256) + (y % 256) * 256 + ((x * y) % 256) * 65536 + 0xFF000000)
end
bench("quantize mediancut 256", 3, sw * sh * 4, function()
Quantize.palette(photo.pixels, sw, sh, 256)
end)
bench("quantize octree 256", 3, sw * sh * 4, function()
Quantize.palette(photo.pixels, sw, sh, 256, { method = "octree" })
end)
local pal = Quantize.palette(photo.pixels, sw, sh, 256)
bench("quantize map", 3, sw * sh * 4, function()
Quantize.map(photo.pixels, sw, sh, pal)
end)
bench("quantize map + dither", 3, sw * sh * 4, function()
Quantize.map(photo.pixels, sw, sh, pal, { dither = true })
end)
bench("gif encode 512x384 (quantize)", 2, sw * sh * 4, function()
Gif.encode(photo)
end)
end
-- ------------------------------------------------------------------------------------------------ ops/ImageOps
do
local Ops = require("@formats/ops/ImageOps")
local img = assert(Png.decode(Bytes.reader(buffer.fromstring(PB[1].data))))
local n = img.width * img.height * 4
bench("imageops resize 1/2 bilinear", 2, n, function()
Ops.resize(img, img.width // 2, img.height // 2, "bilinear")
end)
bench("imageops resize 1/2 lanczos", 2, n, function()
Ops.resize(img, img.width // 2, img.height // 2, "lanczos")
end)
bench("imageops resize x1.5 bilinear", 1, n, function()
Ops.resize(img, img.width * 3 // 2, img.height * 3 // 2, "bilinear")
end)
bench("imageops rotate 30 (expand)", 1, n, function()
Ops.rotate(img, 30)
end)
bench("imageops rotate90", 3, n, function()
Ops.rotate90(img, 1)
end)
bench("imageops convert rgba8 -> gray8", 3, n, function()
Ops.convert(img, "gray8")
end)
local other = assert(Ops.flip(img, "h"))
bench("imageops composite over", 3, n, function()
Ops.composite(img, other)
end)
end
-- ------------------------------------------------------------------------------------------------ image/tiff (ws-imgA)
do
local Tiff = require("@formats/image/tiff")
local Types = require("@formats/Types")
local src = Types.Image.new(1024, 768)
for i = 0, 1024 * 768 - 1 do
local x, y = i % 1024, i // 1024
buffer.writeu32(src.pixels, i * 4, 0xFF000000 + (x % 256) + ((y % 256) * 256) + (((x + y) // 4 % 256) * 65536))
end
for _, comp in { "none", "lzw", "deflate" } do
local enc = Tiff.encode(src, { compression = comp :: any }) :: buffer
bench("tiff decode rgba8 " .. comp, 3, 1024 * 768 * 4, function()
Tiff.decode(Bytes.reader(enc))
end)
bench("tiff encode rgba8 " .. comp, 2, 1024 * 768 * 4, function()
Tiff.encode(src, { compression = comp :: any })
end)
end
local enc16 = Tiff.encode(Types.Image.new(1024, 768, "rgba16"), { compression = "lzw" }) :: buffer
bench("tiff decode rgba16 lzw -> rgba8", 3, 1024 * 768 * 8, function()
Tiff.decode(Bytes.reader(enc16))
end)
end
-- ------------------------------------------------------------------------------------------------ imgA-simple: qoi / tga / pnm / hdr
-- fixtures: tools/fixtures/qoi.py (tests/gen/qoi_bench.luau: run python3 -I tools/fixtures.py qoi first)
do
local Qoi = require("@formats/image/qoi")
local Tga = require("@formats/image/tga")
local Pnm = require("@formats/image/pnm")
local Hdr = require("@formats/image/hdr")
local Types = require("@formats/Types")
local QB = require("@tests/gen/qoi_bench")
local qd = buffer.fromstring(QB.data)
local n = QB.width * QB.height * 4
bench("qoi decode 1024x768", 5, n, function()
Qoi.decode(Bytes.reader(qd))
end)
local img = Types.Image.new(QB.width, QB.height)
img.pixels = buffer.fromstring(QB.pixels)
bench("qoi encode 1024x768", 5, n, function()
Qoi.encode(img)
end)
local tr = Tga.encode(img, { rle = true }) :: buffer
bench("tga decode rle 1024x768", 3, n, function()
Tga.decode(Bytes.reader(tr))
end)
bench("tga encode rle 1024x768", 3, n, function()
Tga.encode(img, { rle = true })
end)
local pp = Pnm.encode(img, { format = "ppm" }) :: buffer
bench("ppm decode 1024x768", 3, n, function()
Pnm.decode(Bytes.reader(pp))
end)
local f = Hdr.decode(Bytes.reader(Hdr.encode(img) :: buffer), { native = true }) :: Types.Image
local hb = Hdr.encode(f) :: buffer
bench("hdr decode rle 1024x768 (rgbaf32)", 3, n, function()
Hdr.decode(Bytes.reader(hb), { native = true })
end)
bench("hdr encode rle 1024x768", 3, n, function()
Hdr.encode(f)
end)
end
do
-- 3D (ws-3d): a 400 x 400 grid mesh (160k vertices, 318k triangles) through our own writers, then the readers; a
-- 128^3 noise voxel grid through VOX and greedy meshing
local Types = require("@formats/Types")
local MeshOps = require("@formats/ops/MeshOps")
local Gltf = require("@formats/model/gltf")
local Obj = require("@formats/model/obj")
local Stl = require("@formats/model/stl")
local Ply = require("@formats/model/ply")
local Vox = require("@formats/model/vox")
local N = 400
local pos = Types.Scene.accessor(nil, "f32", 3, N * N)
local uv = Types.Scene.accessor(nil, "f32", 2, N * N)
for y = 0, N - 1 do
for x = 0, N - 1 do
local i = y * N + x
buffer.writef32(pos.data, i * 12, x / N)
buffer.writef32(pos.data, i * 12 + 4, math.sin(x * 0.1) * math.cos(y * 0.1) * 0.05)
buffer.writef32(pos.data, i * 12 + 8, y / N)
buffer.writef32(uv.data, i * 8, x / N)
buffer.writef32(uv.data, i * 8 + 4, y / N)
end
end
local ind = Types.Scene.accessor(nil, "u32", 1, (N - 1) * (N - 1) * 6)
local k = 0
for y = 0, N - 2 do
for x = 0, N - 2 do
local a = y * N + x
for _, v in { a, a + N, a + 1, a + 1, a + N, a + N + 1 } do
buffer.writeu32(ind.data, k * 4, v)
k += 1
end
end
end
local prim = { attributes = { POSITION = pos, TEXCOORD_0 = uv }, indices = ind, mode = "triangles" } :: any
MeshOps.computeNormals(prim)
local scene = Types.Scene.fromPrimitive(prim, "grid")
bench("meshops computeNormals 318k tris", 3, buffer.len(pos.data), function()
MeshOps.computeNormals(prim)
end)
local glb = assert(Gltf.encode(scene, { binary = true }))
bench("gltf glb decode (" .. buffer.len(glb) // 1000 .. " KB)", 5, buffer.len(glb), function()
Gltf.decode(Bytes.reader(glb))
end)
bench("gltf glb encode", 3, buffer.len(glb), function()
Gltf.encode(scene, { binary = true })
end)
local obj = assert(Obj.encode(scene))
bench("obj decode (" .. buffer.len(obj) // 1000 .. " KB)", 2, buffer.len(obj), function()
Obj.decode(Bytes.reader(obj))
end)
bench("obj encode", 2, buffer.len(obj), function()
Obj.encode(scene)
end)
local stl = assert(Stl.encode(scene))
bench("stl binary decode (" .. buffer.len(stl) // 1000 .. " KB)", 5, buffer.len(stl), function()
Stl.decode(Bytes.reader(stl))
end)
local ply = assert(Ply.encode(scene))
bench("ply binary decode (" .. buffer.len(ply) // 1000 .. " KB)", 5, buffer.len(ply), function()
Ply.decode(Bytes.reader(ply))
end)
local V = 128
local grid = Types.Voxels.new(V, V, V)
for z = 0, V - 1 do
for y = 0, V - 1 do
for x = 0, V - 1 do
local h = (math.sin(x * 0.11) + math.cos(y * 0.07) + 2) * V / 8 + z * 0
if z < h then
Types.Voxels.set(grid, x, y, z, 1 + (x // 8 + y // 8) % 6)
end
end
end
end
local vox = assert(Vox.encode(grid))
bench("vox decode (" .. buffer.len(vox) // 1000 .. " KB)", 5, buffer.len(vox), function()
Vox.decode(Bytes.reader(vox))
end)
bench("greedy mesh 128^3 (MB of cells)", 3, V * V * V, function()
MeshOps.voxelsToPrimitive(grid)
end)
end
do
-- layered + vector (ws-vec): PSD decode / encode of 8 RGBA layers 1024 x 768, flatten (codecs/Blend), SVG
-- rasterize at 512 x 512 (codecs/Raster). No fixtures: the inputs are built here.
local Types = require("@formats/Types")
local Psd = require("@formats/layered/psd")
local LayerOps = require("@formats/ops/LayerOps")
local Svg = require("@formats/vector/svg")
local W, H = 1024, 768
local doc = Types.Layered.new(W, H)
local modes = { "normal", "multiply", "screen", "overlay", "normal", "softLight", "difference", "normal" }
for k = 1, 8 do
local img = Types.Image.new(W, H)
local px = img.pixels
for i = 0, W * H - 1 do
local x, y = i % W, i // W
buffer.writeu32(px, i * 4, ((x * k) % 256) + ((y * 3) % 256) * 256 + (((x + y) // 4) % 256) * 65536 + (if (x // 64 + y // 64 + k) % 3 == 0 then 0 else 200) * 16777216)
end
local l = Types.Layered.layer("L" .. k, img)
l.blend = modes[k]
doc.layers[k] = l
end
local psd = assert(Psd.encode(doc))
bench("psd decode 8 layers 1024x768", 2, W * H * 4 * 9, function()
Psd.decode(Bytes.reader(psd))
end)
bench("psd encode 8 layers (RLE)", 1, W * H * 4 * 9, function()
Psd.encode(doc)
end)
bench("flatten 8 layers (blend modes)", 2, W * H * 4 * 8, function()
LayerOps.flatten(doc)
end)
local shapes = {}
for k = 0, 39 do
table.insert(shapes, string.format("<circle cx='%d' cy='%d' r='%d' fill='url(#g)' stroke='#222' stroke-width='2' opacity='0.8'/>", (k * 37) % 100, (k * 53) % 100, 5 + k % 12))
table.insert(shapes, string.format("<path d='M%d %d q 20 -30 40 0 t 40 0' fill='none' stroke='hsl(%d, 70%%, 50%%)' stroke-width='3' stroke-dasharray='4 2'/>", k % 50, k * 2, k * 9))
end
local text = "<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100'><defs><radialGradient id='g' fx='0.3' fy='0.3'><stop offset='0' stop-color='#fff'/><stop offset='1' stop-color='#36c'/></radialGradient></defs>" .. table.concat(shapes) .. "</svg>"
local v = assert(Svg.decode(Bytes.reader(buffer.fromstring(text))))
bench("svg parse (80 elements)", 5, #text, function()
Svg.decode(Bytes.reader(buffer.fromstring(text)))
end)
bench("svg rasterize 512x512 (80 shapes)", 2, 512 * 512 * 4, function()
Svg.rasterize(v, 512, 512)
end)
end
do
local Webp = require("@formats/image/webp")
local WB = require("@tests/gen/webp_bench")
local n = WB.width * WB.height * 4
local lossy, lossless = buffer.fromstring(WB.lossy), buffer.fromstring(WB.lossless)
bench("webp lossy decode 512x512", 3, n, function()
Webp.decode(Bytes.reader(lossy))
end)
bench("webp lossless decode 512x512", 3, n, function()
Webp.decode(Bytes.reader(lossless))
end)
local img = assert(Webp.decode(Bytes.reader(lossless)))
bench("webp lossless encode (effort 5)", 1, n, function()
Webp.encode(img)
end)
bench("webp lossless encode (effort 1)", 1, n, function()
Webp.encode(img, { effort = 1 })
end)
end
do
local Xml = require("@formats/codecs/Xml")
local XB = require("@tests/gen/xml_bench")
local doc = assert(Xml.decode(XB.text))
bench("xml decode (DOM)", 5, #XB.text, function()
Xml.decode(XB.text)
end)
bench("xml events", 5, #XB.text, function()
for _ in Xml.events(XB.text) do
end
end)
bench("xml encode", 5, #XB.text, function()
Xml.encode(doc)
end)
end
-- ws-m4a: AAC-LC / ALAC decode and ALAC encode (MB/s of 16-bit PCM equivalent: frames * channels * 2), MDCT
do
local M4a = require("@formats/audio/m4a")
local Alac = require("@formats/codecs/Alac")
local Mdct = require("@formats/codecs/Mdct")
local MA = require("@tests/gen/m4a_aac")
local ML = require("@tests/gen/m4a_alac")
local aac = buffer.fromstring(MA[1].data)
local a = assert(M4a.decode(Bytes.reader(aac)))
bench("aac-lc decode (m4a, stereo)", 3, a.frames * a.channels * 2, function()
M4a.decode(Bytes.reader(aac))
end)
local alac = buffer.fromstring(ML[1].data)
local l = assert(M4a.decode(Bytes.reader(alac)))
bench("alac decode (m4a, stereo 16)", 3, l.frames * l.channels * 2, function()
M4a.decode(Bytes.reader(alac))
end)
local enc = assert(Alac.encoder({ sampleRate = 44100, channels = 2, bitDepth = 16 }))
local ints = table.create(a.frames * 2, 0)
for i = 1, a.frames * 2 do
ints[i] = math.floor(buffer.readf32(a.samples, (i - 1) * 4) * 32767)
end
bench("alac encode (stereo 16)", 2, a.frames * 2 * 2, function()
local f = 0
while f < a.frames do
local n = math.min(4096, a.frames - f)
enc:encode(ints, f * 2 + 1, n)
f += n
end
end)
local plan = assert(Mdct.new(2048))
local x, X = table.create(2048, 0.5), table.create(1024, 0)
bench("mdct 2048 x 1000 (forward)", 3, 1000 * 2048 * 4, function()
for _ = 1, 1000 do
Mdct.forward(plan, x, 1, X, 1)
end
end)
end
do
local Opus = require("@formats/audio/opus")
local Cases = require("@tests/audio/_opus_cases")
local c = Cases.list[2]
local a = Cases.signal(c)
local dt = bench("opus celt encode 128k (1.5 s st)", 2, a.frames * a.channels * 2, function()
Opus.encode(a, { bitrate = 128000 })
end)
local _ = dt
end
+1 -1
View File
@@ -3,7 +3,7 @@
cd "$(dirname "$0")/.." || exit 1
LUAU=${LUAU:-$(command -v luau || nix shell nixpkgs#luau -c sh -c 'command -v luau')}
LUAJIT=${LUAJIT:-$(command -v luajit || nix shell nixpkgs#luajit -c sh -c 'command -v luajit')}
python3 -I tools/fixtures.py deflate png mp3 opus flac vorbis > /dev/null || exit 1
python3 -I tools/fixtures.py > /dev/null || exit 1
python3 -I tools/build.py luajit > /dev/null || exit 1
"$LUAU" --codegen -O2 tools/bench.luau
"$LUAJIT" -e 'package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path' build/luajit/tools/bench.lua
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/env python3
# Brotli static data generator (python3 -I tools/brotli_static.py [brotli-source-dir]): writes
# src/Formats/codecs/Brotli/Static.luau from the official brotli C sources (MIT; licenses/brotli-LICENSE.txt):
# the 122784-byte RFC 7932 static dictionary (c/common/dictionary_inc.h, stored deflated + base64), the context
# lookup table (c/common/context.c) and the 121 word transforms (c/common/transform.c).
# Without an argument the source comes from `nix build nixpkgs#brotli.src`.
import base64, os, re, subprocess, sys, zlib
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
OUT = os.path.join(ROOT, "src", "Formats", "codecs", "Brotli", "Static.luau")
def c_array(text, name):
m = re.search(re.escape(name) + r"[^=]*=\s*\{(.*?)\};", text, re.S)
body = re.sub(r"/\*.*?\*/", "", m.group(1), flags=re.S)
body = body.replace("BROTLI_TRANSFORM_IDENTITY", "0").replace("BROTLI_TRANSFORM_UPPERCASE_FIRST", "10")
body = body.replace("BROTLI_TRANSFORM_UPPERCASE_ALL", "11")
body = re.sub(r"BROTLI_TRANSFORM_OMIT_LAST_(\d)", lambda k: k.group(1), body)
body = re.sub(r"BROTLI_TRANSFORM_OMIT_FIRST_(\d)", lambda k: str(11 + int(k.group(1))), body)
return [int(x, 0) for x in re.findall(r"0x[0-9a-fA-F]+|\d+", body)]
def c_string(text, name):
m = re.search(re.escape(name) + r"[^=]*=\s*(.*?);", text, re.S)
parts = re.findall(r'"((?:[^"\\]|\\.)*)"', re.sub(r"/\*.*?\*/", "", m.group(1), flags=re.S))
s = "".join(parts)
return s.encode("latin-1").decode("unicode_escape").encode("latin-1") + b"\0"
def b64_chunks(data, width=96):
s = base64.b64encode(data).decode()
return [s[i:i + width] for i in range(0, len(s), width)]
def main():
src = sys.argv[1] if len(sys.argv) > 1 else subprocess.run(
["nix", "build", "nixpkgs#brotli.src", "--no-link", "--print-out-paths"], capture_output=True, check=True,
text=True).stdout.strip()
common = os.path.join(src, "c", "common")
dict_text = open(os.path.join(common, "dictionary_inc.h")).read()
dictionary = bytes(c_array(dict_text, "kBrotliDictionaryData"))
assert len(dictionary) == 122784
ctx = bytes(c_array(open(os.path.join(common, "context.c")).read(), "_kBrotliContextLookupTable"))
assert len(ctx) == 2048
tr_text = open(os.path.join(common, "transform.c")).read()
ps = c_string(tr_text, "kPrefixSuffix")
assert len(ps) == 217, len(ps)
psmap = c_array(tr_text, "kPrefixSuffixMap")
trans = c_array(tr_text, "kTransformsData")
assert len(psmap) == 50 and len(trans) == 363
z = zlib.compress(dictionary, 9)
lines = [
"--!strict",
"-- codecs/Brotli/Static: GENERATED by tools/brotli_static.py from the brotli C sources (MIT, Google; see",
"-- licenses/brotli-LICENSE.txt) - do not edit. The RFC 7932 static dictionary (122784 bytes, deflated, base64),",
"-- the context lookup table (Appendix B, 4 modes x 512) and the 121 word transforms (Appendix B).",
"return {",
"\tdictionarySize = %d," % len(dictionary),
"\tdictionaryCrc = %d," % zlib.crc32(dictionary),
"\tdictionary = {",
]
lines += ['\t\t"%s",' % c for c in b64_chunks(z)]
lines += ["\t},", "\tcontext = {"]
lines += ['\t\t"%s",' % c for c in b64_chunks(ctx)]
lines += ["\t},"]
lines += ['\tprefixSuffix = "%s",' % base64.b64encode(ps).decode()]
lines += ["\tprefixSuffixMap = { %s }," % ", ".join(map(str, psmap))]
lines += ["\ttransforms = {"]
for i in range(0, len(trans), 30):
lines.append("\t\t%s," % ", ".join(map(str, trans[i:i + 30])))
lines += ["\t},", "}", ""]
with open(OUT, "w") as f:
f.write("\n".join(lines))
print("brotli_static: wrote %s (%d bytes)" % (os.path.relpath(OUT, ROOT), os.path.getsize(OUT)))
if __name__ == "__main__":
main()
+103
View File
@@ -0,0 +1,103 @@
# 7z fixtures (tools/fixtures.py): a small tree (text, x86 machine code, runs, an empty file, empty and nested
# directories, UTF-16 names with accents and a surrogate pair) archived by 7-Zip 2x (nix _7zz) with many method chains:
# LZMA / LZMA2 / copy / Deflate, solid and non-solid, BCJ / ARM64 / delta filters, plain and compressed headers; plus
# BZip2 archives (codecs/Bzip2), archives whose methods are not supported (PPMd, BCJ2, AES) and an empty archive.
# tests/gen/7z.luau { files = { { name, dir, data?, mtime } }, cases = { { name, data, unsupported? } } }
import os, random, subprocess, sys, tempfile
TOOL = "_7zz"
def tree(rng):
with open(os.path.realpath(sys.executable), "rb") as f:
code = f.read(60000)
base = os.path.dirname(os.__file__)
text = b""
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) > 50000:
break
return [
("readme.txt", text[:50000]),
("bin/code.bin", code),
("bin/runs.dat", b"ab" * 5000 + b"\0" * 9000 + bytes(range(256)) * 8),
("bin/random.dat", rng.randbytes(3000)),
("empty.txt", b""),
("emptydir/", None),
("a/b/c/deep.txt", b"deep\n" * 10),
("héllo wörld ☃.txt", "unicode ☃\n".encode()),
("\U0001d11e clef.txt", b"g clef\n"),
]
def generate(ctx):
rng = random.Random(77)
files = tree(rng)
mtime = 1600000000
out_files = []
cases = []
with tempfile.TemporaryDirectory() as d:
src = os.path.join(d, "src")
for name, data in files:
p = os.path.join(src, name)
if data is None:
os.makedirs(p, exist_ok=True)
os.utime(p, (mtime, mtime))
out_files.append({"name": name.rstrip("/"), "dir": True, "mtime": mtime})
else:
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, "wb") as f:
f.write(data)
os.utime(p, (mtime + 60, mtime + 60))
out_files.append({"name": name, "dir": False, "data": data, "mtime": mtime + 60})
for sub in ("bin", "a", "a/b", "a/b/c"):
os.utime(os.path.join(src, sub), (mtime, mtime))
out_files.append({"name": sub, "dir": True, "mtime": mtime})
def make(name, args, unsupported=None):
arc = os.path.join(d, name + ".7z")
if os.path.exists(arc):
os.remove(arc)
subprocess.run(["nix", "shell", "nixpkgs#" + TOOL, "-c", "7zz", "a", "-bd", "-y", arc] + args + ["."],
cwd=src, capture_output=True, check=True)
with open(arc, "rb") as f:
c = {"name": name, "data": f.read()}
if unsupported:
c["unsupported"] = unsupported
cases.append(c)
make("lzma-nonsolid", ["-m0=LZMA", "-ms=off", "-mhc=off"])
make("lzma-solid", ["-m0=LZMA:d=1m", "-ms=on"])
make("lzma2-solid", ["-m0=LZMA2", "-ms=on"])
make("lzma2-mt-blocks", ["-m0=LZMA2:d=64k:c=20k", "-ms=on", "-mmt=4"])
make("lzma2-hc-off", ["-m0=LZMA2", "-mhc=off"])
make("copy", ["-m0=Copy", "-mhc=off"])
make("copy-hc", ["-m0=Copy"])
make("deflate", ["-m0=Deflate", "-ms=on"])
make("bcj-lzma", ["-m0=BCJ", "-m1=LZMA", "-ms=on"])
make("bcj-lzma2", ["-m0=BCJ", "-m1=LZMA2", "-ms=off"])
make("arm64-lzma2", ["-m0=ARM64", "-m1=LZMA2"])
make("arm-lzma2", ["-m0=ARM", "-m1=LZMA2"])
make("delta-lzma", ["-m0=Delta:4", "-m1=LZMA"])
make("ppc-sparc", ["-m0=PPC", "-m1=SPARC", "-m2=LZMA2"])
make("lzma-lc-lp", ["-m0=LZMA:lc=0:lp=2:pb=0", "-ms=e"])
make("auto", ["-mx=9"])
make("fast", ["-mx=1"])
make("bzip2", ["-m0=BZip2", "-mhc=off"])
make("bzip2-solid-bcj", ["-m0=BCJ", "-m1=BZip2", "-ms=on", "-mhc=on"])
make("ppmd", ["-m0=PPMd", "-mhc=off"], unsupported="ppmd")
make("bcj2", ["-m0=BCJ2", "-m1=LZMA", "-m2=LZMA", "-m3=LZMA", "-mb0s0:1", "-mb0s1:2", "-mb0s2:3", "-mhc=off"],
unsupported="bcj2")
make("aes", ["-m0=LZMA2", "-mhc=off", "-pSecret"], unsupported="aes")
# an empty archive
arc = os.path.join(d, "empty.7z")
empty = os.path.join(d, "emptysrc")
os.makedirs(empty)
subprocess.run(["nix", "shell", "nixpkgs#" + TOOL, "-c", "7zz", "a", "-bd", "-y", arc, "-x!*", "."],
cwd=empty, capture_output=True)
if os.path.exists(arc):
with open(arc, "rb") as f:
cases.append({"name": "empty", "data": f.read(), "empty": True})
ctx.emit("7z", {"files": out_files, "cases": cases})
+110
View File
@@ -0,0 +1,110 @@
# Shared helpers for the data-format fixture generators (json, xml, csv, toml, yaml, msgpack, cbor, plist, ...):
# fetch(url, sha256) -> a nix store path of an unpacked tarball (official test suites, pinned by hash)
# canon(value) -> the canonical text a Luau test computes too (tests/data/_canon.luau): typed, sorted keys,
# numbers as %.17g, so Python's parse and ours compare exactly.
import os, subprocess, datetime
def fetch(url, sha256):
expr = 'builtins.fetchTarball { url = "%s"; sha256 = "%s"; }' % (url, sha256)
out = subprocess.run(["nix", "eval", "--raw", "--impure", "--expr", expr], capture_output=True, check=True)
return out.stdout.decode()
def _b(s):
if isinstance(s, str):
return s.encode("utf-8", "surrogatepass")
return bytes(s)
def canon(v):
"""null n; true t; false f; number #%d (integral, under 2^53) or #%.17g; string s<len>:<bytes>;
bytes b<len>:<bytes>; list [..]; dict {k v ...} with keys sorted by their canon bytes; dates d<rfc3339>"""
out = bytearray()
_canon(v, out)
return bytes(out)
def num(x):
x = float(x)
if x != x:
return b"#nan"
if x in (float("inf"), float("-inf")):
return b"#inf" if x > 0 else b"#-inf"
if x == int(x) and abs(x) < 2 ** 53:
return b"#%d" % int(x)
return b"#" + ("%.17g" % x).encode()
def _canon(v, out):
if v is None:
out += b"n"
elif v is True:
out += b"t"
elif v is False:
out += b"f"
elif isinstance(v, (int, float)):
out += num(v)
elif isinstance(v, str):
b = _b(v)
out += b"s%d:" % len(b) + b
elif isinstance(v, (bytes, bytearray)):
out += b"b%d:" % len(v) + bytes(v)
elif isinstance(v, (list, tuple)):
out += b"["
for x in v:
_canon(x, out)
out += b","
out += b"]"
elif isinstance(v, dict):
items = []
for k, x in v.items():
kb = bytearray()
_canon(k, kb)
items.append((bytes(kb), x))
items.sort(key=lambda p: p[0])
out += b"{"
for kb, x in items:
out += kb + b"="
_canon(x, out)
out += b","
out += b"}"
elif isinstance(v, (datetime.datetime, datetime.date, datetime.time)):
out += b"d" + date_text(v).encode()
else:
raise TypeError("canon: %r" % type(v))
def date_text(v):
"""RFC 3339 the way Types.Date prints: fraction without trailing zeros, Z for +00:00"""
def frac(us):
return ("." + ("%06d" % us).rstrip("0")) if us else ""
def tz(t):
off = t.utcoffset()
if off is None:
return ""
m = int(off.total_seconds()) // 60
if m == 0:
return "Z"
sign = "-" if m < 0 else "+"
m = abs(m)
return "%s%02d:%02d" % (sign, m // 60, m % 60)
if isinstance(v, datetime.datetime):
return "%04d-%02d-%02dT%02d:%02d:%02d%s%s" % (v.year, v.month, v.day, v.hour, v.minute, v.second,
frac(v.microsecond), tz(v))
if isinstance(v, datetime.date):
return "%04d-%02d-%02d" % (v.year, v.month, v.day)
return "%02d:%02d:%02d%s" % (v.hour, v.minute, v.second, frac(v.microsecond))
def python(ctx, packages, body):
"""run body (with these helpers prepended, so canon() / date_text() exist) under a nix python with packages;
returns stdout bytes, raising with the script's stderr on failure"""
import subprocess as sp
src = open(os.path.abspath(__file__)).read()
try:
return ctx.python(packages, src + "\n" + body)
except sp.CalledProcessError as e:
raise RuntimeError("fixture python failed:\n" + e.stderr.decode(errors="replace")[-3000:])
+181
View File
@@ -0,0 +1,181 @@
# Font reference data (run by tools/fixtures/fonts.py inside a nix python with fonttools, freetype-py, uharfbuzz and
# brotli). Reads a JSON list of {name, path | b64} on stdin; writes JSON on stdout: per font the bytes, the metrics,
# names, cmap samples (fontTools), advances / side bearings / control boxes / areas of sample glyphs (fontTools pens),
# kerning of sample pairs (HarfBuzz GPOS 'kern', or FreeType for 'kern' tables), FreeType renders (no hinting) of
# sample glyphs at a few sizes, and the WOFF / WOFF2 versions (fontTools).
import base64, io, json, sys
import freetype
import uharfbuzz as hb
from fontTools.pens.areaPen import AreaPen
from fontTools.pens.boundsPen import ControlBoundsPen
from fontTools.ttLib import TTFont, newTable
from fontTools.ttLib.tables._k_e_r_n import KernTable_format_0
SAMPLE_TEXT = "AVTWYLPFoaey.,'\"-0147"
SIZES = [11, 24, 47]
def b64(b):
return base64.b64encode(b).decode()
def load(spec):
if "path" in spec:
return open(spec["path"], "rb").read()
return base64.b64decode(spec["b64"])
def with_kern_table(data):
"""a copy with a 'kern' format 0 table of a few pairs (none of the sample fonts has one)"""
f = TTFont(io.BytesIO(data))
cmap = f.getBestCmap()
order = f.getGlyphOrder()
pairs = {}
letters = "AVTWYLoaey"
for i, a in enumerate(letters):
for j, b in enumerate(letters):
if ord(a) in cmap and ord(b) in cmap and (i * 7 + j * 3) % 4 == 0:
pairs[(cmap[ord(a)], cmap[ord(b)])] = -((i * 13 + j * 5) % 90) - 10
k = newTable("kern")
k.version = 0
st = KernTable_format_0()
st.version, st.coverage, st.format = 0, 1, 0
st.kernTable = pairs
k.kernTables = [st]
f["kern"] = k
if "GPOS" in f:
del f["GPOS"]
out = io.BytesIO()
f.save(out)
return out.getvalue()
def collection(datas):
from fontTools.ttLib.ttCollection import TTCollection
c = TTCollection()
c.fonts = [TTFont(io.BytesIO(d)) for d in datas]
out = io.BytesIO()
c.save(out)
return out.getvalue()
def reference(name, data, index=0):
f = TTFont(io.BytesIO(data), fontNumber=index)
gs = f.getGlyphSet()
order = f.getGlyphOrder()
head, hhea, maxp = f["head"], f["hhea"], f["maxp"]
names = f["name"]
def nm(i):
r = names.getName(i, 3, 1, 0x409) or names.getName(i, 3, 1) or names.getName(i, 1, 0, 0) or names.getName(i, 0, 3)
return r.toUnicode() if r else ""
cmap = f.getBestCmap() or {}
cps = sorted(cmap)
sample_cps = cps[:: max(1, len(cps) // 150)] + [0x10FFFF, 0xFFFF, 0x7F, 0x9999]
cm = [[cp, f.getGlyphID(cmap[cp]) if cp in cmap else 0] for cp in sample_cps]
# glyphs: every glyph for small fonts, else a sample (plus the sample text's)
gids = list(range(len(order))) if len(order) <= 400 else list(range(0, len(order), len(order) // 300))
for ch in SAMPLE_TEXT:
if ord(ch) in cmap:
gids.append(f.getGlyphID(cmap[ord(ch)]))
gids = sorted(set(gids))
hmtx = f["hmtx"]
glyphs = []
for g in gids:
gn = order[g]
adv, lsb = hmtx[gn]
bp = ControlBoundsPen(gs)
gs[gn].draw(bp)
ap = AreaPen(gs)
gs[gn].draw(ap)
e = {"gid": g, "adv": adv, "lsb": lsb, "area": float(ap.value)}
if bp.bounds:
e["box"] = [float(v) for v in bp.bounds]
glyphs.append(e)
# kerning
kern = []
letters = [c for c in SAMPLE_TEXT if ord(c) in cmap]
if "kern" in f and "GPOS" not in f:
face = freetype.Face(io.BytesIO(data), index)
for a in letters:
for b in letters:
ga, gb = f.getGlyphID(cmap[ord(a)]), f.getGlyphID(cmap[ord(b)])
v = face.get_kerning(a, b, freetype.FT_KERNING_UNSCALED) # freetype-py maps characters to glyphs
kern.append([ga, gb, v.x])
elif "GPOS" in f:
blob = hb.Blob(data)
hface = hb.Face(blob, index)
hfont = hb.Font(hface)
feats = {"kern": True, "liga": False, "clig": False, "calt": False, "mark": False, "mkmk": False, "ccmp": False, "locl": False, "rlig": False, "dist": False, "curs": False}
for a in letters:
for b in letters:
buf = hb.Buffer()
buf.add_str(a + b)
buf.guess_segment_properties()
hb.shape(hfont, buf, feats)
ga, gb = buf.glyph_infos[0].codepoint, buf.glyph_infos[1].codepoint
adv = buf.glyph_positions[0].x_advance - hmtx[order[ga]][0]
kern.append([ga, gb, adv])
# FreeType renders
face = freetype.Face(io.BytesIO(data), index)
renders = []
rg = [f.getGlyphID(cmap[ord(c)]) for c in "AgQ@&e%" if ord(c) in cmap]
for px in SIZES:
face.set_pixel_sizes(0, px)
for g in rg:
face.load_glyph(g, freetype.FT_LOAD_NO_HINTING | freetype.FT_LOAD_NO_BITMAP)
face.glyph.render(freetype.FT_RENDER_MODE_NORMAL)
bm = face.glyph.bitmap
rows = []
for y in range(bm.rows):
rows.append(bytes(bm.buffer[y * bm.pitch: y * bm.pitch + bm.width]))
renders.append({"gid": g, "px": px, "w": bm.width, "h": bm.rows, "left": face.glyph.bitmap_left,
"top": face.glyph.bitmap_top, "pixels": b64(b"".join(rows))})
os2 = f["OS/2"] if "OS/2" in f else None
return {
"name": name, "data": b64(data), "index": index, "upem": head.unitsPerEm, "ascent": hhea.ascent,
"descent": hhea.descent, "lineGap": hhea.lineGap, "numGlyphs": maxp.numGlyphs, "family": nm(16) or nm(1),
"style": nm(17) or nm(2), "fullName": nm(4), "weight": os2.usWeightClass if os2 else 0,
"cff": "CFF " in f, "cmap": cm, "glyphs": glyphs, "kern": kern, "renders": renders,
}
def flavors(data):
out = {}
for fl in ("woff", "woff2"):
f = TTFont(io.BytesIO(data))
f.flavor = fl
b = io.BytesIO()
f.save(b)
out[fl] = b64(b.getvalue())
from fontTools.ttLib import woff2
src, dst = io.BytesIO(data), io.BytesIO()
woff2.compress(src, dst, transform_tables={"glyf", "loca", "hmtx"})
out["woff2h"] = b64(dst.getvalue())
return out
def main():
specs = json.load(sys.stdin)
fonts = {}
for s in specs:
fonts[s["name"]] = load(s)
res = {"fonts": [], "woff": []}
for name, data in fonts.items():
res["fonts"].append(reference(name, data))
kd = with_kern_table(fonts["ProggyClean"] if "ProggyClean" in fonts else next(iter(fonts.values())))
res["fonts"].append(reference("kern-table", kd))
names = [n for n in ("Karla-Regular", "Cousine-Regular") if n in fonts]
if len(names) == 2:
ttc = collection([fonts[n] for n in names])
r = reference("collection-1", ttc, 1)
res["fonts"].append(r)
res["ttc"] = {"data": b64(ttc), "count": 2, "second": names[1]}
# woff / woff2 of every font (the reference values are the sfnt's own)
for name, data in fonts.items():
fl = flavors(data)
res["woff"].append({"name": name, "woff": fl["woff"], "woff2": fl["woff2"], "woff2h": fl["woff2h"]})
json.dump(res, sys.stdout)
main()
+34
View File
@@ -0,0 +1,34 @@
-- tools/fixtures/_gltf_encode: run by tools/fixtures/gltf.py (luau CLI, repo root): decodes every glTF case with our
-- reader and encodes it with our writer as .glb and as .gltf with an external .bin and image files, printing
-- "<file>\t<hex>" lines for the reference tools (assimp, trimesh) to read back. Files: rt_<case>.glb, rt_<case>.gltf.
local Gltf = require("@formats/model/gltf")
local Bytes = require("@formats/core/Bytes")
local Cases = require("@tests/gen/gltf_cases")
local HEX = {}
for i = 0, 255 do
HEX[i] = string.format("%02x", i)
end
local function hex(s: string): string
local out = table.create(#s)
for i = 1, #s do
out[i] = HEX[string.byte(s, i)]
end
return table.concat(out)
end
for i, c in Cases do
local scene, err = Gltf.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files })
if scene then
local glb = assert(Gltf.encode(scene, { binary = true }))
print(string.format("rt_%d.glb\t%s", i, hex(buffer.tostring(glb))))
local files = {}
local gltf = assert(Gltf.encode(scene, { external = true, files = files, name = "rt_" .. i .. ".gltf" }))
print(string.format("rt_%d.gltf\t%s", i, hex(buffer.tostring(gltf))))
for name, data in files do
print(name .. "\t" .. hex(if type(data) == "string" then data else buffer.tostring(data)))
end
else
print("skipped " .. c.name .. ": " .. tostring(err))
end
end
+31
View File
@@ -0,0 +1,31 @@
-- tools/fixtures/_m4a_encode: run by tools/fixtures/m4a.py (luau, from the repo root) so the reference tools can check
-- our writers: encodes the test signal (tests/audio/_signal) to ALAC M4A (audio/m4a) and ALAC / PCM CAF (audio/caf)
-- and prints "<name> <hex>" lines. The tests re-encode and compare the CRC with the file ffmpeg validated.
local Signal = require("@tests/audio/_signal")
local M4a = require("@formats/audio/m4a")
local Caf = require("@formats/audio/caf")
local function hex(b: buffer): string
local t = table.create(buffer.len(b))
for i = 0, buffer.len(b) - 1 do
t[i + 1] = string.format("%02x", buffer.readu8(b, i))
end
return table.concat(t)
end
local Cases = require("@tests/audio/_encode_cases")
for _, c in Cases do
local a = Signal.audio(c.rate, c.frames, c.channels, c.bits, c.seed)
a.tags = c.tags or {}
local out, err
if c.container == "caf" then
out, err = Caf.encode(a, { codec = c.codec, bitDepth = c.bits })
else
out, err = M4a.encode(a, { bitDepth = c.bits })
end
if not out then
print(c.name .. " ERROR " .. tostring(err))
else
print(c.name .. " " .. hex(out))
end
end
+41
View File
@@ -0,0 +1,41 @@
# The deterministic integer test signal shared by tools/fixtures/m4a.py, tools/fixtures/caf.py and the Luau side
# (tests/audio/_signal.luau computes the same numbers): triangle + square + MINSTD noise (exact in doubles) + clicks, per channel.
import struct
def signal(frames, channels, bits, seed):
s = seed
peak = 2 ** (bits - 1) - 1
out = []
for i in range(frames):
for c in range(channels):
s = (s * 48271) % 2147483647
p1 = 97 + 31 * c
tri = abs((i % p1) * 2 - p1) * 2 - p1
v = tri * (peak // (4 * p1))
p2 = 1500 + 200 * c
v += (peak // 6) if (i // p2) % 2 == 0 else -(peak // 6)
v += ((s // 65536) % 4096 - 2048) * (peak // 65536 + 1)
if i % 7001 < 3:
v += peak // 2
out.append(max(-peak - 1, min(peak, v)))
return out
def pack(samples, bits, big=False):
e = ">" if big else "<"
if bits == 16:
return struct.pack(e + "%dh" % len(samples), *samples)
if bits == 24:
b = bytearray()
for v in samples:
x = struct.pack("<i", v)[:3]
b += x[::-1] if big else x
return bytes(b)
return struct.pack(e + "%di" % len(samples), *samples)
def wav(samples, channels, rate, bits):
data = pack(samples, bits)
fmt = struct.pack("<HHIIHH", 1, channels, rate, rate * channels * bits // 8, channels * bits // 8, bits)
return b"RIFF" + struct.pack("<I", 36 + len(data)) + b"WAVEfmt " + struct.pack("<I", 16) + fmt + b"data" + struct.pack("<I", len(data)) + data
+69
View File
@@ -0,0 +1,69 @@
# Shared helpers for the model fixture generators (obj.py, gltf.py): reference tools through nix.
# assimp_info(ctx, paths, raw?) -> [ { meshes, materials, vertices, faces, nodes, min, max, perMesh = [ { vertices, faces } ] } ]
# trimesh_metrics(ctx, paths) -> [ { area, faces, bounds, volume? } ] (trimesh, process=False, every geometry merged)
# luau_encode(ctx, script) -> { name: bytes }: runs a Luau script (repo-relative, .luaurc aliases) that prints
# "<name>\t<hex>" lines: how a generator gets our encoder's output for the reference tools to read back.
import json, os, re, subprocess, tempfile, shutil
FLOAT = r"(-?[\d.]+(?:e[-+]?\d+)?|-?nan|-?inf)"
def assimp_info(ctx, paths, raw=False):
# raw: `assimp info -r` (no post-processing: no joined vertices, no merged identical meshes)
out = []
for p in paths:
try:
txt = ctx.nix("assimp", ["assimp", "info", p] + (["-r"] if raw else [])).decode("utf-8", "replace")
except subprocess.CalledProcessError:
out.append({"failed": True})
continue
def num(label):
m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M)
return int(m.group(1)) if m else -1
def point(label):
m = re.search(label + r"\s+\(" + FLOAT + " " + FLOAT + " " + FLOAT + r"\)", txt)
return [float(m.group(i)) for i in (1, 2, 3)] if m else []
per = [{"vertices": int(a), "faces": int(c)} for a, b, c in re.findall(r"^\s+\d+ \(.*?\): \[(\d+) / (\d+) / (\d+) \|", txt, re.M)]
out.append({
"meshes": num("Meshes"), "materials": num("Materials"), "vertices": num("Vertices"), "faces": num("Faces"),
"nodes": num("Nodes"), "min": point("Minimum point"), "max": point("Maximum point"), "perMesh": per,
})
return out
TRIMESH = r"""
import json, sys, trimesh, numpy as np
res = []
for p in json.loads(sys.stdin.read()):
try:
m = trimesh.load(p, force="mesh", process=False)
d = {"area": float(m.area), "faces": int(len(m.faces)), "bounds": [float(v) for v in np.asarray(m.bounds).ravel()] if len(m.faces) else []}
except Exception as e:
d = {"failed": True}
res.append(d)
print(json.dumps(res))
"""
def trimesh_metrics(ctx, paths):
out = ctx.python(["trimesh", "numpy", "networkx", "lxml", "pillow"], TRIMESH, input=json.dumps(paths).encode())
return json.loads(out)
def luau_encode(ctx, script):
exe = shutil.which("luau")
cmd = [exe, script] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau", script]
res = subprocess.run(cmd, cwd=ctx.root, capture_output=True, check=True)
files = {}
for line in res.stdout.decode().split("\n"):
if "\t" in line:
name, hexdata = line.split("\t", 1)
files[name] = bytes.fromhex(hexdata.strip())
return files
def tempdir():
return tempfile.mkdtemp(prefix="formats-model-")
+32
View File
@@ -0,0 +1,32 @@
-- tools/fixtures/_obj_encode: run by tools/fixtures/obj.py (luau CLI, repo root): decodes every OBJ case with our
-- reader, encodes it again with our writer and prints "<file>\t<hex>" lines (the OBJ, its .mtl, textures) for the
-- reference tools (assimp, trimesh) to read back.
local Obj = require("@formats/model/obj")
local Bytes = require("@formats/core/Bytes")
local Cases = require("@tests/gen/obj_cases")
local HEX = {}
for i = 0, 255 do
HEX[i] = string.format("%02x", i)
end
local function hex(s: string): string
local out = table.create(#s)
for i = 1, #s do
out[i] = HEX[string.byte(s, i)]
end
return table.concat(out)
end
for _, c in Cases do
local scene, err = Obj.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files })
if not scene then
error(c.name .. ": " .. tostring(err))
end
local name = "rt_" .. c.name
local files = {}
local out = assert(Obj.encode(scene, { name = name, files = files }))
print(name .. "\t" .. hex(buffer.tostring(out)))
for fname, data in files do
print(fname .. "\t" .. hex(if type(data) == "string" then data else buffer.tostring(data)))
end
end
+56
View File
@@ -0,0 +1,56 @@
-- tools/fixtures/_off_encode.luau: run by tools/fixtures/off.py under the luau CLI (no file I/O): encodes the scenes of
-- tests/gen/off_scenes with each listed option set ("default" = {}, "plain" = no colours / normals / texcoords) and
-- prints "<scene>/<encoding> <hex>" lines, which the fixture step hands to trimesh, assimp and its own reader.
local Off = require("@formats/model/off")
local Types = require("@formats/Types")
local Scenes = require("@tests/gen/off_scenes")
local function build(spec: any): Types.Scene
local scene = Types.Scene.new()
for i, m in spec.meshes do
local prims = {}
for _, p in m.prims do
local attrs = {}
for name, a in p.attrs do
attrs[name] = Types.Scene.accessor(buffer.fromstring(a[3]), a[1], a[2], p.count)
end
local prim: any = { attributes = attrs, mode = p.mode }
if p.indices then
prim.indices = Types.Scene.accessor(buffer.fromstring(p.indices), "u32", 1, #p.indices // 4)
end
if p.faces then
prim.faces = Types.Scene.accessor(buffer.fromstring(p.faces), "u32", 1, #p.faces // 4)
end
if p.faceColors then
prim.extras = { faceColors = Types.Scene.accessor(buffer.fromstring(p.faceColors), "unorm8", 4, #p.faceColors // 4) }
end
table.insert(prims, prim)
end
scene.meshes[i] = { primitives = prims }
end
for i, n in spec.nodes do
scene.nodes[i] = { mesh = n.mesh, children = n.children or {}, translation = n.translation, rotation = n.rotation, scale = n.scale, matrix = n.matrix }
end
scene.roots = spec.roots
return scene
end
local function hex(b: buffer): string
local out = table.create(buffer.len(b))
for i = 0, buffer.len(b) - 1 do
out[i + 1] = string.format("%02x", buffer.readu8(b, i))
end
return table.concat(out)
end
local OPTS: { [string]: any } = { default = {}, plain = { colors = false, normals = false, texcoords = false } }
for _, spec in Scenes do
local scene = build(spec)
for e in spec.encodings do
local b, err = Off.encode(scene, OPTS[e])
if not b then
error(spec.name .. "/" .. e .. ": " .. tostring(err))
end
print(spec.name .. "/" .. e .. " " .. hex(b))
end
end
+32
View File
@@ -0,0 +1,32 @@
# OFF reference values (run by tools/fixtures/off.py through ctx.python(["trimesh", "numpy"], ...), python -I).
# stdin: JSON {"dir": tmp, "make": [name], "read": [name]}
# stdout: JSON {name (only the files trimesh reads): {"vertices": n, "pos_crc": crc of the f32 vertices, "faces": [[...]] or None (n-gons over 4)}}
# make: OFF files written by trimesh (an icosphere, a capsule)
# read: every file read with trimesh.exchange.off.load_off (positions; faces when all are triangles / quads, the
# only polygons trimesh keeps as they are)
import json, os, sys, zlib
import numpy as np
import trimesh
from trimesh.exchange import off as toff
req = json.load(sys.stdin)
d = req["dir"]
out = {}
for name in req["make"]:
m = trimesh.creation.icosphere(subdivisions=2, radius=3.0) if "ico" in name else trimesh.creation.capsule(height=2.0, radius=0.5)
with open(os.path.join(d, name), "w") as f:
f.write(toff.export_off(m, digits=9))
for name in req["read"]:
try:
with open(os.path.join(d, name), "rb") as f:
r = toff.load_off(f)
except Exception: # noqa: BLE001 - trimesh fails on polygons of more than 4 vertices: no reference then
continue
v = np.asarray(r["vertices"], dtype=np.float64).reshape(-1, 3)
res = {"vertices": len(v), "pos_crc": zlib.crc32(v.astype("<f4").tobytes())}
faces = r.get("faces")
res["tris"] = int(len(faces)) if faces is not None and len(np.shape(faces)) == 2 and np.shape(faces)[1] == 3 else -1
if res["tris"] >= 0:
res["faces"] = [[int(x) for x in f] for f in np.asarray(faces)]
out[name] = res
json.dump(out, sys.stdout)
+17
View File
@@ -0,0 +1,17 @@
-- tools/fixtures/_opus_encode: run by tools/fixtures/opus_celt.py (luau, from the repo root): encodes
-- tests/audio/_opus_cases with audio/opus's CELT encoder and prints "<name> <hex>" lines for opusdec / ffmpeg.
local Opus = require("@formats/audio/opus")
local Cases = require("@tests/audio/_opus_cases")
for _, c in Cases.list do
local out, err = Opus.encode(Cases.signal(c), { bitrate = c.bitrate })
if not out then
print(c.name .. " ERROR " .. tostring(err))
else
local t = table.create(buffer.len(out))
for i = 0, buffer.len(out) - 1 do
t[i + 1] = string.format("%02x", buffer.readu8(out, i))
end
print(c.name .. " " .. table.concat(t))
end
end
+180
View File
@@ -0,0 +1,180 @@
-- tools/fixtures/_ours.luau: our encoders' output for the reference tools to read (run by tools/fixtures/*.py through
-- `luau tools/fixtures/_ours.luau -a <format>`). Prints one JSON object: { "data": hex of the encoded file, ... the
-- facts the python side checks the reference's reading against }.
local Types = require("@formats/Types")
local Crc32 = require("@formats/core/Crc32")
local LayerOps = require("@formats/ops/LayerOps")
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 jstr(s: string): string
return '"' .. string.gsub(s, '[%c"\\]', function(c: string): string
return string.format("\\u%04x", string.byte(c))
end) .. '"'
end
local function json(v: any): string
if type(v) == "table" then
if #v > 0 or next(v) == nil then
local t = {}
for i, x in v do
t[i] = json(x)
end
return "[" .. table.concat(t, ",") .. "]"
end
local t = {}
for k, x in v do
table.insert(t, jstr(k) .. ":" .. json(x))
end
return "{" .. table.concat(t, ",") .. "}"
elseif type(v) == "string" then
return jstr(v)
elseif type(v) == "boolean" then
return if v then "true" else "false"
end
return tostring(v)
end
-- a deterministic rgba8 image
local function image(w: number, h: number, seed: number, alpha: boolean?): Types.Image
local img = Types.Image.new(w, h)
for y = 0, h - 1 do
for x = 0, w - 1 do
local o = (y * w + x) * 4
buffer.writeu8(img.pixels, o, (x * (seed + 3) * 7 + y * 5) % 256)
buffer.writeu8(img.pixels, o + 1, (y * (seed + 1) * 9 + x) % 256)
buffer.writeu8(img.pixels, o + 2, ((x + seed) * (y + 1) * 3) % 256)
buffer.writeu8(img.pixels, o + 3, if alpha and (x + y) % 3 == 0 then (x * 40 + seed) % 256 else 255)
end
end
return img
end
local function gray(w: number, h: number): Types.Image
local img = Types.Image.new(w, h, "gray8")
for i = 0, w * h - 1 do
buffer.writeu8(img.pixels, i, (i * 13) % 256)
end
return img
end
-- the Layered document tests/layered/psd.luau also builds (keep them in step)
local function psdDoc(): Types.Layered
local L = Types.Layered
local doc = L.new(36, 24)
local bg = L.layer("Background", image(36, 24, 1))
local mul = L.layer("Multiply", image(20, 12, 2, true), 4, 3)
mul.blend = "multiply"
mul.opacity = 200 / 255
local scr = L.layer("Screen", image(18, 18, 3, true), 12, 4)
scr.blend = "screen"
local iso = L.group("Isolated", { scr })
iso.blend = "normal"
iso.opacity = 180 / 255
local hid = L.layer("Hidden", image(8, 8, 4), 1, 1)
hid.visible = false
local diff = L.layer("Diff \u{e9}\u{65e5}", image(14, 10, 5, true), 18, 12)
diff.blend = "difference"
local pass = L.group("Pass", { hid, diff })
local base = L.layer("Base", image(10, 8, 6), 24, 14)
local clip = L.layer("Clipped", image(14, 12, 7, true), 20, 10)
clip.clip = true
local masked = L.layer("Masked", image(16, 10, 8), 2, 12)
masked.mask = { image = gray(12, 8), x = 4, y = 13, default = 0 }
local fill = L.layer("Fill", image(8, 24, 9, true), 28, 0)
fill.fillOpacity = 128 / 255
fill.blend = "lighten"
doc.layers = { bg, mul, iso, pass, base, clip, masked, fill }
return doc
end
-- an animated sprite (tests/layered/aseprite.luau builds the same one)
local function aseDoc(): Types.Layered
local L = Types.Layered
local doc = L.new(24, 16)
local bgImg = image(24, 16, 1)
local shared = image(10, 8, 2, true)
local frames = {}
for f = 1, 3 do
local bg = L.layer("Background", bgImg)
local mul = L.layer("Mul", if f == 2 then image(10, 8, 7, true) else shared, 3 + (if f == 2 then 1 else 0), 2)
mul.blend = "multiply"
local half = L.layer("Half", image(12, 9, 3 + f, true), f * 2, 4)
half.fillOpacity = 128 / 255
local g = L.group("Group", { mul, half })
local top = L.layer("Top", image(6, 6, 9 + f, true), 16 - f, 8)
top.opacity = 200 / 255
frames[f] = { layers = { bg, g, top }, delay = 0.05 * f }
end
doc.frames = frames
doc.layers = frames[1].layers
doc.meta.tags = { { name = "all", from = 1, to = 3, direction = "pingpong", ["repeat"] = 0 } }
return doc
end
-- a Tiled map (tools/fixtures/tiled.py has Tiled read our TMX and TMJ of it)
local function tiledMap(): Types.TileMap
local m: any = Types.TileMap.new(5, 4, 16, 16)
m.nextLayerId, m.nextObjectId = 5, 4
m.properties = { name = "ours", n = 7, f = 0.5, ok = false, c = "#ff112233" }
m.propertyTypes = { c = "color" }
m.tilesets = { { firstGid = 1, name = "tiles", tileWidth = 16, tileHeight = 16, columns = 4, count = 8, spacing = 0, margin = 0, imageSource = "tiles.png", imageWidth = 64, imageHeight = 32, properties = {}, tiles = { { id = 2, class = "Wall", properties = { hard = true } }, { id = 4, properties = {}, animation = { { tileId = 4, duration = 120 }, { tileId = 5, duration = 80 } } } } } }
local data = {}
for i = 1, 20 do
data[i] = (i * 3) % 9
end
data[2] += 0x80000000
data[10] += 0x40000000
local tiles = { type = "tiles", id = 1, name = "ground", width = 5, height = 4, data = data, visible = true, opacity = 0.8, offsetX = 2, offsetY = 0, properties = { deep = 3 }, encoding = "base64", compression = "zlib" }
local objs = {
{ id = 1, name = "a", class = "Spawn", x = 4, y = 5.5, width = 8, height = 8, rotation = 30, visible = true, shape = "rectangle", properties = { team = "red" } },
{ id = 2, name = "b", class = "", x = 20, y = 10, width = 0, height = 0, rotation = 0, visible = true, shape = "polyline", points = { { 0, 0 }, { 8, 4 }, { 16, 0 } }, properties = {} },
{ id = 3, name = "c", class = "", x = 30, y = 30, width = 60, height = 14, rotation = 0, visible = false, shape = "text", text = { text = "hi there", fontFamily = "sans-serif", pixelSize = 14, wrap = true, color = "#00ff00", bold = false, italic = true, underline = false, strikeout = false, kerning = true, halign = "right", valign = "top" }, properties = {} },
}
local og = { type = "objects", id = 3, name = "things", visible = true, opacity = 1, drawOrder = "topdown", objects = objs, properties = {} }
local img = { type = "image", id = 4, name = "sky", visible = true, opacity = 1, imageSource = "sky.png", imageWidth = 40, imageHeight = 20, repeatX = true, repeatY = false, properties = {} }
local group = { type = "group", id = 2, name = "grp", visible = true, opacity = 0.5, layers = { og, img }, properties = {} }
m.layers = { tiles, group }
return m
end
local which, arg = ...
if which == "psd" then
local Psd = require("@formats/layered/psd")
local doc = psdDoc()
local data = Psd.encode(doc) :: buffer
local flat = LayerOps.flatten(doc) :: Types.Image
local layers = {}
for l, depth in LayerOps.leaves(doc.layers) do
local lay = l :: any
table.insert(layers, { name = lay.name, crc = Crc32.of(lay.image.pixels), left = lay.x, top = lay.y, width = lay.image.width, height = lay.image.height, blend = lay.blend, visible = lay.visible, clip = lay.clip == true, opacity = math.floor(lay.opacity * 255 + 0.5), depth = depth })
end
print(json({ data = hex(data), composite = Crc32.of(flat.pixels), layers = layers }))
elseif which == "aseprite" then
local Ase = require("@formats/layered/aseprite")
local doc = aseDoc()
local data = Ase.encode(doc) :: buffer
local frames = {}
for f = 1, 3 do
frames[f] = hex((LayerOps.flatten(doc, { frame = f }) :: Types.Image).pixels)
end
print(json({ data = hex(data), nframes = 3, frames = frames }))
elseif which == "tiled" then
local Tiled = require("@formats/vector/tiled")
local m = tiledMap()
local tmx = Tiled.encode(m, { format = "tmx" }) :: buffer
local tmj = Tiled.encode(m, { format = "tmj" }) :: buffer
print(json({ tmx = hex(tmx), tmj = hex(tmj) }))
elseif which == "svg" then
-- the SVG text given on the command line, decoded and written back by our encoder
local Svg = require("@formats/vector/svg")
local Bytes = require("@formats/core/Bytes")
local v = Svg.decode(Bytes.reader(buffer.fromstring(arg)))
local out = if v then Svg.encode(v) else nil
print(json({ svg = if out then buffer.tostring(out) else "" }))
end
+52
View File
@@ -0,0 +1,52 @@
-- tools/fixtures/_ply_encode.luau: run by tools/fixtures/ply.py under the luau CLI (no file I/O): encodes the scenes of
-- tests/gen/ply_scenes in the three encodings and prints "<scene>/<encoding> <hex>" lines, which the fixture step
-- hands to plyfile and assimp.
local Ply = require("@formats/model/ply")
local Types = require("@formats/Types")
local Scenes = require("@tests/gen/ply_scenes")
local function build(spec: any): Types.Scene
local scene = Types.Scene.new()
for i, m in spec.meshes do
local prims = {}
for _, p in m.prims do
local attrs = {}
for name, a in p.attrs do
attrs[name] = Types.Scene.accessor(buffer.fromstring(a[3]), a[1], a[2], p.count)
end
local prim: any = { attributes = attrs, mode = p.mode }
if p.indices then
prim.indices = Types.Scene.accessor(buffer.fromstring(p.indices), "u32", 1, #p.indices // 4)
end
if p.faces then
prim.faces = Types.Scene.accessor(buffer.fromstring(p.faces), "u32", 1, #p.faces // 4)
end
table.insert(prims, prim)
end
scene.meshes[i] = { primitives = prims }
end
for i, n in spec.nodes do
scene.nodes[i] = { mesh = n.mesh, children = n.children or {}, translation = n.translation, rotation = n.rotation, scale = n.scale, matrix = n.matrix }
end
scene.roots = spec.roots
return scene
end
local function hex(b: buffer): string
local out = table.create(buffer.len(b))
for i = 0, buffer.len(b) - 1 do
out[i + 1] = string.format("%02x", buffer.readu8(b, i))
end
return table.concat(out)
end
for _, spec in Scenes do
local scene = build(spec)
for _, e in { "ascii", "binary_little_endian", "binary_big_endian" } do
local b, err = Ply.encode(scene, { format = e })
if not b then
error(spec.name .. "/" .. e .. ": " .. tostring(err))
end
print(spec.name .. "/" .. e .. " " .. hex(b))
end
end
+307
View File
@@ -0,0 +1,307 @@
# PLY reference values (run by tools/fixtures/ply.py through ctx.python(["plyfile", "numpy"], ...), python -I).
# stdin: JSON {"dir": tmp, "make": [name], "ref": [name], "ours": [{name, file, scene}]}
# stdout: JSON {"ref": {name: {...}}, "ours": {name: [ok, detail]}}
# make: PLY files written by plyfile (every encoding, every property type, odd orders, lists, extra elements)
# ref: every file read with plyfile, mapped to the library's Scene conventions here (independently of the Luau
# code): CRC-32 of each attribute's packed little-endian bytes, the triangulated / polygon indices, face
# properties, raw elements, comments
# ours: our encoder's output read back by plyfile and compared property by property with the scene it came from
import json, os, sys, zlib
import numpy as np
from plyfile import PlyData, PlyElement
req = json.load(sys.stdin)
d = req["dir"]
out = {"ref": {}, "ours": {}}
def path(n):
return os.path.join(d, n)
def crc(a):
return zlib.crc32(np.ascontiguousarray(a).tobytes())
def le(a):
a = np.asarray(a)
return a.astype(a.dtype.newbyteorder("<"))
def sphere(rng, n):
"""a UV sphere with n x n quads (poles as triangle fans): vertices, quads and triangles"""
vs = [(0.0, 0.0, 1.0)]
for i in range(1, n):
th = np.pi * i / n
for j in range(n):
ph = 2 * np.pi * j / n
vs.append((np.sin(th) * np.cos(ph), np.sin(th) * np.sin(ph), np.cos(th)))
vs.append((0.0, 0.0, -1.0))
faces = []
for j in range(n):
faces.append([0, 1 + j, 1 + (j + 1) % n])
for i in range(n - 2):
for j in range(n):
a = 1 + i * n + j
b = 1 + i * n + (j + 1) % n
faces.append([a, a + n, b + n, b])
last = len(vs) - 1
for j in range(n):
a = 1 + (n - 2) * n
faces.append([last, a + (j + 1) % n, a + j])
return np.array(vs) * (1 + 0.05 * rng.random((len(vs), 1))), faces
def faces_el(faces, ct="u1", it="i4", name="vertex_indices", extra=()):
dt = [(name, "O")] + [(n, t) for n, t, _ in extra]
a = np.empty(len(faces), dtype=dt)
a[name] = [np.array(f, dtype=it) for f in faces]
for n, t, vals in extra:
a[n] = vals
return PlyElement.describe(a, "face", len_types={name: ct}, val_types={name: it[1:] if it[0] in "<>" else it})
def make(name):
seed = sum(map(ord, name))
rng = np.random.default_rng(seed)
comments, obj_info = [], []
if name == "cube-le.ply":
v = np.array([(x, y, z) for x in (0, 1) for y in (0, 1) for z in (0, 1)], dtype=[("x", "f4"), ("y", "f4"), ("z", "f4")])
quads = [[0, 1, 3, 2], [4, 6, 7, 5], [0, 4, 5, 1], [2, 3, 7, 6], [0, 2, 6, 4], [1, 5, 7, 3]]
tris = [t for q in quads for t in ([q[0], q[1], q[2]], [q[0], q[2], q[3]])]
els = [PlyElement.describe(v, "vertex"), faces_el(tris)]
text, byte_order = False, "<"
elif name == "colors-be.ply":
pos, faces = sphere(rng, 12)
n = len(pos)
v = np.empty(n, dtype=[("x", "f4"), ("y", "f4"), ("z", "f4"), ("nx", "f4"), ("ny", "f4"), ("nz", "f4"), ("red", "u1"),
("green", "u1"), ("blue", "u1"), ("alpha", "u1"), ("quality", "f4"), ("flags", "u2")])
v["x"], v["y"], v["z"] = pos.T
nn = pos / np.linalg.norm(pos, axis=1)[:, None]
v["nx"], v["ny"], v["nz"] = nn.T
for c in ("red", "green", "blue", "alpha"):
v[c] = rng.integers(0, 256, n)
v["quality"] = rng.random(n)
v["flags"] = rng.integers(0, 65536, n)
els = [PlyElement.describe(v, "vertex"), faces_el(faces, "u1", "u4")]
comments = ["made by plyfile", "big endian, quads and triangles"]
text, byte_order = False, ">"
elif name == "ascii-mixed.ply":
n = 40
v = np.empty(n, dtype=[("red", "u1"), ("z", "f8"), ("y", "f8"), ("x", "f8"), ("s", "f4"), ("t", "f4"), ("intensity", "i1"), ("id", "i4")])
v["red"] = rng.integers(0, 256, n)
for c in ("x", "y", "z"):
v[c] = rng.random(n) * 20 - 10
v["s"], v["t"] = rng.random(n), rng.random(n)
v["intensity"] = rng.integers(-128, 128, n)
v["id"] = rng.integers(-2 ** 31, 2 ** 31, n)
faces = [list(rng.choice(n, size=int(rng.integers(3, 7)), replace=False)) for _ in range(25)]
f = faces_el(faces, "u1", "i4", "vertex_index", extra=[("material", "u1", rng.integers(0, 4, 25)), ("weight", "f4", rng.random(25))])
e = np.empty(10, dtype=[("vertex1", "i4"), ("vertex2", "i4"), ("crease", "u1")])
e["vertex1"], e["vertex2"], e["crease"] = rng.integers(0, n, 10), rng.integers(0, n, 10), rng.integers(0, 256, 10)
m = np.empty(3, dtype=[("params", "O"), ("index", "i2")])
m["params"] = [np.array(rng.random(k), dtype="f4") for k in (2, 0, 5)]
m["index"] = [-1, 0, 7]
els = [PlyElement.describe(v, "vertex"), f, PlyElement.describe(e, "edge"),
PlyElement.describe(m, "material", len_types={"params": "u1"}, val_types={"params": "f4"})]
comments = ["ascii with odd property order", ""]
obj_info = ["num_cols 5", "num_rows 8"]
text, byte_order = True, "="
elif name == "points-le.ply":
n = 500
v = np.empty(n, dtype=[("x", "f4"), ("y", "f4"), ("z", "f4"), ("red", "u1"), ("green", "u1"), ("blue", "u1")])
for c in ("x", "y", "z"):
v[c] = rng.random(n) * 100
for c in ("red", "green", "blue"):
v[c] = rng.integers(0, 256, n)
els = [PlyElement.describe(v, "vertex")]
text, byte_order = False, "<"
elif name == "points-ascii-float.ply":
n = 60
v = np.empty(n, dtype=[("x", "f4"), ("y", "f4"), ("z", "f4"), ("red", "f4"), ("green", "f4"), ("blue", "f4"), ("u", "f4"), ("v", "f4")])
for c in v.dtype.names:
v[c] = rng.random(n)
els = [PlyElement.describe(v, "vertex")]
text, byte_order = True, "="
elif name == "types-be.ply":
n = 400
types = [("a", "i1"), ("b", "u1"), ("c", "i2"), ("d", "u2"), ("e", "i4"), ("f", "u4"), ("g", "f4"), ("h", "f8")]
v = np.empty(n, dtype=[("x", "f4"), ("y", "f4"), ("z", "f4")] + types)
v["x"], v["y"] = np.cos(np.arange(n) * 2 * np.pi / n), np.sin(np.arange(n) * 2 * np.pi / n)
v["z"] = 0
for nm, t in types:
info = np.iinfo(t) if t[0] in "iu" else None
v[nm] = rng.integers(info.min, info.max, n, endpoint=True, dtype=t) if info else rng.standard_normal(n) * 1e3
faces = [list(range(n - 1, 99, -1)), list(range(0, 100))] # a 300-gon (ushort count) and a 100-gon
els = [PlyElement.describe(v, "vertex"), faces_el(faces, "u2", "i4")]
text, byte_order = False, ">"
elif name == "big-le.ply":
pos, faces = sphere(rng, 180)
tris = [t for q in faces for t in (([q[0], q[1], q[2]], [q[0], q[2], q[3]]) if len(q) == 4 else ([q[0], q[1], q[2]],))]
v = np.empty(len(pos), dtype=[("x", "f4"), ("y", "f4"), ("z", "f4")])
v["x"], v["y"], v["z"] = pos.T
els = [PlyElement.describe(v, "vertex"), faces_el(tris, "u1", "i4")]
text, byte_order = False, "<"
elif name == "tristrips.ply":
v = np.array([(i, i % 2, 0) for i in range(8)], dtype=[("x", "f4"), ("y", "f4"), ("z", "f4")])
s = np.empty(1, dtype=[("vertex_indices", "O")])
s["vertex_indices"] = [np.array([0, 1, 2, 3, 4, -1, 4, 5, 6, 7], dtype="i4")]
els = [PlyElement.describe(v, "vertex"), PlyElement.describe(s, "tristrips", len_types={"vertex_indices": "i4"}, val_types={"vertex_indices": "i4"})]
text, byte_order = False, "<"
else:
raise ValueError(name)
PlyData(els, text=text, byte_order=byte_order, comments=comments, obj_info=obj_info).write(path(name))
for name in req["make"]:
make(name)
ACC = {"i1": "i8", "u1": "u8", "i2": "i16", "u2": "u16", "i4": "i32", "u4": "u32", "f4": "f32", "f8": "f64"}
PAIRS = [("u", "v"), ("s", "t"), ("texture_u", "texture_v"), ("texture_s", "texture_t")]
def kind(a):
return np.dtype(a.dtype).str[1:]
def index_list(f):
for n in ("vertex_indices", "vertex_index"):
if n in f.data.dtype.names and f.properties[[p.name for p in f.properties].index(n)].__class__.__name__ == "PlyListProperty":
return n
return None
def reference(name):
ply = PlyData.read(path(name))
v = ply["vertex"].data
names = v.dtype.names
taken = set()
attrs = {}
def group(attr, cols, acc_type, dt, fill=None):
arr = np.stack([v[c].astype(dt) for c in cols] + ([np.full(len(v), fill, dtype=dt)] if fill is not None else []), axis=1)
attrs[attr] = {"type": acc_type, "components": arr.shape[1], "crc": crc(le(arr))}
taken.update(cols)
if all(c in names for c in "xyz"):
group("POSITION", ["x", "y", "z"], "f32", "<f4")
if all(c in names for c in ("nx", "ny", "nz")) and all(kind(v[c])[0] == "f" for c in ("nx", "ny", "nz")):
group("NORMAL", ["nx", "ny", "nz"], "f32", "<f4")
if all(c in names for c in ("red", "green", "blue")):
cols = ["red", "green", "blue"] + (["alpha"] if "alpha" in names else [])
ks = {"f" if kind(v[c])[0] == "f" else kind(v[c]) for c in cols}
if ks == {"u1"}:
group("COLOR_0", cols, "unorm8", "u1", None if "alpha" in names else 255)
elif ks == {"u2"}:
group("COLOR_0", cols, "unorm16", "<u2", None if "alpha" in names else 65535)
elif ks == {"f"}:
group("COLOR_0", cols, "f32", "<f4", None if "alpha" in names else 1.0)
for a, b in PAIRS:
if a in names and b in names and kind(v[a])[0] == "f" and kind(v[b])[0] == "f":
group("TEXCOORD_0", [a, b], "f32", "<f4")
break
for c in names:
if c not in taken:
attrs["_" + c] = {"type": ACC[kind(v[c])], "components": 1, "crc": crc(le(v[c]))}
encoding = "ascii" if ply.text else ("binary_big_endian" if ply.byte_order == ">" else "binary_little_endian")
res = {"vertices": len(v), "attrs": attrs, "encoding": encoding,
"comments": list(ply.comments), "objInfo": list(ply.obj_info), "order": [e.name for e in ply.elements]}
face = None
if "face" in ply:
f = ply["face"]
il = index_list(f)
if il:
face = f
if face is not None and len(face.data):
lists = [np.asarray(x, dtype=np.int64) for x in face.data[il]]
sizes = [len(x) for x in lists]
corners = np.concatenate(lists) if lists else np.zeros(0, dtype=np.int64)
res["faces"] = len(lists)
res["corners_crc"] = crc(corners.astype("<u4"))
res["sizes_crc"] = crc(np.array(sizes, dtype="<u4"))
tris, fot = [], []
for i, x in enumerate(lists):
for k in range(1, len(x) - 1):
tris += [x[0], x[k], x[k + 1]]
fot.append(i)
res["tri_crc"] = crc(np.array(tris, dtype="<u4"))
res["tris"] = len(tris) // 3
res["fot_crc"] = crc(np.array(fot, dtype="<u4"))
res["allTri"] = all(s == 3 for s in sizes)
fa = {}
for p in face.properties:
if p.name == il:
continue
col = face.data[p.name]
if p.__class__.__name__ == "PlyListProperty":
items = np.concatenate([np.asarray(x) for x in col]) if len(col) else np.zeros(0)
fa[p.name] = {"list": True, "sizes_crc": crc(np.array([len(x) for x in col], dtype="<u4")),
"items_crc": crc(le(np.asarray(items, dtype=np.dtype(p.val_dtype))))}
else:
fa[p.name] = {"type": ACC[kind(col)], "crc": crc(le(col))}
res["faceAttributes"] = fa
else:
res["faces"] = 0
els = []
for e in ply.elements:
if e.name == "vertex" or (face is not None and e is face):
continue
props = []
for p in e.properties:
col = e.data[p.name]
if p.__class__.__name__ == "PlyListProperty":
vd = np.dtype(p.val_dtype)
items = np.concatenate([np.asarray(x, dtype=vd) for x in col]) if len(col) else np.zeros(0, dtype=vd)
props.append({"name": p.name, "list": True, "sizes_crc": crc(np.array([len(x) for x in col], dtype="<u4")),
"values_crc": crc(le(items))})
else:
props.append({"name": p.name, "crc": crc(le(col))})
els.append({"name": e.name, "count": len(e.data), "props": props})
res["elements"] = els
return res
for name in req["ref"]:
out["ref"][name] = reference(name)
# our encoder's output: every expected vertex property (name, kind, values) and the faces
for o in req["ours"]:
name = o["name"]
try:
ply = PlyData.read(path(o["file"]))
v = ply["vertex"].data
ok, detail = True, "%d vertices" % len(v)
want_names = [p["name"] for p in o["props"]]
if list(v.dtype.names) != want_names:
ok, detail = False, "vertex properties %s, want %s" % (list(v.dtype.names), want_names)
else:
for p in o["props"]:
got = np.asarray(v[p["name"]])
want = np.frombuffer(bytes.fromhex(p["values"]), dtype=p["dtype"])
if kind(got) != np.dtype(p["dtype"]).str[1:]:
ok, detail = False, "%s: type %s, want %s" % (p["name"], kind(got), p["dtype"])
break
if p.get("tol"):
if got.shape != want.shape or float(np.abs(got.astype(np.float64) - want).max(initial=0)) > p["tol"]:
ok, detail = False, "%s: values differ" % p["name"]
break
elif not np.array_equal(got, want):
ok, detail = False, "%s: values differ" % p["name"]
break
if ok:
if o.get("faces") is None:
if "face" in ply:
ok, detail = False, "a point cloud with a face element"
else:
f = ply["face"].data
il = "vertex_indices" if "vertex_indices" in f.dtype.names else "vertex_index"
got = [list(map(int, x)) for x in f[il]]
if got != o["faces"]:
ok, detail = False, "faces differ"
else:
detail += ", %d faces" % len(got)
out["ours"][name] = [ok, detail]
except Exception as e: # noqa: BLE001 - a reference failure is a verdict
out["ours"][name] = [False, "plyfile: %s" % e]
json.dump(out, sys.stdout)
+56
View File
@@ -0,0 +1,56 @@
-- tools/fixtures/_stl_encode.luau: run by tools/fixtures/stl.py under the luau CLI (no file I/O): encodes the scenes of
-- tests/gen/stl_scenes with every encoding they list and prints "<scene>/<encoding> <hex>" lines, which the fixture
-- step hands to trimesh and assimp.
local Stl = require("@formats/model/stl")
local Types = require("@formats/Types")
local Scenes = require("@tests/gen/stl_scenes")
local function acc(s: string, t: string, comps: number, count: number): Types.Accessor
return Types.Scene.accessor(buffer.fromstring(s), t, comps, count)
end
local function build(spec: any): Types.Scene
local scene = Types.Scene.new()
for i, m in spec.meshes do
local prims = {}
for _, p in m.prims do
local prim: any = { attributes = { POSITION = acc(p.pos, p.posType or "f32", 3, p.count) }, mode = p.mode }
if p.indices then
prim.indices = acc(p.indices, "u32", 1, #p.indices // 4)
end
if p.faces then
prim.faces = acc(p.faces, "u32", 1, #p.faces // 4)
end
if p.color then
prim.attributes.COLOR_0 = acc(p.color, "unorm8", 4, p.count)
end
table.insert(prims, prim)
end
scene.meshes[i] = { name = m.name, primitives = prims }
end
for i, n in spec.nodes do
scene.nodes[i] = { name = n.name, mesh = n.mesh, children = n.children or {}, translation = n.translation, rotation = n.rotation, scale = n.scale, matrix = n.matrix }
end
scene.roots = spec.roots
return scene
end
local function hex(b: buffer): string
local out = table.create(buffer.len(b))
for i = 0, buffer.len(b) - 1 do
out[i + 1] = string.format("%02x", buffer.readu8(b, i))
end
return table.concat(out)
end
local OPTS: { [string]: any } = { binary = {}, ascii = { ascii = true }, viscam = { colors = "viscam" }, magics = { colors = "magics" } }
for _, spec in Scenes do
local scene = build(spec)
for _, e in spec.encodings do
local b, err = Stl.encode(scene, OPTS[e])
if not b then
error(spec.name .. "/" .. e .. ": " .. tostring(err))
end
print(spec.name .. "/" .. e .. " " .. hex(b))
end
end
+112
View File
@@ -0,0 +1,112 @@
# STL reference values (run by tools/fixtures/stl.py through ctx.python(["trimesh", "numpy"], ...), python -I).
# stdin: JSON {"dir": tmp, "make": [[name, kind, file_type, seed]], "ref": [name], "ours": [{name, file, ...}]}
# stdout: JSON {"ref": {name: {...}}, "ours": {name: [ok, detail]}}
# make: meshes made and exported by trimesh itself (binary / ascii STL)
# ref: every file read with trimesh.exchange.stl.load_stl (the raw arrays, no processing): facet count, CRC-32 of
# the f32 triangle vertices / facet normals (as the file has them), area, bounds, the raw attribute words
# ours: our encoder's output read back by trimesh and compared with the expected world-space triangles
import json, os, sys, zlib
import numpy as np
import trimesh
from trimesh.exchange import stl as tstl
req = json.load(sys.stdin)
d = req["dir"]
out = {"ref": {}, "ours": {}}
def path(n):
return os.path.join(d, n)
for name, kind, ftype, seed in req["make"]:
rng = np.random.default_rng(seed)
if kind == "icosphere":
m = trimesh.creation.icosphere(subdivisions=3, radius=2.5)
elif kind == "box":
m = trimesh.creation.box(extents=(1.5, 2.0, 0.25))
elif kind == "capsule":
m = trimesh.creation.capsule(height=3.0, radius=0.7)
else:
tri = (rng.random((1500, 3, 3)) * 200 - 100).astype(np.float32)
m = trimesh.Trimesh(vertices=tri.reshape(-1, 3), faces=np.arange(4500).reshape(-1, 3), process=False)
data = m.export(file_type=ftype)
with open(path(name), "wb") as f:
f.write(data.encode() if isinstance(data, str) else data)
def load(name):
with open(path(name), "rb") as f:
r = tstl.load_stl(f)
if "geometry" in r: # several solids
parts = list(r["geometry"].values())
if not parts:
return np.zeros((0, 3)), np.zeros((0, 3), dtype=np.int64), np.zeros((0, 3)), None
vs, fs, ns, off = [], [], [], 0
for g in parts:
vs.append(g["vertices"])
fs.append(np.asarray(g["faces"]) + off)
ns.append(g["face_normals"])
off += len(g["vertices"])
# trimesh does not read normals written on the "outer loop" line: no normals then
nrm = None if any(x is None for x in ns) else np.concatenate(ns)
return np.concatenate(vs), np.concatenate(fs), nrm, None
attr = r.get("face_attributes", {}).get("stl")
return np.asarray(r["vertices"]), np.asarray(r["faces"]), np.asarray(r["face_normals"]), attr
def crc(a, dt):
return zlib.crc32(np.ascontiguousarray(np.asarray(a).astype(dt)).tobytes())
for name in req["ref"]:
v, f, n, attr = load(name)
tri = v[f].astype(np.float32) # (n, 3, 3)
m = trimesh.Trimesh(vertices=v, faces=f, process=False)
res = {
"facets": int(len(f)),
"pos_crc": crc(tri, "<f4"),
"area": float(m.area) if len(f) else 0.0,
"bounds": [float(x) for x in (m.bounds.reshape(-1) if len(f) else np.zeros(6))],
}
if n is not None:
res["nrm_crc"] = crc(np.repeat(np.asarray(n, dtype=np.float32), 3, axis=0), "<f4")
if attr is not None:
res["attr"] = [int(x) for x in attr]
out["ref"][name] = res
# our encoder's files
for o in req["ours"]:
name = o["name"]
try:
v, f, n, attr = load(o["file"])
tri = v[f].astype(np.float32).reshape(-1, 9)
want = np.frombuffer(bytes.fromhex(o["expect"]), dtype="<f4").reshape(-1, 9)
if tri.shape != want.shape:
out["ours"][name] = [False, "facet count %s, want %s" % (tri.shape, want.shape)]
continue
tol = 0 if o["exact"] else 1e-5 * max(1.0, float(np.abs(want).max()))
err = float(np.abs(tri.astype(np.float64) - want.astype(np.float64)).max()) if len(want) else 0.0
if err > tol:
out["ours"][name] = [False, "positions differ by %g" % err]
continue
# the stored facet normals: the right-hand rule normal of each triangle
t = want.astype(np.float64).reshape(-1, 3, 3)
cn = np.cross(t[:, 1] - t[:, 0], t[:, 2] - t[:, 0])
ln = np.linalg.norm(cn, axis=1)
cn[ln > 0] /= ln[ln > 0, None]
nerr = float(np.abs(np.asarray(n, dtype=np.float64) - cn).max()) if len(want) else 0.0
if nerr > 1e-4:
out["ours"][name] = [False, "facet normals differ by %g" % nerr]
continue
if "colors" in o:
want_words = o["colors"]
got = [int(x) for x in attr] if attr is not None else []
if got != want_words:
out["ours"][name] = [False, "attribute words differ"]
continue
out["ours"][name] = [True, "%d facets, max error %g" % (len(want), err)]
except Exception as e: # noqa: BLE001 - a reference failure is a verdict
out["ours"][name] = [False, "trimesh: %s" % e]
json.dump(out, sys.stdout)
+95
View File
@@ -0,0 +1,95 @@
-- tools/fixtures/_webp_encode: run by tools/fixtures/webp.py (luau CLI, repo root). Encodes the WebP fixture sources
-- (tests/gen/webp_src) with image/webp at several efforts and two animations, and prints one line per file:
-- "<name> <hex>" (stills: <source>_e<effort>_<exact|loose>) or "anim<k>:<crc>,<crc>,... <hex>" with the CRC-32 of each
-- canvas the input frames composite to (image/webp/Anim.composite), for dwebp / Pillow to check.
local Webp = require("@formats/image/webp")
local Anim = require("@formats/image/webp/Anim")
local Types = require("@formats/Types")
local Crc32 = require("@formats/core/Crc32")
local Src = require("@tests/gen/webp_src")
local HEX = {}
for i = 0, 255 do
HEX[i] = string.format("%02x", i)
end
local function hex(b: buffer): string
local t = table.create(buffer.len(b))
for i = 0, buffer.len(b) - 1 do
t[i + 1] = HEX[buffer.readu8(b, i)]
end
return table.concat(t)
end
local function image(s: any): Types.Image
local img = Types.Image.new(s.width, s.height)
img.pixels = buffer.fromstring(s.rgba)
return img
end
local bySrc = {}
for _, s in Src do
bySrc[s.name] = s
for _, effort in { 0, 3, 5, 9 } do
local out = assert(Webp.encode(image(s), { effort = effort, exact = true }))
print(string.format("%s_e%d_exact %s", s.name, effort, hex(out)))
end
local out = assert(Webp.encode(image(s), { effort = 5 }))
print(string.format("%s_e5_loose %s", s.name, hex(out)))
end
-- crop(src, x, y, w, h) -> an rgba8 Image
local function crop(s: any, x: number, y: number, w: number, h: number): Types.Image
local img = Types.Image.new(w, h)
local px = buffer.fromstring(s.rgba)
for j = 0, h - 1 do
buffer.copy(img.pixels, j * w * 4, px, ((y + j) * s.width + x) * 4, w * 4)
end
return img
end
local function animation(cw: number, ch: number, frames: { Types.Frame }): Types.Image
local img = Types.Image.new(cw, ch)
img.frames = frames
img.loops = 2
return img
end
local rose, rosea, grad = bySrc.rose, bySrc.rose_a, bySrc.grad
local anims = {
-- stored as they are: even offsets, blending, dispose to background
animation(70, 46, {
{ image = crop(rose, 0, 0, 70, 46), delay = 0.1, x = 0, y = 0, dispose = "none", blend = "source" },
{ image = crop(rosea, 10, 4, 30, 20), delay = 0.05, x = 10, y = 4, dispose = "background", blend = "over" },
{ image = crop(rosea, 20, 10, 40, 30), delay = 0.2, x = 20, y = 10, dispose = "none", blend = "over" },
{ image = crop(grad, 0, 0, 24, 16), delay = 0.033, x = 46, y = 30, dispose = "none", blend = "source" },
}),
-- flattened: odd offsets and dispose "previous"
animation(70, 46, {
{ image = crop(rosea, 0, 0, 70, 46), delay = 0.1, x = 0, y = 0, dispose = "none", blend = "source" },
{ image = crop(grad, 3, 3, 21, 13), delay = 0.1, x = 5, y = 7, dispose = "previous", blend = "over" },
{ image = crop(rose, 1, 1, 9, 9), delay = 0.1, x = 33, y = 21, dispose = "background", blend = "over" },
{ image = crop(grad, 0, 0, 10, 10), delay = 0.1, x = 60, y = 36, dispose = "none", blend = "over" },
}),
}
for k, img in anims do
local list = {}
for _, f in img.frames :: { Types.Frame } do
table.insert(list, {
rgba = f.image.pixels,
x = f.x,
y = f.y,
w = f.image.width,
h = f.image.height,
blend = f.blend == "over",
disposeBg = f.dispose == "background",
disposePrev = f.dispose == "previous",
hasAlpha = true,
})
end
local crcs = {}
for _, c in Anim.composite(img.width, img.height, list) do
table.insert(crcs, tostring(Crc32.of(c)))
end
local out = assert(Webp.encode(img, { effort = 5, exact = true }))
print(string.format("anim%d:%s %s", k, table.concat(crcs, ","), hex(out)))
end
+213
View File
@@ -0,0 +1,213 @@
# Aseprite fixtures (tools/fixtures.py). Sprites written here by a small writer following docs/ase-file-specs.md
# (RGBA / grayscale / indexed, raw / zlib / linked cels, groups, hidden layers, blend modes, layer and cel opacity,
# old and new palette chunks, tags, user data), sprites written by LibreSprite (the reference: an Aseprite 1.1 fork,
# in nixpkgs) and LibreSprite's flattened rendering of every frame:
# tests/gen/aseprite.luau { cases = { { name, data, width, height, nframes, cels = { { frame, layer, x, y, w, h,
# crc } }, frames = { RGBA of LibreSprite's frame i } } } }
# tests/gen/aseprite_ours.luau { frames = { ... }, ours = { ... } }: our encoder's sprite (tools/fixtures/_ours.luau)
# rendered by LibreSprite, with our flatten of the same frames
import json, os, shutil, struct, subprocess, tempfile, zlib
INPUTS = ["src/Formats/layered/aseprite", "src/Formats/codecs/Blend.luau", "tools/fixtures/_ours.luau"]
def s(text):
b = text.encode()
return struct.pack("<H", len(b)) + b
def chunk(ctype, body):
return struct.pack("<IH", len(body) + 6, ctype) + body
def layer_chunk(name, flags=3, ltype=0, level=0, blend=0, opacity=255):
return chunk(0x2004, struct.pack("<HHHHHHB3x", flags, ltype, level, 0, 0, blend, opacity) + s(name))
def cel_chunk(layer, x, y, w, h, pixels, opacity=255, kind=2, link=None, z=0):
head = struct.pack("<HhhBHh5x", layer, x, y, opacity, 1 if link is not None else kind, z)
if link is not None:
return chunk(0x2005, head + struct.pack("<H", link))
if kind == 0:
return chunk(0x2005, head + struct.pack("<HH", w, h) + pixels)
return chunk(0x2005, head + struct.pack("<HH", w, h) + zlib.compress(pixels))
def palette_chunk(colors, names=None):
body = struct.pack("<III8x", len(colors), 0, len(colors) - 1)
for i, c in enumerate(colors):
n = (names or {}).get(i)
body += struct.pack("<H4B", 1 if n else 0, *c) + (s(n) if n else b"")
return chunk(0x2019, body)
def old_palette_chunk(colors):
body = struct.pack("<HBB", 1, 0, len(colors) & 255) + b"".join(bytes(c[:3]) for c in colors)
return chunk(0x0004, body)
def tags_chunk(tags):
body = struct.pack("<H8x", len(tags))
for name, a, b, d, rep in tags:
body += struct.pack("<HHBH6x3Bx", a, b, d, rep, 255, 0, 0) + s(name)
return chunk(0x2018, body)
def user_chunk(text=None, color=None):
f = (1 if text is not None else 0) | (2 if color else 0)
return chunk(0x2020, struct.pack("<I", f) + (s(text) if text is not None else b"") + (bytes(color) if color else b""))
def sprite(w, h, depth, frames, transparent=0, flags=3, ncolors=0):
"""frames: [(duration_ms, [chunk bytes])]"""
body = b""
for dur, chunks in frames:
data = b"".join(chunks)
body += struct.pack("<IHHHxxI", len(data) + 16, 0xF1FA, min(len(chunks), 0xFFFF), dur, len(chunks)) + data
head = struct.pack("<IHHHHHIH II B3x H BB hhHH", 128 + len(body), 0xA5E0, len(frames), w, h, depth, flags, 100, 0, 0, transparent, ncolors, 1, 1, 0, 0, 16, 16)
head += b"\0" * (128 - len(head))
return head + body
def rgba(w, h, seed, alpha=True):
out = bytearray()
for y in range(h):
for x in range(w):
a = 255 if not alpha or (x + y) % 4 else (x * 50 + seed * 30) % 256
out += bytes(((x * (seed + 2) * 9 + y * 3) % 256, (y * (seed + 1) * 11 + x) % 256, ((x + seed) * (y + 2) * 5) % 256, a))
return bytes(out)
def case_rgba():
W, H = 32, 24
cels = []
def cel(frame, layer, x, y, w, h, px, **kw):
cels.append({"frame": frame, "layer": layer, "x": x, "y": y, "w": w, "h": h, "crc": zlib.crc32(px)})
return cel_chunk(layer - 1, x, y, w, h, px, **kw)
bg = rgba(W, H, 1, alpha=False)
pal = [(i, 255 - i, (i * 7) % 256, 255) for i in range(0, 256, 16)]
f1 = [
palette_chunk(pal, {0: "first", 3: "fourth"}),
layer_chunk("Background", flags=1 | 2 | 8),
layer_chunk("Group", ltype=1, flags=3),
layer_chunk("Mul", level=1, blend=1, opacity=200),
user_chunk("mul layer", (1, 2, 3, 4)),
layer_chunk("Half", level=1),
layer_chunk("Hidden", flags=2),
layer_chunk("Top"),
tags_chunk([("walk", 0, 1, 0, 0), ("back", 1, 2, 2, 3)]),
user_chunk("walk tag"),
user_chunk(None),
cel(1, 1, 0, 0, W, H, bg, kind=0),
cel(1, 3, 4, 3, 16, 12, rgba(16, 12, 2)),
user_chunk("a cel"),
cel(1, 4, 10, 8, 14, 10, rgba(14, 10, 3), opacity=128),
cel(1, 5, 0, 0, 8, 8, rgba(8, 8, 4)),
cel(1, 6, 20, 2, 10, 20, rgba(10, 20, 5)),
]
f2 = [
cel_chunk(0, 0, 0, W, H, bg, link=0),
cel(2, 3, 6, 5, 16, 12, rgba(16, 12, 6)),
cel(2, 6, -4, 10, 12, 8, rgba(12, 8, 7), kind=0),
]
f3 = [
cel_chunk(0, 0, 0, W, H, bg, link=0),
cel_chunk(2, 4, 3, 16, 12, b"", link=0),
cel(3, 4, 1, 1, 30, 20, rgba(30, 20, 8), opacity=64),
]
# linked cels repeat their target
cels.append({"frame": 2, "layer": 1, "x": 0, "y": 0, "w": W, "h": H, "crc": zlib.crc32(bg)})
cels.append({"frame": 3, "layer": 1, "x": 0, "y": 0, "w": W, "h": H, "crc": zlib.crc32(bg)})
cels.append({"frame": 3, "layer": 3, "x": 4, "y": 3, "w": 16, "h": 12, "crc": zlib.crc32(rgba(16, 12, 2))})
return sprite(W, H, 32, [(100, f1), (150, f2), (200, f3)], ncolors=len(pal)), cels
def case_gray():
cels = []
px = bytes(v for x in range(10 * 6) for v in ((x * 4) % 256, 255 if x % 3 else 128))
exp = b"".join(bytes((px[i * 2],) * 3 + (px[i * 2 + 1],)) for i in range(60))
cels.append({"frame": 1, "layer": 1, "x": 1, "y": 1, "w": 10, "h": 6, "crc": zlib.crc32(exp)})
cels.append({"frame": 2, "layer": 1, "x": 3, "y": 2, "w": 10, "h": 6, "crc": zlib.crc32(exp)})
f1 = [layer_chunk("G"), cel_chunk(0, 1, 1, 10, 6, px)]
f2 = [cel_chunk(0, 3, 2, 10, 6, px, kind=0)]
return sprite(14, 9, 16, [(80, f1), (80, f2)]), cels
def case_indexed():
# the background cel covers the sprite (as Aseprite writes it): its transparent index stays opaque
pal = [(0, 0, 0, 255), (255, 0, 0, 255), (0, 255, 0, 255), (0, 0, 255, 255), (255, 255, 0, 255)]
idx = bytes((x + y) % 5 for y in range(7) for x in range(9))
bgi = bytes((x * y) % 5 for y in range(9) for x in range(12))
exp = b"".join(bytes(pal[i][:3]) + bytes((0 if i == 0 else 255,)) for i in idx)
exp_bg = b"".join(bytes(pal[i]) for i in bgi)
cels = [{"frame": 1, "layer": 1, "x": 0, "y": 0, "w": 12, "h": 9, "crc": zlib.crc32(exp_bg)},
{"frame": 1, "layer": 2, "x": 2, "y": 1, "w": 9, "h": 7, "crc": zlib.crc32(exp)}]
f1 = [old_palette_chunk(pal), layer_chunk("Back", flags=1 | 2 | 8), layer_chunk("Sprite"), cel_chunk(0, 0, 0, 12, 9, bgi), cel_chunk(1, 2, 1, 9, 7, idx)]
return sprite(12, 9, 8, [(100, f1)], transparent=0, ncolors=5), cels
def libresprite(ctx, argv, cwd):
if shutil.which("libresprite"):
subprocess.run(["libresprite"] + argv, check=True, capture_output=True, cwd=cwd)
else:
subprocess.run(["nix", "shell", "nixpkgs#libresprite", "-c", "libresprite"] + argv, check=True, capture_output=True, cwd=cwd)
def rgba_of(ctx, png):
argv = ["magick", png, "-depth", "8", "rgba:-"]
try:
return subprocess.run(argv, check=True, capture_output=True).stdout
except (OSError, subprocess.CalledProcessError):
return ctx.nix("imagemagick", argv)
def render(ctx, data, nframes):
"""LibreSprite's flattened frames of an .ase (RGBA bytes each)"""
with tempfile.TemporaryDirectory() as d:
open(os.path.join(d, "in.aseprite"), "wb").write(data)
libresprite(ctx, ["-b", "in.aseprite", "--save-as", "f.png"], d)
if nframes == 1:
return [rgba_of(ctx, os.path.join(d, "f.png"))]
return [rgba_of(ctx, os.path.join(d, "f%d.png" % i)) for i in range(1, nframes + 1)]
def resave(ctx, data, ext_in="aseprite"):
with tempfile.TemporaryDirectory() as d:
open(os.path.join(d, "in." + ext_in), "wb").write(data)
libresprite(ctx, ["-b", "in." + ext_in, "--save-as", "out.aseprite"], d)
return open(os.path.join(d, "out.aseprite"), "rb").read()
def run_ours(ctx, fmt):
script = os.path.join(ctx.root, "tools", "fixtures", "_ours.luau")
luau = shutil.which("luau")
argv = [luau, script, "-a", fmt] if luau else ["nix", "shell", "nixpkgs#luau", "-c", "luau", script, "-a", fmt]
return json.loads(subprocess.run(argv, check=True, capture_output=True, cwd=ctx.root).stdout)
def gif(ctx):
with tempfile.TemporaryDirectory() as d:
a, b, g = os.path.join(d, "a.png"), os.path.join(d, "b.png"), os.path.join(d, "anim.gif")
for argv in (["magick", "-size", "12x8", "gradient:red-blue", a], ["magick", "-size", "12x8", "xc:green", b], ["magick", "-delay", "20", a, b, "-loop", "0", g]):
try:
subprocess.run(argv, check=True, capture_output=True)
except (OSError, subprocess.CalledProcessError):
ctx.nix("imagemagick", argv)
return open(g, "rb").read()
def generate(ctx):
cases = []
for name, (data, cels) in (("rgba", case_rgba()), ("gray", case_gray()), ("indexed", case_indexed())):
n = struct.unpack_from("<H", data, 6)[0]
w, h = struct.unpack_from("<HH", data, 8)
cases.append({"name": name, "data": data, "width": w, "height": h, "nframes": n, "cels": cels, "frames": render(ctx, data, n)})
# sprites LibreSprite writes: our rgba case re-saved, and a GIF converted
re = resave(ctx, cases[0]["data"])
cases.append({"name": "libresprite-resave", "data": re, "width": 32, "height": 24, "nframes": 3, "cels": [], "frames": render(ctx, re, 3)})
g = resave(ctx, gif(ctx), "gif")
cases.append({"name": "libresprite-gif", "data": g, "width": 12, "height": 8, "nframes": 2, "cels": [], "frames": render(ctx, g, 2)})
ctx.emit("aseprite", {"cases": cases})
o = run_ours(ctx, "aseprite")
data = bytes.fromhex(o["data"])
ctx.emit("aseprite_ours", {"nframes": o["nframes"], "frames": render(ctx, data, o["nframes"]), "ours": [bytes.fromhex(f) for f in o["frames"]]})
+13
View File
@@ -0,0 +1,13 @@
# Base64 fixtures (tools/fixtures.py): random byte strings of every length 0..70 plus a few large ones, with Python's
# base64 (standard, URL-safe, unpadded) as the reference.
# tests/gen/base64_cases.luau { data, std, url, nopad }
import base64
def generate(ctx):
rng = ctx.rng(3)
cases = []
for n in list(range(71)) + [1000, 4097, 65536]:
d = bytes(rng.randrange(256) for _ in range(n))
cases.append({"data": d, "std": base64.b64encode(d), "url": base64.urlsafe_b64encode(d), "nopad": base64.b64encode(d).rstrip(b"=")})
ctx.emit("base64_cases", cases)
+105
View File
@@ -0,0 +1,105 @@
# BMFont fixtures (tools/fixtures.py): a bitmap font rendered from Karla-Regular (imgui-luau fonts, or DejaVu Sans
# from nixpkgs when missing) with FreeType + Pillow, written by an independent Python writer of the three AngelCode
# encodings (text, XML, binary v3) from the BMFont documentation, plus its page PNG.
# tests/gen/bmfont.luau { text, xml, binary, page (png bytes), desc = { info, common, pages, chars, kernings },
# crops = { { id, crc } } (CRC-32 of each glyph's alpha crop) }
import base64, json, os, subprocess
FONT = os.path.join(os.environ.get("IMGUI_FONTS", os.path.expanduser("~/dev/luau/imgui/imgui-luau/fonts")), "Karla-Regular.ttf")
CODE = r'''
import base64, io, json, struct, sys, zlib
import freetype
from PIL import Image
data = base64.b64decode(sys.stdin.read())
face = freetype.Face(io.BytesIO(data))
face.set_pixel_sizes(0, 24)
chars = [c for c in range(32, 127)] + [0xE9, 0x2014]
page = Image.new("RGBA", (256, 256), (255, 255, 255, 0))
x, y, rowh = 1, 1, 0
out = []
crops = []
for cp in chars:
face.load_char(chr(cp), freetype.FT_LOAD_RENDER | freetype.FT_LOAD_NO_HINTING)
g = face.glyph
bm = g.bitmap
w, h = bm.width, bm.rows
if x + w + 1 > 256:
x, y, rowh = 1, y + rowh + 1, 0
alpha = bytes(bm.buffer[r * bm.pitch + c] for r in range(h) for c in range(w))
for r in range(h):
for c in range(w):
page.putpixel((x + c, y + r), (255, 255, 255, alpha[r * w + c]))
out.append({"id": cp, "x": x, "y": y, "width": w, "height": h, "xoffset": g.bitmap_left,
"yoffset": 19 - g.bitmap_top, "xadvance": g.advance.x // 64, "page": 0, "chnl": 15})
crops.append({"id": cp, "crc": zlib.crc32(alpha)})
x += w + 1
rowh = max(rowh, h)
kern = []
for a in "AVTWYLo":
for b in "AVTWYoe.":
k = face.get_kerning(a, b).x // 64
kern.append([ord(a), ord(b), -((ord(a) * 7 + ord(b)) % 5) - 1])
info = {"face": "Karla \"Test\" & Co", "size": 24, "bold": 0, "italic": 1, "charset": "", "unicode": 1, "stretchH": 100,
"smooth": 1, "aa": 1, "padding": [1, 2, 3, 4], "spacing": [1, 1], "outline": 0}
common = {"lineHeight": 28, "base": 19, "scaleW": 256, "scaleH": 256, "pages": 1, "packed": 0, "alphaChnl": 0,
"redChnl": 4, "greenChnl": 4, "blueChnl": 4}
pages = ["karla_0.png"]
CHAR_KEYS = ["id", "x", "y", "width", "height", "xoffset", "yoffset", "xadvance", "page", "chnl"]
def tq(s): return '"' + s.replace('"', "") + '"'
lines = ["info face=%s size=24 bold=0 italic=1 charset=\"\" unicode=1 stretchH=100 smooth=1 aa=1 padding=1,2,3,4 spacing=1,1 outline=0" % tq(info["face"]),
"common lineHeight=28 base=19 scaleW=256 scaleH=256 pages=1 packed=0 alphaChnl=0 redChnl=4 greenChnl=4 blueChnl=4",
'page id=0 file="karla_0.png"', "chars count=%d" % len(out)]
for c in out:
lines.append("char " + " ".join("%s=%d" % (k, c[k]) for k in CHAR_KEYS))
lines.append("kernings count=%d" % len(kern))
for k in kern:
lines.append("kerning first=%d second=%d amount=%d" % tuple(k))
text = "\r\n".join(lines) + "\r\n"
def xe(s): return s.replace("&", "&amp;").replace("<", "&lt;").replace('"', "&quot;")
xl = ['<?xml version="1.0"?>', "<font>",
' <info face="%s" size="24" bold="0" italic="1" charset="" unicode="1" stretchH="100" smooth="1" aa="1" padding="1,2,3,4" spacing="1,1" outline="0"/>' % xe(info["face"]),
' <common lineHeight="28" base="19" scaleW="256" scaleH="256" pages="1" packed="0" alphaChnl="0" redChnl="4" greenChnl="4" blueChnl="4"/>',
" <pages>", ' <page id="0" file="karla_0.png" />', " </pages>", ' <chars count="%d">' % len(out)]
for c in out:
xl.append(" <char " + " ".join('%s="%d"' % (k, c[k]) for k in CHAR_KEYS) + " />")
xl.append(" </chars>")
xl.append(' <kernings count="%d">' % len(kern))
for k in kern:
xl.append(' <kerning first="%d" second="%d" amount="%d" />' % tuple(k))
xl += [" </kernings>", "</font>"]
xml = "\n".join(xl) + "\n"
face_name = info["face"].encode()
b = bytearray(b"BMF\x03")
blk = struct.pack("<hBBHBBBBBBBB", 24, 0x80 | 0x40 | 0x20, 0, 100, 1, 1, 2, 3, 4, 1, 1, 0) + face_name + b"\0"
b += struct.pack("<BI", 1, len(blk)) + blk
blk = struct.pack("<HHHHHBBBBB", 28, 19, 256, 256, 1, 0, 0, 4, 4, 4)
b += struct.pack("<BI", 2, len(blk)) + blk
blk = b"karla_0.png\0"
b += struct.pack("<BI", 3, len(blk)) + blk
blk = b"".join(struct.pack("<IHHHHhhhBB", *[c[k] for k in CHAR_KEYS]) for c in out)
b += struct.pack("<BI", 4, len(blk)) + blk
blk = b"".join(struct.pack("<IIh", *k) for k in kern)
b += struct.pack("<BI", 5, len(blk)) + blk
png = io.BytesIO()
page.save(png, "PNG")
json.dump({"text": base64.b64encode(text.encode()).decode(), "xml": base64.b64encode(xml.encode()).decode(),
"binary": base64.b64encode(bytes(b)).decode(), "page": base64.b64encode(png.getvalue()).decode(),
"desc": {"info": info, "common": common, "pages": pages, "chars": out, "kernings": kern}, "crops": crops},
sys.stdout)
'''
def generate(ctx):
path = FONT
if not os.path.exists(path):
out = subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#dejavu_fonts"], capture_output=True,
check=True, text=True).stdout.strip().split("\n")[-1]
path = os.path.join(out, "share", "fonts", "truetype", "DejaVuSans.ttf")
raw = ctx.python(["freetype-py", "pillow"], CODE, input=base64.b64encode(open(path, "rb").read()))
res = json.loads(raw)
d = base64.b64decode
for k in ("text", "xml", "binary", "page"):
res[k] = d(res[k])
res["ttf"] = open(path, "rb").read()
ctx.emit("bmfont", res)
+101
View File
@@ -0,0 +1,101 @@
# Brotli fixtures (tools/fixtures.py): deterministic corpora compressed by the reference encoder (python brotli
# through nix, and the brotli CLI for the large-window extension): every quality 0..11, windows 10..24, the text /
# font / generic modes, empty input, dictionary-heavy English, and a few-MB bench corpus.
# tests/gen/brotli.luau { corpora = { [name] = bytes }, cases = { { name, corpus, data } } }
# tests/gen/brotli_bench.luau { size, crc, data }
import os, pickle, random, zlib
ENCODE = r'''
import brotli, pickle, sys
jobs = pickle.load(sys.stdin.buffer)
out = []
for data, q, w, mode in jobs:
m = {"generic": brotli.MODE_GENERIC, "text": brotli.MODE_TEXT, "font": brotli.MODE_FONT}[mode]
out.append(brotli.compress(data, mode=m, quality=q, lgwin=w))
sys.stdout.buffer.write(pickle.dumps(out))
'''
WORDS = ("the of and to in is that for it as was with be by on not he this are or his from at which but have an they "
"you were her she there one all we their been has who more will would if so can its what when about into than "
"them only other time new some could these two may first then do any like my now over such our man me even "
"most made after also did many before must through back years where much your way well down should because "
"each just those people Mr how too little state good very make world still own see men work long get here "
"between both life being under never day same another know while last might us great old year off come since "
"against go came right used take three himself few house use during without again place American around "
"however home small found Mrs thought went say part once general high upon school every don't does got united "
"left number course war until always away something fact though water less public put think almost hand "
"enough far took head yet government system better set told nothing night end why called didn't eyes find "
"going look asked later knew point next program city business give group toward young days let room president "
"side social present given several order national possible rather second face per among form important often "
"things looked early white case John become large big need four within felt along children saw best church "
"ever least power development light thing seemed family interest want members mind country area others done "
"turned although open God service certain kind problem began different door thus help sense means whole "
"matter perhaps itself York it's times law human line above name example action company local show whether "
"five history gave today either act feet across taken past quite anything seen having death week experience "
"really body word half field").split()
def english(rng, n):
out = []
size = 0
while size < n:
k = rng.randint(4, 16)
s = " ".join(rng.choice(WORDS) for _ in range(k))
s = s[0].upper() + s[1:] + rng.choice([". ", ", ", "; ", "! ", "? ", ".\n", ". The ", " - "])
if rng.random() < 0.05:
s = '<a href="http://www.' + rng.choice(WORDS) + '.com/">' + s + "</a>\n"
out.append(s)
size += len(s)
return "".join(out).encode()[:n]
def text_corpus(limit):
base = os.path.dirname(os.__file__)
out = bytearray()
for name in sorted(os.listdir(base)):
if name.endswith(".py"):
with open(os.path.join(base, name), "rb") as f:
out += f.read()
if len(out) >= limit:
break
return bytes(out[:limit])
def generate(ctx):
rng = random.Random(7)
text = text_corpus(400000)
corpora = {
"empty": b"",
"one": b"a",
"english": english(rng, 120000),
"text": text[:150000],
"random": rng.randbytes(30000),
"runs": b"abc" * 4000 + b"\0" * 20000 + bytes(range(256)) * 40 + b"z" * 300,
"binary": bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(30000)),
"utf8": ("Grüße, Привет, 你好, こんにちは, ¡Hola! " * 600).encode(),
"far": (lambda r: r + rng.randbytes(70000) + r)(rng.randbytes(9000)),
}
jobs, names = [], []
for cname, data in corpora.items():
for q in range(12):
jobs.append((data, q, 22, "generic"))
names.append(("%s/q%d" % (cname, q), cname))
for w in (10, 12, 16, 18, 24):
jobs.append((data, 9, w, "generic"))
names.append(("%s/q9-w%d" % (cname, w), cname))
for mode in ("text", "font"):
for q in (5, 11):
jobs.append((data, q, 20, mode))
names.append(("%s/%s-q%d" % (cname, mode, q), cname))
outs = pickle.loads(ctx.python(["brotli"], ENCODE, input=pickle.dumps(jobs)))
cases = [{"name": n, "corpus": c, "data": d} for (n, c), d in zip(names, outs)]
# the large-window extension (brotli CLI), on the far-match corpus and the text
for cname in ("far", "text", "english"):
for q in (5, 11):
d = ctx.nix("brotli", ["brotli", "-c", "-q", str(q), "--large_window=26"], input=corpora[cname])
cases.append({"name": "%s/large-q%d" % (cname, q), "corpus": cname, "data": d})
ctx.emit("brotli", {"corpora": corpora, "cases": cases})
bench = (text + english(rng, 1500000) + corpora["binary"] * 10 + text) * 2
bench = bench[:4000000]
bout = pickle.loads(ctx.python(["brotli"], ENCODE, input=pickle.dumps([(bench, 9, 22, "generic")])))[0]
ctx.emit("brotli_bench", {"size": len(bench), "crc": zlib.crc32(bench), "data": bout})
+61
View File
@@ -0,0 +1,61 @@
# Bzip2 fixtures (tools/fixtures.py): deterministic corpora compressed with Python's bz2 module (libbzip2) at block
# sizes 1..9, RLE1 edge cases (runs of 1..300 bytes, runs straddling block ends), every byte value, random data,
# concatenated streams with trailing garbage; plus a 4 MB bench corpus.
# tests/gen/bzip2.luau { corpora = { [name] = bytes }, cases = { { name, corpus, data } } }
# tests/gen/bzip2_bench.luau { size, crc, data }
import bz2, os, zlib
def text_corpus(limit):
base = os.path.dirname(os.__file__)
out = bytearray()
for name in sorted(os.listdir(base)):
if name.endswith(".py"):
with open(os.path.join(base, name), "rb") as f:
out += f.read()
if len(out) >= limit:
break
return bytes(out[:limit])
def generate(ctx):
rng = ctx.rng(7)
runs = bytearray()
for n in list(range(1, 20)) + [250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 300, 1000, 5000]:
runs += bytes([n % 251]) * n + b"x"
corpora = {
"empty": b"",
"one": b"a",
"two": b"ab",
"four": b"aaaa",
"five": b"aaaaa",
"text": text_corpus(300000),
"random": rng.randbytes(60000),
"runs": bytes(runs),
"zeros": b"\0" * 250000,
"allbytes": bytes(range(256)) * 50,
"binary": bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(40000)),
# a run crossing the 100k block boundary at level 1
"boundary": b"q" * 99990 + b"r" * 30 + rng.randbytes(1000),
# more than 18 Huffman group switches / many symbols in use
"skewed": bytes(rng.choice(range(256)) if rng.random() < 0.1 else 65 for _ in range(120000)),
}
cases = []
for cname, data in corpora.items():
for level in (1, 5, 9) if len(data) > 1000 else (9,):
cases.append(("%s/l%d" % (cname, level), cname, bz2.compress(data, level)))
for level in range(1, 10):
cases.append(("text/all-l%d" % level, "text", bz2.compress(corpora["text"], level)))
corpora["multi"] = corpora["text"][:20000] + b"" + corpora["runs"]
multi = bz2.compress(corpora["text"][:20000], 9) + bz2.compress(b"", 1) + bz2.compress(corpora["runs"], 3)
cases.append(("multi/streams", "multi", multi))
cases.append(("multi/trailing", "multi", multi + b"garbage after the last stream"))
ctx.emit("bzip2", {
"corpora": corpora,
"cases": [{"name": n, "corpus": c, "data": d} for n, c, d in cases],
})
bench = bytearray()
while len(bench) < 4_000_000:
bench += corpora["text"] + corpora["binary"] + rng.randbytes(20000)
bench = bytes(bench[:4_000_000])
ctx.emit("bzip2_bench", {"size": len(bench), "crc": zlib.crc32(bench), "data": bz2.compress(bench, 9)})
+108
View File
@@ -0,0 +1,108 @@
# data/cbor fixtures: RFC 8949 Appendix A examples and random values encoded by Python's cbor2 (through nix): every
# integer width (and bignums), floats, text / byte strings, nested arrays / maps, dates (tags 0 / 1), other tags,
# simple values, undefined, indefinite-length items (written by hand), with the canonical form of cbor2's decode.
# tests/gen/cbor.luau { appendix = { { hex, data, canon } }, safe = { { data, canon } }, wide = { { data, canon,
# canonStr } } } safe: our decode + encode gives the same bytes; wide: big integers (doubles / exact text)
import importlib.util, os, pickle
_spec = importlib.util.spec_from_file_location("_data_common", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_data_common.py"))
C = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(C)
APPENDIX = """00 01 0a 17 1818 1819 1864 1903e8 1a000f4240 1b000000e8d4a51000 1bffffffffffffffff c249010000000000000000
3bffffffffffffffff c349010000000000000000 20 29 3863 3903e7 f90000 f98000 f93c00 fb3ff199999999999a f93e00 f97bff
fa47c35000 fa7f7fffff fb7e37e43c8800759c f90001 f90400 f9c400 fbc010666666666666 f97c00 f97e00 f9fc00 fa7f800000
fa7fc00000 faff800000 fb7ff0000000000000 fb7ff8000000000000 fbfff0000000000000 f4 f5 f6 f7 f0 f818 f8ff
c074323031332d30332d32315432303a30343a30305a c11a514b67b0 c1fb41d452d9ec200000 d74401020304
d818456449455446 d82076687474703a2f2f7777772e6578616d706c652e636f6d 40 4401020304 60 6161 6449455446 62225c
62c3bc 63e6b0b4 64f0908591 80 83010203 8301820203820405 98190102030405060708090a0b0c0d0e0f101112131415161718181819
a0 a201020304 a26161016162820203 826161a161626163 a56161614161626142616361436164614461656145 5f42010243030405ff
7f657374726561646d696e67ff 9fff 9f018202039f0405ffff 9f01820203820405ff 83018202039f0405ff 83019f0203ff820405
9f0102030405060708090a0b0c0d0e0f101112131415161718181819ff bf61610161629f0203ffff 826161bf61626163ff
bf6346756ef563416d7421ff"""
BODY = r'''
import cbor2, pickle, random, sys, datetime
from collections.abc import Mapping
HEXES = sys.argv[1:] if False else HEXLIST
def conv(v):
if v is cbor2.undefined:
return ["undefined"]
if isinstance(v, cbor2.CBORSimpleValue):
return ["simple", v.value]
if isinstance(v, cbor2.CBORTag):
return ["tag", v.tag, conv(v.value)]
if isinstance(v, (list, tuple)):
return [conv(x) for x in v]
if isinstance(v, Mapping) or hasattr(v, "items"):
return {(tuple(conv(k)) if isinstance(k, list) else k): conv(x) for k, x in v.items()}
return v
def cstr(v):
if isinstance(v, cbor2.CBORTag):
return cbor2.CBORTag(v.tag, cstr(v.value))
if isinstance(v, int) and not isinstance(v, bool) and abs(v) >= 2**53:
return str(v)
if isinstance(v, (list, tuple)):
return [cstr(x) for x in v]
if isinstance(v, Mapping) or hasattr(v, "items"):
return {k: cstr(x) for k, x in v.items()}
return v
out = {"appendix": [], "safe": [], "wide": []}
for h in HEXES:
data = bytes.fromhex(h)
try:
v = cbor2.loads(data)
except Exception:
out["appendix"].append({"hex": h, "data": data, "error": True}) # e.g. f818: invalid since RFC 8949
continue
if type(v).__name__ in ("Decimal", "Fraction", "UUID") or (isinstance(v, str) and h.startswith("d820")):
continue # semantic tags cbor2 interprets and we keep tagged
out["appendix"].append({"hex": h, "data": data, "canon": canon(conv(v)), "canonStr": canon(conv(cstr(v)))})
rng = random.Random(9)
def rint(wide):
lim = rng.choice([23, 24, 255, 256, 65535, 65536, 2**32 - 1, 2**32, 2**53 - 1])
if wide and rng.random() < 0.4:
lim = rng.choice([2**64 - 1, 2**70])
v = rng.randrange(0, lim + 1)
return -v - 1 if rng.random() < 0.5 else v
def rstr():
return "".join(rng.choice("abé中\U0001f600 \n\x00") for _ in range(rng.choice([0, 1, 23, 24, 255, 300])))
def rval(d, wide):
r = rng.random()
if d > 3 or r < 0.5:
k = rng.randrange(10)
if k == 0: return None
if k == 1: return rng.random() < 0.5
if k in (2, 3): return rint(wide)
if k == 4:
f = rng.uniform(-1e6, 1e6) * 10 ** rng.randrange(-5, 5)
return f if not f.is_integer() else f + 0.5
if k == 5: return rstr()
if k == 6: return rng.randbytes(rng.choice([0, 3, 24, 256]))
if k == 7:
return datetime.datetime.fromtimestamp(rng.randrange(0, 2**33), datetime.timezone.utc)
if k == 8:
return cbor2.CBORTag(rng.choice([6, 1000, 100000]), rval(d + 1, wide))
return rng.choice([cbor2.undefined, cbor2.CBORSimpleValue(rng.choice([0, 19, 32, 255]))])
if r < 0.75:
return [rval(d + 1, wide) for _ in range(rng.choice([0, 1, 3, 23, 24] if d < 2 else [0, 1, 3]))]
m = {}
for _ in range(rng.choice([0, 1, 3, 23, 24] if d < 2 else [0, 1, 3])):
key = rint(False) if rng.random() < 0.3 else "".join(rng.choice("abcé") for _ in range(rng.randrange(6)))
m[key] = rval(d + 1, wide)
return m
for i in range(250):
data = cbor2.dumps(rval(0, False))
out["safe"].append({"data": data, "canon": canon(conv(cbor2.loads(data)))})
for i in range(120):
data = cbor2.dumps(rval(0, True))
v = cbor2.loads(data)
out["wide"].append({"data": data, "canon": canon(conv(v)), "canonStr": canon(conv(cstr(v)))})
sys.stdout.buffer.write(pickle.dumps(out, protocol=4))
'''
def generate(ctx):
hexes = APPENDIX.split()
out = pickle.loads(C.python(ctx, ["cbor2"], "HEXLIST = %r\n" % hexes + BODY))
ctx.emit("cbor", out)
+43
View File
@@ -0,0 +1,43 @@
# data/csv fixtures: random tables (quotes, delimiters, CR / LF / CRLF inside fields, empty fields, unicode) written
# by Python's csv.writer / DictWriter in several dialects, with the rows csv.reader reads back (blank rows dropped:
# we skip blank lines).
# tests/gen/csv.luau { { data, delimiter, rows = { { field } }, keyed? } }
# keyed: the file has a header row (DictWriter)
import csv, io
def rand_field(rng):
alph = 'ab ,;\t|"\n\ré中1.'
k = rng.random()
if k < 0.15:
return ""
if k < 0.3:
return str(rng.randrange(-1000, 1000))
return "".join(rng.choice(alph) for _ in range(rng.randrange(1, 8)))
def generate(ctx):
rng = ctx.rng(13)
cases = []
for i in range(200):
delim = rng.choice([",", ",", ";", "\t", "|"])
ncol = rng.randrange(1, 6)
rows = [[rand_field(rng) for _ in range(ncol)] for _ in range(rng.randrange(1, 12))]
buf = io.StringIO(newline="")
lt = "\r\n" if delim == "," else rng.choice(["\r\n", "\n"])
w = csv.writer(buf, delimiter=delim, lineterminator=lt)
w.writerows(rows)
data = buf.getvalue()
back = [r for r in csv.reader(io.StringIO(data, newline=""), delimiter=delim) if r]
cases.append({"data": data.encode(), "delimiter": delim, "newline": lt, "rows": back})
for i in range(30):
cols = ["id", "name", "note é", "x,y"][: rng.randrange(1, 5)]
rows = [{c: rand_field(rng) for c in cols} for _ in range(rng.randrange(1, 8))]
buf = io.StringIO(newline="")
w = csv.DictWriter(buf, fieldnames=cols)
w.writeheader()
w.writerows(rows)
data = buf.getvalue()
back = [r for r in csv.reader(io.StringIO(data, newline="")) if r]
cases.append({"data": data.encode(), "delimiter": ",", "newline": "\r\n", "rows": back, "keyed": True})
ctx.emit("csv", cases)
+37
View File
@@ -0,0 +1,37 @@
# Font fixtures (tools/fixtures.py): the imgui-luau fonts (TrueType: Cousine, DroidSans, Karla, Proggy*, Roboto, read
# from ~/dev/luau/imgui/imgui-luau/fonts or $IMGUI_FONTS; skipped if missing) and Source Sans 3 (CFF OpenType, nixpkgs
# source-sans), plus a copy of ProggyClean with a 'kern' table and a two-font collection, both made with fontTools.
# Reference values come from tools/fixtures/_font_reference.py: fontTools (metrics, names, cmap, hmtx, control boxes,
# areas, WOFF / WOFF2), HarfBuzz (GPOS kerning), FreeType (kern tables, unhinted renders).
# tests/gen/fonts.luau { fonts = { { name, data, upem, ..., cmap, glyphs, kern, renders } }, woff = { ... }, ttc }
import base64, glob, json, os, subprocess
INPUTS = ["tools/fixtures/_font_reference.py"]
FONTS = os.environ.get("IMGUI_FONTS", os.path.expanduser("~/dev/luau/imgui/imgui-luau/fonts"))
PICK = ["Cousine-Regular", "DroidSans", "Karla-Regular", "ProggyClean", "Roboto-Medium"]
def generate(ctx):
specs = []
for name in PICK:
p = os.path.join(FONTS, name + ".ttf")
if os.path.exists(p):
specs.append({"name": name, "b64": base64.b64encode(open(p, "rb").read()).decode()})
out = subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#source-sans"], capture_output=True,
check=True, text=True).stdout.strip().split("\n")[-1]
otf = os.path.join(out, "share", "fonts", "opentype", "SourceSans3-Regular.otf")
specs.append({"name": "SourceSans3-Regular", "b64": base64.b64encode(open(otf, "rb").read()).decode()})
code = open(os.path.join(ctx.root, "tools", "fixtures", "_font_reference.py")).read()
raw = ctx.python(["fonttools", "freetype-py", "uharfbuzz", "brotli"], code, input=json.dumps(specs).encode())
res = json.loads(raw)
d = base64.b64decode
for f in res["fonts"]:
f["data"] = d(f["data"])
for r in f["renders"]:
r["pixels"] = d(r["pixels"])
for w in res["woff"]:
w["woff"], w["woff2"], w["woff2h"] = d(w["woff"]), d(w["woff2"]), d(w["woff2h"])
if "ttc" in res:
res["ttc"]["data"] = d(res["ttc"]["data"])
ctx.emit("fonts", res)
+133
View File
@@ -0,0 +1,133 @@
# GIF fixtures (tools/fixtures.py): GIFs written by ImageMagick and Pillow (static, interlaced, 2..256 colours, grey,
# transparency, animations with every disposal method, sub-rectangle frames, local colour tables, loop counts,
# comments), each with ImageMagick's decode of every frame as the reference.
# tests/gen/gif.luau { { name, data, width, height, loops, frames = { { w, h, x, y, delay, dispose, crc } },
# first = crc of the first frame on a transparent canvas, comment? } }
# tests/gen/gif_bench.luau a 512 x 384 photo-like GIF (256 colours) and a 40-frame 128 x 128 animation
# CRCs are of rgba8 with transparent pixels (alpha 0) zeroed to 0, 0, 0, 0. delay in centiseconds.
import os, struct, tempfile, zlib
PILLOW = r'''
import io, sys, random
from PIL import Image, ImageDraw
out = sys.argv[1]
rng = random.Random(4)
def frame(w, h, seed, alpha=False):
im = Image.new("RGBA", (w, h), (0, 0, 0, 0) if alpha else (seed * 40 % 256, 90, 200, 255))
d = ImageDraw.Draw(im)
for i in range(5):
x, y = rng.randrange(w), rng.randrange(h)
d.ellipse([x - 6, y - 6, x + 6, y + 6], fill=(rng.randrange(256), rng.randrange(256), seed * 60 % 256, 255))
return im
# animation with per-frame disposal, durations, loop
fr = [frame(48, 32, i) for i in range(4)]
fr[0].save(out + "/pil_anim.gif", save_all=True, append_images=fr[1:], duration=[50, 120, 70, 200], loop=2, disposal=[0, 1, 2, 3], optimize=False)
# transparent animation (sub-rectangles from Pillow's optimizer)
fr = [frame(40, 40, i, alpha=True) for i in range(5)]
fr[0].save(out + "/pil_alpha.gif", save_all=True, append_images=fr[1:], duration=80, loop=0, disposal=2)
# a static interlaced palette image with a comment
im = frame(61, 37, 9).convert("P", palette=Image.Palette.ADAPTIVE, colors=32)
im.save(out + "/pil_interlaced.gif", interlace=True, comment=b"made by tools/fixtures/gif.py")
# 1-bit and a 3-colour image (minimum code size 2)
Image.frombytes("L", (17, 9), bytes((x * 255 // 16) if (x + y) % 3 else 0 for y in range(9) for x in range(17))).convert("1").save(out + "/pil_1bit.gif")
im = Image.new("P", (23, 19)); im.putpalette([255, 0, 0, 0, 255, 0, 0, 0, 255])
im.putdata([(x * y) % 3 for y in range(19) for x in range(23)]); im.save(out + "/pil_3col.gif")
'''
def run_im(ctx, args):
return ctx.nix("imagemagick", ["magick"] + args)
def reference(ctx, path):
info = run_im(ctx, ["identify", "-format", "%w %h %X %Y %T %D %W %H %[comment]|", path]).decode("latin-1")
raw = run_im(ctx, [path, "rgba:-"])
frames, pos = [], 0
comment = None
for line in info.split("|"):
if not line.strip():
continue
parts = line.split(" ", 8)
w, h, x, y, delay = int(parts[0]), int(parts[1]), int(parts[2]), int(parts[3]), int(parts[4])
dispose = parts[5]
cw, ch = int(parts[6]), int(parts[7])
if len(parts) > 8 and parts[8]:
comment = parts[8]
px = bytearray(raw[pos:pos + w * h * 4]); pos += w * h * 4
for i in range(0, len(px), 4):
if px[i + 3] == 0:
px[i:i + 4] = b"\0\0\0\0"
frames.append({"w": w, "h": h, "x": x, "y": y, "delay": delay, "dispose": dispose.lower(), "px": bytes(px), "crc": zlib.crc32(bytes(px))})
assert pos == len(raw), (path, pos, len(raw))
# the first frame on a transparent canvas
f = frames[0]
canvas = bytearray(cw * ch * 4)
for yy in range(f["h"]):
for xx in range(f["w"]):
X, Y = f["x"] + xx, f["y"] + yy
if 0 <= X < cw and 0 <= Y < ch:
p = f["px"][(yy * f["w"] + xx) * 4:(yy * f["w"] + xx) * 4 + 4]
if p[3]:
canvas[(Y * cw + X) * 4:(Y * cw + X) * 4 + 4] = p
for f in frames:
del f["px"]
return cw, ch, frames, zlib.crc32(bytes(canvas)), comment
def loops_of(data):
i = data.find(b"NETSCAPE2.0")
if i < 0:
return None
return data[i + 13] | (data[i + 14] << 8)
def generate(ctx):
work = tempfile.mkdtemp(prefix="gif-fx-")
files = []
def im(name, args):
p = os.path.join(work, name + ".gif")
run_im(ctx, args + [p])
files.append((name, p))
im("rose", ["rose:"])
im("rose_2col", ["rose:", "-colors", "2"])
im("rose_16col_interlaced", ["rose:", "-colors", "16", "-interlace", "GIF"])
im("rose_dither", ["rose:", "-resize", "200%", "-dither", "FloydSteinberg", "-colors", "64"])
im("logo", ["logo:", "-resize", "30%"])
im("gray", ["-size", "64x40", "gradient:", "-colorspace", "gray"])
im("transparent", ["-size", "40x30", "xc:none", "-fill", "red", "-draw", "circle 20,15 20,5"])
for disp in ("None", "Background", "Previous"):
im("anim_" + disp.lower(), ["-delay", "7", "-dispose", disp, "-size", "30x20", "xc:red",
"-size", "10x8", "-page", "+5+4", "xc:blue", "-page", "+12+9", "xc:lime",
"-page", "+0+0", "-size", "6x6", "xc:yellow", "-loop", "3"])
# local colour tables: frames with different 256-colour palettes
im("anim_local", ["-delay", "20", "rose:", "(", "rose:", "-negate", ")", "(", "logo:", "-resize", "70x46!", ")", "-loop", "0"])
# optimised transparency animation
im("anim_optimized", ["-delay", "5", "-size", "50x50", "xc:white", "-fill", "black",
"(", "+clone", "-draw", "circle 10,10 10,5", ")", "(", "+clone", "-draw", "circle 30,30 30,24", ")",
"(", "+clone", "-draw", "circle 40,12 40,6", ")", "-layers", "OptimizeTransparency", "-loop", "0"])
ctx.python(["pillow"], "import sys; sys.argv = ['', %r]\n" % work + PILLOW)
for n in ("pil_anim", "pil_alpha", "pil_interlaced", "pil_1bit", "pil_3col"):
files.append((n, os.path.join(work, n + ".gif")))
cases = []
for name, p in files:
data = open(p, "rb").read()
cw, ch, frames, first, comment = reference(ctx, p)
c = {"name": name, "data": data, "width": cw, "height": ch, "frames": frames, "first": first}
lp = loops_of(data)
if lp is not None:
c["loops"] = lp # the raw NETSCAPE2.0 repeat value
if comment:
c["comment"] = comment
cases.append(c)
ctx.emit("gif", cases)
bench = os.path.join(work, "bench.gif")
run_im(ctx, ["-size", "512x384", "-seed", "3", "plasma:fractal", "-colors", "256", bench])
anim = os.path.join(work, "bench_anim.gif")
args = ["-delay", "4"]
for i in range(40):
args += ["(", "-size", "128x128", "radial-gradient:", "-roll", "+%d+%d" % (i * 3, i * 2), ")"]
run_im(ctx, args + ["-colors", "128", "-loop", "0", anim])
ctx.emit("gif_bench", {"still": open(bench, "rb").read(), "anim": open(anim, "rb").read()})
+115
View File
@@ -0,0 +1,115 @@
# glTF fixtures (tools/fixtures.py): Khronos glTF-Sample-Assets models (tests/fixtures/gltf, licences per model
# folder), gltfpack (meshoptimizer) quantized variants (KHR_mesh_quantization, normalized and integer positions,
# KHR_texture_transform), and files exported by assimp, with reference values from assimp (`assimp info`: meshes, faces,
# bounds, materials, animations, cameras, lights) and trimesh (area, triangles, bounds of the whole scene).
# tests/gen/gltf_cases.luau { name, main, data, files = { uri -> bytes }, assimp, trimesh, like? (the original of a
# quantized variant: compare against its references with a tolerance) }
# tests/gen/gltf_xcheck.luau our encoder's .glb and .gltf for every case (tools/fixtures/_gltf_encode.luau), read back
# by assimp and trimesh: { name, case, assimp, trimesh }
import importlib.util, json, os, struct
INPUTS = ["tests/fixtures/gltf", "src/Formats/model/gltf", "src/Formats/codecs/Json", "src/Formats/codecs/Base64",
"tools/fixtures/_model_ref.py", "tools/fixtures/_gltf_encode.luau"]
def ref_module(ctx):
spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def assimp_extra(ctx, path):
# cameras / lights / animations counts from assimp info (the shared helper parses meshes / faces / bounds)
import re, subprocess
try:
txt = ctx.nix("assimp", ["assimp", "info", path, "-r"]).decode("utf-8", "replace")
except subprocess.CalledProcessError:
return {}
out = {}
for label in ("Animations", "Cameras", "Lights", "Bones"):
m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M)
if m:
out[label.lower()] = int(m.group(1))
return out
def ply_torus(R=2.0, r=0.5, a=16, b=8):
import math
vs, fs = [], []
for i in range(a):
for j in range(b):
u, v = 2 * math.pi * i / a, 2 * math.pi * j / b
vs.append(((R + r * math.cos(v)) * math.cos(u), r * math.sin(v), (R + r * math.cos(v)) * math.sin(u)))
for i in range(a):
for j in range(b):
p, q = i * b + j, ((i + 1) % a) * b + j
p2, q2 = i * b + (j + 1) % b, ((i + 1) % a) * b + (j + 1) % b
fs.append((p, p2, q2))
fs.append((p, q2, q))
head = "ply\nformat ascii 1.0\nelement vertex %d\nproperty float x\nproperty float y\nproperty float z\nelement face %d\nproperty list uchar int vertex_indices\nend_header\n" % (len(vs), len(fs))
return (head + "".join("%r %r %r\n" % v for v in vs) + "".join("3 %d %d %d\n" % f for f in fs)).encode()
def generate(ctx):
M = ref_module(ctx)
root = os.path.join(ctx.root, "tests", "fixtures", "gltf")
cases = []
for model in sorted(os.listdir(root)):
for variant in sorted(os.listdir(os.path.join(root, model))):
d = os.path.join(root, model, variant)
if not os.path.isdir(d):
continue
mains = [f for f in sorted(os.listdir(d)) if f.endswith(".gltf") or f.endswith(".glb")]
if not mains:
continue
files = {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d)) if f != mains[0]}
cases.append({"name": model + "/" + variant, "main": mains[0], "path": os.path.join(d, mains[0]), "files": files})
# gltfpack variants of a few models: default (integer positions + texture transform), -vpn (normalized positions),
# -vpf (float positions, quantized normals / uvs)
tmp = M.tempdir()
for model, variant, main in (("BoxTextured", "glTF", "BoxTextured.gltf"), ("Box", "glTF-Binary", "Box.glb"), ("SimpleSkin", "glTF", "SimpleSkin.gltf"), ("MultiUVTest", "glTF-Binary", "MultiUVTest.glb")):
for flag in ("", "-vpn", "-vpf", "-vpi"):
out = os.path.join(tmp, "%s_q%s.glb" % (model, flag))
args = ["gltfpack", "-i", os.path.join(root, model, variant, main), "-o", out, "-kn", "-km"] + ([flag] if flag else [])
ctx.nix("meshoptimizer", args)
cases.append({"name": "gltfpack/%s%s" % (model, flag), "main": os.path.basename(out), "path": out, "files": {}, "like": model + "/" + variant})
# assimp's glTF exporters
ply = os.path.join(tmp, "torus.ply")
with open(ply, "wb") as f:
f.write(ply_torus())
for ext in ("glb", "gltf"):
out = os.path.join(tmp, "torus_assimp." + ext)
ctx.nix("assimp", ["assimp", "export", ply, out, "-f" + ("glb2" if ext == "glb" else "gltf2")])
files = {}
for f in os.listdir(tmp):
if f.startswith("torus_assimp") and f.endswith(".bin"):
files[f] = open(os.path.join(tmp, f), "rb").read()
cases.append({"name": "assimp/torus." + ext, "main": os.path.basename(out), "path": out, "files": files})
infos = M.assimp_info(ctx, [c["path"] for c in cases], raw=True)
tms = M.trimesh_metrics(ctx, [c["path"] for c in cases])
for c, a, t in zip(cases, infos, tms):
a.update(assimp_extra(ctx, c["path"]))
c["assimp"] = a
c["trimesh"] = t
c["data"] = open(c["path"], "rb").read()
del c["path"]
ctx.emit("gltf_cases", cases)
# the reference tools read our output
ours = M.luau_encode(ctx, "tools/fixtures/_gltf_encode.luau")
xtmp = M.tempdir()
names = []
for name, data in sorted(ours.items()):
with open(os.path.join(xtmp, name), "wb") as f:
f.write(data)
if name.endswith(".glb") or name.endswith(".gltf"):
names.append(name)
paths = [os.path.join(xtmp, n) for n in names]
xi = M.assimp_info(ctx, paths, raw=True)
xt = M.trimesh_metrics(ctx, paths)
out = []
for n, a, t in zip(names, xi, xt):
a.update(assimp_extra(ctx, os.path.join(xtmp, n)))
out.append({"name": n, "case": int(n.split("_")[1].split(".")[0]), "assimp": a, "trimesh": t})
ctx.emit("gltf_xcheck", out)
+93
View File
@@ -0,0 +1,93 @@
# Radiance HDR fixtures (tools/fixtures.py): files ImageMagick writes (new-style RLE, from float PFM sources) and
# hand-written ones (flat and old-style RLE scanlines, narrow images, the "#?RGBE" header, EXPOSURE lines, every
# orientation); references = ImageMagick's float decodes for its files, and for the hand-written ones the RGBE values
# decoded by the rgbe.c rule (m * 2^(e - 136)) here.
# tests/gen/hdr.luau { { name, data, width, height, floats (rgbaf32 little-endian bytes), exposure? } }
import math, os, random, shutil, struct, subprocess, tempfile
def rgbe(r, g, b):
v = max(r, g, b)
if v < 1e-32:
return (0, 0, 0, 0)
m, e = math.frexp(v)
s = m * 256 / v
return (min(255, int(r * s)), min(255, int(g * s)), min(255, int(b * s)), e + 128)
def flt(p):
if p[3] == 0:
return (0.0, 0.0, 0.0)
f = math.ldexp(1.0, p[3] - 136)
return (p[0] * f, p[1] * f, p[2] * f)
def generate(ctx):
magick = ctx.nix("imagemagick", ["sh", "-c", "command -v magick"]).decode().strip()
work = tempfile.mkdtemp(prefix="formats-hdr-")
try:
_generate(ctx, magick, work)
finally:
shutil.rmtree(work, ignore_errors=True)
def _generate(ctx, magick, work):
rng = random.Random(4)
cases = []
def im_case(name, w, h, fn):
pfm = os.path.join(work, name + ".pfm")
with open(pfm, "wb") as f:
f.write(b"PF\n%d %d\n-1.0\n" % (w, h))
for y in range(h - 1, -1, -1):
for x in range(w):
f.write(struct.pack("<fff", *fn(x, y)))
out = os.path.join(work, name + ".hdr")
subprocess.run([magick, pfm, out], check=True, capture_output=True)
fl = subprocess.run([magick, out, "-depth", "32", "-define", "quantum:format=floating-point", "-endian", "LSB", "rgba:-"], check=True, capture_output=True).stdout
cases.append({"name": name, "data": open(out, "rb").read(), "width": w, "height": h, "floats": fl})
im_case("im-gradient", 64, 20, lambda x, y: (x / 16.0, y / 5.0, (x * y) % 7 * 0.3))
im_case("im-noise", 33, 9, lambda x, y: (rng.random() * 100, rng.random(), rng.random() * 0.001))
im_case("im-flat", 100, 3, lambda x, y: (0.5, 0.25, 2.0) if x < 60 else (0.0, 0.0, 0.0))
def hand(name, w, h, header, res, rows, mapping, exposure=None):
"""rows: list of scanline byte strings; mapping(i, j) -> (x, y) of scanline i pixel j; pix: (i, j) -> RGBE"""
data = header + b"\n\n" + res + b"\n" + b"".join(r for r, _ in rows)
fl = [(0.0, 0.0, 0.0)] * (w * h)
for i, (_, pixels) in enumerate(rows):
for j, p in enumerate(pixels):
x, y = mapping(i, j)
fl[y * w + x] = flt(p)
c = {"name": name, "data": data, "width": w, "height": h,
"floats": b"".join(struct.pack("<ffff", *v, 1.0) for v in fl)}
if exposure:
c["exposure"] = exposure
cases.append(c)
def flat_row(n, seed):
px = [rgbe(rng.random() * 4, rng.random(), rng.random() * 0.1) for _ in range(n)]
px = [p if p[:3] != (1, 1, 1) else (2, 1, 1, p[3]) for p in px]
return b"".join(bytes(p) for p in px), px
def oldrle_row(n):
p = rgbe(0.7, 0.2, 0.1)
q = rgbe(3.0, 3.0, 3.0)
# p, then a run of 3 more p, then q, then a run of 2 + (1 << 8)*0 ... keep it simple: q x (n - 5)
pix = [p] * 4 + [q] * (n - 4)
run = n - 5
return bytes(p) + bytes((1, 1, 1, 3)) + bytes(q) + bytes((1, 1, 1, run)), pix
w, h = 5, 3
rows = [flat_row(w, i) for i in range(h)]
hand("flat-narrow", w, h, b"#?RGBE\nFORMAT=32-bit_rle_rgbe\nEXPOSURE=2.0\nEXPOSURE=1.5", b"-Y 3 +X 5", rows, lambda i, j: (j, i), exposure=3.0)
rows = [oldrle_row(12) for _ in range(2)]
hand("old-rle", 12, 2, b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\nSOFTWARE=hand", b"-Y 2 +X 12", rows, lambda i, j: (j, i))
for res, mp in ((b"+Y 3 +X 5", lambda i, j: (j, 2 - i)), (b"-Y 3 -X 5", lambda i, j: (4 - j, i)),
(b"+Y 3 -X 5", lambda i, j: (4 - j, 2 - i))):
rows = [flat_row(5, i) for i in range(3)]
hand("orient " + res.decode(), 5, 3, b"#?RADIANCE", res, rows, mp)
for res, mp in ((b"+X 5 -Y 3", lambda i, j: (i, j)), (b"-X 5 +Y 3", lambda i, j: (4 - i, 2 - j))):
rows = [flat_row(3, i) for i in range(5)]
hand("orient " + res.decode(), 5, 3, b"#?RADIANCE", res, rows, mp)
ctx.emit("hdr", cases)
+93
View File
@@ -0,0 +1,93 @@
# ICO / CUR fixtures (tools/fixtures.py): icons written by ImageMagick (auto-resize sets with a 256 PNG entry) and
# Pillow (PNG and BMP entries), and hand-built ones from Pillow's BMP writer (1 / 4 / 8 / 24 / 32-bit DIBs with AND
# masks, a cursor with hotspots); references = Pillow's RGBA decode of every entry, in file order.
# tests/gen/ico.luau { { name, data, entries = { { width, height, rgba (bytes) } } } }
import struct
CODE = r'''
import io, struct, subprocess, sys
from PIL import Image, IcoImagePlugin
magick = sys.argv[1]
out = []
def refs(data):
if data[2] == 2: # IcoFile reads icons only: decode a cursor's entries as an icon's
data = data[:2] + b"\x01" + data[3:]
f = IcoImagePlugin.IcoFile(io.BytesIO(data))
order = sorted(range(len(f.entry)), key=lambda i: f.entry[i].offset)
res = []
for i in order:
im = f.frame(i).convert("RGBA")
res.append((im.size[0], im.size[1], im.tobytes()))
return res
def emit(name, data):
out.append((name, data, refs(data)))
src = Image.new("RGBA", (64, 64))
px = src.load()
for y in range(64):
for x in range(64):
a = 255 if (x - 32) ** 2 + (y - 32) ** 2 < 900 else (0 if x < 8 else 128)
px[x, y] = ((x * 4) % 256, (y * 4) % 256, ((x ^ y) * 8) % 256, a)
png = io.BytesIO(); src.save(png, "PNG")
r = subprocess.run([magick, "png:-", "-define", "icon:auto-resize=256,48,32,16", "ico:-"], input=png.getvalue(), capture_output=True, check=True)
emit("im-autoresize", r.stdout)
for fmt in ("png", "bmp"):
b = io.BytesIO(); src.save(b, "ICO", sizes=[(16, 16), (32, 32), (64, 64)], bitmap_format=fmt); emit("pil-" + fmt, b.getvalue())
# hand-built DIB entries from Pillow BMPs
def dib(im, mask_fn):
b = io.BytesIO(); im.save(b, "BMP"); d = b.getvalue()[14:]
w, h = im.size
hs = struct.unpack("<I", d[:4])[0]
d = d[:8] + struct.pack("<i", h * 2) + d[12:]
stride = ((w + 31) // 32) * 4
mask = bytearray()
for y in range(h - 1, -1, -1):
row = bytearray(stride)
for x in range(w):
if mask_fn(x, y):
row[x // 8] |= 0x80 >> (x % 8)
mask += row
return d + bytes(mask)
def icon(entries, typ=1, hotspots=None):
hdr = struct.pack("<HHH", 0, typ, len(entries))
off = 6 + 16 * len(entries)
dirs, blobs = b"", b""
for i, (im, blob, bpp) in enumerate(entries):
w, h = im.size
f1, f2 = (1, bpp) if typ == 1 else hotspots[i]
dirs += struct.pack("<BBBBHHII", w % 256, h % 256, 0, 0, f1, f2, len(blob), off)
off += len(blob); blobs += blob
return hdr + dirs + blobs
base = src.resize((24, 20))
m = lambda x, y: (x + y) % 7 == 0
e1 = base.convert("1"); e4 = base.convert("RGB").quantize(16); e8 = base.convert("RGB").quantize(200); e24 = base.convert("RGB")
emit("hand-dibs", icon([(e1, dib(e1, m), 1), (e4, dib(e4, m), 4), (e8, dib(e8, m), 8), (e24, dib(e24, m), 24)]))
e32 = src.resize((30, 17))
b = io.BytesIO(); e32.save(b, "BMP"); d32 = b.getvalue()[14:]
# Pillow writes 32-bit BMPs as BGRA? if not, build one by hand
w, h = e32.size
bgra = b"".join(bytes((p[2], p[1], p[0], p[3])) for y in range(h - 1, -1, -1) for p in (e32.getpixel((x, y)) for x in range(w)))
stride = ((w + 31) // 32) * 4
d32 = struct.pack("<IiiHHIIiiII", 40, w, h * 2, 1, 32, 0, len(bgra), 0, 0, 0, 0) + bgra + bytes(stride * h)
emit("hand-32", icon([(e32, d32, 32)]))
emit("hand-cur", icon([(e24, dib(e24, m), 24), (e8, dib(e8, m), 8)], typ=2, hotspots=[(3, 4), (5, 6)]))
for name, data, rs in out:
sys.stdout.buffer.write(struct.pack("<HIH", len(name), len(data), len(rs)) + name.encode() + data)
for w, h, px in rs:
sys.stdout.buffer.write(struct.pack("<III", w, h, len(px)) + px)
'''
def generate(ctx):
magick = ctx.nix("imagemagick", ["sh", "-c", "command -v magick"]).decode().strip()
raw = ctx.python(["pillow"], CODE.replace("sys.argv[1]", repr(magick)))
cases, p = [], 0
while p < len(raw):
nl, dl, ne = struct.unpack("<HIH", raw[p:p + 8]); p += 8
name = raw[p:p + nl].decode(); p += nl
data = raw[p:p + dl]; p += dl
ents = []
for _ in range(ne):
w, h, pl = struct.unpack("<III", raw[p:p + 12]); p += 12
ents.append({"width": w, "height": h, "rgba": raw[p:p + pl]}); p += pl
cases.append({"name": name, "data": data, "entries": ents})
ctx.emit("ico", cases)
+65
View File
@@ -0,0 +1,65 @@
# ImageOps fixtures (tools/fixtures.py): Pillow references for ops/ImageOps.
# tests/gen/imageops.luau { rgb = { w, h, px }, rgba = {...}, rgba2 = {...}, gray = L bytes of rgb,
# resize = { { filter, mode, w, h, px } }, rotate = { { angle, expand, w, h, px } },
# composite = bytes }
# rgb / rgba: smooth gradients + noise + shapes (Pillow drawing), deterministic.
import struct
CODE = r'''
import random, struct, sys
from PIL import Image, ImageDraw
rng = random.Random(11)
def src(w, h, mode):
im = Image.new("RGBA", (w, h))
px = im.load()
for y in range(h):
for x in range(w):
px[x, y] = ((x * 255) // (w - 1), (y * 255) // (h - 1), (x * y) % 256, 255 if mode == "RGB" else (x * 7 + y * 3) % 256)
d = ImageDraw.Draw(im)
for _ in range(5):
x0, y0 = rng.randrange(w), rng.randrange(h)
d.ellipse([x0, y0, x0 + rng.randrange(4, 20), y0 + rng.randrange(4, 20)], fill=(rng.randrange(256), rng.randrange(256), rng.randrange(256), 255 if mode == "RGB" else rng.randrange(256)))
return im.convert(mode)
out = []
def emit(tag, *parts):
data = b"".join(parts)
out.append(struct.pack("<16sI", tag.encode().ljust(16), len(data)) + data)
rgb = src(61, 47, "RGB"); rgba = src(61, 47, "RGBA"); rgba2 = src(61, 47, "RGBA")
hdr = lambda im: struct.pack("<II", *im.size)
emit("rgb", hdr(rgb), rgb.tobytes()); emit("rgba", hdr(rgba), rgba.tobytes()); emit("rgba2", hdr(rgba2), rgba2.tobytes())
emit("gray", rgb.convert("L").tobytes())
emit("graya", rgba.convert("L").tobytes())
F = {"nearest": Image.NEAREST, "bilinear": Image.BILINEAR, "lanczos": Image.LANCZOS}
for fname, f in F.items():
for (w, h) in ((30, 20), (100, 80), (61, 20), (13, 47), (7, 3), (200, 150)):
for mode in ("RGB", "L"):
r = rgb.convert(mode).resize((w, h), f)
emit("resize", struct.pack("<16s4sII", fname.encode().ljust(16), mode.encode().ljust(4), w, h), r.tobytes())
for angle, expand in ((30, True), (-45, True), (123.4, True), (17, False), (200, False)):
r = rgba.rotate(angle, Image.BILINEAR, expand=expand)
emit("rotate", struct.pack("<dBII", angle, 1 if expand else 0, *r.size), r.tobytes())
emit("composite", Image.alpha_composite(rgba, rgba2).tobytes())
sys.stdout.buffer.write(b"".join(out))
'''
def generate(ctx):
raw = ctx.python(["pillow"], CODE)
p = 0
fx = {"resize": [], "rotate": []}
while p < len(raw):
tag, n = struct.unpack("<16sI", raw[p:p + 20]); p += 20
tag = tag.decode().strip()
data = raw[p:p + n]; p += n
if tag in ("rgb", "rgba", "rgba2"):
w, h = struct.unpack("<II", data[:8])
fx[tag] = {"w": w, "h": h, "px": data[8:]}
elif tag in ("gray", "graya", "composite"):
fx[tag] = data
elif tag == "resize":
f, mode, w, h = struct.unpack("<16s4sII", data[:28])
fx["resize"].append({"filter": f.decode().strip(), "mode": mode.decode().strip(), "w": w, "h": h, "px": data[28:]})
elif tag == "rotate":
a, e, w, h = struct.unpack("<dBII", data[:17])
fx["rotate"].append({"angle": a, "expand": bool(e), "w": w, "h": h, "px": data[17:]})
ctx.emit("imageops", fx)
+62
View File
@@ -0,0 +1,62 @@
# data/ini fixtures: random configs written by Python's configparser (interpolation off, key case kept), and
# hand-written messy files (comments, ':' delimiters, continuation lines, odd spacing, duplicates) with what
# configparser(strict=False) reads from them.
# tests/gen/ini.luau { written = { { data, canon } }, read = { { data, canon } } }
import configparser, importlib.util, io, os
_spec = importlib.util.spec_from_file_location("_data_common", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_data_common.py"))
C = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(C)
def parser():
p = configparser.ConfigParser(interpolation=None, strict=False)
p.optionxform = str
return p
def as_dict(p):
return {s: dict(p.items(s, raw=True)) for s in p.sections()}
MESSY = [
"[a]\nx=1\ny : two words \n; comment\n # indented comment\nz =\n",
"[s]\nkey = line one\n line two\n\tline three\nk2: v\n",
"# top comment\n[one]\na = 1\n[two]\nb = 2\n[one]\nc = 3\n",
"[dup]\na = 1\na = 2\n",
"[weird name with spaces]\n key with spaces = value with = sign \n",
"[s]\nurl = http://x:8080/p?a=b\npath: C:\\dir\n",
"[x]\r\nwin = yes\r\nmore = no\r\n",
"[\u00e9]\n\u4e2d = \u00fc\n",
"[a]\nk = v ; not a comment by default\n",
"[e]\nempty =\nalso:\n",
]
def generate(ctx):
rng = ctx.rng(17)
written = []
alph = "ab xyz09_-.\u00e9/=:;#"
for i in range(80):
p = parser()
for s in range(rng.randrange(1, 5)):
name = "sec%d %s" % (s, rng.choice(["", "x", "\u00e9"]))
p.add_section(name)
for k in range(rng.randrange(0, 6)):
key = "k%d%s" % (k, rng.choice(["", "_a", ".b"]))
val = "".join(rng.choice(alph) for _ in range(rng.randrange(0, 12))).strip()
if rng.random() < 0.15:
val = val + "\nsecond line" + rng.choice(["", "\nthird"])
p.set(name, key, val)
buf = io.StringIO()
p.write(buf)
data = buf.getvalue()
back = parser()
back.read_string(data)
written.append({"data": data.encode(), "canon": C.canon(as_dict(back))})
read = []
for m in MESSY:
p = parser()
p.read_string(m)
read.append({"data": m.encode(), "canon": C.canon(as_dict(p))})
ctx.emit("ini", {"written": written, "read": read})
+89
View File
@@ -0,0 +1,89 @@
# containers/IsoBmff fixtures (tools/fixtures.py): small files from ffmpeg / MP4Box / avifenc (nix) with ffprobe's
# packet lists as the reference.
# tests/gen/isobmff.luau { cases = { { name, data, streams = { { codec, kind, timescale, width?, height?,
# sampleRate?, channels?, extradata }, ... }, packets = { { stream, pos, size, dts, pts, key },
# ... } } }, tagged = { data, tags, cover }, avif = { { name, data, width, height, alpha } } }
import json, os, shutil, subprocess, tempfile
PKGS = ["ffmpeg", "gpac", "libavif"]
def sh(ctx, script, cwd):
return ctx.nix(PKGS, ["sh", "-c", "cd '%s' && %s" % (cwd, script)])
def probe(ctx, path, cwd):
out = sh(ctx, "ffprobe -v error -ignore_editlist 1 -show_streams -show_packets -of json '%s'" % path, cwd)
j = json.loads(out)
streams = []
for s in j["streams"]:
kind = s["codec_type"]
if kind == "video" and s.get("disposition", {}).get("attached_pic"):
continue
tb = s["time_base"].split("/")
e = {"codec": s["codec_name"], "kind": kind, "timescale": int(tb[1]), "index": s["index"],
"extradata": int(s.get("extradata_size", 0))}
if kind == "video":
e["width"], e["height"] = s["width"], s["height"]
if kind == "audio":
e["sampleRate"], e["channels"] = int(s["sample_rate"]), s["channels"]
streams.append(e)
index = {s["index"]: i + 1 for i, s in enumerate(streams)}
packets = []
for p in j["packets"]:
if p["stream_index"] not in index:
continue
packets.append({"stream": index[p["stream_index"]], "pos": int(p["pos"]), "size": int(p["size"]),
"dts": int(p["dts"]), "pts": int(p["pts"]), "key": "K" in p["flags"]})
for s in streams:
del s["index"]
return streams, packets
def generate(ctx):
d = tempfile.mkdtemp(prefix="isobmff-fx-")
try:
src_v = "-f lavfi -i testsrc=size=64x48:rate=10 -t 1.2"
src_a = "-f lavfi -i sine=frequency=440:sample_rate=44100 -t 1.0"
steps = [
("h264_aac.mp4", "ffmpeg -v error %s %s -c:v libx264 -bf 2 -g 5 -pix_fmt yuv420p -c:a aac -b:a 64k -ac 2 h264_aac.mp4" % (src_v, src_a)),
("faststart.mp4", "ffmpeg -v error -i h264_aac.mp4 -c copy -movflags +faststart faststart.mp4"),
("mjpeg_pcm.mov", "ffmpeg -v error %s %s -c:v mjpeg -c:a pcm_s16be mjpeg_pcm.mov" % (src_v, src_a)),
("hevc.mp4", "ffmpeg -v error %s -c:v libx265 -x265-params log-level=none -tag:v hvc1 hevc.mp4" % src_v),
("frag.mp4", "ffmpeg -v error -i h264_aac.mp4 -c copy -movflags frag_keyframe+empty_moov+default_base_moof frag.mp4"),
("mp4box_frag.mp4", "MP4Box -quiet -frag 300 -out mp4box_frag.mp4 h264_aac.mp4 >/dev/null 2>&1"),
("stz2_co64.mp4", "MP4Box -quiet -add h264_aac.mp4#video -add h264_aac.mp4#audio:stz2 -co64 -new stz2_co64.mp4 >/dev/null 2>&1"),
("alac.m4a", "ffmpeg -v error %s -c:a alac alac.m4a" % src_a),
]
cases = []
for name, cmd in steps:
sh(ctx, cmd, d)
streams, packets = probe(ctx, name, d)
with open(os.path.join(d, name), "rb") as f:
data = f.read()
cases.append({"name": name, "data": data, "streams": streams, "packets": packets})
# tags + cover
sh(ctx, "ffmpeg -v error -f lavfi -i color=red:size=8x8 -frames:v 1 -update 1 cover.png", d)
tags = {"title": "Test Title", "artist": "Some Artist", "album": "An Album", "date": "2024",
"genre": "Electronic", "comment": "a comment", "composer": "Composer X", "album_artist": "AA"}
meta = " ".join("-metadata %s='%s'" % (k, v) for k, v in tags.items())
sh(ctx, "ffmpeg -v error %s -i cover.png -map 0 -map 1 -c:a aac -b:a 48k -c:v png -disposition:v attached_pic -t 1 %s -metadata track=3/12 -metadata disc=1/2 tagged.m4a" % (src_a, meta), d)
with open(os.path.join(d, "tagged.m4a"), "rb") as f:
tagged = f.read()
with open(os.path.join(d, "cover.png"), "rb") as f:
cover = f.read()
want = {"title": "Test Title", "artist": "Some Artist", "album": "An Album", "date": "2024",
"genre": "Electronic", "comment": "a comment", "composer": "Composer X", "albumartist": "AA",
"track": "3", "tracktotal": "12", "disc": "1", "disctotal": "2"}
# AVIF stills (libavif): plain and with alpha
avif = []
sh(ctx, "ffmpeg -v error -f lavfi -i testsrc=size=40x24 -frames:v 1 still.png && "
"ffmpeg -v error -f lavfi -i 'testsrc=size=40x24,format=rgba,geq=r=r(X\\,Y):a=X*6' -frames:v 1 alpha.png", d)
for name, png, alpha in (("still.avif", "still.png", False), ("alpha.avif", "alpha.png", True)):
sh(ctx, "avifenc -q 60 -s 10 %s %s >/dev/null" % (png, name), d)
with open(os.path.join(d, name), "rb") as f:
avif.append({"name": name, "data": f.read(), "width": 40, "height": 24, "alpha": alpha})
ctx.emit("isobmff", {"cases": cases, "tagged": {"data": tagged, "tags": want, "cover": len(cover)},
"avif": avif})
finally:
shutil.rmtree(d, ignore_errors=True)
+293
View File
@@ -0,0 +1,293 @@
# JPEG fixtures (tools/fixtures.py), against libjpeg-turbo's cjpeg / djpeg / jpegtran (nix libjpeg_turbo) and Pillow.
# Ported from jpeg-luau tools/fixtures.py; the TMDB test photos are replaced by ImageMagick's built-in images.
# tests/gen/jpeg_dec.luau { { name, data, err?, refs = { { scale, width, height, crc } } | cmyk = rgb bytes } }:
# cjpeg encodes of synthetic and photo-like sources at every quality / sampling /
# progression / restart / colour setting, arithmetic-coded (sequential, progressive,
# restarts, grey, 12-bit), jpegtran transcodes, stripped DHT, odd sizes, 12-bit, CMYK /
# YCCK (Pillow); references = djpeg -dct int decodes at 1, 1/2, 1/4, 1/8 (CRC-32 of the
# RGBA8 pixels), files that must be refused (lossless).
# tests/gen/jpeg_enc.luau { { name, width, height, format, pixels, opts, want } }: raw sources and what cjpeg writes
# for the same settings (our encoder must produce the same bytes).
# tests/gen/jpeg_bench.luau 1024 x 768 baseline / progressive / arithmetic files for tools/bench.luau.
import os, shutil, subprocess, tempfile, zlib
SOURCES = r'''
import os, random, sys
from PIL import Image, ImageDraw
out = sys.argv[1]
def synth(w, h, seed):
rnd = random.Random(seed)
im = Image.new("RGB", (w, h))
px = im.load()
for y in range(h):
for x in range(w):
px[x, y] = ((x * 255) // max(1, w - 1), (y * 255) // max(1, h - 1), ((x + y) * 7) % 256)
d = ImageDraw.Draw(im)
for _ in range(6):
x0, y0 = rnd.randrange(w), rnd.randrange(h)
x1, y1 = x0 + rnd.randrange(1, w // 2 + 2), y0 + rnd.randrange(1, h // 2 + 2)
col = (rnd.randrange(256), rnd.randrange(256), rnd.randrange(256))
if rnd.random() < 0.5:
d.ellipse([x0, y0, x1, y1], fill=col)
else:
d.line([x0, y0, x1, y1], fill=col, width=rnd.randrange(1, 4))
for _ in range(w * h // 20):
x, y = rnd.randrange(w), rnd.randrange(h)
px[x, y] = (rnd.randrange(256), rnd.randrange(256), rnd.randrange(256))
return im
synth(97, 71, 1).save(os.path.join(out, "synth.ppm"))
for w, h in ((1, 1), (7, 5), (17, 9), (33, 1), (1, 33), (16, 16)):
synth(w, h, w * 100 + h).save(os.path.join(out, "s%dx%d.ppm" % (w, h)))
photo = Image.open(os.path.join(out, "photo.ppm")).convert("RGB")
photo.convert("L").save(os.path.join(out, "photo.pgm"))
with open(os.path.join(out, "photo16.ppm"), "wb") as f:
f.write(b"P6\n160 120\n65535\n")
f.write(bytes(b for v in photo.tobytes() for b in ((v * 257) >> 8, (v * 257) & 255)))
cmyk = photo.convert("CMYK")
for name, kw in (("cmyk", {}), ("cmyk_prog", {"progressive": True})):
p = os.path.join(out, "photo_" + name + ".jpg")
cmyk.save(p, "JPEG", quality=90, **kw)
data = bytearray(open(p, "rb").read())
i = data.find(b"Adobe")
assert i > 0
data[i + 11] = 2
open(os.path.join(out, "photo_" + name.replace("cmyk", "ycck") + ".jpg"), "wb").write(data)
for n in (name, name.replace("cmyk", "ycck")):
im = Image.open(os.path.join(out, "photo_" + n + ".jpg"))
raw = im.tobytes()
rgb = bytearray()
for k in range(0, len(raw), 4):
c, m, y, kk = raw[k:k + 4]
kk = 255 - kk
rgb += bytes((((255 - c) * kk + 127) // 255, ((255 - m) * kk + 127) // 255, ((255 - y) * kk + 127) // 255))
open(os.path.join(out, "photo_" + n + ".ref"), "wb").write(rgb)
'''
SCANS = {
"spectral": "0,1,2: 0-0, 0, 0;\n0: 1-5, 0, 0;\n0: 6-63, 0, 0;\n1: 1-63, 0, 0;\n2: 1-63, 0, 0;\n",
"deepsa": (
"0,1,2: 0-0, 0, 2;\n0: 1-5, 0, 3;\n1: 1-63, 0, 1;\n2: 1-63, 0, 1;\n0: 6-63, 0, 3;\n"
"0: 1-63, 3, 2;\n0: 1-63, 2, 1;\n0: 1-63, 1, 0;\n1: 1-63, 1, 0;\n2: 1-63, 1, 0;\n"
"0,1,2: 0-0, 2, 1;\n0,1,2: 0-0, 1, 0;\n"
),
"seqsplit": "0: 0-63, 0, 0;\n1: 0-63, 0, 0;\n2: 0-63, 0, 0;\n",
"dcsplit": "0: 0-0, 0, 0;\n1: 0-0, 0, 0;\n2: 0-0, 0, 0;\n0: 1-63, 0, 0;\n1: 1-63, 0, 0;\n2: 1-63, 0, 0;\n",
}
SAMPLINGS = {"444": "1x1", "422": "2x1", "420": "2x2", "411": "4x1", "440": "1x2"}
def parse_pnm(data):
"""P5 / P6 -> w, h, RGB8 bytes (16-bit samples scaled as djpeg's 12-bit output)"""
fields, pos = [], 0
while len(fields) < 4:
while data[pos:pos + 1].isspace():
pos += 1
if data[pos:pos + 1] == b"#":
while data[pos:pos + 1] != b"\n":
pos += 1
continue
s = pos
while not data[pos:pos + 1].isspace():
pos += 1
fields.append(data[s:pos])
pos += 1
magic, w, h, mx = fields[0], int(fields[1]), int(fields[2]), int(fields[3])
ch = 3 if magic == b"P6" else 1
n = w * h * ch
if mx < 256:
px = data[pos:pos + n]
else:
raw = data[pos:pos + 2 * n]
px = bytes(((raw[2 * i] << 8 | raw[2 * i + 1]) * 255 + mx // 2) // mx for i in range(n))
if ch == 1:
px = bytes(v for v in px for _ in range(3))
return w, h, px
def rgba_crc(rgb):
out = bytearray(len(rgb) // 3 * 4)
out[0::4], out[1::4], out[2::4] = rgb[0::3], rgb[1::3], rgb[2::3]
out[3::4] = b"\xff" * (len(rgb) // 3)
return zlib.crc32(bytes(out))
def generate(ctx):
bindir = os.path.dirname(ctx.nix("libjpeg_turbo", ["sh", "-c", "command -v cjpeg"]).decode().strip())
magick = ctx.nix("imagemagick", ["sh", "-c", "command -v magick"]).decode().strip()
work = tempfile.mkdtemp(prefix="formats-jpeg-")
try:
_generate(ctx, bindir, magick, work)
finally:
shutil.rmtree(work, ignore_errors=True)
def _generate(ctx, bindir, magick, work):
def run(tool, *args):
exe = tool if os.path.isabs(tool) else os.path.join(bindir, tool)
r = subprocess.run([exe] + list(args), capture_output=True)
if r.returncode != 0:
raise SystemExit("fixtures/jpeg: %s %s failed: %s" % (tool, " ".join(args), r.stderr.decode()))
return r.stdout
W = lambda n: os.path.join(work, n)
# photo-like sources: ImageMagick's built-in rose, and a plasma fractal
run(magick, "rose:", "-resize", "160x120!", W("photo.ppm"))
run(magick, "-size", "1024x768", "-seed", "7", "plasma:fractal", "-blur", "0x1", W("big.ppm"))
ctx.python(["pillow"], SOURCES.replace("sys.argv[1]", repr(work)))
for k, v in SCANS.items():
with open(W(k + ".scans"), "w") as f:
f.write(v)
SRC = {"synth": W("synth.ppm"), "photo": W("photo.ppm"), "gray": W("photo.pgm"), "photo16": W("photo16.ppm")}
for w, h in ((1, 1), (7, 5), (17, 9), (33, 1), (1, 33), (16, 16)):
SRC["%dx%d" % (w, h)] = W("s%dx%d.ppm" % (w, h))
cases = [] # (name, path, scales | "cmyk", err)
def cj(name, src, *args, scales=(1, 2, 4, 8), err=None):
out = W(name + ".jpg")
run("cjpeg", *args, "-outfile", out, SRC[src])
cases.append((name, out, scales, err))
for q in (30, 90):
for sn, s in SAMPLINGS.items():
cj("photo_q%d_%s" % (q, sn), "photo", "-quality", str(q), "-sample", s)
cj("photo_q%d_%s_prog" % (q, sn), "photo", "-quality", str(q), "-sample", s, "-progressive")
for sn, s in SAMPLINGS.items():
cj("synth_q75_%s" % sn, "synth", "-quality", "75", "-sample", s)
cj("synth_q75_%s_prog" % sn, "synth", "-quality", "75", "-sample", s, "-progressive")
cj("photo_q100_420", "photo", "-quality", "100", "-sample", "2x2")
cj("photo_q100_420_prog", "photo", "-quality", "100", "-sample", "2x2", "-progressive")
cj("photo_q5_420", "photo", "-quality", "5", "-sample", "2x2")
cj("photo_q5_444_prog", "photo", "-quality", "5", "-sample", "1x1", "-progressive")
cj("photo_optimize", "photo", "-quality", "80", "-optimize")
cj("photo_s31", "photo", "-sample", "3x1,1x1,1x1")
cj("photo_s4242", "photo", "-sample", "4x2,1x1,1x1")
cj("photo_s222111", "photo", "-sample", "2x2,2x1,1x1")
cj("photo_s111222", "photo", "-sample", "1x1,2x2,2x2")
cj("photo_s1422", "photo", "-sample", "1x4,1x2,1x2", "-progressive")
cj("synth_s2222", "synth", "-sample", "2x2,2x2,2x2", "-scans", W("seqsplit.scans"))
cj("photo_rst1", "photo", "-sample", "2x2", "-restart", "1")
cj("photo_rst3b", "photo", "-sample", "2x2", "-restart", "3B")
cj("photo_rst1b_prog", "photo", "-sample", "2x2", "-restart", "1B", "-progressive")
cj("photo_rst2_prog444", "photo", "-sample", "1x1", "-restart", "2", "-progressive")
cj("photo_gray", "photo", "-grayscale")
cj("photo_gray_prog", "photo", "-grayscale", "-progressive")
cj("photo_gray_rst", "photo", "-grayscale", "-restart", "5B")
cj("photo_rgb", "photo", "-rgb")
cj("photo_rgb_prog", "photo", "-rgb", "-progressive")
for k in SCANS:
cj("photo_scans_" + k, "photo", "-sample", "2x2", "-scans", W(k + ".scans"))
cj("synth_scans_" + k, "synth", "-sample", "1x1", "-scans", W(k + ".scans"))
cj("photo_12bit_420", "photo16", "-precision", "12", "-sample", "2x2")
cj("photo_12bit_444_prog", "photo16", "-precision", "12", "-sample", "1x1", "-progressive")
cj("photo_12bit_gray", "photo16", "-precision", "12", "-grayscale")
for k in ("1x1", "7x5", "17x9", "33x1", "1x33", "16x16"):
cj("tiny_%s_420" % k, k, "-sample", "2x2")
cj("tiny_%s_422_prog" % k, k, "-sample", "2x1", "-progressive")
cj("tiny_%s_444" % k, k, "-sample", "1x1", "-quality", "95")
cj("tiny_%s_arith" % k, k, "-sample", "2x2", "-arithmetic")
# arithmetic coding
for sn in ("444", "420", "422"):
cj("photo_arith_%s" % sn, "photo", "-arithmetic", "-sample", SAMPLINGS[sn])
cj("photo_arith_%s_prog" % sn, "photo", "-arithmetic", "-progressive", "-sample", SAMPLINGS[sn])
cj("photo_arith_q5", "photo", "-arithmetic", "-quality", "5")
cj("photo_arith_q100_prog", "photo", "-arithmetic", "-progressive", "-quality", "100")
cj("photo_arith_rst", "photo", "-arithmetic", "-restart", "1")
cj("photo_arith_rst_prog", "photo", "-arithmetic", "-progressive", "-restart", "3B")
cj("photo_arith_gray", "photo", "-arithmetic", "-grayscale")
cj("photo_arith_gray_prog", "photo", "-arithmetic", "-grayscale", "-progressive")
cj("photo_arith_rgb", "photo", "-arithmetic", "-rgb")
cj("photo_arith_12bit", "photo16", "-arithmetic", "-precision", "12", "-sample", "2x2")
cj("photo_arith_12bit_prog", "photo16", "-arithmetic", "-precision", "12", "-progressive")
cj("synth_arith_deepsa", "synth", "-arithmetic", "-sample", "1x1", "-scans", W("deepsa.scans"))
cj("synth_arith_spectral", "synth", "-arithmetic", "-sample", "2x2", "-scans", W("spectral.scans"))
cj("synth_arith_seqsplit", "synth", "-arithmetic", "-sample", "2x2", "-scans", W("seqsplit.scans"))
# refused
cj("photo_lossless", "photo", "-lossless", "1", scales=(), err="lossless")
base = W("photo_q90_420.jpg")
for name, args in (("tran_prog", ["-progressive"]), ("tran_rst", ["-restart", "2B"]), ("tran_optimize", ["-optimize"]),
("tran_arith", ["-arithmetic"]), ("tran_arith_prog", ["-arithmetic", "-progressive"])):
out = W("photo_" + name + ".jpg")
run("jpegtran", *args, "-outfile", out, base)
cases.append(("photo_" + name, out, (1, 2, 4, 8), None))
# an arithmetic file back to Huffman
out = W("photo_tran_unarith.jpg")
run("jpegtran", "-outfile", out, W("photo_arith_420.jpg"))
cases.append(("photo_tran_unarith", out, (1, 2, 4, 8), None))
# stripped DHT: the standard tables
data = open(base, "rb").read()
out, pos = bytearray(data[:2]), 2
while pos < len(data):
m = data[pos + 1]
if m == 0xDA:
out += data[pos:]
break
ln = (data[pos + 2] << 8) | data[pos + 3]
if m != 0xC4:
out += data[pos:pos + 2 + ln]
pos += 2 + ln
open(W("photo_nodht.jpg"), "wb").write(bytes(out))
cases.append(("photo_nodht", W("photo_nodht.jpg"), (1, 2, 4, 8), None))
for n in ("cmyk", "cmyk_prog", "ycck", "ycck_prog"):
cases.append(("photo_" + n, W("photo_" + n + ".jpg"), "cmyk", None))
dec = []
for name, path, scales, err in cases:
e = {"name": name, "data": open(path, "rb").read()}
if err:
e["err"] = err
if scales == "cmyk":
e["cmyk"] = open(path[:-4] + ".ref", "rb").read()
else:
refs = []
for s in scales:
args = ["-dct", "int", "-pnm"] + (["-scale", "1/%d" % s] if s != 1 else []) + [path]
w, h, px = parse_pnm(run("djpeg", *args))
refs.append({"scale": s, "width": w, "height": h, "crc": rgba_crc(px)})
e["refs"] = refs
dec.append(e)
ctx.emit("jpeg_dec", dec)
# encoder: cjpeg's bytes for the same settings
enc = []
def ce(name, src, fmt, opts, *args):
out = W("enc_" + name + ".jpg")
run("cjpeg", "-baseline", *args, "-outfile", out, SRC[src])
w, h, px = parse_pnm(open(SRC[src], "rb").read())
if fmt == "gray8":
px = px[0::3]
enc.append({"name": name, "width": w, "height": h, "format": fmt, "pixels": px, "opts": opts,
"want": open(out, "rb").read()})
for q in (10, 50, 75, 90, 100):
ce("photo_q%d_420" % q, "photo", "rgb8", {"quality": q}, "-quality", str(q), "-sample", "2x2")
for sn in ("444", "422", "420"):
ce("photo_%s" % sn, "photo", "rgb8", {"quality": 85, "subsampling": sn}, "-quality", "85", "-sample", SAMPLINGS[sn])
ce("synth_%s" % sn, "synth", "rgb8", {"quality": 85, "subsampling": sn}, "-quality", "85", "-sample", SAMPLINGS[sn])
ce("photo_%s_prog" % sn, "photo", "rgb8", {"quality": 85, "subsampling": sn, "progressive": True}, "-quality", "85", "-sample", SAMPLINGS[sn], "-progressive")
ce("synth_%s_prog" % sn, "synth", "rgb8", {"quality": 85, "subsampling": sn, "progressive": True}, "-quality", "85", "-sample", SAMPLINGS[sn], "-progressive")
ce("photo_%s_opt" % sn, "photo", "rgb8", {"quality": 85, "subsampling": sn, "optimize": True}, "-quality", "85", "-sample", SAMPLINGS[sn], "-optimize")
ce("photo_gray", "gray", "gray8", {"quality": 80}, "-quality", "80")
ce("photo_gray_prog", "gray", "gray8", {"quality": 80, "progressive": True}, "-quality", "80", "-progressive")
ce("photo_rgb_to_gray", "photo", "rgb8", {"quality": 80, "gray": True}, "-quality", "80", "-grayscale")
ce("photo_rst", "photo", "rgb8", {"quality": 75, "restart": 3}, "-quality", "75", "-sample", "2x2", "-restart", "3B")
ce("photo_rst_prog", "photo", "rgb8", {"quality": 75, "restart": 2, "progressive": True}, "-quality", "75", "-sample", "2x2", "-restart", "2B", "-progressive")
ce("photo_q100_prog444", "photo", "rgb8", {"quality": 100, "subsampling": "444", "progressive": True}, "-quality", "100", "-sample", "1x1", "-progressive")
for k in ("1x1", "7x5", "17x9", "33x1", "1x33", "16x16"):
ce("tiny_%s_420" % k, k, "rgb8", {"quality": 90}, "-quality", "90", "-sample", "2x2")
ce("tiny_%s_422_prog" % k, k, "rgb8", {"quality": 90, "subsampling": "422", "progressive": True}, "-quality", "90", "-sample", "2x1", "-progressive")
ctx.emit("jpeg_enc", enc)
SRC["big"] = W("big.ppm")
bench = []
for name, args in (("baseline 4:2:0", ["-sample", "2x2"]), ("progressive 4:2:0", ["-sample", "2x2", "-progressive"]),
("arithmetic 4:2:0", ["-sample", "2x2", "-arithmetic"]), ("baseline 4:4:4", ["-sample", "1x1"])):
out = W("bench.jpg")
run("cjpeg", "-quality", "85", *args, "-outfile", out, SRC["big"])
w, h, px = parse_pnm(run("djpeg", "-dct", "int", "-pnm", out))
bench.append({"name": name, "width": w, "height": h, "data": open(out, "rb").read(), "crc": rgba_crc(px)})
w, h, px = parse_pnm(open(SRC["big"], "rb").read())
ctx.emit("jpeg_bench", {"files": bench, "width": w, "height": h, "rgb": px})
+91
View File
@@ -0,0 +1,91 @@
# codecs/Json + data/json fixtures: the JSONTestSuite parsing corpus (nst/JSONTestSuite, pinned tarball through nix)
# with Python's json verdicts and canonical values, plus a random corpus written by Python's json.dumps in several
# styles (compact sorted, insertion order, indent 2, ensure_ascii) that the tests must parse and reproduce exactly.
# tests/gen/json_suite.luau { { name, expect = "y" | "n" | "i", data, canon? } }
# tests/gen/json_corpus.luau { { canon, compact, ordered, pretty, ascii } }
# tests/gen/json_bench.luau { text, compact } (~1 MB, indent 1; compact = sorted keys)
import importlib.util, json, os
_spec = importlib.util.spec_from_file_location("_data_common", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_data_common.py"))
C = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(C)
SUITE_URL = "https://github.com/nst/JSONTestSuite/archive/1ef36fa01286573e846ac449e8683f8833c5b26a.tar.gz"
SUITE_SHA = "0zp4gbpfxac9hfzlgjmqg70w8dhql6rbrkh8dhi3rn5aan0qqv5k"
def rand_value(rng, depth=0):
v = _rand_value(rng, depth)
if isinstance(v, float) and v.is_integer():
return int(v) # Python writes 1.0, we write 1: keep integral numbers ints
return v
def _rand_value(rng, depth=0):
r = rng.random()
if depth > 4 or r < 0.45:
k = rng.randrange(9)
if k == 0:
return None
if k == 1:
return rng.random() < 0.5
if k == 2:
return rng.randrange(-10 ** 15, 10 ** 15)
if k == 3:
return rng.randrange(-1000, 1000)
if k == 4:
return round(rng.uniform(-1e6, 1e6), rng.randrange(1, 8))
if k == 5:
return rng.uniform(-1, 1) * 10 ** rng.randrange(-4, 14)
return rand_str(rng)
if r < 0.72:
return [rand_value(rng, depth + 1) for _ in range(rng.randrange(0, 7))]
d = {}
for _ in range(rng.randrange(0, 7)):
d[rand_str(rng)] = rand_value(rng, depth + 1)
return d
ALPH = "abcxyz ABC_019\"\\/\n\t\r\b\f\x01\x1f\x7féü中文\U0001f600
"
def rand_str(rng):
return "".join(rng.choice(ALPH) for _ in range(rng.randrange(0, 12)))
def generate(ctx):
root = C.fetch(SUITE_URL, SUITE_SHA)
d = os.path.join(root, "test_parsing")
cases = []
for name in sorted(os.listdir(d)):
if not name.endswith(".json"):
continue
data = open(os.path.join(d, name), "rb").read()
c = {"name": name, "expect": name[0], "data": data}
try:
v = json.loads(data.decode("utf-8", "surrogatepass"))
c["canon"] = C.canon(v)
except Exception:
pass
cases.append(c)
ctx.emit("json_suite", cases)
rng = ctx.rng(7)
corpus = []
for _ in range(300):
v = rand_value(rng)
corpus.append({
"canon": C.canon(v),
"compact": json.dumps(v, separators=(",", ":"), sort_keys=True, ensure_ascii=False),
"ordered": json.dumps(v, separators=(",", ":"), ensure_ascii=False),
"pretty": json.dumps(v, indent=2, sort_keys=True, ensure_ascii=False),
"ascii": json.dumps(v, separators=(",", ":"), sort_keys=True),
})
ctx.emit("json_corpus", corpus)
big = [rand_value(rng) for _ in range(3000)]
text = json.dumps(big, ensure_ascii=False, indent=1)
while len(text) < 1_000_000:
big = big + big
text = json.dumps(big, ensure_ascii=False, indent=1)
ctx.emit("json_bench", {"text": text, "compact": json.dumps(big, separators=(",", ":"), sort_keys=True, ensure_ascii=False)})
+105
View File
@@ -0,0 +1,105 @@
# LZMA / LZMA2 / xz fixtures (tools/fixtures.py): deterministic corpora compressed by liblzma (Python's lzma module and
# the xz CLI): every preset and -e, lc / lp / pb variants, raw LZMA1 / LZMA2, .lzma files with and without the size
# and end marker, xz with every check type, BCJ (x86, PowerPC, ARM, ARM-Thumb, SPARC, ARM64) and delta filters,
# multi-block (--block-size), multi-stream and stream padding.
# tests/gen/lzma.luau { corpora = { [name] = bytes }, cases = { { name, kind, corpus, data, props?, dict?,
# size? } } } kind: "raw" (LZMA1), "raw2" (LZMA2), "alone", "xz"
# tests/gen/lzma_bench.luau { size, crc, xz, alone } (a ~4 MB corpus at -6)
import lzma, os, random, subprocess, sys, zlib
def text_corpus(limit):
base = os.path.dirname(os.__file__)
out = bytearray()
for name in sorted(os.listdir(base)):
if name.endswith(".py"):
with open(os.path.join(base, name), "rb") as f:
out += f.read()
if len(out) >= limit:
break
return bytes(out[:limit])
def binary_corpus(limit):
# machine code: a slice of the Python interpreter (x86-64 here; exercises the x86 BCJ filter)
with open(os.path.realpath(sys.executable), "rb") as f:
data = f.read()
if len(data) < limit:
lib = os.path.join(os.path.dirname(os.path.realpath(sys.executable)), "..", "lib")
for name in sorted(os.listdir(lib)):
p = os.path.join(lib, name)
if name.startswith("libpython") and os.path.isfile(p):
with open(p, "rb") as f:
data += f.read(limit)
break
return data[:limit]
def xz_cli(args, data):
return subprocess.run(["xz"] + args + ["-c"], input=data, capture_output=True, check=True).stdout
def generate(ctx):
rng = random.Random(7)
corpora = {
"empty": b"",
"one": b"a",
"text": text_corpus(150000),
"binary": binary_corpus(120000),
"random": rng.randbytes(20000),
"runs": b"abc" * 3000 + b"\0" * 30000 + bytes(range(256)) * 30 + b"z" * 300,
"words": b" ".join(rng.choice([b"lorem", b"ipsum", b"dolor", b"sit", b"amet", b"\xff\xfe", b"0123"]) for _ in range(20000)),
}
cases = []
def add(name, kind, corpus, data, **extra):
c = {"name": name, "kind": kind, "corpus": corpus, "data": data}
c.update(extra)
cases.append(c)
for cname, data in corpora.items():
small = cname in ("empty", "one", "random")
presets = [0, 6] if small else [0, 1, 3, 6, 9, 9 | lzma.PRESET_EXTREME]
for p in presets:
add("%s/xz-%d%s" % (cname, p & 15, "e" if p & lzma.PRESET_EXTREME else ""), "xz", cname,
lzma.compress(data, lzma.FORMAT_XZ, check=lzma.CHECK_CRC64, preset=p))
for chk, cn in ((lzma.CHECK_NONE, "none"), (lzma.CHECK_CRC32, "crc32"), (lzma.CHECK_SHA256, "sha256")):
add("%s/xz-check-%s" % (cname, cn), "xz", cname, lzma.compress(data, lzma.FORMAT_XZ, check=chk, preset=2))
# .lzma (alone): with a size (Python writes an end marker and no size; the CLI writes the same); raw streams
add("%s/alone" % cname, "alone", cname, lzma.compress(data, lzma.FORMAT_ALONE, preset=6))
for lc, lp, pb in ((3, 0, 2), (0, 2, 0), (4, 0, 4), (1, 3, 1), (0, 4, 3)):
f = [{"id": lzma.FILTER_LZMA1, "preset": 6, "lc": lc, "lp": lp, "pb": pb, "dict_size": 1 << 20}]
raw = lzma.compress(data, lzma.FORMAT_RAW, filters=f)
add("%s/raw-lc%d-lp%d-pb%d" % (cname, lc, lp, pb), "raw", cname, raw, props=bytes([(pb * 5 + lp) * 9 + lc]), size=len(data))
for lc, lp, pb in ((3, 0, 2), (0, 4, 4), (2, 2, 1)):
f = [{"id": lzma.FILTER_LZMA2, "preset": 6, "lc": lc, "lp": lp, "pb": pb}]
add("%s/raw2-lc%d-lp%d-pb%d" % (cname, lc, lp, pb), "raw2", cname, lzma.compress(data, lzma.FORMAT_RAW, filters=f))
if not small:
for fid, fname in ((lzma.FILTER_X86, "x86"), (lzma.FILTER_POWERPC, "ppc"), (lzma.FILTER_ARM, "arm"),
(lzma.FILTER_ARMTHUMB, "armthumb"), (lzma.FILTER_SPARC, "sparc")):
f = [{"id": fid}, {"id": lzma.FILTER_LZMA2, "preset": 3}]
add("%s/xz-%s" % (cname, fname), "xz", cname, lzma.compress(data, lzma.FORMAT_XZ, filters=f))
f = [{"id": lzma.FILTER_X86, "start_offset": 0x1000}, {"id": lzma.FILTER_LZMA2, "preset": 3}]
add("%s/xz-x86-start" % cname, "xz", cname, lzma.compress(data, lzma.FORMAT_XZ, filters=f))
for dist in (1, 4, 256):
f = [{"id": lzma.FILTER_DELTA, "dist": dist}, {"id": lzma.FILTER_LZMA2, "preset": 3}]
add("%s/xz-delta%d" % (cname, dist), "xz", cname, lzma.compress(data, lzma.FORMAT_XZ, filters=f))
add("%s/xz-cli-arm64" % cname, "xz", cname, xz_cli(["--arm64", "--lzma2=preset=3"], data))
add("%s/xz-cli-blocks" % cname, "xz", cname, xz_cli(["-6", "--block-size=20000"], data))
add("%s/xz-cli-x86-delta" % cname, "xz", cname, xz_cli(["--x86", "--delta=dist=2", "--lzma2=preset=1"], data))
add("%s/alone-cli" % cname, "alone", cname, xz_cli(["--format=lzma", "-3"], data))
# multi-stream + stream padding
corpora["multi"] = corpora["text"][:40000] + corpora["runs"] + b"" + corpora["one"]
multi = (lzma.compress(corpora["text"][:40000], lzma.FORMAT_XZ, preset=1) + b"\0" * 8 +
lzma.compress(corpora["runs"], lzma.FORMAT_XZ, check=lzma.CHECK_CRC32) +
lzma.compress(b"", lzma.FORMAT_XZ) + lzma.compress(b"a", lzma.FORMAT_XZ, check=lzma.CHECK_NONE) + b"\0" * 4)
add("multi/xz-streams", "xz", "multi", multi)
ctx.emit("lzma", {"corpora": corpora, "cases": cases})
# real text and machine code, little long-range repetition
bench = text_corpus(2_000_000) + binary_corpus(1_000_000)
bench = bench[:3_000_000]
ctx.emit("lzma_bench", {"size": len(bench), "crc": zlib.crc32(bench),
"xz": lzma.compress(bench, lzma.FORMAT_XZ, preset=6),
"alone": lzma.compress(bench, lzma.FORMAT_ALONE, preset=6)})
+70
View File
@@ -0,0 +1,70 @@
# LZW fixtures (tools/fixtures.py): code streams written by reference encoders, with the data they encode.
# tests/gen/lzw.luau { gif = { { name, min, codes, data } }, tiff = { { name, codes, data } } }
# gif: Pillow's GIF writer (its own LZW), the image data sub-blocks joined; data = the palette indexes
# tiff: libtiff's LZW (Pillow compression="tiff_lzw"), one strip; data = the raw 8-bit samples
import struct
CODE = r'''
import io, random, struct, sys
from PIL import Image
rng = random.Random(7)
def img(w, h, kind, ncol):
px = bytearray()
for y in range(h):
for x in range(w):
if kind == "noise":
px.append(rng.randrange(ncol))
elif kind == "flat":
px.append(3 % ncol)
else:
px.append(((x // 3) ^ (y // 5)) % ncol if rng.random() < 0.97 else rng.randrange(ncol))
return bytes(px)
out = []
for (w, h, kind, ncol) in ((1, 1, "noise", 2), (16, 16, "noise", 2), (64, 48, "pattern", 4), (64, 48, "noise", 16),
(300, 200, "pattern", 256), (300, 200, "noise", 256), (256, 200, "flat", 256), (97, 3, "noise", 128)):
data = img(w, h, kind, ncol)
im = Image.frombytes("P", (w, h), data)
im.putpalette(bytes(range(256)) * 3)
b = io.BytesIO(); im.save(b, "GIF", optimize=False, interlace=False); g = b.getvalue()
# walk to the image descriptor
p = 13 + (3 << ((g[10] & 7) + 1) if g[10] & 0x80 else 0)
while g[p] != 0x2C:
p += 2
while g[p]: p += g[p] + 1
p += 1
flags = g[p + 9]; p += 10
if flags & 0x80: p += 3 << ((flags & 7) + 1)
mn = g[p]; p += 1; codes = bytearray()
while g[p]: codes += g[p + 1:p + 1 + g[p]]; p += g[p] + 1
# Pillow may reduce the palette: decode its own image back for the indexes
back = Image.open(io.BytesIO(g)); back.load()
out.append(("gif", "%dx%d-%s-%d" % (w, h, kind, ncol), mn, bytes(codes), back.tobytes()))
t = io.BytesIO()
Image.frombytes("L", (w, h), data).save(t, "TIFF", compression="tiff_lzw", rowsperstrip=h)
tb = t.getvalue()
le = tb[:2] == b"II"; E = "<" if le else ">"
ifd = struct.unpack(E + "I", tb[4:8])[0]; n = struct.unpack(E + "H", tb[ifd:ifd + 2])[0]
tags = {}
for i in range(n):
tag, typ, cnt, val = struct.unpack(E + "HHII", tb[ifd + 2 + i * 12: ifd + 14 + i * 12])
if typ == 3 and cnt == 1:
val = struct.unpack(E + "H", tb[ifd + 10 + i * 12: ifd + 12 + i * 12])[0]
tags[tag] = (val, cnt)
assert tags[259][0] == 5 and tags[273][1] == 1, "one LZW strip"
off, cnt = tags[273][0], tags[279][0]
out.append(("tiff", "%dx%d-%s-%d" % (w, h, kind, ncol), 8, tb[off:off + cnt], data))
for kind, name, mn, codes, data in out:
sys.stdout.buffer.write(struct.pack("<4sB", kind.ljust(4).encode(), len(name)) + name.encode() + struct.pack("<BII", mn, len(codes), len(data)) + codes + data)
'''
def generate(ctx):
raw = ctx.python(["pillow"], CODE)
gif, tiff, p = [], [], 0
while p < len(raw):
kind, nl = struct.unpack("<4sB", raw[p:p + 5]); p += 5
name = raw[p:p + nl].decode(); p += nl
mn, cl, dl = struct.unpack("<BII", raw[p:p + 9]); p += 9
codes, data = raw[p:p + cl], raw[p + cl:p + cl + dl]; p += cl + dl
(gif if kind.strip() == b"gif" else tiff).append({"name": name, "min": mn, "codes": codes, "data": data})
ctx.emit("lzw", {"gif": gif, "tiff": tiff})
+198
View File
@@ -0,0 +1,198 @@
# M4A / AAC / ALAC / CAF fixtures (tools/fixtures.py). Reference tools through nix: ffmpeg (AAC + ALAC encoders and
# decoders, the CAF muxer), fdkaac (Fraunhofer's encoder: plain and HE-AAC), MP4Box (-info on our files).
# tests/gen/m4a_alac.luau ALAC in M4A / CAF from ffmpeg: { name, data, container, channels, rate, bits, frames,
# crc } where crc is the CRC-32 of the source integers as little-endian int32
# tests/gen/m4a_aac.luau AAC from ffmpeg / faac (M4A, ADTS, CAF): { name, data, container, channels, rate, frames,
# ref } with ref = ffmpeg's float decode (f32le) of the file
# tests/gen/m4a_he.luau HE-AAC / HE-AACv2 from fdkaac: { name, data, rate (the SBR output rate), ps }
# tests/gen/m4a_ours.luau our writers' files (tools/fixtures/_m4a_encode.luau over tests/audio/_encode_cases.luau)
# checked by ffmpeg: { name, crc (of our bytes), ffmpeg (decodes bit-exactly), frames,
# tags (ffprobe's view), mp4box (MP4Box -info exit status 0) }
import importlib.util, json, math, os, shutil, struct, subprocess, tempfile, zlib
# the shared signal module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml)
_spec = importlib.util.spec_from_file_location("_m4a_signal", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_m4a_signal.py"))
_sig = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_sig)
signal, pack, wav = _sig.signal, _sig.pack, _sig.wav
INPUTS = ["src/Formats/audio/m4a", "src/Formats/audio/caf", "src/Formats/codecs/Alac", "src/Formats/containers/IsoBmff",
"tests/audio/_signal.luau", "tests/audio/_encode_cases.luau", "tools/fixtures/_m4a_encode.luau",
"tools/fixtures/_m4a_signal.py"]
PKGS = ["ffmpeg", "fdk-aac-encoder", "gpac"]
def run(ctx, cmd, cwd):
return ctx.nix(PKGS, ["sh", "-c", "cd '%s' && %s" % (cwd, cmd)])
def crc_ints(ints):
return zlib.crc32(struct.pack("<%di" % len(ints), *ints))
def music(frames, channels, rate, seed):
"""a float test signal for the lossy codecs: tones with vibrato, a chord, noise bursts and clicks (transients)"""
rng = __import__("random").Random(seed)
out = []
for i in range(frames):
t = i / rate
for c in range(channels):
v = 0.25 * math.sin(2 * math.pi * (220 * (c + 1)) * t + 3 * math.sin(2 * math.pi * 5 * t))
v += 0.12 * math.sin(2 * math.pi * 660 * t) + 0.08 * math.sin(2 * math.pi * 1320.5 * t + c)
v += 0.05 * math.sin(2 * math.pi * (5000 + 300 * c) * t)
if (i // (rate // 8)) % 3 == 1:
v += 0.15 * (rng.random() * 2 - 1)
if i % (rate // 3) < 40:
v += 0.6 * (1 - (i % (rate // 3)) / 40) * (1 if (i // 7) % 2 else -1)
out.append(max(-32768, min(32767, int(round(v * 20000)))))
return out
def adts_to_caf(adts):
frames, p = [], 0
while p + 7 <= len(adts):
b1, b2, b3, b4, b5 = adts[p + 1], adts[p + 2], adts[p + 3], adts[p + 4], adts[p + 5]
hs = 7 if b1 & 1 else 9
size = ((b3 & 3) << 11) | (b4 << 3) | (b5 >> 5)
frames.append(adts[p + hs:p + size])
sfi, ch, aot = (b2 >> 2) & 15, ((b2 & 1) << 2) | (b3 >> 6), (b2 >> 6) + 1
p += size
rate = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350][sfi]
asc = struct.pack(">H", (aot << 11) | (sfi << 7) | (ch << 3))
dsi = b"\x05" + bytes([len(asc)]) + asc
dcd = b"\x04" + bytes([13 + len(dsi)]) + bytes([0x40, 0x15, 0, 0, 0]) + struct.pack(">II", 0, 0) + dsi
esd = b"\x03" + bytes([3 + len(dcd) + 3]) + b"\x00\x00\x00" + dcd + b"\x06\x01\x02"
def ber(n):
out = [n & 127]
n >>= 7
while n:
out.insert(0, 128 | (n & 127))
n >>= 7
return bytes(out)
def chunk(t, body):
return t + struct.pack(">q", len(body)) + body
desc = struct.pack(">d4sIIIII", rate, b"aac ", 2, 0, 1024, ch, 0)
pakt = struct.pack(">qqii", len(frames), len(frames) * 1024, 0, 0) + b"".join(ber(len(f)) for f in frames)
data = b"\x00\x00\x00\x00" + b"".join(frames)
return b"caff\x00\x01\x00\x00" + chunk(b"desc", desc) + chunk(b"kuki", b"\x00\x00\x00\x00" + esd) + chunk(b"pakt", pakt) + chunk(b"data", data)
def generate(ctx):
d = tempfile.mkdtemp(prefix="m4a-fx-")
try:
# --- ALAC from ffmpeg: lossless, the decode must equal the source integers
alac = []
for name, frames, ch, rate, bits, container in (
("alac16_stereo.m4a", 10000, 2, 44100, 16, "m4a"),
("alac16_mono.m4a", 4097, 1, 8000, 16, "m4a"),
("alac24_stereo.m4a", 6000, 2, 96000, 24, "m4a"),
("alac16_6ch.m4a", 5000, 6, 48000, 16, "m4a"),
("alac16_stereo.caf", 9000, 2, 44100, 16, "caf"),
):
ints = signal(frames, ch, bits, 11 + frames)
with open(os.path.join(d, "in.wav"), "wb") as f:
f.write(wav(ints, ch, rate, bits))
fmt = "-sample_fmt s32p" if bits == 24 else ""
run(ctx, "ffmpeg -v error -y -i in.wav -c:a alac %s %s" % (fmt, name), d)
with open(os.path.join(d, name), "rb") as f:
data = f.read()
alac.append({"name": name, "data": data, "container": container, "channels": ch, "rate": rate,
"bits": bits, "frames": frames, "crc": crc_ints(ints)})
ctx.emit("m4a_alac", alac)
# --- AAC from ffmpeg / faac: our decode against ffmpeg's float decode
aac = []
specs = (
# name, frames, channels, rate, encoder command (in.wav -> name)
("aac_stereo_128k.m4a", 60000, 2, 44100, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 128k -aac_pns 0 %s"),
("aac_mono_22k.m4a", 30000, 1, 22050, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 48k %s"),
("aac_51_48k.m4a", 30000, 6, 48000, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 256k %s"),
("aac_tools_40k.m4a", 50000, 2, 44100, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 40k -aac_pns 1 -aac_is 1 -aac_ms 1 -aac_tns 1 %s"),
("aac_8k_mono.m4a", 12000, 1, 8000, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 16k %s"),
("aac_96k.m4a", 30000, 2, 96000, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 192k %s"),
("aac_stereo.aac", 40000, 2, 44100, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 96k -aac_pns 0 -f adts %s"),
("fdk_stereo.aac", 40000, 2, 44100, "fdkaac -S -b 96000 -f 2 -o %s in.wav"),
("fdk_mono_32k.aac", 20000, 1, 32000, "fdkaac -S -b 48000 -f 2 -o %s in.wav"),
("fdk_stereo.m4a", 40000, 2, 48000, "fdkaac -S -b 128000 -o %s in.wav"),
("aac_stereo.caf", 30000, 2, 44100, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 96k -f adts %s.adts"),
)
for name, frames, ch, rate, cmd in specs:
ints = music(frames, ch, rate, frames + ch)
with open(os.path.join(d, "in.wav"), "wb") as f:
f.write(wav(ints, ch, rate, 16))
run(ctx, cmd % name, d)
if name.endswith(".caf"):
# ffmpeg cannot write AAC in CAF: wrap its ADTS frames ourselves (desc, kuki esds, pakt, data)
with open(os.path.join(d, name + ".adts"), "rb") as f:
adts = f.read()
with open(os.path.join(d, name), "wb") as f:
f.write(adts_to_caf(adts))
with open(os.path.join(d, name), "rb") as f:
data = f.read()
ref = run(ctx, "ffmpeg -v error -i %s -f f32le -c:a pcm_f32le -" % name, d)
container = "caf" if name.endswith(".caf") else ("adts" if name.endswith(".aac") else "m4a")
aac.append({"name": name, "data": data, "container": container, "channels": ch, "rate": rate,
"frames": len(ref) // (4 * ch), "ref": ref})
ctx.emit("m4a_aac", aac)
# HE-AAC (SBR) and HE-AACv2 (SBR + PS) from fdkaac: we decode the AAC-LC core at the core rate
he = []
for name, frames, ch, rate, prof, br in (("he_aac.m4a", 48000, 2, 44100, 5, 48000), ("he_aac_v2.m4a", 48000, 2, 44100, 29, 32000), ("he_aac.aac", 48000, 2, 44100, 5, 48000)):
ints = music(frames, ch, rate, 99)
with open(os.path.join(d, "in.wav"), "wb") as f:
f.write(wav(ints, ch, rate, 16))
run(ctx, "fdkaac -S -p %d -b %d %s -o %s in.wav" % (prof, br, "-f 2" if name.endswith(".aac") else "", name), d)
with open(os.path.join(d, name), "rb") as f:
he.append({"name": name, "data": f.read(), "rate": rate, "ps": prof == 29})
ctx.emit("m4a_he", he)
# --- our writers, checked by ffmpeg / ffprobe / MP4Box
luau = os.environ.get("LUAU") or shutil.which("luau")
if luau:
out = subprocess.run([luau, "tools/fixtures/_m4a_encode.luau"], capture_output=True, check=True, cwd=ctx.root).stdout
else:
out = ctx.nix("luau", ["luau", os.path.join(ctx.root, "tools/fixtures/_m4a_encode.luau")])
ours = []
meta = {
# name -> frames, channels, bits, seed (tests/audio/_encode_cases.luau)
"ours_alac16_stereo": (4096 * 3 + 1234, 2, 16, 1), "ours_alac16_mono": (5000, 1, 16, 2),
"ours_alac24_stereo": (9000, 2, 24, 3), "ours_alac16_6ch": (4500, 6, 16, 4),
"ours_alac20_stereo": (3000, 2, 20, 5), "ours_caf_alac16": (7000, 2, 16, 6),
"ours_caf_pcm16": (3000, 2, 16, 7), "ours_caf_pcm24": (2000, 1, 24, 8),
}
for line in out.decode().split("\n"):
if not line.strip():
continue
name, hx = line.split(" ", 1)
if hx.startswith("ERROR"):
raise RuntimeError("m4a fixtures: our encoder failed on %s: %s" % (name, hx))
data = bytes.fromhex(hx)
ext = "caf" if "caf" in name else "m4a"
path = name + "." + ext
with open(os.path.join(d, path), "wb") as f:
f.write(data)
frames, ch, bits, seed = meta[name]
ints = signal(frames, ch, bits, seed)
wide = bits > 16
want = pack([v << (32 - bits) for v in ints] if wide else ints, 32 if wide else 16)
got = run(ctx, "ffmpeg -v error -i %s -f %s -" % (path, "s32le" if wide else "s16le"), d)
fbytes = (4 if wide else 2) * ch
# ffmpeg's CAF reader drops the pakt remainder from a partial last ALAC packet (also on its own files):
# accept its output when it is an exact prefix of ours
ok = got == want or (ext == "caf" and len(got) > 0 and want.startswith(got))
probe = json.loads(run(ctx, "ffprobe -v error -show_format -show_streams -of json %s" % path, d))
tags = {k.lower(): v for k, v in probe["format"].get("tags", {}).items()}
mp4box = True
if ext == "m4a":
try:
run(ctx, "MP4Box -info %s >/dev/null 2>&1" % path, d)
except subprocess.CalledProcessError:
mp4box = False
ours.append({"name": name, "crc": zlib.crc32(data), "ffmpeg": ok, "frames": len(got) // fbytes,
"tags": tags, "mp4box": mp4box,
"codec": probe["streams"][0]["codec_name"]})
ctx.emit("m4a_ours", ours)
finally:
shutil.rmtree(d, ignore_errors=True)
+94
View File
@@ -0,0 +1,94 @@
# data/msgpack fixtures: random values packed by Python's msgpack (through nix): every integer width, floats,
# str / bin of every length class, nested arrays / maps (int and str keys), nil / bools, timestamps (all three
# widths) and other ext types; with the canonical form of msgpack's own unpacking.
# tests/gen/msgpack.luau { safe = { { data, canon } }, wide = { { data, canon, canonStr } } }
# safe: no integers past 2^53, no integral floats: our decode + encode must give the same bytes
# wide: 64-bit integers too (canon = as doubles, canonStr = exact text via bigInts = "string")
import importlib.util, os, pickle
_spec = importlib.util.spec_from_file_location("_data_common", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_data_common.py"))
C = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(C)
BODY = r'''
import msgpack, pickle, random, sys, datetime
rng = random.Random(5)
def rint(wide):
k = rng.randrange(8)
lim = [2**5, 2**7, 2**8, 2**15, 2**16, 2**31, 2**32, 2**53 - 1][k]
if wide and rng.random() < 0.4:
lim = rng.choice([2**63 - 1, 2**64 - 1])
v = rng.randrange(0, lim + 1)
if lim == 2**63 - 1 and rng.random() < 0.5:
v = -v - 1
return v
v = rng.randrange(-lim, lim + 1)
return v
def rstr():
n = rng.choice([0, 1, 5, 31, 32, 200, 255, 256, 300])
alph = "abé中\U0001f600 \n\x00"
return "".join(rng.choice(alph) for _ in range(n))[:n]
def rval(d, wide):
r = rng.random()
if d > 3 or r < 0.5:
k = rng.randrange(9)
if k == 0: return None
if k == 1: return rng.random() < 0.5
if k in (2, 3): return rint(wide)
if k == 4:
f = rng.uniform(-1e6, 1e6) * 10 ** rng.randrange(-5, 5)
return f if not f.is_integer() else f + 0.5
if k == 5: return rstr()
if k == 6: return rng.randbytes(rng.choice([0, 3, 255, 256]))
if k == 7:
sec = rng.choice([rng.randrange(0, 2**32), rng.randrange(0, 2**34), rng.randrange(-2**35, 2**37)])
us = rng.choice([0, rng.randrange(1000000)])
return msgpack.Timestamp(sec, us * 1000)
return msgpack.ExtType(rng.randrange(0, 128), rng.randbytes(rng.choice([1, 2, 4, 8, 16, 3, 300])))
if r < 0.75:
return [rval(d + 1, wide) for _ in range(rng.choice([0, 1, 3, 15, 16, 20] if d < 2 else [0, 1, 3]))]
m = {}
for _ in range(rng.choice([0, 1, 3, 15, 16, 17] if d < 2 else [0, 1, 3])):
key = rint(False) if rng.random() < 0.3 else "".join(rng.choice("abc\u00e9") for _ in range(rng.randrange(6)))
m[key] = rval(d + 1, wide)
return m
def conv(v):
if isinstance(v, msgpack.Timestamp):
return v.to_datetime()
if isinstance(v, msgpack.ExtType):
return ["ext", v.code, v.data]
if isinstance(v, list):
return [conv(x) for x in v]
if isinstance(v, dict):
return {k: conv(x) for k, x in v.items()}
return v
def cstr(v):
if isinstance(v, int) and not isinstance(v, bool) and abs(v) >= 2**53:
return str(v)
if isinstance(v, list):
return [cstr(x) for x in v]
if isinstance(v, dict):
return {k: cstr(x) for k, x in v.items()}
return v
out = {"safe": [], "wide": []}
# the 32-bit length forms, once each
for v in ["x" * 70000, b"y" * 70000, list(range(70000)), {i: i for i in range(70000)}]:
data = msgpack.packb(v, use_bin_type=True)
out["safe"].append({"data": data, "canon": canon(msgpack.unpackb(data, strict_map_key=False))})
for i in range(250):
v = rval(0, False)
data = msgpack.packb(v, use_bin_type=True)
back = msgpack.unpackb(data, raw=False, strict_map_key=False)
out["safe"].append({"data": data, "canon": canon(conv(back))})
for i in range(150):
v = rval(0, True)
data = msgpack.packb(v, use_bin_type=True)
back = conv(msgpack.unpackb(data, raw=False, strict_map_key=False))
out["wide"].append({"data": data, "canon": canon(back), "canonStr": canon(cstr(back))})
sys.stdout.buffer.write(pickle.dumps(out, protocol=4))
'''
def generate(ctx):
out = pickle.loads(C.python(ctx, ["msgpack"], BODY))
ctx.emit("msgpack", out)
+257
View File
@@ -0,0 +1,257 @@
# OBJ fixtures (tools/fixtures.py): OBJ / MTL files written here (materials, textures, objects and groups, n-gons,
# negative indices, vertex colours, continuation lines, comments, lines and points, a concave polygon) and files
# exported by assimp (from generated PLY meshes), with reference values from assimp (`assimp info`: meshes, materials,
# vertices, faces, bounds) and trimesh (area, triangle count, bounds).
# tests/gen/obj_cases.luau { name, data, files = { name -> bytes }, assimp = {...}, trimesh = {...}, polygonArea? }
# tests/gen/obj_xcheck.luau our encoder's output for every case (tools/fixtures/_obj_encode.luau), read back by assimp
# and trimesh: { name, assimp, trimesh, want = the original's values }
import importlib.util, math, os, struct
INPUTS = ["src/Formats/model/obj", "tools/fixtures/_model_ref.py", "tools/fixtures/_obj_encode.luau"]
def ref_module(ctx):
spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def png_1x1():
import zlib
def ch(t, d):
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d))
return b"\x89PNG\r\n\x1a\n" + ch(b"IHDR", struct.pack(">IIBBBBB", 1, 1, 8, 6, 0, 0, 0)) + ch(b"IDAT", zlib.compress(b"\0\xff\0\0\xff")) + ch(b"IEND", b"")
def fmt(v):
return "%.6g" % v
CUBE = """# a cube: one object, two groups, two materials, a textured quad
mtllib cube.mtl
o Cube
v 0 0 0
v 1 0 0
v 1 1 0
v 0 1 0
v 0 0 1
v 1 0 1
v 1 1 1
v 0 1 1
vt 0 0
vt 1 0
vt 1 1
vt 0 1
vn 0 0 1
g top
usemtl red
s 1
f 5/1/1 6/2/1 7/3/1 8/4/1
g bottom
usemtl blue
f 1 4 3 2
f 1 2 6 5
f 2 3 7 6
f 3 4 8 7
f 4 1 5 8
"""
CUBE_MTL = """# materials
newmtl red
Ka 0.1 0.1 0.1
Kd 1 0 0
Ks 0.5 0.5 0.5
Ns 50
illum 2
map_Kd -s 2 2 1 -o 0.5 0 0 textures/tex.png
map_Bump -bm 0.5 normal.png
newmtl blue
Kd 0 0 1
d 0.5
Pr 0.25
Pm 1
Ke 0.1 0.2 0.3
"""
def sphere(rng, rings, segs, colors=False):
vs, fs = [], []
for i in range(rings - 1): # no poles: assimp turns degenerate triangles into lines
th = math.pi * (i + 1) / rings
for j in range(segs):
ph = 2 * math.pi * j / segs
vs.append((math.sin(th) * math.cos(ph), math.cos(th), math.sin(th) * math.sin(ph)))
for i in range(rings - 2):
for j in range(segs):
a, b = i * segs + j, i * segs + (j + 1) % segs
c, d = a + segs, b + segs
fs.append((a, c, d, b))
return vs, fs
def random_obj(rng):
vs, fs = sphere(rng, 6, 9)
lines = ["# random sphere: quads, triangles, pentagons, negative indices, vertex colours, continuations"]
for v in vs:
lines.append("v %s %s %s %s %s %s" % (fmt(v[0]), fmt(v[1]), fmt(v[2]), fmt(rng.random()), fmt(rng.random()), fmt(rng.random())))
for k in range(len(vs)):
lines.append("vt %s %s" % (fmt(rng.random()), fmt(rng.random())))
lines.append("vn 0 1 0")
lines.append("vn 1 0 0")
lines.append("g sphere")
n = len(vs)
for i, f in enumerate(fs):
if i % 7 == 0:
# negative (relative) indices
lines.append("f " + " ".join("%d/%d" % (v - n, v - n) for v in f))
elif i % 7 == 1:
lines.append("f " + " ".join("%d//%d" % (v + 1, 1 + i % 2) for v in f))
elif i % 7 == 2:
lines.append("f %d/%d/1 %d/%d/2 \\\n %d/%d/1 %d/%d/2" % (f[0] + 1, f[0] + 1, f[1] + 1, f[1] + 1, f[2] + 1, f[2] + 1, f[3] + 1, f[3] + 1))
elif i % 7 == 3:
lines.append("f %d %d %d" % (f[0] + 1, f[1] + 1, f[2] + 1))
lines.append("f %d %d %d" % (f[0] + 1, f[2] + 1, f[3] + 1))
else:
lines.append("f " + " ".join("%d/%d" % (v + 1, v + 1) for v in f))
# a convex pentagon and a hexagon
base = len(vs)
for k in range(5):
lines.append("v %s %s 2" % (fmt(math.cos(2 * math.pi * k / 5)), fmt(math.sin(2 * math.pi * k / 5))))
lines.append("g pentagon")
lines.append("f " + " ".join(str(base + k + 1) for k in range(5)))
return "\n".join(lines) + "\n"
def concave():
# an L-shaped hexagon (area 3) and a U-shaped octagon (area 5) in the xz plane, as n-gons
L = [(0, 0), (2, 0), (2, 1), (1, 1), (1, 2), (0, 2)]
U = [(3, 0), (6, 0), (6, 2), (5, 2), (5, 1), (4, 1), (4, 2), (3, 2)]
lines = ["o shapes"]
for x, z in L + U:
lines.append("v %d 0 %d" % (x, z))
lines.append("f " + " ".join(str(k + 1) for k in range(len(L))))
lines.append("f " + " ".join(str(len(L) + k + 1) for k in range(len(U))))
area = sum(abs(sum(p[i][0] * p[(i + 1) % len(p)][1] - p[(i + 1) % len(p)][0] * p[i][1] for i in range(len(p)))) / 2 for p in (L, U))
return "\n".join(lines) + "\n", area
def lines_points():
return """o wire
v 0 0 0
v 1 0 0
v 1 1 0
v 0 1 0
l 1 2 3 4 1
p 1 3
f 1 2 3
"""
def ply_torus(rng, R=2.0, r=0.5, a=24, b=12):
vs, fs = [], []
for i in range(a):
for j in range(b):
u, v = 2 * math.pi * i / a, 2 * math.pi * j / b
vs.append(((R + r * math.cos(v)) * math.cos(u), r * math.sin(v), (R + r * math.cos(v)) * math.sin(u)))
for i in range(a):
for j in range(b):
p, q = i * b + j, ((i + 1) % a) * b + j
p2, q2 = i * b + (j + 1) % b, ((i + 1) % a) * b + (j + 1) % b
fs.append((p, p2, q2, q))
head = "ply\nformat ascii 1.0\nelement vertex %d\nproperty float x\nproperty float y\nproperty float z\nelement face %d\nproperty list uchar int vertex_indices\nend_header\n" % (len(vs), len(fs))
body = "".join("%r %r %r\n" % v for v in vs) + "".join("4 %d %d %d %d\n" % f for f in fs)
return (head + body).encode()
def fan_area(text):
# the area of every face fan-triangulated (an exact reference in double precision)
text = text.replace("\\\n", " ")
V, A = [], 0.0
for l in text.split("\n"):
w = l.split()
if not w:
continue
if w[0] == "v":
V.append([float(x) for x in w[1:4]])
elif w[0] == "f":
idx = []
for c in w[1:]:
v = int(c.split("/")[0])
idx.append(v - 1 if v > 0 else len(V) + v)
for k in range(1, len(idx) - 1):
a, b, c = V[idx[0]], V[idx[k]], V[idx[k + 1]]
e1 = [b[i] - a[i] for i in range(3)]
e2 = [c[i] - a[i] for i in range(3)]
x, y, z = e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]
A += math.sqrt(x * x + y * y + z * z) / 2
return A
def generate(ctx):
M = ref_module(ctx)
rng = ctx.rng(11)
tmp = M.tempdir()
cases = []
def add(name, data, files=None, **extra):
path = os.path.join(tmp, name)
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "wb") as f:
f.write(data)
for fn, fd in (files or {}).items():
p = os.path.join(tmp, fn)
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, "wb") as f:
f.write(fd)
c = {"name": name, "data": data, "files": files or {}, "path": path, "fanArea": fan_area(data.decode())}
c.update(extra)
cases.append(c)
png = png_1x1()
add("cube.obj", CUBE.encode(), {"cube.mtl": CUBE_MTL.encode(), "textures/tex.png": png, "normal.png": png})
# assimp joins mixed-attribute corners differently (136 vertices where the file has 101 distinct v/vt/vn): no
# vertex count check for this one
# and trimesh gets its area wrong (12.60 for 12.52: mixed index forms?): only the exact fan area here
add("random.obj", random_obj(rng).encode(), noVertexCount=True, noTrimesh=True)
text, area = concave()
add("concave.obj", text.encode(), polygonArea=area)
add("wire.obj", lines_points().encode(), noTrimesh=True)
# assimp's OBJ exporter, from a PLY torus
ply = os.path.join(tmp, "torus.ply")
with open(ply, "wb") as f:
f.write(ply_torus(rng))
out = os.path.join(tmp, "torus_assimp.obj")
ctx.nix("assimp", ["assimp", "export", ply, out])
files = {}
if os.path.exists(out[:-4] + ".mtl"):
files["torus_assimp.mtl"] = open(out[:-4] + ".mtl", "rb").read()
add("torus_assimp.obj", open(out, "rb").read(), files)
paths = [c["path"] for c in cases]
infos = M.assimp_info(ctx, paths)
tm = M.trimesh_metrics(ctx, [c["path"] for c in cases if not c.get("noTrimesh")])
k = 0
for c, info in zip(cases, infos):
c["assimp"] = info
if not c.get("noTrimesh"):
c["trimesh"] = tm[k]
k += 1
for c in cases:
del c["path"]
ctx.emit("obj_cases", cases)
# the reference tools read our encoder's output (decode -> encode in Luau, then assimp / trimesh)
ours = M.luau_encode(ctx, "tools/fixtures/_obj_encode.luau")
xtmp = M.tempdir()
names = []
for name, data in sorted(ours.items()):
p = os.path.join(xtmp, name)
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, "wb") as f:
f.write(data)
if name.endswith(".obj"):
names.append(name)
xinfos = M.assimp_info(ctx, [os.path.join(xtmp, n) for n in names])
xtm = M.trimesh_metrics(ctx, [os.path.join(xtmp, n) for n in names])
ctx.emit("obj_xcheck", [{"name": n, "assimp": a, "trimesh": t} for n, a, t in zip(names, xinfos, xtm)])
+343
View File
@@ -0,0 +1,343 @@
# OFF fixtures (tools/fixtures.py).
# tests/gen/off_scenes.luau scenes for the encoder (STCNOFF mesh, polygons under a TRS node, a float-colour point
# cloud, polygons with face colours) with the expected file content, computed here
# tests/gen/off.luau cases: OFF files written by trimesh and by hand here (COFF with integer / float colours,
# RGB / RGBA, NOFF, STOFF, STCNOFF, face colours of both kinds, colormap indices, comments
# everywhere, counts on the header line, CRLF and tabs, n-gons, a point cloud), with the
# values they were written from (positions cross-checked with trimesh's OFF reader);
# `ours`: our encoder's output (luau CLI: tools/fixtures/_off_encode.luau) read back by
# trimesh, assimp and a small reader here, as verdicts
import json, math, os, shutil, struct, subprocess, tempfile, zlib
INPUTS = ["src/Formats/model/off", "tools/fixtures/_off_reference.py", "tools/fixtures/_off_encode.luau"]
def f32(x):
return struct.unpack("<f", struct.pack("<f", x))[0]
def pack(fmt, vals):
return struct.pack("<%d%s" % (len(vals), fmt), *vals)
def crc(b):
return zlib.crc32(b)
def fan(faces):
tris, fot = [], []
for i, f in enumerate(faces):
for k in range(1, len(f) - 1):
tris += [f[0], f[k], f[k + 1]]
fot.append(i)
return tris, fot
def random_faces(rng, nv, nf, sizes=(3, 4, 5, 6)):
out = []
for _ in range(nf):
s = rng.choice(sizes)
out.append(rng.sample(range(nv), s))
return out
def colour_tokens(rng, kind, comps):
if kind == "int":
vals = [rng.randrange(256) for _ in range(comps)]
return [str(v) for v in vals], vals
vals = [round(rng.random(), 6) for _ in range(comps)]
return ["%.6f" % v for v in vals], vals
def colour_bytes(kind, vals_list, comps_list):
"""the expected COLOR_0 / faceColors bytes (unorm8 x4 or f32 x4; missing alpha / colour = full)"""
out = b""
for vals, comps in zip(vals_list, comps_list):
if kind == "int":
v = list(vals) + [255] * (4 - len(vals))
out += bytes(v)
else:
v = list(vals) + [1.0] * (4 - len(vals))
out += pack("f", v)
return out
def make_case(rng, name, nv, faces, normals=False, st=False, vcol=None, fcol=None, style=None):
"""an OFF file and the values it holds. vcol / fcol = (kind "int" | "float" | "map", comps)"""
style = style or {}
kw = ("ST" if st else "") + ("C" if vcol else "") + ("N" if normals else "") + "OFF"
nl = "\r\n" if style.get("crlf") else "\n"
sep = "\t" if style.get("tabs") else " "
lines = []
if style.get("comments"):
lines.append("# a comment before the keyword")
if style.get("inline"):
lines.append("%s %d %d 0" % (kw, nv, len(faces)))
else:
lines.append(kw + (" # keyword" if style.get("comments") else ""))
if style.get("comments"):
lines += ["", "# counts next"]
lines.append("%d %d %d" % (nv, len(faces), 0))
pos, nrm, tex, vc_vals, vc_comps = [], [], [], [], []
for i in range(nv):
p = [f32(rng.uniform(-10, 10)) for _ in range(3)]
pos += p
toks = [repr(c) for c in p]
if normals:
v = [rng.uniform(-1, 1) for _ in range(3)]
ln = math.sqrt(sum(c * c for c in v))
n = [f32(c / ln) for c in v]
nrm += n
toks += [repr(c) for c in n]
if vcol:
comps = vcol[1] if vcol[1] != "mixed" else rng.choice((3, 4))
ct, cv = colour_tokens(rng, vcol[0], comps)
toks += ct
vc_vals.append(cv)
vc_comps.append(comps)
if st:
t = [f32(rng.random()) for _ in range(2)]
tex += t
toks += [repr(c) for c in t]
line = sep.join(toks)
if style.get("comments") and i % 3 == 0:
line += " # vertex %d" % i
lines.append(line)
if style.get("comments") and i == 1:
lines.append("")
lines.append(" # an indented comment line")
fc_vals, fc_comps, any_fc, colormap = [], [], False, False
for i, f in enumerate(faces):
toks = [str(len(f))] + [str(x) for x in f]
if fcol and not (fcol[1] == "some" and i % 3 == 1):
if fcol[0] == "map":
toks.append(str(rng.randrange(16)))
colormap = True
fc_vals.append([])
fc_comps.append(0)
else:
comps = 4 if fcol[1] in (4, "some") else 3
ct, cv = colour_tokens(rng, fcol[0], comps)
toks += ct
fc_vals.append(cv)
fc_comps.append(comps)
any_fc = True
else:
fc_vals.append([])
fc_comps.append(0)
lines.append(sep.join(toks))
data = (nl.join(lines) + nl).encode()
exp = {"name": name, "data": data, "keyword": kw, "vertices": nv, "faces": len(faces), "pos_crc": crc(pack("f", pos))}
if normals:
exp["nrm_crc"] = crc(pack("f", nrm))
if st:
exp["tex_crc"] = crc(pack("f", tex))
if vcol:
exp["color"] = {"type": "unorm8" if vcol[0] == "int" else "f32", "crc": crc(colour_bytes(vcol[0], vc_vals, vc_comps))}
if any_fc:
exp["faceColors"] = {"type": "unorm8" if fcol[0] == "int" else "f32", "crc": crc(colour_bytes(fcol[0], fc_vals, fc_comps))}
if colormap:
exp["colormap"] = True
tris, fot = fan(faces)
exp["allTri"] = all(len(f) == 3 for f in faces)
exp["tris"] = len(tris) // 3
exp["tri_crc"] = crc(pack("I", tris))
exp["fot_crc"] = crc(pack("I", fot))
exp["corners_crc"] = crc(pack("I", [c for f in faces for c in f]))
exp["sizes_crc"] = crc(pack("I", [len(f) for f in faces]))
return exp
def handmade(rng):
cases = []
cases.append(make_case(rng, "coff-int.off", 30, random_faces(rng, 30, 20), vcol=("int", 4), fcol=("int", 3), style={"comments": True}))
cases.append(make_case(rng, "coff-float-rgb.off", 25, random_faces(rng, 25, 12, (3, 4)), vcol=("float", 3), fcol=("float", 4)))
cases.append(make_case(rng, "coff-mixed-alpha.off", 12, random_faces(rng, 12, 6, (3,)), vcol=("int", "mixed")))
cases.append(make_case(rng, "noff.off", 20, random_faces(rng, 20, 10, (3,)), normals=True))
cases.append(make_case(rng, "stoff.off", 16, random_faces(rng, 16, 9), st=True, style={"tabs": True}))
cases.append(make_case(rng, "stcnoff.off", 18, random_faces(rng, 18, 11), normals=True, st=True, vcol=("int", 4), fcol=("int", "some")))
cases.append(make_case(rng, "inline-crlf.off", 10, random_faces(rng, 10, 5, (3, 4)), style={"inline": True, "crlf": True}))
cases.append(make_case(rng, "colormap.off", 9, random_faces(rng, 9, 4, (3, 4)), fcol=("map", 1)))
cases.append(make_case(rng, "points.off", 40, []))
cases.append(make_case(rng, "big-ngon.off", 300, [list(range(300)), list(range(0, 300, 7))]))
return cases
# --- encoder scenes
def mat_trs(node):
x, y, z, w = node.get("rotation", [0, 0, 0, 1])
sx, sy, sz = node.get("scale", [1, 1, 1])
tx, ty, tz = node.get("translation", [0, 0, 0])
r = [
[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)],
]
return [[r[i][0] * sx, r[i][1] * sy, r[i][2] * sz, (tx, ty, tz)[i]] for i in range(3)]
def scenes(rng):
out = []
n = 12
pos = [f32(rng.uniform(-5, 5)) for _ in range(n * 3)]
nrm = [f32(rng.uniform(-1, 1)) for _ in range(n * 3)]
col = [rng.randrange(256) for _ in range(n * 4)]
tex = [f32(rng.random()) for _ in range(n * 2)]
idx = [rng.randrange(n) for _ in range(30)]
faces = [idx[i:i + 3] for i in range(0, 30, 3)]
vlines = [pos[i * 3:i * 3 + 3] + nrm[i * 3:i * 3 + 3] + col[i * 4:i * 4 + 4] + tex[i * 2:i * 2 + 2] for i in range(n)]
out.append({"name": "mesh", "nodes": [{"mesh": 1}], "roots": [1], "meshes": [{"prims": [{
"mode": "triangles", "count": n, "indices": pack("I", idx),
"attrs": {"POSITION": ["f32", 3, pack("f", pos)], "NORMAL": ["f32", 3, pack("f", nrm)], "COLOR_0": ["unorm8", 4, bytes(col)],
"TEXCOORD_0": ["f32", 2, pack("f", tex)]}}]}],
"encodings": {"default": {"keyword": "STCNOFF", "vertices": vlines, "faces": faces},
"plain": {"keyword": "OFF", "vertices": [v[:3] for v in vlines], "faces": faces}}})
pv = [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 2, 0, 0, 3, 0.5, 0, 2.5, 1.5, 0.2, 1.5, 1.2, 0.1, 0, 0, 1]
q = [rng.uniform(-1, 1) for _ in range(4)]
ln = math.sqrt(sum(c * c for c in q))
node = {"mesh": 1, "translation": [1, 2, 3], "rotation": [c / ln for c in q], "scale": [2, 0.5, 1.5]}
m = mat_trs(node)
w = [[m[i][0] * pv[k * 3] + m[i][1] * pv[k * 3 + 1] + m[i][2] * pv[k * 3 + 2] + m[i][3] for i in range(3)] for k in range(9)]
pf = [[0, 1, 2, 3], [1, 4, 5, 6, 7, 2], [0, 3, 8]]
out.append({"name": "polys", "nodes": [node], "roots": [1], "meshes": [{"prims": [{
"mode": "polygons", "count": 9, "indices": pack("I", [c for f in pf for c in f]), "faces": pack("I", [len(f) for f in pf]),
"attrs": {"POSITION": ["f32", 3, pack("f", pv)]}}]}],
"encodings": {"default": {"keyword": "OFF", "vertices": w, "faces": pf, "tol": 1e-5}}})
n = 20
pos = [f32(rng.uniform(-50, 50)) for _ in range(n * 3)]
col = [f32(rng.random()) for _ in range(n * 4)]
out.append({"name": "cloud", "nodes": [{"mesh": 1}], "roots": [1], "meshes": [{"prims": [{
"mode": "points", "count": n, "attrs": {"POSITION": ["f32", 3, pack("f", pos)], "COLOR_0": ["f32", 4, pack("f", col)]}}]}],
"encodings": {"default": {"keyword": "COFF", "vertices": [pos[i * 3:i * 3 + 3] + col[i * 4:i * 4 + 4] for i in range(n)], "faces": []}}})
# face colours on planar polygons (assimp triangulates non-planar ones its own way)
pf = [[0, 1, 2, 3], [1, 4, 5, 6, 7, 2], [0, 3, 8]]
pos = [f32(v) for v in pv]
fc = [rng.randrange(256) for _ in range(12)]
out.append({"name": "facecolors", "nodes": [{"mesh": 1}], "roots": [1], "meshes": [{"prims": [{
"mode": "polygons", "count": 9, "indices": pack("I", [c for f in pf for c in f]), "faces": pack("I", [len(f) for f in pf]),
"attrs": {"POSITION": ["f32", 3, pack("f", pos)]}, "faceColors": bytes(fc)}]}],
"encodings": {"default": {"keyword": "OFF", "vertices": [pos[i * 3:i * 3 + 3] for i in range(9)], "faces": pf,
"faceColors": [fc[i * 4:i * 4 + 4] for i in range(3)]}}})
return out
def parse_off(text):
"""a small OFF reader for checking our output: keyword, vertex rows (numbers), faces, face colour rows"""
rows = []
for line in text.split("\n"):
line = line.split("#", 1)[0].strip()
if line:
rows.append(line.split())
kw = rows[0][0]
nv, nf = int(rows[1][0]), int(rows[1][1])
verts = [[float(x) for x in r] for r in rows[2:2 + nv]]
faces, fcols = [], []
for r in rows[2 + nv:2 + nv + nf]:
k = int(r[0])
faces.append([int(x) for x in r[1:1 + k]])
fcols.append([float(x) for x in r[1 + k:]])
return kw, verts, faces, fcols, len(rows) == 2 + nv + nf
def check_ours(text, want):
kw, verts, faces, fcols, exact_rows = parse_off(text)
if kw != want["keyword"]:
return False, "keyword %s, want %s" % (kw, want["keyword"])
if not exact_rows:
return False, "extra or missing rows"
if len(verts) != len(want["vertices"]):
return False, "vertex count"
tol = want.get("tol", 0)
for got, exp in zip(verts, want["vertices"]):
if len(got) != len(exp):
return False, "vertex row length %d, want %d" % (len(got), len(exp))
for g, e in zip(got, exp):
if (abs(f32(g) - f32(e)) > tol * max(1, abs(e))) if tol else f32(g) != f32(e):
return False, "vertex value %r, want %r" % (g, e)
if faces != want["faces"]:
return False, "faces differ"
if "faceColors" in want:
if [list(map(int, c)) for c in fcols] != want["faceColors"]:
return False, "face colours differ"
elif any(fcols):
return False, "unexpected face colours"
return True, "%d vertices, %d faces" % (len(verts), len(faces))
def luau_cmd():
exe = shutil.which("luau")
return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
def assimp_faces(ctx, path):
txt = ctx.nix("assimp", ["assimp", "info", path]).decode(errors="replace")
for line in txt.split("\n"):
if line.startswith("Faces:"):
return int(line.split()[1])
return None
def generate(ctx):
rng = ctx.rng(53)
tmp = tempfile.mkdtemp(prefix="formats-off-")
try:
_generate(ctx, rng, tmp)
finally:
shutil.rmtree(tmp, ignore_errors=True)
def _generate(ctx, rng, tmp):
sc = scenes(rng)
ctx.emit("off_scenes", sc)
cases = handmade(rng)
for c in cases:
with open(os.path.join(tmp, c["name"]), "wb") as f:
f.write(c["data"])
make = ["trimesh-ico.off", "trimesh-capsule.off"]
enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_off_encode.luau")], capture_output=True, check=True, cwd=ctx.root).stdout.decode()
ours = []
byname = {s["name"]: s for s in sc}
for line in enc.split("\n"):
if not line.strip():
continue
label, hexdata = line.split(" ", 1)
scene_name, encoding = label.split("/")
fn = "ours-%s-%s.off" % (scene_name, encoding)
data = bytes.fromhex(hexdata.strip())
with open(os.path.join(tmp, fn), "wb") as f:
f.write(data)
ours.append((label, fn, data, byname[scene_name]["encodings"][encoding]))
names = [c["name"] for c in cases if c["vertices"] > 0] + make + [o[1] for o in ours]
code = open(os.path.join(ctx.root, "tools", "fixtures", "_off_reference.py")).read()
try:
ref = json.loads(ctx.python(["trimesh", "numpy"], code, input=json.dumps({"dir": tmp, "make": make, "read": names}).encode()))
except subprocess.CalledProcessError as e:
raise RuntimeError("off reference: " + e.stderr.decode(errors="replace")[-3000:])
# trimesh agrees with the values the files were written from
for c in cases:
r = ref.get(c["name"])
if r:
assert r["vertices"] == c["vertices"] and r["pos_crc"] == c["pos_crc"], c["name"]
for name in make:
with open(os.path.join(tmp, name), "rb") as f:
data = f.read()
r = ref[name]
tris = [x for f in r["faces"] for x in f]
cases.append({"name": name, "data": data, "keyword": "OFF", "vertices": r["vertices"], "faces": r["tris"], "pos_crc": r["pos_crc"],
"allTri": True, "tris": r["tris"], "tri_crc": crc(pack("I", tris)), "corners_crc": crc(pack("I", tris)),
"sizes_crc": crc(pack("I", [3] * r["tris"]))})
verdicts = []
for label, fn, data, want in ours:
ok, detail = check_ours(data.decode(), want)
r = ref.get(fn)
if ok and r and not want.get("tol"):
exp = pack("f", [c for v in want["vertices"] for c in v[:3]])
if r["pos_crc"] != crc(exp):
ok, detail = False, "trimesh reads other positions"
if ok and want["faces"]:
got = assimp_faces(ctx, os.path.join(tmp, fn))
exp_f = sum(len(f) - 2 for f in want["faces"])
if got != exp_f:
ok, detail = False, "assimp reads %s faces, want %d" % (got, exp_f)
verdicts.append({"name": label, "ok": ok, "detail": detail})
ctx.emit("off", {"cases": cases, "ours": verdicts})
+48
View File
@@ -0,0 +1,48 @@
# The CELT encoder reference check (tools/fixtures.py): runs tools/fixtures/_opus_encode.luau (our encoder over
# tests/audio/_opus_cases.luau), then the reference tools through nix: opusdec --float (libopus), opusinfo (stream
# structure), ffmpeg (an independent Ogg / Opus reader).
# tests/gen/opus_celt.luau { { name, crc (of our bytes), opusdec (f32le 48 kHz decode), opusinfo (exit 0),
# ffmpeg (decoded), ffmpegFrames, comments (opusinfo's user comments) } }
import os, re, shutil, subprocess, tempfile, zlib
INPUTS = ["src/Formats/audio/opus", "src/Formats/codecs/Mdct", "src/Formats/containers/Ogg",
"tests/audio/_opus_cases.luau", "tools/fixtures/_opus_encode.luau"]
def generate(ctx):
luau = os.environ.get("LUAU") or shutil.which("luau")
script = os.path.join(ctx.root, "tools/fixtures/_opus_encode.luau")
if luau:
out = subprocess.run([luau, script], capture_output=True, check=True, cwd=ctx.root).stdout
else:
out = ctx.nix("luau", ["luau", script])
d = tempfile.mkdtemp(prefix="opus-celt-fx-")
try:
cases = []
for line in out.decode().split("\n"):
if not line.strip():
continue
name, hx = line.split(" ", 1)
if hx.startswith("ERROR"):
raise RuntimeError("opus_celt fixtures: our encoder failed on %s: %s" % (name, hx))
data = bytes.fromhex(hx)
path = os.path.join(d, name + ".opus")
with open(path, "wb") as f:
f.write(data)
raw = os.path.join(d, name + ".f32")
ctx.nix("opus-tools", ["opusdec", "--quiet", "--float", "--rate", "48000", path, raw])
with open(raw, "rb") as f:
pcm = f.read()
info = subprocess.run(["nix", "shell", "nixpkgs#opus-tools", "-c", "opusinfo", path], capture_output=True)
text = info.stdout.decode(errors="replace")
comments = {}
for m in re.finditer(r"^\s*([A-Za-z]+)=(.*)$", text, re.M):
comments[m.group(1).lower()] = m.group(2)
ok = info.returncode == 0 and "WARNING" not in text and "ERROR" not in text.upper().replace("ERRORS", "")
ff = subprocess.run(["nix", "shell", "nixpkgs#ffmpeg", "-c", "ffmpeg", "-v", "error", "-i", path, "-f", "f32le", "-ac", "1", "-"], capture_output=True)
cases.append({"name": name, "crc": zlib.crc32(data), "opusdec": pcm, "opusinfo": ok,
"ffmpeg": ff.returncode == 0 and len(ff.stderr) == 0, "ffmpegFrames": len(ff.stdout) // 4,
"comments": comments})
ctx.emit("opus_celt", cases)
finally:
shutil.rmtree(d, ignore_errors=True)
+66
View File
@@ -0,0 +1,66 @@
# Playlist fixtures (tools/fixtures.py): playlist/m3u, playlist/pls, playlist/xspf, codecs/Url, codecs/Text.
# tests/gen/playlist_url.luau random relative references resolved by Python's urllib.parse.urljoin (RFC 3986)
# tests/gen/playlist_cp1252.luau every Windows-1252 byte decoded by Python's cp1252 codec (undefined bytes: U+FFFD)
# tests/gen/playlist_cases.luau playlists written here (M3U8 with EXTINF, PLS via configparser-style lines, XSPF via
# xml.etree.ElementTree) with the entries they hold: { url, title?, duration? }
import random, urllib.parse, xml.etree.ElementTree as ET
BASES = ["http://a/b/c/d;p?q", "https://host.example/lists/m.m3u8", "http://h/x/", "https://cdn.example/a/b/c/list.pls",
"http://a"]
SEGS = ["g", "h", "..", ".", "music", "a b", "x.mp3", "s;p", "%41", "ü"]
def ref(rng):
parts = [rng.choice(SEGS) for _ in range(rng.randrange(1, 5))]
r = "/".join(parts)
k = rng.randrange(6)
if k == 0:
r = "/" + r
elif k == 1:
r = "./" + r
if rng.random() < 0.2:
r += "?y=" + rng.choice(SEGS)
if rng.random() < 0.15:
r += "#" + rng.choice(["s", "f/../x"])
return r
def generate(ctx):
rng = random.Random(8)
cases = []
for _ in range(400):
base = rng.choice(BASES)
r = ref(rng)
if " " in r or "ü" in r or (base == "http://a" and r.startswith(".")):
continue # raw spaces / UTF-8 are encoded first by the playlist code; urljoin keeps a leading "." here
cases.append([r, base, urllib.parse.urljoin(base, r)])
ctx.emit("playlist_url", cases)
ctx.emit("playlist_cp1252", [[b, bytes([b]).decode("cp1252", errors="replace")] for b in range(0x80, 0x100)])
out = []
for n in range(12):
ents = []
for i in range(rng.randrange(1, 9)):
e = {"url": "http://media.example/%d/track%d.mp3" % (n, i)}
if rng.random() < 0.8:
e["title"] = rng.choice(["Song %d" % i, "Björk – Jóga", "A, B & C", "x <y> \"z\""])
if rng.random() < 0.7:
e["duration"] = rng.randrange(1, 600)
ents.append(e)
m3u = "#EXTM3U\n" + "".join(("#EXTINF:%d,%s\n" % (e.get("duration", -1), e.get("title", "")) if ("title" in e or "duration" in e) else "") + e["url"] + "\n" for e in ents)
pls = "[playlist]\n" + "".join("File%d=%s\n" % (i + 1, e["url"]) + ("Title%d=%s\n" % (i + 1, e["title"]) if "title" in e else "") + ("Length%d=%d\n" % (i + 1, e.get("duration", -1))) for i, e in enumerate(ents)) + "NumberOfEntries=%d\nVersion=2\n" % len(ents)
root = ET.Element("playlist", {"version": "1", "xmlns": "http://xspf.org/ns/0/"})
ET.SubElement(root, "title").text = "List %d" % n
tl = ET.SubElement(root, "trackList")
for e in ents:
t = ET.SubElement(tl, "track")
ET.SubElement(t, "location").text = e["url"]
if "title" in e:
ET.SubElement(t, "title").text = e["title"]
if "duration" in e:
ET.SubElement(t, "duration").text = str(e["duration"] * 1000)
xspf = ET.tostring(root, encoding="UTF-8", xml_declaration=True)
expect = [{k: v for k, v in e.items()} for e in ents]
# M3U loses a title when there is no EXTINF text; PLS keeps only what it wrote
out.append({"name": "list%d" % n, "m3u": m3u, "pls": pls, "xspf": xspf, "title": "List %d" % n, "entries": expect})
ctx.emit("playlist_cases", out)
+83
View File
@@ -0,0 +1,83 @@
# data/plist fixtures: random values written by Python's plistlib as XML (insertion order) and as binary, with the
# canonical form of plistlib's own reading (aware UTC datetimes; UIDs as ["uid", n]).
# tests/gen/plist.luau { { xml, binary, canon } } (our XML writer must reproduce xml byte for byte)
# + wide = { { binary, canon } } (UIDs, 64-bit integers: binary only)
import datetime, importlib.util, os, plistlib
_spec = importlib.util.spec_from_file_location("_data_common", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_data_common.py"))
C = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(C)
def rval(rng, d, wide):
r = rng.random()
if d > 3 or r < 0.5:
k = rng.randrange(8)
if k == 0:
return rng.random() < 0.5
if k == 1:
return rng.randrange(-2 ** 31, 2 ** 31)
if k == 2:
return rng.choice([rng.randrange(-2 ** 63, 2 ** 63), rng.randrange(0, 2 ** 64)]) if wide else rng.randrange(-2 ** 53, 2 ** 53)
if k == 3:
f = rng.uniform(-1e6, 1e6) * 10 ** rng.randrange(-5, 5)
return f if not f.is_integer() else f + 0.5
if k == 4:
return "".join(rng.choice("ab <>&\"'é中\U0001f600\n\t") for _ in range(rng.randrange(0, 12)))
if k == 5:
return rng.randbytes(rng.choice([0, 1, 2, 3, 40, 57, 58, 200]))
if k == 6:
return datetime.datetime.fromtimestamp(rng.randrange(-2 ** 31, 2 ** 33), datetime.timezone.utc)
return plistlib.UID(rng.randrange(0, 2 ** 32)) if wide else "x"
if r < 0.75:
return [rval(rng, d + 1, wide) for _ in range(rng.randrange(0, 6))]
return {"".join(rng.choice("abcé <&") for _ in range(rng.randrange(0, 6))): rval(rng, d + 1, wide) for _ in range(rng.randrange(0, 6))}
def conv(v):
if isinstance(v, plistlib.UID):
return ["uid", v.data]
if isinstance(v, list):
return [conv(x) for x in v]
if isinstance(v, dict):
return {k: conv(x) for k, x in v.items()}
return v
def generate(ctx):
rng = ctx.rng(21)
cases = []
for i in range(200):
v = rval(rng, 0, False)
if not isinstance(v, (list, dict)) and rng.random() < 0.5:
v = {"root": v}
xml = plistlib.dumps(v, fmt=plistlib.FMT_XML, sort_keys=False, aware_datetime=True)
binary = plistlib.dumps(v, fmt=plistlib.FMT_BINARY, sort_keys=False, aware_datetime=True)
back = plistlib.loads(xml, aware_datetime=True)
assert C.canon(conv(plistlib.loads(binary, aware_datetime=True))) == C.canon(conv(back))
cases.append({"xml": xml, "binary": binary, "canon": C.canon(conv(back))})
wide = []
for i in range(80):
v = [rval(rng, 1, True) for _ in range(4)]
binary = plistlib.dumps(v, fmt=plistlib.FMT_BINARY, aware_datetime=True)
wide.append({"binary": binary, "canon": C.canon(conv(plistlib.loads(binary, aware_datetime=True)))})
# a hand-written XML plist with whitespace, comments, hex integers, odd reals, a bare value root
extra = b"""<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<!-- comment -->
<dict>
<key>hex</key> <integer>0x1F</integer>
<key>neg</key> <integer>-5</integer>
<key>real</key> <real> 2.5e3 </real>
<key>data</key> <data>
AAEC
AwQ=
</data>
<key>empty</key> <string/>
<key>date</key> <date>2001-01-01T00:00:00Z</date>
</dict>
</plist>
"""
ctx.emit("plist", {"cases": cases, "wide": wide, "extra": extra,
"extraCanon": C.canon(plistlib.loads(extra, aware_datetime=True))})
+192
View File
@@ -0,0 +1,192 @@
# PLY fixtures (tools/fixtures.py).
# tests/gen/ply_scenes.luau scenes for the encoder (an indexed mesh with every attribute kind and custom properties,
# polygons under a TRS node, a float-colour point cloud, two meshes merged, a mirrored
# polygon) with the expected vertex properties (names, types, values) and faces, computed
# here
# tests/gen/ply.luau cases: PLY files written by plyfile (ascii / binary LE / BE, every property type, odd
# orders, n-gons up to 300 vertices, face properties and lists, edge / material / tristrips
# elements, comments, obj_info, point clouds, a 65k-vertex sphere) and by assimp (OFF / OBJ
# -> PLY), each with reference values from plyfile mapped to the Scene conventions;
# `ours`: our encoder's output (luau CLI: tools/fixtures/_ply_encode.luau) read back by
# plyfile and assimp, as verdicts
import json, math, os, shutil, struct, subprocess, tempfile
INPUTS = ["src/Formats/model/ply", "tools/fixtures/_ply_reference.py", "tools/fixtures/_ply_encode.luau"]
def f32(x):
return struct.unpack("<f", struct.pack("<f", x))[0]
def pack(fmt, vals):
return struct.pack("<%d%s" % (len(vals), fmt), *vals)
def mat_trs(node):
x, y, z, w = node.get("rotation", [0, 0, 0, 1])
sx, sy, sz = node.get("scale", [1, 1, 1])
tx, ty, tz = node.get("translation", [0, 0, 0])
r = [
[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)],
]
return [[r[i][0] * sx, r[i][1] * sy, r[i][2] * sz, (tx, ty, tz)[i]] for i in range(3)]
def quat(rng):
q = [rng.uniform(-1, 1) for _ in range(4)]
ln = math.sqrt(sum(c * c for c in q))
return [c / ln for c in q]
def scenes(rng):
out = []
# an indexed mesh with every attribute kind
W, H = 5, 4
n = W * H
pos = [f32(v) for y in range(H) for x in range(W) for v in (x, y, rng.uniform(-1, 1))]
nrm = []
for _ in range(n):
v = [rng.uniform(-1, 1) for _ in range(3)]
ln = math.sqrt(sum(c * c for c in v))
nrm += [f32(c / ln) for c in v]
col = [rng.randrange(256) for _ in range(n * 4)]
tex = [f32(rng.random()) for _ in range(n * 2)]
quality = [f32(rng.uniform(0, 10)) for _ in range(n)]
label = [rng.randrange(65536) for _ in range(n)]
idx = []
for y in range(H - 1):
for x in range(W - 1):
a = y * W + x
idx += [a, a + 1, a + W + 1, a, a + W + 1, a + W]
out.append({"name": "mesh", "nodes": [{"mesh": 1}], "roots": [1], "meshes": [{"prims": [{
"mode": "triangles", "count": n, "indices": pack("I", idx),
"attrs": {"POSITION": ["f32", 3, pack("f", pos)], "NORMAL": ["f32", 3, pack("f", nrm)], "COLOR_0": ["unorm8", 4, bytes(col)],
"TEXCOORD_0": ["f32", 2, pack("f", tex)], "_quality": ["f32", 1, pack("f", quality)], "_label": ["u16", 1, pack("H", label)]}}]}],
"props": [("x", "<f4", pos[0::3]), ("y", "<f4", pos[1::3]), ("z", "<f4", pos[2::3]), ("nx", "<f4", nrm[0::3]), ("ny", "<f4", nrm[1::3]),
("nz", "<f4", nrm[2::3]), ("red", "u1", col[0::4]), ("green", "u1", col[1::4]), ("blue", "u1", col[2::4]), ("alpha", "u1", col[3::4]),
("s", "<f4", tex[0::2]), ("t", "<f4", tex[1::2]), ("label", "<u2", label), ("quality", "<f4", quality)],
"faces": [idx[i:i + 3] for i in range(0, len(idx), 3)]})
# polygons under a TRS node (positions transformed: compared with a tolerance)
pv = [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 2, 0, 0, 3, 0.5, 0, 2.5, 1.5, 0.2, 1.5, 1.2, 0.1, 0, 0, 1]
node = {"mesh": 1, "translation": [1, 2, 3], "rotation": quat(rng), "scale": [2, 0.5, 1.5]}
m = mat_trs(node)
w = [[f32(m[i][0] * pv[k * 3] + m[i][1] * pv[k * 3 + 1] + m[i][2] * pv[k * 3 + 2] + m[i][3]) for i in range(3)] for k in range(9)]
out.append({"name": "polys", "nodes": [node], "roots": [1], "meshes": [{"prims": [{
"mode": "polygons", "count": 9, "indices": pack("I", [0, 1, 2, 3, 1, 4, 5, 6, 7, 2, 0, 3, 8]), "faces": pack("I", [4, 6, 3]),
"attrs": {"POSITION": ["f32", 3, pack("f", pv)]}}]}],
"props": [("x", "<f4", [p[0] for p in w], 1e-5), ("y", "<f4", [p[1] for p in w], 1e-5), ("z", "<f4", [p[2] for p in w], 1e-5)],
"faces": [[0, 1, 2, 3], [1, 4, 5, 6, 7, 2], [0, 3, 8]], "transformed": True})
# a point cloud with float colours (alpha all 1: not written)
n = 30
pos = [f32(rng.uniform(-50, 50)) for _ in range(n * 3)]
col = [f32(rng.random()) if k % 4 != 3 else 1.0 for k in range(n * 4)]
out.append({"name": "cloud", "nodes": [{"mesh": 1}], "roots": [1], "meshes": [{"prims": [{
"mode": "points", "count": n, "attrs": {"POSITION": ["f32", 3, pack("f", pos)], "COLOR_0": ["f32", 4, pack("f", col)]}}]}],
"props": [("x", "<f4", pos[0::3]), ("y", "<f4", pos[1::3]), ("z", "<f4", pos[2::3]), ("red", "<f4", col[0::4]),
("green", "<f4", col[1::4]), ("blue", "<f4", col[2::4])]})
# two meshes merged: the second has no colours (filled with opaque white: alpha not written)
pa = [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0]
ca = [10, 20, 30, 255, 40, 50, 60, 255, 70, 80, 90, 255, 100, 110, 120, 255]
pb = [5, 5, 5, 6, 5, 5, 6, 6, 5, 5, 6, 5.5]
allp = pa + pb
allc = ca + [255] * 16
out.append({"name": "multi", "nodes": [{"mesh": 1}, {"mesh": 2}], "roots": [1, 2], "meshes": [
{"prims": [{"mode": "triangles", "count": 4, "indices": pack("I", [0, 1, 2, 0, 2, 3]),
"attrs": {"POSITION": ["f32", 3, pack("f", pa)], "COLOR_0": ["unorm8", 4, bytes(ca)]}}]},
{"prims": [{"mode": "polygons", "count": 4, "indices": pack("I", [0, 1, 2, 3]), "faces": pack("I", [4]),
"attrs": {"POSITION": ["f32", 3, pack("f", pb)]}}]}],
"props": [("x", "<f4", allp[0::3]), ("y", "<f4", allp[1::3]), ("z", "<f4", allp[2::3]), ("red", "u1", allc[0::4]),
("green", "u1", allc[1::4]), ("blue", "u1", allc[2::4])],
"faces": [[0, 1, 2], [0, 2, 3], [4, 5, 6, 7]]})
# a mirrored polygon: the winding reverses (first corner kept)
pm = [0, 0, 0, 1, 0, 0, 1.5, 1, 0, 0.5, 1.5, 0, -0.5, 1, 0]
out.append({"name": "mirror", "nodes": [{"mesh": 1, "scale": [-1, 1, 1]}], "roots": [1], "meshes": [{"prims": [{
"mode": "polygons", "count": 5, "indices": pack("I", [0, 1, 2, 3, 4]), "faces": pack("I", [5]),
"attrs": {"POSITION": ["f32", 3, pack("f", pm)]}}]}],
"props": [("x", "<f4", [-v for v in pm[0::3]]), ("y", "<f4", pm[1::3]), ("z", "<f4", pm[2::3])],
"faces": [[0, 4, 3, 2, 1]], "transformed": True})
for sc in out:
sc["props"] = [{"name": p[0], "dtype": p[1], "values": struct.pack("<%d%s" % (len(p[2]), {"<f4": "f", "u1": "B", "<u2": "H"}[p[1]]), *p[2]),
**({"tol": p[3]} if len(p) > 3 else {})} for p in sc["props"]]
if "faces" in sc:
sc["faceSizes"] = pack("I", [len(f) for f in sc["faces"]])
sc["faceCorners"] = pack("I", [c for f in sc["faces"] for c in f])
return out
def luau_cmd():
exe = shutil.which("luau")
return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
def assimp_faces(ctx, path):
txt = ctx.nix("assimp", ["assimp", "info", path]).decode(errors="replace")
for line in txt.split("\n"):
if line.startswith("Faces:"):
return int(line.split()[1])
return None
def generate(ctx):
rng = ctx.rng(47)
tmp = tempfile.mkdtemp(prefix="formats-ply-")
try:
_generate(ctx, rng, tmp)
finally:
shutil.rmtree(tmp, ignore_errors=True)
def _generate(ctx, rng, tmp):
sc = scenes(rng)
ctx.emit("ply_scenes", sc)
make = ["cube-le.ply", "colors-be.ply", "ascii-mixed.ply", "points-le.ply", "points-ascii-float.ply", "types-be.ply", "big-le.ply", "tristrips.ply"]
# assimp conversions: OFF -> PLY (ascii), OBJ -> PLY (binary)
off = "OFF\n6 3 0\n" + "".join("%r %r %r\n" % (f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5))) for _ in range(6))
off += "3 0 1 2\n4 1 3 4 2\n3 4 5 2\n"
obj = "".join("v %r %r %r\n" % (f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5))) for _ in range(8))
obj += "vn 0 0 1\nf 1//1 2//1 3//1 4//1\nf 5//1 6//1 7//1\nf 1//1 8//1 5//1\n"
with open(os.path.join(tmp, "in.off"), "w") as f:
f.write(off)
with open(os.path.join(tmp, "in.obj"), "w") as f:
f.write(obj)
ctx.nix("assimp", ["assimp", "export", os.path.join(tmp, "in.off"), os.path.join(tmp, "assimp-off.ply"), "-fply"])
ctx.nix("assimp", ["assimp", "export", os.path.join(tmp, "in.obj"), os.path.join(tmp, "assimp-obj-b.ply"), "-fplyb"])
refs = make + ["assimp-off.ply", "assimp-obj-b.ply"]
enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_ply_encode.luau")], capture_output=True, check=True, cwd=ctx.root).stdout.decode()
ours = []
byname = {s["name"]: s for s in sc}
for line in enc.split("\n"):
if not line.strip():
continue
label, hexdata = line.split(" ", 1)
scene_name, encoding = label.split("/")
s = byname[scene_name]
fn = "ours-%s-%s.ply" % (scene_name, encoding)
with open(os.path.join(tmp, fn), "wb") as f:
f.write(bytes.fromhex(hexdata.strip()))
ours.append({"name": label, "file": fn, "props": [{**p, "values": p["values"].hex()} for p in s["props"]], "faces": s.get("faces")})
code = open(os.path.join(ctx.root, "tools", "fixtures", "_ply_reference.py")).read()
try:
res = json.loads(ctx.python(["plyfile", "numpy"], code, input=json.dumps({"dir": tmp, "make": make, "ref": refs, "ours": ours}).encode()))
except subprocess.CalledProcessError as e:
raise RuntimeError("ply reference: " + e.stderr.decode(errors="replace")[-3000:])
verdicts = []
for o in ours:
ok, detail = res["ours"][o["name"]]
if o["faces"]:
want = sum(len(f) - 2 for f in o["faces"])
got = assimp_faces(ctx, os.path.join(tmp, o["file"]))
if got != want:
ok, detail = False, "assimp reads %s faces, want %d" % (got, want)
verdicts.append({"name": o["name"], "ok": ok, "detail": detail})
cases = []
for name in refs:
with open(os.path.join(tmp, name), "rb") as f:
data = f.read()
r = res["ref"][name]
c = {"name": name, "data": data}
c.update({k: v for k, v in r.items() if v is not None})
cases.append(c)
ctx.emit("ply", {"cases": cases, "ours": verdicts})
+93
View File
@@ -0,0 +1,93 @@
# Netpbm fixtures (tools/fixtures.py): files written by ImageMagick (P1-P7, ASCII / binary, 8 / 16-bit, PAM tuple
# types, PFM both byte orders) and a few hand-written edge cases (comments, packed P1 digits, odd maxvals, PAM
# GRAYSCALE_ALPHA / BLACKANDWHITE); references = ImageMagick's RGBA decodes (8-bit, and 16-bit for 16-bit files).
# tests/gen/pnm.luau { { name, data, width, height, rgba8 (bytes), rgba16? (bytes, big-endian), tol, floats? } }
import os, random, shutil, struct, subprocess, tempfile
def generate(ctx):
magick = ctx.nix("imagemagick", ["sh", "-c", "command -v magick"]).decode().strip()
work = tempfile.mkdtemp(prefix="formats-pnm-")
try:
_generate(ctx, magick, work)
finally:
shutil.rmtree(work, ignore_errors=True)
def _generate(ctx, magick, work):
rng = random.Random(3)
W = lambda n: os.path.join(work, n)
def run(*args, inp=None):
r = subprocess.run([magick] + list(args), input=inp, capture_output=True)
if r.returncode != 0:
raise SystemExit("fixtures/pnm: magick %s failed: %s" % (" ".join(args), r.stderr.decode()))
return r.stdout
# a 16-bit RGBA source with gradients, noise and transparency, written as a 16-bit PAM for ImageMagick
w, h = 37, 23
src = bytearray()
for y in range(h):
for x in range(w):
r = (x * 65535) // (w - 1)
g = (y * 65535) // (h - 1)
b = rng.randrange(65536)
a = 65535 if (x + y) % 5 else (x * 3000) % 65536
src += struct.pack(">HHHH", r, g, b, a)
open(W("src.pam"), "wb").write(b"P7\nWIDTH %d\nHEIGHT %d\nDEPTH 4\nMAXVAL 65535\nTUPLTYPE RGB_ALPHA\nENDHDR\n" % (w, h) + bytes(src))
cases = []
def ref(path, wide, tol=0, floats=None, name=None):
data = open(path, "rb").read()
c = {"name": name or os.path.basename(path), "data": data, "tol": tol}
info = run(path, "-format", "%w %h", "info:").decode().split()
c["width"], c["height"] = int(info[0]), int(info[1])
c["rgba8"] = run(path, "-depth", "8", "rgba:-")
if wide:
c["rgba16"] = run(path, "-depth", "16", "-endian", "MSB", "rgba:-")
if floats is not None:
c["floats"] = floats
cases.append(c)
variants = [
("p1.pbm", ["-colorspace", "gray", "-threshold", "50%", "-compress", "none"], "pbm:", False),
("p4.pbm", ["-colorspace", "gray", "-threshold", "50%"], "pbm:", False),
("p2.pgm", ["-colorspace", "gray", "-depth", "8", "-compress", "none"], "pgm:", False),
("p5.pgm", ["-colorspace", "gray", "-depth", "8"], "pgm:", False),
("p5-16.pgm", ["-colorspace", "gray", "-depth", "16"], "pgm:", True),
("p2-16.pgm", ["-colorspace", "gray", "-depth", "16", "-compress", "none"], "pgm:", True),
("p3.ppm", ["-alpha", "off", "-depth", "8", "-compress", "none"], "ppm:", False),
("p6.ppm", ["-alpha", "off", "-depth", "8"], "ppm:", False),
("p6-16.ppm", ["-alpha", "off", "-depth", "16"], "ppm:", True),
("p3-16.ppm", ["-alpha", "off", "-depth", "16", "-compress", "none"], "ppm:", True),
("rgba.pam", ["-depth", "8"], "pam:", False),
("rgba16.pam", ["-depth", "16"], "pam:", True),
("rgb.pam", ["-alpha", "off", "-depth", "8"], "pam:", False),
("gray.pam", ["-alpha", "off", "-colorspace", "gray", "-depth", "8"], "pam:", False),
("graya.pam", ["-colorspace", "gray", "-depth", "8"], "pam:", False),
("graya16.pam", ["-colorspace", "gray", "-depth", "16"], "pam:", True),
("bw.pam", ["-alpha", "off", "-colorspace", "gray", "-threshold", "50%", "-type", "bilevel"], "pam:", False),
]
for name, args, prefix, wide in variants:
run(W("src.pam"), *args, prefix + W(name))
ref(W(name), wide)
for endian in ("LSB", "MSB"):
for col in ("rgb", "gray"):
name = "%s-%s.pfm" % (col, endian)
extra = ["-colorspace", "gray"] if col == "gray" else []
run(W("src.pam"), "-alpha", "off", *extra, "-endian", endian, "pfm:" + W(name))
fl = run(W(name), "-depth", "32", "-define", "quantum:format=floating-point", "-endian", "LSB", "rgba:-")
ref(W(name), False, tol=1, floats=fl)
# hand-written edge cases (references from ImageMagick too)
def hand(name, data, wide=False, tol=0):
open(W(name), "wb").write(data)
ref(W(name), wide, tol=tol)
hand("comments.ppm", b"P6\n# a comment\n3 # inline\n2\n#another\n255\n" + bytes(range(18)))
hand("packed.pbm", b"P1\n5 3\n10101\n01010\n1 1 1 0 0\n")
hand("maxval1000.pgm", b"P2\n4 2\n1000\n0 250 500 1000\n999 1 333 750\n", wide=True, tol=1)
hand("maxval7.ppm", b"P3 2 2 7 0 1 2 3 4 5 6 7 7 7 0 0\n", tol=1)
hand("p4-odd.pbm", b"P4\n11 3\n" + bytes([0b10101010, 0b11100000, 0b00001111, 0b00100000, 0b11111111, 0b11000000]))
hand("graya-hand.pam", b"P7\nWIDTH 2\nHEIGHT 2\nDEPTH 2\nMAXVAL 255\nTUPLTYPE GRAYSCALE_ALPHA\nENDHDR\n" + bytes([0, 255, 100, 128, 200, 0, 255, 255]))
ctx.emit("pnm", cases)
+389
View File
@@ -0,0 +1,389 @@
# PSD fixtures (tools/fixtures.py): PSD / PSB files written here (a small writer below: every colour mode, 1/8/16/32
# bits, raw / RLE / ZIP / ZIP-with-prediction channels, groups, pass-through, clipping, masks, fill opacity, hidden
# layers, Unicode names, every blend mode) and one written by ImageMagick, all read by psd-tools (the reference):
# tests/gen/psd.luau { cases = { { name, data, width, height, composite (RGBA of psd-tools' merged image),
# layers = { { name, left, top, width, height, crc (RGBA of psd-tools' layer.topil()) } },
# flat (psd-tools' composite of the layers, RGBA) } } }
# tests/gen/psd_ours.luau { checks = { { label, ok } } }: our encoder's PSD (tools/fixtures/_ours.luau, run with
# luau) read by psd-tools, compared with the layers and the flattened image we wrote.
import json, os, random, shutil, struct, subprocess, tempfile, zlib
INPUTS = ["src/Formats/layered/psd", "src/Formats/codecs/Blend.luau", "src/Formats/ops/LayerOps.luau", "tools/fixtures/_ours.luau"]
BLEND = ["norm", "diss", "dark", "mul ", "idiv", "lbrn", "dkCl", "lite", "scrn", "div ", "lddg", "lgCl", "over", "sLit",
"hLit", "vLit", "lLit", "pLit", "hMix", "diff", "smud", "fsub", "fdiv", "hue ", "sat ", "colr", "lum "]
def packbits(row):
out, i, n = bytearray(), 0, len(row)
while i < n:
j = i
while j + 1 < n and row[j + 1] == row[i] and j - i < 127:
j += 1
if j - i >= 2:
out += bytes([257 - (j - i + 1), row[i]])
i = j + 1
else:
k = i
while k < n and k - i < 128 and not (k + 2 < n and row[k] == row[k + 1] == row[k + 2]):
k += 1
out += bytes([k - i - 1]) + row[i:k]
i = k
return bytes(out)
def bytes_per(depth):
return {8: 1, 16: 2, 32: 4}[depth]
def channel_data(plane, w, h, depth, comp, psb=False):
"""plane: bytes (rows of w samples, big endian) -> compression code + data"""
rb = w * bytes_per(depth)
if w == 0 or h == 0:
return struct.pack(">H", 0)
if comp == 0:
return struct.pack(">H", 0) + plane
if comp == 1:
rows = [packbits(plane[y * rb:(y + 1) * rb]) for y in range(h)]
fmt = ">I" if psb else ">H"
return struct.pack(">H", 1) + b"".join(struct.pack(fmt, len(r)) for r in rows) + b"".join(rows)
if comp == 2:
return struct.pack(">H", 2) + zlib.compress(plane)
# zip with prediction
out = bytearray()
for y in range(h):
row = plane[y * rb:(y + 1) * rb]
if depth == 8:
out += bytes([row[0]] + [(row[x] - row[x - 1]) & 255 for x in range(1, w)])
elif depth == 16:
vals = struct.unpack(">%dH" % w, row)
out += struct.pack(">%dH" % w, *([vals[0]] + [(vals[x] - vals[x - 1]) & 0xFFFF for x in range(1, w)]))
else:
planes = bytes(row[x * 4 + k] for k in range(4) for x in range(w))
out += bytes([planes[0]] + [(planes[x] - planes[x - 1]) & 255 for x in range(1, len(planes))])
return struct.pack(">H", 3) + zlib.compress(bytes(out))
def pascal(name, pad=4):
b = name.encode("latin-1", "replace")[:255]
s = bytes([len(b)]) + b
while len(s) % pad:
s += b"\0"
return s
def block(key, data, psb=False):
while len(data) % 4:
data += b"\0"
return b"8BIM" + key + (struct.pack(">Q", len(data)) if psb and key in (b"Lr16", b"Lr32", b"Layr") else struct.pack(">I", len(data))) + data
def luni(name):
u = name.encode("utf-16-be")
return struct.pack(">I", len(u) // 2) + u
class Layer:
def __init__(self, name, left, top, w, h, chans, blend="norm", opacity=255, clip=0, hidden=False, section=None,
section_blend=None, fill=None, mask=None, comp=1):
self.__dict__.update(locals())
def layer_info(layers, depth, psb, neg):
recs, data = bytearray(), bytearray()
for L in layers:
recs += struct.pack(">iiii", L.top, L.left, L.top + L.h, L.left + L.w)
chans = list(L.chans.items())
if L.mask:
chans.append((-2, L.mask["plane"]))
recs += struct.pack(">H", len(chans))
for cid, plane in chans:
if cid == -2:
m = L.mask
cd = channel_data(plane, m["w"], m["h"], depth, 1, psb)
else:
cd = channel_data(plane, L.w, L.h, depth, L.comp, psb)
recs += struct.pack(">h", cid) + (struct.pack(">Q", len(cd)) if psb else struct.pack(">I", len(cd)))
data += cd
flags = 8 | (2 if L.hidden else 0) | (16 if L.section else 0)
recs += b"8BIM" + L.blend.encode() + bytes([L.opacity, L.clip, flags, 0])
ex = bytearray()
if L.mask:
m = L.mask
ex += struct.pack(">IiiiiBBH", 20, m["top"], m["left"], m["top"] + m["h"], m["left"] + m["w"], m["default"], m.get("flags", 0), 0)
else:
ex += struct.pack(">I", 0)
ex += struct.pack(">I", 0)
ex += pascal(L.name)
ex += block(b"luni", luni(L.name))
if L.section is not None:
ex += block(b"lsct", struct.pack(">I", L.section) + (b"8BIM" + L.section_blend.encode() if L.section_blend else b""))
if L.fill is not None:
ex += block(b"iOpa", bytes([L.fill, 0, 0, 0]))
recs += struct.pack(">I", len(ex)) + ex
body = struct.pack(">h", -len(layers) if neg else len(layers)) + recs + data
if len(body) % 2:
body += b"\0"
return body
def psd(w, h, mode, depth, nch, merged_planes, layers=None, psb=False, comp=1, palette=None, lr16=False, neg=True, resources=b""):
out = b"8BPS" + struct.pack(">H", 2 if psb else 1) + b"\0" * 6 + struct.pack(">HIIHH", nch, h, w, depth, mode)
cm = palette or b""
out += struct.pack(">I", len(cm)) + cm
out += struct.pack(">I", len(resources)) + resources
L = lambda n: struct.pack(">Q", n) if psb else struct.pack(">I", n)
if layers:
li = layer_info(layers, depth, psb, neg)
if lr16:
lm = L(0) + struct.pack(">I", 0) + block(b"Lr16" if depth == 16 else b"Lr32", li, psb)
else:
lm = L(len(li)) + li + struct.pack(">I", 0)
out += L(len(lm)) + lm
else:
out += L(0)
rb = (w + 7) // 8 if depth == 1 else w * bytes_per(depth)
if comp == 0:
out += struct.pack(">H", 0) + b"".join(merged_planes)
elif comp == 1:
rows = [packbits(p[y * rb:(y + 1) * rb]) for p in merged_planes for y in range(h)]
fmt = ">I" if psb else ">H"
out += struct.pack(">H", 1) + b"".join(struct.pack(fmt, len(r)) for r in rows) + b"".join(rows)
else:
out += struct.pack(">H", 2) + zlib.compress(b"".join(merged_planes))
return out
def plane8(w, h, f):
return bytes(f(x, y) & 255 for y in range(h) for x in range(w))
def plane16(w, h, f):
return b"".join(struct.pack(">H", f(x, y) & 0xFFFF) for y in range(h) for x in range(w))
def plane32(w, h, f):
return b"".join(struct.pack(">f", f(x, y)) for y in range(h) for x in range(w))
def rgba_layer(name, left, top, w, h, seed, **kw):
rng = random.Random(seed)
k = [rng.randrange(1, 9) for _ in range(8)]
chans = {
0: plane8(w, h, lambda x, y: x * k[0] * 7 + y * k[1]),
1: plane8(w, h, lambda x, y: y * k[2] * 9 + x * k[3]),
2: plane8(w, h, lambda x, y: (x ^ y) * k[4] * 5),
-1: plane8(w, h, lambda x, y: 255 if (x + y) % 5 else 90 + (x * k[5] * 13) % 160),
}
return Layer(name, left, top, w, h, chans, **kw)
def divider():
return Layer("</Layer group>", 0, 0, 0, 0, {0: b"", 1: b"", 2: b"", -1: b""}, section=3)
def group(name, blend="pass", opacity=255, hidden=False):
return Layer(name, 0, 0, 0, 0, {0: b"", 1: b"", 2: b"", -1: b""}, blend=blend, opacity=opacity, section=1, section_blend=blend, hidden=hidden)
def merged_rgb(w, h, alpha=True):
ps = [plane8(w, h, lambda x, y, c=c: x * 5 + y * 3 + c * 70) for c in range(3)]
if alpha:
ps.append(plane8(w, h, lambda x, y: 255 - x))
return ps
def cases():
W, H = 40, 30
out = []
# 1. a full RGB document: groups, pass-through, clipping, masks, fill, hidden, every compression
mask = {"top": 5, "left": 8, "w": 20, "h": 12, "default": 0, "plane": plane8(20, 12, lambda x, y: x * 12)}
layers = [
rgba_layer("Background", 0, 0, W, H, 1, comp=0),
rgba_layer("Multiply", 5, 4, 20, 15, 2, blend="mul ", opacity=200),
divider(),
rgba_layer("Screen", -3, 10, 25, 25, 3, blend="scrn", comp=2),
rgba_layer("Overlay", 15, 2, 30, 12, 4, blend="over", comp=3),
group("Isolated", blend="norm", opacity=180),
divider(),
rgba_layer("Diff é日", 10, 10, 20, 15, 5, blend="diff"),
rgba_layer("Hidden", 0, 0, 10, 10, 6, hidden=True),
group("Pass"),
rgba_layer("Base", 20, 15, 15, 10, 7),
rgba_layer("Clipped", 15, 12, 20, 14, 8, clip=1, blend="mul "),
rgba_layer("Masked", 2, 2, 30, 20, 9, mask=mask),
rgba_layer("Fill", 25, 0, 15, 30, 10, fill=128, blend="lite"),
]
out.append(("rgb-layers", psd(W, H, 3, 8, 4, merged_rgb(W, H), layers)))
# 2. every blend mode on its own (two layers)
for key in BLEND:
ls = [rgba_layer("Bottom", 0, 0, 24, 16, 11, comp=0), rgba_layer("Top " + key, 4, 2, 18, 12, 12, blend=key, opacity=230)]
out.append(("blend-" + key.strip(), psd(24, 16, 3, 8, 4, merged_rgb(24, 16), ls)))
# 3. 16-bit RGB with the layers in Lr16, ZIP with prediction
ch16 = lambda s: {0: plane16(12, 9, lambda x, y: x * 5000 + y * 31 + s), 1: plane16(12, 9, lambda x, y: y * 7000 + s), 2: plane16(12, 9, lambda x, y: (x * y * 997) + s), -1: plane16(12, 9, lambda x, y: 65535 - x * 3000)}
l16 = [Layer("L16a", 0, 0, 12, 9, ch16(1), comp=3), Layer("L16b", 3, 2, 12, 9, ch16(77), comp=1, blend="mul ")]
m16 = [plane16(16, 12, lambda x, y, c=c: x * 4000 + y * 100 + c * 9000) for c in range(3)] + [plane16(16, 12, lambda x, y: 65535)]
out.append(("rgb16-lr16", psd(16, 12, 3, 16, 4, m16, l16, lr16=True)))
# 4. 32-bit: merged only (floats) and a layer in Lr32
m32 = [plane32(10, 7, lambda x, y, c=c: (x + c) / 12.0) for c in range(3)]
l32 = [Layer("F", 1, 1, 6, 5, {0: plane32(6, 5, lambda x, y: x / 6.0), 1: plane32(6, 5, lambda x, y: y / 5.0), 2: plane32(6, 5, lambda x, y: 0.5), -1: plane32(6, 5, lambda x, y: 1.0)}, comp=3)]
out.append(("rgb32", psd(10, 7, 3, 32, 3, m32, l32, lr16=True, comp=0)))
# 5. greyscale with layers, raw merged
gl = [Layer("G1", 0, 0, 20, 10, {0: plane8(20, 10, lambda x, y: x * 12), -1: plane8(20, 10, lambda x, y: 255)}),
Layer("G2", 5, 3, 10, 6, {0: plane8(10, 6, lambda x, y: 200 - y * 20), -1: plane8(10, 6, lambda x, y: 128 + x * 10)}, blend="scrn")]
out.append(("gray", psd(20, 10, 1, 8, 2, [plane8(20, 10, lambda x, y: x * 12 + y), plane8(20, 10, lambda x, y: 255)], gl, comp=0)))
# 6. CMYK, merged + a layer
cm = [plane8(14, 8, lambda x, y, c=c: 255 - (x * 15 + c * 40) % 256) for c in range(4)]
cl = [Layer("C", 2, 1, 8, 5, {0: plane8(8, 5, lambda x, y: 200), 1: plane8(8, 5, lambda x, y: 40 * x), 2: plane8(8, 5, lambda x, y: 255), 3: plane8(8, 5, lambda x, y: 220 + y), -1: plane8(8, 5, lambda x, y: 255)})]
out.append(("cmyk", psd(14, 8, 4, 8, 4, cm, cl)))
# 7. indexed (merged only), 8. bitmap (merged only), 9. Lab
pal = bytes(range(256)) + bytes((i * 3) % 256 for i in range(256)) + bytes(255 - i for i in range(256))
out.append(("indexed", psd(17, 9, 2, 8, 1, [plane8(17, 9, lambda x, y: x * 15 + y)], palette=pal, comp=1)))
out.append(("bitmap", psd(24, 7, 0, 1, 1, [bytes((x * 37 + y * 11) & 255 for y in range(7) for x in range(3))], comp=0)))
out.append(("lab", psd(9, 5, 9, 8, 3, [plane8(9, 5, lambda x, y: x * 28), plane8(9, 5, lambda x, y: 100 + y * 10), plane8(9, 5, lambda x, y: 150)], comp=1)))
# 10. PSB with layers (8-byte lengths, 4-byte RLE counts)
out.append(("psb", psd(W, H, 3, 8, 4, merged_rgb(W, H), [rgba_layer("A", 0, 0, W, H, 21), rgba_layer("B", 3, 3, 10, 10, 22, blend="mul ")], psb=True)))
# 11. no alpha in the merged image, positive layer count
out.append(("rgb-noalpha", psd(W, H, 3, 8, 3, merged_rgb(W, H, False), [rgba_layer("Only", 0, 0, W, H, 31)], neg=False)))
return out
REF = r'''
import json, os, sys, zlib
from psd_tools import PSDImage
d = %r
res = []
for name in sorted(os.listdir(d)):
if not name.endswith(".psd"):
continue
psd = PSDImage.open(os.path.join(d, name))
c = {"name": name[:-4], "width": psd.width, "height": psd.height}
try:
im = psd.topil()
c["composite"] = im.convert("RGBA").tobytes().hex() if im is not None else ""
except Exception as e:
c["composite"] = ""
layers = []
for l in psd.descendants():
if l.is_group():
layers.append({"name": l.name, "group": True})
continue
e = {"name": l.name, "left": l.left, "top": l.top, "width": l.width, "height": l.height}
try:
im = l.topil()
if im is not None:
e["crc"] = zlib.crc32(im.convert("RGBA").tobytes())
except Exception:
pass
layers.append(e)
c["layers"] = layers
try:
f = psd.composite(force=True, color=0.0, alpha=0.0)
c["flat"] = f.convert("RGBA").tobytes().hex()
except Exception as e:
c["flaterr"] = str(e)
res.append(c)
print(json.dumps(res))
'''
def pyrun(ctx, code):
try:
return ctx.python(["psd-tools", "numpy", "pillow"], code)
except subprocess.CalledProcessError as e:
raise RuntimeError("psd-tools failed:\n" + e.stderr.decode(errors="replace"))
def reference(ctx, files):
with tempfile.TemporaryDirectory() as d:
for name, data in files:
open(os.path.join(d, name + ".psd"), "wb").write(data)
res = json.loads(pyrun(ctx, REF % d))
by = {r["name"]: r for r in res}
out = []
for name, data in files:
r = by[name]
case = {"name": name, "data": data, "width": r["width"], "height": r["height"], "composite": bytes.fromhex(r["composite"])}
if "flat" in r:
case["flat"] = bytes.fromhex(r["flat"])
case["layers"] = r["layers"]
out.append(case)
return out
def imagemagick(ctx):
# image 0 is the merged image, the rest are layers (ImageMagick 7.1 writes the blend key of some layers byte-reversed
# ("mron"), which psd-tools refuses: these layers avoid it)
with tempfile.TemporaryDirectory() as d:
p = os.path.join(d, "im.psd")
argv = ["magick", "-size", "32x24", "gradient:red-blue", "(", "-clone", "0", ")",
"(", "-size", "8x8", "radial-gradient:yellow-none", "-repage", "+20+10", ")", p]
try:
subprocess.run(argv, check=True, capture_output=True)
except (OSError, subprocess.CalledProcessError):
ctx.nix("imagemagick", argv)
return open(p, "rb").read()
def generate(ctx):
files = cases()
files.append(("imagemagick", imagemagick(ctx)))
ctx.emit("psd", {"cases": reference(ctx, files)})
ctx.emit("psd_ours", {"checks": ours(ctx)})
def run_ours(ctx, fmt):
"""our encoder's output and facts, from tools/fixtures/_ours.luau"""
script = os.path.join(ctx.root, "tools", "fixtures", "_ours.luau")
argv = [shutil.which("luau") or "luau", script, "-a", fmt]
if shutil.which("luau"):
out = subprocess.run(argv, check=True, capture_output=True, cwd=ctx.root).stdout
else:
out = subprocess.run(["nix", "shell", "nixpkgs#luau", "-c", "luau", script, "-a", fmt], check=True, capture_output=True, cwd=ctx.root).stdout
return json.loads(out)
OURS = r'''
import json, sys, zlib
from psd_tools import PSDImage
psd = PSDImage.open(%r)
res = {"width": psd.width, "height": psd.height, "composite": zlib.crc32(psd.topil().convert("RGBA").tobytes()), "layers": []}
for l in psd.descendants():
if l.is_group():
res["layers"].append({"group": True, "name": l.name, "blend": str(l.blend_mode), "opacity": l.opacity, "visible": l.visible})
continue
res["layers"].append({"name": l.name, "left": l.left, "top": l.top, "width": l.width, "height": l.height,
"crc": zlib.crc32(l.topil().convert("RGBA").tobytes()), "blend": str(l.blend_mode), "opacity": l.opacity,
"visible": l.visible, "clip": bool(l.clipping_layer), "mask": l.has_mask()})
print(json.dumps(res))
'''
PSD_BLEND = {"normal": "NORMAL", "multiply": "MULTIPLY", "screen": "SCREEN", "difference": "DIFFERENCE", "lighten": "LIGHTEN"}
def ours(ctx):
o = run_ours(ctx, "psd")
with tempfile.TemporaryDirectory() as d:
p = os.path.join(d, "ours.psd")
open(p, "wb").write(bytes.fromhex(o["data"]))
ref = json.loads(pyrun(ctx, OURS % p))
checks = []
def check(label, ok):
checks.append({"label": label, "ok": bool(ok)})
check("psd-tools: composite = our flatten", ref["composite"] == o["composite"])
leaves = [l for l in ref["layers"] if not l.get("group")]
check("psd-tools: leaf count", len(leaves) == len(o["layers"]))
for want, got in zip(o["layers"], leaves):
n = want["name"]
check(n + ": name", got["name"] == n)
check(n + ": pixels", got["crc"] == want["crc"])
check(n + ": bounds", (got["left"], got["top"], got["width"], got["height"]) == (want["left"], want["top"], want["width"], want["height"]))
check(n + ": blend", got["blend"].endswith(PSD_BLEND.get(want["blend"], "?")))
check(n + ": opacity", got["opacity"] == want["opacity"])
check(n + ": visible", got["visible"] == want["visible"])
check(n + ": clip", got["clip"] == want["clip"])
groups = [l for l in ref["layers"] if l.get("group")]
check("psd-tools: two groups", [g["name"] for g in groups] == ["Isolated", "Pass"])
check("psd-tools: pass-through group", len(groups) == 2 and groups[1]["blend"].endswith("PASS_THROUGH") and groups[0]["blend"].endswith("NORMAL"))
check("psd-tools: masked layer has a mask", any(l.get("mask") for l in leaves if l["name"] == "Masked"))
return checks
+64
View File
@@ -0,0 +1,64 @@
# QOI fixtures (tools/fixtures.py): Pillow's QOI writer and reader.
# tests/gen/qoi.luau { { name, width, height, mode, pixels (source bytes, RGB or RGBA), data (Pillow's .qoi), crc
# (CRC-32 of Pillow's RGBA decode) } }
# tests/gen/qoi_bench.luau { width, height, pixels (RGBA), data }
import struct
CODE = r'''
import io, random, struct, sys, zlib
from PIL import Image
rng = random.Random(11)
def make(w, h, mode, kind):
n = len(mode)
px = bytearray()
for y in range(h):
for x in range(w):
if kind == "noise":
v = [rng.randrange(256) for _ in range(n)]
elif kind == "grad":
v = [(x * 3 + y) % 256, (y * 5) % 256, (x + y * 2) % 256, 255 - (x % 7) * 30][:n]
elif kind == "flat":
v = [10, 200, 30, 255][:n] if (x // 9 + y // 7) % 2 else [10, 200, 31, 128][:n]
else: # small deltas around a walk, with an occasional jump
base = (x * 2 + y) % 256
v = [(base + rng.randrange(-2, 2)) % 256, (base + rng.randrange(-30, 30)) % 256, (base + rng.randrange(-9, 9)) % 256, 255 if rng.random() < 0.9 else rng.randrange(256)][:n]
px += bytes(v)
return bytes(px)
out = []
for (w, h, mode, kind) in ((1, 1, "RGB", "noise"), (1, 1, "RGBA", "noise"), (3, 2, "RGBA", "grad"), (64, 48, "RGB", "grad"),
(64, 48, "RGBA", "grad"), (100, 37, "RGB", "noise"), (100, 37, "RGBA", "noise"),
(200, 150, "RGBA", "flat"), (200, 150, "RGB", "flat"), (128, 99, "RGBA", "walk"), (128, 99, "RGB", "walk"),
(500, 1, "RGBA", "flat"), (1, 300, "RGB", "walk")):
px = make(w, h, mode, kind)
im = Image.frombytes(mode, (w, h), px)
b = io.BytesIO(); im.save(b, "QOI"); data = b.getvalue()
back = Image.open(io.BytesIO(data)).convert("RGBA").tobytes()
name = "%dx%d-%s-%s" % (w, h, mode, kind)
sys.stdout.buffer.write(struct.pack("<HIIB", len(name), w, h, len(mode)) + name.encode() + struct.pack("<III", len(px), len(data), zlib.crc32(back)) + px + data)
# bench: 1024 x 768 RGBA walk image
w, h = 1024, 768
px = bytearray()
for y in range(h):
for x in range(w):
base = (x // 4 + y // 3) % 256
px += bytes(((base + (x * y) % 5) % 256, (base * 2) % 256, (255 - base + x % 3) % 256, 255))
b = io.BytesIO(); Image.frombytes("RGBA", (w, h), bytes(px)).save(b, "QOI")
sys.stdout.buffer.write(struct.pack("<HIIB", 0, w, h, 4) + struct.pack("<III", len(px), len(b.getvalue()), 0) + bytes(px) + b.getvalue())
'''
def generate(ctx):
raw = ctx.python(["pillow"], CODE)
cases, p, bench = [], 0, None
while p < len(raw):
nl, w, h, ch = struct.unpack("<HIIB", raw[p:p + 11]); p += 11
name = raw[p:p + nl].decode(); p += nl
pl, dl, crc = struct.unpack("<III", raw[p:p + 12]); p += 12
px, data = raw[p:p + pl], raw[p + pl:p + pl + dl]; p += pl + dl
e = {"name": name, "width": w, "height": h, "channels": ch, "pixels": px, "data": data, "crc": crc}
if nl == 0:
bench = e
else:
cases.append(e)
ctx.emit("qoi", cases)
ctx.emit("qoi_bench", bench)
+383
View File
@@ -0,0 +1,383 @@
# STL fixtures (tools/fixtures.py).
# tests/gen/stl_scenes.luau scenes for the encoder (indexed grid with colours, polygons under a TRS node, a node tree
# with a matrix, a mirror and u16 positions) with the expected world-space triangle soup
# (computed here with numpy) and the expected colour attribute words
# tests/gen/stl.luau cases: STL files made by trimesh (binary / ascii), by assimp (obj / ply -> stl / stlb)
# and by hand here (binary starting with "solid", VisCAM and Magics colours, raw attribute
# words, odd ASCII: case, tabs, CRLF, several solids, quads, no endsolid, trailing bytes,
# empty), each with reference values from trimesh's raw STL reader (facets, CRC-32 of the
# f32 vertices and normals, area, bounds, attribute words); `ours`: our encoder's output
# (run through the luau CLI: tools/fixtures/_stl_encode.luau) read back by trimesh and
# assimp, as verdicts
import json, math, os, shutil, struct, subprocess, tempfile, zlib
INPUTS = ["src/Formats/model/stl", "tools/fixtures/_stl_reference.py", "tools/fixtures/_stl_encode.luau"]
def f32(x):
return struct.unpack("<f", struct.pack("<f", x))[0]
def binary_stl(header, tris, normals=None, attrs=None, extra=b""):
out = bytearray(header.ljust(80, b"\0")[:80])
out += struct.pack("<I", len(tris))
for i, t in enumerate(tris):
n = normals[i] if normals else (0.0, 0.0, 0.0)
out += struct.pack("<3f", *n)
for v in t:
out += struct.pack("<3f", *v)
out += struct.pack("<H", attrs[i] if attrs else 0)
return bytes(out) + extra
def rand_tris(rng, n, scale=10.0):
return [[tuple(f32(rng.uniform(-scale, scale)) for _ in range(3)) for _ in range(3)] for _ in range(n)]
def unit_normal(t):
ux, uy, uz = (t[1][k] - t[0][k] for k in range(3))
vx, vy, vz = (t[2][k] - t[0][k] for k in range(3))
n = (uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx)
ln = math.sqrt(sum(c * c for c in n)) or 1.0
return tuple(f32(c / ln) for c in n)
def x8(v):
return (v * 255 + 15) // 31
def to5(c):
return (c * 31 + 127) // 255
def soup_bytes(tris):
return b"".join(struct.pack("<3f", *v) for t in tris for v in t)
def crc(b):
return zlib.crc32(b)
# --- hand-made files: (name, data, expected) where expected holds what trimesh cannot tell us
def handmade(rng):
cases = []
tris = rand_tris(rng, 12)
cases.append(("bin-solid-header.stl", binary_stl(b"solid this is binary all the same", tris, [unit_normal(t) for t in tris]), {}))
# VisCAM: bit 15 = valid, red high; some facets invalid
tris = rand_tris(rng, 40)
words, cols = [], []
for i in range(40):
r, g, b = rng.randrange(32), rng.randrange(32), rng.randrange(32)
if i % 7 == 3:
words.append(rng.randrange(0x8000)) # not valid: the default (opaque white)
cols.append((255, 255, 255, 255))
else:
words.append(0x8000 | r << 10 | g << 5 | b)
cols.append((x8(r), x8(g), x8(b), 255))
cases.append(("viscam.stl", binary_stl(b"VisCAM colours", tris, None, words), {"colors": "viscam", "cols": cols}))
# Magics: COLOR= object colour, bit 15 clear = own colour, red low
tris = rand_tris(rng, 40)
dc = (200, 100, 50, 180)
header = b"magics part COLOR=" + bytes(dc) + b",MATERIAL=" + bytes(range(12))
words, cols = [], []
for i in range(40):
r, g, b = rng.randrange(32), rng.randrange(32), rng.randrange(32)
if i % 5 == 0:
words.append(0x8000 | rng.randrange(0x8000))
cols.append(dc)
else:
words.append(r | g << 5 | b << 10)
cols.append((x8(r), x8(g), x8(b), 255))
cases.append(("magics.stl", binary_stl(header, tris, None, words), {"colors": "magics", "cols": cols, "defaultColor": list(dc)}))
# raw attribute words (no colour convention)
tris = rand_tris(rng, 9)
words = [rng.randrange(1, 0x8000) for _ in range(9)]
cases.append(("attrs.stl", binary_stl(b"attribute words", tris, None, words), {"words": words}))
cases.append(("bin-empty.stl", binary_stl(b"empty", []), {}))
# ASCII oddities: case, tabs, CRLF, exponents, two solids (one unnamed), blank lines
t1, t2 = rand_tris(rng, 3), rand_tris(rng, 2)
s = "SOLID first part\r\n"
for t in t1:
s += "\tFACET NORMAL %.6e %.6e %.6e\r\n\t\tOUTER LOOP\r\n" % unit_normal(t)
for v in t:
s += "\t\t\tVERTEX %.9g\t%.9e %r\r\n" % (v[0], v[1], v[2])
s += "\t\tENDLOOP\r\n\tENDFACET\r\n\r\n"
s += "ENDSOLID first part\r\n\nsolid\n"
for t in t2:
s += "facet normal %r %r %r outer loop\n" % unit_normal(t)
s += " ".join("vertex %r %r %r" % v for v in t) + "\nendloop endfacet\n"
s += "endsolid\n"
normals = [tuple(f32(float("%.6e" % c)) for c in unit_normal(t)) for t in t1] + [unit_normal(t) for t in t2]
cases.append(("ascii-odd.stl", s.encode(), {"solids": ["first part", ""], "solidFacets": [3, 2], "normals": normals}))
# a quad facet (fan-triangulated: trimesh cannot read it, the expectation is computed here)
q = [(0.0, 0.0, 0.0), (2.0, 0.0, 0.0), (2.0, 1.0, 0.0), (0.0, 1.0, 0.5)]
s = "solid quad\nfacet normal 0 0 1\nouter loop\n" + "".join("vertex %r %r %r\n" % v for v in q) + "endloop\nendfacet\nendsolid quad\n"
qt = [[q[0], q[1], q[2]], [q[0], q[2], q[3]]]
cases.append(("ascii-quad.stl", s.encode(), {"self": True, "tris": qt, "normals": [(0.0, 0.0, 1.0)] * 2}))
# no final endsolid
t3 = rand_tris(rng, 2)
s = "solid open\n" + "".join("facet normal 0 0 0\nouter loop\n" + "".join("vertex %r %r %r\n" % v for v in t) + "endloop\nendfacet\n" for t in t3)
cases.append(("ascii-noend.stl", s.encode(), {"self": True, "tris": t3, "normals": [(0.0, 0.0, 0.0)] * 2}))
# binary with trailing bytes (size != 84 + 50 n: trimesh refuses, we tolerate)
t4 = rand_tris(rng, 5)
n4 = [unit_normal(t) for t in t4]
cases.append(("bin-trailing.stl", binary_stl(b"trailing junk", t4, n4, extra=b"JUNK!!!"), {"self": True, "tris": t4, "normals": n4}))
return cases
# --- encoder scenes (also used by tests/model/stl.luau for round trips)
def quat(rng):
q = [rng.uniform(-1, 1) for _ in range(4)]
ln = math.sqrt(sum(c * c for c in q))
return [c / ln for c in q]
def mmul(a, b):
return [[sum(a[i][k] * b[k][j] for k in range(4)) for j in range(4)] for i in range(4)]
def det3(m):
return (m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
+ m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]))
EYE = [[1.0 if i == j else 0.0 for j in range(4)] for i in range(4)]
def mat_trs(node):
"""row-major 4x4 of a node (glTF: column-major matrix, or T * R * S)"""
if "matrix" in node:
c = node["matrix"]
return [[c[j * 4 + i] for j in range(4)] for i in range(4)]
x, y, z, w = node.get("rotation", [0, 0, 0, 1])
sx, sy, sz = node.get("scale", [1, 1, 1])
tx, ty, tz = node.get("translation", [0, 0, 0])
r = [
[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)],
]
return [[r[0][0] * sx, r[0][1] * sy, r[0][2] * sz, tx], [r[1][0] * sx, r[1][1] * sy, r[1][2] * sz, ty],
[r[2][0] * sx, r[2][1] * sy, r[2][2] * sz, tz], [0.0, 0.0, 0.0, 1.0]]
def unpack(fmt, data):
n = len(data) // struct.calcsize("<" + fmt)
return list(struct.unpack("<%d%s" % (n, fmt), data))
def expected_soup(sc):
"""world-space triangles (fan-triangulated polygons, reversed winding under a mirror) as f32 bytes, and the
colour of each facet's first vertex"""
out, cols = [], []
def prim_tris(p):
n = p["count"]
flat = unpack("H" if p.get("posType") == "u16" else "f", p["pos"])
pos = [flat[i * 3:i * 3 + 3] for i in range(n)]
idx = unpack("I", p["indices"]) if "indices" in p else list(range(n))
if p["mode"] == "polygons":
tris, at = [], 0
for s in unpack("I", p["faces"]):
for k in range(1, s - 1):
tris.append((idx[at], idx[at + k], idx[at + k + 1]))
at += s
else:
tris = [tuple(idx[i:i + 3]) for i in range(0, len(idx) - len(idx) % 3, 3)]
return pos, tris
def walk(ni, parent):
node = sc["nodes"][ni - 1]
has = any(k in node for k in ("matrix", "translation", "rotation", "scale"))
m = mmul(parent, mat_trs(node)) if has else parent
if "mesh" in node:
for p in sc["meshes"][node["mesh"] - 1]["prims"]:
pos, tris = prim_tris(p)
flip = det3(m) < 0
w = [[m[i][0] * v[0] + m[i][1] * v[1] + m[i][2] * v[2] + m[i][3] for i in range(3)] for v in pos]
col = p.get("color")
for a, b, c in tris:
if flip:
b, c = c, b
out.append(w[a] + w[b] + w[c])
if col is not None:
cols.append(tuple(col[a * 4:a * 4 + 4]))
for c in node.get("children", []):
walk(c, m)
for r in sc["roots"]:
walk(r, EYE)
return b"".join(struct.pack("<9f", *t) for t in out), cols
def pack(fmt, vals):
return struct.pack("<%d%s" % (len(vals), fmt), *vals)
def scenes(rng):
out = []
# grid: indexed, colours on 5-bit steps, no transform
W, H = 7, 6
pos = [v for y in range(H) for x in range(W) for v in (x * 0.5, y * 0.5, rng.uniform(-1, 1))]
idx = []
for y in range(H - 1):
for x in range(W - 1):
a = y * W + x
idx += [a, a + 1, a + W + 1, a, a + W + 1, a + W]
col = bytes(v for _ in range(W * H) for v in (x8(rng.randrange(32)), x8(rng.randrange(32)), x8(rng.randrange(32)), 255))
out.append({"name": "grid", "nodes": [{"mesh": 1, "name": "grid"}], "roots": [1], "meshes": [{"name": "grid", "prims": [
{"mode": "triangles", "count": W * H, "pos": pack("f", pos), "indices": pack("I", idx), "color": col}]}],
"encodings": ["binary", "ascii", "viscam", "magics"]})
# polygons under a TRS node
pv = [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 2, 0, 0, 3, 0.5, 0, 2.5, 1.5, 0.2, 1.5, 1.2, 0.1, 0, 0, 1]
corners = [0, 1, 2, 3, 1, 4, 5, 6, 7, 2, 0, 3, 8]
out.append({"name": "polys", "nodes": [{"mesh": 1, "translation": [1, 2, 3], "rotation": quat(rng), "scale": [2, 0.5, 1.5]}], "roots": [1],
"meshes": [{"name": "polys", "prims": [{"mode": "polygons", "count": 9, "pos": pack("f", pv),
"indices": pack("I", corners), "faces": pack("I", [4, 6, 3])}]}],
"encodings": ["binary", "ascii"]})
# a node tree: a matrix root, a mirrored child (winding flips), a child without its own transform, u16 positions,
# a soup without indices
soup = [rng.uniform(-3, 3) for _ in range(45)]
u16 = [rng.randrange(0, 100) for _ in range(18)]
c, s = math.cos(0.7), math.sin(0.7)
m = [c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 5, -2, 0.5, 1] # column-major: rotate about z, translate
out.append({"name": "tree", "nodes": [
{"mesh": 2, "matrix": m, "children": [2, 3]},
{"mesh": 1, "scale": [-1, 1, 1], "translation": [0, 0, 1]},
{"mesh": 3, "name": "plain"},
], "roots": [1], "meshes": [
{"name": "soup", "prims": [{"mode": "triangles", "count": 15, "pos": pack("f", soup)}]},
{"name": "u16", "prims": [{"mode": "triangles", "count": 6, "posType": "u16", "pos": pack("H", u16),
"indices": pack("I", [0, 1, 2, 2, 3, 4, 4, 5, 0, 1, 3, 5])}]},
{"name": "pair", "prims": [{"mode": "triangles", "count": 4, "pos": pack("f", [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0.25]),
"indices": pack("I", [0, 1, 2, 0, 2, 3])}]},
], "encodings": ["binary", "ascii"]})
for sc in out:
soup_b, cols = expected_soup(sc)
sc["expect"] = soup_b
sc["exact"] = sc["name"] == "grid"
if cols:
sc["viscamWords"] = [0x8000 | to5(r) << 10 | to5(g) << 5 | to5(b) for r, g, b, _ in cols]
sc["magicsWords"] = [to5(r) | to5(g) << 5 | to5(b) << 10 for r, g, b, _ in cols]
return out
def luau_cmd():
exe = shutil.which("luau")
return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
def assimp_info(ctx, path):
txt = ctx.nix("assimp", ["assimp", "info", path]).decode(errors="replace")
faces = verts = None
for line in txt.split("\n"):
if line.startswith("Faces:"):
faces = int(line.split()[1])
if line.startswith("Vertices:"):
verts = int(line.split()[1])
return faces, verts
def generate(ctx):
rng = ctx.rng(31)
tmp = tempfile.mkdtemp(prefix="formats-stl-")
try:
_generate(ctx, rng, tmp)
finally:
shutil.rmtree(tmp, ignore_errors=True)
def _generate(ctx, rng, tmp):
# scenes first: the encoder script reads them
sc = scenes(rng)
ctx.emit("stl_scenes", sc)
files = {}
hand = handmade(rng)
for name, data, _ in hand:
files[name] = data
# assimp conversions: an OBJ with quads and a PLY -> ASCII and binary STL
obj = "".join("v %r %r %r\n" % (f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5))) for _ in range(12))
obj += "f 1 2 3 4\nf 5 6 7\nf 8 9 10 11 12\nf 2 4 6\n"
ply = "ply\nformat ascii 1.0\nelement vertex 5\nproperty float x\nproperty float y\nproperty float z\nelement face 3\nproperty list uchar int vertex_indices\nend_header\n"
ply += "".join("%r %r %r\n" % (f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5))) for _ in range(5))
ply += "3 0 1 2\n4 0 2 3 4\n3 4 3 1\n"
with open(os.path.join(tmp, "in.obj"), "w") as f:
f.write(obj)
with open(os.path.join(tmp, "in.ply"), "w") as f:
f.write(ply)
for src, dst, fid in (("in.obj", "assimp-obj.stl", "stl"), ("in.obj", "assimp-obj-b.stl", "stlb"), ("in.ply", "assimp-ply-b.stl", "stlb")):
ctx.nix("assimp", ["assimp", "export", os.path.join(tmp, src), os.path.join(tmp, dst), "-f" + fid])
for name, data in files.items():
with open(os.path.join(tmp, name), "wb") as f:
f.write(data)
make = [["trimesh-icosphere.stl", "icosphere", "stl", 1], ["trimesh-icosphere-ascii.stl", "icosphere", "stl_ascii", 1],
["trimesh-box.stl", "box", "stl", 2], ["trimesh-capsule-ascii.stl", "capsule", "stl_ascii", 3],
["trimesh-soup.stl", "soup", "stl", 4], ["trimesh-soup-ascii.stl", "soup", "stl_ascii", 5]]
refnames = [m[0] for m in make] + ["assimp-obj.stl", "assimp-obj-b.stl", "assimp-ply-b.stl"]
refnames += [n for n, _, e in hand if not e.get("self")]
# our encoder's output (the luau CLI prints "<scene>/<encoding> <hex>" lines)
enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_stl_encode.luau")], capture_output=True, check=True, cwd=ctx.root).stdout.decode()
ours = []
byname = {s["name"]: s for s in sc}
for line in enc.split("\n"):
if not line.strip():
continue
label, hexdata = line.split(" ", 1)
scene_name, encoding = label.split("/")
s = byname[scene_name]
fn = "ours-%s-%s.stl" % (scene_name, encoding)
with open(os.path.join(tmp, fn), "wb") as f:
f.write(bytes.fromhex(hexdata.strip()))
o = {"name": label, "file": fn, "expect": s["expect"].hex(), "exact": s["exact"]}
if encoding == "viscam":
o["colors"] = s["viscamWords"]
elif encoding == "magics":
o["colors"] = s["magicsWords"]
ours.append(o)
code = open(os.path.join(ctx.root, "tools", "fixtures", "_stl_reference.py")).read()
try:
res = json.loads(ctx.python(["trimesh", "numpy"], code, input=json.dumps({"dir": tmp, "make": make, "ref": refnames, "ours": ours}).encode()))
except subprocess.CalledProcessError as e:
raise RuntimeError("stl reference: " + e.stderr.decode(errors="replace")[-3000:])
verdicts = []
for o in ours:
ok, detail = res["ours"][o["name"]]
# assimp reads it too
faces, _ = assimp_info(ctx, os.path.join(tmp, o["file"]))
want = len(bytes.fromhex(o["expect"])) // 36
if faces != want:
ok, detail = False, "assimp reads %s faces, want %d" % (faces, want)
verdicts.append({"name": o["name"], "ok": ok, "detail": detail})
cases = []
for name in refnames:
with open(os.path.join(tmp, name), "rb") as f:
data = f.read()
r = res["ref"][name]
c = {"name": name, "data": data, "facets": r["facets"], "pos_crc": r["pos_crc"], "area": r["area"], "bounds": r["bounds"]}
extra = next((e for n, _, e in hand if n == name), {})
if "nrm_crc" in r:
c["nrm_crc"] = r["nrm_crc"]
elif "normals" in extra: # the normals written here (%.6e / repr of f32 values, read as f32)
c["nrm_crc"] = crc(b"".join(struct.pack("<3f", *n) * 3 for n in extra["normals"]))
if "cols" in extra:
c["colors"] = extra["colors"]
c["col_crc"] = crc(b"".join(bytes(col) * 3 for col in extra["cols"]))
# the colour words trimesh read must be the ones written
assert r.get("attr") is not None
if "defaultColor" in extra:
c["defaultColor"] = extra["defaultColor"]
if "words" in extra:
assert r["attr"] == extra["words"]
c["attr_crc"] = crc(struct.pack("<%dH" % len(extra["words"]), *extra["words"]))
if "solids" in extra:
c["solids"] = extra["solids"]
c["solidFacets"] = extra["solidFacets"]
c["binary"] = not data.lstrip()[:5].lower() == b"solid" or (len(data) >= 84 and 84 + 50 * struct.unpack("<I", data[80:84])[0] == len(data))
cases.append(c)
for name, data, e in hand:
if e.get("self"):
tris = e["tris"]
cases.append({"name": name, "data": data, "facets": len(tris), "pos_crc": crc(soup_bytes(tris)),
"nrm_crc": crc(b"".join(struct.pack("<3f", *n) * 3 for n in e["normals"])),
"binary": not data.startswith(b"solid")})
ctx.emit("stl", {"cases": cases, "ours": verdicts})
+140
View File
@@ -0,0 +1,140 @@
# Subtitle fixtures (tests/gen/subtitles.luau, for tests/subtitle/srt.luau, vtt.luau and ass.luau) with
# ffmpeg as the reference: a random SRT script converted by ffmpeg to SRT / WebVTT / ASS, and hand-written WebVTT /
# ASS / SSA files with their features, converted by ffmpeg to SRT. Every case carries the expected cues
# ({ start_ms, stop_ms, plain text }) so the tests compare our decode with ffmpeg's view of the same file.
import os, random, re, shutil, subprocess, tempfile
WORDS = ["alpha", "beta", "gamma", "delta", "omega", "café", "naïve", "日本", "fox", "dog", "42", "hello", "world"]
def ffmpeg(ctx, src_bytes, src_ext, dst_ext):
with tempfile.TemporaryDirectory() as d:
src = os.path.join(d, "in." + src_ext)
dst = os.path.join(d, "out." + dst_ext)
open(src, "wb").write(src_bytes)
argv = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-i", src, dst]
if shutil.which("ffmpeg"):
subprocess.run(argv, check=True, capture_output=True)
else:
ctx.nix("ffmpeg", argv)
return open(dst, "rb").read()
def plain(s):
return re.sub(r"{[^}]*}", "", re.sub(r"<[^>]*>", "", s)).replace("&amp;", "&")
def srt_time(ms):
return "%02d:%02d:%02d,%03d" % (ms // 3600000, ms // 60000 % 60, ms // 1000 % 60, ms % 1000)
def random_srt(rng, n):
cues, t = [], 500
for i in range(n):
start = t + rng.randrange(0, 3000)
stop = start + rng.randrange(300, 5000)
t = stop
lines = []
for _ in range(rng.randrange(1, 3)):
words = [rng.choice(WORDS) for _ in range(rng.randrange(1, 6))]
if rng.random() < 0.3:
k = rng.randrange(len(words))
tag = rng.choice("ibu")
words[k] = "<%s>%s</%s>" % (tag, words[k], tag)
lines.append(" ".join(words))
cues.append((start, stop, "\n".join(lines)))
text = "".join("%d\n%s --> %s\n%s\n\n" % (i + 1, srt_time(a), srt_time(b), t) for i, (a, b, t) in enumerate(cues))
return text.encode(), [{"start": a, "stop": b, "plain": plain(t)} for a, b, t in cues]
VTT = """WEBVTT - a test file
Kind: captions
STYLE
::cue { color: yellow }
REGION
id:r1 width:40%
NOTE this is a comment
over two lines
intro
00:01.000 --> 00:04.500 align:start position:10%
<v Roger>Hello <i>there</i></v>
00:05.250 --> 00:07.000
first line
second line
01:00:02.000 --> 01:00:03.123 line:0
<c.loud>an hour in</c> &amp; more
"""
ASS = """[Script Info]
; Script generated by hand
Title: test
ScriptType: v4.00+
PlayResX: 640
PlayResY: 480
[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
Style: Default,Arial,20,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,2,2,10,10,10,1
Style: Top,Verdana,24,&H0000FFFF,&H000000FF,&H00000000,&H80000000,-1,0,0,0,100,100,0,0,1,2,0,8,10,10,10,1
[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
Dialogue: 0,0:00:01.00,0:00:03.50,Default,Bob,0,0,0,,Hello, {\\i1}world{\\i0}!
Comment: 0,0:00:02.00,0:00:04.00,Default,,0,0,0,,a comment line
Dialogue: 1,0:00:04.20,0:00:06.00,Top,,0,0,0,,{\\an8\\b1}Bold top{\\b0}\\Nsecond line
Dialogue: 0,0:01:02.03,0:01:05.99,Default,,0,0,0,,{\\pos(10,20)}commas, inside, the text
[Fonts]
fontname: x.ttf
ABCDEF
"""
SSA = """[Script Info]
Title: old
ScriptType: v4.00
[V4 Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, TertiaryColour, BackColour, Bold, Italic, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, AlphaLevel, Encoding
Style: Default,Tahoma,24,16777215,65535,65535,-2147483640,-1,0,1,3,0,2,30,30,30,0,0
[Events]
Format: Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
Dialogue: Marked=0,0:00:00.50,0:00:02.00,Default,,0000,0000,0000,,old style
Dialogue: Marked=0,0:00:02.50,0:00:04.25,Default,,0000,0000,0000,,{\\i1}two{\\i0}\\Nlines
"""
def parse_srt(data):
"""the cues of an SRT (ffmpeg's output) -> [{start, stop, plain}]"""
out = []
text = data.decode("utf-8-sig").replace("\r\n", "\n")
for block in re.split(r"\n\s*\n", text.strip()):
lines = block.split("\n")
for k, l in enumerate(lines):
m = re.match(r"(\d+):(\d+):(\d+)[,.](\d+) --> (\d+):(\d+):(\d+)[,.](\d+)", l)
if m:
g = [int(x) for x in m.groups()]
out.append({"start": ((g[0] * 60 + g[1]) * 60 + g[2]) * 1000 + g[3], "stop": ((g[4] * 60 + g[5]) * 60 + g[6]) * 1000 + g[7], "plain": plain("\n".join(lines[k + 1:]))})
break
return out
def generate(ctx):
rng = random.Random(7)
src, cues = random_srt(rng, 40)
out = {"srt": src, "cues": cues}
for ext in ("srt", "vtt", "ass"):
out["ffmpeg_" + ext] = ffmpeg(ctx, src, "srt", ext)
hand = []
for name, ext, data in (("vtt", "vtt", VTT), ("ass", "ass", ASS), ("ssa", "ssa", SSA)):
b = data.encode()
ref = ffmpeg(ctx, b, ext, "srt")
hand.append({"name": name, "data": b, "ffmpeg_srt": ref, "cues": parse_srt(ref)})
out["hand"] = hand
ctx.emit("subtitles", out)
+202
View File
@@ -0,0 +1,202 @@
# SVG fixtures (tools/fixtures.py): hand-written SVGs, one feature area each, rendered by resvg (nixpkgs#resvg, the
# reference rasterizer), and the same documents decoded and written back by our encoder (tools/fixtures/_ours.luau)
# then rendered by resvg too:
# tests/gen/svg.luau { cases = { { name, svg, width, height, ref (resvg RGBA), ours (our SVG text), ours_ref
# (resvg's RGBA of our SVG) } } }
import json, os, shutil, subprocess, tempfile
INPUTS = ["src/Formats/vector/svg", "tools/fixtures/_ours.luau"]
def svg(w, h, body, extra=""):
return '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="%d" height="%d"%s>\n%s\n</svg>\n' % (w, h, extra, body)
CASES = {
"shapes": svg(64, 64, """
<rect x="4" y="4" width="20" height="14" fill="red"/>
<rect x="30" y="4" width="28" height="16" rx="5" fill="#0a0" stroke="black" stroke-width="2"/>
<circle cx="14" cy="34" r="9" fill="blue"/>
<ellipse cx="44" cy="34" rx="14" ry="7" fill="orange" stroke="purple"/>
<line x1="4" y1="50" x2="30" y2="60" stroke="black" stroke-width="3"/>
<polyline points="34,60 40,48 46,58 52,46 60,60" fill="none" stroke="teal" stroke-width="2"/>
<polygon points="4,62 10,52 16,62" fill="magenta"/>"""),
"path-commands": svg(64, 64, """
<path d="M4 4 L20 4 H28 V12 L4 12 Z" fill="#c00"/>
<path d="m34 4 l10 0 h8 v8 l-18 0 z" fill="#0c0"/>
<path d="M4 20 C10 14 18 30 24 20 S36 26 40 20" fill="none" stroke="blue" stroke-width="2"/>
<path d="M4 34 Q14 24 24 34 T44 34 T60 30" fill="none" stroke="black" stroke-width="2"/>
<path d="m4 44 c4-6 12 6 16 0 s8-6 12 0 q4 6 8 0 t8 0" fill="none" stroke="#a0a" stroke-width="2"/>
<path d="M4,60L10,52,16,60zM20 60 52 60 36 50z" fill="gold" stroke="brown"/>"""),
"arcs": svg(64, 64, """
<path d="M8 16 A12 8 0 0 1 32 16" fill="none" stroke="red" stroke-width="2"/>
<path d="M36 16 A12 8 0 1 0 60 16" fill="none" stroke="blue" stroke-width="2"/>
<path d="M8 40 a10 10 0 1 1 20 0 a10 10 0 1 1 -20 0" fill="#9c9"/>
<path d="M36 32 A14 6 30 0 1 58 48" fill="none" stroke="black" stroke-width="2"/>
<path d="M36 58 A3 3 0 0 1 58 58" fill="none" stroke="purple" stroke-width="2"/>"""),
"transforms": svg(64, 64, """
<g transform="translate(32 32)">
<rect x="-6" y="-6" width="12" height="12" fill="red" transform="rotate(30)"/>
<g transform="scale(1.5, 0.75)"><circle cx="12" cy="-20" r="5" fill="blue"/></g>
<rect x="-28" y="10" width="14" height="10" fill="green" transform="skewX(20)"/>
<rect x="10" y="10" width="10" height="10" fill="orange" transform="matrix(1 0.3 -0.2 1 2 0) rotate(-15 15 15)"/>
</g>"""),
"stroke-styles": svg(64, 64, """
<polyline points="6,20 18,6 30,20" fill="none" stroke="black" stroke-width="6" stroke-linejoin="miter"/>
<polyline points="36,20 48,6 60,20" fill="none" stroke="black" stroke-width="6" stroke-linejoin="round"/>
<polyline points="6,40 18,26 30,40" fill="none" stroke="black" stroke-width="6" stroke-linejoin="bevel"/>
<polyline points="36,40 48,38 60,40" fill="none" stroke="black" stroke-width="5" stroke-miterlimit="1.5"/>
<line x1="8" y1="48" x2="56" y2="48" stroke="blue" stroke-width="5" stroke-linecap="butt"/>
<line x1="8" y1="55" x2="56" y2="55" stroke="blue" stroke-width="5" stroke-linecap="round"/>
<line x1="8" y1="62" x2="56" y2="62" stroke="blue" stroke-width="3" stroke-linecap="square"/>"""),
"dashes": svg(64, 64, """
<line x1="4" y1="8" x2="60" y2="8" stroke="black" stroke-width="3" stroke-dasharray="6 3"/>
<line x1="4" y1="18" x2="60" y2="18" stroke="red" stroke-width="3" stroke-dasharray="5,2,1" stroke-dashoffset="3"/>
<circle cx="20" cy="42" r="14" fill="none" stroke="blue" stroke-width="3" stroke-dasharray="8 4"/>
<rect x="40" y="30" width="20" height="24" fill="none" stroke="green" stroke-width="2" stroke-dasharray="4" stroke-linecap="round"/>"""),
"fill-rule": svg(64, 32, """
<path d="M16 2 L22 30 L2 12 L30 12 L10 30 Z" fill="navy" fill-rule="nonzero"/>
<path d="M48 2 L54 30 L34 12 L62 12 L42 30 Z" fill="navy" fill-rule="evenodd"/>"""),
"opacity": svg(64, 64, """
<rect x="2" y="2" width="60" height="60" fill="#eee"/>
<g opacity="0.5"><rect x="6" y="6" width="24" height="24" fill="red"/><rect x="16" y="16" width="24" height="24" fill="blue"/></g>
<rect x="34" y="6" width="24" height="24" fill="green" fill-opacity="0.4" stroke="black" stroke-width="4" stroke-opacity="0.6"/>
<circle cx="20" cy="48" r="12" fill="orange" stroke="purple" stroke-width="6" opacity="0.6"/>
<circle cx="46" cy="48" r="12" fill="rgba(0,0,255,0.5)"/>"""),
"linear-gradient": svg(64, 64, """
<defs>
<linearGradient id="a"><stop offset="0" stop-color="red"/><stop offset="0.5" stop-color="yellow"/><stop offset="1" stop-color="blue"/></linearGradient>
<linearGradient id="b" x1="0" y1="0" x2="0.3" y2="0" spreadMethod="reflect"><stop offset="0" stop-color="#000"/><stop offset="1" stop-color="#fff"/></linearGradient>
<linearGradient id="c" x1="0" y1="0" x2="0.25" y2="0.25" spreadMethod="repeat"><stop offset="0%" stop-color="green"/><stop offset="100%" stop-color="white" stop-opacity="0.2"/></linearGradient>
<linearGradient id="d" gradientTransform="rotate(90 0.5 0.5)"><stop offset="0" stop-color="purple"/><stop offset="1" stop-color="orange"/></linearGradient>
</defs>
<rect x="2" y="2" width="60" height="12" fill="url(#a)"/>
<rect x="2" y="16" width="60" height="12" fill="url(#b)"/>
<rect x="2" y="30" width="28" height="30" fill="url(#c)"/>
<circle cx="47" cy="45" r="14" fill="url(#d)" stroke="url(#a)" stroke-width="3"/>"""),
"radial-gradient": svg(64, 64, """
<defs>
<radialGradient id="r1"><stop offset="0" stop-color="white"/><stop offset="1" stop-color="blue"/></radialGradient>
<radialGradient id="r2" cx="0.5" cy="0.5" r="0.5" fx="0.25" fy="0.25"><stop offset="0" stop-color="yellow"/><stop offset="0.6" stop-color="red"/><stop offset="1" stop-color="black"/></radialGradient>
<radialGradient id="r3" gradientUnits="userSpaceOnUse" cx="16" cy="48" r="8" spreadMethod="repeat"><stop offset="0" stop-color="#fff"/><stop offset="1" stop-color="#080"/></radialGradient>
</defs>
<rect x="2" y="2" width="28" height="28" fill="url(#r1)"/>
<ellipse cx="47" cy="16" rx="15" ry="12" fill="url(#r2)"/>
<rect x="2" y="34" width="28" height="28" fill="url(#r3)"/>
<circle cx="47" cy="48" r="13" fill="url(#r2)" fill-opacity="0.7"/>"""),
"gradient-href": svg(64, 32, """
<defs>
<linearGradient id="base"><stop offset="0" stop-color="#f00"/><stop offset="1" stop-color="#00f"/></linearGradient>
<linearGradient id="tilted" xlink:href="#base" x2="0" y2="1"/>
<radialGradient id="rad" href="#base"/>
</defs>
<rect x="2" y="2" width="28" height="28" fill="url(#tilted)"/>
<rect x="34" y="2" width="28" height="28" fill="url(#rad)"/>"""),
"css": svg(64, 64, """
<style>
rect { fill: red; stroke: black }
.blue { fill: blue }
#special { fill: green; stroke-width: 4 }
circle.big, ellipse { fill: orange; }
/* a comment */
@media print { rect { fill: pink } }
</style>
<rect x="4" y="4" width="20" height="20"/>
<rect x="30" y="4" width="20" height="20" class="blue"/>
<rect x="4" y="30" width="20" height="20" class="blue" id="special"/>
<rect x="30" y="30" width="20" height="20" class="blue" style="fill: purple"/>
<circle class="big" cx="58" cy="58" r="5"/>
<ellipse cx="10" cy="58" rx="6" ry="4" fill="black"/>"""),
"use-symbol": svg(64, 64, """
<defs>
<g id="dot"><circle r="5" fill="red"/><circle r="2" fill="white"/></g>
<symbol id="sym" viewBox="0 0 10 10"><rect width="10" height="10" fill="blue"/><path d="M0 0 L10 10" stroke="white"/></symbol>
<rect id="bar" width="20" height="4"/>
</defs>
<use href="#dot" x="10" y="10"/>
<use xlink:href="#dot" transform="translate(30 10) scale(1.5)"/>
<use href="#sym" x="4" y="24" width="20" height="20"/>
<use href="#sym" x="30" y="24" width="30" height="15"/>
<use href="#bar" x="4" y="54" fill="green"/>
<use href="#bar" x="30" y="54" style="fill: orange" opacity="0.5"/>"""),
"viewbox-meet": svg(64, 40, """
<rect width="100" height="100" fill="#ccc"/><circle cx="50" cy="50" r="40" fill="red"/>""", ' viewBox="0 0 100 100" preserveAspectRatio="xMinYMax meet"'),
"viewbox-slice": svg(64, 40, """
<rect width="100" height="100" fill="#ccc"/><circle cx="50" cy="50" r="40" fill="blue"/>""", ' viewBox="0 0 100 100" preserveAspectRatio="xMidYMid slice"'),
"viewbox-none": svg(64, 40, """
<rect width="100" height="100" fill="#ccc"/><circle cx="50" cy="50" r="40" fill="green"/>""", ' viewBox="0 0 100 100" preserveAspectRatio="none"'),
"nested-svg": svg(64, 64, """
<rect width="64" height="64" fill="#eef"/>
<svg x="8" y="8" width="48" height="24" viewBox="0 0 20 10"><circle cx="5" cy="5" r="5" fill="red"/><circle cx="15" cy="5" r="5" fill="blue"/></svg>
<svg x="8" y="36" width="20" height="20"><rect x="5" y="5" width="50%" height="50%" fill="green"/><circle cx="20" cy="10" r="8" fill="red"/></svg>"""),
"clip-path": svg(64, 64, """
<defs>
<clipPath id="c1"><circle cx="16" cy="16" r="12"/></clipPath>
<clipPath id="c2" clipPathUnits="objectBoundingBox"><rect x="0.25" y="0" width="0.5" height="1"/></clipPath>
<clipPath id="c3"><path d="M34 34 h26 v26 h-26z M40 40 h14 v14 h-14z" clip-rule="evenodd"/></clipPath>
</defs>
<rect x="2" y="2" width="30" height="30" fill="red" clip-path="url(#c1)"/>
<g clip-path="url(#c2)"><rect x="34" y="2" width="28" height="28" fill="blue"/><circle cx="48" cy="16" r="10" fill="yellow"/></g>
<rect x="2" y="34" width="28" height="28" fill="green" clip-path="url(#c2)"/>
<rect x="34" y="34" width="28" height="28" fill="purple" clip-path="url(#c3)"/>"""),
"units": svg(64, 64, """
<rect x="2mm" y="2mm" width="10mm" height="5mm" fill="red"/>
<rect x="40pt" y="4" width="12pt" height="12pt" fill="blue"/>
<rect x="10%" y="50%" width="25%" height="10%" fill="green"/>
<circle cx="48" cy="48" r="1em" fill="orange" style="font-size: 8px"/>
<rect x="4" y="52" width="1in" height="0.1in" fill="black" transform="scale(0.5)"/>"""),
"colors": svg(64, 32, """
<g color="teal">
<rect x="0" y="0" width="8" height="16" fill="cornflowerblue"/>
<rect x="8" y="0" width="8" height="16" fill="#f80"/>
<rect x="16" y="0" width="8" height="16" fill="#ff008080"/>
<rect x="24" y="0" width="8" height="16" fill="rgb(10%, 50%, 90%)"/>
<rect x="32" y="0" width="8" height="16" fill="rgba(200, 0, 100, 0.5)"/>
<rect x="40" y="0" width="8" height="16" fill="hsl(120, 100%, 25%)"/>
<rect x="48" y="0" width="8" height="16" fill="currentColor"/>
<rect x="56" y="0" width="8" height="16" fill="transparent" stroke="currentColor"/>
<rect x="0" y="16" width="64" height="16" fill="none" stroke="DarkOrchid" stroke-width="4"/>
</g>"""),
"inheritance": svg(64, 64, """
<g fill="red" stroke="blue" stroke-width="3">
<rect x="4" y="4" width="24" height="24"/>
<g fill="green"><rect x="36" y="4" width="24" height="24" stroke="inherit"/></g>
<g style="stroke: none"><circle cx="16" cy="46" r="12"/></g>
<g display="none"><rect x="36" y="36" width="24" height="24"/></g>
<rect x="36" y="36" width="10" height="10" visibility="hidden"/>
<g visibility="hidden"><rect x="48" y="48" width="12" height="12" visibility="visible"/></g>
</g>"""),
}
def resvg(ctx, data, w, h):
with tempfile.TemporaryDirectory() as d:
src, png = os.path.join(d, "in.svg"), os.path.join(d, "out.png")
open(src, "wb").write(data)
argv = ["resvg", "-w", str(w), "-h", str(h), src, png]
if shutil.which("resvg"):
subprocess.run(argv, check=True, capture_output=True)
else:
subprocess.run(["nix", "shell", "nixpkgs#resvg", "-c"] + argv, check=True, capture_output=True)
argv = ["magick", png, "-depth", "8", "rgba:-"]
try:
return subprocess.run(argv, check=True, capture_output=True).stdout
except (OSError, subprocess.CalledProcessError):
return ctx.nix("imagemagick", argv)
def ours(ctx, text):
script = os.path.join(ctx.root, "tools", "fixtures", "_ours.luau")
luau = shutil.which("luau")
argv = [luau, script, "-a", "svg", text] if luau else ["nix", "shell", "nixpkgs#luau", "-c", "luau", script, "-a", "svg", text]
return json.loads(subprocess.run(argv, check=True, capture_output=True, cwd=ctx.root).stdout)["svg"]
def generate(ctx):
import re
cases = []
for name, text in CASES.items():
w, h = (int(x) for x in re.search(r'width="(\d+)" height="(\d+)"', text).groups())
data = text.encode()
mine = ours(ctx, text)
cases.append({"name": name, "svg": data, "width": w, "height": h, "ref": resvg(ctx, data, w, h), "ours": mine,
"ours_ref": resvg(ctx, mine.encode(), w, h)})
ctx.emit("svg", {"cases": cases})
+125
View File
@@ -0,0 +1,125 @@
# tar + gzip fixtures (tools/fixtures.py): reference archives from Python's tarfile (ustar / GNU / pax formats, long
# names, non-ASCII names, links, directories, pax mtimes) and from the host / nix GNU tar (--format=ustar / gnu /
# posix / v7), gzip members from Python's gzip and the gzip CLI (FNAME, MTIME, levels, concatenated members), and
# compressed tars (.tar.gz, .tgz, .tar.zst, .tar.xz, .tar.bz2, .tar.br) for the api's unwrap.
# tests/gen/tar.luau { files = { { name, data, ... } }, writes = { { format, entries, data } }, tars = { { name,
# data, entries = { { name, size, type, link?, mtime, mode, crc } } } }, gzips = { ... },
# wrapped = { { name, data, inner = "tar" } } }
import bz2, gzip, io, json, lzma, os, shutil, subprocess, tarfile, tempfile, zlib
def tool(name, pkg, argv, input=None, cwd=None):
exe = shutil.which(name)
cmd = ([exe] if exe else ["nix", "shell", "nixpkgs#" + pkg, "-c", name]) + argv
return subprocess.run(cmd, input=input, capture_output=True, check=True, cwd=cwd).stdout
def entries_of(data):
out = []
with tarfile.open(fileobj=io.BytesIO(data)) as t:
for m in t.getmembers():
e = {"name": m.name + ("/" if m.isdir() and not m.name.endswith("/") else ""), "type": m.type.decode() if m.type != b"\0" else "0",
"size": m.size if m.isfile() else 0, "mtime": m.mtime, "mode": m.mode}
if m.issym() or m.islnk():
e["link"] = m.linkname
if m.isfile():
e["crc"] = zlib.crc32(t.extractfile(m).read())
out.append(e)
return out
def generate(ctx):
rng = ctx.rng(5)
files = [
("hello.txt", b"hello, tar\n"),
("empty", b""),
("dir/sub/data.bin", rng.randbytes(3000)),
("exact512", bytes(range(256)) * 2),
("d" * 60 + "/" + "e" * 60 + "/long-name-over-100-bytes.txt", b"long " * 50),
("x" * 150, b"no slash to split at"),
("unicodé/naïve-ファイル.txt", "ünïcödé".encode()),
]
# the writer test: the same entries through Python's tarfile in three formats (fixed metadata)
writes = []
for fmt, pf in (("ustar", tarfile.USTAR_FORMAT), ("gnu", tarfile.GNU_FORMAT), ("pax", tarfile.PAX_FORMAT)):
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w", format=pf) as t:
ents = []
for name, data in files:
if fmt == "ustar" and (not name.isascii() or name.startswith("x" * 101)):
continue
ti = tarfile.TarInfo(name)
ti.size, ti.mtime, ti.mode, ti.uname, ti.gname = len(data), 1700000000, 0o644, "user", "group"
t.addfile(ti, io.BytesIO(data))
ents.append({"name": name, "data": data})
ti = tarfile.TarInfo("adir")
ti.type, ti.mtime, ti.mode, ti.uname, ti.gname = tarfile.DIRTYPE, 1700000000, 0o755, "user", "group"
t.addfile(ti)
ents.append({"name": "adir", "dir": True})
ti = tarfile.TarInfo("link-to-hello")
ti.type, ti.linkname, ti.mtime, ti.mode, ti.uname, ti.gname = tarfile.SYMTYPE, "hello.txt", 1700000000, 0o777, "user", "group"
t.addfile(ti)
ents.append({"name": "link-to-hello", "type": "2", "link": "hello.txt", "mode": 0o777})
writes.append({"format": fmt, "entries": ents, "data": buf.getvalue()})
tars = []
for w in writes:
tars.append({"name": "python-" + w["format"], "data": w["data"], "entries": entries_of(w["data"])})
# pax with a fractional mtime and a huge uid
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w", format=tarfile.PAX_FORMAT) as t:
ti = tarfile.TarInfo("frac.txt")
ti.size, ti.mtime, ti.uid = 3, 1600000000.5, 3000000
t.addfile(ti, io.BytesIO(b"abc"))
tars.append({"name": "python-pax-extras", "data": buf.getvalue(), "entries": entries_of(buf.getvalue())})
# GNU tar on a real tree
tmp = tempfile.mkdtemp()
try:
root = os.path.join(tmp, "tree")
for name, data in files:
p = os.path.join(root, name)
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, "wb") as f:
f.write(data)
os.makedirs(os.path.join(root, "emptydir"))
os.symlink("hello.txt", os.path.join(root, "sym"))
os.link(os.path.join(root, "hello.txt"), os.path.join(root, "hard"))
for dirpath, dirs, fs in os.walk(root):
for n in dirs + fs:
os.utime(os.path.join(dirpath, n), (1650000000, 1650000000), follow_symlinks=False)
for fmt in ("ustar", "gnu", "posix", "v7"):
argv = ["--format=" + fmt, "--sort=name", "--owner=0", "--group=0", "--numeric-owner", "-cf", "-", "."]
if fmt in ("ustar", "v7"):
argv = ["--exclude=./" + "x" * 150, "--exclude=./d" + "d" * 59] + argv
if fmt == "v7":
argv = ["--exclude=./unicodé"] + argv
data = tool("tar", "gnutar", argv, cwd=root)
tars.append({"name": "gnutar-" + fmt, "data": data, "entries": entries_of(data)})
finally:
shutil.rmtree(tmp)
# gzip
text = ("The quick brown fox jumps over the lazy dog. " * 300).encode()
gzips = []
b = io.BytesIO()
with gzip.GzipFile(filename="story.txt", mode="wb", fileobj=b, mtime=1234567890, compresslevel=9) as g:
g.write(text)
gzips.append({"name": "python-fname", "data": b.getvalue(), "entry": "story.txt", "mtime": 1234567890, "crc": zlib.crc32(text), "size": len(text)})
gzips.append({"name": "python-noname", "data": gzip.compress(text, 1, mtime=0), "entry": "data", "mtime": 0, "crc": zlib.crc32(text), "size": len(text)})
cli = tool("gzip", "gzip", ["-9", "-n", "-c"], input=text)
gzips.append({"name": "cli-n", "data": cli, "entry": "data", "mtime": 0, "crc": zlib.crc32(text), "size": len(text)})
two = gzip.compress(text[:1000], mtime=0) + gzip.compress(text[1000:], mtime=0)
gzips.append({"name": "members", "data": two, "entry": "data", "mtime": 0, "crc": zlib.crc32(text), "size": len(text)})
# compressed tars
inner = writes[2]["data"]
wrapped = [
{"name": "a.tar.gz", "data": gzip.compress(inner, mtime=0), "outer": "gzip"},
{"name": "a.tgz", "data": tool("gzip", "gzip", ["-c", "-n"], input=inner), "outer": "gzip"},
{"name": "a.tar.bz2", "data": bz2.compress(inner), "outer": "bz2"},
{"name": "a.tar.xz", "data": lzma.compress(inner), "outer": "xz"},
{"name": "a.tar.zst", "data": tool("zstd", "zstd", ["-c", "-q"], input=inner), "outer": "zst"},
{"name": "a.tar.br", "data": ctx.python(["brotli"], "import brotli, sys; sys.stdout.buffer.write(brotli.compress(sys.stdin.buffer.read()))", input=inner), "outer": "br"},
]
ctx.emit("tar", {"files": [{"name": n, "data": d} for n, d in files], "writes": writes, "tars": tars,
"gzips": gzips, "wrapped": wrapped, "innerEntries": entries_of(inner)})
+87
View File
@@ -0,0 +1,87 @@
# TGA fixtures (tools/fixtures.py): files written by Pillow (RGB / RGBA / L / P / LA, raw and RLE, both origins) and
# ImageMagick (raw / RLE, palette, grey), plus hand-written ones (15 / 16-bit pixels and colour maps, 8 / 16-bit
# indexes with a first index, right-to-left, RLE packets crossing rows, an image ID, 16-bit grey + alpha);
# references = Pillow's RGBA decodes, ImageMagick's for the files Pillow
# refuses (right-to-left, 16-bit grey + alpha) and for 15 / 16-bit colour, where Pillow differs (5-bit scaling, alpha).
# tests/gen/tga.luau { { name, data, width, height, rgba (bytes) } }
import struct
CODE = r'''
import io, os, random, struct, subprocess, sys
from PIL import Image
magick = sys.argv[1]
rng = random.Random(9)
out = []
def emit(name, data, magick_ref=False):
try:
if magick_ref:
raise ValueError("15 / 16-bit: Pillow scales 5-bit values by x * 255 // 31 and inverts the alpha bit")
im = Image.open(io.BytesIO(data))
rgba = im.convert("RGBA").tobytes()
size = im.size
except Exception:
# files Pillow refuses (right-to-left, 16-bit grey + alpha): ImageMagick's decode
info = subprocess.run([magick, "tga:-", "-format", "%w %h", "info:"], input=data, capture_output=True, check=True).stdout.split()
size = (int(info[0]), int(info[1]))
rgba = subprocess.run([magick, "tga:-", "-depth", "8", "rgba:-"], input=data, capture_output=True, check=True).stdout
out.append((name, data, size, rgba))
w, h = 29, 17
px = bytearray()
for y in range(h):
for x in range(w):
a = 255 if (x + y) % 4 else (x * 37) % 256
px += bytes(((x * 9) % 256, (y * 15) % 256, rng.randrange(256) if x % 3 == 0 else 100, a))
rgba = Image.frombytes("RGBA", (w, h), bytes(px))
for mode in ("RGB", "RGBA", "L", "LA", "P"):
im = rgba.convert(mode) if mode != "P" else rgba.convert("RGB").quantize(37)
for comp in (None, "tga_rle"):
for orient in (1, -1):
b = io.BytesIO()
kw = {"orientation": orient}
if comp:
kw["compression"] = comp
im.save(b, "TGA", **kw)
emit("pil-%s-%s-%s" % (mode, comp or "raw", "top" if orient == 1 else "bottom"), b.getvalue())
# runs that cross rows (RLE)
flat = Image.new("RGB", (13, 9), (10, 20, 30))
for x in range(5):
flat.putpixel((x, 4), (200, 0, 0))
b = io.BytesIO(); flat.save(b, "TGA", compression="tga_rle"); emit("pil-runs", b.getvalue())
# ImageMagick writers
src = io.BytesIO(); rgba.save(src, "PNG")
for name, args in (("im-rgba", []), ("im-rle", ["-compress", "RLE"]), ("im-gray", ["-colorspace", "gray"]), ("im-palette", ["-colors", "20", "-type", "Palette"]),
("im-rgb", ["-alpha", "off"])):
r = subprocess.run([magick, "png:-"] + args + ["tga:-"], input=src.getvalue(), capture_output=True, check=True)
emit(name, r.stdout)
# hand-written
def hdr(idlen, cmt, it, cfirst, clen, cbits, w, h, depth, desc):
return struct.pack("<BBBHHBHHHHBB", idlen, cmt, it, cfirst, clen, cbits, 0, 0, w, h, depth, desc)
def p15(r, g, b, a=1):
return struct.pack("<H", (a << 15) | ((r >> 3) << 10) | ((g >> 3) << 5) | (b >> 3))
cols = [((i * 40) % 256, (i * 90) % 256, (255 - i * 20) % 256) for i in range(12)]
w, h = 6, 4
idx = [(x + y * 2) % 12 for y in range(h) for x in range(w)]
emit("hand-16bit", hdr(0, 0, 2, 0, 0, 0, w, h, 16, 0) + b"".join(p15(*cols[i]) for i in idx), magick_ref=True)
emit("hand-15bit-rtl", hdr(0, 0, 2, 0, 0, 0, w, h, 15, 0x10) + b"".join(p15(*cols[i], a=0) for i in idx), magick_ref=True)
emit("hand-cmap16", hdr(0, 1, 1, 0, 12, 16, w, h, 8, 0x20) + b"".join(p15(*c) for c in cols) + bytes(idx), magick_ref=True)
emit("hand-cmap32-first", hdr(0, 1, 1, 4, 12, 32, w, h, 8, 0x28) + b"".join(bytes((c[2], c[1], c[0], 77)) for c in cols) + bytes(i + 4 for i in idx))
emit("hand-cmap24-rle", hdr(0, 1, 9, 0, 12, 24, w, h, 8, 0) + b"".join(bytes((c[2], c[1], c[0])) for c in cols) + bytes([0x80 + 9, 3, 0x05, 1, 2, 3, 4, 5, 6, 0x80 + 7, 11]))
emit("hand-id-top", hdr(5, 0, 3, 0, 0, 0, w, h, 8, 0x20) + b"hello" + bytes((i * 21) % 256 for i in idx))
emit("hand-graya16", hdr(0, 0, 3, 0, 0, 0, w, h, 16, 0x28) + b"".join(bytes(((i * 21) % 256, (i * 50) % 256)) for i in idx))
emit("hand-rle32-cross", hdr(0, 0, 10, 0, 0, 0, 5, 3, 32, 0x28) + bytes([0x80 + 6, 1, 2, 3, 200, 0x08]) + bytes(range(9 * 4)))
for name, data, size, rgba in out:
sys.stdout.buffer.write(struct.pack("<HIIII", len(name), len(data), size[0], size[1], len(rgba)) + name.encode() + data + rgba)
'''
def generate(ctx):
magick = ctx.nix("imagemagick", ["sh", "-c", "command -v magick"]).decode().strip()
raw = ctx.python(["pillow"], CODE.replace("sys.argv[1]", repr(magick)))
cases, p = [], 0
while p < len(raw):
nl, dl, w, h, rl = struct.unpack("<HIIII", raw[p:p + 18]); p += 18
name = raw[p:p + nl].decode(); p += nl
data = raw[p:p + dl]; p += dl
rgba = raw[p:p + rl]; p += rl
cases.append({"name": name, "data": data, "width": w, "height": h, "rgba": rgba})
ctx.emit("tga", cases)
+226
View File
@@ -0,0 +1,226 @@
# TIFF fixtures (tools/fixtures.py): files written by tifffile (+ imagecodecs) and ImageMagick, with references from
# tifffile's decode (the native sample arrays) turned into what image/tiff must produce.
# tests/gen/tiff.luau { cases = { { name, data, width, height, pages = { { crc, native, ncrc } } } },
# jpeg = data (a JPEG-compressed TIFF for the decodeImage hook test),
# jpegRef = { width, height, rgb } (tifffile + imagecodecs' libjpeg-turbo decode of it) }
# crc CRC-32 of the default rgba8 decode
# native / ncrc: the opts.native pixel format and the CRC-32 of its little-endian bytes
# Every case is decoded by tifffile; the expected pixels follow image/tiff's rules: unsigned samples v / (2^bits - 1),
# floats as stored, min-is-white inverted, palette = ColorMap / 65535, CMYK r = (1 - c)(1 - k), associated alpha
# divided out, then 8-bit = floor(clamp(u) * 255 + 0.5) (16-bit: * 65535).
import os, shutil, struct, subprocess, tempfile
CODE = r'''
import os, struct, sys, zlib
import numpy as np, tifffile
work = WORK
magick = MAGICK
rng = np.random.default_rng(5)
H, W = 37, 53
yy, xx = np.mgrid[0:H, 0:W]
def ramp(maxv, ch):
base = [(xx * 7 + yy * 3) % 256, (xx * 255 // (W - 1)), (yy * 255 // (H - 1)), 255 - ((xx ^ yy) & 63)]
a = np.stack([b for b in base[:ch]], -1).astype(np.float64) / 255.0
noise = rng.random(a.shape) < 0.2
a = np.where(noise, rng.random(a.shape), a)
return np.squeeze(np.round(a * maxv))
cases = []
def add(name, path):
cases.append((name, path))
def tw(name, data, **kw):
p = os.path.join(work, name + ".tif")
tifffile.imwrite(p, data, **kw)
add(name, p)
rgb8 = ramp(255, 3).astype(np.uint8)
rgba8 = ramp(255, 4).astype(np.uint8)
gray8 = ramp(255, 1).astype(np.uint8)
gray16 = ramp(65535, 1).astype(np.uint16)
rgb16 = ramp(65535, 3).astype(np.uint16)
rgba16 = ramp(65535, 4).astype(np.uint16)
f32 = (ramp(1000, 3) / 1000.0 * 1.2 - 0.1).astype(np.float32)
for comp in (None, "lzw", "zlib", "adobe_deflate", "packbits"):
cn = comp or "none"
tw("rgb8_" + cn, rgb8, photometric="rgb", compression=comp)
tw("gray16_" + cn, gray16, photometric="minisblack", compression=comp)
for comp in ("lzw", "zlib"):
tw("rgb8_pred_" + comp, rgb8, photometric="rgb", compression=comp, predictor=True)
tw("rgba16_pred_be_" + comp, rgba16, photometric="rgb", compression=comp, predictor=True, byteorder=">", extrasamples=["unassalpha"])
tw("gray16_pred_" + comp, gray16, photometric="minisblack", compression=comp, predictor=True)
tw("f32_fpred_" + comp, f32, photometric="rgb", compression=comp, predictor=3)
tw("f32_fpred_be_" + comp, f32, photometric="rgb", compression=comp, predictor=3, byteorder=">")
tw("rgba8_assoc", rgba8, photometric="rgb", extrasamples=["assocalpha"])
tw("rgba8_unassoc_tiles", rgba8, photometric="rgb", extrasamples=["unassalpha"], tile=(16, 16), compression="zlib")
tw("rgb8_planar", np.ascontiguousarray(np.moveaxis(rgb8, -1, 0)), photometric="rgb", planarconfig="separate", compression="lzw")
tw("rgb16_planar_tiles_be", np.ascontiguousarray(np.moveaxis(rgb16, -1, 0)), photometric="rgb", planarconfig="separate", tile=(32, 16), byteorder=">", compression="zlib", predictor=True)
tw("rgb8_strips5", rgb8, photometric="rgb", rowsperstrip=5, compression="packbits")
tw("rgb8_bigtiff", rgb8, photometric="rgb", bigtiff=True, compression="zlib")
tw("rgb8_bigtiff_be_tiles", rgb8, photometric="rgb", bigtiff=True, byteorder=">", tile=(16, 32))
tw("gray8_miniswhite", gray8, photometric="miniswhite")
tw("gray8_be", gray8, photometric="minisblack", byteorder=">")
tw("f16_gray", (gray16 / 65535.0).astype(np.float16), photometric="minisblack")
tw("f64_rgb", (f32.astype(np.float64)), photometric="rgb")
tw("f32_gray_tiles", f32[:, :, 0].copy(), photometric="minisblack", tile=(16, 16), compression="zlib")
tw("int16_gray", (gray16.astype(np.int32) - 32768).astype(np.int16), photometric="minisblack")
tw("int8_gray", (gray8.astype(np.int16) - 128).astype(np.int8), photometric="minisblack")
tw("u32_gray", (gray16.astype(np.uint32) * 65537), photometric="minisblack", compression="zlib")
cm = (rng.integers(0, 65536, (3, 256))).astype(np.uint16)
tw("palette8", gray8, photometric="palette", colormap=cm, compression="lzw")
tw("gray4", (gray8 >> 4).astype(np.uint8), photometric="minisblack", bitspersample=4)
tw("gray2_lzw", (gray8 >> 6).astype(np.uint8), photometric="minisblack", bitspersample=2, compression=None)
tw("bilevel", gray8 > 127, photometric="minisblack")
tw("bilevel_white_packbits", gray8 > 100, photometric="miniswhite", compression="packbits")
tw("gray12", (gray16 >> 4).astype(np.uint16), photometric="minisblack", bitspersample=12)
tw("cmyk8", ramp(255, 4).astype(np.uint8), photometric="separated", compression="lzw")
tw("graya8", np.stack([gray8, rgba8[:, :, 3]], -1), photometric="minisblack", extrasamples=["unassalpha"])
with tifffile.TiffWriter(os.path.join(work, "pages3.tif")) as t:
t.write(rgb8, photometric="rgb", compression="zlib")
t.write(gray16, photometric="minisblack", compression="lzw")
t.write(rgba8, photometric="rgb", extrasamples=["unassalpha"])
add("pages3", os.path.join(work, "pages3.tif"))
# ImageMagick
import subprocess
src = os.path.join(work, "src.png")
from PIL import Image
Image.fromarray(rgba8, "RGBA").save(src)
srgb = os.path.join(work, "srgb.png")
Image.fromarray(rgb8, "RGB").save(srgb)
def im(name, *args, s=srgb):
p = os.path.join(work, name + ".tif")
subprocess.run([magick, s] + list(args) + [p], check=True, capture_output=True)
add(name, p)
im("im_lzw", "-compress", "LZW")
im("im_zip_pred", "-compress", "Zip", "-define", "tiff:predictor=2")
im("im_rle", "-compress", "RLE")
im("im_none_msb", "-compress", "None", "-endian", "MSB")
im("im_tiles", "-compress", "LZW", "-define", "tiff:tile-geometry=32x32")
im("im_plane", "-compress", "Zip", "-interlace", "plane")
im("im_16", "-depth", "16", "-compress", "LZW")
im("im_float", "-depth", "32", "-define", "quantum:format=floating-point", "-compress", "Zip")
im("im_alpha", "-compress", "LZW", s=src)
im("im_alpha_assoc", "-define", "tiff:alpha=associated", s=src)
im("im_gray4", "-colorspace", "gray", "-depth", "4")
im("im_bilevel", "-monochrome")
im("im_palette", "-type", "palette", "-compress", "LZW")
im("im_palette4", "-colors", "12", "-type", "palette", "-depth", "4")
im("im_cmyk", "-colorspace", "CMYK", "-compress", "LZW")
p = os.path.join(work, "im_multi.tif")
subprocess.run([magick, srgb, src, srgb, "-compress", "Zip", p], check=True, capture_output=True)
add("im_multi", p)
jp = os.path.join(work, "im_jpeg.tif")
subprocess.run([magick, srgb, "-compress", "JPEG", jp], check=True, capture_output=True)
def expect(page):
a = page.asarray()
spp = page.samplesperpixel
if spp > 1 and page.planarconfig == 2:
a = np.moveaxis(a, 0, -1)
if a.ndim == 2:
a = a[:, :, None]
a = a.reshape(page.imagelength, page.imagewidth, spp)
photo = int(page.photometric)
bps = page.bitspersample
fmt = int(page.sampleformat)
cc = 3 if photo in (2, 6) else (4 if photo == 5 else 1)
alpha = cc if spp > cc else -1
ex = page.extrasamples
assoc = alpha >= 0 and len(ex) > 0 and int(ex[0]) == 1
maxv = float(2 ** min(bps, 32) - 1)
if fmt == 3:
u = a.astype(np.float64)
elif fmt == 2:
u = (a.astype(np.float64) + 2 ** (bps - 1)) / maxv
else:
u = a.astype(np.float64) / maxv
if photo == 3:
cmap = page.colormap.astype(np.float64) / 65535.0
idx = a[:, :, 0].astype(np.int64)
rgb = np.stack([cmap[0][idx], cmap[1][idx], cmap[2][idx]], -1)
elif photo == 2:
rgb = u[:, :, 0:3]
elif photo == 5:
c, m, y, k = u[:, :, 0], u[:, :, 1], u[:, :, 2], u[:, :, 3]
rgb = np.stack([(1 - c) * (1 - k), (1 - m) * (1 - k), (1 - y) * (1 - k)], -1)
else:
v = u[:, :, 0]
if photo == 0:
v = 1 - v
rgb = np.stack([v, v, v], -1)
if alpha >= 0:
al = u[:, :, alpha]
if assoc:
safe = np.where(al > 0, al, 1)
rgb = np.where((al > 0)[:, :, None], np.minimum(rgb / safe[:, :, None], 1), 0)
else:
al = np.ones(rgb.shape[:2])
def q(x, m):
return np.floor(np.clip(np.nan_to_num(x), 0, 1) * m + 0.5)
rgba = np.concatenate([rgb, al[:, :, None]], -1)
out8 = q(rgba, 255).astype(np.uint8)
crc = zlib.crc32(out8.tobytes())
# native
if photo in (3, 5):
kind, nat = "rgba8", out8
elif fmt == 3:
kind, nat = "rgbaf32", rgba.astype("<f4")
elif cc == 1:
if alpha >= 0:
if bps <= 8:
kind, nat = "graya8", q(np.stack([rgb[:, :, 0], al], -1), 255).astype(np.uint8)
else:
kind, nat = "rgba16", q(rgba, 65535).astype("<u2")
else:
if bps <= 8:
kind, nat = "gray8", q(rgb[:, :, 0], 255).astype(np.uint8)
else:
kind, nat = "gray16", q(rgb[:, :, 0], 65535).astype("<u2")
else:
if bps <= 8:
kind, nat = ("rgba8", out8) if alpha >= 0 else ("rgb8", out8[:, :, 0:3].copy())
else:
kind, nat = "rgba16", q(rgba, 65535).astype("<u2")
return crc, kind, zlib.crc32(np.ascontiguousarray(nat).tobytes())
def emit(b):
sys.stdout.buffer.write(struct.pack("<I", len(b)) + b)
emit(str(len(cases)).encode())
for name, path in cases:
with tifffile.TiffFile(path) as t:
pages = [p for p in t.pages if not (int(p.subfiletype) & 1)]
info = []
for pg in pages:
info.append("%d:%s:%d" % expect(pg))
w, h = pages[0].imagewidth, pages[0].imagelength
emit(name.encode()); emit(open(path, "rb").read()); emit(("%d %d " % (w, h) + " ".join(info)).encode())
emit(open(jp, "rb").read())
with tifffile.TiffFile(jp) as t:
a = t.pages[0].asarray()
emit(("%d %d" % (a.shape[1], a.shape[0])).encode())
emit(np.ascontiguousarray(a[:, :, 0:3]).astype(np.uint8).tobytes())
'''
def generate(ctx):
magick = ctx.nix("imagemagick", ["sh", "-c", "command -v magick"]).decode().strip()
work = tempfile.mkdtemp(prefix="formats-tiff-")
try:
raw = ctx.python(["pillow", "tifffile", "numpy", "imagecodecs"], CODE.replace("WORK", repr(work)).replace("MAGICK", repr(magick)))
finally:
shutil.rmtree(work, ignore_errors=True)
p = 0
items = []
while p < len(raw):
n = struct.unpack("<I", raw[p:p + 4])[0]
items.append(raw[p + 4:p + 4 + n])
p += 4 + n
count = int(items[0])
cases = []
for i in range(count):
name, data, info = items[1 + i * 3], items[2 + i * 3], items[3 + i * 3].decode().split()
pages = []
for s in info[2:]:
crc, kind, ncrc = s.split(":")
pages.append({"crc": int(crc), "native": kind, "ncrc": int(ncrc)})
cases.append({"name": name.decode(), "data": data, "width": int(info[0]), "height": int(info[1]), "pages": pages})
jw, jh = map(int, items[2 + count * 3].decode().split())
ctx.emit("tiff", {"cases": cases, "jpeg": items[1 + count * 3],
"jpegRef": {"width": jw, "height": jh, "rgb": items[3 + count * 3]}})
+279
View File
@@ -0,0 +1,279 @@
# Tiled fixtures (tools/fixtures.py), with Tiled itself (nixpkgs#tiled, run headless) as the reference:
# tests/gen/tiled.luau { cases = { { name, tmx (hand-written), tmj (Tiled's export), tiled_tmx (Tiled's re-save) } },
# tsx, tsj (an external tileset and Tiled's JSON export of it) }
# tests/gen/tiled_ours.luau { checks = { { label, ok } } }: a map built and written by our encoder (TMX with
# base64 + zlib data, and TMJ; tools/fixtures/_ours.luau) re-exported by Tiled as JSON and
# compared with our own TMJ
import base64, gzip, json, os, shutil, struct, subprocess, tempfile, zlib
INPUTS = ["src/Formats/vector/tiled", "tools/fixtures/_ours.luau"]
TSX = """<?xml version="1.0" encoding="UTF-8"?>
<tileset version="1.10" tiledversion="1.10.2" name="ext" tilewidth="16" tileheight="16" spacing="0" margin="0" tilecount="8" columns="4">
<tileoffset x="2" y="-3"/>
<properties>
<property name="kind" value="terrain"/>
</properties>
<image source="tiles.png" width="64" height="32"/>
<tile id="1" type="Water" probability="0.5">
<properties>
<property name="speed" type="float" value="0.25"/>
</properties>
<animation>
<frame tileid="1" duration="100"/>
<frame tileid="2" duration="150"/>
</animation>
</tile>
<tile id="5">
<objectgroup draworder="index" id="2">
<object id="1" x="1" y="2" width="10" height="12"/>
<object id="2" x="3" y="3">
<ellipse/>
</object>
</objectgroup>
</tile>
</tileset>
"""
def layer_bytes(gids):
return b"".join(struct.pack("<I", g) for g in gids)
def ortho():
W, H = 6, 4
g1 = [(x + y * W) % 9 for y in range(H) for x in range(W)]
g1[3] |= 0x80000000
g1[7] |= 0x40000000
g1[11] |= 0x20000000
g2 = [(x * y) % 5 for y in range(H) for x in range(W)]
g3 = [9 + (x + y) % 8 if (x + y) % 3 else 0 for y in range(H) for x in range(W)]
g4 = [1 + (x % 2) for y in range(H) for x in range(W)]
csv = ",\n".join(",".join(str(g) for g in g1[y * W:(y + 1) * W]) for y in range(H))
z = base64.b64encode(zlib.compress(layer_bytes(g2))).decode()
gz = base64.b64encode(gzip.compress(layer_bytes(g3), mtime=0)).decode()
raw = base64.b64encode(layer_bytes(g4)).decode()
return f"""<?xml version="1.0" encoding="UTF-8"?>
<map version="1.10" tiledversion="1.10.2" class="Level" orientation="orthogonal" renderorder="left-up" width="{W}" height="{H}" tilewidth="16" tileheight="16" backgroundcolor="#ff102030" infinite="0" nextlayerid="9" nextobjectid="10">
<properties>
<property name="title" value="Ünïcode &amp; more"/>
<property name="count" type="int" value="42"/>
<property name="ratio" type="float" value="1.5"/>
<property name="on" type="bool" value="true"/>
<property name="tint" type="color" value="#80ff0000"/>
<property name="file" type="file" value="other.tmx"/>
<property name="target" type="object" value="3"/>
<property name="notes">line one
line two</property>
</properties>
<tileset firstgid="1" name="inner" tilewidth="16" tileheight="16" spacing="0" margin="0" tilecount="8" columns="4">
<image source="tiles.png" width="64" height="32"/>
<tile id="0">
<properties>
<property name="solid" type="bool" value="true"/>
</properties>
</tile>
<tile id="3" type="Door"/>
</tileset>
<tileset firstgid="9" source="ext.tsx"/>
<layer id="1" name="csv" width="{W}" height="{H}" opacity="0.75" offsetx="3" offsety="-2" tintcolor="#ff00ff">
<properties>
<property name="layerprop" value="x"/>
</properties>
<data encoding="csv">
{csv}
</data>
</layer>
<layer id="2" name="zlib" width="{W}" height="{H}" visible="0" parallaxx="0.5">
<data encoding="base64" compression="zlib">
{z}
</data>
</layer>
<layer id="3" name="gzip" width="{W}" height="{H}" locked="1">
<data encoding="base64" compression="gzip">
{gz}
</data>
</layer>
<layer id="4" name="raw" class="Deco" width="{W}" height="{H}">
<data encoding="base64">
{raw}
</data>
</layer>
<group id="5" name="group" opacity="0.5" offsetx="1">
<imagelayer id="6" name="sky" repeatx="1">
<image source="sky.png" width="40" height="20"/>
</imagelayer>
<objectgroup id="7" name="things" color="#a0a0a4" draworder="index">
<object id="1" name="box" type="Crate" x="10" y="12.5" width="16" height="8" rotation="45">
<properties>
<property name="weight" type="float" value="2.25"/>
</properties>
</object>
<object id="2" name="ring" x="40" y="5" width="10" height="10">
<ellipse/>
</object>
<object id="3" name="spot" x="7" y="9">
<point/>
</object>
<object id="4" name="poly" x="20" y="20">
<polygon points="0,0 16,0 8,-12.5"/>
</object>
<object id="5" name="line" x="30" y="30" visible="0">
<polyline points="0,0 5,5 10,0 15,5"/>
</object>
<object id="6" name="label" x="2" y="40" width="80" height="20">
<text fontfamily="Serif" pixelsize="12" wrap="1" color="#ff0000" bold="1" halign="center" valign="bottom">Hello &lt;Tiled&gt;</text>
</object>
<object id="7" name="tile" gid="2147483651" x="50" y="50" width="16" height="16"/>
</objectgroup>
</group>
</map>
"""
def iso():
W, H = 3, 3
tiles = "\n".join(' <tile gid="%d"/>' % ((x + y) % 4) for y in range(H) for x in range(W))
return f"""<?xml version="1.0" encoding="UTF-8"?>
<map version="1.10" tiledversion="1.10.2" orientation="hexagonal" renderorder="right-down" width="{W}" height="{H}" tilewidth="32" tileheight="28" infinite="0" hexsidelength="14" staggeraxis="x" staggerindex="even" nextlayerid="2" nextobjectid="1">
<tileset firstgid="1" name="inner" tilewidth="16" tileheight="16" tilecount="8" columns="4">
<image source="tiles.png" width="64" height="32"/>
</tileset>
<layer id="1" name="xmltiles" width="{W}" height="{H}">
<data>
{tiles}
</data>
</layer>
</map>
"""
def infinite():
def chunk(cx, cy):
g = [(cx // 16 + cy // 16 + x + y) % 5 for y in range(16) for x in range(16)]
rows = ",\n".join(",".join(str(v) for v in g[y * 16:(y + 1) * 16]) for y in range(16))
return f' <chunk x="{cx}" y="{cy}" width="16" height="16">\n{rows}\n</chunk>'
# Tiled's canonical layout: chunks by row, the layer's size = the chunks' bounds
chunks = "\n".join(chunk(cx, cy) for cx, cy in ((16, -16), (-16, 0), (0, 0)))
return f"""<?xml version="1.0" encoding="UTF-8"?>
<map version="1.10" tiledversion="1.10.2" orientation="orthogonal" renderorder="right-down" width="30" height="20" tilewidth="16" tileheight="16" infinite="1" nextlayerid="2" nextobjectid="1">
<tileset firstgid="1" name="inner" tilewidth="16" tileheight="16" tilecount="8" columns="4">
<image source="tiles.png" width="64" height="32"/>
</tileset>
<layer id="1" name="chunks" width="48" height="32">
<data encoding="csv">
{chunks}
</data>
</layer>
</map>
"""
def tiled(ctx, argv, cwd):
env = dict(os.environ, QT_QPA_PLATFORM="offscreen")
if shutil.which("tiled"):
subprocess.run(["tiled"] + argv, check=True, capture_output=True, cwd=cwd, env=env)
else:
subprocess.run(["nix", "shell", "nixpkgs#tiled", "-c", "tiled"] + argv, check=True, capture_output=True, cwd=cwd, env=env)
def magick(ctx, argv):
try:
subprocess.run(argv, check=True, capture_output=True)
except (OSError, subprocess.CalledProcessError):
ctx.nix("imagemagick", argv)
def workdir(ctx, d):
magick(ctx, ["magick", "-size", "64x32", "gradient:red-blue", os.path.join(d, "tiles.png")])
magick(ctx, ["magick", "-size", "40x20", "xc:skyblue", os.path.join(d, "sky.png")])
open(os.path.join(d, "ext.tsx"), "w").write(TSX)
def run_ours(ctx, fmt):
script = os.path.join(ctx.root, "tools", "fixtures", "_ours.luau")
luau = shutil.which("luau")
argv = [luau, script, "-a", fmt] if luau else ["nix", "shell", "nixpkgs#luau", "-c", "luau", script, "-a", fmt]
return json.loads(subprocess.run(argv, check=True, capture_output=True, cwd=ctx.root).stdout)
def gids(layer):
"""a JSON tile layer's gids (arrays, or base64 with compression) -> list"""
d = layer.get("data")
if isinstance(d, str):
raw = base64.b64decode(d)
c = layer.get("compression", "")
raw = zlib.decompress(raw) if c == "zlib" else gzip.decompress(raw) if c == "gzip" else raw
return list(struct.unpack("<%dI" % (len(raw) // 4), raw))
return d
IGNORE = {"version", "tiledversion", "compressionlevel", "encoding", "compression", "opacity_obj"}
DEFAULTS = {"offsetx": 0, "offsety": 0, "parallaxx": 1, "parallaxy": 1, "locked": False}
def norm(v, obj=False):
"""a JSON map without the fields that only say which Tiled wrote it, or that hold defaults"""
if isinstance(v, dict):
out = {}
if v.get("type") == "tilelayer" and "data" in v:
v = dict(v, data=gids(v))
for k, x in v.items():
if k in IGNORE or (k in DEFAULTS and x == DEFAULTS[k]) or (obj and k == "opacity"):
continue
out[k] = [norm(o, True) for o in x] if k == "objects" else norm(x)
return out
if isinstance(v, list):
return [norm(x) for x in v]
if isinstance(v, float) and v.is_integer():
return int(v)
return v
def diff(a, b, path="", out=None):
out = [] if out is None else out
if isinstance(a, dict) and isinstance(b, dict):
for k in sorted(set(a) | set(b)):
if k not in a or k not in b:
out.append("%s.%s: %s vs %s" % (path, k, a.get(k, "<missing>"), b.get(k, "<missing>")))
else:
diff(a[k], b[k], path + "." + k, out)
elif isinstance(a, list) and isinstance(b, list):
if len(a) != len(b):
out.append("%s: length %d vs %d" % (path, len(a), len(b)))
for i, (x, y) in enumerate(zip(a, b)):
diff(x, y, "%s[%d]" % (path, i), out)
elif a != b:
out.append("%s: %r vs %r" % (path, a, b))
return out
def generate(ctx):
cases = []
with tempfile.TemporaryDirectory() as d:
workdir(ctx, d)
for name, text in (("ortho", ortho()), ("hex", iso()), ("infinite", infinite())):
open(os.path.join(d, name + ".tmx"), "w").write(text)
tiled(ctx, ["--export-map", name + ".tmx", name + "-out.tmj"], d)
tiled(ctx, ["--export-map", name + ".tmx", name + "-out.tmx"], d)
cases.append({"name": name, "tmx": text, "tmj": open(os.path.join(d, name + "-out.tmj"), "rb").read(),
"tiled_tmx": open(os.path.join(d, name + "-out.tmx"), "rb").read()})
tiled(ctx, ["--export-tileset", "ext.tsx", "ext.tsj"], d)
tsj = open(os.path.join(d, "ext.tsj"), "rb").read()
ctx.emit("tiled", {"cases": cases, "tsx": TSX, "tsj": tsj})
# our encoder's files, read by Tiled
o = run_ours(ctx, "tiled")
open(os.path.join(d, "ours.tmx"), "wb").write(bytes.fromhex(o["tmx"]))
open(os.path.join(d, "ours.tmj"), "wb").write(bytes.fromhex(o["tmj"]))
tiled(ctx, ["--export-map", "ours.tmx", "ours-from-tmx.tmj"], d)
tiled(ctx, ["--export-map", "ours.tmj", "ours-from-tmj.tmj"], d)
mine = norm(json.loads(bytes.fromhex(o["tmj"])))
checks = []
for label, f in (("Tiled on our TMX", "ours-from-tmx.tmj"), ("Tiled on our TMJ", "ours-from-tmj.tmj")):
theirs = norm(json.load(open(os.path.join(d, f))))
dd = diff(mine, theirs)
checks.append({"label": label + (": " + "; ".join(dd[:5]) if dd else ""), "ok": not dd})
ctx.emit("tiled_ours", {"checks": checks})
+120
View File
@@ -0,0 +1,120 @@
# data/toml fixtures: the toml-test suite (toml-lang/toml-test v2.2.0, pinned tarball through nix; the files listed
# in tests/files-toml-1.0.0) with each valid case's expected value as the canonical text tests/data/Canon.luau
# computes, plus a random corpus written by tomli-w and read back by Python's tomllib.
# tests/gen/toml_suite.luau { { name, valid, data, canon? } }
# tests/gen/toml_corpus.luau { { data, canon } }
import datetime, importlib.util, json, os, re, tomllib
_spec = importlib.util.spec_from_file_location("_data_common", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_data_common.py"))
C = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(C)
SUITE_URL = "https://github.com/toml-lang/toml-test/archive/refs/tags/v2.2.0.tar.gz"
SUITE_SHA = "1nkgbfcdjaccqgf5pkjs49jh0z1pz4lval94qfxq4j6ikvmlg80s"
DATES = ("datetime", "datetime-local", "date-local", "time-local")
def norm_date(v):
"""a toml-test datetime string the way Types.Date prints it"""
m = re.match(r"^(\d{4}-\d{2}-\d{2})?(?:[Tt ]?(\d{2}:\d{2}:\d{2})(?:\.(\d+))?)?([Zz]|[+-]\d{2}:\d{2})?$", v)
date, time, frac, off = m.groups()
out = date or ""
if time:
out += ("T" if date else "") + time
f = (frac or "")[:9].rstrip("0")
if f:
out += "." + f
if off:
out += "Z" if off in ("Z", "z", "+00:00", "-00:00") else off
return out
def tagged(v, out):
if isinstance(v, dict) and set(v) == {"type", "value"} and isinstance(v["type"], str) and isinstance(v["value"], str):
t, x = v["type"], v["value"]
if t == "string":
b = x.encode("utf-8", "surrogatepass")
out += b"s%d:" % len(b) + b
elif t == "integer":
out += C.num(int(x))
elif t == "float":
out += C.num(float(x))
elif t == "bool":
out += b"t" if x == "true" else b"f"
elif t in DATES:
out += b"d" + norm_date(x).encode()
else:
raise ValueError(t)
elif isinstance(v, list):
out += b"["
for x in v:
tagged(x, out)
out += b","
out += b"]"
else:
items = []
for k, x in v.items():
kb = k.encode("utf-8", "surrogatepass")
items.append((b"s%d:" % len(kb) + kb, x))
items.sort(key=lambda p: p[0])
out += b"{"
for kb, x in items:
out += kb + b"="
tagged(x, out)
out += b","
out += b"}"
GEN = r'''
import datetime, json, random, sys, tomli_w
rng = random.Random(5)
KEYS = ["a", "b-c", "d_e", "1", "with space", "dot.ted", "é", "quote\"", "", "tab\t"]
def scalar():
k = rng.randrange(8)
if k == 0: return rng.randrange(-2**63, 2**63)
if k == 1: return rng.randrange(-1000, 1000)
if k == 2: return rng.choice([0.5, -1.25e-7, 3.14159, 1e300, float("inf"), -float("inf"), 6.02e23])
if k == 3: return rng.random() < 0.5
if k == 4: return "".join(rng.choice("ab \"\\\n\té中\U0001f600\x01\x7f'#=[]") for _ in range(rng.randrange(12)))
if k == 5:
tz = rng.choice([None, datetime.timezone.utc, datetime.timezone(datetime.timedelta(hours=-7, minutes=-30))])
return datetime.datetime(rng.randrange(1, 9999), rng.randrange(1, 13), rng.randrange(1, 29), rng.randrange(24), rng.randrange(60), rng.randrange(60), rng.choice([0, 999999, 500000]), tzinfo=tz)
if k == 6: return datetime.date(rng.randrange(1, 9999), rng.randrange(1, 13), rng.randrange(1, 29))
return datetime.time(rng.randrange(24), rng.randrange(60), rng.randrange(60), rng.choice([0, 123000]))
def table(depth):
d = {}
for _ in range(rng.randrange(1, 6)):
r = rng.random()
k = rng.choice(KEYS)
if depth < 3 and r < 0.2: d[k] = table(depth + 1)
elif depth < 3 and r < 0.3: d[k] = [table(depth + 1) for _ in range(rng.randrange(1, 3))]
elif r < 0.45: d[k] = [scalar() for _ in range(rng.randrange(0, 4))]
elif r < 0.5: d[k] = [[scalar()], [scalar(), scalar()], {"x": scalar()}]
else: d[k] = scalar()
return d
out = []
for _ in range(200):
out.append(tomli_w.dumps(table(0), multiline_strings=rng.random() < 0.3))
json.dump(out, sys.stdout)
'''
def generate(ctx):
root = os.path.join(C.fetch(SUITE_URL, SUITE_SHA), "tests")
names = [l.strip() for l in open(os.path.join(root, "files-toml-1.0.0")) if l.strip().endswith(".toml")]
cases = []
for name in names:
data = open(os.path.join(root, name), "rb").read()
c = {"name": name, "valid": name.startswith("valid/"), "data": data}
if c["valid"]:
out = bytearray()
tagged(json.load(open(os.path.join(root, name[:-5] + ".json"), encoding="utf-8")), out)
c["canon"] = bytes(out)
cases.append(c)
ctx.emit("toml_suite", cases)
texts = json.loads(ctx.python(["tomli-w"], GEN))
corpus = []
for t in texts:
corpus.append({"data": t.encode("utf-8"), "canon": C.canon(tomllib.loads(t))})
ctx.emit("toml_corpus", corpus)
+292
View File
@@ -0,0 +1,292 @@
# VOX fixtures (tools/fixtures.py). There is no MagicaVoxel reader in nixpkgs, so the reference is (1) files saved by
# MagicaVoxel itself (tests/fixtures/vox: ephtracy/voxel-model samples, version 150, and jpaver/opengametools demo files
# with scene graphs, layers, materials, render objects, cameras, notes and META; licences in licenses/), parsed here
# by an independent Python reader written from the spec, and (2) synthetic files written here with every chunk type,
# rotations (including mirrors), nested groups, animation frames and odd cases.
# tests/gen/vox_cases.luau { name, data, version, models = { { size, count, crc (of the dense x-fastest grid),
# faces (exposed unit faces: the greedy mesh area) } }, paletteCrc, chunks = { id = n },
# nodes = { { name, world (row-major 3x4: R | t) } } for every shape node, names, layers,
# materials, notes, cameras, robjs }
import os, struct, zlib
INPUTS = ["tests/fixtures/vox"]
def default_palette():
steps = [0xff, 0xcc, 0x99, 0x66, 0x33, 0]
pal = [(r, g, b, 255) for r in steps for g in steps for b in steps][:215]
ramp = [0xee, 0xdd, 0xbb, 0xaa, 0x88, 0x77, 0x55, 0x44, 0x22, 0x11]
for ch in range(3):
for v in ramp:
c = [0, 0, 0, 255]
c[ch] = v
pal.append(tuple(c))
pal += [(v, v, v, 255) for v in ramp]
return pal
def spec_palette(text):
# the default_palette[256] array of the spec text (ABGR words, entry i = palette index i)
body = text[text.index("default_palette[256]"):]
body = body[body.index("{") + 1:body.index("}")]
words = [int(w, 16) for w in body.replace(",", " ").split()]
return [(w & 255, (w >> 8) & 255, (w >> 16) & 255, w >> 24) for w in words]
# ---------------------------------------------------------------------------------------------- reader (reference)
def rd_dict(d, p):
n, = struct.unpack_from("<i", d, p)
p += 4
out = {}
for _ in range(n):
kl, = struct.unpack_from("<i", d, p)
k = d[p + 4:p + 4 + kl].decode("latin1")
p += 4 + kl
vl, = struct.unpack_from("<i", d, p)
v = d[p + 4:p + 4 + vl].decode("latin1")
p += 4 + vl
out[k] = v
return out, p
def rot(b):
i0, i1 = b & 3, (b >> 2) & 3
i2 = 3 - i0 - i1
R = [[0] * 3 for _ in range(3)]
for row, (i, bit) in enumerate(((i0, 4), (i1, 5), (i2, 6))):
R[row][i] = -1 if b & (1 << bit) else 1
return R
def matmul(A, B): # 3x4 affine (R | t)
R = [[sum(A[r][k] * B[k][c] for k in range(3)) for c in range(3)] for r in range(3)]
t = [sum(A[r][k] * B[k][3] for k in range(3)) + A[r][3] for r in range(3)]
return [R[r] + [t[r]] for r in range(3)]
def parse(d):
assert d[:4] == b"VOX "
version, = struct.unpack_from("<i", d, 4)
assert d[8:12] == b"MAIN"
n, m = struct.unpack_from("<ii", d, 12)
p = 20 + n
end = min(p + m, len(d))
models, size, palette = [], None, None
graph, counts = {}, {}
mats, layers, notes, cams, robjs = {}, [], [], [], []
while p + 12 <= end:
cid = d[p:p + 4].decode("latin1")
n, m = struct.unpack_from("<ii", d, p + 4)
c = p + 12
counts[cid] = counts.get(cid, 0) + 1
if cid == "SIZE":
size = struct.unpack_from("<iii", d, c)
elif cid == "XYZI":
k, = struct.unpack_from("<i", d, c)
sx, sy, sz = size
grid = bytearray(sx * sy * sz)
for i in range(k):
x, y, z, ci = d[c + 4 + i * 4:c + 8 + i * 4]
if x < sx and y < sy and z < sz and ci:
grid[x + sx * (y + sy * z)] = ci
models.append((size, grid))
elif cid == "RGBA":
palette = [tuple(d[c + i * 4:c + i * 4 + 4]) for i in range(255)]
elif cid == "MATL":
mid, = struct.unpack_from("<i", d, c)
mats[mid], _ = rd_dict(d, c + 4)
elif cid == "nTRN":
nid, = struct.unpack_from("<i", d, c)
attrs, q = rd_dict(d, c + 4)
child, _, layer, nf = struct.unpack_from("<iiii", d, q)
q += 16
frames = []
for _ in range(nf):
f, q = rd_dict(d, q)
frames.append(f)
graph[nid] = ("T", attrs, child, frames)
elif cid == "nGRP":
nid, = struct.unpack_from("<i", d, c)
attrs, q = rd_dict(d, c + 4)
k, = struct.unpack_from("<i", d, q)
graph[nid] = ("G", attrs, list(struct.unpack_from("<%di" % k, d, q + 4)))
elif cid == "nSHP":
nid, = struct.unpack_from("<i", d, c)
attrs, q = rd_dict(d, c + 4)
k, = struct.unpack_from("<i", d, q)
mid, = struct.unpack_from("<i", d, q + 4)
graph[nid] = ("S", attrs, mid)
elif cid == "LAYR":
lid, = struct.unpack_from("<i", d, c)
layers.append(rd_dict(d, c + 4)[0])
elif cid == "NOTE":
k, = struct.unpack_from("<i", d, c)
q = c + 4
for _ in range(k):
l, = struct.unpack_from("<i", d, q)
notes.append(d[q + 4:q + 4 + l].decode("latin1"))
q += 4 + l
elif cid == "rCAM":
cams.append(struct.unpack_from("<i", d, c)[0])
elif cid == "rOBJ":
robjs.append(rd_dict(d, c)[0])
p = c + n + m
# shape nodes in depth-first order with world transforms
shapes = []
def walk(nid, parent):
kind, attrs, child, frames = graph[nid]
f = frames[0] if frames else {}
R = rot(int(f["_r"])) if "_r" in f else [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
t = [int(v) for v in f.get("_t", "0 0 0").split()]
world = matmul(parent, [R[r] + [t[r]] for r in range(3)])
ch = graph.get(child)
if ch and ch[0] == "G":
for c2 in ch[2]:
walk(c2, world)
elif ch and ch[0] == "S":
shapes.append({"name": attrs.get("_name", ""), "model": ch[2] + 1, "world": [v for row in world for v in row]})
if 0 in graph:
walk(0, [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]])
pal = palette or default_palette()
out_models = []
for (sx, sy, sz), grid in models:
faces = 0
for z in range(sz):
for y in range(sy):
for x in range(sx):
if grid[x + sx * (y + sy * z)]:
for dx, dy, dz in ((1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)):
X, Y, Z = x + dx, y + dy, z + dz
if not (0 <= X < sx and 0 <= Y < sy and 0 <= Z < sz) or not grid[X + sx * (Y + sy * Z)]:
faces += 1
out_models.append({"size": [sx, sy, sz], "count": sum(1 for v in grid if v), "crc": zlib.crc32(bytes(grid)), "faces": faces})
return {
"version": version,
"models": out_models,
"paletteCrc": zlib.crc32(bytes(v for c in pal for v in c)),
"hasPalette": palette is not None,
"chunks": counts,
"shapes": shapes,
"layers": len(layers),
"materials": len(mats),
"notes": len(notes),
"cameras": len(cams),
"robjs": len(robjs),
"glassMaterials": sum(1 for m in mats.values() if m.get("_type") == "_glass"),
}
# ---------------------------------------------------------------------------------------------- writer (synthetic files)
def s(x):
b = x.encode()
return struct.pack("<i", len(b)) + b
def dct(d):
return struct.pack("<i", len(d)) + b"".join(s(k) + s(v) for k, v in d.items())
def chunk(cid, content, children=b""):
return cid.encode() + struct.pack("<ii", len(content), len(children)) + content + children
def vox(chunks, version=200, main_size=None):
body = b"".join(chunks)
return b"VOX " + struct.pack("<i", version) + b"MAIN" + struct.pack("<ii", 0, main_size if main_size is not None else len(body)) + body
def model(rng, sx, sy, sz, fill=0.4, colors=(1, 255)):
vox_list = []
for z in range(sz):
for y in range(sy):
for x in range(sx):
if rng.random() < fill:
vox_list.append((x, y, z, rng.randrange(*colors)))
rng.shuffle(vox_list)
return [chunk("SIZE", struct.pack("<iii", sx, sy, sz)), chunk("XYZI", struct.pack("<i", len(vox_list)) + b"".join(bytes(v) for v in vox_list))]
def ntrn(nid, child, attrs=None, frames=None, layer=0):
frames = frames or [{}]
return chunk("nTRN", struct.pack("<i", nid) + dct(attrs or {}) + struct.pack("<iiii", child, -1, layer, len(frames)) + b"".join(dct(f) for f in frames))
def ngrp(nid, children, attrs=None):
return chunk("nGRP", struct.pack("<i", nid) + dct(attrs or {}) + struct.pack("<i", len(children)) + b"".join(struct.pack("<i", c) for c in children))
def nshp(nid, models_):
return chunk("nSHP", struct.pack("<i", nid) + dct({}) + struct.pack("<i", len(models_)) + b"".join(struct.pack("<i", m) + dct({"_f": str(i)} if len(models_) > 1 else {}) for i, m in enumerate(models_)))
def rgba(rng):
return chunk("RGBA", bytes(rng.randrange(256) for _ in range(1024)))
def synthetic(rng):
out = []
# 1. a plain v150 model without a palette (the default palette)
out.append(("syn-default-palette", vox(model(rng, 7, 5, 3), 150)))
# 2. full scene: nested groups, every rotation family, mirrors, hidden, layers, materials, notes, cameras, IMAP, META
ch = []
for _ in range(4):
ch += model(rng, rng.randrange(1, 12), rng.randrange(1, 12), rng.randrange(1, 12))
ch += [
ntrn(0, 1, layer=-1),
ngrp(1, [2, 4, 8]),
ntrn(2, 3, {"_name": "a"}, [{"_r": "4", "_t": "1 2 3"}]),
nshp(3, [0]),
ntrn(4, 5, {"_name": "group", "_hidden": "1"}, [{"_r": "17", "_t": "-5 0 7"}], layer=1), # 90 deg about z
ngrp(5, [6, 10]),
ntrn(6, 7, {"_name": "b"}, [{"_r": "20", "_t": "0 0 -4"}]), # a mirror (x flipped)
nshp(7, [1]),
ntrn(8, 9, {"_name": "anim"}, [{"_r": "9", "_t": "3 3 3", "_f": "0"}, {"_r": "4", "_t": "4 4 4", "_f": "5"}]),
nshp(9, [2, 3]),
ntrn(10, 11, {"_name": "c"}, [{"_r": "98", "_t": "10 -20 30"}]),
nshp(11, [3]),
chunk("LAYR", struct.pack("<i", 0) + dct({"_name": "zero"}) + struct.pack("<i", -1)),
chunk("LAYR", struct.pack("<i", 1) + dct({"_name": "one", "_hidden": "1", "_color": "255 0 0"}) + struct.pack("<i", -1)),
rgba(rng),
chunk("IMAP", bytes(range(256))),
]
for mid in (1, 2, 200):
ch.append(chunk("MATL", struct.pack("<i", mid) + dct({"_type": ["_diffuse", "_glass", "_emit"][mid % 3], "_rough": "0.25", "_ior": "1.5", "_flux": "2"})))
ch.append(chunk("rOBJ", dct({"_type": "_bg", "_color": "0 0 0"})))
ch.append(chunk("rCAM", struct.pack("<i", 0) + dct({"_mode": "pers", "_focus": "0 0 0", "_angle": "30 40 0", "_radius": "80", "_frustum": "0.4", "_fov": "45"})))
ch.append(chunk("NOTE", struct.pack("<i", 2) + s("first") + s("second")))
ch.insert(0, chunk("META", dct({"_anim_range": "0 30"})))
ch.append(chunk("ZZZZ", b"unknown payload"))
out.append(("syn-scene", vox(ch)))
# 3. edge cases: voxels outside the grid, index 0, duplicates, a 1x1x1 model
vox_list = [(0, 0, 0, 5), (9, 0, 0, 7), (1, 1, 1, 0), (1, 1, 1, 9), (1, 1, 1, 10)]
ch = [chunk("SIZE", struct.pack("<iii", 2, 2, 2)), chunk("XYZI", struct.pack("<i", len(vox_list)) + b"".join(bytes(v) for v in vox_list)), rgba(rng)]
out.append(("syn-edge", vox(ch)))
out.append(("syn-single", vox([chunk("SIZE", struct.pack("<iii", 1, 1, 1)), chunk("XYZI", struct.pack("<i", 1) + bytes((0, 0, 0, 1)))])))
# 4. a full 64^3 block and a 3d checkerboard (worst case for greedy meshing)
full = [(x, y, z, 1 + (z % 3)) for z in range(64) for y in range(64) for x in range(64)]
out.append(("syn-block64", vox([chunk("SIZE", struct.pack("<iii", 64, 64, 64)), chunk("XYZI", struct.pack("<i", len(full)) + b"".join(bytes(v) for v in full))])))
chk = [(x, y, z, 3) for z in range(16) for y in range(16) for x in range(16) if (x + y + z) % 2 == 0]
out.append(("syn-checker16", vox([chunk("SIZE", struct.pack("<iii", 16, 16, 16)), chunk("XYZI", struct.pack("<i", len(chk)) + b"".join(bytes(v) for v in chk))])))
return out
def generate(ctx):
rng = ctx.rng(7)
cases = []
folder = os.path.join("tests", "fixtures", "vox")
for f in sorted(os.listdir(os.path.join(ctx.root, folder))):
if f.endswith(".vox"):
cases.append((f, ctx.read(os.path.join(folder, f))))
cases += synthetic(rng)
out = []
for name, data in cases:
ref = parse(data)
ref["name"] = name
ref["data"] = data
out.append(ref)
ctx.emit("vox_cases", out)
# the spec's default palette (parsed from the spec text) must equal the formula used by both readers
pal = spec_palette(ctx.read(os.path.join(folder, "MagicaVoxel-file-format-vox.txt")).decode())[1:]
assert pal == default_palette(), "default palette formula differs from the spec"
ctx.emit("vox_default_palette", [list(c) for c in pal])
+344
View File
@@ -0,0 +1,344 @@
# WebP fixtures (tools/fixtures.py). Reference tools: libwebp 1.6 (cwebp, dwebp, img2webp, gif2webp, webpmux),
# ImageMagick (built-in test images, an animated GIF), ffmpeg's libvpx (VP8 key frames from a second encoder, with
# token partitions and loop filter deltas, wrapped in a RIFF here) and Pillow (WebPAnimDecoder: composited frames).
# tests/gen/webp_src.luau the source images: { name, width, height, rgba }
# tests/gen/webp_cases.luau still files: { name, data, width, height, crc (dwebp -pam), lossy, yuv (dwebp -yuv),
# nofancy (dwebp -nofancy -pam), alpha, meta }
# tests/gen/webp_anim.luau animations: { name, data, width, height, loops, frames = { crc, ms } (Pillow) }
# tests/gen/webp_enc.luau our encoder's output checked by dwebp / Pillow (tools/fixtures/_webp_encode.luau):
# { name, effort, crc, ok, size, cwebp }, animations { name, crc, frames }
# tests/gen/webp_bench.luau bigger lossy / lossless files for tools/bench.luau
import json, os, random, shutil, struct, subprocess, tempfile, zlib
INPUTS = ["tools/fixtures/_webp_encode.luau", "src/Formats/codecs/Vp8L", "src/Formats/image/webp"]
TOOLS = ["libwebp", "imagemagick", "ffmpeg"]
def run(tmp, script):
path = os.path.join(tmp, "run.sh")
with open(path, "w") as f:
f.write("set -e\n" + script)
cmd = ["nix", "shell"] + ["nixpkgs#" + t for t in TOOLS] + ["-c", "bash", path]
subprocess.run(cmd, cwd=tmp, check=True, capture_output=True)
def pam_write(path, w, h, rgba):
with open(path, "wb") as f:
f.write(b"P7\nWIDTH %d\nHEIGHT %d\nDEPTH 4\nMAXVAL 255\nTUPLTYPE RGB_ALPHA\nENDHDR\n" % (w, h) + bytes(rgba))
def pam_read(data):
end = data.index(b"ENDHDR\n") + 7
hdr = dict(l.split(b" ", 1) for l in data[:end].split(b"\n")[1:] if b" " in l)
w, h, d = int(hdr[b"WIDTH"]), int(hdr[b"HEIGHT"]), int(hdr[b"DEPTH"])
px = data[end:end + w * h * d]
if d == 4:
return w, h, px
out = bytearray(w * h * 4)
for i in range(w * h):
if d == 3:
out[i * 4:i * 4 + 3] = px[i * 3:i * 3 + 3]
else:
out[i * 4:i * 4 + 3] = bytes([px[i * d]]) * 3
out[i * 4 + 3] = 255 if d < 2 or d == 3 else px[i * d + 1]
return w, h, bytes(out)
def synthetic(rng):
out = []
def img(name, w, h, f):
px = bytearray()
for y in range(h):
for x in range(w):
px += bytes(f(x, y))
out.append((name, w, h, bytes(px)))
img("tiny", 1, 1, lambda x, y: (200, 10, 30, 255))
img("odd", 3, 7, lambda x, y: (rng.randrange(256), rng.randrange(256), rng.randrange(256), 255))
img("strip", 257, 3, lambda x, y: ((x * 7) & 255, (x + y * 50) & 255, (x * x) & 255, 255))
two = [(0, 0, 0, 255), (255, 255, 255, 255)]
img("pal2", 33, 17, lambda x, y: two[(x * 3 + y * 5) % 7 < 3])
three = [(255, 0, 0, 255), (0, 255, 0, 128), (0, 0, 255, 0)]
img("pal3", 40, 9, lambda x, y: three[(x // 3 + y) % 3])
five = [(rng.randrange(256), rng.randrange(256), rng.randrange(256), 255) for _ in range(5)]
img("pal5", 25, 25, lambda x, y: five[(x * y + x) % 5])
p16 = [(rng.randrange(256), rng.randrange(256), rng.randrange(256), rng.choice([255, 255, 90])) for _ in range(16)]
img("pal16", 64, 40, lambda x, y: p16[((x // 4) * 3 + y // 5) % 16])
p17 = [(i * 15, 255 - i * 15, (i * 77) & 255, 255) for i in range(17)]
img("pal17", 51, 30, lambda x, y: p17[(x + y) % 17])
p256 = [(i, (i * 3) & 255, (i * 7) & 255, 255 if i % 9 else 128) for i in range(256)]
img("pal256", 64, 64, lambda x, y: p256[(x * 64 + y * 5 + x * y) % 256])
img("noise", 48, 48, lambda x, y: (rng.randrange(256), rng.randrange(256), rng.randrange(256), rng.randrange(256)))
img("grad", 100, 60, lambda x, y: (x * 255 // 99, y * 255 // 59, (x + y) * 255 // 158, min(255, x * 3 + y)))
img("trans", 50, 50, lambda x, y: (rng.randrange(256), rng.randrange(256), rng.randrange(256), 0 if (x - 25) ** 2 + (y - 25) ** 2 > 300 else 255))
return out
def add_alpha(name, w, h, px, kind):
out = bytearray(px)
for y in range(h):
for x in range(w):
i = (y * w + x) * 4 + 3
if kind == "ramp":
out[i] = 0 if x < w // 6 else min(255, (x * 255) // max(1, w - 1) + 20)
else:
out[i] = 255 if (x // 8 + y // 8) % 3 else (x * y) & 255
return name, w, h, bytes(out)
LOSSLESS = [("z0", "-lossless -z 0"), ("z3", "-lossless -z 3"), ("z6", "-lossless -z 6"), ("z9", "-lossless -z 9"),
("exact", "-lossless -exact -m 6 -q 100"), ("near", "-lossless -near_lossless 40")]
LOSSY = [("q5", "-q 5"), ("q50", "-q 50"), ("q90", "-q 90 -m 6"), ("simple", "-q 75 -nostrong -sharpness 5"),
("seg1", "-q 30 -f 100 -segments 1"), ("nofilter", "-q 60 -sns 0 -f 0"), ("sharpyuv", "-q 80 -sharp_yuv -af")]
ALPHA = [("araw", "-q 70 -alpha_method 0"), ("afnone", "-q 70 -alpha_filter none"), ("affast", "-q 70 -alpha_filter fast"),
("afbest", "-q 70 -alpha_filter best -exact"), ("aq30", "-q 70 -alpha_q 30")]
FULL = {"rose", "plasma", "rose_a", "pal16", "grad", "odd"} # every lossless / lossy variant; others get a few
def ivf_frames(data):
frames, p = [], 32
while p + 12 <= len(data):
n = struct.unpack_from("<I", data, p)[0]
frames.append(data[p + 12:p + 12 + n])
p += 12 + n
return frames
def riff(chunks):
body = b"WEBP"
for fourcc, payload in chunks:
body += fourcc + struct.pack("<I", len(payload)) + payload + (b"\0" if len(payload) % 2 else b"")
return b"RIFF" + struct.pack("<I", len(body)) + body
def chunks_of(data):
out, p = [], 12
while p + 8 <= len(data):
fourcc, n = data[p:p + 4], struct.unpack_from("<I", data, p + 4)[0]
out.append((fourcc, data[p + 8:p + 8 + n]))
p += 8 + n + n % 2
return out
def filter_alpha(a, w, h, f):
out = bytearray(w * h)
for y in range(h):
for x in range(w):
i = y * w + x
if f == 0:
pred = 0
elif y == 0:
pred = a[i - 1] if x else 0
elif x == 0:
pred = a[i - w]
elif f == 1:
pred = a[i - 1]
elif f == 2:
pred = a[i - w]
else:
pred = max(0, min(255, a[i - 1] + a[i - w] - a[i - w - 1]))
out[i] = (a[i] - pred) & 255
return bytes(out)
def craft_alpha(tmp, base_alpha):
name, w, h, px = base_alpha
a = bytes(px[i] for i in range(3, len(px), 4))
src = dict(chunks_of(open(os.path.join(tmp, "rose_a_afnone.webp"), "rb").read()))
out = []
for f in range(4):
alph = bytes([f << 2]) + filter_alpha(a, w, h, f)
data = riff([(b"VP8X", src[b"VP8X"]), (b"ALPH", alph), (b"VP8 ", src[b"VP8 "])])
fname = "alph_raw_f%d.webp" % f
open(os.path.join(tmp, fname), "wb").write(data)
out.append((fname, {"lossy": True}))
return out
def generate(ctx):
tmp = tempfile.mkdtemp(prefix="webp_fx_")
try:
_generate(ctx, tmp)
finally:
shutil.rmtree(tmp, ignore_errors=True)
def _generate(ctx, tmp):
rng = ctx.rng(20260)
# 1. sources: ImageMagick's built-in images (resized) + synthetic ones
run(tmp, "\n".join([
"magick rose: -alpha off PAM:rose.pam",
"magick granite: -alpha off PAM:granite.pam",
"magick netscape: -alpha off PAM:netscape.pam",
"magick wizard: -resize 120x160 -alpha off PAM:wizard.pam",
"magick logo: -resize 160x120 -alpha off PAM:logo.pam",
"magick -seed 7 -size 200x150 plasma:fractal -depth 8 -alpha off PAM:plasma.pam",
"magick wizard: -resize 512x512! -alpha off PAM:bench.pam",
]))
sources = []
for n in ["rose", "granite", "netscape", "wizard", "logo", "plasma"]:
w, h, px = pam_read(open(os.path.join(tmp, n + ".pam"), "rb").read())
sources.append((n, w, h, px))
base = {s[0]: s for s in sources}
sources.append(add_alpha("rose_a", *base["rose"][1:], "ramp"))
sources.append(add_alpha("plasma_a", *base["plasma"][1:], "blocks"))
sources += synthetic(rng)
for n, w, h, px in sources:
pam_write(os.path.join(tmp, n + ".pam"), w, h, px)
ctx.emit("webp_src", [{"name": n, "width": w, "height": h, "rgba": px} for n, w, h, px in sources])
# 2. still files: cwebp lossless / lossy / alpha variants, libvpx key frames, metadata
files = [] # (name, extra info)
lines = []
for n, w, h, px in sources:
has_alpha = any(px[i] != 255 for i in range(3, len(px), 4))
full = n in FULL
for tag, args in LOSSLESS if full else LOSSLESS[2:3]:
lines.append("cwebp -quiet %s %s.pam -o %s_%s.webp" % (args, n, n, tag))
files.append(("%s_%s.webp" % (n, tag), {"lossy": False}))
for tag, args in LOSSY if full else LOSSY[1:2]:
lines.append("cwebp -quiet %s %s.pam -o %s_%s.webp" % (args, n, n, tag))
files.append(("%s_%s.webp" % (n, tag), {"lossy": True}))
if has_alpha:
for tag, args in ALPHA if full or n == "plasma_a" else ALPHA[1:2]:
lines.append("cwebp -quiet %s %s.pam -o %s_%s.webp" % (args, n, n, tag))
files.append(("%s_%s.webp" % (n, tag), {"lossy": True}))
for n in ["rose", "granite", "plasma", "wizard"]:
for k, (slices, q) in enumerate([(1, 10), (2, 30), (4, 50), (8, 63)]):
lines.append("magick %s.pam -alpha off PNG24:%s_vpx.png" % (n, n))
lines.append("ffmpeg -loglevel error -y -i %s_vpx.png -c:v libvpx -slices %d -qmin %d -qmax %d -b:v 1M -sharpness %d -f ivf %s_vpx%d.ivf"
% (n, slices, q, q, k, n, k))
lines.append("cwebp -quiet -q 60 rose_a.pam -o meta_base.webp")
lines.append("head -c 600 /dev/urandom > meta.icc && head -c 100 /dev/urandom > meta.exif && printf '<x:xmpmeta/>' > meta.xmp")
lines.append("webpmux -set icc meta.icc meta_base.webp -o meta1.webp")
lines.append("webpmux -set exif meta.exif meta1.webp -o meta2.webp")
lines.append("webpmux -set xmp meta.xmp meta2.webp -o meta_all.webp")
lines.append("cwebp -quiet -lossless -metadata all rose.pam -o meta_ll.webp && webpmux -set icc meta.icc meta_ll.webp -o meta_ll_icc.webp")
files.append(("meta_all.webp", {"lossy": True, "meta": True}))
files.append(("meta_ll_icc.webp", {"lossy": False, "meta": True}))
run(tmp, "\n".join(lines))
for n in ["rose", "granite", "plasma", "wizard"]:
for k in range(4):
data = open(os.path.join(tmp, "%s_vpx%d.ivf" % (n, k)), "rb").read()
frame = ivf_frames(data)[0]
name = "%s_vpx%d.webp" % (n, k)
open(os.path.join(tmp, name), "wb").write(riff([(b"VP8 ", frame)]))
files.append((name, {"lossy": True}))
# raw ALPH chunks with each of the four filters, written here (rose_a's alpha over its lossy VP8 data)
files += craft_alpha(tmp, base_alpha=[s for s in sources if s[0] == "rose_a"][0])
# references
lines = []
for name, info in files:
lines.append("dwebp -quiet %s -pam -o %s.pam" % (name, name))
if info["lossy"]:
lines.append("dwebp -quiet %s -nofancy -pam -o %s.nf.pam" % (name, name))
lines.append("dwebp -quiet %s -yuv -o %s.yuv" % (name, name))
run(tmp, "\n".join(lines))
cases = []
for name, info in files:
data = open(os.path.join(tmp, name), "rb").read()
w, h, px = pam_read(open(os.path.join(tmp, name + ".pam"), "rb").read())
c = {"name": name, "data": data, "width": w, "height": h, "crc": zlib.crc32(px), "lossy": info["lossy"],
"alpha": any(px[i] != 255 for i in range(3, len(px), 4))}
if info["lossy"]:
c["nofancy"] = zlib.crc32(pam_read(open(os.path.join(tmp, name + ".nf.pam"), "rb").read())[2])
c["yuv"] = zlib.crc32(open(os.path.join(tmp, name + ".yuv"), "rb").read())
if info.get("meta"):
c["icc"] = zlib.crc32(open(os.path.join(tmp, "meta.icc"), "rb").read())
if name == "meta_all.webp":
c["exif"] = zlib.crc32(open(os.path.join(tmp, "meta.exif"), "rb").read())
c["xmp"] = "<x:xmpmeta/>"
cases.append(c)
ctx.emit("webp_cases", cases)
# 3. animations: img2webp (sub-rectangles, blending, mixed lossy / lossless), gif2webp, webpmux frames
lines = []
# frames of one canvas size: rose-sized crops of the sources
for i, (n, w, h, px) in enumerate([s for s in sources if s[0] in ("plasma", "plasma_a", "wizard", "grad", "noise", "netscape")]):
lines.append("magick %s.pam -resize 70x46! -depth 8 PAM:af%d.pam" % (n, i))
lines.append("magick rose.pam -fill red -draw 'rectangle 10,10 30,20' PAM:af6.pam")
lines.append("magick rose.pam -fill blue -draw 'rectangle 40,20 60,40' PAM:af7.pam")
lines.append("magick rose.pam -alpha on -channel A -evaluate set 50%% +channel PAM:af8.pam")
lines.append("img2webp -loop 3 -lossless rose.pam -d 80 af6.pam -d 120 af7.pam af8.pam -lossy -q 60 af0.pam -o anim_mixed.webp")
lines.append("img2webp -min_size -lossless af1.pam af3.pam -d 40 af4.pam af8.pam -o anim_alpha.webp")
lines.append("img2webp -kmax 2 -lossy -q 40 af0.pam af2.pam af5.pam -mixed af6.pam af7.pam -o anim_lossy.webp")
lines.append("magick -dispose background -delay 10 -size 60x40 xc:none -fill red -draw 'circle 20,20 30,20' "
"-dispose previous -delay 20 -size 60x40 xc:none -fill blue -draw 'rectangle 5,5 25,30' "
"-dispose none -delay 30 -size 60x40 xc:none -fill green -draw 'rectangle 30,10 55,35' "
"-loop 0 anim.gif")
lines.append("gif2webp -quiet anim.gif -o anim_gif.webp")
lines.append("gif2webp -quiet -lossy -q 50 anim.gif -o anim_gif_lossy.webp")
lines.append("cwebp -quiet -lossless af6.pam -o fr1.webp && cwebp -quiet -q 50 af7.pam -o fr2.webp")
lines.append("webpmux -frame fr1.webp +100+0+0+0-b -frame fr2.webp +50+10+6+1+b -loop 1 -bgcolor 255,1,2,3 -o anim_mux.webp")
lines.append("webpmux -set icc meta.icc anim_mux.webp -o anim_mux_icc.webp")
run(tmp, "\n".join(lines))
anims = ["anim_mixed.webp", "anim_alpha.webp", "anim_lossy.webp", "anim_gif.webp", "anim_gif_lossy.webp", "anim_mux_icc.webp"]
ref = pillow_frames(ctx, [os.path.join(tmp, a) for a in anims])
out = []
for a, r in zip(anims, ref):
out.append({"name": a, "data": open(os.path.join(tmp, a), "rb").read(), "width": r["w"], "height": r["h"],
"loops": r["loop"], "rgba": r["mode"] == "RGBA", "frames": [{"crc": c, "ms": d} for c, d in r["frames"]]})
ctx.emit("webp_anim", out)
# 4. our encoder, checked by dwebp (still) and Pillow (animations)
res = subprocess.run(["nix", "shell", "nixpkgs#luau", "-c", "luau", "tools/fixtures/_webp_encode.luau"],
cwd=ctx.root, check=True, capture_output=True).stdout.decode()
ours = []
for line in res.split("\n"):
if line.strip():
name, hexdata = line.split(" ")
path = os.path.join(tmp, "ours_" + name.split(":")[0] + ".webp")
open(path, "wb").write(bytes.fromhex(hexdata))
ours.append((name, path))
run(tmp, "\n".join("dwebp -quiet %s -pam -o %s.pam" % (p, p) for n, p in ours if not n.startswith("anim")) + "\n" +
"\n".join("cwebp -quiet -lossless -exact %s.pam -o cw_%s.webp" % (n, n) for n, w, h, px in sources))
src = {n: (w, h, px) for n, w, h, px in sources}
enc = []
anim_paths = [(n, p) for n, p in ours if n.startswith("anim")]
aref = pillow_frames(ctx, [p for n, p in anim_paths])
for name, path in ours:
if name.startswith("anim"):
continue
sname, effort, mode = name.rsplit("_", 2)
w, h, px = src[sname]
_, _, got = pam_read(open(path + ".pam", "rb").read())
want = px if mode == "exact" else bytes(b if px[(i // 4) * 4 + 3] else 0 for i, b in enumerate(px))
enc.append({"name": sname, "effort": int(effort[1:]), "exact": mode == "exact", "ok": got == want,
"size": os.path.getsize(path), "cwebp": os.path.getsize(os.path.join(tmp, "cw_%s.webp" % sname))})
anim_out = []
for (n, p), r in zip(anim_paths, aref):
aname, want = n.split(":")
got = [c for c, d in r["frames"]]
anim_out.append({"name": aname, "data": open(p, "rb").read(), "frames": got, "ms": [d for c, d in r["frames"]],
"loops": r["loop"], "ok": got == [int(c) for c in want.split(",")]})
ctx.emit("webp_enc", {"still": enc, "anim": anim_out})
# 5. bench: a 512 x 512 lossy and lossless file
run(tmp, "cwebp -quiet -q 80 bench.pam -o bench_lossy.webp\ncwebp -quiet -lossless bench.pam -o bench_ll.webp")
w, h, px = pam_read(open(os.path.join(tmp, "bench.pam"), "rb").read())
ctx.emit("webp_bench", {"width": w, "height": h, "rgba": px,
"lossy": open(os.path.join(tmp, "bench_lossy.webp"), "rb").read(),
"lossless": open(os.path.join(tmp, "bench_ll.webp"), "rb").read()})
PILLOW = r"""
import json, sys, zlib
from PIL import Image
out = []
for path in sys.argv[1:]:
im = Image.open(path)
frames = []
for i in range(getattr(im, "n_frames", 1)):
im.seek(i)
frames.append([zlib.crc32(im.convert("RGBA").tobytes()), im.info.get("duration", 0)])
out.append({"w": im.width, "h": im.height, "mode": im.mode, "loop": im.info.get("loop", 0), "frames": frames})
print(json.dumps(out))
"""
def pillow_frames(ctx, paths):
expr = "with import <nixpkgs> {}; python3.withPackages (p: [p.pillow])"
cmd = ["nix", "shell", "--impure", "--expr", expr, "-c", "python3", "-I", "-c", PILLOW] + paths
return json.loads(subprocess.run(cmd, capture_output=True, check=True).stdout)
+174
View File
@@ -0,0 +1,174 @@
# codecs/Xml + data/xml fixtures: random documents (namespaces, attributes with every escape, CDATA, comments, PIs,
# entities from an internal DOCTYPE, mixed content) written by hand, then parsed by Python's xml.etree (expat) for the
# reference tree; the same documents re-encoded as UTF-16 and Latin-1; and well-formedness cases (hand-written plus
# random mutations) with expat's verdict.
# tests/gen/xml_docs.luau { { data, canon } } canon: see canon() below (the test computes the same)
# tests/gen/xml_wf.luau { { data, ok } } ok: expat accepts it
# tests/gen/xml_bench.luau { text } (~1 MB)
import xml.etree.ElementTree as ET
from xml.parsers import expat
NS = [("", None), ("a", "urn:a"), ("b", "http://example.com/b")]
TAGS = ["item", "x", "Data", "set-1", "q.r", "_u", "élément", "名"]
TXT = "ab <>&\"' é中\U0001f600\t\n ]]"
def s(x):
x = x or ""
b = x.encode("utf-8", "surrogatepass")
return b"%d:" % len(b) + b
def canon(e):
out = b"(" + s(e.tag)
for k in sorted(e.attrib):
out += b"|" + s(k) + b"=" + s(e.attrib[k])
out += b"|t" + s(e.text)
for c in e:
out += canon(c)
return out + b")t" + s(e.tail)
def esc_text(t):
return t.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
def esc_attr(t, q):
t = t.replace("&", "&amp;").replace("<", "&lt;")
return t.replace(q, "&quot;" if q == '"' else "&apos;")
def rand_text(rng):
return "".join(rng.choice(TXT) for _ in range(rng.randrange(0, 10)))
def gen_elem(rng, depth, declared):
prefix = rng.choice([p for p in declared])
local = rng.choice(TAGS)
name = (prefix + ":" + local) if prefix else local
attrs = []
newdecl = set(declared)
if depth > 0 and rng.random() < 0.15:
p, uri = rng.choice(NS[1:])
attrs.append(("xmlns:" + p, uri))
newdecl.add(p)
if rng.random() < 0.1:
attrs.append(("xmlns", "urn:default%d" % rng.randrange(3)))
used = set(a for a, _ in attrs)
for _ in range(rng.randrange(0, 4)):
an = rng.choice(["id", "k", "v-1", "é", "x.y"])
if rng.random() < 0.2 and len(newdecl) > 1:
an = rng.choice([p for p in newdecl if p]) + ":" + an
if an in used:
continue
used.add(an)
attrs.append((an, rand_text(rng)))
parts = ["<" + name]
for k, v in attrs:
q = rng.choice("\"'")
parts.append(" %s=%s%s%s" % (k, q, esc_attr(v, q), q))
if depth > 4 or rng.random() < 0.15:
parts.append(rng.choice(["/>", " />"]))
return "".join(parts)
parts.append(">")
for _ in range(rng.randrange(0, 5)):
r = rng.random()
if r < 0.35:
parts.append(esc_text(rand_text(rng)))
elif r < 0.45:
parts.append("<![CDATA[" + rand_text(rng).replace("]", "] ") + "<&>]]>")
elif r < 0.5:
parts.append("<!-- c " + rand_text(rng).replace("-", "=") + " -->")
elif r < 0.53:
parts.append("<?pi data " + rand_text(rng).replace("?", "") + "?>")
elif r < 0.58:
parts.append(rng.choice(["&ent;", "&#233;", "&#x1F600;", "&amp;", "&lt;", "&#10;"]))
else:
parts.append(gen_elem(rng, depth + 1, newdecl))
parts.append("</%s>" % name)
return "".join(parts)
def gen_doc(rng):
head = ""
if rng.random() < 0.5:
head += '<?xml version="1.0" encoding="UTF-8"?>\n'
head += '<!DOCTYPE root [\n <!ENTITY ent "entity &#38;#38; text &lt;">\n <!-- a comment -->\n]>\n'
if rng.random() < 0.3:
head += "<!-- prolog comment -->\n"
declared = {""}
body = gen_elem(rng, 0, declared)
# the root must declare every prefix it may use: declare all at the root
root_decl = " ".join('xmlns:%s="%s"' % (p, u) for p, u in NS[1:])
i = body.index(">") if not body.startswith("<") else 0
name_end = 1
while body[name_end] not in " />":
name_end += 1
body = body[:name_end] + " " + root_decl + body[name_end:]
return head + body + ("\n" if rng.random() < 0.5 else "")
def expat_ok(data):
p = expat.ParserCreate()
try:
p.Parse(data, True)
return True
except Exception: # ExpatError, or LookupError for an unknown encoding name
return False
WF = [
"<a/>", "<a></a>", "<a><b/></a>", "<a>x</b>", "<a>", "</a>", "<a/><b/>", "text<a/>", "<a/>text", "<a b='1' b='2'/>",
"<a b=1/>", "<a b='<'/>", "<a>&undefined;</a>", "<a>&#0;</a>", "<a>&#x110000;</a>", "<a>&#xD800;</a>", "<a>& </a>",
"<a><!-- x -- y --></a>", "<a><!-- x ---></a>", "<a>]]></a>", "<1a/>", "<a 1b='x'/>", "<a b='x'c='y'/>",
"<?xml version='1.0'?><a/>", " <?xml version='1.0'?><a/>", "<a/><?xml version='1.0'?>", "<a><![CDATA[x]]></a>",
"<![CDATA[x]]><a/>", "<a><![CDATA[x</a>", "<a>\x01</a>", "<a b='\x01'/>", "<a><?pi x?></a>", "<a><?pi?></a>",
"<!DOCTYPE a><a/>", "<a/><!DOCTYPE a>", "<!DOCTYPE a [<!ENTITY e 'v'>]><a>&e;</a>", "<a b='&lt;&#65;'/>",
"<a:b xmlns:a='u'/>", "<a\n b\n =\n 'c'\n/>", "<a></a >", "<a></ a>", "< a/>", "<a/ >", "<a b='x' / >",
"<a>é\U0001f600</a>", "<a>&amp;&lt;&gt;&quot;&apos;</a>", "<?xml version='1.0' encoding='UTF-8' standalone='yes'?><a/>",
"<!-- c --><a/><!-- d -->", "<a><!----></a>", "", " ", "<a>x</a>trailing", "<a>x</a><!-- ok --> ",
]
def generate(ctx):
rng = ctx.rng(11)
docs = []
for k in range(250):
text = gen_doc(rng)
root = ET.fromstring(text.encode("utf-8"))
docs.append({"data": text.encode("utf-8"), "canon": canon(root)})
# other encodings: UTF-16 (BOM, both byte orders) and Latin-1
for k in range(10):
text = gen_doc(rng)
body = text.split("?>", 1)[1] if text.startswith("<?xml") else text
c = canon(ET.fromstring(text.encode("utf-8")))
docs.append({"data": ('<?xml version="1.0" encoding="UTF-16"?>' + body).encode("utf-16"), "canon": c})
docs.append({"data": b"\xfe\xff" + ('<?xml version="1.0" encoding="UTF-16"?>' + body).encode("utf-16-be"), "canon": c})
for k in range(10):
text = "<?xml version='1.0' encoding='ISO-8859-1'?><r a='éÿ'>café ½ &#x4e2d;</r>"
data = text.encode("latin-1")
docs.append({"data": data, "canon": canon(ET.fromstring(data))})
ctx.emit("xml_docs", docs)
wf = [{"data": d.encode("utf-8"), "ok": expat_ok(d.encode("utf-8"))} for d in WF]
# mutations of valid documents: delete / duplicate / replace one markup character
for k in range(400):
text = gen_doc(rng).encode("utf-8")
b = bytearray(text)
for _ in range(rng.randrange(1, 3)):
pos = rng.randrange(len(b))
op = rng.randrange(3)
ch = rng.choice(b"<>/&;='\"![]-? ")
if op == 0:
del b[pos]
elif op == 1:
b.insert(pos, ch)
else:
b[pos] = ch
wf.append({"data": bytes(b), "ok": expat_ok(bytes(b))})
ctx.emit("xml_wf", wf)
parts = []
while sum(map(len, parts)) < 1_000_000:
parts.append(gen_elem(rng, 1, {""}))
ctx.emit("xml_bench", {"text": "<root>" + "\n".join(p for p in parts if "&ent;" not in p) + "</root>"})
+111
View File
@@ -0,0 +1,111 @@
# data/yaml fixtures: the yaml-test-suite (data release 2022-01-17, pinned tarball through nix: every case's
# in.yaml, its in.json when there is one, and whether it is an error case), and a random corpus dumped by PyYAML
# (through nix) in several styles: block, flow, indent 4, explicit documents, allow_unicode, multi-document. The
# corpus avoids the strings where YAML 1.1 (PyYAML) and 1.2 resolve plain scalars differently.
# tests/gen/yaml_suite.luau { { name, yaml, json?, error } }
# tests/gen/yaml_corpus.luau { { canon, texts = { [style] = yaml } } }
# tests/gen/yaml_bench.luau { text } (~500 KB, block style)
import importlib.util, json, os, random
_spec = importlib.util.spec_from_file_location("_data_common", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_data_common.py"))
C = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(C)
SUITE_URL = "https://github.com/yaml/yaml-test-suite/archive/refs/tags/data-2022-01-17.tar.gz"
SUITE_SHA = "00xcny67bp56xkvz4iq6d2prvj9p48z7r705xrw49invvgyp4wnd"
WORDS = ["a", "key", "value", "x y", "café", "中文", "\U0001f600", "multi\nline", "trail\n", "two\n\n",
" lead", "tail ", "a: b", "# c", "- x", "[x]", "{y}", "'q'", "\"dq\"", "true", "null", "~", "12", "1.5",
"0x1F", "yes", "no", "on", "-", "?", ":", "a#b", "tab\there", "back\\slash", "", "éé é",
"line1\n indented\nline3", "ends with colon:", "---", "...", "%x", "@x", "`x", "*x", "&x", "!x", "|", ">"]
def rand_value(rng, depth=0):
r = rng.random()
if depth > 3 or r < 0.5:
k = rng.randrange(8)
if k == 0:
return None
if k == 1:
return rng.random() < 0.5
if k == 2:
return rng.randrange(-10 ** 12, 10 ** 12)
if k == 3:
v = round(rng.uniform(-1e5, 1e5), rng.randrange(1, 6))
return int(v) if v.is_integer() else v
return rng.choice(WORDS) + (rng.choice(WORDS) if rng.random() < 0.3 else "")
if r < 0.75:
return [rand_value(rng, depth + 1) for _ in range(rng.randrange(0, 5))]
d = {}
for _ in range(rng.randrange(0, 5)):
k = rng.choice(WORDS[:30])
if rng.random() < 0.15:
k = rng.randrange(100)
d[k] = rand_value(rng, depth + 1)
return d
DUMP = r'''
import json, sys, yaml
values = json.loads(sys.stdin.read())
def fix(v): # JSON object keys are strings: restore the int keys marked "#int:"
if isinstance(v, dict):
return {(int(k[5:]) if k.startswith("#int:") else k): fix(x) for k, x in v.items()}
if isinstance(v, list):
return [fix(x) for x in v]
return v
out = []
for v in values:
v = fix(v)
t = {
"block": yaml.safe_dump(v, default_flow_style=False, sort_keys=False, allow_unicode=True),
"flow": yaml.safe_dump(v, default_flow_style=True, sort_keys=False),
"indent4": yaml.safe_dump(v, default_flow_style=False, indent=4, explicit_start=True, explicit_end=True),
"auto": yaml.safe_dump(v, sort_keys=True, width=20),
"multi": yaml.safe_dump_all([v, {"second": v}], default_flow_style=False, allow_unicode=True),
}
back = yaml.safe_load(t["block"])
out.append({"texts": t, "same": back == v})
print(json.dumps(out))
'''
def keyed(v):
if isinstance(v, dict):
return {("#int:%d" % k if isinstance(k, int) else k): keyed(x) for k, x in v.items()}
if isinstance(v, list):
return [keyed(x) for x in v]
return v
def generate(ctx):
root = C.fetch(SUITE_URL, SUITE_SHA)
cases = []
for name in sorted(os.listdir(root)):
d = os.path.join(root, name)
if not os.path.isdir(d) or name.startswith("."):
continue
dirs = [d] if os.path.exists(os.path.join(d, "in.yaml")) else [os.path.join(d, x) for x in sorted(os.listdir(d))]
for dd in dirs:
if not os.path.exists(os.path.join(dd, "in.yaml")):
continue
c = {"name": os.path.relpath(dd, root), "yaml": open(os.path.join(dd, "in.yaml"), "rb").read(),
"error": os.path.exists(os.path.join(dd, "error"))}
if os.path.exists(os.path.join(dd, "in.json")):
c["json"] = open(os.path.join(dd, "in.json"), "rb").read()
cases.append(c)
ctx.emit("yaml_suite", cases)
rng = ctx.rng(5)
values = [rand_value(rng) for _ in range(250)]
dumped = json.loads(ctx.python(["pyyaml"], DUMP, input=json.dumps([keyed(v) for v in values]).encode()))
corpus = []
for v, d in zip(values, dumped):
if d["same"]:
corpus.append({"canon": C.canon(v), "multi": C.canon([v, {"second": v}]), "texts": d["texts"]})
ctx.emit("yaml_corpus", corpus)
big = [rand_value(rng) for _ in range(1500)]
text = json.loads(ctx.python(["pyyaml"], "import json, sys, yaml\nprint(json.dumps(yaml.safe_dump(json.loads(sys.stdin.read()), default_flow_style=False, allow_unicode=True)))",
input=json.dumps([x for x in big if not isinstance(x, dict) or all(isinstance(k, str) for k in x)]).encode()))
ctx.emit("yaml_bench", {"text": text})
+85
View File
@@ -0,0 +1,85 @@
# Zstd fixtures (tools/fixtures.py): deterministic corpora compressed with the zstd CLI (the reference) at levels
# 1..19 and --ultra -22, --long, small windows (small blocks), with / without the content checksum, with / without the
# content size (stdin), multi-frame and skippable-frame streams, and empty input; plus a ~6 MB bench corpus.
# tests/gen/zstd.luau { corpora = { [name] = bytes }, cases = { { name, corpus, data } } }
# tests/gen/zstd_bench.luau { size, data3, data19, crc }
import os, random, shutil, subprocess, tempfile, zlib
def generate(ctx):
rng = random.Random(7)
def zstd(args, data, from_file=True):
exe = shutil.which("zstd")
if from_file:
with tempfile.TemporaryDirectory() as d:
p = os.path.join(d, "in")
with open(p, "wb") as f:
f.write(data)
argv = ["zstd", "-q", "-c"] + args + [p]
if exe:
return subprocess.run([exe] + argv[1:], capture_output=True, check=True).stdout
return ctx.nix("zstd", argv)
argv = ["zstd", "-q", "-c"] + args
if exe:
return subprocess.run([exe] + argv[1:], input=data, capture_output=True, check=True).stdout
return ctx.nix("zstd", argv, input=data)
def text_corpus(limit):
base = os.path.dirname(os.__file__)
out = bytearray()
for name in sorted(os.listdir(base)):
if name.endswith(".py"):
with open(os.path.join(base, name), "rb") as f:
out += f.read()
if len(out) >= limit:
break
return bytes(out[:limit])
text = text_corpus(400000)
corpora = {
"empty": b"",
"one": b"a",
"short": b"hello, hello, hello zstd world\n",
"text": text[:200000],
"random": rng.randbytes(50000),
"runs": b"abc" * 4000 + b"\0" * 20000 + bytes(range(256)) * 40 + b"z" * 300,
"far": (lambda r: r + rng.randbytes(30000) + r)(rng.randbytes(20000)),
"binary": bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(60000)),
"mixed": bytes(rng.choice(b"aaaaabbbcd\n") for _ in range(30000)) + rng.randbytes(3000) + text[200000:300000],
"big": (text + bytes(rng.choice(b"\0\0\x01\x02\x03xyz") for _ in range(200000))),
}
cases = [] # (name, corpus, data)
for cname, data in corpora.items():
levels = [1, 3, 19] if cname in ("big",) else [1, 2, 3, 5, 7, 9, 12, 15, 17, 19]
for lv in levels:
cases.append(("%s/l%d" % (cname, lv), cname, zstd(["-%d" % lv], data)))
if cname != "big":
cases.append(("%s/ultra22" % cname, cname, zstd(["--ultra", "-22"], data)))
cases.append(("%s/long" % cname, cname, zstd(["--long=24", "-9"], data)))
cases.append(("%s/negative" % cname, cname, zstd(["--fast=3"], data)))
cases.append(("%s/wlog10" % cname, cname, zstd(["--zstd=wlog=10", "-6"], data)))
cases.append(("%s/nocheck" % cname, cname, zstd(["-5", "--no-check"], data)))
cases.append(("%s/stdin" % cname, cname, zstd(["-4", "--check"], data, from_file=False)))
# several frames, a skippable frame between them, and a skippable frame first
t = corpora["text"]
skip = (0x184D2A53).to_bytes(4, "little") + (11).to_bytes(4, "little") + b"skip me now"
multi = zstd(["-3"], t[:50000]) + skip + zstd(["-1", "--no-check"], corpora["runs"]) + zstd(["-3"], b"") + zstd(["-19"], t[50000:90000])
corpora["multi"] = t[:50000] + corpora["runs"] + t[50000:90000]
cases.append(("multi/frames", "multi", multi))
corpora["skipfirst"] = corpora["short"]
cases.append(("skipfirst/frames", "skipfirst", skip + zstd(["-3"], corpora["short"]) + skip))
ctx.emit("zstd", {
"corpora": corpora,
"cases": [{"name": n, "corpus": c, "data": d} for n, c, d in cases],
})
bench = bytearray()
while len(bench) < 6_000_000:
bench += 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])
ctx.emit("zstd_bench", {"size": len(bench), "crc": zlib.crc32(bench), "data3": zstd(["-3"], bench),
"data19": zstd(["-19"], bench)})
+1 -1
View File
@@ -14,7 +14,7 @@ python3 -I tools/fixtures.py $1 || { echo "FAILED: fixtures"; exit 1; }
python3 -I tools/gen_registry.py > /dev/null || { echo "FAILED: gen_registry"; exit 1; }
python3 -I tools/build.py || { echo "FAILED: build"; exit 1; }
passed=0
for t in $(find tests -name '*.luau' -not -path 'tests/gen/*' -not -path 'tests/fixtures/*' -not -name 'T.luau' | sort); do
for t in $(find tests -name '*.luau' -not -path 'tests/gen/*' -not -path 'tests/fixtures/*' -not -name 'T.luau' -not -name '_*' | sort); do
[ -n "$1" ] && [[ "$t" != *$1* ]] && continue
for rt in $RUNTIMES; do
echo "== $t ($rt)"