ws-tex: image/exr (read NONE/RLE/ZIPS/ZIP/PIZ, half/float/uint, scanline + tiled + multipart, mips; write NONE/ZIPS/ZIP)

Tested against the OpenEXR 3.5 python bindings, exrmaketiled (one level / mipmap / ripmap / round up),
exrmultipart, a hand-written subsampled file; PXR24 / B44 / DWAA give UNSUPPORTED; our files read back by
the bindings and exrheader. Broken / zeroed offset tables are rebuilt (exrmultipart writes them zeroed).
This commit is contained in:
4DBug committed 2026-10-31 14:43:02 -05:00
1 parent ef2cd93c88
commit abd01270f0
11 files changed
+1661

No files matched your search

+12
View File
@@ -38,6 +38,18 @@ local list: { Entry } = {
return require("@formats/image/dds")
end,
},
{
name = "exr",
category = "image",
path = "image/exr",
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 },
load = function()
return require("@formats/image/exr")
end,
},
{
name = "gif",
category = "image",
+117
View File
@@ -0,0 +1,117 @@
--!strict
--!native
--!optimize 2
-- image/exr/Codec: the OpenEXR byte-level codecs (from the OpenEXR file layout document and ImfZip / ImfRle, BSD-3-
-- Clause): RLE and ZIP / ZIPS decode (run lengths or zlib, then the delta predictor and the two-half byte interleave),
-- ZIP encode, and the per-line channel sample conversion to floats. Never throws.
local Deflate = require("@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
+367
View File
@@ -0,0 +1,367 @@
--!strict
--!native
--!optimize 2
-- image/exr/Piz: OpenEXR's PIZ decompressor (written from the OpenEXR 3.x sources' algorithm description: ImfPizCompressor
-- / ImfHuf / ImfWav, BSD-3-Clause, licenses/openexr-LICENSE.md): the range bitmap and its reverse LUT, the Huffman
-- stream (packed code lengths, canonical codes, the run-length symbol), the 2-D Haar wavelet (14- and 16-bit
-- variants) per channel plane, then the planes rearranged into scanlines. Never throws: nil, message on bad data.
local Piz = {}
local readu8, readu16, writeu16, readu32 = buffer.readu8, buffer.readu16, buffer.writeu16, buffer.readu32
local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift
local USHORT_RANGE, BITMAP_SIZE = 65536, 8192
local HUF_ENCSIZE = 65537
local DECBITS = 14
local SHORT_ZEROCODE_RUN, LONG_ZEROCODE_RUN, SHORTEST_LONG_RUN = 59, 63, 6
-- ------------------------------------------------------------------------------------------------ Huffman
-- the canonical code table: lengths[i] and codes[i] for symbols im..iM (1-based tables: symbol s at s + 1)
local function unpackTable(src: buffer, p: number, limit: number, im: number, iM: number, len: { number }): number?
local c, lc = 0, 0
local function bits(n: number): number?
while lc < n do
if p >= limit then
return nil
end
c = c * 256 + readu8(src, p)
p += 1
lc += 8
end
lc -= n
local v = c // 2 ^ lc
c -= v * 2 ^ lc
return v
end
local i = im
while i <= iM do
local l = bits(6)
if not l then
return nil
end
if l == LONG_ZEROCODE_RUN then
local z = bits(8)
if not z then
return nil
end
z += SHORTEST_LONG_RUN
if i + z > iM + 1 then
return nil
end
for k = i, i + z - 1 do
len[k + 1] = 0
end
i += z
elseif l >= SHORT_ZEROCODE_RUN then
local z = l - SHORT_ZEROCODE_RUN + 2
if i + z > iM + 1 then
return nil
end
for k = i, i + z - 1 do
len[k + 1] = 0
end
i += z
else
len[i + 1] = l
i += 1
end
end
return p
end
-- hufUncompress: nRaw u16 values from [p, p + n) into out (a buffer of u16) | nil, message
local function huffman(src: buffer, p: number, n: number, out: buffer, nRaw: number): string?
if n == 0 then
return if nRaw == 0 then nil else "empty Huffman data"
end
if n < 20 then
return "truncated Huffman header"
end
local im, iM, nBits = readu32(src, p), readu32(src, p + 4), readu32(src, p + 12)
if im >= HUF_ENCSIZE or iM >= HUF_ENCSIZE or im > iM then
return "bad Huffman symbol range"
end
local limit = p + n
local len = table.create(HUF_ENCSIZE, 0)
local q = unpackTable(src, p + 20, limit, im, iM, len)
if not q then
return "bad Huffman table"
end
if q + (nBits + 7) // 8 > limit then
return "truncated Huffman data"
end
-- canonical codes (OpenEXR's order: longest codes get the smallest values)
local count = table.create(59, 0)
for s = im, iM do
local l = len[s + 1]
if l > 58 then
return "bad Huffman code length"
end
count[l + 1] += 1
end
local start = table.create(59, 0)
local c = 0
for l = 58, 1, -1 do
local nc = (c + count[l + 1]) // 2
start[l + 1] = c
c = nc
end
local fast = buffer.create(lshift(1, DECBITS) * 4) -- (symbol + 1) * 64 + length; 0 = long or invalid
local long: { [number]: { [number]: number } } = {}
local maxLong = 0
for s = im, iM do
local l = len[s + 1]
if l > 0 then
local code = start[l + 1]
start[l + 1] = code + 1
if l <= DECBITS then
local base = code * 2 ^ (DECBITS - l)
local v = (s + 1) * 64 + l
for k = base, base + 2 ^ (DECBITS - l) - 1 do
if k < lshift(1, DECBITS) then
buffer.writeu32(fast, k * 4, v)
end
end
else
if l > 52 then
return "unsupported: Huffman code longer than 52 bits"
end
local t = long[l]
if not t then
t = {}
long[l] = t
end
t[code] = s
maxLong = math.max(maxLong, l)
end
end
end
-- decode MSB-first from a zero-padded copy
local nbytes = (nBits + 7) // 8
local data = buffer.create(nbytes + 8)
buffer.copy(data, 0, src, q, nbytes)
local bp = 0
local o = 0
local rlc = iM
local mask = lshift(1, DECBITS) - 1
while bp < nBits do
local byte = rshift(bp, 3)
local w = bit32.byteswap(readu32(data, byte))
local peek = band(rshift(w, 32 - DECBITS - band(bp, 7)), mask)
local e = readu32(fast, peek * 4)
local sym: number, l: number = 0, 0
if e ~= 0 then
sym = e // 64 - 1
l = band(e, 63)
else
-- a long code: bit by bit from length 15
sym = -1
local code = 0
for k = 0, maxLong - 1 do
local bitAt = bp + k
code = code * 2 + band(rshift(readu8(data, rshift(bitAt, 3)), 7 - band(bitAt, 7)), 1)
if k + 1 > DECBITS then
local t = long[k + 1]
local found: number? = if t then t[code] else nil
if found then
sym = found
l = k + 1
break
end
end
end
if sym < 0 then
return "invalid Huffman code"
end
end
bp += l
if bp > nBits then
return "Huffman code past the end of the data"
end
if sym == rlc then
if bp + 8 > nBits then
return "truncated run length"
end
local b2 = bit32.byteswap(readu32(data, rshift(bp, 3)))
local cs = band(rshift(b2, 24 - band(bp, 7)), 255)
bp += 8
if o + cs > nRaw then
return "too much Huffman data"
end
if o == 0 then
return "run length at the start"
end
local s = readu16(out, (o - 1) * 2)
for _ = 1, cs do
writeu16(out, o * 2, s)
o += 1
end
else
if o >= nRaw then
return "too much Huffman data"
end
writeu16(out, o * 2, sym)
o += 1
end
end
if o ~= nRaw then
return "not enough Huffman data"
end
return nil
end
-- ------------------------------------------------------------------------------------------------ wavelet
-- the inverse 2-D Haar wavelet over n x ny u16 values at element offset base, strides ox / oy (in elements)
local function wav2Decode(t: buffer, base: number, nx: number, ox: number, ny: number, oy: number, mx: number)
local w14 = mx < 16384
local n = math.min(nx, ny)
local p = 1
while p <= n do
p *= 2
end
p //= 2
local p2 = p
p //= 2
local function dec(l: number, h: number): (number, number)
if w14 then
local ls = if l >= 32768 then l - 65536 else l
local hs = if h >= 32768 then h - 65536 else h
local ai = ls + hs % 2 + hs // 2
return ai % 65536, (ai - hs) % 65536
end
local bb = (l - rshift(h, 1)) % 65536
return (h + bb - 32768) % 65536, bb
end
while p >= 1 do
local oy1, oy2, ox1, ox2 = oy * p, oy * p2, ox * p, ox * p2
local py = base
local ey = base + oy * (ny - p2)
while py <= ey do
local px = py
local ex = py + ox * (nx - p2)
while px <= ex do
local p01 = px + ox1
local p10 = px + oy1
local p11 = p10 + ox1
local i00, i10 = dec(readu16(t, px * 2), readu16(t, p10 * 2))
local i01, i11 = dec(readu16(t, p01 * 2), readu16(t, p11 * 2))
local a, b = dec(i00, i01)
writeu16(t, px * 2, a)
writeu16(t, p01 * 2, b)
local c, d = dec(i10, i11)
writeu16(t, p10 * 2, c)
writeu16(t, p11 * 2, d)
px += ox2
end
if band(nx, p) ~= 0 then
local p10 = px + oy1
local a, b = dec(readu16(t, px * 2), readu16(t, p10 * 2))
writeu16(t, px * 2, a)
writeu16(t, p10 * 2, b)
end
py += oy2
end
if band(ny, p) ~= 0 then
local px = py
local ex = py + ox * (nx - p2)
while px <= ex do
local p01 = px + ox1
local a, b = dec(readu16(t, px * 2), readu16(t, p01 * 2))
writeu16(t, px * 2, a)
writeu16(t, p01 * 2, b)
px += ox2
end
end
p2 = p
p //= 2
end
end
-- ------------------------------------------------------------------------------------------------ decode
export type Chan = { nx: number, ny: number, size: number, ys: number }
-- decode(src, p, n, chans, minY, maxY, outSize) -> the uncompressed block (scanline order) | nil, message.
-- chans: per channel (sorted order) its sample counts nx / ny in the block, size (1 = half, 2 = float / uint) and
-- ySampling.
function Piz.decode(src: buffer, p: number, n: number, chans: { Chan }, minY: number, maxY: number, outSize: number): (buffer?, string?)
local total = 0
for _, c in chans do
total += c.nx * c.ny * c.size
end
if total * 2 ~= outSize then
return nil, "PIZ block size mismatch"
end
local out = buffer.create(outSize)
if total == 0 then
return out, nil
end
local limit = p + n
if p + 4 > limit then
return nil, "truncated PIZ header"
end
local minNZ, maxNZ = readu16(src, p), readu16(src, p + 2)
p += 4
if maxNZ >= BITMAP_SIZE then
return nil, "bad PIZ bitmap range"
end
local bitmap = buffer.create(BITMAP_SIZE)
if minNZ <= maxNZ then
local cnt = maxNZ - minNZ + 1
if p + cnt > limit then
return nil, "truncated PIZ bitmap"
end
buffer.copy(bitmap, minNZ, src, p, cnt)
p += cnt
end
-- reverse LUT
local lut = buffer.create(USHORT_RANGE * 2)
local k = 0
for i = 0, USHORT_RANGE - 1 do
if i == 0 or band(readu8(bitmap, rshift(i, 3)), lshift(1, band(i, 7))) ~= 0 then
writeu16(lut, k * 2, i)
k += 1
end
end
local maxValue = k - 1
if p + 4 > limit then
return nil, "truncated PIZ length"
end
local length = readu32(src, p)
p += 4
if length > limit - p then
return nil, "truncated PIZ data"
end
local tmp = buffer.create(total * 2)
local herr = huffman(src, p, length, tmp, total)
if herr then
return nil, herr
end
local starts = table.create(#chans, 0)
local at = 0
for i, c in chans do
starts[i] = at
for j = 0, c.size - 1 do
wav2Decode(tmp, at + j, c.nx, c.size, c.ny, c.nx * c.size, maxValue)
end
at += c.nx * c.ny * c.size
end
for i = 0, total - 1 do
writeu16(tmp, i * 2, readu16(lut, readu16(tmp, i * 2) * 2))
end
-- planes -> scanlines
local o = 0
local cursor = table.clone(starts)
for y = minY, maxY do
for i, c in chans do
if y % c.ys == 0 then
local cnt = c.nx * c.size
buffer.copy(out, o, tmp, cursor[i] * 2, cnt * 2)
cursor[i] += cnt
o += cnt * 2
end
end
end
return out, nil
end
return Piz
+782
View File
@@ -0,0 +1,782 @@
--!strict
-- image/exr: OpenEXR (the OpenEXR file layout and technical introduction documents, openexr.com; new code, the PIZ
-- decoder written after OpenEXR's algorithm, BSD-3-Clause: licenses/openexr-LICENSE.md). Decode: single-part and
-- multipart files (opts.part: 1-based index or part name; meta.source.parts lists them), scanline and tiled parts
-- (one level, mip-map and rip-map levels: level 0, plus the mip-map levels into img.meta.mipmaps with opts.mips),
-- compression NONE / RLE / ZIPS / ZIP / PIZ, HALF / FLOAT / UINT channels, x / y subsampled channels (nearest), any
-- line order, broken offset tables (rebuilt from the chunks of single-part files). R / G / B / A map to the image
-- (opts.layer = "diffuse" reads diffuse.R ...); a Y-only image is grey; every channel name is in meta.source.channels.
-- The image is the data window (meta.dataWindow / meta.displayWindow keep both boxes). opts.native gives the linear
-- rgbaf32 values; the default rgba8 is a display conversion like image/hdr's: round(clamp(v, 0, 1) ^ (1 / 2.2) * 255)
-- for colour, round(clamp(a, 0, 1) * 255) for alpha.
-- Encode: rgbaf32 (or rgba8 through the inverse curve) as a scanline file, HALF (default) or FLOAT channels, A only
-- when some alpha is not 1, compression NONE, ZIPS or ZIP (default). Not supported: deep data, PXR24 / B44 / B44A /
-- DWAA / DWAB / HTJ2K / ZSTD compression (UNSUPPORTED naming the method), RY / BY chroma (the Y channel is used).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@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