Files
rosetta/tests/image/_raster.luau
T

79 lines
2.8 KiB
Luau

-- tests/image/_raster: the shared checks of the simple raster formats' tests (pcx, sgi, sunras, xbm, xpm, ilbm, icns,
-- ani): decode every case against its reference rgba8 pixels, round-trip images through the encoder, fuzz samples.
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local R = {}
local function maxDiff(a: buffer, b: buffer, n: number): (number, number)
local worst, at = 0, -1
for i = 0, n * 4 - 1 do
local d = math.abs(buffer.readu8(a, i) - buffer.readu8(b, i))
if d > worst then
worst, at = d, i // 4
end
end
return worst, at
end
R.maxDiff = maxDiff
-- cases: { { name, data, w, h, rgba, tol? } } (rgba: the reference decode)
function R.decodes(t: any, Fmt: any, cases: { any }, opts: any?): number
local n = 0
for _, c in cases do
local img, err = Fmt.decode(Bytes.reader(buffer.fromstring(c.data)), opts)
t:check(img, c.name .. ": " .. tostring(err))
if img then
t:check(img.width == c.w and img.height == c.h and img.format == "rgba8", string.format("%s: %d x %d %s", c.name, img.width, img.height, img.format))
if img.width == c.w and img.height == c.h then
local d, at = maxDiff(img.pixels, buffer.fromstring(c.rgba), c.w * c.h)
t:check(d <= (c.tol or 0), string.format("%s: %d off the reference at pixel %d", c.name, d, at))
end
n += 1
end
-- from inside a bigger buffer
local big = buffer.create(#c.data + 9)
buffer.writestring(big, 5, c.data)
local img2 = Fmt.decode(Bytes.reader(big, 5, #c.data), opts)
t:check(img2 and img and buffer.tostring(img2.pixels) == buffer.tostring(img.pixels), c.name .. ": from a sub-range")
end
return n
end
-- image(w, h, rgba string) -> Types.Image
function R.image(w: number, h: number, rgba: string): Types.Image
local img = Types.Image.new(w, h)
img.pixels = buffer.fromstring(rgba)
return img
end
-- roundTrip(t, Fmt, img, encodeOpts?, label, tol?) -> the encoded buffer
function R.roundTrip(t: any, Fmt: any, img: Types.Image, eopts: any?, label: string, tol: number?): buffer?
local enc, err = Fmt.encode(img, eopts)
t:check(enc, label .. ": encode " .. tostring(err))
if not enc then
return nil
end
local back, derr = Fmt.decode(Bytes.reader(enc))
t:check(back, label .. ": decode " .. tostring(derr))
if back then
t:check(back.width == img.width and back.height == img.height, label .. ": size")
local d = maxDiff(back.pixels, img.pixels, img.width * img.height)
t:check(d <= (tol or 0), string.format("%s: round trip %d off", label, d))
end
return enc
end
-- samples(cases, every?) -> the fuzz samples (every n-th case's data)
function R.samples(cases: { any }, every: number?): { string }
local samples = {}
for i, c in cases do
if i % (every or 1) == 0 then
table.insert(samples, c.data)
end
end
return samples
end
return R