imgA-gif: image/gif (read + write, animation, transparency, loops, comments) and codecs/Quantize (median cut, octree, Floyd-Steinberg); ImageMagick / Pillow fixtures

This commit is contained in:
4DBug committed 2026-10-31 08:34:32 -05:00
1 parent ba91879bc5
commit 603689bc14
8 files changed
+1549

No files matched your search

+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