373 lines
13 KiB
Luau
373 lines
13 KiB
Luau
--!strict
|
|
-- containers/Riff: the RIFF chunk container (RIFF, RIFX big-endian, RF64 / BW64 with the ds64 chunk), read leniently
|
|
-- and written. Shared by audio/wav and the other RIFF forms (AVI, WebP, ANI, ...). The chunk walker comes from
|
|
-- wav-luau fd9a909 (same author, no third-party code); the writer is new.
|
|
--
|
|
-- local f, err = Riff.read(r, { openEnded = { data = true } }) -- r: a core/Bytes Reader or a buffer
|
|
-- f.container, f.form, f.bigEndian -- "RIFF" | "RIFX" | "RF64", "WAVE", false
|
|
-- for _, c in f.chunks do print(c.id, c.offset, c.size, c.avail) end -- offsets are absolute in f.buf
|
|
-- local c = Riff.find(f, "fmt ")
|
|
-- local subs = Riff.list(f, c) -- the sub-chunks of a LIST body (after its type)
|
|
--
|
|
-- local w = Riff.writer("WAVE", { rf64 = "auto" }) -- or bigEndian = true (RIFX)
|
|
-- w:chunk("fmt ", fmtBody) w:chunk("data", samples) w:list("INFO", { { "INAM", "title" } })
|
|
-- local file = w:finish() -- RF64 + ds64 when a size passes 4 GiB
|
|
-- local parts = w:finish({ parts = true }) -- { buffer }: no copy, for files over 1 GiB
|
|
--
|
|
-- Lenient reading (what real files need): an odd-sized chunk without its pad byte is detected; a chunk declared past
|
|
-- the end keeps what is there (avail < size, truncated = true) and ends the walk; for the ids in opts.openEnded a
|
|
-- size of 0 or 0xFFFFFFFF means "up to the end of the file" (streamed writers) and ends the walk; RF64 sizes of
|
|
-- 0xFFFFFFFF come from the ds64 chunk (and its table). Never throws: bad data returns nil, Err.
|
|
local Err = require("@formats/core/Err")
|
|
local Bytes = require("@formats/core/Bytes")
|
|
|
|
local readu8, readu16, readu32, readstring = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readstring
|
|
|
|
local Riff = {}
|
|
|
|
export type Chunk = {
|
|
id: string,
|
|
offset: number, -- absolute offset of the body in the file's buffer
|
|
size: number, -- declared size (ds64-resolved), or what is available for open-ended / truncated chunks
|
|
declared: number, -- the raw size field
|
|
avail: number, -- body bytes present in the file (<= size)
|
|
truncated: boolean, -- declared past the end of the file
|
|
streamed: boolean, -- an open-ended chunk (size 0 / 0xFFFFFFFF up to the end)
|
|
}
|
|
export type File = {
|
|
container: string, -- "RIFF" | "RIFX" | "RF64" (BW64 reads as RF64)
|
|
form: string, -- the form type: "WAVE", "AVI ", "WEBP", ...
|
|
bigEndian: boolean,
|
|
buf: buffer,
|
|
base: number, -- absolute offset of the file's first byte
|
|
limit: number, -- absolute offset past its last byte
|
|
size: number, -- the RIFF size field (ds64-resolved)
|
|
chunks: { Chunk },
|
|
ds64: { riffSize: number, dataSize: number, sampleCount: number, table: { [string]: number } }?,
|
|
}
|
|
export type ReadOptions = {
|
|
openEnded: { [string]: boolean }?, -- chunk ids whose size 0 / 0xFFFFFFFF means "to the end" (wav: data)
|
|
maxChunks: number?, -- stop after this many chunks (default 100000)
|
|
}
|
|
|
|
-- ------------------------------------------------------------------------------------------------ read
|
|
local function printable4(b: buffer, p: number, limit: number): boolean
|
|
if p + 4 > limit then
|
|
return false
|
|
end
|
|
for i = 0, 3 do
|
|
local c = readu8(b, p + i)
|
|
if c < 32 or c > 126 then
|
|
return false
|
|
end
|
|
end
|
|
return true
|
|
end
|
|
|
|
local function u32(b: buffer, o: number, be: boolean): number
|
|
local v = readu32(b, o)
|
|
return if be then bit32.byteswap(v) else v
|
|
end
|
|
|
|
-- sniff(r) -> the form type ("WAVE", ...) when r starts with a RIFF / RIFX / RF64 / BW64 header, else nil
|
|
function Riff.sniff(r: any): string?
|
|
local magic = r:peek(4)
|
|
if magic ~= "RIFF" and magic ~= "RIFX" and magic ~= "RF64" and magic ~= "BW64" then
|
|
return nil
|
|
end
|
|
local form = r:peek(4, 8)
|
|
return if #form == 4 then form else nil
|
|
end
|
|
|
|
-- walk the chunks of [p, limit) into list; returns the list
|
|
local function walk(b: buffer, p: number, limit: number, be: boolean, opts: ReadOptions?, ds64: any, list: { Chunk }): { Chunk }
|
|
local openEnded = opts and opts.openEnded
|
|
local maxChunks = opts and opts.maxChunks or 100000
|
|
while p + 8 <= limit and #list < maxChunks do
|
|
local id = readstring(b, p, 4)
|
|
local declared = u32(b, p + 4, be)
|
|
local size = declared
|
|
local body = p + 8
|
|
local avail = limit - body
|
|
if declared == 0xFFFFFFFF and ds64 then
|
|
if id == "data" then
|
|
size = ds64.dataSize
|
|
elseif ds64.table[id] then
|
|
size = ds64.table[id]
|
|
end
|
|
end
|
|
local c: Chunk = { id = id, offset = body, size = size, declared = declared, avail = math.min(size, avail), truncated = false, streamed = false }
|
|
table.insert(list, c)
|
|
if openEnded and openEnded[id] and (size == 0 or size == 0xFFFFFFFF or size > avail) then
|
|
c.streamed = size == 0 or size == 0xFFFFFFFF
|
|
c.truncated = not c.streamed
|
|
c.size, c.avail = avail, avail
|
|
break
|
|
end
|
|
if size > avail then
|
|
c.truncated = true
|
|
break
|
|
end
|
|
local nextPos = body + size + size % 2
|
|
-- an odd-sized chunk written without its pad byte: the next id starts right after the body
|
|
if size % 2 == 1 and not printable4(b, nextPos, limit) and printable4(b, body + size, limit) then
|
|
nextPos = body + size
|
|
end
|
|
p = nextPos
|
|
end
|
|
return list
|
|
end
|
|
|
|
-- read(src, opts?) -> File | nil, Err. src: a core/Bytes Reader (its range) or a buffer.
|
|
function Riff.read(src: any, opts: ReadOptions?): (File?, Err.Err?)
|
|
local r = if type(src) == "buffer" then Bytes.reader(src) else src
|
|
if type(r) ~= "table" or type(r.buf) ~= "buffer" then
|
|
return nil, Err.new(Err.ARG, "read: expected a buffer or a Reader")
|
|
end
|
|
local b, base, limit = r.buf, r.base, r.limit
|
|
if limit - base < 12 then
|
|
return nil, Err.new(Err.TRUNCATED, "file too short for a RIFF header", base)
|
|
end
|
|
local magic = readstring(b, base, 4)
|
|
if magic ~= "RIFF" and magic ~= "RIFX" and magic ~= "RF64" and magic ~= "BW64" then
|
|
return nil, Err.new(Err.CORRUPT, "not a RIFF / RIFX / RF64 file", base)
|
|
end
|
|
local be = magic == "RIFX"
|
|
local f: File = {
|
|
container = if magic == "BW64" then "RF64" else magic,
|
|
form = readstring(b, base + 8, 4),
|
|
bigEndian = be,
|
|
buf = b,
|
|
base = base,
|
|
limit = limit,
|
|
size = u32(b, base + 4, be),
|
|
chunks = {},
|
|
ds64 = nil,
|
|
}
|
|
-- RF64: the ds64 chunk comes first
|
|
if f.container == "RF64" and base + 20 <= limit and readstring(b, base + 12, 4) == "ds64" then
|
|
local sz = readu32(b, base + 16)
|
|
local o = base + 20
|
|
if sz >= 24 and o + 24 <= limit then
|
|
local d = {
|
|
riffSize = readu32(b, o) + readu32(b, o + 4) * 4294967296,
|
|
dataSize = readu32(b, o + 8) + readu32(b, o + 12) * 4294967296,
|
|
sampleCount = readu32(b, o + 16) + readu32(b, o + 20) * 4294967296,
|
|
table = {} :: { [string]: number },
|
|
}
|
|
if sz >= 28 and o + 28 <= limit then
|
|
local n = readu32(b, o + 24)
|
|
local q = o + 28
|
|
for _ = 1, math.min(n, 1000) do
|
|
if q + 12 > limit or q + 12 > o + sz then
|
|
break
|
|
end
|
|
d.table[readstring(b, q, 4)] = readu32(b, q + 4) + readu32(b, q + 8) * 4294967296
|
|
q += 12
|
|
end
|
|
end
|
|
f.ds64 = d
|
|
if f.size == 0xFFFFFFFF then
|
|
f.size = d.riffSize
|
|
end
|
|
end
|
|
end
|
|
walk(b, base + 12, limit, be, opts, f.ds64, f.chunks)
|
|
return f, nil
|
|
end
|
|
|
|
-- find(file, id, from?) -> the first chunk with that id (after index from), and its index
|
|
function Riff.find(f: File, id: string, from: number?): (Chunk?, number?)
|
|
for i = (from or 0) + 1, #f.chunks do
|
|
if f.chunks[i].id == id then
|
|
return f.chunks[i], i
|
|
end
|
|
end
|
|
return nil, nil
|
|
end
|
|
|
|
-- listType(file, chunk) -> the 4-byte type of a LIST / RIFF chunk ("INFO", "movi", ...) or nil
|
|
function Riff.listType(f: File, c: Chunk): string?
|
|
if c.avail < 4 then
|
|
return nil
|
|
end
|
|
return readstring(f.buf, c.offset, 4)
|
|
end
|
|
|
|
-- list(file, chunk, opts?) -> the sub-chunks of a LIST body (after its 4-byte type)
|
|
function Riff.list(f: File, c: Chunk, opts: ReadOptions?): { Chunk }
|
|
if c.avail < 4 then
|
|
return {}
|
|
end
|
|
return walk(f.buf, c.offset + 4, c.offset + c.avail, f.bigEndian, opts, nil, {})
|
|
end
|
|
|
|
-- body(file, chunk) -> a Reader over the chunk's available body
|
|
function Riff.body(f: File, c: Chunk): Bytes.Reader
|
|
return Bytes.reader(f.buf, c.offset, c.avail)
|
|
end
|
|
|
|
-- u16 / u32 in the file's byte order (for chunk bodies)
|
|
function Riff.u16(f: File, o: number): number
|
|
if f.bigEndian then
|
|
return readu8(f.buf, o) * 256 + readu8(f.buf, o + 1)
|
|
end
|
|
return readu16(f.buf, o)
|
|
end
|
|
function Riff.u32(f: File, o: number): number
|
|
return u32(f.buf, o, f.bigEndian)
|
|
end
|
|
|
|
-- ------------------------------------------------------------------------------------------------ write
|
|
local Writer = {}
|
|
Writer.__index = Writer
|
|
|
|
export type WriteOptions = {
|
|
bigEndian: boolean?, -- RIFX (default false)
|
|
rf64: (boolean | "auto")?, -- true: always RF64; false: never (sizes over 4 GiB are an error); default "auto"
|
|
sampleCount: number?, -- the ds64 sample count (RF64 WAVE: frames)
|
|
rf64Threshold: number?, -- "auto" switches to RF64 when the RIFF size would pass this (default 0xFFFFFFFF)
|
|
}
|
|
|
|
-- writer(form, opts?) -> Writer: collects chunks; finish() lays out the file
|
|
function Riff.writer(form: string, opts: WriteOptions?): any
|
|
return setmetatable({
|
|
form = string.sub(form .. " ", 1, 4),
|
|
be = opts and opts.bigEndian or false,
|
|
rf64 = if opts and opts.rf64 ~= nil then opts.rf64 else "auto",
|
|
sampleCount = opts and opts.sampleCount or 0,
|
|
threshold = opts and opts.rf64Threshold or 0xFFFFFFFF,
|
|
chunks = {} :: { any },
|
|
}, Writer)
|
|
end
|
|
|
|
-- chunk(id, body, offset?, length?): body is a buffer or a string (a range of a buffer with offset / length), or a
|
|
-- list of buffers written one after the other (a data chunk bigger than one buffer)
|
|
function Writer.chunk(self: any, id: string, body: any, offset: number?, length: number?)
|
|
local parts = {}
|
|
local n = 0
|
|
if type(body) == "table" then
|
|
for _, b in body do
|
|
table.insert(parts, { b, 0, buffer.len(b) })
|
|
n += buffer.len(b)
|
|
end
|
|
else
|
|
local b: buffer = if type(body) == "string" then buffer.fromstring(body) else body
|
|
local o = offset or 0
|
|
n = length or (buffer.len(b) - o)
|
|
parts[1] = { b, o, n }
|
|
end
|
|
table.insert(self.chunks, { id = string.sub(id .. " ", 1, 4), parts = parts, length = n })
|
|
end
|
|
|
|
-- list(type, items): a LIST chunk of { id, string-or-buffer } sub-chunks (strings get a NUL terminator, INFO style)
|
|
function Writer.list(self: any, listType: string, items: { { any } })
|
|
local w = Bytes.writer()
|
|
w:string(string.sub(listType .. " ", 1, 4))
|
|
for _, it in items do
|
|
local v = it[2]
|
|
local data: buffer = if type(v) == "string" then buffer.fromstring(v .. "\0") else v
|
|
local n = buffer.len(data)
|
|
w:string(string.sub(it[1] .. " ", 1, 4))
|
|
if self.be then
|
|
w:u32be(n)
|
|
else
|
|
w:u32le(n)
|
|
end
|
|
w:bytes(data)
|
|
if n % 2 == 1 then
|
|
w:u8(0)
|
|
end
|
|
end
|
|
self:chunk("LIST", w:finish())
|
|
end
|
|
|
|
-- finish(opts?) -> buffer | nil, Err; with opts.parts: { buffer } (the header pieces and the chunk bodies, not copied)
|
|
function Writer.finish(self: any, opts: { parts: boolean? }?): (any, Err.Err?)
|
|
local total = 4 -- the form type
|
|
local big = false
|
|
local dataSize = 0
|
|
for _, c in self.chunks do
|
|
total += 8 + c.length + c.length % 2
|
|
if c.length > 0xFFFFFFFE then
|
|
big = true
|
|
end
|
|
if c.id == "data" then
|
|
dataSize = c.length
|
|
end
|
|
end
|
|
local rf64 = self.rf64 == true or (self.rf64 == "auto" and (big or total > self.threshold))
|
|
if not rf64 and (big or total > 0xFFFFFFFF) then
|
|
return nil, Err.new(Err.LIMIT, "over 4 GiB without RF64")
|
|
end
|
|
if rf64 and self.be then
|
|
return nil, Err.new(Err.ARG, "RF64 is little-endian only")
|
|
end
|
|
if rf64 then
|
|
total += 36 -- ds64
|
|
end
|
|
local asParts = opts and opts.parts
|
|
if not asParts and total + 8 > 0x40000000 then
|
|
return nil, Err.new(Err.LIMIT, "the file would not fit in a buffer (1 GiB): use finish({ parts = true })")
|
|
end
|
|
local out: { buffer } = {}
|
|
local w = Bytes.writer(if asParts then 256 else total + 8)
|
|
local function size32(v: number)
|
|
if self.be then
|
|
w:u32be(v)
|
|
else
|
|
w:u32le(v)
|
|
end
|
|
end
|
|
if rf64 then
|
|
w:string("RF64")
|
|
w:u32le(0xFFFFFFFF)
|
|
w:string(self.form)
|
|
w:string("ds64")
|
|
w:u32le(28)
|
|
w:u64le(total)
|
|
w:u64le(dataSize)
|
|
w:u64le(self.sampleCount)
|
|
w:u32le(0) -- no table: only data may be over 4 GiB
|
|
else
|
|
w:string(if self.be then "RIFX" else "RIFF")
|
|
size32(total)
|
|
w:string(self.form)
|
|
end
|
|
for _, c in self.chunks do
|
|
w:string(c.id)
|
|
if rf64 and (c.id == "data" or c.length > 0xFFFFFFFE) then
|
|
w:u32le(0xFFFFFFFF)
|
|
else
|
|
size32(c.length)
|
|
end
|
|
for _, p in c.parts do
|
|
if asParts then
|
|
table.insert(out, w:finish())
|
|
w = Bytes.writer(64)
|
|
if p[2] == 0 and p[3] == buffer.len(p[1]) then
|
|
table.insert(out, p[1])
|
|
else
|
|
local cp = buffer.create(p[3])
|
|
buffer.copy(cp, 0, p[1], p[2], p[3])
|
|
table.insert(out, cp)
|
|
end
|
|
else
|
|
w:bytes(p[1], p[2], p[3])
|
|
end
|
|
end
|
|
if c.length % 2 == 1 then
|
|
w:u8(0)
|
|
end
|
|
end
|
|
if asParts then
|
|
if w:tell() > 0 then
|
|
table.insert(out, w:finish())
|
|
end
|
|
return out, nil
|
|
end
|
|
return w:finish(), nil
|
|
end
|
|
|
|
return Riff
|