ws-audio: merge ws/absorb (flac, bmp, zip)

This commit is contained in:
4DBug committed 2026-10-31 08:53:32 -05:00
commit 7b5adb2468
125 files changed
+4625 -2

No files matched your search

+36
View File
@@ -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
+238
View File
@@ -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
+605
View File
@@ -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
+220
View File
@@ -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
+383
View File
@@ -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
+131
View File
@@ -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
+668
View File
@@ -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
+247
View File
@@ -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
+424
View File
@@ -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