--!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