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

This commit is contained in:
4DBug committed 2026-10-31 08:50:42 -05:00
1 parent ba91879bc5
commit b2dd3475ac
6 files changed
+1714

No files matched your search

+12
View File
@@ -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
+469
View File
@@ -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
+841
View File
@@ -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