430 lines
15 KiB
Luau
430 lines
15 KiB
Luau
--!strict
|
|
--!optimize 2
|
|
-- image/bmp: Windows / OS/2 BMP. Absorbed from bmp-luau b86aed6 (same author, no third-party code; the reader), plus a
|
|
-- new encoder. Decode: BITMAPCOREHEADER (OS/2 1.x, 12 bytes), OS/2 2.x (16..64), BITMAPINFOHEADER (40), the v2 / v3
|
|
-- variants (52 / 56), BITMAPV4HEADER / BITMAPV5HEADER (108 / 124); 1 / 2 / 4 / 8 bpp paletted, 16 bpp (555 or
|
|
-- BITFIELDS), 24 bpp, 32 bpp (BI_RGB, BITFIELDS, ALPHABITFIELDS), RLE8 / RLE4 (delta / end-of-line / end-of-bitmap),
|
|
-- bottom-up and top-down rows. Lenient: bfSize / biSizeImage are ignored, a bad bfOffBits falls back to the end of the
|
|
-- palette, a short or missing palette pads with opaque black, a truncated pixel array decodes as zero bytes, a 32-bit
|
|
-- image whose alpha is all zero is opaque. Masks scale as Pillow does (v * 255 // max).
|
|
-- Encode (rgba8): 8 bpp paletted when the image is opaque with at most 256 colours (palette in first-appearance
|
|
-- order), else 24 bpp when opaque, else 32 bpp with alpha (BITMAPV4HEADER + BITFIELDS, or BI_RGB with
|
|
-- opts.header = "info" as Pillow writes). Byte-identical to Pillow for 24 bpp, paletted and BI_RGB 32 bpp output.
|
|
-- Not supported: embedded JPEG / PNG, OS/2 Huffman / RLE24, writing RLE / 16 bpp / 1-4 bpp.
|
|
|
|
-- ------------------------------------------------------------------------------------------------ requires
|
|
local Err = require("@formats/core/Err")
|
|
local Bytes = require("@formats/core/Bytes")
|
|
local Types = require("@formats/Types")
|
|
local Pixels = require("@formats/image/bmp/Pixels")
|
|
|
|
-- ------------------------------------------------------------------------------------------------ contract
|
|
local Bmp = {
|
|
name = "bmp",
|
|
category = "image",
|
|
extensions = { "bmp", "dib" },
|
|
mime = { "image/bmp", "image/x-bmp", "image/x-ms-bmp" },
|
|
deps = { "core/Err", "core/Bytes", "Types" },
|
|
caps = { decode = true, encode = true, alpha = true, depths = { 1, 2, 4, 8, 16, 24, 32 }, rle = true },
|
|
}
|
|
|
|
-- ------------------------------------------------------------------------------------------------ types
|
|
export type Info = {
|
|
width: number,
|
|
height: number,
|
|
bitsPerPixel: number,
|
|
compression: number,
|
|
topDown: boolean,
|
|
headerSize: number,
|
|
os2: boolean,
|
|
}
|
|
|
|
export type DecodeOptions = {
|
|
maxPixels: number?, -- refuse images with more pixels than this (default 2^26 = 64 Mpx)
|
|
}
|
|
export type EncodeOptions = {
|
|
bitDepth: (number | "auto")?, -- 8, 24, 32; default "auto": 8 when opaque with <= 256 colours, else 24 when opaque, else 32
|
|
header: ("v4" | "info")?, -- 32 bpp: "v4" (default, BITFIELDS with an alpha mask) or "info" (BI_RGB, as Pillow)
|
|
}
|
|
|
|
-- ------------------------------------------------------------------------------------------------ constants
|
|
local MAX_PIXELS = 2 ^ 26
|
|
local COMPRESSION_NAMES = { [0] = "rgb", "rle8", "rle4", "bitfields", "jpeg", "png", "alphabitfields" }
|
|
|
|
local readu8, readu16, readu32, readi32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32
|
|
local band, rshift, lshift, countrz = bit32.band, bit32.rshift, bit32.lshift, bit32.countrz
|
|
|
|
-- the reader's range as a buffer starting at offset 0 (copied when it is a part of a bigger buffer)
|
|
local function whole(r: Bytes.Reader): buffer
|
|
if r.base == 0 and r.limit == buffer.len(r.buf) then
|
|
return r.buf
|
|
end
|
|
local n = r.limit - r.base
|
|
local b = buffer.create(n)
|
|
buffer.copy(b, 0, r.buf, r.base, n)
|
|
return b
|
|
end
|
|
|
|
-- ------------------------------------------------------------------------------------------------ sniff
|
|
function Bmp.sniff(r: Bytes.Reader): number
|
|
if r:peek(2) ~= "BM" then
|
|
return 0
|
|
end
|
|
-- a known header size: a strong match; "BM" alone is weak
|
|
local n = r:peekU8(14) + math.max(r:peekU8(15), 0) * 256
|
|
if r:peekU8(16) == 0 and r:peekU8(17) == 0 and (n == 12 or n == 16 or n == 40 or n == 52 or n == 56 or n == 64 or n == 108 or n == 124) then
|
|
return 0.9
|
|
end
|
|
return 0.2
|
|
end
|
|
|
|
-- ------------------------------------------------------------------------------------------------ decode
|
|
-- Header parse: info, palette start offset, palette entry size, header-provided masks (or nil) | nil, err
|
|
local function parseHeader(buf: buffer): (Info?, any)
|
|
local n = buffer.len(buf)
|
|
if n < 18 then
|
|
return nil, Err.new(Err.TRUNCATED, "file too short")
|
|
end
|
|
if readu8(buf, 0) ~= 0x42 or readu8(buf, 1) ~= 0x4D then
|
|
return nil, Err.new(Err.CORRUPT, "not a BMP file (no BM signature)")
|
|
end
|
|
local hs = readu32(buf, 14)
|
|
if hs < 12 or 14 + hs > n then
|
|
return nil, Err.new(Err.CORRUPT, "bad header size " .. hs)
|
|
end
|
|
local info: Info = {
|
|
width = 0,
|
|
height = 0,
|
|
bitsPerPixel = 0,
|
|
compression = 0,
|
|
topDown = false,
|
|
headerSize = hs,
|
|
os2 = false,
|
|
}
|
|
if hs == 12 then
|
|
info.width = readu16(buf, 18)
|
|
info.height = readu16(buf, 20)
|
|
info.bitsPerPixel = readu16(buf, 24)
|
|
info.os2 = true
|
|
else
|
|
if hs < 16 then
|
|
return nil, Err.new(Err.CORRUPT, "bad header size " .. hs)
|
|
end
|
|
info.width = readi32(buf, 18)
|
|
local h = readi32(buf, 22)
|
|
info.bitsPerPixel = readu16(buf, 28)
|
|
if hs >= 20 then
|
|
info.compression = readu32(buf, 30)
|
|
end
|
|
if h < 0 then
|
|
info.topDown = true
|
|
h = -h
|
|
end
|
|
info.height = h
|
|
-- OS/2 2.x headers: 16 / 64 bytes, or any size that is not a Windows one
|
|
info.os2 = not (hs == 40 or hs == 52 or hs == 56 or hs == 108 or hs == 124)
|
|
end
|
|
return info
|
|
end
|
|
|
|
-- info(r) -> Info | nil, Err: the header without decoding the pixels
|
|
function Bmp.info(r: Bytes.Reader): (Info?, Err.Err?)
|
|
return parseHeader(whole(r))
|
|
end
|
|
|
|
-- u8 table of size (m + 1) mapping a masked value 0..m to 0..255: v * 255 // m, as Pillow does (browsers replicate
|
|
-- the top bits instead, which can differ by 1). m = 0 -> { empty }.
|
|
local function scaleTable(m: number, empty: number): buffer
|
|
local t = buffer.create(m + 1)
|
|
if m == 0 then
|
|
buffer.writeu8(t, 0, empty)
|
|
else
|
|
for v = 0, m do
|
|
buffer.writeu8(t, v, (v * 255) // m)
|
|
end
|
|
end
|
|
return t
|
|
end
|
|
|
|
-- shift, mask >> shift, table for one channel mask (wider than 16 bits: keep the top 16)
|
|
local function channel(mask: number, empty: number): (number, number, buffer)
|
|
if mask == 0 then
|
|
return 0, 0, scaleTable(0, empty)
|
|
end
|
|
local sh = countrz(mask)
|
|
local m = rshift(mask, sh)
|
|
-- holes in the mask: use the lowest contiguous run of bits
|
|
local bits = 0
|
|
while bits < 32 and band(m, lshift(1, bits)) ~= 0 do
|
|
bits += 1
|
|
end
|
|
if bits > 16 then
|
|
sh += bits - 16
|
|
bits = 16
|
|
end
|
|
m = lshift(1, bits) - 1
|
|
return sh, m, scaleTable(m, empty)
|
|
end
|
|
|
|
-- decode(r, opts?) -> rgba8 Image | nil, Err
|
|
function Bmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
|
local buf = whole(r)
|
|
local info, herr = parseHeader(buf)
|
|
if not info then
|
|
return nil, herr
|
|
end
|
|
local n = buffer.len(buf)
|
|
local hs, w, h, bpp, comp = info.headerSize, info.width, info.height, info.bitsPerPixel, info.compression
|
|
if w <= 0 or h <= 0 then
|
|
return nil, Err.new(Err.CORRUPT, "bad size " .. w .. "x" .. h)
|
|
end
|
|
local maxPixels = (opts and opts.maxPixels) or MAX_PIXELS
|
|
if w * h > maxPixels then
|
|
return nil, Err.new(Err.LIMIT, "image too large (" .. w .. "x" .. h .. ")")
|
|
end
|
|
if info.os2 and hs ~= 12 and (comp == 3 or comp == 4) then
|
|
return nil, Err.new(Err.UNSUPPORTED, "OS/2 Huffman / RLE24 compression is not supported")
|
|
end
|
|
if comp == 4 or comp == 5 then
|
|
return nil, Err.new(Err.UNSUPPORTED, "embedded " .. (if comp == 4 then "JPEG" else "PNG") .. " is not supported")
|
|
end
|
|
if comp > 6 then
|
|
return nil, Err.new(Err.CORRUPT, "unknown compression " .. comp)
|
|
end
|
|
local valid = (bpp == 1 or bpp == 2 or bpp == 4 or bpp == 8 or bpp == 16 or bpp == 24 or bpp == 32)
|
|
if not valid then
|
|
return nil, Err.new(Err.CORRUPT, "unsupported bit depth " .. bpp)
|
|
end
|
|
if (comp == 1 and bpp ~= 8) or (comp == 2 and bpp ~= 4) then
|
|
return nil, Err.new(Err.CORRUPT, "RLE compression " .. comp .. " with " .. bpp .. " bpp")
|
|
end
|
|
if (comp == 3 or comp == 6) and bpp ~= 16 and bpp ~= 24 and bpp ~= 32 then
|
|
return nil, Err.new(Err.CORRUPT, "BITFIELDS with " .. bpp .. " bpp")
|
|
end
|
|
|
|
-- masks: in the v2+ header, or right after a 40-byte header
|
|
local palStart = 14 + hs
|
|
local rm: number, gm: number, bm: number, am: number = 0, 0, 0, 0
|
|
local hasMasks = false
|
|
if comp == 3 or comp == 6 then
|
|
hasMasks = true
|
|
if hs >= 52 then
|
|
rm = readu32(buf, 54)
|
|
gm = readu32(buf, 58)
|
|
bm = readu32(buf, 62)
|
|
if hs >= 56 then
|
|
am = readu32(buf, 66)
|
|
end
|
|
else
|
|
local count = if comp == 6 then 4 else 3
|
|
if palStart + count * 4 > n then
|
|
return nil, Err.new(Err.TRUNCATED, "truncated bit masks")
|
|
end
|
|
rm = readu32(buf, palStart)
|
|
gm = readu32(buf, palStart + 4)
|
|
bm = readu32(buf, palStart + 8)
|
|
if comp == 6 then
|
|
am = readu32(buf, palStart + 12)
|
|
end
|
|
palStart += count * 4
|
|
end
|
|
if comp == 3 and hs < 56 then
|
|
am = 0
|
|
end
|
|
if rm == 0 and gm == 0 and bm == 0 then
|
|
hasMasks = false -- all-zero masks: use the defaults
|
|
end
|
|
end
|
|
|
|
-- palette
|
|
local entrySize = if hs == 12 then 3 else 4
|
|
local declared = if hs >= 36 then readu32(buf, 46) else 0
|
|
local palCount = 0
|
|
if bpp <= 8 then
|
|
palCount = if declared == 0 or declared > lshift(1, bpp) then lshift(1, bpp) else declared
|
|
end
|
|
local off = readu32(buf, 10)
|
|
local pixelEnd = palStart + palCount * entrySize
|
|
if off < palStart or off >= n then
|
|
-- bad bfOffBits: the pixels start after the palette as declared
|
|
off = math.min(pixelEnd, n)
|
|
elseif bpp <= 8 and off < pixelEnd then
|
|
-- palette shorter than declared: it ends where the pixels start
|
|
palCount = (off - palStart) // entrySize
|
|
end
|
|
palCount = math.max(0, math.min(palCount, (n - palStart) // entrySize))
|
|
local pal = buffer.create(256 * 4)
|
|
for i = 0, 255 do
|
|
buffer.writeu32(pal, i * 4, 0xFF000000)
|
|
end
|
|
for i = 0, palCount - 1 do
|
|
local p = palStart + i * entrySize
|
|
local bb, gg, rr = readu8(buf, p), readu8(buf, p + 1), readu8(buf, p + 2)
|
|
buffer.writeu32(pal, i * 4, rr + gg * 256 + bb * 65536 + 0xFF000000)
|
|
end
|
|
|
|
local img = Types.Image.new(w, h, "rgba8")
|
|
local pixels = img.pixels
|
|
img.meta.source = {
|
|
format = "bmp",
|
|
bitDepth = bpp,
|
|
compression = COMPRESSION_NAMES[comp],
|
|
topDown = info.topDown,
|
|
headerSize = hs,
|
|
paletteSize = palCount,
|
|
os2 = info.os2,
|
|
}
|
|
if bpp <= 8 and palCount > 0 then
|
|
local palette: { { number } } = {}
|
|
for i = 0, palCount - 1 do
|
|
palette[i + 1] = { readu8(pal, i * 4), readu8(pal, i * 4 + 1), readu8(pal, i * 4 + 2), 255 }
|
|
end
|
|
img.meta.palette = palette
|
|
end
|
|
if hs >= 40 then
|
|
local xp, yp = readi32(buf, 38), readi32(buf, 42)
|
|
if xp > 0 and yp > 0 then
|
|
img.meta.dpi = { x = xp * 0.0254, y = yp * 0.0254 }
|
|
end
|
|
end
|
|
|
|
if comp == 1 or comp == 2 then
|
|
Pixels.rle(buf, off, n, comp == 2, pixels, w, h, info.topDown, pal)
|
|
return img, nil
|
|
end
|
|
|
|
-- uncompressed: make sure every row is readable (a truncated file reads as zeros)
|
|
local stride = ((w * bpp + 31) // 32) * 4
|
|
local need = stride * h
|
|
local src, base = buf, off
|
|
if off + need > n then
|
|
src = buffer.create(need)
|
|
buffer.copy(src, 0, buf, off, n - off)
|
|
base = 0
|
|
end
|
|
|
|
if bpp <= 8 then
|
|
Pixels.indexed(src, base, stride, bpp, pixels, w, h, info.topDown, pal)
|
|
elseif bpp == 24 and not hasMasks then
|
|
Pixels.bgr24(src, base, stride, pixels, w, h, info.topDown)
|
|
elseif bpp == 32 and (not hasMasks or (rm == 0xFF0000 and gm == 0xFF00 and bm == 0xFF and (am == 0xFF000000 or am == 0))) then
|
|
local aor = Pixels.bgra32(src, base, stride, pixels, w, h, info.topDown)
|
|
if aor == 0 or (hasMasks and am == 0) then
|
|
Pixels.opaque(pixels, w * h)
|
|
end
|
|
else
|
|
if not hasMasks then
|
|
if bpp == 16 then
|
|
rm, gm, bm, am = 0x7C00, 0x3E0, 0x1F, 0
|
|
else
|
|
rm, gm, bm, am = 0xFF0000, 0xFF00, 0xFF, 0
|
|
end
|
|
end
|
|
local shr, mr, tr = channel(rm, 0)
|
|
local shg, mg, tg = channel(gm, 0)
|
|
local shb, mb, tb = channel(bm, 0)
|
|
local sha, ma, ta = channel(am, 255)
|
|
local aor =
|
|
Pixels.masked(src, base, stride, bpp, pixels, w, h, info.topDown, shr, mr, tr, shg, mg, tg, shb, mb, tb, sha, ma, ta)
|
|
if ma ~= 0 and aor == 0 then
|
|
Pixels.opaque(pixels, w * h)
|
|
end
|
|
end
|
|
return img, nil
|
|
end
|
|
|
|
-- ------------------------------------------------------------------------------------------------ encode
|
|
-- encode(img, opts?) -> buffer | nil, Err
|
|
function Bmp.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
|
if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then
|
|
return nil, Err.new(Err.ARG, "encode: needs an rgba8 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 % 1 ~= 0 or h % 1 ~= 0 or w > 0x7FFFFFFF or h > 0x7FFFFFFF then
|
|
return nil, Err.new(Err.ARG, "encode: bad image size")
|
|
end
|
|
if buffer.len(img.pixels) < w * h * 4 then
|
|
return nil, Err.new(Err.ARG, "encode: the pixel buffer is smaller than width * height * 4")
|
|
end
|
|
local want = opts and opts.bitDepth or "auto"
|
|
if want ~= "auto" and want ~= 8 and want ~= 24 and want ~= 32 then
|
|
return nil, Err.new(Err.ARG, "encode: bitDepth must be 8, 24, 32 or auto")
|
|
end
|
|
local headerKind = opts and opts.header or "v4"
|
|
if headerKind ~= "v4" and headerKind ~= "info" then
|
|
return nil, Err.new(Err.ARG, "encode: header must be v4 or info")
|
|
end
|
|
local colours, alpha = Pixels.colours(img.pixels, w * h, 256)
|
|
local bpp: number
|
|
if want == "auto" then
|
|
bpp = if alpha then 32 elseif #colours <= 256 then 8 else 24
|
|
else
|
|
bpp = want :: number
|
|
if bpp == 8 and #colours > 256 then
|
|
return nil, Err.new(Err.ARG, "encode: more than 256 colours for 8 bpp")
|
|
end
|
|
end
|
|
local v4 = bpp == 32 and headerKind == "v4"
|
|
local hs = if v4 then 108 else 40
|
|
local stride = ((w * bpp + 31) // 32) * 4
|
|
local palCount = if bpp == 8 then #colours else 0
|
|
local off = 14 + hs + palCount * 4
|
|
local imageSize = stride * h
|
|
if off + imageSize > 0x3FFFFFFF then
|
|
return nil, Err.new(Err.LIMIT, "encode: the file would be over 1 GiB")
|
|
end
|
|
local out = buffer.create(off + imageSize)
|
|
local o = Bytes.writer(off)
|
|
o:string("BM")
|
|
o:u32le(off + imageSize)
|
|
o:u32le(0)
|
|
o:u32le(off)
|
|
o:u32le(hs)
|
|
o:i32le(w)
|
|
o:i32le(h)
|
|
o:u16le(1)
|
|
o:u16le(bpp)
|
|
o:u32le(if v4 then 3 else 0) -- BI_BITFIELDS / BI_RGB
|
|
o:u32le(imageSize)
|
|
local dpi = img.meta and img.meta.dpi
|
|
local xp: number, yp: number = 3780, 3780 -- 96 dpi, as Pillow
|
|
if type(dpi) == "table" and type(dpi.x) == "number" and type(dpi.y) == "number" and dpi.x > 0 and dpi.y > 0 then
|
|
xp = math.floor((dpi.x :: number) * 39.3701 + 0.5)
|
|
yp = math.floor((dpi.y :: number) * 39.3701 + 0.5)
|
|
end
|
|
o:i32le(xp)
|
|
o:i32le(yp)
|
|
o:u32le(palCount)
|
|
o:u32le(palCount)
|
|
if v4 then
|
|
o:u32le(0x00FF0000)
|
|
o:u32le(0x0000FF00)
|
|
o:u32le(0x000000FF)
|
|
o:u32le(0xFF000000)
|
|
o:string("BGRs") -- LCS_sRGB (stored little-endian: 'sRGB')
|
|
o:fill(0, 36 + 12) -- endpoints, gamma
|
|
end
|
|
local idx: { [number]: number } = {}
|
|
for i, c in colours do
|
|
if i > palCount then
|
|
break
|
|
end
|
|
idx[c] = i - 1
|
|
o:u8(band(rshift(c, 16), 255))
|
|
o:u8(band(rshift(c, 8), 255))
|
|
o:u8(band(c, 255))
|
|
o:u8(0)
|
|
end
|
|
buffer.copy(out, 0, o.buf, 0, off)
|
|
if bpp == 8 then
|
|
Pixels.encode8(img.pixels, w, h, out, off, stride, idx)
|
|
elseif bpp == 24 then
|
|
Pixels.encode24(img.pixels, w, h, out, off, stride)
|
|
else
|
|
Pixels.encode32(img.pixels, w, h, out, off)
|
|
end
|
|
return out, nil
|
|
end
|
|
|
|
return Bmp
|