From 84c461f10dde975ee797ce7644d7d30cad5d67ba Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:45:33 -0500 Subject: [PATCH] imgA-simple: image/pnm (PBM/PGM/PPM ASCII + binary, PAM, PFM; read/write, 16-bit, odd maxvals) against ImageMagick --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/image/pnm/Codec.luau | 289 +++++++++++++++++++++++ src/Formats/image/pnm/init.luau | 383 +++++++++++++++++++++++++++++++ tests/image/pnm.luau | 125 ++++++++++ tools/fixtures/pnm.py | 93 ++++++++ 6 files changed, 903 insertions(+) create mode 100644 src/Formats/image/pnm/Codec.luau create mode 100644 src/Formats/image/pnm/init.luau create mode 100644 tests/image/pnm.luau create mode 100644 tools/fixtures/pnm.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 84e2a3c..d6adcd8 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 | pnm | .pnm .pbm .pgm .ppm .pam .pfm | yes | yes | alpha: true, depths: 1, 8, 16, 32, float: true | `tests/image/pnm.luau` | | image | qoi | .qoi | yes | yes | alpha: true, depths: 8 | `tests/image/qoi.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 b482f97..3d0d3f3 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 = "pnm", + category = "image", + path = "image/pnm", + extensions = { "pnm", "pbm", "pgm", "ppm", "pam", "pfm" }, + mime = { "image/x-portable-anymap", "image/x-portable-bitmap", "image/x-portable-graymap", "image/x-portable-pixmap", "image/x-portable-arbitrarymap", "image/x-portable-floatmap" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, depths = { 1, 8, 16, 32 }, float = true }, + load = function() + return require("@formats/image/pnm") + end, + }, { name = "qoi", category = "image", diff --git a/src/Formats/image/pnm/Codec.luau b/src/Formats/image/pnm/Codec.luau new file mode 100644 index 0000000..5bc6285 --- /dev/null +++ b/src/Formats/image/pnm/Codec.luau @@ -0,0 +1,289 @@ +--!strict +--!native +--!optimize 2 +-- image/pnm/Codec: the Netpbm sample loops (native; never throws). Written from the Netpbm format pages (pbm, pgm, +-- ppm, pam, pfm). Reading: binary 8 / 16-bit samples, ASCII samples (P1 digits may run together), P4 bit rows, PFM +-- floats (either byte order, bottom-to-top rows); packing samples into a Types pixel format with maxval scaling. +-- Writing: samples of any pixel format extracted at 1..4 channels and 8 or 16 bits. Every read is bounds-checked. +local readu8, writeu8, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16 +local readf32, writef32, readu32, writeu32 = buffer.readf32, buffer.writef32, buffer.readu32, buffer.writeu32 +local byteswap = bit32.byteswap + +local Codec = {} + +-- readSamples(b, p, limit, count, mode, out) -> true | false, message: count raw values into out (u16 each). +-- mode 1 = binary 8-bit, 2 = binary 16-bit big-endian, 3 = ASCII decimal, 4 = ASCII P1 (single digits) +function Codec.readSamples(b: buffer, p: number, limit: number, count: number, mode: number, out: buffer): (boolean, string?) + if mode == 1 then + if p + count > limit then + return false, "truncated" + end + for i = 0, count - 1 do + writeu16(out, i * 2, readu8(b, p + i)) + end + return true, nil + elseif mode == 2 then + if p + count * 2 > limit then + return false, "truncated" + end + for i = 0, count - 1 do + writeu16(out, i * 2, readu8(b, p + i * 2) * 256 + readu8(b, p + i * 2 + 1)) + end + return true, nil + end + local i = 0 + while i < count do + -- skip whitespace and comments + while p < limit do + local c = readu8(b, p) + if c == 35 then -- '#' + while p < limit and readu8(b, p) ~= 10 and readu8(b, p) ~= 13 do + p += 1 + end + elseif c == 32 or (c >= 9 and c <= 13) then + p += 1 + else + break + end + end + if p >= limit then + return false, "truncated" + end + local c = readu8(b, p) + if c < 48 or c > 57 then + return false, "bad ASCII sample" + end + if mode == 4 then + writeu16(out, i * 2, c - 48) + p += 1 + else + local v = 0 + while p < limit do + local d = readu8(b, p) + if d < 48 or d > 57 then + break + end + v = math.min(v * 10 + d - 48, 65535) + p += 1 + end + writeu16(out, i * 2, v) + end + i += 1 + end + return true, nil +end + +-- readBits(b, p, limit, w, h, out) -> ok, message: P4 rows (MSB first, rows padded to bytes) as u16 0 / 1 values +function Codec.readBits(b: buffer, p: number, limit: number, w: number, h: number, out: buffer): (boolean, string?) + local rowBytes = (w + 7) // 8 + if p + rowBytes * h > limit then + return false, "truncated" + end + for y = 0, h - 1 do + local r = p + y * rowBytes + for x = 0, w - 1 do + local byte = readu8(b, r + x // 8) + writeu16(out, (y * w + x) * 2, (byte // 2 ^ (7 - x % 8)) % 2) + end + end + return true, nil +end + +-- format codes for pack / extract +Codec.RGBA8, Codec.RGB8, Codec.GRAY8, Codec.GRAYA8, Codec.RGBA16, Codec.GRAY16, Codec.RGBAF32 = 0, 1, 2, 3, 4, 5, 6 + +-- pack(samples, n, ch, maxval, invert, fmt, dst): n pixels of ch raw samples (u16, 0..maxval; invert: 1 - v for +-- PBM bits) into dst in pixel format fmt, scaled to the format's range (8-bit: round(v * 255 / maxval)) +function Codec.pack(s: buffer, n: number, ch: number, maxval: number, invert: boolean, fmt: number, dst: buffer) + local wide = fmt == 4 or fmt == 5 + local top = if wide then 65535 else 255 + local half = maxval // 2 + local function get(i: number): number + local v = math.min(readu16(s, i * 2), maxval) + if invert then + v = maxval - v + end + if maxval == top then + return v + end + return (v * top + half) // maxval + end + for i = 0, n - 1 do + local q = i * ch + local r, g, b, a + if ch == 1 then + r = get(q) + g, b, a = r, r, top + elseif ch == 2 then + r = get(q) + g, b, a = r, r, get(q + 1) + elseif ch == 3 then + r, g, b, a = get(q), get(q + 1), get(q + 2), top + else + r, g, b, a = get(q), get(q + 1), get(q + 2), get(q + 3) + end + if fmt == 0 then + writeu32(dst, i * 4, r + g * 256 + b * 65536 + a * 16777216) + elseif fmt == 1 then + writeu8(dst, i * 3, r) + writeu8(dst, i * 3 + 1, g) + writeu8(dst, i * 3 + 2, b) + elseif fmt == 2 then + writeu8(dst, i, r) + elseif fmt == 3 then + writeu8(dst, i * 2, r) + writeu8(dst, i * 2 + 1, a) + elseif fmt == 4 then + writeu16(dst, i * 8, r) + writeu16(dst, i * 8 + 2, g) + writeu16(dst, i * 8 + 4, b) + writeu16(dst, i * 8 + 6, a) + elseif fmt == 5 then + writeu16(dst, i * 2, r) + end + end +end + +-- readFloats(b, p, limit, w, h, ch, le, dst) -> ok, message: PFM rows (bottom-to-top) into rgbaf32 dst +function Codec.readFloats(b: buffer, p: number, limit: number, w: number, h: number, ch: number, le: boolean, dst: buffer): (boolean, string?) + if p + w * h * ch * 4 > limit then + return false, "truncated" + end + local tmp = buffer.create(4) + for y = 0, h - 1 do + local row = p + (h - 1 - y) * w * ch * 4 + for x = 0, w - 1 do + local o = (y * w + x) * 16 + for c = 0, ch - 1 do + local v + if le then + v = readf32(b, row + (x * ch + c) * 4) + else + writeu32(tmp, 0, byteswap(readu32(b, row + (x * ch + c) * 4))) + v = readf32(tmp, 0) + end + writef32(dst, o + c * 4, v) + end + if ch == 1 then + local v = readf32(dst, o) + writef32(dst, o + 4, v) + writef32(dst, o + 8, v) + end + writef32(dst, o + 12, 1) + end + end + return true, nil +end + +local function f(v: number): number + if v ~= v then + return 0 + end + return math.floor(math.clamp(v, 0, 1) * 65535 + 0.5) +end + +-- extract(px, fmt, n, ch, wide) -> u16 samples: n pixels of format fmt as ch channels (1 grey (Rec. 601 luma for +-- colour sources, Pillow's L = (299 R + 587 G + 114 B) / 1000), 2 grey + alpha, 3 RGB, 4 RGBA), 16-bit if wide +function Codec.extract(px: buffer, fmt: number, n: number, ch: number, wide: boolean): buffer + local out = buffer.create(n * ch * 2) + local srcWide = fmt == 4 or fmt == 5 + local isGray = fmt == 2 or fmt == 3 or fmt == 5 + for i = 0, n - 1 do + local r, g, b, a + if fmt == 0 then + r, g, b, a = readu8(px, i * 4), readu8(px, i * 4 + 1), readu8(px, i * 4 + 2), readu8(px, i * 4 + 3) + elseif fmt == 1 then + r, g, b, a = readu8(px, i * 3), readu8(px, i * 3 + 1), readu8(px, i * 3 + 2), 255 + elseif fmt == 2 then + r = readu8(px, i) + g, b, a = r, r, 255 + elseif fmt == 3 then + r, a = readu8(px, i * 2), readu8(px, i * 2 + 1) + g, b = r, r + elseif fmt == 4 then + r, g, b, a = readu16(px, i * 8), readu16(px, i * 8 + 2), readu16(px, i * 8 + 4), readu16(px, i * 8 + 6) + elseif fmt == 5 then + r = readu16(px, i * 2) + g, b, a = r, r, 65535 + else + r, g, b, a = f(readf32(px, i * 16)), f(readf32(px, i * 16 + 4)), f(readf32(px, i * 16 + 8)), f(readf32(px, i * 16 + 12)) + end + local w16 = srcWide or fmt == 6 + local gray = r + if ch <= 2 and not isGray then + gray = (r * 299 + g * 587 + b * 114) // 1000 + end + local vals = if ch == 1 then 1 elseif ch == 2 then 2 else ch + for c = 0, vals - 1 do + local v + if ch <= 2 then + v = if c == 0 then gray else a + else + v = if c == 0 then r elseif c == 1 then g elseif c == 2 then b else a + end + if wide and not w16 then + v *= 257 + elseif w16 and not wide then + v = (v * 255 + 32767) // 65535 + end + writeu16(out, (i * ch + c) * 2, v) + end + end + return out +end + +-- writeSamples(s, count, wide, out, o) -> new offset: binary samples (8-bit or 16-bit big-endian) +function Codec.writeSamples(s: buffer, count: number, wide: boolean, out: buffer, o: number): number + if wide then + for i = 0, count - 1 do + local v = readu16(s, i * 2) + writeu8(out, o, v // 256) + writeu8(out, o + 1, v % 256) + o += 2 + end + else + for i = 0, count - 1 do + writeu8(out, o, readu16(s, i * 2)) + o += 1 + end + end + return o +end + +-- writeBits(s, w, h, threshold, out, o) -> new offset: P4 rows from grey samples (below threshold = black = 1) +function Codec.writeBits(s: buffer, w: number, h: number, threshold: number, out: buffer, o: number): number + for y = 0, h - 1 do + local acc, nb = 0, 0 + for x = 0, w - 1 do + acc = acc * 2 + (if readu16(s, (y * w + x) * 2) < threshold then 1 else 0) + nb += 1 + if nb == 8 then + writeu8(out, o, acc) + o += 1 + acc, nb = 0, 0 + end + end + if nb > 0 then + writeu8(out, o, acc * 2 ^ (8 - nb)) + o += 1 + end + end + return o +end + +-- writeFloats(px, w, h, ch, out, o) -> new offset: rgbaf32 (ch 3) or its first channel (ch 1) as little-endian PFM +-- rows, bottom-to-top +function Codec.writeFloats(px: buffer, w: number, h: number, ch: number, out: buffer, o: number): number + for y = h - 1, 0, -1 do + for x = 0, w - 1 do + local q = (y * w + x) * 16 + for c = 0, ch - 1 do + writef32(out, o, readf32(px, q + c * 4)) + o += 4 + end + end + end + return o +end + +return Codec diff --git a/src/Formats/image/pnm/init.luau b/src/Formats/image/pnm/init.luau new file mode 100644 index 0000000..237e474 --- /dev/null +++ b/src/Formats/image/pnm/init.luau @@ -0,0 +1,383 @@ +--!strict +-- image/pnm: the Netpbm family, written from the Netpbm format pages: PBM (P1 ASCII / P4 binary), PGM (P2 / P5), +-- PPM (P3 / P6), PAM (P7: BLACKANDWHITE, GRAYSCALE, GRAYSCALE_ALPHA, RGB, RGB_ALPHA and their _ALPHA forms, any +-- tuple type of depth 1..4) and PFM (PF colour / Pf grey 32-bit float, either byte order, bottom-to-top rows). +-- maxval 1..65535 (scaled to 8 bits by round(v * 255 / maxval)). Decode: rgba8, or with opts.native the source layout +-- (gray8, gray16, graya8, rgb8, rgba8, rgba16 for 16-bit colour or grey + alpha, rgbaf32 for PFM). PFM to rgba8 is +-- clamp(v, 0, 1) * 255 rounded (linear, no gamma). Encode: any of the seven types, binary or ASCII, from every pixel +-- format; the subtype comes from opts.format / the file extension (pbm, pgm, ppm, pam, pfm) or the image. +-- Not supported: multi-image streams (the first image is read), PAM depths above 4. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Codec = require("@formats/image/pnm/Codec") + +-- ------------------------------------------------------------------------------------------------ contract +local Pnm = { + name = "pnm", + category = "image", + extensions = { "pnm", "pbm", "pgm", "ppm", "pam", "pfm" }, + mime = { "image/x-portable-anymap", "image/x-portable-bitmap", "image/x-portable-graymap", "image/x-portable-pixmap", "image/x-portable-arbitrarymap", "image/x-portable-floatmap" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, depths = { 1, 8, 16, 32 }, float = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + native: boolean?, -- keep the source layout (default false: rgba8) + maxPixels: number?, -- refuse larger images (default 2^26) +} +export type EncodeOptions = { + format: string?, -- "pbm" | "pgm" | "ppm" | "pam" | "pfm" (default: from the image: grey -> pgm, opaque colour + -- -> ppm, alpha -> pam, rgbaf32 -> pfm); "pnm" means the default + ascii: boolean?, -- P1 / P2 / P3 instead of P4 / P5 / P6 (default false) + maxval: number?, -- 1..65535 (default 255, or 65535 for 16-bit / float sources); pbm ignores it + threshold: number?, -- pbm: grey below this (0..255) is black (default 128) +} + +-- ------------------------------------------------------------------------------------------------ constants +local FMT_CODE = { rgba8 = 0, rgb8 = 1, gray8 = 2, graya8 = 3, rgba16 = 4, gray16 = 5, rgbaf32 = 6 } +local BPP = { rgba8 = 4, rgb8 = 3, gray8 = 1, graya8 = 2, rgba16 = 8, gray16 = 2, rgbaf32 = 16 } +local readu8 = buffer.readu8 + +-- ------------------------------------------------------------------------------------------------ sniff +function Pnm.sniff(r: Bytes.Reader): number + if r:remaining() < 3 then + return 0 + end + local a, b, c = r:peekU8(0), r:peekU8(1), r:peekU8(2) + if a ~= 80 then -- 'P' + return 0 + end + local ws = c == 32 or (c >= 9 and c <= 13) + if b >= 49 and b <= 55 and ws then -- P1..P7 + return 0.9 + end + if (b == 70 or b == 102) and ws then -- PF / Pf + return 0.9 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function isSpace(c: number): boolean + return c == 32 or (c >= 9 and c <= 13) +end + +-- the next header token from p: token, position after it (nil at the end) +local function token(b: buffer, p: number, limit: number): (string?, number) + while p < limit do + local c = readu8(b, p) + if c == 35 then + while p < limit and readu8(b, p) ~= 10 and readu8(b, p) ~= 13 do + p += 1 + end + elseif isSpace(c) then + p += 1 + else + break + end + end + local s = p + while p < limit and not isSpace(readu8(b, p)) and readu8(b, p) ~= 35 do + p += 1 + end + if p == s then + return nil, p + end + return buffer.readstring(b, s, p - s), p +end + +local function int(s: string?): number? + if s == nil or not string.match(s, "^%d+$") or #s > 9 then + return nil + end + return tonumber(s) +end + +function Pnm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local native = opts and opts.native or false + local b, limit = r.buf, r.limit + if r.limit - r.base < 3 or readu8(b, r.base) ~= 80 then + return nil, Err.new(Err.CORRUPT, "not a Netpbm file", r.base) + end + local kind = string.char(readu8(b, r.base + 1)) + local p = r.base + 2 + local w, h, maxval, ch, mode + local bits = false -- PBM: 1 = black + local bw = false -- PAM BLACKANDWHITE: 1 = white + local tupl: string? = nil + local scale: number? = nil + if kind == "1" or kind == "2" or kind == "3" or kind == "4" or kind == "5" or kind == "6" or kind == "F" or kind == "f" then + local t1, t2, t3 + t1, p = token(b, p, limit) + t2, p = token(b, p, limit) + w, h = int(t1), int(t2) + if kind == "1" or kind == "4" then + maxval = 1 + elseif kind == "F" or kind == "f" then + t3, p = token(b, p, limit) + scale = if t3 then tonumber(t3) else nil + if scale == nil or scale == 0 then + return nil, Err.new(Err.CORRUPT, "bad PFM scale", p) + end + maxval = 1 + else + t3, p = token(b, p, limit) + maxval = int(t3) + end + if w == nil or h == nil or maxval == nil then + return nil, if p >= limit then Err.new(Err.TRUNCATED, "header ends early", p) else Err.new(Err.CORRUPT, "bad header", p) + end + if kind ~= "1" and kind ~= "2" and kind ~= "3" then + p += 1 -- exactly one whitespace byte before binary data + end + ch = if kind == "3" or kind == "6" or kind == "F" then 3 else 1 + bits = kind == "1" or kind == "4" + mode = if kind == "1" then 4 elseif kind == "2" or kind == "3" then 3 elseif kind == "4" then 0 elseif maxval > 255 then 2 else 1 + elseif kind == "7" then + local depth + while true do + local key + key, p = token(b, p, limit) + if key == nil then + return nil, Err.new(Err.TRUNCATED, "PAM header ends early", p) + end + if key == "ENDHDR" then + break + end + local v + v, p = token(b, p, limit) + if key == "WIDTH" then + w = int(v) + elseif key == "HEIGHT" then + h = int(v) + elseif key == "DEPTH" then + depth = int(v) + elseif key == "MAXVAL" then + maxval = int(v) + elseif key == "TUPLTYPE" then + tupl = v + -- the rest of the line belongs to the value + while p < limit and readu8(b, p) ~= 10 do + p += 1 + end + end + end + -- ENDHDR ends with a newline + while p < limit and readu8(b, p) ~= 10 do + p += 1 + end + p += 1 + if w == nil or h == nil or depth == nil or maxval == nil then + return nil, Err.new(Err.CORRUPT, "PAM header misses WIDTH / HEIGHT / DEPTH / MAXVAL", p) + end + if depth < 1 or depth > 4 then + return nil, Err.new(Err.UNSUPPORTED, "PAM depth " .. depth) + end + ch = depth + bw = tupl ~= nil and string.sub(tupl, 1, 13) == "BLACKANDWHITE" + mode = if maxval > 255 then 2 else 1 + else + return nil, Err.new(Err.CORRUPT, "not a Netpbm file", r.base) + end + if w < 1 or h < 1 or maxval < 1 or maxval > 65535 then + return nil, Err.new(Err.CORRUPT, string.format("bad size %d x %d or maxval %d", w, h, maxval)) + end + 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 n = w * h + local img: Types.Image + local colorType = if ch == 1 then "gray" elseif ch == 2 then "graya" elseif ch == 3 then "rgb" else "rgba" + if scale then + local f = Types.Image.new(w, h, "rgbaf32") + local ok, e = Codec.readFloats(b, p, limit, w, h, ch, (scale :: number) < 0, f.pixels) + if not ok then + return nil, Err.new(Err.TRUNCATED, tostring(e)) + end + img = f + if not native then + local o = Types.Image.new(w, h, "rgba8") + for i = 0, n * 4 - 1 do + local v = buffer.readf32(f.pixels, i * 4) + buffer.writeu8(o.pixels, i, if v ~= v then 0 else math.floor(math.clamp(v, 0, 1) * 255 + 0.5)) + end + img = o + end + img.meta.source = { format = "pnm", type = if ch == 3 then "pfm" else "pfm-gray", bitDepth = 32, colorType = colorType, scale = math.abs(scale :: number), byteOrder = if (scale :: number) < 0 then "little" else "big" } + return img, nil + end + local samples = buffer.create(n * ch * 2) + local ok, e + if mode == 0 then + ok, e = Codec.readBits(b, p, limit, w, h, samples) + else + ok, e = Codec.readSamples(b, p, limit, n * ch, mode, samples) + end + if not ok then + return nil, Err.new(if e == "truncated" then Err.TRUNCATED else Err.CORRUPT, tostring(e)) + end + local fmt = "rgba8" + if native then + local wide = maxval > 255 + if bits or bw or ch == 1 then + fmt = if wide then "gray16" else "gray8" + elseif ch == 2 then + fmt = if wide then "rgba16" else "graya8" + elseif ch == 3 then + fmt = if wide then "rgba16" else "rgb8" + else + fmt = if wide then "rgba16" else "rgba8" + end + end + img = Types.Image.new(w, h, fmt :: Types.PixelFormat) + Codec.pack(samples, n, ch, maxval, bits, FMT_CODE[fmt], img.pixels) + local typ = if kind == "7" then "pam" elseif bits then "pbm" elseif ch == 1 then "pgm" else "ppm" + img.meta.source = { + format = "pnm", + type = typ, + ascii = mode == 3 or mode == 4, + bitDepth = if bits or bw then 1 elseif maxval > 255 then 16 else 8, + maxval = maxval, + colorType = if bits or bw then "bilevel" else colorType, + tupltype = tupl, + } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local SUBTYPES = { pbm = true, pgm = true, ppm = true, pam = true, pfm = true } + +function Pnm.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 fc = FMT_CODE[img.format] + if fc == nil then + return nil, Err.new(Err.ARG, "unsupported pixel format " .. tostring(img.format)) + end + local w, h = img.width, img.height + if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * BPP[img.format] then + return nil, Err.new(Err.ARG, "bad image size or pixel buffer") + end + local o: any = opts or {} + local n = w * h + local isGray = img.format == "gray8" or img.format == "gray16" or img.format == "graya8" + local hasAlpha = img.format == "graya8" or img.format == "rgba16" or img.format == "rgba8" or img.format == "rgbaf32" + if hasAlpha and img.format ~= "graya8" then + -- an alpha channel that is fully opaque does not count + local opaque = true + for i = 0, n - 1 do + local a + if img.format == "rgba8" then + a = buffer.readu8(img.pixels, i * 4 + 3) == 255 + elseif img.format == "rgba16" then + a = buffer.readu16(img.pixels, i * 8 + 6) == 65535 + else + a = buffer.readf32(img.pixels, i * 16 + 12) == 1 + end + if not a then + opaque = false + break + end + end + hasAlpha = not opaque + end + local sub = if type(o.format) == "string" then string.lower(o.format) else nil + if not (sub and SUBTYPES[sub]) then + if img.format == "rgbaf32" and not hasAlpha then + sub = "pfm" + elseif hasAlpha then + sub = "pam" + elseif isGray then + sub = "pgm" + else + sub = "ppm" + end + end + local ascii = o.ascii == true + local wideSrc = img.format == "gray16" or img.format == "rgba16" or img.format == "rgbaf32" + local maxval = o.maxval or (if wideSrc then 65535 else 255) + if type(maxval) ~= "number" or maxval < 1 or maxval > 65535 or maxval % 1 ~= 0 then + return nil, Err.new(Err.ARG, "maxval must be 1..65535") + end + local out: buffer + local op = 0 + local function header(s: string, extra: number) + out = buffer.create(#s + extra) + buffer.writestring(out, 0, s) + op = #s + end + if sub == "pfm" then + local ch = if isGray then 1 else 3 + local src = img + if img.format ~= "rgbaf32" then + local s = Codec.extract(img.pixels, fc, n, 4, true) + src = Types.Image.new(w, h, "rgbaf32") + for i = 0, n * 4 - 1 do + buffer.writef32(src.pixels, i * 4, buffer.readu16(s, i * 2) / 65535) + end + end + header(string.format("%s\n%d %d\n-1.0\n", if ch == 3 then "PF" else "Pf", w, h), n * ch * 4) + op = Codec.writeFloats(src.pixels, w, h, ch, out, op) + return out, nil + end + local ch = if sub == "pbm" or sub == "pgm" then 1 elseif sub == "ppm" then 3 elseif isGray then (if hasAlpha then 2 else 1) else (if hasAlpha then 4 else 3) + if sub == "pbm" then + local thr = o.threshold or 128 + local s = Codec.extract(img.pixels, fc, n, 1, false) + if ascii then + local parts = table.create(h + 1) + parts[1] = string.format("P1\n%d %d\n", w, h) + for y = 0, h - 1 do + local row = table.create(w) + for x = 0, w - 1 do + row[x + 1] = if buffer.readu16(s, (y * w + x) * 2) < thr then "1" else "0" + end + parts[y + 2] = table.concat(row, " ") .. "\n" + end + return buffer.fromstring(table.concat(parts)), nil + end + header(string.format("P4\n%d %d\n", w, h), ((w + 7) // 8) * h) + op = Codec.writeBits(s, w, h, thr, out, op) + return out, nil + end + local wide = maxval > 255 + local s = Codec.extract(img.pixels, fc, n, ch, wide) + if maxval ~= 255 and maxval ~= 65535 then + local top = if wide then 65535 else 255 + for i = 0, n * ch - 1 do + buffer.writeu16(s, i * 2, (buffer.readu16(s, i * 2) * maxval + top // 2) // top) + end + end + local magic + if sub == "pam" then + local tt = if ch == 1 then "GRAYSCALE" elseif ch == 2 then "GRAYSCALE_ALPHA" elseif ch == 3 then "RGB" else "RGB_ALPHA" + header(string.format("P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n", w, h, ch, maxval, tt), n * ch * (if wide then 2 else 1)) + op = Codec.writeSamples(s, n * ch, wide, out, op) + return out, nil + end + magic = if sub == "pgm" then (if ascii then "P2" else "P5") else (if ascii then "P3" else "P6") + if ascii then + local parts = table.create(h + 1) + parts[1] = string.format("%s\n%d %d\n%d\n", magic, w, h, maxval) + local rowLen = w * ch + for y = 0, h - 1 do + local row = table.create(rowLen) + for i = 0, rowLen - 1 do + row[i + 1] = tostring(buffer.readu16(s, (y * rowLen + i) * 2)) + end + parts[y + 2] = table.concat(row, " ") .. "\n" + end + return buffer.fromstring(table.concat(parts)), nil + end + header(string.format("%s\n%d %d\n%d\n", magic, w, h, maxval), n * ch * (if wide then 2 else 1)) + op = Codec.writeSamples(s, n * ch, wide, out, op) + return out, nil +end + +return Pnm diff --git a/tests/image/pnm.luau b/tests/image/pnm.luau new file mode 100644 index 0000000..a5b58e4 --- /dev/null +++ b/tests/image/pnm.luau @@ -0,0 +1,125 @@ +-- image/pnm tests: ImageMagick-written P1-P7 / PFM files (ASCII and binary, 8 / 16-bit, PAM tuple types, both PFM +-- byte orders) and hand-written edge cases (comments, packed P1 digits, odd maxvals) against ImageMagick's RGBA +-- decodes (8-bit; 16-bit and float natively); round trips of every subtype through our encoder, binary and ASCII; +-- errors; the fuzz no-throw pass. Fixtures: tools/fixtures/pnm.py. +local T = require("@tests/T") +local Pnm = require("@formats/image/pnm") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/pnm") + +local t = T.suite("pnm") + +t:eq(Pnm.name, "pnm", "name") +t:check(Pnm.caps.decode and Pnm.caps.encode, "caps") + +local function dec(data: any, opts: any?): (any, any) + return Pnm.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts) +end + +-- channel c (0..3) of pixel i of a native image, in 16-bit scale +local function chan16(img: any, i: number, c: number): number + local px, f = img.pixels, img.format + if f == "gray16" then + return if c == 3 then 65535 else buffer.readu16(px, i * 2) + elseif f == "rgba16" then + return buffer.readu16(px, i * 8 + c * 2) + elseif f == "gray8" then + return if c == 3 then 65535 else buffer.readu8(px, i) * 257 + elseif f == "graya8" then + return buffer.readu8(px, i * 2 + (if c == 3 then 1 else 0)) * 257 + elseif f == "rgb8" then + return if c == 3 then 65535 else buffer.readu8(px, i * 3 + c) * 257 + end + return buffer.readu8(px, i * 4 + c) * 257 +end + +for _, c in Fx do + local img, err = dec(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") + local worst = 0 + for i = 0, c.width * c.height * 4 - 1 do + worst = math.max(worst, math.abs(buffer.readu8(img.pixels, i) - string.byte(c.rgba8, i + 1))) + end + t:check(worst <= c.tol, string.format("%s: max difference %d against ImageMagick (allowed %d)", c.name, worst, c.tol)) + local nat = dec(c.data, { native = true }) + if c.rgba16 then + local w16 = 0 + for i = 0, c.width * c.height - 1 do + for k = 0, 3 do + local o = (i * 4 + k) * 2 + 1 + local want = string.byte(c.rgba16, o) * 256 + string.byte(c.rgba16, o + 1) + w16 = math.max(w16, math.abs(chan16(nat, i, k) - want)) + end + end + t:check(w16 <= c.tol * 66, string.format("%s: 16-bit max difference %d", c.name, w16)) + end + if c.floats then + t:eq(nat.format, "rgbaf32", c.name .. ": native float") + local fb = buffer.fromstring(c.floats) + local fw = 0 + for i = 0, c.width * c.height * 4 - 1 do + fw = math.max(fw, math.abs(buffer.readf32(nat.pixels, i * 4) - buffer.readf32(fb, i * 4))) + end + t:check(fw < 1e-6, c.name .. ": floats") + end + -- round trips through our encoder: the same subtype, binary and ASCII + local ext = string.match(c.name, "%.(%a+)$") + for _, ascii in { false, true } do + local enc, eerr = Pnm.encode(nat, { format = ext, ascii = ascii }) + t:check(enc, c.name .. ": encode: " .. tostring(eerr)) + local back = dec(enc, { native = true }) + t:check(back and back.format == nat.format and buffer.tostring(back.pixels) == buffer.tostring(nat.pixels), string.format("%s: round trip (ascii %s)", c.name, tostring(ascii))) + end +end +t:note("%d files match ImageMagick and round-trip", #Fx) + +-- encoder choices, conversions, options +do + local img = Types.Image.new(3, 2) + for i = 0, 23 do + buffer.writeu8(img.pixels, i, (i * 40) % 256) + end + for i = 0, 5 do + buffer.writeu8(img.pixels, i * 4 + 3, 255) + end + local s = buffer.tostring(Pnm.encode(img) :: buffer) + t:eq(string.sub(s, 1, 2), "P6", "opaque rgba8 -> P6") + buffer.writeu8(img.pixels, 3, 7) + t:eq(string.sub(buffer.tostring(Pnm.encode(img) :: buffer), 1, 2), "P7", "alpha -> PAM") + t:eq(string.sub(buffer.tostring(Pnm.encode(img, { format = "pgm" }) :: buffer), 1, 2), "P5", "pgm by name") + t:eq(string.sub(buffer.tostring(Pnm.encode(img, { format = "pbm", ascii = true }) :: buffer), 1, 2), "P1", "ascii pbm") + t:eq(string.sub(buffer.tostring(Pnm.encode(img, { format = "pfm" }) :: buffer), 1, 2), "PF", "pfm by name") + local g = Types.Image.new(2, 1, "gray8") + t:eq(string.sub(buffer.tostring(Pnm.encode(g) :: buffer), 1, 2), "P5", "gray8 -> P5") + local m = Pnm.encode(g, { maxval = 15, ascii = true }) :: buffer + t:check(string.find(buffer.tostring(m), "\n15\n", 1, true) ~= nil, "maxval option") + local _, e = Pnm.encode(img, { maxval = 0 }) + t:check(e and e.code == Err.ARG, "bad maxval") + local _, e2 = Pnm.encode({} :: any) + t:check(e2 and e2.code == Err.ARG, "not an image") + t:eq(Pnm.sniff(Bytes.reader(buffer.fromstring("P6\n1 1\n255\n..."))), 0.9, "sniff") + t:eq(Pnm.sniff(Bytes.reader(buffer.fromstring("PNG"))), 0, "sniff other") + local _, e3 = dec("P6\n100 100\n255\n" .. string.rep("x", 50)) + t:check(e3 and e3.code == Err.TRUNCATED, "truncated") + local _, e4 = dec("P6\n10 10\n255\n", { maxPixels = 50 }) + t:check(e4 and e4.code == Err.LIMIT, "maxPixels") + local _, e5 = dec("P3\n1 1\n255\n1 x 3\n") + t:check(e5 and e5.code == Err.CORRUPT, "bad ascii") +end + +do + local samples = {} + for i, c in Fx do + if i % 3 == 0 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + return Pnm.decode(Bytes.reader(b)) + end, samples) +end + +t:done() diff --git a/tools/fixtures/pnm.py b/tools/fixtures/pnm.py new file mode 100644 index 0000000..e2b2646 --- /dev/null +++ b/tools/fixtures/pnm.py @@ -0,0 +1,93 @@ +# Netpbm fixtures (tools/fixtures.py): files written by ImageMagick (P1-P7, ASCII / binary, 8 / 16-bit, PAM tuple +# types, PFM both byte orders) and a few hand-written edge cases (comments, packed P1 digits, odd maxvals, PAM +# GRAYSCALE_ALPHA / BLACKANDWHITE); references = ImageMagick's RGBA decodes (8-bit, and 16-bit for 16-bit files). +# tests/gen/pnm.luau { { name, data, width, height, rgba8 (bytes), rgba16? (bytes, big-endian), tol, floats? } } +import os, random, shutil, struct, subprocess, tempfile + + +def generate(ctx): + magick = ctx.nix("imagemagick", ["sh", "-c", "command -v magick"]).decode().strip() + work = tempfile.mkdtemp(prefix="formats-pnm-") + try: + _generate(ctx, magick, work) + finally: + shutil.rmtree(work, ignore_errors=True) + + +def _generate(ctx, magick, work): + rng = random.Random(3) + W = lambda n: os.path.join(work, n) + + def run(*args, inp=None): + r = subprocess.run([magick] + list(args), input=inp, capture_output=True) + if r.returncode != 0: + raise SystemExit("fixtures/pnm: magick %s failed: %s" % (" ".join(args), r.stderr.decode())) + return r.stdout + + # a 16-bit RGBA source with gradients, noise and transparency, written as a 16-bit PAM for ImageMagick + w, h = 37, 23 + src = bytearray() + for y in range(h): + for x in range(w): + r = (x * 65535) // (w - 1) + g = (y * 65535) // (h - 1) + b = rng.randrange(65536) + a = 65535 if (x + y) % 5 else (x * 3000) % 65536 + src += struct.pack(">HHHH", r, g, b, a) + open(W("src.pam"), "wb").write(b"P7\nWIDTH %d\nHEIGHT %d\nDEPTH 4\nMAXVAL 65535\nTUPLTYPE RGB_ALPHA\nENDHDR\n" % (w, h) + bytes(src)) + + cases = [] + + def ref(path, wide, tol=0, floats=None, name=None): + data = open(path, "rb").read() + c = {"name": name or os.path.basename(path), "data": data, "tol": tol} + info = run(path, "-format", "%w %h", "info:").decode().split() + c["width"], c["height"] = int(info[0]), int(info[1]) + c["rgba8"] = run(path, "-depth", "8", "rgba:-") + if wide: + c["rgba16"] = run(path, "-depth", "16", "-endian", "MSB", "rgba:-") + if floats is not None: + c["floats"] = floats + cases.append(c) + + variants = [ + ("p1.pbm", ["-colorspace", "gray", "-threshold", "50%", "-compress", "none"], "pbm:", False), + ("p4.pbm", ["-colorspace", "gray", "-threshold", "50%"], "pbm:", False), + ("p2.pgm", ["-colorspace", "gray", "-depth", "8", "-compress", "none"], "pgm:", False), + ("p5.pgm", ["-colorspace", "gray", "-depth", "8"], "pgm:", False), + ("p5-16.pgm", ["-colorspace", "gray", "-depth", "16"], "pgm:", True), + ("p2-16.pgm", ["-colorspace", "gray", "-depth", "16", "-compress", "none"], "pgm:", True), + ("p3.ppm", ["-alpha", "off", "-depth", "8", "-compress", "none"], "ppm:", False), + ("p6.ppm", ["-alpha", "off", "-depth", "8"], "ppm:", False), + ("p6-16.ppm", ["-alpha", "off", "-depth", "16"], "ppm:", True), + ("p3-16.ppm", ["-alpha", "off", "-depth", "16", "-compress", "none"], "ppm:", True), + ("rgba.pam", ["-depth", "8"], "pam:", False), + ("rgba16.pam", ["-depth", "16"], "pam:", True), + ("rgb.pam", ["-alpha", "off", "-depth", "8"], "pam:", False), + ("gray.pam", ["-alpha", "off", "-colorspace", "gray", "-depth", "8"], "pam:", False), + ("graya.pam", ["-colorspace", "gray", "-depth", "8"], "pam:", False), + ("graya16.pam", ["-colorspace", "gray", "-depth", "16"], "pam:", True), + ("bw.pam", ["-alpha", "off", "-colorspace", "gray", "-threshold", "50%", "-type", "bilevel"], "pam:", False), + ] + for name, args, prefix, wide in variants: + run(W("src.pam"), *args, prefix + W(name)) + ref(W(name), wide) + for endian in ("LSB", "MSB"): + for col in ("rgb", "gray"): + name = "%s-%s.pfm" % (col, endian) + extra = ["-colorspace", "gray"] if col == "gray" else [] + run(W("src.pam"), "-alpha", "off", *extra, "-endian", endian, "pfm:" + W(name)) + fl = run(W(name), "-depth", "32", "-define", "quantum:format=floating-point", "-endian", "LSB", "rgba:-") + ref(W(name), False, tol=1, floats=fl) + + # hand-written edge cases (references from ImageMagick too) + def hand(name, data, wide=False, tol=0): + open(W(name), "wb").write(data) + ref(W(name), wide, tol=tol) + hand("comments.ppm", b"P6\n# a comment\n3 # inline\n2\n#another\n255\n" + bytes(range(18))) + hand("packed.pbm", b"P1\n5 3\n10101\n01010\n1 1 1 0 0\n") + hand("maxval1000.pgm", b"P2\n4 2\n1000\n0 250 500 1000\n999 1 333 750\n", wide=True, tol=1) + hand("maxval7.ppm", b"P3 2 2 7 0 1 2 3 4 5 6 7 7 7 0 0\n", tol=1) + hand("p4-odd.pbm", b"P4\n11 3\n" + bytes([0b10101010, 0b11100000, 0b00001111, 0b00100000, 0b11111111, 0b11000000])) + hand("graya-hand.pam", b"P7\nWIDTH 2\nHEIGHT 2\nDEPTH 2\nMAXVAL 255\nTUPLTYPE GRAYSCALE_ALPHA\nENDHDR\n" + bytes([0, 255, 100, 128, 200, 0, 255, 255])) + ctx.emit("pnm", cases)