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

+183
View File
@@ -0,0 +1,183 @@
--!strict
-- image/ani: Windows animated cursors (RIFF "ACON": the anih header, rate / seq chunks, LIST fram of icon chunks;
-- containers/Riff; new code). Decode: every step of the animation as img.frames (the seq order when there is one,
-- each step's rate or the default iDispRate in jiffies of 1/60 s as the delay), the icon chunks (ICO / CUR files)
-- through the api hook opts.decodeImage (F.load passes it; without it: UNSUPPORTED), the hotspots of CUR frames
-- (frame image meta.hotspot), INFO title / author (meta.text). The image is the first step; img.loops = 0 (cursors
-- loop forever). Encode: img.frames (or the image) through opts.encodeImage(frame, "ico") as icon chunks, with a
-- rate chunk when the delays differ. Not supported: raw (non-icon) frame bitmaps (AF_ICON clear: UNSUPPORTED).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Riff = require("@rosetta/containers/Riff")
-- ------------------------------------------------------------------------------------------------ contract
local Ani = {
name = "ani",
category = "image",
extensions = { "ani" },
mime = { "application/x-navi-animation" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Riff" },
caps = { decode = true, encode = true, alpha = true, animation = true, frames = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes the ICO / CUR frames (the api passes one)
maxFrames: number?, -- refuse more steps (default 10000)
}
export type EncodeOptions = {
encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes the ICO / CUR frames (the api passes one)
}
-- ------------------------------------------------------------------------------------------------ sniff
function Ani.sniff(r: Bytes.Reader): number
return if r:peek(4) == "RIFF" and r:peek(4, 8) == "ACON" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Ani.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local f, ferr = Riff.read(r)
if not f then
return nil, ferr
end
if f.form ~= "ACON" then
return nil, Err.new(Err.CORRUPT, "not an ACON form", r.base + 8)
end
local anih = Riff.find(f, "anih")
if not anih or anih.avail < 36 then
return nil, Err.new(Err.CORRUPT, "missing anih header", r.base + 12)
end
local a = anih.offset
local nFrames, nSteps = Riff.u32(f, a + 4), Riff.u32(f, a + 8)
local dispRate, flags = Riff.u32(f, a + 28), Riff.u32(f, a + 32)
local maxFrames = opts and opts.maxFrames or 10000
if nSteps == 0 then
nSteps = nFrames
end
if nFrames > maxFrames or nSteps > maxFrames then
return nil, Err.new(Err.LIMIT, "too many frames", a + 4)
end
if bit32.band(flags, 1) == 0 then
return nil, Err.new(Err.UNSUPPORTED, "raw frame bitmaps (AF_ICON clear)", a + 32)
end
local decodeImage = opts and opts.decodeImage
if not decodeImage then
return nil, Err.new(Err.UNSUPPORTED, "icon frames need the decodeImage hook")
end
-- the icon chunks
local icons: { Types.Image } = {}
for _, c in f.chunks do
if c.id == "LIST" and Riff.listType(f, c) == "fram" then
for _, ic in Riff.list(f, c) do
if ic.id == "icon" then
local sub = buffer.create(ic.avail)
buffer.copy(sub, 0, f.buf, ic.offset, ic.avail)
local ok, im, ierr = pcall(decodeImage, sub)
if not ok or not im then
return nil, Err.new(Err.CORRUPT, "frame " .. (#icons + 1) .. ": " .. tostring(if ok then ierr else im), ic.offset)
end
table.insert(icons, im :: Types.Image)
end
end
end
end
if #icons == 0 then
return nil, Err.new(Err.TRUNCATED, "no icon frames")
end
local rate = Riff.find(f, "rate")
local seq = Riff.find(f, "seq ")
local frames: { Types.Frame } = {}
for s = 0, nSteps - 1 do
local idx = s
if seq and seq.avail >= (s + 1) * 4 then
idx = Riff.u32(f, seq.offset + s * 4)
end
local im = icons[idx + 1]
if not im then
if s >= #icons and not seq then
break -- fewer icons than steps: keep what is there
end
return nil, Err.new(Err.CORRUPT, "step " .. s .. " names frame " .. idx)
end
local jiffies = dispRate
if rate and rate.avail >= (s + 1) * 4 then
jiffies = Riff.u32(f, rate.offset + s * 4)
end
table.insert(frames, { image = im, delay = jiffies / 60, x = 0, y = 0, dispose = "background", blend = "source" } :: Types.Frame)
end
local first = frames[1].image
local img = Types.Image.new(0, 0, first.format)
img.width, img.height, img.pixels = first.width, first.height, first.pixels
img.frames = frames
img.loops = 0
img.meta.hotspot = first.meta.hotspot
local text: { [string]: string } = {}
for _, c in f.chunks do
if c.id == "LIST" and Riff.listType(f, c) == "INFO" then
for _, it in Riff.list(f, c) do
local key = if it.id == "INAM" then "title" elseif it.id == "IART" then "author" else nil
if key then
text[key] = (string.gsub(buffer.readstring(f.buf, it.offset, it.avail), "%z+$", ""))
end
end
end
end
if next(text) then
img.meta.text = text
end
img.meta.source = { format = "ani", frames = #icons, steps = #frames, sequence = seq ~= nil, rate = dispRate }
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Ani.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(img) ~= "table" or type(img.pixels) ~= "buffer" then
return nil, Err.new(Err.ARG, "needs an Image")
end
local encodeImage = opts and opts.encodeImage
if not encodeImage then
return nil, Err.new(Err.UNSUPPORTED, "icon frames need the encodeImage hook")
end
local frames: { Types.Frame } = if type(img.frames) == "table" and #img.frames > 0 then img.frames else { { image = img, delay = 1 / 6, x = 0, y = 0, dispose = "background", blend = "source" } :: Types.Frame }
local w = Riff.writer("ACON")
local jiffies: { number } = {}
local same = true
for i, fr in frames do
jiffies[i] = math.max(1, math.floor((fr.delay or 0) * 60 + 0.5))
same = same and jiffies[i] == jiffies[1]
end
local head = Bytes.writer(36)
head:u32le(36)
head:u32le(#frames)
head:u32le(#frames)
head:u32le(0)
head:u32le(0)
head:u32le(0)
head:u32le(0)
head:u32le(jiffies[1])
head:u32le(1)
w:chunk("anih", head:finish())
if not same then
local rw = Bytes.writer(#frames * 4)
for _, j in jiffies do
rw:u32le(j)
end
w:chunk("rate", rw:finish())
end
local items = {}
for i, fr in frames do
local im = fr.image
local ok, data, err = pcall(encodeImage, im, "ico")
if not ok or not data then
return nil, Err.new(Err.ARG, "frame " .. i .. ": " .. tostring(if ok then err else data))
end
table.insert(items, { "icon", data })
end
w:list("fram", items)
return w:finish()
end
return Ani
+266
View File
@@ -0,0 +1,266 @@
--!strict
-- image/blp: Blizzard BLP textures (Warcraft III: BLP1; World of Warcraft: BLP2), read, and BLP2 written
-- (uncompressed BGRA). Written from the wowdev.wiki BLP page; no code taken.
-- Decode, mip 0 (meta.source.mips counts the levels) to rgba8:
-- BLP1 JPEG: the shared JPEG header + the mip's data through codecs/image/Jpeg; 4-component files (the usual
-- Warcraft III layout) are BGRA without colour conversion, 3-component ones YCbCr -> BGR (R and B swapped back);
-- BLP1 palette: 8-bit indexes into a BGRA palette, then an 8-bit alpha plane when alphaBits is 8 (else opaque);
-- BLP2 palette: indexes + a 1 / 4 / 8-bit alpha plane (LSB first), DXT1 / DXT3 / DXT5 (codecs/image/Bcn: alpha
-- type 0 / 1 / 7), uncompressed BGRA.
-- Encode: BLP2 uncompressed BGRA with 8-bit alpha (opts.mips = true adds the box-filtered mip chain).
-- Not supported: BLP0 (external .b00 mip files), BLP2 JPEG (never used by the games).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Jpeg = require("@rosetta/codecs/image/Jpeg")
local Bcn = require("@rosetta/codecs/image/Bcn")
-- ------------------------------------------------------------------------------------------------ contract
local Blp = {
name = "blp",
category = "image",
extensions = { "blp" },
mime = { "image/x-blp" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Jpeg", "codecs/image/Bcn" },
caps = { decode = true, encode = true, alpha = true, variants = { "blp1", "blp2" }, compressions = { "jpeg", "palette", "dxt1", "dxt3", "dxt5", "bgra" } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = { maxPixels: number? } -- default 2^26
export type EncodeOptions = { mips: boolean? } -- write the mip chain (default false)
-- ------------------------------------------------------------------------------------------------ constants
local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8
-- ------------------------------------------------------------------------------------------------ sniff
function Blp.sniff(r: Bytes.Reader): number
local m = r:peek(4)
return if m == "BLP1" or m == "BLP2" then 1 elseif m == "BLP0" then 0.8 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- BGRA u32 (b at the lowest address) -> RGBA u32 with the given alpha
local function swap(v: number, a: number): number
local b, g, r = v % 256, (v // 256) % 256, (v // 65536) % 256
return r + g * 256 + b * 65536 + a * 16777216
end
-- alpha of pixel i from a packed plane at p of depth bits
local function alphaAt(b: buffer, p: number, depth: number, i: number): number
if depth == 8 then
return readu8(b, p + i)
elseif depth == 4 then
local v = readu8(b, p + i // 2)
local n = if i % 2 == 0 then v % 16 else v // 16
return n * 17
elseif depth == 1 then
local v = readu8(b, p + i // 8)
return if bit32.band(v, bit32.lshift(1, i % 8)) ~= 0 then 255 else 0
end
return 255
end
function Blp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local size = r.limit - r.base
local b, base = r.buf, r.base
local magic = r:peek(4)
if magic == "BLP0" then
return nil, Err.new(Err.UNSUPPORTED, "BLP0 (mips in external files)", 0)
end
if magic ~= "BLP1" and magic ~= "BLP2" then
return nil, Err.new(if size < 4 then Err.TRUNCATED else Err.CORRUPT, "bad magic", 0)
end
local v2 = magic == "BLP2"
local headerSize = if v2 then 20 + 128 + 1024 else 28 + 128
if size < headerSize then
return nil, Err.new(Err.TRUNCATED, "header", 0)
end
local kind = readu32(b, base + 4) -- BLP1: 0 = JPEG, 1 = palette; BLP2: 1 (0 = JPEG)
local compression = if v2 then readu8(b, base + 8) elseif kind == 0 then 0 else 1
local alphaDepth = if v2 then readu8(b, base + 9) else readu32(b, base + 8)
local alphaType = if v2 then readu8(b, base + 10) else 0
local w, h = readu32(b, base + 12), readu32(b, base + 16)
local mipsAt = if v2 then 20 else 28
if w == 0 or h == 0 or w > 65535 or h > 65535 then
return nil, Err.new(Err.CORRUPT, "bad size " .. w .. " x " .. h, 12)
end
if w * h > (opts and opts.maxPixels or 2 ^ 26) then
return nil, Err.new(Err.LIMIT, "image too big")
end
local offs: { number }, lens: { number } = {}, {}
local mips = 0
for i = 0, 15 do
offs[i + 1] = readu32(b, base + mipsAt + i * 4)
lens[i + 1] = readu32(b, base + mipsAt + 64 + i * 4)
if offs[i + 1] ~= 0 and lens[i + 1] ~= 0 then
mips += 1
end
end
local at, len = offs[1], lens[1]
if at + len > size or len == 0 then
return nil, Err.new(Err.TRUNCATED, "mip 0 past the end", mipsAt)
end
local img = Types.Image.new(w, h)
local px = img.pixels
local n = w * h
local src = base + at
local name: string
if (not v2 and kind == 0) or (v2 and kind == 0) then
if v2 then
return nil, Err.new(Err.UNSUPPORTED, "BLP2 JPEG")
end
-- the JPEG header shared by the mips, then the mip's own data
if size < headerSize + 4 then
return nil, Err.new(Err.TRUNCATED, "JPEG header size", headerSize)
end
local hs = readu32(b, base + headerSize)
if hs > 0x10000 or headerSize + 4 + hs > size then
return nil, Err.new(Err.CORRUPT, "bad JPEG header size", headerSize)
end
local jpg = buffer.create(hs + len)
buffer.copy(jpg, 0, b, base + headerSize + 4, hs)
buffer.copy(jpg, hs, b, src, len)
local info = Jpeg.info(jpg)
local four = info ~= nil and (info :: any).components == 4
local dec, err = Jpeg.decode(jpg, 0, nil, { raw = four, maxPixels = opts and opts.maxPixels })
if not dec then
return nil, err
end
local dw, dh = math.min(dec.width, w), math.min(dec.height, h)
for y = 0, dh - 1 do
for x = 0, dw - 1 do
local v = readu32(dec.pixels, (y * dec.width + x) * 4)
local a = if four and alphaDepth > 0 then v // 16777216 else 255
writeu32(px, (y * w + x) * 4, swap(v, a))
end
end
name = "jpeg"
elseif compression == 1 then
local palAt = base + (if v2 then 148 else headerSize)
local dataAt = src
if not v2 then
-- BLP1: the palette follows the header; the mip offsets point past it
if headerSize + 1024 > size then
return nil, Err.new(Err.TRUNCATED, "palette", headerSize)
end
end
local depth = if v2 then alphaDepth else (if alphaDepth >= 8 then 8 else 0)
local need = n + (if depth == 8 then n elseif depth == 4 then (n + 1) // 2 elseif depth == 1 then (n + 7) // 8 else 0)
if at + need > size then
return nil, Err.new(Err.TRUNCATED, "palette mip past the end", at)
end
for i = 0, n - 1 do
local e = readu32(b, palAt + readu8(b, dataAt + i) * 4)
writeu32(px, i * 4, swap(e, if depth > 0 then alphaAt(b, dataAt + n, depth, i) else 255))
end
name = "palette"
elseif compression == 2 then
local kindName = if alphaType == 7 then "bc3" elseif alphaType == 1 then "bc2" else "bc1"
local want: number = Bcn.size(kindName, w, h) or 0
if len < want then
return nil, Err.new(Err.TRUNCATED, "DXT mip shorter than " .. want .. " bytes", mipsAt + 64)
end
local dec, err = Bcn.decode(kindName, b, src, w, h)
if not dec then
return nil, Err.from(err)
end
buffer.copy(px, 0, dec, 0, n * 4)
if kindName == "bc1" and alphaDepth == 0 then
for i = 0, n - 1 do
writeu8(px, i * 4 + 3, 255)
end
end
name = ({ bc1 = "dxt1", bc2 = "dxt3", bc3 = "dxt5" } :: { [string]: string })[kindName]
elseif compression == 3 then
if len < n * 4 then
return nil, Err.new(Err.TRUNCATED, "BGRA mip too short", mipsAt + 64)
end
for i = 0, n - 1 do
local v = readu32(b, src + i * 4)
writeu32(px, i * 4, swap(v, v // 16777216))
end
name = "bgra"
else
return nil, Err.new(Err.UNSUPPORTED, "compression " .. tostring(compression))
end
img.meta.source = { format = "blp", version = if v2 then 2 else 1, compression = name, alphaDepth = alphaDepth, alphaType = alphaType, mips = mips }
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- halve(px, w, h) -> the next mip (2 x 2 box filter; odd edges repeat)
local function halve(px: buffer, w: number, h: number): (buffer, number, number)
local nw, nh = math.max(1, w // 2), math.max(1, h // 2)
local out = buffer.create(nw * nh * 4)
for y = 0, nh - 1 do
for x = 0, nw - 1 do
for c = 0, 3 do
local s = 0
for dy = 0, 1 do
for dx = 0, 1 do
local sx, sy = math.min(x * 2 + dx, w - 1), math.min(y * 2 + dy, h - 1)
s += readu8(px, (sy * w + sx) * 4 + c)
end
end
writeu8(out, (y * nw + x) * 4 + c, (s + 2) // 4)
end
end
end
return out, nw, nh
end
function Blp.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, "expected an rgba8 Image")
end
local w, h = img.width, img.height
if w < 1 or h < 1 or w > 65535 or h > 65535 then
return nil, Err.new(Err.ARG, "bad size")
end
local levels: { buffer } = { img.pixels }
local sizes: { { number } } = { { w, h } }
if opts and opts.mips then
local p, cw, ch = img.pixels, w, h
while (cw > 1 or ch > 1) and #levels < 16 do
p, cw, ch = halve(p, cw, ch)
table.insert(levels, p)
table.insert(sizes, { cw, ch })
end
end
local out = Bytes.writer(1172 + w * h * 6)
out:string("BLP2")
out:u32le(1)
out:u8(3) -- uncompressed BGRA
out:u8(8) -- alpha depth
out:u8(8) -- alpha type
out:u8(if #levels > 1 then 1 else 0)
out:u32le(w)
out:u32le(h)
local at = 1172
for i = 1, 16 do
local l = levels[i]
out:u32le(if l then at else 0)
if l then
at += buffer.len(l)
end
end
for i = 1, 16 do
local l = levels[i]
out:u32le(if l then buffer.len(l) else 0)
end
out:fill(0, 1024)
for _, l in levels do
local p = out:reserve(buffer.len(l))
local o = out.buf
for i = 0, buffer.len(l) // 4 - 1 do
local v = readu32(l, i * 4)
writeu32(o, p + i * 4, swap(v, v // 16777216))
end
out.pos = p + buffer.len(l)
end
return out:finish(), nil
end
return Blp
+429
View File
@@ -0,0 +1,429 @@
--!strict
--!optimize 2
-- image/bmp: Windows / OS/2 BMP. Absorbed from bmp-luau b86aed6 (same author, no third-party code; the reader), plus a
-- new encoder. Decode: BITMAPCOREHEADER (OS/2 1.x, 12 bytes), OS/2 2.x (16..64), BITMAPINFOHEADER (40), the v2 / v3
-- variants (52 / 56), BITMAPV4HEADER / BITMAPV5HEADER (108 / 124); 1 / 2 / 4 / 8 bpp paletted, 16 bpp (555 or
-- BITFIELDS), 24 bpp, 32 bpp (BI_RGB, BITFIELDS, ALPHABITFIELDS), RLE8 / RLE4 (delta / end-of-line / end-of-bitmap),
-- bottom-up and top-down rows. Lenient: bfSize / biSizeImage are ignored, a bad bfOffBits falls back to the end of the
-- palette, a short or missing palette pads with opaque black, a truncated pixel array decodes as zero bytes, a 32-bit
-- image whose alpha is all zero is opaque. Masks scale as Pillow does (v * 255 // max).
-- Encode (rgba8): 8 bpp paletted when the image is opaque with at most 256 colours (palette in first-appearance
-- order), else 24 bpp when opaque, else 32 bpp with alpha (BITMAPV4HEADER + BITFIELDS, or BI_RGB with
-- opts.header = "info" as Pillow writes). Byte-identical to Pillow for 24 bpp, paletted and BI_RGB 32 bpp output.
-- Not supported: embedded JPEG / PNG, OS/2 Huffman / RLE24, writing RLE / 16 bpp / 1-4 bpp.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Pixels = require("@rosetta/codecs/image/Pixels")
-- ------------------------------------------------------------------------------------------------ contract
local Bmp = {
name = "bmp",
category = "image",
extensions = { "bmp", "dib" },
mime = { "image/bmp", "image/x-bmp", "image/x-ms-bmp" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels" },
caps = { decode = true, encode = true, alpha = true, depths = { 1, 2, 4, 8, 16, 24, 32 }, rle = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type Info = {
width: number,
height: number,
bitsPerPixel: number,
compression: number,
topDown: boolean,
headerSize: number,
os2: boolean,
}
export type DecodeOptions = {
maxPixels: number?, -- refuse images with more pixels than this (default 2^26 = 64 Mpx)
}
export type EncodeOptions = {
bitDepth: (number | "auto")?, -- 8, 24, 32; default "auto": 8 when opaque with <= 256 colours, else 24 when opaque, else 32
header: ("v4" | "info")?, -- 32 bpp: "v4" (default, BITFIELDS with an alpha mask) or "info" (BI_RGB, as Pillow)
}
-- ------------------------------------------------------------------------------------------------ constants
local MAX_PIXELS = 2 ^ 26
local COMPRESSION_NAMES = { [0] = "rgb", "rle8", "rle4", "bitfields", "jpeg", "png", "alphabitfields" }
local readu8, readu16, readu32, readi32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32
local band, rshift, lshift, countrz = bit32.band, bit32.rshift, bit32.lshift, bit32.countrz
-- the reader's range as a buffer starting at offset 0 (copied when it is a part of a bigger buffer)
local function whole(r: Bytes.Reader): buffer
if r.base == 0 and r.limit == buffer.len(r.buf) then
return r.buf
end
local n = r.limit - r.base
local b = buffer.create(n)
buffer.copy(b, 0, r.buf, r.base, n)
return b
end
-- ------------------------------------------------------------------------------------------------ sniff
function Bmp.sniff(r: Bytes.Reader): number
if r:peek(2) ~= "BM" then
return 0
end
-- a known header size: a strong match; "BM" alone is weak
local n = r:peekU8(14) + math.max(r:peekU8(15), 0) * 256
if r:peekU8(16) == 0 and r:peekU8(17) == 0 and (n == 12 or n == 16 or n == 40 or n == 52 or n == 56 or n == 64 or n == 108 or n == 124) then
return 0.9
end
return 0.2
end
-- ------------------------------------------------------------------------------------------------ decode
-- Header parse: info, palette start offset, palette entry size, header-provided masks (or nil) | nil, err
local function parseHeader(buf: buffer): (Info?, any)
local n = buffer.len(buf)
if n < 18 then
return nil, Err.new(Err.TRUNCATED, "file too short")
end
if readu8(buf, 0) ~= 0x42 or readu8(buf, 1) ~= 0x4D then
return nil, Err.new(Err.CORRUPT, "not a BMP file (no BM signature)")
end
local hs = readu32(buf, 14)
if hs < 12 or 14 + hs > n then
return nil, Err.new(Err.CORRUPT, "bad header size " .. hs)
end
local info: Info = {
width = 0,
height = 0,
bitsPerPixel = 0,
compression = 0,
topDown = false,
headerSize = hs,
os2 = false,
}
if hs == 12 then
info.width = readu16(buf, 18)
info.height = readu16(buf, 20)
info.bitsPerPixel = readu16(buf, 24)
info.os2 = true
else
if hs < 16 then
return nil, Err.new(Err.CORRUPT, "bad header size " .. hs)
end
info.width = readi32(buf, 18)
local h = readi32(buf, 22)
info.bitsPerPixel = readu16(buf, 28)
if hs >= 20 then
info.compression = readu32(buf, 30)
end
if h < 0 then
info.topDown = true
h = -h
end
info.height = h
-- OS/2 2.x headers: 16 / 64 bytes, or any size that is not a Windows one
info.os2 = not (hs == 40 or hs == 52 or hs == 56 or hs == 108 or hs == 124)
end
return info
end
-- info(r) -> Info | nil, Err: the header without decoding the pixels
function Bmp.info(r: Bytes.Reader): (Info?, Err.Err?)
return parseHeader(whole(r))
end
-- u8 table of size (m + 1) mapping a masked value 0..m to 0..255: v * 255 // m, as Pillow does (browsers replicate
-- the top bits instead, which can differ by 1). m = 0 -> { empty }.
local function scaleTable(m: number, empty: number): buffer
local t = buffer.create(m + 1)
if m == 0 then
buffer.writeu8(t, 0, empty)
else
for v = 0, m do
buffer.writeu8(t, v, (v * 255) // m)
end
end
return t
end
-- shift, mask >> shift, table for one channel mask (wider than 16 bits: keep the top 16)
local function channel(mask: number, empty: number): (number, number, buffer)
if mask == 0 then
return 0, 0, scaleTable(0, empty)
end
local sh = countrz(mask)
local m = rshift(mask, sh)
-- holes in the mask: use the lowest contiguous run of bits
local bits = 0
while bits < 32 and band(m, lshift(1, bits)) ~= 0 do
bits += 1
end
if bits > 16 then
sh += bits - 16
bits = 16
end
m = lshift(1, bits) - 1
return sh, m, scaleTable(m, empty)
end
-- decode(r, opts?) -> rgba8 Image | nil, Err
function Bmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local buf = whole(r)
local info, herr = parseHeader(buf)
if not info then
return nil, herr
end
local n = buffer.len(buf)
local hs, w, h, bpp, comp = info.headerSize, info.width, info.height, info.bitsPerPixel, info.compression
if w <= 0 or h <= 0 then
return nil, Err.new(Err.CORRUPT, "bad size " .. w .. "x" .. h)
end
local maxPixels = (opts and opts.maxPixels) or MAX_PIXELS
if w * h > maxPixels then
return nil, Err.new(Err.LIMIT, "image too large (" .. w .. "x" .. h .. ")")
end
if info.os2 and hs ~= 12 and (comp == 3 or comp == 4) then
return nil, Err.new(Err.UNSUPPORTED, "OS/2 Huffman / RLE24 compression is not supported")
end
if comp == 4 or comp == 5 then
return nil, Err.new(Err.UNSUPPORTED, "embedded " .. (if comp == 4 then "JPEG" else "PNG") .. " is not supported")
end
if comp > 6 then
return nil, Err.new(Err.CORRUPT, "unknown compression " .. comp)
end
local valid = (bpp == 1 or bpp == 2 or bpp == 4 or bpp == 8 or bpp == 16 or bpp == 24 or bpp == 32)
if not valid then
return nil, Err.new(Err.CORRUPT, "unsupported bit depth " .. bpp)
end
if (comp == 1 and bpp ~= 8) or (comp == 2 and bpp ~= 4) then
return nil, Err.new(Err.CORRUPT, "RLE compression " .. comp .. " with " .. bpp .. " bpp")
end
if (comp == 3 or comp == 6) and bpp ~= 16 and bpp ~= 24 and bpp ~= 32 then
return nil, Err.new(Err.CORRUPT, "BITFIELDS with " .. bpp .. " bpp")
end
-- masks: in the v2+ header, or right after a 40-byte header
local palStart = 14 + hs
local rm: number, gm: number, bm: number, am: number = 0, 0, 0, 0
local hasMasks = false
if comp == 3 or comp == 6 then
hasMasks = true
if hs >= 52 then
rm = readu32(buf, 54)
gm = readu32(buf, 58)
bm = readu32(buf, 62)
if hs >= 56 then
am = readu32(buf, 66)
end
else
local count = if comp == 6 then 4 else 3
if palStart + count * 4 > n then
return nil, Err.new(Err.TRUNCATED, "truncated bit masks")
end
rm = readu32(buf, palStart)
gm = readu32(buf, palStart + 4)
bm = readu32(buf, palStart + 8)
if comp == 6 then
am = readu32(buf, palStart + 12)
end
palStart += count * 4
end
if comp == 3 and hs < 56 then
am = 0
end
if rm == 0 and gm == 0 and bm == 0 then
hasMasks = false -- all-zero masks: use the defaults
end
end
-- palette
local entrySize = if hs == 12 then 3 else 4
local declared = if hs >= 36 then readu32(buf, 46) else 0
local palCount = 0
if bpp <= 8 then
palCount = if declared == 0 or declared > lshift(1, bpp) then lshift(1, bpp) else declared
end
local off = readu32(buf, 10)
local pixelEnd = palStart + palCount * entrySize
if off < palStart or off >= n then
-- bad bfOffBits: the pixels start after the palette as declared
off = math.min(pixelEnd, n)
elseif bpp <= 8 and off < pixelEnd then
-- palette shorter than declared: it ends where the pixels start
palCount = (off - palStart) // entrySize
end
palCount = math.max(0, math.min(palCount, (n - palStart) // entrySize))
local pal = buffer.create(256 * 4)
for i = 0, 255 do
buffer.writeu32(pal, i * 4, 0xFF000000)
end
for i = 0, palCount - 1 do
local p = palStart + i * entrySize
local bb, gg, rr = readu8(buf, p), readu8(buf, p + 1), readu8(buf, p + 2)
buffer.writeu32(pal, i * 4, rr + gg * 256 + bb * 65536 + 0xFF000000)
end
local img = Types.Image.new(w, h, "rgba8")
local pixels = img.pixels
img.meta.source = {
format = "bmp",
bitDepth = bpp,
compression = COMPRESSION_NAMES[comp],
topDown = info.topDown,
headerSize = hs,
paletteSize = palCount,
os2 = info.os2,
}
if bpp <= 8 and palCount > 0 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), 255 }
end
img.meta.palette = palette
end
if hs >= 40 then
local xp, yp = readi32(buf, 38), readi32(buf, 42)
if xp > 0 and yp > 0 then
img.meta.dpi = { x = xp * 0.0254, y = yp * 0.0254 }
end
end
if comp == 1 or comp == 2 then
Pixels.rle(buf, off, n, comp == 2, pixels, w, h, info.topDown, pal)
return img, nil
end
-- uncompressed: make sure every row is readable (a truncated file reads as zeros)
local stride = ((w * bpp + 31) // 32) * 4
local need = stride * h
local src, base = buf, off
if off + need > n then
src = buffer.create(need)
buffer.copy(src, 0, buf, off, n - off)
base = 0
end
if bpp <= 8 then
Pixels.indexed(src, base, stride, bpp, pixels, w, h, info.topDown, pal)
elseif bpp == 24 and not hasMasks then
Pixels.bgr24(src, base, stride, pixels, w, h, info.topDown)
elseif bpp == 32 and (not hasMasks or (rm == 0xFF0000 and gm == 0xFF00 and bm == 0xFF and (am == 0xFF000000 or am == 0))) then
local aor = Pixels.bgra32(src, base, stride, pixels, w, h, info.topDown)
if aor == 0 or (hasMasks and am == 0) then
Pixels.opaque(pixels, w * h)
end
else
if not hasMasks then
if bpp == 16 then
rm, gm, bm, am = 0x7C00, 0x3E0, 0x1F, 0
else
rm, gm, bm, am = 0xFF0000, 0xFF00, 0xFF, 0
end
end
local shr, mr, tr = channel(rm, 0)
local shg, mg, tg = channel(gm, 0)
local shb, mb, tb = channel(bm, 0)
local sha, ma, ta = channel(am, 255)
local aor =
Pixels.masked(src, base, stride, bpp, pixels, w, h, info.topDown, shr, mr, tr, shg, mg, tg, shb, mb, tb, sha, ma, ta)
if ma ~= 0 and aor == 0 then
Pixels.opaque(pixels, w * h)
end
end
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- encode(img, opts?) -> buffer | nil, Err
function Bmp.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, "encode: needs an rgba8 Image")
end
local w, h = img.width, img.height
if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or w > 0x7FFFFFFF or h > 0x7FFFFFFF then
return nil, Err.new(Err.ARG, "encode: bad image size")
end
if buffer.len(img.pixels) < w * h * 4 then
return nil, Err.new(Err.ARG, "encode: the pixel buffer is smaller than width * height * 4")
end
local want = opts and opts.bitDepth or "auto"
if want ~= "auto" and want ~= 8 and want ~= 24 and want ~= 32 then
return nil, Err.new(Err.ARG, "encode: bitDepth must be 8, 24, 32 or auto")
end
local headerKind = opts and opts.header or "v4"
if headerKind ~= "v4" and headerKind ~= "info" then
return nil, Err.new(Err.ARG, "encode: header must be v4 or info")
end
local colours, alpha = Pixels.colours(img.pixels, w * h, 256)
local bpp: number
if want == "auto" then
bpp = if alpha then 32 elseif #colours <= 256 then 8 else 24
else
bpp = want :: number
if bpp == 8 and #colours > 256 then
return nil, Err.new(Err.ARG, "encode: more than 256 colours for 8 bpp")
end
end
local v4 = bpp == 32 and headerKind == "v4"
local hs = if v4 then 108 else 40
local stride = ((w * bpp + 31) // 32) * 4
local palCount = if bpp == 8 then #colours else 0
local off = 14 + hs + palCount * 4
local imageSize = stride * h
if off + imageSize > 0x3FFFFFFF then
return nil, Err.new(Err.LIMIT, "encode: the file would be over 1 GiB")
end
local out = buffer.create(off + imageSize)
local o = Bytes.writer(off)
o:string("BM")
o:u32le(off + imageSize)
o:u32le(0)
o:u32le(off)
o:u32le(hs)
o:i32le(w)
o:i32le(h)
o:u16le(1)
o:u16le(bpp)
o:u32le(if v4 then 3 else 0) -- BI_BITFIELDS / BI_RGB
o:u32le(imageSize)
local dpi = img.meta and img.meta.dpi
local xp: number, yp: number = 3780, 3780 -- 96 dpi, as Pillow
if type(dpi) == "table" and type(dpi.x) == "number" and type(dpi.y) == "number" and dpi.x > 0 and dpi.y > 0 then
xp = math.floor((dpi.x :: number) * 39.3701 + 0.5)
yp = math.floor((dpi.y :: number) * 39.3701 + 0.5)
end
o:i32le(xp)
o:i32le(yp)
o:u32le(palCount)
o:u32le(palCount)
if v4 then
o:u32le(0x00FF0000)
o:u32le(0x0000FF00)
o:u32le(0x000000FF)
o:u32le(0xFF000000)
o:string("BGRs") -- LCS_sRGB (stored little-endian: 'sRGB')
o:fill(0, 36 + 12) -- endpoints, gamma
end
local idx: { [number]: number } = {}
for i, c in colours do
if i > palCount then
break
end
idx[c] = i - 1
o:u8(band(rshift(c, 16), 255))
o:u8(band(rshift(c, 8), 255))
o:u8(band(c, 255))
o:u8(0)
end
buffer.copy(out, 0, o.buf, 0, off)
if bpp == 8 then
Pixels.encode8(img.pixels, w, h, out, off, stride, idx)
elseif bpp == 24 then
Pixels.encode24(img.pixels, w, h, out, off, stride)
else
Pixels.encode32(img.pixels, w, h, out, off)
end
return out, nil
end
return Bmp
+497
View File
@@ -0,0 +1,497 @@
--!strict
-- image/dds: DirectDraw Surface (Microsoft "DDS" programming guide: DDS_HEADER, DDS_PIXELFORMAT, DDS_HEADER_DXT10; new
-- code). Decode: every DXGI format with a pixel layout (BC1..BC7 through codecs/image/Bcn; the uncompressed UNORM /
-- SNORM / UINT / SINT / FLOAT / packed / shared-exponent ones and YUY2 / AYUV / RGBG through codecs/image/Texel), the
-- legacy FourCC codes (DXT1..DXT5, ATI1 / BC4U / BC4S, ATI2 / BC5U / BC5S, RXGB, YUY2 / UYVY / RGBG / GRGB, the
-- D3DFMT float / 16-bit numbers) and legacy bit-mask RGB / luminance / alpha formats; mip chains, cube maps (all six
-- faces or a subset), texture arrays (DX10 arraySize) and volume textures. The first surface is the image; when there
-- are more (faces, layers, depth slices) img.frames lists every one of them (meta.layout = "2d" / "cube" / "array" /
-- "volume", meta.faces), and with opts.mips the smaller levels of the first surface go to img.meta.mipmaps. rgba8 by
-- default (BC6H and float formats clamped to 0..1); opts.native keeps rgbaf32 / rgba16 where the source has more.
-- Encode: rgba8 as uncompressed (R8G8B8A8 / B8G8R8A8), BC1 / BC3 / BC4 / BC5 (legacy FourCC headers), rgba16 / rgbaf32
-- as DX10 R16G16B16A16_UNORM / R32G32B32A32_FLOAT / R16G16B16A16_FLOAT; optional mip chains (box filter) and the
-- frames as a texture array or a cube map. Not supported: planar video formats (NV12, P010, ...), palettes (P8),
-- 1-bit R1_UNORM, the depth-stencil formats with stencil channels, BC encoders other than 1 / 3 / 4 / 5.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Sniff = require("@rosetta/core/Sniff")
local Types = require("@rosetta/Types")
local Bcn = require("@rosetta/codecs/image/Bcn")
local Texel = require("@rosetta/codecs/image/Texel")
local Texture = require("@rosetta/codecs/image/Texture")
-- ------------------------------------------------------------------------------------------------ contract
local Dds = {
name = "dds",
category = "image",
extensions = { "dds" },
mime = { "image/vnd-ms.dds", "image/x-dds" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Bcn", "codecs/image/Texel", "codecs/image/Texture" },
caps = { decode = true, encode = true, alpha = true, float = true, mipmaps = true, cubemap = true, compressed = { "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7" } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
native: boolean?, -- keep rgbaf32 / rgba16 for float / 16-bit / BC6H sources (default false: rgba8)
mips: boolean?, -- decode the smaller mip levels of the first surface into img.meta.mipmaps (default false)
surfaces: boolean?, -- decode every face / layer / slice into img.frames (default true)
maxPixels: number?, -- refuse larger images (default 2^26, counted over every decoded surface)
}
export type EncodeOptions = {
pixelFormat: ("rgba8" | "bgra8" | "bc1" | "bc3" | "bc4" | "bc5" | "rgba16" | "rgba16f" | "rgba32f")?, -- default:
-- rgba8 for rgba8 images, rgba16 / rgba32f for rgba16 / rgbaf32 ones
mips: boolean?, -- write a full mip chain (default false)
dx10: boolean?, -- always write the DX10 header (default: only when the format needs it, or for arrays)
cube: boolean?, -- write img.frames (6) as a cube map (default: when img.meta.layout == "cube")
alphaThreshold: number?, -- BC1: alpha below this is transparent (default 128)
}
-- ------------------------------------------------------------------------------------------------ constants
-- DXGI_FORMAT -> texture format name, sRGB
local DXGI: { [number]: string } = {
[1] = "rgba32f", [2] = "rgba32f", [3] = "rgba32ui", [4] = "rgba32i",
[5] = "rgb32f", [6] = "rgb32f", [7] = "rgb32ui", [8] = "rgb32i",
[9] = "rgba16", [10] = "rgba16f", [11] = "rgba16", [12] = "rgba16ui", [13] = "rgba16s", [14] = "rgba16i",
[15] = "rg32f", [16] = "rg32f", [17] = "rg32ui", [18] = "rg32i",
[23] = "rgb10a2", [24] = "rgb10a2", [26] = "r11g11b10f",
[27] = "rgba8", [28] = "rgba8", [29] = "rgba8", [30] = "rgba8ui", [31] = "rgba8s", [32] = "rgba8i",
[33] = "rg16", [34] = "rg16f", [35] = "rg16", [36] = "rg16ui", [37] = "rg16s", [38] = "rg16i",
[39] = "r32f", [40] = "r32f", [41] = "r32f", [42] = "r32ui", [43] = "r32i",
[48] = "rg8", [49] = "rg8", [50] = "rg8ui", [51] = "rg8s", [52] = "rg8i",
[53] = "r16", [54] = "r16f", [55] = "r16", [56] = "r16", [57] = "r16ui", [58] = "r16s", [59] = "r16i",
[60] = "r8", [61] = "r8", [62] = "r8ui", [63] = "r8s", [64] = "r8i", [65] = "a8",
[67] = "rgb9e5", [68] = "rgbg", [69] = "grgb",
[70] = "bc1", [71] = "bc1", [72] = "bc1", [73] = "bc2", [74] = "bc2", [75] = "bc2", [76] = "bc3", [77] = "bc3", [78] = "bc3",
[79] = "bc4", [80] = "bc4", [81] = "bc4s", [82] = "bc5", [83] = "bc5", [84] = "bc5s",
[85] = "b5g6r5", [86] = "b5g5r5a1", [87] = "bgra8", [88] = "bgrx8", [90] = "bgra8", [91] = "bgra8", [92] = "bgrx8", [93] = "bgrx8",
[94] = "bc6h", [95] = "bc6h", [96] = "bc6hs", [97] = "bc7", [98] = "bc7", [99] = "bc7",
[100] = "ayuv", [107] = "yuy2", [115] = "b4g4r4a4", [191] = "a4b4g4r4",
}
local SRGB = { [29] = true, [72] = true, [75] = true, [78] = true, [91] = true, [93] = true, [99] = true }
-- legacy FourCC codes (strings and D3DFMT numbers)
local FOURCC: { [string]: string } = {
DXT1 = "bc1", DXT2 = "bc2", DXT3 = "bc2", DXT4 = "bc3", DXT5 = "bc3", RXGB = "bc3",
ATI1 = "bc4", BC4U = "bc4", BC4S = "bc4s", ATI2 = "bc5", BC5U = "bc5", BC5S = "bc5s",
YUY2 = "yuy2", UYVY = "uyvy", RGBG = "rgbg", GRGB = "grgb",
}
local D3DFMT: { [number]: string } = {
[36] = "rgba16", [110] = "rgba16s", [111] = "r16f", [112] = "rg16f", [113] = "rgba16f",
[114] = "r32f", [115] = "rg32f", [116] = "rgba32f", [117] = "rg8s", [60] = "rg8s", [63] = "rgba8s", [64] = "rg16s",
}
local FACES = { "+x", "-x", "+y", "-y", "+z", "-z" }
local MAGIC = "DDS "
local DDSD_MIPMAPCOUNT, DDSD_DEPTH = 0x20000, 0x800000
local DDPF_ALPHAPIXELS, DDPF_ALPHA, DDPF_FOURCC, DDPF_RGB, DDPF_LUMINANCE, DDPF_BUMPDUDV = 0x1, 0x2, 0x4, 0x40, 0x20000, 0x80000
local CAPS2_CUBEMAP, CAPS2_VOLUME = 0x200, 0x200000
local MISC_CUBE = 0x4
local band = bit32.band
-- ------------------------------------------------------------------------------------------------ sniff
function Dds.sniff(r: Bytes.Reader): number
return math.max(Sniff.magic(r, MAGIC .. "\124\0\0\0"), Sniff.magic(r, MAGIC, 0, 0.6))
end
-- ------------------------------------------------------------------------------------------------ decode
export type Info = {
width: number,
height: number,
depth: number,
mips: number,
format: string, -- the texture format name (codecs/image/Texture)
layout: string, -- "2d" | "cube" | "array" | "volume"
layers: number,
faces: { string }, -- cube faces present (in file order), else { }
srgb: boolean,
dxgi: number?,
fourcc: string?,
dataOffset: number, -- relative to the file start
alphaMode: number?,
premultiplied: boolean?,
masked: Texel.Desc?, -- legacy bit-mask formats (format = "masked" unless the masks have a name)
}
local function u32(b: buffer, o: number): number
return buffer.readu32(b, o)
end
-- info(r) -> Info | nil, Err (the headers only)
function Dds.info(r: Bytes.Reader): (Info?, Err.Err?)
local b, o, n = r.buf, r.base, r.limit - r.base
if n < 128 or buffer.readstring(b, o, 4) ~= MAGIC then
return nil, Err.new(if n < 128 and n >= 4 and buffer.readstring(b, o, 4) == MAGIC then Err.TRUNCATED else Err.CORRUPT, "not a DDS file", o)
end
if u32(b, o + 4) ~= 124 then
return nil, Err.new(Err.CORRUPT, "bad header size " .. u32(b, o + 4), o + 4)
end
local flags = u32(b, o + 8)
local h, w = u32(b, o + 12), u32(b, o + 16)
local depth = u32(b, o + 24)
local mips = u32(b, o + 28)
local pfFlags, fourccNum = u32(b, o + 80), u32(b, o + 84)
local bitCount = u32(b, o + 88)
local rm, gm, bm, am = u32(b, o + 92), u32(b, o + 96), u32(b, o + 100), u32(b, o + 104)
local caps2 = u32(b, o + 112)
if w == 0 or h == 0 or w > 65536 or h > 65536 then
return nil, Err.new(Err.CORRUPT, string.format("bad size %d x %d", w, h), o + 12)
end
if band(flags, DDSD_MIPMAPCOUNT) == 0 and mips > 1 and band(u32(b, o + 108), 0x400000) == 0 then
mips = 1 -- a count without the flag or the caps bit: some writers leave garbage
end
mips = math.max(1, mips)
local maxMips = 1
do
local m = math.max(w, h, depth)
while m > 1 do
m //= 2
maxMips += 1
end
end
if mips > maxMips then
return nil, Err.new(Err.CORRUPT, "more mip levels than the size allows", o + 28)
end
local info: Info = {
width = w,
height = h,
depth = 1,
mips = mips,
format = "",
layout = "2d",
layers = 1,
faces = {},
srgb = false,
dataOffset = 128,
}
local volume = band(caps2, CAPS2_VOLUME) ~= 0 or band(flags, DDSD_DEPTH) ~= 0 and depth > 1
if band(pfFlags, DDPF_FOURCC) ~= 0 then
local fourcc = buffer.readstring(b, o + 84, 4)
if fourcc == "DX10" then
if n < 148 then
return nil, Err.new(Err.TRUNCATED, "missing DX10 header", o + 128)
end
local dxgi, dim, misc, arr, misc2 = u32(b, o + 128), u32(b, o + 132), u32(b, o + 136), u32(b, o + 140), u32(b, o + 144)
info.dxgi = dxgi
info.dataOffset = 148
local name = DXGI[dxgi]
if not name then
return nil, Err.new(Err.UNSUPPORTED, "DXGI format " .. dxgi, o + 128)
end
info.format = name
info.srgb = SRGB[dxgi] == true
info.alphaMode = band(misc2, 7)
info.premultiplied = band(misc2, 7) == 2
info.layers = math.max(1, arr)
if info.layers > 4096 then
return nil, Err.new(Err.CORRUPT, "array size " .. arr, o + 140)
end
if dim == 4 then
volume = true
elseif dim ~= 2 and dim ~= 3 and dim ~= 0 then
return nil, Err.new(Err.CORRUPT, "bad resource dimension " .. dim, o + 132)
else
volume = false
end
if band(misc, MISC_CUBE) ~= 0 then
info.layout = "cube"
info.faces = table.clone(FACES)
elseif info.layers > 1 then
info.layout = "array"
end
else
info.fourcc = fourcc
local name = FOURCC[fourcc] or D3DFMT[fourccNum]
if not name then
return nil, Err.new(Err.UNSUPPORTED, "FourCC " .. string.format("%q", fourcc), o + 84)
end
info.format = name
info.premultiplied = fourcc == "DXT2" or fourcc == "DXT4"
end
elseif band(pfFlags, DDPF_RGB + DDPF_LUMINANCE + DDPF_ALPHA + DDPF_BUMPDUDV + 0x200) ~= 0 then
local bytes = bitCount // 8
if bitCount % 8 ~= 0 or bytes < 1 or bytes > 4 then
return nil, Err.new(Err.UNSUPPORTED, bitCount .. "-bit pixels", o + 88)
end
local lum = band(pfFlags, DDPF_LUMINANCE) ~= 0
local alphaOnly = band(pfFlags, DDPF_ALPHA) ~= 0 and band(pfFlags, DDPF_RGB + DDPF_LUMINANCE) == 0
local a = if band(pfFlags, DDPF_ALPHAPIXELS + DDPF_ALPHA) ~= 0 then am else 0
local d
if alphaOnly then
d = Texel.masked(bytes, 0, 0, 0, if am ~= 0 then am else 0xFF)
elseif band(pfFlags, DDPF_BUMPDUDV) ~= 0 then
d = nil -- signed bump maps: handled by the D3DFMT names when they come as FourCC
else
d = Texel.masked(bytes, rm, if lum then 0 else gm, if lum then 0 else bm, a, lum)
end
if not d then
return nil, Err.new(Err.UNSUPPORTED, "pixel format masks", o + 92)
end
-- the common masks map onto named texel formats (fast paths, sane names)
local key = string.format("%d:%x:%x:%x:%x:%s", bitCount, rm, gm, bm, a, tostring(lum))
local named = ({
["32:ff:ff00:ff0000:ff000000:false"] = "rgba8",
["32:ff0000:ff00:ff:ff000000:false"] = "bgra8",
["32:ff0000:ff00:ff:0:false"] = "bgrx8",
["32:ff:ff00:ff0000:0:false"] = "rgbx8",
["24:ff0000:ff00:ff:0:false"] = "bgr8",
["24:ff:ff00:ff0000:0:false"] = "rgb8",
["8:ff:0:0:0:true"] = "l8",
["16:ffff:0:0:0:true"] = "l16",
} :: { [string]: string })[key]
info.format = named or "masked"
info.masked = d
else
return nil, Err.new(Err.UNSUPPORTED, string.format("pixel format flags 0x%x", pfFlags), o + 80)
end
if volume then
info.layout = "volume"
info.depth = math.max(1, depth)
if info.depth > 2048 then
return nil, Err.new(Err.CORRUPT, "depth " .. depth, o + 24)
end
elseif band(caps2, CAPS2_CUBEMAP) ~= 0 and not info.dxgi then
info.layout = "cube"
for i, f in FACES do
if band(caps2, bit32.lshift(0x400, i - 1)) ~= 0 then
table.insert(info.faces, f)
end
end
if #info.faces == 0 then
info.faces = table.clone(FACES)
end
end
return info, nil
end
-- the bytes of one surface of format f
local function surfaceSize(info: any, w: number, h: number): number
if info.format == "masked" then
return (info.masked :: Texel.Desc).bytes * w * h
end
return Texture.size(info.format, w, h) :: number
end
function Dds.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local info, ierr = Dds.info(r)
if not info then
return nil, ierr
end
local native = opts and opts.native or false
local wantMips = opts and opts.mips or false
local wantAll = not (opts and opts.surfaces == false)
local maxPixels = opts and opts.maxPixels or 2 ^ 26
local b, base = r.buf, r.base
local p = base + info.dataOffset
local limit = r.limit
local count = if info.layout == "cube" then #info.faces * info.layers else info.layers
local list: { Texture.Surface } = {}
local pixels = 0
local stop = false
for layer = 0, count - 1 do
local w, h, d = info.width, info.height, info.depth
for level = 0, info.mips - 1 do
local size = surfaceSize(info, w, h)
for slice = 0, d - 1 do
local want = (level == 0 and (wantAll or (layer == 0 and slice == 0))) or (wantMips and layer == 0 and slice == 0)
if want then
if p + size > limit then
if level > 0 or layer > 0 or slice > 0 then
stop = true -- a cut mip chain / later surface: keep what decoded
break
end
return nil, Err.new(Err.TRUNCATED, "surface data runs past the end", p)
end
pixels += w * h
if pixels > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("over the %d pixel limit", maxPixels))
end
local px, pf
if info.format == "masked" then
px, pf = Texel.decode(info.masked :: Texel.Desc, b, p, w, h, native)
else
px, pf = Texture.decode(info.format, b, p, w, h, native)
end
if not px then
return nil, Err.from(pf, p)
end
local face = if info.layout == "cube" then layer % #info.faces else 0
table.insert(list, { level = level, layer = layer, face = face, slice = slice, image = Texture.image(px, pf, w, h) })
end
p += size
end
if stop then
break
end
w, h, d = math.max(1, w // 2), math.max(1, h // 2), math.max(1, d // 2)
end
if stop then
break
end
end
local img = Texture.assemble(list, info.layout)
if not img then
return nil, Err.new(Err.TRUNCATED, "no surface data", base + info.dataOffset)
end
if info.layout == "cube" then
img.meta.faces = info.faces
end
if info.srgb then
img.meta.colorSpace = "srgb"
elseif string.find(info.format, "f$") or info.format == "bc6h" or info.format == "bc6hs" or info.format == "rgb9e5" then
img.meta.colorSpace = "linear"
end
img.meta.source = {
format = "dds",
pixelFormat = info.format,
dxgi = info.dxgi,
fourcc = info.fourcc,
mips = info.mips,
layers = info.layers,
depth = info.depth,
premultiplied = info.premultiplied,
}
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local BYTES_PF: { [string]: number } = { rgba8 = 4, bgra8 = 4, rgba16 = 8, rgba16f = 8, rgba32f = 16 }
local DX10_OUT: { [string]: number } = { rgba8 = 28, bgra8 = 87, bc1 = 71, bc3 = 77, bc4 = 80, bc5 = 83, rgba16 = 11, rgba16f = 10, rgba32f = 2 }
-- the surface bytes of one image in format f
local function surface(img: Types.Image, f: string, opts: EncodeOptions?): (buffer?, Err.Err?)
local w, h, px = img.width, img.height, img.pixels
if f == "bc1" or f == "bc3" or f == "bc4" or f == "bc5" then
local blocks, err = Bcn.encode(f, px, w, h, opts and { alphaThreshold = opts.alphaThreshold } or nil)
if not blocks then
return nil, Err.new(Err.ARG, tostring(err))
end
return blocks, nil
elseif f == "bgra8" then
local out = buffer.create(w * h * 4)
for i = 0, w * h - 1 do
local v = buffer.readu32(px, i * 4)
buffer.writeu32(out, i * 4, band(v, 0xFF00FF00) + band(bit32.rshift(v, 16), 0xFF) + bit32.lshift(band(v, 0xFF), 16))
end
return out, nil
elseif f == "rgba16f" then
return Texture.toHalf(px, w * h), nil
end
local out = buffer.create(w * h * (BYTES_PF[f] :: number))
buffer.copy(out, 0, px, 0, buffer.len(out))
return out, nil
end
local function writeHeader(out: Bytes.Writer, w: number, h: number, f: string, mips: number, dx10: boolean, layers: number, cube: boolean)
local blockFmt = f == "bc1" or f == "bc3" or f == "bc4" or f == "bc5"
out:string(MAGIC)
out:u32le(124)
local flags = 0x1007 + (if mips > 1 then DDSD_MIPMAPCOUNT else 0) + (if blockFmt then 0x80000 else 0x8)
out:u32le(flags)
out:u32le(h)
out:u32le(w)
out:u32le(if blockFmt then Texture.size(f, w, h) :: number else w * (BYTES_PF[f] :: number))
out:u32le(0)
out:u32le(if mips > 1 then mips else 0)
out:fill(0, 44)
-- DDS_PIXELFORMAT
out:u32le(32)
if dx10 then
out:u32le(DDPF_FOURCC)
out:string("DX10")
out:fill(0, 20)
elseif blockFmt then
out:u32le(DDPF_FOURCC)
out:string(({ bc1 = "DXT1", bc3 = "DXT5", bc4 = "ATI1", bc5 = "ATI2" } :: { [string]: string })[f])
out:fill(0, 20)
else
out:u32le(DDPF_RGB + DDPF_ALPHAPIXELS)
out:u32le(0)
out:u32le(32)
if f == "bgra8" then
out:u32le(0xFF0000)
out:u32le(0xFF00)
out:u32le(0xFF)
else
out:u32le(0xFF)
out:u32le(0xFF00)
out:u32le(0xFF0000)
end
out:u32le(0xFF000000)
end
out:u32le(0x1000 + (if mips > 1 then 0x400008 else 0) + (if cube then 0x8 else 0))
out:u32le(if cube then 0xFE00 else 0)
out:fill(0, 12)
if dx10 then
out:u32le(DX10_OUT[f])
out:u32le(3)
out:u32le(if cube then MISC_CUBE else 0)
out:u32le(if cube then layers // 6 else layers)
out:u32le(0)
end
end
function Dds.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or img.width < 1 or img.height < 1 then
return nil, Err.new(Err.ARG, "needs an Image")
end
local pf = img.format
if pf ~= "rgba8" and pf ~= "rgba16" and pf ~= "rgbaf32" then
return nil, Err.new(Err.ARG, "needs an rgba8, rgba16 or rgbaf32 Image (got " .. tostring(pf) .. ")")
end
local f: string = (opts and opts.pixelFormat) or (if pf == "rgba8" then "rgba8" elseif pf == "rgba16" then "rgba16" else "rgba32f")
if not DX10_OUT[f] then
return nil, Err.new(Err.ARG, "unknown pixelFormat " .. tostring(f))
end
local needs = if f == "rgba16" then "rgba16" elseif f == "rgba16f" or f == "rgba32f" then "rgbaf32" else "rgba8"
if pf ~= needs then
return nil, Err.new(Err.ARG, string.format("pixelFormat %s needs an %s Image", f, needs))
end
-- surfaces: the frames (array / cube faces) or the image
local images: { Types.Image } = { img }
if img.frames and #img.frames > 1 then
images = {}
for i, fr in img.frames do
local fi = fr.image
if type(fi) ~= "table" or fi.width ~= img.width or fi.height ~= img.height or fi.format ~= pf then
return nil, Err.new(Err.ARG, "frame " .. i .. ": every surface needs the image's size and pixel format")
end
images[i] = fi
end
end
local cube = if opts and opts.cube ~= nil then opts.cube else (img.meta and img.meta.layout == "cube")
if cube and #images % 6 ~= 0 then
return nil, Err.new(Err.ARG, "a cube map needs 6 faces per layer")
end
local dx10 = (opts and opts.dx10) or f == "rgba16" or f == "rgba16f" or f == "rgba32f" or (#images > 1 and not (cube and #images == 6))
local mips = 1
if opts and opts.mips then
local m = math.max(img.width, img.height)
while m > 1 do
m //= 2
mips += 1
end
end
local out = Bytes.writer(img.width * img.height * 4 * #images + 200)
writeHeader(out, img.width, img.height, f, mips, dx10, #images, cube == true)
for _, im in images do
local level = im
for m = 1, mips do
local data, err = surface(level, f, opts)
if not data then
return nil, err
end
out:bytes(data)
if m < mips then
level = Texture.halve(level)
end
end
end
return out:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ extras
Dds.DXGI = DXGI
return Dds
+117
View File
@@ -0,0 +1,117 @@
--!strict
--!native
--!optimize 2
-- image/exr/Codec: the OpenEXR byte-level codecs (from the OpenEXR file layout document and ImfZip / ImfRle, BSD-3-
-- Clause): RLE and ZIP / ZIPS decode (run lengths or zlib, then the delta predictor and the two-half byte interleave),
-- ZIP encode, and the per-line channel sample conversion to floats. Never throws.
local Deflate = require("@rosetta/codecs/compress/Deflate")
local Half = require("@rosetta/codecs/image/Half")
local Codec = {}
local readu8, writeu8, readi8, readu16, readu32, readf32, writef32 = buffer.readu8, buffer.writeu8, buffer.readi8, buffer.readu16, buffer.readu32, buffer.readf32, buffer.writef32
local HALF = Half.TABLE
-- undoes the predictor and the interleave of t (n bytes) -> a new buffer
local function reconstruct(t: buffer, n: number): buffer
local prev = if n > 0 then readu8(t, 0) else 0
for i = 1, n - 1 do
prev = (prev + readu8(t, i) - 128) % 256
writeu8(t, i, prev)
end
local out = buffer.create(n)
local half = (n + 1) // 2
for i = 0, half - 1 do
writeu8(out, i * 2, readu8(t, i))
end
for i = 0, n - half - 1 do
writeu8(out, i * 2 + 1, readu8(t, half + i))
end
return out
end
-- rle(src, p, n, outSize) -> the raw block | nil, message
function Codec.rle(src: buffer, p: number, n: number, outSize: number): (buffer?, string?)
local t = buffer.create(outSize)
local o, stop = 0, p + n
while p < stop do
local c = readi8(src, p)
p += 1
if c < 0 then
local cnt = -c
if p + cnt > stop or o + cnt > outSize then
return nil, "bad RLE run"
end
buffer.copy(t, o, src, p, cnt)
p += cnt
o += cnt
else
if p >= stop or o + c + 1 > outSize then
return nil, "bad RLE run"
end
buffer.fill(t, o, readu8(src, p), c + 1)
p += 1
o += c + 1
end
end
if o ~= outSize then
return nil, "RLE data too short"
end
return reconstruct(t, outSize), nil
end
-- zip(src, p, n, outSize) -> the raw block | nil, message (ZIP and ZIPS)
function Codec.unzip(src: buffer, p: number, n: number, outSize: number): (buffer?, string?)
local t, err = Deflate.zlib(src, p, n, outSize)
if not t then
return nil, tostring(err)
end
if buffer.len(t) ~= outSize then
return nil, "zlib block has the wrong size"
end
return reconstruct(t, outSize), nil
end
-- zipEncode(raw, level) -> the compressed block (interleave, predictor, zlib)
function Codec.zip(raw: buffer, level: number): buffer
local n = buffer.len(raw)
local t = buffer.create(n)
local half = (n + 1) // 2
for i = 0, n - 1 do
local v = readu8(raw, i)
if i % 2 == 0 then
writeu8(t, i // 2, v)
else
writeu8(t, half + i // 2, v)
end
end
local prev = if n > 0 then readu8(t, 0) else 0
for i = 1, n - 1 do
local v = readu8(t, i)
writeu8(t, i, (v - prev + 384) % 256)
prev = v
end
return Deflate.zlibCompress(t, { level = level }) :: buffer
end
-- samples(src, p, count, kind, dst, d, step) -> reads count samples of kind (0 uint, 1 half, 2 float) at p into
-- dst (f32) at byte offset d, step bytes apart; returns the source offset after them
function Codec.samples(src: buffer, p: number, count: number, kind: number, dst: buffer, d: number, step: number): number
if kind == 1 then
for i = 0, count - 1 do
writef32(dst, d + i * step, HALF[readu16(src, p + i * 2)])
end
return p + count * 2
elseif kind == 2 then
for i = 0, count - 1 do
writef32(dst, d + i * step, readf32(src, p + i * 4))
end
else
for i = 0, count - 1 do
writef32(dst, d + i * step, readu32(src, p + i * 4))
end
end
return p + count * 4
end
return Codec
+367
View File
@@ -0,0 +1,367 @@
--!strict
--!native
--!optimize 2
-- image/exr/Piz: OpenEXR's PIZ decompressor (written from the OpenEXR 3.x sources' algorithm description: ImfPizCompressor
-- / ImfHuf / ImfWav, BSD-3-Clause, licenses/openexr-LICENSE.md): the range bitmap and its reverse LUT, the Huffman
-- stream (packed code lengths, canonical codes, the run-length symbol), the 2-D Haar wavelet (14- and 16-bit
-- variants) per channel plane, then the planes rearranged into scanlines. Never throws: nil, message on bad data.
local Piz = {}
local readu8, readu16, writeu16, readu32 = buffer.readu8, buffer.readu16, buffer.writeu16, buffer.readu32
local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift
local USHORT_RANGE, BITMAP_SIZE = 65536, 8192
local HUF_ENCSIZE = 65537
local DECBITS = 14
local SHORT_ZEROCODE_RUN, LONG_ZEROCODE_RUN, SHORTEST_LONG_RUN = 59, 63, 6
-- ------------------------------------------------------------------------------------------------ Huffman
-- the canonical code table: lengths[i] and codes[i] for symbols im..iM (1-based tables: symbol s at s + 1)
local function unpackTable(src: buffer, p: number, limit: number, im: number, iM: number, len: { number }): number?
local c, lc = 0, 0
local function bits(n: number): number?
while lc < n do
if p >= limit then
return nil
end
c = c * 256 + readu8(src, p)
p += 1
lc += 8
end
lc -= n
local v = c // 2 ^ lc
c -= v * 2 ^ lc
return v
end
local i = im
while i <= iM do
local l = bits(6)
if not l then
return nil
end
if l == LONG_ZEROCODE_RUN then
local z = bits(8)
if not z then
return nil
end
z += SHORTEST_LONG_RUN
if i + z > iM + 1 then
return nil
end
for k = i, i + z - 1 do
len[k + 1] = 0
end
i += z
elseif l >= SHORT_ZEROCODE_RUN then
local z = l - SHORT_ZEROCODE_RUN + 2
if i + z > iM + 1 then
return nil
end
for k = i, i + z - 1 do
len[k + 1] = 0
end
i += z
else
len[i + 1] = l
i += 1
end
end
return p
end
-- hufUncompress: nRaw u16 values from [p, p + n) into out (a buffer of u16) | nil, message
local function huffman(src: buffer, p: number, n: number, out: buffer, nRaw: number): string?
if n == 0 then
return if nRaw == 0 then nil else "empty Huffman data"
end
if n < 20 then
return "truncated Huffman header"
end
local im, iM, nBits = readu32(src, p), readu32(src, p + 4), readu32(src, p + 12)
if im >= HUF_ENCSIZE or iM >= HUF_ENCSIZE or im > iM then
return "bad Huffman symbol range"
end
local limit = p + n
local len = table.create(HUF_ENCSIZE, 0)
local q = unpackTable(src, p + 20, limit, im, iM, len)
if not q then
return "bad Huffman table"
end
if q + (nBits + 7) // 8 > limit then
return "truncated Huffman data"
end
-- canonical codes (OpenEXR's order: longest codes get the smallest values)
local count = table.create(59, 0)
for s = im, iM do
local l = len[s + 1]
if l > 58 then
return "bad Huffman code length"
end
count[l + 1] += 1
end
local start = table.create(59, 0)
local c = 0
for l = 58, 1, -1 do
local nc = (c + count[l + 1]) // 2
start[l + 1] = c
c = nc
end
local fast = buffer.create(lshift(1, DECBITS) * 4) -- (symbol + 1) * 64 + length; 0 = long or invalid
local long: { [number]: { [number]: number } } = {}
local maxLong = 0
for s = im, iM do
local l = len[s + 1]
if l > 0 then
local code = start[l + 1]
start[l + 1] = code + 1
if l <= DECBITS then
local base = code * 2 ^ (DECBITS - l)
local v = (s + 1) * 64 + l
for k = base, base + 2 ^ (DECBITS - l) - 1 do
if k < lshift(1, DECBITS) then
buffer.writeu32(fast, k * 4, v)
end
end
else
if l > 52 then
return "unsupported: Huffman code longer than 52 bits"
end
local t = long[l]
if not t then
t = {}
long[l] = t
end
t[code] = s
maxLong = math.max(maxLong, l)
end
end
end
-- decode MSB-first from a zero-padded copy
local nbytes = (nBits + 7) // 8
local data = buffer.create(nbytes + 8)
buffer.copy(data, 0, src, q, nbytes)
local bp = 0
local o = 0
local rlc = iM
local mask = lshift(1, DECBITS) - 1
while bp < nBits do
local byte = rshift(bp, 3)
local w = bit32.byteswap(readu32(data, byte))
local peek = band(rshift(w, 32 - DECBITS - band(bp, 7)), mask)
local e = readu32(fast, peek * 4)
local sym: number, l: number = 0, 0
if e ~= 0 then
sym = e // 64 - 1
l = band(e, 63)
else
-- a long code: bit by bit from length 15
sym = -1
local code = 0
for k = 0, maxLong - 1 do
local bitAt = bp + k
code = code * 2 + band(rshift(readu8(data, rshift(bitAt, 3)), 7 - band(bitAt, 7)), 1)
if k + 1 > DECBITS then
local t = long[k + 1]
local found: number? = if t then t[code] else nil
if found then
sym = found
l = k + 1
break
end
end
end
if sym < 0 then
return "invalid Huffman code"
end
end
bp += l
if bp > nBits then
return "Huffman code past the end of the data"
end
if sym == rlc then
if bp + 8 > nBits then
return "truncated run length"
end
local b2 = bit32.byteswap(readu32(data, rshift(bp, 3)))
local cs = band(rshift(b2, 24 - band(bp, 7)), 255)
bp += 8
if o + cs > nRaw then
return "too much Huffman data"
end
if o == 0 then
return "run length at the start"
end
local s = readu16(out, (o - 1) * 2)
for _ = 1, cs do
writeu16(out, o * 2, s)
o += 1
end
else
if o >= nRaw then
return "too much Huffman data"
end
writeu16(out, o * 2, sym)
o += 1
end
end
if o ~= nRaw then
return "not enough Huffman data"
end
return nil
end
-- ------------------------------------------------------------------------------------------------ wavelet
-- the inverse 2-D Haar wavelet over n x ny u16 values at element offset base, strides ox / oy (in elements)
local function wav2Decode(t: buffer, base: number, nx: number, ox: number, ny: number, oy: number, mx: number)
local w14 = mx < 16384
local n = math.min(nx, ny)
local p = 1
while p <= n do
p *= 2
end
p //= 2
local p2 = p
p //= 2
local function dec(l: number, h: number): (number, number)
if w14 then
local ls = if l >= 32768 then l - 65536 else l
local hs = if h >= 32768 then h - 65536 else h
local ai = ls + hs % 2 + hs // 2
return ai % 65536, (ai - hs) % 65536
end
local bb = (l - rshift(h, 1)) % 65536
return (h + bb - 32768) % 65536, bb
end
while p >= 1 do
local oy1, oy2, ox1, ox2 = oy * p, oy * p2, ox * p, ox * p2
local py = base
local ey = base + oy * (ny - p2)
while py <= ey do
local px = py
local ex = py + ox * (nx - p2)
while px <= ex do
local p01 = px + ox1
local p10 = px + oy1
local p11 = p10 + ox1
local i00, i10 = dec(readu16(t, px * 2), readu16(t, p10 * 2))
local i01, i11 = dec(readu16(t, p01 * 2), readu16(t, p11 * 2))
local a, b = dec(i00, i01)
writeu16(t, px * 2, a)
writeu16(t, p01 * 2, b)
local c, d = dec(i10, i11)
writeu16(t, p10 * 2, c)
writeu16(t, p11 * 2, d)
px += ox2
end
if band(nx, p) ~= 0 then
local p10 = px + oy1
local a, b = dec(readu16(t, px * 2), readu16(t, p10 * 2))
writeu16(t, px * 2, a)
writeu16(t, p10 * 2, b)
end
py += oy2
end
if band(ny, p) ~= 0 then
local px = py
local ex = py + ox * (nx - p2)
while px <= ex do
local p01 = px + ox1
local a, b = dec(readu16(t, px * 2), readu16(t, p01 * 2))
writeu16(t, px * 2, a)
writeu16(t, p01 * 2, b)
px += ox2
end
end
p2 = p
p //= 2
end
end
-- ------------------------------------------------------------------------------------------------ decode
export type Chan = { nx: number, ny: number, size: number, ys: number }
-- decode(src, p, n, chans, minY, maxY, outSize) -> the uncompressed block (scanline order) | nil, message.
-- chans: per channel (sorted order) its sample counts nx / ny in the block, size (1 = half, 2 = float / uint) and
-- ySampling.
function Piz.decode(src: buffer, p: number, n: number, chans: { Chan }, minY: number, maxY: number, outSize: number): (buffer?, string?)
local total = 0
for _, c in chans do
total += c.nx * c.ny * c.size
end
if total * 2 ~= outSize then
return nil, "PIZ block size mismatch"
end
local out = buffer.create(outSize)
if total == 0 then
return out, nil
end
local limit = p + n
if p + 4 > limit then
return nil, "truncated PIZ header"
end
local minNZ, maxNZ = readu16(src, p), readu16(src, p + 2)
p += 4
if maxNZ >= BITMAP_SIZE then
return nil, "bad PIZ bitmap range"
end
local bitmap = buffer.create(BITMAP_SIZE)
if minNZ <= maxNZ then
local cnt = maxNZ - minNZ + 1
if p + cnt > limit then
return nil, "truncated PIZ bitmap"
end
buffer.copy(bitmap, minNZ, src, p, cnt)
p += cnt
end
-- reverse LUT
local lut = buffer.create(USHORT_RANGE * 2)
local k = 0
for i = 0, USHORT_RANGE - 1 do
if i == 0 or band(readu8(bitmap, rshift(i, 3)), lshift(1, band(i, 7))) ~= 0 then
writeu16(lut, k * 2, i)
k += 1
end
end
local maxValue = k - 1
if p + 4 > limit then
return nil, "truncated PIZ length"
end
local length = readu32(src, p)
p += 4
if length > limit - p then
return nil, "truncated PIZ data"
end
local tmp = buffer.create(total * 2)
local herr = huffman(src, p, length, tmp, total)
if herr then
return nil, herr
end
local starts = table.create(#chans, 0)
local at = 0
for i, c in chans do
starts[i] = at
for j = 0, c.size - 1 do
wav2Decode(tmp, at + j, c.nx, c.size, c.ny, c.nx * c.size, maxValue)
end
at += c.nx * c.ny * c.size
end
for i = 0, total - 1 do
writeu16(tmp, i * 2, readu16(lut, readu16(tmp, i * 2) * 2))
end
-- planes -> scanlines
local o = 0
local cursor = table.clone(starts)
for y = minY, maxY do
for i, c in chans do
if y % c.ys == 0 then
local cnt = c.nx * c.size
buffer.copy(out, o, tmp, cursor[i] * 2, cnt * 2)
cursor[i] += cnt
o += cnt * 2
end
end
end
return out, nil
end
return Piz
+782
View File
@@ -0,0 +1,782 @@
--!strict
-- image/exr: OpenEXR (the OpenEXR file layout and technical introduction documents, openexr.com; new code, the PIZ
-- decoder written after OpenEXR's algorithm, BSD-3-Clause: licenses/openexr-LICENSE.md). Decode: single-part and
-- multipart files (opts.part: 1-based index or part name; meta.source.parts lists them), scanline and tiled parts
-- (one level, mip-map and rip-map levels: level 0, plus the mip-map levels into img.meta.mipmaps with opts.mips),
-- compression NONE / RLE / ZIPS / ZIP / PIZ, HALF / FLOAT / UINT channels, x / y subsampled channels (nearest), any
-- line order, broken offset tables (rebuilt from the chunks of single-part files). R / G / B / A map to the image
-- (opts.layer = "diffuse" reads diffuse.R ...); a Y-only image is grey; every channel name is in meta.source.channels.
-- The image is the data window (meta.dataWindow / meta.displayWindow keep both boxes). opts.native gives the linear
-- rgbaf32 values; the default rgba8 is a display conversion like image/hdr's: round(clamp(v, 0, 1) ^ (1 / 2.2) * 255)
-- for colour, round(clamp(a, 0, 1) * 255) for alpha.
-- Encode: rgbaf32 (or rgba8 through the inverse curve) as a scanline file, HALF (default) or FLOAT channels, A only
-- when some alpha is not 1, compression NONE, ZIPS or ZIP (default). Not supported: deep data, PXR24 / B44 / B44A /
-- DWAA / DWAB / HTJ2K / ZSTD compression (UNSUPPORTED naming the method), RY / BY chroma (the Y channel is used).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Sniff = require("@rosetta/core/Sniff")
local Types = require("@rosetta/Types")
local Half = require("@rosetta/codecs/image/Half")
local Codec = require("@rosetta/image/exr/Codec")
local Piz = require("@rosetta/image/exr/Piz")
-- ------------------------------------------------------------------------------------------------ contract
local Exr = {
name = "exr",
category = "image",
extensions = { "exr" },
mime = { "image/x-exr", "image/aces" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Half", "codecs/compress/Deflate" },
caps = { decode = true, encode = true, alpha = true, float = true, hdr = true, depths = { 16, 32 }, multipart = true, tiled = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
native: boolean?, -- linear rgbaf32 (default false: rgba8 through a 1 / 2.2 display gamma)
part: (number | string)?, -- multipart files: the part to read (1-based index or name; default 1)
layer: string?, -- read <layer>.R / .G / .B / .A instead of R / G / B / A
mips: boolean?, -- tiled mip-map parts: decode the smaller levels into img.meta.mipmaps (default false)
maxPixels: number?, -- refuse larger images (default 2^26)
}
export type EncodeOptions = {
compression: ("none" | "zips" | "zip")?, -- default "zip"
pixelType: ("half" | "float")?, -- default "half"
alpha: boolean?, -- write A (default: when some alpha is not 1)
level: number?, -- zlib level 1..9 (default 6)
}
-- ------------------------------------------------------------------------------------------------ constants
local MAGIC = "\118\47\49\1"
local COMPRESSION: { [number]: string } = { [0] = "none", "rle", "zips", "zip", "piz", "pxr24", "b44", "b44a", "dwaa", "dwab", "htj2k256", "htj2k32", "zstd" }
local LINES: { [number]: number } = { [0] = 1, 1, 1, 16, 32, 16, 32, 32, 32, 256 }
local GAMMA = 1 / 2.2
local readu8, readu32, readi32, readf32, readstring = buffer.readu8, buffer.readu32, buffer.readi32, buffer.readf32, buffer.readstring
-- ------------------------------------------------------------------------------------------------ sniff
function Exr.sniff(r: Bytes.Reader): number
return Sniff.magic(r, MAGIC)
end
-- ------------------------------------------------------------------------------------------------ decode
type Channel = { name: string, kind: number, linear: boolean, xs: number, ys: number }
type Part = {
attrs: { [string]: any },
channels: { Channel },
compression: number,
box: { number }, -- data window xMin, yMin, xMax, yMax
display: { number },
tiled: boolean,
tiles: { number }?, -- xSize, ySize, mode, rounding
name: string?,
type: string?,
chunks: number,
offsets: { number },
}
local function cstr(b: buffer, p: number, limit: number, max: number): (string?, number)
local q = p
while q < limit and q - p <= max do
if readu8(b, q) == 0 then
return readstring(b, p, q - p), q + 1
end
q += 1
end
return nil, q
end
local function f32(b: buffer, o: number): number
return readf32(b, o)
end
-- one attribute value of a known type
local function value(b: buffer, p: number, size: number, typ: string): any
if typ == "chlist" then
local list: { Channel } = {}
local q, stop = p, p + size
while q < stop and readu8(b, q) ~= 0 do
local name, nq = cstr(b, q, stop, 255)
if not name or nq + 16 > stop then
return nil
end
table.insert(list, { name = name, kind = readi32(b, nq), linear = readu8(b, nq + 4) ~= 0, xs = readi32(b, nq + 8), ys = readi32(b, nq + 12) })
q = nq + 16
end
return list
elseif typ == "compression" or typ == "lineOrder" or typ == "envmap" or typ == "deepImageState" then
return if size >= 1 then readu8(b, p) else nil
elseif typ == "box2i" then
return if size >= 16 then { readi32(b, p), readi32(b, p + 4), readi32(b, p + 8), readi32(b, p + 12) } else nil
elseif typ == "box2f" then
return if size >= 16 then { f32(b, p), f32(b, p + 4), f32(b, p + 8), f32(b, p + 12) } else nil
elseif typ == "v2i" then
return if size >= 8 then { readi32(b, p), readi32(b, p + 4) } else nil
elseif typ == "v2f" then
return if size >= 8 then { f32(b, p), f32(b, p + 4) } else nil
elseif typ == "v3f" then
return if size >= 12 then { f32(b, p), f32(b, p + 4), f32(b, p + 8) } else nil
elseif typ == "float" then
return if size >= 4 then f32(b, p) else nil
elseif typ == "double" then
return if size >= 8 then buffer.readf64(b, p) else nil
elseif typ == "int" then
return if size >= 4 then readi32(b, p) else nil
elseif typ == "string" then
return readstring(b, p, size)
elseif typ == "tiledesc" then
if size < 9 then
return nil
end
local m = readu8(b, p + 8)
return { readu32(b, p), readu32(b, p + 4), m % 16, m // 16 }
elseif typ == "chromaticities" then
if size < 32 then
return nil
end
local t = {}
for i = 0, 7 do
t[i + 1] = f32(b, p + i * 4)
end
return t
end
local raw = buffer.create(size)
buffer.copy(raw, 0, b, p, size)
return raw
end
-- the attributes of one header from p -> attrs, the offset after its terminating NUL | nil, Err
local function header(b: buffer, p: number, limit: number): ({ [string]: any }?, number, Err.Err?)
local attrs: { [string]: any } = {}
local types: { [string]: string } = {}
while true do
if p >= limit then
return nil, p, Err.new(Err.TRUNCATED, "header runs past the end", p)
end
if readu8(b, p) == 0 then
attrs._types = types
return attrs, p + 1, nil
end
local name, q = cstr(b, p, limit, 255)
if not name then
return nil, p, Err.new(Err.CORRUPT, "bad attribute name", p)
end
local typ, q2 = cstr(b, q, limit, 255)
if not typ then
return nil, p, Err.new(Err.CORRUPT, "bad attribute type", q)
end
if q2 + 4 > limit then
return nil, p, Err.new(Err.TRUNCATED, "attribute size runs past the end", q2)
end
local size = readi32(b, q2)
if size < 0 or q2 + 4 + size > limit then
return nil, p, Err.new(Err.TRUNCATED, "attribute " .. name .. " runs past the end", q2)
end
attrs[name] = value(b, q2 + 4, size, typ)
types[name] = typ
p = q2 + 4 + size
end
end
-- level sizes of a tiled part
local function levelSize(n: number, l: number, roundUp: boolean): number
local d = 2 ^ l
return math.max(1, if roundUp then math.ceil(n / d) else n // d)
end
local function levelCount(w: number, h: number, mode: number, roundUp: boolean): (number, number)
local function count(n: number): number
local c = 1
while levelSize(n, c - 1, roundUp) > 1 do
c += 1
end
return c
end
if mode == 0 then
return 1, 1
elseif mode == 1 then
local c = count(math.max(w, h))
return c, c
end
return count(w), count(h)
end
-- chunk count of a part (single-part files: computed)
local function chunkCount(pt: Part): number
local w, h = pt.box[3] - pt.box[1] + 1, pt.box[4] - pt.box[2] + 1
if not pt.tiled then
return (h + LINES[pt.compression] - 1) // LINES[pt.compression]
end
local t = pt.tiles :: { number }
local tx, ty, mode, roundUp = t[1], t[2], t[3], t[4] == 1
local lx, ly = levelCount(w, h, mode, roundUp)
local n = 0
if mode == 2 then
for y = 0, ly - 1 do
for x = 0, lx - 1 do
n += math.ceil(levelSize(w, x, roundUp) / tx) * math.ceil(levelSize(h, y, roundUp) / ty)
end
end
else
for l = 0, lx - 1 do
n += math.ceil(levelSize(w, l, roundUp) / tx) * math.ceil(levelSize(h, l, roundUp) / ty)
end
end
return n
end
export type Info = { multipart: boolean, tiled: boolean, deep: boolean, parts: { Part }, dataStart: number }
local function parse(r: Bytes.Reader): (Info?, Err.Err?)
local b, base, limit = r.buf, r.base, r.limit
if limit - base < 8 or readstring(b, base, 4) ~= MAGIC then
return nil, Err.new(Err.CORRUPT, "not an OpenEXR file", base)
end
local ver = readu32(b, base + 4)
if ver % 256 ~= 2 then
return nil, Err.new(Err.UNSUPPORTED, "version " .. ver % 256, base + 4)
end
local flags = ver // 256
local tiledFlag, deep, multi = bit32.band(flags, 2) ~= 0, bit32.band(flags, 8) ~= 0, bit32.band(flags, 16) ~= 0
local info: Info = { multipart = multi, tiled = tiledFlag, deep = deep, parts = {}, dataStart = 0 }
local p = base + 8
repeat
local attrs, q, herr = header(b, p, limit)
if not attrs then
return nil, herr
end
p = q
local chans = attrs.channels
local box = attrs.dataWindow
if type(chans) ~= "table" or type(box) ~= "table" or type(attrs.compression) ~= "number" then
return nil, Err.new(Err.CORRUPT, "missing channels / dataWindow / compression", p)
end
local typ = attrs.type
local pt: Part = {
attrs = attrs,
channels = chans,
compression = attrs.compression,
box = box,
display = attrs.displayWindow or box,
tiled = if typ then (typ == "tiledimage" or typ == "deeptile") else tiledFlag,
tiles = attrs.tiles,
name = attrs.name,
type = typ,
chunks = 0,
offsets = {},
}
if pt.tiled and type(pt.tiles) ~= "table" then
return nil, Err.new(Err.CORRUPT, "tiled part without tiles", p)
end
if box[3] < box[1] or box[4] < box[2] or box[3] - box[1] >= 2 ^ 24 or box[4] - box[2] >= 2 ^ 24 then
return nil, Err.new(Err.CORRUPT, "bad data window", p)
end
if pt.tiled and ((pt.tiles :: any)[1] < 1 or (pt.tiles :: any)[2] < 1) then
return nil, Err.new(Err.CORRUPT, "bad tile size", p)
end
for _, c in chans do
if c.xs < 1 or c.ys < 1 or c.kind < 0 or c.kind > 2 then
return nil, Err.new(Err.CORRUPT, "bad channel " .. c.name, p)
end
end
table.insert(info.parts, pt)
if #info.parts > 4096 then
return nil, Err.new(Err.LIMIT, "too many parts", p)
end
until not multi or (p < limit and readu8(b, p) == 0)
if multi then
p += 1
end
-- offset tables
for _, pt in info.parts do
local n = if type(pt.attrs.chunkCount) == "number" then pt.attrs.chunkCount else (if LINES[pt.compression] then chunkCount(pt) else 0)
if n < 0 or n > 2 ^ 24 then
return nil, Err.new(Err.CORRUPT, "bad chunk count", p)
end
pt.chunks = n
if p + n * 8 > limit then
return nil, Err.new(Err.TRUNCATED, "offset table runs past the end", p)
end
for i = 0, n - 1 do
pt.offsets[i + 1] = readu32(b, p + i * 8) + readu32(b, p + i * 8 + 4) * 4294967296
end
p += n * 8
end
info.dataStart = p - base
return info, nil
end
-- info(r) -> { multipart, tiled, deep, parts = { { name, type, attrs, channels, compression, box, ... } } } | nil, Err
function Exr.info(r: Bytes.Reader): (Info?, Err.Err?)
return parse(r)
end
-- bytes of a sample kind
local SIZE = { [0] = 4, 2, 4 }
-- number of multiples of s in [a, b]
local function samples(a: number, b: number, s: number): number
return b // s - (a - 1) // s
end
type Target = { [number]: number } -- channel index -> output component (0..3, 4 = grey)
local function newPlane(pw: number, ph: number): buffer
local px = buffer.create(pw * ph * 16)
for i = 0, pw * ph - 1 do
buffer.writef32(px, i * 16 + 12, 1)
end
return px
end
-- one decompressed block: the lines y0..y1 (absolute), columns x0..x0 + bw - 1 of plane (pw wide, origin ox, oy)
local function block(part: Part, target: Target, data: buffer, dp: number, y0: number, y1: number, x0: number, bw: number, plane: buffer, pw: number, ph: number, ox: number, oy: number): Err.Err?
local p = dp
for y = y0, y1 do
for i, c in part.channels do
if y % c.ys == 0 then
local nx = if c.xs == 1 then bw else samples(x0, x0 + bw - 1, c.xs)
local sz = SIZE[c.kind]
if p + nx * sz > buffer.len(data) then
return Err.new(Err.CORRUPT, "block too short")
end
local k = target[i]
if k ~= nil then
local row = y - oy
if c.xs == 1 and c.ys == 1 and k < 4 then
Codec.samples(data, p, nx, c.kind, plane, (row * pw + (x0 - ox)) * 16 + k * 4, 16)
else
local tmp = buffer.create(nx * 4)
Codec.samples(data, p, nx, c.kind, tmp, 0, 4)
local first = (x0 + c.xs - 1) // c.xs * c.xs
for s = 0, nx - 1 do
local v = buffer.readf32(tmp, s * 4)
local sx = first + s * c.xs
for yy = row, math.min(row + c.ys - 1, ph - 1) do
for xx = sx - ox, math.min(sx - ox + c.xs - 1, pw - 1) do
local o = (yy * pw + xx) * 16
if k == 4 then
buffer.writef32(plane, o, v)
buffer.writef32(plane, o + 4, v)
buffer.writef32(plane, o + 8, v)
else
buffer.writef32(plane, o + k * 4, v)
end
end
end
end
end
end
p += nx * sz
end
end
end
return nil
end
-- the raw bytes of a block (uncompressed size raw)
local function unpack(b: buffer, comp: number, part: Part, p: number, size: number, raw: number, y0: number, y1: number, x0: number, bw: number): (buffer?, number, Err.Err?)
if size == raw or comp == 0 then
if size < raw then
return nil, 0, Err.new(Err.CORRUPT, "short uncompressed block", p)
end
return b, p, nil
end
local out, err
if comp == 1 then
out, err = Codec.rle(b, p, size, raw)
elseif comp == 2 or comp == 3 then
out, err = Codec.unzip(b, p, size, raw)
else
local chans: { Piz.Chan } = {}
for i, c in part.channels do
chans[i] = { nx = samples(x0, x0 + bw - 1, c.xs), ny = samples(y0, y1, c.ys), size = SIZE[c.kind] // 2, ys = c.ys }
end
out, err = Piz.decode(b, p, size, chans, y0, y1, raw)
end
if not out then
return nil, 0, Err.from(err, p)
end
return out, 0, nil
end
local function rawSize(part: Part, y0: number, y1: number, x0: number, bw: number): number
local n = 0
for y = y0, y1 do
for _, c in part.channels do
if y % c.ys == 0 then
n += samples(x0, x0 + bw - 1, c.xs) * SIZE[c.kind]
end
end
end
return n
end
function Exr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local info, perr = parse(r)
if not info then
return nil, perr
end
local b, base, limit = r.buf, r.base, r.limit
local want = opts and opts.part or 1
local pt: Part? = nil
local partIndex = 0
for i, p in info.parts do
if (type(want) == "number" and i == want) or (type(want) == "string" and p.name == want) then
pt, partIndex = p, i
end
end
if not pt then
return nil, Err.new(Err.ARG, "no part " .. tostring(want))
end
local part = pt :: Part
if info.deep or (part.type and string.find(part.type, "deep")) then
return nil, Err.new(Err.UNSUPPORTED, "deep data")
end
local comp: number = part.compression
if comp > 4 then
return nil, Err.new(Err.UNSUPPORTED, "compression " .. (COMPRESSION[comp] or tostring(comp)))
end
local box = part.box
local xMin, yMin, xMax, yMax = box[1], box[2], box[3], box[4]
local w, h = xMax - xMin + 1, yMax - yMin + 1
local maxPixels = opts and opts.maxPixels or 2 ^ 26
if w * h > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
end
-- channel -> output component
local prefix = if opts and opts.layer then opts.layer .. "." else ""
local target: Target = {}
local hasRgb = false
for i, c in part.channels do
local n = c.name
if string.sub(n, 1, #prefix) == prefix then
local s = string.sub(n, #prefix + 1)
local k = if s == "R" or s == "r" then 0 elseif s == "G" or s == "g" then 1 elseif s == "B" or s == "b" then 2 elseif s == "A" or s == "a" then 3 else nil
if k then
target[i] = k
hasRgb = hasRgb or k < 3
end
end
end
if not hasRgb then
for i, c in part.channels do
if c.name == prefix .. "Y" then
target[i] = 4
end
end
end
local multi = info.multipart
-- offsets: single-part tables with holes are rebuilt from the chunk sequence
local offsets = part.offsets
local bad = false
for _, o in offsets do
if o < info.dataStart or base + o + 8 > limit then
bad = true
break
end
end
if bad then
-- rebuild from the chunk sequence (every part's chunks follow the tables; multipart chunks name their part)
offsets = {}
local p = base + info.dataStart
local total = 0
for _, q in info.parts do
total += q.chunks
end
for _ = 1, total do
local pi = 1
local at = p
if multi then
if p + 4 > limit then
break
end
pi = readi32(b, p) + 1
p += 4
end
local q = info.parts[pi]
if not q then
break
end
local head = if q.tiled then 20 else 8
if p + head > limit then
break
end
local size = readi32(b, p + head - 4)
if size < 0 then
break
end
if pi == partIndex then
table.insert(offsets, at - base)
end
p += head + size
end
end
local planes: { [number]: buffer } = { [0] = newPlane(w, h) } -- level -> rgbaf32 pixels
local tiles = part.tiles
local roundUp = tiles ~= nil and tiles[4] == 1
local wantMips = opts and opts.mips and tiles ~= nil and tiles[3] == 1
local lpb = LINES[comp]
for ci, off in offsets do
local p = base + off
if multi then
if p + 4 > limit then
return nil, Err.new(Err.TRUNCATED, "chunk past the end", p)
end
if readi32(b, p) ~= partIndex - 1 then
return nil, Err.new(Err.CORRUPT, "chunk of another part in this part's table", p)
end
p += 4
end
if part.tiled then
if p + 20 > limit then
return nil, Err.new(Err.TRUNCATED, "tile header past the end", p)
end
local tx, ty, lx, ly, size = readi32(b, p), readi32(b, p + 4), readi32(b, p + 8), readi32(b, p + 12), readi32(b, p + 16)
p += 20
local t = tiles :: { number }
local level = if lx == 0 and ly == 0 then 0 elseif wantMips and lx == ly then lx else -1
if level >= 0 then
local lw, lh = levelSize(w, level, roundUp), levelSize(h, level, roundUp)
local x0, y0 = tx * t[1], ty * t[2]
if tx < 0 or ty < 0 or x0 >= lw or y0 >= lh then
return nil, Err.new(Err.CORRUPT, "tile outside the image", p)
end
if size < 0 or p + size > limit then
return nil, Err.new(Err.TRUNCATED, "tile data past the end", p)
end
local bw, bh = math.min(t[1], lw - x0), math.min(t[2], lh - y0)
local plane = planes[level]
if not plane then
plane = newPlane(lw, lh)
planes[level] = plane
end
-- tile coordinates are relative to the level's data window origin
local ax, ay = xMin + x0, yMin + y0
local raw = rawSize(part, ay, ay + bh - 1, ax, bw)
local data, dp, uerr = unpack(b, comp, part, p, size, raw, ay, ay + bh - 1, ax, bw)
if not data then
return nil, uerr
end
local berr = block(part, target, data, dp, ay, ay + bh - 1, ax, bw, plane, lw, lh, xMin, yMin)
if berr then
return nil, berr
end
end
else
if p + 8 > limit then
return nil, Err.new(Err.TRUNCATED, "chunk header past the end", p)
end
local y, size = readi32(b, p), readi32(b, p + 4)
p += 8
if y < yMin or y > yMax or (y - yMin) % lpb ~= 0 then
return nil, Err.new(Err.CORRUPT, "bad scanline block y " .. y, p - 8)
end
if size < 0 or p + size > limit then
if ci > 1 then
break -- a cut file: keep the lines that decoded (meta.truncated)
end
return nil, Err.new(Err.TRUNCATED, "block data past the end", p)
end
local y1 = math.min(y + lpb - 1, yMax)
local raw = rawSize(part, y, y1, xMin, w)
local data, dp, uerr = unpack(b, comp, part, p, size, raw, y, y1, xMin, w)
if not data then
return nil, uerr
end
local berr = block(part, target, data, dp, y, y1, xMin, w, planes[0], w, h, xMin, yMin)
if berr then
return nil, berr
end
end
end
local native = opts and opts.native
local function finish(px: buffer, pw: number, ph: number): Types.Image
if native then
local img = Types.Image.new(0, 0, "rgbaf32")
img.width, img.height, img.pixels = pw, ph, px
return img
end
local img = Types.Image.new(pw, ph, "rgba8")
local o = img.pixels
for i = 0, pw * ph - 1 do
for c = 0, 3 do
local v = buffer.readf32(px, i * 16 + c * 4)
v = if v ~= v or v <= 0 then 0 elseif v >= 1 then 1 else v
buffer.writeu8(o, i * 4 + c, math.floor((if c < 3 then v ^ GAMMA else v) * 255 + 0.5))
end
end
return img
end
local img = finish(planes[0], w, h)
if wantMips then
local mips = {}
local l = 1
while planes[l] do
mips[l] = finish(planes[l], levelSize(w, l, roundUp), levelSize(h, l, roundUp))
l += 1
end
if #mips > 0 then
img.meta.mipmaps = mips
end
end
local names, parts = {}, {}
for i, c in part.channels do
names[i] = c.name
end
for i, p in info.parts do
parts[i] = { name = p.name or "", type = p.type or (if p.tiled then "tiledimage" else "scanlineimage") }
end
img.meta.colorSpace = "linear"
img.meta.dataWindow = { x = xMin, y = yMin, width = w, height = h }
local dw = part.display
img.meta.displayWindow = { x = dw[1], y = dw[2], width = dw[3] - dw[1] + 1, height = dw[4] - dw[2] + 1 }
local attrs = {}
for k, v in part.attrs do
if k ~= "_types" and (type(v) == "string" or type(v) == "number") then
attrs[k] = v
end
end
img.meta.attributes = attrs
local kinds = {}
for i, c in part.channels do
kinds[i] = ({ [0] = "uint", "half", "float" })[c.kind]
end
img.meta.source = {
format = "exr",
compression = COMPRESSION[comp],
channels = names,
pixelTypes = kinds,
part = partIndex,
parts = parts,
tiled = part.tiled,
lineOrder = part.attrs.lineOrder,
bitDepth = if kinds[1] == "half" then 16 else 32,
}
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function attr(w: Bytes.Writer, name: string, typ: string, data: buffer)
w:cstring(name)
w:cstring(typ)
w:u32le(buffer.len(data))
w:bytes(data)
end
function Exr.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(img) ~= "table" or type(img.pixels) ~= "buffer" or (img.format ~= "rgbaf32" and img.format ~= "rgba8") then
return nil, Err.new(Err.ARG, "needs an rgbaf32 or rgba8 Image")
end
local w, h = img.width, img.height
if type(w) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then
return nil, Err.new(Err.ARG, "bad image size")
end
local compName = opts and opts.compression or "zip"
local comp = if compName == "none" then 0 elseif compName == "zips" then 2 elseif compName == "zip" then 3 else nil
if not comp then
return nil, Err.new(Err.ARG, "compression must be none, zips or zip")
end
local ptype = opts and opts.pixelType or "half"
if ptype ~= "half" and ptype ~= "float" then
return nil, Err.new(Err.ARG, "pixelType must be half or float")
end
local level = opts and opts.level or 6
-- the float values
local n = w * h
local fl = buffer.create(n * 16)
if img.format == "rgbaf32" then
buffer.copy(fl, 0, img.pixels, 0, n * 16)
else
for i = 0, n * 4 - 1 do
local v = buffer.readu8(img.pixels, i) / 255
buffer.writef32(fl, i * 4, if i % 4 < 3 then v ^ 2.2 else v)
end
end
local alpha = opts and opts.alpha
if alpha == nil then
alpha = false
for i = 0, n - 1 do
if buffer.readf32(fl, i * 16 + 12) ~= 1 then
alpha = true
break
end
end
end
local chans = if alpha then { { "A", 3 }, { "B", 2 }, { "G", 1 }, { "R", 0 } } else { { "B", 2 }, { "G", 1 }, { "R", 0 } }
local kind = if ptype == "half" then 1 else 2
local sz = if kind == 1 then 2 else 4
local lpb = LINES[comp]
local nblocks = (h + lpb - 1) // lpb
-- header
local hw = Bytes.writer(512)
hw:string(MAGIC)
hw:u32le(2)
local cl = Bytes.writer()
for _, c in chans do
cl:cstring(c[1])
cl:u32le(kind)
cl:u8(0)
cl:fill(0, 3)
cl:u32le(1)
cl:u32le(1)
end
cl:u8(0)
attr(hw, "channels", "chlist", cl:finish())
attr(hw, "compression", "compression", buffer.fromstring(string.char(comp)))
local bw = Bytes.writer(16)
bw:u32le(0)
bw:u32le(0)
bw:u32le(w - 1)
bw:u32le(h - 1)
local boxb = bw:finish()
attr(hw, "dataWindow", "box2i", boxb)
attr(hw, "displayWindow", "box2i", boxb)
attr(hw, "lineOrder", "lineOrder", buffer.fromstring("\0"))
local fw = Bytes.writer(4)
fw:f32le(1)
attr(hw, "pixelAspectRatio", "float", fw:finish())
attr(hw, "screenWindowCenter", "v2f", buffer.create(8))
attr(hw, "screenWindowWidth", "float", fw:finish())
hw:u8(0)
local tableAt = hw:tell()
hw:fill(0, nblocks * 8)
local from = Half.fromFloat
for bi = 0, nblocks - 1 do
local y0 = bi * lpb
local y1 = math.min(y0 + lpb - 1, h - 1)
local raw = buffer.create((y1 - y0 + 1) * #chans * w * sz)
local o = 0
for y = y0, y1 do
for _, c in chans do
local k = c[2]
for x = 0, w - 1 do
local v = buffer.readf32(fl, ((y * w + x) * 4 + k) * 4)
if kind == 1 then
buffer.writeu16(raw, o, from(v))
else
buffer.writef32(raw, o, v)
end
o += sz
end
end
end
local data = raw
if comp ~= 0 then
local z = Codec.zip(raw, level)
if buffer.len(z) < buffer.len(raw) then
data = z
end
end
local at = hw:tell()
hw:setU32le(tableAt + bi * 8, at)
hw:u32le(y0)
hw:u32le(buffer.len(data))
hw:bytes(data)
end
return hw:finish(), nil
end
return Exr
+68
View File
@@ -0,0 +1,68 @@
--!strict
--!native
--!optimize 2
-- image/gif/Decode: the per-frame pixel work (native; never throws): palette indexes (plain or interlaced rows) to
-- rgba8, and drawing a frame onto the canvas (transparent pixels leave the canvas as it is). The caller sizes every
-- buffer: indexes fw * fh bytes, the palette 256 u32 entries, the frame fw * fh * 4, the canvas cw * ch * 4.
local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32
local Decode = {}
-- the source row of output row y in an interlaced frame (passes: every 8th from 0, every 8th from 4, every 4th from
-- 2, every 2nd from 1)
local function interlacedRow(fh: number): { number }
local map = table.create(fh, 0)
local r = 0
for _, pass in { { 0, 8 }, { 4, 8 }, { 2, 4 }, { 1, 2 } } do
local y = pass[1]
while y < fh do
map[y + 1] = r
r += 1
y += pass[2]
end
end
return map
end
-- toRgba(indexes, fw, fh, interlaced, palette, out): out = the frame in rgba8 (palette: 256 u32 entries, the
-- transparent one already alpha 0)
function Decode.toRgba(indexes: buffer, fw: number, fh: number, interlaced: boolean, palette: buffer, out: buffer)
local rows = if interlaced then interlacedRow(fh) else nil
for y = 0, fh - 1 do
local src = (if rows then rows[y + 1] else y) * fw
local dst = y * fw * 4
for x = 0, fw - 1 do
writeu32(out, dst + x * 4, readu32(palette, readu8(indexes, src + x) * 4))
end
end
end
-- draw(canvas, cw, ch, frame, fx, fy, fw, fh): frame pixels with alpha > 0 replace the canvas (clipped)
function Decode.draw(canvas: buffer, cw: number, ch: number, frame: buffer, fx: number, fy: number, fw: number, fh: number)
local x0, y0 = math.max(0, fx), math.max(0, fy)
local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh)
for y = y0, y1 - 1 do
local s = ((y - fy) * fw - fx) * 4
local d = y * cw * 4
for x = x0, x1 - 1 do
local v = readu32(frame, s + x * 4)
if v >= 0x01000000 then
writeu32(canvas, d + x * 4, v)
end
end
end
end
-- clear(canvas, cw, ch, fx, fy, fw, fh): the frame's rectangle to transparent black (dispose to background)
function Decode.clear(canvas: buffer, cw: number, ch: number, fx: number, fy: number, fw: number, fh: number)
local x0, y0 = math.max(0, fx), math.max(0, fy)
local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh)
if x1 <= x0 then
return
end
for y = y0, y1 - 1 do
buffer.fill(canvas, (y * cw + x0) * 4, 0, (x1 - x0) * 4)
end
end
return Decode
+534
View File
@@ -0,0 +1,534 @@
--!strict
-- image/gif: GIF87a / GIF89a. New code from the GIF89a spec (W3C / CompuServe 1990). Supports: decode of every image
-- (global / local colour tables, interlaced rows, LZW minimum code sizes 2..8 and the odd 1, transparency, frames
-- smaller than or outside the canvas), animation (Graphic Control Extension delays, disposal none / background /
-- previous, NETSCAPE2.0 / ANIMEXTS1.0 loop counts), comments (meta.text.comment); truncated files keep the frames
-- read so far (meta.truncated). Encode of rgba8 images and animations (Types.Frame lists) through codecs/image/Quantize
-- (median cut or octree, optional Floyd-Steinberg dithering; exact palettes, so lossless, at <= 256 colours) with
-- alpha < 128 as the transparent index.
-- Not supported: the plain text extension (skipped), the aspect ratio (kept in meta.source.aspect), the "user input"
-- flag, and blend = "source" frames that clear pixels to transparent (GIF can only draw over).
--
-- Decoded value: img.pixels = the first frame composited on a transparent canvas; for animations img.frames = every
-- frame's own rectangle (rgba8; blend "over" when it has a transparent index, else "source") and img.loops, the
-- number of plays (0 = forever; 1 when the file has no loop extension). The NETSCAPE2.0 value counts repeats, as
-- browsers and ImageMagick read it: a stored n plays n + 1 times (n = 0: forever).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Lzw = require("@rosetta/codecs/compress/Lzw")
local Quantize = require("@rosetta/codecs/image/Quantize")
local Types = require("@rosetta/Types")
local Decode = require("@rosetta/image/gif/Decode")
-- ------------------------------------------------------------------------------------------------ contract
local Gif = {
name = "gif",
category = "image",
extensions = { "gif" },
mime = { "image/gif" },
deps = { "core/Err", "core/Bytes", "codecs/compress/Lzw", "codecs/image/Quantize", "Types" },
caps = { decode = true, encode = true, animation = true, alpha = true, palette = true, depths = { 1, 2, 4, 8 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxPixels: number?, -- refuse a canvas or frame larger than this (default 2^26)
maxTotalPixels: number?, -- refuse animations whose frames add up to more (default 2^28)
maxFrames: number?, -- stop after this many frames (default: all)
}
export type EncodeOptions = {
maxColors: number?, -- 2..256 per palette (default 256; one is taken by transparency when needed)
method: ("mediancut" | "octree")?, -- default "mediancut"
dither: boolean?, -- Floyd-Steinberg (default false)
loops: number?, -- animation plays override (0 = forever, 1..65536; default img.loops)
globalPalette: boolean?, -- one palette for every frame (default false: a single image uses the global table,
-- each animation frame gets its own local table)
}
-- ------------------------------------------------------------------------------------------------ constants
local readu8 = buffer.readu8
local DISPOSE = { [0] = "none", [1] = "none", [2] = "background", [3] = "previous" }
local DISPOSE_CODE: { [string]: number } = { none = 1, background = 2, previous = 3 }
-- ------------------------------------------------------------------------------------------------ sniff
function Gif.sniff(r: Bytes.Reader): number
local s = r:peek(6)
return if s == "GIF89a" or s == "GIF87a" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- a colour table at p (n entries) -> 256 u32 rgba entries (missing ones opaque black) and the { r, g, b, a } list
local function colorTable(b: buffer, p: number, n: number): (buffer, { { number } })
local t = buffer.create(1024)
local list: { { number } } = table.create(n) :: { { number } }
for i = 0, 255 do
buffer.writeu32(t, i * 4, 0xFF000000)
end
for i = 0, n - 1 do
local q = p + i * 3
local r, g, bl = readu8(b, q), readu8(b, q + 1), readu8(b, q + 2)
buffer.writeu32(t, i * 4, r + g * 256 + bl * 65536 + 0xFF000000)
list[i + 1] = { r, g, bl, 255 }
end
return t, list
end
function Gif.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local maxPixels = opts and opts.maxPixels or 2 ^ 26
local maxTotal = opts and opts.maxTotalPixels or 2 ^ 28
local maxFrames = opts and opts.maxFrames or math.huge
local sig = r:string(6)
local cw, ch = r:u16le(), r:u16le()
local flags, bg, aspect = r:u8(), r:u8(), r:u8()
if r.err then
return nil, r.err
end
if sig ~= "GIF89a" and sig ~= "GIF87a" then
return nil, Err.new(Err.CORRUPT, "bad signature", r.base)
end
if cw == 0 or ch == 0 then
return nil, Err.new(Err.CORRUPT, "zero canvas size", r.base + 6)
end
if cw * ch > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", cw, ch, maxPixels))
end
local b = r.buf
local gct: buffer? = nil
local gpal: { { number } }? = nil
if bit32.band(flags, 0x80) ~= 0 then
local n = bit32.lshift(1, bit32.band(flags, 7) + 1)
if not r:need(n * 3) then
return nil, r.err
end
gct, gpal = colorTable(b, r.pos, n)
r.pos += n * 3
end
local img = Types.Image.new(cw, ch, "rgba8")
local frames: { Types.Frame } = {}
local comments: { string } = {}
local loops: number? = nil
local total = 0
-- the pending Graphic Control Extension
local delay, dispose, trans = 0, 0, -1
local truncated = false
local interlacedAny = false
local localTables = 0
local minCode = 8
local limit = r.limit
-- the sub-blocks at r.pos: joined into one buffer (nil when they run past the end)
local function subBlocks(): (buffer?, number)
local p = r.pos
local n = 0
while true do
if p >= limit then
return nil, p
end
local len = readu8(b, p)
if len == 0 then
break
end
if p + 1 + len > limit then
-- keep what is there: a truncated last block
n += limit - p - 1
p = limit
local out = buffer.create(n)
local q, o = r.pos, 0
while q < limit do
local l = math.min(readu8(b, q), limit - q - 1)
buffer.copy(out, o, b, q + 1, l)
o += l
q += 1 + l
end
return out, -1
end
n += len
p += 1 + len
end
local out = buffer.create(n)
local q, o = r.pos, 0
while q < p do
local l = readu8(b, q)
buffer.copy(out, o, b, q + 1, l)
o += l
q += 1 + l
end
return out, p + 1
end
local function skipBlocks(): boolean
local p = r.pos
while p < limit do
local len = readu8(b, p)
if len == 0 then
r.pos = p + 1
return true
end
p += 1 + len
end
r.pos = limit
return false
end
while true do
if r.pos >= limit then
truncated = true
break
end
local intro = r:u8()
if intro == 0x3B then
break
elseif intro == 0x21 then
local label = r:u8()
if r.err then
truncated = true
break
end
local p = r.pos
if label == 0xF9 and p + 6 <= limit and readu8(b, p) >= 4 then
local f = readu8(b, p + 1)
dispose = bit32.band(bit32.rshift(f, 2), 7)
delay = readu8(b, p + 2) + readu8(b, p + 3) * 256
trans = if bit32.band(f, 1) ~= 0 then readu8(b, p + 4) else -1
elseif label == 0xFF and p + 15 <= limit and readu8(b, p) == 11 then
local id = buffer.readstring(b, p + 1, 11)
if (id == "NETSCAPE2.0" or id == "ANIMEXTS1.0") and readu8(b, p + 12) >= 3 and readu8(b, p + 13) == 1 then
local rep = readu8(b, p + 14) + readu8(b, p + 15) * 256
loops = if rep == 0 then 0 else rep + 1 -- the stored value repeats: plays = value + 1
end
elseif label == 0xFE then
local data = subBlocks()
if data then
table.insert(comments, buffer.tostring(data))
end
end
if not skipBlocks() then
truncated = true
break
end
elseif intro == 0x2C then
local fx, fy, fw, fh = r:u16le(), r:u16le(), r:u16le(), r:u16le()
local f = r:u8()
if r.err then
truncated = true
break
end
if fw * fh > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("a %d x %d frame is over the %d pixel limit", fw, fh, maxPixels), r.pos)
end
total += fw * fh
if total > maxTotal then
return nil, Err.new(Err.LIMIT, string.format("the frames add up to over %d pixels", maxTotal), r.pos)
end
local pal = gct
if bit32.band(f, 0x80) ~= 0 then
local n = bit32.lshift(1, bit32.band(f, 7) + 1)
if not r:need(n * 3) then
truncated = true
break
end
pal = colorTable(b, r.pos, n)
r.pos += n * 3
localTables += 1
end
local interlaced = bit32.band(f, 0x40) ~= 0
interlacedAny = interlacedAny or interlaced
local mc = r:u8()
if r.err then
truncated = true
break
end
if mc < 1 or mc > 11 then
return nil, Err.new(Err.CORRUPT, "bad LZW minimum code size " .. mc, r.pos - 1)
end
minCode = mc
local data, nextPos = subBlocks()
if not data then
truncated = true
break
end
local n = fw * fh
local idx = buffer.create(n)
local got, lerr = Lzw.decode(data, 0, buffer.len(data), idx, 0, n, "gif", mc)
if got < n or nextPos < 0 then
truncated = true -- the missing pixels stay index 0, as most decoders show them
end
local _ = lerr -- a corrupt code ends the frame early (kept: what was decoded is shown)
local t = buffer.create(1024)
if pal then
buffer.copy(t, 0, pal)
else
-- no colour table at all: a grey ramp (what the spec leaves to the decoder)
for i = 0, 255 do
buffer.writeu32(t, i * 4, i + i * 256 + i * 65536 + 0xFF000000)
end
end
if trans >= 0 then
buffer.writeu32(t, trans * 4, 0)
end
local fimg = Types.Image.new(fw, fh, "rgba8")
Decode.toRgba(idx, fw, fh, interlaced, t, fimg.pixels)
if #frames == 0 then
Decode.draw(img.pixels, cw, ch, fimg.pixels, fx, fy, fw, fh)
end
table.insert(frames, {
image = fimg,
delay = delay / 100,
x = fx,
y = fy,
dispose = DISPOSE[dispose] or "none",
blend = if trans >= 0 then "over" else "source",
} :: Types.Frame)
delay, dispose, trans = 0, 0, -1
if nextPos < 0 then
break
end
r.pos = nextPos
if #frames >= maxFrames then
break
end
else
-- junk between blocks: stop here, keeping what was read
if #frames == 0 then
return nil, Err.new(Err.CORRUPT, string.format("bad block introducer 0x%02x", intro), r.pos - 1)
end
truncated = true
break
end
end
if #frames == 0 then
return nil, Err.new(Err.TRUNCATED, "no image data", r.pos)
end
if #frames > 1 then
img.frames = frames
img.loops = loops or 1
else
img.loops = loops or 0
end
img.meta.palette = gpal
img.meta.background = bg
if #comments > 0 then
img.meta.text = { comment = table.concat(comments, "\n") }
end
if truncated then
img.meta.truncated = true
end
img.meta.source = {
format = "gif",
version = string.sub(sig, 4),
bitDepth = minCode,
colorType = "palette",
frames = #frames,
interlaced = interlacedAny,
localPalettes = localTables,
aspect = aspect,
loopExtension = loops ~= nil,
}
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function validImage(i: any): boolean
return type(i) == "table" and i.format == "rgba8" and type(i.pixels) == "buffer" and type(i.width) == "number" and type(i.height) == "number" and i.width >= 1 and i.height >= 1 and i.width <= 65535 and i.height <= 65535 and i.width % 1 == 0 and i.height % 1 == 0 and buffer.len(i.pixels) >= i.width * i.height * 4
end
local function hasTransparency(px: buffer, n: number): boolean
for i = 0, n - 1 do
if readu8(px, i * 4 + 3) < 128 then
return true
end
end
return false
end
-- palette list -> padded table bytes (power of two entries, >= 2) and its size code
local function writeTable(w: Bytes.Writer, pal: { { number } }): number
local bits = 1
while bit32.lshift(1, bits) < #pal do
bits += 1
end
for i = 1, bit32.lshift(1, bits) do
local c = pal[i]
if c then
w:u8(c[1])
w:u8(c[2])
w:u8(c[3])
else
w:fill(0, 3)
end
end
return bits
end
local function tableBits(n: number): number
local bits = 1
while bit32.lshift(1, bits) < n do
bits += 1
end
return bits
end
function Gif.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if not validImage(img) then
return nil, Err.new(Err.ARG, "needs an rgba8 Image of 1..65535 x 1..65535 pixels")
end
local maxColors = opts and opts.maxColors or 256
if type(maxColors) ~= "number" or maxColors < 2 or maxColors > 256 then
return nil, Err.new(Err.ARG, "maxColors must be 2..256")
end
maxColors = math.floor(maxColors)
local method = opts and opts.method or "mediancut"
if method ~= "mediancut" and method ~= "octree" then
return nil, Err.new(Err.ARG, "method must be mediancut or octree")
end
local dither = opts and opts.dither or false
-- the frames to write: { image, x, y, delay, dispose }
local list: { Types.Frame } = {}
if type(img.frames) == "table" and #(img.frames :: any) > 0 then
for i, f in img.frames :: { Types.Frame } do
if type(f) ~= "table" or not validImage(f.image) then
return nil, Err.new(Err.ARG, "frame " .. i .. ": 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 + f.image.width > 65535 or y + f.image.height > 65535 then
return nil, Err.new(Err.ARG, "frame " .. i .. ": bad position")
end
table.insert(list, f)
end
else
list[1] = { image = img, x = 0, y = 0, delay = 0, dispose = "none", blend = "source" }
end
local animated = #list > 1
local loops = opts and opts.loops or img.loops or 0
if type(loops) ~= "number" or loops < 0 or loops > 65536 or loops % 1 ~= 0 then
return nil, Err.new(Err.ARG, "loops must be 0..65536")
end
-- palettes
local shared = (opts and opts.globalPalette) or not animated
local qopts: Quantize.PaletteOptions = { method = method, dither = dither }
local globalPal: { { number } }? = nil
local globalTrans = false
if shared then
-- every frame's pixels together
local npx = 0
for _, f in list do
npx += f.image.width * f.image.height
end
local all = buffer.create(npx * 4)
local o = 0
for _, f in list do
local n = f.image.width * f.image.height * 4
buffer.copy(all, o, f.image.pixels, 0, n)
o += n
end
globalTrans = hasTransparency(all, npx)
local pal = Quantize.palette(all, npx, 1, if globalTrans then maxColors - 1 else maxColors, qopts)
if #pal == 0 then
pal = { { 0, 0, 0, 255 } }
end
if globalTrans then
table.insert(pal, { 0, 0, 0, 0 })
end
globalPal = pal
end
local w = Bytes.writer(img.width * img.height + 1024)
w:string("GIF89a")
w:u16le(img.width)
w:u16le(img.height)
if globalPal then
w:u8(0x80 + 0x70 + (tableBits(#globalPal) - 1))
w:u8(0)
w:u8(0)
writeTable(w, globalPal)
else
w:u8(0x70)
w:u8(0)
w:u8(0)
end
if animated and loops ~= 1 then
w:u8(0x21)
w:u8(0xFF)
w:u8(11)
w:string("NETSCAPE2.0")
w:u8(3)
w:u8(1)
w:u16le(if loops == 0 then 0 else loops - 1)
w:u8(0)
end
local text = img.meta and img.meta.text
local comment = text and (text.comment or text.Comment)
if type(comment) == "string" and #comment > 0 then
w:u8(0x21)
w:u8(0xFE)
for i = 1, #comment, 255 do
local part = string.sub(comment, i, i + 254)
w:u8(#part)
w:string(part)
end
w:u8(0)
end
for _, f in list do
local fi = f.image
local fw, fh = fi.width, fi.height
local n = fw * fh
local pal: { { number } }
local tidx: number? = nil
if globalPal then
pal = globalPal
if globalTrans then
tidx = #pal - 1
end
else
local tr = hasTransparency(fi.pixels, n)
pal = Quantize.palette(fi.pixels, fw, fh, if tr then maxColors - 1 else maxColors, qopts)
if #pal == 0 then
pal = { { 0, 0, 0, 255 } }
end
if tr then
table.insert(pal, { 0, 0, 0, 0 })
tidx = #pal - 1
end
end
local idx = Quantize.map(fi.pixels, fw, fh, pal, { dither = dither, transparentIndex = tidx })
-- the Graphic Control Extension: always for animations, else only for transparency
if animated or tidx then
local d = DISPOSE_CODE[f.dispose or "none"] or 1
w:u8(0x21)
w:u8(0xF9)
w:u8(4)
w:u8(d * 4 + (if tidx then 1 else 0))
w:u16le(math.clamp(math.floor((f.delay or 0) * 100 + 0.5), 0, 65535))
w:u8(tidx or 0)
w:u8(0)
end
w:u8(0x2C)
w:u16le(f.x or 0)
w:u16le(f.y or 0)
w:u16le(fw)
w:u16le(fh)
local bits
if globalPal then
w:u8(0)
bits = tableBits(#globalPal)
else
bits = tableBits(#pal)
w:u8(0x80 + bits - 1)
writeTable(w, pal)
end
local mc = math.max(2, bits)
w:u8(mc)
local codes = Lzw.encode(idx, 0, n, "gif", mc)
local cl = buffer.len(codes)
local p = 0
while p < cl do
local l = math.min(255, cl - p)
w:u8(l)
w:bytes(codes, p, l)
p += l
end
w:u8(0)
end
w:u8(0x3B)
return w:finish(), nil
end
return Gif
+219
View File
@@ -0,0 +1,219 @@
--!strict
--!native
--!optimize 2
-- image/hdr/Codec: Radiance RGBE scanlines (native; never throws). Written from the Radiance file format notes
-- (Greg Ward, "Real Pixels", Graphics Gems II) and Bruce Walter's rgbe.c conventions: flat pixels, old-style RLE
-- (1, 1, 1, n repeats the previous pixel, shifted by 8 for consecutive markers) and new-style RLE (2, 2, width, then
-- four run-length coded channel planes). RGBE -> float is mantissa * 2^(e - 136), as rgbe.c, stb_image and
-- ImageMagick (no +0.5 offset); float -> RGBE as rgbe.c float2rgbe (frexp). Every read is bounds-checked.
local readu8, writeu8, writef32, readf32 = buffer.readu8, buffer.writeu8, buffer.writef32, buffer.readf32
local frexp = math.frexp
local Codec = {}
-- readLine(b, p, limit, w, row) -> new position | nil, message: one scanline into row (w * 4 RGBE bytes)
function Codec.readLine(b: buffer, p: number, limit: number, w: number, row: buffer): (number?, string?)
if w >= 8 and w <= 32767 and p + 4 <= limit and readu8(b, p) == 2 and readu8(b, p + 1) == 2 and readu8(b, p + 2) < 128 then
if readu8(b, p + 2) * 256 + readu8(b, p + 3) ~= w then
return nil, "scanline width mismatch"
end
p += 4
for c = 0, 3 do
local x = 0
while x < w do
if p >= limit then
return nil, "truncated"
end
local n = readu8(b, p)
p += 1
if n > 128 then
n -= 128
if x + n > w or p >= limit then
return nil, if p >= limit then "truncated" else "bad run"
end
local v = readu8(b, p)
p += 1
for i = x, x + n - 1 do
writeu8(row, i * 4 + c, v)
end
else
if n == 0 or x + n > w then
return nil, "bad count"
end
if p + n > limit then
return nil, "truncated"
end
for i = x, x + n - 1 do
writeu8(row, i * 4 + c, readu8(b, p))
p += 1
end
end
x += n
end
end
return p, nil
end
-- flat pixels, with old-style runs
local x = 0
local shift = 0
while x < w do
if p + 4 > limit then
return nil, "truncated"
end
local r, g, bl, e = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2), readu8(b, p + 3)
p += 4
if r == 1 and g == 1 and bl == 1 then
if x == 0 then
return nil, "run at the start of a scanline"
end
local n = e * 2 ^ shift
if x + n > w then
return nil, "bad run"
end
local q = (x - 1) * 4
local pr, pg, pb, pe = readu8(row, q), readu8(row, q + 1), readu8(row, q + 2), readu8(row, q + 3)
for i = x, x + n - 1 do
writeu8(row, i * 4, pr)
writeu8(row, i * 4 + 1, pg)
writeu8(row, i * 4 + 2, pb)
writeu8(row, i * 4 + 3, pe)
end
x += n
shift += 8
if shift > 24 then
return nil, "bad run"
end
else
writeu8(row, x * 4, r)
writeu8(row, x * 4 + 1, g)
writeu8(row, x * 4 + 2, bl)
writeu8(row, x * 4 + 3, e)
x += 1
shift = 0
end
end
return p, nil
end
-- toFloat(row, n, out, offsets): n RGBE pixels -> rgbaf32 at out byte offsets dest(i) = base + i * step
function Codec.toFloat(row: buffer, n: number, out: buffer, base: number, step: number)
for i = 0, n - 1 do
local q = i * 4
local e = readu8(row, q + 3)
local o = base + i * step
if e == 0 then
writef32(out, o, 0)
writef32(out, o + 4, 0)
writef32(out, o + 8, 0)
else
local f = 2 ^ (e - 136)
writef32(out, o, readu8(row, q) * f)
writef32(out, o + 4, readu8(row, q + 1) * f)
writef32(out, o + 8, readu8(row, q + 2) * f)
end
writef32(out, o + 12, 1)
end
end
-- fromFloat(px, y, w, row): row y of an rgbaf32 image -> w RGBE pixels (rgbe.c float2rgbe)
function Codec.fromFloat(px: buffer, y: number, w: number, row: buffer)
for x = 0, w - 1 do
local q = (y * w + x) * 16
local r, g, b = readf32(px, q), readf32(px, q + 4), readf32(px, q + 8)
if r ~= r or r < 0 then
r = 0
end
if g ~= g or g < 0 then
g = 0
end
if b ~= b or b < 0 then
b = 0
end
local v = math.max(r, g, b)
local o = x * 4
if v < 1e-32 or v == math.huge then
if v == math.huge then
-- clamp infinities to the largest RGBE value
writeu8(row, o, if r == math.huge then 255 else 0)
writeu8(row, o + 1, if g == math.huge then 255 else 0)
writeu8(row, o + 2, if b == math.huge then 255 else 0)
writeu8(row, o + 3, 255)
else
writeu8(row, o, 0)
writeu8(row, o + 1, 0)
writeu8(row, o + 2, 0)
writeu8(row, o + 3, 0)
end
else
local m, e = frexp(v)
if e > 127 then
writeu8(row, o, 255)
writeu8(row, o + 1, 255)
writeu8(row, o + 2, 255)
writeu8(row, o + 3, 255)
else
local s = m * 256 / v
writeu8(row, o, math.min(255, math.floor(r * s)))
writeu8(row, o + 1, math.min(255, math.floor(g * s)))
writeu8(row, o + 2, math.min(255, math.floor(b * s)))
writeu8(row, o + 3, e + 128)
end
end
end
end
-- writeLine(row, w, out, o) -> new offset: new-style RLE (rgbe.c RGBE_WriteBytes_RLE); out needs w * 4 + w + 8
function Codec.writeLine(row: buffer, w: number, out: buffer, o: number): number
writeu8(out, o, 2)
writeu8(out, o + 1, 2)
writeu8(out, o + 2, w // 256)
writeu8(out, o + 3, w % 256)
o += 4
for c = 0, 3 do
local cur = 0
while cur < w do
-- find the next run of at least 4
local begRun = cur
local runCount = 0
local oldRun = 0
while runCount < 4 and begRun < w do
begRun += runCount
oldRun = runCount
runCount = 1
if begRun < w then
local v = readu8(row, begRun * 4 + c)
while begRun + runCount < w and runCount < 127 and readu8(row, (begRun + runCount) * 4 + c) == v do
runCount += 1
end
end
end
-- a short run just before the long one
if oldRun > 1 and oldRun == begRun - cur then
writeu8(out, o, 128 + oldRun)
writeu8(out, o + 1, readu8(row, cur * 4 + c))
o += 2
cur = begRun
end
-- raw bytes up to the run
while cur < begRun do
local n = math.min(begRun - cur, 128)
writeu8(out, o, n)
o += 1
for i = cur, cur + n - 1 do
writeu8(out, o, readu8(row, i * 4 + c))
o += 1
end
cur += n
end
if runCount >= 4 then
writeu8(out, o, 128 + runCount)
writeu8(out, o + 1, readu8(row, begRun * 4 + c))
o += 2
cur += runCount
end
end
end
return o
end
return Codec
+234
View File
@@ -0,0 +1,234 @@
--!strict
-- image/hdr: Radiance HDR / RGBE (.hdr, .pic), written from the Radiance file format notes and rgbe.c conventions.
-- Decode: "#?RADIANCE" / "#?RGBE" (any "#?" program name) headers, FORMAT=32-bit_rle_rgbe, EXPOSURE (the product of
-- every EXPOSURE line, kept in meta.exposure, not applied), other header lines in meta.text, the eight resolution
-- orientations (-Y +X standard, +Y, -X and the X-major ones), flat, old-style RLE and new-style RLE scanlines.
-- opts.native gives the linear rgbaf32 values (alpha 1); the default rgba8 is a display conversion:
-- round(clamp(v, 0, 1) ^ (1 / 2.2) * 255) per channel. Encode: rgbaf32 (or rgba8 through the inverse curve) to a
-- -Y +X file with new-style RLE (flat scanlines for widths outside 8..32767).
-- Not supported: FORMAT=32-bit_rle_xyze (CIE XYZ files: UNSUPPORTED), PRIMARIES / COLORCORR (ignored).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Codec = require("@rosetta/image/hdr/Codec")
-- ------------------------------------------------------------------------------------------------ contract
local Hdr = {
name = "hdr",
category = "image",
extensions = { "hdr", "pic", "rgbe" },
mime = { "image/vnd.radiance", "image/x-hdr" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, alpha = false, float = true, depths = { 32 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
native: boolean?, -- linear rgbaf32 (default false: rgba8 through a 1 / 2.2 display gamma)
maxPixels: number?, -- refuse larger images (default 2^26)
}
export type EncodeOptions = {
rle: boolean?, -- new-style RLE scanlines (default true)
exposure: number?, -- write an EXPOSURE line (default meta.exposure when not 1)
}
-- ------------------------------------------------------------------------------------------------ constants
local GAMMA = 1 / 2.2
-- ------------------------------------------------------------------------------------------------ sniff
function Hdr.sniff(r: Bytes.Reader): number
local s = r:peek(10)
if s == "#?RADIANCE" then
return 1
end
if string.sub(s, 1, 6) == "#?RGBE" then
return 1
end
if string.sub(s, 1, 2) == "#?" and string.match(s, "^#%?%u") then
return 0.5
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Hdr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local maxPixels = opts and opts.maxPixels or 2 ^ 26
local b, limit = r.buf, r.limit
local p = r.base
-- header lines up to the first empty one
local function line(): string?
local s = p
while p < limit and buffer.readu8(b, p) ~= 10 do
p += 1
end
if p >= limit then
return nil
end
local l = buffer.readstring(b, s, p - s)
p += 1
return l
end
local first = line()
if not first or string.sub(first, 1, 2) ~= "#?" then
return nil, Err.new(Err.CORRUPT, "not a Radiance file (no #? line)", r.base)
end
local exposure = 1
local format = nil
local text: { [string]: string } = {}
while true do
local l = line()
if l == nil then
return nil, Err.new(Err.TRUNCATED, "header ends early", p)
end
l = string.gsub(l, "\r$", "")
if l == "" then
break
end
local k, v = string.match(l, "^%s*([%w_%-]+)%s*=%s*(.-)%s*$")
if k == "FORMAT" then
format = v
elseif k == "EXPOSURE" then
local e = tonumber(v)
if e and e > 0 then
exposure *= e
end
elseif k then
text[k] = v :: string
end
end
if format and format ~= "32-bit_rle_rgbe" then
return nil, Err.new(Err.UNSUPPORTED, "FORMAT=" .. format)
end
local res = line()
if not res then
return nil, Err.new(Err.TRUNCATED, "no resolution line", p)
end
local s1, a1, n1, s2, a2, n2 = string.match(res, "^%s*([%+%-])([XY])%s+(%d+)%s+([%+%-])([XY])%s+(%d+)%s*$")
if not s1 or a1 == a2 or #(n1 :: string) > 9 or #(n2 :: string) > 9 then
return nil, Err.new(Err.CORRUPT, "bad resolution line", p)
end
local outer, inner = tonumber(n1) :: number, tonumber(n2) :: number
local w, h = if a1 == "Y" then inner else outer, if a1 == "Y" then outer else inner
if w < 1 or h < 1 then
return nil, Err.new(Err.CORRUPT, "zero size")
end
if w * h > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
end
local img = Types.Image.new(w, h, "rgbaf32")
local px = img.pixels
local row = buffer.create(inner * 4)
local truncated = false
for i = 0, outer - 1 do
local np, err = Codec.readLine(b, p, limit, inner, row)
if not np then
if err == "truncated" then
truncated = true
break
end
return nil, Err.new(Err.CORRUPT, tostring(err), p)
end
p = np
-- where scanline i, pixel j lands: Y decreasing ("-Y") = top first, X increasing ("+X") = left first
local base, step
if a1 == "Y" then
local y = if s1 == "-" then i else h - 1 - i
if s2 == "+" then
base, step = y * w * 16, 16
else
base, step = (y * w + w - 1) * 16, -16
end
else
local x = if s1 == "+" then i else w - 1 - i
if s2 == "-" then
base, step = x * 16, w * 16
else
base, step = ((h - 1) * w + x) * 16, -w * 16
end
end
Codec.toFloat(row, inner, px, base, step)
end
if not (opts and opts.native) then
local o = Types.Image.new(w, h, "rgba8")
for i = 0, w * h - 1 do
for c = 0, 2 do
local v = buffer.readf32(px, i * 16 + c * 4)
buffer.writeu8(o.pixels, i * 4 + c, math.floor(math.clamp(v, 0, 1) ^ GAMMA * 255 + 0.5))
end
buffer.writeu8(o.pixels, i * 4 + 3, 255)
end
o.meta = img.meta
img = o
end
img.meta.exposure = exposure
img.meta.colorSpace = "linear"
if next(text) then
img.meta.text = text
end
if truncated then
img.meta.truncated = true
end
img.meta.source = { format = "hdr", bitDepth = 32, colorType = "rgbe", program = string.sub(first, 3), orientation = string.format("%s%s %s%s", s1, a1 :: string, s2 :: string, a2 :: string) }
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Hdr.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(img) ~= "table" or type(img.pixels) ~= "buffer" or (img.format ~= "rgbaf32" and img.format ~= "rgba8") then
return nil, Err.new(Err.ARG, "needs an rgbaf32 or rgba8 Image")
end
local w, h = img.width, img.height
local bpp = if img.format == "rgbaf32" then 16 else 4
if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * bpp then
return nil, Err.new(Err.ARG, "bad image size or pixel buffer")
end
local o: any = opts or {}
local px = img.pixels
if bpp == 4 then
-- rgba8 through the inverse of the decoder's display curve
local lut = table.create(256, 0)
for v = 0, 255 do
lut[v + 1] = (v / 255) ^ 2.2
end
px = buffer.create(w * h * 16)
for i = 0, w * h - 1 do
for c = 0, 2 do
buffer.writef32(px, i * 16 + c * 4, lut[buffer.readu8(img.pixels, i * 4 + c) + 1])
end
buffer.writef32(px, i * 16 + 12, 1)
end
end
local exposure = o.exposure or (img.meta and img.meta.exposure)
local head = "#?RADIANCE\n# written by rosetta\nFORMAT=32-bit_rle_rgbe\n"
if type(exposure) == "number" and exposure > 0 and exposure ~= 1 then
head ..= string.format("EXPOSURE=%.9g\n", exposure)
end
head ..= string.format("\n-Y %d +X %d\n", h, w)
local rle = o.rle ~= false and w >= 8 and w <= 32767
local out = buffer.create(#head + h * (w * 5 + 8))
buffer.writestring(out, 0, head)
local op = #head
local row = buffer.create(w * 4)
for y = 0, h - 1 do
Codec.fromFloat(px, y, w, row)
if rle then
op = Codec.writeLine(row, w, out, op)
else
buffer.copy(out, op, row, 0, w * 4)
for x = 0, w - 1 do
-- 1, 1, 1 would read as an old-style run marker
if buffer.readu8(out, op + x * 4) == 1 and buffer.readu8(out, op + x * 4 + 1) == 1 and buffer.readu8(out, op + x * 4 + 2) == 1 then
buffer.writeu8(out, op + x * 4 + 2, 0)
end
end
op += w * 4
end
end
local res = buffer.create(op)
buffer.copy(res, 0, out, 0, op)
return res, nil
end
return Hdr
+337
View File
@@ -0,0 +1,337 @@
--!strict
-- image/icns: Apple Icon Image files (the icns resource type; new code; chunks through containers/Chunks). Decode:
-- the legacy RGB entries is32 / il32 / ih32 / it32 (the icns RLE, or raw) with their s8mk / l8mk / h8mk / t8mk alpha
-- masks, ic04 / ic05 ARGB entries, the 1-bit ics# / ICN# / ich# / icm# icons with their masks, and PNG entries in any
-- type (icp4 .. ic14) through the api hook opts.decodeImage. JPEG 2000 entries are skipped (meta.skipped lists them),
-- like 4 / 8-bit palette entries and nested dark-mode / TOC chunks. The image is the largest entry; img.frames lists
-- every decoded entry (each with meta.source = { type = "ic07", ... }); a file of JPEG 2000 entries only returns
-- UNSUPPORTED. Encode: the image and every img.frames image (square, 16 .. 1024): PNG entries through opts.encodeImage
-- (icp4 / icp5 / icp6 / ic07 / ic08 / ic09 / ic10), or without the hook (or opts.legacy) the RLE entries for 16 / 32 /
-- 48 / 128 with masks.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Sniff = require("@rosetta/core/Sniff")
local Types = require("@rosetta/Types")
local Chunks = require("@rosetta/containers/Chunks")
-- ------------------------------------------------------------------------------------------------ contract
local Icns = {
name = "icns",
category = "image",
extensions = { "icns" },
mime = { "image/icns", "image/x-icns" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "containers/Chunks" },
caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 24, 32 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes PNG entries (the api passes one)
maxPixels: number?, -- refuse entries larger than this (default 2^22)
}
export type EncodeOptions = {
encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes PNG entries (the api passes one)
legacy: boolean?, -- RLE entries (16 / 32 / 48 / 128) even when encodeImage is there (default false)
}
-- ------------------------------------------------------------------------------------------------ constants
local RGB: { [string]: { any } } = { is32 = { 16, "s8mk" }, il32 = { 32, "l8mk" }, ih32 = { 48, "h8mk" }, it32 = { 128, "t8mk" } }
local MASKS: { [string]: boolean } = { s8mk = true, l8mk = true, h8mk = true, t8mk = true }
local ARGB: { [string]: number } = { ic04 = 16, ic05 = 32 }
local MONO: { [string]: { number } } = { ["ics#"] = { 16, 16 }, ["ICN#"] = { 32, 32 }, ["ich#"] = { 48, 48 }, ["icm#"] = { 16, 12 } }
local PNG_TYPES: { [number]: string } = { [16] = "icp4", [32] = "icp5", [64] = "icp6", [128] = "ic07", [256] = "ic08", [512] = "ic09", [1024] = "ic10" }
local LEGACY: { [number]: { string } } = { [16] = { "is32", "s8mk" }, [32] = { "il32", "l8mk" }, [48] = { "ih32", "h8mk" }, [128] = { "it32", "t8mk" } }
local LAYOUT: Chunks.Layout = {
bigEndian = true,
resize = function(_id: string, declared: number): number?
return math.max(0, declared - 8)
end,
}
local readu8 = buffer.readu8
-- ------------------------------------------------------------------------------------------------ sniff
function Icns.sniff(r: Bytes.Reader): number
return Sniff.magic(r, "icns")
end
-- ------------------------------------------------------------------------------------------------ decode
-- the icns RLE of n channels of count bytes each from [p, stop) into out at channel offsets (interleaved, step 4)
local function unrle(b: buffer, p: number, stop: number, out: buffer, channels: { number }, count: number): boolean
for _, ch in channels do
local i = 0
while i < count do
if p >= stop then
return false
end
local c = readu8(b, p)
p += 1
if c >= 128 then
local n = c - 125
if p >= stop then
return false
end
local v = readu8(b, p)
p += 1
for _ = 1, math.min(n, count - i) do
buffer.writeu8(out, i * 4 + ch, v)
i += 1
end
else
local n = c + 1
if p + n > stop then
return false
end
for k = 0, math.min(n, count - i) - 1 do
buffer.writeu8(out, (i + k) * 4 + ch, readu8(b, p + k))
end
i += math.min(n, count - i)
p += n
end
end
end
return true
end
local function isPng(b: buffer, p: number, n: number): boolean
return n >= 8 and buffer.readstring(b, p, 8) == "\137PNG\r\n\26\n"
end
local function isJp2(b: buffer, p: number, n: number): boolean
return n >= 12 and (buffer.readstring(b, p, 12) == "\0\0\0\12jP \r\n\135\n" or buffer.readstring(b, p, 4) == "\255\79\255\81")
end
function Icns.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local b, o, limit = r.buf, r.base, r.limit
if limit - o < 8 or buffer.readstring(b, o, 4) ~= "icns" then
return nil, Err.new(Err.CORRUPT, "not an icns file", o)
end
local total = bit32.byteswap(buffer.readu32(b, o + 4))
local stop = math.min(limit, o + math.max(total, 8))
local list = Chunks.walk(b, o + 8, stop, LAYOUT)
local decodeImage = opts and opts.decodeImage
local maxPixels = opts and opts.maxPixels or 2 ^ 22
local masks: { [string]: Chunks.Chunk } = {}
for _, c in list do
if MASKS[c.id] then
masks[c.id] = c
end
end
local frames: { Types.Frame } = {}
local skipped: { string } = {}
local function add(im: Types.Image, typ: string, extra: { [string]: any }?)
local src: { [string]: any } = { format = "icns", type = typ }
if extra then
for k, v in extra do
src[k] = v
end
end
im.meta.source = src :: any
table.insert(frames, { image = im, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } :: Types.Frame)
end
for _, c in list do
local id, p, n = c.id, c.offset, c.avail
if c.truncated then
table.insert(skipped, id .. " (truncated)")
elseif RGB[id] then
local size = RGB[id][1]
local im = Types.Image.new(size, size, "rgba8")
local px = im.pixels
local q = if id == "it32" then p + 4 else p
local count = size * size
local ok
if n == count * 3 then
for i = 0, count - 1 do
for k = 0, 2 do
buffer.writeu8(px, i * 4 + k, readu8(b, p + k * count + i))
end
end
ok = true
else
ok = unrle(b, q, p + n, px, { 0, 1, 2 }, count)
end
local m = masks[RGB[id][2]]
for i = 0, count - 1 do
buffer.writeu8(px, i * 4 + 3, if m and m.avail >= count then readu8(b, m.offset + i) else 255)
end
if ok then
add(im, id, { bitDepth = 24, mask = m ~= nil })
else
table.insert(skipped, id .. " (bad RLE)")
end
elseif ARGB[id] and n >= 4 and buffer.readstring(b, p, 4) == "ARGB" then
local size = ARGB[id]
local im = Types.Image.new(size, size, "rgba8")
if unrle(b, p + 4, p + n, im.pixels, { 3, 0, 1, 2 }, size * size) then
add(im, id, { bitDepth = 32 })
else
table.insert(skipped, id .. " (bad RLE)")
end
elseif MONO[id] then
local w, h = MONO[id][1], MONO[id][2]
local bytes = w * h // 8
if n >= bytes * 2 then
local im = Types.Image.new(w, h, "rgba8")
for i = 0, w * h - 1 do
local bit = bit32.band(bit32.rshift(readu8(b, p + bit32.rshift(i, 3)), 7 - bit32.band(i, 7)), 1)
local mbit = bit32.band(bit32.rshift(readu8(b, p + bytes + bit32.rshift(i, 3)), 7 - bit32.band(i, 7)), 1)
buffer.writeu32(im.pixels, i * 4, (if bit == 1 then 0 else 0xFFFFFF) + mbit * 0xFF000000)
end
add(im, id, { bitDepth = 1 })
end
elseif isPng(b, p, n) then
if decodeImage then
local sub = buffer.create(n)
buffer.copy(sub, 0, b, p, n)
local okc, im, ierr = pcall(decodeImage, sub)
if okc and im then
if im.width * im.height <= maxPixels then
add(im :: Types.Image, id, { png = true })
else
table.insert(skipped, id .. " (over maxPixels)")
end
else
table.insert(skipped, id .. " (PNG: " .. tostring(if okc then ierr else im) .. ")")
end
else
table.insert(skipped, id .. " (PNG: no decodeImage hook)")
end
elseif isJp2(b, p, n) then
table.insert(skipped, id .. " (JPEG 2000)")
elseif not MASKS[id] and id ~= "TOC " and id ~= "icnV" and id ~= "name" and id ~= "info" then
table.insert(skipped, id)
end
end
if #frames == 0 then
if #skipped > 0 then
return nil, Err.new(Err.UNSUPPORTED, "no decodable entry (" .. table.concat(skipped, ", ") .. ")")
end
return nil, Err.new(Err.CORRUPT, "no icon entries", o + 8)
end
local main = frames[1].image
for _, f in frames do
if f.image.width * f.image.height > main.width * main.height then
main = f.image
end
end
local img = Types.Image.new(0, 0, "rgba8")
img.width, img.height, img.pixels = main.width, main.height, main.pixels
if #frames > 1 then
img.frames = frames
end
if #skipped > 0 then
img.meta.skipped = skipped
end
img.meta.source = { format = "icns", type = main.meta.source and main.meta.source.type, entries = #frames }
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- the icns RLE of one channel (count bytes, step 4 from ch) into w
local function rle(w: Bytes.Writer, px: buffer, ch: number, count: number)
local i = 0
while i < count do
local v = readu8(px, i * 4 + ch)
local run = 1
while i + run < count and run < 130 and readu8(px, (i + run) * 4 + ch) == v do
run += 1
end
if run >= 3 then
w:u8(run + 125)
w:u8(v)
i += run
else
local lit = 0
while i + lit < count and lit < 128 do
local a = readu8(px, (i + lit) * 4 + ch)
if i + lit + 2 < count and readu8(px, (i + lit + 1) * 4 + ch) == a and readu8(px, (i + lit + 2) * 4 + ch) == a then
break
end
lit += 1
end
lit = math.max(lit, 1)
w:u8(lit - 1)
for k = 0, lit - 1 do
w:u8(readu8(px, (i + k) * 4 + ch))
end
i += lit
end
end
end
function Icns.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(img) ~= "table" or type(img.pixels) ~= "buffer" then
return nil, Err.new(Err.ARG, "needs an Image")
end
local images: { Types.Image } = {}
local seen: { [number]: boolean } = {}
local function take(im: Types.Image): Err.Err?
if type(im) ~= "table" or im.format ~= "rgba8" or im.width ~= im.height then
return Err.new(Err.ARG, "icons are square rgba8 images")
end
if not seen[im.width] then
seen[im.width] = true
table.insert(images, im)
end
return nil
end
local e = take(img)
if e then
return nil, e
end
if type(img.frames) == "table" then
for _, f in img.frames do
local fe = take(f.image)
if fe then
return nil, fe
end
end
end
table.sort(images, function(a: Types.Image, c: Types.Image): boolean
return a.width < c.width
end)
local encodeImage = opts and opts.encodeImage
local legacy = (opts and opts.legacy) or encodeImage == nil
local body = Bytes.writer()
local function chunk(id: string, data: buffer)
body:string(id)
body:u32be(buffer.len(data) + 8)
body:bytes(data)
end
for _, im in images do
local s = im.width
if legacy and LEGACY[s] then
local types = LEGACY[s]
local w = Bytes.writer()
if s == 128 then
w:u32be(0)
end
for ch = 0, 2 do
rle(w, im.pixels, ch, s * s)
end
chunk(types[1], w:finish())
local m = buffer.create(s * s)
for i = 0, s * s - 1 do
buffer.writeu8(m, i, readu8(im.pixels, i * 4 + 3))
end
chunk(types[2], m)
elseif encodeImage and PNG_TYPES[s] then
local ok, png, perr = pcall(encodeImage, im, "png")
if not ok or not png then
return nil, Err.new(Err.ARG, "PNG entry " .. s .. ": " .. tostring(if ok then perr else png))
end
chunk(PNG_TYPES[s], png :: buffer)
else
return nil, Err.new(Err.ARG, string.format("no icns entry for %d x %d%s", s, s, if encodeImage then "" else " without an encodeImage hook (16 / 32 / 48 / 128 only)"))
end
end
local data = body:finish()
local out = Bytes.writer(buffer.len(data) + 8)
out:string("icns")
out:u32be(buffer.len(data) + 8)
out:bytes(data)
return out:finish(), nil
end
return Icns
+99
View File
@@ -0,0 +1,99 @@
--!strict
--!native
--!optimize 2
-- image/ico/Dib: the BMP device-independent bitmaps inside ICO / CUR entries (native; never throws). Written from
-- the Microsoft ICO / BITMAPINFOHEADER documentation: a colour (XOR) bitmap of 1 / 4 / 8 / 16 (5-5-5) / 24 / 32-bit
-- pixels, bottom-up rows padded to 4 bytes, then a 1-bit AND mask (1 = transparent). 32-bit entries use their alpha
-- channel unless it is all zero (old icons), in which case the AND mask decides. The row loops are
-- codecs/image/Pixels (shared with BMP); the AND mask and the alpha rule are ICO's.
local Pixels = require("@rosetta/codecs/image/Pixels")
local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32
local Dib = {}
-- decode(b, p, e, w, h, bpp, pal, palN, out) -> ok, message: the XOR + AND bitmaps at b[p, e) into rgba8 out
function Dib.decode(b: buffer, p: number, e: number, w: number, h: number, bpp: number, pal: buffer, palN: number, out: buffer): (boolean, string?)
local stride = ((w * bpp + 31) // 32) * 4
local maskStride = ((w + 31) // 32) * 4
if p + stride * h > e then
return false, "colour bitmap runs past the entry"
end
local hasMask = p + stride * h + maskStride * h <= e
local anyAlpha = false
if bpp == 32 then
anyAlpha = Pixels.bgra32(b, p, stride, out, w, h, false) ~= 0
elseif bpp == 24 then
Pixels.bgr24(b, p, stride, out, w, h, false)
elseif bpp == 16 then
Pixels.rgb555(b, p, stride, out, w, h, false)
else
-- palette indexes past palN read as opaque black
local full = buffer.create(1024)
for i = 0, 255 do
writeu32(full, i * 4, if i < palN then readu32(pal, i * 4) else 0xFF000000)
end
Pixels.indexed(b, p, stride, bpp, out, w, h, false, full)
end
if bpp == 32 and anyAlpha then
return true, nil
end
if hasMask then
local mp = p + stride * h
for y = 0, h - 1 do
local row = mp + (h - 1 - y) * maskStride
for x = 0, w - 1 do
local o = (y * w + x) * 4
local px = readu32(out, o) % 16777216
if (readu8(b, row + x // 8) // 2 ^ (7 - x % 8)) % 2 == 1 then
writeu32(out, o, px) -- transparent
else
writeu32(out, o, px + 0xFF000000)
end
end
end
elseif bpp == 32 then
-- no alpha and no mask: opaque
for i = 0, w * h - 1 do
writeu32(out, i * 4, readu32(out, i * 4) % 16777216 + 0xFF000000)
end
end
return true, nil
end
-- encode(px, w, h, out, o) -> new offset: rgba8 as a 32-bit BGRA bitmap (bottom-up) + an AND mask (alpha 0 = 1).
-- out needs room for w * h * 4 + maskStride * h bytes.
function Dib.encode(px: buffer, w: number, h: number, out: buffer, o: number): number
for y = h - 1, 0, -1 do
for x = 0, w - 1 do
local q = (y * w + x) * 4
buffer.writeu8(out, o, readu8(px, q + 2))
buffer.writeu8(out, o + 1, readu8(px, q + 1))
buffer.writeu8(out, o + 2, readu8(px, q))
buffer.writeu8(out, o + 3, readu8(px, q + 3))
o += 4
end
end
local maskStride = ((w + 31) // 32) * 4
for y = h - 1, 0, -1 do
local acc, nb, written = 0, 0, 0
for x = 0, w - 1 do
acc = acc * 2 + (if readu8(px, (y * w + x) * 4 + 3) == 0 then 1 else 0)
nb += 1
if nb == 8 then
buffer.writeu8(out, o + written, acc)
written += 1
acc, nb = 0, 0
end
end
if nb > 0 then
buffer.writeu8(out, o + written, acc * 2 ^ (8 - nb))
written += 1
end
buffer.fill(out, o + written, 0, maskStride - written)
o += maskStride
end
return o
end
return Dib
+282
View File
@@ -0,0 +1,282 @@
--!strict
-- image/ico: Windows icons and cursors (ICO / CUR), written from Microsoft's ICO format documentation. Decode: every
-- directory entry, as a BMP DIB (1 / 4 / 8 / 16 / 24 / 32-bit with a colour table and the AND mask; 32-bit alpha) or
-- an embedded PNG, decoded through the api hook opts.decodeImage (F.load supplies it; without it PNG entries are
-- skipped, and a file of PNG entries only returns UNSUPPORTED). The image is the largest entry (then the deepest);
-- img.frames lists every decoded entry in file order (Types.Frame, each frame image with meta.source.bitDepth / png
-- and, for cursors, meta.hotspot = { x, y }). Encode: the image, or every img.frames image (each up to 256 x 256), as
-- 32-bit DIB entries with an AND mask; 256-pixel entries (or all with opts.png) as PNG through opts.encodeImage when it
-- is there; a cursor (CUR) with opts.cursor or when the image has meta.hotspot.
-- Not supported: resizing to a set of icon sizes (do that with ops/ImageOps first), DIB compression (BI_BITFIELDS
-- 16 / 32-bit is read as 5-5-5 / BGRA), the obsolete 2-colour planes.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Dib = require("@rosetta/image/ico/Dib")
-- ------------------------------------------------------------------------------------------------ contract
local Ico = {
name = "ico",
category = "image",
extensions = { "ico", "cur" },
mime = { "image/vnd.microsoft.icon", "image/x-icon" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels" },
caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 4, 8, 16, 24, 32 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes PNG entries (the api passes one)
maxPixels: number?, -- refuse larger entries (default 2^26)
}
export type EncodeOptions = {
encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes PNG entries (the api passes one)
png: boolean?, -- every entry as PNG (needs encodeImage; default: only 256-pixel entries, when it exists)
cursor: boolean?, -- write a CUR (default: when the image has meta.hotspot)
}
-- ------------------------------------------------------------------------------------------------ constants
local PNG_SIG = "\137PNG\r\n\26\n"
local readu8 = buffer.readu8
-- ------------------------------------------------------------------------------------------------ sniff
function Ico.sniff(r: Bytes.Reader): number
if r:remaining() < 22 then
return 0
end
local b, o = r.buf, r.pos
local typ = buffer.readu16(b, o + 2)
local count = buffer.readu16(b, o + 4)
if buffer.readu16(b, o) ~= 0 or (typ ~= 1 and typ ~= 2) or count == 0 then
return 0
end
-- the first entry: reserved byte 0, a size and offset inside the file
local size, off = buffer.readu32(b, o + 14), buffer.readu32(b, o + 18)
if readu8(b, o + 9) ~= 0 or size == 0 or off < 6 + count * 16 then
return 0
end
return 0.8
end
-- ------------------------------------------------------------------------------------------------ decode
local function le16(b: buffer, p: number): number
return buffer.readu16(b, p)
end
local function le32(b: buffer, p: number): number
return buffer.readu32(b, p)
end
function Ico.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local maxPixels = opts and opts.maxPixels or 2 ^ 26
local decodeImage = opts and opts.decodeImage
local b, base, limit = r.buf, r.base, r.limit
if limit - base < 6 then
return nil, Err.new(Err.TRUNCATED, "short header", base)
end
local typ, count = le16(b, base + 2), le16(b, base + 4)
if le16(b, base) ~= 0 or (typ ~= 1 and typ ~= 2) then
return nil, Err.new(Err.CORRUPT, "not an ICO / CUR file", base)
end
if count == 0 then
return nil, Err.new(Err.CORRUPT, "no images", base)
end
if base + 6 + count * 16 > limit then
return nil, Err.new(Err.TRUNCATED, "directory runs past the end", base)
end
local frames: { Types.Frame } = {}
local best: Types.Image? = nil
local bestScore = -1
local skipped, lastErr = 0, nil :: Err.Err?
for i = 0, count - 1 do
local d = base + 6 + i * 16
local dw, dh = readu8(b, d), readu8(b, d + 1)
dw = if dw == 0 then 256 else dw
dh = if dh == 0 then 256 else dh
local f1, f2 = le16(b, d + 4), le16(b, d + 6)
local size, off = le32(b, d + 8), le32(b, d + 12)
local p, e = base + off, base + off + size
local img: Types.Image? = nil
local depth = 0
local isPng = false
if off < 6 or p >= limit then
lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. " lies past the end", d)
else
e = math.min(e, limit)
if e - p >= 8 and buffer.readstring(b, p, 8) == PNG_SIG then
isPng = true
depth = 32
if decodeImage then
local sub = buffer.create(e - p)
buffer.copy(sub, 0, b, p, e - p)
local ok, pimg, perr = pcall(decodeImage, sub)
if ok and pimg and pimg.format == "rgba8" then
img = pimg
else
lastErr = if ok and perr then perr else Err.new(Err.CORRUPT, "entry " .. (i + 1) .. ": bad PNG")
end
else
lastErr = Err.new(Err.UNSUPPORTED, "PNG entries need opts.decodeImage (F.load passes it)")
end
elseif e - p >= 40 then
local hs = le32(b, p)
local bw = buffer.readi32(b, p + 4)
local bh = buffer.readi32(b, p + 8)
local bpp = le16(b, p + 14)
local clrUsed = le32(b, p + 32)
local w = if bw > 0 then bw else dw
local h = if bh ~= 0 then math.abs(bh) // 2 else dh
if hs < 12 or hs > e - p or w < 1 or h < 1 or w > 4096 or h > 4096 then
lastErr = Err.new(Err.CORRUPT, "entry " .. (i + 1) .. ": bad bitmap header", p)
elseif bpp ~= 1 and bpp ~= 4 and bpp ~= 8 and bpp ~= 16 and bpp ~= 24 and bpp ~= 32 then
lastErr = Err.new(Err.UNSUPPORTED, "entry " .. (i + 1) .. ": " .. bpp .. "-bit bitmap", p)
elseif w * h > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
else
depth = bpp
local q = p + hs
local palN = 0
local pal = buffer.create(4)
if bpp <= 8 then
palN = if clrUsed > 0 and clrUsed < 2 ^ bpp then clrUsed else 2 ^ bpp
if q + palN * 4 > e then
palN = 0
lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. ": colour table runs past the entry", q)
else
pal = buffer.create(palN * 4)
for k = 0, palN - 1 do
local c = q + k * 4
buffer.writeu32(pal, k * 4, readu8(b, c + 2) + readu8(b, c + 1) * 256 + readu8(b, c) * 65536 + 0xFF000000)
end
q += palN * 4
end
end
if bpp > 8 or palN > 0 then
if bpp == 16 and le32(b, p + 16) == 3 then
q += 12 -- BI_BITFIELDS masks (assumed 5-5-5)
end
local out = Types.Image.new(w, h, "rgba8")
local ok, msg = Dib.decode(b, q, e, w, h, bpp, pal, palN, out.pixels)
if ok then
img = out
else
lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. ": " .. tostring(msg), q)
end
end
end
else
lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. " is too short", p)
end
end
if img then
local im = img :: Types.Image
im.meta.source = { format = "ico", bitDepth = depth, png = isPng, colorCount = readu8(b, d + 2) }
if typ == 2 then
im.meta.hotspot = { x = f1, y = f2 }
end
table.insert(frames, { image = im, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } :: Types.Frame)
local score = im.width * im.height * 64 + depth
if score > bestScore then
best, bestScore = im, score
end
else
skipped += 1
end
end
if not best then
return nil, lastErr or Err.new(Err.CORRUPT, "no decodable entry")
end
local main = best :: Types.Image
local img = Types.Image.new(main.width, main.height, "rgba8")
buffer.copy(img.pixels, 0, main.pixels)
if #frames > 1 then
img.frames = frames
end
img.meta.source = { format = "ico", type = if typ == 2 then "cur" else "ico", bitDepth = main.meta.source and main.meta.source.bitDepth, entries = count, skipped = skipped, png = main.meta.source and main.meta.source.png }
img.meta.hotspot = main.meta.hotspot
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Ico.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(img) ~= "table" then
return nil, Err.new(Err.ARG, "needs an Image")
end
local o: any = opts or {}
local list: { Types.Image } = {}
if type(img.frames) == "table" and #img.frames > 0 then
for _, f in img.frames do
table.insert(list, f.image)
end
else
list[1] = img
end
local cursor = o.cursor
if cursor == nil then
cursor = type(img.meta) == "table" and img.meta.hotspot ~= nil
end
local blobs: { buffer } = {}
for i, im in list do
if type(im) ~= "table" or im.format ~= "rgba8" or type(im.pixels) ~= "buffer" then
return nil, Err.new(Err.ARG, "entry " .. i .. ": needs an rgba8 Image")
end
local w, h = im.width, im.height
if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w > 256 or h > 256 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(im.pixels) < w * h * 4 then
return nil, Err.new(Err.ARG, "entry " .. i .. ": icons are 1..256 pixels per side")
end
local png = nil
if o.encodeImage and (o.png or w == 256 or h == 256) then
local ok, res, err = pcall(o.encodeImage, im, "png")
if not ok or not res then
return nil, if ok and err then err else Err.new(Err.ARG, "entry " .. i .. ": PNG encode failed")
end
png = res
elseif o.png then
return nil, Err.new(Err.ARG, "opts.png needs opts.encodeImage (F.save passes it)")
end
if png then
blobs[i] = png
else
local maskStride = ((w + 31) // 32) * 4
local n = 40 + w * h * 4 + maskStride * h
local d = buffer.create(n)
buffer.writeu32(d, 0, 40)
buffer.writei32(d, 4, w)
buffer.writei32(d, 8, h * 2)
buffer.writeu16(d, 12, 1)
buffer.writeu16(d, 14, 32)
buffer.writeu32(d, 20, w * h * 4 + maskStride * h)
Dib.encode(im.pixels, w, h, d, 40)
blobs[i] = d
end
end
local total = 6 + #list * 16
for _, bl in blobs do
total += buffer.len(bl)
end
local out = buffer.create(total)
buffer.writeu16(out, 2, if cursor then 2 else 1)
buffer.writeu16(out, 4, #list)
local off = 6 + #list * 16
for i, im in list do
local d = 6 + (i - 1) * 16
buffer.writeu8(out, d, im.width % 256)
buffer.writeu8(out, d + 1, im.height % 256)
if cursor then
local hs = (type(im.meta) == "table" and im.meta.hotspot) or (img.meta and img.meta.hotspot) or { x = 0, y = 0 }
buffer.writeu16(out, d + 4, math.clamp(math.floor(tonumber(hs.x) or 0), 0, 65535))
buffer.writeu16(out, d + 6, math.clamp(math.floor(tonumber(hs.y) or 0), 0, 65535))
else
buffer.writeu16(out, d + 4, 1)
buffer.writeu16(out, d + 6, 32)
end
buffer.writeu32(out, d + 8, buffer.len(blobs[i]))
buffer.writeu32(out, d + 12, off)
buffer.copy(out, off, blobs[i])
off += buffer.len(blobs[i])
end
return out, nil
end
return Ico
+324
View File
@@ -0,0 +1,324 @@
--!strict
-- image/ilbm: IFF ILBM and PBM pictures (EA IFF 85 "ILBM" standard, the Amiga ROM Kernel Manual; new code; chunks
-- through containers/Chunks, ByteRun1 through codecs/compress/PackBits). Decode: planar ILBM with 1..8 planes and a
-- CMAP (grey without one), EHB (extra half-brite, CAMG 0x80), HAM6 / HAM8 (CAMG 0x800), deep 24 / 32-plane RGB(A),
-- chunky PBM (8-bit, Deluxe Paint), masking 1 (a mask plane) and 2 (a transparent colour index), uncompressed or
-- ByteRun1 bodies; opts.adjustColors scales 4-bit OCS palettes (all low nibbles zero) to 8 bits; NAME / ANNO / AUTH
-- text (meta.text). HAM channel values replicate their bits (4-bit v -> v * 17; ilbmtoppm shifts: v * 16). Encode: rgba8 as a planar ILBM: up to 256 opaque colours with a CMAP and the fewest planes, else
-- 24 planes (32 with alpha), ByteRun1 (default) or uncompressed. Not supported: animations (ANIM), the rarer
-- encodings (RGBN / RGB8 / ACBM / DEEP chunks: UNSUPPORTED), SHAM / PCHG palette changes (ignored).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Chunks = require("@rosetta/containers/Chunks")
local PackBits = require("@rosetta/codecs/compress/PackBits")
local Pixels = require("@rosetta/codecs/image/Pixels")
-- ------------------------------------------------------------------------------------------------ contract
local Ilbm = {
name = "ilbm",
category = "image",
extensions = { "iff", "ilbm", "lbm", "pbm" },
mime = { "image/x-ilbm", "image/x-iff" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/compress/PackBits", "codecs/image/Pixels" },
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 3, 4, 5, 6, 7, 8, 24, 32 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
adjustColors: boolean?, -- scale 4-bit OCS palettes (every low nibble 0) to 8 bits (default false)
maxPixels: number?, -- refuse larger images (default 2^26)
}
export type EncodeOptions = {
compress: boolean?, -- ByteRun1 (default true)
}
local readu8, readu16 = buffer.readu8, buffer.readu16
local function be16(b: buffer, o: number): number
return bit32.rshift(bit32.byteswap(readu16(b, o)), 16)
end
-- ------------------------------------------------------------------------------------------------ sniff
function Ilbm.sniff(r: Bytes.Reader): number
if r:peek(4) ~= "FORM" then
return 0
end
local t = r:peek(4, 8)
return if t == "ILBM" or t == "PBM " then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Ilbm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local b, o, limit = r.buf, r.base, r.limit
if limit - o < 12 or buffer.readstring(b, o, 4) ~= "FORM" then
return nil, Err.new(Err.CORRUPT, "not an IFF FORM", o)
end
local form = buffer.readstring(b, o + 8, 4)
if form ~= "ILBM" and form ~= "PBM " then
return nil, Err.new(Err.UNSUPPORTED, "FORM " .. form, o + 8)
end
local chunky = form == "PBM "
local list = Chunks.walk(b, o + 12, math.min(limit, o + 8 + bit32.byteswap(buffer.readu32(b, o + 4))), Chunks.IFF)
local bmhd, cmap, body = Chunks.find(list, "BMHD"), Chunks.find(list, "CMAP"), Chunks.find(list, "BODY")
if not bmhd or bmhd.avail < 20 then
return nil, Err.new(Err.CORRUPT, "missing BMHD", o + 12)
end
if not body then
return nil, Err.new(Err.TRUNCATED, "missing BODY", o + 12)
end
local q = bmhd.offset
local w, h = be16(b, q), be16(b, q + 2)
local planes, masking, comp = readu8(b, q + 8), readu8(b, q + 9), readu8(b, q + 10)
local trans = be16(b, q + 12)
if w == 0 or h == 0 then
return nil, Err.new(Err.CORRUPT, "bad size", q)
end
if comp > 1 then
return nil, Err.new(Err.UNSUPPORTED, "compression " .. comp, q + 10)
end
if not (planes >= 1 and planes <= 8 or planes == 24 or planes == 32) or (chunky and planes ~= 8) then
return nil, Err.new(Err.UNSUPPORTED, planes .. " planes", q + 8)
end
local maxPixels = opts and opts.maxPixels or 2 ^ 26
if w * h > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
end
local camg = 0
local c = Chunks.find(list, "CAMG")
if c and c.avail >= 4 then
camg = bit32.byteswap(buffer.readu32(b, c.offset))
end
local ham = bit32.band(camg, 0x800) ~= 0 and (planes == 6 or planes == 8)
local ehb = bit32.band(camg, 0x80) ~= 0 and planes == 6 and not ham
-- palette
local pal = buffer.create(1024)
local ncol = 0
if cmap then
ncol = math.min(256, cmap.avail // 3)
local low = true
for i = 0, ncol * 3 - 1 do
low = low and bit32.band(readu8(b, cmap.offset + i), 15) == 0
end
local adjust = low and opts and opts.adjustColors
for i = 0, ncol - 1 do
local function ch(k: number): number
local v = readu8(b, cmap.offset + i * 3 + k)
return if adjust then v + bit32.rshift(v, 4) else v
end
buffer.writeu32(pal, i * 4, ch(0) + ch(1) * 256 + ch(2) * 65536 + 0xFF000000)
end
end
if ncol == 0 and planes <= 8 then
local n = bit32.lshift(1, planes)
for i = 0, n - 1 do
local g = (i * 255) // math.max(1, n - 1)
buffer.writeu32(pal, i * 4, g * 0x10101 + 0xFF000000)
end
ncol = n
end
if ehb then
for i = 0, 31 do
local v = buffer.readu32(pal, i * 4)
local rr, gg, bb = bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255)
buffer.writeu32(pal, (32 + i) * 4, bit32.rshift(rr, 1) + bit32.rshift(gg, 1) * 256 + bit32.rshift(bb, 1) * 65536 + 0xFF000000)
end
end
-- the body, decompressed
local rowBytes = if chunky then w + w % 2 else ((w + 15) // 16) * 2
local total = if chunky then rowBytes * h else rowBytes * (planes + (if masking == 1 then 1 else 0)) * h
local raw = buffer.create(total)
local truncated
if comp == 1 then
local written = PackBits.decode(b, body.offset, body.offset + body.avail, raw, 0, total)
truncated = written < total
else
local n = math.min(total, body.avail)
buffer.copy(raw, 0, b, body.offset, n)
truncated = n < total
end
local img = Types.Image.new(w, h, "rgba8")
local px = img.pixels
if chunky then
Pixels.indexed(raw, 0, rowBytes, 8, px, w, h, true, pal)
if masking == 2 then
for i = 0, w * h - 1 do
local y, x = i // w, i % w
if readu8(raw, y * rowBytes + x) == trans then
buffer.writeu32(px, i * 4, 0)
end
end
end
else
local stride = rowBytes * (planes + (if masking == 1 then 1 else 0))
local deep = planes >= 24
local bits = planes - 2
for y = 0, h - 1 do
local row = y * stride
local pr: number, pg: number, pb: number = 0, 0, 0
if ham then
local v = buffer.readu32(pal, 0)
pr = bit32.band(v, 255)
pg = bit32.band(bit32.rshift(v, 8), 255)
pb = bit32.band(bit32.rshift(v, 16), 255)
end
for x = 0, w - 1 do
local byteAt, shift = bit32.rshift(x, 3), 7 - bit32.band(x, 7)
local idx = 0
for k = 0, planes - 1 do
idx += bit32.band(bit32.rshift(readu8(raw, row + k * rowBytes + byteAt), shift), 1) * 2 ^ k
end
local out: number
if deep then
local a = if planes == 32 then bit32.rshift(idx, 24) % 256 else 255
out = bit32.band(idx, 0xFFFFFF) + a * 16777216
elseif ham then
local ctl = bit32.rshift(idx, bits)
local val = bit32.band(idx, bit32.lshift(1, bits) - 1)
local v8 = if bits == 4 then val * 17 else val * 4 + bit32.rshift(val, 4)
if ctl == 0 then
local v = buffer.readu32(pal, val * 4)
pr = bit32.band(v, 255)
pg = bit32.band(bit32.rshift(v, 8), 255)
pb = bit32.band(bit32.rshift(v, 16), 255)
elseif ctl == 1 then
pb = v8
elseif ctl == 2 then
pr = v8
else
pg = v8
end
out = pr + pg * 256 + pb * 65536 + 0xFF000000
else
out = buffer.readu32(pal, bit32.band(idx, 255) * 4)
if masking == 2 and idx == trans then
out = 0
end
end
if masking == 1 then
local m = bit32.band(bit32.rshift(readu8(raw, row + planes * rowBytes + byteAt), shift), 1)
if m == 0 then
out = 0
end
end
buffer.writeu32(px, (y * w + x) * 4, out)
end
end
end
if ncol > 0 and planes <= 8 and not ham then
local plist: { { number } } = {}
for i = 0, (if ehb then 64 else ncol) - 1 do
local v = buffer.readu32(pal, i * 4)
plist[i + 1] = { bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255), 255 }
end
img.meta.palette = plist
end
local text: { [string]: string } = {}
for _, ch in list do
if ch.id == "NAME" or ch.id == "ANNO" or ch.id == "AUTH" or ch.id == "(c) " then
local s = buffer.readstring(b, ch.offset, ch.avail)
local key = string.gsub(ch.id, "[^%w]", "")
text[string.lower(key)] = (string.gsub(s, "%z+$", ""))
end
end
if next(text) then
img.meta.text = text
end
if truncated then
img.meta.truncated = true
end
img.meta.source = { format = "ilbm", form = form, planes = planes, bitDepth = planes, ham = ham, ehb = ehb, masking = masking, compression = comp, camg = camg }
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Ilbm.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, "needs an rgba8 Image")
end
local w, h = img.width, img.height
if w < 1 or h < 1 or w > 65535 or h > 65535 then
return nil, Err.new(Err.ARG, "size must be 1..65535")
end
local px = img.pixels
local cols, alpha = Pixels.colours(px, w * h, 256)
local usePal = not alpha and #cols <= 256
local planes = if usePal then 1 elseif alpha then 32 else 24
if usePal then
while bit32.lshift(1, planes) < #cols do
planes += 1
end
end
local compress = not (opts and opts.compress == false)
local index: { [number]: number } = {}
for i, cv in cols do
index[cv] = i - 1
end
local rowBytes = ((w + 15) // 16) * 2
local body = Bytes.writer(rowBytes * planes * h)
local row = buffer.create(rowBytes)
for y = 0, h - 1 do
for k = 0, planes - 1 do
buffer.fill(row, 0, 0, rowBytes)
for x = 0, w - 1 do
local v = buffer.readu32(px, (y * w + x) * 4)
local idx = if usePal then (index[bit32.band(v, 0xFFFFFF)] or 0) else v
if bit32.band(bit32.rshift(idx, k), 1) == 1 then
local at = bit32.rshift(x, 3)
buffer.writeu8(row, at, bit32.bor(readu8(row, at), bit32.rshift(0x80, bit32.band(x, 7))))
end
end
if compress then
body:bytes(PackBits.encode(row, 0, rowBytes))
else
body:bytes(row)
end
end
end
local bodyData = body:finish()
local out = Bytes.writer(buffer.len(bodyData) + 900)
out:string("FORM")
out:u32be(0)
out:string("ILBM")
out:string("BMHD")
out:u32be(20)
out:u16be(w)
out:u16be(h)
out:u16be(0)
out:u16be(0)
out:u8(planes)
out:u8(0)
out:u8(if compress then 1 else 0)
out:u8(0)
out:u16be(0)
out:u8(1)
out:u8(1)
out:u16be(w)
out:u16be(h)
if usePal then
local n = bit32.lshift(1, planes)
out:string("CMAP")
out:u32be(n * 3)
for i = 1, n do
local cv = cols[i] or 0
out:u8(bit32.band(cv, 255))
out:u8(bit32.band(bit32.rshift(cv, 8), 255))
out:u8(bit32.rshift(cv, 16))
end
if (n * 3) % 2 == 1 then
out:u8(0)
end
end
out:string("BODY")
out:u32be(buffer.len(bodyData))
out:bytes(bodyData)
if buffer.len(bodyData) % 2 == 1 then
out:u8(0)
end
local res = out:finish()
buffer.writeu32(res, 4, bit32.byteswap(buffer.len(res) - 8))
return res, nil
end
return Ilbm
+149
View File
@@ -0,0 +1,149 @@
--!strict
-- image/jpeg: JPEG / JFIF / EXIF (ITU T.81), a thin format over codecs/image/Jpeg (the engine, shared with the Motion-JPEG
-- video tracks; absorbed from jpeg-luau 1.0, same author, bit-exact with libjpeg-turbo's djpeg and byte-identical
-- with cjpeg; IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md). This module is the contract, the sniff, the
-- options and the meta segments: meta.exif (APP1), meta.icc (APP2 chunks), meta.text.comment (COM) and meta.dpi
-- (JFIF density) are written from the Image on encode and read back on decode. Encode also takes yuv420p Images
-- (coded 4:2:0 from the planes as they are).
-- Decode: baseline, extended and progressive frames, Huffman or arithmetic coded (SOF0/1/2/9/10), 8 and 12-bit
-- samples, 1, 3 or 4 components with any sampling factors 1..4, restart intervals (resynchronising after corrupt
-- data), grey / YCbCr / RGB / CMYK / YCCK (Adobe APP14), scaled decodes (opts.scale = 2, 4, 8 through libjpeg's
-- reduced IDCTs), EXIF orientation reported in meta.orientation and applied with opts.orient. Truncated or corrupt
-- scans decode as far as they go (meta.truncated = true).
-- Encode: baseline (standard or optimised Huffman tables) and progressive (libjpeg's simple progression), grey or
-- YCbCr 4:4:4 / 4:2:2 / 4:2:0, libjpeg quality tables, restart intervals, EXIF / ICC / comment segments from meta;
-- byte-identical to cjpeg for the same settings.
-- Not supported: lossless (SOF3) and hierarchical frames, DNL, 2-component images, ICC colour management, 12-bit
-- or CMYK encoding.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Codec = require("@rosetta/codecs/image/Jpeg")
-- ------------------------------------------------------------------------------------------------ contract
local Jpeg = {
name = "jpeg",
category = "image",
extensions = { "jpg", "jpeg", "jpe", "jfif" },
mime = { "image/jpeg" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Jpeg" },
caps = { decode = true, encode = true, lossy = true, alpha = false, depths = { 8, 12 }, progressive = true, arithmetic = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
scale: number?, -- 1 (default), 2, 4 or 8: decode at ceil(size / scale) (8 reads the DC coefficients only)
orient: boolean?, -- apply the EXIF orientation (default false: reported in meta.orientation only)
native: boolean?, -- grey files decode to gray8 (default false: rgba8)
maxPixels: number?, -- refuse larger images (default 2^26)
}
export type EncodeOptions = {
quality: number?, -- 1..100 (default 90), libjpeg's scaling of the T.81 annex K tables
subsampling: ("420" | "422" | "444")?, -- chroma subsampling (default "420")
progressive: boolean?, -- default false
optimize: boolean?, -- optimised Huffman tables for baseline files (default false; progressive always optimises)
gray: boolean?, -- a one-component file (default: true for gray8 images)
restart: number?, -- restart interval in MCUs (default 0 = none)
jfif: boolean?, -- write the JFIF APP0 header (default true)
meta: boolean?, -- write meta.exif (APP1), meta.icc (APP2) and meta.text.comment (COM) (default true)
}
export type Info = Codec.Info
-- ------------------------------------------------------------------------------------------------ sniff
function Jpeg.sniff(r: Bytes.Reader): number
local s = r:peek(3)
return if s == "\255\216\255" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- info(r) -> Info | nil, Err (reads the headers up to the frame header)
function Jpeg.info(r: Bytes.Reader): (Info?, Err.Err?)
return Codec.info(r.buf, r.base, r.limit - r.base)
end
function Jpeg.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
if opts ~= nil and type(opts) ~= "table" then
return nil, Err.new(Err.ARG, "options must be a table")
end
local o = opts or {} :: DecodeOptions
-- one image: no yuv output, no field weaving (two JPEGs back to back are an image and a preview, as in MPF)
return Codec.decode(r.buf, r.base, r.limit - r.base, {
scale = o.scale,
orient = o.orient,
native = o.native,
maxPixels = o.maxPixels,
fields = false,
})
end
-- ------------------------------------------------------------------------------------------------ encode
-- the APP1 / APP2 / COM segments and the JFIF density from img.meta
local function metaSegments(meta: any): ({ { marker: number, data: buffer } }, { unit: number, x: number, y: number }?)
local segments = {}
if type(meta.exif) == "buffer" and buffer.len(meta.exif) <= 65527 then
local d = buffer.create(buffer.len(meta.exif) + 6)
buffer.writestring(d, 0, "Exif\0\0")
buffer.copy(d, 6, meta.exif)
table.insert(segments, { marker = 0xE1, data = d })
end
if type(meta.icc) == "buffer" then
local icc = meta.icc :: buffer
local n = buffer.len(icc)
local chunk = 65519
local count = math.max(1, math.ceil(n / chunk))
if count <= 255 then
for i = 1, count do
local a = (i - 1) * chunk
local l = math.min(chunk, n - a)
local d = buffer.create(l + 14)
buffer.writestring(d, 0, "ICC_PROFILE\0")
buffer.writeu8(d, 12, i)
buffer.writeu8(d, 13, count)
buffer.copy(d, 14, icc, a, l)
table.insert(segments, { marker = 0xE2, data = d })
end
end
end
local text = meta.text
if type(text) == "table" and type(text.comment) == "string" and #text.comment <= 65533 then
table.insert(segments, { marker = 0xFE, data = buffer.fromstring(text.comment) })
end
local density = nil
if type(meta.dpi) == "table" and type(meta.dpi.x) == "number" and type(meta.dpi.y) == "number" then
density = { unit = 1, x = math.clamp(math.floor(meta.dpi.x + 0.5), 1, 65535), y = math.clamp(math.floor(meta.dpi.y + 0.5), 1, 65535) }
end
return segments, density
end
function Jpeg.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(img) ~= "table" then
return nil, Err.new(Err.ARG, "needs an Image")
end
if opts ~= nil and type(opts) ~= "table" then
return nil, Err.new(Err.ARG, "options must be a table")
end
local o: any = opts or {}
local segments, density = {}, nil
if o.meta ~= false then
segments, density = metaSegments(img.meta or {})
elseif type(img.meta) == "table" then
local _
_, density = metaSegments({ dpi = img.meta.dpi })
end
return Codec.encode(img, {
quality = o.quality,
subsampling = o.subsampling,
progressive = o.progressive,
optimize = o.optimize,
gray = o.gray,
restart = o.restart,
jfif = o.jfif,
density = density,
segments = segments,
})
end
return Jpeg
+672
View File
@@ -0,0 +1,672 @@
--!strict
-- image/ktx: Khronos texture containers (KTX 1.1 and KTX 2.0 specifications; new code). Decode: KTX1 (OpenGL
-- glInternalFormat / glFormat + glType: the S3TC / RGTC / BPTC / ETC1 / ETC2 / EAC compressed formats and the
-- uncompressed ones with 4-byte row alignment; big-endian files) and KTX2 (VkFormat: BCn, ETC2 / EAC and every
-- uncompressed format codecs/image/Texel knows; Zstandard (codecs/compress/Zstd) and ZLIB supercompression); mip
-- levels, cube maps, arrays and 3D textures, the key / value data (meta.keyValue) and KTXorientation (T=u rows are
-- flipped). Like image/dds: the first surface is the image, img.frames lists every face / layer / slice when there is
-- more than one (meta.layout), opts.mips decodes the smaller levels into img.meta.mipmaps; rgba8 unless opts.native.
-- Encode: KTX2, uncompressed: rgba8 (R8G8B8A8_UNORM, or _SRGB when meta.colorSpace is "srgb"), rgba16
-- (R16G16B16A16_UNORM), rgbaf32 (R32G32B32A32_SFLOAT or R16G16B16A16_SFLOAT), with a full DFD, optional mip chain,
-- frames as layers or cube faces, optional ZLIB supercompression. Not supported: Basis Universal (BasisLZ / ETC1S and
-- UASTC: UNSUPPORTED), ASTC and PVRTC, writing KTX1 or Zstandard.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Sniff = require("@rosetta/core/Sniff")
local Types = require("@rosetta/Types")
local Deflate = require("@rosetta/codecs/compress/Deflate")
local Zstd = require("@rosetta/codecs/compress/Zstd")
local Texel = require("@rosetta/codecs/image/Texel")
local Texture = require("@rosetta/codecs/image/Texture")
-- ------------------------------------------------------------------------------------------------ contract
local Ktx = {
name = "ktx",
category = "image",
extensions = { "ktx2", "ktx" },
mime = { "image/ktx2", "image/ktx" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/image/Texel", "codecs/image/Texture" },
caps = { decode = true, encode = true, alpha = true, float = true, mipmaps = true, cubemap = true, compressed = { "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7", "etc1", "etc2", "eac" } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
native: boolean?, -- keep rgbaf32 / rgba16 for float / 16-bit / BC6H / EAC sources (default false: rgba8)
mips: boolean?, -- decode the smaller mip levels of the first surface into img.meta.mipmaps (default false)
surfaces: boolean?, -- decode every face / layer / slice into img.frames (default true)
maxPixels: number?, -- refuse larger images (default 2^26, over every decoded surface)
}
export type EncodeOptions = {
pixelFormat: ("rgba8" | "rgba16" | "rgba16f" | "rgba32f")?, -- default: the image's own (rgbaf32 -> rgba32f)
srgb: boolean?, -- rgba8 as R8G8B8A8_SRGB (default: meta.colorSpace == "srgb")
mips: boolean?, -- a full mip chain (box filter; default false)
cube: boolean?, -- img.frames as cube faces (default: meta.layout == "cube")
zlib: number?, -- ZLIB-supercompress every level at this level 1..9 (default none)
keyValue: { [string]: string }?, -- extra key / value pairs (KTXwriter is always written)
}
-- ------------------------------------------------------------------------------------------------ constants
local ID1 = "\171KTX 11\187\r\n\26\n"
local ID2 = "\171KTX 20\187\r\n\26\n"
-- VkFormat -> texture format name
local VK: { [number]: string } = {
[2] = "a4b4g4r4", [3] = "a4r4g4b4", [4] = "b5g6r5", [5] = "r5g6b5", [6] = "a1b5g5r5", [7] = "a1r5g5b5", [8] = "b5g5r5a1",
[9] = "r8", [10] = "r8s", [13] = "r8ui", [14] = "r8i", [15] = "r8",
[16] = "rg8", [17] = "rg8s", [20] = "rg8ui", [21] = "rg8i", [22] = "rg8",
[23] = "rgb8", [24] = "rgb8s", [27] = "rgb8ui", [28] = "rgb8i", [29] = "rgb8",
[30] = "bgr8", [36] = "bgr8",
[37] = "rgba8", [38] = "rgba8s", [41] = "rgba8ui", [42] = "rgba8i", [43] = "rgba8",
[44] = "bgra8", [50] = "bgra8",
[58] = "bgr10a2", [64] = "rgb10a2",
[70] = "r16", [71] = "r16s", [74] = "r16ui", [75] = "r16i", [76] = "r16f",
[77] = "rg16", [78] = "rg16s", [81] = "rg16ui", [82] = "rg16i", [83] = "rg16f",
[84] = "rgb16", [85] = "rgb16s", [88] = "rgb16ui", [89] = "rgb16i", [90] = "rgb16f",
[91] = "rgba16", [92] = "rgba16s", [95] = "rgba16ui", [96] = "rgba16i", [97] = "rgba16f",
[98] = "r32ui", [99] = "r32i", [100] = "r32f", [101] = "rg32ui", [102] = "rg32i", [103] = "rg32f",
[104] = "rgb32ui", [105] = "rgb32i", [106] = "rgb32f", [107] = "rgba32ui", [108] = "rgba32i", [109] = "rgba32f",
[122] = "r11g11b10f", [123] = "rgb9e5", [124] = "r16", [126] = "r32f",
[131] = "bc1", [132] = "bc1", [133] = "bc1", [134] = "bc1", [135] = "bc2", [136] = "bc2", [137] = "bc3", [138] = "bc3",
[139] = "bc4", [140] = "bc4s", [141] = "bc5", [142] = "bc5s", [143] = "bc6h", [144] = "bc6hs", [145] = "bc7", [146] = "bc7",
[147] = "etc2_rgb", [148] = "etc2_rgb", [149] = "etc2_rgba1", [150] = "etc2_rgba1", [151] = "etc2_rgba", [152] = "etc2_rgba",
[153] = "eac_r11", [154] = "eac_r11s", [155] = "eac_rg11", [156] = "eac_rg11s",
}
local VK_SRGB = { [15] = true, [22] = true, [29] = true, [36] = true, [43] = true, [50] = true, [132] = true, [134] = true, [136] = true, [138] = true, [146] = true, [148] = true, [150] = true, [152] = true }
local VK_OPAQUE = { [131] = true, [132] = true } -- BC1 RGB: the 3-colour mode's index 3 is opaque black
-- OpenGL compressed internal formats
local GL_COMPRESSED: { [number]: string } = {
[0x83F0] = "bc1", [0x83F1] = "bc1", [0x83F2] = "bc2", [0x83F3] = "bc3",
[0x8C4C] = "bc1", [0x8C4D] = "bc1", [0x8C4E] = "bc2", [0x8C4F] = "bc3",
[0x8DBB] = "bc4", [0x8DBC] = "bc4s", [0x8DBD] = "bc5", [0x8DBE] = "bc5s",
[0x8E8C] = "bc7", [0x8E8D] = "bc7", [0x8E8E] = "bc6hs", [0x8E8F] = "bc6h",
[0x8D64] = "etc1", [0x9274] = "etc2_rgb", [0x9275] = "etc2_rgb", [0x9276] = "etc2_rgba1", [0x9277] = "etc2_rgba1",
[0x9278] = "etc2_rgba", [0x9279] = "etc2_rgba", [0x9270] = "eac_r11", [0x9271] = "eac_r11s", [0x9272] = "eac_rg11", [0x9273] = "eac_rg11s",
}
local GL_SRGB = { [0x8C4C] = true, [0x8C4D] = true, [0x8C4E] = true, [0x8C4F] = true, [0x8E8D] = true, [0x9275] = true, [0x9277] = true, [0x9279] = true, [0x8C41] = true, [0x8C43] = true }
local GL_OPAQUE = { [0x83F0] = true, [0x8C4C] = true }
-- glFormat -> channel order; glType -> bit size, Texel suffix
local GL_ORDER: { [number]: string } = {
[0x1903] = "r", [0x8227] = "rg", [0x1907] = "rgb", [0x1908] = "rgba", [0x80E0] = "bgr", [0x80E1] = "bgra",
[0x1909] = "l", [0x190A] = "la", [0x1906] = "a",
[0x8D94] = "r", [0x8228] = "rg", [0x8D98] = "rgb", [0x8D99] = "rgba", -- the _INTEGER formats
}
local GL_INTEGER = { [0x8D94] = true, [0x8228] = true, [0x8D98] = true, [0x8D99] = true }
local GL_PACKED: { [number]: string } = {
[0x8363] = "b5g6r5", [0x8033] = "a4b4g4r4", [0x8034] = "a1b5g5r5", [0x8368] = "rgb10a2", [0x8C3B] = "r11g11b10f", [0x8C3E] = "rgb9e5",
}
local GL_TYPES: { [number]: { any } } = {
[0x1401] = { 8, "", "ui" }, [0x1400] = { 8, "s", "i" }, [0x1403] = { 16, "", "ui" }, [0x1402] = { 16, "s", "i" },
[0x1405] = { 32, "ui", "ui" }, [0x1404] = { 32, "i", "i" }, [0x140B] = { 16, "f", "f" }, [0x1406] = { 32, "f", "f" },
}
local FACES = { "+x", "-x", "+y", "-y", "+z", "-z" }
local readu32, readstring = buffer.readu32, buffer.readstring
-- ------------------------------------------------------------------------------------------------ sniff
function Ktx.sniff(r: Bytes.Reader): number
return math.max(Sniff.magic(r, ID2), Sniff.magic(r, ID1))
end
-- ------------------------------------------------------------------------------------------------ decode
export type Info = {
version: number, -- 1 or 2
width: number,
height: number,
depth: number, -- 1 for 2D
layers: number,
faces: number,
levels: number,
format: string?, -- the texture format name (nil when unsupported: see unsupported)
unsupported: string?,
srgb: boolean,
opaque: boolean, -- BC1 RGB
vkFormat: number?,
glInternalFormat: number?,
supercompression: number?,
keyValue: { [string]: string },
bigEndian: boolean?,
typeSize: number,
dataOffset: number, -- KTX1: the first imageSize field (relative to the file)
levelIndex: { { offset: number, length: number, uncompressed: number } }?, -- KTX2
}
local function u64(b: buffer, o: number): number
return readu32(b, o) + readu32(b, o + 4) * 4294967296
end
-- key / value pairs from [p, stop): u32 length, key NUL value, padding to 4
local function keyValues(b: buffer, p: number, stop: number, be: boolean): { [string]: string }
local kv: { [string]: string } = {}
while p + 4 <= stop do
local n = readu32(b, p)
if be then
n = bit32.byteswap(n)
end
p += 4
if n > stop - p then
break
end
local s = readstring(b, p, n)
local z = string.find(s, "\0", 1, true)
if z then
local v = string.sub(s, z + 1)
if string.sub(v, -1) == "\0" then
v = string.sub(v, 1, -2)
end
kv[string.sub(s, 1, z - 1)] = v
end
p += n + (3 - (n + 3) % 4)
end
return kv
end
local function info1(r: Bytes.Reader): (Info?, Err.Err?)
local b, o, n = r.buf, r.base, r.limit - r.base
if n < 64 then
return nil, Err.new(Err.TRUNCATED, "short KTX1 header", o)
end
local e = readu32(b, o + 12)
local be = e == 0x01020304
if not be and e ~= 0x04030201 then
return nil, Err.new(Err.CORRUPT, "bad endianness field", o + 12)
end
local function f(i: number): number
local v = readu32(b, o + 16 + i * 4)
return if be then bit32.byteswap(v) else v
end
local glType, typeSize, glFormat, internal = f(0), f(1), f(2), f(3)
local w, h, d, arr, faces, levels, kvBytes = f(5), f(6), f(7), f(8), f(9), f(10), f(11)
if w == 0 or w > 65536 or h > 65536 or d > 2048 or arr > 4096 or (faces ~= 1 and faces ~= 6) or levels > 32 then
return nil, Err.new(Err.CORRUPT, "bad KTX1 header", o + 16)
end
if 64 + kvBytes > n then
return nil, Err.new(Err.TRUNCATED, "key / value data runs past the end", o + 64)
end
local info: Info = {
version = 1,
width = w,
height = math.max(1, h),
depth = math.max(1, d),
layers = math.max(1, arr),
faces = faces,
levels = math.max(1, levels),
srgb = GL_SRGB[internal] == true,
opaque = GL_OPAQUE[internal] == true,
glInternalFormat = internal,
keyValue = keyValues(b, o + 64, o + 64 + kvBytes, be),
bigEndian = be,
typeSize = typeSize,
dataOffset = 64 + kvBytes,
}
if glType == 0 then
info.format = GL_COMPRESSED[internal]
if not info.format then
info.unsupported = string.format("compressed glInternalFormat 0x%04X", internal)
end
else
local name = GL_PACKED[glType]
if not name then
local order = GL_ORDER[glFormat]
local int = GL_INTEGER[glFormat] == true
-- glType -> component bits, Texel suffix (normalized / integer)
local t = GL_TYPES[glType]
local size: number? = t and t[1]
local suffix: string = if t then (if int then t[3] else t[2]) else ""
if order and size then
name = order .. tostring(size) .. suffix
end
end
if name and Texel.FORMATS[name] then
info.format = name
else
info.unsupported = string.format("glFormat 0x%04X / glType 0x%04X", glFormat, glType)
end
end
return info, nil
end
local function info2(r: Bytes.Reader): (Info?, Err.Err?)
local b, o, n = r.buf, r.base, r.limit - r.base
if n < 80 then
return nil, Err.new(Err.TRUNCATED, "short KTX2 header", o)
end
local vk, typeSize = readu32(b, o + 12), readu32(b, o + 16)
local w, h, d = readu32(b, o + 20), readu32(b, o + 24), readu32(b, o + 28)
local layers, faces, levels, scheme = readu32(b, o + 32), readu32(b, o + 36), readu32(b, o + 40), readu32(b, o + 44)
if w == 0 or w > 65536 or h > 65536 or d > 2048 or layers > 4096 or (faces ~= 1 and faces ~= 6) or levels > 32 then
return nil, Err.new(Err.CORRUPT, "bad KTX2 header", o + 20)
end
local nl = math.max(1, levels)
if 80 + nl * 24 > n then
return nil, Err.new(Err.TRUNCATED, "level index runs past the end", o + 80)
end
local dfdOff, dfdLen, kvOff, kvLen = readu32(b, o + 48), readu32(b, o + 52), readu32(b, o + 56), readu32(b, o + 60)
local info: Info = {
version = 2,
width = w,
height = math.max(1, h),
depth = math.max(1, d),
layers = math.max(1, layers),
faces = faces,
levels = nl,
srgb = VK_SRGB[vk] == true,
opaque = VK_OPAQUE[vk] == true,
vkFormat = vk,
supercompression = scheme,
keyValue = if kvLen > 0 and kvOff + kvLen <= n then keyValues(b, o + kvOff, o + kvOff + kvLen, false) else {},
typeSize = typeSize,
dataOffset = 0,
levelIndex = {},
}
for i = 0, nl - 1 do
local q = o + 80 + i * 24
table.insert(info.levelIndex :: any, { offset = u64(b, q), length = u64(b, q + 8), uncompressed = u64(b, q + 16) })
end
-- the colour model of the DFD tells Basis Universal apart
local model = -1
if dfdLen >= 16 and dfdOff + dfdLen <= n then
model = buffer.readu8(b, o + dfdOff + 12)
if buffer.readu8(b, o + dfdOff + 14) == 2 then
info.srgb = true
end
end
if scheme == 1 or model == 163 then
info.unsupported = "Basis Universal ETC1S / BasisLZ"
elseif model == 166 then
info.unsupported = "Basis Universal UASTC"
elseif scheme > 3 then
info.unsupported = "supercompression scheme " .. scheme
elseif vk == 0 then
info.unsupported = "VK_FORMAT_UNDEFINED"
else
info.format = VK[vk]
if not info.format then
info.unsupported = "VkFormat " .. vk .. (if vk >= 157 and vk <= 184 or vk >= 1000066000 then " (ASTC)" else "")
end
end
return info, nil
end
-- info(r) -> Info | nil, Err (the headers only)
function Ktx.info(r: Bytes.Reader): (Info?, Err.Err?)
local id = r:peek(12)
if id == ID2 then
return info2(r)
elseif id == ID1 then
return info1(r)
end
return nil, Err.new(Err.CORRUPT, "not a KTX file", r.base)
end
-- reverses the bytes of every typeSize-wide element of a big-endian KTX1 image
local function swapped(b: buffer, p: number, n: number, size: number): buffer
local out = buffer.create(n)
buffer.copy(out, 0, b, p, n)
for i = 0, n - size, size do
if size == 2 then
buffer.writeu16(out, i, bit32.rshift(bit32.byteswap(buffer.readu16(out, i)), 16))
else
buffer.writeu32(out, i, bit32.byteswap(buffer.readu32(out, i)))
end
end
return out
end
-- flips the rows of a decoded surface (KTXorientation T=u)
local function flip(img: Types.Image)
local row = img.width * (Types.BPP[img.format] or 4)
local px = img.pixels
local tmp = buffer.create(row)
for y = 0, img.height // 2 - 1 do
local a, z = y * row, (img.height - 1 - y) * row
buffer.copy(tmp, 0, px, a, row)
buffer.copy(px, a, px, z, row)
buffer.copy(px, z, tmp, 0, row)
end
end
function Ktx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local info, ierr = Ktx.info(r)
if not info then
return nil, ierr
end
local fmt = info.format
if not fmt then
return nil, Err.new(Err.UNSUPPORTED, info.unsupported or "format")
end
local native = opts and opts.native or false
local wantMips = opts and opts.mips or false
local wantAll = not (opts and opts.surfaces == false)
local maxPixels = opts and opts.maxPixels or 2 ^ 26
local b, base, limit = r.buf, r.base, r.limit
local bw, bh, bbytes = Texture.block(fmt)
local blockFmt = bw == 4
local orient = info.keyValue.KTXorientation or ""
local up = string.find(orient, "T=u", 1, true) ~= nil or (info.version == 2 and string.sub(orient, 2, 2) == "u")
local list: { Texture.Surface } = {}
local pixels = 0
local count = info.layers * info.faces
local p = base + info.dataOffset
local w, h, d = info.width, info.height, info.depth
for level = 0, info.levels - 1 do
local want = level == 0 or wantMips
-- the level's data: buf, offset, the image stride and row pitch
local lb, lp = b, 0
local rowPitch: number? = nil
local imgSize = Texture.size(fmt, w, h) :: number
local stride = imgSize
if info.version == 1 then
if p + 4 > limit then
if level == 0 then
return nil, Err.new(Err.TRUNCATED, "missing level 0", p)
end
break
end
local declared = readu32(b, p)
if info.bigEndian then
declared = bit32.byteswap(declared)
end
p += 4
if not blockFmt then
local tight = (bbytes :: number) * w
rowPitch = tight + (3 - (tight + 3) % 4)
imgSize = (rowPitch :: number) * h
end
stride = imgSize + (3 - (imgSize + 3) % 4) -- cube padding
local total = stride * count * d
if declared < imgSize * (if info.faces == 6 and info.layers == 1 then 1 else count * d) and level == 0 then
return nil, Err.new(Err.CORRUPT, "imageSize too small for the format", p - 4)
end
if p + total > limit then
if level == 0 then
return nil, Err.new(Err.TRUNCATED, "level 0 data runs past the end", p)
end
break
end
lp = p
p += total
p += 3 - (total + 3) % 4
if info.bigEndian and info.typeSize > 1 and want then
lb, lp = swapped(b, lp, total, info.typeSize), 0
end
else
local li = (info.levelIndex :: any)[level + 1]
local off, len = base + li.offset, li.length
if off + len > limit or li.offset < 80 then
if level == 0 then
return nil, Err.new(Err.TRUNCATED, "level 0 data runs past the end", off)
end
break
end
local expect = imgSize * count * d
if want then
local scheme = info.supercompression
if scheme == 2 or scheme == 3 then
if li.uncompressed < expect or li.uncompressed > 2 ^ 31 then
return nil, Err.new(Err.CORRUPT, "bad uncompressed level size", base + 80 + level * 24)
end
local out, zerr
if scheme == 2 then
out, zerr = Zstd.decompress(b, off, len, { maxBytes = li.uncompressed })
else
out, zerr = Deflate.zlib(b, off, len, li.uncompressed)
end
if not out then
return nil, Err.wrap(zerr)
end
lb, lp = out, 0
else
lb, lp = b, off
end
if lp + expect > buffer.len(lb) then
return nil, Err.new(Err.TRUNCATED, "level " .. level .. " is too small", off)
end
end
end
if want then
for layer = 0, count - 1 do
for slice = 0, d - 1 do
if level == 0 and not wantAll and (layer > 0 or slice > 0) then
continue
end
if level > 0 and (layer > 0 or slice > 0) then
continue
end
pixels += w * h
if pixels > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("over the %d pixel limit", maxPixels))
end
local at = lp + (layer * d + slice) * stride
local px, pf
if rowPitch then
px, pf = Texel.decode(fmt, lb, at, w, h, native, rowPitch)
else
px, pf = Texture.decode(fmt, lb, at, w, h, native)
end
if not px then
return nil, Err.from(pf, at)
end
local im = Texture.image(px, pf, w, h)
if info.opaque then
for i = 0, w * h - 1 do
buffer.writeu8(px, i * 4 + 3, 255)
end
end
if up then
flip(im)
end
table.insert(list, { level = level, layer = layer, face = layer % info.faces, slice = slice, image = im })
end
end
end
w, h, d = math.max(1, w // 2), math.max(1, h // 2), math.max(1, d // 2)
end
local layout = if info.depth > 1 then "volume" elseif info.faces == 6 then "cube" elseif info.layers > 1 then "array" else "2d"
local img = Texture.assemble(list, layout)
if not img then
return nil, Err.new(Err.TRUNCATED, "no image data")
end
if info.faces == 6 then
img.meta.faces = table.clone(FACES)
end
if info.srgb then
img.meta.colorSpace = "srgb"
elseif string.find(fmt, "f$") or fmt == "bc6h" or fmt == "bc6hs" or fmt == "rgb9e5" then
img.meta.colorSpace = "linear"
end
img.meta.keyValue = info.keyValue
img.meta.source = {
format = "ktx",
version = info.version,
pixelFormat = fmt,
vkFormat = info.vkFormat,
glInternalFormat = info.glInternalFormat,
supercompression = info.supercompression,
mips = info.levels,
layers = info.layers,
depth = info.depth,
}
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- format -> VkFormat, bytes per texel, component bytes, kind
local OUT: { [string]: { number } } = {
rgba8 = { 37, 4, 1 },
rgba16 = { 91, 8, 2 },
rgba16f = { 97, 8, 2 },
rgba32f = { 109, 16, 4 },
}
-- the DFD: one basic descriptor block with four samples (R G B A)
local function dfd(f: string, srgb: boolean): buffer
local spec = OUT[f]
local texel, comp = spec[2], spec[3]
local float = f == "rgba16f" or f == "rgba32f"
local w = Bytes.writer(92)
local blockSize = 24 + 16 * 4
w:u32le(4 + blockSize)
w:u32le(0) -- vendor 0, descriptor type 0
w:u32le(2 + blockSize * 65536) -- version 2, block size
w:u8(1) -- colour model RGBSDA
w:u8(1) -- primaries BT.709
w:u8(if srgb then 2 else 1) -- transfer: sRGB / linear
w:u8(0) -- straight alpha
w:u32le(0) -- texel block 1 x 1 x 1 x 1
w:u32le(texel) -- bytesPlane0
w:u32le(0)
for c = 0, 3 do
local channel = if c == 3 then 15 else c
local qual = (if float then 0xC0 else 0) + (if srgb and c == 3 then 0x10 else 0)
w:u16le(c * comp * 8)
w:u8(comp * 8 - 1)
w:u8(channel + qual)
w:u32le(0) -- sample position
if float then
w:u32le(0xBF800000)
w:u32le(0x3F800000)
else
w:u32le(0)
w:u32le(if comp == 1 then 255 else 65535)
end
end
return w:finish()
end
function Ktx.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or img.width < 1 or img.height < 1 then
return nil, Err.new(Err.ARG, "needs an Image")
end
local pf = img.format
if pf ~= "rgba8" and pf ~= "rgba16" and pf ~= "rgbaf32" then
return nil, Err.new(Err.ARG, "needs an rgba8, rgba16 or rgbaf32 Image (got " .. tostring(pf) .. ")")
end
local f: string = (opts and opts.pixelFormat) or (if pf == "rgbaf32" then "rgba32f" else pf)
local spec = OUT[f]
if not spec then
return nil, Err.new(Err.ARG, "unknown pixelFormat " .. tostring(f))
end
local needs = if f == "rgba16f" or f == "rgba32f" then "rgbaf32" else f
if pf ~= needs then
return nil, Err.new(Err.ARG, string.format("pixelFormat %s needs an %s Image", f, needs))
end
local srgb = f == "rgba8" and (if opts and opts.srgb ~= nil then opts.srgb else (img.meta and img.meta.colorSpace == "srgb"))
local images: { Types.Image } = { img }
if img.frames and #img.frames > 1 then
images = {}
for i, fr in img.frames do
local fi = fr.image
if type(fi) ~= "table" or fi.width ~= img.width or fi.height ~= img.height or fi.format ~= pf then
return nil, Err.new(Err.ARG, "frame " .. i .. ": every surface needs the image's size and pixel format")
end
images[i] = fi
end
end
local cube = if opts and opts.cube ~= nil then opts.cube else (img.meta and img.meta.layout == "cube")
if cube and (#images % 6 ~= 0 or img.width ~= img.height) then
return nil, Err.new(Err.ARG, "a cube map needs 6 square faces per layer")
end
local faces = if cube then 6 else 1
local layers = #images // faces
local levels = 1
if opts and opts.mips then
local m = math.max(img.width, img.height)
while m > 1 do
m //= 2
levels += 1
end
end
local zl = opts and opts.zlib
if zl ~= nil and (type(zl) ~= "number" or zl < 1 or zl > 9) then
return nil, Err.new(Err.ARG, "zlib level must be 1..9")
end
-- level data: the images of every layer / face per level
local levelData: { buffer } = {}
local raw: { number } = {}
local cur = table.clone(images)
for lv = 1, levels do
local w = Bytes.writer()
for i, im in cur do
local data = if f == "rgba16f" then Texture.toHalf(im.pixels, im.width * im.height) else im.pixels
w:bytes(data, 0, im.width * im.height * spec[2])
if lv < levels then
cur[i] = Texture.halve(im)
end
end
local lb = w:finish()
raw[lv] = buffer.len(lb)
if zl then
lb = Deflate.zlibCompress(lb, { level = zl }) :: buffer
end
levelData[lv] = lb
end
-- key / value data
local kvw = Bytes.writer()
local pairs_: { { string } } = { { "KTXwriter", "rosetta" } }
if opts and opts.keyValue then
for k, v in opts.keyValue do
if k ~= "KTXwriter" then
table.insert(pairs_, { k, v })
end
end
end
table.sort(pairs_, function(a: { string }, c: { string }): boolean
return a[1] < c[1]
end)
for _, kv in pairs_ do
local n = #kv[1] + 1 + #kv[2] + 1
kvw:u32le(n)
kvw:string(kv[1])
kvw:u8(0)
kvw:string(kv[2])
kvw:u8(0)
kvw:fill(0, 3 - (n + 3) % 4)
end
local kvd = kvw:finish()
local d = dfd(f, srgb == true)
local dfdOff = 80 + levels * 24
local kvOff = dfdOff + buffer.len(d)
local dataStart = kvOff + buffer.len(kvd)
local align = if zl then 1 else (if spec[2] % 4 == 0 then spec[2] else 4)
-- smallest level first
local offsets: { number } = {}
local p = dataStart
for lv = levels, 1, -1 do
p += (align - p % align) % align
offsets[lv] = p
p += buffer.len(levelData[lv])
end
local out = Bytes.writer(p)
out:string(ID2)
out:u32le(if f == "rgba8" and srgb then 43 else spec[1])
out:u32le(spec[3])
out:u32le(img.width)
out:u32le(img.height)
out:u32le(0)
out:u32le(if layers > 1 then layers else 0)
out:u32le(faces)
out:u32le(levels)
out:u32le(if zl then 3 else 0)
out:u32le(dfdOff)
out:u32le(buffer.len(d))
out:u32le(kvOff)
out:u32le(buffer.len(kvd))
out:u64le(0)
out:u64le(0)
for lv = 1, levels do
out:u64le(offsets[lv])
out:u64le(buffer.len(levelData[lv]))
out:u64le(raw[lv])
end
out:bytes(d)
out:bytes(kvd)
for lv = levels, 1, -1 do
out:fill(0, offsets[lv] - out:tell())
out:bytes(levelData[lv])
end
return out:finish(), nil
end
return Ktx
+266
View File
@@ -0,0 +1,266 @@
--!strict
-- image/pcx: ZSoft PC Paintbrush (the ZSoft "Technical Reference Manual" PCX header and RLE; new code). Decode: 1-bit
-- monochrome, 1-bit x 2..4 planes (EGA, the header palette), 2 / 4-bit packed (the header palette), 8-bit with the
-- 256-colour palette at the end (grey when it is missing), 8-bit x 3 / 4 planes (RGB / RGBA); RLE (runs may cross
-- scan lines) and the rare uncompressed encoding; the window (xMin / yMin) and DPI (meta.dpi). Encode: rgba8 as
-- 8-bit palette (up to 256 opaque colours), 24-bit (3 planes) or 32-bit (4 planes, when there is alpha), RLE.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Pixels = require("@rosetta/codecs/image/Pixels")
-- ------------------------------------------------------------------------------------------------ contract
local Pcx = {
name = "pcx",
category = "image",
extensions = { "pcx", "pcc", "dcx" },
mime = { "image/vnd.zbrush.pcx", "image/x-pcx" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels" },
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 4, 8, 24, 32 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxPixels: number?, -- refuse larger images (default 2^26)
}
export type EncodeOptions = {
palette: boolean?, -- 8-bit palette when possible (default true); false: always 24 / 32-bit planes
}
local readu8, readu16 = buffer.readu8, buffer.readu16
-- ------------------------------------------------------------------------------------------------ sniff
function Pcx.sniff(r: Bytes.Reader): number
if r:size() < 128 then
return 0
end
local m, v, e, bpp = r:peekU8(0), r:peekU8(1), r:peekU8(2), r:peekU8(3)
if m ~= 10 or (v ~= 0 and v ~= 2 and v ~= 3 and v ~= 4 and v ~= 5) or e > 1 then
return 0
end
return if bpp == 1 or bpp == 2 or bpp == 4 or bpp == 8 then 0.8 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Pcx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local b, o, limit = r.buf, r.base, r.limit
if limit - o < 128 then
return nil, Err.new(Err.TRUNCATED, "short header", o)
end
if readu8(b, o) ~= 10 then
return nil, Err.new(Err.CORRUPT, "not a PCX file", o)
end
local version, enc, bpp = readu8(b, o + 1), readu8(b, o + 2), readu8(b, o + 3)
local x0, y0, x1, y1 = readu16(b, o + 4), readu16(b, o + 6), readu16(b, o + 8), readu16(b, o + 10)
local planes, bpl = readu8(b, o + 65), readu16(b, o + 66)
local w, h = x1 - x0 + 1, y1 - y0 + 1
if x1 < x0 or y1 < y0 then
return nil, Err.new(Err.CORRUPT, "bad window", o + 4)
end
local maxPixels = opts and opts.maxPixels or 2 ^ 26
if w * h > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
end
local kind
if bpp == 8 and planes == 1 then
kind = "pal8"
elseif bpp == 8 and (planes == 3 or planes == 4) then
kind = "rgb"
elseif bpp == 1 and planes >= 1 and planes <= 4 then
kind = "planar"
elseif (bpp == 2 or bpp == 4) and planes == 1 then
kind = "packed"
else
return nil, Err.new(Err.UNSUPPORTED, string.format("%d bits x %d planes", bpp, planes), o + 3)
end
if bpl * 8 < w * bpp then
return nil, Err.new(Err.CORRUPT, "bytes per line too small", o + 66)
end
-- the scan lines (planes after each other per line), RLE across lines
local total = bpl * planes * h
local raw = buffer.create(total)
local p, q = o + 128, 0
local truncated = false
if enc == 1 then
while q < total do
if p >= limit then
truncated = true
break
end
local c = readu8(b, p)
p += 1
if c >= 0xC0 then
if p >= limit then
truncated = true
break
end
local n = math.min(c - 0xC0, total - q)
buffer.fill(raw, q, readu8(b, p), n)
p += 1
q += n
else
buffer.writeu8(raw, q, c)
q += 1
end
end
else
local n = math.min(total, limit - p)
buffer.copy(raw, 0, b, p, n)
p += n
truncated = n < total
end
-- palettes
local pal = buffer.create(1024)
local function setPal(i: number, rr: number, gg: number, bb: number)
buffer.writeu32(pal, i * 4, rr + gg * 256 + bb * 65536 + 0xFF000000)
end
if kind == "pal8" then
local at = limit - 769
if at >= p and readu8(b, at) == 12 then
for i = 0, 255 do
setPal(i, readu8(b, at + 1 + i * 3), readu8(b, at + 2 + i * 3), readu8(b, at + 3 + i * 3))
end
else
for i = 0, 255 do
setPal(i, i, i, i)
end
end
elseif kind == "planar" and planes == 1 then
setPal(0, 0, 0, 0)
setPal(1, 255, 255, 255)
else
for i = 0, 15 do
setPal(i, readu8(b, o + 16 + i * 3), readu8(b, o + 17 + i * 3), readu8(b, o + 18 + i * 3))
end
end
local img = Types.Image.new(w, h, "rgba8")
local px = img.pixels
if kind == "pal8" or kind == "packed" then
Pixels.indexed(raw, 0, bpl, bpp, px, w, h, true, pal)
elseif kind == "planar" then
for y = 0, h - 1 do
local row = y * bpl * planes
for x = 0, w - 1 do
local idx = 0
for pl = 0, planes - 1 do
local byte = readu8(raw, row + pl * bpl + bit32.rshift(x, 3))
idx += bit32.band(bit32.rshift(byte, 7 - bit32.band(x, 7)), 1) * bit32.lshift(1, pl)
end
buffer.writeu32(px, (y * w + x) * 4, buffer.readu32(pal, idx * 4))
end
end
else
for y = 0, h - 1 do
local row = y * bpl * planes
for x = 0, w - 1 do
local d = (y * w + x) * 4
buffer.writeu8(px, d, readu8(raw, row + x))
buffer.writeu8(px, d + 1, readu8(raw, row + bpl + x))
buffer.writeu8(px, d + 2, readu8(raw, row + 2 * bpl + x))
buffer.writeu8(px, d + 3, if planes == 4 then readu8(raw, row + 3 * bpl + x) else 255)
end
end
end
if kind == "pal8" or kind == "packed" or (kind == "planar" and planes > 1) then
local list: { { number } } = {}
for i = 0, (if kind == "pal8" then 256 else bit32.lshift(1, bpp * planes)) - 1 do
local v = buffer.readu32(pal, i * 4)
list[i + 1] = { bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255), 255 }
end
img.meta.palette = list
end
local hd, vd = readu16(b, o + 12), readu16(b, o + 14)
if hd > 0 and vd > 0 then
img.meta.dpi = { x = hd, y = vd }
end
if truncated then
img.meta.truncated = true
end
img.meta.source = { format = "pcx", version = version, bitDepth = bpp * planes, planes = planes, x = x0, y = y0, rle = enc == 1 }
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- RLE of one plane row into w
local function rleRow(out: Bytes.Writer, src: buffer, p: number, n: number)
local i = 0
while i < n do
local v = readu8(src, p + i)
local run = 1
while i + run < n and run < 63 and readu8(src, p + i + run) == v do
run += 1
end
if run > 1 or v >= 0xC0 then
out:u8(0xC0 + run)
end
out:u8(v)
i += run
end
end
function Pcx.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, "needs an rgba8 Image")
end
local w, h = img.width, img.height
if w < 1 or h < 1 or w > 65535 or h > 65535 then
return nil, Err.new(Err.ARG, "size must be 1..65535")
end
local px = img.pixels
local cols, alpha = Pixels.colours(px, w * h, 256)
local usePal = not alpha and #cols <= 256 and not (opts and opts.palette == false)
local planes = if usePal then 1 elseif alpha then 4 else 3
local bpl = w + w % 2
local out = Bytes.writer(128 + w * h * planes + 800)
out:u8(10)
out:u8(5)
out:u8(1)
out:u8(8)
out:u16le(0)
out:u16le(0)
out:u16le(w - 1)
out:u16le(h - 1)
local dpi = img.meta and img.meta.dpi
out:u16le(if dpi then math.floor(dpi.x + 0.5) else 72)
out:u16le(if dpi then math.floor(dpi.y + 0.5) else 72)
out:fill(0, 48)
out:u8(0)
out:u8(planes)
out:u16le(bpl)
out:u16le(1)
out:fill(0, 58)
local row = buffer.create(bpl)
local index: { [number]: number } = {}
for i, c in cols do
index[c] = i - 1
end
for y = 0, h - 1 do
for pl = 0, planes - 1 do
for x = 0, w - 1 do
local s = (y * w + x) * 4
local v
if usePal then
v = index[bit32.band(buffer.readu32(px, s), 0xFFFFFF)] or 0
else
v = readu8(px, s + pl)
end
buffer.writeu8(row, x, v)
end
rleRow(out, row, 0, bpl)
end
end
if usePal then
out:u8(12)
for i = 0, 255 do
local c = cols[i + 1] or 0
out:u8(bit32.band(c, 255))
out:u8(bit32.band(bit32.rshift(c, 8), 255))
out:u8(bit32.rshift(c, 16))
end
end
return out:finish(), nil
end
return Pcx
+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
+289
View File
@@ -0,0 +1,289 @@
--!strict
--!native
--!optimize 2
-- image/pnm/Codec: the Netpbm sample loops (native; never throws). Written from the Netpbm format pages (pbm, pgm,
-- ppm, pam, pfm). Reading: binary 8 / 16-bit samples, ASCII samples (P1 digits may run together), P4 bit rows, PFM
-- floats (either byte order, bottom-to-top rows); packing samples into a Types pixel format with maxval scaling.
-- Writing: samples of any pixel format extracted at 1..4 channels and 8 or 16 bits. Every read is bounds-checked.
local readu8, writeu8, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16
local readf32, writef32, readu32, writeu32 = buffer.readf32, buffer.writef32, buffer.readu32, buffer.writeu32
local byteswap = bit32.byteswap
local Codec = {}
-- readSamples(b, p, limit, count, mode, out) -> true | false, message: count raw values into out (u16 each).
-- mode 1 = binary 8-bit, 2 = binary 16-bit big-endian, 3 = ASCII decimal, 4 = ASCII P1 (single digits)
function Codec.readSamples(b: buffer, p: number, limit: number, count: number, mode: number, out: buffer): (boolean, string?)
if mode == 1 then
if p + count > limit then
return false, "truncated"
end
for i = 0, count - 1 do
writeu16(out, i * 2, readu8(b, p + i))
end
return true, nil
elseif mode == 2 then
if p + count * 2 > limit then
return false, "truncated"
end
for i = 0, count - 1 do
writeu16(out, i * 2, readu8(b, p + i * 2) * 256 + readu8(b, p + i * 2 + 1))
end
return true, nil
end
local i = 0
while i < count do
-- skip whitespace and comments
while p < limit do
local c = readu8(b, p)
if c == 35 then -- '#'
while p < limit and readu8(b, p) ~= 10 and readu8(b, p) ~= 13 do
p += 1
end
elseif c == 32 or (c >= 9 and c <= 13) then
p += 1
else
break
end
end
if p >= limit then
return false, "truncated"
end
local c = readu8(b, p)
if c < 48 or c > 57 then
return false, "bad ASCII sample"
end
if mode == 4 then
writeu16(out, i * 2, c - 48)
p += 1
else
local v = 0
while p < limit do
local d = readu8(b, p)
if d < 48 or d > 57 then
break
end
v = math.min(v * 10 + d - 48, 65535)
p += 1
end
writeu16(out, i * 2, v)
end
i += 1
end
return true, nil
end
-- readBits(b, p, limit, w, h, out) -> ok, message: P4 rows (MSB first, rows padded to bytes) as u16 0 / 1 values
function Codec.readBits(b: buffer, p: number, limit: number, w: number, h: number, out: buffer): (boolean, string?)
local rowBytes = (w + 7) // 8
if p + rowBytes * h > limit then
return false, "truncated"
end
for y = 0, h - 1 do
local r = p + y * rowBytes
for x = 0, w - 1 do
local byte = readu8(b, r + x // 8)
writeu16(out, (y * w + x) * 2, (byte // 2 ^ (7 - x % 8)) % 2)
end
end
return true, nil
end
-- format codes for pack / extract
Codec.RGBA8, Codec.RGB8, Codec.GRAY8, Codec.GRAYA8, Codec.RGBA16, Codec.GRAY16, Codec.RGBAF32 = 0, 1, 2, 3, 4, 5, 6
-- pack(samples, n, ch, maxval, invert, fmt, dst): n pixels of ch raw samples (u16, 0..maxval; invert: 1 - v for
-- PBM bits) into dst in pixel format fmt, scaled to the format's range (8-bit: round(v * 255 / maxval))
function Codec.pack(s: buffer, n: number, ch: number, maxval: number, invert: boolean, fmt: number, dst: buffer)
local wide = fmt == 4 or fmt == 5
local top = if wide then 65535 else 255
local half = maxval // 2
local function get(i: number): number
local v = math.min(readu16(s, i * 2), maxval)
if invert then
v = maxval - v
end
if maxval == top then
return v
end
return (v * top + half) // maxval
end
for i = 0, n - 1 do
local q = i * ch
local r, g, b, a
if ch == 1 then
r = get(q)
g, b, a = r, r, top
elseif ch == 2 then
r = get(q)
g, b, a = r, r, get(q + 1)
elseif ch == 3 then
r, g, b, a = get(q), get(q + 1), get(q + 2), top
else
r, g, b, a = get(q), get(q + 1), get(q + 2), get(q + 3)
end
if fmt == 0 then
writeu32(dst, i * 4, r + g * 256 + b * 65536 + (a :: number) * 16777216)
elseif fmt == 1 then
writeu8(dst, i * 3, r)
writeu8(dst, i * 3 + 1, g)
writeu8(dst, i * 3 + 2, b)
elseif fmt == 2 then
writeu8(dst, i, r)
elseif fmt == 3 then
writeu8(dst, i * 2, r)
writeu8(dst, i * 2 + 1, a :: number)
elseif fmt == 4 then
writeu16(dst, i * 8, r)
writeu16(dst, i * 8 + 2, g)
writeu16(dst, i * 8 + 4, b)
writeu16(dst, i * 8 + 6, a :: number)
elseif fmt == 5 then
writeu16(dst, i * 2, r)
end
end
end
-- readFloats(b, p, limit, w, h, ch, le, dst) -> ok, message: PFM rows (bottom-to-top) into rgbaf32 dst
function Codec.readFloats(b: buffer, p: number, limit: number, w: number, h: number, ch: number, le: boolean, dst: buffer): (boolean, string?)
if p + w * h * ch * 4 > limit then
return false, "truncated"
end
local tmp = buffer.create(4)
for y = 0, h - 1 do
local row = p + (h - 1 - y) * w * ch * 4
for x = 0, w - 1 do
local o = (y * w + x) * 16
for c = 0, ch - 1 do
local v
if le then
v = readf32(b, row + (x * ch + c) * 4)
else
writeu32(tmp, 0, byteswap(readu32(b, row + (x * ch + c) * 4)))
v = readf32(tmp, 0)
end
writef32(dst, o + c * 4, v)
end
if ch == 1 then
local v = readf32(dst, o)
writef32(dst, o + 4, v)
writef32(dst, o + 8, v)
end
writef32(dst, o + 12, 1)
end
end
return true, nil
end
local function f(v: number): number
if v ~= v then
return 0
end
return math.floor(math.clamp(v, 0, 1) * 65535 + 0.5)
end
-- extract(px, fmt, n, ch, wide) -> u16 samples: n pixels of format fmt as ch channels (1 grey (Rec. 601 luma for
-- colour sources, Pillow's L = (299 R + 587 G + 114 B) / 1000), 2 grey + alpha, 3 RGB, 4 RGBA), 16-bit if wide
function Codec.extract(px: buffer, fmt: number, n: number, ch: number, wide: boolean): buffer
local out = buffer.create(n * ch * 2)
local srcWide = fmt == 4 or fmt == 5
local isGray = fmt == 2 or fmt == 3 or fmt == 5
for i = 0, n - 1 do
local r, g, b, a
if fmt == 0 then
r, g, b, a = readu8(px, i * 4), readu8(px, i * 4 + 1), readu8(px, i * 4 + 2), readu8(px, i * 4 + 3)
elseif fmt == 1 then
r, g, b, a = readu8(px, i * 3), readu8(px, i * 3 + 1), readu8(px, i * 3 + 2), 255
elseif fmt == 2 then
r = readu8(px, i)
g, b, a = r, r, 255
elseif fmt == 3 then
r, a = readu8(px, i * 2), readu8(px, i * 2 + 1)
g, b = r, r
elseif fmt == 4 then
r, g, b, a = readu16(px, i * 8), readu16(px, i * 8 + 2), readu16(px, i * 8 + 4), readu16(px, i * 8 + 6)
elseif fmt == 5 then
r = readu16(px, i * 2)
g, b, a = r, r, 65535
else
r, g, b, a = f(readf32(px, i * 16)), f(readf32(px, i * 16 + 4)), f(readf32(px, i * 16 + 8)), f(readf32(px, i * 16 + 12))
end
local w16 = srcWide or fmt == 6
local gray = r
if ch <= 2 and not isGray then
gray = (r * 299 + g * 587 + b * 114) // 1000
end
local vals = if ch == 1 then 1 elseif ch == 2 then 2 else ch
for c = 0, vals - 1 do
local v
if ch <= 2 then
v = if c == 0 then gray else a :: number
else
v = if c == 0 then r elseif c == 1 then g elseif c == 2 then b else a :: number
end
if wide and not w16 then
v *= 257
elseif w16 and not wide then
v = (v * 255 + 32767) // 65535
end
writeu16(out, (i * ch + c) * 2, v)
end
end
return out
end
-- writeSamples(s, count, wide, out, o) -> new offset: binary samples (8-bit or 16-bit big-endian)
function Codec.writeSamples(s: buffer, count: number, wide: boolean, out: buffer, o: number): number
if wide then
for i = 0, count - 1 do
local v = readu16(s, i * 2)
writeu8(out, o, v // 256)
writeu8(out, o + 1, v % 256)
o += 2
end
else
for i = 0, count - 1 do
writeu8(out, o, readu16(s, i * 2))
o += 1
end
end
return o
end
-- writeBits(s, w, h, threshold, out, o) -> new offset: P4 rows from grey samples (below threshold = black = 1)
function Codec.writeBits(s: buffer, w: number, h: number, threshold: number, out: buffer, o: number): number
for y = 0, h - 1 do
local acc, nb = 0, 0
for x = 0, w - 1 do
acc = acc * 2 + (if readu16(s, (y * w + x) * 2) < threshold then 1 else 0)
nb += 1
if nb == 8 then
writeu8(out, o, acc)
o += 1
acc, nb = 0, 0
end
end
if nb > 0 then
writeu8(out, o, acc * 2 ^ (8 - nb))
o += 1
end
end
return o
end
-- writeFloats(px, w, h, ch, out, o) -> new offset: rgbaf32 (ch 3) or its first channel (ch 1) as little-endian PFM
-- rows, bottom-to-top
function Codec.writeFloats(px: buffer, w: number, h: number, ch: number, out: buffer, o: number): number
for y = h - 1, 0, -1 do
for x = 0, w - 1 do
local q = (y * w + x) * 16
for c = 0, ch - 1 do
writef32(out, o, readf32(px, q + c * 4))
o += 4
end
end
end
return o
end
return Codec
+384
View File
@@ -0,0 +1,384 @@
--!strict
-- image/pnm: the Netpbm family, written from the Netpbm format pages: PBM (P1 ASCII / P4 binary), PGM (P2 / P5),
-- PPM (P3 / P6), PAM (P7: BLACKANDWHITE, GRAYSCALE, GRAYSCALE_ALPHA, RGB, RGB_ALPHA and their _ALPHA forms, any
-- tuple type of depth 1..4) and PFM (PF colour / Pf grey 32-bit float, either byte order, bottom-to-top rows).
-- maxval 1..65535 (scaled to 8 bits by round(v * 255 / maxval)). Decode: rgba8, or with opts.native the source layout
-- (gray8, gray16, graya8, rgb8, rgba8, rgba16 for 16-bit colour or grey + alpha, rgbaf32 for PFM). PFM to rgba8 is
-- clamp(v, 0, 1) * 255 rounded (linear, no gamma). Encode: any of the seven types, binary or ASCII, from every pixel
-- format; the subtype comes from opts.format / the file extension (pbm, pgm, ppm, pam, pfm) or the image.
-- Not supported: multi-image streams (the first image is read), PAM depths above 4.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Codec = require("@rosetta/image/pnm/Codec")
-- ------------------------------------------------------------------------------------------------ contract
local Pnm = {
name = "pnm",
category = "image",
extensions = { "pnm", "pbm", "pgm", "ppm", "pam", "pfm" },
mime = { "image/x-portable-anymap", "image/x-portable-bitmap", "image/x-portable-graymap", "image/x-portable-pixmap", "image/x-portable-arbitrarymap", "image/x-portable-floatmap" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, alpha = true, depths = { 1, 8, 16, 32 }, float = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
native: boolean?, -- keep the source layout (default false: rgba8)
maxPixels: number?, -- refuse larger images (default 2^26)
}
export type EncodeOptions = {
format: string?, -- "pbm" | "pgm" | "ppm" | "pam" | "pfm" (default: from the image: grey -> pgm, opaque colour
-- -> ppm, alpha -> pam, rgbaf32 -> pfm); "pnm" means the default
ascii: boolean?, -- P1 / P2 / P3 instead of P4 / P5 / P6 (default false)
maxval: number?, -- 1..65535 (default 255, or 65535 for 16-bit / float sources); pbm ignores it
threshold: number?, -- pbm: grey below this (0..255) is black (default 128)
}
-- ------------------------------------------------------------------------------------------------ constants
local FMT_CODE: { [string]: number } = { rgba8 = 0, rgb8 = 1, gray8 = 2, graya8 = 3, rgba16 = 4, gray16 = 5, rgbaf32 = 6 }
local BPP: { [string]: number } = { rgba8 = 4, rgb8 = 3, gray8 = 1, graya8 = 2, rgba16 = 8, gray16 = 2, rgbaf32 = 16 }
local readu8 = buffer.readu8
-- ------------------------------------------------------------------------------------------------ sniff
function Pnm.sniff(r: Bytes.Reader): number
if r:remaining() < 3 then
return 0
end
local a, b, c = r:peekU8(0), r:peekU8(1), r:peekU8(2)
if a ~= 80 then -- 'P'
return 0
end
local ws = c == 32 or (c >= 9 and c <= 13)
if b >= 49 and b <= 55 and ws then -- P1..P7
return 0.9
end
if (b == 70 or b == 102) and ws then -- PF / Pf
return 0.9
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function isSpace(c: number): boolean
return c == 32 or (c >= 9 and c <= 13)
end
-- the next header token from p: token, position after it (nil at the end)
local function token(b: buffer, p: number, limit: number): (string?, number)
while p < limit do
local c = readu8(b, p)
if c == 35 then
while p < limit and readu8(b, p) ~= 10 and readu8(b, p) ~= 13 do
p += 1
end
elseif isSpace(c) then
p += 1
else
break
end
end
local s = p
while p < limit and not isSpace(readu8(b, p)) and readu8(b, p) ~= 35 do
p += 1
end
if p == s then
return nil, p
end
return buffer.readstring(b, s, p - s), p
end
local function int(s: string?): number?
if s == nil or not string.match(s, "^%d+$") or #s > 9 then
return nil
end
return tonumber(s)
end
function Pnm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local maxPixels = opts and opts.maxPixels or 2 ^ 26
local native = opts and opts.native or false
local b, limit = r.buf, r.limit
if r.limit - r.base < 3 or readu8(b, r.base) ~= 80 then
return nil, Err.new(Err.CORRUPT, "not a Netpbm file", r.base)
end
local kind = string.char(readu8(b, r.base + 1))
local p = r.base + 2
local w: number?, h: number?, maxval: number?, ch: number, mode: number
local bits = false -- PBM: 1 = black
local bw = false -- PAM BLACKANDWHITE: 1 = white
local tupl: string? = nil
local scale: number? = nil
if kind == "1" or kind == "2" or kind == "3" or kind == "4" or kind == "5" or kind == "6" or kind == "F" or kind == "f" then
local t1, t2, t3
t1, p = token(b, p, limit)
t2, p = token(b, p, limit)
w, h = int(t1), int(t2)
if kind == "1" or kind == "4" then
maxval = 1
elseif kind == "F" or kind == "f" then
t3, p = token(b, p, limit)
scale = if t3 then tonumber(t3) else nil
if scale == nil or scale == 0 then
return nil, Err.new(Err.CORRUPT, "bad PFM scale", p)
end
maxval = 1
else
t3, p = token(b, p, limit)
maxval = int(t3)
end
if w == nil or h == nil or maxval == nil then
return nil, if p >= limit then Err.new(Err.TRUNCATED, "header ends early", p) else Err.new(Err.CORRUPT, "bad header", p)
end
if kind ~= "1" and kind ~= "2" and kind ~= "3" then
p += 1 -- exactly one whitespace byte before binary data
end
ch = if kind == "3" or kind == "6" or kind == "F" then 3 else 1
bits = kind == "1" or kind == "4"
mode = if kind == "1" then 4 elseif kind == "2" or kind == "3" then 3 elseif kind == "4" then 0 elseif (maxval :: number) > 255 then 2 else 1
elseif kind == "7" then
local depth: number?
while true do
local key
key, p = token(b, p, limit)
if key == nil then
return nil, Err.new(Err.TRUNCATED, "PAM header ends early", p)
end
if key == "ENDHDR" then
break
end
local v
v, p = token(b, p, limit)
if key == "WIDTH" then
w = int(v)
elseif key == "HEIGHT" then
h = int(v)
elseif key == "DEPTH" then
depth = int(v)
elseif key == "MAXVAL" then
maxval = int(v)
elseif key == "TUPLTYPE" then
tupl = v
-- the rest of the line belongs to the value
while p < limit and readu8(b, p) ~= 10 do
p += 1
end
end
end
-- ENDHDR ends with a newline
while p < limit and readu8(b, p) ~= 10 do
p += 1
end
p += 1
if w == nil or h == nil or depth == nil or maxval == nil then
return nil, Err.new(Err.CORRUPT, "PAM header misses WIDTH / HEIGHT / DEPTH / MAXVAL", p)
end
if (depth :: number) < 1 or (depth :: number) > 4 then
return nil, Err.new(Err.UNSUPPORTED, "PAM depth " .. (depth :: number))
end
ch = depth :: number
bw = tupl ~= nil and string.sub(tupl :: string, 1, 13) == "BLACKANDWHITE"
mode = if (maxval :: number) > 255 then 2 else 1
else
return nil, Err.new(Err.CORRUPT, "not a Netpbm file", r.base)
end
local w, h, maxval = w :: number, h :: number, maxval :: number -- each branch above returns when one is nil
if w < 1 or h < 1 or maxval < 1 or maxval > 65535 then
return nil, Err.new(Err.CORRUPT, string.format("bad size %d x %d or maxval %d", w, h, maxval))
end
if w * h > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
end
local n = w * h
local img: Types.Image
local colorType = if ch == 1 then "gray" elseif ch == 2 then "graya" elseif ch == 3 then "rgb" else "rgba"
if scale then
local f = Types.Image.new(w, h, "rgbaf32")
local ok, e = Codec.readFloats(b, p, limit, w, h, ch, (scale :: number) < 0, f.pixels)
if not ok then
return nil, Err.new(Err.TRUNCATED, tostring(e))
end
img = f
if not native then
local o = Types.Image.new(w, h, "rgba8")
for i = 0, n * 4 - 1 do
local v = buffer.readf32(f.pixels, i * 4)
buffer.writeu8(o.pixels, i, if v ~= v then 0 else math.floor(math.clamp(v, 0, 1) * 255 + 0.5))
end
img = o
end
img.meta.source = { format = "pnm", type = if ch == 3 then "pfm" else "pfm-gray", bitDepth = 32, colorType = colorType, scale = math.abs(scale :: number), byteOrder = if (scale :: number) < 0 then "little" else "big" }
return img, nil
end
local samples = buffer.create(n * ch * 2)
local ok, e
if mode == 0 then
ok, e = Codec.readBits(b, p, limit, w, h, samples)
else
ok, e = Codec.readSamples(b, p, limit, n * ch, mode, samples)
end
if not ok then
return nil, Err.new(if e == "truncated" then Err.TRUNCATED else Err.CORRUPT, tostring(e))
end
local fmt: Types.PixelFormat = "rgba8"
if native then
local wide = maxval > 255
if bits or bw or ch == 1 then
fmt = if wide then "gray16" else "gray8"
elseif ch == 2 then
fmt = if wide then "rgba16" else "graya8"
elseif ch == 3 then
fmt = if wide then "rgba16" else "rgb8"
else
fmt = if wide then "rgba16" else "rgba8"
end
end
img = Types.Image.new(w, h, fmt :: Types.PixelFormat)
Codec.pack(samples, n, ch, maxval, bits, FMT_CODE[fmt], img.pixels)
local typ = if kind == "7" then "pam" elseif bits then "pbm" elseif ch == 1 then "pgm" else "ppm"
img.meta.source = {
format = "pnm",
type = typ,
ascii = mode == 3 or mode == 4,
bitDepth = if bits or bw then 1 elseif maxval > 255 then 16 else 8,
maxval = maxval,
colorType = if bits or bw then "bilevel" else colorType,
tupltype = tupl,
}
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local SUBTYPES = { pbm = true, pgm = true, ppm = true, pam = true, pfm = true }
function Pnm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(img) ~= "table" or type(img.pixels) ~= "buffer" then
return nil, Err.new(Err.ARG, "needs an Image")
end
local fc = FMT_CODE[img.format]
if fc == nil then
return nil, Err.new(Err.ARG, "unsupported pixel format " .. tostring(img.format))
end
local w: number, h: number = img.width, img.height
if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * BPP[img.format] then
return nil, Err.new(Err.ARG, "bad image size or pixel buffer")
end
local o: any = opts or {}
local n = w * h
local isGray = img.format == "gray8" or img.format == "gray16" or img.format == "graya8"
local hasAlpha = img.format == "graya8" or img.format == "rgba16" or img.format == "rgba8" or img.format == "rgbaf32"
if hasAlpha and img.format ~= "graya8" then
-- an alpha channel that is fully opaque does not count
local opaque = true
for i = 0, n - 1 do
local a
if img.format == "rgba8" then
a = buffer.readu8(img.pixels, i * 4 + 3) == 255
elseif img.format == "rgba16" then
a = buffer.readu16(img.pixels, i * 8 + 6) == 65535
else
a = buffer.readf32(img.pixels, i * 16 + 12) == 1
end
if not a then
opaque = false
break
end
end
hasAlpha = not opaque
end
local sub = if type(o.format) == "string" then string.lower(o.format) else nil
if not (sub and SUBTYPES[sub]) then
if img.format == "rgbaf32" and not hasAlpha then
sub = "pfm"
elseif hasAlpha then
sub = "pam"
elseif isGray then
sub = "pgm"
else
sub = "ppm"
end
end
local ascii = o.ascii == true
local wideSrc = img.format == "gray16" or img.format == "rgba16" or img.format == "rgbaf32"
local maxval: number = o.maxval or (if wideSrc then 65535 else 255)
if type(maxval) ~= "number" or maxval < 1 or maxval > 65535 or maxval % 1 ~= 0 then
return nil, Err.new(Err.ARG, "maxval must be 1..65535")
end
local out: buffer
local op = 0
local function header(s: string, extra: number)
out = buffer.create(#s + extra)
buffer.writestring(out, 0, s)
op = #s
end
if sub == "pfm" then
local ch = if isGray then 1 else 3
local src = img
if img.format ~= "rgbaf32" then
local s = Codec.extract(img.pixels, fc, n, 4, true)
src = Types.Image.new(w, h, "rgbaf32")
for i = 0, n * 4 - 1 do
buffer.writef32(src.pixels, i * 4, buffer.readu16(s, i * 2) / 65535)
end
end
header(string.format("%s\n%d %d\n-1.0\n", if ch == 3 then "PF" else "Pf", w, h), n * ch * 4)
op = Codec.writeFloats(src.pixels, w, h, ch, out, op)
return out, nil
end
local ch = if sub == "pbm" or sub == "pgm" then 1 elseif sub == "ppm" then 3 elseif isGray then (if hasAlpha then 2 else 1) else (if hasAlpha then 4 else 3)
if sub == "pbm" then
local thr = o.threshold or 128
local s = Codec.extract(img.pixels, fc, n, 1, false)
if ascii then
local parts = table.create(h + 1)
parts[1] = string.format("P1\n%d %d\n", w, h)
for y = 0, h - 1 do
local row = table.create(w)
for x = 0, w - 1 do
row[x + 1] = if buffer.readu16(s, (y * w + x) * 2) < thr then "1" else "0"
end
parts[y + 2] = table.concat(row, " ") .. "\n"
end
return buffer.fromstring(table.concat(parts)), nil
end
header(string.format("P4\n%d %d\n", w, h), ((w + 7) // 8) * h)
op = Codec.writeBits(s, w, h, thr, out, op)
return out, nil
end
local wide = maxval > 255
local s = Codec.extract(img.pixels, fc, n, ch, wide)
if maxval ~= 255 and maxval ~= 65535 then
local top = if wide then 65535 else 255
for i = 0, n * ch - 1 do
buffer.writeu16(s, i * 2, (buffer.readu16(s, i * 2) * maxval + top // 2) // top)
end
end
local magic
if sub == "pam" then
local tt = if ch == 1 then "GRAYSCALE" elseif ch == 2 then "GRAYSCALE_ALPHA" elseif ch == 3 then "RGB" else "RGB_ALPHA"
header(string.format("P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n", w, h, ch, maxval, tt), n * ch * (if wide then 2 else 1))
op = Codec.writeSamples(s, n * ch, wide, out, op)
return out, nil
end
magic = if sub == "pgm" then (if ascii then "P2" else "P5") else (if ascii then "P3" else "P6")
if ascii then
local parts = table.create(h + 1)
parts[1] = string.format("%s\n%d %d\n%d\n", magic, w, h, maxval)
local rowLen = w * ch
for y = 0, h - 1 do
local row = table.create(rowLen)
for i = 0, rowLen - 1 do
row[i + 1] = tostring(buffer.readu16(s, (y * rowLen + i) * 2))
end
parts[y + 2] = table.concat(row, " ") .. "\n"
end
return buffer.fromstring(table.concat(parts)), nil
end
header(string.format("%s\n%d %d\n%d\n", magic, w, h, maxval), n * ch * (if wide then 2 else 1))
op = Codec.writeSamples(s, n * ch, wide, out, op)
return out, nil
end
return Pnm
+152
View File
@@ -0,0 +1,152 @@
--!strict
--!native
--!optimize 2
-- image/qoi/Codec: the QOI op loops (native; never throws). Written from the QOI specification 1.0 (qoiformat.org).
-- decode reads ops from b[p, limit) into an rgba8 buffer; encode writes ops for rgba8 / rgb8 pixels. Every input read
-- is checked against limit; the output buffer has exactly w * h * 4 bytes and the loop stops when it is full.
local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32
local Codec = {}
local index = buffer.create(256)
-- decode(b, p, limit, out, n) -> true | false, "truncated" (n pixels into out)
function Codec.decode(b: buffer, p: number, limit: number, out: buffer, n: number): (boolean, string?)
buffer.fill(index, 0, 0, 256)
local r, g, bl, a = 0, 0, 0, 255
local o = 0
local stop = n * 4
while o < stop do
if p >= limit then
return false, "truncated"
end
local op = readu8(b, p)
p += 1
if op == 0xFE then
if p + 3 > limit then
return false, "truncated"
end
r = readu8(b, p)
g = readu8(b, p + 1)
bl = readu8(b, p + 2)
p += 3
elseif op == 0xFF then
if p + 4 > limit then
return false, "truncated"
end
r = readu8(b, p)
g = readu8(b, p + 1)
bl = readu8(b, p + 2)
a = readu8(b, p + 3)
p += 4
else
local tag = op // 64
if tag == 0 then
local q = op * 4
r = readu8(index, q)
g = readu8(index, q + 1)
bl = readu8(index, q + 2)
a = readu8(index, q + 3)
elseif tag == 1 then
r = (r + (op // 16) % 4 - 2) % 256
g = (g + (op // 4) % 4 - 2) % 256
bl = (bl + op % 4 - 2) % 256
elseif tag == 2 then
if p >= limit then
return false, "truncated"
end
local d2 = readu8(b, p)
p += 1
local dg = op % 64 - 32
g = (g + dg) % 256
r = (r + dg + d2 // 16 - 8) % 256
bl = (bl + dg + d2 % 16 - 8) % 256
else
local run = op % 64 -- 1..62 more copies of the previous pixel (63 / 64 are RGB / RGBA)
local v = r + g * 256 + bl * 65536 + a * 16777216
local e = math.min(o + run * 4, stop - 4)
while o < e do
writeu32(out, o, v)
o += 4
end
end
end
writeu32(out, o, r + g * 256 + bl * 65536 + a * 16777216)
o += 4
local h = ((r * 3 + g * 5 + bl * 7 + a * 11) % 64) * 4
writeu8(index, h, r)
writeu8(index, h + 1, g)
writeu8(index, h + 2, bl)
writeu8(index, h + 3, a)
end
return true, nil
end
-- encode(px, n, bpp, out, o) -> new offset: n pixels of bpp (3 or 4) bytes; out has room for n * (bpp + 1) bytes
function Codec.encode(px: buffer, n: number, bpp: number, out: buffer, o: number): number
buffer.fill(index, 0, 0, 256)
local pr, pg, pb, pa = 0, 0, 0, 255
local run = 0
local hasA = bpp == 4
for i = 0, n - 1 do
local q = i * bpp
local r, g, b = readu8(px, q), readu8(px, q + 1), readu8(px, q + 2)
local a = if hasA then readu8(px, q + 3) else 255
if r == pr and g == pg and b == pb and a == pa then
run += 1
if run == 62 or i == n - 1 then
writeu8(out, o, 0xC0 + run - 1)
o += 1
run = 0
end
else
if run > 0 then
writeu8(out, o, 0xC0 + run - 1)
o += 1
run = 0
end
local h = (r * 3 + g * 5 + b * 7 + a * 11) % 64
local hq = h * 4
if readu8(index, hq) == r and readu8(index, hq + 1) == g and readu8(index, hq + 2) == b and readu8(index, hq + 3) == a then
writeu8(out, o, h)
o += 1
else
writeu8(index, hq, r)
writeu8(index, hq + 1, g)
writeu8(index, hq + 2, b)
writeu8(index, hq + 3, a)
if a == pa then
local dr = (r - pr + 128) % 256 - 128
local dg = (g - pg + 128) % 256 - 128
local db = (b - pb + 128) % 256 - 128
local dgr, dgb = dr - dg, db - dg
if dr >= -2 and dr <= 1 and dg >= -2 and dg <= 1 and db >= -2 and db <= 1 then
writeu8(out, o, 0x40 + (dr + 2) * 16 + (dg + 2) * 4 + db + 2)
o += 1
elseif dg >= -32 and dg <= 31 and dgr >= -8 and dgr <= 7 and dgb >= -8 and dgb <= 7 then
writeu8(out, o, 0x80 + dg + 32)
writeu8(out, o + 1, (dgr + 8) * 16 + dgb + 8)
o += 2
else
writeu8(out, o, 0xFE)
writeu8(out, o + 1, r)
writeu8(out, o + 2, g)
writeu8(out, o + 3, b)
o += 4
end
else
writeu8(out, o, 0xFF)
writeu8(out, o + 1, r)
writeu8(out, o + 2, g)
writeu8(out, o + 3, b)
writeu8(out, o + 4, a)
o += 5
end
end
pr, pg, pb, pa = r, g, b, a
end
end
return o
end
return Codec
+122
View File
@@ -0,0 +1,122 @@
--!strict
-- image/qoi: QOI, the Quite OK Image format (specification 1.0, qoiformat.org). New code written from the spec.
-- Supports: decode of RGB and RGBA files (either colour space tag) to rgba8 (opts.native: rgb8 for 3-channel files);
-- encode of rgba8 (4 channels) and rgb8 (3 channels), lossless; meta.source.colorSpace keeps the sRGB / linear tag.
-- Not supported: nothing in the spec is left out.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Codec = require("@rosetta/image/qoi/Codec")
-- ------------------------------------------------------------------------------------------------ contract
local Qoi = {
name = "qoi",
category = "image",
extensions = { "qoi" },
mime = { "image/qoi", "image/x-qoi" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, alpha = true, depths = { 8 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
native: boolean?, -- rgb8 for 3-channel files (default false: always rgba8)
maxPixels: number?, -- refuse larger images (default 2^26)
}
export type EncodeOptions = {
channels: number?, -- 3 or 4 (default: 3 for rgb8 images or opaque rgba8, else 4)
linear: boolean?, -- tag the file as linear instead of sRGB (default: meta.source.colorSpace == "linear")
}
-- ------------------------------------------------------------------------------------------------ sniff
function Qoi.sniff(r: Bytes.Reader): number
return if r:peek(4) == "qoif" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Qoi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local maxPixels = opts and opts.maxPixels or 2 ^ 26
local magic = r:string(4)
local w, h = r:u32be(), r:u32be()
local channels, cs = r:u8(), r:u8()
if r.err then
return nil, r.err
end
if magic ~= "qoif" then
return nil, Err.new(Err.CORRUPT, "bad magic", r.base)
end
if w == 0 or h == 0 or (channels ~= 3 and channels ~= 4) or cs > 1 then
return nil, Err.new(Err.CORRUPT, "bad header", r.base + 4)
end
if w * h > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
end
local img = Types.Image.new(w, h, "rgba8")
local ok, e = Codec.decode(r.buf, r.pos, r.limit, img.pixels, w * h)
if not ok then
return nil, Err.new(Err.TRUNCATED, tostring(e))
end
if opts and opts.native and channels == 3 then
local rgb = Types.Image.new(w, h, "rgb8")
local src, dst = img.pixels, rgb.pixels
for i = 0, w * h - 1 do
buffer.writeu16(dst, i * 3, buffer.readu16(src, i * 4))
buffer.writeu8(dst, i * 3 + 2, buffer.readu8(src, i * 4 + 2))
end
img = rgb
end
img.meta.source = { format = "qoi", bitDepth = 8, colorType = if channels == 4 then "rgba" else "rgb", channels = channels, colorSpace = if cs == 1 then "linear" else "srgb" }
if cs == 1 then
img.meta.colorSpace = "linear"
end
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Qoi.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(img) ~= "table" or type(img.pixels) ~= "buffer" or (img.format ~= "rgba8" and img.format ~= "rgb8") then
return nil, Err.new(Err.ARG, "needs an rgba8 or rgb8 Image")
end
local w, h = img.width, img.height
local bpp = if img.format == "rgba8" then 4 else 3
if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * bpp then
return nil, Err.new(Err.ARG, "bad image size or pixel buffer")
end
local channels = opts and opts.channels
if channels == nil then
channels = 3
if bpp == 4 then
local px = img.pixels
for i = 0, w * h - 1 do
if buffer.readu8(px, i * 4 + 3) ~= 255 then
channels = 4
break
end
end
end
elseif channels ~= 3 and channels ~= 4 then
return nil, Err.new(Err.ARG, "channels must be 3 or 4")
end
local linear = opts and opts.linear
if linear == nil then
local src = img.meta and img.meta.source
linear = (type(src) == "table" and src.colorSpace == "linear") or (img.meta and img.meta.colorSpace == "linear") or false
end
local n = w * h
local out = buffer.create(14 + n * (bpp + 1) + 8)
buffer.writestring(out, 0, "qoif")
buffer.writeu32(out, 4, bit32.byteswap(w))
buffer.writeu32(out, 8, bit32.byteswap(h))
buffer.writeu8(out, 12, channels :: number)
buffer.writeu8(out, 13, if linear then 1 else 0)
local o = Codec.encode(img.pixels, n, bpp, out, 14)
buffer.writestring(out, o, "\0\0\0\0\0\0\0\1")
o += 8
local res = buffer.create(o)
buffer.copy(res, 0, out, 0, o)
return res, nil
end
return Qoi
+286
View File
@@ -0,0 +1,286 @@
--!strict
-- image/sgi: Silicon Graphics image files (.rgb / .sgi / .bw / .rgba; Paul Haeberli's "The SGI Image File Format"
-- 1.00; new code). Decode: verbatim and RLE storage, 1 and 2 bytes per channel, 1 (grey), 2 (grey + alpha), 3 (RGB)
-- and 4 (RGBA) channels, dimension 1 / 2 / 3, rows bottom-up; rgba8 (2-byte channels keep their high byte), or rgba16
-- with opts.native for 2-byte files; the image name (meta.text.name). Encode: rgba8 as RGB (or RGBA when there is
-- alpha), RLE (default) or verbatim; rgba16 as 2-byte channels. Not supported: the obsolete dithered / screen /
-- colour-map files (colormap field 1..3: UNSUPPORTED).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Sniff = require("@rosetta/core/Sniff")
local Types = require("@rosetta/Types")
-- ------------------------------------------------------------------------------------------------ contract
local Sgi = {
name = "sgi",
category = "image",
extensions = { "sgi", "rgb", "rgba", "bw", "int", "inta" },
mime = { "image/sgi", "image/x-rgb" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" },
caps = { decode = true, encode = true, alpha = true, depths = { 8, 16 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
native: boolean?, -- rgba16 for 2-byte files (default false: rgba8)
maxPixels: number?, -- refuse larger images (default 2^26)
}
export type EncodeOptions = {
rle: boolean?, -- RLE storage (default true)
name: string?, -- the image name (up to 79 bytes; default meta.text.name)
}
local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32
local function be16(b: buffer, o: number): number
return bit32.rshift(bit32.byteswap(readu16(b, o)), 16)
end
local function be32(b: buffer, o: number): number
return bit32.byteswap(readu32(b, o))
end
-- ------------------------------------------------------------------------------------------------ sniff
function Sgi.sniff(r: Bytes.Reader): number
if Sniff.magic(r, "\1\218") == 0 or r:size() < 512 then
return 0
end
local st, bpc = r:peekU8(2), r:peekU8(3)
return if st <= 1 and (bpc == 1 or bpc == 2) then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Sgi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local b, o, limit = r.buf, r.base, r.limit
if limit - o < 512 then
return nil, Err.new(Err.TRUNCATED, "short header", o)
end
if be16(b, o) ~= 474 then
return nil, Err.new(Err.CORRUPT, "not an SGI image", o)
end
local rle, bpc, dim = readu8(b, o + 2), readu8(b, o + 3), be16(b, o + 4)
local w, h, z = be16(b, o + 6), be16(b, o + 8), be16(b, o + 10)
if dim == 1 then
h, z = 1, 1
elseif dim == 2 then
z = 1
end
if rle > 1 or (bpc ~= 1 and bpc ~= 2) or dim < 1 or dim > 3 or w == 0 or h == 0 or z == 0 then
return nil, Err.new(Err.CORRUPT, "bad header", o + 2)
end
if z > 4 then
return nil, Err.new(Err.UNSUPPORTED, z .. " channels", o + 10)
end
local cmap = be32(b, o + 104)
if cmap ~= 0 then
return nil, Err.new(Err.UNSUPPORTED, "colormap type " .. cmap, o + 104)
end
local maxPixels = opts and opts.maxPixels or 2 ^ 26
if w * h > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
end
-- channel planes as 16-bit samples (8-bit values scaled * 257)
local plane = buffer.create(w * h * z * 2)
local truncated = false
local function put(c: number, row: number, x: number, v: number)
buffer.writeu16(plane, ((c * h + row) * w + x) * 2, if bpc == 1 then v * 257 else v)
end
if rle == 0 then
local need = w * h * z * bpc
local p = o + 512
local avail = math.min(need, limit - p)
truncated = avail < need
for i = 0, avail // bpc - 1 do
local v = if bpc == 1 then readu8(b, p + i) else be16(b, p + i * 2)
buffer.writeu16(plane, i * 2, if bpc == 1 then v * 257 else v)
end
else
local n = h * z
if o + 512 + n * 8 > limit then
return nil, Err.new(Err.TRUNCATED, "RLE tables run past the end", o + 512)
end
for c = 0, z - 1 do
for row = 0, h - 1 do
local i = c * h + row
local start, len = be32(b, o + 512 + i * 4), be32(b, o + 512 + n * 4 + i * 4)
local p = o + start
local stop = math.min(limit, p + len)
local x = 0
while x < w and p + bpc <= stop do
local cnt = if bpc == 1 then readu8(b, p) else be16(b, p)
p += bpc
local count = bit32.band(cnt, 0x7F)
if count == 0 then
break
end
if bit32.band(cnt, 0x80) ~= 0 then
for _ = 1, count do
if x >= w or p + bpc > stop then
break
end
put(c, row, x, if bpc == 1 then readu8(b, p) else be16(b, p))
p += bpc
x += 1
end
else
if p + bpc > stop then
break
end
local v = if bpc == 1 then readu8(b, p) else be16(b, p)
p += bpc
for _ = 1, count do
if x >= w then
break
end
put(c, row, x, v)
x += 1
end
end
end
if x < w then
truncated = true
end
end
end
end
local wide = opts and opts.native and bpc == 2
local img = Types.Image.new(w, h, if wide then "rgba16" else "rgba8")
local px = img.pixels
for y = 0, h - 1 do
local row = h - 1 - y
for x = 0, w - 1 do
local function s(c: number): number
return buffer.readu16(plane, ((c * h + row) * w + x) * 2)
end
local rr: number = s(0)
local gg: number = if z >= 3 then s(1) else rr
local bb: number = if z >= 3 then s(2) else rr
local aa: number = if z == 2 then s(1) elseif z == 4 then s(3) else 65535
local d = (y * w + x)
if wide then
buffer.writeu16(px, d * 8, rr)
buffer.writeu16(px, d * 8 + 2, gg)
buffer.writeu16(px, d * 8 + 4, bb)
buffer.writeu16(px, d * 8 + 6, aa)
else
buffer.writeu32(px, d * 4, bit32.rshift(rr, 8) + bit32.rshift(gg, 8) * 256 + bit32.rshift(bb, 8) * 65536 + bit32.rshift(aa, 8) * 16777216)
end
end
end
local name = buffer.readstring(b, o + 24, 80)
local zpos = string.find(name, "\0", 1, true)
name = if zpos then string.sub(name, 1, zpos - 1) else name
if name ~= "" then
img.meta.text = { name = name }
end
if truncated then
img.meta.truncated = true
end
img.meta.source = { format = "sgi", bitDepth = bpc * 8, channels = z, rle = rle == 1, dimension = dim }
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Sgi.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(img) ~= "table" or (img.format ~= "rgba8" and img.format ~= "rgba16") or type(img.pixels) ~= "buffer" then
return nil, Err.new(Err.ARG, "needs an rgba8 or rgba16 Image")
end
local w, h = img.width, img.height
if w < 1 or h < 1 or w > 65535 or h > 65535 then
return nil, Err.new(Err.ARG, "size must be 1..65535")
end
local wide = img.format == "rgba16"
local bpc = if wide then 2 else 1
local px = img.pixels
local function sample(x: number, y: number, c: number): number
local i = (y * w + x) * 4 + c
return if wide then buffer.readu16(px, i * 2) else readu8(px, i)
end
local z = 3
for i = 0, w * h - 1 do
if (if wide then buffer.readu16(px, i * 8 + 6) < 65535 else readu8(px, i * 4 + 3) < 255) then
z = 4
break
end
end
local rle = not (opts and opts.rle == false)
local out = Bytes.writer(512 + w * h * z * bpc + h * z * 8)
out:u16be(474)
out:u8(if rle then 1 else 0)
out:u8(bpc)
out:u16be(3)
out:u16be(w)
out:u16be(h)
out:u16be(z)
out:u32be(0)
out:u32be(if wide then 65535 else 255)
out:u32be(0)
local name = (opts and opts.name) or (img.meta and img.meta.text and img.meta.text.name) or ""
name = string.sub(name, 1, 79)
out:string(name)
out:fill(0, 80 - #name)
out:u32be(0)
out:fill(0, 404)
local function put(v: number)
if wide then
out:u16be(v)
else
out:u8(v)
end
end
if not rle then
for c = 0, z - 1 do
for row = 0, h - 1 do
local y = h - 1 - row
for x = 0, w - 1 do
put(sample(x, y, c))
end
end
end
return out:finish(), nil
end
local tables = out:tell()
out:fill(0, h * z * 8)
for c = 0, z - 1 do
for row = 0, h - 1 do
local y = h - 1 - row
local start = out:tell()
local x = 0
while x < w do
-- a run of equal samples (>= 3) or literals up to the next run
local v = sample(x, y, c)
local run = 1
while x + run < w and run < 127 and sample(x + run, y, c) == v do
run += 1
end
if run >= 3 then
put(run)
put(v)
x += run
else
local lit = 0
while x + lit < w and lit < 127 do
local a = sample(x + lit, y, c)
if x + lit + 2 < w and sample(x + lit + 1, y, c) == a and sample(x + lit + 2, y, c) == a then
break
end
lit += 1
end
lit = math.max(lit, 1)
put(0x80 + lit)
for k = 0, lit - 1 do
put(sample(x + k, y, c))
end
x += lit
end
end
put(0)
local i = c * h + row
out:setU32be(tables + i * 4, start)
out:setU32be(tables + h * z * 4 + i * 4, out:tell() - start)
end
end
return out:finish(), nil
end
return Sgi
+247
View File
@@ -0,0 +1,247 @@
--!strict
-- image/sunras: Sun Raster (rasterfile(5), SunOS <rasterfile.h>; new code). Decode: 1-bit (0 = white without a colour
-- map), 8-bit (grey or the RGB colour map), 24-bit and 32-bit pixels in BGR / XBGR order (RT_STANDARD, RT_OLD,
-- RT_BYTE_ENCODED) or RGB / XRGB order (RT_FORMAT_RGB), the byte-encoded RLE (0x80 escapes), 16-bit row padding; in
-- 32-bit files the X byte is alpha when it is not all zero. Encode: rgba8 as 24-bit (opaque) or 32-bit (alpha in the
-- X byte) BGR, RT_BYTE_ENCODED (default) or RT_STANDARD. Not supported: RT_FORMAT_TIFF / RT_FORMAT_IFF (UNSUPPORTED),
-- raw colour maps (RMT_RAW is ignored).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Sniff = require("@rosetta/core/Sniff")
local Types = require("@rosetta/Types")
local Pixels = require("@rosetta/codecs/image/Pixels")
-- ------------------------------------------------------------------------------------------------ contract
local Sunras = {
name = "sunras",
category = "image",
extensions = { "ras", "sun", "rs", "im1", "im8", "im24", "im32" },
mime = { "image/x-sun-raster", "image/x-cmu-raster" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Pixels" },
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 8, 24, 32 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxPixels: number?, -- refuse larger images (default 2^26)
}
export type EncodeOptions = {
rle: boolean?, -- RT_BYTE_ENCODED (default true); false: RT_STANDARD
}
local MAGIC = "\89\166\106\149"
local readu8, readu32 = buffer.readu8, buffer.readu32
local function be32(b: buffer, o: number): number
return bit32.byteswap(readu32(b, o))
end
-- ------------------------------------------------------------------------------------------------ sniff
function Sunras.sniff(r: Bytes.Reader): number
return Sniff.magic(r, MAGIC)
end
-- ------------------------------------------------------------------------------------------------ decode
function Sunras.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local b, o, limit = r.buf, r.base, r.limit
if limit - o < 32 then
return nil, Err.new(Err.TRUNCATED, "short header", o)
end
if buffer.readstring(b, o, 4) ~= MAGIC then
return nil, Err.new(Err.CORRUPT, "not a Sun raster", o)
end
local w, h, depth, typ, maptype, maplen = be32(b, o + 4), be32(b, o + 8), be32(b, o + 12), be32(b, o + 20), be32(b, o + 24), be32(b, o + 28)
if w == 0 or h == 0 or w > 65536 or h > 65536 then
return nil, Err.new(Err.CORRUPT, "bad size", o + 4)
end
if depth ~= 1 and depth ~= 8 and depth ~= 24 and depth ~= 32 then
return nil, Err.new(Err.UNSUPPORTED, depth .. "-bit pixels", o + 12)
end
if typ == 4 or typ == 5 or typ > 5 and typ ~= 0xFFFF then
return nil, Err.new(Err.UNSUPPORTED, "raster type " .. typ, o + 20)
end
local maxPixels = opts and opts.maxPixels or 2 ^ 26
if w * h > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
end
local p = o + 32
if p + maplen > limit then
return nil, Err.new(Err.TRUNCATED, "colour map runs past the end", p)
end
local pal = buffer.create(1024)
local ncol = 0
if maptype == 1 and maplen > 0 then
ncol = math.min(256, maplen // 3)
for i = 0, ncol - 1 do
buffer.writeu32(pal, i * 4, readu8(b, p + i) + readu8(b, p + ncol + i) * 256 + readu8(b, p + 2 * ncol + i) * 65536 + 0xFF000000)
end
elseif depth == 1 then
buffer.writeu32(pal, 0, 0xFFFFFFFF)
buffer.writeu32(pal, 4, 0xFF000000)
else
for i = 0, 255 do
buffer.writeu32(pal, i * 4, i * 0x10101 + 0xFF000000)
end
end
p += maplen
local stride = ((w * depth + 15) // 16) * 2
local total = stride * h
local raw = buffer.create(total + 4)
local truncated = false
if typ == 2 then
local q = 0
while q < total and p < limit do
local c = readu8(b, p)
p += 1
if c ~= 0x80 then
buffer.writeu8(raw, q, c)
q += 1
else
if p >= limit then
break
end
local n = readu8(b, p)
p += 1
if n == 0 then
buffer.writeu8(raw, q, 0x80)
q += 1
else
if p >= limit then
break
end
local cnt = math.min(n + 1, total - q)
buffer.fill(raw, q, readu8(b, p), cnt)
p += 1
q += cnt
end
end
end
truncated = q < total
else
local n = math.min(total, limit - p)
buffer.copy(raw, 0, b, p, n)
truncated = n < total
end
local img = Types.Image.new(w, h, "rgba8")
local px = img.pixels
if depth <= 8 then
Pixels.indexed(raw, 0, stride, depth, px, w, h, true, pal)
else
local rgb = typ == 3
local bytes = depth // 8
local alpha = false
if bytes == 4 then
for y = 0, h - 1 do
for x = 0, w - 1 do
if readu8(raw, y * stride + x * 4) ~= 0 then
alpha = true
end
end
end
end
for y = 0, h - 1 do
for x = 0, w - 1 do
local s = y * stride + x * bytes
local a = 255
if bytes == 4 then
a = if alpha then readu8(raw, s) else 255
s += 1
end
local c0, c1, c2 = readu8(raw, s), readu8(raw, s + 1), readu8(raw, s + 2)
local rr, bb = if rgb then c0 else c2, if rgb then c2 else c0
buffer.writeu32(px, (y * w + x) * 4, rr + c1 * 256 + bb * 65536 + a * 16777216)
end
end
end
if ncol > 0 then
local list: { { number } } = {}
for i = 0, ncol - 1 do
local v = buffer.readu32(pal, i * 4)
list[i + 1] = { bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255), 255 }
end
img.meta.palette = list
end
if truncated then
img.meta.truncated = true
end
img.meta.source = { format = "sunras", bitDepth = depth, type = typ, rle = typ == 2 }
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Sunras.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, "needs an rgba8 Image")
end
local w, h = img.width, img.height
if w < 1 or h < 1 then
return nil, Err.new(Err.ARG, "bad size")
end
local px = img.pixels
local alpha = false
for i = 0, w * h - 1 do
if readu8(px, i * 4 + 3) < 255 then
alpha = true
break
end
end
local depth = if alpha then 32 else 24
local bytes = depth // 8
local stride = ((w * depth + 15) // 16) * 2
local raw = buffer.create(stride * h)
for y = 0, h - 1 do
for x = 0, w - 1 do
local s, d = (y * w + x) * 4, y * stride + x * bytes
if alpha then
buffer.writeu8(raw, d, readu8(px, s + 3))
d += 1
end
buffer.writeu8(raw, d, readu8(px, s + 2))
buffer.writeu8(raw, d + 1, readu8(px, s + 1))
buffer.writeu8(raw, d + 2, readu8(px, s))
end
end
local rle = not (opts and opts.rle == false)
local body = raw
if rle then
local wr = Bytes.writer(stride * h)
local i, n = 0, stride * h
while i < n do
local v = readu8(raw, i)
local run = 1
while i + run < n and run < 256 and readu8(raw, i + run) == v do
run += 1
end
if run >= 3 or v == 0x80 then
if run == 1 then
wr:u8(0x80)
wr:u8(0)
else
wr:u8(0x80)
wr:u8(run - 1)
wr:u8(v)
end
else
for _ = 1, run do
wr:u8(v)
end
end
i += run
end
body = wr:finish()
end
local out = Bytes.writer(32 + buffer.len(body))
out:string(MAGIC)
out:u32be(w)
out:u32be(h)
out:u32be(depth)
out:u32be(buffer.len(body))
out:u32be(if rle then 2 else 1)
out:u32be(0)
out:u32be(0)
out:bytes(body)
return out:finish(), nil
end
return Sunras
+157
View File
@@ -0,0 +1,157 @@
--!strict
--!native
--!optimize 2
-- image/tga/Codec: the Truevision TGA pixel loops (native; never throws). Written from the Truevision TGA 2.0
-- specification. decode reads raw or RLE pixel data (packets may cross scanlines) into rgba8 at the oriented
-- position; encode writes raw or RLE rows. Every read is bounds-checked; the output has exactly w * h * 4 bytes.
local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32
local Codec = {}
-- one source pixel at b[p] -> rgba as a u32; kind: 0 grey 8, 1 grey + alpha 16, 2 = 15/16-bit ARGB1555,
-- 3 = BGR 24, 4 = BGRA 32, 5 = index 8, 6 = index 16 (pal: u32 entries, palN of them)
local function pixel(b: buffer, p: number, kind: number, alpha1: boolean, pal: buffer, palN: number): number
if kind == 0 then
return readu8(b, p) * 0x10101 + 0xFF000000
elseif kind == 1 then
return readu8(b, p) * 0x10101 + readu8(b, p + 1) * 0x1000000
elseif kind == 2 then
local v = readu16(b, p)
local r, g, bl = (v // 1024) % 32, (v // 32) % 32, v % 32
local a = if alpha1 and v < 32768 then 0 else 255
return (r * 255 + 15) // 31 + ((g * 255 + 15) // 31) * 256 + ((bl * 255 + 15) // 31) * 65536 + a * 16777216 -- round(v * 255 / 31), as ImageMagick
elseif kind == 3 then
return readu8(b, p + 2) + readu8(b, p + 1) * 256 + readu8(b, p) * 65536 + 0xFF000000
elseif kind == 4 then
return readu8(b, p + 2) + readu8(b, p + 1) * 256 + readu8(b, p) * 65536 + readu8(b, p + 3) * 16777216
end
local i = if kind == 5 then readu8(b, p) else readu16(b, p)
if i >= palN then
return 0xFF000000
end
return readu32(pal, i * 4)
end
Codec.pixel = pixel
-- decode(b, p, limit, w, h, bpp, kind, alpha1, rle, bottomUp, rtl, pal, palN, out) -> pixels written, truncated?
function Codec.decode(b: buffer, p: number, limit: number, w: number, h: number, bpp: number, kind: number, alpha1: boolean, rle: boolean, bottomUp: boolean, rtl: boolean, pal: buffer, palN: number, out: buffer): (number, boolean)
local n = w * h
local i = 0
local function put(v: number)
local row, col = i // w, i % w
if bottomUp then
row = h - 1 - row
end
if rtl then
col = w - 1 - col
end
writeu32(out, (row * w + col) * 4, v)
i += 1
end
if not rle then
local avail = math.min(n, (limit - p) // bpp)
for _ = 1, avail do
put(pixel(b, p, kind, alpha1, pal, palN))
p += bpp
end
return i, avail < n
end
while i < n do
if p >= limit then
return i, true
end
local hd = readu8(b, p)
p += 1
local count = hd % 128 + 1
if hd >= 128 then
if p + bpp > limit then
return i, true
end
local v = pixel(b, p, kind, alpha1, pal, palN)
p += bpp
for _ = 1, math.min(count, n - i) do
put(v)
end
else
for _ = 1, math.min(count, n - i) do
if p + bpp > limit then
return i, true
end
put(pixel(b, p, kind, alpha1, pal, palN))
p += bpp
end
end
end
return i, false
end
-- encode(px, w, h, srcBpp, outBpp, rle, topDown, out, o) -> new offset. px: rgba8 / rgb8 / gray8 (srcBpp 4 / 3 / 1);
-- written as BGRA / BGR / grey (outBpp 4 / 3 / 1), rows top-down or bottom-up; RLE packets stay inside a row.
-- out needs room for w * h * (outBpp + 1) bytes.
function Codec.encode(px: buffer, w: number, h: number, srcBpp: number, outBpp: number, rle: boolean, topDown: boolean, out: buffer, o: number): number
local function get(q: number): number
if srcBpp == 1 then
return readu8(px, q)
elseif srcBpp == 3 then
return readu8(px, q) + readu8(px, q + 1) * 256 + readu8(px, q + 2) * 65536 + 0xFF000000
end
return readu32(px, q)
end
local function emit(v: number)
if outBpp == 1 then
writeu8(out, o, v % 256)
else
writeu8(out, o, (v // 65536) % 256)
writeu8(out, o + 1, (v // 256) % 256)
writeu8(out, o + 2, v % 256)
if outBpp == 4 then
writeu8(out, o + 3, v // 16777216)
end
end
o += outBpp
end
for y = 0, h - 1 do
local row = if topDown then y else h - 1 - y
local base = row * w * srcBpp
if not rle then
for x = 0, w - 1 do
emit(get(base + x * srcBpp))
end
else
local x = 0
while x < w do
local v = get(base + x * srcBpp)
local run = 1
while x + run < w and run < 128 and get(base + (x + run) * srcBpp) == v do
run += 1
end
if run >= 2 then
writeu8(out, o, 127 + run)
o += 1
emit(v)
x += run
else
-- a raw packet up to the next run of 2 or more
local s = x
local cnt = 0
while x < w and cnt < 128 do
local c = get(base + x * srcBpp)
if x + 1 < w and get(base + (x + 1) * srcBpp) == c then
break
end
cnt += 1
x += 1
end
writeu8(out, o, cnt - 1)
o += 1
for k = s, s + cnt - 1 do
emit(get(base + k * srcBpp))
end
end
end
end
end
return o
end
return Codec
+276
View File
@@ -0,0 +1,276 @@
--!strict
-- image/tga: Truevision TGA (TGA 2.0 specification; new code). Decode: colour-mapped (1), true-colour (2) and grey (3)
-- images, raw or RLE (9, 10, 11; packets may cross scanlines), 8 / 15 / 16 / 24 / 32-bit pixels, 15 / 16 / 24 /
-- 32-bit colour maps with a first index, 8 / 16-bit indexes, grey + alpha (16-bit type 3), every origin (bottom-left,
-- top-left, right-to-left), the alpha bits of the descriptor (16-bit: alpha only when it declares 1 alpha bit; 32-bit:
-- alpha always), the image ID (meta.text.id) and the TGA 2.0 footer (tolerated, not needed). Truncated pixel data
-- leaves the rest transparent black (meta.truncated). opts.native: gray8 for grey files, rgb8 for 24-bit.
-- Encode: rgba8 (32-bit BGRA when there is alpha, else 24-bit), rgb8 (24-bit), gray8 (type 3), raw or RLE, bottom-left
-- (default) or top-left origin, with the TGA 2.0 footer. Not supported: the extension area's fields (gamma, postage
-- stamp, ...), which are ignored.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Codec = require("@rosetta/image/tga/Codec")
-- ------------------------------------------------------------------------------------------------ contract
local Tga = {
name = "tga",
category = "image",
extensions = { "tga", "icb", "vda", "vst", "tpic" },
mime = { "image/x-tga", "image/x-targa" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8, 15, 16, 24, 32 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
native: boolean?, -- gray8 for grey files, rgb8 for 24-bit ones (default false: rgba8)
maxPixels: number?, -- refuse larger images (default 2^26)
}
export type EncodeOptions = {
rle: boolean?, -- run-length encode (default false)
origin: ("bottom-left" | "top-left")?, -- default "bottom-left" (the classic layout every reader understands)
alpha: boolean?, -- force 32-bit (true) or 24-bit (false) for rgba8 (default: 32-bit when any alpha < 255)
id: string?, -- the image ID field (up to 255 bytes; default meta.text.id)
}
-- ------------------------------------------------------------------------------------------------ constants
local TYPES = { [1] = true, [2] = true, [3] = true, [9] = true, [10] = true, [11] = true }
local FOOTER = "TRUEVISION-XFILE.\0"
local readu8 = buffer.readu8
-- ------------------------------------------------------------------------------------------------ sniff
type Header = {
idLen: number,
cmapType: number,
imageType: number,
cmapFirst: number,
cmapLen: number,
cmapBits: number,
width: number,
height: number,
depth: number,
desc: number,
}
local function header(r: Bytes.Reader): Header?
if r.limit - r.base < 18 then
return nil
end
local b, o = r.buf, r.base
local function u16(q: number): number
return readu8(b, o + q) + readu8(b, o + q + 1) * 256
end
local h: Header = {
idLen = readu8(b, o),
cmapType = readu8(b, o + 1),
imageType = readu8(b, o + 2),
cmapFirst = u16(3),
cmapLen = u16(5),
cmapBits = readu8(b, o + 7),
width = u16(12),
height = u16(14),
depth = readu8(b, o + 16),
desc = readu8(b, o + 17),
}
return h
end
-- plausible(h) -> nil | why not
local function implausible(h: Header): string?
local t = h.imageType
if not TYPES[t] then
return "image type " .. t
end
if h.cmapType > 1 then
return "colour map type " .. h.cmapType
end
local mapped = t == 1 or t == 9
if mapped and (h.cmapType ~= 1 or (h.depth ~= 8 and h.depth ~= 16)) then
return "colour-mapped image without a colour map"
end
if h.cmapType == 1 and h.cmapLen > 0 and h.cmapBits ~= 15 and h.cmapBits ~= 16 and h.cmapBits ~= 24 and h.cmapBits ~= 32 then
return "colour map entry size " .. h.cmapBits
end
if (t == 2 or t == 10) and h.depth ~= 15 and h.depth ~= 16 and h.depth ~= 24 and h.depth ~= 32 then
return "pixel depth " .. h.depth
end
if (t == 3 or t == 11) and h.depth ~= 8 and h.depth ~= 16 then
return "grey pixel depth " .. h.depth
end
if h.width == 0 or h.height == 0 then
return "zero size"
end
if h.desc >= 64 then
return "interleaving / reserved descriptor bits"
end
return nil
end
function Tga.sniff(r: Bytes.Reader): number
local h = header(r)
if not h or implausible(h) then
return 0
end
local n = r.limit - r.base
if n >= 44 and buffer.readstring(r.buf, r.limit - 18, 18) == FOOTER then
return 0.9
end
return 0.2
end
-- ------------------------------------------------------------------------------------------------ decode
function Tga.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local maxPixels = opts and opts.maxPixels or 2 ^ 26
local h = header(r)
if not h then
return nil, Err.new(Err.TRUNCATED, "short header", r.base)
end
local why = implausible(h)
if why then
return nil, Err.new(if h.imageType == 0 then Err.UNSUPPORTED else Err.CORRUPT, why, r.base)
end
local w, ht = h.width, h.height
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 = r.buf
local p = r.base + 18
local id = if h.idLen > 0 and p + h.idLen <= r.limit then buffer.readstring(b, p, h.idLen) else nil
p += h.idLen
-- colour map
local pal = buffer.create(4)
local palN = 0
if h.cmapType == 1 and h.cmapLen > 0 then
local eb = (h.cmapBits + 7) // 8
if p + h.cmapLen * eb > r.limit then
return nil, Err.new(Err.TRUNCATED, "colour map runs past the end", p)
end
local first = h.cmapFirst
palN = first + h.cmapLen
pal = buffer.create(palN * 4)
buffer.fill(pal, 0, 0, palN * 4)
local kind = if h.cmapBits == 24 then 3 elseif h.cmapBits == 32 then 4 else 2
for i = 0, h.cmapLen - 1 do
buffer.writeu32(pal, (first + i) * 4, Codec.pixel(b, p + i * eb, kind, false, pal, 0))
end
for i = 0, first - 1 do
buffer.writeu32(pal, i * 4, 0xFF000000)
end
p += h.cmapLen * eb
end
local t = h.imageType
local alphaBits = h.desc % 16
local kind
if t == 1 or t == 9 then
kind = if h.depth == 8 then 5 else 6
elseif t == 3 or t == 11 then
kind = if h.depth == 8 then 0 else 1
else
kind = if h.depth == 24 then 3 elseif h.depth == 32 then 4 else 2
end
local bpp = (h.depth + 7) // 8
local bottomUp = (h.desc // 32) % 2 == 0
local rtl = (h.desc // 16) % 2 == 1
local img = Types.Image.new(w, ht, "rgba8")
local _, truncated = Codec.decode(b, p, r.limit, w, ht, bpp, kind, h.depth == 16 and alphaBits >= 1, t >= 9, bottomUp, rtl, pal, palN, img.pixels)
local native = opts and opts.native
if native and kind == 0 then
local g = Types.Image.new(w, ht, "gray8")
for i = 0, w * ht - 1 do
buffer.writeu8(g.pixels, i, readu8(img.pixels, i * 4))
end
img = g
elseif native and kind == 3 then
local c = Types.Image.new(w, ht, "rgb8")
for i = 0, w * ht - 1 do
buffer.writeu16(c.pixels, i * 3, buffer.readu16(img.pixels, i * 4))
buffer.writeu8(c.pixels, i * 3 + 2, readu8(img.pixels, i * 4 + 2))
end
img = c
end
if palN > 0 then
local palette = {}
for i = 0, palN - 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 id then
img.meta.text = { id = id }
end
if truncated then
img.meta.truncated = true
end
img.meta.source = {
format = "tga",
bitDepth = h.depth,
colorType = if kind >= 5 then "palette" elseif kind <= 1 then (if kind == 1 then "graya" else "gray") else (if kind == 3 then "rgb" else "rgba"),
rle = t >= 9,
origin = (if bottomUp then "bottom" else "top") .. "-" .. (if rtl then "right" else "left"),
alphaBits = alphaBits,
}
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Tga.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(img) ~= "table" or type(img.pixels) ~= "buffer" then
return nil, Err.new(Err.ARG, "needs an Image")
end
local srcBpp = if img.format == "rgba8" then 4 elseif img.format == "rgb8" then 3 elseif img.format == "gray8" then 1 else nil
if not srcBpp then
return nil, Err.new(Err.ARG, "needs an rgba8, rgb8 or gray8 Image")
end
local w, h = img.width, img.height
if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w > 65535 or h > 65535 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * srcBpp then
return nil, Err.new(Err.ARG, "bad image size or pixel buffer (1..65535 per side)")
end
local o: any = opts or {}
local origin = o.origin or "bottom-left"
if origin ~= "bottom-left" and origin ~= "top-left" then
return nil, Err.new(Err.ARG, "origin must be \"bottom-left\" or \"top-left\"")
end
local outBpp = srcBpp
if srcBpp == 4 then
local alpha = o.alpha
if alpha == nil then
alpha = false
for i = 0, w * h - 1 do
if readu8(img.pixels, i * 4 + 3) ~= 255 then
alpha = true
break
end
end
end
outBpp = if alpha then 4 else 3
end
local id = o.id or (img.meta and img.meta.text and img.meta.text.id) or ""
if type(id) ~= "string" then
id = ""
end
id = string.sub(id, 1, 255)
local rle = o.rle == true
local out = buffer.create(18 + #id + w * h * (outBpp + 1) + 26)
buffer.writeu8(out, 0, #id)
buffer.writeu8(out, 2, (if outBpp == 1 then 3 else 2) + (if rle then 8 else 0))
buffer.writeu16(out, 12, w)
buffer.writeu16(out, 14, h)
buffer.writeu8(out, 16, outBpp * 8)
buffer.writeu8(out, 17, (if outBpp == 4 then 8 else 0) + (if origin == "top-left" then 32 else 0))
buffer.writestring(out, 18, id)
local op = Codec.encode(img.pixels, w, h, srcBpp, outBpp, rle, origin == "top-left", out, 18 + #id)
-- TGA 2.0 footer: no extension / developer areas
buffer.writeu32(out, op, 0)
buffer.writeu32(out, op + 4, 0)
buffer.writestring(out, op + 8, FOOTER)
op += 26
local res = buffer.create(op)
buffer.copy(res, 0, out, 0, op)
return res, nil
end
return Tga
+399
View File
@@ -0,0 +1,399 @@
--!strict
--!native
--!optimize 2
-- image/tiff/Pixels: the hot loops of the TIFF codec (native; never throws): the horizontal (2) and
-- floating-point (3) predictors both ways (TIFF 6.0 section 14, Adobe TIFF technote 3; predictor 3 as libtiff's
-- fpAcc / fpDiff), fill-order bit reversal, and the sample converter from decoded planes to a Types.Image layout.
-- Callers (image/tiff/init) size every buffer before calling: planes hold h rows of rb bytes plus 8 bytes of slack.
local Bytes = require("@rosetta/core/Bytes")
local readu8, writeu8, readu16, writeu16, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32, buffer.writeu32
local readf32, writef32, readf64 = buffer.readf32, buffer.writef32, buffer.readf64
local band, bor, rshift, lshift, byteswap = bit32.band, bit32.bor, bit32.rshift, bit32.lshift, bit32.byteswap
local floor = math.floor
local Pixels = {}
local scratch = buffer.create(8)
-- floats read through their bits: NaN / infinity never load from memory (LuaJIT's FFI would hand back a NaN with an
-- arbitrary payload, which its NaN-tagged values misread as a table / userdata)
local function f32(bits: number): number
if band(bits, 0x7F800000) == 0x7F800000 then
if band(bits, 0x7FFFFF) ~= 0 then
return 0 / 0
end
return if bits >= 0x80000000 then -math.huge else math.huge
end
writeu32(scratch, 0, bits)
return readf32(scratch, 0)
end
local function f64(lo: number, hi: number): number
if band(hi, 0x7FF00000) == 0x7FF00000 then
if band(hi, 0xFFFFF) ~= 0 or lo ~= 0 then
return 0 / 0
end
return if hi >= 0x80000000 then -math.huge else math.huge
end
writeu32(scratch, 0, lo)
writeu32(scratch, 4, hi)
return readf64(scratch, 0)
end
Pixels.f32 = f32
Pixels.f64 = f64
-- ------------------------------------------------------------------------------------------------ fill order
local REV = buffer.create(256)
for i = 0, 255 do
local r = 0
for k = 0, 7 do
if band(i, lshift(1, k)) ~= 0 then
r = bor(r, lshift(1, 7 - k))
end
end
writeu8(REV, i, r)
end
function Pixels.reverseBits(b: buffer, off: number, len: number)
for i = off, off + len - 1 do
writeu8(b, i, readu8(REV, readu8(b, i)))
end
end
-- ------------------------------------------------------------------------------------------------ predictors
-- unpredict2(b, off, rows, rb, stride, bps, le): undo horizontal differencing (bps 8, 16 or 32; others untouched)
function Pixels.unpredict2(b: buffer, off: number, rows: number, rb: number, stride: number, bps: number, le: boolean)
for r = 0, rows - 1 do
local base = off + r * rb
if bps == 8 then
for i = base + stride, base + rb - 1 do
writeu8(b, i, band(readu8(b, i) + readu8(b, i - stride), 255))
end
elseif bps == 16 then
local n = rb // 2
for k = stride, n - 1 do
local i = base + k * 2
local j = i - stride * 2
if le then
writeu16(b, i, band(readu16(b, i) + readu16(b, j), 0xFFFF))
else
local v = readu8(b, i) * 256 + readu8(b, i + 1) + readu8(b, j) * 256 + readu8(b, j + 1)
writeu8(b, i, band(rshift(v, 8), 255))
writeu8(b, i + 1, band(v, 255))
end
end
elseif bps == 32 then
local n = rb // 4
for k = stride, n - 1 do
local i = base + k * 4
local j = i - stride * 4
if le then
writeu32(b, i, (readu32(b, i) + readu32(b, j)) % 4294967296)
else
writeu32(b, i, byteswap((byteswap(readu32(b, i)) + byteswap(readu32(b, j))) % 4294967296))
end
end
end
end
end
-- predict2(b, off, rows, rb, stride, bps): apply horizontal differencing to little-endian samples (8 / 16 bit)
function Pixels.predict2(b: buffer, off: number, rows: number, rb: number, stride: number, bps: number)
for r = 0, rows - 1 do
local base = off + r * rb
if bps == 8 then
for i = base + rb - 1, base + stride, -1 do
writeu8(b, i, band(readu8(b, i) - readu8(b, i - stride), 255))
end
elseif bps == 16 then
for k = rb // 2 - 1, stride, -1 do
local i = base + k * 2
writeu16(b, i, band(readu16(b, i) - readu16(b, i - stride * 2), 0xFFFF))
end
end
end
end
-- unpredict3(b, off, rows, rb, bytes, stride, tmp): undo the floating-point predictor; the samples come out little
-- endian whatever the file's byte order (libtiff fpAcc). tmp holds at least rb bytes.
function Pixels.unpredict3(b: buffer, off: number, rows: number, rb: number, bytes: number, stride: number, tmp: buffer)
local wc = rb // bytes
for r = 0, rows - 1 do
local base = off + r * rb
for i = base + stride, base + rb - 1 do
writeu8(b, i, band(readu8(b, i) + readu8(b, i - stride), 255))
end
buffer.copy(tmp, 0, b, base, rb)
for c = 0, wc - 1 do
for k = 0, bytes - 1 do
writeu8(b, base + c * bytes + k, readu8(tmp, (bytes - k - 1) * wc + c))
end
end
end
end
-- predict3(b, off, rows, rb, bytes, stride, tmp): the floating-point predictor on little-endian samples (fpDiff)
function Pixels.predict3(b: buffer, off: number, rows: number, rb: number, bytes: number, stride: number, tmp: buffer)
local wc = rb // bytes
for r = 0, rows - 1 do
local base = off + r * rb
for c = 0, wc - 1 do
for k = 0, bytes - 1 do
writeu8(tmp, (bytes - k - 1) * wc + c, readu8(b, base + c * bytes + k))
end
end
buffer.copy(b, base, tmp, 0, rb)
for i = base + rb - 1, base + stride, -1 do
writeu8(b, i, band(readu8(b, i) - readu8(b, i - stride), 255))
end
end
end
-- ------------------------------------------------------------------------------------------------ samples
local half = Bytes.half
export type Params = {
planes: { buffer },
rb: number, -- bytes per row in each plane
chunky: boolean,
w: number,
h: number,
spp: number,
bps: number,
sfmt: number, -- 1 uint, 2 int, 3 float
le: boolean,
photo: number, -- 0 min-is-white, 1 min-is-black, 2 RGB, 3 palette, 5 CMYK
alpha: number, -- sample index of the alpha channel, -1 = none
assoc: boolean, -- premultiplied alpha (undone)
cmap: buffer?, -- palette: 3 * 2^bps u16 (red block, green block, blue block)
kind: string, -- the output pixel format
out: buffer,
}
-- the common 8-bit chunky cases without per-sample dispatch; false when P is not one of them
local function fast(P: Params): boolean
if not P.chunky or P.bps ~= 8 or P.sfmt ~= 1 or P.assoc then
return false
end
local b, rb, w, h, spp, alpha, kind, out = P.planes[1], P.rb, P.w, P.h, P.spp, P.alpha, P.kind, P.out
local o = 0
if P.photo == 2 and spp >= 3 and (kind == "rgba8" or kind == "rgb8") then
local four = kind == "rgba8"
for y = 0, h - 1 do
local p = y * rb
for _ = 0, w - 1 do
writeu8(out, o, readu8(b, p))
writeu8(out, o + 1, readu8(b, p + 1))
writeu8(out, o + 2, readu8(b, p + 2))
if four then
writeu8(out, o + 3, if alpha >= 0 then readu8(b, p + alpha) else 255)
o += 4
else
o += 3
end
p += spp
end
end
return true
elseif (P.photo == 1 or P.photo == 0) and (kind == "rgba8" or kind == "gray8" or kind == "graya8") then
local inv = if P.photo == 0 then 255 else 0
for y = 0, h - 1 do
local p = y * rb
for _ = 0, w - 1 do
local v = math.abs(inv - readu8(b, p))
if kind == "gray8" then
writeu8(out, o, v)
o += 1
elseif kind == "graya8" then
writeu8(out, o, v)
writeu8(out, o + 1, if alpha >= 0 then readu8(b, p + alpha) else 255)
o += 2
else
writeu32(out, o, v * 0x10101 + (if alpha >= 0 then readu8(b, p + alpha) else 255) * 0x1000000)
o += 4
end
p += spp
end
end
return true
end
return false
end
-- convert(P): every pixel into P.out in P.kind's layout
function Pixels.convert(P: Params)
if fast(P) then
return
end
local planes, rb, chunky, w, h, spp, bps, sfmt, le = P.planes, P.rb, P.chunky, P.w, P.h, P.spp, P.bps, P.sfmt, P.le
local photo, alpha, assoc, cmap, kind, out = P.photo, P.alpha, P.assoc, P.cmap, P.kind, P.out
local maxv = 2 ^ math.min(bps, 32) - 1
local float = sfmt == 3
local signed = sfmt == 2
local cmapN = 2 ^ math.min(bps, 16)
-- raw sample s of pixel x in the row starting at byte ro of its plane
local function raw(s: number, x: number, row: number): number
local b, i
if chunky then
b, i = planes[1], x * spp + s
else
b, i = planes[s + 1], x
end
local ro = row * rb
if bps == 8 then
local v = readu8(b, ro + i)
return if signed then (v + 128) % 256 else v
elseif bps == 16 then
local p = ro + i * 2
local v = if le then readu16(b, p) else readu8(b, p) * 256 + readu8(b, p + 1)
if float then
return half(v)
end
return if signed then (v + 32768) % 65536 else v
elseif bps == 32 then
local p = ro + i * 4
if float then
return f32(if le then readu32(b, p) else byteswap(readu32(b, p)))
end
local v = if le then readu32(b, p) else byteswap(readu32(b, p))
return if signed then (v + 2147483648) % 4294967296 else v
elseif bps == 64 then
local p = ro + i * 8
if le then
return f64(readu32(b, p), readu32(b, p + 4))
end
return f64(byteswap(readu32(b, p + 4)), byteswap(readu32(b, p)))
else
-- any other depth (1..31): MSB-first bit fields
local bit = i * bps
local v = 0
local need = bps
local p = ro + rshift(bit, 3)
local sh = band(bit, 7)
local cur = band(readu8(b, p), rshift(255, sh))
local avail = 8 - sh
while need > 0 do
if need >= avail then
v = v * 2 ^ avail + cur
need -= avail
p += 1
cur = if need > 0 then readu8(b, p) else 0
avail = 8
else
v = v * 2 ^ need + rshift(cur, avail - need)
need = 0
end
end
return v
end
end
-- normalised 0..1 (floats as stored)
local function norm(s: number, x: number, row: number): number
local v = raw(s, x, row)
if float then
return v
end
return v / maxv
end
local o = 0
local is8 = kind == "rgba8" or kind == "rgb8" or kind == "gray8" or kind == "graya8"
local is16 = kind == "rgba16" or kind == "gray16"
local nch = if kind == "rgba8" or kind == "rgba16" or kind == "rgbaf32" then 4 elseif kind == "rgb8" then 3 elseif kind == "graya8" then 2 else 1
for y = 0, h - 1 do
for x = 0, w - 1 do
local r, g, bl, a
if photo == 3 then
local idx = raw(0, x, y)
if cmap and idx < cmapN then
r = readu16(cmap, idx * 2) / 65535
g = readu16(cmap, (cmapN + idx) * 2) / 65535
bl = readu16(cmap, (2 * cmapN + idx) * 2) / 65535
else
r, g, bl = 0, 0, 0
end
elseif photo == 2 then
r = norm(0, x, y)
g = norm(1, x, y)
bl = norm(2, x, y)
elseif photo == 5 then
local c, m, ye, k = norm(0, x, y), norm(1, x, y), norm(2, x, y), norm(3, x, y)
r, g, bl = (1 - c) * (1 - k), (1 - m) * (1 - k), (1 - ye) * (1 - k)
else
local v = norm(0, x, y)
if photo == 0 then
v = 1 - v
end
r, g, bl = v, v, v
end
if alpha >= 0 then
a = norm(alpha, x, y)
if assoc then
if a > 0 then
r = math.min(r / a, 1)
g = math.min(g / a, 1)
bl = math.min(bl / a, 1)
else
r, g, bl = 0, 0, 0
end
end
else
a = 1
end
if is8 then
if r ~= r then
r = 0
end
if g ~= g then
g = 0
end
if bl ~= bl then
bl = 0
end
if a ~= a then
a = 0
end
local R = floor(math.clamp(r, 0, 1) * 255 + 0.5)
if nch == 1 then
writeu8(out, o, R)
elseif nch == 2 then
writeu8(out, o, R)
writeu8(out, o + 1, floor(math.clamp(a, 0, 1) * 255 + 0.5))
else
writeu8(out, o, R)
writeu8(out, o + 1, floor(math.clamp(g, 0, 1) * 255 + 0.5))
writeu8(out, o + 2, floor(math.clamp(bl, 0, 1) * 255 + 0.5))
if nch == 4 then
writeu8(out, o + 3, floor(math.clamp(a, 0, 1) * 255 + 0.5))
end
end
o += nch
elseif is16 then
if r ~= r then
r = 0
end
if g ~= g then
g = 0
end
if bl ~= bl then
bl = 0
end
if a ~= a then
a = 0
end
writeu16(out, o, floor(math.clamp(r, 0, 1) * 65535 + 0.5))
if nch == 4 then
writeu16(out, o + 2, floor(math.clamp(g, 0, 1) * 65535 + 0.5))
writeu16(out, o + 4, floor(math.clamp(bl, 0, 1) * 65535 + 0.5))
writeu16(out, o + 6, floor(math.clamp(a, 0, 1) * 65535 + 0.5))
end
o += nch * 2
else
writef32(out, o, r)
writef32(out, o + 4, g)
writef32(out, o + 8, bl)
writef32(out, o + 12, a)
o += 16
end
end
end
end
return Pixels
+842
View File
@@ -0,0 +1,842 @@
--!strict
-- image/tiff: TIFF 6.0 (+ Adobe technote 3 floating point, BigTIFF). New code from the TIFF 6.0 specification.
-- Decode: both byte orders, classic and BigTIFF, strips and tiles, planar configuration 1 and 2, compression none /
-- LZW (codecs/compress/Lzw, also old-style) / Deflate (8 and 32946, codecs/compress/Deflate) / PackBits, JPEG (7) through the api's
-- opts.decodeImage hook (JPEGTables stitched to each strip / tile), predictors 2 (8 / 16 / 32-bit) and 3 (float),
-- 1..32-bit unsigned / signed integer and 16 / 32 / 64-bit float samples, min-is-white / min-is-black, RGB, palette,
-- CMYK (naive conversion), extra samples (associated alpha is un-premultiplied), fill order 2, every page as
-- img.frames, resolution (meta.dpi), ICC (meta.icc). Decodes to rgba8, or with opts.native to the nearest standard
-- layout (gray8, gray16, graya8, rgb8, rgba8, rgba16, rgbaf32).
-- Encode: rgba8 / rgb8 / gray8 / graya8 / gray16 / rgba16 / rgbaf32 as the matching TIFF layout, compression none /
-- deflate / lzw / packbits with predictor 2 (integers) or 3 (floats), strips, multi-page from img.frames.
-- Not supported: old-style JPEG (6), CCITT fax (2, 3, 4), uncompressed YCbCr with subsampling, CIELab, JBIG.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Deflate = require("@rosetta/codecs/compress/Deflate")
local Lzw = require("@rosetta/codecs/compress/Lzw")
local Pixels = require("@rosetta/image/tiff/Pixels")
local PackBits = require("@rosetta/codecs/compress/PackBits")
-- ------------------------------------------------------------------------------------------------ contract
local Tiff = {
name = "tiff",
category = "image",
extensions = { "tif", "tiff" },
mime = { "image/tiff" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/compress/Lzw", "codecs/compress/PackBits" },
caps = { decode = true, encode = true, alpha = true, pages = true, depths = { 1, 2, 4, 8, 16, 32 }, float = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
native: boolean?, -- keep the source layout (gray8 / gray16 / graya8 / rgb8 / rgba8 / rgba16 / rgbaf32); default rgba8
maxPixels: number?, -- per page (default 2^26)
maxPages: number?, -- pages decoded into img.frames (default 1024)
page: number?, -- decode only this page (1-based)
decodeImage: ((buffer) -> (any, any))?, -- the api's hook, for JPEG-compressed pages
}
export type EncodeOptions = {
compression: ("none" | "deflate" | "lzw" | "packbits")?, -- default "deflate"
predictor: boolean?, -- horizontal / float predictor with deflate and lzw (default true)
level: number?, -- deflate level 0..9 (default 6)
rowsPerStrip: number?, -- default: about 64 KB per strip
}
-- ------------------------------------------------------------------------------------------------ constants
local TYPE_SIZE = { [1] = 1, [2] = 1, [3] = 2, [4] = 4, [5] = 8, [6] = 1, [7] = 1, [8] = 2, [9] = 4, [10] = 8, [11] = 4, [12] = 8, [13] = 4, [16] = 8, [17] = 8, [18] = 8 }
local COMPRESSION = { [1] = "none", [5] = "lzw", [8] = "deflate", [32946] = "deflate", [32773] = "packbits", [7] = "jpeg" }
local PHOTOMETRIC = { [0] = "miniswhite", [1] = "minisblack", [2] = "rgb", [3] = "palette", [5] = "cmyk", [6] = "ycbcr" }
local TWO32 = 4294967296
local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32
-- ------------------------------------------------------------------------------------------------ sniff
function Tiff.sniff(r: Bytes.Reader): number
local s = r:peek(4)
if s == "II*\0" or s == "MM\0*" or s == "II+\0" or s == "MM\0+" then
return 1
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
type Entry = { tag: number, typ: number, count: number, at: number }
type Ctx = { b: buffer, base: number, limit: number, le: boolean, big: boolean }
local function u16(c: Ctx, at: number): number
if at < c.base or at + 2 > c.limit then
return 0
end
return if c.le then readu16(c.b, at) else readu8(c.b, at) * 256 + readu8(c.b, at + 1)
end
local function u32(c: Ctx, at: number): number
if at < c.base or at + 4 > c.limit then
return 0
end
local v = readu32(c.b, at)
return if c.le then v else bit32.byteswap(v)
end
local function u64(c: Ctx, at: number): number
local lo, hi = u32(c, at), u32(c, at + 4)
if not c.le then
lo, hi = hi, lo
end
return hi * TWO32 + lo
end
local function off(c: Ctx, at: number): number
return if c.big then u64(c, at) else u32(c, at)
end
-- values(c, e, max) -> the entry's numbers (rationals divided) | nil when out of range / too many
local function values(c: Ctx, e: Entry?, max: number?): { number }?
if not e then
return nil
end
local size = TYPE_SIZE[e.typ]
if not size or e.count > (max or 1e7) or e.at < c.base or e.at + e.count * size > c.limit then
return nil
end
local out = table.create(e.count, 0)
local b = c.b
for i = 0, e.count - 1 do
local p = e.at + i * size
local t = e.typ
local v
if t == 1 or t == 2 or t == 7 then
v = readu8(b, p)
elseif t == 6 then
v = buffer.readi8(b, p)
elseif t == 3 then
v = u16(c, p)
elseif t == 8 then
v = u16(c, p)
if v >= 32768 then
v -= 65536
end
elseif t == 4 or t == 13 then
v = u32(c, p)
elseif t == 9 then
v = u32(c, p)
if v >= 2147483648 then
v -= TWO32
end
elseif t == 5 or t == 10 then
local n, d = u32(c, p), u32(c, p + 4)
if t == 10 then
if n >= 2147483648 then
n -= TWO32
end
if d >= 2147483648 then
d -= TWO32
end
end
v = if d ~= 0 then n / d else 0
elseif t == 11 then
v = Pixels.f32(u32(c, p))
elseif t == 12 then
local lo, hi = u32(c, p), u32(c, p + 4)
if not c.le then
lo, hi = hi, lo
end
v = Pixels.f64(lo, hi)
else
v = u64(c, p)
end
out[i + 1] = v
end
return out
end
local function one(c: Ctx, e: Entry?, default: number): number
local v = values(c, e, 64)
return if v and v[1] then v[1] else default
end
-- the IFD at absolute offset p: { [tag] = Entry }, next IFD offset (absolute, 0 = none) | nil, Err
local function readIfd(c: Ctx, p: number): ({ [number]: Entry }?, number, Err.Err?)
local esize = if c.big then 20 else 12
local hsize = if c.big then 8 else 2
if p < c.base or p + hsize > c.limit then
return nil, 0, Err.new(Err.TRUNCATED, "IFD past the end", p)
end
local n = if c.big then u64(c, p) else u16(c, p)
if n == 0 or p + hsize + n * esize > c.limit then
return nil, 0, Err.new(if n == 0 then Err.CORRUPT else Err.TRUNCATED, "bad IFD entry count " .. n, p)
end
local entries: { [number]: Entry } = {}
for i = 0, n - 1 do
local q = p + hsize + i * esize
local tag, typ = u16(c, q), u16(c, q + 2)
local count = if c.big then u64(c, q + 4) else u32(c, q + 4)
local vat = q + (if c.big then 12 else 8)
local size = TYPE_SIZE[typ]
if size then
local at = vat
if count * size > (if c.big then 8 else 4) then
at = c.base + off(c, vat)
end
entries[tag] = { tag = tag, typ = typ, count = count, at = at }
end
end
local nq = p + hsize + n * esize
local nextOff = 0
if nq + (if c.big then 8 else 4) <= c.limit then
nextOff = off(c, nq)
end
return entries, if nextOff > 0 then c.base + nextOff else 0, nil
end
local function bytesOf(c: Ctx, e: Entry?, max: number): buffer?
if not e or e.at < c.base then
return nil
end
local size = TYPE_SIZE[e.typ] or 1
local n = e.count * size
if n > max or e.at + n > c.limit then
return nil
end
local x = buffer.create(n)
buffer.copy(x, 0, c.b, e.at, n)
return x
end
-- decompress one chunk at [p, p + len) into out[o, o + size): bytes produced | nil, Err
local function inflateChunk(c: Ctx, comp: number, p: number, len: number, out: buffer, o: number, size: number, rev: boolean): (number?, Err.Err?)
if p < c.base or len < 0 or p + len > c.limit then
-- a chunk past the end: keep what exists (truncated files)
len = math.max(0, math.min(len, c.limit - p))
if p < c.base or p >= c.limit then
return 0, nil
end
end
local src, sp = c.b, p
if rev then
src = buffer.create(len)
buffer.copy(src, 0, c.b, p, len)
Pixels.reverseBits(src, 0, len)
sp = 0
end
if comp == 1 then
local n = math.min(len, size)
buffer.copy(out, o, src, sp, n)
return n, nil
elseif comp == 5 then
local n = Lzw.decode(src, sp, len, out, o, size, "tiff")
return n, nil
elseif comp == 8 or comp == 32946 then
local raw = Deflate.zlib(src, sp, len, size)
if not raw then
raw = Deflate.zlib(src, sp, len) or Deflate.inflate(src, sp, len)
end
if not raw then
return nil, Err.new(Err.CORRUPT, "bad deflate data", p)
end
local n = math.min(buffer.len(raw :: buffer), size)
buffer.copy(out, o, raw :: buffer, 0, n)
return n, nil
elseif comp == 32773 then
return (PackBits.decode(src, sp, sp + len, out, o, size)), nil
end
return nil, Err.new(Err.UNSUPPORTED, "compression " .. comp)
end
type Page = { image: Types.Image, info: { [string]: any } }
local function decodePage(c: Ctx, t: { [number]: Entry }, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local w, h = one(c, t[256], 0), one(c, t[257], 0)
if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then
return nil, Err.new(Err.CORRUPT, "bad image size")
end
local maxPixels = opts and opts.maxPixels or 2 ^ 26
if w * h > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
end
local spp = one(c, t[277], 1)
local bpsList = values(c, t[258], 64) or { 1 }
local bps = bpsList[1] or 1
for i = 2, math.min(#bpsList, spp) do
if bpsList[i] ~= bps then
return nil, Err.new(Err.UNSUPPORTED, "different bit depths per sample")
end
end
local comp = one(c, t[259], 1)
local photo = one(c, t[262], if spp >= 3 then 2 else 1)
local planar = one(c, t[284], 1)
local predictor = one(c, t[317], 1)
local sfmt = one(c, t[339], 1)
local fill = one(c, t[266], 1)
if spp < 1 or spp > 16 or bps < 1 or bps > 64 then
return nil, Err.new(Err.UNSUPPORTED, string.format("%d samples of %d bits", spp, bps))
end
if sfmt == 3 and bps ~= 16 and bps ~= 32 and bps ~= 64 then
return nil, Err.new(Err.UNSUPPORTED, bps .. "-bit floats")
end
if sfmt ~= 3 and bps > 32 then
return nil, Err.new(Err.UNSUPPORTED, bps .. "-bit integers")
end
if not COMPRESSION[comp] then
local names = { [2] = "CCITT RLE", [3] = "CCITT fax 3", [4] = "CCITT fax 4", [6] = "old-style JPEG", [34712] = "JPEG 2000", [34925] = "LZMA", [50000] = "Zstandard", [50001] = "WebP" }
return nil, Err.new(Err.UNSUPPORTED, (names[comp] or "compression") .. " (" .. comp .. ")")
end
if not PHOTOMETRIC[photo] then
return nil, Err.new(Err.UNSUPPORTED, "photometric interpretation " .. photo)
end
local cc = if photo == 2 or photo == 6 then 3 elseif photo == 5 then 4 else 1
if spp < cc then
return nil, Err.new(Err.CORRUPT, string.format("%d samples for photometric %d", spp, photo))
end
if photo == 5 and one(c, t[332], 1) ~= 1 then
return nil, Err.new(Err.UNSUPPORTED, "separated image that is not CMYK")
end
local extra = values(c, t[338], 16) or {}
local alpha, assoc = -1, false
if spp > cc then
local kind = extra[1] or 0
alpha = cc
assoc = kind == 1
end
local chunky = planar ~= 2 or spp == 1
local tiled = t[322] ~= nil
local cw = if tiled then one(c, t[322], 0) else w
local ch = if tiled then one(c, t[323], 0) else math.min(one(c, t[278], h), h)
if cw < 1 or ch < 1 or cw > 65536 or (tiled and ch > 65536) then
return nil, Err.new(Err.CORRUPT, "bad tile / strip size")
end
if ch > h and not tiled then
ch = h
end
local pspp = if chunky then spp else 1 -- samples per pixel in one plane
local nplanes = if chunky then 1 else spp
local rb = math.ceil(w * pspp * bps / 8) -- bytes per image row in a plane
local crb = math.ceil(cw * pspp * bps / 8) -- bytes per chunk row
if rb * h * nplanes > 2 ^ 30 or crb * ch > 2 ^ 30 then
return nil, Err.new(Err.LIMIT, "decoded data over 1 GB")
end
local across = if tiled then math.ceil(w / cw) else 1
local down = math.ceil(h / ch)
local perPlane = across * down
local offs = values(c, if tiled then t[324] else t[273], 2 ^ 24)
local lens = values(c, if tiled then t[325] else t[279], 2 ^ 24)
if not offs or #offs < perPlane * nplanes then
return nil, Err.new(Err.CORRUPT, "missing or short strip / tile offsets")
end
local planes: { buffer } = table.create(nplanes) :: { buffer }
for i = 1, nplanes do
planes[i] = buffer.create(rb * h + 8)
end
local tmp = buffer.create(crb * ch + 8)
local ftmp = buffer.create(math.max(rb, crb) + 8)
local le = c.le
local bytesPer = bps // 8
local hook = opts and opts.decodeImage
local jpegTables = if comp == 7 then bytesOf(c, t[347], 1 * 2 ^ 20) else nil
local jpegPixels: buffer? = nil
if comp == 7 then
if type(hook) ~= "function" then
return nil, Err.new(Err.UNSUPPORTED, "JPEG-compressed TIFF needs opts.decodeImage (F.load supplies it)")
end
jpegPixels = buffer.create(w * h * 4)
end
for pl = 0, nplanes - 1 do
for ty = 0, down - 1 do
for tx = 0, across - 1 do
local idx = pl * perPlane + ty * across + tx
local p = c.base + offs[idx + 1]
local len = if lens and lens[idx + 1] then lens[idx + 1] else c.limit - p
local rows = if tiled then ch else math.min(ch, h - ty * ch)
local size = rows * crb
if comp == 7 then
-- JPEGTables (SOI .. EOI) + the chunk (SOI .. EOI): one stream without the inner EOI / SOI
if p < c.base or p + len > c.limit or len < 4 then
return nil, Err.new(Err.TRUNCATED, "JPEG chunk past the end", p)
end
local tl = if jpegTables and buffer.len(jpegTables) >= 4 then buffer.len(jpegTables) - 2 else 0
local s = buffer.create(tl + len - (if tl > 0 then 2 else 0))
if tl > 0 then
buffer.copy(s, 0, jpegTables :: buffer, 0, tl)
buffer.copy(s, tl, c.b, p + 2, len - 2)
else
buffer.copy(s, 0, c.b, p, len)
end
local ok, img, herr = pcall(hook :: any, s)
if not ok or type(img) ~= "table" or img.format ~= "rgba8" then
return nil, if ok and herr then herr else Err.new(Err.CORRUPT, "embedded JPEG: " .. tostring(if ok then herr else img))
end
local x0, y0 = tx * cw, ty * ch
local cwid = math.min(cw, w - x0, img.width)
for yy = 0, math.min(rows, h - y0, img.height) - 1 do
buffer.copy(jpegPixels :: buffer, ((y0 + yy) * w + x0) * 4, img.pixels, yy * img.width * 4, cwid * 4)
end
continue
end
buffer.fill(tmp, 0, 0, size)
local _, derr = inflateChunk(c, comp, p, len, tmp, 0, size, fill == 2)
if derr then
return nil, derr
end
if predictor == 2 then
Pixels.unpredict2(tmp, 0, rows, crb, pspp, bps, le)
elseif predictor == 3 and bytesPer >= 2 and crb % bytesPer == 0 then
Pixels.unpredict3(tmp, 0, rows, crb, bytesPer, pspp, ftmp)
end
-- into the plane
local plane = planes[pl + 1]
local x0b = math.floor(tx * cw * pspp * bps / 8)
local cols = math.min(cw, w - tx * cw)
local nb = math.min(math.ceil(cols * pspp * bps / 8), rb - x0b)
for yy = 0, rows - 1 do
local y = ty * ch + yy
if y >= h then
break
end
buffer.copy(plane, y * rb + x0b, tmp, yy * crb, nb)
end
end
end
end
local floatOut = sfmt == 3
if predictor == 3 and floatOut then
le = true -- fpAcc leaves the samples little endian
end
local colorType = PHOTOMETRIC[photo]
-- the output layout
local kind = "rgba8"
if opts and opts.native and comp ~= 7 then
if photo == 3 or photo == 5 then
kind = "rgba8"
elseif floatOut then
kind = "rgbaf32"
elseif cc == 1 then
if alpha >= 0 then
kind = if bps <= 8 then "graya8" else "rgba16"
else
kind = if bps <= 8 then "gray8" else "gray16"
end
else
if alpha >= 0 then
kind = if bps <= 8 then "rgba8" else "rgba16"
else
kind = if bps <= 8 then "rgb8" else "rgba16"
end
end
end
local img = Types.Image.new(w, h, kind :: any)
if comp == 7 then
img.pixels = jpegPixels :: buffer
else
if photo == 6 then
return nil, Err.new(Err.UNSUPPORTED, "uncompressed YCbCr")
end
local cmap = nil
if photo == 3 then
local n = 3 * 2 ^ math.min(bps, 16)
local cv = values(c, t[320], n)
if not cv or #cv < n then
return nil, Err.new(Err.CORRUPT, "palette image without a full ColorMap")
end
cmap = buffer.create(n * 2)
for i = 1, n do
buffer.writeu16(cmap, (i - 1) * 2, math.clamp(cv[i], 0, 65535))
end
end
Pixels.convert({
planes = planes,
rb = rb,
chunky = chunky,
w = w,
h = h,
spp = spp,
bps = bps,
sfmt = sfmt,
le = le,
photo = photo,
alpha = alpha,
assoc = assoc,
cmap = cmap,
kind = kind,
out = img.pixels,
})
end
local xr, yr = one(c, t[282], 0), one(c, t[283], 0)
if xr > 0 and yr > 0 then
local unit = one(c, t[296], 2)
local k = if unit == 3 then 2.54 else 1
if unit ~= 1 then
img.meta.dpi = { x = xr * k, y = yr * k }
end
end
img.meta.icc = bytesOf(c, t[34675], 2 ^ 26)
local function ascii(tag: number): string?
local v = bytesOf(c, t[tag], 65536)
if not v then
return nil
end
local s = buffer.tostring(v)
local z = string.find(s, "\0", 1, true)
return if z then string.sub(s, 1, z - 1) else s
end
local text = {}
for tag, key in { [270] = "description", [305] = "software", [306] = "datetime", [315] = "artist", [33432] = "copyright" } do
local s = ascii(tag)
if s and s ~= "" then
text[key] = s
end
end
if next(text) then
img.meta.text = text
end
img.meta.source = {
format = "tiff",
bitDepth = bps,
colorType = colorType,
photometric = photo,
samples = spp,
sampleFormat = if sfmt == 3 then "float" elseif sfmt == 2 then "int" else "uint",
compression = COMPRESSION[comp],
predictor = predictor,
planar = planar,
tiled = tiled,
alpha = if alpha >= 0 then (if assoc then "associated" else "unassociated") else nil,
bigtiff = c.big,
byteOrder = if c.le then "II" else "MM",
}
return img, nil
end
-- pages(r) -> the IFD tables of every page (and the context) | nil, Err
local function pages(r: Bytes.Reader, maxPages: number): ({ { [number]: Entry } }?, Ctx?, Err.Err?)
local b, base, limit = r.buf, r.base, r.limit
if limit - base < 8 then
return nil, nil, Err.new(Err.TRUNCATED, "short header")
end
local bo = buffer.readstring(b, base, 2)
if bo ~= "II" and bo ~= "MM" then
return nil, nil, Err.new(Err.CORRUPT, "bad byte order mark")
end
local c: Ctx = { b = b, base = base, limit = limit, le = bo == "II", big = false }
local magic = u16(c, base + 2)
local first
if magic == 42 then
first = u32(c, base + 4)
elseif magic == 43 then
if limit - base < 16 or u16(c, base + 4) ~= 8 then
return nil, nil, Err.new(Err.CORRUPT, "bad BigTIFF header")
end
c.big = true
first = u64(c, base + 8)
else
return nil, nil, Err.new(Err.CORRUPT, "bad magic " .. magic)
end
local list = {}
local seen = {}
local p = base + first
while p > 0 and #list < maxPages do
if seen[p] then
break -- an IFD loop
end
seen[p] = true
local t, nextP, err = readIfd(c, p)
if not t then
if #list == 0 then
return nil, nil, err
end
break
end
table.insert(list, t)
p = nextP
end
return list, c, nil
end
-- info(r) -> { pages, width, height, bitDepth, samples, compression } of page 1 | nil, Err
function Tiff.info(r: Bytes.Reader): ({ [string]: any }?, Err.Err?)
local list, c, err = pages(r, 1024)
if not list or not c then
return nil, err
end
local t = list[1]
return {
pages = #list,
width = one(c, t[256], 0),
height = one(c, t[257], 0),
bitDepth = one(c, t[258], 1),
samples = one(c, t[277], 1),
compression = COMPRESSION[one(c, t[259], 1)] or tostring(one(c, t[259], 1)),
photometric = PHOTOMETRIC[one(c, t[262], 1)],
bigtiff = c.big,
},
nil
end
function Tiff.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local maxPages = opts and opts.maxPages or 1024
local list, c, err = pages(r, if opts and opts.page then math.max(1, opts.page) else maxPages)
if not list or not c then
return nil, err
end
if opts and opts.page then
local t = list[opts.page]
if not t then
return nil, Err.new(Err.ARG, "no page " .. tostring(opts.page))
end
local img, perr = decodePage(c, t, opts)
if img then
(img.meta.source :: { [string]: any }).pages = #list
end
return img, perr
end
local first: Types.Image? = nil
local frames = {}
for i, t in list do
-- reduced-resolution subfiles (thumbnails) after page 1 are skipped
local sub = one(c, t[254], 0)
if i > 1 and bit32.band(sub, 1) ~= 0 then
continue
end
local img, perr = decodePage(c, t, opts)
if not img then
if i == 1 then
return nil, perr
end
continue
end
if not first then
first = img
end
table.insert(frames, { image = img, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" })
end
local img = first :: Types.Image
(img.meta.source :: { [string]: any }).pages = #frames
if #frames > 1 then
img.frames = frames :: any
end
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- layout per pixel format: samples, bits, sample format, photometric, extra samples
local LAYOUT = {
gray8 = { 1, 8, 1, 1 },
graya8 = { 2, 8, 1, 1 },
gray16 = { 1, 16, 1, 1 },
rgb8 = { 3, 8, 1, 2 },
rgba8 = { 4, 8, 1, 2 },
rgba16 = { 4, 16, 1, 2 },
rgbaf32 = { 4, 32, 3, 2 },
}
local COMP_CODES = { none = 1, deflate = 8, lzw = 5, packbits = 32773 }
type Tag = { tag: number, typ: number, vals: { number }?, data: buffer? }
local function encodePage(img: Types.Image, o: EncodeOptions, comp: number): ({ Tag }?, { buffer }?, Err.Err?)
local L = LAYOUT[img.format]
if not L then
return nil, nil, Err.new(Err.ARG, "unsupported pixel format " .. tostring(img.format))
end
local w, h = img.width, img.height
local spp, bps, sfmt, photo = L[1], L[2], L[3], L[4]
local rb = w * spp * bps // 8
if type(w) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or w > 2 ^ 31 or buffer.len(img.pixels) < rb * h then
return nil, nil, Err.new(Err.ARG, "bad image size or pixel buffer")
end
local rps = o.rowsPerStrip or math.max(1, 65536 // rb)
if type(rps) ~= "number" or rps < 1 then
return nil, nil, Err.new(Err.ARG, "rowsPerStrip must be >= 1")
end
rps = math.min(math.floor(rps), h)
local predictor = 1
if (comp == 8 or comp == 5) and o.predictor ~= false then
predictor = if sfmt == 3 then 3 else 2
end
local strips = {}
local tmp = buffer.create(rb + 8)
for y0 = 0, h - 1, rps do
local rows = math.min(rps, h - y0)
local raw = buffer.create(rows * rb)
buffer.copy(raw, 0, img.pixels, y0 * rb, rows * rb)
if predictor == 2 then
Pixels.predict2(raw, 0, rows, rb, spp, bps)
elseif predictor == 3 then
Pixels.predict3(raw, 0, rows, rb, 4, spp, tmp)
end
local out
if comp == 1 then
out = raw
elseif comp == 8 then
out = Deflate.zlibCompress(raw, { level = o.level or 6 }) :: buffer
elseif comp == 5 then
out = Lzw.encode(raw, 0, rows * rb, "tiff")
else
local parts, total = {}, 0
for r = 0, rows - 1 do
local p = PackBits.encode(raw, r * rb, rb)
table.insert(parts, p)
total += buffer.len(p)
end
out = buffer.create(total)
local q = 0
for _, p in parts do
buffer.copy(out, q, p)
q += buffer.len(p)
end
end
table.insert(strips, out)
end
local bpsv = table.create(spp, bps)
local tags: { Tag } = {
{ tag = 254, typ = 4, vals = { 0 } },
{ tag = 256, typ = 4, vals = { w } },
{ tag = 257, typ = 4, vals = { h } },
{ tag = 258, typ = 3, vals = bpsv },
{ tag = 259, typ = 3, vals = { comp } },
{ tag = 262, typ = 3, vals = { photo } },
{ tag = 273, typ = 4, vals = table.create(#strips, 0) }, -- patched
{ tag = 277, typ = 3, vals = { spp } },
{ tag = 278, typ = 4, vals = { rps } },
{ tag = 279, typ = 4, vals = table.create(#strips, 0) },
{ tag = 284, typ = 3, vals = { 1 } },
}
for i, s in strips do
(tags[10].vals :: { number })[i] = buffer.len(s)
end
local dpi = img.meta and img.meta.dpi
if type(dpi) == "table" and type(dpi.x) == "number" and type(dpi.y) == "number" and dpi.x > 0 and dpi.y > 0 then
table.insert(tags, { tag = 282, typ = 5, vals = { dpi.x } })
table.insert(tags, { tag = 283, typ = 5, vals = { dpi.y } })
table.insert(tags, { tag = 296, typ = 3, vals = { 2 } })
end
if predictor > 1 then
table.insert(tags, { tag = 317, typ = 3, vals = { predictor } })
end
if spp == 2 or spp == 4 then
table.insert(tags, { tag = 338, typ = 3, vals = { 2 } })
end
if sfmt ~= 1 then
table.insert(tags, { tag = 339, typ = 3, vals = table.create(spp, sfmt) })
end
local icc = img.meta and img.meta.icc
if type(icc) == "buffer" then
table.insert(tags, { tag = 34675, typ = 7, data = icc })
end
local text = img.meta and img.meta.text
if type(text) == "table" then
for key, tag in { description = 270, software = 305, datetime = 306, artist = 315, copyright = 33432 } :: { [string]: number } do
if type(text[key]) == "string" then
table.insert(tags, { tag = tag, typ = 2, data = buffer.fromstring(text[key] .. "\0") })
end
end
end
table.sort(tags, function(a: Tag, b: Tag): boolean
return a.tag < b.tag
end)
return tags, strips, nil
end
function Tiff.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(img) ~= "table" or type(img.pixels) ~= "buffer" then
return nil, Err.new(Err.ARG, "needs an Image")
end
local o: EncodeOptions = opts or {}
local comp = COMP_CODES[o.compression or "deflate"]
if not comp then
return nil, Err.new(Err.ARG, "compression must be none, deflate, lzw or packbits")
end
local list = { img }
if type(img.frames) == "table" and #img.frames > 1 then
list = {}
for _, f in img.frames :: any do
if type(f) ~= "table" or type(f.image) ~= "table" then
return nil, Err.new(Err.ARG, "bad frame")
end
table.insert(list, f.image)
end
end
local w = Bytes.writer(1024)
w:string("II")
w:u16le(42)
w:u32le(0) -- first IFD, patched
local prevNext = 4
for _, page in list do
local tags, strips, err = encodePage(page, o, comp)
if not tags or not strips then
return nil, err
end
-- strip data first
local soffs = {}
for i, s in strips do
if w:tell() % 2 == 1 then
w:u8(0)
end
soffs[i] = w:tell()
w:bytes(s)
end
for _, tg in tags do
if tg.tag == 273 then
tg.vals = soffs
end
end
-- out-of-line values
local valOff: { [number]: number } = {}
for i, tg in tags do
local size = TYPE_SIZE[tg.typ]
local n = if tg.data then buffer.len(tg.data :: buffer) else #(tg.vals :: { number }) * size
if n > 4 then
if w:tell() % 2 == 1 then
w:u8(0)
end
valOff[i] = w:tell()
if tg.data then
w:bytes(tg.data :: buffer)
else
for _, v in tg.vals :: { number } do
if tg.typ == 3 then
w:u16le(v)
elseif tg.typ == 4 then
w:u32le(v)
elseif tg.typ == 5 then
w:u32le(math.floor(v * 10000 + 0.5))
w:u32le(10000)
end
end
end
end
end
if w:tell() % 2 == 1 then
w:u8(0)
end
local ifd = w:tell()
w:setU32le(prevNext, ifd)
w:u16le(#tags)
for i, tg in tags do
local count = if tg.data then buffer.len(tg.data :: buffer) else #(tg.vals :: { number })
w:u16le(tg.tag)
w:u16le(tg.typ)
w:u32le(count)
if valOff[i] then
w:u32le(valOff[i])
else
local start = w:tell()
if tg.data then
w:bytes(tg.data :: buffer)
else
for _, v in tg.vals :: { number } do
if tg.typ == 3 then
w:u16le(v)
else
w:u32le(v)
end
end
end
w:fill(0, 4 - (w:tell() - start))
end
end
prevNext = w:tell()
w:u32le(0)
end
return w:finish(), nil
end
return Tiff
+247
View File
@@ -0,0 +1,247 @@
--!strict
-- image/tim: PlayStation TIM images (magic 0x10), read and write. Written from the PSX "File Formats" documentation
-- (Sony, TIM: pmode, CLUT and image blocks with their VRAM positions); no code taken.
-- Decode: 4-bit and 8-bit CLUT images (opts.clut picks the palette row, default 0), 15-bit direct and 24-bit
-- direct, to rgba8: PSX colours are 1-5-5-5 STP-B-G-R, channels expanded as (v << 3) | (v >> 2); the colour 0x0000
-- is transparent (alpha 0) as on the hardware, others opaque (the STP bit is kept in meta.source.stp = true when
-- any pixel or CLUT entry has it). meta.source = { format, bpp, clut = { x, y, colours, count }?, x, y (VRAM) }.
-- Encode: rgba8 to 16-bit direct (default), 24-bit (opts.bpp = 24, alpha dropped) or 4 / 8-bit CLUT when the image
-- has at most 16 / 256 PSX colours (opts.bpp = 4 / 8; Err.ARG otherwise); alpha below 128 becomes 0x0000; opaque
-- black is written as 0x8000 (STP set) so it stays opaque. Not supported: mixed mode (pmode 4) images.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
-- ------------------------------------------------------------------------------------------------ contract
local Tim = {
name = "tim",
category = "image",
extensions = { "tim" },
mime = { "image/x-tim" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 4, 8, 16, 24 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
clut: number?, -- the CLUT row to use for indexed images (0-based, default 0)
maxPixels: number?, -- default 2^26
}
export type EncodeOptions = {
bpp: number?, -- 4, 8, 16 (default) or 24
x: number?, -- VRAM position of the image (default 0, 0)
y: number?,
clutX: number?, -- VRAM position of the CLUT (default 0, 480)
clutY: number?,
}
-- ------------------------------------------------------------------------------------------------ constants
local readu8, readu16, writeu32, writeu16, readu32 = buffer.readu8, buffer.readu16, buffer.writeu32, buffer.writeu16, buffer.readu32
local BPP = { [0] = 4, [1] = 8, [2] = 16, [3] = 24 }
-- ------------------------------------------------------------------------------------------------ sniff
function Tim.sniff(r: Bytes.Reader): number
if r:remaining() < 20 or r:peek(4) ~= "\16\0\0\0" then
return 0
end
local flags = r:peekU8(4)
if flags > 0x0F or (flags % 8) > 3 or r:peek(3, 5) ~= "\0\0\0" then
return 0
end
return 0.8
end
-- ------------------------------------------------------------------------------------------------ decode
local function colour(c: number): number
if c == 0 then
return 0
end
local r, g, b = c % 32, (c // 32) % 32, (c // 1024) % 32
r, g, b = r * 8 + r // 4, g * 8 + g // 4, b * 8 + b // 4
return 0xFF000000 + b * 65536 + g * 256 + r
end
function Tim.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local magic, flags = r:u32le(), r:u32le()
if r.err then
return nil, r.err
end
if magic ~= 0x10 then
return nil, Err.new(Err.CORRUPT, "bad magic", 0)
end
local pmode = flags % 8
local bpp = BPP[pmode]
if not bpp then
return nil, Err.new(Err.UNSUPPORTED, "pmode " .. pmode .. " (mixed / unknown)", 4)
end
local stp = false
local pal: buffer? = nil
local clutInfo: any = nil
if bit32.band(flags, 8) ~= 0 then
local start = r:tell()
local bnum, cx, cy, cw, ch = r:u32le(), r:u16le(), r:u16le(), r:u16le(), r:u16le()
if r.err then
return nil, r.err
end
if bnum < 12 or cw * ch * 2 > bnum - 12 then
return nil, Err.new(Err.CORRUPT, "bad CLUT block", start)
end
if not r:need(cw * ch * 2) then
return nil, r.err
end
local row = math.clamp(math.floor(opts and opts.clut or 0), 0, math.max(ch - 1, 0))
pal = buffer.create(256 * 4)
local p = r.pos + row * cw * 2
for i = 0, math.min(cw, 256) - 1 do
local c = readu16(r.buf, p + i * 2)
if c >= 0x8000 then
stp = true
end
writeu32(pal :: buffer, i * 4, if c == 0x8000 then 0xFF000000 else colour(c % 0x8000))
end
clutInfo = { x = cx, y = cy, colours = cw, count = ch, row = row }
r:seek(start + bnum)
if r.err then
return nil, r.err
end
elseif bpp <= 8 then
return nil, Err.new(Err.CORRUPT, "indexed image without a CLUT", 4)
end
local start = r:tell()
local bnum, ix, iy, iw, ih = r:u32le(), r:u16le(), r:u16le(), r:u16le(), r:u16le()
if r.err then
return nil, r.err
end
local w = if bpp == 4 then iw * 4 elseif bpp == 8 then iw * 2 elseif bpp == 16 then iw else (iw * 2) // 3
local stride = iw * 2
if w * ih > (opts and opts.maxPixels or 2 ^ 26) then
return nil, Err.new(Err.LIMIT, "image too big")
end
if bnum < 12 or stride * ih > bnum - 12 then
return nil, Err.new(Err.CORRUPT, "bad image block", start)
end
if not r:need(stride * ih) then
return nil, r.err
end
local img = Types.Image.new(w, ih)
local px, src, at = img.pixels, r.buf, r.pos
for y = 0, ih - 1 do
local row = at + y * stride
local d = y * w * 4
if bpp == 4 then
for x = 0, w - 1 do
local v = readu8(src, row + x // 2)
local i = if x % 2 == 0 then v % 16 else v // 16
writeu32(px, d + x * 4, readu32(pal :: buffer, i * 4))
end
elseif bpp == 8 then
for x = 0, w - 1 do
writeu32(px, d + x * 4, readu32(pal :: buffer, readu8(src, row + x) * 4))
end
elseif bpp == 16 then
for x = 0, w - 1 do
local c = readu16(src, row + x * 2)
if c >= 0x8000 then
stp = true
end
writeu32(px, d + x * 4, if c == 0x8000 then 0xFF000000 else colour(c % 0x8000))
end
else
for x = 0, w - 1 do
local o = row + x * 3
writeu32(px, d + x * 4, 0xFF000000 + readu8(src, o + 2) * 65536 + readu8(src, o + 1) * 256 + readu8(src, o))
end
end
end
img.meta.source = { format = "tim", bpp = bpp, x = ix, y = iy, clut = clutInfo, stp = stp or nil }
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- rgba8 pixel -> PSX colour
local function psx(v: number): number
local r, g, b, a = v % 256, (v // 256) % 256, (v // 65536) % 256, v // 16777216
if a < 128 then
return 0
end
local c = (b // 8) * 1024 + (g // 8) * 32 + r // 8
return if c == 0 then 0x8000 else c
end
function Tim.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, "expected an rgba8 Image")
end
local w, h = img.width, img.height
local bpp = opts and opts.bpp or 16
local per = ({ [4] = 4, [8] = 2, [16] = 1, [24] = 2 / 3 } :: { [number]: number })[bpp]
if not per then
return nil, Err.new(Err.ARG, "bpp must be 4, 8, 16 or 24")
end
local iw = if bpp == 24 then (w * 3 + 1) // 2 else math.ceil(w / per)
if iw > 0xFFFF or h > 0xFFFF then
return nil, Err.new(Err.ARG, "image too wide for TIM")
end
local px = img.pixels
local out = Bytes.writer(64 + iw * 2 * h)
out:u32le(0x10)
local colours: { number } = {}
local index: { [number]: number } = {}
if bpp <= 8 then
for i = 0, w * h - 1 do
local c = psx(readu32(px, i * 4))
if not index[c] then
table.insert(colours, c)
index[c] = #colours - 1
if #colours > (if bpp == 4 then 16 else 256) then
return nil, Err.new(Err.ARG, "more than " .. (if bpp == 4 then 16 else 256) .. " colours for a " .. bpp .. "-bit TIM")
end
end
end
local n = if bpp == 4 then 16 else 256
out:u32le(8 + (if bpp == 4 then 0 else 1))
out:u32le(12 + n * 2)
out:u16le(opts and opts.clutX or 0)
out:u16le(opts and opts.clutY or 480)
out:u16le(n)
out:u16le(1)
for i = 1, n do
out:u16le(colours[i] or 0)
end
else
out:u32le(if bpp == 16 then 2 else 3)
end
out:u32le(12 + iw * 2 * h)
out:u16le(opts and opts.x or 0)
out:u16le(opts and opts.y or 0)
out:u16le(iw)
out:u16le(h)
local at = out:reserve(iw * 2 * h)
local b = out.buf
buffer.fill(b, at, 0, iw * 2 * h)
for y = 0, h - 1 do
local row = at + y * iw * 2
for x = 0, w - 1 do
local v = readu32(px, (y * w + x) * 4)
if bpp == 4 then
local i = index[psx(v)]
local o = row + x // 2
buffer.writeu8(b, o, buffer.readu8(b, o) + (if x % 2 == 0 then i else i * 16))
elseif bpp == 8 then
buffer.writeu8(b, row + x, index[psx(v)])
elseif bpp == 16 then
writeu16(b, row + x * 2, psx(v))
else
buffer.writeu8(b, row + x * 3, v % 256)
buffer.writeu8(b, row + x * 3 + 1, (v // 256) % 256)
buffer.writeu8(b, row + x * 3 + 2, (v // 65536) % 256)
end
end
end
out.pos = at + iw * 2 * h
return out:finish(), nil
end
return Tim
+245
View File
@@ -0,0 +1,245 @@
--!strict
-- image/vtf: Valve Texture Format (VTF 7.0 - 7.5: Source engine textures), read. Written from the Valve Developer
-- Community "VTF (Valve Texture Format)" page; no code taken.
-- Decode: the high-resolution image (located by the 7.3+ resource directory or after the low-resolution thumbnail
-- for 7.0 - 7.2), mip 0 of slice 0 and face 0 (opts.mip / opts.face / opts.slice pick others), frame 1 as the Image
-- and every frame of an animated texture in img.frames (opts.frames ~= false; delay opts.delay, default 0.1 s), to
-- rgba8. Texel formats: RGBA8888, ABGR8888, RGB888, BGR888, RGB565, I8, IA88, A8, RGB888 / BGR888 bluescreen (pure
-- blue transparent), ARGB8888, BGRA8888, BGRX8888, BGR565, BGRX5551, BGRA5551, BGRA4444, UV88, UVWQ8888, UVLX8888,
-- RGBA16161616 (integers) / RGBA16161616F (halves, clamped), R32F, RGB323232F, RGBA32323232F (all through
-- codecs/image/Texel), DXT1 (+ one-bit alpha),
-- DXT3, DXT5, ATI1N, ATI2N (ids 35 / 34 since Alien Swarm, 38 / 37 in Source 2013) through codecs/image/Bcn. meta.source = { format, version, flags, frames, faces, depth, mips,
-- texel, reflectivity, bumpScale }.
-- Not supported: P8 (never implemented by Valve), the newer Strata / Source 2 formats, writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Bcn = require("@rosetta/codecs/image/Bcn")
local Texel = require("@rosetta/codecs/image/Texel")
-- ------------------------------------------------------------------------------------------------ contract
local Vtf = {
name = "vtf",
category = "image",
extensions = { "vtf" },
mime = { "image/x-vtf" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Bcn", "codecs/image/Texel" },
caps = { decode = true, encode = false, alpha = true, animation = true, versions = { "7.0", "7.1", "7.2", "7.3", "7.4", "7.5" } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
mip: number?, -- mip level (0 = full size, default)
face: number?, -- cube map face (0-based, default 0)
slice: number?, -- volume slice (0-based, default 0)
frames: boolean?, -- decode every frame into img.frames (default true)
delay: number?, -- frame delay in seconds (default 0.1)
maxPixels: number?, -- default 2^26
}
-- ------------------------------------------------------------------------------------------------ constants
local M = Texel.masked
-- format id -> a codecs/image/Texel format (name or bit-mask descriptor) | { texel, bluescreen = true } | a BCn kind
local FORMATS: { [number]: any } = {
[0] = "rgba8", -- RGBA8888
[1] = M(4, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF), -- ABGR8888
[2] = "rgb8", -- RGB888
[3] = "bgr8", -- BGR888
[4] = "r5g6b5", -- RGB565: red in the low bits (as VTFLib / srctools read it)
[5] = "l8", -- I8
[6] = "la8", -- IA88
[8] = "a8", -- A8
[9] = { texel = "rgb8", bluescreen = true }, -- RGB888_BLUESCREEN
[10] = { texel = "bgr8", bluescreen = true }, -- BGR888_BLUESCREEN
[11] = M(4, 0xFF000000, 0x000000FF, 0x0000FF00, 0x00FF0000), -- ARGB8888: VTFLib's layout (G, B, A, R in memory)
[12] = "bgra8", -- BGRA8888
[13] = "bc1", -- DXT1
[14] = "bc2", -- DXT3
[15] = "bc3", -- DXT5
[16] = "bgrx8", -- BGRX8888
[17] = "b5g6r5", -- BGR565: blue in the low bits
[18] = "b5g5r5x1", -- BGRX5551
[19] = "b4g4r4a4", -- BGRA4444
[20] = "bc1a", -- DXT1_ONEBITALPHA
[21] = "b5g5r5a1", -- BGRA5551
[22] = "rg8", -- UV88
[23] = "rgba8", -- UVWQ8888
[24] = "rgba16f", -- RGBA16161616F
[25] = "rgba16", -- RGBA16161616
[26] = "rgba8", -- UVLX8888
[27] = "r32f", -- R32F
[28] = "rgb32f", -- RGB323232F
[29] = "rgba32f", -- RGBA32323232F
[34] = "bc5", -- ATI2N (Alien Swarm and later)
[35] = "bc4", -- ATI1N (Alien Swarm and later)
[37] = "bc5", -- ATI2N (Source 2013)
[38] = "bc4", -- ATI1N (Source 2013)
}
local BCN: { [string]: boolean } = { bc1 = true, bc1a = true, bc2 = true, bc3 = true, bc4 = true, bc5 = true }
local NAMES: { [number]: string } = { [0] = "RGBA8888", "ABGR8888", "RGB888", "BGR888", "RGB565", "I8", "IA88", "P8", "A8", "RGB888_BLUESCREEN",
"BGR888_BLUESCREEN", "ARGB8888", "BGRA8888", "DXT1", "DXT3", "DXT5", "BGRX8888", "BGR565", "BGRX5551", "BGRA4444",
"DXT1_ONEBITALPHA", "BGRA5551", "UV88", "UVWQ8888", "RGBA16161616F", "RGBA16161616", "UVLX8888", "R32F", "RGB323232F",
"RGBA32323232F", "NV_DST16", "NV_DST24", "NV_INTZ", "NV_RAWZ", "ATI2N", "ATI1N", "NV_NULL", "ATI2N", "ATI1N" }
local ENVMAP = 0x4000
-- ------------------------------------------------------------------------------------------------ sniff
function Vtf.sniff(r: Bytes.Reader): number
return if r:peek(4) == "VTF\0" and r:peekU8(4) == 7 then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- bytes of one w x h image in format f
local function imageSize(f: any, w: number, h: number): number
if type(f) == "string" and BCN[f] then
return Bcn.size(if f == "bc1a" then "bc1" else f, w, h) or 0
end
return Texel.size(if type(f) == "table" and f.texel then f.texel else f, w, h) or 0
end
function Vtf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local size = r.limit - r.base
local b, base = r.buf, r.base
if size < 64 then
return nil, Err.new(Err.TRUNCATED, "header", 0)
end
if buffer.readstring(b, base, 4) ~= "VTF\0" then
return nil, Err.new(Err.CORRUPT, "bad magic", 0)
end
local major, minor = buffer.readu32(b, base + 4), buffer.readu32(b, base + 8)
if major ~= 7 or minor > 5 then
return nil, Err.new(Err.UNSUPPORTED, "VTF version " .. major .. "." .. minor, 4)
end
local headerSize = buffer.readu32(b, base + 12)
local w, h = buffer.readu16(b, base + 16), buffer.readu16(b, base + 18)
local flags = buffer.readu32(b, base + 20)
local frames, firstFrame = buffer.readu16(b, base + 24), buffer.readu16(b, base + 26)
local refl = { buffer.readf32(b, base + 32), buffer.readf32(b, base + 36), buffer.readf32(b, base + 40) }
local bump = buffer.readf32(b, base + 48)
local fmtId = buffer.readi32(b, base + 52)
local mips = buffer.readu8(b, base + 56)
local lowFmt = buffer.readi32(b, base + 57)
local lowW, lowH = buffer.readu8(b, base + 61), buffer.readu8(b, base + 62)
local depth = if minor >= 2 and size >= 65 then math.max(1, buffer.readu16(b, base + 63)) else 1
if w == 0 or h == 0 then
return nil, Err.new(Err.CORRUPT, "zero size", 16)
end
if w * h > (opts and opts.maxPixels or 2 ^ 26) then
return nil, Err.new(Err.LIMIT, "image too big")
end
local f: any = FORMATS[fmtId]
if not f then
return nil, Err.new(Err.UNSUPPORTED, "texel format " .. (NAMES[fmtId] or tostring(fmtId)), 52)
end
frames = math.max(1, frames)
mips = math.max(1, mips)
local faces = 1
if bit32.band(flags, ENVMAP) ~= 0 then
faces = if minor < 5 and firstFrame ~= 0xFFFF then 7 else 6
end
-- where the high-resolution data starts
local dataAt: number? = nil
if minor >= 3 then
if size < 80 then
return nil, Err.new(Err.TRUNCATED, "resource directory", 68)
end
local nres = buffer.readu32(b, base + 68)
if nres > 32 or 80 + nres * 8 > size then
return nil, Err.new(Err.CORRUPT, "bad resource count", 68)
end
for i = 0, nres - 1 do
local o = base + 80 + i * 8
if buffer.readu8(b, o) == 0x30 and buffer.readu8(b, o + 1) == 0 and buffer.readu8(b, o + 2) == 0 then
dataAt = buffer.readu32(b, o + 4)
end
end
if not dataAt then
return nil, Err.new(Err.CORRUPT, "no high-resolution image resource", 80)
end
else
local lf = FORMATS[lowFmt]
local lowSize = if lowFmt >= 0 and lowW > 0 and lowH > 0 and lf then imageSize(lf, lowW, lowH) else 0
dataAt = headerSize + lowSize
end
-- the chain: mips smallest first; per mip: frames, faces, slices
local mip = math.clamp(math.floor(opts and opts.mip or 0), 0, mips - 1)
local face = math.clamp(math.floor(opts and opts.face or 0), 0, faces - 1)
local slice = math.clamp(math.floor(opts and opts.slice or 0), 0, depth - 1)
local off = dataAt :: number
for m = mips - 1, mip + 1, -1 do
local mw, mh, md = math.max(1, w // 2 ^ m), math.max(1, h // 2 ^ m), math.max(1, depth // 2 ^ m)
off += imageSize(f, mw, mh) * md * faces * frames
end
local mw, mh, md = math.max(1, w // 2 ^ mip), math.max(1, h // 2 ^ mip), math.max(1, depth // 2 ^ mip)
local one = imageSize(f, mw, mh)
local function image(frame: number): (Types.Image?, Err.Err?)
local at = off + ((frame * faces + face) * md + math.min(slice, md - 1)) * one
if at + one > size or at < 0 then
return nil, Err.new(Err.TRUNCATED, "image data past the end", at)
end
local img = Types.Image.new(mw, mh)
if type(f) == "string" and BCN[f] then
local kind = if f == "bc1a" then "bc1" else f
local px, e = Bcn.decode(kind, b, base + at, mw, mh)
if not px then
return nil, Err.from(e)
end
buffer.copy(img.pixels, 0, px, 0, mw * mh * 4)
if f == "bc1" then
-- plain DXT1 carries no alpha: the transparent colour of 3-colour blocks reads as opaque black
for i = 0, mw * mh - 1 do
buffer.writeu8(img.pixels, i * 4 + 3, 255)
end
end
else
local blue = type(f) == "table" and f.bluescreen == true
local px, e = Texel.decode(if blue then f.texel else f, b, base + at, mw, mh)
if not px then
return nil, Err.from(e)
end
buffer.copy(img.pixels, 0, px, 0, mw * mh * 4)
if blue then
-- pure blue is the transparent key
for i = 0, mw * mh - 1 do
if buffer.readu32(img.pixels, i * 4) == 0xFFFF0000 then
buffer.writeu32(img.pixels, i * 4, 0)
end
end
end
end
return img, nil
end
local img, err = image(0)
if not img then
return nil, err
end
if frames > 1 and not (opts and opts.frames == false) then
local delay = opts and opts.delay or 0.1
local list: { Types.Frame } = { { image = img, delay = delay, x = 0, y = 0, dispose = "none", blend = "source" } :: any }
for fr = 1, frames - 1 do
local fi, ferr = image(fr)
if not fi then
return nil, ferr
end
table.insert(list, { image = fi, delay = delay, x = 0, y = 0, dispose = "none", blend = "source" } :: any)
end
img.frames = list
img.loops = 0
end
img.meta.source = {
format = "vtf",
version = major .. "." .. minor,
flags = flags,
frames = frames,
faces = faces,
depth = depth,
mips = mips,
texel = NAMES[fmtId],
reflectivity = refl,
bumpScale = bump,
}
return img, nil
end
return Vtf
+76
View File
@@ -0,0 +1,76 @@
--!strict
--!native
-- image/webp/Alpha: the ALPH chunk (RFC 9649 section 2.7.1.2): header byte (compression, filter, pre-processing),
-- raw or VP8L-compressed alpha (the green channel of a headerless VP8L stream), and the horizontal / vertical /
-- gradient unfilters of libwebp src/dsp/filters.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt). Never throws.
local Vp8L = require("@rosetta/codecs/image/Vp8L")
local readu8, writeu8 = buffer.readu8, buffer.writeu8
local Alpha = {}
local function unfilter(a: buffer, w: number, h: number, filter: number)
if filter == 0 then
return
end
for y = 0, h - 1 do
local row = y * w
local prev = row - w
if y == 0 or filter == 1 then
-- horizontal (also the first row of the other filters): the left pixel, the first one from above
local pred = if y == 0 then 0 else readu8(a, prev)
for i = row, row + w - 1 do
pred = (pred + readu8(a, i)) % 256
writeu8(a, i, pred)
end
elseif filter == 2 then
for i = 0, w - 1 do
writeu8(a, row + i, (readu8(a, prev + i) + readu8(a, row + i)) % 256)
end
else
local top = readu8(a, prev)
local topLeft, left = top, top
for i = 0, w - 1 do
top = readu8(a, prev + i)
local g = left + top - topLeft
g = if g < 0 then 0 elseif g > 255 then 255 else g
left = (readu8(a, row + i) + g) % 256
topLeft = top
writeu8(a, row + i, left)
end
end
end
end
-- decode(buf, off, len, w, h) -> w * h alpha bytes, header info | nil, message
function Alpha.decode(buf: buffer, off: number, len: number, w: number, h: number): (buffer?, any)
if len <= 1 then
return nil, "truncated: ALPH chunk"
end
local hb = readu8(buf, off)
local method = hb % 4
local filter = (hb // 4) % 4
local pre = (hb // 16) % 4
if method > 1 or pre > 1 or hb >= 64 then
return nil, "bad ALPH header"
end
local a: buffer
if method == 0 then
if len - 1 < w * h then
return nil, "truncated: raw alpha"
end
a = buffer.create(w * h)
buffer.copy(a, 0, buf, off + 1, w * h)
else
local d, err = Vp8L.decodeAlpha(buf, off + 1, len - 1, w, h)
if not d then
local e = err :: any
return nil, if e.code == "TRUNCATED" then "truncated: alpha " .. e.message else "alpha: " .. e.message
end
a = d
end
unfilter(a, w, h, filter)
return a, { method = method, filter = filter, preprocessing = pre }
end
return Alpha
+162
View File
@@ -0,0 +1,162 @@
--!strict
--!native
-- image/webp/Anim: animation compositing. coalesce() reproduces libwebp's WebPAnimDecoder (src/demux/anim_decode.c,
-- BSD-3-Clause, licenses/libwebp-LICENSE.txt) exactly: key frame detection, transparent canvas (the background colour
-- is ignored, as the spec recommends and libwebp does), non-premultiplied "over" blending of the pixels with alpha
-- < 255, dispose to background. composite() is the generic Types.Frame model (also dispose "previous") used by the
-- encoder to flatten frames WebP cannot store as they are. Pixels are rgba8; never throws.
local band, rshift = bit32.band, bit32.rshift
local readu32, writeu32 = buffer.readu32, buffer.writeu32
local bcreate, bcopy, bfill = buffer.create, buffer.copy, buffer.fill
local Anim = {}
export type Frame = {
rgba: buffer, -- w * h rgba8
x: number,
y: number,
w: number,
h: number,
blend: boolean, -- alpha-blend over the canvas (false: overwrite)
disposeBg: boolean, -- after display, clear the rectangle to transparent
disposePrev: boolean?, -- after display, restore the canvas as it was before the frame (composite() only)
hasAlpha: boolean,
}
-- blend(src, dst) -> src over dst, both non-premultiplied 0xAABBGGRR (libwebp BlendPixelNonPremult)
local function blendPixel(src: number, dst: number): number
local sa = rshift(src, 24)
if sa == 0 then
return dst
end
local da = rshift(dst, 24)
local dfa = rshift(da * (256 - sa), 8)
local ba = sa + dfa
local scale = 16777216 // ba
local r = ((band(src, 255) * sa + band(dst, 255) * dfa) * scale) // 16777216
local g = ((band(rshift(src, 8), 255) * sa + band(rshift(dst, 8), 255) * dfa) * scale) // 16777216
local b = ((band(rshift(src, 16), 255) * sa + band(rshift(dst, 16), 255) * dfa) * scale) // 16777216
return r + g * 256 + b * 65536 + ba * 16777216
end
Anim.blendPixel = blendPixel
-- blendRow(cur, prev, offset, n): pixels of cur with alpha < 255 blended over prev (pixel offsets)
local function blendRow(cur: buffer, prev: buffer, o: number, n: number)
for i = o, o + n - 1 do
local s = readu32(cur, i * 4)
if s < 0xff000000 then
writeu32(cur, i * 4, blendPixel(s, readu32(prev, i * 4)))
end
end
end
-- draw(canvas, cw, f): copy the frame rectangle into the canvas
local function draw(canvas: buffer, cw: number, f: Frame)
for j = 0, f.h - 1 do
bcopy(canvas, ((f.y + j) * cw + f.x) * 4, f.rgba, j * f.w * 4, f.w * 4)
end
end
local function clearRect(canvas: buffer, cw: number, x: number, y: number, w: number, h: number)
for j = 0, h - 1 do
bfill(canvas, ((y + j) * cw + x) * 4, 0, w * 4)
end
end
-- coalesce(cw, ch, frames) -> one full canvas (rgba8) per frame, as WebPAnimDecoder returns them
function Anim.coalesce(cw: number, ch: number, frames: { Frame }): { buffer }
local size = cw * ch * 4
local out: { buffer } = {}
local disposed = bcreate(size)
local prev: Frame? = nil
local prevKey = false
for n, f in frames do
local full = f.w == cw and f.h == ch
local key
if n == 1 then
key = true
elseif (not f.hasAlpha or not f.blend) and full then
key = true
else
local p = prev :: Frame
key = p.disposeBg and ((p.w == cw and p.h == ch) or prevKey)
end
local cur = bcreate(size)
if not key then
bcopy(cur, 0, disposed, 0, size)
end
draw(cur, cw, f)
if n > 1 and f.blend and not key then
local p = prev :: Frame
if not p.disposeBg then
for j = 0, f.h - 1 do
blendRow(cur, disposed, (f.y + j) * cw + f.x, f.w)
end
else
-- the previous rectangle was cleared: blending with transparent there is a no-op for libwebp
local pmx, pmy = p.x + p.w, p.y + p.h
local smx = f.x + f.w
for j = 0, f.h - 1 do
local cy = f.y + j
if cy < p.y or cy >= pmy or f.x >= pmx or smx <= p.x then
blendRow(cur, disposed, cy * cw + f.x, f.w)
else
if f.x < p.x then
blendRow(cur, disposed, cy * cw + f.x, p.x - f.x)
end
if smx > pmx then
blendRow(cur, disposed, cy * cw + pmx, smx - pmx)
end
end
end
end
end
table.insert(out, cur)
prev = f
prevKey = key
bcopy(disposed, 0, cur, 0, size)
if f.disposeBg then
clearRect(disposed, cw, f.x, f.y, f.w, f.h)
end
end
return out
end
-- composite(cw, ch, frames) -> one full canvas per frame in the generic model: start transparent, draw (blend or
-- overwrite; "over" a fully transparent pixel copies it), show, then dispose (background: clear the rectangle;
-- previous: restore)
function Anim.composite(cw: number, ch: number, frames: { Frame }): { buffer }
local size = cw * ch * 4
local canvas = bcreate(size)
local out: { buffer } = {}
for _, f in frames do
local saved: buffer? = nil
if f.disposePrev then
saved = bcreate(size)
bcopy(saved :: buffer, 0, canvas, 0, size)
end
if f.blend then
for j = 0, f.h - 1 do
local co = (f.y + j) * cw + f.x
for i = 0, f.w - 1 do
local s = readu32(f.rgba, (j * f.w + i) * 4)
local d = readu32(canvas, (co + i) * 4)
writeu32(canvas, (co + i) * 4, if s >= 0xff000000 or d < 0x01000000 then s else blendPixel(s, d))
end
end
else
draw(canvas, cw, f)
end
local shown = bcreate(size)
bcopy(shown, 0, canvas, 0, size)
table.insert(out, shown)
if saved then
canvas = saved
elseif f.disposeBg then
clearRect(canvas, cw, f.x, f.y, f.w, f.h)
end
end
return out
end
return Anim
+627
View File
@@ -0,0 +1,627 @@
--!strict
-- image/webp: WebP (RFC 9649; Google's "WebP Container Specification"). New code: the bitstreams are ports of libwebp 1.6
-- (codecs/image/Vp8, codecs/image/Vp8L; BSD-3-Clause, licenses/libwebp-LICENSE.txt), the chunks go through containers/Riff, the
-- container rules and the compositing follow libwebp's demux / WebPAnimDecoder.
-- Supports: decode of lossy (VP8 key frames: bit-exact with dwebp, fancy or point chroma upsampling, or the raw
-- yuv420p planes with opts.native), lossless (VP8L, bit-exact), alpha (ALPH raw or lossless, every filter), the
-- extended format (VP8X), animation (ANIM / ANMF: frames as their own rectangles plus the composited first frame, or
-- every frame composited exactly as WebPAnimDecoder with opts.coalesce), ICC / EXIF / XMP into meta.icc / meta.exif
-- / meta.xmp; encode of rgba8 images and animations as lossless VP8L (VP8X / ANIM / ANMF for animations and
-- metadata).
-- Not supported: lossy encoding (UNSUPPORTED), the VP8 horizontal / vertical scale fields (ignored, as dwebp does),
-- alpha dithering / premultiplied output.
-- Speed (one Zen 5 core, 512 x 512, tools/bench.luau): lossy decode ~50 MB/s of rgba8 out (luau --codegen) / ~38 MB/s
-- (LuaJIT), lossless decode ~43 / ~73 MB/s, lossless encode ~6 / ~8 MB/s at effort 5 (~15 / ~18 MB/s at effort 1).
-- Encoded size: within ~4 % of cwebp -lossless on photos at effort 9, smaller on some synthetic images.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Vp8 = require("@rosetta/codecs/image/Vp8")
local Vp8L = require("@rosetta/codecs/image/Vp8L")
local Riff = require("@rosetta/containers/Riff")
local Alpha = require("@rosetta/image/webp/Alpha")
local Anim = require("@rosetta/image/webp/Anim")
-- ------------------------------------------------------------------------------------------------ contract
local Webp = {
name = "webp",
category = "image",
extensions = { "webp" },
mime = { "image/webp" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Vp8", "codecs/image/Vp8L", "containers/Riff" },
caps = { decode = true, encode = true, animation = true, alpha = true, lossy = true, lossless = true, depths = { 8 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxPixels: number?, -- refuse a canvas or frame larger than this (default 2^26)
native: boolean?, -- a still lossy image without alpha decodes to its yuv420p planes (default false: rgba8)
upsampling: ("fancy" | "nearest")?, -- lossy chroma upsampling, default "fancy" (libwebp's default; "nearest" =
-- dwebp -nofancy)
coalesce: boolean?, -- animations: every frame is the full composited canvas (x = y = 0, dispose "none",
-- blend "source"), exactly what WebPAnimDecoder returns (default false: each frame's own rectangle)
frames: boolean?, -- animations: decode every frame (default true; false: only the first canvas)
}
export type EncodeOptions = {
lossless: boolean?, -- must be true or nil (lossy encoding is not supported)
effort: number?, -- 0..9, default 5: VP8L encoder effort (more = smaller, slower)
exact: boolean?, -- keep the RGB of fully transparent pixels (default false: they may be changed)
loops: number?, -- animations: play count (default img.loops; 0 = forever)
background: { number }?, -- animations: ANIM background colour { r, g, b, a } (default meta.background or 0)
}
-- ------------------------------------------------------------------------------------------------ constants
local DEFAULT_MAX_PIXELS = 2 ^ 26
local FLAG_ANIM, FLAG_XMP, FLAG_EXIF, FLAG_ALPHA, FLAG_ICC = 0x02, 0x04, 0x08, 0x10, 0x20
local readu8 = buffer.readu8
local function u24(buf: buffer, p: number): number
return readu8(buf, p) + readu8(buf, p + 1) * 256 + readu8(buf, p + 2) * 65536
end
local function corrupt(msg: string, offset: number?): (nil, Err.Err)
return nil, Err.new(Err.CORRUPT, msg, offset)
end
-- an Err from a submodule message ("truncated: ...", "limit: ...", "unsupported: ...", else CORRUPT)
local function fromMessage(msg: any, offset: number?): Err.Err
if Err.is(msg) then
return msg
end
local m = tostring(msg)
for _, k in { { "truncated: ", Err.TRUNCATED }, { "limit: ", Err.LIMIT }, { "unsupported: ", Err.UNSUPPORTED } } do
if string.sub(m, 1, #k[1]) == k[1] then
return Err.new(k[2], string.sub(m, #k[1] + 1), offset)
end
end
return Err.new(Err.CORRUPT, m, offset)
end
-- ------------------------------------------------------------------------------------------------ sniff
function Webp.sniff(r: Bytes.Reader): number
if r:peek(4) == "RIFF" and r:peek(4, 8) == "WEBP" then
return 1
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
type Chunk = { id: string, off: number, size: number } -- off: absolute offset of the payload
local function convert(list: { Riff.Chunk }): ({ Chunk }?, Err.Err?)
local out: { Chunk } = {}
for _, c in list do
if c.truncated then
return nil, Err.new(Err.TRUNCATED, "chunk '" .. c.id .. "' runs past the end", c.offset)
end
table.insert(out, { id = c.id, off = c.offset, size = c.size })
end
return out, nil
end
-- readChunks(r) -> the chunks of a RIFF "WEBP" file, the containers/Riff File | nil, Err. As libwebp: the RIFF size
-- must fit the data (TRUNCATED) and bytes after it are ignored.
local function readChunks(r: Bytes.Reader): ({ Chunk }?, any)
local buf, base, limit = r.buf, r.base, r.limit
if limit - base < 12 then
return nil, Err.new(Err.TRUNCATED, "RIFF header", base)
end
if buffer.readstring(buf, base, 4) ~= "RIFF" or buffer.readstring(buf, base + 8, 4) ~= "WEBP" then
return nil, Err.new(Err.CORRUPT, "not a RIFF WEBP file", base)
end
local size = buffer.readu32(buf, base + 4)
if size < 12 then
return nil, Err.new(Err.CORRUPT, "RIFF size too small", base + 4)
end
if 8 + size > limit - base then
return nil, Err.new(Err.TRUNCATED, "the RIFF size runs past the end of the data", base + 4)
end
local f, err = Riff.read(Bytes.reader(buf, base, 8 + size))
if not f then
return nil, err
end
local list, cerr = convert(f.chunks)
if not list then
return nil, cerr
end
return list, f
end
-- subChunks(f, c) -> the chunks inside an ANMF payload (after its 16-byte header)
local function subChunks(f: Riff.File, c: Chunk): ({ Chunk }?, Err.Err?)
local n = c.size - 12
return convert(Riff.list(f, { id = c.id, start = c.off + 4, offset = c.off + 12, size = n, declared = n, avail = n, truncated = false, streamed = false }))
end
type Bitstream = { rgba: buffer?, yuv: Types.Image?, w: number, h: number, hasAlpha: boolean, source: { [string]: any } }
-- the image chunks of a still image or an ANMF frame: the first ALPH (if any) and the first VP8 / VP8L chunk
local function findImage(chunks: { Chunk }, from: number): (Chunk?, Chunk?)
local alph: Chunk? = nil
for i = from, #chunks do
local c = chunks[i]
if c.id == "ALPH" and not alph then
alph = c
elseif c.id == "VP8 " or c.id == "VP8L" then
return c, alph
elseif c.id == "ANMF" then
break
end
end
return nil, nil
end
local function decodeBitstream(buf: buffer, c: Chunk, alph: Chunk?, opts: DecodeOptions, allowNative: boolean): (Bitstream?, Err.Err?)
local maxPixels = opts.maxPixels or DEFAULT_MAX_PIXELS
if c.id == "VP8L" then
local rgba, w, h, alphaHint = Vp8L.decode(buf, c.off, c.size, maxPixels)
if not rgba then
return nil, w
end
return { rgba = rgba, w = w, h = h :: number, hasAlpha = alphaHint == true, source = { codec = "vp8l", lossless = true } }, nil
end
local y, u, v, w, h = Vp8.decodePlanes(buf, c.off, c.size, { maxPixels = maxPixels })
if not y then
return nil, u
end
local fw, fh = w :: number, h :: number
local source: { [string]: any } = { codec = "vp8", lossless = false }
if allowNative and opts.native and not alph then
local img = Types.Image.new(fw, fh, "yuv420p")
local ny, nc = fw * fh, buffer.len(v :: buffer)
buffer.copy(img.pixels, 0, y, 0, ny)
buffer.copy(img.pixels, ny, u, 0, nc)
buffer.copy(img.pixels, ny + nc, v :: buffer, 0, nc)
return { yuv = img, w = fw, h = fh, hasAlpha = false, source = source }, nil
end
local rgba = Vp8.yuvToRgba(y, u, v :: buffer, fw, fh, opts.upsampling ~= "nearest")
if alph then
local a, info = Alpha.decode(buf, alph.off, alph.size, fw, fh)
if not a then
return nil, fromMessage(info, alph.off)
end
Vp8.setAlpha(rgba, a, fw * fh)
source.alpha = info
end
return { rgba = rgba, w = fw, h = fh, hasAlpha = alph ~= nil, source = source }, nil
end
local function collectMeta(buf: buffer, chunks: { Chunk }, meta: Types.ImageMeta)
for _, c in chunks do
local key = if c.id == "ICCP" then "icc" elseif c.id == "EXIF" then "exif" elseif c.id == "XMP " then "xmp" else nil
if key and meta[key] == nil then
local b = buffer.create(c.size)
buffer.copy(b, 0, buf, c.off, c.size)
meta[key] = b
end
end
end
function Webp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local o: DecodeOptions = opts or {}
local maxPixels = o.maxPixels or DEFAULT_MAX_PIXELS
local buf = r.buf
local chunks, file = readChunks(r)
if not chunks then
return nil, file
end
local first = chunks[1]
if not first then
return corrupt("no chunks", r.base + 12)
end
if first.id == "VP8 " or first.id == "VP8L" then
local bs, err = decodeBitstream(buf, first, nil, o, true)
if not bs then
return nil, err
end
local img = bs.yuv or Types.Image.new(bs.w, bs.h, "rgba8")
if bs.rgba then
img.pixels = bs.rgba
end
bs.source.format = "webp"
bs.source.bitDepth = 8
bs.source.extended = false
img.meta.source = bs.source
return img, nil
end
if first.id ~= "VP8X" then
return corrupt("the first chunk is '" .. first.id .. "', not VP8, VP8L or VP8X", first.off - 8)
end
if first.size < 10 then
return nil, Err.new(Err.TRUNCATED, "VP8X chunk too small", first.off)
end
local flags = readu8(buf, first.off)
local cw = u24(buf, first.off + 4) + 1
local ch = u24(buf, first.off + 7) + 1
if cw * ch > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("%d x %d canvas is over the %d pixel limit", cw, ch, maxPixels))
end
local meta: Types.ImageMeta = {}
collectMeta(buf, chunks, meta)
if bit32.band(flags, FLAG_ANIM) == 0 then
local c, alph = findImage(chunks, 2)
if not c then
return corrupt("no VP8 / VP8L image chunk")
end
local bs, err = decodeBitstream(buf, c, if c.id == "VP8 " then alph else nil, o, true)
if not bs then
return nil, err
end
if bs.w ~= cw or bs.h ~= ch then
return corrupt(string.format("image %d x %d does not match the %d x %d canvas", bs.w, bs.h, cw, ch), c.off)
end
local img = bs.yuv or Types.Image.new(cw, ch, "rgba8")
if bs.rgba then
img.pixels = bs.rgba
end
for k, v in meta do
img.meta[k] = v
end
bs.source.format = "webp"
bs.source.bitDepth = 8
bs.source.extended = true
bs.source.flags = flags
img.meta.source = bs.source
return img, nil
end
-- animation: ANIM then ANMF frames
local bg, loops = 0, 0
local haveAnim = false
local frames: { Anim.Frame } = {}
local sources: { any } = {}
local delays: { number } = {}
local wantAll = o.frames ~= false
for i = 2, #chunks do
local c = chunks[i]
if c.id == "ANIM" then
if c.size < 6 then
return nil, Err.new(Err.TRUNCATED, "ANIM chunk too small", c.off)
end
bg = buffer.readu32(buf, c.off)
loops = buffer.readu16(buf, c.off + 4)
haveAnim = true
elseif c.id == "ANMF" then
if not haveAnim then
return corrupt("ANMF before ANIM", c.off)
end
if c.size < 16 then
return nil, Err.new(Err.TRUNCATED, "ANMF chunk too small", c.off)
end
local fx = u24(buf, c.off) * 2
local fy = u24(buf, c.off + 3) * 2
local fw = u24(buf, c.off + 6) + 1
local fh = u24(buf, c.off + 9) + 1
local dur = u24(buf, c.off + 12)
local fl = readu8(buf, c.off + 15)
if fx + fw > cw or fy + fh > ch then
return corrupt("frame " .. (#frames + 1) .. " lies outside the canvas", c.off)
end
local sub, serr = subChunks(file, c)
if not sub then
return nil, serr
end
local img, alph = findImage(sub, 1)
if not img then
return corrupt("frame " .. (#frames + 1) .. " has no image data", c.off)
end
local bs, err = decodeBitstream(buf, img, if img.id == "VP8 " then alph else nil, o, false)
if not bs then
return nil, err
end
if bs.w ~= fw or bs.h ~= fh then
return corrupt(string.format("frame %d: image %d x %d does not match its ANMF size %d x %d", #frames + 1, bs.w, bs.h, fw, fh), c.off)
end
table.insert(frames, {
rgba = bs.rgba :: buffer,
x = fx,
y = fy,
w = fw,
h = fh,
blend = bit32.band(fl, 2) == 0,
disposeBg = bit32.band(fl, 1) == 1,
hasAlpha = bs.hasAlpha,
})
bs.source.hasAlpha = bs.hasAlpha
table.insert(sources, bs.source)
table.insert(delays, dur)
if not wantAll then
break
end
end
end
if #frames == 0 then
return corrupt("animation without frames")
end
local canvases = Anim.coalesce(cw, ch, frames)
local img = Types.Image.new(cw, ch, "rgba8")
img.pixels = canvases[1]
img.loops = loops
for k, v in meta do
img.meta[k] = v
end
img.meta.background = { bit32.band(bit32.rshift(bg, 16), 255), bit32.band(bit32.rshift(bg, 8), 255), bit32.band(bg, 255), bit32.rshift(bg, 24) }
img.meta.source = { format = "webp", bitDepth = 8, extended = true, flags = flags, animated = true, codec = sources[1].codec, lossless = sources[1].lossless }
if wantAll then
local list: { Types.Frame } = {}
for i, f in frames do
local fi: Types.Image
if o.coalesce then
fi = Types.Image.new(cw, ch, "rgba8")
fi.pixels = canvases[i]
else
fi = Types.Image.new(f.w, f.h, "rgba8")
fi.pixels = f.rgba
end
fi.meta.source = sources[i]
fi.meta.duration = delays[i]
list[i] = {
image = fi,
delay = delays[i] / 1000,
x = if o.coalesce then 0 else f.x,
y = if o.coalesce then 0 else f.y,
dispose = if not o.coalesce and f.disposeBg then "background" else "none",
blend = if not o.coalesce and f.blend then "over" else "source",
}
end
img.frames = list
end
return img, nil
end
-- info(r) -> { width, height, animated, alpha, lossless, frames? } from the headers only | nil, Err
function Webp.info(r: Bytes.Reader): (any, Err.Err?)
local chunks, cerr = readChunks(r)
if not chunks then
return nil, cerr
end
local first = chunks[1]
if not first then
return corrupt("no chunks")
end
local buf = r.buf
if first.id == "VP8X" and first.size >= 10 then
local flags = readu8(buf, first.off)
local n = 0
for _, c in chunks do
if c.id == "ANMF" then
n += 1
end
end
return {
width = u24(buf, first.off + 4) + 1,
height = u24(buf, first.off + 7) + 1,
animated = bit32.band(flags, FLAG_ANIM) ~= 0,
alpha = bit32.band(flags, FLAG_ALPHA) ~= 0,
frames = if n > 0 then n else 1,
}, nil
elseif first.id == "VP8L" then
local i, err = Vp8L.info(buf, first.off, first.size)
if not i then
return nil, err
end
return { width = i.width, height = i.height, animated = false, alpha = i.alpha, lossless = true, frames = 1 }, nil
elseif first.id == "VP8 " then
local h, err = Vp8.info(buf, first.off, first.size)
if not h then
return nil, err
end
return { width = h.width, height = h.height, animated = false, alpha = false, lossless = false, frames = 1 }, nil
end
return corrupt("the first chunk is '" .. first.id .. "', not VP8, VP8L or VP8X")
end
-- ------------------------------------------------------------------------------------------------ encode
local function hasAlpha(px: buffer, n: number): boolean
for i = 0, n - 1 do
if readu8(px, i * 4 + 3) ~= 255 then
return true
end
end
return false
end
local function validImage(img: any): boolean
return type(img) == "table" and img.format == "rgba8" and type(img.pixels) == "buffer" and type(img.width) == "number" and type(img.height) == "number" and img.width >= 1 and img.height >= 1 and img.width <= 16384 and img.height <= 16384 and img.width % 1 == 0 and img.height % 1 == 0 and buffer.len(img.pixels) >= img.width * img.height * 4
end
local function vp8x(flags: number, w: number, h: number): buffer
local b = Bytes.writer(10)
b:u8(flags)
b:u24le(0)
b:u24le(w - 1)
b:u24le(h - 1)
return b:finish()
end
local function metaChunk(meta: any, key: string): buffer?
local v = meta and meta[key]
if type(v) == "buffer" and buffer.len(v) > 0 then
return v
elseif type(v) == "string" and #v > 0 then
return buffer.fromstring(v)
end
return nil
end
function Webp.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: EncodeOptions = opts or {}
if o.lossless == false then
return nil, Err.new(Err.UNSUPPORTED, "lossy WebP encoding is not supported (use lossless)")
end
if not validImage(img) then
return nil, Err.new(Err.ARG, "needs an rgba8 Image (1..16384 pixels a side)")
end
local effort = o.effort or 5
if type(effort) ~= "number" or effort < 0 or effort > 9 then
return nil, Err.new(Err.ARG, "effort must be 0..9")
end
local vopts: Vp8L.EncodeOptions = { effort = effort, exact = o.exact }
local w, h = img.width, img.height
local icc, exif, xmp = metaChunk(img.meta, "icc"), metaChunk(img.meta, "exif"), metaChunk(img.meta, "xmp")
local frames = img.frames
local body = Riff.writer("WEBP", { rf64 = false })
if not frames or #frames == 0 then
local bits, err = Vp8L.encode(img.pixels, w, h, vopts)
if not bits then
return nil, err
end
if icc or exif or xmp then
local flags = (if icc then FLAG_ICC else 0) + (if exif then FLAG_EXIF else 0) + (if xmp then FLAG_XMP else 0)
if hasAlpha(img.pixels, w * h) then
flags += FLAG_ALPHA
end
body:chunk("VP8X", vp8x(flags, w, h))
if icc then
body:chunk("ICCP", icc)
end
body:chunk("VP8L", bits)
if exif then
body:chunk("EXIF", exif)
end
if xmp then
body:chunk("XMP ", xmp)
end
else
body:chunk("VP8L", bits)
end
return body:finish()
end
-- animation: frames as they are when WebP can store them (even offsets, dispose none / background), else every
-- frame flattened to a full canvas
local list: { Anim.Frame } = {}
local direct = true
for i, f in frames do
if type(f) ~= "table" or not validImage(f.image) then
return nil, Err.new(Err.ARG, "frame " .. i .. ": needs an rgba8 image")
end
local fx, fy = f.x or 0, f.y or 0
local fw, fh = f.image.width, f.image.height
if type(fx) ~= "number" or type(fy) ~= "number" or fx < 0 or fy < 0 or fx % 1 ~= 0 or fy % 1 ~= 0 or fx + fw > w or fy + fh > h then
return nil, Err.new(Err.ARG, "frame " .. i .. ": rectangle outside the canvas")
end
local dispose = f.dispose or "none"
if dispose ~= "none" and dispose ~= "background" and dispose ~= "previous" then
return nil, Err.new(Err.ARG, "frame " .. i .. ": bad dispose " .. tostring(dispose))
end
if dispose == "previous" or fx % 2 == 1 or fy % 2 == 1 then
direct = false
end
table.insert(list, {
rgba = f.image.pixels,
x = fx,
y = fy,
w = fw,
h = fh,
blend = f.blend == "over",
disposeBg = dispose == "background",
disposePrev = dispose == "previous",
hasAlpha = true,
})
end
if not direct then
local canvases = Anim.composite(w, h, list)
for i, c in canvases do
list[i] = { rgba = c, x = 0, y = 0, w = w, h = h, blend = false, disposeBg = false, hasAlpha = true }
end
end
local anyAlpha = false
for _, f in list do
if hasAlpha(f.rgba, f.w * f.h) then
anyAlpha = true
break
end
end
local flags = FLAG_ANIM + (if anyAlpha then FLAG_ALPHA else 0) + (if icc then FLAG_ICC else 0) + (if exif then FLAG_EXIF else 0) + (if xmp then FLAG_XMP else 0)
body:chunk("VP8X", vp8x(flags, w, h))
if icc then
body:chunk("ICCP", icc)
end
local loops = o.loops or img.loops or 0
if type(loops) ~= "number" or loops < 0 or loops > 65535 then
return nil, Err.new(Err.ARG, "loops must be 0..65535")
end
local bgc = o.background or (img.meta and img.meta.background) or { 0, 0, 0, 0 }
if type(bgc) ~= "table" then
return nil, Err.new(Err.ARG, "background must be { r, g, b, a }")
end
for k = 1, 4 do
local v = bgc[k]
if v ~= nil and (type(v) ~= "number" or v < 0 or v > 255 or v % 1 ~= 0) then
return nil, Err.new(Err.ARG, "background must be { r, g, b, a } with 0..255 integers")
end
end
local anim = buffer.create(6)
-- the background colour is stored as B, G, R, A
buffer.writeu8(anim, 0, bgc[3] or 0)
buffer.writeu8(anim, 1, bgc[2] or 0)
buffer.writeu8(anim, 2, bgc[1] or 0)
buffer.writeu8(anim, 3, bgc[4] or 0)
buffer.writeu16(anim, 4, loops)
body:chunk("ANIM", anim)
for i, f in list do
local bits, err = Vp8L.encode(f.rgba, f.w, f.h, vopts)
if not bits then
return nil, err
end
local delay = frames[i].delay
local ms = if type(delay) == "number" and delay == delay then math.clamp(math.floor(delay * 1000 + 0.5), 0, 0xffffff) else 100
local hdr = Bytes.writer(16 + buffer.len(bits) + 9)
hdr:u24le(f.x // 2)
hdr:u24le(f.y // 2)
hdr:u24le(f.w - 1)
hdr:u24le(f.h - 1)
hdr:u24le(ms)
hdr:u8((if f.blend then 0 else 2) + (if f.disposeBg then 1 else 0))
local nb = buffer.len(bits)
hdr:string("VP8L")
hdr:u32le(nb)
hdr:bytes(bits)
if nb % 2 == 1 then
hdr:u8(0)
end
body:chunk("ANMF", hdr.buf, 0, hdr:tell())
end
if exif then
body:chunk("EXIF", exif)
end
if xmp then
body:chunk("XMP ", xmp)
end
return body:finish()
end
-- ------------------------------------------------------------------------------------------------ extras
-- coalesce(img) -> the full composited canvases of a decoded animation's frames ({ buffer }, rgba8), the way
-- WebPAnimDecoder composites them (nil for a still image or frames that do not fit the canvas)
function Webp.coalesce(img: Types.Image): { buffer }?
if type(img) ~= "table" or type(img.frames) ~= "table" or type(img.width) ~= "number" or type(img.height) ~= "number" then
return nil
end
local list: { Anim.Frame } = {}
for _, f in img.frames :: { Types.Frame } do
if type(f) ~= "table" or not validImage(f.image) or type(f.x) ~= "number" or type(f.y) ~= "number" or f.x < 0 or f.y < 0 or f.x % 1 ~= 0 or f.y % 1 ~= 0 or f.x + f.image.width > img.width or f.y + f.image.height > img.height then
return nil
end
table.insert(list, {
rgba = f.image.pixels,
x = f.x,
y = f.y,
w = f.image.width,
h = f.image.height,
blend = f.blend == "over",
disposeBg = f.dispose == "background",
hasAlpha = not (f.image.meta.source and f.image.meta.source.hasAlpha == false),
})
end
return Anim.coalesce(img.width, img.height, list)
end
return Webp
+162
View File
@@ -0,0 +1,162 @@
--!strict
-- image/xbm: X BitMap (X11 bitmap(1) C source; X10 16-bit variant; new code). Decode: the #define _width / _height
-- (and _x_hot / _y_hot: meta.hotspot), the char / short bits array in hex, decimal or octal, LSB first, set bits black,
-- clear bits white (opts.transparent: clear bits transparent instead). Encode: rgba8 thresholded (luminance below
-- opts.threshold, default 128, and alpha >= 128 is black), X11 format, opts.name (default "image").
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Sniff = require("@rosetta/core/Sniff")
local Types = require("@rosetta/Types")
-- ------------------------------------------------------------------------------------------------ contract
local Xbm = {
name = "xbm",
category = "image",
extensions = { "xbm", "bm" },
mime = { "image/x-xbitmap", "image/x-xbm" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" },
caps = { decode = true, encode = true, depths = { 1 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
transparent: boolean?, -- clear bits transparent (default false: white)
maxPixels: number?, -- refuse larger images (default 2^26)
}
export type EncodeOptions = {
name: string?, -- the C identifier prefix (default "image"; an extension is dropped, other characters become _)
threshold: number?, -- luminance below this is black (default 128)
}
-- ------------------------------------------------------------------------------------------------ sniff
function Xbm.sniff(r: Bytes.Reader): number
local s = Sniff.text(r, 256, true)
if string.match(s, "^#define%s+[%w_]*_?width%s+%d+") or string.match(s, "^/%*.-%*/%s*#define%s+[%w_]*width%s+%d+") then
return 0.9
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Xbm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local n = r.limit - r.base
if n > 2 ^ 26 then
return nil, Err.new(Err.LIMIT, "file too large")
end
local s = buffer.readstring(r.buf, r.base, n)
local w = tonumber(string.match(s, "#define%s+[%w_]-_?width%s+(%d+)"))
local h = tonumber(string.match(s, "#define%s+[%w_]-_?height%s+(%d+)"))
if not w or not h or w < 1 or h < 1 then
return nil, Err.new(Err.CORRUPT, "missing width / height defines")
end
local maxPixels = opts and opts.maxPixels or 2 ^ 26
if w * h > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
end
local brace = string.find(s, "{", 1, true)
if not brace then
return nil, Err.new(Err.CORRUPT, "missing bits array")
end
local decl = string.sub(s, 1, brace)
local short = string.find(decl, "short", 1, true) ~= nil
local unit = if short then 16 else 8
local per = (w + unit - 1) // unit
local want = per * h
local img = Types.Image.new(w, h, "rgba8")
local px = img.pixels
local clear = if opts and opts.transparent then 0x00FFFFFF else 0xFFFFFFFF
local got = 0
local body = string.gsub(string.sub(s, brace + 1), "/%*.-%*/", " ")
for tok in string.gmatch(body, "[%w]+") do
if got >= want then
break
end
local v
if string.match(tok, "^0[xX]%x+$") then
v = tonumber(string.sub(tok, 3), 16)
elseif string.match(tok, "^0%d+$") then
v = tonumber(tok, 8)
elseif string.match(tok, "^%d+$") then
v = tonumber(tok)
end
if v then
local y, cx = got // per, (got % per) * unit
for k = 0, unit - 1 do
local x = cx + k
if x < w then
buffer.writeu32(px, (y * w + x) * 4, if bit32.band(bit32.rshift(v, k), 1) == 1 then 0xFF000000 else clear)
end
end
got += 1
end
end
if got < want then
for i = got * unit, want * unit - 1 do
local y, x = i // (per * unit), i % (per * unit)
if x < w then
buffer.writeu32(px, (y * w + x) * 4, clear)
end
end
img.meta.truncated = true
end
local hx = tonumber(string.match(s, "#define%s+[%w_]-_?x_hot%s+(%d+)"))
local hy = tonumber(string.match(s, "#define%s+[%w_]-_?y_hot%s+(%d+)"))
if hx and hy then
img.meta.hotspot = { x = hx, y = hy }
end
local name = string.match(s, "#define%s+([%w_]-)_?width%s")
img.meta.source = { format = "xbm", bitDepth = 1, name = name, x10 = short }
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Xbm.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, "needs an rgba8 Image")
end
local w, h = img.width, img.height
if w < 1 or h < 1 then
return nil, Err.new(Err.ARG, "bad size")
end
-- a C identifier from opts.name (F.save passes the file name: "out.xbm" -> out)
local name = string.gsub(string.gsub(opts and opts.name or "image", "%.[^.]*$", ""), "[^%w_]", "_")
if name == "" or string.match(name, "^%d") then
name = "_" .. name
end
local th = opts and opts.threshold or 128
local px = img.pixels
local parts = {
string.format("#define %s_width %d\n#define %s_height %d\n", name, w, name, h),
}
local hs: { x: number, y: number }? = img.meta and img.meta.hotspot
if hs then
table.insert(parts, string.format("#define %s_x_hot %d\n#define %s_y_hot %d\n", name, hs.x, name, hs.y))
end
table.insert(parts, string.format("static unsigned char %s_bits[] = {\n", name))
local per = (w + 7) // 8
local bytes = {}
for y = 0, h - 1 do
for bx = 0, per - 1 do
local v = 0
for k = 0, 7 do
local x = bx * 8 + k
if x < w then
local o = (y * w + x) * 4
local lum = 0.299 * buffer.readu8(px, o) + 0.587 * buffer.readu8(px, o + 1) + 0.114 * buffer.readu8(px, o + 2)
if lum < th and buffer.readu8(px, o + 3) >= 128 then
v += bit32.lshift(1, k)
end
end
end
table.insert(bytes, string.format("0x%02x", v))
end
end
for i = 1, #bytes, 12 do
table.insert(parts, " " .. table.concat(bytes, ", ", i, math.min(i + 11, #bytes)) .. (if i + 11 < #bytes then ",\n" else " };\n"))
end
return buffer.fromstring(table.concat(parts)), nil
end
return Xbm
+57
View File
@@ -0,0 +1,57 @@
--!strict
-- image/xpm/Names: colour names for XPM colour tables: the CSS Color 4 named colours (which come from X11), with X11's
-- own values where the two differ (gray / grey, green, maroon, purple), and X11's grey0 .. grey100 / gray0 .. gray100.
-- lookup(name) takes a lower-case name without spaces and returns R + G * 256 + B * 65536, or nil.
local Names = {}
local HEX: { [string]: number } = {
aliceblue = 0xF0F8FF, antiquewhite = 0xFAEBD7, aqua = 0x00FFFF, aquamarine = 0x7FFFD4, azure = 0xF0FFFF,
beige = 0xF5F5DC, bisque = 0xFFE4C4, black = 0x000000, blanchedalmond = 0xFFEBCD, blue = 0x0000FF,
blueviolet = 0x8A2BE2, brown = 0xA52A2A, burlywood = 0xDEB887, cadetblue = 0x5F9EA0, chartreuse = 0x7FFF00,
chocolate = 0xD2691E, coral = 0xFF7F50, cornflowerblue = 0x6495ED, cornsilk = 0xFFF8DC, crimson = 0xDC143C,
cyan = 0x00FFFF, darkblue = 0x00008B, darkcyan = 0x008B8B, darkgoldenrod = 0xB8860B, darkgray = 0xA9A9A9,
darkgreen = 0x006400, darkgrey = 0xA9A9A9, darkkhaki = 0xBDB76B, darkmagenta = 0x8B008B, darkolivegreen = 0x556B2F,
darkorange = 0xFF8C00, darkorchid = 0x9932CC, darkred = 0x8B0000, darksalmon = 0xE9967A, darkseagreen = 0x8FBC8F,
darkslateblue = 0x483D8B, darkslategray = 0x2F4F4F, darkslategrey = 0x2F4F4F, darkturquoise = 0x00CED1,
darkviolet = 0x9400D3, deeppink = 0xFF1493, deepskyblue = 0x00BFFF, dimgray = 0x696969, dimgrey = 0x696969,
dodgerblue = 0x1E90FF, firebrick = 0xB22222, floralwhite = 0xFFFAF0, forestgreen = 0x228B22, fuchsia = 0xFF00FF,
gainsboro = 0xDCDCDC, ghostwhite = 0xF8F8FF, gold = 0xFFD700, goldenrod = 0xDAA520, gray = 0xBEBEBE,
green = 0x00FF00, greenyellow = 0xADFF2F, grey = 0xBEBEBE, honeydew = 0xF0FFF0, hotpink = 0xFF69B4,
indianred = 0xCD5C5C, indigo = 0x4B0082, ivory = 0xFFFFF0, khaki = 0xF0E68C, lavender = 0xE6E6FA,
lavenderblush = 0xFFF0F5, lawngreen = 0x7CFC00, lemonchiffon = 0xFFFACD, lightblue = 0xADD8E6, lightcoral = 0xF08080,
lightcyan = 0xE0FFFF, lightgoldenrodyellow = 0xFAFAD2, lightgray = 0xD3D3D3, lightgreen = 0x90EE90,
lightgrey = 0xD3D3D3, lightpink = 0xFFB6C1, lightsalmon = 0xFFA07A, lightseagreen = 0x20B2AA, lightskyblue = 0x87CEFA,
lightslategray = 0x778899, lightslategrey = 0x778899, lightsteelblue = 0xB0C4DE, lightyellow = 0xFFFFE0,
lime = 0x00FF00, limegreen = 0x32CD32, linen = 0xFAF0E6, magenta = 0xFF00FF, maroon = 0xB03060,
mediumaquamarine = 0x66CDAA, mediumblue = 0x0000CD, mediumorchid = 0xBA55D3, mediumpurple = 0x9370DB,
mediumseagreen = 0x3CB371, mediumslateblue = 0x7B68EE, mediumspringgreen = 0x00FA9A, mediumturquoise = 0x48D1CC,
mediumvioletred = 0xC71585, midnightblue = 0x191970, mintcream = 0xF5FFFA, mistyrose = 0xFFE4E1, moccasin = 0xFFE4B5,
navajowhite = 0xFFDEAD, navy = 0x000080, navyblue = 0x000080, oldlace = 0xFDF5E6, olive = 0x808000, olivedrab = 0x6B8E23,
orange = 0xFFA500, orangered = 0xFF4500, orchid = 0xDA70D6, palegoldenrod = 0xEEE8AA, palegreen = 0x98FB98,
paleturquoise = 0xAFEEEE, palevioletred = 0xDB7093, papayawhip = 0xFFEFD5, peachpuff = 0xFFDAB9, peru = 0xCD853F,
pink = 0xFFC0CB, plum = 0xDDA0DD, powderblue = 0xB0E0E6, purple = 0xA020F0, rebeccapurple = 0x663399, red = 0xFF0000,
rosybrown = 0xBC8F8F, royalblue = 0x4169E1, saddlebrown = 0x8B4513, salmon = 0xFA8072, sandybrown = 0xF4A460,
seagreen = 0x2E8B57, seashell = 0xFFF5EE, sienna = 0xA0522D, silver = 0xC0C0C0, skyblue = 0x87CEEB,
slateblue = 0x6A5ACD, slategray = 0x708090, slategrey = 0x708090, snow = 0xFFFAFA, springgreen = 0x00FF7F,
steelblue = 0x4682B4, tan = 0xD2B48C, teal = 0x008080, thistle = 0xD8BFD8, tomato = 0xFF6347, turquoise = 0x40E0D0,
violet = 0xEE82EE, wheat = 0xF5DEB3, white = 0xFFFFFF, whitesmoke = 0xF5F5F5, yellow = 0xFFFF00, yellowgreen = 0x9ACD32,
}
-- lookup(name) -> R + G * 256 + B * 65536 | nil (name: lower case, no spaces)
function Names.lookup(name: string): number?
local v = HEX[name]
if v then
return bit32.rshift(v, 16) + bit32.band(v, 0xFF00) + bit32.band(v, 0xFF) * 65536
end
local n = string.match(name, "^gr[ae]y(%d+)$")
if n then
local k = tonumber(n) :: number
if k <= 100 then
local g = math.floor(k * 255 / 100 + 0.49)
return g * 0x10101
end
end
return nil
end
return Names
+272
View File
@@ -0,0 +1,272 @@
--!strict
-- image/xpm: X PixMap (XPM 3 C source and the XPM 2 plain form; the "XPM Manual" by Arnaud Le Hors; new code). Decode:
-- the values line (width, height, colours, chars per pixel, hotspot: meta.hotspot), colour lines with the c / g / g4 /
-- m / s keys (c preferred, then g, g4, m), #RGB / #RRGGBB / #RRRGGGBBB / #RRRRGGGGBBBB, None (transparent) and colour
-- names (image/xpm/Names: the CSS / X11 names and grey0..100; an unknown name is black and listed in
-- meta.unknownColours), the extensions section skipped. Encode: rgba8 as XPM 3 with hex colours, alpha < 128 as None,
-- the fewest chars per pixel; opts.name (default "image").
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Sniff = require("@rosetta/core/Sniff")
local Types = require("@rosetta/Types")
local Names = require("@rosetta/image/xpm/Names")
-- ------------------------------------------------------------------------------------------------ contract
local Xpm = {
name = "xpm",
category = "image",
extensions = { "xpm", "pm" },
mime = { "image/x-xpixmap", "image/x-xpm" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" },
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxPixels: number?, -- refuse larger images (default 2^26)
}
export type EncodeOptions = {
name: string?, -- the C identifier (default "image"; an extension is dropped, other characters become _)
}
-- the characters of pixel codes (printable ASCII without '"' and '\')
local CODE_CHARS = " .XoO+@#$%&*=-;:>,<1234567890qwertyuipasdfghjklzxcvbnmMNBVCZASDFGHJKLPIUYTREWQ!~^/()_`'][{}|"
-- ------------------------------------------------------------------------------------------------ sniff
function Xpm.sniff(r: Bytes.Reader): number
local s = Sniff.text(r, 64, true)
if string.sub(s, 1, 9) == "/* XPM */" or string.sub(s, 1, 6) == "! XPM2" then
return 1
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- colour value -> rgba8 u32, or nil for an unknown name
local function colour(v: string): number?
local l = string.lower(v)
if l == "none" or l == "transparent" then
return 0
end
if string.sub(v, 1, 1) == "#" then
local hex = string.sub(v, 2)
local n = #hex
if n % 3 ~= 0 or n == 0 or n > 12 or not string.match(hex, "^%x+$") then
return nil
end
local k = n // 3
local mx = 16 ^ k - 1
local c = 0
for i = 0, 2 do
local x = tonumber(string.sub(hex, i * k + 1, i * k + k), 16) :: number
c += math.floor(x * 255 / mx + 0.5) * 256 ^ i
end
return c + 0xFF000000
end
local rgb = Names.lookup(l)
return if rgb then rgb + 0xFF000000 else nil
end
-- the strings of the file: C string literals (XPM 3) or plain lines (XPM 2)
local function strings(s: string): { string }
local out = {}
if string.sub(Sniff.dropBom(s), 1, 6) == "! XPM2" then
local first = true
for line in string.gmatch(s, "[^\n]+") do
if first then
first = false
else
table.insert(out, (string.gsub(line, "\r$", "")))
end
end
return out
end
local i, n = 1, #s
while i <= n do
local c = string.sub(s, i, i)
if c == "/" and string.sub(s, i + 1, i + 1) == "*" then
local e = string.find(s, "*/", i + 2, true)
i = if e then e + 2 else n + 1
elseif c == '"' then
local parts = {}
local j = i + 1
while j <= n do
local d = string.sub(s, j, j)
if d == "\\" then
table.insert(parts, string.sub(s, j + 1, j + 1))
j += 2
elseif d == '"' then
break
else
local e = string.find(s, '["\\]', j)
local stop = (e or n + 1) - 1
table.insert(parts, string.sub(s, j, stop))
j = stop + 1
end
end
table.insert(out, table.concat(parts))
i = j + 1
else
i += 1
end
end
return out
end
local KEYS = { c = true, m = true, g4 = true, g = true, s = true }
function Xpm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local n = r.limit - r.base
if n > 2 ^ 27 then
return nil, Err.new(Err.LIMIT, "file too large")
end
local list = strings(buffer.readstring(r.buf, r.base, n))
if #list == 0 then
return nil, Err.new(Err.CORRUPT, "no XPM strings")
end
local vals: { number } = {}
for tok in string.gmatch(list[1], "%S+") do
table.insert(vals, tonumber(tok) or -1)
end
local w: number, h: number, nc: number, cpp: number = vals[1] or -1, vals[2] or -1, vals[3] or -1, vals[4] or -1
if w < 1 or h < 1 or nc < 1 or cpp < 1 or cpp > 8 or w % 1 ~= 0 or h % 1 ~= 0 then
return nil, Err.new(Err.CORRUPT, "bad values line")
end
local maxPixels = opts and opts.maxPixels or 2 ^ 26
if w * h > maxPixels or nc > 2 ^ 24 then
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
end
if #list < 1 + nc then
return nil, Err.new(Err.TRUNCATED, "colour table runs past the end")
end
local map: { [string]: number } = {}
local unknown: { string } = {}
local palette: { { number } } = {}
for i = 1, nc do
local line = list[1 + i]
local code = string.sub(line, 1, cpp)
local rest = string.sub(line, cpp + 1)
local found: { [string]: string } = {}
local key: string? = nil
local acc = {}
for tok in string.gmatch(rest, "%S+") do
if KEYS[tok] and (key == nil or #acc > 0) then
if key then
found[key] = table.concat(acc, " ")
end
key, acc = tok, {}
else
table.insert(acc, tok)
end
end
if key then
found[key] = table.concat(acc, " ")
end
local v = found.c or found.g or found.g4 or found.m
local c = if v then colour(v) else nil
if v and not c then
c = colour((string.gsub(v, " ", "")))
end
local cv: number = c or 0xFF000000
if not c then
table.insert(unknown, v or "")
end
c = cv
map[code] = cv
palette[i] = { bit32.band(cv, 255), bit32.band(bit32.rshift(cv, 8), 255), bit32.band(bit32.rshift(cv, 16), 255), bit32.rshift(cv, 24) }
end
local img = Types.Image.new(w, h, "rgba8")
local px = img.pixels
local truncated = false
for y = 0, h - 1 do
local row = list[2 + nc + y]
if not row then
truncated = true
break
end
for x = 0, w - 1 do
local c = map[string.sub(row, x * cpp + 1, x * cpp + cpp)]
buffer.writeu32(px, (y * w + x) * 4, c or 0)
end
end
if #vals >= 6 and vals[5] >= 0 and vals[6] >= 0 then
img.meta.hotspot = { x = vals[5], y = vals[6] }
end
if #unknown > 0 then
img.meta.unknownColours = unknown
end
if truncated then
img.meta.truncated = true
end
img.meta.palette = palette
img.meta.source = { format = "xpm", colours = nc, charsPerPixel = cpp }
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Xpm.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, "needs an rgba8 Image")
end
local w, h = img.width, img.height
if w < 1 or h < 1 then
return nil, Err.new(Err.ARG, "bad size")
end
-- a C identifier from opts.name (F.save passes the file name: "out.xbm" -> out)
local name = string.gsub(string.gsub(opts and opts.name or "image", "%.[^.]*$", ""), "[^%w_]", "_")
if name == "" or string.match(name, "^%d") then
name = "_" .. name
end
local px = img.pixels
local index: { [number]: number } = {}
local order: { number } = {}
local keys = table.create(w * h, 0)
for i = 0, w * h - 1 do
local v = buffer.readu32(px, i * 4)
local k = if v < 0x80000000 then -1 else bit32.band(v, 0xFFFFFF)
if not index[k] then
table.insert(order, k)
index[k] = #order
end
keys[i + 1] = index[k]
end
local nchars = #CODE_CHARS
local cpp = 1
while nchars ^ cpp < #order do
cpp += 1
end
local codes: { string } = {}
for i = 1, #order do
local v, s = i - 1, ""
for _ = 1, cpp do
local d = v % nchars
s ..= string.sub(CODE_CHARS, d + 1, d + 1)
v //= nchars
end
codes[i] = s
end
local parts = { "/* XPM */\n", string.format("static char *%s[] = {\n", name) }
local hs: { x: number, y: number }? = img.meta and img.meta.hotspot
if hs then
table.insert(parts, string.format('"%d %d %d %d %d %d",\n', w, h, #order, cpp, hs.x, hs.y))
else
table.insert(parts, string.format('"%d %d %d %d",\n', w, h, #order, cpp))
end
for i, k in order do
local col = if k < 0 then "None" else string.format("#%02X%02X%02X", bit32.band(k, 255), bit32.band(bit32.rshift(k, 8), 255), bit32.rshift(k, 16))
table.insert(parts, string.format('"%s c %s",\n', codes[i], col))
end
for y = 0, h - 1 do
local row = table.create(w, "")
for x = 0, w - 1 do
row[x + 1] = codes[keys[y * w + x + 1]]
end
table.insert(parts, '"' .. table.concat(row) .. '"' .. (if y < h - 1 then ",\n" else "\n"))
end
table.insert(parts, "};\n")
return buffer.fromstring(table.concat(parts)), nil
end
return Xpm