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)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
commit
ccb06775c5
226 files changed
+8409
No files matched your search
@@ -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