Files
rosetta/src/Rosetta/audio/opus/init.luau
T

378 lines
13 KiB
Luau

--!strict
--!optimize 2
-- audio/opus: Ogg Opus (RFC 6716, RFC 7845); absorbed from opus-luau dd2b4e5, a port of the libopus 1.6 decoder (BSD:
-- licenses/libopus-BSD.txt). Supports: every mode / bandwidth / frame size, mapping families 0 / 1 / 255, seeking, PLC;
-- encode CELT only (20 ms, full band, CBR). Not supported: SILK / hybrid encoding, mapping family 3, chained streams.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Ogg = require("@rosetta/containers/Ogg")
local Decoder = require("@rosetta/codecs/audio/Opus/Decoder")
local Packet = require("@rosetta/codecs/audio/Opus/Packet")
local VorbisComment = require("@rosetta/codecs/audio/VorbisComment")
local Pcm = require("@rosetta/codecs/audio/Pcm")
local RangeDecoder = require("@rosetta/codecs/entropy/RangeCoder/Decoder")
local Celt = require("@rosetta/codecs/audio/Opus/Celt")
local Silk = require("@rosetta/codecs/audio/Opus/Silk")
local Encode = require("@rosetta/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/entropy/RangeCoder/Decoder", "codecs/audio/Pcm", "codecs/audio/Resample", "codecs/audio/VorbisComment", "codecs/audio/Opus/CeltEncoder", "codecs/audio/Opus/Decoder", "codecs/audio/Opus/Packet", "codecs/audio/Opus/Celt", "codecs/audio/Opus/Silk" },
caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" }, encodeChannels = 2 },
}
-- ------------------------------------------------------------------------------------------------ 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)
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)
local function parseTags(b: buffer, off: number, size: number): (string, { [string]: string }, { VorbisComment.Field })
if size < 16 or buffer.readstring(b, off, 8) ~= "OpusTags" then
return "", {}, {}
end
local p = off + 8
local e = off + size
local vlen = buffer.readu32(b, p)
p += 4
if p + vlen > e then
return "", {}, {}
end
local vendor = buffer.readstring(b, p, vlen)
p += vlen
local list = {}
if p + 4 <= e then
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
table.insert(list, buffer.readstring(b, p, l))
p += l
end
end
local tags, raw = VorbisComment.tags(list)
return vendor, tags, raw
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
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
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
return Pcm.drain(dec, { format = "opus", channels = dec.sourceChannels, preSkip = dec.preSkip, vendor = dec.vendor, comments = dec.comments, mappingFamily = dec.head.mappingFamily, inputSampleRate = dec.head.inputSampleRate })
end
-- ------------------------------------------------------------------------------------------------ encode
function Opus.encode(value: any, opts: Encode.Options?): (buffer?, Err.Err?)
return Encode.encode(value, opts)
end
-- ------------------------------------------------------------------------------------------------ open
local Stream = {}
Stream.__index = 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
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
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)
if self.order then
Pcm.reorder(out, got * ch * 4, n, ch, self.order)
end
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
end
return out, got
end
function Stream.position(self: any): number
return (self.next - self.preSkip) / SAMPLE_RATE
end
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
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, rawTags = 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,
comments = rawTags,
-- mapping family 1 is in Vorbis channel order; the output is WAVE order (codecs/audio/Pcm)
order = if not downmix and head.mappingFamily == 1 and head.channels > 2 then Pcm.WAVE_FROM_VORBIS[head.channels] else nil,
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