The decoders / encoders are libraries, not the file format: audio/opus/{Celt, CeltTables, CeltEncoder, Mdct, Packet,
Silk, SilkTables, Decoder} -> codecs/audio/Opus; audio/vorbis/{Codebook, Packet, Setup, Tables} ->
codecs/audio/Vorbis; audio/flac/{Frame, Encode} -> codecs/audio/Flac; audio/mp3/{Core, Tables, Header, Encode2,
Encode3, EncTables, Analysis} -> codecs/audio/Mpa (tools/move.py; code unchanged). Each gets an index init.luau.
The format folders keep the file mapping: Ogg Opus / Ogg Vorbis (headers, granules, seeking, the Vorbis encoder's
Ogg writer), native / Ogg FLAC streams and metadata, ID3 / Xing / the MP3 frame index. docs: STYLE says a codec is
not the format. Full suite: 248 runs pass on both runtimes, lint green.
384 lines
11 KiB
Luau
384 lines
11 KiB
Luau
--!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/codecs/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
|