ws-tex: image/sgi + image/sunras (read + write)

SGI: verbatim / RLE, 1-2 bytes per channel, 1-4 channels (rgba16 native); write RGB(A) RLE / verbatim.
Sun Raster: 1 / 8 / 24 / 32-bit, standard / byte-encoded / RGB types, colour maps; write 24 / 32-bit.
References: ImageMagick, netpbm (sgitopnm-era writers, rasttopnm), Pillow.
This commit is contained in:
4DBug committed 2026-10-31 14:52:47 -05:00
1 parent d294c211f9
commit 403a4d6f31
10 files changed
+745

No files matched your search

+2
View File
@@ -17,6 +17,8 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| image | png | .png .apng | yes | yes | animation: true, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` |
| image | pnm | .pnm .pbm .pgm .ppm .pam .pfm | yes | yes | alpha: true, depths: 1, 8, 16, 32, float: true | `tests/image/pnm.luau` |
| image | qoi | .qoi | yes | yes | alpha: true, depths: 8 | `tests/image/qoi.luau` |
| image | sgi | .sgi .rgb .rgba .bw .int .inta | yes | yes | alpha: true, depths: 8, 16 | `tests/image/sgi.luau` |
| image | sunras | .ras .sun .rs .im1 .im8 .im24 .im32 | yes | yes | alpha: true, palette: true, depths: 1, 8, 24, 32 | `tests/image/sunras.luau` |
| image | tga | .tga .icb .vda .vst .tpic | yes | yes | alpha: true, palette: true, depths: 8, 15, 16, 24, 32 | `tests/image/tga.luau` |
| image | tiff | .tif .tiff | yes | yes | alpha: true, pages: true, depths: 1, 2, 4, 8, 16, 32, float: true | `tests/image/tiff.luau` |
| image | webp | .webp | yes | yes | animation: true, alpha: true, lossy: true, lossless: true, depths: 8 | `tests/image/webp.luau` |
+24
View File
@@ -158,6 +158,30 @@ local list: { Entry } = {
return require("@formats/image/qoi")
end,
},
{
name = "sgi",
category = "image",
path = "image/sgi",
extensions = { "sgi", "rgb", "rgba", "bw", "int", "inta" },
mime = { "image/sgi", "image/x-rgb" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" },
caps = { decode = true, encode = true, alpha = true, depths = { 8, 16 } },
load = function()
return require("@formats/image/sgi")
end,
},
{
name = "sunras",
category = "image",
path = "image/sunras",
extensions = { "ras", "sun", "rs", "im1", "im8", "im24", "im32" },
mime = { "image/x-sun-raster", "image/x-cmu-raster" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Pixels" },
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 8, 24, 32 } },
load = function()
return require("@formats/image/sunras")
end,
},
{
name = "tga",
category = "image",
+286
View File
@@ -0,0 +1,286 @@
--!strict
-- image/sgi: Silicon Graphics image files (.rgb / .sgi / .bw / .rgba; Paul Haeberli's "The SGI Image File Format"
-- 1.00; new code). Decode: verbatim and RLE storage, 1 and 2 bytes per channel, 1 (grey), 2 (grey + alpha), 3 (RGB)
-- and 4 (RGBA) channels, dimension 1 / 2 / 3, rows bottom-up; rgba8 (2-byte channels keep their high byte), or rgba16
-- with opts.native for 2-byte files; the image name (meta.text.name). Encode: rgba8 as RGB (or RGBA when there is
-- alpha), RLE (default) or verbatim; rgba16 as 2-byte channels. Not supported: the obsolete dithered / screen /
-- colour-map files (colormap field 1..3: UNSUPPORTED).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Sniff = require("@formats/core/Sniff")
local Types = require("@formats/Types")
-- ------------------------------------------------------------------------------------------------ contract
local Sgi = {
name = "sgi",
category = "image",
extensions = { "sgi", "rgb", "rgba", "bw", "int", "inta" },
mime = { "image/sgi", "image/x-rgb" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" },
caps = { decode = true, encode = true, alpha = true, depths = { 8, 16 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
native: boolean?, -- rgba16 for 2-byte files (default false: rgba8)
maxPixels: number?, -- refuse larger images (default 2^26)
}
export type EncodeOptions = {
rle: boolean?, -- RLE storage (default true)
name: string?, -- the image name (up to 79 bytes; default meta.text.name)
}
local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32
local function be16(b: buffer, o: number): number
return bit32.rshift(bit32.byteswap(readu16(b, o)), 16)
end
local function be32(b: buffer, o: number): number
return bit32.byteswap(readu32(b, o))
end
-- ------------------------------------------------------------------------------------------------ sniff
function Sgi.sniff(r: Bytes.Reader): number
if Sniff.magic(r, "\1\218") == 0 or r:size() < 512 then
return 0
end
local st, bpc = r:peekU8(2), r:peekU8(3)
return if st <= 1 and (bpc == 1 or bpc == 2) then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Sgi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local b, o, limit = r.buf, r.base, r.limit
if limit - o < 512 then
return nil, Err.new(Err.TRUNCATED, "short header", o)
end
if be16(b, o) ~= 474 then
return nil, Err.new(Err.CORRUPT, "not an SGI image", o)
end
local rle, bpc, dim = readu8(b, o + 2), readu8(b, o + 3), be16(b, o + 4)
local w, h, z = be16(b, o + 6), be16(b, o + 8), be16(b, o + 10)
if dim == 1 then
h, z = 1, 1
elseif dim == 2 then
z = 1
end
if rle > 1 or (bpc ~= 1 and bpc ~= 2) or dim < 1 or dim > 3 or w == 0 or h == 0 or z == 0 then
return nil, Err.new(Err.CORRUPT, "bad header", o + 2)
end
if z > 4 then
return nil, Err.new(Err.UNSUPPORTED, z .. " channels", o + 10)
end
local cmap = be32(b, o + 104)
if cmap ~= 0 then
return nil, Err.new(Err.UNSUPPORTED, "colormap type " .. cmap, o + 104)
end
local maxPixels = opts and opts.maxPixels or 2 ^ 26
if w * h > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
end
-- channel planes as 16-bit samples (8-bit values scaled * 257)
local plane = buffer.create(w * h * z * 2)
local truncated = false
local function put(c: number, row: number, x: number, v: number)
buffer.writeu16(plane, ((c * h + row) * w + x) * 2, if bpc == 1 then v * 257 else v)
end
if rle == 0 then
local need = w * h * z * bpc
local p = o + 512
local avail = math.min(need, limit - p)
truncated = avail < need
for i = 0, avail // bpc - 1 do
local v = if bpc == 1 then readu8(b, p + i) else be16(b, p + i * 2)
buffer.writeu16(plane, i * 2, if bpc == 1 then v * 257 else v)
end
else
local n = h * z
if o + 512 + n * 8 > limit then
return nil, Err.new(Err.TRUNCATED, "RLE tables run past the end", o + 512)
end
for c = 0, z - 1 do
for row = 0, h - 1 do
local i = c * h + row
local start, len = be32(b, o + 512 + i * 4), be32(b, o + 512 + n * 4 + i * 4)
local p = o + start
local stop = math.min(limit, p + len)
local x = 0
while x < w and p + bpc <= stop do
local cnt = if bpc == 1 then readu8(b, p) else be16(b, p)
p += bpc
local count = bit32.band(cnt, 0x7F)
if count == 0 then
break
end
if bit32.band(cnt, 0x80) ~= 0 then
for _ = 1, count do
if x >= w or p + bpc > stop then
break
end
put(c, row, x, if bpc == 1 then readu8(b, p) else be16(b, p))
p += bpc
x += 1
end
else
if p + bpc > stop then
break
end
local v = if bpc == 1 then readu8(b, p) else be16(b, p)
p += bpc
for _ = 1, count do
if x >= w then
break
end
put(c, row, x, v)
x += 1
end
end
end
if x < w then
truncated = true
end
end
end
end
local wide = opts and opts.native and bpc == 2
local img = Types.Image.new(w, h, if wide then "rgba16" else "rgba8")
local px = img.pixels
for y = 0, h - 1 do
local row = h - 1 - y
for x = 0, w - 1 do
local function s(c: number): number
return buffer.readu16(plane, ((c * h + row) * w + x) * 2)
end
local rr: number = s(0)
local gg: number = if z >= 3 then s(1) else rr
local bb: number = if z >= 3 then s(2) else rr
local aa: number = if z == 2 then s(1) elseif z == 4 then s(3) else 65535
local d = (y * w + x)
if wide then
buffer.writeu16(px, d * 8, rr)
buffer.writeu16(px, d * 8 + 2, gg)
buffer.writeu16(px, d * 8 + 4, bb)
buffer.writeu16(px, d * 8 + 6, aa)
else
buffer.writeu32(px, d * 4, bit32.rshift(rr, 8) + bit32.rshift(gg, 8) * 256 + bit32.rshift(bb, 8) * 65536 + bit32.rshift(aa, 8) * 16777216)
end
end
end
local name = buffer.readstring(b, o + 24, 80)
local zpos = string.find(name, "\0", 1, true)
name = if zpos then string.sub(name, 1, zpos - 1) else name
if name ~= "" then
img.meta.text = { name = name }
end
if truncated then
img.meta.truncated = true
end
img.meta.source = { format = "sgi", bitDepth = bpc * 8, channels = z, rle = rle == 1, dimension = dim }
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Sgi.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(img) ~= "table" or (img.format ~= "rgba8" and img.format ~= "rgba16") or type(img.pixels) ~= "buffer" then
return nil, Err.new(Err.ARG, "needs an rgba8 or rgba16 Image")
end
local w, h = img.width, img.height
if w < 1 or h < 1 or w > 65535 or h > 65535 then
return nil, Err.new(Err.ARG, "size must be 1..65535")
end
local wide = img.format == "rgba16"
local bpc = if wide then 2 else 1
local px = img.pixels
local function sample(x: number, y: number, c: number): number
local i = (y * w + x) * 4 + c
return if wide then buffer.readu16(px, i * 2) else readu8(px, i)
end
local z = 3
for i = 0, w * h - 1 do
if (if wide then buffer.readu16(px, i * 8 + 6) < 65535 else readu8(px, i * 4 + 3) < 255) then
z = 4
break
end
end
local rle = not (opts and opts.rle == false)
local out = Bytes.writer(512 + w * h * z * bpc + h * z * 8)
out:u16be(474)
out:u8(if rle then 1 else 0)
out:u8(bpc)
out:u16be(3)
out:u16be(w)
out:u16be(h)
out:u16be(z)
out:u32be(0)
out:u32be(if wide then 65535 else 255)
out:u32be(0)
local name = (opts and opts.name) or (img.meta and img.meta.text and img.meta.text.name) or ""
name = string.sub(name, 1, 79)
out:string(name)
out:fill(0, 80 - #name)
out:u32be(0)
out:fill(0, 404)
local function put(v: number)
if wide then
out:u16be(v)
else
out:u8(v)
end
end
if not rle then
for c = 0, z - 1 do
for row = 0, h - 1 do
local y = h - 1 - row
for x = 0, w - 1 do
put(sample(x, y, c))
end
end
end
return out:finish(), nil
end
local tables = out:tell()
out:fill(0, h * z * 8)
for c = 0, z - 1 do
for row = 0, h - 1 do
local y = h - 1 - row
local start = out:tell()
local x = 0
while x < w do
-- a run of equal samples (>= 3) or literals up to the next run
local v = sample(x, y, c)
local run = 1
while x + run < w and run < 127 and sample(x + run, y, c) == v do
run += 1
end
if run >= 3 then
put(run)
put(v)
x += run
else
local lit = 0
while x + lit < w and lit < 127 do
local a = sample(x + lit, y, c)
if x + lit + 2 < w and sample(x + lit + 1, y, c) == a and sample(x + lit + 2, y, c) == a then
break
end
lit += 1
end
lit = math.max(lit, 1)
put(0x80 + lit)
for k = 0, lit - 1 do
put(sample(x + k, y, c))
end
x += lit
end
end
put(0)
local i = c * h + row
out:setU32be(tables + i * 4, start)
out:setU32be(tables + h * z * 4 + i * 4, out:tell() - start)
end
end
return out:finish(), nil
end
return Sgi
+247
View File
@@ -0,0 +1,247 @@
--!strict
-- image/sunras: Sun Raster (rasterfile(5), SunOS <rasterfile.h>; new code). Decode: 1-bit (0 = white without a colour
-- map), 8-bit (grey or the RGB colour map), 24-bit and 32-bit pixels in BGR / XBGR order (RT_STANDARD, RT_OLD,
-- RT_BYTE_ENCODED) or RGB / XRGB order (RT_FORMAT_RGB), the byte-encoded RLE (0x80 escapes), 16-bit row padding; in
-- 32-bit files the X byte is alpha when it is not all zero. Encode: rgba8 as 24-bit (opaque) or 32-bit (alpha in the
-- X byte) BGR, RT_BYTE_ENCODED (default) or RT_STANDARD. Not supported: RT_FORMAT_TIFF / RT_FORMAT_IFF (UNSUPPORTED),
-- raw colour maps (RMT_RAW is ignored).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Sniff = require("@formats/core/Sniff")
local Types = require("@formats/Types")
local Pixels = require("@formats/codecs/image/Pixels")
-- ------------------------------------------------------------------------------------------------ contract
local Sunras = {
name = "sunras",
category = "image",
extensions = { "ras", "sun", "rs", "im1", "im8", "im24", "im32" },
mime = { "image/x-sun-raster", "image/x-cmu-raster" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Pixels" },
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 8, 24, 32 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxPixels: number?, -- refuse larger images (default 2^26)
}
export type EncodeOptions = {
rle: boolean?, -- RT_BYTE_ENCODED (default true); false: RT_STANDARD
}
local MAGIC = "\89\166\106\149"
local readu8, readu32 = buffer.readu8, buffer.readu32
local function be32(b: buffer, o: number): number
return bit32.byteswap(readu32(b, o))
end
-- ------------------------------------------------------------------------------------------------ sniff
function Sunras.sniff(r: Bytes.Reader): number
return Sniff.magic(r, MAGIC)
end
-- ------------------------------------------------------------------------------------------------ decode
function Sunras.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local b, o, limit = r.buf, r.base, r.limit
if limit - o < 32 then
return nil, Err.new(Err.TRUNCATED, "short header", o)
end
if buffer.readstring(b, o, 4) ~= MAGIC then
return nil, Err.new(Err.CORRUPT, "not a Sun raster", o)
end
local w, h, depth, typ, maptype, maplen = be32(b, o + 4), be32(b, o + 8), be32(b, o + 12), be32(b, o + 20), be32(b, o + 24), be32(b, o + 28)
if w == 0 or h == 0 or w > 65536 or h > 65536 then
return nil, Err.new(Err.CORRUPT, "bad size", o + 4)
end
if depth ~= 1 and depth ~= 8 and depth ~= 24 and depth ~= 32 then
return nil, Err.new(Err.UNSUPPORTED, depth .. "-bit pixels", o + 12)
end
if typ == 4 or typ == 5 or typ > 5 and typ ~= 0xFFFF then
return nil, Err.new(Err.UNSUPPORTED, "raster type " .. typ, o + 20)
end
local maxPixels = opts and opts.maxPixels or 2 ^ 26
if w * h > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
end
local p = o + 32
if p + maplen > limit then
return nil, Err.new(Err.TRUNCATED, "colour map runs past the end", p)
end
local pal = buffer.create(1024)
local ncol = 0
if maptype == 1 and maplen > 0 then
ncol = math.min(256, maplen // 3)
for i = 0, ncol - 1 do
buffer.writeu32(pal, i * 4, readu8(b, p + i) + readu8(b, p + ncol + i) * 256 + readu8(b, p + 2 * ncol + i) * 65536 + 0xFF000000)
end
elseif depth == 1 then
buffer.writeu32(pal, 0, 0xFFFFFFFF)
buffer.writeu32(pal, 4, 0xFF000000)
else
for i = 0, 255 do
buffer.writeu32(pal, i * 4, i * 0x10101 + 0xFF000000)
end
end
p += maplen
local stride = ((w * depth + 15) // 16) * 2
local total = stride * h
local raw = buffer.create(total + 4)
local truncated = false
if typ == 2 then
local q = 0
while q < total and p < limit do
local c = readu8(b, p)
p += 1
if c ~= 0x80 then
buffer.writeu8(raw, q, c)
q += 1
else
if p >= limit then
break
end
local n = readu8(b, p)
p += 1
if n == 0 then
buffer.writeu8(raw, q, 0x80)
q += 1
else
if p >= limit then
break
end
local cnt = math.min(n + 1, total - q)
buffer.fill(raw, q, readu8(b, p), cnt)
p += 1
q += cnt
end
end
end
truncated = q < total
else
local n = math.min(total, limit - p)
buffer.copy(raw, 0, b, p, n)
truncated = n < total
end
local img = Types.Image.new(w, h, "rgba8")
local px = img.pixels
if depth <= 8 then
Pixels.indexed(raw, 0, stride, depth, px, w, h, true, pal)
else
local rgb = typ == 3
local bytes = depth // 8
local alpha = false
if bytes == 4 then
for y = 0, h - 1 do
for x = 0, w - 1 do
if readu8(raw, y * stride + x * 4) ~= 0 then
alpha = true
end
end
end
end
for y = 0, h - 1 do
for x = 0, w - 1 do
local s = y * stride + x * bytes
local a = 255
if bytes == 4 then
a = if alpha then readu8(raw, s) else 255
s += 1
end
local c0, c1, c2 = readu8(raw, s), readu8(raw, s + 1), readu8(raw, s + 2)
local rr, bb = if rgb then c0 else c2, if rgb then c2 else c0
buffer.writeu32(px, (y * w + x) * 4, rr + c1 * 256 + bb * 65536 + a * 16777216)
end
end
end
if ncol > 0 then
local list: { { number } } = {}
for i = 0, ncol - 1 do
local v = buffer.readu32(pal, i * 4)
list[i + 1] = { bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255), 255 }
end
img.meta.palette = list
end
if truncated then
img.meta.truncated = true
end
img.meta.source = { format = "sunras", bitDepth = depth, type = typ, rle = typ == 2 }
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Sunras.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then
return nil, Err.new(Err.ARG, "needs an rgba8 Image")
end
local w, h = img.width, img.height
if w < 1 or h < 1 then
return nil, Err.new(Err.ARG, "bad size")
end
local px = img.pixels
local alpha = false
for i = 0, w * h - 1 do
if readu8(px, i * 4 + 3) < 255 then
alpha = true
break
end
end
local depth = if alpha then 32 else 24
local bytes = depth // 8
local stride = ((w * depth + 15) // 16) * 2
local raw = buffer.create(stride * h)
for y = 0, h - 1 do
for x = 0, w - 1 do
local s, d = (y * w + x) * 4, y * stride + x * bytes
if alpha then
buffer.writeu8(raw, d, readu8(px, s + 3))
d += 1
end
buffer.writeu8(raw, d, readu8(px, s + 2))
buffer.writeu8(raw, d + 1, readu8(px, s + 1))
buffer.writeu8(raw, d + 2, readu8(px, s))
end
end
local rle = not (opts and opts.rle == false)
local body = raw
if rle then
local wr = Bytes.writer(stride * h)
local i, n = 0, stride * h
while i < n do
local v = readu8(raw, i)
local run = 1
while i + run < n and run < 256 and readu8(raw, i + run) == v do
run += 1
end
if run >= 3 or v == 0x80 then
if run == 1 then
wr:u8(0x80)
wr:u8(0)
else
wr:u8(0x80)
wr:u8(run - 1)
wr:u8(v)
end
else
for _ = 1, run do
wr:u8(v)
end
end
i += run
end
body = wr:finish()
end
local out = Bytes.writer(32 + buffer.len(body))
out:string(MAGIC)
out:u32be(w)
out:u32be(h)
out:u32be(depth)
out:u32be(buffer.len(body))
out:u32be(if rle then 2 else 1)
out:u32be(0)
out:u32be(0)
out:bytes(body)
return out:finish(), nil
end
return Sunras
+34
View File
@@ -0,0 +1,34 @@
-- image/sgi tests: files from netpbm / ImageMagick / Pillow against ImageMagick's decode, our encoder's files read
-- by ImageMagick, round trips through every option, errors, the fuzz no-throw pass. Fixtures: tools/fixtures/sgi.py.
local T = require("@tests/T")
local Sgi = require("@formats/image/sgi")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local R = require("@tests/image/_raster")
local Fx = require("@tests/gen/sgi")
local t = T.suite("sgi")
t:eq(Sgi.name, "sgi", "name")
t:check(Sgi.caps.decode and Sgi.caps.encode, "caps")
t:note("%d files match ImageMagick", R.decodes(t, Sgi, Fx.cases))
t:note("%d of our files read by ImageMagick", R.decodes(t, Sgi, Fx.ours))
for _, c in Fx.cases do
R.roundTrip(t, Sgi, R.image(c.w, c.h, c.rgba), nil, c.name .. " re-encoded")
R.roundTrip(t, Sgi, R.image(c.w, c.h, c.rgba), { rle = false }, c.name .. " re-encoded without RLE")
end
do
local enc = Sgi.encode(R.image(2, 2, string.rep("\1\2\3\4", 4))) :: buffer
t:eq(Sgi.sniff(Bytes.reader(enc)), 1, "sniff")
t:eq(Sgi.sniff(Bytes.reader(buffer.fromstring("GIF89a"))), 0, "sniff other")
local _, e = Sgi.decode(Bytes.reader(buffer.fromstring(string.sub(buffer.tostring(enc), 1, 20))))
t:check(e and e.code == Err.TRUNCATED, "short header")
local _, e2 = Sgi.decode(Bytes.reader(enc), { maxPixels = 2 })
t:check(e2 and e2.code == Err.LIMIT, "limit")
local _, e3 = Sgi.encode({} :: any)
t:check(e3 and e3.code == Err.ARG, "bad image")
end
t:fuzz("decode", function(b: buffer)
return Sgi.decode(Bytes.reader(b))
end, R.samples(Fx.cases), { mutations = 6 })
t:done()
+42
View File
@@ -0,0 +1,42 @@
-- image/sunras tests: files from netpbm / ImageMagick against ImageMagick's decode, our encoder's files read
-- by rasttopnm, round trips through every option, errors, the fuzz no-throw pass. Fixtures: tools/fixtures/sunras.py.
local T = require("@tests/T")
local Sunras = require("@formats/image/sunras")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local R = require("@tests/image/_raster")
local Fx = require("@tests/gen/sunras")
local t = T.suite("sunras")
t:eq(Sunras.name, "sunras", "name")
t:check(Sunras.caps.decode and Sunras.caps.encode, "caps")
t:note("%d files match rasttopnm / ImageMagick", R.decodes(t, Sunras, Fx.cases))
-- our files: rasttopnm reads the colours (it drops alpha)
for _, o in Fx.ours do
local img = Sunras.decode(Bytes.reader(buffer.fromstring(o.data))) :: any
local px = buffer.fromstring(buffer.tostring(img.pixels))
for i = 0, o.w * o.h - 1 do
buffer.writeu8(px, i * 4 + 3, 255)
end
t:eq(R.maxDiff(px, buffer.fromstring(o.rgba), o.w * o.h), 0, o.name .. ": rasttopnm reads our file")
end
for _, c in Fx.cases do
R.roundTrip(t, Sunras, R.image(c.w, c.h, c.rgba), nil, c.name .. " re-encoded")
R.roundTrip(t, Sunras, R.image(c.w, c.h, c.rgba), { rle = false }, c.name .. " re-encoded without RLE")
end
do
local enc = Sunras.encode(R.image(2, 2, string.rep("\1\2\3\4", 4))) :: buffer
t:eq(Sunras.sniff(Bytes.reader(enc)), 1, "sniff")
t:eq(Sunras.sniff(Bytes.reader(buffer.fromstring("GIF89a"))), 0, "sniff other")
local _, e = Sunras.decode(Bytes.reader(buffer.fromstring(string.sub(buffer.tostring(enc), 1, 20))))
t:check(e and e.code == Err.TRUNCATED, "short header")
local _, e2 = Sunras.decode(Bytes.reader(enc), { maxPixels = 2 })
t:check(e2 and e2.code == Err.LIMIT, "limit")
local _, e3 = Sunras.encode({} :: any)
t:check(e3 and e3.code == Err.ARG, "bad image")
end
t:fuzz("decode", function(b: buffer)
return Sunras.decode(Bytes.reader(b))
end, R.samples(Fx.cases), { mutations = 6 })
t:done()
+22
View File
@@ -0,0 +1,22 @@
# Shared by the simple raster fixture generators: run our encoder (tools/fixtures/_tex_encode.luau -a <fmt>) and
# decode files with ImageMagick into rgba8 (through PAM).
import os, shutil, subprocess
def ours(ctx, which):
exe = shutil.which("luau")
cmd = [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
res = subprocess.run(cmd + ["tools/fixtures/_tex_encode.luau", "-a", which], cwd=ctx.root, capture_output=True, check=True)
files = {}
for line in res.stdout.decode().split("\n"):
if line.startswith("ours_") and "\t" in line:
n, hx = line.split("\t", 1)
files[n] = bytes.fromhex(hx.strip())
return files
def magick_cases(R, w, names, fmt=None):
"""ImageMagick decodes of the named files in the work dir -> { name: (w, h, rgba) }"""
pre = (fmt + ":") if fmt else ""
w.sh("imagemagick", ["magick %s%s -depth 8 -alpha on pam:%s.pam" % (pre, n, n) for n in names])
return {n: R.pnm_rgba(w.read(n + ".pam")) for n in names}
+4
View File
@@ -132,6 +132,10 @@ end
local function simple(): any
if which == "pcx" then
return require("@formats/image/pcx")
elseif which == "sgi" then
return require("@formats/image/sgi")
elseif which == "sunras" then
return require("@formats/image/sunras")
end
return nil
end
+39
View File
@@ -0,0 +1,39 @@
# SGI fixtures (tools/fixtures.py): files from netpbm (pnmtosgi: RLE and verbatim, RGB and grey), ImageMagick (RGB,
# RGBA, 16-bit) and Pillow (L, RGB, RGBA), plus our encoder's files (tools/fixtures/_tex_encode.luau -a sgi); the
# reference is ImageMagick's decode of each file (16-bit within 1: it rounds where we keep the high byte).
# tests/gen/sgi.luau { cases = { { name, data, w, h, rgba, tol } }, ours = { ... } }
import importlib.util, os
def _load(n):
spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
R, S = _load("_raster_ref"), _load("_simple")
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/sgi"]
def generate(ctx):
w = R.Work(ctx)
try:
w.png("photo.png", 37, 23, R.photo(37, 23))
w.png("alpha.png", 30, 17, R.photo(30, 17, 3, True))
w.sh("netpbm", ["pngtopam photo.png | pamtopnm > photo.ppm", "pnmtosgi -rle photo.ppm > nb_rle.sgi", "pnmtosgi -verbatim photo.ppm > nb_verbatim.sgi",
"ppmtopgm photo.ppm | pnmtosgi -rle > nb_grey.sgi"])
w.sh("imagemagick", ["magick photo.png -alpha off im_rgb.sgi", "magick alpha.png im_rgba.sgi", "magick photo.png -alpha off -depth 16 im_rgb16.sgi",
"magick alpha.png -compress none im_rgba_verbatim.sgi"])
ctx.python(["pillow"], ("from PIL import Image\nimport os\nos.chdir(%r)\nim=Image.open('alpha.png')\nim.save('pil_rgba.sgi')\n"
"im.convert('RGB').save('pil_rgb.sgi')\nim.convert('L').save('pil_l.sgi')\n") % w.dir)
names = sorted(f for f in os.listdir(w.dir) if f.endswith(".sgi"))
mine = S.ours(ctx, "sgi")
for n, d in mine.items():
w.write(n, d)
ref = S.magick_cases(R, w, names + sorted(mine))
out = {"cases": [], "ours": []}
for n in names + sorted(mine):
ww, hh, rgba = ref[n]
out["ours" if n.startswith("ours_") else "cases"].append({"name": n, "data": w.read(n), "w": ww, "h": hh, "rgba": rgba, "tol": 1 if "16" in n else 0})
ctx.emit("sgi", out)
finally:
w.close()
+45
View File
@@ -0,0 +1,45 @@
# Sun Raster fixtures (tools/fixtures.py): files from netpbm (pnmtorast: standard and byte-encoded, 1 / 8 / 24-bit) and
# ImageMagick (24-bit, 32-bit with alpha, 8-bit palette, 1-bit), plus our encoder's files (tools/fixtures/_tex_encode
# .luau -a sunras); the reference is rasttopnm for netpbm's and our files (RGB only) and ImageMagick's decode for the others.
# tests/gen/sunras.luau { cases = { { name, data, w, h, rgba } }, ours = { ... } }
import importlib.util, os
def _load(n):
spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
R, S = _load("_raster_ref"), _load("_simple")
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/sunras"]
def generate(ctx):
w = R.Work(ctx)
try:
w.png("photo.png", 37, 23, R.photo(37, 23))
w.png("pal.png", 31, 19, R.palette_image(31, 19, 40))
w.png("alpha.png", 30, 17, R.photo(30, 17, 3, True))
w.sh("netpbm", ["pngtopam photo.png | pamtopnm > photo.ppm", "pngtopam pal.png | pamtopnm > pal.ppm",
"pnmtorast -standard photo.ppm > nb_24_standard.ras", "pnmtorast -rle photo.ppm > nb_24_rle.ras",
"pnmtorast -rle pal.ppm > nb_8_rle.ras", "ppmtopgm photo.ppm | pnmtorast -standard > nb_grey.ras",
"ppmtopgm photo.ppm | pgmtopbm | pnmtorast -rle > nb_1.ras"])
w.sh("imagemagick", ["magick photo.png -alpha off im_24.ras", "magick alpha.png im_32.ras", "magick pal.png -alpha off -type palette im_8.ras",
"magick photo.png -monochrome im_1.ras"])
names = sorted(f for f in os.listdir(w.dir) if f.endswith(".ras"))
mine = S.ours(ctx, "sunras")
for n, d in mine.items():
w.write(n, d)
# netpbm's own files through rasttopnm (ImageMagick cuts the last row of nb_8_rle short), the rest through ImageMagick
nb = [n for n in names if n.startswith("nb_")] + sorted(mine)
w.sh("netpbm", ["rasttopnm %s > %s.pnm" % (n, n) for n in nb])
ref = S.magick_cases(R, w, [n for n in names if not n.startswith("nb_")], "sun")
for n in nb:
ref[n] = R.pnm_rgba(w.read(n + ".pnm"))
out = {"cases": [], "ours": []}
for n in names + sorted(mine):
ww, hh, rgba = ref[n]
out["ours" if n.startswith("ours_") else "cases"].append({"name": n, "data": w.read(n), "w": ww, "h": hh, "rgba": rgba})
ctx.emit("sunras", out)
finally:
w.close()