imgA-simple: image/hdr (Radiance RGBE: flat / old / new RLE, all orientations, EXPOSURE; RLE writer) against ImageMagick and rgbe.c
This commit is contained in:
1 parent
f2e15af64d
commit
e15774c10b
6 files changed
+676
No files matched your search
@@ -5,6 +5,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
|
||||
|
||||
| Category | Format | Extensions | Read | Write | Capabilities | Test |
|
||||
|---|---|---|---|---|---|---|
|
||||
| image | hdr | .hdr .pic .rgbe | yes | yes | alpha: false, float: true, depths: 32 | `tests/image/hdr.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` |
|
||||
|
||||
@@ -14,6 +14,18 @@ export type Entry = {
|
||||
}
|
||||
|
||||
local list: { Entry } = {
|
||||
{
|
||||
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 = "png",
|
||||
category = "image",
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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()
|
||||
@@ -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("<fff", *fn(x, y)))
|
||||
out = os.path.join(work, name + ".hdr")
|
||||
subprocess.run([magick, pfm, out], check=True, capture_output=True)
|
||||
fl = subprocess.run([magick, out, "-depth", "32", "-define", "quantum:format=floating-point", "-endian", "LSB", "rgba:-"], check=True, capture_output=True).stdout
|
||||
cases.append({"name": name, "data": open(out, "rb").read(), "width": w, "height": h, "floats": fl})
|
||||
|
||||
im_case("im-gradient", 64, 20, lambda x, y: (x / 16.0, y / 5.0, (x * y) % 7 * 0.3))
|
||||
im_case("im-noise", 33, 9, lambda x, y: (rng.random() * 100, rng.random(), rng.random() * 0.001))
|
||||
im_case("im-flat", 100, 3, lambda x, y: (0.5, 0.25, 2.0) if x < 60 else (0.0, 0.0, 0.0))
|
||||
|
||||
def hand(name, w, h, header, res, rows, mapping, exposure=None):
|
||||
"""rows: list of scanline byte strings; mapping(i, j) -> (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("<ffff", *v, 1.0) for v in fl)}
|
||||
if exposure:
|
||||
c["exposure"] = exposure
|
||||
cases.append(c)
|
||||
|
||||
def flat_row(n, seed):
|
||||
px = [rgbe(rng.random() * 4, rng.random(), rng.random() * 0.1) for _ in range(n)]
|
||||
px = [p if p[:3] != (1, 1, 1) else (2, 1, 1, p[3]) for p in px]
|
||||
return b"".join(bytes(p) for p in px), px
|
||||
|
||||
def oldrle_row(n):
|
||||
p = rgbe(0.7, 0.2, 0.1)
|
||||
q = rgbe(3.0, 3.0, 3.0)
|
||||
# p, then a run of 3 more p, then q, then a run of 2 + (1 << 8)*0 ... keep it simple: q x (n - 5)
|
||||
pix = [p] * 4 + [q] * (n - 4)
|
||||
run = n - 5
|
||||
return bytes(p) + bytes((1, 1, 1, 3)) + bytes(q) + bytes((1, 1, 1, run)), pix
|
||||
|
||||
w, h = 5, 3
|
||||
rows = [flat_row(w, i) for i in range(h)]
|
||||
hand("flat-narrow", w, h, b"#?RGBE\nFORMAT=32-bit_rle_rgbe\nEXPOSURE=2.0\nEXPOSURE=1.5", b"-Y 3 +X 5", rows, lambda i, j: (j, i), exposure=3.0)
|
||||
rows = [oldrle_row(12) for _ in range(2)]
|
||||
hand("old-rle", 12, 2, b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\nSOFTWARE=hand", b"-Y 2 +X 12", rows, lambda i, j: (j, i))
|
||||
for res, mp in ((b"+Y 3 +X 5", lambda i, j: (j, 2 - i)), (b"-Y 3 -X 5", lambda i, j: (4 - j, i)),
|
||||
(b"+Y 3 -X 5", lambda i, j: (4 - j, 2 - i))):
|
||||
rows = [flat_row(5, i) for i in range(3)]
|
||||
hand("orient " + res.decode(), 5, 3, b"#?RADIANCE", res, rows, mp)
|
||||
for res, mp in ((b"+X 5 -Y 3", lambda i, j: (i, j)), (b"-X 5 +Y 3", lambda i, j: (4 - i, 2 - j))):
|
||||
rows = [flat_row(3, i) for i in range(5)]
|
||||
hand("orient " + res.decode(), 5, 3, b"#?RADIANCE", res, rows, mp)
|
||||
ctx.emit("hdr", cases)
|
||||
Reference in new issue
Block a user