--!strict -- audio/vorbis: Ogg Vorbis (Vorbis I specification, Xiph.Org; RFC 5215 for the Ogg mapping). The decoder is a Luau -- port of stb_vorbis 1.22 (public domain / MIT, licenses/stb_vorbis-LICENSE.txt) on containers/Ogg and codecs/Mdct, -- with libvorbis' sample-exact timing: start trimming from the first page's granule, end trimming from the last -- page's, granule-exact seeking (bisection, then decoding forward to a page boundary to recover the position). -- Supports: decode / open of any channel count (1..255), rates, block sizes 64..8192, floor 1, residues 0 / 1 / 2, -- coupling, sparse / ordered codebooks, lookup types 1 / 2; comment-header tags (lower-cased keys); a packet-level -- decoder (Vorbis.packetDecoder) for Vorbis in Matroska / WebM / MP4. Encode (audio/vorbis/Encode, new code): a basic -- Ogg Vorbis encoder from an Audio or a streamed Decoder (long blocks, floor 1, coupled residue 2, a fixed codebook -- set, quality -1 .. 10). Not supported: floor 0 (Err.UNSUPPORTED, as in stb_vorbis; no encoder has produced it since -- 2000), chained streams (the first logical Vorbis stream is decoded), short blocks in the encoder. -- ------------------------------------------------------------------------------------------------ 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 Setup = require("@formats/audio/vorbis/Setup") local Packet = require("@formats/audio/vorbis/Packet") local Encode = require("@formats/audio/vorbis/Encode") local Pcm = require("@formats/codecs/Pcm") -- ------------------------------------------------------------------------------------------------ contract local Vorbis = { name = "vorbis", category = "audio", extensions = { "ogg", "oga" }, mime = { "audio/ogg", "audio/vorbis" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/Pcm" }, caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255 }, } export type OpenOptions = { verify: boolean?, -- check the Ogg page CRCs (default true) } export type EncodeOptions = { quality: number?, -- -1 .. 10 (default 3): the floor sits 2 * quality - 1 dB under the band energies (8 dB -- less at the top of the spectrum), which sets the residue's quantization step serial: number?, -- the Ogg stream serial number (default 0x464C5541) } -- ------------------------------------------------------------------------------------------------ constants local TAG_KEYS = { tracknumber = "track", description = "comment" } local function tagsOf(comments: { string }): Types.Tags local tags: Types.Tags = {} for _, s in comments do local eq = string.find(s, "=", 1, true) if eq then local k = string.lower(string.sub(s, 1, eq - 1)) local v = string.sub(s, eq + 1) k = TAG_KEYS[k] or k tags[k] = if tags[k] then tags[k] .. "; " .. v else v end end return tags end -- the three headers -> ident, setup, vendor, tags | nil, Err local function headers(h1: any, h2: any, h3: any): (any, any, string?, Types.Tags?, Err.Err?) local id, ierr = Setup.ident(h1.data, h1.offset, h1.size) if not id then return nil, nil, nil, nil, Err.new(Err.CORRUPT, ierr or "bad identification header") end local vendor, comments = Setup.comment(h2.data, h2.offset, h2.size) if not vendor then return nil, nil, nil, nil, Err.new(Err.CORRUPT, "bad comment header") end local setup, serr = Setup.setup(h3.data, h3.offset, h3.size, id) if not setup then local code = if serr == "floor 0" then Err.UNSUPPORTED else Err.CORRUPT return nil, nil, nil, nil, Err.new(code, serr or "bad setup header") end return id, setup, vendor, tagsOf(comments or {}), nil end -- ------------------------------------------------------------------------------------------------ sniff function Vorbis.sniff(r: Bytes.Reader): number if r:remaining() < 35 or r:peek(4) ~= "OggS" then return 0 end local b, p = r.buf, r.pos local nseg = buffer.readu8(b, p + 26) local d = p + 27 + nseg if d + 7 > r.limit then return 0 end return if buffer.readu8(b, d) == 1 and buffer.readstring(b, d + 1, 6) == "vorbis" then 1 else 0 end -- ------------------------------------------------------------------------------------------------ decode function Vorbis.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) local dec, err = Vorbis.open(r, opts) if not dec then return nil, err end local d = dec :: any local ch = d.channels local parts, total = {}, 0 while true do local b, n = d:read(65536) if n == 0 then break end local copy = buffer.create(n * ch * 4) buffer.copy(copy, 0, b, 0, n * ch * 4) table.insert(parts, copy) total += n end local a = Types.Audio.new(d.sampleRate, ch, total) local o = 0 for _, p in parts do buffer.copy(a.samples, o, p) o += buffer.len(p) end a.tags = d.tags a.meta.source = d.source return a, nil end -- ------------------------------------------------------------------------------------------------ encode -- encode(audioOrDecoder, opts?) -> an Ogg Vorbis file | nil, Err function Vorbis.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local src, serr = Pcm.source(value) if not src then return nil, serr end local o: EncodeOptions = opts or {} local q = o.quality or 3 if type(q) ~= "number" or q ~= q or q < -1 or q > 10 then return nil, Err.new(Err.ARG, "quality must be -1 .. 10") end if src.channels > 255 then return nil, Err.new(Err.ARG, "at most 255 channels") end if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate < 1 or src.sampleRate >= 2 ^ 32 then return nil, Err.new(Err.ARG, "the sample rate must be a positive integer") end local serial = o.serial or 0x464C5541 if type(serial) ~= "number" or serial ~= math.floor(serial) or serial < 0 or serial >= 2 ^ 32 then return nil, Err.new(Err.ARG, "serial must be a 32-bit unsigned integer") end local out, msg = Encode.encode(src :: any, { quality = q, vendor = "formats-luau Vorbis encoder", serial = serial }) if not out then return nil, Err.new(Err.CORRUPT, tostring(msg)) end return out, nil end -- ------------------------------------------------------------------------------------------------ open local Stream = {} Stream.__index = Stream -- queue the chunk arrays[first .. first + count - 1] whose first sample has granule g0, trimmed to [lo, hi) local function push(self: any, arrays: { { number } }, g0: number, count: number, hi: number) local lo = math.max(g0, self.startG, self.skipTo) if hi > g0 + count then hi = g0 + count end if hi > lo then table.insert(self.queue, { arrays, lo - g0 + 1, hi - g0, lo }) end end local function copyOut(self: any, count: number): { { number } } local t = table.create(self.channels) for c = 1, self.channels do local src = self.st.out[c] local a = table.create(count, 0) table.move(src, 1, count, 1, a) t[c] = a end return t end -- decode packets until something is queued; false at the end of the stream local function decodeMore(self: any): boolean local reader, st = self.reader, self.st while not self.ended do local p = reader:nextPacket() if p == nil then self.ended = true break end if p.gap then Packet.reset(st) self.syncing, self.pend, self.pendCount = true, {}, 0 end local count = Packet.decode(st, p.data, p.offset, p.size) if count >= 0 then local endG = if p.eos and p.granule >= 0 then p.granule else math.huge if self.syncing then if count > 0 then table.insert(self.pend, { copyOut(self, count), count }) self.pendCount += count end if p.granule >= 0 then -- the position is known again: this packet's output ends at its granule local g = p.granule - self.pendCount if p.eos and self.pendCount > 0 then g = math.max(g, self.pos) -- an end-trimmed last page: keep the running position end for _, c in self.pend do push(self, c[1], g, c[2], endG) g += c[2] end self.pos = g self.syncing, self.pend, self.pendCount = false, {}, 0 end else local g0 = self.pos self.pos += count if count > 0 then push(self, st.out, g0, count, endG) end if p.granule >= 0 and not p.eos then self.pos = p.granule end end if p.eos then self.ended = true end if #self.queue > 0 then return true end end end return #self.queue > 0 end function Stream.read(self: any, n: number, out: buffer?): (buffer, number) local ch = self.channels n = math.max(0, math.floor(n)) local b = if out and buffer.len(out) >= n * ch * 4 then out else buffer.create(n * ch * 4) local got = 0 local writef32 = buffer.writef32 while got < n do local q = self.queue[1] if q == nil then if not decodeMore(self) then break end q = self.queue[1] end local arrays, first, last = q[1], q[2], q[3] local take = math.min(n - got, last - first + 1) for c = 1, ch do local a = arrays[c] local o = got * ch * 4 + (c - 1) * 4 for i = first, first + take - 1 do writef32(b, o, a[i]) o += ch * 4 end end got += take self.next = q[4] + take if first + take > last then table.remove(self.queue, 1) else q[2] = first + take q[4] += take end end if got > 0 then self.skipTo = -math.huge end return b, got end function Stream.position(self: any): number return (self.next - self.startG) / self.sampleRate end -- back to the first audio packet local function restart(self: any) local r = self.reader r:rewind() for _ = 1, 3 do r:nextPacket() end Packet.reset(self.st) self.pos = self.base self.syncing, self.pend, self.pendCount = false, {}, 0 self.ended = false self.queue = {} end function Stream.seek(self: any, seconds: number) local target = self.startG + math.floor(math.max(0, seconds) * self.sampleRate + 0.5) if target ~= target then target = self.startG end if self.lastG >= 0 and target > self.lastG then target = self.lastG end self.skipTo = target self.next = target local r = self.reader local g = target - self.st.n1 for _ = 1, 16 do if g <= self.startG then break end local G = r:seekGranule(g) if G == nil or G < 0 then break end -- decode forward to the next page boundary to learn the exact position Packet.reset(self.st) self.queue = {} self.ended = false self.syncing, self.pend, self.pendCount = true, {}, 0 self.pos = G local ok = false while true do local p = r:nextPacket() if p == nil then break end local count = Packet.decode(self.st, p.data, p.offset, p.size) if count > 0 then table.insert(self.pend, { copyOut(self, count), count }) self.pendCount += count end if p.granule >= 0 then if not p.eos then local g0 = p.granule - self.pendCount for _, c in self.pend do push(self, c[1], g0, c[2], math.huge) g0 += c[2] end self.pos = p.granule self.syncing, self.pend, self.pendCount = false, {}, 0 ok = true end break end end if ok then return end g = G - 1 -- the last page: start one page earlier end restart(self) self.skipTo = target self.next = target end function Vorbis.open(r: any, opts: OpenOptions?): (Types.Decoder?, Err.Err?) local demux, derr = Ogg.open(r, if opts and opts.verify == false then { verify = false } else nil) if not demux then return nil, derr end local serial = demux:find("vorbis") if serial == nil then return nil, Err.new(Err.CORRUPT, "no Vorbis stream in the Ogg file") end local reader = demux:reader(serial) local h1 = reader:nextPacket() if h1 == nil then return nil, Err.new(Err.TRUNCATED, "missing identification header") end local id0, ierr = Setup.ident(h1.data, h1.offset, h1.size) if not id0 then return nil, Err.new(Err.CORRUPT, ierr or "bad identification header") end local h2 = reader:nextPacket() if h2 == nil then return nil, Err.new(Err.TRUNCATED, "missing comment header") end local h2copy = { data = Ogg.copy(h2), offset = 0, size = h2.size } local h3 = reader:nextPacket() if h3 == nil then return nil, Err.new(Err.TRUNCATED, "missing setup header") end local id, setup, vendor, tags, herr = headers(h1, h2copy, h3) if not id then return nil, herr end local st = Packet.new(id, setup) if not st then return nil, Err.new(Err.CORRUPT, "bad block sizes") end -- the granule of the first returned sample: the first granule page minus what its packets return local base = 0 do local prev, sum = 0, 0 while true do local p = reader:nextPacket() if p == nil then break end local bs = Packet.blocksize(st, p.data, p.offset, p.size) if bs > 0 then if prev > 0 then sum += prev // 4 + bs // 4 end prev = bs end if p.granule >= 0 then base = p.granule - sum if p.eos then base = 0 -- one page holds the whole stream: the spec trims its end, not its start end break end end end local info = demux:stream(serial) local lastG = if info and info.lastGranule and info.lastGranule >= 0 then info.lastGranule else -1 local startG = math.max(base, 0) local frames = if lastG >= 0 then math.max(0, lastG - startG) else 0 local rate = id.sampleRate local self = setmetatable({ sampleRate = rate, channels = id.channels, frames = frames, duration = frames / rate, bitrate = if frames > 0 then math.floor(demux.size * 8 / (frames / rate)) else id.bitrateNominal, tags = tags, vendor = vendor, ident = id, source = { format = "vorbis", codec = "vorbis", vendor = vendor, blocksizes = { id.blocksize0, id.blocksize1 }, nominalBitrate = id.bitrateNominal, }, demux = demux, reader = reader, st = st, base = base, startG = startG, lastG = lastG, pos = base, next = startG, skipTo = -math.huge, queue = {}, syncing = false, pend = {}, pendCount = 0, ended = false, }, Stream) restart(self) return self :: any, nil end -- ------------------------------------------------------------------------------------------------ extras -- packetDecoder(ident, comment, setup) -> a decoder of raw Vorbis packets (Matroska / WebM / MP4 carry the three -- headers in their codec private data) | nil, Err. Each argument is a buffer holding one header packet. -- local pd = Vorbis.packetDecoder(h1, h2, h3) -- local n = pd:decode(buf, offset, size) -- frames returned (first packet 0; -1 = not audio); pd.out[ch][1 .. n] -- pd:reset() -- after a seek function Vorbis.packetDecoder(h1: buffer, h2: buffer, h3: buffer): (any, Err.Err?) local function pk(b: buffer): any return { data = b, offset = 0, size = buffer.len(b) } end local id, setup, vendor, tags, err = headers(pk(h1), pk(h2), pk(h3)) if not id then return nil, err end local st = Packet.new(id, setup) if not st then return nil, Err.new(Err.CORRUPT, "bad block sizes") end return { sampleRate = id.sampleRate, channels = id.channels, vendor = vendor, tags = tags, out = st.out, decode = function(_self: any, b: buffer, offset: number, size: number): number if offset < 0 or size < 0 or offset + size > buffer.len(b) then return -1 end return Packet.decode(st, b, offset, size) end, reset = function(_self: any) Packet.reset(st) end, }, nil end return Vorbis