init.luau (small, backward compatible): loadTextures forwards those four options to F.load.
634 lines
22 KiB
Luau
634 lines
22 KiB
Luau
--!strict
|
|
-- image/png: PNG (ISO/IEC 15948, W3C PNG 3rd ed.) and APNG 1.0; from png-luau 1.0.0 (same author). Supports: every
|
|
-- colour type and bit depth, tRNS, Adam7, tEXt, acTL / fcTL / fdAT, row-streaming decode with power-of-two box
|
|
-- reduction; writes RGBA / RGB / grey(+alpha) and APNG. Not supported: colour management (iCCP kept raw), 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?, -- default false
|
|
maxPixels: number?, -- default 2^26, of the source image
|
|
maxSide: number?, -- output sides at most this: the smallest power-of-two box reduction that fits
|
|
reduce: number?, -- box reduction factor, a power of two (default 1)
|
|
yield: (() -> ())?, -- pcall'ed every yieldRows rows, and per 64 KB inflated when interlaced
|
|
yieldRows: number?, -- default: about 64 KB of row data
|
|
}
|
|
export type EncodeOptions = {
|
|
level: number?, -- 0..9, default 6
|
|
colorType: ("auto" | "rgba" | "rgb" | "gray" | "graya")?, -- default "auto": the smallest lossless one
|
|
apng: boolean?, -- 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 }
|
|
|
|
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
|
|
|
|
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" }
|
|
|
|
type Reduce = { k: number, hook: (() -> ())?, every: number }
|
|
|
|
local function pixels(b: buffer, chunks: { { number } }, w: number, ht: number, depth: number, ct: number, interlace: number, pal: buffer, tr: number, out: buffer, rd: Reduce): Err.Err?
|
|
local k = rd.k
|
|
local channels = Decode.CHANNELS[ct]
|
|
if interlace == 0 then
|
|
local stride = Decode.rowBytes(w, channels, depth) + 1
|
|
local window = math.min(if rd.hook then 65536 else 262144, ht * stride)
|
|
local every = if rd.every > 0 then rd.every else math.max(1, 65536 // stride)
|
|
local sink, status = Decode.stream(w, ht, depth, ct, pal, tr, k, out, rd.hook, every)
|
|
local _, zerr = Deflate.zlibStream(b, chunks, sink, window)
|
|
local y, derr = status()
|
|
if derr then
|
|
return Err.new(Err.CORRUPT, derr)
|
|
elseif zerr then
|
|
return zerr
|
|
elseif y < ht then
|
|
return Err.new(Err.CORRUPT, string.format("image data ends after %d of %d rows", y, ht))
|
|
end
|
|
return nil
|
|
end
|
|
-- Adam7: the whole inflated stream (every pass row has a filter byte), then the full image when reducing
|
|
local expected = 0
|
|
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
|
|
local raw = buffer.create(expected)
|
|
local got = 0
|
|
local hook = rd.hook
|
|
local _, zerr = Deflate.zlibStream(b, chunks, function(win: buffer, from: number, to: number): number
|
|
local n = math.min(to - from, expected - got)
|
|
if n > 0 then
|
|
buffer.copy(raw, got, win, from, n)
|
|
got += n
|
|
end
|
|
if hook then
|
|
pcall(hook)
|
|
end
|
|
return 0
|
|
end, math.min(if hook then 65536 else 262144, expected))
|
|
if zerr then
|
|
return zerr
|
|
elseif got < expected then
|
|
return Err.new(Err.CORRUPT, string.format("inflate: output is %d bytes, expected %d", got, expected))
|
|
end
|
|
local full = if k > 1 then buffer.create(w * ht * 4) else out
|
|
local ok, derr = Decode.run(raw, w, ht, depth, ct, pal, tr, full, hook, if rd.every > 0 then rd.every else math.max(1, 65536 // (w * 4)))
|
|
if not ok then
|
|
return Err.new(Err.CORRUPT, tostring(derr))
|
|
end
|
|
if k > 1 then
|
|
Decode.reduce(full, w, ht, k, out, Decode.opaque(ct, tr, pal))
|
|
end
|
|
return nil
|
|
end
|
|
|
|
local function reduction(w: number, ht: number, opts: DecodeOptions?): (Reduce?, Err.Err?)
|
|
local o: any = opts or {}
|
|
local k = 1
|
|
if o.reduce ~= nil then
|
|
local r = o.reduce
|
|
if type(r) ~= "number" or r < 1 or r > 2 ^ 31 or r % 1 ~= 0 or bit32.band(r, r - 1) ~= 0 then
|
|
return nil, Err.new(Err.ARG, "reduce must be a power of two")
|
|
end
|
|
k = r
|
|
end
|
|
if o.maxSide ~= nil then
|
|
local m = o.maxSide
|
|
if type(m) ~= "number" or not (m >= 1) then
|
|
return nil, Err.new(Err.ARG, "maxSide must be at least 1")
|
|
end
|
|
while (w + k - 1) // k > m or (ht + k - 1) // k > m do
|
|
k *= 2
|
|
end
|
|
end
|
|
local hook = o.yield
|
|
if hook ~= nil and type(hook) ~= "function" then
|
|
return nil, Err.new(Err.ARG, "yield must be a function")
|
|
end
|
|
local every = o.yieldRows or 0
|
|
if type(every) ~= "number" or not (every >= 0) or every % 1 ~= 0 then
|
|
return nil, Err.new(Err.ARG, "yieldRows must be a positive integer")
|
|
end
|
|
return { k = k, hook = hook, every = every }, 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 rd, rerr = reduction(w, ht, opts)
|
|
if not rd then
|
|
return nil, rerr
|
|
end
|
|
local k = rd.k
|
|
local b, n = r.buf, r.limit
|
|
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 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 })
|
|
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 + k - 1) // k, (ht + k - 1) // k, "rgba8")
|
|
local ierr = pixels(b, idat, w, ht, h.bitDepth, ct, h.interlace, pal, tr, img.pixels, rd)
|
|
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(img.width, img.height, "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 + k - 1) // k, (f.height + k - 1) // k, "rgba8")
|
|
local ferr = pixels(b, f.chunks, f.width, f.height, h.bitDepth, ct, h.interlace, pal, tr, fimg.pixels, rd)
|
|
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 // k,
|
|
y = f.y // k,
|
|
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, width = w, height = ht, reduce = k }
|
|
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 }
|
|
|
|
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
|
|
|
|
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
|
|
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
|
|
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
|