842 lines
27 KiB
Luau
842 lines
27 KiB
Luau
--!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
|