merge master (ws/tex, ws/3d3, ws/video2, ...)
This commit is contained in:
commit
43df95f6e0
200 files changed
+45540
-1559
No files matched your search
@@ -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,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("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Sniff = require("@formats/core/Sniff")
|
||||
local Types = require("@formats/Types")
|
||||
local Bcn = require("@formats/codecs/image/Bcn")
|
||||
local Texel = require("@formats/codecs/image/Texel")
|
||||
local Texture = require("@formats/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
|
||||
@@ -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("@formats/codecs/compress/Deflate")
|
||||
local Half = require("@formats/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
|
||||
@@ -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
|
||||
@@ -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("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Sniff = require("@formats/core/Sniff")
|
||||
local Types = require("@formats/Types")
|
||||
local Half = require("@formats/codecs/image/Half")
|
||||
local Codec = require("@formats/image/exr/Codec")
|
||||
local Piz = require("@formats/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
|
||||
@@ -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
|
||||
@@ -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("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Chunks = require("@formats/containers/Chunks")
|
||||
local PackBits = require("@formats/codecs/compress/PackBits")
|
||||
local Pixels = require("@formats/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
|
||||
@@ -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("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Sniff = require("@formats/core/Sniff")
|
||||
local Types = require("@formats/Types")
|
||||
local Deflate = require("@formats/codecs/compress/Deflate")
|
||||
local Zstd = require("@formats/codecs/compress/Zstd")
|
||||
local Texel = require("@formats/codecs/image/Texel")
|
||||
local Texture = require("@formats/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", "formats-luau" } }
|
||||
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
|
||||
@@ -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("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Pixels = require("@formats/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
|
||||
@@ -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("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Sniff = require("@formats/core/Sniff")
|
||||
local Types = require("@formats/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
|
||||
@@ -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("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Sniff = require("@formats/core/Sniff")
|
||||
local Types = require("@formats/Types")
|
||||
local Pixels = require("@formats/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
|
||||
@@ -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("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Sniff = require("@formats/core/Sniff")
|
||||
local Types = require("@formats/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
|
||||
@@ -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
|
||||
@@ -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("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Sniff = require("@formats/core/Sniff")
|
||||
local Types = require("@formats/Types")
|
||||
local Names = require("@formats/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
|
||||
Reference in new issue
Block a user