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
@@ -5,7 +5,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| Category | Format | Extensions | Read | Write | Capabilities | Test |
|---|---|---|---|---|---|---|
| image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` |
| image | png | .png .apng | yes | yes | animation: true, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` |
Codecs (layer 1, shared by formats; not loadable on their own):
+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
+171
View File
@@ -0,0 +1,171 @@
-- image/png APNG tests: animated PNGs from ffmpeg's encoder and hand-written ones (every dispose / blend op, sub-rects,
-- palette + tRNS, grey, RGB, a hidden default image) decoded into frames and composited, compared with ffmpeg's
-- composited canvases (CRC-32); the APNG encoder's round trips; bad sequence numbers / rectangles; the fuzz pass.
-- Fixtures: tools/fixtures/apng.py.
local T = require("@tests/T")
local Png = require("@formats/image/png")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Cases = require("@tests/gen/apng_cases")
local t = T.suite("apng")
t:check(Png.caps.animation == true, "caps.animation")
local function decode(data: any, opts: any?): (any, any)
local b = if type(data) == "string" then buffer.fromstring(data) else data
return Png.decode(Bytes.reader(b), opts)
end
local DISPOSE = { [0] = "none", [1] = "background", [2] = "previous" }
local function canvasCrc(b: buffer, opaque: boolean): number
if opaque then
local c = buffer.create(buffer.len(b))
buffer.copy(c, 0, b)
for i = 3, buffer.len(c) - 1, 4 do
buffer.writeu8(c, i, 255)
end
b = c
end
return Crc32.of(b)
end
local function same(a: Types.Image, b: Types.Image): boolean
return a.width == b.width and a.height == b.height and buffer.tostring(a.pixels) == buffer.tostring(b.pixels)
end
for _, c in Cases do
local img, err = decode(c.data, { checkCrc = true })
t:check(img, c.name .. ": " .. tostring(err))
t:eq(img.width, c.width, c.name .. ": width")
t:check(img.frames ~= nil, c.name .. ": frames")
t:eq(#img.frames, #c.crcs, c.name .. ": frame count")
t:eq(img.loops, c.plays, c.name .. ": loops")
if c.frames then
for i, e in c.frames do
local f = img.frames[i]
t:check(f.x == e.x and f.y == e.y and f.image.width == e.w and f.image.height == e.h, c.name .. ": frame " .. i .. " rect")
t:check(math.abs(f.delay - e.num / (if e.den == 0 then 100 else e.den)) < 1e-12, c.name .. ": frame " .. i .. " delay")
t:eq(f.dispose, DISPOSE[e.dispose], c.name .. ": frame " .. i .. " dispose")
t:eq(f.blend, if e.blend == 1 then "over" else "source", c.name .. ": frame " .. i .. " blend")
end
end
if c.defaultCrc then
t:eq(Crc32.of(img.pixels), c.defaultCrc, c.name .. ": hidden default image")
t:check(img.meta.apngDefaultHidden == true, c.name .. ": apngDefaultHidden")
else
t:check(img.meta.apngDefaultHidden == false, c.name .. ": default image is frame 1")
t:check(buffer.tostring(img.pixels) == buffer.tostring(img.frames[1].image.pixels), c.name .. ": pixels = frame 1")
end
local canv, cerr = Png.composite(img)
t:check(canv, c.name .. ": composite " .. tostring(cerr))
for i, want in c.crcs do
t:eq(canvasCrc(canv[i].pixels, c.opaque), want, c.name .. ": composited frame " .. i .. (if c.ffmpeg then " vs ffmpeg" else " vs reference"))
end
-- round trip through the encoder: the same frames, rectangles, ops, delays, loops and default image
local enc, eerr = Png.encode(img)
t:check(enc, c.name .. ": encode " .. tostring(eerr))
local back, berr = Png.decode(Bytes.reader(enc :: buffer), { checkCrc = true })
t:check(back, c.name .. ": decode our APNG " .. tostring(berr))
t:check(same(back, img), c.name .. ": round trip default image")
t:eq(back.loops, img.loops, c.name .. ": round trip loops")
t:eq(#back.frames, #img.frames, c.name .. ": round trip frame count")
t:eq(back.meta.apngDefaultHidden, img.meta.apngDefaultHidden, c.name .. ": round trip hidden default")
for i, f in img.frames do
local g = back.frames[i]
t:check(same(g.image, f.image) and g.x == f.x and g.y == f.y and g.dispose == f.dispose and g.blend == f.blend, c.name .. ": round trip frame " .. i)
t:check(math.abs(g.delay - f.delay) < 1e-9, c.name .. ": round trip delay " .. i)
end
end
t:note("%d APNGs match the reference canvases and round-trip", #Cases)
-- encoder: frames built here (sub-rects, delays in seconds), opts.apng, validation
do
local function solid(w: number, h: number, r: number, g: number, b: number, a: number): Types.Image
local im = Types.Image.new(w, h)
for i = 0, w * h - 1 do
buffer.writeu8(im.pixels, i * 4, r)
buffer.writeu8(im.pixels, i * 4 + 1, g)
buffer.writeu8(im.pixels, i * 4 + 2, b)
buffer.writeu8(im.pixels, i * 4 + 3, a)
end
return im
end
local base = solid(8, 6, 10, 20, 30, 255)
base.frames = {
{ image = base, delay = 0.1, x = 0, y = 0, dispose = "none", blend = "source" },
{ image = solid(3, 2, 200, 0, 0, 128), delay = 1 / 30, x = 5, y = 4, dispose = "background", blend = "over" },
{ image = solid(1, 1, 0, 255, 0, 255), delay = 70, x = 7, y = 0, dispose = "previous", blend = "source" },
}
base.loops = 5
local enc = Png.encode(base) :: buffer
local back = decode(enc)
t:check(back and #back.frames == 3 and back.loops == 5, "built APNG decodes")
t:check(math.abs(back.frames[2].delay - 1 / 30) < 1e-9 and back.frames[3].delay == 70 and back.frames[1].delay == 0.1, "delays")
t:eq(back.meta.source.colorType, "rgba", "colour type covers every frame (alpha in frame 2 only)")
local canv = Png.composite(back) :: { Types.Image }
-- frame 2 over: 128 alpha red over opaque (10, 20, 30)
local o = (4 * 8 + 5) * 4
t:eq(buffer.readu8(canv[2].pixels, o + 3), 255, "over: alpha")
t:eq(buffer.readu8(canv[2].pixels, o), (128 * 200 + 127 * 10 + 128) * 257 // 65536, "over: red")
t:eq(buffer.readu32(canv[3].pixels, o), 0, "background dispose cleared frame 2's rect")
-- one frame + opts.apng; a still image stays a PNG
local still = solid(4, 4, 1, 2, 3, 255)
local plain = decode(Png.encode(still) :: buffer)
t:check(plain.frames == nil, "still image: no acTL")
local one = decode(Png.encode(still, { apng = true }) :: buffer)
t:check(one.frames and #one.frames == 1 and same(one.frames[1].image, still), "opts.apng: a one-frame APNG")
-- bad frames
local function bad(frames: any, label: string)
local im = solid(4, 4, 0, 0, 0, 255)
im.frames = frames
local r, e = Png.encode(im)
t:check(r == nil and e and e.code == Err.ARG, label .. ": " .. tostring(e))
end
bad({ { image = still, x = 0, y = 0 }, { image = still, x = 1, y = 0 } }, "frame outside the canvas")
bad({ { image = still }, { image = {} } }, "frame without an image")
bad({ { image = still }, { image = still, dispose = "explode" } }, "bad dispose")
bad({ { image = still }, { image = still, blend = "add" } }, "bad blend")
bad({ { image = still }, { image = still, delay = -1 } }, "negative delay")
end
-- crafted bad input: a broken sequence number, a frame outside the canvas
do
local c = Cases[1]
local s = c.data
-- find the second fcTL and bump its sequence number (fix the CRC so checkCrc does not mask it)
local first = string.find(s, "fcTL", 1, true) :: number
local second = string.find(s, "fcTL", first + 4, true) :: number
local b = buffer.fromstring(s)
local d = second + 3 -- 0-based offset of the chunk data
buffer.writeu32(b, d, bit32.byteswap(bit32.byteswap(buffer.readu32(b, d)) + 1))
local _, e = Png.decode(Bytes.reader(b))
t:check(e and e.code == Err.CORRUPT, "bad sequence: " .. tostring(e))
local b2 = buffer.fromstring(s)
buffer.writeu32(b2, d + 12, bit32.byteswap(c.width)) -- x offset = the canvas width
local _, e2 = Png.decode(Bytes.reader(b2))
t:check(e2 and e2.code == Err.CORRUPT, "frame outside the canvas: " .. tostring(e2))
local _, e3 = decode(s, { maxPixels = c.width * c.height + 1 })
t:check(e3 and e3.code == Err.LIMIT, "maxPixels counts the frames: " .. tostring(e3))
t:check(Png.composite({} :: any) == nil, "composite of a non-image")
end
-- fuzz
do
local samples = {}
for _, c in Cases do
table.insert(samples, c.data)
end
t:fuzz("decode", function(b: buffer)
local img = Png.decode(Bytes.reader(b))
if img and img.frames then
Png.composite(img)
end
return img
end, samples, { mutations = 30, keepHeader = 8 })
end
t:done()
+220
View File
@@ -0,0 +1,220 @@
# APNG fixtures (tools/fixtures.py).
# tests/gen/apng_cases.luau animated PNGs with the reference composited canvases (CRC-32 of each full rgba8 frame)
# - made by ffmpeg's apng encoder (sub-rectangles, dispose / blend chosen by ffmpeg, -plays)
# - written here by hand: every dispose op (none / background / previous) and blend op (source / over) on
# sub-rectangles with partial alpha, a hidden default image (IDAT not part of the animation), palette + tRNS,
# grey, RGB, a first frame with dispose previous, split fdATs
# The reference canvases come from ffmpeg (`-f apng -i x -f rawvideo -pix_fmt rgba`); a small compositor here
# (the same integer blend as ffmpeg's pngdec.c) must agree with ffmpeg, so a broken reference is caught too.
# Files ffmpeg cannot represent (the hidden default image) use the compositor here alone.
import os, random, struct, subprocess, tempfile, zlib
def chunk(t, d):
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d))
CH = {0: 1, 2: 3, 3: 1, 6: 4}
def raw_rows(px, w, h, ct, rng):
"""px: list of h rows of w sample tuples -> filtered (random filter per row) scanlines"""
ch = CH[ct]
out = bytearray()
prev = None
for y in range(h):
row = bytes(s for p in px[y] for s in p)
ft = rng.randrange(5)
out.append(ft)
for i, x in enumerate(row):
a = row[i - ch] if i >= ch else 0
b = prev[i] if prev else 0
c = prev[i - ch] if prev and i >= ch else 0
if ft == 4:
p = a + b - c
pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
pred = a if pa <= pb and pa <= pc else (b if pb <= pc else c)
else:
pred = (0, a, b, (a + b) // 2)[ft]
out.append((x - pred) & 255)
prev = row
return bytes(out)
def to_rgba(ct, s, plte=None, trns=None):
if ct == 6:
return tuple(s)
if ct == 2:
return (s[0], s[1], s[2], 255)
if ct == 0:
return (s[0], s[0], s[0], 255)
c = plte[s[0]]
a = trns[s[0]] if trns and s[0] < len(trns) else 255
return (c[0], c[1], c[2], a)
def apng(w, h, ct, frames, plays=0, default=None, plte=None, trns=None, rng=None, split=1):
"""frames: list of dict(x, y, w, h, px, num, den, dispose, blend); default: px of a hidden default image"""
rng = rng or random.Random(1)
out = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, ct, 0, 0, 0))
out += chunk(b"acTL", struct.pack(">II", len(frames), plays))
if plte:
out += chunk(b"PLTE", b"".join(bytes(c) for c in plte))
if trns:
out += chunk(b"tRNS", bytes(trns))
seq = 0
if default is not None:
out += chunk(b"IDAT", zlib.compress(raw_rows(default, w, h, ct, rng)))
for i, f in enumerate(frames):
out += chunk(b"fcTL", struct.pack(">IIIIIHHBB", seq, f["w"], f["h"], f["x"], f["y"], f["num"], f["den"], f["dispose"], f["blend"]))
seq += 1
z = zlib.compress(raw_rows(f["px"], f["w"], f["h"], ct, rng))
step = max(1, -(-len(z) // split))
for k in range(0, len(z), step):
if i == 0 and default is None:
out += chunk(b"IDAT", z[k:k + step])
else:
out += chunk(b"fdAT", struct.pack(">I", seq) + z[k:k + step])
seq += 1
return out + chunk(b"IEND", b"")
def div255(x):
return ((x + 128) * 257) >> 16
def composite(w, h, ct, frames, plte=None, trns=None):
"""full rgba8 canvases (bytes), blending like ffmpeg's pngdec.c (APNG spec semantics)"""
canvas = [(0, 0, 0, 0)] * (w * h)
outs = []
for i, f in enumerate(frames):
dispose, blend = f["dispose"], f["blend"]
if i == 0:
blend = 0
if dispose == 2:
dispose = 1
saved = list(canvas)
for yy in range(f["h"]):
for xx in range(f["w"]):
src = to_rgba(ct, f["px"][yy][xx], plte, trns)
k = (f["y"] + yy) * w + f["x"] + xx
if blend == 0 or src[3] == 255:
canvas[k] = src
elif src[3] == 0:
pass
else:
fa, bg = src[3], canvas[k]
ba = bg[3]
oa = fa + div255((255 - fa) * ba)
if ba == 255:
canvas[k] = tuple(div255(fa * src[c] + (255 - fa) * bg[c]) for c in range(3)) + (oa,)
else:
canvas[k] = tuple((255 * fa * src[c] + (255 - fa) * ba * bg[c]) // (255 * oa) for c in range(3)) + (oa,)
outs.append(b"".join(bytes(p) for p in canvas))
if dispose == 1:
for yy in range(f["h"]):
for xx in range(f["w"]):
canvas[(f["y"] + yy) * w + f["x"] + xx] = (0, 0, 0, 0)
elif dispose == 2:
canvas = saved
return outs
def ffmpeg_frames(ctx, data, w, h):
with tempfile.TemporaryDirectory() as tmp:
p = os.path.join(tmp, "in.png")
with open(p, "wb") as f:
f.write(data)
raw = subprocess.run(["ffmpeg", "-v", "error", "-f", "apng", "-i", p, "-f", "rawvideo", "-pix_fmt", "rgba", "-fps_mode", "passthrough", "-"],
capture_output=True, check=True).stdout
n = w * h * 4
return [raw[i:i + n] for i in range(0, len(raw), n)]
def sprite(rng, w, h, ct, alpha=True, ncolors=None):
px = []
for y in range(h):
row = []
for x in range(w):
if ct == 3:
row.append((rng.randrange(ncolors),))
elif ct == 0:
row.append(((x * 17 + y * 5 + rng.randrange(8)) & 255,))
elif ct == 2:
row.append((rng.randrange(256), (x * 9) & 255, (y * 13) & 255))
else:
a = rng.choice((0, 255, 255, rng.randrange(256))) if alpha else 255
row.append((rng.randrange(256), (x * 9) & 255, (y * 13) & 255, a))
px.append(row)
return px
def frame(rng, ct, x, y, w, h, dispose, blend, num=1, den=10, **kw):
return {"x": x, "y": y, "w": w, "h": h, "px": sprite(rng, w, h, ct, **kw), "num": num, "den": den, "dispose": dispose, "blend": blend}
def generate(ctx):
rng = random.Random(77)
cases = []
def add(name, data, w, h, frames_meta, refs, default_crc=None, plays=0, ffmpeg=True, opaque=False):
c = {"name": name, "data": data, "width": w, "height": h, "plays": plays,
"frames": [{"x": f["x"], "y": f["y"], "w": f["w"], "h": f["h"], "num": f["num"], "den": f["den"], "dispose": f["dispose"], "blend": f["blend"]} for f in frames_meta],
"crcs": [zlib.crc32(r) for r in refs], "ffmpeg": ffmpeg, "opaque": opaque}
if default_crc is not None:
c["defaultCrc"] = default_crc
cases.append(c)
def hand(name, w, h, ct, frames, plays=0, plte=None, trns=None, split=1):
data = apng(w, h, ct, frames, plays=plays, plte=plte, trns=trns, rng=rng, split=split)
mine = composite(w, h, ct, frames, plte, trns)
ref = ffmpeg_frames(ctx, data, w, h)
if ct in (0, 2): # ffmpeg decodes to an opaque pixel format: disposed pixels come out opaque black
mine = [bytes(v if i % 4 != 3 else 255 for i, v in enumerate(m)) for m in mine]
if ref != mine:
for fi, (a, b) in enumerate(zip(ref, mine)):
if a != b:
k = next(j for j in range(len(a)) if a[j] != b[j])
print("apng fixture mismatch:", name, fi, k // 4 % w, k // 4 // w, a[k - k % 4:k - k % 4 + 4], b[k - k % 4:k - k % 4 + 4], frames[fi]["dispose"], frames[fi]["blend"], frames[fi - 1]["dispose"] if fi else None, sum(1 for j in range(0, len(a), 4) if a[j:j + 4] != b[j:j + 4]))
raise RuntimeError("apng fixture %s: ffmpeg and the reference compositor disagree (%d vs %d frames)" % (name, len(ref), len(mine)))
add(name, data, w, h, frames, ref, plays=plays, opaque=ct in (0, 2))
# every dispose x blend on sub-rectangles over a semi-transparent background
W, H = 20, 16
fr = [frame(rng, 6, 0, 0, W, H, 0, 0)]
for d in (0, 1, 2):
for b in (0, 1):
fr.append(frame(rng, 6, rng.randrange(8), rng.randrange(6), 1 + rng.randrange(12), 1 + rng.randrange(10), d, b, num=rng.randrange(1, 200), den=rng.choice((0, 100, 1000))))
fr.append(frame(rng, 6, 3, 2, 9, 7, 2, 1))
fr.append(frame(rng, 6, 0, 0, W, H, 0, 1))
hand("rgba-dispose-blend", W, H, 6, fr, plays=3, split=2)
# first frame dispose previous (= background), then over
hand("first-previous", 12, 9, 6, [frame(rng, 6, 0, 0, 12, 9, 2, 1), frame(rng, 6, 2, 2, 5, 4, 0, 1), frame(rng, 6, 0, 0, 3, 3, 1, 0)])
# palette + tRNS, over
pal = [(rng.randrange(256), rng.randrange(256), rng.randrange(256)) for _ in range(40)]
trns = [rng.choice((0, 128, 255, rng.randrange(256))) for _ in range(30)]
hand("palette-trns", 17, 13, 3, [frame(rng, 3, 0, 0, 17, 13, 1, 0, ncolors=40)] + [frame(rng, 3, rng.randrange(5), rng.randrange(5), 1 + rng.randrange(12), 1 + rng.randrange(8), rng.randrange(3), rng.randrange(2), ncolors=40) for _ in range(5)], plte=pal, trns=trns)
# grey and RGB (no alpha: over = source)
hand("gray", 15, 11, 0, [frame(rng, 0, 0, 0, 15, 11, 0, 0)] + [frame(rng, 0, rng.randrange(5), rng.randrange(5), 1 + rng.randrange(10), 1 + rng.randrange(6), rng.randrange(3), rng.randrange(2)) for _ in range(4)], plays=1)
hand("rgb", 15, 11, 2, [frame(rng, 2, 0, 0, 15, 11, 1, 0)] + [frame(rng, 2, rng.randrange(5), rng.randrange(5), 1 + rng.randrange(10), 1 + rng.randrange(6), rng.randrange(3), rng.randrange(2)) for _ in range(4)])
# a single-frame APNG
hand("one-frame", 7, 5, 6, [frame(rng, 6, 0, 0, 7, 5, 0, 0)])
# hidden default image (not part of the animation): ffmpeg's demuxer cannot express it, so the compositor here
dpx = sprite(rng, 10, 8, 6)
fr = [frame(rng, 6, 0, 0, 10, 8, 0, 0), frame(rng, 6, 2, 1, 4, 5, 1, 1), frame(rng, 6, 5, 3, 5, 5, 0, 1)]
data = apng(10, 8, 6, fr, default=dpx, rng=rng)
add("hidden-default", data, 10, 8, fr, composite(10, 8, 6, fr), default_crc=zlib.crc32(b"".join(bytes(p) for row in dpx for p in row)), ffmpeg=False)
# ffmpeg's own encoder (it picks sub-rectangles, dispose and blend ops)
for name, src, pix, plays in (
("ffmpeg-testsrc", "testsrc=size=40x30:rate=10", "rgb24", 0),
("ffmpeg-rgba", "testsrc2=size=36x28:rate=8,format=rgba,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='if(lt(mod(X+T*40,20),10),255,90)'", "rgba", 2),
):
data = subprocess.run(["ffmpeg", "-v", "error", "-f", "lavfi", "-i", src, "-frames:v", "7", "-pix_fmt", pix, "-plays", str(plays), "-f", "apng", "-"],
capture_output=True, check=True).stdout
w, h = struct.unpack(">II", data[16:24])
ref = ffmpeg_frames(ctx, data, w, h)
cases.append({"name": name, "data": data, "width": w, "height": h, "plays": plays, "crcs": [zlib.crc32(r) for r in ref], "ffmpeg": True, "opaque": pix == "rgb24"})
ctx.emit("apng_cases", cases)