From b2dd3475ac14f3cda41f12039ca036bd980ed4e4 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:50:42 -0500 Subject: [PATCH 1/2] imgA-tiff: image/tiff read (strips/tiles, planar, LZW/Deflate/PackBits/JPEG via hook, predictors 2/3, 1-32 bit int + 16/32/64 float, palette, CMYK, alpha, BigTIFF, pages) and write (none/deflate/lzw/packbits, predictors, multi-page); tifffile + ImageMagick fixtures --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/image/tiff/Pixels.luau | 469 ++++++++++++++++ src/Formats/image/tiff/init.luau | 841 +++++++++++++++++++++++++++++ tests/image/tiff.luau | 172 ++++++ tools/fixtures/tiff.py | 219 ++++++++ 6 files changed, 1714 insertions(+) create mode 100644 src/Formats/image/tiff/Pixels.luau create mode 100644 src/Formats/image/tiff/init.luau create mode 100644 tests/image/tiff.luau create mode 100644 tools/fixtures/tiff.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 17d4818..89c6ef4 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -6,6 +6,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | Category | Format | Extensions | Read | Write | Capabilities | Test | |---|---|---|---|---|---|---| | image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | +| image | tiff | .tif .tiff | yes | yes | alpha: true, pages: true, depths: 1, 2, 4, 8, 16, 32, float: true | `tests/image/tiff.luau` | Codecs (layer 1, shared by formats; not loadable on their own): diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index ba09f70..5b6ef27 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -26,6 +26,18 @@ local list: { Entry } = { return require("@formats/image/png") end, }, + { + name = "tiff", + category = "image", + path = "image/tiff", + extensions = { "tif", "tiff" }, + mime = { "image/tiff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate", "codecs/Lzw" }, + caps = { decode = true, encode = true, alpha = true, pages = true, depths = { 1, 2, 4, 8, 16, 32 }, float = true }, + load = function() + return require("@formats/image/tiff") + end, + }, } return list diff --git a/src/Formats/image/tiff/Pixels.luau b/src/Formats/image/tiff/Pixels.luau new file mode 100644 index 0000000..6ae16d4 --- /dev/null +++ b/src/Formats/image/tiff/Pixels.luau @@ -0,0 +1,469 @@ +--!strict +--!native +--!optimize 2 +-- image/tiff/Pixels: the hot loops of the TIFF codec (native; never throws): PackBits, the horizontal (2) and +-- floating-point (3) predictors both ways (TIFF 6.0 section 14, Adobe TIFF technote 3; predictor 3 as libtiff's +-- fpAcc / fpDiff), fill-order bit reversal, and the sample converter from decoded planes to a Types.Image layout. +-- Callers (image/tiff/init) size every buffer before calling: planes hold h rows of rb bytes plus 8 bytes of slack. +local readu8, writeu8, readu16, writeu16, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32, buffer.writeu32 +local readf32, writef32, readf64 = buffer.readf32, buffer.writef32, buffer.readf64 +local band, bor, rshift, lshift, byteswap = bit32.band, bit32.bor, bit32.rshift, bit32.lshift, bit32.byteswap +local floor = math.floor + +local Pixels = {} + +local scratch = buffer.create(8) + +-- floats read through their bits: NaN / infinity never load from memory (LuaJIT's FFI would hand back a NaN with an +-- arbitrary payload, which its NaN-tagged values misread as a table / userdata) +local function f32(bits: number): number + if band(bits, 0x7F800000) == 0x7F800000 then + if band(bits, 0x7FFFFF) ~= 0 then + return 0 / 0 + end + return if bits >= 0x80000000 then -math.huge else math.huge + end + writeu32(scratch, 0, bits) + return readf32(scratch, 0) +end +local function f64(lo: number, hi: number): number + if band(hi, 0x7FF00000) == 0x7FF00000 then + if band(hi, 0xFFFFF) ~= 0 or lo ~= 0 then + return 0 / 0 + end + return if hi >= 0x80000000 then -math.huge else math.huge + end + writeu32(scratch, 0, lo) + writeu32(scratch, 4, hi) + return readf64(scratch, 0) +end +Pixels.f32 = f32 +Pixels.f64 = f64 + +-- ------------------------------------------------------------------------------------------------ PackBits +-- packbits(src, off, len, out, outOff, max) -> bytes written (stops when out or src is exhausted) +function Pixels.packbits(src: buffer, off: number, len: number, out: buffer, outOff: number, max: number): number + local p, e = off, off + len + local o, lim = outOff, outOff + max + while p < e and o < lim do + local n = readu8(src, p) + p += 1 + if n < 128 then + local cnt = math.min(n + 1, e - p, lim - o) + if cnt <= 0 then + break + end + buffer.copy(out, o, src, p, cnt) + p += n + 1 + o += cnt + elseif n > 128 then + if p >= e then + break + end + local cnt = math.min(257 - n, lim - o) + buffer.fill(out, o, readu8(src, p), cnt) + p += 1 + o += cnt + end + end + return o - outOff +end + +-- packbitsEncode(src, off, len) -> buffer (one row at a time is the caller's business) +function Pixels.packbitsEncode(src: buffer, off: number, len: number): buffer + local out = buffer.create(len + (len + 127) // 128 + 8) + local o = 0 + local p, e = off, off + len + while p < e do + local run = 1 + local v = readu8(src, p) + while p + run < e and run < 128 and readu8(src, p + run) == v do + run += 1 + end + if run >= 3 then + writeu8(out, o, 257 - run) + writeu8(out, o + 1, v) + o += 2 + p += run + else + local s = p + local n = 0 + while p < e and n < 128 do + if p + 2 < e and readu8(src, p) == readu8(src, p + 1) and readu8(src, p) == readu8(src, p + 2) then + break + end + p += 1 + n += 1 + end + writeu8(out, o, n - 1) + buffer.copy(out, o + 1, src, s, n) + o += n + 1 + end + end + local r = buffer.create(o) + buffer.copy(r, 0, out, 0, o) + return r +end + +-- ------------------------------------------------------------------------------------------------ fill order +local REV = buffer.create(256) +for i = 0, 255 do + local r = 0 + for k = 0, 7 do + if band(i, lshift(1, k)) ~= 0 then + r = bor(r, lshift(1, 7 - k)) + end + end + writeu8(REV, i, r) +end +function Pixels.reverseBits(b: buffer, off: number, len: number) + for i = off, off + len - 1 do + writeu8(b, i, readu8(REV, readu8(b, i))) + end +end + +-- ------------------------------------------------------------------------------------------------ predictors +-- unpredict2(b, off, rows, rb, stride, bps, le): undo horizontal differencing (bps 8, 16 or 32; others untouched) +function Pixels.unpredict2(b: buffer, off: number, rows: number, rb: number, stride: number, bps: number, le: boolean) + for r = 0, rows - 1 do + local base = off + r * rb + if bps == 8 then + for i = base + stride, base + rb - 1 do + writeu8(b, i, band(readu8(b, i) + readu8(b, i - stride), 255)) + end + elseif bps == 16 then + local n = rb // 2 + for k = stride, n - 1 do + local i = base + k * 2 + local j = i - stride * 2 + if le then + writeu16(b, i, band(readu16(b, i) + readu16(b, j), 0xFFFF)) + else + local v = readu8(b, i) * 256 + readu8(b, i + 1) + readu8(b, j) * 256 + readu8(b, j + 1) + writeu8(b, i, band(rshift(v, 8), 255)) + writeu8(b, i + 1, band(v, 255)) + end + end + elseif bps == 32 then + local n = rb // 4 + for k = stride, n - 1 do + local i = base + k * 4 + local j = i - stride * 4 + if le then + writeu32(b, i, (readu32(b, i) + readu32(b, j)) % 4294967296) + else + writeu32(b, i, byteswap((byteswap(readu32(b, i)) + byteswap(readu32(b, j))) % 4294967296)) + end + end + end + end +end + +-- predict2(b, off, rows, rb, stride, bps): apply horizontal differencing to little-endian samples (8 / 16 bit) +function Pixels.predict2(b: buffer, off: number, rows: number, rb: number, stride: number, bps: number) + for r = 0, rows - 1 do + local base = off + r * rb + if bps == 8 then + for i = base + rb - 1, base + stride, -1 do + writeu8(b, i, band(readu8(b, i) - readu8(b, i - stride), 255)) + end + elseif bps == 16 then + for k = rb // 2 - 1, stride, -1 do + local i = base + k * 2 + writeu16(b, i, band(readu16(b, i) - readu16(b, i - stride * 2), 0xFFFF)) + end + end + end +end + +-- unpredict3(b, off, rows, rb, bytes, stride, tmp): undo the floating-point predictor; the samples come out little +-- endian whatever the file's byte order (libtiff fpAcc). tmp holds at least rb bytes. +function Pixels.unpredict3(b: buffer, off: number, rows: number, rb: number, bytes: number, stride: number, tmp: buffer) + local wc = rb // bytes + for r = 0, rows - 1 do + local base = off + r * rb + for i = base + stride, base + rb - 1 do + writeu8(b, i, band(readu8(b, i) + readu8(b, i - stride), 255)) + end + buffer.copy(tmp, 0, b, base, rb) + for c = 0, wc - 1 do + for k = 0, bytes - 1 do + writeu8(b, base + c * bytes + k, readu8(tmp, (bytes - k - 1) * wc + c)) + end + end + end +end + +-- predict3(b, off, rows, rb, bytes, stride, tmp): the floating-point predictor on little-endian samples (fpDiff) +function Pixels.predict3(b: buffer, off: number, rows: number, rb: number, bytes: number, stride: number, tmp: buffer) + local wc = rb // bytes + for r = 0, rows - 1 do + local base = off + r * rb + for c = 0, wc - 1 do + for k = 0, bytes - 1 do + writeu8(tmp, (bytes - k - 1) * wc + c, readu8(b, base + c * bytes + k)) + end + end + buffer.copy(b, base, tmp, 0, rb) + for i = base + rb - 1, base + stride, -1 do + writeu8(b, i, band(readu8(b, i) - readu8(b, i - stride), 255)) + end + end +end + +-- ------------------------------------------------------------------------------------------------ samples +local function half(h: number): number + local s = if h >= 0x8000 then -1 else 1 + local e = band(rshift(h, 10), 31) + local m = band(h, 1023) + if e == 0 then + return s * m * 2 ^ -24 + elseif e == 31 then + return if m == 0 then s * math.huge else 0 / 0 + end + return s * (1 + m / 1024) * 2 ^ (e - 15) +end + +export type Params = { + planes: { buffer }, + rb: number, -- bytes per row in each plane + chunky: boolean, + w: number, + h: number, + spp: number, + bps: number, + sfmt: number, -- 1 uint, 2 int, 3 float + le: boolean, + photo: number, -- 0 min-is-white, 1 min-is-black, 2 RGB, 3 palette, 5 CMYK + alpha: number, -- sample index of the alpha channel, -1 = none + assoc: boolean, -- premultiplied alpha (undone) + cmap: buffer?, -- palette: 3 * 2^bps u16 (red block, green block, blue block) + kind: string, -- the output pixel format + out: buffer, +} + +-- the common 8-bit chunky cases without per-sample dispatch; false when P is not one of them +local function fast(P: Params): boolean + if not P.chunky or P.bps ~= 8 or P.sfmt ~= 1 or P.assoc then + return false + end + local b, rb, w, h, spp, alpha, kind, out = P.planes[1], P.rb, P.w, P.h, P.spp, P.alpha, P.kind, P.out + local o = 0 + if P.photo == 2 and spp >= 3 and (kind == "rgba8" or kind == "rgb8") then + local four = kind == "rgba8" + for y = 0, h - 1 do + local p = y * rb + for _ = 0, w - 1 do + writeu8(out, o, readu8(b, p)) + writeu8(out, o + 1, readu8(b, p + 1)) + writeu8(out, o + 2, readu8(b, p + 2)) + if four then + writeu8(out, o + 3, if alpha >= 0 then readu8(b, p + alpha) else 255) + o += 4 + else + o += 3 + end + p += spp + end + end + return true + elseif (P.photo == 1 or P.photo == 0) and (kind == "rgba8" or kind == "gray8" or kind == "graya8") then + local inv = if P.photo == 0 then 255 else 0 + for y = 0, h - 1 do + local p = y * rb + for _ = 0, w - 1 do + local v = math.abs(inv - readu8(b, p)) + if kind == "gray8" then + writeu8(out, o, v) + o += 1 + elseif kind == "graya8" then + writeu8(out, o, v) + writeu8(out, o + 1, if alpha >= 0 then readu8(b, p + alpha) else 255) + o += 2 + else + writeu32(out, o, v * 0x10101 + (if alpha >= 0 then readu8(b, p + alpha) else 255) * 0x1000000) + o += 4 + end + p += spp + end + end + return true + end + return false +end + +-- convert(P): every pixel into P.out in P.kind's layout +function Pixels.convert(P: Params) + if fast(P) then + return + end + local planes, rb, chunky, w, h, spp, bps, sfmt, le = P.planes, P.rb, P.chunky, P.w, P.h, P.spp, P.bps, P.sfmt, P.le + local photo, alpha, assoc, cmap, kind, out = P.photo, P.alpha, P.assoc, P.cmap, P.kind, P.out + local maxv = 2 ^ math.min(bps, 32) - 1 + local float = sfmt == 3 + local signed = sfmt == 2 + local cmapN = 2 ^ math.min(bps, 16) + -- raw sample s of pixel x in the row starting at byte ro of its plane + local function raw(s: number, x: number, row: number): number + local b, i + if chunky then + b, i = planes[1], x * spp + s + else + b, i = planes[s + 1], x + end + local ro = row * rb + if bps == 8 then + local v = readu8(b, ro + i) + return if signed then (v + 128) % 256 else v + elseif bps == 16 then + local p = ro + i * 2 + local v = if le then readu16(b, p) else readu8(b, p) * 256 + readu8(b, p + 1) + if float then + return half(v) + end + return if signed then (v + 32768) % 65536 else v + elseif bps == 32 then + local p = ro + i * 4 + if float then + return f32(if le then readu32(b, p) else byteswap(readu32(b, p))) + end + local v = if le then readu32(b, p) else byteswap(readu32(b, p)) + return if signed then (v + 2147483648) % 4294967296 else v + elseif bps == 64 then + local p = ro + i * 8 + if le then + return f64(readu32(b, p), readu32(b, p + 4)) + end + return f64(byteswap(readu32(b, p + 4)), byteswap(readu32(b, p))) + else + -- any other depth (1..31): MSB-first bit fields + local bit = i * bps + local v = 0 + local need = bps + local p = ro + rshift(bit, 3) + local sh = band(bit, 7) + local cur = band(readu8(b, p), rshift(255, sh)) + local avail = 8 - sh + while need > 0 do + if need >= avail then + v = v * 2 ^ avail + cur + need -= avail + p += 1 + cur = if need > 0 then readu8(b, p) else 0 + avail = 8 + else + v = v * 2 ^ need + rshift(cur, avail - need) + need = 0 + end + end + return v + end + end + -- normalised 0..1 (floats as stored) + local function norm(s: number, x: number, row: number): number + local v = raw(s, x, row) + if float then + return v + end + return v / maxv + end + local o = 0 + local is8 = kind == "rgba8" or kind == "rgb8" or kind == "gray8" or kind == "graya8" + local is16 = kind == "rgba16" or kind == "gray16" + local nch = if kind == "rgba8" or kind == "rgba16" or kind == "rgbaf32" then 4 elseif kind == "rgb8" then 3 elseif kind == "graya8" then 2 else 1 + for y = 0, h - 1 do + for x = 0, w - 1 do + local r, g, bl, a + if photo == 3 then + local idx = raw(0, x, y) + if cmap and idx < cmapN then + r = readu16(cmap, idx * 2) / 65535 + g = readu16(cmap, (cmapN + idx) * 2) / 65535 + bl = readu16(cmap, (2 * cmapN + idx) * 2) / 65535 + else + r, g, bl = 0, 0, 0 + end + elseif photo == 2 then + r, g, bl = norm(0, x, y), norm(1, x, y), norm(2, x, y) + elseif photo == 5 then + local c, m, ye, k = norm(0, x, y), norm(1, x, y), norm(2, x, y), norm(3, x, y) + r, g, bl = (1 - c) * (1 - k), (1 - m) * (1 - k), (1 - ye) * (1 - k) + else + local v = norm(0, x, y) + if photo == 0 then + v = 1 - v + end + r, g, bl = v, v, v + end + if alpha >= 0 then + a = norm(alpha, x, y) + if assoc then + if a > 0 then + r, g, bl = math.min(r / a, 1), math.min(g / a, 1), math.min(bl / a, 1) + else + r, g, bl = 0, 0, 0 + end + end + else + a = 1 + end + if is8 then + if r ~= r then + r = 0 + end + if g ~= g then + g = 0 + end + if bl ~= bl then + bl = 0 + end + if a ~= a then + a = 0 + end + local R = floor(math.clamp(r, 0, 1) * 255 + 0.5) + if nch == 1 then + writeu8(out, o, R) + elseif nch == 2 then + writeu8(out, o, R) + writeu8(out, o + 1, floor(math.clamp(a, 0, 1) * 255 + 0.5)) + else + writeu8(out, o, R) + writeu8(out, o + 1, floor(math.clamp(g, 0, 1) * 255 + 0.5)) + writeu8(out, o + 2, floor(math.clamp(bl, 0, 1) * 255 + 0.5)) + if nch == 4 then + writeu8(out, o + 3, floor(math.clamp(a, 0, 1) * 255 + 0.5)) + end + end + o += nch + elseif is16 then + if r ~= r then + r = 0 + end + if g ~= g then + g = 0 + end + if bl ~= bl then + bl = 0 + end + if a ~= a then + a = 0 + end + writeu16(out, o, floor(math.clamp(r, 0, 1) * 65535 + 0.5)) + if nch == 4 then + writeu16(out, o + 2, floor(math.clamp(g, 0, 1) * 65535 + 0.5)) + writeu16(out, o + 4, floor(math.clamp(bl, 0, 1) * 65535 + 0.5)) + writeu16(out, o + 6, floor(math.clamp(a, 0, 1) * 65535 + 0.5)) + end + o += nch * 2 + else + writef32(out, o, r) + writef32(out, o + 4, g) + writef32(out, o + 8, bl) + writef32(out, o + 12, a) + o += 16 + end + end + end +end + +return Pixels diff --git a/src/Formats/image/tiff/init.luau b/src/Formats/image/tiff/init.luau new file mode 100644 index 0000000..81dca4b --- /dev/null +++ b/src/Formats/image/tiff/init.luau @@ -0,0 +1,841 @@ +--!strict +-- image/tiff: TIFF 6.0 (+ Adobe technote 3 floating point, BigTIFF). New code from the TIFF 6.0 specification. +-- Decode: both byte orders, classic and BigTIFF, strips and tiles, planar configuration 1 and 2, compression none / +-- LZW (codecs/Lzw, also old-style) / Deflate (8 and 32946, codecs/Deflate) / PackBits, JPEG (7) through the api's +-- opts.decodeImage hook (JPEGTables stitched to each strip / tile), predictors 2 (8 / 16 / 32-bit) and 3 (float), +-- 1..32-bit unsigned / signed integer and 16 / 32 / 64-bit float samples, min-is-white / min-is-black, RGB, palette, +-- CMYK (naive conversion), extra samples (associated alpha is un-premultiplied), fill order 2, every page as +-- img.frames, resolution (meta.dpi), ICC (meta.icc). Decodes to rgba8, or with opts.native to the nearest standard +-- layout (gray8, gray16, graya8, rgb8, rgba8, rgba16, rgbaf32). +-- Encode: rgba8 / rgb8 / gray8 / graya8 / gray16 / rgba16 / rgbaf32 as the matching TIFF layout, compression none / +-- deflate / lzw / packbits with predictor 2 (integers) or 3 (floats), strips, multi-page from img.frames. +-- Not supported: old-style JPEG (6), CCITT fax (2, 3, 4), uncompressed YCbCr with subsampling, CIELab, JBIG. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Deflate = require("@formats/codecs/Deflate") +local Lzw = require("@formats/codecs/Lzw") +local Pixels = require("@formats/image/tiff/Pixels") + +-- ------------------------------------------------------------------------------------------------ contract +local Tiff = { + name = "tiff", + category = "image", + extensions = { "tif", "tiff" }, + mime = { "image/tiff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate", "codecs/Lzw" }, + caps = { decode = true, encode = true, alpha = true, pages = true, depths = { 1, 2, 4, 8, 16, 32 }, float = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + native: boolean?, -- keep the source layout (gray8 / gray16 / graya8 / rgb8 / rgba8 / rgba16 / rgbaf32); default rgba8 + maxPixels: number?, -- per page (default 2^26) + maxPages: number?, -- pages decoded into img.frames (default 1024) + page: number?, -- decode only this page (1-based) + decodeImage: ((buffer) -> (any, any))?, -- the api's hook, for JPEG-compressed pages +} +export type EncodeOptions = { + compression: ("none" | "deflate" | "lzw" | "packbits")?, -- default "deflate" + predictor: boolean?, -- horizontal / float predictor with deflate and lzw (default true) + level: number?, -- deflate level 0..9 (default 6) + rowsPerStrip: number?, -- default: about 64 KB per strip +} + +-- ------------------------------------------------------------------------------------------------ constants +local TYPE_SIZE = { [1] = 1, [2] = 1, [3] = 2, [4] = 4, [5] = 8, [6] = 1, [7] = 1, [8] = 2, [9] = 4, [10] = 8, [11] = 4, [12] = 8, [13] = 4, [16] = 8, [17] = 8, [18] = 8 } +local COMPRESSION = { [1] = "none", [5] = "lzw", [8] = "deflate", [32946] = "deflate", [32773] = "packbits", [7] = "jpeg" } +local PHOTOMETRIC = { [0] = "miniswhite", [1] = "minisblack", [2] = "rgb", [3] = "palette", [5] = "cmyk", [6] = "ycbcr" } +local TWO32 = 4294967296 + +local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 + +-- ------------------------------------------------------------------------------------------------ sniff +function Tiff.sniff(r: Bytes.Reader): number + local s = r:peek(4) + if s == "II*\0" or s == "MM\0*" or s == "II+\0" or s == "MM\0+" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Entry = { tag: number, typ: number, count: number, at: number } +type Ctx = { b: buffer, base: number, limit: number, le: boolean, big: boolean } + +local function u16(c: Ctx, at: number): number + if at < c.base or at + 2 > c.limit then + return 0 + end + return if c.le then readu16(c.b, at) else readu8(c.b, at) * 256 + readu8(c.b, at + 1) +end +local function u32(c: Ctx, at: number): number + if at < c.base or at + 4 > c.limit then + return 0 + end + local v = readu32(c.b, at) + return if c.le then v else bit32.byteswap(v) +end +local function u64(c: Ctx, at: number): number + local lo, hi = u32(c, at), u32(c, at + 4) + if not c.le then + lo, hi = hi, lo + end + return hi * TWO32 + lo +end +local function off(c: Ctx, at: number): number + return if c.big then u64(c, at) else u32(c, at) +end + +-- values(c, e, max) -> the entry's numbers (rationals divided) | nil when out of range / too many +local function values(c: Ctx, e: Entry?, max: number?): { number }? + if not e then + return nil + end + local size = TYPE_SIZE[e.typ] + if not size or e.count > (max or 1e7) or e.at < c.base or e.at + e.count * size > c.limit then + return nil + end + local out = table.create(e.count, 0) + local b = c.b + for i = 0, e.count - 1 do + local p = e.at + i * size + local t = e.typ + local v + if t == 1 or t == 2 or t == 7 then + v = readu8(b, p) + elseif t == 6 then + v = buffer.readi8(b, p) + elseif t == 3 then + v = u16(c, p) + elseif t == 8 then + v = u16(c, p) + if v >= 32768 then + v -= 65536 + end + elseif t == 4 or t == 13 then + v = u32(c, p) + elseif t == 9 then + v = u32(c, p) + if v >= 2147483648 then + v -= TWO32 + end + elseif t == 5 or t == 10 then + local n, d = u32(c, p), u32(c, p + 4) + if t == 10 then + if n >= 2147483648 then + n -= TWO32 + end + if d >= 2147483648 then + d -= TWO32 + end + end + v = if d ~= 0 then n / d else 0 + elseif t == 11 then + v = Pixels.f32(u32(c, p)) + elseif t == 12 then + local lo, hi = u32(c, p), u32(c, p + 4) + if not c.le then + lo, hi = hi, lo + end + v = Pixels.f64(lo, hi) + else + v = u64(c, p) + end + out[i + 1] = v + end + return out +end + +local function one(c: Ctx, e: Entry?, default: number): number + local v = values(c, e, 64) + return if v and v[1] then v[1] else default +end + +-- the IFD at absolute offset p: { [tag] = Entry }, next IFD offset (absolute, 0 = none) | nil, Err +local function readIfd(c: Ctx, p: number): ({ [number]: Entry }?, number, Err.Err?) + local esize = if c.big then 20 else 12 + local hsize = if c.big then 8 else 2 + if p < c.base or p + hsize > c.limit then + return nil, 0, Err.new(Err.TRUNCATED, "IFD past the end", p) + end + local n = if c.big then u64(c, p) else u16(c, p) + if n == 0 or p + hsize + n * esize > c.limit then + return nil, 0, Err.new(if n == 0 then Err.CORRUPT else Err.TRUNCATED, "bad IFD entry count " .. n, p) + end + local entries: { [number]: Entry } = {} + for i = 0, n - 1 do + local q = p + hsize + i * esize + local tag, typ = u16(c, q), u16(c, q + 2) + local count = if c.big then u64(c, q + 4) else u32(c, q + 4) + local vat = q + (if c.big then 12 else 8) + local size = TYPE_SIZE[typ] + if size then + local at = vat + if count * size > (if c.big then 8 else 4) then + at = c.base + off(c, vat) + end + entries[tag] = { tag = tag, typ = typ, count = count, at = at } + end + end + local nq = p + hsize + n * esize + local nextOff = 0 + if nq + (if c.big then 8 else 4) <= c.limit then + nextOff = off(c, nq) + end + return entries, if nextOff > 0 then c.base + nextOff else 0, nil +end + +local function bytesOf(c: Ctx, e: Entry?, max: number): buffer? + if not e or e.at < c.base then + return nil + end + local size = TYPE_SIZE[e.typ] or 1 + local n = e.count * size + if n > max or e.at + n > c.limit then + return nil + end + local x = buffer.create(n) + buffer.copy(x, 0, c.b, e.at, n) + return x +end + +-- decompress one chunk at [p, p + len) into out[o, o + size): bytes produced | nil, Err +local function inflateChunk(c: Ctx, comp: number, p: number, len: number, out: buffer, o: number, size: number, rev: boolean): (number?, Err.Err?) + if p < c.base or len < 0 or p + len > c.limit then + -- a chunk past the end: keep what exists (truncated files) + len = math.max(0, math.min(len, c.limit - p)) + if p < c.base or p >= c.limit then + return 0 + end + end + local src, sp = c.b, p + if rev then + src = buffer.create(len) + buffer.copy(src, 0, c.b, p, len) + Pixels.reverseBits(src, 0, len) + sp = 0 + end + if comp == 1 then + local n = math.min(len, size) + buffer.copy(out, o, src, sp, n) + return n + elseif comp == 5 then + local n = Lzw.decode(src, sp, len, out, o, size, "tiff") + return n + elseif comp == 8 or comp == 32946 then + local raw = Deflate.zlib(src, sp, len, size) + if not raw then + raw = Deflate.zlib(src, sp, len) or Deflate.inflate(src, sp, len) + end + if not raw then + return nil, Err.new(Err.CORRUPT, "bad deflate data", p) + end + local n = math.min(buffer.len(raw :: buffer), size) + buffer.copy(out, o, raw :: buffer, 0, n) + return n + elseif comp == 32773 then + return Pixels.packbits(src, sp, len, out, o, size) + end + return nil, Err.new(Err.UNSUPPORTED, "compression " .. comp) +end + +type Page = { image: Types.Image, info: { [string]: any } } + +local function decodePage(c: Ctx, t: { [number]: Entry }, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local w, h = one(c, t[256], 0), one(c, t[257], 0) + if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad image size") + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local spp = one(c, t[277], 1) + local bpsList = values(c, t[258], 64) or { 1 } + local bps = bpsList[1] or 1 + for i = 2, math.min(#bpsList, spp) do + if bpsList[i] ~= bps then + return nil, Err.new(Err.UNSUPPORTED, "different bit depths per sample") + end + end + local comp = one(c, t[259], 1) + local photo = one(c, t[262], if spp >= 3 then 2 else 1) + local planar = one(c, t[284], 1) + local predictor = one(c, t[317], 1) + local sfmt = one(c, t[339], 1) + local fill = one(c, t[266], 1) + if spp < 1 or spp > 16 or bps < 1 or bps > 64 then + return nil, Err.new(Err.UNSUPPORTED, string.format("%d samples of %d bits", spp, bps)) + end + if sfmt == 3 and bps ~= 16 and bps ~= 32 and bps ~= 64 then + return nil, Err.new(Err.UNSUPPORTED, bps .. "-bit floats") + end + if sfmt ~= 3 and bps > 32 then + return nil, Err.new(Err.UNSUPPORTED, bps .. "-bit integers") + end + if not COMPRESSION[comp] then + local names = { [2] = "CCITT RLE", [3] = "CCITT fax 3", [4] = "CCITT fax 4", [6] = "old-style JPEG", [34712] = "JPEG 2000", [34925] = "LZMA", [50000] = "Zstandard", [50001] = "WebP" } + return nil, Err.new(Err.UNSUPPORTED, (names[comp] or "compression") .. " (" .. comp .. ")") + end + if not PHOTOMETRIC[photo] then + return nil, Err.new(Err.UNSUPPORTED, "photometric interpretation " .. photo) + end + local cc = if photo == 2 or photo == 6 then 3 elseif photo == 5 then 4 else 1 + if spp < cc then + return nil, Err.new(Err.CORRUPT, string.format("%d samples for photometric %d", spp, photo)) + end + if photo == 5 and one(c, t[332], 1) ~= 1 then + return nil, Err.new(Err.UNSUPPORTED, "separated image that is not CMYK") + end + local extra = values(c, t[338], 16) or {} + local alpha, assoc = -1, false + if spp > cc then + local kind = extra[1] or 0 + alpha = cc + assoc = kind == 1 + end + local chunky = planar ~= 2 or spp == 1 + local tiled = t[322] ~= nil + local cw = if tiled then one(c, t[322], 0) else w + local ch = if tiled then one(c, t[323], 0) else math.min(one(c, t[278], h), h) + if cw < 1 or ch < 1 or cw > 65536 or (tiled and ch > 65536) then + return nil, Err.new(Err.CORRUPT, "bad tile / strip size") + end + if ch > h and not tiled then + ch = h + end + local pspp = if chunky then spp else 1 -- samples per pixel in one plane + local nplanes = if chunky then 1 else spp + local rb = math.ceil(w * pspp * bps / 8) -- bytes per image row in a plane + local crb = math.ceil(cw * pspp * bps / 8) -- bytes per chunk row + if rb * h * nplanes > 2 ^ 30 or crb * ch > 2 ^ 30 then + return nil, Err.new(Err.LIMIT, "decoded data over 1 GB") + end + local across = if tiled then math.ceil(w / cw) else 1 + local down = math.ceil(h / ch) + local perPlane = across * down + local offs = values(c, if tiled then t[324] else t[273], 2 ^ 24) + local lens = values(c, if tiled then t[325] else t[279], 2 ^ 24) + if not offs or #offs < perPlane * nplanes then + return nil, Err.new(Err.CORRUPT, "missing or short strip / tile offsets") + end + local planes = table.create(nplanes) + for i = 1, nplanes do + planes[i] = buffer.create(rb * h + 8) + end + local tmp = buffer.create(crb * ch + 8) + local ftmp = buffer.create(math.max(rb, crb) + 8) + local le = c.le + local bytesPer = bps // 8 + local hook = opts and opts.decodeImage + local jpegTables = if comp == 7 then bytesOf(c, t[347], 1 * 2 ^ 20) else nil + local jpegPixels: buffer? = nil + if comp == 7 then + if type(hook) ~= "function" then + return nil, Err.new(Err.UNSUPPORTED, "JPEG-compressed TIFF needs opts.decodeImage (F.load supplies it)") + end + jpegPixels = buffer.create(w * h * 4) + end + for pl = 0, nplanes - 1 do + for ty = 0, down - 1 do + for tx = 0, across - 1 do + local idx = pl * perPlane + ty * across + tx + local p = c.base + offs[idx + 1] + local len = if lens and lens[idx + 1] then lens[idx + 1] else c.limit - p + local rows = if tiled then ch else math.min(ch, h - ty * ch) + local size = rows * crb + if comp == 7 then + -- JPEGTables (SOI .. EOI) + the chunk (SOI .. EOI): one stream without the inner EOI / SOI + if p < c.base or p + len > c.limit or len < 4 then + return nil, Err.new(Err.TRUNCATED, "JPEG chunk past the end", p) + end + local tl = if jpegTables and buffer.len(jpegTables) >= 4 then buffer.len(jpegTables) - 2 else 0 + local s = buffer.create(tl + len - (if tl > 0 then 2 else 0)) + if tl > 0 then + buffer.copy(s, 0, jpegTables :: buffer, 0, tl) + buffer.copy(s, tl, c.b, p + 2, len - 2) + else + buffer.copy(s, 0, c.b, p, len) + end + local ok, img, herr = pcall(hook :: any, s) + if not ok or type(img) ~= "table" or img.format ~= "rgba8" then + return nil, if ok and herr then herr else Err.new(Err.CORRUPT, "embedded JPEG: " .. tostring(if ok then herr else img)) + end + local x0, y0 = tx * cw, ty * ch + local cwid = math.min(cw, w - x0, img.width) + for yy = 0, math.min(rows, h - y0, img.height) - 1 do + buffer.copy(jpegPixels :: buffer, ((y0 + yy) * w + x0) * 4, img.pixels, yy * img.width * 4, cwid * 4) + end + continue + end + buffer.fill(tmp, 0, 0, size) + local _, derr = inflateChunk(c, comp, p, len, tmp, 0, size, fill == 2) + if derr then + return nil, derr + end + if predictor == 2 then + Pixels.unpredict2(tmp, 0, rows, crb, pspp, bps, le) + elseif predictor == 3 and bytesPer >= 2 and crb % bytesPer == 0 then + Pixels.unpredict3(tmp, 0, rows, crb, bytesPer, pspp, ftmp) + end + -- into the plane + local plane = planes[pl + 1] + local x0b = math.floor(tx * cw * pspp * bps / 8) + local cols = math.min(cw, w - tx * cw) + local nb = math.min(math.ceil(cols * pspp * bps / 8), rb - x0b) + for yy = 0, rows - 1 do + local y = ty * ch + yy + if y >= h then + break + end + buffer.copy(plane, y * rb + x0b, tmp, yy * crb, nb) + end + end + end + end + local floatOut = sfmt == 3 + if predictor == 3 and floatOut then + le = true -- fpAcc leaves the samples little endian + end + local colorType = PHOTOMETRIC[photo] + -- the output layout + local kind = "rgba8" + if opts and opts.native and comp ~= 7 then + if photo == 3 or photo == 5 then + kind = "rgba8" + elseif floatOut then + kind = "rgbaf32" + elseif cc == 1 then + if alpha >= 0 then + kind = if bps <= 8 then "graya8" else "rgba16" + else + kind = if bps <= 8 then "gray8" else "gray16" + end + else + if alpha >= 0 then + kind = if bps <= 8 then "rgba8" else "rgba16" + else + kind = if bps <= 8 then "rgb8" else "rgba16" + end + end + end + local img = Types.Image.new(w, h, kind :: any) + if comp == 7 then + img.pixels = jpegPixels :: buffer + else + if photo == 6 then + return nil, Err.new(Err.UNSUPPORTED, "uncompressed YCbCr") + end + local cmap = nil + if photo == 3 then + local n = 3 * 2 ^ math.min(bps, 16) + local cv = values(c, t[320], n) + if not cv or #cv < n then + return nil, Err.new(Err.CORRUPT, "palette image without a full ColorMap") + end + cmap = buffer.create(n * 2) + for i = 1, n do + buffer.writeu16(cmap, (i - 1) * 2, math.clamp(cv[i], 0, 65535)) + end + end + Pixels.convert({ + planes = planes, + rb = rb, + chunky = chunky, + w = w, + h = h, + spp = spp, + bps = bps, + sfmt = sfmt, + le = le, + photo = photo, + alpha = alpha, + assoc = assoc, + cmap = cmap, + kind = kind, + out = img.pixels, + }) + end + local xr, yr = one(c, t[282], 0), one(c, t[283], 0) + if xr > 0 and yr > 0 then + local unit = one(c, t[296], 2) + local k = if unit == 3 then 2.54 else 1 + if unit ~= 1 then + img.meta.dpi = { x = xr * k, y = yr * k } + end + end + img.meta.icc = bytesOf(c, t[34675], 2 ^ 26) + local function ascii(tag: number): string? + local v = bytesOf(c, t[tag], 65536) + if not v then + return nil + end + local s = buffer.tostring(v) + local z = string.find(s, "\0", 1, true) + return if z then string.sub(s, 1, z - 1) else s + end + local text = {} + for tag, key in { [270] = "description", [305] = "software", [306] = "datetime", [315] = "artist", [33432] = "copyright" } do + local s = ascii(tag) + if s and s ~= "" then + text[key] = s + end + end + if next(text) then + img.meta.text = text + end + img.meta.source = { + format = "tiff", + bitDepth = bps, + colorType = colorType, + photometric = photo, + samples = spp, + sampleFormat = if sfmt == 3 then "float" elseif sfmt == 2 then "int" else "uint", + compression = COMPRESSION[comp], + predictor = predictor, + planar = planar, + tiled = tiled, + alpha = if alpha >= 0 then (if assoc then "associated" else "unassociated") else nil, + bigtiff = c.big, + byteOrder = if c.le then "II" else "MM", + } + return img, nil +end + +-- pages(r) -> the IFD tables of every page (and the context) | nil, Err +local function pages(r: Bytes.Reader, maxPages: number): ({ { [number]: Entry } }?, Ctx?, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 8 then + return nil, nil, Err.new(Err.TRUNCATED, "short header") + end + local bo = buffer.readstring(b, base, 2) + if bo ~= "II" and bo ~= "MM" then + return nil, nil, Err.new(Err.CORRUPT, "bad byte order mark") + end + local c: Ctx = { b = b, base = base, limit = limit, le = bo == "II", big = false } + local magic = u16(c, base + 2) + local first + if magic == 42 then + first = u32(c, base + 4) + elseif magic == 43 then + if limit - base < 16 or u16(c, base + 4) ~= 8 then + return nil, nil, Err.new(Err.CORRUPT, "bad BigTIFF header") + end + c.big = true + first = u64(c, base + 8) + else + return nil, nil, Err.new(Err.CORRUPT, "bad magic " .. magic) + end + local list = {} + local seen = {} + local p = base + first + while p > 0 and #list < maxPages do + if seen[p] then + break -- an IFD loop + end + seen[p] = true + local t, nextP, err = readIfd(c, p) + if not t then + if #list == 0 then + return nil, nil, err + end + break + end + table.insert(list, t) + p = nextP + end + return list, c, nil +end + +-- info(r) -> { pages, width, height, bitDepth, samples, compression } of page 1 | nil, Err +function Tiff.info(r: Bytes.Reader): ({ [string]: any }?, Err.Err?) + local list, c, err = pages(r, 1024) + if not list or not c then + return nil, err + end + local t = list[1] + return { + pages = #list, + width = one(c, t[256], 0), + height = one(c, t[257], 0), + bitDepth = one(c, t[258], 1), + samples = one(c, t[277], 1), + compression = COMPRESSION[one(c, t[259], 1)] or tostring(one(c, t[259], 1)), + photometric = PHOTOMETRIC[one(c, t[262], 1)], + bigtiff = c.big, + }, + nil +end + +function Tiff.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local maxPages = opts and opts.maxPages or 1024 + local list, c, err = pages(r, if opts and opts.page then math.max(1, opts.page) else maxPages) + if not list or not c then + return nil, err + end + if opts and opts.page then + local t = list[opts.page] + if not t then + return nil, Err.new(Err.ARG, "no page " .. tostring(opts.page)) + end + local img, perr = decodePage(c, t, opts) + if img then + img.meta.source.pages = #list + end + return img, perr + end + local first: Types.Image? = nil + local frames = {} + for i, t in list do + -- reduced-resolution subfiles (thumbnails) after page 1 are skipped + local sub = one(c, t[254], 0) + if i > 1 and bit32.band(sub, 1) ~= 0 then + continue + end + local img, perr = decodePage(c, t, opts) + if not img then + if i == 1 then + return nil, perr + end + continue + end + if not first then + first = img + end + table.insert(frames, { image = img, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }) + end + local img = first :: Types.Image + img.meta.source.pages = #frames + if #frames > 1 then + img.frames = frames :: any + end + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- layout per pixel format: samples, bits, sample format, photometric, extra samples +local LAYOUT = { + gray8 = { 1, 8, 1, 1 }, + graya8 = { 2, 8, 1, 1 }, + gray16 = { 1, 16, 1, 1 }, + rgb8 = { 3, 8, 1, 2 }, + rgba8 = { 4, 8, 1, 2 }, + rgba16 = { 4, 16, 1, 2 }, + rgbaf32 = { 4, 32, 3, 2 }, +} +local COMP_CODES = { none = 1, deflate = 8, lzw = 5, packbits = 32773 } + +type Tag = { tag: number, typ: number, vals: { number }?, data: buffer? } + +local function encodePage(img: Types.Image, o: EncodeOptions, comp: number): ({ Tag }?, { buffer }?, Err.Err?) + local L = LAYOUT[img.format] + if not L then + return nil, nil, Err.new(Err.ARG, "unsupported pixel format " .. tostring(img.format)) + end + local w, h = img.width, img.height + local spp, bps, sfmt, photo = L[1], L[2], L[3], L[4] + local rb = w * spp * bps // 8 + if type(w) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or w > 2 ^ 31 or buffer.len(img.pixels) < rb * h then + return nil, nil, Err.new(Err.ARG, "bad image size or pixel buffer") + end + local rps = o.rowsPerStrip or math.max(1, 65536 // rb) + if type(rps) ~= "number" or rps < 1 then + return nil, nil, Err.new(Err.ARG, "rowsPerStrip must be >= 1") + end + rps = math.min(math.floor(rps), h) + local predictor = 1 + if (comp == 8 or comp == 5) and o.predictor ~= false then + predictor = if sfmt == 3 then 3 else 2 + end + local strips = {} + local tmp = buffer.create(rb + 8) + for y0 = 0, h - 1, rps do + local rows = math.min(rps, h - y0) + local raw = buffer.create(rows * rb) + buffer.copy(raw, 0, img.pixels, y0 * rb, rows * rb) + if predictor == 2 then + Pixels.predict2(raw, 0, rows, rb, spp, bps) + elseif predictor == 3 then + Pixels.predict3(raw, 0, rows, rb, 4, spp, tmp) + end + local out + if comp == 1 then + out = raw + elseif comp == 8 then + out = Deflate.zlibCompress(raw, { level = o.level or 6 }) :: buffer + elseif comp == 5 then + out = Lzw.encode(raw, 0, rows * rb, "tiff") + else + local parts, total = {}, 0 + for r = 0, rows - 1 do + local p = Pixels.packbitsEncode(raw, r * rb, rb) + table.insert(parts, p) + total += buffer.len(p) + end + out = buffer.create(total) + local q = 0 + for _, p in parts do + buffer.copy(out, q, p) + q += buffer.len(p) + end + end + table.insert(strips, out) + end + local bpsv = table.create(spp, bps) + local tags: { Tag } = { + { tag = 254, typ = 4, vals = { 0 } }, + { tag = 256, typ = 4, vals = { w } }, + { tag = 257, typ = 4, vals = { h } }, + { tag = 258, typ = 3, vals = bpsv }, + { tag = 259, typ = 3, vals = { comp } }, + { tag = 262, typ = 3, vals = { photo } }, + { tag = 273, typ = 4, vals = table.create(#strips, 0) }, -- patched + { tag = 277, typ = 3, vals = { spp } }, + { tag = 278, typ = 4, vals = { rps } }, + { tag = 279, typ = 4, vals = table.create(#strips, 0) }, + { tag = 284, typ = 3, vals = { 1 } }, + } + for i, s in strips do + (tags[10].vals :: { number })[i] = buffer.len(s) + end + local dpi = img.meta and img.meta.dpi + if type(dpi) == "table" and type(dpi.x) == "number" and type(dpi.y) == "number" and dpi.x > 0 and dpi.y > 0 then + table.insert(tags, { tag = 282, typ = 5, vals = { dpi.x } }) + table.insert(tags, { tag = 283, typ = 5, vals = { dpi.y } }) + table.insert(tags, { tag = 296, typ = 3, vals = { 2 } }) + end + if predictor > 1 then + table.insert(tags, { tag = 317, typ = 3, vals = { predictor } }) + end + if spp == 2 or spp == 4 then + table.insert(tags, { tag = 338, typ = 3, vals = { 2 } }) + end + if sfmt ~= 1 then + table.insert(tags, { tag = 339, typ = 3, vals = table.create(spp, sfmt) }) + end + local icc = img.meta and img.meta.icc + if type(icc) == "buffer" then + table.insert(tags, { tag = 34675, typ = 7, data = icc }) + end + local text = img.meta and img.meta.text + if type(text) == "table" then + for key, tag in { description = 270, software = 305, datetime = 306, artist = 315, copyright = 33432 } do + if type(text[key]) == "string" then + table.insert(tags, { tag = tag, typ = 2, data = buffer.fromstring(text[key] .. "\0") }) + end + end + end + table.sort(tags, function(a: Tag, b: Tag): boolean + return a.tag < b.tag + end) + return tags, strips, nil +end + +function Tiff.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an Image") + end + local o: EncodeOptions = opts or {} + local comp = COMP_CODES[o.compression or "deflate"] + if not comp then + return nil, Err.new(Err.ARG, "compression must be none, deflate, lzw or packbits") + end + local list = { img } + if type(img.frames) == "table" and #img.frames > 1 then + list = {} + for _, f in img.frames :: any do + if type(f) ~= "table" or type(f.image) ~= "table" then + return nil, Err.new(Err.ARG, "bad frame") + end + table.insert(list, f.image) + end + end + local w = Bytes.writer(1024) + w:string("II") + w:u16le(42) + w:u32le(0) -- first IFD, patched + local prevNext = 4 + for _, page in list do + local tags, strips, err = encodePage(page, o, comp) + if not tags or not strips then + return nil, err + end + -- strip data first + local soffs = {} + for i, s in strips do + if w:tell() % 2 == 1 then + w:u8(0) + end + soffs[i] = w:tell() + w:bytes(s) + end + for _, tg in tags do + if tg.tag == 273 then + tg.vals = soffs + end + end + -- out-of-line values + local valOff: { [number]: number } = {} + for i, tg in tags do + local size = TYPE_SIZE[tg.typ] + local n = if tg.data then buffer.len(tg.data :: buffer) else #(tg.vals :: { number }) * size + if n > 4 then + if w:tell() % 2 == 1 then + w:u8(0) + end + valOff[i] = w:tell() + if tg.data then + w:bytes(tg.data :: buffer) + else + for _, v in tg.vals :: { number } do + if tg.typ == 3 then + w:u16le(v) + elseif tg.typ == 4 then + w:u32le(v) + elseif tg.typ == 5 then + w:u32le(math.floor(v * 10000 + 0.5)) + w:u32le(10000) + end + end + end + end + end + if w:tell() % 2 == 1 then + w:u8(0) + end + local ifd = w:tell() + w:setU32le(prevNext, ifd) + w:u16le(#tags) + for i, tg in tags do + local count = if tg.data then buffer.len(tg.data :: buffer) else #(tg.vals :: { number }) + w:u16le(tg.tag) + w:u16le(tg.typ) + w:u32le(count) + if valOff[i] then + w:u32le(valOff[i]) + else + local start = w:tell() + if tg.data then + w:bytes(tg.data :: buffer) + else + for _, v in tg.vals :: { number } do + if tg.typ == 3 then + w:u16le(v) + else + w:u32le(v) + end + end + end + w:fill(0, 4 - (w:tell() - start)) + end + end + prevNext = w:tell() + w:u32le(0) + end + return w:finish(), nil +end + +return Tiff diff --git a/tests/image/tiff.luau b/tests/image/tiff.luau new file mode 100644 index 0000000..53b029b --- /dev/null +++ b/tests/image/tiff.luau @@ -0,0 +1,172 @@ +-- image/tiff tests: files written by tifffile / imagecodecs and ImageMagick (every compression, predictors, strips and +-- tiles, planar, both byte orders, BigTIFF, 1..32-bit integer and 16 / 32 / 64-bit float samples, palette, CMYK, +-- alpha, multi-page) against tifffile's decode, in rgba8 and native layouts; the JPEG hook; encoder round trips for +-- every layout and compression; errors; the fuzz pass. Fixtures: tools/fixtures/tiff.py. +local T = require("@tests/T") +local Tiff = require("@formats/image/tiff") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/tiff") + +local t = T.suite("tiff") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Tiff.decode(Bytes.reader(b), opts) +end + +-- contract +t:eq(Tiff.name, "tiff", "name") +t:check(Tiff.caps.decode and Tiff.caps.encode, "caps") +t:eq(Tiff.sniff(Bytes.reader(buffer.fromstring("II*\0\8\0\0\0"))), 1, "sniff II") +t:eq(Tiff.sniff(Bytes.reader(buffer.fromstring("MM\0*"))), 1, "sniff MM") +t:eq(Tiff.sniff(Bytes.reader(buffer.fromstring("\137PNG"))), 0, "sniff png") + +-- reference files +local pagesChecked = 0 +for _, c in Fx.cases do + local img, err = decode(c.data) + t:check(img, c.name .. ": " .. tostring(err)) + t:check(img.width == c.width and img.height == c.height and img.format == "rgba8", c.name .. ": size / format") + local frames = img.frames or { { image = img } } + t:eq(#frames, #c.pages, c.name .. ": pages") + local nat = decode(c.data, { native = true }) + local nframes = nat.frames or { { image = nat } } + for i, p in c.pages do + local crc = Crc32.of(frames[i].image.pixels) + t:check(crc == p.crc, string.format("%s page %d: rgba8 crc %08x, want %08x", c.name, i, crc, p.crc)) + local ni = nframes[i].image + t:eq(ni.format, p.native, c.name .. " page " .. i .. ": native format") + local ncrc = Crc32.of(ni.pixels) + t:check(ncrc == p.ncrc, string.format("%s page %d: native crc %08x, want %08x", c.name, i, ncrc, p.ncrc)) + pagesChecked += 1 + end + -- inside a bigger buffer + local big = buffer.create(#c.data + 9) + buffer.writestring(big, 5, c.data) + local img3 = Tiff.decode(Bytes.reader(big, 5, #c.data)) + t:check(img3 and Crc32.of(img3.pixels) == c.pages[1].crc, c.name .. ": sub-range decode") +end +t:note("%d files, %d pages match tifffile", #Fx.cases, pagesChecked) + +-- info, single page, meta +do + local multi + for _, c in Fx.cases do + if c.name == "pages3" then + multi = c + end + end + local info = Tiff.info(Bytes.reader(buffer.fromstring(multi.data))) + t:check(info and info.pages == 3 and info.width == multi.width, "info") + local p2 = decode(multi.data, { page = 2, native = true }) + t:check(p2 and p2.format == "gray16" and Crc32.of(p2.pixels) == multi.pages[2].ncrc, "opts.page") + local _, e = decode(multi.data, { page = 9 }) + t:check(e and e.code == Err.ARG, "missing page") + local _, e2 = decode(multi.data, { maxPixels = 10 }) + t:check(e2 and e2.code == Err.LIMIT, "maxPixels") + local img = decode(multi.data) + t:check(img.meta.source.format == "tiff" and img.meta.source.compression == "deflate", "meta.source") +end + +-- JPEG-compressed: needs the hook; the hook gets one stitched JPEG stream per strip +do + local _, e = decode(Fx.jpeg) + t:check(e and e.code == Err.UNSUPPORTED, "jpeg without hook: " .. tostring(e)) + local calls = 0 + local img = decode(Fx.jpeg, { + decodeImage = function(b: buffer) + calls += 1 + t:check(buffer.readu8(b, 0) == 0xFF and buffer.readu8(b, 1) == 0xD8, "stitched stream starts with SOI") + local s = buffer.tostring(b) + t:check(string.find(s, "\255\218", 1, true) ~= nil, "stitched stream has SOS") + t:check(string.find(s, "\255\196", 1, true) ~= nil or string.find(s, "\255\219", 1, true) ~= nil, "stitched stream has tables") + local im = Types.Image.new(64, 64) + buffer.fill(im.pixels, 0, 200) + return im + end, + }) + t:check(img and calls > 0, "jpeg through the hook") +end + +-- encoder round trips +do + local rand = T.rng(11) + local function image(fmt: string, w: number, h: number): Types.Image + local img = Types.Image.new(w, h, fmt :: any) + local n = buffer.len(img.pixels) + if fmt == "rgbaf32" then + for i = 0, n // 4 - 1 do + buffer.writef32(img.pixels, i * 4, (rand(2000) - 300) / 1000) + end + else + for i = 0, n - 1 do + buffer.writeu8(img.pixels, i, if rand(3) == 0 then rand(256) else (i * 7) % 256) + end + end + return img + end + local trips = 0 + for _, fmt in { "rgba8", "rgb8", "gray8", "graya8", "gray16", "rgba16", "rgbaf32" } do + for _, comp in { "none", "deflate", "lzw", "packbits" } do + for _, pred in { true, false } do + for _, size in { { 1, 1 }, { 13, 7 }, { 200, 90 } } do + local img = image(fmt, size[1], size[2]) + img.meta.dpi = { x = 300, y = 150 } + local out, err = Tiff.encode(img, { compression = comp :: any, predictor = pred, rowsPerStrip = if size[1] == 200 then 16 else nil }) + t:check(out, fmt .. " " .. comp .. ": " .. tostring(err)) + local back, berr = Tiff.decode(Bytes.reader(out :: buffer), { native = true }) + t:check(back, fmt .. " " .. comp .. ": decode: " .. tostring(berr)) + t:eq(back.format, fmt, fmt .. " " .. comp .. ": format") + t:check(buffer.tostring(back.pixels) == buffer.tostring(img.pixels), string.format("%s %s pred=%s %dx%d: round trip", fmt, comp, tostring(pred), size[1], size[2])) + t:check(back.meta.dpi and math.abs(back.meta.dpi.x - 300) < 0.01 and math.abs(back.meta.dpi.y - 150) < 0.01, "dpi") + trips += 1 + end + end + end + end + t:note("%d encoder round trips", trips) + -- multi-page + local a, b = image("rgb8", 20, 10), image("gray16", 7, 9) + local anim = image("rgb8", 20, 10) + anim.frames = { { image = a, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }, { image = b, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } } :: any + local out = Tiff.encode(anim, { compression = "lzw" }) :: buffer + local back = Tiff.decode(Bytes.reader(out), { native = true }) + t:check(back.frames and #back.frames == 2, "multi-page count") + t:check(buffer.tostring(back.frames[1].image.pixels) == buffer.tostring(a.pixels), "page 1") + t:check(buffer.tostring(back.frames[2].image.pixels) == buffer.tostring(b.pixels) and back.frames[2].image.format == "gray16", "page 2") + local _, e = Tiff.encode({} :: any) + t:check(e and e.code == Err.ARG, "encode non-image") + local _, e2 = Tiff.encode(image("rgb8", 2, 2), { compression = "jpeg" } :: any) + t:check(e2 and e2.code == Err.ARG, "bad compression") + local _, e3 = Tiff.encode(Types.Image.new(2, 2, "yuv420p")) + t:check(e3 and e3.code == Err.ARG, "unsupported layout") +end + +-- errors +do + local _, e = decode("II*\0\255\255\0\0") + t:check(e and (e.code == Err.TRUNCATED or e.code == Err.CORRUPT), "bad IFD offset") + local _, e2 = decode("XX*\0") + t:check(e2 and e2.code == Err.TRUNCATED or e2.code == Err.CORRUPT, "junk") +end + +-- fuzz +do + local samples = {} + for i, c in Fx.cases do + if i % 3 == 0 and #c.data < 40000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + return Tiff.decode(Bytes.reader(b)) + end, samples, { mutations = 12 }) + t:fuzz("decode native", function(b: buffer) + return Tiff.decode(Bytes.reader(b), { native = true }) + end, samples, { mutations = 4, garbage = 50 }) +end + +t:done() diff --git a/tools/fixtures/tiff.py b/tools/fixtures/tiff.py new file mode 100644 index 0000000..77c9256 --- /dev/null +++ b/tools/fixtures/tiff.py @@ -0,0 +1,219 @@ +# TIFF fixtures (tools/fixtures.py): files written by tifffile (+ imagecodecs) and ImageMagick, with references from +# tifffile's decode (the native sample arrays) turned into what image/tiff must produce. +# tests/gen/tiff.luau { cases = { { name, data, width, height, pages = { { crc, native, ncrc } } } }, +# jpeg = { name, data } (a JPEG-compressed TIFF for the decodeImage hook test) } +# crc CRC-32 of the default rgba8 decode +# native / ncrc: the opts.native pixel format and the CRC-32 of its little-endian bytes +# Every case is decoded by tifffile; the expected pixels follow image/tiff's rules: unsigned samples v / (2^bits - 1), +# floats as stored, min-is-white inverted, palette = ColorMap / 65535, CMYK r = (1 - c)(1 - k), associated alpha +# divided out, then 8-bit = floor(clamp(u) * 255 + 0.5) (16-bit: * 65535). +import os, shutil, struct, subprocess, tempfile + +CODE = r''' +import os, struct, sys, zlib +import numpy as np, tifffile +work = WORK +magick = MAGICK +rng = np.random.default_rng(5) +H, W = 37, 53 +yy, xx = np.mgrid[0:H, 0:W] +def ramp(maxv, ch): + base = [(xx * 7 + yy * 3) % 256, (xx * 255 // (W - 1)), (yy * 255 // (H - 1)), 255 - ((xx ^ yy) & 63)] + a = np.stack([b for b in base[:ch]], -1).astype(np.float64) / 255.0 + noise = rng.random(a.shape) < 0.2 + a = np.where(noise, rng.random(a.shape), a) + return np.squeeze(np.round(a * maxv)) +cases = [] +def add(name, path): + cases.append((name, path)) +def tw(name, data, **kw): + p = os.path.join(work, name + ".tif") + tifffile.imwrite(p, data, **kw) + add(name, p) +rgb8 = ramp(255, 3).astype(np.uint8) +rgba8 = ramp(255, 4).astype(np.uint8) +gray8 = ramp(255, 1).astype(np.uint8) +gray16 = ramp(65535, 1).astype(np.uint16) +rgb16 = ramp(65535, 3).astype(np.uint16) +rgba16 = ramp(65535, 4).astype(np.uint16) +f32 = (ramp(1000, 3) / 1000.0 * 1.2 - 0.1).astype(np.float32) +for comp in (None, "lzw", "zlib", "adobe_deflate", "packbits"): + cn = comp or "none" + tw("rgb8_" + cn, rgb8, photometric="rgb", compression=comp) + tw("gray16_" + cn, gray16, photometric="minisblack", compression=comp) +for comp in ("lzw", "zlib"): + tw("rgb8_pred_" + comp, rgb8, photometric="rgb", compression=comp, predictor=True) + tw("rgba16_pred_be_" + comp, rgba16, photometric="rgb", compression=comp, predictor=True, byteorder=">", extrasamples=["unassalpha"]) + tw("gray16_pred_" + comp, gray16, photometric="minisblack", compression=comp, predictor=True) + tw("f32_fpred_" + comp, f32, photometric="rgb", compression=comp, predictor=3) + tw("f32_fpred_be_" + comp, f32, photometric="rgb", compression=comp, predictor=3, byteorder=">") +tw("rgba8_assoc", rgba8, photometric="rgb", extrasamples=["assocalpha"]) +tw("rgba8_unassoc_tiles", rgba8, photometric="rgb", extrasamples=["unassalpha"], tile=(16, 16), compression="zlib") +tw("rgb8_planar", np.ascontiguousarray(np.moveaxis(rgb8, -1, 0)), photometric="rgb", planarconfig="separate", compression="lzw") +tw("rgb16_planar_tiles_be", np.ascontiguousarray(np.moveaxis(rgb16, -1, 0)), photometric="rgb", planarconfig="separate", tile=(32, 16), byteorder=">", compression="zlib", predictor=True) +tw("rgb8_strips5", rgb8, photometric="rgb", rowsperstrip=5, compression="packbits") +tw("rgb8_bigtiff", rgb8, photometric="rgb", bigtiff=True, compression="zlib") +tw("rgb8_bigtiff_be_tiles", rgb8, photometric="rgb", bigtiff=True, byteorder=">", tile=(16, 32)) +tw("gray8_miniswhite", gray8, photometric="miniswhite") +tw("gray8_be", gray8, photometric="minisblack", byteorder=">") +tw("f16_gray", (gray16 / 65535.0).astype(np.float16), photometric="minisblack") +tw("f64_rgb", (f32.astype(np.float64)), photometric="rgb") +tw("f32_gray_tiles", f32[:, :, 0].copy(), photometric="minisblack", tile=(16, 16), compression="zlib") +tw("int16_gray", (gray16.astype(np.int32) - 32768).astype(np.int16), photometric="minisblack") +tw("int8_gray", (gray8.astype(np.int16) - 128).astype(np.int8), photometric="minisblack") +tw("u32_gray", (gray16.astype(np.uint32) * 65537), photometric="minisblack", compression="zlib") +cm = (rng.integers(0, 65536, (3, 256))).astype(np.uint16) +tw("palette8", gray8, photometric="palette", colormap=cm, compression="lzw") +tw("gray4", (gray8 >> 4).astype(np.uint8), photometric="minisblack", bitspersample=4) +tw("gray2_lzw", (gray8 >> 6).astype(np.uint8), photometric="minisblack", bitspersample=2, compression=None) +tw("bilevel", gray8 > 127, photometric="minisblack") +tw("bilevel_white_packbits", gray8 > 100, photometric="miniswhite", compression="packbits") +tw("gray12", (gray16 >> 4).astype(np.uint16), photometric="minisblack", bitspersample=12) +tw("cmyk8", ramp(255, 4).astype(np.uint8), photometric="separated", compression="lzw") +tw("graya8", np.stack([gray8, rgba8[:, :, 3]], -1), photometric="minisblack", extrasamples=["unassalpha"]) +with tifffile.TiffWriter(os.path.join(work, "pages3.tif")) as t: + t.write(rgb8, photometric="rgb", compression="zlib") + t.write(gray16, photometric="minisblack", compression="lzw") + t.write(rgba8, photometric="rgb", extrasamples=["unassalpha"]) +add("pages3", os.path.join(work, "pages3.tif")) +# ImageMagick +import subprocess +src = os.path.join(work, "src.png") +from PIL import Image +Image.fromarray(rgba8, "RGBA").save(src) +srgb = os.path.join(work, "srgb.png") +Image.fromarray(rgb8, "RGB").save(srgb) +def im(name, *args, s=srgb): + p = os.path.join(work, name + ".tif") + subprocess.run([magick, s] + list(args) + [p], check=True, capture_output=True) + add(name, p) +im("im_lzw", "-compress", "LZW") +im("im_zip_pred", "-compress", "Zip", "-define", "tiff:predictor=2") +im("im_rle", "-compress", "RLE") +im("im_none_msb", "-compress", "None", "-endian", "MSB") +im("im_tiles", "-compress", "LZW", "-define", "tiff:tile-geometry=32x32") +im("im_plane", "-compress", "Zip", "-interlace", "plane") +im("im_16", "-depth", "16", "-compress", "LZW") +im("im_float", "-depth", "32", "-define", "quantum:format=floating-point", "-compress", "Zip") +im("im_alpha", "-compress", "LZW", s=src) +im("im_alpha_assoc", "-define", "tiff:alpha=associated", s=src) +im("im_gray4", "-colorspace", "gray", "-depth", "4") +im("im_bilevel", "-monochrome") +im("im_palette", "-type", "palette", "-compress", "LZW") +im("im_palette4", "-colors", "12", "-type", "palette", "-depth", "4") +im("im_cmyk", "-colorspace", "CMYK", "-compress", "LZW") +p = os.path.join(work, "im_multi.tif") +subprocess.run([magick, srgb, src, srgb, "-compress", "Zip", p], check=True, capture_output=True) +add("im_multi", p) +jp = os.path.join(work, "im_jpeg.tif") +subprocess.run([magick, srgb, "-compress", "JPEG", jp], check=True, capture_output=True) + +def expect(page): + a = page.asarray() + spp = page.samplesperpixel + if spp > 1 and page.planarconfig == 2: + a = np.moveaxis(a, 0, -1) + if a.ndim == 2: + a = a[:, :, None] + a = a.reshape(page.imagelength, page.imagewidth, spp) + photo = int(page.photometric) + bps = page.bitspersample + fmt = int(page.sampleformat) + cc = 3 if photo in (2, 6) else (4 if photo == 5 else 1) + alpha = cc if spp > cc else -1 + ex = page.extrasamples + assoc = alpha >= 0 and len(ex) > 0 and int(ex[0]) == 1 + maxv = float(2 ** min(bps, 32) - 1) + if fmt == 3: + u = a.astype(np.float64) + elif fmt == 2: + u = (a.astype(np.float64) + 2 ** (bps - 1)) / maxv + else: + u = a.astype(np.float64) / maxv + if photo == 3: + cmap = page.colormap.astype(np.float64) / 65535.0 + idx = a[:, :, 0].astype(np.int64) + rgb = np.stack([cmap[0][idx], cmap[1][idx], cmap[2][idx]], -1) + elif photo == 2: + rgb = u[:, :, 0:3] + elif photo == 5: + c, m, y, k = u[:, :, 0], u[:, :, 1], u[:, :, 2], u[:, :, 3] + rgb = np.stack([(1 - c) * (1 - k), (1 - m) * (1 - k), (1 - y) * (1 - k)], -1) + else: + v = u[:, :, 0] + if photo == 0: + v = 1 - v + rgb = np.stack([v, v, v], -1) + if alpha >= 0: + al = u[:, :, alpha] + if assoc: + safe = np.where(al > 0, al, 1) + rgb = np.where((al > 0)[:, :, None], np.minimum(rgb / safe[:, :, None], 1), 0) + else: + al = np.ones(rgb.shape[:2]) + def q(x, m): + return np.floor(np.clip(np.nan_to_num(x), 0, 1) * m + 0.5) + rgba = np.concatenate([rgb, al[:, :, None]], -1) + out8 = q(rgba, 255).astype(np.uint8) + crc = zlib.crc32(out8.tobytes()) + # native + if photo in (3, 5): + kind, nat = "rgba8", out8 + elif fmt == 3: + kind, nat = "rgbaf32", rgba.astype("= 0: + if bps <= 8: + kind, nat = "graya8", q(np.stack([rgb[:, :, 0], al], -1), 255).astype(np.uint8) + else: + kind, nat = "rgba16", q(rgba, 65535).astype("= 0 else ("rgb8", out8[:, :, 0:3].copy()) + else: + kind, nat = "rgba16", q(rgba, 65535).astype(" Date: Sat, 31 Oct 2026 08:51:47 -0500 Subject: [PATCH 2/2] imgA-tiff: bench block (decode / encode none, lzw, deflate; rgba16) --- tools/bench.luau | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/tools/bench.luau b/tools/bench.luau index 9f6aef7..8b27f59 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -56,3 +56,27 @@ do Png.encode(img) end) end + +-- ------------------------------------------------------------------------------------------------ image/tiff (ws-imgA) +do + local Tiff = require("@formats/image/tiff") + local Types = require("@formats/Types") + local src = Types.Image.new(1024, 768) + for i = 0, 1024 * 768 - 1 do + local x, y = i % 1024, i // 1024 + buffer.writeu32(src.pixels, i * 4, 0xFF000000 + (x % 256) + ((y % 256) * 256) + (((x + y) // 4 % 256) * 65536)) + end + for _, comp in { "none", "lzw", "deflate" } do + local enc = Tiff.encode(src, { compression = comp :: any }) :: buffer + bench("tiff decode rgba8 " .. comp, 3, 1024 * 768 * 4, function() + Tiff.decode(Bytes.reader(enc)) + end) + bench("tiff encode rgba8 " .. comp, 2, 1024 * 768 * 4, function() + Tiff.encode(src, { compression = comp :: any }) + end) + end + local enc16 = Tiff.encode(Types.Image.new(1024, 768, "rgba16"), { compression = "lzw" }) :: buffer + bench("tiff decode rgba16 lzw -> rgba8", 3, 1024 * 768 * 8, function() + Tiff.decode(Bytes.reader(enc16)) + end) +end