ws-tex: image/icns (read RLE / ARGB / 1-bit / PNG-hook entries, JP2 skipped; write PNG via encodeImage or RLE)

Tested against libicns (png2icns / icns2png -x), Pillow's writer and a hand-written file.
This commit is contained in:
4DBug committed 2026-10-31 15:07:07 -05:00
1 parent ce4845ae13
commit 9e114fba8b
6 files changed
+519

No files matched your search

+12
View File
@@ -74,6 +74,18 @@ local list: { Entry } = {
return require("@formats/image/hdr")
end,
},
{
name = "icns",
category = "image",
path = "image/icns",
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 } },
load = function()
return require("@formats/image/icns")
end,
},
{
name = "ico",
category = "image",
+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("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Sniff = require("@formats/core/Sniff")
local Types = require("@formats/Types")
local Chunks = require("@formats/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