diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 6a27c0b..81bdc07 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -6,8 +6,13 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | Category | Format | Extensions | Read | Write | Capabilities | Test | |---|---|---|---|---|---|---| | image | gif | .gif | yes | yes | animation: true, alpha: true, palette: true, depths: 1, 2, 4, 8 | `tests/image/gif.luau` | +| image | hdr | .hdr .pic .rgbe | yes | yes | alpha: false, float: true, depths: 32 | `tests/image/hdr.luau` | +| image | ico | .ico .cur | yes | yes | alpha: true, frames: true, depths: 1, 4, 8, 16, 24, 32 | `tests/image/ico.luau` | | image | jpeg | .jpg .jpeg .jpe .jfif | yes | yes | lossy: true, alpha: false, depths: 8, 12, progressive: true, arithmetic: true | `tests/image/jpeg.luau` | | 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` | +| image | tga | .tga .icb .vda .vst .tpic | yes | yes | alpha: true, palette: true, depths: 8, 15, 16, 24, 32 | `tests/image/tga.luau` | | image | tiff | .tif .tiff | yes | yes | alpha: true, pages: true, depths: 1, 2, 4, 8, 16, 32, float: true | `tests/image/tiff.luau` | Codecs (layer 1, shared by formats; not loadable on their own): diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6747154..3c40401 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -26,6 +26,30 @@ local list: { Entry } = { return require("@formats/image/gif") end, }, + { + name = "hdr", + category = "image", + path = "image/hdr", + extensions = { "hdr", "pic", "rgbe" }, + mime = { "image/vnd.radiance", "image/x-hdr" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = false, float = true, depths = { 32 } }, + load = function() + return require("@formats/image/hdr") + end, + }, + { + name = "ico", + category = "image", + path = "image/ico", + extensions = { "ico", "cur" }, + mime = { "image/vnd.microsoft.icon", "image/x-icon" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 4, 8, 16, 24, 32 } }, + load = function() + return require("@formats/image/ico") + end, + }, { name = "jpeg", category = "image", @@ -50,6 +74,42 @@ 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", + path = "image/qoi", + extensions = { "qoi" }, + mime = { "image/qoi", "image/x-qoi" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, depths = { 8 } }, + load = function() + return require("@formats/image/qoi") + end, + }, + { + name = "tga", + category = "image", + path = "image/tga", + extensions = { "tga", "icb", "vda", "vst", "tpic" }, + mime = { "image/x-tga", "image/x-targa" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8, 15, 16, 24, 32 } }, + load = function() + return require("@formats/image/tga") + end, + }, { name = "tiff", category = "image", diff --git a/src/Formats/image/hdr/Codec.luau b/src/Formats/image/hdr/Codec.luau new file mode 100644 index 0000000..7f97f5e --- /dev/null +++ b/src/Formats/image/hdr/Codec.luau @@ -0,0 +1,219 @@ +--!strict +--!native +--!optimize 2 +-- image/hdr/Codec: Radiance RGBE scanlines (native; never throws). Written from the Radiance file format notes +-- (Greg Ward, "Real Pixels", Graphics Gems II) and Bruce Walter's rgbe.c conventions: flat pixels, old-style RLE +-- (1, 1, 1, n repeats the previous pixel, shifted by 8 for consecutive markers) and new-style RLE (2, 2, width, then +-- four run-length coded channel planes). RGBE -> float is mantissa * 2^(e - 136), as rgbe.c, stb_image and +-- ImageMagick (no +0.5 offset); float -> RGBE as rgbe.c float2rgbe (frexp). Every read is bounds-checked. +local readu8, writeu8, writef32, readf32 = buffer.readu8, buffer.writeu8, buffer.writef32, buffer.readf32 +local frexp = math.frexp + +local Codec = {} + +-- readLine(b, p, limit, w, row) -> new position | nil, message: one scanline into row (w * 4 RGBE bytes) +function Codec.readLine(b: buffer, p: number, limit: number, w: number, row: buffer): (number?, string?) + if w >= 8 and w <= 32767 and p + 4 <= limit and readu8(b, p) == 2 and readu8(b, p + 1) == 2 and readu8(b, p + 2) < 128 then + if readu8(b, p + 2) * 256 + readu8(b, p + 3) ~= w then + return nil, "scanline width mismatch" + end + p += 4 + for c = 0, 3 do + local x = 0 + while x < w do + if p >= limit then + return nil, "truncated" + end + local n = readu8(b, p) + p += 1 + if n > 128 then + n -= 128 + if x + n > w or p >= limit then + return nil, if p >= limit then "truncated" else "bad run" + end + local v = readu8(b, p) + p += 1 + for i = x, x + n - 1 do + writeu8(row, i * 4 + c, v) + end + else + if n == 0 or x + n > w then + return nil, "bad count" + end + if p + n > limit then + return nil, "truncated" + end + for i = x, x + n - 1 do + writeu8(row, i * 4 + c, readu8(b, p)) + p += 1 + end + end + x += n + end + end + return p, nil + end + -- flat pixels, with old-style runs + local x = 0 + local shift = 0 + while x < w do + if p + 4 > limit then + return nil, "truncated" + end + local r, g, bl, e = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2), readu8(b, p + 3) + p += 4 + if r == 1 and g == 1 and bl == 1 then + if x == 0 then + return nil, "run at the start of a scanline" + end + local n = e * 2 ^ shift + if x + n > w then + return nil, "bad run" + end + local q = (x - 1) * 4 + local pr, pg, pb, pe = readu8(row, q), readu8(row, q + 1), readu8(row, q + 2), readu8(row, q + 3) + for i = x, x + n - 1 do + writeu8(row, i * 4, pr) + writeu8(row, i * 4 + 1, pg) + writeu8(row, i * 4 + 2, pb) + writeu8(row, i * 4 + 3, pe) + end + x += n + shift += 8 + if shift > 24 then + return nil, "bad run" + end + else + writeu8(row, x * 4, r) + writeu8(row, x * 4 + 1, g) + writeu8(row, x * 4 + 2, bl) + writeu8(row, x * 4 + 3, e) + x += 1 + shift = 0 + end + end + return p, nil +end + +-- toFloat(row, n, out, offsets): n RGBE pixels -> rgbaf32 at out byte offsets dest(i) = base + i * step +function Codec.toFloat(row: buffer, n: number, out: buffer, base: number, step: number) + for i = 0, n - 1 do + local q = i * 4 + local e = readu8(row, q + 3) + local o = base + i * step + if e == 0 then + writef32(out, o, 0) + writef32(out, o + 4, 0) + writef32(out, o + 8, 0) + else + local f = 2 ^ (e - 136) + writef32(out, o, readu8(row, q) * f) + writef32(out, o + 4, readu8(row, q + 1) * f) + writef32(out, o + 8, readu8(row, q + 2) * f) + end + writef32(out, o + 12, 1) + end +end + +-- fromFloat(px, y, w, row): row y of an rgbaf32 image -> w RGBE pixels (rgbe.c float2rgbe) +function Codec.fromFloat(px: buffer, y: number, w: number, row: buffer) + for x = 0, w - 1 do + local q = (y * w + x) * 16 + local r, g, b = readf32(px, q), readf32(px, q + 4), readf32(px, q + 8) + if r ~= r or r < 0 then + r = 0 + end + if g ~= g or g < 0 then + g = 0 + end + if b ~= b or b < 0 then + b = 0 + end + local v = math.max(r, g, b) + local o = x * 4 + if v < 1e-32 or v == math.huge then + if v == math.huge then + -- clamp infinities to the largest RGBE value + writeu8(row, o, if r == math.huge then 255 else 0) + writeu8(row, o + 1, if g == math.huge then 255 else 0) + writeu8(row, o + 2, if b == math.huge then 255 else 0) + writeu8(row, o + 3, 255) + else + writeu8(row, o, 0) + writeu8(row, o + 1, 0) + writeu8(row, o + 2, 0) + writeu8(row, o + 3, 0) + end + else + local m, e = frexp(v) + if e > 127 then + writeu8(row, o, 255) + writeu8(row, o + 1, 255) + writeu8(row, o + 2, 255) + writeu8(row, o + 3, 255) + else + local s = m * 256 / v + writeu8(row, o, math.min(255, math.floor(r * s))) + writeu8(row, o + 1, math.min(255, math.floor(g * s))) + writeu8(row, o + 2, math.min(255, math.floor(b * s))) + writeu8(row, o + 3, e + 128) + end + end + end +end + +-- writeLine(row, w, out, o) -> new offset: new-style RLE (rgbe.c RGBE_WriteBytes_RLE); out needs w * 4 + w + 8 +function Codec.writeLine(row: buffer, w: number, out: buffer, o: number): number + writeu8(out, o, 2) + writeu8(out, o + 1, 2) + writeu8(out, o + 2, w // 256) + writeu8(out, o + 3, w % 256) + o += 4 + for c = 0, 3 do + local cur = 0 + while cur < w do + -- find the next run of at least 4 + local begRun = cur + local runCount = 0 + local oldRun = 0 + while runCount < 4 and begRun < w do + begRun += runCount + oldRun = runCount + runCount = 1 + if begRun < w then + local v = readu8(row, begRun * 4 + c) + while begRun + runCount < w and runCount < 127 and readu8(row, (begRun + runCount) * 4 + c) == v do + runCount += 1 + end + end + end + -- a short run just before the long one + if oldRun > 1 and oldRun == begRun - cur then + writeu8(out, o, 128 + oldRun) + writeu8(out, o + 1, readu8(row, cur * 4 + c)) + o += 2 + cur = begRun + end + -- raw bytes up to the run + while cur < begRun do + local n = math.min(begRun - cur, 128) + writeu8(out, o, n) + o += 1 + for i = cur, cur + n - 1 do + writeu8(out, o, readu8(row, i * 4 + c)) + o += 1 + end + cur += n + end + if runCount >= 4 then + writeu8(out, o, 128 + runCount) + writeu8(out, o + 1, readu8(row, begRun * 4 + c)) + o += 2 + cur += runCount + end + end + end + return o +end + +return Codec diff --git a/src/Formats/image/hdr/init.luau b/src/Formats/image/hdr/init.luau new file mode 100644 index 0000000..ceb84a3 --- /dev/null +++ b/src/Formats/image/hdr/init.luau @@ -0,0 +1,234 @@ +--!strict +-- image/hdr: Radiance HDR / RGBE (.hdr, .pic), written from the Radiance file format notes and rgbe.c conventions. +-- Decode: "#?RADIANCE" / "#?RGBE" (any "#?" program name) headers, FORMAT=32-bit_rle_rgbe, EXPOSURE (the product of +-- every EXPOSURE line, kept in meta.exposure, not applied), other header lines in meta.text, the eight resolution +-- orientations (-Y +X standard, +Y, -X and the X-major ones), flat, old-style RLE and new-style RLE scanlines. +-- opts.native gives the linear rgbaf32 values (alpha 1); the default rgba8 is a display conversion: +-- round(clamp(v, 0, 1) ^ (1 / 2.2) * 255) per channel. Encode: rgbaf32 (or rgba8 through the inverse curve) to a +-- -Y +X file with new-style RLE (flat scanlines for widths outside 8..32767). +-- Not supported: FORMAT=32-bit_rle_xyze (CIE XYZ files: UNSUPPORTED), PRIMARIES / COLORCORR (ignored). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Codec = require("@formats/image/hdr/Codec") + +-- ------------------------------------------------------------------------------------------------ contract +local Hdr = { + name = "hdr", + category = "image", + extensions = { "hdr", "pic", "rgbe" }, + mime = { "image/vnd.radiance", "image/x-hdr" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = false, float = true, depths = { 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + native: boolean?, -- linear rgbaf32 (default false: rgba8 through a 1 / 2.2 display gamma) + maxPixels: number?, -- refuse larger images (default 2^26) +} +export type EncodeOptions = { + rle: boolean?, -- new-style RLE scanlines (default true) + exposure: number?, -- write an EXPOSURE line (default meta.exposure when not 1) +} + +-- ------------------------------------------------------------------------------------------------ constants +local GAMMA = 1 / 2.2 + +-- ------------------------------------------------------------------------------------------------ sniff +function Hdr.sniff(r: Bytes.Reader): number + local s = r:peek(10) + if s == "#?RADIANCE" then + return 1 + end + if string.sub(s, 1, 6) == "#?RGBE" then + return 1 + end + if string.sub(s, 1, 2) == "#?" and string.match(s, "^#%?%u") then + return 0.5 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Hdr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local b, limit = r.buf, r.limit + local p = r.base + -- header lines up to the first empty one + local function line(): string? + local s = p + while p < limit and buffer.readu8(b, p) ~= 10 do + p += 1 + end + if p >= limit then + return nil + end + local l = buffer.readstring(b, s, p - s) + p += 1 + return l + end + local first = line() + if not first or string.sub(first, 1, 2) ~= "#?" then + return nil, Err.new(Err.CORRUPT, "not a Radiance file (no #? line)", r.base) + end + local exposure = 1 + local format = nil + local text: { [string]: string } = {} + while true do + local l = line() + if l == nil then + return nil, Err.new(Err.TRUNCATED, "header ends early", p) + end + l = string.gsub(l, "\r$", "") + if l == "" then + break + end + local k, v = string.match(l, "^%s*([%w_%-]+)%s*=%s*(.-)%s*$") + if k == "FORMAT" then + format = v + elseif k == "EXPOSURE" then + local e = tonumber(v) + if e and e > 0 then + exposure *= e + end + elseif k then + text[k] = v :: string + end + end + if format and format ~= "32-bit_rle_rgbe" then + return nil, Err.new(Err.UNSUPPORTED, "FORMAT=" .. format) + end + local res = line() + if not res then + return nil, Err.new(Err.TRUNCATED, "no resolution line", p) + end + local s1, a1, n1, s2, a2, n2 = string.match(res, "^%s*([%+%-])([XY])%s+(%d+)%s+([%+%-])([XY])%s+(%d+)%s*$") + if not s1 or a1 == a2 or #n1 > 9 or #n2 > 9 then + return nil, Err.new(Err.CORRUPT, "bad resolution line", p) + end + local outer, inner = tonumber(n1) :: number, tonumber(n2) :: number + local w, h = if a1 == "Y" then inner else outer, if a1 == "Y" then outer else inner + if w < 1 or h < 1 then + return nil, Err.new(Err.CORRUPT, "zero size") + 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 img = Types.Image.new(w, h, "rgbaf32") + local px = img.pixels + local row = buffer.create(inner * 4) + local truncated = false + for i = 0, outer - 1 do + local np, err = Codec.readLine(b, p, limit, inner, row) + if not np then + if err == "truncated" then + truncated = true + break + end + return nil, Err.new(Err.CORRUPT, tostring(err), p) + end + p = np + -- where scanline i, pixel j lands: Y decreasing ("-Y") = top first, X increasing ("+X") = left first + local base, step + if a1 == "Y" then + local y = if s1 == "-" then i else h - 1 - i + if s2 == "+" then + base, step = y * w * 16, 16 + else + base, step = (y * w + w - 1) * 16, -16 + end + else + local x = if s1 == "+" then i else w - 1 - i + if s2 == "-" then + base, step = x * 16, w * 16 + else + base, step = ((h - 1) * w + x) * 16, -w * 16 + end + end + Codec.toFloat(row, inner, px, base, step) + end + if not (opts and opts.native) then + local o = Types.Image.new(w, h, "rgba8") + for i = 0, w * h - 1 do + for c = 0, 2 do + local v = buffer.readf32(px, i * 16 + c * 4) + buffer.writeu8(o.pixels, i * 4 + c, math.floor(math.clamp(v, 0, 1) ^ GAMMA * 255 + 0.5)) + end + buffer.writeu8(o.pixels, i * 4 + 3, 255) + end + o.meta = img.meta + img = o + end + img.meta.exposure = exposure + img.meta.colorSpace = "linear" + if next(text) then + img.meta.text = text + end + if truncated then + img.meta.truncated = true + end + img.meta.source = { format = "hdr", bitDepth = 32, colorType = "rgbe", program = string.sub(first, 3), orientation = string.format("%s%s %s%s", s1, a1, s2, a2) } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Hdr.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" or (img.format ~= "rgbaf32" and img.format ~= "rgba8") then + return nil, Err.new(Err.ARG, "needs an rgbaf32 or rgba8 Image") + end + local w, h = img.width, img.height + local bpp = if img.format == "rgbaf32" then 16 else 4 + 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 then + return nil, Err.new(Err.ARG, "bad image size or pixel buffer") + end + local o: any = opts or {} + local px = img.pixels + if bpp == 4 then + -- rgba8 through the inverse of the decoder's display curve + local lut = table.create(256, 0) + for v = 0, 255 do + lut[v + 1] = (v / 255) ^ 2.2 + end + px = buffer.create(w * h * 16) + for i = 0, w * h - 1 do + for c = 0, 2 do + buffer.writef32(px, i * 16 + c * 4, lut[buffer.readu8(img.pixels, i * 4 + c) + 1]) + end + buffer.writef32(px, i * 16 + 12, 1) + end + end + local exposure = o.exposure or (img.meta and img.meta.exposure) + local head = "#?RADIANCE\n# written by formats-luau\nFORMAT=32-bit_rle_rgbe\n" + if type(exposure) == "number" and exposure > 0 and exposure ~= 1 then + head ..= string.format("EXPOSURE=%.9g\n", exposure) + end + head ..= string.format("\n-Y %d +X %d\n", h, w) + local rle = o.rle ~= false and w >= 8 and w <= 32767 + local out = buffer.create(#head + h * (w * 5 + 8)) + buffer.writestring(out, 0, head) + local op = #head + local row = buffer.create(w * 4) + for y = 0, h - 1 do + Codec.fromFloat(px, y, w, row) + if rle then + op = Codec.writeLine(row, w, out, op) + else + buffer.copy(out, op, row, 0, w * 4) + for x = 0, w - 1 do + -- 1, 1, 1 would read as an old-style run marker + if buffer.readu8(out, op + x * 4) == 1 and buffer.readu8(out, op + x * 4 + 1) == 1 and buffer.readu8(out, op + x * 4 + 2) == 1 then + buffer.writeu8(out, op + x * 4 + 2, 0) + end + end + op += w * 4 + end + end + local res = buffer.create(op) + buffer.copy(res, 0, out, 0, op) + return res, nil +end + +return Hdr diff --git a/src/Formats/image/ico/Dib.luau b/src/Formats/image/ico/Dib.luau new file mode 100644 index 0000000..447fa5e --- /dev/null +++ b/src/Formats/image/ico/Dib.luau @@ -0,0 +1,106 @@ +--!strict +--!native +--!optimize 2 +-- image/ico/Dib: the BMP device-independent bitmaps inside ICO / CUR entries (native; never throws). Written from +-- the Microsoft ICO / BITMAPINFOHEADER documentation: a colour (XOR) bitmap of 1 / 4 / 8 / 16 (5-5-5) / 24 / 32-bit +-- pixels, bottom-up rows padded to 4 bytes, then a 1-bit AND mask (1 = transparent). 32-bit entries use their alpha +-- channel unless it is all zero (old icons), in which case the AND mask decides. +local readu8, readu16, readu32, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32 + +local Dib = {} + +-- decode(b, p, e, w, h, bpp, pal, palN, out) -> ok, message: the XOR + AND bitmaps at b[p, e) into rgba8 out +function Dib.decode(b: buffer, p: number, e: number, w: number, h: number, bpp: number, pal: buffer, palN: number, out: buffer): (boolean, string?) + local stride = ((w * bpp + 31) // 32) * 4 + local maskStride = ((w + 31) // 32) * 4 + if p + stride * h > e then + return false, "colour bitmap runs past the entry" + end + local hasMask = p + stride * h + maskStride * h <= e + local anyAlpha = false + for y = 0, h - 1 do + local row = p + (h - 1 - y) * stride + for x = 0, w - 1 do + local v + if bpp == 32 then + v = readu8(b, row + x * 4 + 2) + readu8(b, row + x * 4 + 1) * 256 + readu8(b, row + x * 4) * 65536 + readu8(b, row + x * 4 + 3) * 16777216 + if v >= 16777216 then + anyAlpha = true + end + elseif bpp == 24 then + v = readu8(b, row + x * 3 + 2) + readu8(b, row + x * 3 + 1) * 256 + readu8(b, row + x * 3) * 65536 + 0xFF000000 + elseif bpp == 16 then + local s = readu16(b, row + x * 2) + local r, g, bl = (s // 1024) % 32, (s // 32) % 32, s % 32 + v = (r * 255 + 15) // 31 + ((g * 255 + 15) // 31) * 256 + ((bl * 255 + 15) // 31) * 65536 + 0xFF000000 + else + local bit = x * bpp + local byte = readu8(b, row + bit // 8) + local idx = (byte // 2 ^ (8 - bpp - bit % 8)) % 2 ^ bpp + v = if idx < palN then readu32(pal, idx * 4) else 0xFF000000 + end + writeu32(out, (y * w + x) * 4, v) + end + end + if bpp == 32 and anyAlpha then + return true, nil + end + if hasMask then + local mp = p + stride * h + for y = 0, h - 1 do + local row = mp + (h - 1 - y) * maskStride + for x = 0, w - 1 do + local o = (y * w + x) * 4 + local px = readu32(out, o) % 16777216 + if (readu8(b, row + x // 8) // 2 ^ (7 - x % 8)) % 2 == 1 then + writeu32(out, o, px) -- transparent + else + writeu32(out, o, px + 0xFF000000) + end + end + end + elseif bpp == 32 then + -- no alpha and no mask: opaque + for i = 0, w * h - 1 do + writeu32(out, i * 4, readu32(out, i * 4) % 16777216 + 0xFF000000) + end + end + return true, nil +end + +-- encode(px, w, h, out, o) -> new offset: rgba8 as a 32-bit BGRA bitmap (bottom-up) + an AND mask (alpha 0 = 1). +-- out needs room for w * h * 4 + maskStride * h bytes. +function Dib.encode(px: buffer, w: number, h: number, out: buffer, o: number): number + for y = h - 1, 0, -1 do + for x = 0, w - 1 do + local q = (y * w + x) * 4 + buffer.writeu8(out, o, readu8(px, q + 2)) + buffer.writeu8(out, o + 1, readu8(px, q + 1)) + buffer.writeu8(out, o + 2, readu8(px, q)) + buffer.writeu8(out, o + 3, readu8(px, q + 3)) + o += 4 + end + end + local maskStride = ((w + 31) // 32) * 4 + for y = h - 1, 0, -1 do + local acc, nb, written = 0, 0, 0 + for x = 0, w - 1 do + acc = acc * 2 + (if readu8(px, (y * w + x) * 4 + 3) == 0 then 1 else 0) + nb += 1 + if nb == 8 then + buffer.writeu8(out, o + written, acc) + written += 1 + acc, nb = 0, 0 + end + end + if nb > 0 then + buffer.writeu8(out, o + written, acc * 2 ^ (8 - nb)) + written += 1 + end + buffer.fill(out, o + written, 0, maskStride - written) + o += maskStride + end + return o +end + +return Dib diff --git a/src/Formats/image/ico/init.luau b/src/Formats/image/ico/init.luau new file mode 100644 index 0000000..9fc05a1 --- /dev/null +++ b/src/Formats/image/ico/init.luau @@ -0,0 +1,282 @@ +--!strict +-- image/ico: Windows icons and cursors (ICO / CUR), written from Microsoft's ICO format documentation. Decode: every +-- directory entry, as a BMP DIB (1 / 4 / 8 / 16 / 24 / 32-bit with a colour table and the AND mask; 32-bit alpha) or +-- an embedded PNG, decoded through the api hook opts.decodeImage (F.load supplies it; without it PNG entries are +-- skipped, and a file of PNG entries only returns UNSUPPORTED). The image is the largest entry (then the deepest); +-- img.frames lists every decoded entry in file order (Types.Frame, each frame image with meta.source.bitDepth / png +-- and, for cursors, meta.hotspot = { x, y }). Encode: the image, or every img.frames image (each up to 256 x 256), as +-- 32-bit DIB entries with an AND mask; 256-pixel entries (or all with opts.png) as PNG through opts.encodeImage when it +-- is there; a cursor (CUR) with opts.cursor or when the image has meta.hotspot. +-- Not supported: resizing to a set of icon sizes (do that with ops/ImageOps first), DIB compression (BI_BITFIELDS +-- 16 / 32-bit is read as 5-5-5 / BGRA), the obsolete 2-colour planes. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Dib = require("@formats/image/ico/Dib") + +-- ------------------------------------------------------------------------------------------------ contract +local Ico = { + name = "ico", + category = "image", + extensions = { "ico", "cur" }, + mime = { "image/vnd.microsoft.icon", "image/x-icon" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 4, 8, 16, 24, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes PNG entries (the api passes one) + maxPixels: number?, -- refuse larger entries (default 2^26) +} +export type EncodeOptions = { + encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes PNG entries (the api passes one) + png: boolean?, -- every entry as PNG (needs encodeImage; default: only 256-pixel entries, when it exists) + cursor: boolean?, -- write a CUR (default: when the image has meta.hotspot) +} + +-- ------------------------------------------------------------------------------------------------ constants +local PNG_SIG = "\137PNG\r\n\26\n" +local readu8 = buffer.readu8 + +-- ------------------------------------------------------------------------------------------------ sniff +function Ico.sniff(r: Bytes.Reader): number + if r:remaining() < 22 then + return 0 + end + local b, o = r.buf, r.pos + local typ = buffer.readu16(b, o + 2) + local count = buffer.readu16(b, o + 4) + if buffer.readu16(b, o) ~= 0 or (typ ~= 1 and typ ~= 2) or count == 0 then + return 0 + end + -- the first entry: reserved byte 0, a size and offset inside the file + local size, off = buffer.readu32(b, o + 14), buffer.readu32(b, o + 18) + if readu8(b, o + 9) ~= 0 or size == 0 or off < 6 + count * 16 then + return 0 + end + return 0.8 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function le16(b: buffer, p: number): number + return buffer.readu16(b, p) +end +local function le32(b: buffer, p: number): number + return buffer.readu32(b, p) +end + +function Ico.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local decodeImage = opts and opts.decodeImage + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 6 then + return nil, Err.new(Err.TRUNCATED, "short header", base) + end + local typ, count = le16(b, base + 2), le16(b, base + 4) + if le16(b, base) ~= 0 or (typ ~= 1 and typ ~= 2) then + return nil, Err.new(Err.CORRUPT, "not an ICO / CUR file", base) + end + if count == 0 then + return nil, Err.new(Err.CORRUPT, "no images", base) + end + if base + 6 + count * 16 > limit then + return nil, Err.new(Err.TRUNCATED, "directory runs past the end", base) + end + local frames: { Types.Frame } = {} + local best: Types.Image? = nil + local bestScore = -1 + local skipped, lastErr = 0, nil :: Err.Err? + for i = 0, count - 1 do + local d = base + 6 + i * 16 + local dw, dh = readu8(b, d), readu8(b, d + 1) + dw = if dw == 0 then 256 else dw + dh = if dh == 0 then 256 else dh + local f1, f2 = le16(b, d + 4), le16(b, d + 6) + local size, off = le32(b, d + 8), le32(b, d + 12) + local p, e = base + off, base + off + size + local img: Types.Image? = nil + local depth = 0 + local isPng = false + if off < 6 or p >= limit then + lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. " lies past the end", d) + else + e = math.min(e, limit) + if e - p >= 8 and buffer.readstring(b, p, 8) == PNG_SIG then + isPng = true + depth = 32 + if decodeImage then + local sub = buffer.create(e - p) + buffer.copy(sub, 0, b, p, e - p) + local ok, pimg, perr = pcall(decodeImage, sub) + if ok and pimg and pimg.format == "rgba8" then + img = pimg + else + lastErr = if ok and perr then perr else Err.new(Err.CORRUPT, "entry " .. (i + 1) .. ": bad PNG") + end + else + lastErr = Err.new(Err.UNSUPPORTED, "PNG entries need opts.decodeImage (F.load passes it)") + end + elseif e - p >= 40 then + local hs = le32(b, p) + local bw = buffer.readi32(b, p + 4) + local bh = buffer.readi32(b, p + 8) + local bpp = le16(b, p + 14) + local clrUsed = le32(b, p + 32) + local w = if bw > 0 then bw else dw + local h = if bh ~= 0 then math.abs(bh) // 2 else dh + if hs < 12 or hs > e - p or w < 1 or h < 1 or w > 4096 or h > 4096 then + lastErr = Err.new(Err.CORRUPT, "entry " .. (i + 1) .. ": bad bitmap header", p) + elseif bpp ~= 1 and bpp ~= 4 and bpp ~= 8 and bpp ~= 16 and bpp ~= 24 and bpp ~= 32 then + lastErr = Err.new(Err.UNSUPPORTED, "entry " .. (i + 1) .. ": " .. bpp .. "-bit bitmap", p) + elseif w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + else + depth = bpp + local q = p + hs + local palN = 0 + local pal = buffer.create(4) + if bpp <= 8 then + palN = if clrUsed > 0 and clrUsed < 2 ^ bpp then clrUsed else 2 ^ bpp + if q + palN * 4 > e then + palN = 0 + lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. ": colour table runs past the entry", q) + else + pal = buffer.create(palN * 4) + for k = 0, palN - 1 do + local c = q + k * 4 + buffer.writeu32(pal, k * 4, readu8(b, c + 2) + readu8(b, c + 1) * 256 + readu8(b, c) * 65536 + 0xFF000000) + end + q += palN * 4 + end + end + if bpp > 8 or palN > 0 then + if bpp == 16 and le32(b, p + 16) == 3 then + q += 12 -- BI_BITFIELDS masks (assumed 5-5-5) + end + local out = Types.Image.new(w, h, "rgba8") + local ok, msg = Dib.decode(b, q, e, w, h, bpp, pal, palN, out.pixels) + if ok then + img = out + else + lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. ": " .. tostring(msg), q) + end + end + end + else + lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. " is too short", p) + end + end + if img then + local im = img :: Types.Image + im.meta.source = { format = "ico", bitDepth = depth, png = isPng, colorCount = readu8(b, d + 2) } + if typ == 2 then + im.meta.hotspot = { x = f1, y = f2 } + end + table.insert(frames, { image = im, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }) + local score = im.width * im.height * 64 + depth + if score > bestScore then + best, bestScore = im, score + end + else + skipped += 1 + end + end + if not best then + return nil, lastErr or Err.new(Err.CORRUPT, "no decodable entry") + end + local main = best :: Types.Image + local img = Types.Image.new(main.width, main.height, "rgba8") + buffer.copy(img.pixels, 0, main.pixels) + if #frames > 1 then + img.frames = frames + end + img.meta.source = { format = "ico", type = if typ == 2 then "cur" else "ico", bitDepth = main.meta.source and main.meta.source.bitDepth, entries = count, skipped = skipped, png = main.meta.source and main.meta.source.png } + img.meta.hotspot = main.meta.hotspot + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Ico.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" then + return nil, Err.new(Err.ARG, "needs an Image") + end + local o: any = opts or {} + local list: { Types.Image } = {} + if type(img.frames) == "table" and #img.frames > 0 then + for _, f in img.frames do + table.insert(list, f.image) + end + else + list[1] = img + end + local cursor = o.cursor + if cursor == nil then + cursor = type(img.meta) == "table" and img.meta.hotspot ~= nil + end + local blobs: { buffer } = {} + for i, im in list do + if type(im) ~= "table" or im.format ~= "rgba8" or type(im.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "entry " .. i .. ": needs an rgba8 Image") + end + local w, h = im.width, im.height + if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w > 256 or h > 256 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(im.pixels) < w * h * 4 then + return nil, Err.new(Err.ARG, "entry " .. i .. ": icons are 1..256 pixels per side") + end + local png = nil + if o.encodeImage and (o.png or w == 256 or h == 256) then + local ok, res, err = pcall(o.encodeImage, im, "png") + if not ok or not res then + return nil, if ok and err then err else Err.new(Err.ARG, "entry " .. i .. ": PNG encode failed") + end + png = res + elseif o.png then + return nil, Err.new(Err.ARG, "opts.png needs opts.encodeImage (F.save passes it)") + end + if png then + blobs[i] = png + else + local maskStride = ((w + 31) // 32) * 4 + local n = 40 + w * h * 4 + maskStride * h + local d = buffer.create(n) + buffer.writeu32(d, 0, 40) + buffer.writei32(d, 4, w) + buffer.writei32(d, 8, h * 2) + buffer.writeu16(d, 12, 1) + buffer.writeu16(d, 14, 32) + buffer.writeu32(d, 20, w * h * 4 + maskStride * h) + Dib.encode(im.pixels, w, h, d, 40) + blobs[i] = d + end + end + local total = 6 + #list * 16 + for _, bl in blobs do + total += buffer.len(bl) + end + local out = buffer.create(total) + buffer.writeu16(out, 2, if cursor then 2 else 1) + buffer.writeu16(out, 4, #list) + local off = 6 + #list * 16 + for i, im in list do + local d = 6 + (i - 1) * 16 + buffer.writeu8(out, d, im.width % 256) + buffer.writeu8(out, d + 1, im.height % 256) + if cursor then + local hs = (type(im.meta) == "table" and im.meta.hotspot) or (img.meta and img.meta.hotspot) or { x = 0, y = 0 } + buffer.writeu16(out, d + 4, math.clamp(math.floor(tonumber(hs.x) or 0), 0, 65535)) + buffer.writeu16(out, d + 6, math.clamp(math.floor(tonumber(hs.y) or 0), 0, 65535)) + else + buffer.writeu16(out, d + 4, 1) + buffer.writeu16(out, d + 6, 32) + end + buffer.writeu32(out, d + 8, buffer.len(blobs[i])) + buffer.writeu32(out, d + 12, off) + buffer.copy(out, off, blobs[i]) + off += buffer.len(blobs[i]) + end + return out, nil +end + +return Ico 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/src/Formats/image/qoi/Codec.luau b/src/Formats/image/qoi/Codec.luau new file mode 100644 index 0000000..2936f07 --- /dev/null +++ b/src/Formats/image/qoi/Codec.luau @@ -0,0 +1,144 @@ +--!strict +--!native +--!optimize 2 +-- image/qoi/Codec: the QOI op loops (native; never throws). Written from the QOI specification 1.0 (qoiformat.org). +-- decode reads ops from b[p, limit) into an rgba8 buffer; encode writes ops for rgba8 / rgb8 pixels. Every input read +-- is checked against limit; the output buffer has exactly w * h * 4 bytes and the loop stops when it is full. +local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32 + +local Codec = {} + +local index = buffer.create(256) + +-- decode(b, p, limit, out, n) -> true | false, "truncated" (n pixels into out) +function Codec.decode(b: buffer, p: number, limit: number, out: buffer, n: number): (boolean, string?) + buffer.fill(index, 0, 0, 256) + local r, g, bl, a = 0, 0, 0, 255 + local o = 0 + local stop = n * 4 + while o < stop do + if p >= limit then + return false, "truncated" + end + local op = readu8(b, p) + p += 1 + if op == 0xFE then + if p + 3 > limit then + return false, "truncated" + end + r, g, bl = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2) + p += 3 + elseif op == 0xFF then + if p + 4 > limit then + return false, "truncated" + end + r, g, bl, a = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2), readu8(b, p + 3) + p += 4 + else + local tag = op // 64 + if tag == 0 then + local q = op * 4 + r, g, bl, a = readu8(index, q), readu8(index, q + 1), readu8(index, q + 2), readu8(index, q + 3) + elseif tag == 1 then + r = (r + (op // 16) % 4 - 2) % 256 + g = (g + (op // 4) % 4 - 2) % 256 + bl = (bl + op % 4 - 2) % 256 + elseif tag == 2 then + if p >= limit then + return false, "truncated" + end + local d2 = readu8(b, p) + p += 1 + local dg = op % 64 - 32 + g = (g + dg) % 256 + r = (r + dg + d2 // 16 - 8) % 256 + bl = (bl + dg + d2 % 16 - 8) % 256 + else + local run = op % 64 -- 1..62 more copies of the previous pixel (63 / 64 are RGB / RGBA) + local v = r + g * 256 + bl * 65536 + a * 16777216 + local e = math.min(o + run * 4, stop - 4) + while o < e do + writeu32(out, o, v) + o += 4 + end + end + end + writeu32(out, o, r + g * 256 + bl * 65536 + a * 16777216) + o += 4 + local h = ((r * 3 + g * 5 + bl * 7 + a * 11) % 64) * 4 + writeu8(index, h, r) + writeu8(index, h + 1, g) + writeu8(index, h + 2, bl) + writeu8(index, h + 3, a) + end + return true, nil +end + +-- encode(px, n, bpp, out, o) -> new offset: n pixels of bpp (3 or 4) bytes; out has room for n * (bpp + 1) bytes +function Codec.encode(px: buffer, n: number, bpp: number, out: buffer, o: number): number + buffer.fill(index, 0, 0, 256) + local pr, pg, pb, pa = 0, 0, 0, 255 + local run = 0 + local hasA = bpp == 4 + for i = 0, n - 1 do + local q = i * bpp + local r, g, b = readu8(px, q), readu8(px, q + 1), readu8(px, q + 2) + local a = if hasA then readu8(px, q + 3) else 255 + if r == pr and g == pg and b == pb and a == pa then + run += 1 + if run == 62 or i == n - 1 then + writeu8(out, o, 0xC0 + run - 1) + o += 1 + run = 0 + end + else + if run > 0 then + writeu8(out, o, 0xC0 + run - 1) + o += 1 + run = 0 + end + local h = (r * 3 + g * 5 + b * 7 + a * 11) % 64 + local hq = h * 4 + if readu8(index, hq) == r and readu8(index, hq + 1) == g and readu8(index, hq + 2) == b and readu8(index, hq + 3) == a then + writeu8(out, o, h) + o += 1 + else + writeu8(index, hq, r) + writeu8(index, hq + 1, g) + writeu8(index, hq + 2, b) + writeu8(index, hq + 3, a) + if a == pa then + local dr = (r - pr + 128) % 256 - 128 + local dg = (g - pg + 128) % 256 - 128 + local db = (b - pb + 128) % 256 - 128 + local dgr, dgb = dr - dg, db - dg + if dr >= -2 and dr <= 1 and dg >= -2 and dg <= 1 and db >= -2 and db <= 1 then + writeu8(out, o, 0x40 + (dr + 2) * 16 + (dg + 2) * 4 + db + 2) + o += 1 + elseif dg >= -32 and dg <= 31 and dgr >= -8 and dgr <= 7 and dgb >= -8 and dgb <= 7 then + writeu8(out, o, 0x80 + dg + 32) + writeu8(out, o + 1, (dgr + 8) * 16 + dgb + 8) + o += 2 + else + writeu8(out, o, 0xFE) + writeu8(out, o + 1, r) + writeu8(out, o + 2, g) + writeu8(out, o + 3, b) + o += 4 + end + else + writeu8(out, o, 0xFF) + writeu8(out, o + 1, r) + writeu8(out, o + 2, g) + writeu8(out, o + 3, b) + writeu8(out, o + 4, a) + o += 5 + end + end + pr, pg, pb, pa = r, g, b, a + end + end + return o +end + +return Codec diff --git a/src/Formats/image/qoi/init.luau b/src/Formats/image/qoi/init.luau new file mode 100644 index 0000000..ef11dc6 --- /dev/null +++ b/src/Formats/image/qoi/init.luau @@ -0,0 +1,122 @@ +--!strict +-- image/qoi: QOI, the Quite OK Image format (specification 1.0, qoiformat.org). New code written from the spec. +-- Supports: decode of RGB and RGBA files (either colour space tag) to rgba8 (opts.native: rgb8 for 3-channel files); +-- encode of rgba8 (4 channels) and rgb8 (3 channels), lossless; meta.source.colorSpace keeps the sRGB / linear tag. +-- Not supported: nothing in the spec is left out. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Codec = require("@formats/image/qoi/Codec") + +-- ------------------------------------------------------------------------------------------------ contract +local Qoi = { + name = "qoi", + category = "image", + extensions = { "qoi" }, + mime = { "image/qoi", "image/x-qoi" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, depths = { 8 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + native: boolean?, -- rgb8 for 3-channel files (default false: always rgba8) + maxPixels: number?, -- refuse larger images (default 2^26) +} +export type EncodeOptions = { + channels: number?, -- 3 or 4 (default: 3 for rgb8 images or opaque rgba8, else 4) + linear: boolean?, -- tag the file as linear instead of sRGB (default: meta.source.colorSpace == "linear") +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Qoi.sniff(r: Bytes.Reader): number + return if r:peek(4) == "qoif" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Qoi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local magic = r:string(4) + local w, h = r:u32be(), r:u32be() + local channels, cs = r:u8(), r:u8() + if r.err then + return nil, r.err + end + if magic ~= "qoif" then + return nil, Err.new(Err.CORRUPT, "bad magic", r.base) + end + if w == 0 or h == 0 or (channels ~= 3 and channels ~= 4) or cs > 1 then + return nil, Err.new(Err.CORRUPT, "bad header", r.base + 4) + 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 img = Types.Image.new(w, h, "rgba8") + local ok, e = Codec.decode(r.buf, r.pos, r.limit, img.pixels, w * h) + if not ok then + return nil, Err.new(Err.TRUNCATED, tostring(e)) + end + if opts and opts.native and channels == 3 then + local rgb = Types.Image.new(w, h, "rgb8") + local src, dst = img.pixels, rgb.pixels + for i = 0, w * h - 1 do + buffer.writeu16(dst, i * 3, buffer.readu16(src, i * 4)) + buffer.writeu8(dst, i * 3 + 2, buffer.readu8(src, i * 4 + 2)) + end + img = rgb + end + img.meta.source = { format = "qoi", bitDepth = 8, colorType = if channels == 4 then "rgba" else "rgb", channels = channels, colorSpace = if cs == 1 then "linear" else "srgb" } + if cs == 1 then + img.meta.colorSpace = "linear" + end + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Qoi.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" or (img.format ~= "rgba8" and img.format ~= "rgb8") then + return nil, Err.new(Err.ARG, "needs an rgba8 or rgb8 Image") + end + local w, h = img.width, img.height + local bpp = if img.format == "rgba8" then 4 else 3 + 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 then + return nil, Err.new(Err.ARG, "bad image size or pixel buffer") + end + local channels = opts and opts.channels + if channels == nil then + channels = 3 + if bpp == 4 then + local px = img.pixels + for i = 0, w * h - 1 do + if buffer.readu8(px, i * 4 + 3) ~= 255 then + channels = 4 + break + end + end + end + elseif channels ~= 3 and channels ~= 4 then + return nil, Err.new(Err.ARG, "channels must be 3 or 4") + end + local linear = opts and opts.linear + if linear == nil then + local src = img.meta and img.meta.source + linear = (type(src) == "table" and src.colorSpace == "linear") or (img.meta and img.meta.colorSpace == "linear") or false + end + local n = w * h + local out = buffer.create(14 + n * (bpp + 1) + 8) + buffer.writestring(out, 0, "qoif") + buffer.writeu32(out, 4, bit32.byteswap(w)) + buffer.writeu32(out, 8, bit32.byteswap(h)) + buffer.writeu8(out, 12, channels) + buffer.writeu8(out, 13, if linear then 1 else 0) + local o = Codec.encode(img.pixels, n, bpp, out, 14) + buffer.writestring(out, o, "\0\0\0\0\0\0\0\1") + o += 8 + local res = buffer.create(o) + buffer.copy(res, 0, out, 0, o) + return res, nil +end + +return Qoi diff --git a/src/Formats/image/tga/Codec.luau b/src/Formats/image/tga/Codec.luau new file mode 100644 index 0000000..1cbb0bd --- /dev/null +++ b/src/Formats/image/tga/Codec.luau @@ -0,0 +1,157 @@ +--!strict +--!native +--!optimize 2 +-- image/tga/Codec: the Truevision TGA pixel loops (native; never throws). Written from the Truevision TGA 2.0 +-- specification. decode reads raw or RLE pixel data (packets may cross scanlines) into rgba8 at the oriented +-- position; encode writes raw or RLE rows. Every read is bounds-checked; the output has exactly w * h * 4 bytes. +local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32 + +local Codec = {} + +-- one source pixel at b[p] -> rgba as a u32; kind: 0 grey 8, 1 grey + alpha 16, 2 = 15/16-bit ARGB1555, +-- 3 = BGR 24, 4 = BGRA 32, 5 = index 8, 6 = index 16 (pal: u32 entries, palN of them) +local function pixel(b: buffer, p: number, kind: number, alpha1: boolean, pal: buffer, palN: number): number + if kind == 0 then + return readu8(b, p) * 0x10101 + 0xFF000000 + elseif kind == 1 then + return readu8(b, p) * 0x10101 + readu8(b, p + 1) * 0x1000000 + elseif kind == 2 then + local v = readu16(b, p) + local r, g, bl = (v // 1024) % 32, (v // 32) % 32, v % 32 + local a = if alpha1 and v < 32768 then 0 else 255 + return (r * 255 + 15) // 31 + ((g * 255 + 15) // 31) * 256 + ((bl * 255 + 15) // 31) * 65536 + a * 16777216 -- round(v * 255 / 31), as ImageMagick + elseif kind == 3 then + return readu8(b, p + 2) + readu8(b, p + 1) * 256 + readu8(b, p) * 65536 + 0xFF000000 + elseif kind == 4 then + return readu8(b, p + 2) + readu8(b, p + 1) * 256 + readu8(b, p) * 65536 + readu8(b, p + 3) * 16777216 + end + local i = if kind == 5 then readu8(b, p) else readu16(b, p) + if i >= palN then + return 0xFF000000 + end + return readu32(pal, i * 4) +end +Codec.pixel = pixel + +-- decode(b, p, limit, w, h, bpp, kind, alpha1, rle, bottomUp, rtl, pal, palN, out) -> pixels written, truncated? +function Codec.decode(b: buffer, p: number, limit: number, w: number, h: number, bpp: number, kind: number, alpha1: boolean, rle: boolean, bottomUp: boolean, rtl: boolean, pal: buffer, palN: number, out: buffer): (number, boolean) + local n = w * h + local i = 0 + local function put(v: number) + local row, col = i // w, i % w + if bottomUp then + row = h - 1 - row + end + if rtl then + col = w - 1 - col + end + writeu32(out, (row * w + col) * 4, v) + i += 1 + end + if not rle then + local avail = math.min(n, (limit - p) // bpp) + for _ = 1, avail do + put(pixel(b, p, kind, alpha1, pal, palN)) + p += bpp + end + return i, avail < n + end + while i < n do + if p >= limit then + return i, true + end + local hd = readu8(b, p) + p += 1 + local count = hd % 128 + 1 + if hd >= 128 then + if p + bpp > limit then + return i, true + end + local v = pixel(b, p, kind, alpha1, pal, palN) + p += bpp + for _ = 1, math.min(count, n - i) do + put(v) + end + else + for _ = 1, math.min(count, n - i) do + if p + bpp > limit then + return i, true + end + put(pixel(b, p, kind, alpha1, pal, palN)) + p += bpp + end + end + end + return i, false +end + +-- encode(px, w, h, srcBpp, outBpp, rle, topDown, out, o) -> new offset. px: rgba8 / rgb8 / gray8 (srcBpp 4 / 3 / 1); +-- written as BGRA / BGR / grey (outBpp 4 / 3 / 1), rows top-down or bottom-up; RLE packets stay inside a row. +-- out needs room for w * h * (outBpp + 1) bytes. +function Codec.encode(px: buffer, w: number, h: number, srcBpp: number, outBpp: number, rle: boolean, topDown: boolean, out: buffer, o: number): number + local function get(q: number): number + if srcBpp == 1 then + return readu8(px, q) + elseif srcBpp == 3 then + return readu8(px, q) + readu8(px, q + 1) * 256 + readu8(px, q + 2) * 65536 + 0xFF000000 + end + return readu32(px, q) + end + local function emit(v: number) + if outBpp == 1 then + writeu8(out, o, v % 256) + else + writeu8(out, o, (v // 65536) % 256) + writeu8(out, o + 1, (v // 256) % 256) + writeu8(out, o + 2, v % 256) + if outBpp == 4 then + writeu8(out, o + 3, v // 16777216) + end + end + o += outBpp + end + for y = 0, h - 1 do + local row = if topDown then y else h - 1 - y + local base = row * w * srcBpp + if not rle then + for x = 0, w - 1 do + emit(get(base + x * srcBpp)) + end + else + local x = 0 + while x < w do + local v = get(base + x * srcBpp) + local run = 1 + while x + run < w and run < 128 and get(base + (x + run) * srcBpp) == v do + run += 1 + end + if run >= 2 then + writeu8(out, o, 127 + run) + o += 1 + emit(v) + x += run + else + -- a raw packet up to the next run of 2 or more + local s = x + local cnt = 0 + while x < w and cnt < 128 do + local c = get(base + x * srcBpp) + if x + 1 < w and get(base + (x + 1) * srcBpp) == c then + break + end + cnt += 1 + x += 1 + end + writeu8(out, o, cnt - 1) + o += 1 + for k = s, s + cnt - 1 do + emit(get(base + k * srcBpp)) + end + end + end + end + end + return o +end + +return Codec diff --git a/src/Formats/image/tga/init.luau b/src/Formats/image/tga/init.luau new file mode 100644 index 0000000..1b4400b --- /dev/null +++ b/src/Formats/image/tga/init.luau @@ -0,0 +1,276 @@ +--!strict +-- image/tga: Truevision TGA (TGA 2.0 specification; new code). Decode: colour-mapped (1), true-colour (2) and grey (3) +-- images, raw or RLE (9, 10, 11; packets may cross scanlines), 8 / 15 / 16 / 24 / 32-bit pixels, 15 / 16 / 24 / +-- 32-bit colour maps with a first index, 8 / 16-bit indexes, grey + alpha (16-bit type 3), every origin (bottom-left, +-- top-left, right-to-left), the alpha bits of the descriptor (16-bit: alpha only when it declares 1 alpha bit; 32-bit: +-- alpha always), the image ID (meta.text.id) and the TGA 2.0 footer (tolerated, not needed). Truncated pixel data +-- leaves the rest transparent black (meta.truncated). opts.native: gray8 for grey files, rgb8 for 24-bit. +-- Encode: rgba8 (32-bit BGRA when there is alpha, else 24-bit), rgb8 (24-bit), gray8 (type 3), raw or RLE, bottom-left +-- (default) or top-left origin, with the TGA 2.0 footer. Not supported: the extension area's fields (gamma, postage +-- stamp, ...), which are ignored. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Codec = require("@formats/image/tga/Codec") + +-- ------------------------------------------------------------------------------------------------ contract +local Tga = { + name = "tga", + category = "image", + extensions = { "tga", "icb", "vda", "vst", "tpic" }, + mime = { "image/x-tga", "image/x-targa" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8, 15, 16, 24, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + native: boolean?, -- gray8 for grey files, rgb8 for 24-bit ones (default false: rgba8) + maxPixels: number?, -- refuse larger images (default 2^26) +} +export type EncodeOptions = { + rle: boolean?, -- run-length encode (default false) + origin: ("bottom-left" | "top-left")?, -- default "bottom-left" (the classic layout every reader understands) + alpha: boolean?, -- force 32-bit (true) or 24-bit (false) for rgba8 (default: 32-bit when any alpha < 255) + id: string?, -- the image ID field (up to 255 bytes; default meta.text.id) +} + +-- ------------------------------------------------------------------------------------------------ constants +local TYPES = { [1] = true, [2] = true, [3] = true, [9] = true, [10] = true, [11] = true } +local FOOTER = "TRUEVISION-XFILE.\0" +local readu8 = buffer.readu8 + +-- ------------------------------------------------------------------------------------------------ sniff +type Header = { + idLen: number, + cmapType: number, + imageType: number, + cmapFirst: number, + cmapLen: number, + cmapBits: number, + width: number, + height: number, + depth: number, + desc: number, +} + +local function header(r: Bytes.Reader): Header? + if r.limit - r.base < 18 then + return nil + end + local b, o = r.buf, r.base + local function u16(q: number): number + return readu8(b, o + q) + readu8(b, o + q + 1) * 256 + end + local h: Header = { + idLen = readu8(b, o), + cmapType = readu8(b, o + 1), + imageType = readu8(b, o + 2), + cmapFirst = u16(3), + cmapLen = u16(5), + cmapBits = readu8(b, o + 7), + width = u16(12), + height = u16(14), + depth = readu8(b, o + 16), + desc = readu8(b, o + 17), + } + return h +end + +-- plausible(h) -> nil | why not +local function implausible(h: Header): string? + local t = h.imageType + if not TYPES[t] then + return "image type " .. t + end + if h.cmapType > 1 then + return "colour map type " .. h.cmapType + end + local mapped = t == 1 or t == 9 + if mapped and (h.cmapType ~= 1 or (h.depth ~= 8 and h.depth ~= 16)) then + return "colour-mapped image without a colour map" + end + if h.cmapType == 1 and h.cmapLen > 0 and h.cmapBits ~= 15 and h.cmapBits ~= 16 and h.cmapBits ~= 24 and h.cmapBits ~= 32 then + return "colour map entry size " .. h.cmapBits + end + if (t == 2 or t == 10) and h.depth ~= 15 and h.depth ~= 16 and h.depth ~= 24 and h.depth ~= 32 then + return "pixel depth " .. h.depth + end + if (t == 3 or t == 11) and h.depth ~= 8 and h.depth ~= 16 then + return "grey pixel depth " .. h.depth + end + if h.width == 0 or h.height == 0 then + return "zero size" + end + if h.desc >= 64 then + return "interleaving / reserved descriptor bits" + end + return nil +end + +function Tga.sniff(r: Bytes.Reader): number + local h = header(r) + if not h or implausible(h) then + return 0 + end + local n = r.limit - r.base + if n >= 44 and buffer.readstring(r.buf, r.limit - 18, 18) == FOOTER then + return 0.9 + end + return 0.2 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Tga.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local h = header(r) + if not h then + return nil, Err.new(Err.TRUNCATED, "short header", r.base) + end + local why = implausible(h) + if why then + return nil, Err.new(if h.imageType == 0 then Err.UNSUPPORTED else Err.CORRUPT, why, r.base) + end + local w, ht = h.width, h.height + if w * ht > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, ht, maxPixels)) + end + local b = r.buf + local p = r.base + 18 + local id = if h.idLen > 0 and p + h.idLen <= r.limit then buffer.readstring(b, p, h.idLen) else nil + p += h.idLen + -- colour map + local pal = buffer.create(4) + local palN = 0 + if h.cmapType == 1 and h.cmapLen > 0 then + local eb = (h.cmapBits + 7) // 8 + if p + h.cmapLen * eb > r.limit then + return nil, Err.new(Err.TRUNCATED, "colour map runs past the end", p) + end + local first = h.cmapFirst + palN = first + h.cmapLen + pal = buffer.create(palN * 4) + buffer.fill(pal, 0, 0, palN * 4) + local kind = if h.cmapBits == 24 then 3 elseif h.cmapBits == 32 then 4 else 2 + for i = 0, h.cmapLen - 1 do + buffer.writeu32(pal, (first + i) * 4, Codec.pixel(b, p + i * eb, kind, false, pal, 0)) + end + for i = 0, first - 1 do + buffer.writeu32(pal, i * 4, 0xFF000000) + end + p += h.cmapLen * eb + end + local t = h.imageType + local alphaBits = h.desc % 16 + local kind + if t == 1 or t == 9 then + kind = if h.depth == 8 then 5 else 6 + elseif t == 3 or t == 11 then + kind = if h.depth == 8 then 0 else 1 + else + kind = if h.depth == 24 then 3 elseif h.depth == 32 then 4 else 2 + end + local bpp = (h.depth + 7) // 8 + local bottomUp = (h.desc // 32) % 2 == 0 + local rtl = (h.desc // 16) % 2 == 1 + local img = Types.Image.new(w, ht, "rgba8") + local _, truncated = Codec.decode(b, p, r.limit, w, ht, bpp, kind, h.depth == 16 and alphaBits >= 1, t >= 9, bottomUp, rtl, pal, palN, img.pixels) + local native = opts and opts.native + if native and kind == 0 then + local g = Types.Image.new(w, ht, "gray8") + for i = 0, w * ht - 1 do + buffer.writeu8(g.pixels, i, readu8(img.pixels, i * 4)) + end + img = g + elseif native and kind == 3 then + local c = Types.Image.new(w, ht, "rgb8") + for i = 0, w * ht - 1 do + buffer.writeu16(c.pixels, i * 3, buffer.readu16(img.pixels, i * 4)) + buffer.writeu8(c.pixels, i * 3 + 2, readu8(img.pixels, i * 4 + 2)) + end + img = c + end + if palN > 0 then + local palette = {} + for i = 0, palN - 1 do + palette[i + 1] = { readu8(pal, i * 4), readu8(pal, i * 4 + 1), readu8(pal, i * 4 + 2), readu8(pal, i * 4 + 3) } + end + img.meta.palette = palette + end + if id then + img.meta.text = { id = id } + end + if truncated then + img.meta.truncated = true + end + img.meta.source = { + format = "tga", + bitDepth = h.depth, + colorType = if kind >= 5 then "palette" elseif kind <= 1 then (if kind == 1 then "graya" else "gray") else (if kind == 3 then "rgb" else "rgba"), + rle = t >= 9, + origin = (if bottomUp then "bottom" else "top") .. "-" .. (if rtl then "right" else "left"), + alphaBits = alphaBits, + } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Tga.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 srcBpp = if img.format == "rgba8" then 4 elseif img.format == "rgb8" then 3 elseif img.format == "gray8" then 1 else nil + if not srcBpp then + return nil, Err.new(Err.ARG, "needs an rgba8, rgb8 or gray8 Image") + end + local w, h = img.width, img.height + if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w > 65535 or h > 65535 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * srcBpp then + return nil, Err.new(Err.ARG, "bad image size or pixel buffer (1..65535 per side)") + end + local o: any = opts or {} + local origin = o.origin or "bottom-left" + if origin ~= "bottom-left" and origin ~= "top-left" then + return nil, Err.new(Err.ARG, "origin must be \"bottom-left\" or \"top-left\"") + end + local outBpp = srcBpp + if srcBpp == 4 then + local alpha = o.alpha + if alpha == nil then + alpha = false + for i = 0, w * h - 1 do + if readu8(img.pixels, i * 4 + 3) ~= 255 then + alpha = true + break + end + end + end + outBpp = if alpha then 4 else 3 + end + local id = o.id or (img.meta and img.meta.text and img.meta.text.id) or "" + if type(id) ~= "string" then + id = "" + end + id = string.sub(id, 1, 255) + local rle = o.rle == true + local out = buffer.create(18 + #id + w * h * (outBpp + 1) + 26) + buffer.writeu8(out, 0, #id) + buffer.writeu8(out, 2, (if outBpp == 1 then 3 else 2) + (if rle then 8 else 0)) + buffer.writeu16(out, 12, w) + buffer.writeu16(out, 14, h) + buffer.writeu8(out, 16, outBpp * 8) + buffer.writeu8(out, 17, (if outBpp == 4 then 8 else 0) + (if origin == "top-left" then 32 else 0)) + buffer.writestring(out, 18, id) + local op = Codec.encode(img.pixels, w, h, srcBpp, outBpp, rle, origin == "top-left", out, 18 + #id) + -- TGA 2.0 footer: no extension / developer areas + buffer.writeu32(out, op, 0) + buffer.writeu32(out, op + 4, 0) + buffer.writestring(out, op + 8, FOOTER) + op += 26 + local res = buffer.create(op) + buffer.copy(res, 0, out, 0, op) + return res, nil +end + +return Tga diff --git a/tests/image/hdr.luau b/tests/image/hdr.luau new file mode 100644 index 0000000..b923ef2 --- /dev/null +++ b/tests/image/hdr.luau @@ -0,0 +1,117 @@ +-- image/hdr tests: ImageMagick-written Radiance files (new-style RLE) against its float decodes, hand-written ones +-- (flat and old-style RLE scanlines, "#?RGBE", EXPOSURE products, all orientations) against the rgbe.c rule; the +-- display conversion to rgba8; our encoder round-trips (RLE and flat, rgbaf32 and rgba8) within RGBE precision; +-- errors; the fuzz no-throw pass. Fixtures: tools/fixtures/hdr.py. +local T = require("@tests/T") +local Hdr = require("@formats/image/hdr") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/hdr") + +local t = T.suite("hdr") + +t:eq(Hdr.name, "hdr", "name") +t:check(Hdr.caps.decode and Hdr.caps.encode, "caps") + +local function dec(data: any, opts: any?): (any, any) + return Hdr.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts) +end + +-- worst relative error between two rgbaf32 buffers +local function relErr(a: buffer, b: buffer, n: number): number + local worst = 0 + for i = 0, n * 4 - 1 do + local x, y = buffer.readf32(a, i * 4), buffer.readf32(b, i * 4) + local d = math.abs(x - y) / math.max(math.abs(y), 1e-30) + if math.abs(x - y) > 1e-30 then + worst = math.max(worst, d) + end + end + return worst +end + +for _, c in Fx do + local img, err = dec(c.data, { native = true }) + t:check(img, c.name .. ": " .. tostring(err)) + t:check(img.width == c.width and img.height == c.height and img.format == "rgbaf32", c.name .. ": size") + local e = relErr(img.pixels, buffer.fromstring(c.floats), c.width * c.height) + t:check(e < 1e-6, string.format("%s: relative error %g against the reference", c.name, e)) + if c.exposure then + t:check(math.abs(img.meta.exposure - c.exposure) < 1e-9, c.name .. ": exposure") + end + -- the default rgba8 display conversion + local d8 = dec(c.data) + t:eq(d8.format, "rgba8", c.name .. ": rgba8 by default") + local v = buffer.readf32(img.pixels, 0) + t:eq(buffer.readu8(d8.pixels, 0), math.floor(math.clamp(v, 0, 1) ^ (1 / 2.2) * 255 + 0.5), c.name .. ": display curve") + -- round trips: RGBE is lossless for values already on its grid + for _, rle in { true, false } do + local enc = Hdr.encode(img, { rle = rle }) :: buffer + local back = dec(enc, { native = true }) + local re = relErr(back.pixels, img.pixels, c.width * c.height) + t:check(re < 1e-6, string.format("%s: round trip rle=%s relative error %g", c.name, tostring(rle), re)) + end +end +t:note("%d files match their references and round-trip", #Fx) + +do + -- arbitrary floats: RGBE keeps about 1% relative precision on the largest channel + local rand = T.rng(8) + local img = Types.Image.new(40, 10, "rgbaf32") + for i = 0, 399 do + for c = 0, 2 do + buffer.writef32(img.pixels, i * 16 + c * 4, rand(100000) / 1000) + end + buffer.writef32(img.pixels, i * 16 + 12, 1) + end + local back = dec(Hdr.encode(img) :: buffer, { native = true }) + local worst = 0 + for i = 0, 399 do + local m = 0 + for c = 0, 2 do + m = math.max(m, buffer.readf32(img.pixels, i * 16 + c * 4)) + end + for c = 0, 2 do + worst = math.max(worst, math.abs(buffer.readf32(back.pixels, i * 16 + c * 4) - buffer.readf32(img.pixels, i * 16 + c * 4)) / math.max(m, 1e-9)) + end + end + t:check(worst < 1 / 128, "float precision " .. worst) + -- rgba8 in, rgba8 out + local i8 = Types.Image.new(9, 2) + for i = 0, 17 do + buffer.writeu32(i8.pixels, i * 4, 0xFF000000 + (i * 14) * 0x10101) + end + local b8 = dec(Hdr.encode(i8) :: buffer) + local w8 = 0 + for i = 0, 71 do + w8 = math.max(w8, math.abs(buffer.readu8(b8.pixels, i) - buffer.readu8(i8.pixels, i))) + end + t:check(w8 <= 2, "rgba8 round trip within 2: " .. w8) + local ex = dec(Hdr.encode(img, { exposure = 0.5 }) :: buffer) + t:eq(ex.meta.exposure, 0.5, "exposure written") + t:eq(Hdr.sniff(Bytes.reader(buffer.fromstring("#?RADIANCE\n"))), 1, "sniff") + t:eq(Hdr.sniff(Bytes.reader(buffer.fromstring("P6\n"))), 0, "sniff other") + local _, e1 = dec("#?RADIANCE\nFORMAT=32-bit_rle_xyze\n\n-Y 1 +X 1\n\0\0\0\0") + t:check(e1 and e1.code == Err.UNSUPPORTED, "xyze unsupported") + local _, e2 = dec("#?RADIANCE\n\n-Y 10 +X 10\n", { maxPixels = 50 }) + t:check(e2 and e2.code == Err.LIMIT, "maxPixels") + local _, e3 = dec("#?RADIANCE\n\nnonsense\n") + t:check(e3 and e3.code == Err.CORRUPT, "bad resolution") + local tr = dec(string.sub(Fx[1].data, 1, #Fx[1].data // 2)) + t:check(tr and tr.meta.truncated, "truncated data flagged") + local _, e4 = Hdr.encode(Types.Image.new(1, 1, "gray8")) + t:check(e4 and e4.code == Err.ARG, "gray8 refused") +end + +do + local samples = {} + for _, c in Fx do + table.insert(samples, c.data) + end + t:fuzz("decode", function(b: buffer) + return Hdr.decode(Bytes.reader(b)) + end, samples) +end + +t:done() diff --git a/tests/image/ico.luau b/tests/image/ico.luau new file mode 100644 index 0000000..00397f4 --- /dev/null +++ b/tests/image/ico.luau @@ -0,0 +1,123 @@ +-- image/ico tests: ImageMagick- and Pillow-written icons (PNG and BMP entries, a 256 PNG entry) and hand-built ones +-- (1 / 4 / 8 / 24 / 32-bit DIBs with AND masks, a cursor with hotspots) against Pillow's decode of every entry; PNG +-- entries through opts.decodeImage (and UNSUPPORTED without it); the main image is the largest entry; our encoder +-- (DIB, PNG through opts.encodeImage, cursors) round-trips; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/ico.py. +local T = require("@tests/T") +local Ico = require("@formats/image/ico") +local Png = require("@formats/image/png") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/ico") + +local t = T.suite("ico") + +t:eq(Ico.name, "ico", "name") +t:check(Ico.caps.decode and Ico.caps.encode, "caps") + +local hooks = { + decodeImage = function(b: buffer) + return Png.decode(Bytes.reader(b)) + end, + encodeImage = function(img: any, _fmt: string) + return Png.encode(img) + end, +} + +local function dec(data: any, opts: any?): (any, any) + return Ico.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts) +end + +local entries = 0 +for _, c in Fx do + local img, err = dec(c.data, hooks) + t:check(img, c.name .. ": " .. tostring(err)) + local frames = img.frames or { { image = img } } + t:eq(#frames, #c.entries, c.name .. ": entry count") + local biggest = 0 + for i, e in c.entries do + local f = frames[i].image + t:check(f.width == e.width and f.height == e.height, string.format("%s entry %d: size %dx%d, want %dx%d", c.name, i, f.width, f.height, e.width, e.height)) + local worst = 0 + for k = 0, #e.rgba - 1 do + worst = math.max(worst, math.abs(buffer.readu8(f.pixels, k) - string.byte(e.rgba, k + 1))) + end + t:check(worst == 0, string.format("%s entry %d: differs from Pillow by %d", c.name, i, worst)) + biggest = math.max(biggest, e.width * e.height) + entries += 1 + end + t:eq(img.width * img.height, biggest, c.name .. ": the main image is the largest entry") + -- round trip through our encoder (DIB entries, and PNG for 256 through the hook) + local enc, eerr = Ico.encode(img, hooks) + t:check(enc, c.name .. ": encode: " .. tostring(eerr)) + local back = dec(enc, hooks) + local bf = back.frames or { { image = back } } + t:eq(#bf, #frames, c.name .. ": round trip entries") + for i, f in frames do + local a, b = f.image, bf[i].image + local same = a.width == b.width and a.height == b.height + if same then + -- alpha-0 pixels keep their colour in 32-bit DIBs too + same = buffer.tostring(a.pixels) == buffer.tostring(b.pixels) + end + t:check(same, string.format("%s: round trip entry %d", c.name, i)) + end +end +t:note("%d icons, %d entries match Pillow and round-trip", #Fx, entries) + +do + local byName = {} + for _, c in Fx do + byName[c.name] = c + end + -- without the hook: PNG entries are skipped, BMP entries still decode + local big, sm = Types.Image.new(256, 256), Types.Image.new(16, 16) + buffer.fill(big.pixels, 0, 77, 256 * 256 * 4) + buffer.fill(sm.pixels, 0, 99, 16 * 16 * 4) + local two = Types.Image.new(256, 256) + two.frames = { { image = big, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }, { image = sm, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } } + local mixed = Ico.encode(two, hooks) :: buffer + t:eq(buffer.readstring(mixed, 6 + 32, 4), "\137PNG", "the 256 entry is written as PNG through the hook") + local im = dec(mixed) + t:check(im and im.width == 16 and im.meta.source.skipped == 1, "no hook: the PNG entry is skipped") + t:eq(dec(mixed, hooks).width, 256, "with the hook: the PNG entry is the main image") + local _, e = dec(byName["pil-png"].data) + t:check(e and e.code == Err.UNSUPPORTED, "PNG-only icon without the hook: " .. tostring(e)) + local cur = dec(byName["hand-cur"].data) + t:check(cur.meta.source.type == "cur" and cur.meta.hotspot and cur.meta.hotspot.x == 3 and cur.meta.hotspot.y == 4, "cursor hotspot") + t:eq(cur.frames[2].image.meta.hotspot.x, 5, "second hotspot") + local cenc = Ico.encode(cur) :: buffer + t:eq(buffer.readu16(cenc, 2), 2, "cursor written as CUR") + local cb = dec(cenc) + t:check(cb.meta.hotspot.x == 3 and cb.frames[2].image.meta.hotspot.y == 6, "hotspots round-trip") + -- PNG entries on request + local small = Types.Image.new(16, 16) + buffer.fill(small.pixels, 0, 200, 16 * 16 * 4) + local pe = Ico.encode(small, { png = true, encodeImage = hooks.encodeImage }) :: buffer + t:eq(buffer.readstring(pe, 22, 4), "\137PNG", "opts.png writes a PNG entry") + local _, e2 = Ico.encode(small, { png = true }) + t:check(e2 and e2.code == Err.ARG, "opts.png without a hook") + local _, e3 = Ico.encode(Types.Image.new(300, 10)) + t:check(e3 and e3.code == Err.ARG, "over 256 pixels") + t:eq(Ico.sniff(Bytes.reader(buffer.fromstring(byName["pil-bmp"].data))), 0.8, "sniff") + t:eq(Ico.sniff(Bytes.reader(buffer.fromstring(string.rep("\0", 30)))), 0, "sniff zeros") + local _, e4 = dec(string.sub(byName["pil-bmp"].data, 1, 20)) + t:check(e4 and e4.code == Err.TRUNCATED, "truncated directory") +end + +do + local samples = {} + for _, c in Fx do + if #c.data < 40000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + return Ico.decode(Bytes.reader(b), hooks) + end, samples) + t:fuzz("decode without hooks", function(b: buffer) + return Ico.decode(Bytes.reader(b)) + end, samples, { mutations = 3, garbage = 50 }) +end + +t:done() 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/tests/image/qoi.luau b/tests/image/qoi.luau new file mode 100644 index 0000000..d78c5cb --- /dev/null +++ b/tests/image/qoi.luau @@ -0,0 +1,85 @@ +-- image/qoi tests: Pillow-written QOI files (RGB / RGBA, noise / gradients / runs / small deltas, 1x1 to 500x1) +-- decode to Pillow's pixels; our encoder writes the same bytes as Pillow for the same pixels and round-trips exactly; +-- native rgb8 output, the colour space tag, errors, and the fuzz no-throw pass. Fixtures: tools/fixtures/qoi.py. +local T = require("@tests/T") +local Qoi = require("@formats/image/qoi") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/qoi") + +local t = T.suite("qoi") + +t:eq(Qoi.name, "qoi", "name") +t:check(Qoi.caps.decode and Qoi.caps.encode, "caps") + +local same = 0 +for _, c in Fx do + local img, err = Qoi.decode(Bytes.reader(buffer.fromstring(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") + t:eq(Crc32.of(img.pixels), c.crc, c.name .. ": pixels against Pillow") + -- encode the source pixels: the same bytes as Pillow's writer + local src = Types.Image.new(c.width, c.height, if c.channels == 4 then "rgba8" else "rgb8") + src.pixels = buffer.fromstring(c.pixels) + local enc = Qoi.encode(src, { channels = c.channels, linear = string.byte(c.data, 14) == 1 }) :: buffer -- Pillow tags its files linear + if buffer.tostring(enc) == c.data then + same += 1 + end + local back = Qoi.decode(Bytes.reader(enc)) + t:eq(Crc32.of(back.pixels), c.crc, c.name .. ": our encoding round-trips") + -- native rgb8 + if c.channels == 3 then + local n = Qoi.decode(Bytes.reader(buffer.fromstring(c.data)), { native = true }) + t:check(n.format == "rgb8" and buffer.tostring(n.pixels) == c.pixels, c.name .. ": native rgb8") + end +end +t:eq(same, #Fx, "byte-identical to Pillow's encoder") +t:note("%d Pillow files decode; %d of our encodings are byte-identical to Pillow's", #Fx, same) + +-- round trips of random images, a sub-range reader, colour space, errors +do + local rand = T.rng(5) + for _, s in { { 1, 1 }, { 70, 3 }, { 33, 33 } } do + local img = Types.Image.new(s[1], s[2]) + for i = 0, s[1] * s[2] * 4 - 1 do + buffer.writeu8(img.pixels, i, if rand(3) == 0 then rand(256) else (i // 4) % 256) + end + local back = Qoi.decode(Bytes.reader(Qoi.encode(img) :: buffer)) + t:check(buffer.tostring(back.pixels) == buffer.tostring(img.pixels), "random round trip") + end + local c = Fx[4] + local big = buffer.create(#c.data + 9) + buffer.writestring(big, 5, c.data) + local img = Qoi.decode(Bytes.reader(big, 5, #c.data)) + t:check(img and Crc32.of(img.pixels) == c.crc, "decode from a sub-range") + local lin = Types.Image.new(2, 2) + local d = Qoi.encode(lin, { linear = true }) :: buffer + t:eq(buffer.readu8(d, 13), 1, "linear tag") + t:eq(Qoi.decode(Bytes.reader(d)).meta.source.colorSpace, "linear", "linear read back") + t:eq(Qoi.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, "sniff") + t:eq(Qoi.sniff(Bytes.reader(buffer.fromstring("GIF8"))), 0, "sniff other") + local _, e = Qoi.decode(Bytes.reader(buffer.fromstring(c.data)), { maxPixels = 10 }) + t:check(e and e.code == Err.LIMIT, "maxPixels") + local _, e2 = Qoi.decode(Bytes.reader(buffer.fromstring(string.sub(c.data, 1, 40)))) + t:check(e2 and e2.code == Err.TRUNCATED, "truncated: " .. tostring(e2)) + local _, e3 = Qoi.decode(Bytes.reader(buffer.fromstring("qoix" .. string.rep("\0", 20)))) + t:check(e3 and e3.code == Err.CORRUPT, "bad magic") + local _, e4 = Qoi.encode(Types.Image.new(2, 2, "gray8")) + t:check(e4 and e4.code == Err.ARG, "encode gray8 -> ARG") +end + +do + local samples = {} + for i, c in Fx do + if i % 2 == 0 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + return Qoi.decode(Bytes.reader(b)) + end, samples, { keepHeader = 4 }) +end + +t:done() diff --git a/tests/image/tga.luau b/tests/image/tga.luau new file mode 100644 index 0000000..2fe016c --- /dev/null +++ b/tests/image/tga.luau @@ -0,0 +1,96 @@ +-- image/tga tests: Pillow- and ImageMagick-written TGAs (RGB / RGBA / grey / grey + alpha / palette, raw and RLE, both +-- origins) and hand-written ones (15 / 16-bit pixels and colour maps, first index, right-to-left, RLE across rows, an +-- image ID) against the reference RGBA decodes; our encoder (raw / RLE, origins, 24 / 32-bit / grey) round-trips; +-- sniffing stays low without a footer; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/tga.py. +local T = require("@tests/T") +local Tga = require("@formats/image/tga") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/tga") + +local t = T.suite("tga") + +t:eq(Tga.name, "tga", "name") +t:check(Tga.caps.decode and Tga.caps.encode, "caps") + +local function dec(data: any, opts: any?): (any, any) + return Tga.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts) +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, c.name .. ": size") + local worst, at = 0, -1 + for i = 0, #c.rgba - 1 do + local d = math.abs(buffer.readu8(img.pixels, i) - string.byte(c.rgba, i + 1)) + if d > worst then + worst, at = d, i + end + end + t:check(worst == 0, string.format("%s: differs from the reference by %d at byte %d", c.name, worst, at)) + t:check(not img.meta.truncated, c.name .. ": not truncated") + -- round trips through our encoder + for _, rle in { false, true } do + for _, origin in { "bottom-left", "top-left" } do + local enc = Tga.encode(img, { rle = rle, origin = origin }) :: buffer + local back = dec(enc) + t:check(back and buffer.tostring(back.pixels) == buffer.tostring(img.pixels), string.format("%s: round trip rle=%s %s", c.name, tostring(rle), origin)) + end + end +end +t:note("%d files match the reference decodes and round-trip", #Fx) + +do + local byName = {} + for _, c in Fx do + byName[c.name] = c + end + local id = dec(byName["hand-id-top"].data) + t:check(id.meta.text and id.meta.text.id == "hello", "image ID") + local g = dec(byName["pil-L-raw-top"].data, { native = true }) + t:eq(g.format, "gray8", "native grey") + t:eq(Tga.encode(g) and buffer.readu8(Tga.encode(g) :: buffer, 2), 3, "gray8 encodes as type 3") + local rgb = dec(byName["pil-RGB-raw-top"].data, { native = true }) + t:eq(rgb.format, "rgb8", "native rgb8") + local p = dec(byName["pil-P-raw-top"].data) + t:check(p.meta.palette and #p.meta.palette > 0, "palette in meta") + -- sniff: low without a footer, higher with ours, never for other formats + t:eq(Tga.sniff(Bytes.reader(buffer.fromstring(byName["hand-16bit"].data))), 0.2, "sniff without a footer") + t:eq(Tga.sniff(Bytes.reader(Tga.encode(p) :: buffer)), 0.9, "sniff with the footer") + t:eq(Tga.sniff(Bytes.reader(buffer.fromstring("\0\0\1\0\1\0\16\16\0\0\1\0\32\0\0\0\0\0\0\0\0\0"))), 0, "an ICO header is not a TGA") + t:eq(Tga.sniff(Bytes.reader(buffer.fromstring("\137PNG\r\n\26\n\0\0\0\13IHDR\0\0\0\0\0\0"))), 0, "a PNG is not a TGA") + -- encoder choices + local img = Types.Image.new(3, 2) + buffer.fill(img.pixels, 0, 255, 24) + t:eq(buffer.readu8(Tga.encode(img) :: buffer, 16), 24, "opaque rgba8 -> 24-bit") + buffer.writeu8(img.pixels, 3, 0) + t:eq(buffer.readu8(Tga.encode(img) :: buffer, 16), 32, "alpha -> 32-bit") + local _, e = Tga.encode(img, { origin = "middle" } :: any) + t:check(e and e.code == Err.ARG, "bad origin") + local _, e2 = Tga.encode(Types.Image.new(2, 2, "gray16")) + t:check(e2 and e2.code == Err.ARG, "gray16 refused") + -- truncation keeps what is there + local s = byName["pil-RGBA-raw-top"].data + local tr = dec(string.sub(s, 1, #s // 2)) + t:check(tr and tr.meta.truncated, "truncated pixels flagged") + local _, e3 = dec(string.sub(s, 1, 10)) + t:check(e3 and e3.code == Err.TRUNCATED, "short header") + local _, e4 = dec(s, { maxPixels = 10 }) + t:check(e4 and e4.code == Err.LIMIT, "maxPixels") +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 Tga.decode(Bytes.reader(b)) + end, samples) +end + +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index 70b461f..9db6488 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -178,3 +178,43 @@ do Tiff.decode(Bytes.reader(enc16)) end) end + +-- ------------------------------------------------------------------------------------------------ imgA-simple: qoi / tga / pnm / hdr +-- fixtures: tools/fixtures/qoi.py (tests/gen/qoi_bench.luau: run python3 -I tools/fixtures.py qoi first) +do + local Qoi = require("@formats/image/qoi") + local Tga = require("@formats/image/tga") + local Pnm = require("@formats/image/pnm") + local Hdr = require("@formats/image/hdr") + local Types = require("@formats/Types") + local QB = require("@tests/gen/qoi_bench") + local qd = buffer.fromstring(QB.data) + local n = QB.width * QB.height * 4 + bench("qoi decode 1024x768", 5, n, function() + Qoi.decode(Bytes.reader(qd)) + end) + local img = Types.Image.new(QB.width, QB.height) + img.pixels = buffer.fromstring(QB.pixels) + bench("qoi encode 1024x768", 5, n, function() + Qoi.encode(img) + end) + local tr = Tga.encode(img, { rle = true }) :: buffer + bench("tga decode rle 1024x768", 3, n, function() + Tga.decode(Bytes.reader(tr)) + end) + bench("tga encode rle 1024x768", 3, n, function() + Tga.encode(img, { rle = true }) + end) + local pp = Pnm.encode(img, { format = "ppm" }) :: buffer + bench("ppm decode 1024x768", 3, n, function() + Pnm.decode(Bytes.reader(pp)) + end) + local f = Hdr.decode(Bytes.reader(Hdr.encode(img) :: buffer), { native = true }) :: Types.Image + local hb = Hdr.encode(f) :: buffer + bench("hdr decode rle 1024x768 (rgbaf32)", 3, n, function() + Hdr.decode(Bytes.reader(hb), { native = true }) + end) + bench("hdr encode rle 1024x768", 3, n, function() + Hdr.encode(f) + end) +end diff --git a/tools/fixtures/hdr.py b/tools/fixtures/hdr.py new file mode 100644 index 0000000..bdf1017 --- /dev/null +++ b/tools/fixtures/hdr.py @@ -0,0 +1,93 @@ +# Radiance HDR fixtures (tools/fixtures.py): files ImageMagick writes (new-style RLE, from float PFM sources) and +# hand-written ones (flat and old-style RLE scanlines, narrow images, the "#?RGBE" header, EXPOSURE lines, every +# orientation); references = ImageMagick's float decodes for its files, and for the hand-written ones the RGBE values +# decoded by the rgbe.c rule (m * 2^(e - 136)) here. +# tests/gen/hdr.luau { { name, data, width, height, floats (rgbaf32 little-endian bytes), exposure? } } +import math, os, random, shutil, struct, subprocess, tempfile + + +def rgbe(r, g, b): + v = max(r, g, b) + if v < 1e-32: + return (0, 0, 0, 0) + m, e = math.frexp(v) + s = m * 256 / v + return (min(255, int(r * s)), min(255, int(g * s)), min(255, int(b * s)), e + 128) + + +def flt(p): + if p[3] == 0: + return (0.0, 0.0, 0.0) + f = math.ldexp(1.0, p[3] - 136) + return (p[0] * f, p[1] * f, p[2] * f) + + +def generate(ctx): + magick = ctx.nix("imagemagick", ["sh", "-c", "command -v magick"]).decode().strip() + work = tempfile.mkdtemp(prefix="formats-hdr-") + try: + _generate(ctx, magick, work) + finally: + shutil.rmtree(work, ignore_errors=True) + + +def _generate(ctx, magick, work): + rng = random.Random(4) + cases = [] + + def im_case(name, w, h, fn): + pfm = os.path.join(work, name + ".pfm") + with open(pfm, "wb") as f: + f.write(b"PF\n%d %d\n-1.0\n" % (w, h)) + for y in range(h - 1, -1, -1): + for x in range(w): + f.write(struct.pack(" (x, y) of scanline i pixel j; pix: (i, j) -> RGBE""" + data = header + b"\n\n" + res + b"\n" + b"".join(r for r, _ in rows) + fl = [(0.0, 0.0, 0.0)] * (w * h) + for i, (_, pixels) in enumerate(rows): + for j, p in enumerate(pixels): + x, y = mapping(i, j) + fl[y * w + x] = flt(p) + c = {"name": name, "data": data, "width": w, "height": h, + "floats": b"".join(struct.pack("> (x % 8) + mask += row + return d + bytes(mask) +def icon(entries, typ=1, hotspots=None): + hdr = 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) diff --git a/tools/fixtures/qoi.py b/tools/fixtures/qoi.py new file mode 100644 index 0000000..9da4391 --- /dev/null +++ b/tools/fixtures/qoi.py @@ -0,0 +1,64 @@ +# QOI fixtures (tools/fixtures.py): Pillow's QOI writer and reader. +# tests/gen/qoi.luau { { name, width, height, mode, pixels (source bytes, RGB or RGBA), data (Pillow's .qoi), crc +# (CRC-32 of Pillow's RGBA decode) } } +# tests/gen/qoi_bench.luau { width, height, pixels (RGBA), data } +import struct + +CODE = r''' +import io, random, struct, sys, zlib +from PIL import Image +rng = random.Random(11) +def make(w, h, mode, kind): + n = len(mode) + px = bytearray() + for y in range(h): + for x in range(w): + if kind == "noise": + v = [rng.randrange(256) for _ in range(n)] + elif kind == "grad": + v = [(x * 3 + y) % 256, (y * 5) % 256, (x + y * 2) % 256, 255 - (x % 7) * 30][:n] + elif kind == "flat": + v = [10, 200, 30, 255][:n] if (x // 9 + y // 7) % 2 else [10, 200, 31, 128][:n] + else: # small deltas around a walk, with an occasional jump + base = (x * 2 + y) % 256 + v = [(base + rng.randrange(-2, 2)) % 256, (base + rng.randrange(-30, 30)) % 256, (base + rng.randrange(-9, 9)) % 256, 255 if rng.random() < 0.9 else rng.randrange(256)][:n] + px += bytes(v) + return bytes(px) +out = [] +for (w, h, mode, kind) in ((1, 1, "RGB", "noise"), (1, 1, "RGBA", "noise"), (3, 2, "RGBA", "grad"), (64, 48, "RGB", "grad"), + (64, 48, "RGBA", "grad"), (100, 37, "RGB", "noise"), (100, 37, "RGBA", "noise"), + (200, 150, "RGBA", "flat"), (200, 150, "RGB", "flat"), (128, 99, "RGBA", "walk"), (128, 99, "RGB", "walk"), + (500, 1, "RGBA", "flat"), (1, 300, "RGB", "walk")): + px = make(w, h, mode, kind) + im = Image.frombytes(mode, (w, h), px) + b = io.BytesIO(); im.save(b, "QOI"); data = b.getvalue() + back = Image.open(io.BytesIO(data)).convert("RGBA").tobytes() + name = "%dx%d-%s-%s" % (w, h, mode, kind) + sys.stdout.buffer.write(struct.pack("> 3) << 10) | ((g >> 3) << 5) | (b >> 3)) +cols = [((i * 40) % 256, (i * 90) % 256, (255 - i * 20) % 256) for i in range(12)] +w, h = 6, 4 +idx = [(x + y * 2) % 12 for y in range(h) for x in range(w)] +emit("hand-16bit", hdr(0, 0, 2, 0, 0, 0, w, h, 16, 0) + b"".join(p15(*cols[i]) for i in idx), magick_ref=True) +emit("hand-15bit-rtl", hdr(0, 0, 2, 0, 0, 0, w, h, 15, 0x10) + b"".join(p15(*cols[i], a=0) for i in idx), magick_ref=True) +emit("hand-cmap16", hdr(0, 1, 1, 0, 12, 16, w, h, 8, 0x20) + b"".join(p15(*c) for c in cols) + bytes(idx), magick_ref=True) +emit("hand-cmap32-first", hdr(0, 1, 1, 4, 12, 32, w, h, 8, 0x28) + b"".join(bytes((c[2], c[1], c[0], 77)) for c in cols) + bytes(i + 4 for i in idx)) +emit("hand-cmap24-rle", hdr(0, 1, 9, 0, 12, 24, w, h, 8, 0) + b"".join(bytes((c[2], c[1], c[0])) for c in cols) + bytes([0x80 + 9, 3, 0x05, 1, 2, 3, 4, 5, 6, 0x80 + 7, 11])) +emit("hand-id-top", hdr(5, 0, 3, 0, 0, 0, w, h, 8, 0x20) + b"hello" + bytes((i * 21) % 256 for i in idx)) +emit("hand-graya16", hdr(0, 0, 3, 0, 0, 0, w, h, 16, 0x28) + b"".join(bytes(((i * 21) % 256, (i * 50) % 256)) for i in idx)) +emit("hand-rle32-cross", hdr(0, 0, 10, 0, 0, 0, 5, 3, 32, 0x28) + bytes([0x80 + 6, 1, 2, 3, 200, 0x08]) + bytes(range(9 * 4))) +for name, data, size, rgba in out: + sys.stdout.buffer.write(struct.pack("