Files
rosetta/src/Formats/image/ico/init.luau
T

283 lines
11 KiB
Luau

--!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("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Dib = require("@formats/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" },
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" })
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