diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 46d0547..48b6db4 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -7,6 +7,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build |---|---|---|---|---|---|---| | image | bmp | .bmp .dib | yes | yes | alpha: true, depths: 1, 2, 4, 8, 16, 24, 32, rle: true | `tests/image/bmp.luau` | | image | dds | .dds | yes | yes | alpha: true, float: true, mipmaps: true, cubemap: true, compressed: "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7" | `tests/image/dds.luau` | +| image | exr | .exr | yes | yes | alpha: true, float: true, hdr: true, depths: 16, 32, multipart: true, tiled: true | `tests/image/exr.luau` | | image | gif | .gif | yes | yes | animation: true, alpha: true, palette: true, depths: 1, 2, 4, 8 | `tests/image/gif.luau` | | image | hdr | .hdr .pic .rgbe | yes | yes | alpha: false, float: true, depths: 32 | `tests/image/hdr.luau` | | image | ico | .ico .cur | yes | yes | alpha: true, frames: true, depths: 1, 4, 8, 16, 24, 32 | `tests/image/ico.luau` | diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index 1fa543c..23e52ba 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -39,6 +39,7 @@ | `src/Formats/codecs/H264/` (Tables: CAVLC / CABAC / deblocking / scaling constant tables of ITU-T H.264, extracted from openh264 sources; the decoder itself is written from the spec) | openh264 2.x (Cisco) | BSD-2-Clause: [openh264-LICENSE.txt](openh264-LICENSE.txt) | | `tests/gen/h264_jvt` (downloaded at fixture time, not committed) | ITU-T H.264.1 / JVT conformance bitstreams (itu.int) | ITU-T test data | | `src/Formats/codecs/image/Bcn/Decode.luau` (the BC1..BC7 block decoders and the BPTC tables; changed to follow the D3D11 rules) | Pillow 12 `src/libImaging/BcnDecode.c` | CC0 1.0: [pillow-bcn-CC0.txt](pillow-bcn-CC0.txt) | +| `src/Formats/image/exr/Piz.luau`, `src/Formats/image/exr/Codec.luau` (the PIZ Huffman / wavelet / LUT steps and the ZIP / RLE byte predictor, re-implemented in Luau after the OpenEXR algorithms) | OpenEXR 3.x (ImfPizCompressor, ImfHuf, ImfWav, ImfZip, ImfRle) | BSD-3-Clause: [openexr-LICENSE.md](openexr-LICENSE.md) | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this folder (see docs/STYLE.md, "Absorbing an existing repo"). diff --git a/licenses/openexr-LICENSE.md b/licenses/openexr-LICENSE.md new file mode 100644 index 0000000..b2a016e --- /dev/null +++ b/licenses/openexr-LICENSE.md @@ -0,0 +1,11 @@ +Copyright (c) Contributors to the OpenEXR Project. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 718bbaa..beaefc8 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -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", diff --git a/src/Formats/image/exr/Codec.luau b/src/Formats/image/exr/Codec.luau new file mode 100644 index 0000000..a369338 --- /dev/null +++ b/src/Formats/image/exr/Codec.luau @@ -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 diff --git a/src/Formats/image/exr/Piz.luau b/src/Formats/image/exr/Piz.luau new file mode 100644 index 0000000..3016030 --- /dev/null +++ b/src/Formats/image/exr/Piz.luau @@ -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 diff --git a/src/Formats/image/exr/init.luau b/src/Formats/image/exr/init.luau new file mode 100644 index 0000000..58e4922 --- /dev/null +++ b/src/Formats/image/exr/init.luau @@ -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 .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 diff --git a/tests/image/exr.luau b/tests/image/exr.luau new file mode 100644 index 0000000..64078a5 --- /dev/null +++ b/tests/image/exr.luau @@ -0,0 +1,143 @@ +-- image/exr tests: files from the OpenEXR 3.5 bindings (NONE / RLE / ZIPS / ZIP / PIZ; HALF / FLOAT / UINT; offset +-- data window; decreasing lines; Y-only; a layer), a hand-written subsampled file, exrmaketiled tiles (one level, +-- mip-map, rip-map, round up) and exrmultipart parts against the bindings' reads; PXR24 / B44 / DWAA UNSUPPORTED; our +-- files read back by the bindings and exrheader; round trips; errors; the fuzz no-throw pass. Fixtures: +-- tools/fixtures/exr.py. +local T = require("@tests/T") +local Exr = require("@formats/image/exr") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/exr") + +local t = T.suite("exr") + +t:eq(Exr.name, "exr", "name") +t:check(Exr.caps.decode and Exr.caps.encode, "caps") + +local function dec(data: any, opts: any?): (any, any) + return Exr.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts) +end + +-- the largest difference between two rgbaf32 buffers (exact for HALF / FLOAT, UINT as their values) +local function worst(a: buffer, b: buffer, n: number): number + local m = 0 + for i = 0, n * 4 - 1 do + local x, y = buffer.readf32(a, i * 4), buffer.readf32(b, i * 4) + if x ~= y then + m = math.max(m, math.abs(x - y) / math.max(1, math.abs(y))) + end + end + return m +end + +for _, c in Fx.cases do + if c.unsupported then + local img, e = dec(c.data) + t:check(img == nil and e and e.code == Err.UNSUPPORTED, c.name .. ": UNSUPPORTED (" .. tostring(e) .. ")") + continue + end + local opts = { native = true, layer = c.layer, part = c.part, mips = c.mips } + local img, err = dec(c.data, opts) + t:check(img, c.name .. ": " .. tostring(err)) + t:check(img.width == c.w and img.height == c.h and img.format == "rgbaf32", c.name .. ": size") + local d = worst(img.pixels, buffer.fromstring(c.floats), c.w * c.h) + t:check(d < 1e-6, string.format("%s: off by %g", c.name, d)) + if c.partName then + local byName = dec(c.data, { native = true, part = c.partName }) + t:check(byName and buffer.tostring(byName.pixels) == buffer.tostring(img.pixels), c.name .. ": part by name") + t:eq(img.meta.source.parts[c.part].name, c.partName, c.name .. ": part names") + end + if c.mips and string.find(c.name, "mip") then + local mm = img.meta.mipmaps + t:check(mm and #mm >= 5, c.name .. ": mip levels") + local up = string.find(c.name, "up") ~= nil + t:eq(mm[1].width, if up then math.ceil(c.w / 2) else c.w // 2, c.name .. ": level 1 width") + end + -- the rgba8 display conversion + local d8 = dec(c.data, { layer = c.layer, part = c.part }) + t:eq(d8.format, "rgba8", c.name .. ": rgba8 by default") +end +t:note("%d files match the OpenEXR bindings", #Fx.cases) + +-- the window, the attributes +do + for _, c in Fx.cases do + if c.name == "window_zip.exr" then + local img = dec(c.data) + t:check(img.meta.dataWindow.x == 5 and img.meta.dataWindow.y == -3, "data window origin") + t:check(img.meta.displayWindow.width == 40 and img.meta.displayWindow.height == 20, "display window") + t:eq(img.meta.source.compression, "zip", "compression name") + end + end +end + +-- our files: the bindings read our values back, exrheader accepts them +for _, o in Fx.ours do + t:check(o.headerOk, o.name .. ": exrheader") + local img = dec(o.data, { native = true }) + local n = img.width * img.height + local d = worst(img.pixels, buffer.fromstring(o.floats), n) + t:check(d == 0, string.format("%s: the bindings read %g off our decode", o.name, d)) +end +t:note("%d of our files read back by the OpenEXR bindings", #Fx.ours) + +-- round trips: FLOAT exactly, HALF to half precision +do + local f = Types.Image.new(13, 9, "rgbaf32") + local rand = T.rng(5) + for i = 0, 13 * 9 * 4 - 1 do + buffer.writef32(f.pixels, i * 4, (rand(20000) - 5000) / 997) + end + for _, comp in { "none", "zips", "zip" } do + local back = dec(Exr.encode(f, { compression = comp :: any, pixelType = "float" }) :: buffer, { native = true }) + t:eq(buffer.tostring(back.pixels), buffer.tostring(f.pixels), comp .. ": float round trip") + local hb = dec(Exr.encode(f, { compression = comp :: any }) :: buffer, { native = true }) + t:check(worst(hb.pixels, f.pixels, 13 * 9) < 1e-3, comp .. ": half round trip") + end + local img8 = Types.Image.new(4, 4) + for i = 0, 63 do + buffer.writeu8(img8.pixels, i, (i * 37) % 256) + end + local back8 = dec(Exr.encode(img8, { pixelType = "float" }) :: buffer) + local ok = true + for i = 0, 63 do + ok = ok and math.abs(buffer.readu8(back8.pixels, i) - buffer.readu8(img8.pixels, i)) <= 1 + end + t:check(ok, "rgba8 through the display curve and back") + local _, e = Exr.encode(f, { compression = "piz" :: any }) + t:check(e and e.code == Err.ARG, "no PIZ encoder") +end + +-- sniff, info, errors +do + local c = Fx.cases[1] + t:eq(Exr.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, "sniff") + t:eq(Exr.sniff(Bytes.reader(buffer.fromstring("v/1\0"))), 0, "sniff other") + local info = Exr.info(Bytes.reader(buffer.fromstring(c.data))) + t:check(info and #info.parts == 1 and #info.parts[1].channels == 4, "info") + local _, e = dec(string.sub(c.data, 1, 40)) + t:check(e and e.code == Err.TRUNCATED, "short header: " .. tostring(e)) + local _, e2 = dec(c.data, { maxPixels = 10 }) + t:check(e2 and e2.code == Err.LIMIT, "limit") + local _, e3 = dec(c.data, { part = 3 }) + t:check(e3 and e3.code == Err.ARG, "no such part") + -- a zeroed offset table is rebuilt + local b = buffer.fromstring(c.data) + local info2 = Exr.info(Bytes.reader(b)) :: any + local tab = info2.dataStart - 8 * info2.parts[1].chunks + buffer.fill(b, tab, 0, 8 * info2.parts[1].chunks) + local img = dec(b, { native = true }) + t:check(img and buffer.tostring(img.pixels) == buffer.tostring(dec(c.data, { native = true }).pixels), "rebuilt offset table") +end + +local samples = {} +for i, c in Fx.cases do + if i % 3 == 0 or c.unsupported then + table.insert(samples, c.data) + end +end +t:fuzz("decode", function(b: buffer) + return dec(b, { mips = true }) +end, samples, { mutations = 6 }) +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index 5486408..6f108fd 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -1102,3 +1102,20 @@ do Bcn.decode("bc6h", b6, 0, w, h) end) end +do + -- OpenEXR (ws-tex): a 512 x 256 half RGBA image from the OpenEXR bindings (tools/fixtures/exr.py), ZIP and PIZ; + -- MB/s of rgbaf32 output; our ZIP encoder on the decoded floats + local Exr = require("@formats/image/exr") + local EB = require("@tests/gen/exr_bench") + local n = 512 * 256 * 16 + for _, k in { "zip", "piz" } do + local data = buffer.fromstring(EB[k]) + bench("exr decode " .. k .. " 512x256 half", 3, n, function() + Exr.decode(Bytes.reader(data), { native = true }) + end) + end + local img = Exr.decode(Bytes.reader(buffer.fromstring(EB.zip)), { native = true }) :: any + bench("exr encode zip 512x256 half", 2, n, function() + Exr.encode(img) + end) +end diff --git a/tools/fixtures/_tex_encode.luau b/tools/fixtures/_tex_encode.luau index 14a7df0..4c21f24 100644 --- a/tools/fixtures/_tex_encode.luau +++ b/tools/fixtures/_tex_encode.luau @@ -93,3 +93,18 @@ if which == "ktx" then cube.meta.layout = "array" emit("ours_array.ktx2", Ktx.encode(cube)) end + +if which == "exr" then + local Exr = require("@formats/image/exr") + local f = image(37, 23, "rgbaf32", 0, 4) + for _, c in { "none", "zips", "zip" } do + emit("ours_half_" .. c .. ".exr", Exr.encode(f, { compression = c :: any })) + emit("ours_float_" .. c .. ".exr", Exr.encode(f, { compression = c :: any, pixelType = "float" })) + end + local opaque = image(20, 40, "rgbaf32", 1, 2) + for i = 0, 20 * 40 - 1 do + buffer.writef32(opaque.pixels, i * 16 + 12, 1) + end + emit("ours_rgb_zip.exr", Exr.encode(opaque)) + emit("ours_from_rgba8.exr", Exr.encode(image(16, 16, "rgba8", 2))) +end diff --git a/tools/fixtures/exr.py b/tools/fixtures/exr.py new file mode 100644 index 0000000..1281c4d --- /dev/null +++ b/tools/fixtures/exr.py @@ -0,0 +1,195 @@ +# OpenEXR fixtures (tools/fixtures.py): files written by the OpenEXR 3.5 python bindings (every compression NONE / +# RLE / ZIPS / ZIP / PIZ, HALF / FLOAT / UINT channels, odd sizes, an offset data window, decreasing line order, a +# Y-only image, a layer (diffuse.R ...), subsampled channels, PXR24 / B44 / DWAA for the UNSUPPORTED path), tiled +# versions by exrmaketiled (one level, mip-map with unfiltered levels, rip-map, round up, several compressions), +# multipart files by exrmultipart; our encoder's files (tools/fixtures/_tex_encode.luau -a exr) read back by the +# bindings and exrheader. References: the bindings' read of each file (RGBA as little-endian f32; Y as grey). +# tests/gen/exr.luau { cases = { { name, data, w, h, floats?, unsupported?, opts?, mips? } }, ours = { { name, +# data, floats, compression, header_ok } } } +# tests/gen/exr_bench.luau a 512 x 256 half RGBA image in ZIP and PIZ +import os, shutil, subprocess, tempfile + +INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/exr"] + +WRITE = r''' +import OpenEXR, numpy as np, os, sys, json +w = sys.argv[1] +rng = np.random.default_rng(3) +def win(x0, y0, x1, y1): + return (np.array([x0, y0], dtype=np.int32), np.array([x1, y1], dtype=np.int32)) +def img(h, wd, kind="f2"): + y, x = np.mgrid[0:h, 0:wd] + r = (x / max(1, wd - 1)) * 3 - 0.5 + g = np.sin(y * 0.7) * 0.5 + 0.5 + b = rng.random((h, wd)) * 0.01 + (x * y % 7) * 0.2 + a = ((x + y) % 4) / 3.0 + return [c.astype(kind) for c in (r, g, b, a)] +def save(name, header, channels): + h = {"type": OpenEXR.scanlineimage} + h.update(header) + OpenEXR.File(h, channels).write(os.path.join(w, name)) +C = {"none": OpenEXR.NO_COMPRESSION, "rle": OpenEXR.RLE_COMPRESSION, "zips": OpenEXR.ZIPS_COMPRESSION, + "zip": OpenEXR.ZIP_COMPRESSION, "piz": OpenEXR.PIZ_COMPRESSION} +names = [] +for cn, c in C.items(): + r, g, b, a = img(23, 37) + save("half_rgba_%s.exr" % cn, {"compression": c}, {"R": r, "G": g, "B": b, "A": a}) + r, g, b, a = img(19, 41, "f4") + save("float_rgb_%s.exr" % cn, {"compression": c}, {"R": r, "G": g, "B": b}) + r, g, b, a = img(37, 70) + u = (rng.random((37, 70)) * 100000).astype("uint32") + save("mixed_%s.exr" % cn, {"compression": c, "lineOrder": OpenEXR.DECREASING_Y}, {"R": r, "G": g.astype("f4"), "B": u}) + names += ["half_rgba_%s.exr" % cn, "float_rgb_%s.exr" % cn, "mixed_%s.exr" % cn] +r, g, b, a = img(20, 30) +save("window_zip.exr", {"compression": C["zip"], "dataWindow": win(5, -3, 34, 16), "displayWindow": win(0, 0, 39, 19)}, {"R": r, "G": g, "B": b, "A": a}) +save("grey_piz.exr", {"compression": C["piz"]}, {"Y": r}) +save("layer_zips.exr", {"compression": C["zips"]}, {"diffuse.R": r, "diffuse.G": g, "diffuse.B": b, "R": a, "G": a, "B": a}) +r, g, b, a = img(64, 96) +save("big_piz.exr", {"compression": C["piz"]}, {"R": r, "G": g, "B": b, "A": a}) +save("big_zip.exr", {"compression": C["zip"]}, {"R": r, "G": g, "B": b, "A": a}) +names += ["window_zip.exr", "grey_piz.exr", "layer_zips.exr", "big_piz.exr", "big_zip.exr"] +y, x = np.mgrid[0:16, 0:24] +Y = (x / 23.0).astype("f2") +sub = (np.mgrid[0:8, 0:12][1] / 11.0).astype("f2") +# subsampled: hand-written (the bindings only write full-resolution channels): NONE, A at 2 x 2, R / G / B full +import struct +def attr(n, t, d): + return n.encode() + b"\0" + t.encode() + b"\0" + struct.pack(" 3 and name.startswith("layer") else "" + px = np.zeros((H, W, 4), dtype="f4") + px[:, :, 3] = 1 + def get(n): + c = ch.get(layer + n) + if c is None: + return None + p = c.pixels.astype("f4") + if p.shape != (H, W): + p = np.repeat(np.repeat(p, c.ySampling, axis=0), c.xSampling, axis=1)[:H, :W] + return p + if get("R") is None and get("Y") is not None: + for k in range(3): + px[:, :, k] = get("Y") + for k, n in enumerate("RGBA"): + p = get(n) + if p is not None: + px[:, :, k] = p + out[name] = {"w": W, "h": H, "floats": px.tobytes().hex(), "compression": str(hdr["compression"]).split(".")[-1]} +print(json.dumps(out)) +''' + + +def generate(ctx): + work = tempfile.mkdtemp(prefix="formats-exr-") + try: + _generate(ctx, work) + finally: + shutil.rmtree(work, ignore_errors=True) + + +def py(ctx, code, *args): + expr = "with import {}; python3.withPackages (p: [p.openexr p.numpy])" + res = subprocess.run(["nix", "shell", "--impure", "--expr", expr, "-c", "python3", "-I", "-c", code] + list(args), capture_output=True) + if res.returncode: + raise RuntimeError("OpenEXR bindings failed: " + res.stderr.decode()[-2000:]) + return res.stdout + + +def _generate(ctx, work): + import json + names = json.loads(py(ctx, WRITE, work)) + tiled = [] + sh = [] + for cn in ("none", "rle", "zip", "piz"): + sh.append("exrmaketiled -o -t 16 8 -z %s half_rgba_zip.exr tiled_%s.exr" % (cn, cn)) + tiled.append("tiled_%s.exr" % cn) + sh.append("exrmaketiled -m -t 8 8 -z zip -f R -f G -f B -f A half_rgba_zip.exr tiled_mip.exr") + sh.append("exrmaketiled -m -u -t 8 8 -z piz half_rgba_zip.exr tiled_mip_up.exr") + sh.append("exrmaketiled -r -t 16 16 -z zips half_rgba_zip.exr tiled_rip.exr") + sh.append("exrmaketiled -o -t 8 8 -z zip float_rgb_none.exr tiled_float.exr") + sh.append("exrmaketiled -o -t 7 5 -z zip window_zip.exr tiled_window.exr") + tiled += ["tiled_mip.exr", "tiled_mip_up.exr", "tiled_rip.exr", "tiled_float.exr", "tiled_window.exr"] + sh.append("exrmultipart -combine -i half_rgba_piz.exr::left half_rgba_rle.exr::right tiled_zip.exr::tiles -o multipart.exr") + ctx.nix("openexr", ["sh", "-c", "cd %s && %s" % (work, " && ".join(sh))]) + ref = json.loads(py(ctx, READ, work, json.dumps(names + tiled), "diffuse.")) + cases = [] + for n in names + tiled: + r = ref[n] + c = {"name": n, "data": open(os.path.join(work, n), "rb").read(), "w": r["w"], "h": r["h"], "floats": bytes.fromhex(r["floats"])} + if n.startswith("layer"): + c["layer"] = "diffuse" + if n.startswith("tiled_mip") or n.startswith("tiled_rip"): + c["mips"] = True + cases.append(c) + # multipart: every part against the file it came from + mp = open(os.path.join(work, "multipart.exr"), "rb").read() + for i, (src, pname) in enumerate((("half_rgba_piz.exr", "left"), ("half_rgba_rle.exr", "right"), ("tiled_zip.exr", "tiles"))): + r = ref[src] + cases.append({"name": "multipart part %d (%s)" % (i + 1, pname), "data": mp, "part": i + 1, "partName": pname, + "w": r["w"], "h": r["h"], "floats": bytes.fromhex(r["floats"])}) + for cn in ("pxr24", "b44", "dwaa"): + cases.append({"name": "unsupported_%s.exr" % cn, "data": open(os.path.join(work, "unsupported_%s.exr" % cn), "rb").read(), "unsupported": True}) + ours = _ours(ctx, work) + ctx.emit("exr", {"cases": cases, "ours": ours}) + ctx.emit("exr_bench", {"zip": open(os.path.join(work, "bench_zip.exr"), "rb").read(), "piz": open(os.path.join(work, "bench_piz.exr"), "rb").read()}) + + +def _ours(ctx, work): + import json + exe = shutil.which("luau") + cmd = [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"] + res = subprocess.run(cmd + ["tools/fixtures/_tex_encode.luau", "-a", "exr"], cwd=ctx.root, capture_output=True, check=True) + files = {} + for line in res.stdout.decode().split("\n"): + if "\t" in line: + n, hx = line.split("\t", 1) + files[n] = bytes.fromhex(hx.strip()) + names = sorted(files) + for n in names: + open(os.path.join(work, n), "wb").write(files[n]) + ref = json.loads(py(ctx, READ, work, json.dumps(names))) + rc = ctx.nix("openexr", ["sh", "-c", "cd %s && for f in %s; do exrheader $f > /dev/null 2>&1; echo $f $?; done" % (work, " ".join(names))]).decode() + ok = {line.split()[0]: line.split()[1] == "0" for line in rc.strip().split("\n")} + return [{"name": n, "data": files[n], "floats": bytes.fromhex(ref[n]["floats"]), "compression": ref[n]["compression"], "headerOk": ok.get(n, False)} for n in names]