ws-tex: image/ani (animated cursors -> frames through the decodeImage hook; write through encodeImage)
seq / rate steps, jiffy delays, CUR hotspots, INFO title; AF_ICON clear is UNSUPPORTED. Tested against Pillow-written ICO / CUR frames assembled into ANI files.
This commit is contained in:
1 parent
9e114fba8b
commit
00d47096ed
5 files changed
+334
No files matched your search
@@ -5,6 +5,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
|
||||
|
||||
| Category | Format | Extensions | Read | Write | Capabilities | Test |
|
||||
|---|---|---|---|---|---|---|
|
||||
| image | ani | .ani | yes | yes | alpha: true, animation: true, frames: true | `tests/image/ani.luau` |
|
||||
| image | bmp | .bmp .dib | yes | yes | alpha: true, depths: 1, 2, 4, 8, 16, 24, 32, rle: true | `tests/image/bmp.luau` |
|
||||
| image | dds | .dds | yes | yes | alpha: true, float: true, mipmaps: true, cubemap: true, compressed: "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7" | `tests/image/dds.luau` |
|
||||
| image | exr | .exr | yes | yes | alpha: true, float: true, hdr: true, depths: 16, 32, multipart: true, tiled: true | `tests/image/exr.luau` |
|
||||
|
||||
@@ -14,6 +14,18 @@ export type Entry = {
|
||||
}
|
||||
|
||||
local list: { Entry } = {
|
||||
{
|
||||
name = "ani",
|
||||
category = "image",
|
||||
path = "image/ani",
|
||||
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 },
|
||||
load = function()
|
||||
return require("@formats/image/ani")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "bmp",
|
||||
category = "image",
|
||||
|
||||
@@ -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("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Riff = require("@formats/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
|
||||
@@ -0,0 +1,72 @@
|
||||
-- image/ani tests: animated cursors around Pillow-written ICO / CUR frames (seq + rate, plain, cursor hotspots, INFO
|
||||
-- title) against Pillow's frame decodes and the written steps / delays; AF_ICON clear and a missing hook are
|
||||
-- UNSUPPORTED; the encoder through the ICO hook round-trips; the fuzz no-throw pass. Fixtures: tools/fixtures/ani.py.
|
||||
local T = require("@tests/T")
|
||||
local Ani = require("@formats/image/ani")
|
||||
local Ico = require("@formats/image/ico")
|
||||
local Png = require("@formats/image/png")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local R = require("@tests/image/_raster")
|
||||
local Fx = require("@tests/gen/ani")
|
||||
|
||||
local t = T.suite("ani")
|
||||
t:eq(Ani.name, "ani", "name")
|
||||
t:check(Ani.caps.decode and Ani.caps.encode, "caps")
|
||||
|
||||
local hooks = {
|
||||
decodeImage = function(b: buffer): (any, any)
|
||||
-- Pillow writes the ICO entries as PNG: the ICO decoder gets its own hook
|
||||
return Ico.decode(Bytes.reader(b), { decodeImage = function(p: buffer): (any, any)
|
||||
return Png.decode(Bytes.reader(p))
|
||||
end })
|
||||
end,
|
||||
encodeImage = function(img: any, _fmt: string): (any, any)
|
||||
return Ico.encode(img)
|
||||
end,
|
||||
}
|
||||
|
||||
for _, c in Fx.cases do
|
||||
local img, err = Ani.decode(Bytes.reader(buffer.fromstring(c.data)), hooks)
|
||||
if c.unsupported then
|
||||
t:check(img == nil and err and err.code == Err.UNSUPPORTED, c.name .. ": UNSUPPORTED")
|
||||
continue
|
||||
end
|
||||
t:check(img, c.name .. ": " .. tostring(err))
|
||||
t:check(img.width == c.w and img.height == c.h, c.name .. ": size")
|
||||
t:eq(#img.frames, #c.steps, c.name .. ": steps")
|
||||
for i, s in c.steps do
|
||||
local f = img.frames[i]
|
||||
t:check(math.abs(f.delay - s.delay) < 1e-9, c.name .. ": step " .. i .. " delay")
|
||||
t:eq(R.maxDiff(f.image.pixels, buffer.fromstring(c.frames[s.frame]), c.w * c.h), 0, c.name .. ": step " .. i .. " pixels")
|
||||
end
|
||||
t:eq(img.loops, 0, c.name .. ": loops forever")
|
||||
if c.title then
|
||||
t:eq(img.meta.text.title, c.title, c.name .. ": title")
|
||||
end
|
||||
if c.hotspot then
|
||||
t:check(img.meta.hotspot and img.meta.hotspot.x == c.hotspot[1] and img.meta.hotspot.y == c.hotspot[2], c.name .. ": hotspot")
|
||||
end
|
||||
-- re-encode through the ICO hook
|
||||
local enc, eerr = Ani.encode(img, hooks)
|
||||
t:check(enc, c.name .. ": encode " .. tostring(eerr))
|
||||
local back = Ani.decode(Bytes.reader(enc :: buffer), hooks) :: any
|
||||
t:eq(#back.frames, #img.frames, c.name .. ": re-encoded steps")
|
||||
for i, f in back.frames do
|
||||
t:eq(buffer.tostring(f.image.pixels), buffer.tostring(img.frames[i].image.pixels), c.name .. ": re-encoded frame " .. i)
|
||||
t:check(math.abs(f.delay - img.frames[i].delay) < 1 / 120, c.name .. ": re-encoded delay " .. i)
|
||||
end
|
||||
end
|
||||
do
|
||||
local c = Fx.cases[1]
|
||||
t:eq(Ani.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, "sniff")
|
||||
t:eq(Ani.sniff(Bytes.reader(buffer.fromstring("RIFF\0\0\0\0WAVE"))), 0, "sniff WAVE")
|
||||
local _, e = Ani.decode(Bytes.reader(buffer.fromstring(c.data)))
|
||||
t:check(e and e.code == Err.UNSUPPORTED, "no hook")
|
||||
local _, e2 = Ani.encode(Ico.decode(Bytes.reader(buffer.fromstring(c.data))) or ({ pixels = buffer.create(4) } :: any))
|
||||
t:check(e2 ~= nil, "encode without the hook")
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Ani.decode(Bytes.reader(b), hooks)
|
||||
end, R.samples(Fx.cases), { mutations = 10 })
|
||||
t:done()
|
||||
@@ -0,0 +1,66 @@
|
||||
# ANI fixtures (tools/fixtures.py): animated cursors assembled here around ICO / CUR frames written by Pillow (32 x 32
|
||||
# RGBA; the CUR ones patched from Pillow's ICO with hotspots): with seq + rate chunks, with neither, with INFO text, and
|
||||
# one with AF_ICON clear (UNSUPPORTED). References: Pillow's decode of every frame, the step order and delays here.
|
||||
# tests/gen/ani.luau { cases = { { name, data, w, h, steps = { { frame, delay } }, frames = { rgba }, hotspot?,
|
||||
# title?, unsupported? } } }
|
||||
import importlib.util, os, struct
|
||||
|
||||
def _load(n):
|
||||
spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
R, T = _load("_raster_ref"), _load("_tex_reference")
|
||||
|
||||
|
||||
def chunk(cid, data):
|
||||
return cid + struct.pack("<I", len(data)) + data + (b"\0" if len(data) % 2 else b"")
|
||||
|
||||
|
||||
def riff_list(kind, items):
|
||||
return chunk(b"LIST", kind + b"".join(chunk(c, d) for c, d in items))
|
||||
|
||||
|
||||
def ani(icons, steps=None, rates=None, disp=10, flags=1, title=None):
|
||||
n = len(icons)
|
||||
ns = len(steps) if steps else n
|
||||
body = b"ACON" + chunk(b"anih", struct.pack("<9I", 36, n, ns, 32, 32, 32, 1, disp, flags | (2 if steps else 0)))
|
||||
if title:
|
||||
body += riff_list(b"INFO", [(b"INAM", title.encode() + b"\0")])
|
||||
if rates:
|
||||
body += chunk(b"rate", struct.pack("<%dI" % len(rates), *rates))
|
||||
if steps:
|
||||
body += chunk(b"seq ", struct.pack("<%dI" % len(steps), *steps))
|
||||
body += riff_list(b"fram", [(b"icon", d) for d in icons])
|
||||
return b"RIFF" + struct.pack("<I", len(body)) + body
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
w = R.Work(ctx)
|
||||
try:
|
||||
for i in range(4):
|
||||
px = bytes(v for p in range(32 * 32) for v in (((p * (i + 3)) % 256, 40 * i, (p // 32) * 8, 255 if (p + i) % 5 else 0)))
|
||||
w.png("f%d.png" % i, 32, 32, px)
|
||||
ctx.python(["pillow"], "from PIL import Image\nimport os\nos.chdir(%r)\nfor i in range(4):\n Image.open('f%%d.png' %% i).save('f%%d.ico' %% i, sizes=[(32, 32)])\n" % w.dir)
|
||||
icos = [w.read("f%d.ico" % i) for i in range(4)]
|
||||
# CUR: type 2, the planes / bit count fields of the entry become the hotspot
|
||||
curs = []
|
||||
for i, d in enumerate(icos):
|
||||
b = bytearray(d)
|
||||
b[2:4] = struct.pack("<H", 2)
|
||||
b[6 + 4:6 + 8] = struct.pack("<HH", 3 + i, 7)
|
||||
curs.append(bytes(b))
|
||||
refs = [T.rgba_from(m, raw) for (m, ww, hh, raw) in T.pillow(ctx, icos)]
|
||||
cases = []
|
||||
steps, rates = [0, 1, 2, 1, 3], [6, 12, 6, 30, 3]
|
||||
cases.append({"name": "seq + rate", "data": ani(icos, steps, rates, title="spinner"), "w": 32, "h": 32,
|
||||
"steps": [{"frame": s + 1, "delay": r / 60} for s, r in zip(steps, rates)], "frames": refs, "title": "spinner"})
|
||||
cases.append({"name": "plain", "data": ani(icos[:3], disp=4), "w": 32, "h": 32,
|
||||
"steps": [{"frame": i + 1, "delay": 4 / 60} for i in range(3)], "frames": refs[:3]})
|
||||
cases.append({"name": "cursor frames", "data": ani(curs[:2], disp=8), "w": 32, "h": 32,
|
||||
"steps": [{"frame": i + 1, "delay": 8 / 60} for i in range(2)], "frames": refs[:2], "hotspot": [3, 7]})
|
||||
cases.append({"name": "raw bitmaps", "data": ani(icos[:1], flags=0), "unsupported": True})
|
||||
ctx.emit("ani", {"cases": cases})
|
||||
finally:
|
||||
w.close()
|
||||
Reference in new issue
Block a user