formats-luau foundation: build (darklua + token passes) for Roblox and LuaJIT, compat prelude, core, Types, host adapters, API + registry, lint, tests on both runtimes; absorb deflate (codecs/Deflate + new compressor) and png (image/png + new encoder)
This commit is contained in:
commit
cdcb5b0b77
226 files changed
+8409
No files matched your search
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,306 @@
|
||||
--!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).
|
||||
-- Not supported: APNG animation (the default image is decoded), 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("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
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")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Png = {
|
||||
name = "png",
|
||||
category = "image",
|
||||
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 } },
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ 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
|
||||
|
||||
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
|
||||
local p = r.base + 8
|
||||
local first = true
|
||||
while p + 12 <= n do
|
||||
local len = be32(b, p)
|
||||
local typ = buffer.readstring(b, p + 4, 4)
|
||||
if len > n - p - 12 then
|
||||
return nil, Err.new(Err.TRUNCATED, "chunk " .. typ .. " runs past the end", p)
|
||||
end
|
||||
local d = p + 8
|
||||
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
|
||||
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 == "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
|
||||
p = d + len + 4
|
||||
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
|
||||
-- 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))
|
||||
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 }
|
||||
|
||||
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
|
||||
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 want = opts and opts.colorType or "auto"
|
||||
local ctName: string = want
|
||||
if want == "auto" then
|
||||
ctName = Encode.pickColorType(img.pixels, w, h)
|
||||
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 out = Bytes.writer(buffer.len(z) + 128)
|
||||
local function chunk(typ: string, data: buffer?)
|
||||
local len = if data then buffer.len(data) else 0
|
||||
out:u32be(len)
|
||||
local start = out:tell()
|
||||
out:string(typ)
|
||||
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 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
|
||||
chunk("IDAT", z)
|
||||
chunk("IEND", nil)
|
||||
return out:finish(), nil
|
||||
end
|
||||
|
||||
return Png
|
||||
Reference in new issue
Block a user