imgA: merge ws/imgA-simple (tga, qoi, pnm, ico, hdr)

This commit is contained in:
4DBug committed 2026-10-31 08:58:09 -05:00
commit f0f1eb6c47
23 files changed
+3293

No files matched your search

+60
View File
@@ -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",
+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
+106
View File
@@ -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
+282
View File
@@ -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
+289
View File
@@ -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
+383
View File
@@ -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
+144
View File
@@ -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
+122
View File
@@ -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
+157
View File
@@ -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
+276
View File
@@ -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