diff --git a/docs/FORMATS.md b/docs/FORMATS.md index db5070f..deb0912 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -5,6 +5,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | Category | Format | Extensions | Read | Write | Capabilities | Test | |---|---|---|---|---|---|---| +| image | bmp | .bmp .dib | yes | yes | alpha: true, depths: 1, 2, 4, 8, 16, 24, 32, rle: true | `tests/image/bmp.luau` | | image | png | .png .apng | yes | yes | animation: true, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | | audio | flac | .flac .oga | yes | - | streaming: true, depths: 4, 8, 12, 16, 20, 24, 32, ogg: true, seek: true | `tests/audio/flac.luau` | | audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | - | streaming: true, seek: true, layers: 1, 2, 3, channels: 2 | `tests/audio/mp3.luau` | diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index 1d1c0e2..3167a65 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -10,6 +10,8 @@ | `tests/fixtures/mp3/` | made by ffmpeg (libmp3lame / mp2) from a synthetic signal; `*.ref` are minimp3 decodes of them | test data, no third-party content | | `src/Formats/audio/opus/` (Decoder, Celt, Silk, Mdct, RangeDecoder, Packet, CeltTables, SilkTables) | opus-luau dd2b4e5 (same author): a port of the libopus 1.6 decoder (git bafd40dcbd50; tables generated from its sources); the stereo downmix weights follow opusfile | libopus BSD 3-clause (Xiph.Org, Skype, Octasic, J.-M. Valin, T. B. Terriberry, CSIRO, G. Maxwell, M. Borgerding, E. de Castro Lopo, Mozilla, Amazon), opusfile BSD 3-clause: [libopus-BSD.txt](libopus-BSD.txt) | | `src/Formats/audio/flac/` | flac-luau 7083d0d (same author), written from RFC 9639 | no licence chosen yet; no third-party code | +| `src/Formats/image/bmp/` | bmp-luau b86aed6 (same author), written from the Microsoft BMP documentation | no licence chosen yet; no third-party code | +| `tests/fixtures/bmpsuite/` | BMP Suite 2.8 by Jason Summers (generated images) | public domain: [bmpsuite-NOTICE.txt](bmpsuite-NOTICE.txt) | | `tests/fixtures/pngsuite/` | PngSuite by Willem van Schaik | [PngSuite-LICENSE.txt](PngSuite-LICENSE.txt) | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this diff --git a/licenses/bmpsuite-NOTICE.txt b/licenses/bmpsuite-NOTICE.txt new file mode 100644 index 0000000..a47b169 --- /dev/null +++ b/licenses/bmpsuite-NOTICE.txt @@ -0,0 +1,7 @@ +tests/fixtures/bmpsuite/ (g/, q/, b/ and the reference PNGs in ref/) come from the BMP Suite 2.8 by Jason Summers +(https://entropymine.com/jason/bmpsuite/). The suite's generator program is GPL-3.0, but, in its own words: + + Image files generated by this program are in the public domain. + +Only the generated image files are included here (ref.txt, mapping files to their reference PNG, was written for +formats-luau from the suite's bmpsuite.html). diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 1fd157e..2503f9d 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -14,6 +14,18 @@ export type Entry = { } local list: { Entry } = { + { + name = "bmp", + category = "image", + path = "image/bmp", + 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 }, + load = function() + return require("@formats/image/bmp") + end, + }, { name = "png", category = "image", diff --git a/src/Formats/image/bmp/Pixels.luau b/src/Formats/image/bmp/Pixels.luau new file mode 100644 index 0000000..331b198 --- /dev/null +++ b/src/Formats/image/bmp/Pixels.luau @@ -0,0 +1,247 @@ +--!strict +--!native +--!optimize 2 +-- image/bmp/Pixels: the pixel loops (native), decode and encode. Absorbed from bmp-luau b86aed6 (same author, no +-- third-party code); the encoder loops are new. They never throw: the caller (init.luau) validates every size first, and +-- hands in a source buffer that holds every byte an uncompressed loop can read (a truncated file is copied into a +-- zero-padded buffer). The RLE loop checks each read against its end offset. Output: RGBA8, top-down rows, one +-- u32 per pixel (R | G << 8 | B << 16 | A << 24, little-endian = bytes R, G, B, A). +local readu8, readu16, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32, buffer.writeu8 +local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lshift + +local Pixels = {} + +-- 1, 2, 4 and 8 bpp through a 256-entry u32 palette (pal) +function Pixels.indexed(src: buffer, base: number, stride: number, bpp: number, dst: buffer, w: number, h: number, + topDown: boolean, pal: buffer) + local mask = lshift(1, bpp) - 1 + for r = 0, h - 1 do + local so = base + r * stride + local d = (if topDown then r else h - 1 - r) * w * 4 + if bpp == 8 then + for x = 0, w - 1 do + writeu32(dst, d + x * 4, readu32(pal, readu8(src, so + x) * 4)) + end + elseif bpp == 4 then + for x = 0, w - 1 do + local b = readu8(src, so + rshift(x, 1)) + local i = if band(x, 1) == 0 then rshift(b, 4) else band(b, 15) + writeu32(dst, d + x * 4, readu32(pal, i * 4)) + end + else + for x = 0, w - 1 do + local bit = x * bpp + local b = readu8(src, so + rshift(bit, 3)) + local i = band(rshift(b, 8 - bpp - band(bit, 7)), mask) + writeu32(dst, d + x * 4, readu32(pal, i * 4)) + end + end + end +end + +-- 24 bpp BI_RGB: B, G, R +function Pixels.bgr24(src: buffer, base: number, stride: number, dst: buffer, w: number, h: number, topDown: boolean) + for r = 0, h - 1 do + local so = base + r * stride + local d = (if topDown then r else h - 1 - r) * w * 4 + for x = 0, w - 1 do + local s = so + x * 3 + writeu32(dst, d + x * 4, + bor(readu8(src, s + 2), lshift(readu8(src, s + 1), 8), lshift(readu8(src, s), 16), 0xFF000000)) + end + end +end + +-- 32 bpp B, G, R, A (BI_RGB, or BITFIELDS with the standard masks). Returns the OR of every alpha byte. +function Pixels.bgra32(src: buffer, base: number, stride: number, dst: buffer, w: number, h: number, + topDown: boolean): number + local aor = 0 + for r = 0, h - 1 do + local so = base + r * stride + local d = (if topDown then r else h - 1 - r) * w * 4 + for x = 0, w - 1 do + local p = readu32(src, so + x * 4) + -- swap R and B: B G R A -> R G B A + writeu32(dst, d + x * 4, bor(band(p, 0xFF00FF00), band(rshift(p, 16), 0xFF), lshift(band(p, 0xFF), 16))) + aor = bor(aor, p) + end + end + return rshift(aor, 24) +end + +-- 16 / 24 / 32 bpp through bit masks. sh* = shift of each mask, m* = mask >> shift, t* = scale tables (u8, one entry +-- per masked value). A channel without a mask has m = 0 and a 1-entry table (0 for colour, 255 for alpha). +-- Returns the OR of every masked alpha value (before scaling). +function Pixels.masked(src: buffer, base: number, stride: number, bpp: number, dst: buffer, w: number, h: number, + topDown: boolean, shr: number, mr: number, tr: buffer, shg: number, mg: number, tg: buffer, shb: number, + mb: number, tb: buffer, sha: number, ma: number, ta: buffer): number + local bytes = rshift(bpp, 3) + local aor = 0 + for r = 0, h - 1 do + local so = base + r * stride + local d = (if topDown then r else h - 1 - r) * w * 4 + for x = 0, w - 1 do + local s = so + x * bytes + local p + if bytes == 2 then + p = readu16(src, s) + elseif bytes == 4 then + p = readu32(src, s) + else + p = bor(readu16(src, s), lshift(readu8(src, s + 2), 16)) + end + local a = band(rshift(p, sha), ma) + aor = bor(aor, a) + local o = d + x * 4 + writeu8(dst, o, readu8(tr, band(rshift(p, shr), mr))) + writeu8(dst, o + 1, readu8(tg, band(rshift(p, shg), mg))) + writeu8(dst, o + 2, readu8(tb, band(rshift(p, shb), mb))) + writeu8(dst, o + 3, readu8(ta, a)) + end + end + return aor +end + +-- Sets every alpha byte to 255 (32-bit images whose alpha channel is all zero are opaque). +function Pixels.opaque(dst: buffer, n: number) + for i = 0, n - 1 do + writeu8(dst, i * 4 + 3, 255) + end +end + +-- RLE8 / RLE4 from src[pos, stop) into dst (pre-filled with transparent black; pixels the stream skips with a +-- delta, an early end of line or an early end of bitmap stay transparent). Malformed or truncated data stops the +-- decode and keeps what was drawn. Returns the number of pixels written. +function Pixels.rle(src: buffer, pos: number, stop: number, rle4: boolean, dst: buffer, w: number, h: number, + topDown: boolean, pal: buffer): number + local x, y = 0, 0 + local written = 0 + local row = (if topDown then 0 else h - 1) * w * 4 + local rowStep = if topDown then w * 4 else -w * 4 + while y < h and pos + 1 < stop do + local n = readu8(src, pos) + local v = readu8(src, pos + 1) + pos += 2 + if n > 0 then + -- encoded run: n pixels of index v (RLE4: alternating high / low nibble) + local e = math.min(x + n, w) + if rle4 then + local hi, lo = readu32(pal, rshift(v, 4) * 4), readu32(pal, band(v, 15) * 4) + for i = x, e - 1 do + writeu32(dst, row + i * 4, if band(i - x, 1) == 0 then hi else lo) + end + else + local c = readu32(pal, v * 4) + for i = x, e - 1 do + writeu32(dst, row + i * 4, c) + end + end + if e > x then + written += e - x + end + x += n + elseif v == 0 then + -- end of line + x = 0 + y += 1 + row += rowStep + elseif v == 1 then + break -- end of bitmap + elseif v == 2 then + -- delta: right dx, up (in file rows) dy + if pos + 1 >= stop then + break + end + local dx, dy = readu8(src, pos), readu8(src, pos + 1) + pos += 2 + x += dx + y += dy + row += rowStep * dy + else + -- absolute run of v pixels, padded to a 16-bit boundary + local nb = if rle4 then rshift(v + 1, 1) else v + if pos + nb > stop then + break + end + local e = math.min(x + v, w) + for i = x, e - 1 do + local k = i - x + local idx + if rle4 then + local b = readu8(src, pos + rshift(k, 1)) + idx = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15) + else + idx = readu8(src, pos + k) + end + writeu32(dst, row + i * 4, readu32(pal, idx * 4)) + end + if e > x then + written += e - x + end + x += v + pos += nb + band(nb, 1) + end + end + return written +end + +-- Encoder: rgba8 (top-down) -> 24 bpp BGR rows, bottom-up, each padded to stride (dst is zero-filled) +function Pixels.encode24(src: buffer, w: number, h: number, dst: buffer, base: number, stride: number) + for y = 0, h - 1 do + local s = y * w * 4 + local d = base + (h - 1 - y) * stride + for x = 0, w - 1 do + local v = readu32(src, s + x * 4) + writeu8(dst, d, band(rshift(v, 16), 255)) + writeu8(dst, d + 1, band(rshift(v, 8), 255)) + writeu8(dst, d + 2, band(v, 255)) + d += 3 + end + end +end + +-- rgba8 -> 32 bpp BGRA, bottom-up +function Pixels.encode32(src: buffer, w: number, h: number, dst: buffer, base: number) + for y = 0, h - 1 do + local s = y * w * 4 + local d = base + (h - 1 - y) * w * 4 + for x = 0, w - 1 do + local v = readu32(src, s + x * 4) + -- R G B A (little-endian u32: R | G << 8 | B << 16 | A << 24) -> B G R A + writeu32(dst, d + x * 4, bor(band(v, 0xFF00FF00), band(rshift(v, 16), 255), lshift(band(v, 255), 16))) + end + end +end + +-- rgba8 -> 8 bpp indexes through idx (a table colour -> index, colours as R | G << 8 | B << 16), bottom-up +function Pixels.encode8(src: buffer, w: number, h: number, dst: buffer, base: number, stride: number, idx: { [number]: number }) + for y = 0, h - 1 do + local s = y * w * 4 + local d = base + (h - 1 - y) * stride + for x = 0, w - 1 do + writeu8(dst, d + x, idx[band(readu32(src, s + x * 4), 0xFFFFFF)] or 0) + end + end +end + +-- colours(src, n, max) -> the distinct RGB colours in first-appearance order (R | G << 8 | B << 16), whether any +-- alpha is below 255; stops counting at max + 1 colours +function Pixels.colours(src: buffer, n: number, max: number): ({ number }, boolean) + local seen: { [number]: boolean } = {} + local list: { number } = {} + local alpha = false + for i = 0, n - 1 do + local v = readu32(src, i * 4) + if v < 0xFF000000 then + alpha = true + end + local c = band(v, 0xFFFFFF) + if #list <= max and not seen[c] then + seen[c] = true + list[#list + 1] = c + end + end + return list, alpha +end + +return Pixels diff --git a/src/Formats/image/bmp/init.luau b/src/Formats/image/bmp/init.luau new file mode 100644 index 0000000..335b8e8 --- /dev/null +++ b/src/Formats/image/bmp/init.luau @@ -0,0 +1,424 @@ +--!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, gm, bm = readu32(buf, 54), readu32(buf, 58), 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, gm, bm = readu32(buf, palStart), readu32(buf, palStart + 4), 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, yp = math.floor((dpi.x :: number) * 39.3701 + 0.5), 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 diff --git a/tests/fixtures/bmpsuite/b/badbitcount.bmp b/tests/fixtures/bmpsuite/b/badbitcount.bmp new file mode 100644 index 0000000..d4fa4e8 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/badbitcount.bmp differ diff --git a/tests/fixtures/bmpsuite/b/badbitssize.bmp b/tests/fixtures/bmpsuite/b/badbitssize.bmp new file mode 100644 index 0000000..0a99a60 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/badbitssize.bmp differ diff --git a/tests/fixtures/bmpsuite/b/baddens1.bmp b/tests/fixtures/bmpsuite/b/baddens1.bmp new file mode 100644 index 0000000..a6150a6 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/baddens1.bmp differ diff --git a/tests/fixtures/bmpsuite/b/baddens2.bmp b/tests/fixtures/bmpsuite/b/baddens2.bmp new file mode 100644 index 0000000..f2c1dfb Binary files /dev/null and b/tests/fixtures/bmpsuite/b/baddens2.bmp differ diff --git a/tests/fixtures/bmpsuite/b/badfilesize.bmp b/tests/fixtures/bmpsuite/b/badfilesize.bmp new file mode 100644 index 0000000..da52cb5 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/badfilesize.bmp differ diff --git a/tests/fixtures/bmpsuite/b/badheadersize.bmp b/tests/fixtures/bmpsuite/b/badheadersize.bmp new file mode 100644 index 0000000..2a4083a Binary files /dev/null and b/tests/fixtures/bmpsuite/b/badheadersize.bmp differ diff --git a/tests/fixtures/bmpsuite/b/badpalettesize.bmp b/tests/fixtures/bmpsuite/b/badpalettesize.bmp new file mode 100644 index 0000000..7d9d1b7 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/badpalettesize.bmp differ diff --git a/tests/fixtures/bmpsuite/b/badplanes.bmp b/tests/fixtures/bmpsuite/b/badplanes.bmp new file mode 100644 index 0000000..92d2855 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/badplanes.bmp differ diff --git a/tests/fixtures/bmpsuite/b/badrle.bmp b/tests/fixtures/bmpsuite/b/badrle.bmp new file mode 100644 index 0000000..cbf8fdc Binary files /dev/null and b/tests/fixtures/bmpsuite/b/badrle.bmp differ diff --git a/tests/fixtures/bmpsuite/b/badrle4.bmp b/tests/fixtures/bmpsuite/b/badrle4.bmp new file mode 100644 index 0000000..632787a Binary files /dev/null and b/tests/fixtures/bmpsuite/b/badrle4.bmp differ diff --git a/tests/fixtures/bmpsuite/b/badrle4bis.bmp b/tests/fixtures/bmpsuite/b/badrle4bis.bmp new file mode 100644 index 0000000..130b7e6 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/badrle4bis.bmp differ diff --git a/tests/fixtures/bmpsuite/b/badrle4ter.bmp b/tests/fixtures/bmpsuite/b/badrle4ter.bmp new file mode 100644 index 0000000..8107a33 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/badrle4ter.bmp differ diff --git a/tests/fixtures/bmpsuite/b/badrlebis.bmp b/tests/fixtures/bmpsuite/b/badrlebis.bmp new file mode 100644 index 0000000..893eb11 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/badrlebis.bmp differ diff --git a/tests/fixtures/bmpsuite/b/badrleter.bmp b/tests/fixtures/bmpsuite/b/badrleter.bmp new file mode 100644 index 0000000..04d5874 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/badrleter.bmp differ diff --git a/tests/fixtures/bmpsuite/b/badwidth.bmp b/tests/fixtures/bmpsuite/b/badwidth.bmp new file mode 100644 index 0000000..9fca005 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/badwidth.bmp differ diff --git a/tests/fixtures/bmpsuite/b/pal8badindex.bmp b/tests/fixtures/bmpsuite/b/pal8badindex.bmp new file mode 100644 index 0000000..efe16c0 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/pal8badindex.bmp differ diff --git a/tests/fixtures/bmpsuite/b/reallybig.bmp b/tests/fixtures/bmpsuite/b/reallybig.bmp new file mode 100644 index 0000000..101e0b4 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/reallybig.bmp differ diff --git a/tests/fixtures/bmpsuite/b/rgb16-880.bmp b/tests/fixtures/bmpsuite/b/rgb16-880.bmp new file mode 100644 index 0000000..72e7ce0 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/rgb16-880.bmp differ diff --git a/tests/fixtures/bmpsuite/b/rletopdown.bmp b/tests/fixtures/bmpsuite/b/rletopdown.bmp new file mode 100644 index 0000000..21a909f Binary files /dev/null and b/tests/fixtures/bmpsuite/b/rletopdown.bmp differ diff --git a/tests/fixtures/bmpsuite/b/shortfile.bmp b/tests/fixtures/bmpsuite/b/shortfile.bmp new file mode 100644 index 0000000..7396079 Binary files /dev/null and b/tests/fixtures/bmpsuite/b/shortfile.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal1.bmp b/tests/fixtures/bmpsuite/g/pal1.bmp new file mode 100644 index 0000000..4776f82 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal1.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal1bg.bmp b/tests/fixtures/bmpsuite/g/pal1bg.bmp new file mode 100644 index 0000000..466d0ba Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal1bg.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal1wb.bmp b/tests/fixtures/bmpsuite/g/pal1wb.bmp new file mode 100644 index 0000000..56cb932 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal1wb.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal4.bmp b/tests/fixtures/bmpsuite/g/pal4.bmp new file mode 100644 index 0000000..7fd3630 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal4.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal4gs.bmp b/tests/fixtures/bmpsuite/g/pal4gs.bmp new file mode 100644 index 0000000..813268c Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal4gs.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal4rle.bmp b/tests/fixtures/bmpsuite/g/pal4rle.bmp new file mode 100644 index 0000000..a5672ae Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal4rle.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal8-0.bmp b/tests/fixtures/bmpsuite/g/pal8-0.bmp new file mode 100644 index 0000000..ab8815a Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal8-0.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal8.bmp b/tests/fixtures/bmpsuite/g/pal8.bmp new file mode 100644 index 0000000..96b2f86 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal8.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal8gs.bmp b/tests/fixtures/bmpsuite/g/pal8gs.bmp new file mode 100644 index 0000000..66a0d70 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal8gs.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal8nonsquare.bmp b/tests/fixtures/bmpsuite/g/pal8nonsquare.bmp new file mode 100644 index 0000000..0aa8de0 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal8nonsquare.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal8os2.bmp b/tests/fixtures/bmpsuite/g/pal8os2.bmp new file mode 100644 index 0000000..14901b3 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal8os2.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal8rle.bmp b/tests/fixtures/bmpsuite/g/pal8rle.bmp new file mode 100644 index 0000000..d431014 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal8rle.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal8topdown.bmp b/tests/fixtures/bmpsuite/g/pal8topdown.bmp new file mode 100644 index 0000000..4b2f8e0 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal8topdown.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal8v4.bmp b/tests/fixtures/bmpsuite/g/pal8v4.bmp new file mode 100644 index 0000000..34ebb80 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal8v4.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal8v5.bmp b/tests/fixtures/bmpsuite/g/pal8v5.bmp new file mode 100644 index 0000000..c54647a Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal8v5.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal8w124.bmp b/tests/fixtures/bmpsuite/g/pal8w124.bmp new file mode 100644 index 0000000..b7cc2d8 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal8w124.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal8w125.bmp b/tests/fixtures/bmpsuite/g/pal8w125.bmp new file mode 100644 index 0000000..06efed7 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal8w125.bmp differ diff --git a/tests/fixtures/bmpsuite/g/pal8w126.bmp b/tests/fixtures/bmpsuite/g/pal8w126.bmp new file mode 100644 index 0000000..112aa9f Binary files /dev/null and b/tests/fixtures/bmpsuite/g/pal8w126.bmp differ diff --git a/tests/fixtures/bmpsuite/g/rgb16-565.bmp b/tests/fixtures/bmpsuite/g/rgb16-565.bmp new file mode 100644 index 0000000..c03a279 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/rgb16-565.bmp differ diff --git a/tests/fixtures/bmpsuite/g/rgb16-565pal.bmp b/tests/fixtures/bmpsuite/g/rgb16-565pal.bmp new file mode 100644 index 0000000..e7632e3 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/rgb16-565pal.bmp differ diff --git a/tests/fixtures/bmpsuite/g/rgb16.bmp b/tests/fixtures/bmpsuite/g/rgb16.bmp new file mode 100644 index 0000000..6bfe47a Binary files /dev/null and b/tests/fixtures/bmpsuite/g/rgb16.bmp differ diff --git a/tests/fixtures/bmpsuite/g/rgb16bfdef.bmp b/tests/fixtures/bmpsuite/g/rgb16bfdef.bmp new file mode 100644 index 0000000..30fe8bb Binary files /dev/null and b/tests/fixtures/bmpsuite/g/rgb16bfdef.bmp differ diff --git a/tests/fixtures/bmpsuite/g/rgb24.bmp b/tests/fixtures/bmpsuite/g/rgb24.bmp new file mode 100644 index 0000000..40f8bb0 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/rgb24.bmp differ diff --git a/tests/fixtures/bmpsuite/g/rgb24pal.bmp b/tests/fixtures/bmpsuite/g/rgb24pal.bmp new file mode 100644 index 0000000..102e971 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/rgb24pal.bmp differ diff --git a/tests/fixtures/bmpsuite/g/rgb32.bmp b/tests/fixtures/bmpsuite/g/rgb32.bmp new file mode 100644 index 0000000..5d57eaa Binary files /dev/null and b/tests/fixtures/bmpsuite/g/rgb32.bmp differ diff --git a/tests/fixtures/bmpsuite/g/rgb32bf.bmp b/tests/fixtures/bmpsuite/g/rgb32bf.bmp new file mode 100644 index 0000000..20fa9a1 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/rgb32bf.bmp differ diff --git a/tests/fixtures/bmpsuite/g/rgb32bfdef.bmp b/tests/fixtures/bmpsuite/g/rgb32bfdef.bmp new file mode 100644 index 0000000..d7e64e5 Binary files /dev/null and b/tests/fixtures/bmpsuite/g/rgb32bfdef.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal1huffmsb.bmp b/tests/fixtures/bmpsuite/q/pal1huffmsb.bmp new file mode 100644 index 0000000..0ade234 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal1huffmsb.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal1p1.bmp b/tests/fixtures/bmpsuite/q/pal1p1.bmp new file mode 100644 index 0000000..b68321c Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal1p1.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal2.bmp b/tests/fixtures/bmpsuite/q/pal2.bmp new file mode 100644 index 0000000..983e9fa Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal2.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal2color.bmp b/tests/fixtures/bmpsuite/q/pal2color.bmp new file mode 100644 index 0000000..27fe727 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal2color.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal4rlecut.bmp b/tests/fixtures/bmpsuite/q/pal4rlecut.bmp new file mode 100644 index 0000000..2f32d1d Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal4rlecut.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal4rletrns.bmp b/tests/fixtures/bmpsuite/q/pal4rletrns.bmp new file mode 100644 index 0000000..58994e9 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal4rletrns.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal8offs.bmp b/tests/fixtures/bmpsuite/q/pal8offs.bmp new file mode 100644 index 0000000..8673e97 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal8offs.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal8os2-hs.bmp b/tests/fixtures/bmpsuite/q/pal8os2-hs.bmp new file mode 100644 index 0000000..018a3c4 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal8os2-hs.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal8os2-sz.bmp b/tests/fixtures/bmpsuite/q/pal8os2-sz.bmp new file mode 100644 index 0000000..7f1455d Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal8os2-sz.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal8os2sp.bmp b/tests/fixtures/bmpsuite/q/pal8os2sp.bmp new file mode 100644 index 0000000..e532c89 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal8os2sp.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal8os2v2-16.bmp b/tests/fixtures/bmpsuite/q/pal8os2v2-16.bmp new file mode 100644 index 0000000..95a1d23 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal8os2v2-16.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal8os2v2-40sz.bmp b/tests/fixtures/bmpsuite/q/pal8os2v2-40sz.bmp new file mode 100644 index 0000000..d1e66b6 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal8os2v2-40sz.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal8os2v2-sz.bmp b/tests/fixtures/bmpsuite/q/pal8os2v2-sz.bmp new file mode 100644 index 0000000..6fe566e Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal8os2v2-sz.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal8os2v2.bmp b/tests/fixtures/bmpsuite/q/pal8os2v2.bmp new file mode 100644 index 0000000..1324a40 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal8os2v2.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal8oversizepal.bmp b/tests/fixtures/bmpsuite/q/pal8oversizepal.bmp new file mode 100644 index 0000000..93b8187 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal8oversizepal.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal8rlecut.bmp b/tests/fixtures/bmpsuite/q/pal8rlecut.bmp new file mode 100644 index 0000000..840d31c Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal8rlecut.bmp differ diff --git a/tests/fixtures/bmpsuite/q/pal8rletrns.bmp b/tests/fixtures/bmpsuite/q/pal8rletrns.bmp new file mode 100644 index 0000000..a2af88d Binary files /dev/null and b/tests/fixtures/bmpsuite/q/pal8rletrns.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb16-231.bmp b/tests/fixtures/bmpsuite/q/rgb16-231.bmp new file mode 100644 index 0000000..6300f69 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb16-231.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb16-3103.bmp b/tests/fixtures/bmpsuite/q/rgb16-3103.bmp new file mode 100644 index 0000000..6e01226 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb16-3103.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb16faketrns.bmp b/tests/fixtures/bmpsuite/q/rgb16faketrns.bmp new file mode 100644 index 0000000..62fb393 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb16faketrns.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb24jpeg.bmp b/tests/fixtures/bmpsuite/q/rgb24jpeg.bmp new file mode 100644 index 0000000..87d73d7 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb24jpeg.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb24largepal.bmp b/tests/fixtures/bmpsuite/q/rgb24largepal.bmp new file mode 100644 index 0000000..d5e418c Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb24largepal.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb24lprof.bmp b/tests/fixtures/bmpsuite/q/rgb24lprof.bmp new file mode 100644 index 0000000..b868b88 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb24lprof.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb24png.bmp b/tests/fixtures/bmpsuite/q/rgb24png.bmp new file mode 100644 index 0000000..e87ec7a Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb24png.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb24prof.bmp b/tests/fixtures/bmpsuite/q/rgb24prof.bmp new file mode 100644 index 0000000..627e676 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb24prof.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb24prof2.bmp b/tests/fixtures/bmpsuite/q/rgb24prof2.bmp new file mode 100644 index 0000000..f9f61b8 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb24prof2.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb24rle24.bmp b/tests/fixtures/bmpsuite/q/rgb24rle24.bmp new file mode 100644 index 0000000..360aee6 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb24rle24.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb32-111110.bmp b/tests/fixtures/bmpsuite/q/rgb32-111110.bmp new file mode 100644 index 0000000..ec07d89 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb32-111110.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb32-7187.bmp b/tests/fixtures/bmpsuite/q/rgb32-7187.bmp new file mode 100644 index 0000000..887ba52 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb32-7187.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb32-xbgr.bmp b/tests/fixtures/bmpsuite/q/rgb32-xbgr.bmp new file mode 100644 index 0000000..c6c05e1 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb32-xbgr.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb32fakealpha.bmp b/tests/fixtures/bmpsuite/q/rgb32fakealpha.bmp new file mode 100644 index 0000000..cb544da Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb32fakealpha.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgb32h52.bmp b/tests/fixtures/bmpsuite/q/rgb32h52.bmp new file mode 100644 index 0000000..db6e453 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgb32h52.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgba16-1924.bmp b/tests/fixtures/bmpsuite/q/rgba16-1924.bmp new file mode 100644 index 0000000..6564098 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgba16-1924.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgba16-4444.bmp b/tests/fixtures/bmpsuite/q/rgba16-4444.bmp new file mode 100644 index 0000000..051ff23 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgba16-4444.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgba16-5551.bmp b/tests/fixtures/bmpsuite/q/rgba16-5551.bmp new file mode 100644 index 0000000..73e2cd5 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgba16-5551.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgba32-1.bmp b/tests/fixtures/bmpsuite/q/rgba32-1.bmp new file mode 100644 index 0000000..3c1e264 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgba32-1.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgba32-1010102.bmp b/tests/fixtures/bmpsuite/q/rgba32-1010102.bmp new file mode 100644 index 0000000..1a918ce Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgba32-1010102.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgba32-2.bmp b/tests/fixtures/bmpsuite/q/rgba32-2.bmp new file mode 100644 index 0000000..829c7c7 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgba32-2.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgba32-61754.bmp b/tests/fixtures/bmpsuite/q/rgba32-61754.bmp new file mode 100644 index 0000000..d5936fd Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgba32-61754.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgba32-81284.bmp b/tests/fixtures/bmpsuite/q/rgba32-81284.bmp new file mode 100644 index 0000000..1f9fc29 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgba32-81284.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgba32abf.bmp b/tests/fixtures/bmpsuite/q/rgba32abf.bmp new file mode 100644 index 0000000..d9bb018 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgba32abf.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgba32h56.bmp b/tests/fixtures/bmpsuite/q/rgba32h56.bmp new file mode 100644 index 0000000..343baa3 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgba32h56.bmp differ diff --git a/tests/fixtures/bmpsuite/q/rgba64.bmp b/tests/fixtures/bmpsuite/q/rgba64.bmp new file mode 100644 index 0000000..2e78d44 Binary files /dev/null and b/tests/fixtures/bmpsuite/q/rgba64.bmp differ diff --git a/tests/fixtures/bmpsuite/ref.txt b/tests/fixtures/bmpsuite/ref.txt new file mode 100644 index 0000000..1dd7e15 --- /dev/null +++ b/tests/fixtures/bmpsuite/ref.txt @@ -0,0 +1,27 @@ +g/pal1.bmp pal1.png +g/pal1bg.bmp pal1bg.png +g/pal1wb.bmp pal1.png +g/pal4.bmp pal4.png +g/pal4gs.bmp pal4gs.png +g/pal4rle.bmp pal4.png +g/pal8-0.bmp pal8.png +g/pal8.bmp pal8.png +g/pal8gs.bmp pal8gs.png +g/pal8nonsquare.bmp pal8nonsquare-v.png +g/pal8os2.bmp pal8.png +g/pal8rle.bmp pal8.png +g/pal8topdown.bmp pal8.png +g/pal8v4.bmp pal8.png +g/pal8v5.bmp pal8.png +g/pal8w124.bmp pal8w124.png +g/pal8w125.bmp pal8w125.png +g/pal8w126.bmp pal8w126.png +g/rgb16-565.bmp rgb16-565.png +g/rgb16-565pal.bmp rgb16-565.png +g/rgb16.bmp rgb16.png +g/rgb16bfdef.bmp rgb16.png +g/rgb24.bmp rgb24.png +g/rgb24pal.bmp rgb24.png +g/rgb32.bmp rgb24.png +g/rgb32bf.bmp rgb24.png +g/rgb32bfdef.bmp rgb24.png diff --git a/tests/fixtures/bmpsuite/ref/pal1.png b/tests/fixtures/bmpsuite/ref/pal1.png new file mode 100644 index 0000000..89a433e Binary files /dev/null and b/tests/fixtures/bmpsuite/ref/pal1.png differ diff --git a/tests/fixtures/bmpsuite/ref/pal1bg.png b/tests/fixtures/bmpsuite/ref/pal1bg.png new file mode 100644 index 0000000..20c4bb8 Binary files /dev/null and b/tests/fixtures/bmpsuite/ref/pal1bg.png differ diff --git a/tests/fixtures/bmpsuite/ref/pal4.png b/tests/fixtures/bmpsuite/ref/pal4.png new file mode 100644 index 0000000..188bb04 Binary files /dev/null and b/tests/fixtures/bmpsuite/ref/pal4.png differ diff --git a/tests/fixtures/bmpsuite/ref/pal4gs.png b/tests/fixtures/bmpsuite/ref/pal4gs.png new file mode 100644 index 0000000..a2558fa Binary files /dev/null and b/tests/fixtures/bmpsuite/ref/pal4gs.png differ diff --git a/tests/fixtures/bmpsuite/ref/pal8.png b/tests/fixtures/bmpsuite/ref/pal8.png new file mode 100644 index 0000000..6dd9961 Binary files /dev/null and b/tests/fixtures/bmpsuite/ref/pal8.png differ diff --git a/tests/fixtures/bmpsuite/ref/pal8gs.png b/tests/fixtures/bmpsuite/ref/pal8gs.png new file mode 100644 index 0000000..a537e3a Binary files /dev/null and b/tests/fixtures/bmpsuite/ref/pal8gs.png differ diff --git a/tests/fixtures/bmpsuite/ref/pal8nonsquare-v.png b/tests/fixtures/bmpsuite/ref/pal8nonsquare-v.png new file mode 100644 index 0000000..124736c Binary files /dev/null and b/tests/fixtures/bmpsuite/ref/pal8nonsquare-v.png differ diff --git a/tests/fixtures/bmpsuite/ref/pal8w124.png b/tests/fixtures/bmpsuite/ref/pal8w124.png new file mode 100644 index 0000000..92bd357 Binary files /dev/null and b/tests/fixtures/bmpsuite/ref/pal8w124.png differ diff --git a/tests/fixtures/bmpsuite/ref/pal8w125.png b/tests/fixtures/bmpsuite/ref/pal8w125.png new file mode 100644 index 0000000..7e5e6b4 Binary files /dev/null and b/tests/fixtures/bmpsuite/ref/pal8w125.png differ diff --git a/tests/fixtures/bmpsuite/ref/pal8w126.png b/tests/fixtures/bmpsuite/ref/pal8w126.png new file mode 100644 index 0000000..1422f6e Binary files /dev/null and b/tests/fixtures/bmpsuite/ref/pal8w126.png differ diff --git a/tests/fixtures/bmpsuite/ref/rgb16-565.png b/tests/fixtures/bmpsuite/ref/rgb16-565.png new file mode 100644 index 0000000..04a3121 Binary files /dev/null and b/tests/fixtures/bmpsuite/ref/rgb16-565.png differ diff --git a/tests/fixtures/bmpsuite/ref/rgb16.png b/tests/fixtures/bmpsuite/ref/rgb16.png new file mode 100644 index 0000000..d954584 Binary files /dev/null and b/tests/fixtures/bmpsuite/ref/rgb16.png differ diff --git a/tests/fixtures/bmpsuite/ref/rgb24.png b/tests/fixtures/bmpsuite/ref/rgb24.png new file mode 100644 index 0000000..86a9c94 Binary files /dev/null and b/tests/fixtures/bmpsuite/ref/rgb24.png differ diff --git a/tests/image/bmp.luau b/tests/image/bmp.luau new file mode 100644 index 0000000..967c732 --- /dev/null +++ b/tests/image/bmp.luau @@ -0,0 +1,479 @@ +-- image/bmp tests: synthesized BMPs (every header type, bit depth and compression, row order, palettes, masks and alpha +-- rules, the RLE escapes, the lenient paths, errors), the BMP Suite against Pillow (g/ must match, q/ and b/ must not +-- throw), the encoder byte-exact against Pillow (24 bpp, 8 bpp paletted, 32 bpp BI_RGB) plus the V4 alpha header and +-- round trips (the V4 output was also checked by hand: Pillow and ImageMagick read the same RGBA), the api, and the +-- fuzz passes. Ported from bmp-luau tests/core.luau + tests/files.luau. +-- Fixtures: tools/fixtures/bmp.py. +local T = require("@tests/T") +local BmpF = require("@formats/image/bmp") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local F = require("@formats") +local Suite = require("@tests/gen/bmp_suite") +local Enc = require("@tests/gen/bmp_enc") + +local t = T.suite("bmp") +local function check(cond: any, label: string) + t:check(cond, label) +end + +-- the bmp-luau API on top of the contract (the ported tests below use it): decode(string | buffer) -> image with the +-- old fields | nil, message +local Bmp = {} +function Bmp.decode(s: any, opts: any?): (any, any) + local b = if type(s) == "string" then buffer.fromstring(s) else s + if type(b) ~= "buffer" then + return nil, "expected a buffer or a string" + end + local img, err = BmpF.decode(Bytes.reader(b), opts) + if not img then + return nil, (err :: any).message + end + local src = img.meta.source :: any + local o = img :: any + o.bitsPerPixel, o.compression, o.topDown = src.bitDepth, src.compression, src.topDown + o.paletteSize, o.headerSize = src.paletteSize, src.headerSize + return img, nil +end +function Bmp.info(s: string): any + return BmpF.info(Bytes.reader(buffer.fromstring(s))) +end +function Bmp.isBmp(s: string): boolean + return BmpF.sniff(Bytes.reader(buffer.fromstring(s))) > 0 +end + +local function le(v: number, n: number): string + local b = buffer.create(4) + buffer.writeu32(b, 0, v % 4294967296) + return buffer.readstring(b, 0, n) +end +local function u16(v: number): string + return le(v, 2) +end +local function u32(v: number): string + return le(v, 4) +end +local function i32(v: number): string + return le(if v < 0 then v + 4294967296 else v, 4) +end + +-- Builds a BMP. o: w, h (negative = top-down), bpp, comp, hs (12, 40, 52, 56, 108, 124), palette ({ {r,g,b} }), +-- clrUsed, masks ({r,g,b[,a]}: in the header for hs >= 52, else after it), pixels (string), off / bfSize overrides. +local function make(o): string + local hs = o.hs or 40 + local hdr + if hs == 12 then + hdr = u32(12) .. u16(o.w) .. u16(o.h) .. u16(1) .. u16(o.bpp) + else + hdr = u32(hs) .. i32(o.w) .. i32(o.h) .. u16(1) .. u16(o.bpp) .. u32(o.comp or 0) .. u32(o.sizeImage or #o.pixels) + .. i32(2835) .. i32(2835) .. u32(o.clrUsed or 0) .. u32(0) + if hs >= 52 then + local m = o.masks or {} + hdr ..= u32(m[1] or 0) .. u32(m[2] or 0) .. u32(m[3] or 0) + if hs >= 56 then + hdr ..= u32(m[4] or 0) + end + end + hdr ..= string.rep("\0", hs - #hdr) + end + local extra = "" + if hs == 40 and o.masks then + for _, m in o.masks do + extra ..= u32(m) + end + end + local pal = "" + for _, c in o.palette or {} do + pal ..= string.char(c[3], c[2], c[1]) .. (if hs == 12 then "" else "\0") + end + local off = o.off or (14 + #hdr + #extra + #pal) + local body = hdr .. extra .. pal .. o.pixels + local size = o.bfSize or (14 + #body) + return "BM" .. u32(size) .. u32(0) .. u32(off) .. body +end + +local function px(img, x, y): (number, number, number, number) + local o = (y * img.width + x) * 4 + local b = img.pixels + return buffer.readu8(b, o), buffer.readu8(b, o + 1), buffer.readu8(b, o + 2), buffer.readu8(b, o + 3) +end + +local function is(img, x, y, r, g, b, a, label) + local pr, pg, pb, pa = px(img, x, y) + check(pr == r and pg == g and pb == b and pa == a, + ("%s: (%d,%d) = %d,%d,%d,%d, want %d,%d,%d,%d"):format(label, x, y, pr, pg, pb, pa, r, g, b, a)) +end + +local function decode(s: string, label: string): any + local img, err = Bmp.decode(s) + check(img ~= nil, label .. ": " .. tostring(err)) + return img +end + +-- 24 bpp, bottom-up, row padding (w = 3 -> 9 bytes + 3 padding) +do + -- file rows: bottom row first. bottom = red green blue, top = white black grey + local bottom = "\0\0\255" .. "\0\255\0" .. "\255\0\0" .. "\0\0\0" + local top = "\255\255\255" .. "\0\0\0" .. "\128\128\128" .. "\0\0\0" + local img = decode(make({ w = 3, h = 2, bpp = 24, pixels = bottom .. top }), "rgb24") + check(img.width == 3 and img.height == 2 and buffer.len(img.pixels) == 24, "rgb24 size") + check(img.compression == "rgb" and img.bitsPerPixel == 24 and not img.topDown, "rgb24 fields") + is(img, 0, 1, 255, 0, 0, 255, "rgb24 bottom-left red") + is(img, 1, 1, 0, 255, 0, 255, "rgb24 green") + is(img, 2, 1, 0, 0, 255, 255, "rgb24 blue") + is(img, 0, 0, 255, 255, 255, 255, "rgb24 top-left white") + is(img, 2, 0, 128, 128, 128, 255, "rgb24 grey") + -- top-down (negative height): the first file row is the top + local td = decode(make({ w = 3, h = -2, bpp = 24, pixels = bottom .. top }), "rgb24 top-down") + check(td.topDown and td.height == 2, "top-down fields") + is(td, 0, 0, 255, 0, 0, 255, "top-down first row on top") + is(td, 0, 1, 255, 255, 255, 255, "top-down second row") + -- string and buffer input are the same + local b = Bmp.decode(buffer.fromstring(make({ w = 3, h = 2, bpp = 24, pixels = bottom .. top }))) + check(b and buffer.tostring(b.pixels) == buffer.tostring(img.pixels), "buffer input") +end + +local PAL = { { 0, 0, 0 }, { 255, 255, 255 }, { 255, 0, 0 }, { 0, 255, 0 }, { 0, 0, 255 } } + +-- 1 bpp: 10 pixels per row (2 bytes + 2 padding), MSB first +do + local row = string.char(0xA5, 0x80) .. "\0\0" -- 1010 0101 | 10 + local img = decode(make({ w = 10, h = 1, bpp = 1, palette = { { 10, 20, 30 }, { 40, 50, 60 } }, pixels = row }), "pal1") + local want = { 1, 0, 1, 0, 0, 1, 0, 1, 1, 0 } + for x = 0, 9 do + local c = if want[x + 1] == 1 then 40 else 10 + is(img, x, 0, c, c + 10, c + 20, 255, "pal1 x" .. x) + end + check(img.paletteSize == 2, "pal1 palette size") +end + +-- 2 bpp (non-standard, as in the BMP Suite's q/pal2.bmp) +do + local img = decode(make({ w = 4, h = 1, bpp = 2, palette = PAL, clrUsed = 4, pixels = string.char(0x1B) .. "\0\0\0" }), "pal2") + is(img, 0, 0, 0, 0, 0, 255, "pal2 0") + is(img, 1, 0, 255, 255, 255, 255, "pal2 1") + is(img, 2, 0, 255, 0, 0, 255, "pal2 2") + is(img, 3, 0, 0, 255, 0, 255, "pal2 3") +end + +-- 4 bpp, odd width; palette shorter than 16 (clrUsed = 5): index 7 is past it -> opaque black +do + local img = decode(make({ w = 3, h = 1, bpp = 4, palette = PAL, clrUsed = 5, pixels = string.char(0x24, 0x70, 0, 0) }), "pal4") + is(img, 0, 0, 255, 0, 0, 255, "pal4 x0 = 2") + is(img, 1, 0, 0, 0, 255, 255, "pal4 x1 = 4") + is(img, 2, 0, 0, 0, 0, 255, "pal4 x2 = 7 (past the palette)") + check(img.paletteSize == 5, "pal4 palette size") +end + +-- 8 bpp with clrUsed = 0 but only 3 entries before bfOffBits (a palette shorter than 2^bpp) +do + local s = make({ w = 4, h = 1, bpp = 8, palette = { PAL[3], PAL[4], PAL[5] }, pixels = string.char(0, 1, 2, 200) }) + local img = decode(s, "pal8 short") + check(img.paletteSize == 3, "pal8 short palette size " .. img.paletteSize) + is(img, 0, 0, 255, 0, 0, 255, "pal8 0") + is(img, 2, 0, 0, 0, 255, 255, "pal8 2") + is(img, 3, 0, 0, 0, 0, 255, "pal8 200 -> black") +end + +-- OS/2 1.x core header: 16-bit dimensions, 3-byte palette entries +do + local img = decode(make({ hs = 12, w = 2, h = 2, bpp = 8, palette = PAL, pixels = string.char(1, 2, 0, 0, 3, 4, 0, 0) }), "core") + check(img.headerSize == 12 and img.paletteSize == 5, "core fields") + is(img, 0, 1, 255, 255, 255, 255, "core bottom-left") + is(img, 1, 1, 255, 0, 0, 255, "core bottom-right") + is(img, 0, 0, 0, 255, 0, 255, "core top-left") + is(img, 1, 0, 0, 0, 255, 255, "core top-right") + local img24 = decode(make({ hs = 12, w = 1, h = 1, bpp = 24, pixels = "\1\2\3\0" }), "core 24") + is(img24, 0, 0, 3, 2, 1, 255, "core 24") +end + +-- 16 bpp: BI_RGB = 555; BITFIELDS 565; v3 header with a 4444 alpha mask. Scaling is v * 255 // max (as Pillow). +do + local p555 = 31 * 1024 + 16 * 32 + 1 -- r 31, g 16, b 1 + local img = decode(make({ w = 1, h = 1, bpp = 16, pixels = u16(p555) .. "\0\0" }), "555") + is(img, 0, 0, 255, 131, 8, 255, "555") + local p565 = 1 * 2048 + 63 * 32 + 30 + local img2 = decode(make({ w = 1, h = 1, bpp = 16, comp = 3, masks = { 0xF800, 0x7E0, 0x1F }, pixels = u16(p565) .. "\0\0" }), "565") + is(img2, 0, 0, 8, 255, 246, 255, "565") + check(img2.compression == "bitfields", "565 compression name") + local m4444 = { 0x0F00, 0x00F0, 0x000F, 0xF000 } + local img3 = decode(make({ hs = 56, w = 2, h = 1, bpp = 16, comp = 3, masks = m4444, pixels = u16(0x8F00) .. u16(0x00F0) }), "4444") + is(img3, 0, 0, 255, 0, 0, 136, "4444 alpha") + is(img3, 1, 0, 0, 255, 0, 0, "4444 transparent") + -- an alpha mask whose values are all zero: opaque + local img4 = decode(make({ hs = 56, w = 1, h = 1, bpp = 16, comp = 3, masks = m4444, pixels = u16(0x0F00) .. "\0\0" }), "4444 zero alpha") + is(img4, 0, 0, 255, 0, 0, 255, "4444 all-zero alpha -> opaque") + -- v4 header with BI_RGB: masks in the header are ignored -> 555 + local img5 = decode(make({ hs = 108, w = 1, h = 1, bpp = 16, masks = { 0xF800, 0x7E0, 0x1F }, pixels = u16(p555) .. "\0\0" }), "v4 555") + is(img5, 0, 0, 255, 131, 8, 255, "v4 BI_RGB 16 -> 555") +end + +-- 32 bpp +do + -- BI_RGB, alpha bytes all zero -> opaque + local img = decode(make({ w = 2, h = 1, bpp = 32, pixels = "\1\2\3\0\4\5\6\0" }), "rgb32 zero alpha") + is(img, 0, 0, 3, 2, 1, 255, "rgb32 opaque 0") + is(img, 1, 0, 6, 5, 4, 255, "rgb32 opaque 1") + -- BI_RGB with alpha bytes used (as browsers do) + local img2 = decode(make({ w = 2, h = 1, bpp = 32, pixels = "\1\2\3\128\4\5\6\0" }), "rgb32 alpha") + is(img2, 0, 0, 3, 2, 1, 128, "rgb32 alpha 128") + is(img2, 1, 0, 6, 5, 4, 0, "rgb32 alpha 0") + -- BITFIELDS in an unusual order (R in the top byte), no alpha mask -> opaque even with bytes there + local img3 = decode(make({ w = 1, h = 1, bpp = 32, comp = 3, masks = { 0xFF000000, 0xFF0000, 0xFF00 }, pixels = "\9\3\2\1" }), "rgb32 bf") + is(img3, 0, 0, 1, 2, 3, 255, "rgb32 bitfields order") + -- standard BITFIELDS without an alpha mask: the 4th byte is ignored + local img4 = decode(make({ w = 1, h = 1, bpp = 32, comp = 3, masks = { 0xFF0000, 0xFF00, 0xFF }, pixels = "\1\2\3\77" }), "rgb32 bf std") + is(img4, 0, 0, 3, 2, 1, 255, "rgb32 std bitfields opaque") + -- ALPHABITFIELDS (compression 6) after a 40-byte header + local img5 = decode(make({ w = 1, h = 1, bpp = 32, comp = 6, masks = { 0xFF, 0xFF00, 0xFF0000, 0xFF000000 }, pixels = "\1\2\3\4" }), "alphabf") + is(img5, 0, 0, 1, 2, 3, 4, "alphabitfields RGBA") + check(img5.compression == "alphabitfields", "alphabitfields name") + -- v5 header with BITFIELDS + alpha mask; 10-bit channels (1010102) + local v = 1023 + 512 * 1024 + 0 * 1048576 + 3 * 1073741824 + local img6 = decode(make({ hs = 124, w = 1, h = 1, bpp = 32, comp = 3, masks = { 0x3FF, 0xFFC00, 0x3FF00000, 0xC0000000 }, pixels = u32(v) }), "1010102") + is(img6, 0, 0, 255, 127, 0, 255, "1010102") + -- v4 header with BI_RGB 32: alpha byte used + local img7 = decode(make({ hs = 108, w = 1, h = -1, bpp = 32, pixels = "\1\2\3\200" }), "v4 rgb32") + is(img7, 0, 0, 3, 2, 1, 200, "v4 rgb32 alpha") + -- 24 bpp with BITFIELDS (Pillow accepts it) + local img8 = decode(make({ w = 1, h = 1, bpp = 24, comp = 3, masks = { 0xFF, 0xFF00, 0xFF0000 }, pixels = "\1\2\3\0" }), "rgb24 bf") + is(img8, 0, 0, 1, 2, 3, 255, "rgb24 bitfields") +end + +-- RLE8: run, absolute (odd length, padded), end of line, delta, end of bitmap; skipped pixels are transparent +do + local pal = PAL + local stream = string.char( + 3, 2, -- row 0 (bottom): 3 x red + 0, 3, 1, 3, 4, 0, -- absolute 3: white green blue + pad + 0, 0, -- EOL (row 0 is 6 wide: x = 6, w = 8: x 6..7 skipped) + 0, 2, 2, 1, -- delta right 2, up 1: row 2, x = 2 + 2, 4, -- 2 x blue at row 2 x 2..3 + 0, 1 -- EOB: row 3 never written + ) + local img = decode(make({ w = 8, h = 4, bpp = 8, comp = 1, palette = pal, pixels = stream }), "rle8") + check(img.compression == "rle8", "rle8 name") + for x = 0, 2 do + is(img, x, 3, 255, 0, 0, 255, "rle8 run " .. x) + end + is(img, 3, 3, 255, 255, 255, 255, "rle8 abs 0") + is(img, 4, 3, 0, 255, 0, 255, "rle8 abs 1") + is(img, 5, 3, 0, 0, 255, 255, "rle8 abs 2") + is(img, 6, 3, 0, 0, 0, 0, "rle8 EOL skipped -> transparent") + is(img, 0, 2, 0, 0, 0, 0, "rle8 row 1 skipped by the delta") + is(img, 1, 1, 0, 0, 0, 0, "rle8 delta skip") + is(img, 2, 1, 0, 0, 255, 255, "rle8 after delta 0") + is(img, 3, 1, 0, 0, 255, 255, "rle8 after delta 1") + is(img, 4, 1, 0, 0, 0, 0, "rle8 after the run") + is(img, 0, 0, 0, 0, 0, 0, "rle8 EOB: top row empty") + -- a run past the row end is clipped; truncated data keeps what was drawn + local img2 = decode(make({ w = 2, h = 1, bpp = 8, comp = 1, palette = pal, pixels = string.char(5, 2, 0) }), "rle8 clip") + is(img2, 1, 0, 255, 0, 0, 255, "rle8 clipped run") + -- top-down RLE (out of spec, accepted) + local img3 = decode(make({ w = 1, h = -2, bpp = 8, comp = 1, palette = pal, pixels = string.char(1, 2, 0, 0, 1, 3, 0, 1) }), "rle8 top-down") + is(img3, 0, 0, 255, 0, 0, 255, "rle8 top-down row 0") + is(img3, 0, 1, 0, 255, 0, 255, "rle8 top-down row 1") +end + +-- RLE4: alternating nibbles in a run, an odd absolute run (3 pixels in 2 bytes, padded to 4) +do + local stream = string.char(5, 0x23, 0, 3, 0x14, 0x30, 0, 0, 0, 1) + local img = decode(make({ w = 8, h = 1, bpp = 4, comp = 2, palette = PAL, pixels = stream }), "rle4") + check(img.compression == "rle4", "rle4 name") + local want = { 2, 3, 2, 3, 2, 1, 4, 3 } + for x = 0, 7 do + local c = PAL[want[x + 1] + 1] + is(img, x, 0, c[1], c[2], c[3], 255, "rle4 x" .. x) + end +end + +-- leniency: bad bfSize, bad biSizeImage, bad bfOffBits, truncated pixels +do + local pixels = "\0\0\255" .. "\0\0\0" .. "\255\0\0" .. "\0\0\0" + local base = decode(make({ w = 1, h = 3, bpp = 24, pixels = pixels }), "lenient base") + local function same(img, label) + check(img and buffer.tostring(img.pixels) == buffer.tostring(base.pixels), label) + end + same(Bmp.decode(make({ w = 1, h = 3, bpp = 24, pixels = pixels, bfSize = 0 })), "bfSize 0") + same(Bmp.decode(make({ w = 1, h = 3, bpp = 24, pixels = pixels, bfSize = 999999 })), "bfSize too big") + same(Bmp.decode(make({ w = 1, h = 3, bpp = 24, pixels = pixels, sizeImage = 0 })), "biSizeImage 0") + same(Bmp.decode(make({ w = 1, h = 3, bpp = 24, pixels = pixels, sizeImage = 123456 })), "biSizeImage wrong") + same(Bmp.decode(make({ w = 1, h = 3, bpp = 24, pixels = pixels, off = 0 })), "bfOffBits 0") + same(Bmp.decode(make({ w = 1, h = 3, bpp = 24, pixels = pixels, off = 99999 })), "bfOffBits past the end") + -- truncated: the missing (top) rows read as zeros = opaque black + local t = decode(make({ w = 1, h = 3, bpp = 24, pixels = string.sub(pixels, 1, 5) }), "truncated") + is(t, 0, 2, 255, 0, 0, 255, "truncated: bottom row intact") + is(t, 0, 1, 0, 0, 0, 255, "truncated: partial row zero-filled") + is(t, 0, 0, 0, 0, 0, 255, "truncated: missing row black") + local t2 = decode(make({ w = 4, h = 4, bpp = 8, palette = PAL, pixels = "" }), "no pixel data") + is(t2, 3, 3, 0, 0, 0, 255, "no pixel data: index 0") +end + +-- info / isBmp +do + local s = make({ hs = 124, w = 7, h = -5, bpp = 32, comp = 3, masks = { 0xFF0000, 0xFF00, 0xFF, 0xFF000000 }, pixels = "" }) + local info = Bmp.info(s) + check(info and info.width == 7 and info.height == 5 and info.topDown and info.bitsPerPixel == 32, "info fields") + check(info and info.compression == 3 and info.headerSize == 124 and not info.os2, "info compression / header") + check(Bmp.isBmp(s) and not Bmp.isBmp("\137PNG") and not Bmp.isBmp(""), "isBmp") +end + +-- errors: nil + message, never a throw +do + local function fails(s: any, pattern: string, label: string, opts: any?) + local ok, img, err = pcall(Bmp.decode, s, opts) + check(ok, label .. ": threw " .. tostring(img)) + check(img == nil and type(err) == "string" and string.find(err, pattern) ~= nil, label .. ": " .. tostring(err)) + end + fails("", "too short", "empty") + fails(123, "expected a buffer", "not a buffer") + fails("\137PNG\r\n\26\n" .. string.rep("\0", 40), "not a BMP", "png") + fails("BM" .. string.rep("\0", 12) .. u32(200) .. string.rep("\0", 20), "header size", "header past the end") + fails("BM" .. string.rep("\0", 12) .. u32(8) .. string.rep("\0", 40), "header size", "header too small") + fails(make({ w = 0, h = 1, bpp = 24, pixels = "" }), "bad size", "zero width") + fails(make({ w = -4, h = 1, bpp = 24, pixels = "" }), "bad size", "negative width") + fails(make({ w = 1, h = 0, bpp = 24, pixels = "" }), "bad size", "zero height") + fails(make({ w = 1, h = 1, bpp = 3, pixels = "\0\0\0\0" }), "bit depth", "bpp 3") + fails(make({ w = 1, h = 1, bpp = 64, pixels = string.rep("\0", 8) }), "bit depth", "bpp 64") + fails(make({ w = 1, h = 1, bpp = 24, comp = 1, pixels = "" }), "RLE", "RLE8 with 24 bpp") + fails(make({ w = 1, h = 1, bpp = 8, comp = 3, pixels = "" }), "BITFIELDS", "BITFIELDS with 8 bpp") + fails(make({ w = 1, h = 1, bpp = 24, comp = 4, pixels = "" }), "JPEG", "jpeg") + fails(make({ w = 1, h = 1, bpp = 24, comp = 5, pixels = "" }), "PNG", "png in bmp") + fails(make({ w = 1, h = 1, bpp = 24, comp = 9, pixels = "" }), "compression", "unknown compression") + fails(make({ w = 1, h = 1, bpp = 32, comp = 3, pixels = "" }), "masks", "truncated bit masks") + fails(make({ w = 100000, h = 100000, bpp = 24, pixels = "" }), "too large", "too large") + fails(make({ w = 100, h = 100, bpp = 24, pixels = "" }), "too large", "maxPixels option", { maxPixels = 9999 }) +end + +-- fuzz: truncations and byte flips of every kind of file above must never throw +do + local seeds = { + make({ w = 3, h = 2, bpp = 24, pixels = string.rep("\1\2\3", 8) }), + make({ w = 10, h = 3, bpp = 1, palette = PAL, clrUsed = 2, pixels = string.rep("\170\85\0\0", 3) }), + make({ w = 5, h = 2, bpp = 4, palette = PAL, pixels = string.rep("\18\52\5\0", 2) }), + make({ hs = 12, w = 2, h = 2, bpp = 8, palette = PAL, pixels = string.char(1, 2, 0, 0, 3, 4, 0, 0) }), + make({ hs = 56, w = 2, h = 1, bpp = 16, comp = 3, masks = { 0x0F00, 0xF0, 0xF, 0xF000 }, pixels = "\1\2\3\4" }), + make({ hs = 124, w = 2, h = -2, bpp = 32, comp = 3, masks = { 0xFF0000, 0xFF00, 0xFF, 0xFF000000 }, pixels = string.rep("\1\2\3\4", 4) }), + make({ w = 8, h = 4, bpp = 8, comp = 1, palette = PAL, pixels = string.char(3, 2, 0, 3, 1, 3, 4, 0, 0, 0, 0, 2, 2, 1, 2, 4, 0, 1) }), + make({ w = 8, h = 1, bpp = 4, comp = 2, palette = PAL, pixels = string.char(5, 0x23, 0, 3, 0x14, 0x30, 0, 0, 0, 1) }), + } + local state = 12345 + local function rand(n: number): number + state = (state * 1103515245 + 12345) % 2147483648 + return state % n + end + local runs = 0 + for _, s in seeds do + for cut = 0, #s do + local ok, img = pcall(Bmp.decode, string.sub(s, 1, cut)) + check(ok, "truncated at " .. cut .. " threw: " .. tostring(img)) + runs += 1 + end + for _ = 1, 400 do + local b = buffer.fromstring(s) + for _ = 1, 1 + rand(4) do + buffer.writeu8(b, rand(#s), rand(256)) + end + local ok, img = pcall(Bmp.decode, b, { maxPixels = 2 ^ 20 }) + check(ok, "corrupted file threw: " .. tostring(img)) + if ok and img then + check(buffer.len(img.pixels) == img.width * img.height * 4, "corrupted file: pixel buffer size") + end + runs += 1 + end + end + t:note("fuzz: %d decodes, no throw", runs) +end + + +-- ------------------------------------------------------------------------------------------------ the BMP Suite +do + local nMatch, nOther = 0, 0 + local samples = {} + for _, e in Suite do + local ok, img, err = pcall(BmpF.decode, Bytes.reader(buffer.fromstring(e.data))) + t:check(ok, e.name .. ": threw " .. tostring(img)) + local same = img and e.w and img.width == e.w and img.height == e.h and Crc32.of(img.pixels) == e.crc + if e.mode == "match" then + t:check(same, e.name .. ": matches Pillow (" .. tostring(err) .. ")") + nMatch += 1 + else + t:check(img == nil or buffer.len(img.pixels) == img.width * img.height * 4, e.name .. ": pixel buffer size") + nOther += 1 + end + if #samples < 30 then + table.insert(samples, e.data) + end + end + t:note("BMP Suite: %d g/ files match Pillow, %d q/ + b/ files decode or fail cleanly", nMatch, nOther) + t:fuzz("decode (suite)", function(b: buffer) + return BmpF.decode(Bytes.reader(b), { maxPixels = 2 ^ 20 }) + end, samples, { mutations = 6 }) +end + +-- ------------------------------------------------------------------------------------------------ encoder +do + for _, c in Enc do + local img = Types.Image.new(c.w, c.h) + buffer.writestring(img.pixels, 0, c.rgba) + local opts: any = if c.mode == "RGBA" then { header = "info" } elseif c.mode == "RGB" then { bitDepth = 24 } else nil + local out, err = BmpF.encode(img, opts) + t:check(out, c.name .. ": encode: " .. tostring(err)) + local same = buffer.tostring(out :: buffer) == c.bmp + if not same then + t:note("%s ours %s", c.name, T.hex(out :: buffer, 70)) + t:note("%s pillow %s", c.name, T.hex(buffer.fromstring(c.bmp), 70)) + end + t:check(same, c.name .. ": identical to Pillow") + local back = BmpF.decode(Bytes.reader(out :: buffer)) :: any + t:check(back and buffer.tostring(back.pixels) == c.rgba, c.name .. ": round trip") + -- the default 32 bpp header (V4 BITFIELDS) round-trips too + if c.mode == "RGBA" then + local v4 = BmpF.encode(img) :: buffer + t:eq(buffer.readu32(v4, 14), 108, c.name .. ": V4 header") + local b2 = BmpF.decode(Bytes.reader(v4)) :: any + t:check(b2 and buffer.tostring(b2.pixels) == c.rgba and b2.meta.source.compression == "bitfields", c.name .. ": V4 round trip") + end + end + t:note("encoder: %d files identical to Pillow", #Enc) + -- forced depths, dpi, errors + local img = Types.Image.new(5, 4) + for i = 0, 19 do + buffer.writeu32(img.pixels, i * 4, 0xFF000000 + i * 0x010203) + end + for _, d in { 8, 24, 32 } do + local out = BmpF.encode(img, { bitDepth = d }) :: buffer + local back = BmpF.decode(Bytes.reader(out)) :: any + t:check(back.meta.source.bitDepth == d and buffer.tostring(back.pixels) == buffer.tostring(img.pixels), "bitDepth " .. d) + end + img.meta.dpi = { x = 300, y = 150 } + local withDpi = BmpF.decode(Bytes.reader(BmpF.encode(img) :: buffer)) :: any + t:check(math.abs(withDpi.meta.dpi.x - 300) < 0.1 and math.abs(withDpi.meta.dpi.y - 150) < 0.1, "dpi round trip") + local many = Types.Image.new(300, 1) + for i = 0, 299 do + buffer.writeu32(many.pixels, i * 4, 0xFF000000 + i) + end + local _, e1 = BmpF.encode(many, { bitDepth = 8 }) + t:check(e1 and e1.code == Err.ARG, "8 bpp with 300 colours") + t:eq(buffer.readu16(BmpF.encode(many) :: buffer, 28), 24, "auto: 300 opaque colours -> 24 bpp") + local _, e2 = BmpF.encode({} :: any) + t:check(e2 and e2.code == Err.ARG, "not an image") + local _, e3 = BmpF.encode(img, { bitDepth = 16 } :: any) + t:check(e3 and e3.code == Err.ARG, "bitDepth 16") + -- the api + local c = Enc[1] + local loaded = F.image.load(c.bmp) + t:check(loaded and loaded.width == c.w and buffer.tostring(loaded.pixels) == c.rgba, "F.image.load") + t:eq(F.detect(c.bmp), "bmp", "F.detect") + local saved = F.save(loaded, nil, { format = "bmp" }) + t:check(saved and buffer.tostring(saved) == c.bmp, "F.save bmp") + -- a sub-range reader + local big = buffer.create(#c.bmp + 5) + buffer.writestring(big, 3, c.bmp) + local sub = BmpF.decode(Bytes.reader(big, 3, #c.bmp)) :: any + t:check(sub and buffer.tostring(sub.pixels) == c.rgba, "decode from a sub-range") +end + +t:done() diff --git a/tools/fixtures/_bmp_reference.py b/tools/fixtures/_bmp_reference.py new file mode 100644 index 0000000..7b6ae6d --- /dev/null +++ b/tools/fixtures/_bmp_reference.py @@ -0,0 +1,134 @@ +# BMP reference decodes with Pillow (run by tools/fixtures/bmp.py inside a nix python with pillow): reads a JSON request +# on stdin, writes JSON on stdout. Ported from bmp-luau tools/mkfixtures.py (its Pillow rules: see "expected"). +# {"root": dir, "files": [rel...], "refs": {rel: png}, "encode": [{"name", "mode", "w", "h", "rgba" (hex), "palette"?}]} +# -> {"files": [{"name", "w", "h", "crc"} or {"name", "error"}], "encode": [{"name", "bmp" (hex)}]} +# Expected pixels: Pillow's RGBA, with these rules (Pillow differs from browsers there): +# - 32 bpp BI_RGB: the 4th byte is alpha (Pillow ignores it), unless every one is 0 (then opaque). +# - 32 bpp with an alpha mask whose values are all 0: opaque. +# - RLE: decoded by rle_reference below over Pillow's palette (Pillow's RLE decoder has bugs); skipped pixels are +# transparent black. +# - Files Pillow cannot read (unusual BITFIELDS in the suite's g/): the suite's own reference PNG. +import io, json, os, struct, sys, zlib +from PIL import Image, ImageFile + +# truncated files (a bad bfSize / short pixel array, as in some skins): Pillow fills the missing rows with 0 +ImageFile.LOAD_TRUNCATED_IMAGES = True + +# RLE: Pillow's decoder mishandles odd RLE4 absolute runs, an end of line at x = 0 and an end of bitmap before the +# last row (as in the Winamp base skin), so the reference for RLE files is this spec decoder over Pillow's palette. +# Pixels the stream skips (delta, early end of line / bitmap) are transparent black, as in browsers. +# (Pillow's own RLE decode still has to load without failing, for the palette: pad its output with index 0) +from PIL import BmpImagePlugin +_set_as_raw = BmpImagePlugin.BmpRleDecoder.set_as_raw +def _padded(self, data, rawmode=None, extra=()): + need = self.state.xsize * self.state.ysize + return _set_as_raw(self, data + b"\0" * max(0, need - len(data)), rawmode, extra) +BmpImagePlugin.BmpRleDecoder.set_as_raw = _padded + +def rle_reference(im, raw, w, h, rle4): + off = struct.unpack_from("> 4 if k % 2 == 0 else v & 15) if rle4 else v) + x += c + elif v == 0: + x, y = 0, y + 1 + elif v == 1: + break + elif v == 2: + if p + 1 >= n: + break + x, y = x + raw[p], y + raw[p + 1] + p += 2 + else: + nb = (v + 1) // 2 if rle4 else v + if p + nb > n: + break + for k in range(v): + b = raw[p + k // 2] if rle4 else raw[p + k] + put(x + k, y, (b >> 4 if k % 2 == 0 else b & 15) if rle4 else b) + x += v + p += nb + (nb & 1) + return bytes(out) + +def expected(path, raw, root): + try: + im = Image.open(path) + im.load() + except Exception: + ref = REFS.get(os.path.relpath(path, root)) + if not ref: + raise + ref = os.path.join(root, "ref", ref) + im = Image.open(ref) + im.load() + w, h = im.size + hs = struct.unpack_from("= 40 else 0 + if comp in (1, 2) and im.format == "BMP": + return w, h, rle_reference(im, raw, w, h, comp == 2), True + rgba = bytearray(im.convert("RGBA").tobytes()) + if hs >= 40: + bpp, comp = struct.unpack_from("