imgA: merge ws/imgA-gif (image/gif + codecs/Quantize)

This commit is contained in:
4DBug committed 2026-10-31 08:44:55 -05:00
commit 5c0d77b4fe
9 files changed
+1629

No files matched your search

+12
View File
@@ -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 = "jpeg",
category = "image",
+483
View File
@@ -0,0 +1,483 @@
--!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 } } = {}
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
local function scored(lo: number, hi: number): { number }
local c, range, n = stats({ lo, hi })
return { lo, hi, c, if hi > lo then range * math.sqrt(n) else 0 }
end
boxes[1] = scored(1, #bins)
while #boxes < maxColors do
-- split the box with the largest range * sqrt(count) score (ties: the first)
local pick, pickScore = 0, 0
for i, box in boxes do
if box[4] > pickScore then
pick, pickScore = i, box[4]
end
end
if pick == 0 then
break
end
local box = boxes[pick]
local lo, hi, c = box[1], box[2], box[3]
-- sort the range by the channel, ties by bin number: unique numeric keys, no comparator
local keys = table.create(hi - lo + 1)
for i = lo, hi do
keys[i - lo + 1] = channel(bins[i], c) * BINS + bins[i]
end
table.sort(keys)
local total = 0
for i = 1, #keys do
local bin = keys[i] % BINS
bins[lo + i - 1] = bin
total += readu32(cnt, bin * 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] = scored(lo, cut)
table.insert(boxes, scored(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
-- sorted by green (the heaviest weight), so the search can stop once 4 * dg^2 alone is worse than the best
do
local order = table.create(np)
for k = 1, np do
order[k] = pg[k] * 65536 + k
end
table.sort(order)
local r2, g2, b2, i2 = table.create(np), table.create(np), table.create(np), table.create(np)
for k = 1, np do
local j = order[k] % 65536
r2[k], g2[k], b2[k], i2[k] = pr[j], pg[j], pb[j], pi[j]
end
pr, pg, pb, pi = r2, g2, b2, i2
end
local startAt = table.create(256, np) -- the first entry with green >= g (1-based), np + 1 past the end
do
local k = 1
for g = 0, 255 do
while k <= np and pg[k] < g do
k += 1
end
startAt[g + 1] = k
end
end
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
local up = startAt[math.clamp(g, 0, 255) + 1]
local down = up - 1
while up <= np or down >= 1 do
if up <= np then
local dg = pg[up] - g
if dg * dg * 4 >= bd then
up = np + 1
else
local dr, db = r - pr[up], b - pb[up]
local d = dr * dr * 2 + dg * dg * 4 + db * db * 3
if d < bd then
best, bd = up, d
end
up += 1
end
end
if down >= 1 then
local dg = g - pg[down]
if dg * dg * 4 >= bd then
down = 0
else
local dr, db = r - pr[down], b - pb[down]
local d = dr * dr * 2 + dg * dg * 4 + db * db * 3
if d < bd then
best, bd = down, d
end
down -= 1
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
+68
View File
@@ -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
+534
View File
@@ -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