From 985bb5364d68e98b025c1ec2ee5e4d6bbbf76d8f Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:42:06 -0500 Subject: [PATCH] imgA-simple: image/qoi (full spec read/write; byte-identical to Pillow's encoder) with Pillow fixtures --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 +++ src/Formats/image/qoi/Codec.luau | 144 +++++++++++++++++++++++++++++++ src/Formats/image/qoi/init.luau | 122 ++++++++++++++++++++++++++ tests/image/qoi.luau | 85 ++++++++++++++++++ tools/fixtures/qoi.py | 64 ++++++++++++++ 6 files changed, 428 insertions(+) create mode 100644 src/Formats/image/qoi/Codec.luau create mode 100644 src/Formats/image/qoi/init.luau create mode 100644 tests/image/qoi.luau create mode 100644 tools/fixtures/qoi.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 17d4818..84e2a3c 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -6,6 +6,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | Category | Format | Extensions | Read | Write | Capabilities | Test | |---|---|---|---|---|---|---| | image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | +| image | qoi | .qoi | yes | yes | alpha: true, depths: 8 | `tests/image/qoi.luau` | Codecs (layer 1, shared by formats; not loadable on their own): diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index ba09f70..b482f97 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -26,6 +26,18 @@ local list: { Entry } = { return require("@formats/image/png") end, }, + { + name = "qoi", + category = "image", + path = "image/qoi", + extensions = { "qoi" }, + mime = { "image/qoi", "image/x-qoi" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, depths = { 8 } }, + load = function() + return require("@formats/image/qoi") + end, + }, } return list diff --git a/src/Formats/image/qoi/Codec.luau b/src/Formats/image/qoi/Codec.luau new file mode 100644 index 0000000..2936f07 --- /dev/null +++ b/src/Formats/image/qoi/Codec.luau @@ -0,0 +1,144 @@ +--!strict +--!native +--!optimize 2 +-- image/qoi/Codec: the QOI op loops (native; never throws). Written from the QOI specification 1.0 (qoiformat.org). +-- decode reads ops from b[p, limit) into an rgba8 buffer; encode writes ops for rgba8 / rgb8 pixels. Every input read +-- is checked against limit; the output buffer has exactly w * h * 4 bytes and the loop stops when it is full. +local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32 + +local Codec = {} + +local index = buffer.create(256) + +-- decode(b, p, limit, out, n) -> true | false, "truncated" (n pixels into out) +function Codec.decode(b: buffer, p: number, limit: number, out: buffer, n: number): (boolean, string?) + buffer.fill(index, 0, 0, 256) + local r, g, bl, a = 0, 0, 0, 255 + local o = 0 + local stop = n * 4 + while o < stop do + if p >= limit then + return false, "truncated" + end + local op = readu8(b, p) + p += 1 + if op == 0xFE then + if p + 3 > limit then + return false, "truncated" + end + r, g, bl = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2) + p += 3 + elseif op == 0xFF then + if p + 4 > limit then + return false, "truncated" + end + r, g, bl, a = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2), readu8(b, p + 3) + p += 4 + else + local tag = op // 64 + if tag == 0 then + local q = op * 4 + r, g, bl, a = readu8(index, q), readu8(index, q + 1), readu8(index, q + 2), readu8(index, q + 3) + elseif tag == 1 then + r = (r + (op // 16) % 4 - 2) % 256 + g = (g + (op // 4) % 4 - 2) % 256 + bl = (bl + op % 4 - 2) % 256 + elseif tag == 2 then + if p >= limit then + return false, "truncated" + end + local d2 = readu8(b, p) + p += 1 + local dg = op % 64 - 32 + g = (g + dg) % 256 + r = (r + dg + d2 // 16 - 8) % 256 + bl = (bl + dg + d2 % 16 - 8) % 256 + else + local run = op % 64 -- 1..62 more copies of the previous pixel (63 / 64 are RGB / RGBA) + local v = r + g * 256 + bl * 65536 + a * 16777216 + local e = math.min(o + run * 4, stop - 4) + while o < e do + writeu32(out, o, v) + o += 4 + end + end + end + writeu32(out, o, r + g * 256 + bl * 65536 + a * 16777216) + o += 4 + local h = ((r * 3 + g * 5 + bl * 7 + a * 11) % 64) * 4 + writeu8(index, h, r) + writeu8(index, h + 1, g) + writeu8(index, h + 2, bl) + writeu8(index, h + 3, a) + end + return true, nil +end + +-- encode(px, n, bpp, out, o) -> new offset: n pixels of bpp (3 or 4) bytes; out has room for n * (bpp + 1) bytes +function Codec.encode(px: buffer, n: number, bpp: number, out: buffer, o: number): number + buffer.fill(index, 0, 0, 256) + local pr, pg, pb, pa = 0, 0, 0, 255 + local run = 0 + local hasA = bpp == 4 + for i = 0, n - 1 do + local q = i * bpp + local r, g, b = readu8(px, q), readu8(px, q + 1), readu8(px, q + 2) + local a = if hasA then readu8(px, q + 3) else 255 + if r == pr and g == pg and b == pb and a == pa then + run += 1 + if run == 62 or i == n - 1 then + writeu8(out, o, 0xC0 + run - 1) + o += 1 + run = 0 + end + else + if run > 0 then + writeu8(out, o, 0xC0 + run - 1) + o += 1 + run = 0 + end + local h = (r * 3 + g * 5 + b * 7 + a * 11) % 64 + local hq = h * 4 + if readu8(index, hq) == r and readu8(index, hq + 1) == g and readu8(index, hq + 2) == b and readu8(index, hq + 3) == a then + writeu8(out, o, h) + o += 1 + else + writeu8(index, hq, r) + writeu8(index, hq + 1, g) + writeu8(index, hq + 2, b) + writeu8(index, hq + 3, a) + if a == pa then + local dr = (r - pr + 128) % 256 - 128 + local dg = (g - pg + 128) % 256 - 128 + local db = (b - pb + 128) % 256 - 128 + local dgr, dgb = dr - dg, db - dg + if dr >= -2 and dr <= 1 and dg >= -2 and dg <= 1 and db >= -2 and db <= 1 then + writeu8(out, o, 0x40 + (dr + 2) * 16 + (dg + 2) * 4 + db + 2) + o += 1 + elseif dg >= -32 and dg <= 31 and dgr >= -8 and dgr <= 7 and dgb >= -8 and dgb <= 7 then + writeu8(out, o, 0x80 + dg + 32) + writeu8(out, o + 1, (dgr + 8) * 16 + dgb + 8) + o += 2 + else + writeu8(out, o, 0xFE) + writeu8(out, o + 1, r) + writeu8(out, o + 2, g) + writeu8(out, o + 3, b) + o += 4 + end + else + writeu8(out, o, 0xFF) + writeu8(out, o + 1, r) + writeu8(out, o + 2, g) + writeu8(out, o + 3, b) + writeu8(out, o + 4, a) + o += 5 + end + end + pr, pg, pb, pa = r, g, b, a + end + end + return o +end + +return Codec diff --git a/src/Formats/image/qoi/init.luau b/src/Formats/image/qoi/init.luau new file mode 100644 index 0000000..ef11dc6 --- /dev/null +++ b/src/Formats/image/qoi/init.luau @@ -0,0 +1,122 @@ +--!strict +-- image/qoi: QOI, the Quite OK Image format (specification 1.0, qoiformat.org). New code written from the spec. +-- Supports: decode of RGB and RGBA files (either colour space tag) to rgba8 (opts.native: rgb8 for 3-channel files); +-- encode of rgba8 (4 channels) and rgb8 (3 channels), lossless; meta.source.colorSpace keeps the sRGB / linear tag. +-- Not supported: nothing in the spec is left out. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Codec = require("@formats/image/qoi/Codec") + +-- ------------------------------------------------------------------------------------------------ contract +local Qoi = { + name = "qoi", + category = "image", + extensions = { "qoi" }, + mime = { "image/qoi", "image/x-qoi" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, depths = { 8 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + native: boolean?, -- rgb8 for 3-channel files (default false: always rgba8) + maxPixels: number?, -- refuse larger images (default 2^26) +} +export type EncodeOptions = { + channels: number?, -- 3 or 4 (default: 3 for rgb8 images or opaque rgba8, else 4) + linear: boolean?, -- tag the file as linear instead of sRGB (default: meta.source.colorSpace == "linear") +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Qoi.sniff(r: Bytes.Reader): number + return if r:peek(4) == "qoif" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Qoi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local magic = r:string(4) + local w, h = r:u32be(), r:u32be() + local channels, cs = r:u8(), r:u8() + if r.err then + return nil, r.err + end + if magic ~= "qoif" then + return nil, Err.new(Err.CORRUPT, "bad magic", r.base) + end + if w == 0 or h == 0 or (channels ~= 3 and channels ~= 4) or cs > 1 then + return nil, Err.new(Err.CORRUPT, "bad header", r.base + 4) + end + 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 img = Types.Image.new(w, h, "rgba8") + local ok, e = Codec.decode(r.buf, r.pos, r.limit, img.pixels, w * h) + if not ok then + return nil, Err.new(Err.TRUNCATED, tostring(e)) + end + if opts and opts.native and channels == 3 then + local rgb = Types.Image.new(w, h, "rgb8") + local src, dst = img.pixels, rgb.pixels + for i = 0, w * h - 1 do + buffer.writeu16(dst, i * 3, buffer.readu16(src, i * 4)) + buffer.writeu8(dst, i * 3 + 2, buffer.readu8(src, i * 4 + 2)) + end + img = rgb + end + img.meta.source = { format = "qoi", bitDepth = 8, colorType = if channels == 4 then "rgba" else "rgb", channels = channels, colorSpace = if cs == 1 then "linear" else "srgb" } + if cs == 1 then + img.meta.colorSpace = "linear" + end + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Qoi.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" or (img.format ~= "rgba8" and img.format ~= "rgb8") then + return nil, Err.new(Err.ARG, "needs an rgba8 or rgb8 Image") + end + local w, h = img.width, img.height + local bpp = if img.format == "rgba8" then 4 else 3 + if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * bpp then + return nil, Err.new(Err.ARG, "bad image size or pixel buffer") + end + local channels = opts and opts.channels + if channels == nil then + channels = 3 + if bpp == 4 then + local px = img.pixels + for i = 0, w * h - 1 do + if buffer.readu8(px, i * 4 + 3) ~= 255 then + channels = 4 + break + end + end + end + elseif channels ~= 3 and channels ~= 4 then + return nil, Err.new(Err.ARG, "channels must be 3 or 4") + end + local linear = opts and opts.linear + if linear == nil then + local src = img.meta and img.meta.source + linear = (type(src) == "table" and src.colorSpace == "linear") or (img.meta and img.meta.colorSpace == "linear") or false + end + local n = w * h + local out = buffer.create(14 + n * (bpp + 1) + 8) + buffer.writestring(out, 0, "qoif") + buffer.writeu32(out, 4, bit32.byteswap(w)) + buffer.writeu32(out, 8, bit32.byteswap(h)) + buffer.writeu8(out, 12, channels) + buffer.writeu8(out, 13, if linear then 1 else 0) + local o = Codec.encode(img.pixels, n, bpp, out, 14) + buffer.writestring(out, o, "\0\0\0\0\0\0\0\1") + o += 8 + local res = buffer.create(o) + buffer.copy(res, 0, out, 0, o) + return res, nil +end + +return Qoi diff --git a/tests/image/qoi.luau b/tests/image/qoi.luau new file mode 100644 index 0000000..d78c5cb --- /dev/null +++ b/tests/image/qoi.luau @@ -0,0 +1,85 @@ +-- image/qoi tests: Pillow-written QOI files (RGB / RGBA, noise / gradients / runs / small deltas, 1x1 to 500x1) +-- decode to Pillow's pixels; our encoder writes the same bytes as Pillow for the same pixels and round-trips exactly; +-- native rgb8 output, the colour space tag, errors, and the fuzz no-throw pass. Fixtures: tools/fixtures/qoi.py. +local T = require("@tests/T") +local Qoi = require("@formats/image/qoi") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/qoi") + +local t = T.suite("qoi") + +t:eq(Qoi.name, "qoi", "name") +t:check(Qoi.caps.decode and Qoi.caps.encode, "caps") + +local same = 0 +for _, c in Fx do + local img, err = Qoi.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(img, c.name .. ": " .. tostring(err)) + t:check(img.width == c.width and img.height == c.height and img.format == "rgba8", c.name .. ": size") + t:eq(Crc32.of(img.pixels), c.crc, c.name .. ": pixels against Pillow") + -- encode the source pixels: the same bytes as Pillow's writer + local src = Types.Image.new(c.width, c.height, if c.channels == 4 then "rgba8" else "rgb8") + src.pixels = buffer.fromstring(c.pixels) + local enc = Qoi.encode(src, { channels = c.channels, linear = string.byte(c.data, 14) == 1 }) :: buffer -- Pillow tags its files linear + if buffer.tostring(enc) == c.data then + same += 1 + end + local back = Qoi.decode(Bytes.reader(enc)) + t:eq(Crc32.of(back.pixels), c.crc, c.name .. ": our encoding round-trips") + -- native rgb8 + if c.channels == 3 then + local n = Qoi.decode(Bytes.reader(buffer.fromstring(c.data)), { native = true }) + t:check(n.format == "rgb8" and buffer.tostring(n.pixels) == c.pixels, c.name .. ": native rgb8") + end +end +t:eq(same, #Fx, "byte-identical to Pillow's encoder") +t:note("%d Pillow files decode; %d of our encodings are byte-identical to Pillow's", #Fx, same) + +-- round trips of random images, a sub-range reader, colour space, errors +do + local rand = T.rng(5) + for _, s in { { 1, 1 }, { 70, 3 }, { 33, 33 } } do + local img = Types.Image.new(s[1], s[2]) + for i = 0, s[1] * s[2] * 4 - 1 do + buffer.writeu8(img.pixels, i, if rand(3) == 0 then rand(256) else (i // 4) % 256) + end + local back = Qoi.decode(Bytes.reader(Qoi.encode(img) :: buffer)) + t:check(buffer.tostring(back.pixels) == buffer.tostring(img.pixels), "random round trip") + end + local c = Fx[4] + local big = buffer.create(#c.data + 9) + buffer.writestring(big, 5, c.data) + local img = Qoi.decode(Bytes.reader(big, 5, #c.data)) + t:check(img and Crc32.of(img.pixels) == c.crc, "decode from a sub-range") + local lin = Types.Image.new(2, 2) + local d = Qoi.encode(lin, { linear = true }) :: buffer + t:eq(buffer.readu8(d, 13), 1, "linear tag") + t:eq(Qoi.decode(Bytes.reader(d)).meta.source.colorSpace, "linear", "linear read back") + t:eq(Qoi.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, "sniff") + t:eq(Qoi.sniff(Bytes.reader(buffer.fromstring("GIF8"))), 0, "sniff other") + local _, e = Qoi.decode(Bytes.reader(buffer.fromstring(c.data)), { maxPixels = 10 }) + t:check(e and e.code == Err.LIMIT, "maxPixels") + local _, e2 = Qoi.decode(Bytes.reader(buffer.fromstring(string.sub(c.data, 1, 40)))) + t:check(e2 and e2.code == Err.TRUNCATED, "truncated: " .. tostring(e2)) + local _, e3 = Qoi.decode(Bytes.reader(buffer.fromstring("qoix" .. string.rep("\0", 20)))) + t:check(e3 and e3.code == Err.CORRUPT, "bad magic") + local _, e4 = Qoi.encode(Types.Image.new(2, 2, "gray8")) + t:check(e4 and e4.code == Err.ARG, "encode gray8 -> ARG") +end + +do + local samples = {} + for i, c in Fx do + if i % 2 == 0 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + return Qoi.decode(Bytes.reader(b)) + end, samples, { keepHeader = 4 }) +end + +t:done() diff --git a/tools/fixtures/qoi.py b/tools/fixtures/qoi.py new file mode 100644 index 0000000..9da4391 --- /dev/null +++ b/tools/fixtures/qoi.py @@ -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("