--!strict -- audio/opus: Ogg Opus (RFC 6716 codec, RFC 7845 encapsulation). Absorbed from opus-luau dd2b4e5 (same author; a -- port of the libopus 1.6 decoder, BSD: licenses/libopus-BSD.txt): the range decoder, CELT (float), SILK -- (bit-exact fixed point), hybrid, mode transitions, PLC, multistream (mapping families 0, 1, 255). -- Supports: decode of every Opus mode / bandwidth / frame size, mono, stereo and surround (optional stereo downmix, -- opts.stereo), pre-skip, end trimming, output gain, OpusTags, sample-accurate seeking (granule bisection + 80 ms -- pre-roll), damaged files (concealment). Output is always 48 kHz f32. -- Encoding (audio/opus/Encode + CeltEncoder, ws-m4a): a CELT-only fixed-frame encoder (20 ms, full band, constant -- bit rate, mono or dual stereo; other input rates resampled to 48 kHz) writing Ogg Opus with OpusTags. -- Not supported: SILK / hybrid encoding, transients / pitch pre-filter in the encoder, mapping family 3 (ambisonics -- projection), chained streams (the first Opus stream is decoded), CELT pitch PLC (noise PLC only). -- Changes from opus-luau: the injected Ogg demuxer is containers/Ogg; errors are core/Err values; read() takes an -- optional output buffer; decode() fully decodes to an Audio. -- -- local dec, err = Opus.open(Bytes.reader(buf)) -- the Types.Decoder: dec:read(n, out?), dec:seek(s), ... -- local audio = Opus.decode(Bytes.reader(buf)) -- a Types.Audio -- Opus.Decoder.new(channels) + Opus.Decoder.decode(st, buf, off, len, pcm, base, maxFrames) -- raw packets -- local file = Opus.encode(audio, { bitrate = 96000 }) -- Ogg Opus (CELT only) -- ------------------------------------------------------------------------------------------------ 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 Decoder = require("@formats/audio/opus/Decoder") local Packet = require("@formats/audio/opus/Packet") local RangeDecoder = require("@formats/audio/opus/RangeDecoder") local Celt = require("@formats/audio/opus/Celt") local Silk = require("@formats/audio/opus/Silk") local Encode = require("@formats/audio/opus/Encode") -- ------------------------------------------------------------------------------------------------ contract local Opus = { name = "opus", category = "audio", extensions = { "opus" }, mime = { "audio/opus", "audio/ogg" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct" }, caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" } }, } -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { verify: boolean?, -- check the Ogg page CRCs (default true; false decodes damaged files) stereo: boolean?, -- downmix more than 2 channels to stereo (default false; dec.channels is then 2) } -- ------------------------------------------------------------------------------------------------ constants local SAMPLE_RATE = 48000 -- stereo downmix weights for the Vorbis channel orders of mapping family 1 (3 to 8 channels), as in opusfile local DOWNMIX = { [3] = { 0.5858, 0, 0.4142, 0.4142, 0, 0.5858 }, [4] = { 0.4226, 0, 0, 0.4226, 0.366, 0.2114, 0.2114, 0.366 }, [5] = { 0.651, 0, 0.46, 0.46, 0, 0.651, 0.5636, 0.3254, 0.3254, 0.5636 }, [6] = { 0.529, 0, 0.3741, 0.3741, 0, 0.529, 0.4582, 0.2645, 0.2645, 0.4582, 0.3741, 0.3741 }, [7] = { 0.4553, 0, 0.322, 0.322, 0, 0.4553, 0.3943, 0.2277, 0.2277, 0.3943, 0.2788, 0.2788, 0.322, 0.322 }, [8] = { 0.3886, 0, 0.2748, 0.2748, 0, 0.3886, 0.3366, 0.1943, 0.1943, 0.3366, 0.3366, 0.1943, 0.1943, 0.3366, 0.2748, 0.2748 }, } local PREROLL = 3840 -- 80 ms, RFC 7845 section 4.6 local MAX_PACKET = 5760 -- 120 ms export type Head = { version: number, channels: number, preSkip: number, inputSampleRate: number, outputGain: number, -- Q7.8 dB mappingFamily: number, streams: number, coupled: number, mapping: { number }, } -- OpusHead (RFC 7845 section 5.1). Returns the header or nil, message. local function parseHead(b: buffer, off: number, size: number): (Head?, string?) if size < 19 or buffer.readstring(b, off, 8) ~= "OpusHead" then return nil, "not an OpusHead packet" end local version = buffer.readu8(b, off + 8) if bit32.rshift(version, 4) ~= 0 then return nil, "unsupported OpusHead version " .. version end local channels = buffer.readu8(b, off + 9) if channels < 1 then return nil, "OpusHead: zero channels" end local head: Head = { version = version, channels = channels, preSkip = buffer.readu16(b, off + 10), inputSampleRate = buffer.readu32(b, off + 12), outputGain = buffer.readi16(b, off + 16), mappingFamily = buffer.readu8(b, off + 18), streams = 1, coupled = channels - 1, mapping = {}, } if head.mappingFamily == 0 then if channels > 2 then return nil, "OpusHead: mapping family 0 with more than 2 channels" end head.mapping = if channels == 2 then { 0, 1 } else { 0 } else if head.mappingFamily == 3 then return nil, "unsupported channel mapping family 3 (projection)" end if size < 21 + channels then return nil, "OpusHead: truncated channel mapping table" end head.streams = buffer.readu8(b, off + 19) head.coupled = buffer.readu8(b, off + 20) if head.streams < 1 or head.coupled > head.streams or head.streams + head.coupled > 255 then return nil, "OpusHead: bad stream counts" end for c = 0, channels - 1 do local m = buffer.readu8(b, off + 21 + c) if m ~= 255 and m >= head.streams + head.coupled then return nil, "OpusHead: bad channel mapping" end head.mapping[c + 1] = m end end return head, nil end -- OpusTags (RFC 7845 section 5.2): vendor string and a table of lower-cased field names to values (repeated -- fields joined with "; "). local function parseTags(b: buffer, off: number, size: number): (string, { [string]: string }) local tags = {} if size < 16 or buffer.readstring(b, off, 8) ~= "OpusTags" then return "", tags end local p = off + 8 local e = off + size local vlen = buffer.readu32(b, p) p += 4 if p + vlen > e then return "", tags end local vendor = buffer.readstring(b, p, vlen) p += vlen if p + 4 > e then return vendor, tags end local n = buffer.readu32(b, p) p += 4 for _ = 1, n do if p + 4 > e then break end local l = buffer.readu32(b, p) p += 4 if p + l > e then break end local s = buffer.readstring(b, p, l) p += l 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) tags[k] = if tags[k] then tags[k] .. "; " .. v else v end end return vendor, tags end Opus.Decoder = Decoder Opus.Packet = Packet Opus.RangeDecoder = RangeDecoder Opus.Celt = Celt Opus.Silk = Silk Opus.parseHead = parseHead Opus.parseTags = parseTags Opus.SAMPLE_RATE = SAMPLE_RATE -- ------------------------------------------------------------------------------------------------ sniff -- 1 when the file starts with an Ogg page whose first packet is an OpusHead function Opus.sniff(r: Bytes.Reader): number if r:peek(4) ~= "OggS" then return 0 end local nseg = r:peekU8(26) if nseg < 1 then return 0 end return if r:peek(8, 27 + nseg) == "OpusHead" then 1 else 0 end -- ------------------------------------------------------------------------------------------------ decode -- decode(r, opts?) -> Audio | nil, Err: the whole stream (48 kHz f32) function Opus.decode(r: any, opts: OpenOptions?): (Types.Audio?, Err.Err?) local dec, err = Opus.open(r, opts) if not dec then return nil, err end local ch = dec.channels local a = Types.Audio.new(SAMPLE_RATE, ch, dec.frames) local total = 0 while total < dec.frames do local pcm, n = dec:read(math.min(65536, dec.frames - total)) if n == 0 then break end buffer.copy(a.samples, total * ch * 4, pcm, 0, n * ch * 4) total += n end if total < dec.frames then -- a truncated file: keep what decoded local s = buffer.create(total * ch * 4) buffer.copy(s, 0, a.samples, 0, total * ch * 4) a.samples = s a.frames = total end a.tags = dec.tags a.meta.source = { format = "opus", channels = dec.sourceChannels, preSkip = dec.preSkip, vendor = dec.vendor, mappingFamily = dec.head.mappingFamily, inputSampleRate = dec.head.inputSampleRate } return a, nil end -- ------------------------------------------------------------------------------------------------ encode -- encode(audio | decoder, opts?) -> Ogg Opus buffer | nil, Err (CELT only; see audio/opus/Encode) function Opus.encode(value: any, opts: Encode.Options?): (buffer?, Err.Err?) return Encode.encode(value, opts) end -- ------------------------------------------------------------------------------------------------ open local Stream = {} Stream.__index = Stream -- Decodes the next packet into the pending buffer. Returns false at the end of the stream. local function decodeNext(self: any): boolean local p = self.demux:nextPacket(self.serial) if p == nil then return false end local n if p.size > 0 then n = Decoder.decodeMultistream(self.ms, p.data, p.offset, p.size, self.pend, 1, MAX_PACKET) else n = -1 end if n < 0 then -- corrupt or empty packet: conceal for its nominal duration local dur = if p.size > 0 then Packet.samples(p.data, p.offset, p.size) else -1 if dur <= 0 then dur = self.lastDuration end n = Decoder.decodeMultistream(self.ms, nil, 0, 0, self.pend, 1, dur) if n < 0 then n = dur for i = 1, n * self.channels do self.pend[i] = 0 end end end self.lastDuration = n self.pendStart = self.decoded self.pendLen = n self.pendPos = 0 self.decoded += n return true end -- dec:read(maxFrames, out?) -> buffer of interleaved f32 samples, frames read (0 at the end of the stream). out (if -- given and big enough) is filled instead of a new buffer. function Stream.read(self: any, maxFrames: number, into: buffer?): (buffer, number) local ch = self.channels local mf = if type(maxFrames) == "number" and maxFrames == maxFrames then maxFrames else 0 local want = math.max(0, math.min(math.floor(mf), self.endSample - self.next)) local reuse = into ~= nil and buffer.len(into) >= want * ch * 4 local out = if reuse then into :: buffer else buffer.create(want * ch * 4) local got = 0 local gain = self.gain while got < want do if self.pendPos >= self.pendLen then if not decodeNext(self) then break end end -- skip decoded samples before the next wanted one (pre-skip, seek pre-roll) local s = self.pendStart + self.pendPos if s < self.next then self.pendPos = math.min(self.pendLen, self.pendPos + (self.next - s)) continue end local n = math.min(self.pendLen - self.pendPos, want - got) if self.downmix then Decoder.writeDownmix(self.pend, self.pendPos * self.sourceChannels, n, self.sourceChannels, self.downmix, gain, out, got * 8) else Decoder.writeF32(self.pend, self.pendPos * ch, n * ch, gain, out, got * ch * 4) end self.pendPos += n got += n self.next += n end if got < want then if not reuse then local trimmed = buffer.create(got * ch * 4) buffer.copy(trimmed, 0, out, 0, got * ch * 4) out = trimmed end self.endSample = self.next -- the stream ended early (truncated file) end return out, got end -- current playback position in seconds function Stream.position(self: any): number return (self.next - self.preSkip) / SAMPLE_RATE end -- seek to a time in seconds (clamped to the stream): granule bisection with 80 ms pre-roll function Stream.seek(self: any, seconds: number) local sec = if type(seconds) == "number" and seconds == seconds then seconds else 0 local p = math.floor(math.max(0, math.min(sec, 1e12)) * SAMPLE_RATE + 0.5) p = math.min(p, self.frames) local target = p + self.preSkip -- decoded-sample index of the wanted sample Decoder.resetMultistream(self.ms) self.pendLen, self.pendPos = 0, 0 local g = target - PREROLL + self.startGranule local start = -1 if g > self.startGranule then start = self.demux:seekGranule(self.serial, g) or -1 end if start < 0 then self.demux:rewind(self.serial) self.demux:nextPacket(self.serial) -- OpusHead self.demux:nextPacket(self.serial) -- OpusTags self.decoded = 0 else self.decoded = start - self.startGranule end self.pendStart = self.decoded self.next = target end -- open(r, opts?) -> Decoder | nil, Err (r: a core/Bytes Reader, or a buffer) function Opus.open(r: any, opts: OpenOptions?): (any, 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("opus") if serial == nil then return nil, Err.new(Err.CORRUPT, "no Opus stream in the Ogg file") end local hp = demux:nextPacket(serial) if hp == nil then return nil, Err.new(Err.TRUNCATED, "missing OpusHead") end local head, herr = parseHead(hp.data, hp.offset, hp.size) if not head then return nil, Err.new(if string.find(herr or "", "unsupported", 1, true) then Err.UNSUPPORTED else Err.CORRUPT, herr or "bad OpusHead") end local tp = demux:nextPacket(serial) if tp == nil then return nil, Err.new(Err.TRUNCATED, "missing OpusTags") end local vendor, tags = parseTags(tp.data, tp.offset, tp.size) -- granule of the first audio sample: first page granule minus the packets that end on it local startGranule = 0 local sum = 0 while true do local p = demux:nextPacket(serial) if p == nil then break end local d = if p.size > 0 then Packet.samples(p.data, p.offset, p.size) else 0 sum += math.max(d, 0) if p.granule ~= -1 then startGranule = math.max(0, p.granule - sum) break end end demux:rewind(serial) demux:nextPacket(serial) demux:nextPacket(serial) local info = demux:stream(serial) local last = if info and info.lastGranule and info.lastGranule >= 0 then info.lastGranule else startGranule local frames = math.max(0, last - startGranule - head.preSkip) local downmix = nil if opts and opts.stereo and head.channels > 2 then downmix = DOWNMIX[head.channels] if downmix == nil or head.mappingFamily ~= 1 then -- unknown layout: every channel to both sides, equally downmix = table.create(head.channels * 2, 1 / head.channels) end end local self = setmetatable({ demux = demux, serial = serial, head = head, vendor = vendor, tags = tags, sampleRate = SAMPLE_RATE, channels = if downmix then 2 else head.channels, sourceChannels = head.channels, downmix = downmix, frames = frames, duration = frames / SAMPLE_RATE, bitrate = if frames > 0 then math.floor(demux.size * 8 / (frames / SAMPLE_RATE)) else 0, preSkip = head.preSkip, startGranule = startGranule, gain = 10 ^ (head.outputGain / (20 * 256)), ms = Decoder.newMultistream(head.channels, head.streams, head.coupled, head.mapping), pend = table.create(MAX_PACKET * head.channels, 0), pendStart = 0, pendLen = 0, pendPos = 0, decoded = 0, -- decoded-sample index of the next packet's first sample next = head.preSkip, -- decoded-sample index of the next sample read() returns endSample = head.preSkip + frames, lastDuration = 960, }, Stream) return self, nil end return Opus