From 9a928bd5be9d04fdfb1c199760626adb6c4fb649 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:34:32 -0500 Subject: [PATCH] imgA-gif: image/gif (read + write, animation, transparency, loops, comments) and codecs/Quantize (median cut, octree, Floyd-Steinberg); ImageMagick / Pillow fixtures --- docs/FORMATS.md | 2 + src/Formats/Registry.luau | 12 + src/Formats/codecs/Quantize/init.luau | 444 +++++++++++++++++++++ src/Formats/image/gif/Decode.luau | 68 ++++ src/Formats/image/gif/init.luau | 534 ++++++++++++++++++++++++++ tests/codecs/quantize.luau | 135 +++++++ tests/image/gif.luau | 221 +++++++++++ tools/fixtures/gif.py | 133 +++++++ 8 files changed, 1549 insertions(+) create mode 100644 src/Formats/codecs/Quantize/init.luau create mode 100644 src/Formats/image/gif/Decode.luau create mode 100644 src/Formats/image/gif/init.luau create mode 100644 tests/codecs/quantize.luau create mode 100644 tests/image/gif.luau create mode 100644 tools/fixtures/gif.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 17d4818..ca4475f 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -5,9 +5,11 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | Category | Format | Extensions | Read | Write | Capabilities | Test | |---|---|---|---|---|---|---| +| image | gif | .gif | yes | yes | animation: true, alpha: true, palette: true, depths: 1, 2, 4, 8 | `tests/image/gif.luau` | | image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | Codecs (layer 1, shared by formats; not loadable on their own): - codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. - codecs/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and +- codecs/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index ba09f70..d9fc2c0 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -14,6 +14,18 @@ export type Entry = { } local list: { Entry } = { + { + name = "gif", + category = "image", + path = "image/gif", + extensions = { "gif" }, + mime = { "image/gif" }, + deps = { "core/Err", "core/Bytes", "codecs/Lzw", "codecs/Quantize", "Types" }, + caps = { decode = true, encode = true, animation = true, alpha = true, palette = true, depths = { 1, 2, 4, 8 } }, + load = function() + return require("@formats/image/gif") + end, + }, { name = "png", category = "image", diff --git a/src/Formats/codecs/Quantize/init.luau b/src/Formats/codecs/Quantize/init.luau new file mode 100644 index 0000000..ed84c5f --- /dev/null +++ b/src/Formats/codecs/Quantize/init.luau @@ -0,0 +1,444 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette +-- writer) builds on it. New code: Heckbert's median cut and Gervautz-Purgathofer octree, both over a 5-bit-per-channel +-- weighted histogram (palette colours are the exact means of the pixels they cover), nearest-colour mapping with +-- optional Floyd-Steinberg error diffusion. Deterministic: the same palette and indexes on every runtime (no table +-- iteration order is ever relied on). +-- +-- local pal, exact = Quantize.palette(pixels, w, h, 256, { method = "mediancut" }) -- { {r, g, b, 255} }, boolean +-- local idx = Quantize.map(pixels, w, h, pal, { dither = true, transparentIndex = 255 }) -- buffer of w * h u8 +-- +-- Pixels with alpha < 128 are "transparent": palette() ignores them, map() gives them opts.transparentIndex (0-based) +-- when set (otherwise they map like opaque pixels). When the opaque pixels have at most maxColors distinct colours, +-- palette() returns exactly those (in first-seen order) and exact = true, and map() is then lossless. The octree +-- folds whole nodes, so it may return fewer than maxColors entries; below 8 colours median cut is used instead. +-- Never throws: bad arguments give an empty palette / a zero-filled index buffer. +local readu8, writeu8 = buffer.readu8, buffer.writeu8 +local readu32, writeu32, readf64, writef64 = buffer.readu32, buffer.writeu32, buffer.readf64, buffer.writef64 +local floor = math.floor +local blen = buffer.len + +local Quantize = {} + +export type Color = { number } -- { r, g, b, a } 0..255 +export type PaletteOptions = { + method: ("mediancut" | "octree")?, -- default "mediancut" +} +export type MapOptions = { + dither: boolean?, -- Floyd-Steinberg error diffusion (default false) + transparentIndex: number?, -- 0-based index for pixels with alpha < 128 (default: none) +} + +local BINS = 32768 -- 5 bits per channel + +-- ------------------------------------------------------------------------------------------------ helpers +local function count(pixels: buffer, n: number): (buffer, buffer) + -- per bin: u32 count; f64 sums of r, g, b + local cnt = buffer.create(BINS * 4) + local sums = buffer.create(BINS * 24) + for i = 0, n - 1 do + local o = i * 4 + if readu8(pixels, o + 3) >= 128 then + local r, g, b = readu8(pixels, o), readu8(pixels, o + 1), readu8(pixels, o + 2) + local bin = (r // 8) * 1024 + (g // 8) * 32 + b // 8 + writeu32(cnt, bin * 4, readu32(cnt, bin * 4) + 1) + local s = bin * 24 + writef64(sums, s, readf64(sums, s) + r) + writef64(sums, s + 8, readf64(sums, s + 8) + g) + writef64(sums, s + 16, readf64(sums, s + 16) + b) + end + end + return cnt, sums +end + +local function mean(cnt: buffer, sums: buffer, bins: { number }, lo: number, hi: number): Color + local n, r, g, b = 0, 0, 0, 0 + for i = lo, hi do + local bin = bins[i] + n += readu32(cnt, bin * 4) + r += readf64(sums, bin * 24) + g += readf64(sums, bin * 24 + 8) + b += readf64(sums, bin * 24 + 16) + end + if n == 0 then + return { 0, 0, 0, 255 } + end + return { floor(r / n + 0.5), floor(g / n + 0.5), floor(b / n + 0.5), 255 } +end + +-- ------------------------------------------------------------------------------------------------ median cut +local function medianCut(cnt: buffer, sums: buffer, maxColors: number): { Color } + local bins: { number } = {} + for bin = 0, BINS - 1 do + if readu32(cnt, bin * 4) > 0 then + table.insert(bins, bin) + end + end + if #bins == 0 then + return {} + end + -- boxes: { lo, hi } ranges of the bins array + local boxes: { { number } } = { { 1, #bins } } + local function channel(bin: number, c: number): number + if c == 0 then + return bin // 1024 + elseif c == 1 then + return (bin // 32) % 32 + end + return bin % 32 + end + local function stats(box: { number }): (number, number, number) + -- returns the widest channel, its range, the pixel count + local mins, maxs = { 31, 31, 31 }, { 0, 0, 0 } + local n = 0 + for i = box[1], box[2] do + local bin = bins[i] + n += readu32(cnt, bin * 4) + for c = 0, 2 do + local v = channel(bin, c) + if v < mins[c + 1] then + mins[c + 1] = v + end + if v > maxs[c + 1] then + maxs[c + 1] = v + end + end + end + local best, range = 0, -1 + for c = 0, 2 do + local rg = maxs[c + 1] - mins[c + 1] + if rg > range then + best, range = c, rg + end + end + return best, range, n + end + while #boxes < maxColors do + -- split the box with the largest range * sqrt(count) score (ties: the first) + local pick, pickScore, pickC = 0, 0, 0 + for i, box in boxes do + if box[2] > box[1] then + local c, range, n = stats(box) + local score = range * math.sqrt(n) + if score > pickScore then + pick, pickScore, pickC = i, score, c + end + end + end + if pick == 0 then + break + end + local box = boxes[pick] + local lo, hi = box[1], box[2] + -- sort the range by the channel (stable: ties by bin number) + local seg = table.create(hi - lo + 1) + for i = lo, hi do + seg[i - lo + 1] = bins[i] + end + local c = pickC + table.sort(seg, function(a: number, b: number): boolean + local va, vb = channel(a, c), channel(b, c) + if va ~= vb then + return va < vb + end + return a < b + end) + local total = 0 + for i = 1, #seg do + bins[lo + i - 1] = seg[i] + total += readu32(cnt, seg[i] * 4) + end + -- the weighted median, keeping both halves non-empty + local acc, cut = 0, lo + for i = lo, hi - 1 do + acc += readu32(cnt, bins[i] * 4) + cut = i + if acc * 2 >= total then + break + end + end + boxes[pick] = { lo, cut } + table.insert(boxes, { cut + 1, hi }) + end + local pal = table.create(#boxes) + for i, box in boxes do + pal[i] = mean(cnt, sums, bins, box[1], box[2]) + end + return pal +end + +-- ------------------------------------------------------------------------------------------------ octree +-- over the histogram bins: 5 levels (one bit of each channel per level). Nodes are array slots. +local function octree(cnt: buffer, sums: buffer, maxColors: number): { Color } + local child: { number } = {} -- node * 8 + k -> node (0 = none) + local n: { number } = {} -- pixel count + local sr: { number }, sg: { number }, sb: { number } = {}, {}, {} + local leaf: { boolean } = {} + local level: { number } = {} + local nodes = 1 + n[1], sr[1], sg[1], sb[1], leaf[1], level[1] = 0, 0, 0, 0, false, 0 + for k = 1, 8 do + child[k] = 0 + end + local byLevel: { { number } } = { {}, {}, {}, {}, {} } -- inner nodes per level 0..4, creation order + table.insert(byLevel[1], 1) + local leaves = 0 + for bin = 0, BINS - 1 do + local c = readu32(cnt, bin * 4) + if c > 0 then + local r5, g5, b5 = bin // 1024, (bin // 32) % 32, bin % 32 + local node = 1 + for lv = 0, 4 do + local sh = 4 - lv + local k = ((r5 // 2 ^ sh) % 2) * 4 + ((g5 // 2 ^ sh) % 2) * 2 + (b5 // 2 ^ sh) % 2 + local slot = (node - 1) * 8 + k + 1 + local nx = child[slot] + if nx == 0 then + nodes += 1 + nx = nodes + child[slot] = nx + for j = 1, 8 do + child[(nx - 1) * 8 + j] = 0 + end + n[nx], sr[nx], sg[nx], sb[nx], level[nx] = 0, 0, 0, 0, lv + 1 + leaf[nx] = lv == 4 + if lv == 4 then + leaves += 1 + else + table.insert(byLevel[lv + 2], nx) + end + end + node = nx + end + n[node] += c + sr[node] += readf64(sums, bin * 24) + sg[node] += readf64(sums, bin * 24 + 8) + sb[node] += readf64(sums, bin * 24 + 16) + end + end + -- fold the deepest inner nodes (fewest pixels first, ties by creation order) until few enough leaves remain + local function fold(node: number): number + -- merges the children (all leaves) into node; returns how many leaves disappeared + local merged = 0 + for k = 1, 8 do + local slot = (node - 1) * 8 + k + local ch = child[slot] + if ch ~= 0 then + n[node] += n[ch] + sr[node] += sr[ch] + sg[node] += sg[ch] + sb[node] += sb[ch] + child[slot] = 0 + merged += 1 + end + end + leaf[node] = true + return merged - 1 + end + local function subtotal(node: number): number + local s = 0 + for k = 1, 8 do + local ch = child[(node - 1) * 8 + k] + if ch ~= 0 then + s += n[ch] + end + end + return s + end + for lv = 5, 1, -1 do + if leaves <= maxColors then + break + end + local list = byLevel[lv] + local order = table.create(#list) + for i, node in list do + order[i] = { node, subtotal(node), i } + end + table.sort(order, function(a: { number }, b: { number }): boolean + if a[2] ~= b[2] then + return a[2] < b[2] + end + return a[3] < b[3] + end) + for _, e in order do + if leaves <= maxColors then + break + end + leaves -= fold(e[1]) + end + end + -- collect leaves depth first in child order + local pal: { Color } = {} + local function walk(node: number) + if leaf[node] then + local c = n[node] + if c > 0 then + table.insert(pal, { floor(sr[node] / c + 0.5), floor(sg[node] / c + 0.5), floor(sb[node] / c + 0.5), 255 }) + end + return + end + for k = 1, 8 do + local ch = child[(node - 1) * 8 + k] + if ch ~= 0 then + walk(ch) + end + end + end + walk(1) + -- the root itself can end up a leaf with everything (maxColors 1) + while #pal > maxColors do + table.remove(pal) + end + return pal +end + +-- ------------------------------------------------------------------------------------------------ palette +-- palette(pixels, w, h, maxColors, opts?) -> palette, exact +function Quantize.palette(pixels: buffer, w: number, h: number, maxColors: number, opts: PaletteOptions?): ({ Color }, boolean) + if type(pixels) ~= "buffer" or type(w) ~= "number" or type(h) ~= "number" or w < 0 or h < 0 or blen(pixels) < w * h * 4 then + return {}, false + end + local maxc = math.clamp(floor(tonumber(maxColors) or 256), 1, 65536) + local npx = w * h + -- exact colours, in first-seen order (stops counting past maxColors) + local seen: { [number]: boolean } = {} + local exact: { Color } = {} + local over = false + for i = 0, npx - 1 do + local o = i * 4 + if readu8(pixels, o + 3) >= 128 then + local r, g, b = readu8(pixels, o), readu8(pixels, o + 1), readu8(pixels, o + 2) + local key = r * 65536 + g * 256 + b + if not seen[key] then + if #exact >= maxc then + over = true + break + end + seen[key] = true + table.insert(exact, { r, g, b, 255 }) + end + end + end + if not over then + return exact, true + end + local cnt, sums = count(pixels, npx) + local method = opts and opts.method or "mediancut" + if method == "octree" and maxc >= 8 then -- below 8 the octree can only fold to a single colour + return octree(cnt, sums, maxc), false + end + return medianCut(cnt, sums, maxc), false +end + +-- ------------------------------------------------------------------------------------------------ map +-- map(pixels, w, h, palette, opts?) -> buffer of w * h palette indexes (0-based) +function Quantize.map(pixels: buffer, w: number, h: number, palette: { Color }, opts: MapOptions?): buffer + if type(pixels) ~= "buffer" or type(w) ~= "number" or type(h) ~= "number" or w < 0 or h < 0 or blen(pixels) < w * h * 4 or type(palette) ~= "table" then + return buffer.create(0) + end + local npx = w * h + local out = buffer.create(npx) + local dither = opts and opts.dither or false + local tidx = opts and opts.transparentIndex + -- the searchable entries (the transparent slot is excluded) + local pr, pg, pb, pi = {}, {}, {}, {} + for i, c in palette do + if tidx == nil or i - 1 ~= tidx then + table.insert(pr, c[1] or 0) + table.insert(pg, c[2] or 0) + table.insert(pb, c[3] or 0) + table.insert(pi, i - 1) + end + end + local np = #pr + if np == 0 then + if tidx then + buffer.fill(out, 0, math.clamp(tidx, 0, 255), npx) + end + return out + end + local cache: { [number]: number } = {} + local function nearest(r: number, g: number, b: number): number + local key = r * 65536 + g * 256 + b + local hit = cache[key] + if hit then + return hit + end + local best, bd = 1, math.huge + for k = 1, np do + local dr, dg, db = r - pr[k], g - pg[k], b - pb[k] + local d = dr * dr * 2 + dg * dg * 4 + db * db * 3 + if d < bd then + best, bd = k, d + if d == 0 then + break + end + end + end + cache[key] = best + return best + end + local tbyte = if tidx then math.clamp(tidx, 0, 255) else 0 + if not dither then + for i = 0, npx - 1 do + local o = i * 4 + if tidx and readu8(pixels, o + 3) < 128 then + writeu8(out, i, tbyte) + else + writeu8(out, i, pi[nearest(readu8(pixels, o), readu8(pixels, o + 1), readu8(pixels, o + 2))]) + end + end + return out + end + -- Floyd-Steinberg: error rows (f64 r, g, b per pixel, one extra pixel each side) + local rowLen = (w + 2) * 24 + local cur, nxt = buffer.create(rowLen), buffer.create(rowLen) + for y = 0, h - 1 do + buffer.fill(nxt, 0, 0, rowLen) + for x = 0, w - 1 do + local i = y * w + x + local o = i * 4 + if tidx and readu8(pixels, o + 3) < 128 then + writeu8(out, i, tbyte) + else + local e = (x + 1) * 24 + local r = math.clamp(floor(readu8(pixels, o) + readf64(cur, e) + 0.5), 0, 255) + local g = math.clamp(floor(readu8(pixels, o + 1) + readf64(cur, e + 8) + 0.5), 0, 255) + local b = math.clamp(floor(readu8(pixels, o + 2) + readf64(cur, e + 16) + 0.5), 0, 255) + local k = nearest(r, g, b) + writeu8(out, i, pi[k]) + local er, eg, eb = r - pr[k], g - pg[k], b - pb[k] + -- 7/16 right, 3/16 down-left, 5/16 down, 1/16 down-right + writef64(cur, e + 24, readf64(cur, e + 24) + er * 0.4375) + writef64(cur, e + 32, readf64(cur, e + 32) + eg * 0.4375) + writef64(cur, e + 40, readf64(cur, e + 40) + eb * 0.4375) + writef64(nxt, e - 24, readf64(nxt, e - 24) + er * 0.1875) + writef64(nxt, e - 16, readf64(nxt, e - 16) + eg * 0.1875) + writef64(nxt, e - 8, readf64(nxt, e - 8) + eb * 0.1875) + writef64(nxt, e, readf64(nxt, e) + er * 0.3125) + writef64(nxt, e + 8, readf64(nxt, e + 8) + eg * 0.3125) + writef64(nxt, e + 16, readf64(nxt, e + 16) + eb * 0.3125) + writef64(nxt, e + 24, readf64(nxt, e + 24) + er * 0.0625) + writef64(nxt, e + 32, readf64(nxt, e + 32) + eg * 0.0625) + writef64(nxt, e + 40, readf64(nxt, e + 40) + eb * 0.0625) + end + end + cur, nxt = nxt, cur + end + return out +end + +-- quantize(pixels, w, h, maxColors, opts?) -> indexes, palette, exact: palette() then map() (opts of both) +function Quantize.quantize(pixels: buffer, w: number, h: number, maxColors: number, opts: any?): (buffer, { Color }, boolean) + local pal, exact = Quantize.palette(pixels, w, h, maxColors, opts) + local mo = opts + if exact and opts and opts.dither then + mo = table.clone(opts) + mo.dither = false -- nothing to diffuse + end + return Quantize.map(pixels, w, h, pal, mo), pal, exact +end + +return Quantize diff --git a/src/Formats/image/gif/Decode.luau b/src/Formats/image/gif/Decode.luau new file mode 100644 index 0000000..98a6c7c --- /dev/null +++ b/src/Formats/image/gif/Decode.luau @@ -0,0 +1,68 @@ +--!strict +--!native +--!optimize 2 +-- image/gif/Decode: the per-frame pixel work (native; never throws): palette indexes (plain or interlaced rows) to +-- rgba8, and drawing a frame onto the canvas (transparent pixels leave the canvas as it is). The caller sizes every +-- buffer: indexes fw * fh bytes, the palette 256 u32 entries, the frame fw * fh * 4, the canvas cw * ch * 4. +local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32 + +local Decode = {} + +-- the source row of output row y in an interlaced frame (passes: every 8th from 0, every 8th from 4, every 4th from +-- 2, every 2nd from 1) +local function interlacedRow(fh: number): { number } + local map = table.create(fh, 0) + local r = 0 + for _, pass in { { 0, 8 }, { 4, 8 }, { 2, 4 }, { 1, 2 } } do + local y = pass[1] + while y < fh do + map[y + 1] = r + r += 1 + y += pass[2] + end + end + return map +end + +-- toRgba(indexes, fw, fh, interlaced, palette, out): out = the frame in rgba8 (palette: 256 u32 entries, the +-- transparent one already alpha 0) +function Decode.toRgba(indexes: buffer, fw: number, fh: number, interlaced: boolean, palette: buffer, out: buffer) + local rows = if interlaced then interlacedRow(fh) else nil + for y = 0, fh - 1 do + local src = (if rows then rows[y + 1] else y) * fw + local dst = y * fw * 4 + for x = 0, fw - 1 do + writeu32(out, dst + x * 4, readu32(palette, readu8(indexes, src + x) * 4)) + end + end +end + +-- draw(canvas, cw, ch, frame, fx, fy, fw, fh): frame pixels with alpha > 0 replace the canvas (clipped) +function Decode.draw(canvas: buffer, cw: number, ch: number, frame: buffer, fx: number, fy: number, fw: number, fh: number) + local x0, y0 = math.max(0, fx), math.max(0, fy) + local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh) + for y = y0, y1 - 1 do + local s = ((y - fy) * fw - fx) * 4 + local d = y * cw * 4 + for x = x0, x1 - 1 do + local v = readu32(frame, s + x * 4) + if v >= 0x01000000 then + writeu32(canvas, d + x * 4, v) + end + end + end +end + +-- clear(canvas, cw, ch, fx, fy, fw, fh): the frame's rectangle to transparent black (dispose to background) +function Decode.clear(canvas: buffer, cw: number, ch: number, fx: number, fy: number, fw: number, fh: number) + local x0, y0 = math.max(0, fx), math.max(0, fy) + local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh) + if x1 <= x0 then + return + end + for y = y0, y1 - 1 do + buffer.fill(canvas, (y * cw + x0) * 4, 0, (x1 - x0) * 4) + end +end + +return Decode diff --git a/src/Formats/image/gif/init.luau b/src/Formats/image/gif/init.luau new file mode 100644 index 0000000..c2b84f4 --- /dev/null +++ b/src/Formats/image/gif/init.luau @@ -0,0 +1,534 @@ +--!strict +-- image/gif: GIF87a / GIF89a. New code from the GIF89a spec (W3C / CompuServe 1990). Supports: decode of every image +-- (global / local colour tables, interlaced rows, LZW minimum code sizes 2..8 and the odd 1, transparency, frames +-- smaller than or outside the canvas), animation (Graphic Control Extension delays, disposal none / background / +-- previous, NETSCAPE2.0 / ANIMEXTS1.0 loop counts), comments (meta.text.comment); truncated files keep the frames +-- read so far (meta.truncated). Encode of rgba8 images and animations (Types.Frame lists) through codecs/Quantize +-- (median cut or octree, optional Floyd-Steinberg dithering; exact palettes, so lossless, at <= 256 colours) with +-- alpha < 128 as the transparent index. +-- Not supported: the plain text extension (skipped), the aspect ratio (kept in meta.source.aspect), the "user input" +-- flag, and blend = "source" frames that clear pixels to transparent (GIF can only draw over). +-- +-- Decoded value: img.pixels = the first frame composited on a transparent canvas; for animations img.frames = every +-- frame's own rectangle (rgba8; blend "over" when it has a transparent index, else "source") and img.loops, the +-- number of plays (0 = forever; 1 when the file has no loop extension). The NETSCAPE2.0 value counts repeats, as +-- browsers and ImageMagick read it: a stored n plays n + 1 times (n = 0: forever). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Lzw = require("@formats/codecs/Lzw") +local Quantize = require("@formats/codecs/Quantize") +local Types = require("@formats/Types") +local Decode = require("@formats/image/gif/Decode") + +-- ------------------------------------------------------------------------------------------------ contract +local Gif = { + name = "gif", + category = "image", + extensions = { "gif" }, + mime = { "image/gif" }, + deps = { "core/Err", "core/Bytes", "codecs/Lzw", "codecs/Quantize", "Types" }, + caps = { decode = true, encode = true, animation = true, alpha = true, palette = true, depths = { 1, 2, 4, 8 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxPixels: number?, -- refuse a canvas or frame larger than this (default 2^26) + maxTotalPixels: number?, -- refuse animations whose frames add up to more (default 2^28) + maxFrames: number?, -- stop after this many frames (default: all) +} +export type EncodeOptions = { + maxColors: number?, -- 2..256 per palette (default 256; one is taken by transparency when needed) + method: ("mediancut" | "octree")?, -- default "mediancut" + dither: boolean?, -- Floyd-Steinberg (default false) + loops: number?, -- animation plays override (0 = forever, 1..65536; default img.loops) + globalPalette: boolean?, -- one palette for every frame (default false: a single image uses the global table, + -- each animation frame gets its own local table) +} + +-- ------------------------------------------------------------------------------------------------ constants +local readu8 = buffer.readu8 +local DISPOSE = { [0] = "none", [1] = "none", [2] = "background", [3] = "previous" } +local DISPOSE_CODE = { none = 1, background = 2, previous = 3 } + +-- ------------------------------------------------------------------------------------------------ sniff +function Gif.sniff(r: Bytes.Reader): number + local s = r:peek(6) + return if s == "GIF89a" or s == "GIF87a" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a colour table at p (n entries) -> 256 u32 rgba entries (missing ones opaque black) and the { r, g, b, a } list +local function colorTable(b: buffer, p: number, n: number): (buffer, { { number } }) + local t = buffer.create(1024) + local list = table.create(n) + for i = 0, 255 do + buffer.writeu32(t, i * 4, 0xFF000000) + end + for i = 0, n - 1 do + local q = p + i * 3 + local r, g, bl = readu8(b, q), readu8(b, q + 1), readu8(b, q + 2) + buffer.writeu32(t, i * 4, r + g * 256 + bl * 65536 + 0xFF000000) + list[i + 1] = { r, g, bl, 255 } + end + return t, list +end + +function Gif.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local maxTotal = opts and opts.maxTotalPixels or 2 ^ 28 + local maxFrames = opts and opts.maxFrames or math.huge + local sig = r:string(6) + local cw, ch = r:u16le(), r:u16le() + local flags, bg, aspect = r:u8(), r:u8(), r:u8() + if r.err then + return nil, r.err + end + if sig ~= "GIF89a" and sig ~= "GIF87a" then + return nil, Err.new(Err.CORRUPT, "bad signature", r.base) + end + if cw == 0 or ch == 0 then + return nil, Err.new(Err.CORRUPT, "zero canvas size", r.base + 6) + end + if cw * ch > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", cw, ch, maxPixels)) + end + local b = r.buf + local gct: buffer? = nil + local gpal: { { number } }? = nil + if bit32.band(flags, 0x80) ~= 0 then + local n = bit32.lshift(1, bit32.band(flags, 7) + 1) + if not r:need(n * 3) then + return nil, r.err + end + gct, gpal = colorTable(b, r.pos, n) + r.pos += n * 3 + end + local img = Types.Image.new(cw, ch, "rgba8") + local frames: { Types.Frame } = {} + local comments: { string } = {} + local loops: number? = nil + local total = 0 + -- the pending Graphic Control Extension + local delay, dispose, trans = 0, 0, -1 + local truncated = false + local interlacedAny = false + local localTables = 0 + local minCode = 8 + local limit = r.limit + -- the sub-blocks at r.pos: joined into one buffer (nil when they run past the end) + local function subBlocks(): (buffer?, number) + local p = r.pos + local n = 0 + while true do + if p >= limit then + return nil, p + end + local len = readu8(b, p) + if len == 0 then + break + end + if p + 1 + len > limit then + -- keep what is there: a truncated last block + n += limit - p - 1 + p = limit + local out = buffer.create(n) + local q, o = r.pos, 0 + while q < limit do + local l = math.min(readu8(b, q), limit - q - 1) + buffer.copy(out, o, b, q + 1, l) + o += l + q += 1 + l + end + return out, -1 + end + n += len + p += 1 + len + end + local out = buffer.create(n) + local q, o = r.pos, 0 + while q < p do + local l = readu8(b, q) + buffer.copy(out, o, b, q + 1, l) + o += l + q += 1 + l + end + return out, p + 1 + end + local function skipBlocks(): boolean + local p = r.pos + while p < limit do + local len = readu8(b, p) + if len == 0 then + r.pos = p + 1 + return true + end + p += 1 + len + end + r.pos = limit + return false + end + while true do + if r.pos >= limit then + truncated = true + break + end + local intro = r:u8() + if intro == 0x3B then + break + elseif intro == 0x21 then + local label = r:u8() + if r.err then + truncated = true + break + end + local p = r.pos + if label == 0xF9 and p + 6 <= limit and readu8(b, p) >= 4 then + local f = readu8(b, p + 1) + dispose = bit32.band(bit32.rshift(f, 2), 7) + delay = readu8(b, p + 2) + readu8(b, p + 3) * 256 + trans = if bit32.band(f, 1) ~= 0 then readu8(b, p + 4) else -1 + elseif label == 0xFF and p + 15 <= limit and readu8(b, p) == 11 then + local id = buffer.readstring(b, p + 1, 11) + if (id == "NETSCAPE2.0" or id == "ANIMEXTS1.0") and readu8(b, p + 12) >= 3 and readu8(b, p + 13) == 1 then + local rep = readu8(b, p + 14) + readu8(b, p + 15) * 256 + loops = if rep == 0 then 0 else rep + 1 -- the stored value repeats: plays = value + 1 + end + elseif label == 0xFE then + local data = subBlocks() + if data then + table.insert(comments, buffer.tostring(data)) + end + end + if not skipBlocks() then + truncated = true + break + end + elseif intro == 0x2C then + local fx, fy, fw, fh = r:u16le(), r:u16le(), r:u16le(), r:u16le() + local f = r:u8() + if r.err then + truncated = true + break + end + if fw * fh > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("a %d x %d frame is over the %d pixel limit", fw, fh, maxPixels), r.pos) + end + total += fw * fh + if total > maxTotal then + return nil, Err.new(Err.LIMIT, string.format("the frames add up to over %d pixels", maxTotal), r.pos) + end + local pal = gct + if bit32.band(f, 0x80) ~= 0 then + local n = bit32.lshift(1, bit32.band(f, 7) + 1) + if not r:need(n * 3) then + truncated = true + break + end + pal = colorTable(b, r.pos, n) + r.pos += n * 3 + localTables += 1 + end + local interlaced = bit32.band(f, 0x40) ~= 0 + interlacedAny = interlacedAny or interlaced + local mc = r:u8() + if r.err then + truncated = true + break + end + if mc < 1 or mc > 11 then + return nil, Err.new(Err.CORRUPT, "bad LZW minimum code size " .. mc, r.pos - 1) + end + minCode = mc + local data, nextPos = subBlocks() + if not data then + truncated = true + break + end + local n = fw * fh + local idx = buffer.create(n) + local got, lerr = Lzw.decode(data, 0, buffer.len(data), idx, 0, n, "gif", mc) + if got < n or nextPos < 0 then + truncated = true -- the missing pixels stay index 0, as most decoders show them + end + local _ = lerr -- a corrupt code ends the frame early (kept: what was decoded is shown) + local t = buffer.create(1024) + if pal then + buffer.copy(t, 0, pal) + else + -- no colour table at all: a grey ramp (what the spec leaves to the decoder) + for i = 0, 255 do + buffer.writeu32(t, i * 4, i + i * 256 + i * 65536 + 0xFF000000) + end + end + if trans >= 0 then + buffer.writeu32(t, trans * 4, 0) + end + local fimg = Types.Image.new(fw, fh, "rgba8") + Decode.toRgba(idx, fw, fh, interlaced, t, fimg.pixels) + if #frames == 0 then + Decode.draw(img.pixels, cw, ch, fimg.pixels, fx, fy, fw, fh) + end + table.insert(frames, { + image = fimg, + delay = delay / 100, + x = fx, + y = fy, + dispose = DISPOSE[dispose] or "none", + blend = if trans >= 0 then "over" else "source", + } :: Types.Frame) + delay, dispose, trans = 0, 0, -1 + if nextPos < 0 then + break + end + r.pos = nextPos + if #frames >= maxFrames then + break + end + else + -- junk between blocks: stop here, keeping what was read + if #frames == 0 then + return nil, Err.new(Err.CORRUPT, string.format("bad block introducer 0x%02x", intro), r.pos - 1) + end + truncated = true + break + end + end + if #frames == 0 then + return nil, Err.new(Err.TRUNCATED, "no image data", r.pos) + end + if #frames > 1 then + img.frames = frames + img.loops = loops or 1 + else + img.loops = loops or 0 + end + img.meta.palette = gpal + img.meta.background = bg + if #comments > 0 then + img.meta.text = { comment = table.concat(comments, "\n") } + end + if truncated then + img.meta.truncated = true + end + img.meta.source = { + format = "gif", + version = string.sub(sig, 4), + bitDepth = minCode, + colorType = "palette", + frames = #frames, + interlaced = interlacedAny, + localPalettes = localTables, + aspect = aspect, + loopExtension = loops ~= nil, + } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function validImage(i: any): boolean + return type(i) == "table" and i.format == "rgba8" and type(i.pixels) == "buffer" and type(i.width) == "number" and type(i.height) == "number" and i.width >= 1 and i.height >= 1 and i.width <= 65535 and i.height <= 65535 and i.width % 1 == 0 and i.height % 1 == 0 and buffer.len(i.pixels) >= i.width * i.height * 4 +end + +local function hasTransparency(px: buffer, n: number): boolean + for i = 0, n - 1 do + if readu8(px, i * 4 + 3) < 128 then + return true + end + end + return false +end + +-- palette list -> padded table bytes (power of two entries, >= 2) and its size code +local function writeTable(w: Bytes.Writer, pal: { { number } }): number + local bits = 1 + while bit32.lshift(1, bits) < #pal do + bits += 1 + end + for i = 1, bit32.lshift(1, bits) do + local c = pal[i] + if c then + w:u8(c[1]) + w:u8(c[2]) + w:u8(c[3]) + else + w:fill(0, 3) + end + end + return bits +end + +local function tableBits(n: number): number + local bits = 1 + while bit32.lshift(1, bits) < n do + bits += 1 + end + return bits +end + +function Gif.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if not validImage(img) then + return nil, Err.new(Err.ARG, "needs an rgba8 Image of 1..65535 x 1..65535 pixels") + end + local maxColors = opts and opts.maxColors or 256 + if type(maxColors) ~= "number" or maxColors < 2 or maxColors > 256 then + return nil, Err.new(Err.ARG, "maxColors must be 2..256") + end + maxColors = math.floor(maxColors) + local method = opts and opts.method or "mediancut" + if method ~= "mediancut" and method ~= "octree" then + return nil, Err.new(Err.ARG, "method must be mediancut or octree") + end + local dither = opts and opts.dither or false + -- the frames to write: { image, x, y, delay, dispose } + local list: { Types.Frame } = {} + if type(img.frames) == "table" and #(img.frames :: any) > 0 then + for i, f in img.frames :: { Types.Frame } do + if type(f) ~= "table" or not validImage(f.image) then + return nil, Err.new(Err.ARG, "frame " .. i .. ": needs an rgba8 image") + end + local x, y = f.x or 0, f.y or 0 + if type(x) ~= "number" or type(y) ~= "number" or x < 0 or y < 0 or x + f.image.width > 65535 or y + f.image.height > 65535 then + return nil, Err.new(Err.ARG, "frame " .. i .. ": bad position") + end + table.insert(list, f) + end + else + list[1] = { image = img, x = 0, y = 0, delay = 0, dispose = "none", blend = "source" } + end + local animated = #list > 1 + local loops = opts and opts.loops or img.loops or 0 + if type(loops) ~= "number" or loops < 0 or loops > 65536 or loops % 1 ~= 0 then + return nil, Err.new(Err.ARG, "loops must be 0..65536") + end + -- palettes + local shared = (opts and opts.globalPalette) or not animated + local qopts = { method = method, dither = dither } + local globalPal: { { number } }? = nil + local globalTrans = false + if shared then + -- every frame's pixels together + local npx = 0 + for _, f in list do + npx += f.image.width * f.image.height + end + local all = buffer.create(npx * 4) + local o = 0 + for _, f in list do + local n = f.image.width * f.image.height * 4 + buffer.copy(all, o, f.image.pixels, 0, n) + o += n + end + globalTrans = hasTransparency(all, npx) + local pal = Quantize.palette(all, npx, 1, if globalTrans then maxColors - 1 else maxColors, qopts) + if #pal == 0 then + pal = { { 0, 0, 0, 255 } } + end + if globalTrans then + table.insert(pal, { 0, 0, 0, 0 }) + end + globalPal = pal + end + local w = Bytes.writer(img.width * img.height + 1024) + w:string("GIF89a") + w:u16le(img.width) + w:u16le(img.height) + if globalPal then + w:u8(0x80 + 0x70 + (tableBits(#globalPal) - 1)) + w:u8(0) + w:u8(0) + writeTable(w, globalPal) + else + w:u8(0x70) + w:u8(0) + w:u8(0) + end + if animated and loops ~= 1 then + w:u8(0x21) + w:u8(0xFF) + w:u8(11) + w:string("NETSCAPE2.0") + w:u8(3) + w:u8(1) + w:u16le(if loops == 0 then 0 else loops - 1) + w:u8(0) + end + local text = img.meta and img.meta.text + local comment = text and (text.comment or text.Comment) + if type(comment) == "string" and #comment > 0 then + w:u8(0x21) + w:u8(0xFE) + for i = 1, #comment, 255 do + local part = string.sub(comment, i, i + 254) + w:u8(#part) + w:string(part) + end + w:u8(0) + end + for _, f in list do + local fi = f.image + local fw, fh = fi.width, fi.height + local n = fw * fh + local pal: { { number } } + local tidx: number? = nil + if globalPal then + pal = globalPal + if globalTrans then + tidx = #pal - 1 + end + else + local tr = hasTransparency(fi.pixels, n) + pal = Quantize.palette(fi.pixels, fw, fh, if tr then maxColors - 1 else maxColors, qopts) + if #pal == 0 then + pal = { { 0, 0, 0, 255 } } + end + if tr then + table.insert(pal, { 0, 0, 0, 0 }) + tidx = #pal - 1 + end + end + local idx = Quantize.map(fi.pixels, fw, fh, pal, { dither = dither, transparentIndex = tidx }) + -- the Graphic Control Extension: always for animations, else only for transparency + if animated or tidx then + local d = DISPOSE_CODE[f.dispose or "none"] or 1 + w:u8(0x21) + w:u8(0xF9) + w:u8(4) + w:u8(d * 4 + (if tidx then 1 else 0)) + w:u16le(math.clamp(math.floor((f.delay or 0) * 100 + 0.5), 0, 65535)) + w:u8(tidx or 0) + w:u8(0) + end + w:u8(0x2C) + w:u16le(f.x or 0) + w:u16le(f.y or 0) + w:u16le(fw) + w:u16le(fh) + local bits + if globalPal then + w:u8(0) + bits = tableBits(#globalPal) + else + bits = tableBits(#pal) + w:u8(0x80 + bits - 1) + writeTable(w, pal) + end + local mc = math.max(2, bits) + w:u8(mc) + local codes = Lzw.encode(idx, 0, n, "gif", mc) + local cl = buffer.len(codes) + local p = 0 + while p < cl do + local l = math.min(255, cl - p) + w:u8(l) + w:bytes(codes, p, l) + p += l + end + w:u8(0) + end + w:u8(0x3B) + return w:finish(), nil +end + +return Gif diff --git a/tests/codecs/quantize.luau b/tests/codecs/quantize.luau new file mode 100644 index 0000000..60c761b --- /dev/null +++ b/tests/codecs/quantize.luau @@ -0,0 +1,135 @@ +-- codecs/Quantize tests: palette size bounds for every method and colour budget, the exact (lossless) palette at +-- <= maxColors colours, transparency handling, PSNR of quantized images above thresholds, determinism of both +-- methods and of Floyd-Steinberg dithering (the same CRC on both runtimes), bad arguments, and a no-throw pass. +local T = require("@tests/T") +local Quantize = require("@formats/codecs/Quantize") +local Crc32 = require("@formats/core/Crc32") + +local t = T.suite("quantize") +local rand = T.rng(5) + +local function photo(w: number, h: number): buffer + local px = buffer.create(w * h * 4) + for i = 0, w * h - 1 do + local x, y = i % w, i // w + local r = (x * 255) // (w - 1) + local g = (y * 255) // (h - 1) + local b = math.floor(128 + 100 * math.sin(x * 0.11) * math.cos(y * 0.07)) + rand(9) + buffer.writeu32(px, i * 4, r + g * 256 + math.clamp(b, 0, 255) * 65536 + 0xFF000000) + end + return px +end + +local function render(idx: buffer, pal: { { number } }, n: number): buffer + local out = buffer.create(n * 4) + for i = 0, n - 1 do + local c = pal[buffer.readu8(idx, i) + 1] + buffer.writeu32(out, i * 4, c[1] + c[2] * 256 + c[3] * 65536 + 0xFF000000) + end + return out +end + +local function psnr(a: buffer, b: buffer): number + local se, n = 0, 0 + for o = 0, buffer.len(a) - 4, 4 do + for k = 0, 2 do + local d = buffer.readu8(a, o + k) - buffer.readu8(b, o + k) + se += d * d + n += 1 + end + end + return if se == 0 then 99 else 10 * math.log10(255 * 255 * n / se) +end + +local W, H = 128, 96 +local px = photo(W, H) +-- palette bounds and quality +local MIN_PSNR = { [256] = 30, [64] = 24, [16] = 17, [2] = 10 } +for _, method in { "mediancut", "octree" } do + for _, k in { 2, 16, 64, 256 } do + local pal, exact = Quantize.palette(px, W, H, k, { method = method }) + t:check(#pal >= 1 and #pal <= k, string.format("%s %d: palette size %d", method, k, #pal)) + t:check(not exact, method .. ": not exact") + for _, c in pal do + t:check(#c == 4 and c[4] == 255 and c[1] % 1 == 0 and c[1] >= 0 and c[1] <= 255, "palette entries") + end + for _, dither in { false, true } do + local idx = Quantize.map(px, W, H, pal, { dither = dither }) + t:eq(buffer.len(idx), W * H, "index buffer size") + local p = psnr(render(idx, pal, W * H), px) + local want = MIN_PSNR[k] - (if dither then 4 else 0) + t:check(p > want, string.format("%s %d dither=%s: PSNR %.1f > %d", method, k, tostring(dither), p, want)) + if k == 256 or k == 16 then + t:note("%-9s %3d colours dither=%-5s PSNR %.1f dB, crc %08x", method, k, tostring(dither), p, Crc32.of(idx)) + end + end + end +end + +-- exact palettes: lossless +do + local n = 50 * 40 + local b = buffer.create(n * 4) + for i = 0, n - 1 do + local k = (i * 7 + i // 50) % 200 + buffer.writeu32(b, i * 4, (k * 3) % 256 + ((k * 11) % 256) * 256 + k * 65536 + 0xFF000000) + end + local pal, exact = Quantize.palette(b, 50, 40, 256) + t:check(exact and #pal == 200, "exact palette of 200 colours: " .. #pal) + local idx = Quantize.map(b, 50, 40, pal, { dither = true }) + t:check(buffer.tostring(render(idx, pal, n)) == buffer.tostring(b), "exact palette maps losslessly (dither too)") + local pal2, exact2 = Quantize.palette(b, 50, 40, 199) + t:check(not exact2 and #pal2 <= 199, "199 colours is not exact") + local i3, p3, e3 = Quantize.quantize(b, 50, 40, 256, { dither = true }) + t:check(e3 and #p3 == 200 and buffer.tostring(render(i3, p3, n)) == buffer.tostring(b), "quantize() exact") +end + +-- transparency +do + local b = buffer.create(16 * 4) + for i = 0, 15 do + buffer.writeu32(b, i * 4, if i % 3 == 0 then 0x10FFFFFF else 0xFF0000FF + i * 256) + end + local pal, exact = Quantize.palette(b, 4, 4, 255) + t:check(exact and #pal == 10, "transparent pixels are not in the palette") + table.insert(pal, { 0, 0, 0, 0 }) + local idx = Quantize.map(b, 4, 4, pal, { transparentIndex = #pal - 1, dither = true }) + for i = 0, 15 do + local v = buffer.readu8(idx, i) + t:check((i % 3 == 0) == (v == #pal - 1), "transparent index " .. i) + end +end + +-- determinism (also across runtimes: these CRCs are pinned) +do + local pal = Quantize.palette(px, W, H, 64, { method = "mediancut" }) + local a = Crc32.of(Quantize.map(px, W, H, pal, { dither = true })) + local pal2 = Quantize.palette(px, W, H, 64, { method = "mediancut" }) + t:eq(Crc32.of(Quantize.map(px, W, H, pal2, { dither = true })), a, "mediancut + dither deterministic") + t:eq(a, 0xd2c76537, "mediancut 64 + dither: the pinned CRC (the same on both runtimes)") + local o1 = Quantize.palette(px, W, H, 37, { method = "octree" }) + local o2 = Quantize.palette(px, W, H, 37, { method = "octree" }) + t:check(#o1 == #o2 and o1[#o1][1] == o2[#o2][1], "octree deterministic") +end + +-- bad arguments never throw +do + t:eq(#Quantize.palette(nil :: any, 1, 1, 4), 0, "nil pixels") + t:eq(#Quantize.palette(buffer.create(3), 1, 1, 4), 0, "short buffer") + t:eq(buffer.len(Quantize.map(px, W, H, {})), W * H, "empty palette") + t:eq(buffer.len(Quantize.map(buffer.create(1), 2, 2, { { 1, 2, 3, 255 } })), 0, "short buffer map") + local ok = pcall(function() + for i = 1, 20 do + local w, h = 1 + rand(20), 1 + rand(20) + local b = buffer.create(w * h * 4) + for k = 0, w * h * 4 - 1 do + buffer.writeu8(b, k, rand(256)) + end + local pal = Quantize.palette(b, w, h, 1 + rand(256), { method = if i % 2 == 0 then "octree" else "mediancut" }) + Quantize.map(b, w, h, pal, { dither = i % 3 == 0, transparentIndex = if i % 4 == 0 then 0 else nil }) + end + end) + t:check(ok, "random images never throw") +end + +t:done() diff --git a/tests/image/gif.luau b/tests/image/gif.luau new file mode 100644 index 0000000..a2ccae8 --- /dev/null +++ b/tests/image/gif.luau @@ -0,0 +1,221 @@ +-- image/gif tests: GIFs from ImageMagick and Pillow (static, interlaced, 2..256 colours, grey, transparency, +-- animations with every disposal, sub-rectangles, local colour tables, loop counts, comments) against ImageMagick's +-- decode of every frame; the encoder (lossless round trips at <= 256 colours, quantized PSNR above, animations with +-- frames / delays / disposal / transparency / loops, options); error codes; the fuzz no-throw pass. +-- Fixtures: tools/fixtures/gif.py. +local T = require("@tests/T") +local Gif = require("@formats/image/gif") +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/gif") + +local t = T.suite("gif") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Gif.decode(Bytes.reader(b), opts) +end + +-- rgba8 with alpha-0 pixels zeroed (the fixtures' convention) +local function norm(px: buffer): buffer + local n = buffer.len(px) + local c = buffer.create(n) + buffer.copy(c, 0, px) + for o = 0, n - 4, 4 do + if buffer.readu8(c, o + 3) == 0 then + buffer.writeu32(c, o, 0) + end + end + return c +end + +-- the contract +t:eq(Gif.name, "gif", "name") +t:eq(Gif.category, "image", "category") +t:check(Gif.caps.decode and Gif.caps.encode and Gif.caps.animation, "caps") + +-- every fixture against ImageMagick +local nframes = 0 +for _, c in Fx do + local img, err = decode(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 .. ": canvas") + t:check(not img.meta.truncated, c.name .. ": flagged truncated") + t:eq(Crc32.of(norm(img.pixels)), c.first, c.name .. ": first frame composited") + local frames = img.frames or { { image = img, x = 0, y = 0, delay = 0, dispose = "none" } } + t:eq(#frames, #c.frames, c.name .. ": frame count") + for i, rf in c.frames do + local f = frames[i] + local label = c.name .. " frame " .. i + if img.frames then + t:check(f.image.width == rf.w and f.image.height == rf.h and f.x == rf.x and f.y == rf.y, label .. ": rectangle") + t:eq(math.floor(f.delay * 100 + 0.5), rf.delay, label .. ": delay") + local want = if rf.dispose == "undefined" then "none" else rf.dispose + t:eq(f.dispose, want, label .. ": dispose") + t:eq(Crc32.of(norm(f.image.pixels)), rf.crc, label .. ": pixels") + else + t:eq(Crc32.of(norm(img.pixels)), rf.crc, label .. ": pixels") + end + nframes += 1 + end + if c.loops then + t:eq(img.loops, if c.loops == 0 then 0 else c.loops + 1, c.name .. ": loops (plays)") + end + if c.comment then + t:eq(img.meta.text and img.meta.text.comment, c.comment, c.name .. ": comment") + end +end +t:note("%d files, %d frames match ImageMagick", #Fx, nframes) + +-- sniff, meta, limits, errors +do + local c = Fx[1] + t:eq(Gif.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, "sniff a GIF") + t:eq(Gif.sniff(Bytes.reader(buffer.fromstring("\137PNG\r\n\26\n"))), 0, "sniff a PNG") + t:eq(Gif.sniff(Bytes.reader(buffer.create(0))), 0, "sniff nothing") + local img = decode(c.data) + t:check(img.meta.source.format == "gif" and img.meta.source.version == "89a", "meta.source") + t:check(img.meta.palette and #img.meta.palette >= 2 and #img.meta.palette[1] == 4, "meta.palette") + local _, e = decode(c.data, { maxPixels = 100 }) + t:check(e and e.code == Err.LIMIT, "maxPixels: " .. tostring(e)) + local _, e2 = decode("GIF89a") + t:check(e2 and e2.code == Err.TRUNCATED, "header only: " .. tostring(e2)) + local _, e3 = decode("NOTGIF1234567") + t:check(e3 and e3.code == Err.CORRUPT, "junk: " .. tostring(e3)) + -- a truncated file keeps its frames + for _, f in Fx do + if f.name == "anim_none" then + local cut = string.sub(f.data, 1, #f.data - 20) + local part = decode(cut) + t:check(part and part.meta.truncated, "truncated animation decodes partially") + local one = decode(f.data, { maxFrames = 1 }) + t:check(one and one.frames == nil, "maxFrames = 1") + local big = buffer.create(#f.data + 9) + buffer.writestring(big, 5, f.data) + local sub = Gif.decode(Bytes.reader(big, 5, #f.data)) + t:check(sub and sub.frames and #sub.frames == 4, "decode from a sub-range") + end + end +end + +-- the encoder +local rand = T.rng(17) +local function image(w: number, h: number, colors: number?, alpha: boolean?): Types.Image + local img = Types.Image.new(w, h) + for i = 0, w * h - 1 do + local x, y = i % w, i // w + local r, g, b + if colors then + local k = (x // 3 + y // 2 * 7 + rand(2)) % colors + r, g, b = (k * 53) % 256, (k * 97) % 256, (k * 31) % 256 + else + r, g, b = (x * 255) // math.max(1, w - 1), (y * 255) // math.max(1, h - 1), ((x + y) * 3 + rand(16)) % 256 + end + local a = if alpha and (x * x + y * y) % 11 == 0 then 0 else 255 + buffer.writeu32(img.pixels, i * 4, r + g * 256 + b * 65536 + a * 16777216) + end + return img +end +local function same(a: buffer, b: buffer): boolean + return buffer.tostring(norm(a)) == buffer.tostring(norm(b)) +end +local function psnr(a: buffer, b: buffer): number + local se, n = 0, 0 + for o = 0, buffer.len(a) - 4, 4 do + for k = 0, 2 do + local d = buffer.readu8(a, o + k) - buffer.readu8(b, o + k) + se += d * d + n += 1 + end + end + if se == 0 then + return 99 + end + return 10 * math.log10(255 * 255 * n / se) +end +do + for _, colors in { 2, 3, 16, 200, 256 } do + for _, alpha in { false, true } do + local ncol = if alpha and colors == 256 then 255 else colors + local img = image(37, 23, ncol, alpha) + local gif, err = Gif.encode(img) + t:check(gif, "encode: " .. tostring(err)) + local back = decode(gif) + t:check(back and same(back.pixels, img.pixels), string.format("%d colours alpha=%s: lossless round trip", ncol, tostring(alpha))) + t:check(back.frames == nil, "single image") + end + end + -- more than 256 colours: quantized, every method, with and without dithering + local photo = image(96, 64) + for _, method in { "mediancut", "octree" } do + for _, dither in { false, true } do + local gif = Gif.encode(photo, { method = method, dither = dither }) :: buffer + local back = decode(gif) + local p = psnr(back.pixels, photo.pixels) + t:check(p > (if dither then 28 else 30), string.format("%s dither=%s: PSNR %.1f", method, tostring(dither), p)) + t:note("encode %s dither=%s: %d bytes, PSNR %.1f dB", method, tostring(dither), buffer.len(gif), p) + end + end + local small = Gif.encode(photo, { maxColors = 4 }) :: buffer + local sb = decode(small) + t:check(sb.meta.palette and #sb.meta.palette <= 4, "maxColors = 4") + -- animation: frames, delays, disposal, transparency, loops, comment, local / global palettes + local anim = image(40, 30, 50) + anim.frames = { + { image = image(40, 30, 50), x = 0, y = 0, delay = 0.1, dispose = "none", blend = "source" }, + { image = image(10, 12, 7, true), x = 5, y = 6, delay = 0.25, dispose = "background", blend = "over" }, + { image = image(20, 5), x = 20, y = 25, delay = 1.5, dispose = "previous", blend = "source" }, + } + anim.loops = 4 + anim.meta.text = { comment = "hello gif" } + for _, global in { false, true } do + local gif, err = Gif.encode(anim, { globalPalette = global }) + t:check(gif, "animation encode: " .. tostring(err)) + local back = decode(gif) + t:check(back.frames and #back.frames == 3, "animation frames") + t:eq(back.loops, 4, "loops") + t:eq(back.meta.text.comment, "hello gif", "comment") + for i, f in anim.frames :: { Types.Frame } do + local g = back.frames[i] + t:check(g.x == f.x and g.y == f.y and g.image.width == f.image.width and g.image.height == f.image.height, "frame rectangle " .. i) + t:eq(g.delay, f.delay, "frame delay " .. i) + t:eq(g.dispose, f.dispose, "frame dispose " .. i) + end + t:check(same(back.frames[1].image.pixels, anim.frames[1].image.pixels), "frame 1 lossless") + t:check(same(back.frames[2].image.pixels, anim.frames[2].image.pixels), "frame 2 lossless (transparency)") + t:eq(back.frames[2].blend, "over", "frame 2 blend") + t:check(psnr(back.frames[3].image.pixels, anim.frames[3].image.pixels) > 25, "frame 3 quantized") + t:eq(back.meta.source.localPalettes, if global then 0 else 3, "palettes") + end + -- deterministic output + t:eq(Crc32.of(Gif.encode(photo, { dither = true }) :: buffer), Crc32.of(Gif.encode(photo, { dither = true }) :: buffer), "deterministic") + -- bad arguments + local _, e = Gif.encode({} :: any) + t:check(e and e.code == Err.ARG, "encode of a non-image") + local _, e2 = Gif.encode(photo, { maxColors = 1 }) + t:check(e2 and e2.code == Err.ARG, "maxColors = 1") + local _, e3 = Gif.encode(photo, { method = "kmeans" } :: any) + t:check(e3 and e3.code == Err.ARG, "unknown method") + local _, e4 = Gif.encode(Types.Image.new(70000, 1)) + t:check(e4 and e4.code == Err.ARG, "too wide") +end + +-- fuzz +do + local samples = {} + for _, c in Fx do + if #c.data < 40000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + return Gif.decode(Bytes.reader(b)) + end, samples, { mutations = 12, keepHeader = 6 }) + t:fuzz("decode (header too)", function(b: buffer) + return Gif.decode(Bytes.reader(b), { maxPixels = 1e6 }) + end, samples, { mutations = 4, garbage = 50 }) +end + +t:done() diff --git a/tools/fixtures/gif.py b/tools/fixtures/gif.py new file mode 100644 index 0000000..257fb21 --- /dev/null +++ b/tools/fixtures/gif.py @@ -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()})