diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 7f04fd3..edcb10f 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -5,14 +5,17 @@ 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 | aiff | .aiff .aif .aifc .afc | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, lossy: false | `tests/audio/aiff.luau` | | audio | au | .au .snd | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, lossy: false | `tests/audio/au.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` | | audio | opus | .opus | yes | - | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000 | `tests/audio/opus.luau` | | audio | voc | .voc | yes | yes | streaming: true, depths: 8, 16, lossy: false | `tests/audio/voc.luau` | | audio | vorbis | .ogg .oga | yes | - | streaming: true, seek: true, lossy: true, channels: 255 | `tests/audio/vorbis.luau` | | audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` | +| archive | zip | .zip .wsz | yes | yes | methods: "store", "deflate", zip64: true | `tests/archive/zip.luau` | Codecs (layer 1, shared by formats; not loadable on their own): diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index b4980ac..e218c97 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -10,6 +10,10 @@ | `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/vorbis/` (Setup, Codebook, Packet, Tables) | a Luau port of stb_vorbis 1.22 by Sean Barrett (https://github.com/nothings/stb): setup parsing, codebooks, floor 1, residues, coupling (the IMDCT is codecs/Mdct; the timing follows libvorbis / the spec) | public domain or MIT (dual): [stb_vorbis-LICENSE.txt](stb_vorbis-LICENSE.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) | +| `src/Formats/containers/Zip/` (the reader), `src/Formats/archive/zip/` | zip-luau 121d4b0 (same author), written from PKWARE's APPNOTE.TXT 6.3 | no licence chosen yet; no third-party code | | `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 400adba..941a69b 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", @@ -50,6 +62,18 @@ local list: { Entry } = { return require("@formats/audio/au") end, }, + { + name = "flac", + category = "audio", + path = "audio/flac", + extensions = { "flac", "oga" }, + mime = { "audio/flac", "audio/x-flac" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" }, + caps = { decode = true, encode = false, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true }, + load = function() + return require("@formats/audio/flac") + end, + }, { name = "mp3", category = "audio", @@ -110,6 +134,18 @@ local list: { Entry } = { return require("@formats/audio/wav") end, }, + { + name = "zip", + category = "archive", + path = "archive/zip", + extensions = { "zip", "wsz" }, + mime = { "application/zip", "application/x-zip-compressed" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Zip" }, + caps = { decode = true, encode = true, methods = { "store", "deflate" }, zip64 = true }, + load = function() + return require("@formats/archive/zip") + end, + }, } return list diff --git a/src/Formats/archive/zip/init.luau b/src/Formats/archive/zip/init.luau new file mode 100644 index 0000000..081a7e0 --- /dev/null +++ b/src/Formats/archive/zip/init.luau @@ -0,0 +1,238 @@ +--!strict +-- archive/zip: ZIP archives as the standard Archive (Types.Archive: list / read / add / write) on containers/Zip. +-- Absorbed from zip-luau 121d4b0 (same author, no third-party code; the reader, now containers/Zip) plus a new +-- writer. Supports: reading stored and deflated entries (CRC-checked), ZIP64, data descriptors, archive comments, +-- prefixed archives (self-extractors), UTF-8 names, case-insensitive / basename lookup; writing stored and deflated +-- entries (codecs/Deflate), unchanged entries copied without recompressing, ZIP64 when needed. +-- Not supported: encryption (traditional PKWARE or AES), compression methods other than store / deflate (bzip2, +-- LZMA, zstd entries are listed but not readable), multi-disk archives. +-- +-- local a = Zip.decode(Bytes.reader(buf)) -- or F.archive.load(buf) +-- for _, e in a:list() do print(e.name, e.size, e.method) end +-- local data = a:read("dir/file.txt") +-- a:add("new.txt", "hello", { level = 9 }) -- or { method = "store", mtime = os.time() } +-- local out = a:write({ comment = "made here" }) -- or Zip.encode(a) / F.save(a, nil, { format = "zip" }) +-- local b = Zip.create() -- an empty archive + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Container = require("@formats/containers/Zip") + +-- ------------------------------------------------------------------------------------------------ contract +local Zip = { + name = "zip", + category = "archive", + extensions = { "zip", "wsz" }, + mime = { "application/zip", "application/x-zip-compressed" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Zip" }, + caps = { decode = true, encode = true, methods = { "store", "deflate" }, zip64 = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + verify: boolean?, -- check every entry's CRC-32 on read (default true) +} +export type AddOptions = Container.AddOptions +export type WriteOptions = Container.FinishOptions + +-- ------------------------------------------------------------------------------------------------ constants +local METHODS = { [0] = "store", [8] = "deflate", [9] = "deflate64", [12] = "bzip2", [14] = "lzma", [93] = "zstd", [95] = "xz", [99] = "aes" } + +local Archive = {} +Archive.__index = Archive + +local function new(zip: any, verify: boolean): any + local a = setmetatable({ + kind = "archive", + format = "zip", + meta = { source = { format = "zip" }, comment = if zip then zip.comment else nil, zip64 = if zip then zip.zip64 else nil }, + _zip = zip, + _verify = verify, + _order = {} :: { string }, + _items = {} :: { [string]: any }, + }, Archive) + if zip then + for _, e in zip:list() do + if a._items[e.name] == nil then + table.insert(a._order, e.name) + end + a._items[e.name] = { raw = e } + end + end + return a +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Zip.sniff(r: Bytes.Reader): number + local s = r:peek(4) + -- ZIP-based formats (docx, jar, 3mf, ...) score higher in their own sniff + if s == "PK\3\4" or s == "PK\5\6" then + return 0.6 + end + if string.sub(s, 1, 2) == "MZ" then + return 0 -- a self-extractor opens with Zip.decode / opts.format = "zip" + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Archive | nil, Err +function Zip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?) + local zip, err = Container.open(r) + if not zip then + return nil, err + end + return new(zip, not (opts and opts.verify == false)), nil +end + +-- create() -> an empty Archive +function Zip.create(): Types.Archive + return new(nil, true) +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(archive, opts?) -> buffer | nil, Err. archive: an Archive (any format's: its entries are read and written +-- here), or a plain table { [name] = buffer | string }. +function Zip.encode(value: any, opts: WriteOptions?): (buffer?, Err.Err?) + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "encode: needs an Archive or a { name = data } table") + end + if getmetatable(value) == Archive then + return value:write(opts) + end + local a = new(nil, true) + if value.kind == "archive" and type(value.list) == "function" and type(value.read) == "function" then + for _, e in value:list() do + if e.dir then + a:add(e.name, nil, { mtime = e.mtime }) + else + local data, err = value:read(e.name) + if not data then + return nil, err + end + a:add(e.name, data, { mtime = e.mtime }) + end + end + else + local names = {} + for k, v in value do + if type(k) ~= "string" or (type(v) ~= "buffer" and type(v) ~= "string") then + return nil, Err.new(Err.ARG, "encode: a { name = data } table needs string names and buffer / string data") + end + table.insert(names, k) + end + table.sort(names) + for _, k in names do + a:add(k, value[k]) + end + end + return a:write(opts) +end + +-- ------------------------------------------------------------------------------------------------ extras +-- the Archive methods (Types.Archive) + +-- list() -> { ArchiveEntry } in archive order (+ crc32, comment) +function Archive.list(self: any): { Types.ArchiveEntry } + local out = {} + for _, name in self._order do + local it = self._items[name] + if it.raw then + local e = it.raw + table.insert(out, { + name = e.name, + size = e.size, + compressedSize = e.compressedSize, + method = METHODS[e.method] or ("method " .. e.method), + mtime = e.mtime, + dir = e.isDir, + crc32 = e.crc32, + comment = e.comment, + }) + else + table.insert(out, { + name = name, + size = buffer.len(it.data), + compressedSize = nil, + method = it.opts.method or "deflate", + mtime = it.opts.mtime, + dir = string.sub(name, -1) == "/", + }) + end + end + return out +end + +-- read(name) -> buffer | nil, Err: an exact name, else the reader's case-insensitive / basename lookup +function Archive.read(self: any, name: string): (buffer?, Err.Err?) + if type(name) ~= "string" then + return nil, Err.new(Err.ARG, "read: name must be a string") + end + local it = self._items[name] + if it and not it.raw then + local copy = buffer.create(buffer.len(it.data)) + buffer.copy(copy, 0, it.data) + return copy, nil + end + if it then + return self._zip:read(it.raw, self._verify) + end + if self._zip then + local e = self._zip:find(name) + if e and self._items[e.name] and self._items[e.name].raw == e then + return self._zip:read(e, self._verify) + end + end + return nil, Err.new(Err.ARG, "no entry " .. name) +end + +-- add(name, data, opts?): add or replace an entry (data: buffer or string; nil for a directory "name/") +function Archive.add(self: any, name: string, data: any, opts: AddOptions?) + local b: buffer = if type(data) == "string" then buffer.fromstring(data) elseif type(data) == "buffer" then data else buffer.create(0) + if self._items[name] == nil then + table.insert(self._order, name) + end + self._items[name] = { data = b, opts = opts or {} } +end + +-- remove(name) -> true when there was such an entry +function Archive.remove(self: any, name: string): boolean + if self._items[name] == nil then + return false + end + self._items[name] = nil + local i = table.find(self._order, name) + if i then + table.remove(self._order, i) + end + return true +end + +-- write(opts?) -> buffer | nil, Err: the archive with every change; unchanged entries are copied as they are +function Archive.write(self: any, opts: WriteOptions?): (buffer?, Err.Err?) + local w = Container.writer() + for _, name in self._order do + local it = self._items[name] + local ok, err + if it.raw then + ok, err = w:addRaw(it.raw, self._zip) + else + ok, err = w:add(name, it.data, it.opts) + end + if not ok then + return nil, err + end + end + local o: WriteOptions = opts or {} + if o.comment == nil and self.meta.comment and self.meta.comment ~= "" then + o = table.clone(o) + o.comment = self.meta.comment + end + return w:finish(o) +end + +Zip.Container = Container + +return Zip diff --git a/src/Formats/audio/flac/Frame.luau b/src/Formats/audio/flac/Frame.luau new file mode 100644 index 0000000..d31ed05 --- /dev/null +++ b/src/Formats/audio/flac/Frame.luau @@ -0,0 +1,605 @@ +--!strict +--!native +--!optimize 2 +-- audio/flac/Frame: FLAC frames: header parsing (CRC-8), the sync search, subframes (constant, verbatim, fixed, LPC, wasted bits), +-- residuals (Rice / Rice2 partitions, escapes), stereo decorrelation and the CRC-16 check. +-- +-- The input buffer must have at least PAD zero bytes after the data end (`len`): the bit reader reads 32-bit +-- words without bounds checks and instead compares its position with the data end once per sample. Nothing here +-- throws: bad data gives nil, err. +-- Absorbed from flac-luau 7083d0d (same author, no third-party code). +local readu8, readu32 = buffer.readu8, buffer.readu32 +local band, bxor, lshift, rshift, countlz, byteswap = bit32.band, bit32.bxor, bit32.lshift, bit32.rshift, + bit32.countlz, bit32.byteswap +local floor = math.floor + +local Frame = {} +Frame.PAD = 32 + +-- CRC-8 (poly 0x07) and CRC-16 (poly 0x8005), MSB first, init 0 +local CRC8 = table.create(256, 0) +local CRC16 = table.create(256, 0) +for i = 0, 255 do + local c = i + for _ = 1, 8 do + c = if band(c, 0x80) ~= 0 then band(bxor(lshift(c, 1), 0x07), 0xFF) else band(lshift(c, 1), 0xFF) + end + CRC8[i + 1] = c + local d = lshift(i, 8) + for _ = 1, 8 do + d = if band(d, 0x8000) ~= 0 then band(bxor(lshift(d, 1), 0x8005), 0xFFFF) else band(lshift(d, 1), 0xFFFF) + end + CRC16[i + 1] = d +end + +local function crc16(b: buffer, from: number, to: number): number + local c = 0 + for i = from, to - 1 do + c = bxor(band(lshift(c, 8), 0xFFFF), CRC16[bxor(rshift(c, 8), readu8(b, i)) + 1]) + end + return c +end +Frame.crc16 = crc16 + +local POW2 = table.create(64, 0) +for i = 0, 63 do + POW2[i + 1] = 2 ^ i +end + +local BLOCK = { [1] = 192, [2] = 576, [3] = 1152, [4] = 2304, [5] = 4608, [8] = 256, [9] = 512, [10] = 1024, + [11] = 2048, [12] = 4096, [13] = 8192, [14] = 16384, [15] = 32768 } +local RATE = { [1] = 88200, [2] = 176400, [3] = 192000, [4] = 8000, [5] = 16000, [6] = 22050, [7] = 24000, + [8] = 32000, [9] = 44100, [10] = 48000, [11] = 96000 } +local BITS = { [1] = 8, [2] = 12, [4] = 16, [5] = 20, [6] = 24, [7] = 32 } + +export type Header = { + offset: number, -- byte offset of the sync code + size: number, -- header bytes, CRC-8 included + blockSize: number, + sampleRate: number, + channels: number, + assignment: number, -- 0..7 independent, 8 left/side, 9 side/right, 10 mid/side + bps: number, + variable: boolean, -- variable block size: number is a sample number, else a frame number + number: number, +} + +-- Parse the frame header at pos (data ends at len; the buffer is padded). si gives the STREAMINFO defaults +-- (sampleRate, bitsPerSample) for the "from STREAMINFO" codes. Returns nil when it is not a valid header. +function Frame.header(b: buffer, pos: number, len: number, si: any): Header? + if pos < 0 or pos + 6 > len then + return nil + end + if readu8(b, pos) ~= 0xFF then + return nil + end + local b1 = readu8(b, pos + 1) + if band(b1, 0xFE) ~= 0xF8 then + return nil + end + local b2 = readu8(b, pos + 2) + local b3 = readu8(b, pos + 3) + local bsCode, rCode = rshift(b2, 4), band(b2, 15) + local chCode, sCode = rshift(b3, 4), band(rshift(b3, 1), 7) + if bsCode == 0 or rCode == 15 or chCode > 10 or sCode == 3 or band(b3, 1) ~= 0 then + return nil + end + -- UTF-8-like coded number + local p = pos + 4 + local x = readu8(b, p) + p += 1 + local num, more + if x < 0x80 then + num, more = x, 0 + elseif x >= 0xC0 and x < 0xE0 then + num, more = band(x, 0x1F), 1 + elseif x >= 0xE0 and x < 0xF0 then + num, more = band(x, 0x0F), 2 + elseif x >= 0xF0 and x < 0xF8 then + num, more = band(x, 0x07), 3 + elseif x >= 0xF8 and x < 0xFC then + num, more = band(x, 0x03), 4 + elseif x >= 0xFC and x < 0xFE then + num, more = band(x, 0x01), 5 + elseif x == 0xFE then + num, more = 0, 6 + else + return nil + end + for _ = 1, more do + local c = readu8(b, p) + p += 1 + if band(c, 0xC0) ~= 0x80 then + return nil + end + num = num * 64 + band(c, 0x3F) + end + local variable = band(b1, 1) == 1 + if not variable and more > 5 then + return nil + end + local bs = BLOCK[bsCode] + if bsCode == 6 then + bs = readu8(b, p) + 1 + p += 1 + elseif bsCode == 7 then + bs = readu8(b, p) * 256 + readu8(b, p + 1) + 1 + p += 2 + end + local rate = RATE[rCode] + if rCode == 0 then + rate = si and si.sampleRate or 0 + elseif rCode == 12 then + rate = readu8(b, p) * 1000 + p += 1 + elseif rCode == 13 then + rate = readu8(b, p) * 256 + readu8(b, p + 1) + p += 2 + elseif rCode == 14 then + rate = (readu8(b, p) * 256 + readu8(b, p + 1)) * 10 + p += 2 + end + local bps = BITS[sCode] + if sCode == 0 then + bps = si and si.bitsPerSample or 0 + end + if not bs or not bps or bps < 4 or bps > 32 or p + 1 > len then + return nil + end + -- CRC-8 over the header + local c = 0 + for i = pos, p - 1 do + c = CRC8[bxor(c, readu8(b, i)) + 1] + end + if c ~= readu8(b, p) then + return nil + end + return { + offset = pos, + size = p + 1 - pos, + blockSize = bs, + sampleRate = rate or 0, + channels = if chCode < 8 then chCode + 1 else 2, + assignment = chCode, + bps = bps, + variable = variable, + number = num, + } +end + +-- The first valid header at an offset in [pos, limit) +function Frame.find(b: buffer, pos: number, limit: number, len: number, si: any): Header? + local lim = math.min(limit, len - 6) + if pos < 0 then + pos = 0 + end + while pos < lim do + if readu8(b, pos) == 0xFF then + local b1 = readu8(b, pos + 1) + if b1 == 0xF8 or b1 == 0xF9 then + local h = Frame.header(b, pos, len, si) + if h then + return h + end + end + end + pos += 1 + end + return nil +end + +-- Bit reading for the header parts of subframes: n <= 32 bits at bit position p (unsigned) +local function bits(b: buffer, p: number, n: number): number + if n == 0 then + return 0 + elseif n <= 24 then + return rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), 32 - n) + end + local hi = rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), 32 - (n - 16)) + local q = p + n - 16 + return hi * 65536 + rshift(lshift(byteswap(readu32(b, rshift(q, 3))), band(q, 7)), 16) +end + +local function sbits(b: buffer, p: number, n: number): number + local v = bits(b, p, n) + if n > 0 and v >= POW2[n] then + v -= POW2[n + 1] + end + return v +end + +-- Residual coding: fills s[order + 1 .. n] with residuals. Returns the new bit position, or -1. +local function residual(b: buffer, p: number, lim: number, s: { number }, n: number, order: number): number + local method = bits(b, p, 2) + if method > 1 then + return -1 + end + local porder = bits(b, p + 2, 4) + p += 6 + local pbits = if method == 0 then 4 else 5 + local escape = if method == 0 then 15 else 31 + local parts = POW2[porder + 1] + local psize = rshift(n, porder) + if psize * parts ~= n or psize < order then + return -1 + end + local i = order + 1 + for part = 0, parts - 1 do + if p > lim then + return -1 + end + local k = bits(b, p, pbits) + p += pbits + local stop = (part + 1) * psize + if k == escape then + local nb = bits(b, p, 5) + p += 5 + if nb == 0 then + for j = i, stop do + s[j] = 0 + end + else + local half, full = POW2[nb], POW2[nb + 1] + for j = i, stop do + if p > lim then + return -1 + end + local v = bits(b, p, nb) + p += nb + if v >= half then + v -= full + end + s[j] = v + end + end + elseif k <= 24 then + -- the hot loop: unary quotient + k-bit remainder, zigzag + local pk = POW2[k + 1] + local rk = 32 - k + for j = i, stop do + if p > lim then + return -1 + end + local sh = band(p, 7) + local w = lshift(byteswap(readu32(b, rshift(p, 3))), sh) + local q, r + if w ~= 0 then + q = countlz(w) + local used = q + 1 + k + if used <= 32 - sh then + r = if k == 0 then 0 else rshift(lshift(w, q + 1), rk) + p += used + else + p += q + 1 + r = if k == 0 then 0 else rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), rk) + p += k + end + else + -- a long run of zeros + q = 32 - sh + p += q + while true do + if p > lim then + return -1 + end + local w2 = lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)) + if w2 ~= 0 then + local z = countlz(w2) + q += z + p += z + 1 + break + end + local adv = 32 - band(p, 7) + q += adv + p += adv + end + r = if k == 0 then 0 else rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), rk) + p += k + end + local u = q * pk + r + local h = floor(u * 0.5) + s[j] = if h + h == u then h else -h - 1 + end + else + -- k = 25..30 (Rice2): the remainder takes two reads + local pk = POW2[k + 1] + for j = i, stop do + if p > lim then + return -1 + end + local q = 0 + while true do + if p > lim then + return -1 + end + local w = lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)) + if w ~= 0 then + local z = countlz(w) + q += z + p += z + 1 + break + end + local adv = 32 - band(p, 7) + q += adv + p += adv + end + local r = bits(b, p, k) + p += k + local u = q * pk + r + local h = floor(u * 0.5) + s[j] = if h + h == u then h else -h - 1 + end + end + i = stop + 1 + end + return p +end + +local function fixed(s: { number }, n: number, order: number) + if order == 1 then + local a = s[1] + for i = 2, n do + a += s[i] + s[i] = a + end + elseif order == 2 then + local a, c = s[2], s[1] + for i = 3, n do + local v = s[i] + 2 * a - c + s[i] = v + c = a + a = v + end + elseif order == 3 then + local a, c, d = s[3], s[2], s[1] + for i = 4, n do + local v = s[i] + 3 * a - 3 * c + d + s[i] = v + d = c + c = a + a = v + end + elseif order == 4 then + local a, c, d, e = s[4], s[3], s[2], s[1] + for i = 5, n do + local v = s[i] + 4 * a - 6 * c + 4 * d - e + s[i] = v + e = d + d = c + c = a + a = v + end + end +end + +-- LPC restoration: s[i] += floor(sum(coef[j] * s[i - j]) / 2^shift); unrolled for orders up to 12 +local function lpc(s: { number }, n: number, cf: { number }, order: number, shift: number) + local div = POW2[shift + 1] + local inv = 1 / div + if order <= 4 then + local c1, c2, c3, c4 = cf[1], cf[2] or 0, cf[3] or 0, cf[4] or 0 + local s1, s2, s3, s4 = s[order], s[order - 1] or 0, s[order - 2] or 0, s[order - 3] or 0 + for i = order + 1, n do + local v = s[i] + floor((c1 * s1 + c2 * s2 + c3 * s3 + c4 * s4) * inv) + s[i] = v + s4 = s3 + s3 = s2 + s2 = s1 + s1 = v + end + elseif order <= 8 then + local c1, c2, c3, c4, c5, c6, c7, c8 = cf[1], cf[2], cf[3], cf[4], cf[5], cf[6] or 0, cf[7] or 0, cf[8] or 0 + local s1, s2, s3, s4, s5 = s[order], s[order - 1], s[order - 2], s[order - 3], s[order - 4] + local s6, s7, s8 = s[order - 5] or 0, s[order - 6] or 0, s[order - 7] or 0 + for i = order + 1, n do + local v = s[i] + + floor((c1 * s1 + c2 * s2 + c3 * s3 + c4 * s4 + c5 * s5 + c6 * s6 + c7 * s7 + c8 * s8) * inv) + s[i] = v + s8 = s7 + s7 = s6 + s6 = s5 + s5 = s4 + s4 = s3 + s3 = s2 + s2 = s1 + s1 = v + end + elseif order <= 12 then + local c1, c2, c3, c4, c5, c6, c7, c8 = cf[1], cf[2], cf[3], cf[4], cf[5], cf[6], cf[7], cf[8] + local c9, c10, c11, c12 = cf[9], cf[10] or 0, cf[11] or 0, cf[12] or 0 + local s1, s2, s3, s4, s5, s6 = s[order], s[order - 1], s[order - 2], s[order - 3], s[order - 4], s[order - 5] + local s7, s8, s9 = s[order - 6], s[order - 7], s[order - 8] + local s10, s11, s12 = s[order - 9] or 0, s[order - 10] or 0, s[order - 11] or 0 + for i = order + 1, n do + local v = s[i] + + floor( + ( + c1 * s1 + c2 * s2 + c3 * s3 + c4 * s4 + c5 * s5 + c6 * s6 + + c7 * s7 + c8 * s8 + c9 * s9 + c10 * s10 + c11 * s11 + c12 * s12 + ) * inv + ) + s[i] = v + s12 = s11 + s11 = s10 + s10 = s9 + s9 = s8 + s8 = s7 + s7 = s6 + s6 = s5 + s5 = s4 + s4 = s3 + s3 = s2 + s2 = s1 + s1 = v + end + else + for i = order + 1, n do + local sum = 0 + for j = 1, order do + sum += cf[j] * s[i - j] + end + s[i] += floor(sum * inv) + end + end +end + +-- One subframe into s[1..n]. Returns the new bit position, or -1. +local function subframe(b: buffer, p: number, lim: number, s: { number }, n: number, bps: number, cf: { number }): number + if p > lim then + return -1 + end + local hdr = bits(b, p, 8) + p += 8 + if hdr >= 128 then + return -1 + end + local typ = rshift(hdr, 1) + local wasted = 0 + if band(hdr, 1) == 1 then + -- unary count of wasted bits (minus one) + while true do + if p > lim or wasted > 32 then + return -1 + end + local bit = bits(b, p, 1) + p += 1 + wasted += 1 + if bit == 1 then + break + end + end + bps -= wasted + if bps < 1 then + return -1 + end + end + if typ == 0 then + local v = sbits(b, p, bps) + p += bps + for i = 1, n do + s[i] = v + end + elseif typ == 1 then + for i = 1, n do + if p > lim then + return -1 + end + s[i] = sbits(b, p, bps) + p += bps + end + elseif typ >= 8 and typ <= 12 then + local order = typ - 8 + if order > n then + return -1 + end + for i = 1, order do + if p > lim then + return -1 + end + s[i] = sbits(b, p, bps) + p += bps + end + p = residual(b, p, lim, s, n, order) + if p < 0 then + return -1 + end + fixed(s, n, order) + elseif typ >= 32 then + local order = typ - 31 + if order > n then + return -1 + end + for i = 1, order do + if p > lim then + return -1 + end + s[i] = sbits(b, p, bps) + p += bps + end + local prec = bits(b, p, 4) + 1 + p += 4 + if prec == 16 then + return -1 + end + local shift = sbits(b, p, 5) + p += 5 + if shift < 0 then + return -1 + end + for j = 1, order do + if p > lim then + return -1 + end + cf[j] = sbits(b, p, prec) + p += prec + end + for j = order + 1, 12 do + cf[j] = 0 -- the unrolled filters read up to 12 coefficients + end + p = residual(b, p, lim, s, n, order) + if p < 0 then + return -1 + end + lpc(s, n, cf, order, shift) + else + return -1 + end + if wasted > 0 then + local m = POW2[wasted + 1] + for i = 1, n do + s[i] *= m + end + end + return p +end + +-- Decode the frame whose header h was parsed (data ends at len). chans[c] are tables of at least h.blockSize +-- numbers; they receive the samples. Returns the byte offset after the frame, or nil, err. +function Frame.decode(b: buffer, len: number, h: Header, chans: { { number } }, cf: { number }, checkCrc: boolean): (number?, string?) + local n = h.blockSize + local lim = len * 8 + local p = (h.offset + h.size) * 8 + local asg = h.assignment + for c = 1, h.channels do + local bps = h.bps + if (asg == 8 and c == 2) or (asg == 9 and c == 1) or (asg == 10 and c == 2) then + bps += 1 -- the side channel + end + p = subframe(b, p, lim, chans[c], n, bps, cf) + if p < 0 then + return nil, "bad subframe" + end + end + local e = rshift(p + 7, 3) -- byte align + if e + 2 > len then + return nil, "truncated frame" + end + if checkCrc then + local want = readu8(b, e) * 256 + readu8(b, e + 1) + if crc16(b, h.offset, e) ~= want then + return nil, "crc16 mismatch" + end + end + if asg >= 8 then + local l, r = chans[1], chans[2] + if asg == 8 then + for i = 1, n do + r[i] = l[i] - r[i] + end + elseif asg == 9 then + for i = 1, n do + l[i] += r[i] + end + else + for i = 1, n do + local side = r[i] + local m = l[i] * 2 + (side % 2) + l[i] = (m + side) * 0.5 + r[i] = (m - side) * 0.5 + end + end + end + return e + 2, nil +end + +return Frame diff --git a/src/Formats/audio/flac/Meta.luau b/src/Formats/audio/flac/Meta.luau new file mode 100644 index 0000000..0c81354 --- /dev/null +++ b/src/Formats/audio/flac/Meta.luau @@ -0,0 +1,220 @@ +--!strict +--!native +--!optimize 2 +-- audio/flac/Meta: FLAC metadata blocks: STREAMINFO, SEEKTABLE, VORBIS_COMMENT and PICTURE (its fields are listed, the image is +-- left in place); every other block is skipped. Nothing throws: bad data gives nil, err. +-- Absorbed from flac-luau 7083d0d (same author, no third-party code). +local readu8, readu32 = buffer.readu8, buffer.readu32 + +local Meta = {} + +local function be16(b: buffer, p: number): number + return readu8(b, p) * 256 + readu8(b, p + 1) +end +local function be24(b: buffer, p: number): number + return readu8(b, p) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2) +end +local function be32(b: buffer, p: number): number + return be16(b, p) * 65536 + be16(b, p + 2) +end + +export type StreamInfo = { + minBlockSize: number, + maxBlockSize: number, + minFrameSize: number, -- 0 = unknown + maxFrameSize: number, + sampleRate: number, + channels: number, + bitsPerSample: number, + totalSamples: number, -- 0 = unknown + md5: string, -- 32 hex digits (all zero = not set) +} + +export type SeekPoint = { sample: number, offset: number, samples: number } + +export type Picture = { + type: number, + mime: string, + description: string, + width: number, + height: number, + depth: number, + colors: number, + offset: number, -- the image bytes are buf[offset .. offset + size - 1] + size: number, +} + +export type Info = { + streamInfo: StreamInfo, + seekTable: { SeekPoint }, + vendor: string, + tags: { [string]: string }, -- upper-case keys; repeated keys are joined with "; " + comments: { { key: string, value: string } }, -- every comment in order + pictures: { Picture }, + firstFrame: number, -- byte offset just after the last metadata block +} + +local function streamInfo(b: buffer, p: number): StreamInfo + local b12, b13 = readu8(b, p + 12), readu8(b, p + 13) + local hex = table.create(16) + for i = 0, 15 do + hex[i + 1] = string.format("%02x", readu8(b, p + 18 + i)) + end + return { + minBlockSize = be16(b, p), + maxBlockSize = be16(b, p + 2), + minFrameSize = be24(b, p + 4), + maxFrameSize = be24(b, p + 7), + sampleRate = readu8(b, p + 10) * 4096 + readu8(b, p + 11) * 16 + bit32.rshift(b12, 4), + channels = bit32.band(bit32.rshift(b12, 1), 7) + 1, + bitsPerSample = bit32.band(b12, 1) * 16 + bit32.rshift(b13, 4) + 1, + totalSamples = bit32.band(b13, 15) * 4294967296 + be32(b, p + 14), + md5 = table.concat(hex), + } +end + +local function vorbisComment(b: buffer, p: number, e: number, info: Info): boolean + if p + 4 > e then + return false + end + local vl = readu32(b, p) + p += 4 + if p + vl > e then + return false + end + info.vendor = buffer.readstring(b, p, vl) + p += vl + if p + 4 > e then + return false + end + local n = readu32(b, p) + p += 4 + for _ = 1, n do + if p + 4 > e then + return false + end + local l = readu32(b, p) + p += 4 + if p + l > e then + return false + end + local s = buffer.readstring(b, p, l) + p += l + local eq = string.find(s, "=", 1, true) + if eq then + local key, value = string.upper(string.sub(s, 1, eq - 1)), string.sub(s, eq + 1) + table.insert(info.comments, { key = key, value = value }) + local old = info.tags[key] + info.tags[key] = if old then old .. "; " .. value else value + end + end + return true +end + +local function picture(b: buffer, p: number, e: number): Picture? + if p + 8 > e then + return nil + end + local typ = be32(b, p) + local ml = be32(b, p + 4) + p += 8 + if p + ml + 4 > e then + return nil + end + local mime = buffer.readstring(b, p, ml) + p += ml + local dl = be32(b, p) + p += 4 + if p + dl + 20 > e then + return nil + end + local desc = buffer.readstring(b, p, dl) + p += dl + local pic = { + type = typ, + mime = mime, + description = desc, + width = be32(b, p), + height = be32(b, p + 4), + depth = be32(b, p + 8), + colors = be32(b, p + 12), + offset = p + 20, + size = be32(b, p + 16), + } + if pic.offset + pic.size > e then + return nil + end + return pic +end + +-- Parse the metadata blocks that follow "fLaC" at pos (data ends at len) +function Meta.parse(b: buffer, pos: number, len: number): (Info?, string?) + if pos + 4 > len or buffer.readstring(b, pos, 4) ~= "fLaC" then + return nil, "Flac: no fLaC marker" + end + local info: Info = { + streamInfo = nil :: any, + seekTable = {}, + vendor = "", + tags = {}, + comments = {}, + pictures = {}, + firstFrame = 0, + } + local p = pos + 4 + while true do + if p + 4 > len then + return nil, "Flac: truncated metadata" + end + local h = readu8(b, p) + local last = h >= 128 + local typ = bit32.band(h, 127) + local size = be24(b, p + 1) + p += 4 + local e = p + size + if e > len then + return nil, "Flac: truncated metadata block" + end + if typ == 0 then + if size < 34 then + return nil, "Flac: bad STREAMINFO" + end + info.streamInfo = streamInfo(b, p) + elseif typ == 3 then + for q = p, e - 18, 18 do + local hi = be32(b, q) + if hi ~= 0xFFFFFFFF then -- placeholder points are all ones + table.insert(info.seekTable, { + sample = hi * 4294967296 + be32(b, q + 4), + offset = be32(b, q + 8) * 4294967296 + be32(b, q + 12), + samples = be16(b, q + 16), + }) + end + end + elseif typ == 4 then + vorbisComment(b, p, e, info) -- a broken comment block leaves what was read + elseif typ == 6 then + local pic = picture(b, p, e) + if pic then + table.insert(info.pictures, pic) + end + elseif typ == 127 then + return nil, "Flac: invalid metadata block type" + end + p = e + if last then + break + end + end + if not info.streamInfo then + return nil, "Flac: no STREAMINFO" + end + local si = info.streamInfo + if si.sampleRate == 0 then + return nil, "Flac: bad STREAMINFO values" + end + info.firstFrame = p + return info, nil +end + +return Meta diff --git a/src/Formats/audio/flac/Stream.luau b/src/Formats/audio/flac/Stream.luau new file mode 100644 index 0000000..b6a5dc5 --- /dev/null +++ b/src/Formats/audio/flac/Stream.luau @@ -0,0 +1,383 @@ +--!strict +--!native +--!optimize 2 +-- audio/flac/Stream: the streaming FLAC decoder (native FLAC with an optional ID3v2 tag in front, and Ogg FLAC through +-- containers/Ogg): stream setup, read / readInt with resync past corrupt frames, sample-accurate seeking (seek table, +-- byte bisection by sync search, then a frame walk), length from the last frame when STREAMINFO has none. Absorbed +-- from flac-luau 7083d0d (same author, no third-party code; the Ogg demuxer is now a direct require instead of an +-- injected module). Nothing throws: open returns nil, message, code. +local Bytes = require("@formats/core/Bytes") +local Ogg = require("@formats/containers/Ogg") +local Frame = require("@formats/audio/flac/Frame") +local Meta = require("@formats/audio/flac/Meta") + +local Stream = {} + +local writef32, writei32 = buffer.writef32, buffer.writei32 +type Header = any -- Frame.Header +local PAD = Frame.PAD + +export type Decoder = { + sampleRate: number, + channels: number, + bitsPerSample: number, + frames: number, -- total sample frames (per channel); 0 if unknown and not found + duration: number, -- seconds + bitrate: number, -- average bits per second of the audio data + tags: { [string]: string }, + comments: { { key: string, value: string } }, + vendor: string, + md5: string, + seekTable: { any }, + pictures: { any }, + container: string, -- "flac" | "ogg" + read: (Decoder, number, buffer?) -> (buffer, number), + readInt: (Decoder, number, buffer?) -> (buffer, number), + seek: (Decoder, number) -> boolean, + seekSample: (Decoder, number) -> boolean, + position: (Decoder) -> (number, number), +} + +local Dec = {} +Dec.__index = Dec + +-- the sample number of a frame +local function sampleOf(self: any, h: Header): number + return if h.variable then h.number else h.number * self._nominal +end + +-- a header that also matches the stream (guards the sync search against false syncs) +local function plausible(self: any, h: Header): boolean + if h.channels ~= self.channels or h.bps ~= self.bitsPerSample or h.blockSize > 65536 then + return false + end + if self.frames > 0 and sampleOf(self, h) >= self.frames then + return false + end + return true +end + +local function findFrame(self: any, pos: number, limit: number): Header? + local b, len, si = self._b, self._len, self._si + while true do + local h = Frame.find(b, pos, limit, len, si) + if not h then + return nil + end + if plausible(self, h) then + return h + end + pos = h.offset + 1 + end +end + +local function ensure(self: any, n: number) + if n > self._cap then + for c = 1, self.channels do + self._chans[c] = table.create(n, 0) + end + self._cap = n + end +end + +-- Decode the frame at or after pos (resyncing past corrupt data). Sets the current frame; false at the end. +local function decodeAt(self: any, pos: number): boolean + local b, len = self._b, self._len + while true do + local h = Frame.header(b, pos, len, self._si) + if not h or not plausible(self, h) then + h = findFrame(self, pos, len) + if not h then + self._pos = len + return false + end + end + ensure(self, h.blockSize) + local nextPos = Frame.decode(b, len, h, self._chans, self._cf, self._crc) + if nextPos then + local s = sampleOf(self, h) + local n = h.blockSize + if self.frames > 0 and s + n > self.frames then + n = math.max(0, self.frames - s) + end + self._pos = nextPos + self._fs = s + self._fn = n + self._cur = 0 + return true + end + pos = h.offset + 1 + end +end + +local function pull(self: any, maxFrames: number, asInt: boolean, dst: buffer?): (buffer, number) + local ch = self.channels + local want = math.floor(tonumber(maxFrames) or 0) + if not (want >= 0) then + want = 0 -- negative or NaN + end + want = math.min(want, 2 ^ 26 // ch) -- keeps the output buffer under 256 MB + local reuse = dst ~= nil and type(dst) == "buffer" and buffer.len(dst) >= want * ch * 4 + local out = if reuse then dst :: buffer else buffer.create(want * ch * 4) + local got = 0 + local scale = 1 / 2 ^ (self.bitsPerSample - 1) + local stride = ch * 4 + while got < want do + if self._cur >= self._fn then + if self._pos >= self._len or not decodeAt(self, self._pos) then + self._fs += self._cur + self._cur, self._fn = 0, 0 + break + end + end + local take = math.min(want - got, self._fn - self._cur) + local from = self._cur + 1 + local to = self._cur + take + for c = 1, ch do + local s = self._chans[c] + local o = (got * ch + c - 1) * 4 + if asInt then + for i = from, to do + writei32(out, o, s[i]) + o += stride + end + else + for i = from, to do + writef32(out, o, s[i] * scale) + o += stride + end + end + end + self._cur += take + got += take + end + if got < want and not reuse then + local short = buffer.create(got * ch * 4) + buffer.copy(short, 0, out, 0, got * ch * 4) + out = short + end + return out, got +end + +-- Up to maxFrames sample frames as interleaved f32 (sample / 2^(bps-1)); 0 frames = end of stream. out (if given) is +-- reused when big enough. +function Dec.read(self: any, maxFrames: number, out: buffer?): (buffer, number) + return pull(self, maxFrames, false, out) +end + +-- The same as interleaved i32 integer samples (bit-exact, right-aligned) +function Dec.readInt(self: any, maxFrames: number, out: buffer?): (buffer, number) + return pull(self, maxFrames, true, out) +end + +-- seconds, sample frame of the next frame read() returns +function Dec.position(self: any): (number, number) + local s = self._fs + self._cur + return s / self.sampleRate, s +end + +-- Seek so the next read starts exactly at sample frame t. Uses the seek table to bracket t, bisects byte offsets +-- by sync search, then walks frame headers forward. Returns false if the stream has no frame there. +function Dec.seekSample(self: any, t: number): boolean + t = math.floor(tonumber(t) or 0) + if not (t >= 0) then + t = 0 -- negative or NaN + end + if self.frames > 0 and t >= self.frames then + self._pos, self._fs, self._fn, self._cur = self._len, self.frames, 0, 0 + return true + end + if self._fn > 0 and t >= self._fs and t < self._fs + self._fn then + self._cur = t - self._fs + return true + end + local first, len = self._first, self._len + local lo, hi = first, len + for _, sp in self.seekTable do + local o = first + sp.offset + if o < len then + if sp.sample <= t then + lo = math.max(lo, o) + else + hi = math.min(hi, o) + break + end + end + end + local window = math.max(16384, 2 * self._si.maxFrameSize) + while hi - lo > window do + local mid = (lo + hi) // 2 + local h = findFrame(self, mid, hi) + if h and sampleOf(self, h) <= t then + lo = h.offset + else + hi = mid + end + end + local pos = lo + while true do + local h = findFrame(self, pos, len) + if not h then + self._pos, self._fs, self._fn, self._cur = len, math.max(t, self.frames), 0, 0 + return false + end + local s = sampleOf(self, h) + if s + h.blockSize > t then + if decodeAt(self, h.offset) then + if self._fs <= t and t < self._fs + self._fn then + self._cur = t - self._fs + return true + elseif self._fs > t then + return false -- a hole in the stream: we are at the next frame + end + pos = self._pos + else + return false + end + else + pos = h.offset + h.size + end + end +end + +function Dec.seek(self: any, seconds: number): boolean + return self:seekSample(math.floor((tonumber(seconds) or 0) * self.sampleRate + 0.5)) +end + +-- Find the total length from the last frame (when STREAMINFO does not give it) +local function scanLength(self: any): number + local len = self._len + local step = math.max(65536, 2 * self._si.maxFrameSize) + local from = len + while from > self._first do + local start = math.max(self._first, from - step) + local best: Header? = nil + local pos = start + while true do + local h = findFrame(self, pos, from) + if not h then + break + end + best = h + pos = h.offset + 1 + end + if best then + local s = sampleOf(self, best) + -- the last frame may be shorter than its header claims only via STREAMINFO, which is unknown here + return s + best.blockSize + end + from = start + end + return 0 +end + +local function skipId3(b: buffer, base: number, len: number): number + local p = 0 + while p + 10 <= len and buffer.readstring(b, base + p, 3) == "ID3" do + local sz = 0 + for i = 6, 9 do + sz = sz * 128 + bit32.band(buffer.readu8(b, base + p + i), 127) + end + local footer = bit32.band(buffer.readu8(b, base + p + 5), 0x10) ~= 0 + p += 10 + sz + (if footer then 10 else 0) + end + return p +end + +-- opts.crc16 = false skips the per-frame CRC-16 check +function Stream.open(buf: buffer, base: number, srcLen: number, opts: { crc16: boolean? }?): (Decoder?, string?, string?) + local b, len, container + if srcLen >= 4 and buffer.readstring(buf, base, 4) == "OggS" then + local demux, err = Ogg.open(Bytes.reader(buf, base, srcLen)) + if not demux then + return nil, (err :: any).message, "CORRUPT" + end + local serial = demux:find("flac") + if not serial then + return nil, "no FLAC stream in the Ogg file", "CORRUPT" + end + -- rebuild a native stream: "fLaC" + metadata (from the header packets) + frames (one per packet) + local packets, total = {}, 0 + for p in demux:packets(serial) do + local off, size = p.offset, p.size + if #packets == 0 then + if size < 13 then + return nil, "bad Ogg FLAC header", "CORRUPT" + end + off += 9 + size -= 9 + end + table.insert(packets, { p.data, off, size }) + total += size + end + b = buffer.create(total + PAD) + local o = 0 + for _, p in packets do + buffer.copy(b, o, p[1], p[2], p[3]) + o += p[3] + end + len = total + container = "ogg" + else + local start = skipId3(buf, base, srcLen) + if start + 4 > srcLen or buffer.readstring(buf, base + start, 4) ~= "fLaC" then + return nil, "not a FLAC file", "CORRUPT" + end + len = srcLen - start + b = buffer.create(len + PAD) + buffer.copy(b, 0, buf, base + start, len) + container = "flac" + end + local info, err = Meta.parse(b, 0, len) + if not info then + return nil, err, "CORRUPT" + end + local si = info.streamInfo + local self = setmetatable({ + sampleRate = si.sampleRate, + channels = si.channels, + bitsPerSample = si.bitsPerSample, + frames = si.totalSamples, + duration = 0, + bitrate = 0, + tags = info.tags, + comments = info.comments, + vendor = info.vendor, + md5 = si.md5, + seekTable = info.seekTable, + pictures = info.pictures, + container = container, + _b = b, + _len = len, + _si = si, + _first = info.firstFrame, + _pos = info.firstFrame, + _chans = {}, + _cap = 0, + _cf = table.create(32, 0), + _crc = not (opts and opts.crc16 == false), + _fs = 0, + _fn = 0, + _cur = 0, + _nominal = math.max(si.maxBlockSize, 1), + }, Dec) + ensure(self, math.max(si.maxBlockSize, 16)) + local h = findFrame(self, info.firstFrame, len) + if h then + if not h.variable then + self._nominal = h.blockSize + end + end + if self.frames == 0 then + self.frames = scanLength(self) + end + self.duration = self.frames / self.sampleRate + if self.duration > 0 then + self.bitrate = (len - info.firstFrame) * 8 / self.duration + end + return self :: any, nil +end + +Stream.Dec = Dec + +return Stream diff --git a/src/Formats/audio/flac/init.luau b/src/Formats/audio/flac/init.luau new file mode 100644 index 0000000..bcf2578 --- /dev/null +++ b/src/Formats/audio/flac/init.luau @@ -0,0 +1,131 @@ +--!strict +-- audio/flac: FLAC (RFC 9639), native and in Ogg (the Ogg FLAC mapping). Absorbed from flac-luau 7083d0d (same author, +-- no third-party code); the Ogg demuxer is now a direct require of containers/Ogg instead of an injected module. +-- Supports: every subframe type (constant, verbatim, fixed, LPC up to order 32, wasted bits), Rice / Rice2 residuals +-- with escapes, every stereo mode, 4-32 bits, 1-8 channels, any sample rate, fixed and variable block sizes, frame +-- CRC-16 checks with resync past corrupt frames, sample-accurate seeking (seek table + bisection), an ID3v2 tag in +-- front, STREAMINFO / SEEKTABLE / VORBIS_COMMENT / PICTURE metadata, the total length from the last frame when +-- STREAMINFO has none. Not supported: encoding (ws-audio), MD5 verification, chained Ogg streams. +-- +-- local dec = Flac.open(Bytes.reader(buf)) -- the Types.Decoder (+ bitsPerSample, readInt, seekSample, ...) +-- local f32, n = dec:read(4096) -- interleaved f32 in [-1, 1); n = 0 at the end +-- local i32, n = dec:readInt(4096) -- bit-exact integer samples +-- local audio = Flac.decode(Bytes.reader(buf)) -- Types.Audio + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Ogg = require("@formats/containers/Ogg") +local Stream = require("@formats/audio/flac/Stream") + +-- ------------------------------------------------------------------------------------------------ contract +local Flac = { + name = "flac", + category = "audio", + extensions = { "flac", "oga" }, + mime = { "audio/flac", "audio/x-flac" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" }, + caps = { decode = true, encode = false, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type Decoder = Stream.Decoder +export type OpenOptions = { + crc16: boolean?, -- check every frame's CRC-16 (default true; a bad frame is skipped by resyncing) + maxFrames: number?, -- decode(): refuse streams longer than this many sample frames (default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Flac.sniff(r: Bytes.Reader): number + local head = r:peek(4) + if head == "fLaC" then + return 1 + end + if head == "OggS" then + -- the first page's packet: 0x7F "FLAC" (the Ogg FLAC mapping) + local nseg = r:peekU8(26) + if nseg > 0 and r:peek(5, 27 + nseg) == "\127FLAC" then + return 1 + end + return 0 + end + if string.sub(head, 1, 3) == "ID3" then + -- an ID3v2 tag, then fLaC (mp3 files start with ID3 too) + local sz = 0 + for i = 6, 9 do + local v = r:peekU8(i) + if v < 0 then + return 0 + end + sz = sz * 128 + bit32.band(v, 127) + end + local footer = bit32.band(math.max(r:peekU8(5), 0), 0x10) ~= 0 + return if r:peek(4, 10 + sz + (if footer then 10 else 0)) == "fLaC" then 1 else 0 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream +function Flac.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = Flac.open(r, opts) + if not dec then + return nil, err + end + local d = dec :: any + local limit = opts and opts.maxFrames or 2 ^ 28 + if d.frames > limit or d.frames * d.channels > 2 ^ 28 then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames)) + end + local ch = d.channels + local parts, total = {}, 0 + if d.frames > 0 then + local out, n = d:read(d.frames) + table.insert(parts, out) + total = n + end + while true do -- frames past what STREAMINFO / the scan said + local out, n = d:read(65536) + if n == 0 then + break + end + table.insert(parts, out) + total += n + if total > limit then + return nil, Err.new(Err.LIMIT, "stream over the frame limit") + end + end + local a = Types.Audio.new(d.sampleRate, ch, total) + local o = 0 + for _, p in parts do + local n = math.min(buffer.len(p), total * ch * 4 - o) + buffer.copy(a.samples, o, p, 0, n) + o += n + end + a.tags = d.tags + a.meta.source = { format = "flac", bitDepth = d.bitsPerSample, container = d.container, vendor = d.vendor, md5 = d.md5, pictures = d.pictures } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> Decoder | nil, Err +function Flac.open(r: Bytes.Reader, opts: OpenOptions?): (Decoder?, Err.Err?) + if type(r) == "buffer" then + r = Bytes.reader(r :: any) + end + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local dec, msg, code = Stream.open(r.buf, r.base, r.limit - r.base, opts) + if not dec then + return nil, Err.new(code or Err.CORRUPT, tostring(msg)) + end + return dec, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +Flac.Stream = Stream +Flac.Ogg = Ogg + +return Flac diff --git a/src/Formats/containers/Zip/init.luau b/src/Formats/containers/Zip/init.luau new file mode 100644 index 0000000..1545ce2 --- /dev/null +++ b/src/Formats/containers/Zip/init.luau @@ -0,0 +1,668 @@ +--!strict +--!optimize 2 +-- containers/Zip: the ZIP container (PKWARE APPNOTE 6.3): a reader and a writer. The reader is absorbed from +-- zip-luau 121d4b0 (same author, no third-party code): the end of central directory record (searched back over an +-- archive comment), the central directory, ZIP64 (records, locator, extra fields), a prefix shift (self-extractor +-- stubs), stored and deflated entries with a CRC-32 check, data descriptors, a wrong local header fallback, +-- case-insensitive / basename lookup that skips __MACOSX. The DEFLATE codec is now required directly +-- (codecs/Deflate) instead of injected. The writer is new: stored / deflated entries (codecs/Deflate compress, stored +-- when that is not smaller), UTF-8 names, DOS times, raw copies of existing entries, ZIP64 when needed. +-- +-- local zip, err = Zip.open(buf) -- buffer, string or core/Bytes Reader +-- for _, e in zip:list() do print(e.name, e.size) end +-- local data, err = zip:read("Main.bmp") -- exact, then case-insensitive, then by basename; CRC-checked +-- +-- local w = Zip.writer() +-- w:add("readme.txt", "hello", { level = 9 }) -- or { method = "store" }, mtime = unix seconds +-- local file = w:finish({ comment = "..." }) +-- +-- Never throws: corrupt archives and bad arguments return nil, Err. Parsing runs interpreted (it is cold); the native +-- code it reaches (Deflate, Crc32) does not throw either. +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Deflate = require("@formats/codecs/Deflate") + +local Zip = {} +Zip.version = "1.1.0" + +export type Entry = { + name: string, -- the path with "\" turned into "/" + rawName: string, -- the name bytes as stored + index: number, -- position in the central directory, 1-based + size: number, -- uncompressed size + compressedSize: number, + crc32: number, + method: number, -- 0 stored, 8 deflate (others are listed but not readable) + flags: number, -- general purpose bits (1 encrypted, 8 data descriptor, 2048 UTF-8 name) + offset: number, -- local header offset (already corrected for a prefix such as a self-extractor stub) + isDir: boolean, + utf8: boolean, + comment: string, + modified: { year: number, month: number, day: number, hour: number, min: number, sec: number }, + mtime: number, -- the modification time as Unix seconds (the DOS time read as UTC) + time: number, -- the raw DOS time and date + date: number, + attributes: number, -- external attributes + -- central-directory lengths of the name and extra field (a fallback when the local header is wrong) + cdNameLen: number, + cdExtraLen: number, +} + +-- ------------------------------------------------------------------------------------------------ read +local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 + +local SIG_LOCAL, SIG_CD, SIG_EOCD = 0x04034b50, 0x02014b50, 0x06054b50 +local SIG_Z64_EOCD, SIG_Z64_LOC = 0x06064b50, 0x07064b50 + +local function readu64(b: buffer, o: number): number + return readu32(b, o) + readu32(b, o + 4) * 4294967296 +end + +local function sigAt(b: buffer, o: number, sig: number): boolean + return o >= 0 and o + 4 <= buffer.len(b) and readu32(b, o) == sig +end + +local function normalize(name: string): string + name = string.gsub(name, "\\", "/") + name = string.gsub(name, "^%./", "") + name = string.gsub(name, "^/+", "") + return name +end + +local function basename(name: string): string + return string.match(name, "([^/]*)/*$") or name +end + +-- junk that shares a basename with real files: macOS resource forks +local function isJunk(name: string): boolean + local l = string.lower(name) + return string.find(l, "__macosx/", 1, true) ~= nil or string.sub(basename(l), 1, 2) == "._" +end + +local Archive = {} +Archive.__index = Archive + + +-- isZip(buf) -> true when buf starts like a zip (a local header, or the end record of an empty archive) +function Zip.isZip(buf: buffer | string): boolean + local b = if type(buf) == "string" then buffer.fromstring(string.sub(buf, 1, 4)) else buf + return sigAt(b, 0, SIG_LOCAL) or sigAt(b, 0, SIG_EOCD) +end + +local function findEocd(b: buffer): number? + local n = buffer.len(b) + local fallback = nil + local stop = math.max(0, n - 22 - 65535) + for p = n - 22, stop, -1 do + if readu8(b, p) == 0x50 and readu32(b, p) == SIG_EOCD then + if p + 22 + readu16(b, p + 20) == n then + return p + end + fallback = fallback or p -- comment length disagrees (trailing junk or a wrong length): keep looking + end + end + return fallback +end + +local function parse(b: buffer): (any, Err.Err?) + local n = buffer.len(b) + if n < 22 then + return nil, Err.new(Err.TRUNCATED, "too small for an end of central directory record") + end + local eocd = findEocd(b) + if not eocd then + return nil, Err.new(Err.CORRUPT, "no end of central directory record") + end + local count = readu16(b, eocd + 10) + local cdSize = readu32(b, eocd + 12) + local cdOff = readu32(b, eocd + 16) + local commentLen = math.min(readu16(b, eocd + 20), n - eocd - 22) + local comment = buffer.readstring(b, eocd + 22, commentLen) + local cdEnd = eocd + -- ZIP64: the locator sits just before the end record + local zip64 = false + if sigAt(b, eocd - 20, SIG_Z64_LOC) then + local z = readu64(b, eocd - 20 + 8) + if not sigAt(b, z, SIG_Z64_EOCD) then + -- a prefix shifted everything: the record directly precedes the locator (56 bytes + extensible data) + local guess = eocd - 20 - 56 + if sigAt(b, guess, SIG_Z64_EOCD) then + z = guess + else + z = -1 + end + end + if z >= 0 and z + 56 <= n then + zip64 = true + count = readu64(b, z + 32) + cdSize = readu64(b, z + 40) + cdOff = readu64(b, z + 48) + cdEnd = z + end + end + if not zip64 and (count == 0xFFFF or cdSize == 0xFFFFFFFF or cdOff == 0xFFFFFFFF) then + return nil, Err.new(Err.CORRUPT, "ZIP64 fields without a ZIP64 record") + end + -- a prefix (self-extractor stub, or a zip appended to another file) shifts every offset + local delta = 0 + if count > 0 and not sigAt(b, cdOff, SIG_CD) then + delta = cdEnd - (cdOff + cdSize) + if not sigAt(b, cdOff + delta, SIG_CD) then + return nil, Err.new(Err.CORRUPT, "central directory not found") + end + end + local entries: { any } = table.create(math.min(count, 65536)) + local p = cdOff + delta + for i = 1, count do + if not sigAt(b, p, SIG_CD) or p + 46 > n then + return nil, Err.new(Err.CORRUPT, string.format("bad central directory entry %d", i), p) + end + local flags = readu16(b, p + 8) + local method = readu16(b, p + 10) + local time, date = readu16(b, p + 12), readu16(b, p + 14) + local crc = readu32(b, p + 16) + local csize, usize = readu32(b, p + 20), readu32(b, p + 24) + local nameLen, extraLen, cmtLen = readu16(b, p + 28), readu16(b, p + 30), readu16(b, p + 32) + local disk = readu16(b, p + 34) + local off = readu32(b, p + 42) + if p + 46 + nameLen + extraLen + cmtLen > n then + return nil, Err.new(Err.TRUNCATED, string.format("central directory entry %d runs past the end", i), p) + end + local raw = buffer.readstring(b, p + 46, nameLen) + -- extra fields: ZIP64 (0x0001) holds the 32-bit fields that are all ones, in this order + local q, qe = p + 46 + nameLen, p + 46 + nameLen + extraLen + while q + 4 <= qe do + local id, sz = readu16(b, q), readu16(b, q + 2) + if id == 0x0001 then + local r, re = q + 4, math.min(q + 4 + sz, qe) + if usize == 0xFFFFFFFF and r + 8 <= re then + usize = readu64(b, r) + r += 8 + end + if csize == 0xFFFFFFFF and r + 8 <= re then + csize = readu64(b, r) + r += 8 + end + if off == 0xFFFFFFFF and r + 8 <= re then + off = readu64(b, r) + r += 8 + end + if disk == 0xFFFF and r + 4 <= re then + disk = readu32(b, r) + end + end + q += 4 + sz + end + local name = normalize(raw) + entries[i] = { + name = name, + rawName = raw, + index = i, + size = usize, + compressedSize = csize, + crc32 = crc, + method = method, + flags = flags, + offset = off + delta, + isDir = string.sub(raw, -1) == "/" or string.sub(raw, -1) == "\\", + utf8 = bit32.band(flags, 0x800) ~= 0, + comment = buffer.readstring(b, qe, cmtLen), + modified = { + year = 1980 + bit32.rshift(date, 9), + month = bit32.band(bit32.rshift(date, 5), 15), + day = bit32.band(date, 31), + hour = bit32.rshift(time, 11), + min = bit32.band(bit32.rshift(time, 5), 63), + sec = bit32.band(time, 31) * 2, + }, + mtime = Zip.unixTime(time, date), + time = time, + date = date, + attributes = readu32(b, p + 38), + cdNameLen = nameLen, + cdExtraLen = extraLen, + } + p = qe + cmtLen + end + local exact, lower, base = {}, {}, {} + for _, e in entries do + if not e.isDir then + exact[e.name] = exact[e.name] or e + local l = string.lower(e.name) + lower[l] = lower[l] or e + if not isJunk(e.name) then + local bn = basename(l) + local prev = base[bn] + -- prefer the shallowest path, then the first in directory order + if not prev or select(2, string.gsub(e.name, "/", "")) < select(2, string.gsub(prev.name, "/", "")) then + base[bn] = e + end + end + end + end + return setmetatable({ + buf = b, + entries = entries, + comment = comment, + zip64 = zip64, + _exact = exact, + _lower = lower, + _base = base, + }, Archive) +end + +-- open(src) -> Archive | nil, Err. src: a buffer, a string, or a core/Bytes Reader (its range is copied when it is a +-- part of a bigger buffer) +function Zip.open(src: any): (any, Err.Err?) + local b: buffer + if type(src) == "string" then + b = buffer.fromstring(src) + elseif type(src) == "buffer" then + b = src + elseif type(src) == "table" and type(src.buf) == "buffer" then + if src.base == 0 and src.limit == buffer.len(src.buf) then + b = src.buf + else + local n = math.max(0, src.limit - src.base) + b = buffer.create(n) + buffer.copy(b, 0, src.buf, src.base, n) + end + else + return nil, Err.new(Err.ARG, "open: expected a buffer, a string or a Reader") + end + local ok, res, err = pcall(parse, b) + if not ok then + return nil, Err.new(Err.CORRUPT, "corrupt archive (" .. tostring(res) .. ")") + end + return res, err +end + +-- every entry (directories included), in central directory order +function Archive.list(self: any): { Entry } + return self.entries +end + +-- find(name) -> entry | nil: the exact path, else the path case-insensitively, else the basename +-- case-insensitively (skins sometimes nest everything in a folder). "\" and "/" are the same; directories and +-- macOS "__MACOSX/" / "._" files never match by basename. +function Archive.find(self: any, name: string): Entry? + local n = normalize(name) + local e = self._exact[n] + if e then + return e + end + local l = string.lower(n) + e = self._lower[l] + if e then + return e + end + return self._base[basename(l)] +end + +local function extract(b: buffer, e: Entry, dataStart: number): (buffer?, any) + local n = buffer.len(b) + if dataStart > n then + return nil, "data starts past the end" + end + if e.method == 0 then + if dataStart + e.size > n then + return nil, "truncated stored data" + end + local out = buffer.create(e.size) + buffer.copy(out, 0, b, dataStart, e.size) + return out + end + local len = math.min(e.compressedSize, n - dataStart) + local out, err = Deflate.inflate(b, dataStart, len, e.size) + if not out then + -- a wrong size in the directory: inflate without it and let the CRC decide + local out2 = Deflate.inflate(b, dataStart, n - dataStart) + if out2 then + return out2 + end + return nil, if type(err) == "table" then err.message else tostring(err) + end + return out +end + +-- the data offset candidates of an entry: the local header's own lengths, then the central directory's (some writers +-- get the local extra length wrong) +function Zip._starts(b: buffer, e: Entry): { number } + local o = e.offset + local starts = {} + if o >= 0 and o + 30 <= buffer.len(b) and readu32(b, o) == SIG_LOCAL then + table.insert(starts, o + 30 + readu16(b, o + 26) + readu16(b, o + 28)) + end + local alt = o + 30 + e.cdNameLen + e.cdExtraLen + if alt ~= starts[1] then + table.insert(starts, alt) + end + if alt ~= o + 30 + e.cdNameLen then + table.insert(starts, o + 30 + e.cdNameLen) + end + return starts +end + +-- read(entry | name, verify = true) -> buffer | nil, Err +function Archive.read(self: any, entry: Entry | string, verify: boolean?): (buffer?, Err.Err?) + local e: Entry? = if type(entry) == "string" then self:find(entry) else entry :: Entry + if not e then + return nil, Err.new(Err.ARG, "no entry " .. tostring(entry)) + end + if e.isDir then + return buffer.create(0), nil + end + if bit32.band(e.flags, 1) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, e.name .. " is encrypted") + end + if e.method ~= 0 and e.method ~= 8 then + return nil, Err.new(Err.UNSUPPORTED, string.format("%s uses compression method %d (only stored and deflate)", e.name, e.method)) + end + local b = self.buf + local n = buffer.len(b) + local o = e.offset + if o < 0 or o + 30 > n then + return nil, Err.new(Err.CORRUPT, e.name .. ": local header out of range", o) + end + local starts = Zip._starts(b, e) + local firstErr: string? = nil + local code = Err.CORRUPT + for _, s in starts do + local out, err = extract(b, e, s) + if out then + if verify == false then + return out, nil + end + if buffer.len(out) ~= e.size then + err = string.format("size %d, expected %d", buffer.len(out), e.size) + else + local c = Deflate.crc32(out) + if c == e.crc32 then + return out, nil + end + err = string.format("CRC-32 mismatch (%08x, expected %08x)", c, e.crc32) + end + end + firstErr = firstErr or err + end + return nil, Err.new(if firstErr and string.find(firstErr, "CRC", 1, true) then Err.CHECKSUM else code, e.name .. ": " .. tostring(firstErr)) +end + +-- readString(entry | name, verify?) -> string | nil, Err +function Archive.readString(self: any, entry: Entry | string, verify: boolean?): (string?, Err.Err?) + local out, err = self:read(entry, verify) + if not out then + return nil, err + end + return buffer.tostring(out), nil +end + +-- ------------------------------------------------------------------------------------------------ write +local Writer = {} +Writer.__index = Writer + +export type AddOptions = { + method: ("deflate" | "store")?, -- default "deflate" (stored instead when deflate does not make it smaller) + level: number?, -- deflate level 0..9 (default 6) + mtime: number?, -- modification time, Unix seconds (UTC); default 1980-01-01 00:00:00 (reproducible output) + comment: string?, + utf8: boolean?, -- set the UTF-8 name flag (default: when the name is not plain ASCII) + attributes: number?, -- external attributes (default: Unix 0644 for files, 0755 + MS-DOS directory for dirs) +} +export type FinishOptions = { + comment: string?, -- the archive comment + zip64: boolean?, -- force the ZIP64 records (default: only when counts, sizes or offsets need them) +} + +-- writer() -> Writer +function Zip.writer(): any + return setmetatable({ files = {} :: { any } }, Writer) +end + +-- days from 1970-01-01 to y-m-d (proleptic Gregorian) +local function civil(z: number): (number, number, number) + z += 719468 + local era = (if z >= 0 then z else z - 146096) // 146097 + local doe = z - era * 146097 + local yoe = (doe - doe // 1460 + doe // 36524 - doe // 146096) // 365 + local y = yoe + era * 400 + local doy = doe - (365 * yoe + yoe // 4 - yoe // 100) + local mp = (5 * doy + 2) // 153 + local d = doy - (153 * mp + 2) // 5 + 1 + local m = if mp < 10 then mp + 3 else mp - 9 + return (if m <= 2 then y + 1 else y), m, d +end +local function daysFrom(y: number, m: number, d: number): number + y = if m <= 2 then y - 1 else y + local era = (if y >= 0 then y else y - 399) // 400 + local yoe = y - era * 400 + local mp = if m > 2 then m - 3 else m + 9 + local doy = (153 * mp + 2) // 5 + d - 1 + local doe = yoe * 365 + yoe // 4 - yoe // 100 + doy + return era * 146097 + doe - 719468 +end + +-- Unix seconds -> DOS time, date (clamped to 1980..2107) +function Zip.dosTime(t: number?): (number, number) + if type(t) ~= "number" or t ~= t then + return 0, 0x21 + end + local s = math.floor(t) + local days = s // 86400 + local rem = s - days * 86400 + local y, m, d = civil(days) + if y < 1980 then + return 0, 0x21 + elseif y > 2107 then + y, m, d, rem = 2107, 12, 31, 86399 + end + local time = (rem // 3600) * 2048 + ((rem // 60) % 60) * 32 + (rem % 60) // 2 + return time, (y - 1980) * 512 + m * 32 + d +end + +-- DOS time, date -> Unix seconds (UTC) +function Zip.unixTime(time: number, date: number): number + local y = 1980 + bit32.rshift(date, 9) + local m = math.clamp(bit32.band(bit32.rshift(date, 5), 15), 1, 12) + local d = math.clamp(bit32.band(date, 31), 1, 31) + return daysFrom(y, m, d) * 86400 + bit32.rshift(time, 11) * 3600 + bit32.band(bit32.rshift(time, 5), 63) * 60 + bit32.band(time, 31) * 2 +end + +local function isAscii(s: string): boolean + return string.find(s, "[\128-\255]") == nil +end + +-- add(name, data, opts?) -> true | false, Err: compresses now (data: buffer or string) +function Writer.add(self: any, name: string, data: any, opts: AddOptions?): (boolean, Err.Err?) + if type(name) ~= "string" or name == "" or #name > 65535 then + return false, Err.new(Err.ARG, "add: bad entry name") + end + local b: buffer + if type(data) == "string" then + b = buffer.fromstring(data) + elseif type(data) == "buffer" then + b = data + elseif data == nil and string.sub(name, -1) == "/" then + b = buffer.create(0) + else + return false, Err.new(Err.ARG, "add: data must be a buffer or a string") + end + local o: AddOptions = opts or {} + local method = o.method or "deflate" + if method ~= "deflate" and method ~= "store" then + return false, Err.new(Err.ARG, "add: method must be deflate or store") + end + local isDir = string.sub(name, -1) == "/" + local n = buffer.len(b) + local comp, code = b, 0 + if method == "deflate" and n > 0 and not isDir then + local z, zerr = Deflate.compress(b, { level = o.level or 6 }) + if not z then + return false, zerr + end + if buffer.len(z) < n then + comp, code = z, 8 + end + end + local time, date = Zip.dosTime(o.mtime) + table.insert(self.files, { + name = name, + method = code, + crc = if n > 0 then Crc32.of(b) else 0, + size = n, + data = comp, + dataOffset = 0, + dataLength = buffer.len(comp), + time = time, + date = date, + comment = o.comment or "", + utf8 = if o.utf8 ~= nil then o.utf8 else not isAscii(name), + attributes = o.attributes or (if isDir then 0x41ED0010 else 0x81A40000), + }) + return true, nil +end + +-- addRaw(entry, archive): copy an entry of an opened archive without recompressing it -> true | false, Err +function Writer.addRaw(self: any, e: Entry, archive: any, newName: string?): (boolean, Err.Err?) + local b = archive.buf + local start: number? = nil + for _, s in Zip._starts(b, e) do + if s >= 0 and s + e.compressedSize <= buffer.len(b) then + start = s + break + end + end + if not start or bit32.band(e.flags, 1) ~= 0 then + return false, Err.new(Err.CORRUPT, e.name .. ": cannot copy the entry data") + end + local name = newName or e.name + table.insert(self.files, { + name = name, + method = e.method, + crc = e.crc32, + size = e.size, + data = b, + dataOffset = start, + dataLength = e.compressedSize, + time = e.time or 0, + date = e.date or 0x21, + comment = e.comment or "", + utf8 = e.utf8 or not isAscii(name), + attributes = e.attributes or (if e.isDir then 0x41ED0010 else 0x81A40000), + }) + return true, nil +end + +-- finish(opts?) -> the archive | nil, Err +function Writer.finish(self: any, opts: FinishOptions?): (buffer?, Err.Err?) + local comment = opts and opts.comment or "" + if #comment > 65535 then + return nil, Err.new(Err.ARG, "finish: archive comment over 65535 bytes") + end + local force = opts and opts.zip64 or false + local total = 22 + #comment + 98 + for _, f in self.files do + total += 30 + #f.name + 20 + f.dataLength + 46 + #f.name + 28 + #f.comment + end + if total > 0x3FFFFFFF then + return nil, Err.new(Err.LIMIT, "finish: the archive would be over 1 GiB") + end + local w = Bytes.writer(total) + local offsets = {} + for i, f in self.files do + local off = w:tell() + offsets[i] = off + local big = force or f.size >= 0xFFFFFFFF or f.dataLength >= 0xFFFFFFFF + local flags = if f.utf8 then 0x800 else 0 + w:u32le(SIG_LOCAL) + w:u16le(if big then 45 else 20) + w:u16le(flags) + w:u16le(f.method) + w:u16le(f.time) + w:u16le(f.date) + w:u32le(f.crc) + w:u32le(if big then 0xFFFFFFFF else f.dataLength) + w:u32le(if big then 0xFFFFFFFF else f.size) + w:u16le(#f.name) + w:u16le(if big then 20 else 0) + w:string(f.name) + if big then + w:u16le(1) + w:u16le(16) + w:u64le(f.size) + w:u64le(f.dataLength) + end + w:bytes(f.data, f.dataOffset, f.dataLength) + end + local cdOff = w:tell() + for i, f in self.files do + local off = offsets[i] + local bigSize = force or f.size >= 0xFFFFFFFF or f.dataLength >= 0xFFFFFFFF + local bigOff = force or off >= 0xFFFFFFFF + local extra = (if bigSize then 16 else 0) + (if bigOff then 8 else 0) + local version = if bigSize or bigOff then 45 else 20 + w:u32le(SIG_CD) + w:u16le(0x0300 + version) -- made by: Unix + w:u16le(version) + w:u16le(if f.utf8 then 0x800 else 0) + w:u16le(f.method) + w:u16le(f.time) + w:u16le(f.date) + w:u32le(f.crc) + w:u32le(if bigSize then 0xFFFFFFFF else f.dataLength) + w:u32le(if bigSize then 0xFFFFFFFF else f.size) + w:u16le(#f.name) + w:u16le(if extra > 0 then extra + 4 else 0) + w:u16le(#f.comment) + w:u16le(0) -- disk + w:u16le(0) -- internal attributes + w:u32le(f.attributes) + w:u32le(if bigOff then 0xFFFFFFFF else off) + w:string(f.name) + if extra > 0 then + w:u16le(1) + w:u16le(extra) + if bigSize then + w:u64le(f.size) + w:u64le(f.dataLength) + end + if bigOff then + w:u64le(off) + end + end + w:string(f.comment) + end + local cdSize = w:tell() - cdOff + local count = #self.files + local z64 = force or count >= 0xFFFF or cdOff >= 0xFFFFFFFF or cdSize >= 0xFFFFFFFF + if z64 then + local rec = w:tell() + w:u32le(SIG_Z64_EOCD) + w:u64le(44) + w:u16le(0x032D) + w:u16le(45) + w:u32le(0) + w:u32le(0) + w:u64le(count) + w:u64le(count) + w:u64le(cdSize) + w:u64le(cdOff) + w:u32le(SIG_Z64_LOC) + w:u32le(0) + w:u64le(rec) + w:u32le(1) + end + w:u32le(SIG_EOCD) + w:u16le(0) + w:u16le(0) + w:u16le(if z64 then 0xFFFF else count) + w:u16le(if z64 then 0xFFFF else count) + w:u32le(if z64 then 0xFFFFFFFF else cdSize) + w:u32le(if z64 then 0xFFFFFFFF else cdOff) + w:u16le(#comment) + w:string(comment) + return w:finish(), nil +end + +return Zip 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/archive/zip.luau b/tests/archive/zip.luau new file mode 100644 index 0000000..26efdec --- /dev/null +++ b/tests/archive/zip.luau @@ -0,0 +1,268 @@ +-- archive/zip + containers/Zip tests: generated archives (comment with a fake end record, data descriptors, +-- force_zip64, an all-ZIP64 archive, 66000 entries, a prefix stub, a wrong local header, unicode, empty) read entry by +-- entry against Python's zipfile listing (and every Webamp demo skin when SKINS_DIR is set); lookup rules; bad CRC, +-- encrypted and unsupported entries; the writer (stored / deflated, levels, UTF-8 names, DOS times, comments, ZIP64, +-- raw copies) read back; the Archive API (list / read / add / remove / write, create, encode of a table) and the api; +-- corrupt input never throws. The writer's output was also checked by hand: `unzip -t`, Python zipfile and 7z read it. +-- Ported from zip-luau tests/zip.luau. Fixtures: tools/fixtures/zip.py. +local T = require("@tests/T") +local Zip = require("@formats/containers/Zip") +local ZipF = require("@formats/archive/zip") +local Deflate = require("@formats/codecs/Deflate") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local F = require("@formats") +local Fx = require("@tests/gen/zip_cases") + +local t = T.suite("zip") + +local function dataOf(a: any): string + if a.data then + return a.data + end + return buffer.tostring(Deflate.zlib(buffer.fromstring(a.dataZ)) :: buffer) +end + +-- open an archive and compare it with zipfile's listing; read every entry +local function verify(a: any, label: string): (any, number) + local z, err = Zip.open(dataOf(a)) + t:check(z, label .. ": open: " .. tostring(err)) + local list = z:list() + t:eq(#list, a.count, label .. ": entries") + local bytes = 0 + for i, want in a.entries do + local e = list[i] + t:check(e.rawName == want[1] or e.name == string.gsub(want[1], "\\", "/"), label .. ": name " .. e.rawName) + t:check(e.size == want[2] and e.crc32 == want[3] and e.method == want[4], label .. ": " .. e.name .. " size / crc / method") + local data, rerr = z:read(e) + t:check(data, label .. ": read " .. e.name .. ": " .. tostring(rerr)) + t:check(buffer.len(data :: buffer) == want[2] and Crc32.of(data :: buffer) == want[3], label .. ": " .. e.name .. " content") + bytes += want[2] + end + return z, bytes +end + +local byName = {} +for _, a in Fx.archives do + byName[a.name] = a + a.zip = verify(a, a.name) +end +t:note("%d generated archives match Python zipfile", #Fx.archives) +local total, nent = 0, 0 +for _, s in Fx.skins do + local _, bytes = verify(s, s.name) + total += bytes + nent += s.count +end +if #Fx.skins > 0 then + t:note("%d skins, %d entries, %.2f MB read and CRC-checked", #Fx.skins, nent, total / 1e6) +else + t:note("(no skins: set SKINS_DIR to the Webamp demo skins)") +end + +-- lookup and specifics +do + local z = byName.basic.zip + t:eq(z:find("readme.txt").name, "readme.txt", "find exact") + t:eq(z:find("README.TXT").name, "readme.txt", "find case-insensitive") + t:eq(z:find("main.bmp").name, "Skin/Main.BMP", "find by basename skips __MACOSX") + t:eq(z:find("skin\\MAIN.bmp").name, "Skin/Main.BMP", "find with backslashes") + t:check(z:find("__MACOSX/Skin/._Main.BMP") ~= nil, "junk still found by its full path") + t:check(z:find("Skin/") == nil, "directories are not found") + t:check(z:find("nope.bmp") == nil, "missing") + t:eq(z:find("deep.txt").name, "Skin/sub/deep.txt", "basename in a deeper folder") + t:eq(z:readString("DEEP.TXT"), "deep", "readString by name") + t:eq(z:readString("Other/\u{fc}nicode.txt"), "h\u{e9}llo", "unicode basename") + local u = z:find("sk\u{ef}n/\u{fc}nicode.txt") + t:check(u and u.utf8 and z:readString(u) == "h\u{e9}llo", "unicode name") + local m = z:find("readme.txt").modified + t:check(m.year == 2020 and m.month == 5 and m.day == 17 and m.hour == 13 and m.min == 37 and m.sec == 42, "dos time") + t:eq(z:find("readme.txt").mtime, 1589722662, "mtime (unix seconds)") + local _, e = z:read("nope") + t:check(e and e.code == Err.ARG, "read a missing name") + t:eq(string.sub(byName.comment.zip.comment, 1, 14), "a comment with", "archive comment") + t:check(byName.zip64_by_hand.zip.zip64 and byName.many.zip.zip64, "zip64 records detected") + t:check(bit32.band(byName.descriptors.zip:list()[1].flags, 8) ~= 0, "data descriptor flag") + t:check(not byName.basic.zip.zip64, "basic is not zip64") + t:eq(byName.many.zip:readString("d/65999.txt"), "65999", "last of 66000 entries") + t:eq(#byName.empty.zip:list(), 0, "empty archive") + t:check(Zip.isZip(byName.basic.data) and Zip.isZip(byName.empty.data) and not Zip.isZip("GIF89a"), "isZip") + -- a sub-range reader + local s = byName.basic.data + local big = buffer.create(#s + 10) + buffer.writestring(big, 4, s) + local zs = Zip.open(Bytes.reader(big, 4, #s)) + t:check(zs and zs:readString("readme.txt") ~= nil, "open a sub-range Reader") +end + +-- a bad CRC, encrypted and unsupported entries +do + local data = buffer.fromstring(byName.basic.data) + local z = Zip.open(byName.basic.data) + local st = z:find("stored.bin") + local p = st.offset + 30 + buffer.readu16(data, st.offset + 26) + buffer.readu16(data, st.offset + 28) + 10 + buffer.writeu8(data, p, bit32.bxor(buffer.readu8(data, p), 0xFF)) + local z2 = Zip.open(data) + local out, err = z2:read("stored.bin") + t:check(out == nil and err.code == Err.CHECKSUM, "stored CRC mismatch: " .. tostring(err)) + t:check(z2:read("stored.bin", false) ~= nil, "verify = false") + local e = table.clone(z:find("readme.txt")) + e.flags = 1 + local _, ee = z:read(e) + t:check(ee and ee.code == Err.UNSUPPORTED, "encrypted refused") + e.flags, e.method = 0, 12 + local _, merr = z:read(e) + t:check(merr and merr.code == Err.UNSUPPORTED and string.find(merr.message, "method 12", 1, true), "bzip2 refused: " .. tostring(merr)) + local _, oe = Zip.open(5 :: any) + t:check(oe and oe.code == Err.ARG, "a non-buffer argument") +end + +-- the writer +do + local rand = T.rng(5) + local w = Zip.writer() + local files = {} + local text = string.rep("the quick brown fox jumps over the lazy dog ", 2000) + local noise = buffer.create(5000) + for i = 0, 4999 do + buffer.writeu8(noise, i, rand(2147483648) // 8388608) + end + local function put(name: string, data: any, opts: any?) + t:check(w:add(name, data, opts), "add " .. name) + table.insert(files, { name, if type(data) == "string" then data elseif data then buffer.tostring(data) else "" }) + end + put("text.txt", text, { level = 9, mtime = 1589722662 }) + put("stored.txt", text, { method = "store" }) + put("noise.bin", noise) -- deflate is not smaller: stored + put("empty.txt", "") + put("dir/", nil) + put("dir/\u{fc}nicode.txt", "h\u{e9}llo", { comment = "a file comment" }) + put("level0.txt", text, { level = 0 }) + local out, err = w:finish({ comment = "archive comment" }) + t:check(out, "finish: " .. tostring(err)) + local z = Zip.open(out :: buffer) + t:check(z, "our archive opens") + local list = z:list() + t:eq(#list, #files, "entry count") + for i, f in files do + t:eq(list[i].name, f[1], "name " .. i) + t:eq(z:readString(list[i]), f[2], "content " .. f[1]) + end + t:eq(list[1].method, 8, "deflated") + t:check(list[1].compressedSize < #text // 10, "compressed") + t:eq(list[2].method, 0, "stored") + t:eq(list[3].method, 0, "incompressible data is stored") + t:check(list[5].isDir, "directory entry") + t:check(list[6].utf8 and not list[1].utf8, "UTF-8 flag only for non-ASCII names") + t:eq(list[6].comment, "a file comment", "entry comment") + t:eq(list[1].mtime, 1589722662, "mtime round trip") + local md = list[1].modified + t:check(md.year == 2020 and md.month == 5 and md.day == 17 and md.hour == 13 and md.min == 37 and md.sec == 42, "dos time written") + t:check(list[2].modified.year == 1980 and list[2].modified.month == 1 and list[2].modified.day == 1, "default time 1980-01-01") + t:eq(z.comment, "archive comment", "archive comment written") + t:check(not z.zip64, "small archive is not ZIP64") + -- forced ZIP64 + local w64 = Zip.writer() + w64:add("a.txt", text) + w64:add("b.txt", "bee", { method = "store" }) + local z64 = Zip.open(w64:finish({ zip64 = true }) :: buffer) + t:check(z64 and z64.zip64 and z64:readString("a.txt") == text and z64:readString("b.txt") == "bee", "forced ZIP64 round trip") + -- over 65535 entries: the ZIP64 end record + local wm = Zip.writer() + for i = 0, 65999 do + wm:add(string.format("d/%05d.txt", i), tostring(i), { method = "store" }) + end + local zm = Zip.open(wm:finish() :: buffer) + t:check(zm and zm.zip64 and #zm:list() == 66000 and zm:readString("d/65999.txt") == "65999", "66000 entries") + -- dates + for _, s in { 315532800, 946684799, 1700000000, 4354819198 } do + local tm, dt = Zip.dosTime(s) + t:eq(Zip.unixTime(tm, dt), s - s % 2, "dos time of " .. s) + end + t:check(select(2, Zip.dosTime(0)) == 0x21, "before 1980 clamps") + -- bad arguments + t:check(not w:add("", "x"), "empty name") + t:check(not w:add("x", 5 :: any), "bad data") + t:check(not w:add("x", "y", { method = "lzma" } :: any), "bad method") +end + +-- the Archive (archive/zip) +do + t:eq(ZipF.name, "zip", "name") + t:eq(ZipF.category, "archive", "category") + local a, err = ZipF.decode(Bytes.reader(buffer.fromstring(byName.basic.data))) + t:check(a and a.kind == "archive" and a.format == "zip", "decode: " .. tostring(err)) + local list = a:list() + t:eq(#list, byName.basic.count, "list") + t:check(list[1].name == "readme.txt" and list[1].method == "deflate" and not list[1].dir and list[1].mtime == 1589722662, "entry fields") + t:check(list[4].dir, "dir entry") + local rd = a:read("readme.txt") + t:check(rd and Crc32.of(rd :: buffer) == byName.basic.entries[1][3], "read") + t:check(a:read("MAIN.bmp") ~= nil, "read by the lookup rules") + -- edit: replace, add, remove, then write; unchanged entries are copied raw + a:add("readme.txt", "replaced") + a:add("new/one.txt", string.rep("x", 1000), { level = 9 }) + t:check(a:remove("Skin/stored.bin") and not a:remove("nope"), "remove") + local out = a:write() :: buffer + local b = ZipF.decode(Bytes.reader(out)) :: any + t:check(b, "rewritten archive opens") + t:eq(buffer.tostring(b:read("readme.txt")), "replaced", "replaced entry") + t:eq(buffer.tostring(b:read("new/one.txt")), string.rep("x", 1000), "added entry") + t:check(b:read("Skin/stored.bin") == nil, "removed entry") + t:check(b:read("Skin/Main.BMP") and Crc32.of(b:read("Skin/Main.BMP")) == byName.basic.entries[2][3], "copied entry") + local names = {} + for _, e in b:list() do + table.insert(names, e.name) + end + t:eq(table.concat(names, ","), "readme.txt,Skin/Main.BMP,Skin/,Skin/sub/deep.txt,empty.txt,__MACOSX/Skin/._Main.BMP,Sk\u{ef}n/\u{fc}nicode.txt,new/one.txt", "order kept") + -- create, encode of a table, encode of another Archive + local c = ZipF.create() + c:add("hello.txt", "hi") + local cz = ZipF.decode(Bytes.reader(ZipF.encode(c) :: buffer)) :: any + t:eq(buffer.tostring(cz:read("hello.txt")), "hi", "create + encode") + local tz = ZipF.decode(Bytes.reader(ZipF.encode({ ["b.txt"] = "bee", ["a.txt"] = buffer.fromstring("ay") }) :: buffer)) :: any + t:check(tz:list()[1].name == "a.txt" and buffer.tostring(tz:read("b.txt")) == "bee", "encode a { name = data } table") + local _, ee = ZipF.encode(5 :: any) + t:check(ee and ee.code == Err.ARG, "encode a number") + -- comments survive a rewrite + local cm = ZipF.decode(Bytes.reader(buffer.fromstring(byName.comment.data))) :: any + t:eq(string.sub(Zip.open(cm:write()).comment, 1, 14), "a comment with", "comment kept on write") + -- the api + local la = F.archive.load(byName.basic.data) + t:check(la and la.kind == "archive" and #la:list() == byName.basic.count, "F.archive.load") + t:eq(F.detect(byName.basic.data), "zip", "F.detect") + local saved = F.save(la, nil, { format = "zip" }) + t:check(saved and #Zip.open(saved):list() == byName.basic.count, "F.save zip") + local saved2 = F.save(la) + t:check(saved2 ~= nil, "F.save without a format uses the source format") +end + +-- corrupt archives never throw +local samples = {} +for _, a in Fx.archives do + if a.data then + table.insert(samples, a.data) + end +end +t:fuzz("open + read every entry", function(b: buffer) + local z = Zip.open(b) + if z then + for _, e in z:list() do + z:read(e) + end + end + return z +end, samples, { mutations = 40 }) +t:fuzz("archive decode + write", function(b: buffer) + local a = ZipF.decode(Bytes.reader(b)) + if a then + for _, e in a:list() do + a:read(e.name) + end + a:write() + end + return a +end, samples, { mutations = 10, garbage = 50 }) + +t:done() diff --git a/tests/audio/flac.luau b/tests/audio/flac.luau new file mode 100644 index 0000000..c1d2305 --- /dev/null +++ b/tests/audio/flac.luau @@ -0,0 +1,203 @@ +-- audio/flac tests: every fixture from tools/fixtures/flac.py (flac 0-8, 4-32 bits, 1-6 channels, odd rates and block +-- sizes, LPC order 32, wasted bits, every stereo mode, ffmpeg's encoder, Ogg FLAC, ID3v2 in front) decoded bit-exact +-- against `flac -d`; sample-accurate seeking; f32 scaling and output reuse; decode() to an Audio from a sub-range +-- Reader; tags and pictures; the length from the last frame; sniff; the api; damaged frames skipped; the fuzz pass. +-- Ported from flac-luau tests/flac.luau. Fixtures: tools/fixtures/flac.py. +local T = require("@tests/T") +local Flac = require("@formats/audio/flac") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local F = require("@formats") +local Cases = require("@tests/gen/flac_cases") + +local t = T.suite("flac") + +local function open(b: any, opts: any?): (any, any) + return Flac.open(Bytes.reader(if type(b) == "string" then buffer.fromstring(b) else b), opts) +end +local byName = {} +for _, c in Cases do + byName[c.name] = c +end + +t:eq(Flac.name, "flac", "name") +t:check(Flac.caps.decode and not Flac.caps.encode, "caps") + +local seekChecks = 0 +for _, fx in Cases do + local name = fx.name + local dec, err = open(fx.data) + t:check(dec, name .. ": open: " .. tostring(err)) + t:check(dec.sampleRate == fx.rate and dec.channels == fx.channels and dec.bitsPerSample == fx.bps, name .. ": format") + t:eq(dec.frames, fx.frames, name .. ": frames") + t:check(math.abs(dec.duration - fx.frames / fx.rate) < 1e-9, name .. ": duration") + t:eq(dec.container, if fx.ogg then "ogg" else "flac", name .. ": container") + local ch = dec.channels + local all = table.create(fx.frames * ch, 0) + local crc, n, k = 0, 0, 0 + local sizes = { 4096, 1, 777, 10000, 3 } + while true do + k += 1 + local out, got = dec:readInt(sizes[k % #sizes + 1]) + if got == 0 then + break + end + crc = Crc32.of(out, 0, got * ch * 4, crc) + for i = 0, got * ch - 1 do + all[n * ch + i + 1] = buffer.readi32(out, i * 4) + end + n += got + end + t:eq(n, fx.frames, name .. ": decoded frames") + t:eq(crc, fx.crc, name .. ": samples identical to flac -d") + t:eq(select(2, dec:position()), fx.frames, name .. ": position at end") + -- f32 scaling, output reuse + dec:seekSample(0) + local reuse = buffer.create(100 * ch * 4) + local f, gotf = dec:read(100, reuse) + t:check(f == reuse, name .. ": output buffer reused") + local scale = 2 ^ (fx.bps - 1) + local bad = 0 + for i = 0, math.min(gotf, 100) * ch - 1 do + if math.abs(buffer.readf32(f, i * 4) - all[i + 1] / scale) >= 1e-7 then + bad += 1 + end + end + t:eq(bad, 0, name .. ": f32 samples") + -- seeking + local rand = T.rng(99) + local targets = { 0, 1, fx.frames - 1, fx.frames // 2, 4096, 4095, 4097, 1152, 1151 } + for _ = 1, 12 do + table.insert(targets, rand(fx.frames)) + end + for _, s in targets do + if s >= 0 and s < fx.frames then + t:check(dec:seekSample(s), name .. ": seek " .. s) + t:eq(select(2, dec:position()), s, name .. ": position after seek " .. s) + local out, got = dec:readInt(50) + t:eq(got, math.min(50, fx.frames - s), name .. ": read after seek") + local diff = 0 + for i = 0, got * ch - 1 do + if buffer.readi32(out, i * 4) ~= all[s * ch + i + 1] then + diff += 1 + end + end + t:eq(diff, 0, name .. ": samples after seek " .. s) + seekChecks += 1 + end + end + dec:seek(dec.duration / 3) + local _, pos = dec:position() + t:check(math.abs(pos - fx.frames / 3) <= 1, name .. ": seek seconds") + dec:seek(dec.duration + 5) + t:eq(select(2, dec:read(10)), 0, name .. ": read past the end") + for key, v in fx.tags or {} do + t:eq(dec.tags[key], v, name .. ": tag " .. key) + end + t:eq(Flac.sniff(Bytes.reader(buffer.fromstring(fx.data))), 1, name .. ": sniff") +end +t:note("%d fixtures bit-exact against flac -d, %d seeks", #Cases, seekChecks) + +-- decode() from a sub-range Reader +for _, name in { "s16_l5", "ogg_s16", "id3", "s24_96k" } do + local fx = byName[name] + local big = buffer.create(#fx.data + 13) + buffer.writestring(big, 6, fx.data) + local a, err = Flac.decode(Bytes.reader(big, 6, #fx.data)) + t:check(a and a.kind == "audio" and a.frames == fx.frames and a.channels == fx.channels, name .. ": decode: " .. tostring(err)) + local d = open(fx.data) + local ref = d:read(fx.frames) + t:check(buffer.tostring(ref) == buffer.tostring(a.samples), name .. ": decode = read") + t:eq(a.meta.source.bitDepth, fx.bps, name .. ": meta.source") +end + +-- tags and pictures +do + local dec = open(byName.s16_noseek.data) + t:check(#dec.pictures == 1 and dec.pictures[1].mime == "image/png" and dec.pictures[1].width == 1, "picture") + t:eq(#dec.seekTable, 0, "no seek table") + t:check(string.find(dec.vendor, "reference libFLAC", 1, true), "vendor") + t:eq(#dec.md5, 32, "md5") +end + +-- STREAMINFO without a total length: found from the last frame +for _, name in { "s16_l5", "varblock", "bs17" } do + local fx = byName[name] + local b = buffer.fromstring(fx.data) + buffer.writeu8(b, 8 + 13, bit32.band(buffer.readu8(b, 8 + 13), 0xF0)) + buffer.writeu32(b, 8 + 14, 0) + local dec = open(b) + t:check(dec and dec.frames == fx.frames, name .. ": length from the last frame") + local crc, n = 0, 0 + while true do + local out, got = dec:readInt(5000) + if got == 0 then + break + end + crc = Crc32.of(out, 0, got * dec.channels * 4, crc) + n += got + end + t:check(n == fx.frames and crc == fx.crc, name .. ": decode without total length") +end + +-- sniff, errors, the api +do + t:eq(Flac.sniff(Bytes.reader(buffer.fromstring("ID3\4\0\0\0\0\0\2xxfLaC"))), 1, "sniff ID3 + fLaC") + t:eq(Flac.sniff(Bytes.reader(buffer.fromstring("ID3\4\0\0\0\0\0\2xx\255\251"))), 0, "sniff ID3 + mp3") + t:eq(Flac.sniff(Bytes.reader(buffer.fromstring("RIFF"))), 0, "sniff RIFF") + local _, e1 = open("fLaC") + t:check(e1 and Err.is(e1), "no metadata: " .. tostring(e1)) + local _, e2 = open(buffer.create(0)) + t:check(e2 and e2.code == Err.CORRUPT, "empty") + local fx = byName.ogg_s16 + t:eq(F.detect(fx.data), "flac", "F.detect Ogg FLAC") + local a = F.audio.load(fx.data) + t:check(a and a.frames == fx.frames, "F.audio.load") + local d = F.audio.open(byName.s16_l3.data) + t:check(d and d.frames == byName.s16_l3.frames, "F.audio.open") + local _, se = F.save(a, nil, { format = "flac" }) + t:check(se and se.code == Err.UNSUPPORTED, "F.save flac is read-only here: " .. tostring(se)) +end + +-- a damaged frame is dropped, the rest decodes +do + local src = buffer.fromstring(byName.s16_l5.data) + local len = buffer.len(src) + buffer.writeu8(src, len // 2, bit32.bxor(buffer.readu8(src, len // 2), 0x55)) + local d = open(src) + local total = 0 + while true do + local _, got = d:read(4096) + if got == 0 then + break + end + total += got + end + t:check(total < d.frames and total >= d.frames - 2 * 4096, "one damaged frame dropped: " .. total) +end + +-- fuzz +local samples = {} +for _, name in { "s16_l5", "ogg_s16", "id3", "varblock", "s32_rice2", "u8_mono", "bits4" } do + table.insert(samples, byName[name].data) +end +t:fuzz("open + read + seek", function(b: buffer) + local d = Flac.open(Bytes.reader(b)) + if d then + local guard = 0 + while select(2, d:read(4096)) > 0 and guard < 200 do + guard += 1 + end + d:seek(0.1) + d:read(100) + d:seekSample(d.frames // 2) + d:read(100) + end + return d +end, samples, { mutations = 12, keepHeader = 42 }) +t:fuzz("decode", function(b: buffer) + return Flac.decode(Bytes.reader(b)) +end, samples, { mutations = 6, garbage = 60 }) + +t:done() 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/bench.luau b/tools/bench.luau index 5465ca5..cde94d3 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -1,6 +1,7 @@ -- Throughput (bash tools/bench.sh): codec MB/s under both runtimes. MB/s are of decompressed output, best of n runs. -- Fixtures: tools/fixtures/deflate.py (a 6 MB corpus), tools/fixtures/png.py (1024 x 768 images), tools/fixtures/mp3.py, --- tools/fixtures/opus.py (3 s stereo files; MB/s of f32 output, 48 kHz stereo f32 is 0.384 MB/s of real time). +-- tools/fixtures/opus.py (3 s stereo files; MB/s of f32 output, 48 kHz stereo f32 is 0.384 MB/s of real time), +-- tools/fixtures/flac.py; wav encodes / decodes a generated tone. local Deflate = require("@formats/codecs/Deflate") local Crc32 = require("@formats/core/Crc32") local Bytes = require("@formats/core/Bytes") @@ -13,6 +14,10 @@ local Opus = require("@formats/audio/opus") local OpusCelt = require("@tests/gen/opus_celt_st_128") local OpusSilk = require("@tests/gen/opus_silk_wb_st") local OpusHybrid = require("@tests/gen/opus_hybrid_st") +local Flac = require("@formats/audio/flac") +local FC = require("@tests/gen/flac_cases") +local Wav = require("@formats/audio/wav") +local Types = require("@formats/Types") local runtime = if (_G :: any).jit ~= nil then "luajit" else "luau" @@ -93,4 +98,29 @@ do Vorbis.decode(Bytes.reader(b)) end) print(string.format("%-8s %-30s %8.0fx real time", runtime, "", VB.frames / VB.rate / dt)) +for _, name in { "s16_long", "s24_96k" } do + for _, c in FC do + if c.name == name then + local b = buffer.fromstring(c.data) + local dec = assert(Flac.open(Bytes.reader(b))) + local secs = dec.duration + local dt = bench("flac decode " .. name, 5, dec.frames * dec.channels * 4, function() + Flac.decode(Bytes.reader(b)) + end) + print(string.format("%-8s %-30s %8.0fx real time", runtime, "", secs / dt)) + end + end +end +do + local a = Types.Audio.new(44100, 2, 44100 * 10) + for i = 0, 44100 * 20 - 1 do + buffer.writef32(a.samples, i * 4, math.sin(i * 0.01) * 0.5) + end + bench("wav encode s16 (10 s stereo)", 5, buffer.len(a.samples), function() + Wav.encode(a) + end) + local file = assert(Wav.encode(a)) + bench("wav decode s16 (10 s stereo)", 5, buffer.len(a.samples), function() + Wav.decode(Bytes.reader(file)) + end) end diff --git a/tools/bench.sh b/tools/bench.sh index 814df57..afc7a43 100644 --- a/tools/bench.sh +++ b/tools/bench.sh @@ -3,7 +3,7 @@ cd "$(dirname "$0")/.." || exit 1 LUAU=${LUAU:-$(command -v luau || nix shell nixpkgs#luau -c sh -c 'command -v luau')} LUAJIT=${LUAJIT:-$(command -v luajit || nix shell nixpkgs#luajit -c sh -c 'command -v luajit')} -python3 -I tools/fixtures.py deflate png mp3 opus vorbis > /dev/null || exit 1 +python3 -I tools/fixtures.py deflate png mp3 opus flac vorbis > /dev/null || exit 1 python3 -I tools/build.py luajit > /dev/null || exit 1 "$LUAU" --codegen -O2 tools/bench.luau "$LUAJIT" -e 'package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path' build/luajit/tools/bench.lua 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("> wasted) << wasted + out.append(x) + return out + + +def write_wav(path, ints, ch, rate, bits): + container = (bits + 7) // 8 * 8 + data = bytearray() + for v in ints: + x = v << (container - bits) + if container == 8: + data.append((x + 128) & 255) + else: + data += x.to_bytes(container // 8, "little", signed=True) + guid = b"\x01\x00\x00\x00\x00\x00\x10\x00\x80\x00\x00\xaa\x00\x38\x9b\x71" + fmt = struct.pack("> (container - bits)) + return out + + +def crc_ints(ints): + return zlib.crc32(b"".join(struct.pack(">= 6 + lim >>= 1 + if n <= lim: + break + k = len(out) + 1 + first = ((0xFF00 >> k) & 0xFF) | n + return bytes([first]) + bytes(reversed(out)) + + +def frames_of(data): + """(offset, header_len, end) of each frame of a fixed-blocksize native stream (CRC-validated).""" + p = 4 + while True: + h = data[p] + size = int.from_bytes(data[p + 1:p + 4], "big") + p += 4 + size + if h & 0x80: + break + syncs = [] + for i in range(p, len(data) - 1): + if data[i] == 0xFF and data[i + 1] == 0xF8: + syncs.append(i) + frames, start = [], syncs[0] + k = 1 + while start < len(data): + found = None + for e in syncs[k:] + [len(data)]: + if e > start and crc16(data[start:e - 2]) == int.from_bytes(data[e - 2:e], "big"): + found = e + break + frames.append((start, found)) + k = syncs.index(found) + 1 if found in syncs else len(syncs) + start = found + return p, frames + + +def make_varblock(): + """Frames of two encodes (block 4096 and 1152) spliced every 36864 samples, headers rewritten as variable.""" + ints = signal(2.0, 44100, 2, 16, "music", 4) + wav = os.path.join(TMP, "vb.wav") + write_wav(wav, ints, 2, 44100, 16) + enc = {} + for bs in (4096, 1152): + out = os.path.join(TMP, "vb%d.flac" % bs) + CTX.nix("flac", ["flac", "-s", "-f", "-5", "--no-seektable", "--no-padding", "-b", str(bs), wav, "-o", out]) + enc[bs] = open(out, "rb").read() + first, fa = frames_of(enc[4096]) + _, fb = frames_of(enc[1152]) + out = bytearray(enc[4096][:first]) + sample, use, maxf = 0, 4096, 0 + total = len(ints) // 2 + while sample < total: + frames = fa if use == 4096 else fb + fi = sample // use + for j in range(fi, min(fi + 36864 // use, len(frames))): + a, e = frames[j] + fr = enc[use][a:e] + # old header: 4 bytes, the coded frame number, optional fields; rebuild with the sample number + b0 = fr[4] + nl = 1 if b0 < 0x80 else (2 if b0 < 0xE0 else 3 if b0 < 0xF0 else 4 if b0 < 0xF8 else 5 if b0 < 0xFC else 6) + bscode = fr[2] >> 4 + extra = {6: 1, 7: 2}.get(bscode, 0) + {12: 1, 13: 2, 14: 2}.get(fr[2] & 15, 0) + hlen = 4 + nl + extra + hdr = bytes([0xFF, 0xF9]) + fr[2:4] + utf8num(sample + (j - fi) * use) + fr[4 + nl:hlen] + body = hdr + bytes([crc8(hdr)]) + fr[hlen + 1:-2] + body += crc16(body).to_bytes(2, "big") + out += body + maxf = max(maxf, len(body)) + sample = (fi + min(36864 // use, len(frames) - fi)) * use + use = 1152 if use == 4096 else 4096 + # STREAMINFO: min block 1152, max 4096, frame sizes unknown + out[8:10] = (1152).to_bytes(2, "big") + out[10:12] = (4096).to_bytes(2, "big") + out[12:18] = bytes(6) + path = os.path.join(TMP, "varblock.flac") + open(path, "wb").write(bytes(out)) + emit("varblock", path, 44100, 2, 16, "variable block size: 4096 / 1152 frames spliced, sample-number headers") + + +def ffmpeg(name, secs, rate, ch, bits, args, kind="music"): + wav = os.path.join(TMP, name + ".wav") + out = os.path.join(TMP, name + ".flac") + write_wav(wav, signal(secs, rate, ch, bits, kind, 5), ch, rate, bits) + CTX.nix("ffmpeg", ["ffmpeg", "-v", "error", "-y", "-i", wav] + args + [out]) + emit(name, out, rate, ch, bits, "ffmpeg " + " ".join(args)) + + +def generate(ctx): + global CTX, TMP + CTX = ctx + TMP = tempfile.mkdtemp() + CASES.clear() + for lv in range(9): + flac("s16_l%d" % lv, 0.4, 44100, 2, 16, ["-%d" % lv]) + flac("s16_long", 3.0, 44100, 2, 16, ["-5", "-S", "0.5s"], seed=2, + note="flac -5, 3 s, seek points every 0.5 s (bench + seek)") + png = os.path.join(TMP, "p.png") + open(png, "wb").write(base64.b64decode( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==")) + flac("s16_noseek", 2.0, 44100, 2, 16, ["-6", "--no-seektable", "-T", "ARTIST=Some One", "-T", "TITLE=Test Tone", + "--picture", png], seed=3, + note="no seektable (bisection seek), tags, a picture", tags={"ARTIST": "Some One", "TITLE": "Test Tone"}) + flac("u8_mono", 0.5, 22050, 1, 8, ["-5"]) + flac("s24_96k", 0.3, 96000, 2, 24, ["-8"]) + flac("s24_l0", 0.3, 48000, 2, 24, ["-0"]) + flac("s32", 0.2, 48000, 2, 32, ["-5"]) + flac("s32_l8", 0.2, 48000, 2, 32, ["-8"], kind="noise", note="flac -8, 32-bit noise (verbatim / escapes)") + flac("ch6", 0.3, 48000, 6, 16, ["-5"]) + flac("ch3_24", 0.2, 44100, 3, 24, ["-7"]) + flac("rate37000", 0.4, 37000, 1, 16, ["-5"]) + flac("rate11025", 0.4, 11025, 2, 16, ["-3"]) + flac("rate352800", 0.05, 352800, 2, 24, ["-5", "--lax"]) + flac("rate100001", 0.1, 100001, 1, 16, ["-5", "--lax"], note="a rate only STREAMINFO can hold") + flac("rate7", 30.0, 7, 1, 16, ["-5", "--lax", "-b", "16"], note="7 Hz") + flac("bs17", 0.2, 44100, 1, 16, ["-5", "--lax", "-b", "17"]) + flac("bs4609", 0.5, 44100, 2, 16, ["-8", "--lax", "-b", "4609"]) + flac("bs65535", 1.6, 44100, 2, 16, ["-5", "--lax", "-b", "65535", "-r", "15"]) + flac("lpc32", 0.3, 44100, 2, 16, ["--lax", "-b", "1001", "-l", "32", "-r", "0,8", "-e", "-p"], + note="LPC order 32, block 1001, exhaustive") + flac("bits12", 0.3, 44100, 2, 12, ["-5"]) + flac("bits20", 0.3, 44100, 2, 20, ["-8"]) + flac("bits4", 0.3, 8000, 1, 4, ["-5", "--lax"]) + flac("wasted", 0.3, 44100, 2, 16, ["-5"], wasted=3, note="low 3 bits zero (wasted bits)") + flac("smooth", 0.3, 44100, 2, 24, ["-2"], kind="smooth", note="flac -2, 24-bit pure tones (fixed order 4)") + flac("s32_rice2", 0.2, 48000, 2, 32, ["-5"], kind="loudnoise", note="32-bit tone + noise (Rice2, k > 24)") + make_varblock() + flac("silence", 0.3, 44100, 2, 16, ["-5"], kind="silence") + flac("square", 0.3, 44100, 2, 16, ["-5"], kind="square") + flac("noise16", 0.3, 44100, 2, 16, ["-5"], kind="noise") + flac("ogg_s16", 1.0, 44100, 2, 16, ["-5", "--ogg"], ogg=True, note="Ogg FLAC") + for mode in ("left_side", "right_side", "mid_side", "indep"): + ffmpeg("ff_" + mode, 0.3, 44100, 2, 16, ["-c:a", "flac", "-ch_mode", mode]) + ffmpeg("ff_l12", 0.4, 44100, 2, 16, ["-c:a", "flac", "-compression_level", "12"]) + ffmpeg("ff_s24", 0.3, 48000, 2, 24, ["-c:a", "flac", "-sample_fmt", "s32", "-bits_per_raw_sample", "24", + "-compression_level", "8"]) + ffmpeg("ff_exact", 0.3, 44100, 2, 16, ["-c:a", "flac", "-exact_rice_parameters", "1", "-multi_dim_quant", "1", + "-lpc_type", "cholesky", "-lpc_passes", "2"]) + # an ID3v2 tag in front of fLaC + src = os.path.join(TMP, "s16_l5.flac") + id3 = b"ID3\x04\x00\x00" + bytes([0, 0, 0, 20]) + b"TIT2\x00\x00\x00\x0a\x00\x00\x03hello id3" + emit("id3", src, 44100, 2, 16, "s16_l5 with an ID3v2 tag in front", prefix=id3) + + + ctx.emit("flac_cases", CASES) diff --git a/tools/fixtures/zip.py b/tools/fixtures/zip.py new file mode 100644 index 0000000..3a66642 --- /dev/null +++ b/tools/fixtures/zip.py @@ -0,0 +1,161 @@ +# ZIP fixtures (tools/fixtures.py): containers/Zip + archive/zip. Ported from zip-luau tools/fixtures.py. +# tests/gen/zip_cases.luau generated archives with Python zipfile's view of every entry ({ name, size, crc, method }): +# stored and deflate entries, an archive comment holding a fake end record, data descriptors, +# force_zip64, a hand-built all-ZIP64 archive, 66000 entries (ZIP64 end record), a prefix +# stub, a wrong local extra length, unicode names, empty; plus every .wsz skin in $SKINS_DIR +# when it is set (the Webamp demo skins; not redistributable, so not committed). Archives +# over 1 MB are stored zlib-compressed (dataZ) +import io, os, random, struct, sys, zipfile, zlib + +SKINS = os.environ.get("SKINS_DIR", "") +TEXT = b"".join(b"line %d: the quick brown fox jumps over the lazy dog\n" % i for i in range(3000)) + + +class Unseekable(io.RawIOBase): + def __init__(self): + self.buf = bytearray() + def writable(self): + return True + def write(self, b): + self.buf += b + return len(b) + +def mk(files, comment=b"", stream=False, force64=False): + out = Unseekable() if stream else io.BytesIO() + with zipfile.ZipFile(out, "w") as z: + for name, data, method in files: + zi = zipfile.ZipInfo(name, (2020, 5, 17, 13, 37, 42)) + zi.compress_type = method + if force64: + with z.open(zi, "w", force_zip64=True) as f: + f.write(data) + else: + z.writestr(zi, data) + z.comment = comment + return bytes(out.buf if stream else out.getvalue()) + +def zip64_by_hand(files): + # every size / offset field is 0xFFFFFFFF with the values in ZIP64 extras, plus the ZIP64 end record + locator + local, cd = bytearray(), bytearray() + for name, data in files: + n = name.encode() + c = zlib.compressobj(9, zlib.DEFLATED, -15) + comp = c.compress(data) + c.flush() + crc = zlib.crc32(data) + off = len(local) + lx = struct.pack(" the archive zipfile reads for the expected listing (when zipfile cannot read the real one) + def add(label, data, ref=None): + archives.append((label, data)) + if ref is not None: + REF[label] = ref + + add("basic", mk(basic)) + # zipfile itself takes the fake end record in this comment (it searches for the last signature) + add("comment", mk(basic[:3], comment=b"a comment with a fake end record PK\x05\x06" + b"\0" * 18 + b" and more" * 100), mk(basic[:3])) + add("descriptors", mk(basic[:6], stream=True)) + add("force_zip64", mk(basic[:6], force64=True)) + add("zip64_by_hand", zip64_by_hand([("a.txt", TEXT), ("b/c.bin", rng.randbytes(4000)), ("z.txt", b"")])) + add("prefixed", b"MZ" + b"\x90" * 3000 + mk(basic[:3])) + add("empty", mk([])) + w = bytearray(mk([("x.txt", TEXT, D), ("y.txt", b"why" * 1000, S)])) + struct.pack_into(" 1000000: + c["dataZ"] = zlib.compress(data, 9) # big archives (66000 entries): zlib, inflated by the test + else: + c["data"] = data + out[key].append(c) + ctx.emit("zip_cases", out)