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:
4DBug committed 2026-10-31 08:51:42 -05:00
1 parent f2e15af64d
commit e15774c10b
6 files changed
+676

No files matched your search

+12
View File
@@ -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",
+219
View File
@@ -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
+234
View File
@@ -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