--!strict -- audio/opus/Encode: Ogg Opus writing (RFC 7845) around audio/opus/CeltEncoder: CELT-only packets (TOC config 31: -- full band, 20 ms, code 0), OpusHead (mapping family 0, the pre-skip = the encoder's delay), OpusTags (vendor + -- the tags as Vorbis comments), granule positions with end trimming, pages through containers/Ogg's muxer. Input at -- other rates is resampled to 48 kHz (a Kaiser-windowed sinc; quality enough for a codec input). New in formats-luau. local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Ogg = require("@formats/containers/Ogg") local CeltEncoder = require("@formats/audio/opus/CeltEncoder") local Encode = {} export type Options = { bitrate: number?, -- bits per second (default 64000 per channel; 6000 .. 510000, constant) tags: { [string]: string }?, -- default: the audio's tags vendor: string?, -- OpusTags vendor (default "formats-luau") serial: number?, -- Ogg stream serial (default 0x4f707573) } local floor, sin, pi, sqrt = math.floor, math.sin, math.pi, math.sqrt local function besselI0(x: number): number local sum, term = 1, 1 for k = 1, 60 do term *= (x / (2 * k)) ^ 2 sum += term if term < sum * 1e-15 then break end end return sum end -- resample(src (interleaved f32 buffer), frames, channels, from, to) -> { number } interleaved, frames out local function resample(src: buffer, frames: number, channels: number, from: number, to: number): ({ number }, number) local outFrames = floor(frames * to / from + 0.5) local out = table.create(outFrames * channels, 0) local ratio = to / from local cutoff = 0.97 * math.min(1, ratio) -- of the input Nyquist local half = 16 -- zero crossings each side (at the cutoff) local width = half / cutoff local beta = 8 local i0b = besselI0(beta) local readf32 = buffer.readf32 for j = 0, outFrames - 1 do local t = j / ratio -- the input position local first = math.max(0, floor(t - width) + 1) local last = math.min(frames - 1, floor(t + width)) for c = 0, channels - 1 do local acc, wsum = 0, 0 for i = first, last do local d = i - t local x = d * cutoff local s = if x == 0 then 1 else sin(pi * x) / (pi * x) local r = d / width local w = besselI0(beta * sqrt(math.max(0, 1 - r * r))) / i0b local h = s * w acc += readf32(src, (i * channels + c) * 4) * h wsum += h end out[j * channels + c + 1] = if wsum ~= 0 then acc / wsum else 0 end end return out, outFrames end local TAG_NAMES: { [string]: string } = { title = "TITLE", artist = "ARTIST", album = "ALBUM", albumartist = "ALBUMARTIST", date = "DATE", genre = "GENRE", track = "TRACKNUMBER", tracktotal = "TRACKTOTAL", disc = "DISCNUMBER", comment = "COMMENT", composer = "COMPOSER", } -- encode(audio | decoder, opts) -> buffer | nil, Err function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?) local o = opts or {} if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") end local ch = value.channels if ch ~= 1 and ch ~= 2 then return nil, Err.new(Err.UNSUPPORTED, "the CELT encoder writes mono or stereo (got " .. ch .. " channels)") end local rate = value.sampleRate if rate < 1000 or rate > 768000 then return nil, Err.new(Err.ARG, "bad sample rate " .. tostring(rate)) end local bitrate = o.bitrate or 64000 * ch if type(bitrate) ~= "number" or bitrate < 6000 or bitrate > 510000 then return nil, Err.new(Err.ARG, "bitrate 6000 .. 510000") end -- the whole input as an interleaved f32 buffer local samples: buffer, frames: number if value.kind == "audio" and type(value.samples) == "buffer" then samples, frames = value.samples, value.frames if buffer.len(samples) < frames * ch * 4 then return nil, Err.new(Err.ARG, "audio.samples is shorter than frames * channels") end elseif type(value.read) == "function" then local w = Bytes.writer(65536) frames = 0 local chunk: buffer? = nil while true do local b, n = value:read(16384, chunk) chunk = b if n <= 0 then break end w:bytes(b, 0, n * ch * 4) frames += n end samples = w:finish() else return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") end -- 48 kHz floats local pcm: { number }, n48: number if rate == 48000 then n48 = frames pcm = table.create(frames * ch, 0) for i = 1, frames * ch do pcm[i] = buffer.readf32(samples, (i - 1) * 4) end else pcm, n48 = resample(samples, frames, ch, rate, 48000) end local FRAME = CeltEncoder.FRAME local preSkip = CeltEncoder.DELAY local packets = (n48 + preSkip + FRAME - 1) // FRAME -- zero padding to whole frames for i = n48 * ch + 1, packets * FRAME * ch do pcm[i] = 0 end local bytes = math.clamp(floor(bitrate * FRAME / 48000 / 8), if ch == 2 then 40 else 20, 1275 - 1) local st = CeltEncoder.new(ch) local mux = Ogg.muxer({ pageSize = 4096 }) local s = mux:stream(o.serial or 0x4f707573) -- OpusHead local head = Bytes.writer(19) head:string("OpusHead") head:u8(1) head:u8(ch) head:u16le(preSkip) head:u32le(floor(rate)) head:u16le(0) head:u8(0) s:packet(head:finish(), 0, { flush = true }) -- OpusTags local tags = o.tags or value.tags or {} local tw = Bytes.writer(256) tw:string("OpusTags") local vendor = o.vendor or "formats-luau" tw:u32le(#vendor) tw:string(vendor) local keys = {} for k, v in tags do if type(k) == "string" and type(v) == "string" then table.insert(keys, k) end end table.sort(keys) tw:u32le(#keys) for _, k in keys do local field = (TAG_NAMES[k] or string.upper(k)) .. "=" .. tags[k] tw:u32le(#field) tw:string(field) end s:packet(tw:finish(), 0, { flush = true }) -- audio local toc = 31 * 8 + (if ch == 2 then 4 else 0) for p = 0, packets - 1 do local frame = CeltEncoder.encodeFrame(st, pcm, p * FRAME * ch + 1, ch, bytes) local pkt = buffer.create(bytes + 1) buffer.writeu8(pkt, 0, toc) buffer.copy(pkt, 1, frame, 0, bytes) local last = p == packets - 1 local granule = if last then preSkip + n48 else (p + 1) * FRAME s:packet(pkt, granule, { eos = last }) end return mux:finish(), nil end return Encode