rename: src/Formats -> src/Rosetta, @formats -> @rosetta requires, build/luajit/rosetta + rosetta._compat, build/roblox/Rosetta, ROSETTA_* env/globals, writer vendor strings

This commit is contained in:
4DBug committed 2026-11-01 01:19:16 -05:00
1 parent 2956576d7f
commit 22ddcd78fa
941 files changed
+3364 -3364

No files matched your search

+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
+253
View File
@@ -0,0 +1,253 @@
--!strict
--!native
--!optimize 2
-- image/png/Decode: the PNG pixel stage. Undo the per-row filters (none / sub / up / average / Paeth) in place in the
-- inflated image data, then expand every colour type and bit depth to RGBA8, for one image or the 7 Adam7 passes.
-- Absorbed from png-luau src/Png/Decode.luau (same author).
--
-- The caller (init) has validated the header and checked that the data holds at least the expected number of
-- bytes, so every index here is in range. A bad filter type returns false, message: nothing in this module throws.
local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift
local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32
local bcopy = buffer.copy
local Decode = {}
-- Adam7: x0, y0, dx, dy per pass
local PASSES = {
{ 0, 0, 8, 8 },
{ 4, 0, 8, 8 },
{ 0, 4, 4, 8 },
{ 2, 0, 4, 4 },
{ 0, 2, 2, 4 },
{ 1, 0, 2, 2 },
{ 0, 1, 1, 2 },
}
Decode.PASSES = PASSES
local CHANNELS = { [0] = 1, [2] = 3, [3] = 1, [4] = 2, [6] = 4 }
Decode.CHANNELS = CHANNELS
-- bytes per row (without the filter byte) for a pass width
function Decode.rowBytes(pw: number, channels: number, depth: number): number
return (pw * channels * depth + 7) // 8
end
-- Unfilter ph rows of rb bytes starting at raw[p] (each row: a filter byte, then rb bytes). bpp: bytes per
-- complete pixel (at least 1). Returns true, or false + the bad filter type.
local function unfilter(raw: buffer, p: number, ph: number, rb: number, bpp: number): (boolean, number)
local stride = rb + 1
for r = 0, ph - 1 do
local f = readu8(raw, p)
local cur = p + 1
if f == 0 then
-- none
elseif f == 1 then
for i = cur + bpp, cur + rb - 1 do
writeu8(raw, i, readu8(raw, i) + readu8(raw, i - bpp))
end
elseif f == 2 then
if r > 0 then
local i = cur
local e4 = cur + rb - 4
while i <= e4 do
-- four bytes at once: add without carries between the byte lanes
local x, y = readu32(raw, i), readu32(raw, i - stride)
local lo = band(x, 0x7F7F7F7F) + band(y, 0x7F7F7F7F)
writeu32(raw, i, bit32.bxor(lo, band(bit32.bxor(x, y), 0x80808080)))
i += 4
end
while i < cur + rb do
writeu8(raw, i, readu8(raw, i) + readu8(raw, i - stride))
i += 1
end
end
elseif f == 3 then
if r > 0 then
for i = cur, cur + bpp - 1 do
writeu8(raw, i, readu8(raw, i) + rshift(readu8(raw, i - stride), 1))
end
for i = cur + bpp, cur + rb - 1 do
writeu8(raw, i, readu8(raw, i) + rshift(readu8(raw, i - bpp) + readu8(raw, i - stride), 1))
end
else
for i = cur + bpp, cur + rb - 1 do
writeu8(raw, i, readu8(raw, i) + rshift(readu8(raw, i - bpp), 1))
end
end
elseif f == 4 then
if r > 0 then
-- the first pixel: a = c = 0, so Paeth picks b
for i = cur, cur + bpp - 1 do
writeu8(raw, i, readu8(raw, i) + readu8(raw, i - stride))
end
for i = cur + bpp, cur + rb - 1 do
local a = readu8(raw, i - bpp)
local b = readu8(raw, i - stride)
local c = readu8(raw, i - stride - bpp)
local pa = math.abs(b - c)
local pb = math.abs(a - c)
local pc = math.abs(a + b - c - c)
local v
if pa <= pb and pa <= pc then
v = a
elseif pb <= pc then
v = b
else
v = c
end
writeu8(raw, i, readu8(raw, i) + v)
end
else
-- no previous row: Paeth is sub
for i = cur + bpp, cur + rb - 1 do
writeu8(raw, i, readu8(raw, i) + readu8(raw, i - bpp))
end
end
else
return false, f
end
p += stride
end
return true, 0
end
-- Expand one unfiltered row (pw pixels at raw[ro]) to RGBA8 at out[oo], oo stepping by ostep bytes.
-- pal: 256 RGBA8 entries (index -> u32 little-endian RGBA). tr: the tRNS key for grey / RGB (-1 if none),
-- as a sample value (grey) or r * 2^32 + g * 2^16 + b (RGB), at the image's bit depth.
local function convert(raw: buffer, ro: number, pw: number, out: buffer, oo: number, ostep: number, ct: number, depth: number, pal: buffer, tr: number)
if ct == 6 then
if depth == 8 then
if ostep == 4 then
bcopy(out, oo, raw, ro, pw * 4)
else
for x = 0, pw - 1 do
writeu32(out, oo + x * ostep, readu32(raw, ro + x * 4))
end
end
else
for x = 0, pw - 1 do
local s = ro + x * 8
local o = oo + x * ostep
writeu8(out, o, readu8(raw, s))
writeu8(out, o + 1, readu8(raw, s + 2))
writeu8(out, o + 2, readu8(raw, s + 4))
writeu8(out, o + 3, readu8(raw, s + 6))
end
end
elseif ct == 2 then
if depth == 8 then
for x = 0, pw - 1 do
local s = ro + x * 3
local r, g, b = readu8(raw, s), readu8(raw, s + 1), readu8(raw, s + 2)
local a = 255
if tr >= 0 and r * 4294967296 + g * 65536 + b == tr then
a = 0
end
writeu32(out, oo + x * ostep, r + g * 256 + b * 65536 + a * 16777216)
end
else
for x = 0, pw - 1 do
local s = ro + x * 6
local r = readu8(raw, s) * 256 + readu8(raw, s + 1)
local g = readu8(raw, s + 2) * 256 + readu8(raw, s + 3)
local b = readu8(raw, s + 4) * 256 + readu8(raw, s + 5)
local a = 255
if tr >= 0 and r * 4294967296 + g * 65536 + b == tr then
a = 0
end
writeu32(out, oo + x * ostep, rshift(r, 8) + band(g, 0xFF00) + lshift(rshift(b, 8), 16) + a * 16777216)
end
end
elseif ct == 3 then
if depth == 8 then
for x = 0, pw - 1 do
writeu32(out, oo + x * ostep, readu32(pal, readu8(raw, ro + x) * 4))
end
else
local per = 8 // depth
local mask = lshift(1, depth) - 1
for x = 0, pw - 1 do
local byte = readu8(raw, ro + x // per)
local idx = band(rshift(byte, 8 - depth - (x % per) * depth), mask)
writeu32(out, oo + x * ostep, readu32(pal, idx * 4))
end
end
elseif ct == 0 then
if depth == 8 then
for x = 0, pw - 1 do
local v = readu8(raw, ro + x)
local a = if v == tr then 0 else 255
writeu32(out, oo + x * ostep, v * 0x10101 + a * 16777216)
end
elseif depth == 16 then
for x = 0, pw - 1 do
local hi = readu8(raw, ro + x * 2)
local v = hi * 256 + readu8(raw, ro + x * 2 + 1)
local a = if v == tr then 0 else 255
writeu32(out, oo + x * ostep, hi * 0x10101 + a * 16777216)
end
else
local per = 8 // depth
local mask = lshift(1, depth) - 1
local scale = 255 // mask
for x = 0, pw - 1 do
local byte = readu8(raw, ro + x // per)
local v = band(rshift(byte, 8 - depth - (x % per) * depth), mask)
local a = if v == tr then 0 else 255
writeu32(out, oo + x * ostep, v * scale * 0x10101 + a * 16777216)
end
end
else -- ct == 4: grey + alpha
if depth == 8 then
for x = 0, pw - 1 do
local v, a = readu8(raw, ro + x * 2), readu8(raw, ro + x * 2 + 1)
writeu32(out, oo + x * ostep, v * 0x10101 + a * 16777216)
end
else
for x = 0, pw - 1 do
local v, a = readu8(raw, ro + x * 4), readu8(raw, ro + x * 4 + 2)
writeu32(out, oo + x * ostep, v * 0x10101 + a * 16777216)
end
end
end
end
-- Decode the inflated data raw (at least the expected size) of a w x h image to out (w * h * 4 bytes, RGBA8).
-- Returns true, or false + message.
function Decode.run(raw: buffer, w: number, h: number, depth: number, ct: number, interlace: number, pal: buffer, tr: number, out: buffer): (boolean, string?)
local channels = CHANNELS[ct]
local bpp = math.max(1, (channels * depth) // 8)
local p = 0
if interlace == 0 then
local rb = Decode.rowBytes(w, channels, depth)
local ok, f = unfilter(raw, 0, h, rb, bpp)
if not ok then
return false, "bad filter type " .. f
end
for y = 0, h - 1 do
convert(raw, y * (rb + 1) + 1, w, out, y * w * 4, 4, ct, depth, pal, tr)
end
return true, nil
end
for _, pass in 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 h > y0 then (h - y0 + dy - 1) // dy else 0
if pw > 0 and ph > 0 then
local rb = Decode.rowBytes(pw, channels, depth)
local ok, f = unfilter(raw, p, ph, rb, bpp)
if not ok then
return false, "bad filter type " .. f
end
for r = 0, ph - 1 do
local y = y0 + r * dy
convert(raw, p + r * (rb + 1) + 1, pw, out, (y * w + x0) * 4, dx * 4, ct, depth, pal, tr)
end
p += ph * (rb + 1)
end
end
return true, nil
end
return Decode
+162
View File
@@ -0,0 +1,162 @@
--!strict
--!native
--!optimize 2
-- image/png/Encode: the PNG encoder's pixel stage. Picks the smallest lossless colour type for rgba8 pixels and
-- writes the filtered scanlines (a filter byte + the row), choosing each row's filter by the minimum sum of absolute
-- signed residuals (the libpng heuristic). Nothing here throws: the caller (init) validated the image.
local readu8, writeu8 = buffer.readu8, buffer.writeu8
local bcreate, bcopy = buffer.create, buffer.copy
local Encode = {}
local CHANNELS = { [0] = 1, [2] = 3, [4] = 2, [6] = 4 }
-- pickColorType(px, w, h) -> "rgba" | "rgb" | "graya" | "gray"
function Encode.pickColorType(px: buffer, w: number, h: number): string
local opaque, gray = true, true
for i = 0, w * h - 1 do
local o = i * 4
local r, g, b, a = readu8(px, o), readu8(px, o + 1), readu8(px, o + 2), readu8(px, o + 3)
if a ~= 255 then
opaque = false
end
if r ~= g or g ~= b then
gray = false
end
if not opaque and not gray then
return "rgba"
end
end
if gray then
return if opaque then "gray" else "graya"
end
return "rgb"
end
-- convert rgba8 to the colour type's packed rows (no filter bytes)
local function pack(px: buffer, w: number, h: number, ct: number): buffer
local ch = CHANNELS[ct]
if ch == 4 then
return px
end
local out = bcreate(w * h * ch)
local n = w * h
if ct == 2 then
for i = 0, n - 1 do
bcopy(out, i * 3, px, i * 4, 3)
end
elseif ct == 0 then
for i = 0, n - 1 do
writeu8(out, i, readu8(px, i * 4))
end
else -- graya
for i = 0, n - 1 do
writeu8(out, i * 2, readu8(px, i * 4))
writeu8(out, i * 2 + 1, readu8(px, i * 4 + 3))
end
end
return out
end
local function paeth(a: number, b: number, c: number): number
local pa = math.abs(b - c)
local pb = math.abs(a - c)
local pc = math.abs(a + b - c - c)
if pa <= pb and pa <= pc then
return a
elseif pb <= pc then
return b
end
return c
end
-- the five filter costs (sums of |signed residual|) of the row at s (rb bytes; previous row at s - rb unless first);
-- the arithmetic is inlined: this runs for every byte
local function costs(src: buffer, s: number, rb: number, bpp: number, first: boolean): (number, number, number, number, number)
local c0, c1, c2, c3, c4 = 0, 0, 0, 0, 0
local p = s - rb
for i = 0, rb - 1 do
local x = readu8(src, s + i)
local a = if i >= bpp then readu8(src, s + i - bpp) else 0
local b, c = 0, 0
if not first then
b = readu8(src, p + i)
if i >= bpp then
c = readu8(src, p + i - bpp)
end
end
local d = if x < 128 then x else 256 - x
c0 += d
d = (x - a) % 256
c1 += if d < 128 then d else 256 - d
d = (x - b) % 256
c2 += if d < 128 then d else 256 - d
d = (x - (a + b) // 2) % 256
c3 += if d < 128 then d else 256 - d
local pa, pb, pc = math.abs(b - c), math.abs(a - c), math.abs(a + b - c - c)
local pr = if pa <= pb and pa <= pc then a elseif pb <= pc then b else c
d = (x - pr) % 256
c4 += if d < 128 then d else 256 - d
end
return c0, c1, c2, c3, c4
end
-- write the row at s filtered with f to out[o + 1 ..] (out[o] = f)
local function apply(src: buffer, s: number, rb: number, bpp: number, first: boolean, f: number, out: buffer, o: number)
writeu8(out, o, f)
o += 1
if f == 0 or (f == 2 and first) then
bcopy(out, o, src, s, rb)
return
end
local p = s - rb
for i = 0, rb - 1 do
local x = readu8(src, s + i)
local a = if i >= bpp then readu8(src, s + i - bpp) else 0
local pred
if f == 1 then
pred = a
elseif f == 2 then
pred = readu8(src, p + i)
elseif f == 3 then
pred = (a + (if first then 0 else readu8(src, p + i))) // 2
elseif first then
pred = a
else
local c = if i >= bpp then readu8(src, p + i - bpp) else 0
pred = paeth(a, readu8(src, p + i), c)
end
writeu8(out, o + i, x - pred)
end
end
-- filter(px, w, h, ct) -> the filtered scanlines (h * (1 + rowBytes)); each row's filter: the minimum sum of
-- |signed residuals| (the libpng heuristic)
function Encode.filter(px: buffer, w: number, h: number, ct: number): buffer
local ch = CHANNELS[ct]
local src = pack(px, w, h, ct)
local rb = w * ch
local out = bcreate(h * (rb + 1))
for y = 0, h - 1 do
local s = y * rb
local first = y == 0
local c0, c1, c2, c3, c4 = costs(src, s, rb, ch, first)
local best, bc = 0, c0
if c1 < bc then
best, bc = 1, c1
end
if c2 < bc then
best, bc = 2, c2
end
if c3 < bc then
best, bc = 3, c3
end
if c4 < bc then
best = 4
end
apply(src, s, rb, ch, first, best, out, y * (rb + 1))
end
return out
end
return Encode
+596
View File
@@ -0,0 +1,596 @@
--!strict
-- image/png: PNG (ISO/IEC 15948, W3C PNG 3rd ed.). Absorbed from png-luau 1.0.0 (same author) + a new encoder.
-- 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).
-- 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
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Crc32 = require("@rosetta/core/Crc32")
local Deflate = require("@rosetta/codecs/compress/Deflate")
local Types = require("@rosetta/Types")
local Chunks = require("@rosetta/containers/Chunks")
local Decode = require("@rosetta/image/png/Decode")
local Encode = require("@rosetta/image/png/Encode")
local Apng = require("@rosetta/image/png/Apng")
-- ------------------------------------------------------------------------------------------------ contract
local Png = {
name = "png",
category = "image",
extensions = { "png", "apng" },
mime = { "image/png", "image/apng" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Deflate", "Types", "containers/Chunks" },
caps = { decode = true, encode = true, animation = true, alpha = true, depths = { 1, 2, 4, 8, 16 } },
}
export type DecodeOptions = {
checkCrc: boolean?, -- verify every chunk's CRC-32 (default false)
maxPixels: number?, -- refuse larger images (default 2^26 = 64 Mpixel, a 256 MB RGBA buffer)
}
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
local SIGNATURE = "\137PNG\r\n\26\n"
local VALID = {
[0] = { [1] = true, [2] = true, [4] = true, [8] = true, [16] = true },
[2] = { [8] = true, [16] = true },
[3] = { [1] = true, [2] = true, [4] = true, [8] = true },
[4] = { [8] = true, [16] = true },
[6] = { [8] = true, [16] = true },
}
local COLOR_NAMES = { [0] = "gray", [2] = "rgb", [3] = "palette", [4] = "graya", [6] = "rgba" }
local readu8, readu32 = buffer.readu8, buffer.readu32
local function be32(b: buffer, o: number): number
return bit32.byteswap(readu32(b, o))
end
-- ------------------------------------------------------------------------------------------------ sniff
function Png.sniff(r: Bytes.Reader): number
return if r:peek(8) == SIGNATURE then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
type Header = { width: number, height: number, bitDepth: number, colorType: number, interlace: number }
-- the IHDR at r's start: Header | nil, Err
local function header(r: Bytes.Reader): (Header?, Err.Err?)
local b, o, n = r.buf, r.base, r.limit - r.base
if n < 8 or readu8(b, o) ~= 137 or buffer.readstring(b, o, 8) ~= SIGNATURE then
return nil, Err.new(Err.CORRUPT, "bad signature", o)
end
if n < 33 or buffer.readstring(b, o + 12, 4) ~= "IHDR" or be32(b, o + 8) ~= 13 then
return nil, Err.new(Err.CORRUPT, "missing IHDR", o + 8)
end
local h = {
width = be32(b, o + 16),
height = be32(b, o + 20),
bitDepth = readu8(b, o + 24),
colorType = readu8(b, o + 25),
interlace = readu8(b, o + 28),
}
if h.width == 0 or h.height == 0 or h.width >= 2 ^ 31 or h.height >= 2 ^ 31 then
return nil, Err.new(Err.CORRUPT, "bad image size", o + 16)
end
local depths = VALID[h.colorType]
if not depths then
return nil, Err.new(Err.CORRUPT, "bad colour type " .. h.colorType, o + 25)
end
if not depths[h.bitDepth] then
return nil, Err.new(Err.CORRUPT, string.format("bad bit depth %d for colour type %d", h.bitDepth, h.colorType), o + 24)
end
if readu8(b, o + 26) ~= 0 or readu8(b, o + 27) ~= 0 or h.interlace > 1 then
return nil, Err.new(Err.UNSUPPORTED, "unknown compression, filter or interlace method", o + 26)
end
return h, nil
end
-- info(r) -> { width, height, bitDepth, colorType, interlace } | nil, Err (reads only the header)
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
local h, herr = header(r)
if not h then
return nil, herr
end
local w, ht, depth, ct = h.width, h.height, h.bitDepth, h.colorType
if w * ht > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, ht, maxPixels))
end
local b, n = r.buf, r.limit
-- chunks
local pal = buffer.create(1024)
for i = 0, 255 do
buffer.writeu32(pal, i * 4, 0xFF000000) -- out-of-range indexes: opaque black
end
local palCount = 0
local tr = -1
local idat: { { number } } = {}
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
for _, c in Chunks.walk(b, p, n, Chunks.PNG) do
local len, typ, d = c.size, c.id, c.offset
p = c.start
if c.truncated then
if p + 12 > n then
break -- not even a whole chunk header + CRC left (a cut tail)
end
return nil, Err.new(Err.TRUNCATED, "chunk " .. typ .. " runs past the end", p)
end
if checkCrc then
local want = be32(b, d + len)
if Crc32.raw(b, p + 4, len + 4) ~= want then
return nil, Err.new(Err.CHECKSUM, "CRC mismatch in chunk " .. typ, d + len)
end
end
if first and typ ~= "IHDR" then
return nil, Err.new(Err.CORRUPT, "IHDR is not the first chunk", p)
end
first = false
if typ == "PLTE" then
if len % 3 ~= 0 or len > 768 or len == 0 then
return nil, Err.new(Err.CORRUPT, "bad PLTE length", p)
end
palCount = len // 3
for i = 0, palCount - 1 do
local q = d + i * 3
buffer.writeu32(pal, i * 4, readu8(b, q) + readu8(b, q + 1) * 256 + readu8(b, q + 2) * 65536 + 0xFF000000)
end
elseif typ == "tRNS" then
if ct == 3 then
for i = 0, math.min(len, 256) - 1 do
buffer.writeu8(pal, i * 4 + 3, readu8(b, d + i))
end
elseif ct == 0 and len >= 2 then
tr = readu8(b, d) * 256 + readu8(b, d + 1)
elseif ct == 2 and len >= 6 then
local function u16(q: number): number
return readu8(b, d + q) * 256 + readu8(b, d + q + 1)
end
tr = u16(0) * 4294967296 + u16(2) * 65536 + u16(4)
end
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)
if z then
text[string.sub(s, 1, z - 1)] = string.sub(s, z + 1)
end
elseif typ == "iCCP" then
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
return nil, Err.new(Err.UNSUPPORTED, "unknown critical chunk " .. typ, p)
end
end
if #idat == 0 then
return nil, Err.new(Err.TRUNCATED, "no image data", p)
end
if ct == 3 and palCount == 0 then
return nil, Err.new(Err.CORRUPT, "palette image without PLTE")
end
local img = Types.Image.new(w, ht, "rgba8")
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 } } = {}
for i = 0, palCount - 1 do
palette[i + 1] = { readu8(pal, i * 4), readu8(pal, i * 4 + 1), readu8(pal, i * 4 + 2), readu8(pal, i * 4 + 3) }
end
img.meta.palette = palette
end
if next(text) then
img.meta.text = text
end
img.meta.iccCompressed = iccCompressed
img.meta.source = { format = "png", bitDepth = depth, colorType = COLOR_NAMES[ct], interlace = h.interlace }
return img, nil
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, "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 not validImage(img) then
return nil, Err.new(Err.ARG, "needs an rgba8 Image")
end
local w, h = img.width, img.height
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, "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, "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
-- 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, "unknown colorType " .. tostring(want))
end
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(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
out:u32be(Crc32.raw(out.buf, start, len + 4))
end
out:string(SIGNATURE)
local ihdr = Bytes.writer(13)
ihdr:u32be(w)
ihdr:u32be(h)
ihdr:u8(8)
ihdr:u8(ct)
ihdr:u8(0)
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()
t:string(k)
t:u8(0)
t:string(v)
chunk("tEXt", t:finish())
end
end
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