Files
rosetta/src/Formats/containers/Avi/init.luau
T

524 lines
15 KiB
Luau

--!strict
-- containers/Avi: the AVI RIFF form (Microsoft AVI 1.0 + the OpenDML 1.02 extensions). New in formats-luau.
-- Reading: hdrl (avih, strl: strh / strf / strn / indx), every RIFF piece (RIFF AVI + RIFF AVIX ...), and the chunk
-- index of every stream: from the OpenDML super index (indx -> ix## standard / field indexes), else idx1 (offsets
-- relative to the movi list or absolute, detected), else a linear scan of the movi lists (LIST rec included).
-- Writing: AVI 1.0 (avih, strl, LIST movi, idx1) with an OpenDML odml / dmlh header, chunks interleaved as given.
--
-- local avi, err = Avi.read(buf, base, limit)
-- avi.streams[i] = { type = "vids" | "auds" | ..., handler, scale, rate, start, length, sampleSize, strf
-- (buffer), name, chunks = { { offset, size, key } } } -- offsets of the chunk data, absolute
-- local w = Avi.writer({ streams = {...}, avih = {...} }); w:chunk(streamIndex, data, key); local file = w:finish()
--
-- Never throws: malformed data returns nil, Err (a damaged index falls back to scanning).
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 Avi = {}
export type Chunk = { offset: number, size: number, key: boolean }
export type Stream = {
index: number, -- 0-based stream number (the "##" of the chunk ids)
type: string, -- strh fccType: "vids", "auds", "txts", "mids"
handler: string,
flags: number,
scale: number,
rate: number,
start: number,
length: number,
suggestedBufferSize: number,
sampleSize: number,
frame: { number }, -- rcFrame left, top, right, bottom
strf: buffer, -- the format block (BITMAPINFOHEADER / WAVEFORMATEX ...)
name: string?,
chunks: { Chunk },
}
export type File = {
avih: { microSecPerFrame: number, flags: number, totalFrames: number, streams: number, width: number, height: number },
streams: { Stream },
odml: { totalFrames: number }?,
info: { [string]: string },
index: string, -- "odml" | "idx1" | "scan"
}
local function u32(b: buffer, o: number): number
return readu32(b, o)
end
-- chunk walker over [p, limit): calls fn(id, dataOffset, size, listType?) for each chunk (LIST bodies are not
-- entered); returns where it stopped
local function walk(b: buffer, p: number, limit: number, fn: (id: string, data: number, size: number, ltype: string?) -> boolean?): number
while p + 8 <= limit do
local id = readstring(b, p, 4)
local size = u32(b, p + 4)
local data = p + 8
local ltype: string? = nil
if (id == "LIST" or id == "RIFF") and data + 4 <= limit then
ltype = readstring(b, data, 4)
end
if data + size > limit then
size = limit - data
end
if fn(id, data, size, ltype) == false then
return p
end
p = data + size + (size % 2)
end
return p
end
local function streamNumber(id: string): number?
local a, b = string.byte(id, 1, 2)
if not a or not b then
return nil
end
local function hex(c: number): number?
if c >= 48 and c <= 57 then
return c - 48
elseif c >= 65 and c <= 70 then
return c - 55
elseif c >= 97 and c <= 102 then
return c - 87
end
return nil
end
local h, l = hex(a), hex(b)
if h and l then
return h * 16 + l
end
return nil
end
Avi.streamNumber = streamNumber
local function parseStrl(b: buffer, data: number, size: number, index: number): Stream
local s: Stream = {
index = index,
type = "",
handler = "",
flags = 0,
scale = 1,
rate = 1,
start = 0,
length = 0,
suggestedBufferSize = 0,
sampleSize = 0,
frame = { 0, 0, 0, 0 },
strf = buffer.create(0),
chunks = {},
}
local indx: { number }? = nil
walk(b, data + 4, data + size, function(id: string, d: number, n: number): boolean?
if id == "strh" and n >= 48 then
s.type = readstring(b, d, 4)
s.handler = readstring(b, d + 4, 4)
s.flags = u32(b, d + 8)
s.scale = u32(b, d + 20)
s.rate = u32(b, d + 24)
s.start = u32(b, d + 28)
s.length = u32(b, d + 32)
s.suggestedBufferSize = u32(b, d + 36)
s.sampleSize = u32(b, d + 44)
if n >= 56 then
s.frame = { buffer.readi16(b, d + 48), buffer.readi16(b, d + 50), buffer.readi16(b, d + 52), buffer.readi16(b, d + 54) }
end
elseif id == "strf" then
local f = buffer.create(n)
buffer.copy(f, 0, b, d, n)
s.strf = f
elseif id == "strn" then
local str = readstring(b, d, n)
s.name = string.match(str, "^[^%z]*")
elseif id == "indx" and n >= 24 then
indx = { d, n }
end
return nil
end)
;(s :: any)._indx = indx
return s
end
-- an OpenDML index chunk (indx super index or ix## standard index) at d with n bytes: appends chunks to s
local function readIndex(b: buffer, d: number, n: number, s: Stream, limit: number, depth: number): boolean
if n < 24 or depth > 2 then
return false
end
local longsPerEntry = readu16(b, d)
local subType = readu8(b, d + 2)
local indexType = readu8(b, d + 3)
local entries = u32(b, d + 4)
if indexType == 0 then -- AVI_INDEX_OF_INDEXES: { qwOffset, dwSize, dwDuration }
if longsPerEntry ~= 4 then
return false
end
local p = d + 24
for _ = 1, entries do
if p + 16 > d + n then
break
end
local off = u32(b, p) + u32(b, p + 4) * 4294967296
local size = u32(b, p + 8)
p += 16
if off > 0 and off + 8 <= limit then
local sz = math.min(u32(b, off + 4), limit - off - 8)
readIndex(b, off + 8, if size > 0 then math.min(sz, size) else sz, s, limit, depth + 1)
end
end
return #s.chunks > 0
elseif indexType == 1 then -- AVI_INDEX_OF_CHUNKS: base offset, { dwOffset, dwSize } (or field index: 3 longs)
if n < 24 then
return false
end
local base = u32(b, d + 12) + u32(b, d + 16) * 4294967296
local per = if subType == 1 then 12 else 8 -- AVI_INDEX_2FIELD
local p = d + 24
for _ = 1, entries do
if p + per > d + n then
break
end
local off = u32(b, p)
local size = u32(b, p + 4)
p += per
local key = size < 0x80000000
size %= 0x80000000
local at = base + off
if at >= 0 and at + size <= limit then
table.insert(s.chunks, { offset = at, size = size, key = key })
end
end
return true
end
return false
end
-- read(buf, base, limit) -> File | nil, Err
function Avi.read(b: buffer, base: number, limit: number): (File?, Err.Err?)
if limit - base < 12 or readstring(b, base, 4) ~= "RIFF" or readstring(b, base + 8, 4) ~= "AVI " then
return nil, Err.new(Err.CORRUPT, "not an AVI file", base)
end
local file: File = {
avih = { microSecPerFrame = 0, flags = 0, totalFrames = 0, streams = 0, width = 0, height = 0 },
streams = {},
odml = nil,
info = {},
index = "scan",
}
local movis: { { number } } = {} -- { data offset of the 'movi' fourcc, end }
local idx1: { number }? = nil
local hdrl = false
-- every RIFF piece (AVI, then AVIX for OpenDML files)
walk(b, base, limit, function(id: string, d: number, n: number, ltype: string?): boolean?
if id ~= "RIFF" then
return nil
end
walk(b, d + 4, d + n, function(cid: string, cd: number, cn: number, cltype: string?): boolean?
if cid == "LIST" and cltype == "hdrl" and not hdrl then
hdrl = true
local si = 0
walk(b, cd + 4, cd + cn, function(hid: string, hd: number, hn: number, hltype: string?): boolean?
if hid == "avih" and hn >= 40 then
file.avih = {
microSecPerFrame = u32(b, hd),
flags = u32(b, hd + 12),
totalFrames = u32(b, hd + 16),
streams = u32(b, hd + 24),
width = u32(b, hd + 32),
height = u32(b, hd + 36),
}
elseif hid == "LIST" and hltype == "strl" then
table.insert(file.streams, parseStrl(b, hd, hn, si))
si += 1
elseif hid == "LIST" and hltype == "odml" then
walk(b, hd + 4, hd + hn, function(oid: string, od: number, on: number): boolean?
if oid == "dmlh" and on >= 4 then
file.odml = { totalFrames = u32(b, od) }
end
return nil
end)
end
return nil
end)
elseif cid == "LIST" and cltype == "movi" then
table.insert(movis, { cd, cd + cn })
elseif cid == "LIST" and cltype == "INFO" then
walk(b, cd + 4, cd + cn, function(iid: string, idd: number, inn: number): boolean?
file.info[iid] = string.match(readstring(b, idd, inn), "^[^%z]*") or ""
return nil
end)
elseif cid == "idx1" and not idx1 then
idx1 = { cd, cn }
end
return nil
end)
return nil
end)
if not hdrl then
return nil, Err.new(Err.CORRUPT, "no hdrl list")
end
if #file.streams == 0 then
return nil, Err.new(Err.CORRUPT, "no streams")
end
-- 1. OpenDML indexes
local odml = true
for _, s in file.streams do
local ix = (s :: any)._indx
if not ix or not readIndex(b, ix[1], ix[2], s, limit, 0) then
odml = false
end
end
if odml then
file.index = "odml"
else
for _, s in file.streams do
table.clear(s.chunks)
end
-- 2. idx1
local ok = false
if idx1 and movis[1] then
local d, n = idx1[1], idx1[2]
local count = n // 16
local moviBase = movis[1][1] -- the 'movi' fourcc
-- relative or absolute offsets: check the first entry that points at a chunk id
local rel = true
if count > 0 then
local off = u32(b, d + 8)
local ckid = readstring(b, d, 4)
local relAt, absAt = moviBase + off, base + off
if relAt + 4 <= limit and readstring(b, relAt, 4) == ckid then
rel = true
elseif absAt + 4 <= limit and readstring(b, absAt, 4) == ckid then
rel = false
end
end
for k = 0, count - 1 do
local e = d + k * 16
local ckid = readstring(b, e, 4)
local flags = u32(b, e + 4)
local off = u32(b, e + 8)
local size = u32(b, e + 12)
local sn = streamNumber(ckid)
local s = sn and file.streams[sn + 1]
if s and string.sub(ckid, 3, 4) ~= "pc" then
local at = (if rel then moviBase else base) + off + 8
if at + size <= limit then
table.insert(s.chunks, { offset = at, size = size, key = bit32.band(flags, 0x10) ~= 0 })
ok = true
end
end
end
end
if ok then
file.index = "idx1"
else
for _, s in file.streams do
table.clear(s.chunks)
end
-- 3. scan the movi lists
local function scan(d0: number, e0: number)
walk(b, d0, e0, function(id: string, d: number, n: number, ltype: string?): boolean?
if id == "LIST" and ltype == "rec " then
scan(d + 4, d + n)
return nil
end
local sn = streamNumber(id)
local s = sn and file.streams[sn + 1]
if s and string.sub(id, 1, 2) ~= "ix" and string.sub(id, 3, 4) ~= "pc" then
table.insert(s.chunks, { offset = d, size = n, key = true })
end
return nil
end)
end
for _, m in movis do
scan(m[1] + 4, m[2])
end
file.index = "scan"
end
end
for _, s in file.streams do
(s :: any)._indx = nil
end
return file, nil
end
-- ------------------------------------------------------------------------------------------------ writing
export type WStream = {
type: string, -- "vids" | "auds"
handler: string, -- fccHandler (4 chars)
scale: number,
rate: number,
sampleSize: number, -- 0 = every chunk one sample (video, VBR audio)
strf: buffer,
name: string?,
width: number?,
height: number?,
quality: number?,
ckid: string?, -- the chunk id suffix: "dc" (video), "wb" (audio)
}
export type WOptions = {
streams: { WStream },
microSecPerFrame: number,
width: number,
height: number,
software: string?,
}
-- write(opts, chunks) -> buffer: chunks = { { stream (1-based), data: buffer, key: boolean } } in file order
function Avi.write(opts: WOptions, chunks: { { any } }): buffer
local ns = #opts.streams
local lengths = table.create(ns, 0)
local maxChunk = table.create(ns, 0)
local bytes = table.create(ns, 0)
local total = 0
for _, c in chunks do
local si, data = c[1], c[2]
local n = buffer.len(data)
local s = opts.streams[si]
if s.sampleSize > 0 then
lengths[si] += n // s.sampleSize
else
lengths[si] += 1
end
bytes[si] += n
if n > maxChunk[si] then
maxChunk[si] = n
end
total += n + 8 + (n % 2)
end
local frames = 0
for si, s in opts.streams do
if s.type == "vids" and frames == 0 then
frames = lengths[si]
end
end
local w = Bytes.writer(total + 4096 + #chunks * 16)
w:string("RIFF")
local riffSize = w:tell()
w:u32le(0)
w:string("AVI ")
-- hdrl
w:string("LIST")
local hdrlSize = w:tell()
w:u32le(0)
w:string("hdrl")
w:string("avih")
w:u32le(56)
local duration = if opts.microSecPerFrame > 0 then frames * opts.microSecPerFrame / 1e6 else 1
local maxBytes = 0
for si = 1, ns do
maxBytes += bytes[si]
end
w:u32le(math.floor(opts.microSecPerFrame + 0.5))
w:u32le(if duration > 0 then math.floor(maxBytes / duration) else 0)
w:u32le(0) -- padding granularity
w:u32le(0x10 + 0x100) -- AVIF_HASINDEX | AVIF_ISINTERLEAVED
w:u32le(frames)
w:u32le(0) -- initial frames
w:u32le(ns)
local suggested = 0
for si = 1, ns do
suggested = math.max(suggested, maxChunk[si] + 8)
end
w:u32le(suggested)
w:u32le(opts.width)
w:u32le(opts.height)
for _ = 1, 4 do
w:u32le(0)
end
for si, s in opts.streams do
w:string("LIST")
local strlSize = w:tell()
w:u32le(0)
w:string("strl")
w:string("strh")
w:u32le(56)
w:string(s.type)
w:string(s.handler)
w:u32le(0) -- flags
w:u16le(0) -- priority
w:u16le(0) -- language
w:u32le(0) -- initial frames
w:u32le(s.scale)
w:u32le(s.rate)
w:u32le(0) -- start
w:u32le(lengths[si])
w:u32le(maxChunk[si])
w:u32le(if s.quality then s.quality else 0xFFFFFFFF)
w:u32le(s.sampleSize)
w:u16le(0)
w:u16le(0)
w:u16le(s.width or 0)
w:u16le(s.height or 0)
w:string("strf")
w:u32le(buffer.len(s.strf))
w:bytes(s.strf)
if buffer.len(s.strf) % 2 == 1 then
w:u8(0)
end
if s.name then
local nm = s.name .. "\0"
w:string("strn")
w:u32le(#nm)
w:string(nm)
if #nm % 2 == 1 then
w:u8(0)
end
end
w:setU32le(strlSize, w:tell() - strlSize - 4)
end
-- OpenDML extended header (total frames)
w:string("LIST")
w:u32le(16)
w:string("odml")
w:string("dmlh")
w:u32le(4)
w:u32le(frames)
w:setU32le(hdrlSize, w:tell() - hdrlSize - 4)
-- INFO
local sw = (opts.software or "formats-luau") .. "\0"
if #sw % 2 == 1 then
sw ..= "\0"
end
w:string("LIST")
w:u32le(4 + 8 + #sw)
w:string("INFO")
w:string("ISFT")
w:u32le(#sw)
w:string(sw)
-- movi
w:string("LIST")
local moviSize = w:tell()
w:u32le(0)
local moviBase = w:tell()
w:string("movi")
local index = table.create(#chunks)
for _, c in chunks do
local si, data, key = c[1], c[2], c[3]
local s = opts.streams[si]
local id = string.format("%02d", si - 1) .. (s.ckid or (if s.type == "vids" then "dc" else "wb"))
local at = w:tell()
local n = buffer.len(data)
w:string(id)
w:u32le(n)
w:bytes(data)
if n % 2 == 1 then
w:u8(0)
end
table.insert(index, { id, if key then 0x10 else 0, at - moviBase, n })
end
w:setU32le(moviSize, w:tell() - moviSize - 4)
-- idx1
w:string("idx1")
w:u32le(#index * 16)
for _, e in index do
w:string(e[1])
w:u32le(e[2])
w:u32le(e[3])
w:u32le(e[4])
end
w:setU32le(riffSize, w:tell() - 8)
return w:finish()
end
return Avi