absorb: apng decode (acTL/fcTL/fdAT -> img.frames, loops, hidden default image, sequence/rect/limit checks), Png.composite (dispose/blend, byte-exact with ffmpeg), APNG encoder from img.frames; tests vs ffmpeg + hand-made APNGs

This commit is contained in:
4DBug committed 2026-10-31 08:28:47 -05:00
1 parent cdcb5b0b77
commit e26de7cda8
6 files changed
+815 -54

No files matched your search

+1 -1
View File
@@ -21,7 +21,7 @@ local list: { Entry } = {
extensions = { "png", "apng" },
mime = { "image/png", "image/apng" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/Deflate", "Types" },
caps = { decode = true, encode = true, animation = false, alpha = true, depths = { 1, 2, 4, 8, 16 } },
caps = { decode = true, encode = true, animation = true, alpha = true, depths = { 1, 2, 4, 8, 16 } },
load = function()
return require("@formats/image/png")
end,
+82
View File
@@ -0,0 +1,82 @@
--!strict
--!native
--!optimize 2
-- image/png/Apng: APNG frame compositing (APNG spec 1.0: dispose_op none / background / previous, blend_op source /
-- over) onto full rgba8 canvases. The "over" blend uses the same integer arithmetic as ffmpeg's pngdec.c, so the
-- canvases match ffmpeg byte for byte. Nothing here throws: the caller (init) validated every frame rectangle.
local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32
local bcreate, bcopy, bfill = buffer.create, buffer.copy, buffer.fill
local Apng = {}
local function div255(x: number): number
return (x + 128) * 257 // 65536
end
-- blend(canvas, cw, src, fw, fh, fx, fy, over): draw an rgba8 rectangle onto the canvas
local function blend(canvas: buffer, cw: number, src: buffer, fw: number, fh: number, fx: number, fy: number, over: boolean)
for y = 0, fh - 1 do
local so = y * fw * 4
local co = ((fy + y) * cw + fx) * 4
if not over then
bcopy(canvas, co, src, so, fw * 4)
else
for x = 0, fw - 1 do
local s, c = so + x * 4, co + x * 4
local fa = readu8(src, s + 3)
if fa == 255 then
writeu32(canvas, c, readu32(src, s))
elseif fa ~= 0 then
local ba = readu8(canvas, c + 3)
local oa = fa + div255((255 - fa) * ba)
if ba == 255 then
for k = 0, 2 do
writeu8(canvas, c + k, div255(fa * readu8(src, s + k) + (255 - fa) * readu8(canvas, c + k)))
end
else
local den = 255 * oa
for k = 0, 2 do
writeu8(canvas, c + k, (255 * fa * readu8(src, s + k) + (255 - fa) * ba * readu8(canvas, c + k)) // den)
end
end
writeu8(canvas, c + 3, oa)
end
end
end
end
end
-- composite(w, h, frames) -> { buffer }: the full canvas after each frame (frames: { image, x, y, dispose, blend })
function Apng.composite(w: number, h: number, frames: { any }): { buffer }
local canvas = bcreate(w * h * 4)
local saved = bcreate(w * h * 4)
local out: { buffer } = {}
for i, f in frames do
local fi = f.image
local fw, fh = fi.width, fi.height
local dispose, over = f.dispose, f.blend == "over"
if i == 1 then
over = false -- the canvas starts transparent black: source and over differ only in hidden colour
if dispose == "previous" then
dispose = "background"
end
end
if dispose == "previous" then
bcopy(saved, 0, canvas, 0)
end
blend(canvas, w, fi.pixels, fw, fh, f.x, f.y, over)
local snap = bcreate(w * h * 4)
bcopy(snap, 0, canvas, 0)
out[i] = snap
if dispose == "background" then
for y = 0, fh - 1 do
bfill(canvas, ((f.y + y) * w + f.x) * 4, 0, fw * 4)
end
elseif dispose == "previous" then
bcopy(canvas, 0, saved, 0)
end
end
return out
end
return Apng
+340 -52
View File
@@ -3,7 +3,11 @@
-- Supports: decode of every colour type (grey, RGB, palette, grey + alpha, RGBA) at every bit depth (1, 2, 4, 8, 16),
-- PLTE / tRNS transparency, the five filters, Adam7, tEXt; encode of rgba8 to RGBA / RGB / grey / grey + alpha
-- (chosen automatically) with adaptive filters. Decodes to rgba8 (16-bit samples keep their high byte).
-- Not supported: APNG animation (the default image is decoded), colour management (gAMA / cHRM / sRGB / iCCP are
-- APNG (APNG 1.0): acTL / fcTL / fdAT decode to img.frames (each frame its own rectangle, delay in seconds, dispose /
-- blend ops), img.loops = num_plays; img.pixels stays the default image (meta.apngDefaultHidden when the IDAT is not
-- part of the animation). Png.composite(img) draws the frames onto full canvases (byte-exact with ffmpeg). Encode
-- writes an APNG when img.frames is a non-empty list (or opts.apng). Sequence numbers and frame rectangles are checked.
-- Not supported: colour management (gAMA / cHRM / sRGB / iCCP are
-- ignored; iCCP is kept raw-compressed in meta.iccCompressed), palette / 16-bit / interlaced output.
-- ------------------------------------------------------------------------------------------------ requires
@@ -14,6 +18,7 @@ local Deflate = require("@formats/codecs/Deflate")
local Types = require("@formats/Types")
local Decode = require("@formats/image/png/Decode")
local Encode = require("@formats/image/png/Encode")
local Apng = require("@formats/image/png/Apng")
-- ------------------------------------------------------------------------------------------------ contract
local Png = {
@@ -22,7 +27,7 @@ local Png = {
extensions = { "png", "apng" },
mime = { "image/png", "image/apng" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/Deflate", "Types" },
caps = { decode = true, encode = true, animation = false, alpha = true, depths = { 1, 2, 4, 8, 16 } },
caps = { decode = true, encode = true, animation = true, alpha = true, depths = { 1, 2, 4, 8, 16 } },
}
export type DecodeOptions = {
@@ -32,6 +37,8 @@ export type DecodeOptions = {
export type EncodeOptions = {
level: number?, -- deflate level 0..9 (default 6)
colorType: ("auto" | "rgba" | "rgb" | "gray" | "graya")?, -- default "auto": the smallest lossless one
apng: boolean?, -- true: an APNG even without img.frames (one frame); false: a still PNG; default: APNG when
-- img.frames is a non-empty list
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -95,6 +102,66 @@ function Png.info(r: Bytes.Reader): (Header?, Err.Err?)
return header(r)
end
type FrameControl = {
width: number,
height: number,
x: number,
y: number,
num: number,
den: number,
dispose: number,
blend: number,
chunks: { { number } }, -- fdAT payloads: offset, length
len: number,
}
local DISPOSE: { [number]: "none" | "background" | "previous" } = { [0] = "none", [1] = "background", [2] = "previous" }
-- pixels(b, chunks, total, w, h, depth, ct, interlace, pal, tr, out) -> nil | Err: inflate the zlib stream split
-- over chunks ({ offset, length } in b), unfilter and expand it to rgba8 in out (w x h)
local function pixels(b: buffer, chunks: { { number } }, total: number, w: number, ht: number, depth: number, ct: number, interlace: number, pal: buffer, tr: number, out: buffer): Err.Err?
-- the inflated size: every (pass) row has a filter byte
local channels = Decode.CHANNELS[ct]
local expected = 0
if interlace == 0 then
expected = ht * (Decode.rowBytes(w, channels, depth) + 1)
else
for _, pass in Decode.PASSES do
local x0, y0, dx, dy = pass[1], pass[2], pass[3], pass[4]
local pw = if w > x0 then (w - x0 + dx - 1) // dx else 0
local ph = if ht > y0 then (ht - y0 + dy - 1) // dy else 0
if pw > 0 and ph > 0 then
expected += ph * (Decode.rowBytes(pw, channels, depth) + 1)
end
end
end
local z: buffer
if #chunks == 1 then
z = b
else
z = buffer.create(total)
local w0 = 0
for _, c in chunks do
buffer.copy(z, w0, b, c[1], c[2])
w0 += c[2]
end
end
local zo = if #chunks == 1 then chunks[1][1] else 0
local raw, zerr = Deflate.zlib(z, zo, total, expected)
if not raw then
-- some encoders leave extra bytes after the rows: inflate without the exact size, keep the rows
local loose = Deflate.zlib(z, zo, total)
if not loose or buffer.len(loose) < expected then
return zerr or Err.new(Err.CORRUPT, "bad image data")
end
raw = loose
end
local ok, derr = Decode.run(raw :: buffer, w, ht, depth, ct, interlace, pal, tr, out)
if not ok then
return Err.new(Err.CORRUPT, tostring(derr))
end
return nil
end
function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local checkCrc = opts and opts.checkCrc or false
local maxPixels = opts and opts.maxPixels or 2 ^ 26
@@ -118,6 +185,12 @@ function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
local idatLen = 0
local text: { [string]: string } = {}
local iccCompressed: buffer? = nil
-- APNG: acTL, then fcTL (+ IDAT for frame 1 when it is the default image) / fdAT, one sequence counter
local plays: number? = nil
local fctls: { FrameControl } = {}
local seq = 0
local idatInAnim = false
local animPixels = 0
local p = r.base + 8
local first = true
while p + 12 <= n do
@@ -162,6 +235,9 @@ function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
elseif typ == "IDAT" then
table.insert(idat, { d, len })
idatLen += len
if #fctls == 1 and #idat == 1 then
idatInAnim = true
end
elseif typ == "tEXt" then
local s = buffer.readstring(b, d, len)
local z = string.find(s, "\0", 1, true)
@@ -172,6 +248,58 @@ function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
local cb = buffer.create(len)
buffer.copy(cb, 0, b, d, len)
iccCompressed = cb
elseif typ == "acTL" then
if len >= 8 and plays == nil and #idat == 0 then
plays = be32(b, d + 4)
end
elseif typ == "fcTL" and plays ~= nil then
if len < 26 then
return nil, Err.new(Err.CORRUPT, "short fcTL", p)
end
if be32(b, d) ~= seq then
return nil, Err.new(Err.CORRUPT, string.format("fcTL sequence %d, expected %d", be32(b, d), seq), p)
end
seq += 1
local f: FrameControl = {
width = be32(b, d + 4),
height = be32(b, d + 8),
x = be32(b, d + 12),
y = be32(b, d + 16),
num = readu8(b, d + 20) * 256 + readu8(b, d + 21),
den = readu8(b, d + 22) * 256 + readu8(b, d + 23),
dispose = readu8(b, d + 24),
blend = readu8(b, d + 25),
chunks = {},
len = 0,
}
if f.width == 0 or f.height == 0 or f.x + f.width > w or f.y + f.height > ht then
return nil, Err.new(Err.CORRUPT, "fcTL frame outside the image", p)
end
if f.dispose > 2 or f.blend > 1 then
return nil, Err.new(Err.CORRUPT, "bad fcTL dispose / blend op", p)
end
if #idat == 0 and (f.width ~= w or f.height ~= ht or f.x ~= 0 or f.y ~= 0) then
return nil, Err.new(Err.CORRUPT, "the fcTL before IDAT must cover the image", p)
end
animPixels += f.width * f.height
if animPixels > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("the animation frames are over the %d pixel limit", maxPixels))
end
table.insert(fctls, f)
elseif typ == "fdAT" and plays ~= nil then
if len < 4 then
return nil, Err.new(Err.CORRUPT, "short fdAT", p)
end
if be32(b, d) ~= seq then
return nil, Err.new(Err.CORRUPT, string.format("fdAT sequence %d, expected %d", be32(b, d), seq), p)
end
seq += 1
local f = fctls[#fctls]
if not f or (#fctls == 1 and idatInAnim) then
return nil, Err.new(Err.CORRUPT, "fdAT without its fcTL", p)
end
table.insert(f.chunks, { d + 4, len - 4 })
f.len += len - 4
elseif typ == "IEND" then
break -- a missing IEND is tolerated (truncated tail after the data)
elseif bit32.band(readu8(b, p + 4), 0x20) == 0 and typ ~= "IHDR" then
@@ -185,46 +313,45 @@ function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
if ct == 3 and palCount == 0 then
return nil, Err.new(Err.CORRUPT, "palette image without PLTE")
end
-- the inflated size: every (pass) row has a filter byte
local channels = Decode.CHANNELS[ct]
local expected = 0
if h.interlace == 0 then
expected = ht * (Decode.rowBytes(w, channels, depth) + 1)
else
for _, pass in Decode.PASSES do
local x0, y0, dx, dy = pass[1], pass[2], pass[3], pass[4]
local pw = if w > x0 then (w - x0 + dx - 1) // dx else 0
local ph = if ht > y0 then (ht - y0 + dy - 1) // dy else 0
if pw > 0 and ph > 0 then
expected += ph * (Decode.rowBytes(pw, channels, depth) + 1)
end
end
end
local z: buffer
if #idat == 1 then
z = b
else
z = buffer.create(idatLen)
local w0 = 0
for _, c in idat do
buffer.copy(z, w0, b, c[1], c[2])
w0 += c[2]
end
end
local zo, zl = if #idat == 1 then idat[1][1] else 0, idatLen
local raw, zerr = Deflate.zlib(z, zo, zl, expected)
if not raw then
-- some encoders leave extra bytes after the rows: inflate without the exact size, keep the rows
local loose = Deflate.zlib(z, zo, zl)
if not loose or buffer.len(loose) < expected then
return nil, zerr
end
raw = loose
end
local img = Types.Image.new(w, ht, "rgba8")
local ok, derr = Decode.run(raw :: buffer, w, ht, depth, ct, h.interlace, pal, tr, img.pixels)
if not ok then
return nil, Err.new(Err.CORRUPT, tostring(derr))
local ierr = pixels(b, idat, idatLen, w, ht, h.bitDepth, ct, h.interlace, pal, tr, img.pixels)
if ierr then
return nil, ierr
end
if plays ~= nil and #fctls > 0 then
local last = fctls[#fctls]
if #fctls > 1 and #last.chunks == 0 then
fctls[#fctls] = nil -- a truncated file: the last frame never got its data
end
local frames: { Types.Frame } = {}
for i, f in fctls do
local fimg: Types.Image
if i == 1 and idatInAnim then
fimg = Types.Image.new(w, ht, "rgba8")
buffer.copy(fimg.pixels, 0, img.pixels)
else
if #f.chunks == 0 then
return nil, Err.new(Err.CORRUPT, "APNG frame " .. i .. " has no data")
end
fimg = Types.Image.new(f.width, f.height, "rgba8")
local ferr = pixels(b, f.chunks, f.len, f.width, f.height, h.bitDepth, ct, h.interlace, pal, tr, fimg.pixels)
if ferr then
ferr.message = "frame " .. i .. ": " .. ferr.message
return nil, ferr
end
end
frames[i] = {
image = fimg,
delay = f.num / (if f.den == 0 then 100 else f.den),
x = f.x,
y = f.y,
dispose = DISPOSE[f.dispose] :: any,
blend = if f.blend == 1 then "over" :: "over" else "source" :: "source",
}
end
img.frames = frames
img.loops = plays
img.meta.apngDefaultHidden = not idatInAnim
end
if ct == 3 then
local palette: { { number } } = {}
@@ -243,37 +370,131 @@ end
-- ------------------------------------------------------------------------------------------------ encode
local CT_CODES = { gray = 0, rgb = 2, graya = 4, rgba = 6 }
local DISPOSE_CODES: { [string]: number } = { none = 0, background = 1, previous = 2 }
local BLEND_CODES: { [string]: number } = { source = 0, over = 1 }
-- a frame delay in seconds -> num, den (u16 each): the smallest exact denominator, else milliseconds
local function delayFraction(delay: number): (number, number)
for den = 1, 1000 do
local num = math.floor(delay * den + 0.5)
if num > 65535 then
break
end
if math.abs(num / den - delay) < 1e-9 then
return num, den
end
end
if delay * 1000 <= 65535 then
return math.floor(delay * 1000 + 0.5), 1000
elseif delay * 100 <= 65535 then
return math.floor(delay * 100 + 0.5), 100
end
return math.min(65535, math.floor(delay + 0.5)), 1
end
local function validImage(im: any): boolean
return type(im) == "table"
and im.format == "rgba8"
and type(im.pixels) == "buffer"
and type(im.width) == "number"
and type(im.height) == "number"
and im.width >= 1
and im.height >= 1
and im.width % 1 == 0
and im.height % 1 == 0
and buffer.len(im.pixels) >= im.width * im.height * 4
end
-- the frames to write as an APNG (nil for a plain PNG), or nil, Err for a bad frame list
local function animationFrames(img: Types.Image, opts: EncodeOptions?): ({ Types.Frame }?, Err.Err?)
local frames = img.frames
local mode = if opts then opts.apng else nil
if mode == false then
return nil, nil
end
if frames ~= nil and type(frames) ~= "table" then
return nil, Err.new(Err.ARG, "png encode: frames must be a list")
end
if frames == nil or #frames == 0 then
if mode then
return { { image = img, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } :: any }, nil
end
return nil, nil
end
for i, f in frames do
local label = "png encode: frame " .. i
if type(f) ~= "table" or not validImage(f.image) then
return nil, Err.new(Err.ARG, label .. ": 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 % 1 ~= 0 or y % 1 ~= 0 or x + f.image.width > img.width or y + f.image.height > img.height then
return nil, Err.new(Err.ARG, label .. ": rectangle outside the image")
end
if f.delay ~= nil and (type(f.delay) ~= "number" or not (f.delay >= 0)) then
return nil, Err.new(Err.ARG, label .. ": bad delay")
end
if f.dispose ~= nil and DISPOSE_CODES[f.dispose] == nil then
return nil, Err.new(Err.ARG, label .. ": bad dispose " .. tostring(f.dispose))
end
if f.blend ~= nil and BLEND_CODES[f.blend] == nil then
return nil, Err.new(Err.ARG, label .. ": bad blend " .. tostring(f.blend))
end
end
return frames, nil
end
function Png.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then
if not validImage(img) then
return nil, Err.new(Err.ARG, "png encode: needs an rgba8 Image")
end
local w, h = img.width, img.height
if w < 1 or h < 1 or buffer.len(img.pixels) < w * h * 4 then
return nil, Err.new(Err.ARG, "png encode: bad image size or pixel buffer")
end
local level = opts and opts.level or 6
if type(level) ~= "number" or level < 0 or level > 9 then
return nil, Err.new(Err.ARG, "png encode: level must be 0..9")
end
local frames, ferr = animationFrames(img, opts)
if ferr then
return nil, ferr
end
local loops = img.loops or 0
if frames and (type(loops) ~= "number" or loops < 0 or loops > 4294967295 or loops % 1 ~= 0) then
return nil, Err.new(Err.ARG, "png encode: loops must be an integer 0..2^32-1")
end
local want = opts and opts.colorType or "auto"
local ctName: string = want
if want == "auto" then
ctName = Encode.pickColorType(img.pixels, w, h)
-- the smallest colour type that holds the image and every frame
local alpha, color = false, false
local function scan(im: Types.Image)
local c = Encode.pickColorType(im.pixels, im.width, im.height)
alpha = alpha or c == "rgba" or c == "graya"
color = color or c == "rgba" or c == "rgb"
end
scan(img)
if frames then
for _, f in frames do
scan(f.image)
end
end
ctName = if color then (if alpha then "rgba" else "rgb") else (if alpha then "graya" else "gray")
end
local ct = CT_CODES[ctName]
if ct == nil then
return nil, Err.new(Err.ARG, "png encode: unknown colorType " .. tostring(want))
end
local raw = Encode.filter(img.pixels, w, h, ct)
local z = Deflate.zlibCompress(raw, { level = level }) :: buffer
local function zdata(im: Types.Image): buffer
return Deflate.zlibCompress(Encode.filter(im.pixels, im.width, im.height, ct), { level = level }) :: buffer
end
local out = Bytes.writer(buffer.len(z) + 128)
local function chunk(typ: string, data: buffer?)
local len = if data then buffer.len(data) else 0
local out = Bytes.writer(w * h + 128)
local function chunk(typ: string, data: buffer?, prefix: number?)
local len = (if data then buffer.len(data) else 0) + (if prefix then 4 else 0)
out:u32be(len)
local start = out:tell()
out:string(typ)
if prefix then
out:u32be(prefix)
end
if data then
out:bytes(data)
end
@@ -289,6 +510,12 @@ function Png.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
ihdr:u8(0)
ihdr:u8(0)
chunk("IHDR", ihdr:finish())
if frames then
local actl = Bytes.writer(8)
actl:u32be(#frames)
actl:u32be(loops)
chunk("acTL", actl:finish())
end
if img.meta and img.meta.text then
for k, v in img.meta.text do
local t = Bytes.writer()
@@ -298,9 +525,70 @@ function Png.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
chunk("tEXt", t:finish())
end
end
chunk("IDAT", z)
if not frames then
chunk("IDAT", zdata(img))
chunk("IEND", nil)
return out:finish(), nil
end
-- frame 1 is the default image when it covers the canvas with the same pixels; otherwise the default image is
-- written first, outside the animation
local f1 = frames[1]
local f1i = f1.image
local inAnim = f1i == img
or ((f1.x or 0) == 0 and (f1.y or 0) == 0 and f1i.width == w and f1i.height == h and buffer.len(f1i.pixels) >= w * h * 4 and buffer.readstring(f1i.pixels, 0, w * h * 4) == buffer.readstring(img.pixels, 0, w * h * 4))
local seq = 0
if not inAnim then
chunk("IDAT", zdata(img))
end
for i, f in frames do
local fi = f.image
local num, den = delayFraction(f.delay or 0)
local fc = Bytes.writer(26)
fc:u32be(seq)
fc:u32be(fi.width)
fc:u32be(fi.height)
fc:u32be(f.x or 0)
fc:u32be(f.y or 0)
fc:u16be(num)
fc:u16be(den)
fc:u8(DISPOSE_CODES[f.dispose or "none"])
fc:u8(BLEND_CODES[f.blend or "source"])
chunk("fcTL", fc:finish())
seq += 1
if i == 1 and inAnim then
chunk("IDAT", zdata(img))
else
chunk("fdAT", zdata(fi), seq)
seq += 1
end
end
chunk("IEND", nil)
return out:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ extras
-- composite(img) -> { Image } | nil, Err: every APNG frame drawn onto a full canvas (dispose / blend applied, as a
-- player shows them; byte-exact with ffmpeg). A still image gives { a copy of img }.
function Png.composite(img: Types.Image): ({ Types.Image }?, Err.Err?)
if not validImage(img) then
return nil, Err.new(Err.ARG, "composite: needs an rgba8 Image")
end
local frames, ferr = animationFrames(img, { apng = true })
if not frames then
return nil, ferr
end
local w, h = img.width, img.height
local list = {}
for i, f in frames do
list[i] = { image = f.image, x = f.x or 0, y = f.y or 0, dispose = f.dispose or "none", blend = f.blend or "source" }
end
local out = {}
for i, b in Apng.composite(w, h, list) do
local im = Types.Image.new(w, h, "rgba8")
im.pixels = b
out[i] = im
end
return out, nil
end
return Png