diff --git a/docs/FORMATS.md b/docs/FORMATS.md index a1b8835..56ef2f2 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -12,7 +12,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | audio | flac | .flac .oga | yes | - | streaming: true, depths: 4, 8, 12, 16, 20, 24, 32, ogg: true, seek: true | `tests/audio/flac.luau` | | audio | m4a | .m4a .m4b .m4r .aac.mp4 | yes | yes | codecs: "aac", "alac", encodeCodecs: "alac", tags: true, streaming: true | `tests/audio/m4a.luau` | | audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | - | streaming: true, seek: true, layers: 1, 2, 3, channels: 2 | `tests/audio/mp3.luau` | -| audio | opus | .opus | yes | - | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000 | `tests/audio/opus.luau` | +| audio | opus | .opus | yes | yes | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000, encodeModes: "celt" | `tests/audio/opus.luau` | | audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` | | archive | zip | .zip .wsz | yes | yes | methods: "store", "deflate", zip64: true | `tests/archive/zip.luau` | | playlist | m3u | .m3u .m3u8 | yes | yes | hls: true | `tests/playlist/m3u.luau` | diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index f3a49b2..b1c5c7b 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -16,6 +16,7 @@ | `src/Formats/playlist/` (m3u, pls; xspf is new), `src/Formats/codecs/Url/`, `src/Formats/codecs/Text/` | playlist-luau 3fc7fd3 (same author), written from RFC 3986 / RFC 8216 | no licence chosen yet; no third-party code | | `src/Formats/codecs/Aac/Tables.luau` | the Huffman codebooks, scalefactor band offsets and TNS limits of ISO/IEC 14496-3 (Annex 4.A), transcribed mechanically from FFmpeg's `libavcodec/aactab.c` (tables of the standard only; no FFmpeg code) | FFmpeg is LGPL-2.1-or-later; the tables are the standard's data | | `src/Formats/codecs/Aac/`, `codecs/Alac/`, `codecs/Mdct/`, `containers/IsoBmff/`, `audio/m4a`, `audio/aac`, `audio/caf` | written for this library from ISO/IEC 14496-3 / 14496-12 / 23008-12, Apple's ALAC and CAF specifications | no third-party code | +| `src/Formats/audio/opus/CeltEncoder.luau`, `src/Formats/audio/opus/RangeEncoder.luau` | the encoder side of libopus 1.6 (celt_encoder.c, entenc.c, quant_bands.c, laplace.c, rate.c, bands.c, vq.c, cwrs.c), ported to mirror the absorbed decoder; analysis simplified (ws-m4a) | libopus BSD 3-clause: [libopus-BSD.txt](libopus-BSD.txt) | | `tests/fixtures/pngsuite/` | PngSuite by Willem van Schaik | [PngSuite-LICENSE.txt](PngSuite-LICENSE.txt) | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index b20418f..689c4e2 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -104,8 +104,8 @@ local list: { Entry } = { path = "audio/opus", extensions = { "opus" }, mime = { "audio/opus", "audio/ogg" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" }, - caps = { decode = true, encode = false, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 } }, + 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" } }, load = function() return require("@formats/audio/opus") end, diff --git a/src/Formats/audio/opus/CeltEncoder.luau b/src/Formats/audio/opus/CeltEncoder.luau new file mode 100644 index 0000000..7c8225a --- /dev/null +++ b/src/Formats/audio/opus/CeltEncoder.luau @@ -0,0 +1,1078 @@ +--!strict +--!native +--!optimize 2 +-- audio/opus/CeltEncoder: a fixed-frame CELT encoder (RFC 6716 section 5.3): 20 ms frames (LM 3), full band, constant +-- bit rate, long MDCTs only (no transient detection), no pitch pre-filter, normal spreading, default allocation trim, +-- mono, or stereo as mid / side per band (the angle, intensity when it has no bits; dual L / R stereo on request). The bitstream side is a port of the libopus 1.6 encoder paths +-- (celt_encoder.c, quant_bands.c, laplace.c, rate.c, bands.c, vq.c, cwrs.c; BSD: licenses/libopus-BSD.txt) that +-- mirror audio/opus/Celt's decoder step for step; the analysis is simplified. The MDCT is codecs/Mdct. +-- Never throws. +local RE = require("@formats/audio/opus/RangeEncoder") +local T = require("@formats/audio/opus/CeltTables") +local Mdct = require("@formats/codecs/Mdct") + +local CeltEncoder = {} + +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift +local min, max, sqrt, floor, cos, log, atan2 = math.min, math.max, math.sqrt, math.floor, math.cos, math.log, math.atan2 +local encBitLogp, encIcdf, encBits, encUint, encEncode, encEncodeBin = RE.bitLogp, RE.icdf, RE.bits, RE.uint, RE.encode, RE.encodeBin +local tell, tellFrac = RE.tell, RE.tellFrac + +local NB_EBANDS = 21 +local OVERLAP = 120 +local SHORT_MDCT = 120 +local BITRES = 3 +local MAX_FINE_BITS = 8 +local FINE_OFFSET = 21 +local QTHETA_OFFSET = 4 +local PREEMPH = 0.85000610 +local LM = 3 -- 20 ms frames +local M = 8 +local N = 960 + +local EB = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100 } +local ALLOC = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 90, 80, 75, 69, 63, 56, 49, 40, 34, 29, 20, 18, 10, 0, 0, 0, 0, 0, 0, 0, 0, + 110, 100, 90, 84, 78, 71, 65, 58, 51, 45, 39, 32, 26, 20, 12, 0, 0, 0, 0, 0, 0, + 118, 110, 103, 93, 86, 80, 75, 70, 65, 59, 53, 47, 40, 31, 23, 15, 4, 0, 0, 0, 0, + 126, 119, 112, 104, 95, 89, 83, 78, 72, 66, 60, 54, 47, 39, 32, 25, 17, 12, 1, 0, 0, + 134, 127, 120, 114, 103, 97, 91, 85, 78, 72, 66, 60, 54, 47, 41, 35, 29, 23, 16, 10, 1, + 144, 137, 130, 124, 113, 107, 101, 95, 88, 82, 76, 70, 64, 57, 51, 45, 39, 33, 26, 15, 1, + 152, 145, 138, 132, 123, 117, 111, 105, 98, 92, 86, 80, 74, 67, 61, 55, 49, 43, 36, 20, 1, + 162, 155, 148, 142, 133, 127, 121, 115, 108, 102, 96, 90, 84, 77, 71, 65, 59, 53, 46, 30, 1, + 172, 165, 158, 152, 143, 137, 131, 125, 118, 112, 106, 100, 94, 87, 81, 75, 69, 63, 56, 45, 20, + 200, 200, 200, 200, 200, 200, 200, 200, 198, 193, 188, 183, 178, 173, 168, 163, 158, 153, 148, 129, 104, +} +local NB_ALLOC_VECTORS = 11 +local LOG2_FRAC_TABLE = { 0, 8, 13, 16, 19, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 32, 33, 34, 34, 35, 36, 36, 37, 37 } +local LOGN = T.logN400 +local CACHE_INDEX = T.cache_index50 +local CACHE_BITS = T.cache_bits50 +local CACHE_CAPS = T.cache_caps50 +local E_PROB = T.e_prob_model +local E_MEANS = { + 6.437500, 6.250000, 5.750000, 5.312500, 5.062500, 4.812500, 4.500000, 4.375000, 4.875000, 4.687500, + 4.562500, 4.437500, 4.875000, 4.625000, 4.312500, 4.500000, 4.375000, 4.625000, 4.750000, 4.437500, + 3.750000, +} +local PRED_COEF = { 29440 / 32768, 26112 / 32768, 21248 / 32768, 16384 / 32768 } +local BETA_COEF = { 30147 / 32768, 22282 / 32768, 12124 / 32768, 6554 / 32768 } +local BETA_INTRA = 4915 / 32768 +local TF_SELECT = { 0, -2, 0, -3, 3, 0, 1, -1 } -- LM 3 +local TRIM_ICDF = { 126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0 } +local SPREAD_ICDF = { 25, 23, 2, 0 } +local SMALL_ENERGY_ICDF = { 2, 1, 0 } +local EXP2_TABLE8 = { 16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048 } +local SPREAD_NORMAL = 2 +local SPREAD_FACTOR = { 15, 10, 5 } + +-- the MDCT window (the decoder's) and plan +local WINDOW = table.create(OVERLAP, 0) +for i = 0, OVERLAP - 1 do + local s = math.sin(0.5 * math.pi * (i + 0.5) / OVERLAP) + WINDOW[i + 1] = math.sin(0.5 * math.pi * s * s) +end +local PLAN = Mdct.new(2 * N) :: Mdct.Plan +-- forward scale matching the decoder's backward MDCT (calibrated against audio/opus/Mdct: tests/audio/opus_encode) +local MDCT_SCALE = 2 / N + +-- PVQ codebook sizes U(n, k), flat: U[n * UK + k + 1] +local UK = 177 +local U = table.create(UK * UK, 0) +U[1] = 1 +for n = 1, UK - 1 do + for k = 1, UK - 1 do + U[n * UK + k + 1] = U[(n - 1) * UK + k + 1] + U[n * UK + k] + U[(n - 1) * UK + k] + end +end +local function pvqU(n: number, k: number): number + return U[n * UK + k + 1] +end + +local function imin(a: number, b: number): number + return if a < b then a else b +end +local function imax(a: number, b: number): number + return if a > b then a else b +end +local function tdiv(a: number, b: number): number + local q = a / b + return if q >= 0 then floor(q) else -floor(-q) +end +local function fracMul16(a: number, b: number): number + return (16384 + a * b) // 32768 +end +local function bitexactCos(x: number): number + local x2 = (4096 + x * x) // 8192 + x2 = (32767 - x2) + fracMul16(x2, (-7651 + fracMul16(x2, (8277 + fracMul16(-626, x2))))) + return 1 + x2 +end +local function bitexactLog2tan(isin: number, icos: number): number + local lc = RE.ilog(icos) + local ls = RE.ilog(isin) + icos = icos * 2 ^ (15 - lc) + isin = isin * 2 ^ (15 - ls) + return (ls - lc) * 2048 + fracMul16(isin, fracMul16(isin, -2597) + 7932) - fracMul16(icos, fracMul16(icos, -2597) + 7932) +end + +-- ------------------------------------------------------------------------------------------------ energy +-- ec_laplace_encode: returns the value actually coded (clamped in the flat tail) +local function laplaceEncode(enc: RE.Enc, value: number, fs: number, decay: number): number + local fl = 0 + local val = value + if val ~= 0 then + local s = if val < 0 then -1 else 0 + val = if val < 0 then -val else val + fl = fs + fs = ((32768 - 32 - fs) * (16384 - decay)) // 32768 -- ec_laplace_get_freq1 + local i = 1 + while fs > 0 and i < val do + fs *= 2 + fl += fs + 2 + fs = (fs * decay) // 32768 + i += 1 + end + if fs == 0 then + local ndiMax = 32768 - fl + 1 - 1 + ndiMax = rshift(ndiMax - s, 1) + local di = imin(val - i, ndiMax - 1) + fl += (2 * di + 1 + s) + fs = imin(1, 32768 - fl) + value = if s ~= 0 then -(i + di) else i + di + else + fs += 1 + if s == 0 then + fl += fs + end + end + end + encEncodeBin(enc, fl, fl + fs, 15) + return value +end + +export type State = { + channels: number, + oldBandE: { number }, -- the decoder's view (2 * 21) + preMem: { number }, + inMem: { { number } }, -- the last OVERLAP pre-emphasised samples per channel + frames: number, + X: { { number } }, -- per channel 960 normalised coefficients + bandLogE: { number }, + bandE: { number }, -- linear band amplitudes (intensity stereo weights) + error: { number }, + work: { number }, + tmp: { number }, + iy: { number }, + remaining: number, + spread: number, + dual: boolean, -- stereo: L / R coded independently (default false: mid / side) +} + +-- new(channels) -> State +function CeltEncoder.new(channels: number): State + local inMem = {} + local X = {} + for c = 1, channels do + inMem[c] = table.create(OVERLAP, 0) + X[c] = table.create(N, 0) + end + return { + channels = channels, + oldBandE = table.create(2 * NB_EBANDS, 0), + preMem = table.create(channels, 0), + inMem = inMem, + frames = 0, + X = X, + bandLogE = table.create(2 * NB_EBANDS, 0), + bandE = table.create(2 * NB_EBANDS, 0), + error = table.create(2 * NB_EBANDS, 0), + work = table.create(2 * N, 0), + tmp = table.create(2 * N, 0), + iy = table.create(256, 0), + remaining = 0, + spread = SPREAD_NORMAL, + dual = false, + } +end + +local function quantCoarseEnergy(st: State, intra: boolean, enc: RE.Enc, C: number, budget: number, nbBytes: number) + local oldE, bandLogE, err = st.oldBandE, st.bandLogE, st.error + local probBase = LM * 84 + (if intra then 42 else 0) + local coef, beta + if intra then + coef, beta = 0, BETA_INTRA + else + coef, beta = PRED_COEF[LM + 1], BETA_COEF[LM + 1] + end + local maxDecay = min(16, nbBytes / 8) + local prev0, prev1 = 0, 0 + for i = 0, NB_EBANDS - 1 do + for c = 0, C - 1 do + local k = c * NB_EBANDS + i + 1 + local x = bandLogE[k] + local e = max(-9, oldE[k]) + local prev = if c == 0 then prev0 else prev1 + local f = x - coef * e - prev + local qi = floor(0.5 + f) + local decayBound = max(-28, oldE[k]) - maxDecay + if qi < 0 and x < decayBound then + qi += tdiv(decayBound - x, 1) + if qi > 0 then + qi = 0 + end + end + local t = tell(enc) + local bitsLeft = budget - t - 3 * C * (NB_EBANDS - i) + if i ~= 0 and bitsLeft < 30 then + if bitsLeft < 24 then + qi = imin(1, qi) + end + if bitsLeft < 16 then + qi = imax(-1, qi) + end + end + if budget - t >= 15 then + local pi = 2 * imin(i, 20) + qi = laplaceEncode(enc, qi, E_PROB[probBase + pi + 1] * 128, E_PROB[probBase + pi + 2] * 64) + elseif budget - t >= 2 then + qi = imax(-1, imin(qi, 1)) + encIcdf(enc, if qi < 0 then 1 else 2 * qi, SMALL_ENERGY_ICDF, 2) + elseif budget - t >= 1 then + qi = imin(0, qi) + encBitLogp(enc, qi ~= 0, 1) + else + qi = -1 + end + err[k] = f - qi + oldE[k] = coef * e + prev + qi + prev = prev + qi - beta * qi + if c == 0 then + prev0 = prev + else + prev1 = prev + end + end + end +end + +local function quantFineEnergy(st: State, fineQuant: { number }, enc: RE.Enc, C: number) + local oldE, err = st.oldBandE, st.error + for i = 0, NB_EBANDS - 1 do + local extra = fineQuant[i + 1] + if extra <= 0 then + continue + end + if tell(enc) + C * extra > enc.storage * 8 then + continue + end + local frac = 2 ^ extra + for c = 0, C - 1 do + local k = c * NB_EBANDS + i + 1 + local q2 = floor((err[k] + 0.5) * frac) + q2 = math.clamp(q2, 0, frac - 1) + encBits(enc, q2, extra) + local offset = (q2 + 0.5) * 2 ^ (14 - extra) * (1 / 16384) - 0.5 + oldE[k] += offset + err[k] -= offset + end + end +end + +local function quantEnergyFinalise(st: State, fineQuant: { number }, finePriority: { number }, bitsLeft: number, enc: RE.Enc, C: number) + local oldE, err = st.oldBandE, st.error + for prio = 0, 1 do + local i = 0 + while i < NB_EBANDS and bitsLeft >= C do + if fineQuant[i + 1] >= MAX_FINE_BITS or finePriority[i + 1] ~= prio then + i += 1 + continue + end + for c = 0, C - 1 do + local k = c * NB_EBANDS + i + 1 + local q2 = if err[k] < 0 then 0 else 1 + encBits(enc, q2, 1) + local offset = (q2 - 0.5) * 2 ^ (14 - fineQuant[i + 1] - 1) * (1 / 16384) + oldE[k] += offset + err[k] -= offset + bitsLeft -= 1 + end + i += 1 + end + end +end + +-- ------------------------------------------------------------------------------------------------ allocation +local function bits2pulses(bandI: number, lm: number, bits: number): number + local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1] + local lo, hi = 0, CACHE_BITS[base + 1] + bits -= 1 + for _ = 1, 6 do + local mid = rshift(lo + hi + 1, 1) + if CACHE_BITS[base + mid + 1] >= bits then + hi = mid + else + lo = mid + end + end + local loBits = if lo == 0 then -1 else CACHE_BITS[base + lo + 1] + if bits - loBits <= CACHE_BITS[base + hi + 1] - bits then + return lo + end + return hi +end + +local function pulses2bits(bandI: number, lm: number, pulses: number): number + if pulses == 0 then + return 0 + end + local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1] + return CACHE_BITS[base + pulses + 1] + 1 +end + +local function getPulses(i: number): number + if i < 8 then + return i + end + return lshift(8 + band(i, 7), rshift(i, 3) - 1) +end + +-- clt_compute_allocation (encoder side): keeps every band it can, no intensity stereo, dual stereo for C == 2 +local function computeAllocation(offsets: { number }, cap: { number }, allocTrim: number, total: number, + pulses: { number }, ebits: { number }, finePriority: { number }, C: number, enc: RE.Enc, wantDual: boolean) + local start, endb = 0, NB_EBANDS + total = imax(total, 0) + local len = NB_EBANDS + local skipStart = start + local skipRsv = if total >= 8 then 8 else 0 + total -= skipRsv + local intensityRsv, dualStereoRsv = 0, 0 + if C == 2 then + intensityRsv = LOG2_FRAC_TABLE[endb - start + 1] + if intensityRsv > total then + intensityRsv = 0 + else + total -= intensityRsv + dualStereoRsv = if total >= 8 then 8 else 0 + total -= dualStereoRsv + end + end + local bits1, bits2, thresh, trimOffset = {}, {}, {}, {} + for j = start, endb - 1 do + local w = EB[j + 2] - EB[j + 1] + thresh[j + 1] = imax(C * 8, (3 * w * 2 ^ LM * 8) // 16) + trimOffset[j + 1] = (C * w * (allocTrim - 5 - LM) * (endb - j - 1) * 2 ^ (LM + BITRES)) // 64 + if w * 2 ^ LM == 1 then + trimOffset[j + 1] -= C * 8 + end + end + local lo, hi = 1, NB_ALLOC_VECTORS - 1 + repeat + local done = false + local psum = 0 + local mid = rshift(lo + hi, 1) + for j = endb - 1, start, -1 do + local Nw = EB[j + 2] - EB[j + 1] + local bitsj = (C * Nw * ALLOC[mid * len + j + 1] * 2 ^ LM) // 4 + if bitsj > 0 then + bitsj = imax(0, bitsj + trimOffset[j + 1]) + end + bitsj += offsets[j + 1] + if bitsj >= thresh[j + 1] or done then + done = true + psum += imin(bitsj, cap[j + 1]) + elseif bitsj >= C * 8 then + psum += C * 8 + end + end + if psum > total then + hi = mid - 1 + else + lo = mid + 1 + end + until lo > hi + hi = lo + lo -= 1 + for j = start, endb - 1 do + local Nw = EB[j + 2] - EB[j + 1] + local bits1j = (C * Nw * ALLOC[lo * len + j + 1] * 2 ^ LM) // 4 + local bits2j = if hi >= NB_ALLOC_VECTORS then cap[j + 1] else (C * Nw * ALLOC[hi * len + j + 1] * 2 ^ LM) // 4 + if bits1j > 0 then + bits1j = imax(0, bits1j + trimOffset[j + 1]) + end + if bits2j > 0 then + bits2j = imax(0, bits2j + trimOffset[j + 1]) + end + if lo > 0 then + bits1j += offsets[j + 1] + end + bits2j += offsets[j + 1] + if offsets[j + 1] > 0 then + skipStart = j + end + bits2j = imax(0, bits2j - bits1j) + bits1[j + 1] = bits1j + bits2[j + 1] = bits2j + end + -- interp_bits2pulses + local bits = pulses + local allocFloor = C * 8 + local stereo = if C > 1 then 1 else 0 + local logM = LM * 8 + lo, hi = 0, 64 + for _ = 1, 6 do + local mid = rshift(lo + hi, 1) + local psum = 0 + local done = false + for j = endb - 1, start, -1 do + local tmp = bits1[j + 1] + (mid * bits2[j + 1]) // 64 + if tmp >= thresh[j + 1] or done then + done = true + psum += imin(tmp, cap[j + 1]) + elseif tmp >= allocFloor then + psum += allocFloor + end + end + if psum > total then + hi = mid + else + lo = mid + end + end + local psum = 0 + local done = false + for j = endb - 1, start, -1 do + local tmp = bits1[j + 1] + (lo * bits2[j + 1]) // 64 + if tmp < thresh[j + 1] and not done then + if tmp >= allocFloor then + tmp = allocFloor + else + tmp = 0 + end + else + done = true + end + tmp = imin(tmp, cap[j + 1]) + bits[j + 1] = tmp + psum += tmp + end + local codedBands = endb + while true do + local j = codedBands - 1 + if j <= skipStart then + total += skipRsv + break + end + local left = total - psum + local percoeff = left // (EB[codedBands + 1] - EB[start + 1]) + left -= (EB[codedBands + 1] - EB[start + 1]) * percoeff + local rem = imax(left - (EB[j + 1] - EB[start + 1]), 0) + local bandWidth = EB[codedBands + 1] - EB[j + 1] + local bandBits = bits[j + 1] + percoeff * bandWidth + rem + if bandBits >= imax(thresh[j + 1], allocFloor + 8) then + -- keep every band that can be coded: signal "no more skipping" + encBitLogp(enc, true, 1) + break + end + psum -= bits[j + 1] + intensityRsv + if intensityRsv > 0 then + intensityRsv = LOG2_FRAC_TABLE[j - start + 1] + end + psum += intensityRsv + if bandBits >= allocFloor then + psum += allocFloor + bits[j + 1] = allocFloor + else + bits[j + 1] = 0 + end + codedBands -= 1 + end + local intensity, dualStereo = 0, false + if intensityRsv > 0 then + intensity = codedBands -- no intensity stereo + encUint(enc, intensity - start, codedBands + 1 - start) + end + if intensity <= start then + total += dualStereoRsv + dualStereoRsv = 0 + end + if dualStereoRsv > 0 then + dualStereo = wantDual + encBitLogp(enc, dualStereo, 1) + end + local left = total - psum + local percoeff = left // (EB[codedBands + 1] - EB[start + 1]) + left -= (EB[codedBands + 1] - EB[start + 1]) * percoeff + for j = start, codedBands - 1 do + bits[j + 1] += percoeff * (EB[j + 2] - EB[j + 1]) + end + for j = start, codedBands - 1 do + local tmp = imin(left, EB[j + 2] - EB[j + 1]) + bits[j + 1] += tmp + left -= tmp + end + local balance = 0 + local j = start + while j < codedBands do + local N0 = EB[j + 2] - EB[j + 1] + local Nw = N0 * 2 ^ LM + local bit = bits[j + 1] + balance + local excess + if Nw > 1 then + excess = imax(bit - cap[j + 1], 0) + bits[j + 1] = bit - excess + local den = C * Nw + (if C == 2 and Nw > 2 and not dualStereo and j < intensity then 1 else 0) + local NClogN = den * (LOGN[j + 1] + logM) + local offset = (NClogN // 2) - den * FINE_OFFSET + if Nw == 2 then + offset += (den * 8) // 4 + end + if bits[j + 1] + offset < den * 2 * 8 then + offset += NClogN // 4 + elseif bits[j + 1] + offset < den * 3 * 8 then + offset += NClogN // 8 + end + local eb = imax(0, bits[j + 1] + offset + den * 4) + eb = (eb // den) // 8 + if C * eb > (bits[j + 1] // 8) then + eb = (bits[j + 1] // 2 ^ stereo) // 8 + end + eb = imin(eb, MAX_FINE_BITS) + finePriority[j + 1] = if eb * (den * 8) >= bits[j + 1] + offset then 1 else 0 + bits[j + 1] -= C * eb * 8 + ebits[j + 1] = eb + else + excess = imax(0, bit - C * 8) + bits[j + 1] = bit - excess + ebits[j + 1] = 0 + finePriority[j + 1] = 1 + end + if excess > 0 then + local extraFine = imin(excess // 2 ^ (stereo + BITRES), MAX_FINE_BITS - ebits[j + 1]) + ebits[j + 1] += extraFine + local extraBits = extraFine * C * 8 + finePriority[j + 1] = if extraBits >= excess - balance then 1 else 0 + excess -= extraBits + end + balance = excess + j += 1 + end + while j < endb do + ebits[j + 1] = (bits[j + 1] // 2 ^ stereo) // 8 + bits[j + 1] = 0 + finePriority[j + 1] = if ebits[j + 1] < 1 then 1 else 0 + j += 1 + end + return codedBands, balance, intensity, dualStereo +end + +-- ------------------------------------------------------------------------------------------------ PVQ +-- icwrs: the index of the pulse vector iy[1..n] +local function icwrs(n: number, iy: { number }): number + local j = n -- 1-based position of _y[n - 1] + local i = if iy[j] < 0 then 1 else 0 + local k = math.abs(iy[j]) + repeat + j -= 1 + local nn = n - (j - 1) -- _n - j with 0-based j + i += pvqU(nn, k) + k += math.abs(iy[j]) + if iy[j] < 0 then + i += pvqU(nn, k + 1) + end + until j <= 1 + return i +end + +local function expRotation1(X: { number }, xo: number, len: number, stride: number, c: number, s: number) + local ms = -s + local p = xo + 1 + for _ = 0, len - stride - 1 do + local x1 = X[p] + local x2 = X[p + stride] + X[p + stride] = c * x2 + s * x1 + X[p] = c * x1 + ms * x2 + p += 1 + end + p = xo + len - 2 * stride + for _ = len - 2 * stride - 1, 0, -1 do + local x1 = X[p] + local x2 = X[p + stride] + X[p + stride] = c * x2 + s * x1 + X[p] = c * x1 + ms * x2 + p -= 1 + end +end + +-- exp_rotation(X, len, dir = 1, stride, K, spread): the encoder's spreading rotation +local function expRotation(X: { number }, xo: number, len: number, stride: number, K: number, spread: number) + if 2 * K >= len or spread == 0 then + return + end + local factor = SPREAD_FACTOR[spread] + local gain = len / (len + factor * K) + local theta = 0.5 * (gain * gain) + local c = cos(0.5 * math.pi * theta) + local s = cos(0.5 * math.pi * (1 - theta)) + local stride2 = 0 + if len >= 8 * stride then + stride2 = 1 + while (stride2 * stride2 + stride2) * stride + rshift(stride, 2) < len do + stride2 += 1 + end + end + len = len // stride + for i = 0, stride - 1 do + local x = xo + i * len + expRotation1(X, x, len, 1, c, -s) + if stride2 ~= 0 then + expRotation1(X, x, len, stride2, s, -c) + end + end +end + +-- op_pvq_search: the K-pulse vector closest to X[xo + 1 .. xo + n] into iy[1..n] +local function pvqSearch(X: { number }, xo: number, n: number, K: number, iy: { number }, y: { number }, absx: { number }) + local sign = y -- reuse: y holds 2 * |pulses| during the search, signs kept in absx's sign + local xy, yy = 0, 0 + local pulsesLeft = K + for j = 1, n do + local v = X[xo + j] + absx[j] = if v < 0 then -v else v + sign[j] = 0 + iy[j] = 0 + end + if K > rshift(n, 1) then + local sum = 0 + for j = 1, n do + sum += absx[j] + end + if not (sum > 1e-15 and sum < 64) then + absx[1] = 1 + for j = 2, n do + absx[j] = 0 + end + sum = 1 + end + local rcp = (K + 0.8) / sum + for j = 1, n do + local p = floor(rcp * absx[j]) + iy[j] = p + yy += p * p + xy += absx[j] * p + sign[j] = 2 * p + pulsesLeft -= p + end + end + if pulsesLeft > n + 3 then + yy += pulsesLeft * pulsesLeft + pulsesLeft * sign[1] + iy[1] += pulsesLeft + pulsesLeft = 0 + end + for _ = 1, pulsesLeft do + yy += 1 + local best = 1 + local rxy = xy + absx[1] + local bestNum = rxy * rxy + local bestDen = yy + sign[1] + for j = 2, n do + rxy = xy + absx[j] + local num = rxy * rxy + local den = yy + sign[j] + if bestDen * num > den * bestNum then + bestDen, bestNum, best = den, num, j + end + end + xy += absx[best] + yy += sign[best] + sign[best] += 2 + iy[best] += 1 + end + for j = 1, n do + if X[xo + j] < 0 then + iy[j] = -iy[j] + end + end +end + +local SCRATCH_Y = table.create(256, 0) +local SCRATCH_A = table.create(256, 0) +local ROT = table.create(256, 0) + +local function algQuant(st: State, X: { number }, xo: number, n: number, K: number, enc: RE.Enc) + -- rotate a copy (the original band stays for nothing else, but keep it intact) + for j = 1, n do + ROT[j] = X[xo + j] + end + expRotation(ROT, 0, n, 1, K, st.spread) + local iy = st.iy + pvqSearch(ROT, 0, n, K, iy, SCRATCH_Y, SCRATCH_A) + encUint(enc, icwrs(n, iy), pvqU(n, K) + pvqU(n, K + 1)) +end + +-- ------------------------------------------------------------------------------------------------ bands +local function computeQn(n: number, b: number, offset: number, pulseCap: number): number + local N2 = 2 * n - 1 + local qb = tdiv(b + N2 * offset, N2) + qb = imin(b - pulseCap - 32, qb) + qb = imin(64, qb) + if qb < 4 then + return 1 + end + local qn = rshift(EXP2_TABLE8[band(qb, 7) + 1], 14 - rshift(qb, 3)) + return lshift(rshift(qn + 1, 1), 1) +end + +-- quant_partition (encoder, B = 1, mono): returns nothing (no resynthesis) +local function quantPartition(st: State, bandI: number, X: { number }, xo: number, n: number, b: number, lm: number, enc: RE.Enc) + local split = false + if lm ~= -1 and n > 2 then + local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1] + split = b > CACHE_BITS[base + CACHE_BITS[base + 1] + 1] + 12 + end + if split then + n = rshift(n, 1) + local yo = xo + n + lm -= 1 + -- compute_theta (mono split, B0 = 1: triangular pdf) + local pulseCap = LOGN[bandI + 1] + lm * 8 + local offset = (pulseCap // 2) - QTHETA_OFFSET + local qn = computeQn(n, b, offset, pulseCap) + local t0 = tellFrac(enc) + local itheta = 0 + if qn ~= 1 then + local emid, eside = 1e-15, 1e-15 + for j = 1, n do + emid += X[xo + j] * X[xo + j] + eside += X[yo + j] * X[yo + j] + end + local it = floor(0.5 + 16384 * 0.63662 * atan2(sqrt(eside), sqrt(emid))) + itheta = (it * qn + 8192) // 16384 + local h = rshift(qn, 1) + local ft = (h + 1) * (h + 1) + local fs = if itheta <= h then itheta + 1 else qn + 1 - itheta + local fl = if itheta <= h then rshift(itheta * (itheta + 1), 1) else ft - rshift((qn + 1 - itheta) * (qn + 2 - itheta), 1) + encEncode(enc, fl, fl + fs, ft) + itheta = (itheta * 16384) // qn + end + local qalloc = tellFrac(enc) - t0 + b -= qalloc + local delta + if itheta == 0 then + delta = -16384 + elseif itheta == 16384 then + delta = 16384 + else + local imid = bitexactCos(itheta) + local iside = bitexactCos(16384 - itheta) + delta = fracMul16((n - 1) * 128, bitexactLog2tan(iside, imid)) + end + local mbits = imax(0, imin(b, tdiv(b - delta, 2))) + local sbits = b - mbits + st.remaining -= qalloc + local rebalance = st.remaining + if mbits >= sbits then + quantPartition(st, bandI, X, xo, n, mbits, lm, enc) + rebalance = mbits - (rebalance - st.remaining) + if rebalance > 24 and itheta ~= 0 then + sbits += rebalance - 24 + end + quantPartition(st, bandI, X, yo, n, sbits, lm, enc) + else + quantPartition(st, bandI, X, yo, n, sbits, lm, enc) + rebalance = sbits - (rebalance - st.remaining) + if rebalance > 24 and itheta ~= 16384 then + mbits += rebalance - 24 + end + quantPartition(st, bandI, X, xo, n, mbits, lm, enc) + end + else + local q = bits2pulses(bandI, lm, b) + local currBits = pulses2bits(bandI, lm, q) + st.remaining -= currBits + while st.remaining < 0 and q > 0 do + st.remaining += currBits + q -= 1 + currBits = pulses2bits(bandI, lm, q) + st.remaining -= currBits + end + if q ~= 0 then + algQuant(st, X, xo, n, getPulses(q), enc) + end + end +end + +-- quant_band_stereo (encoder, N > 2, B = 1): the mid / side angle (step pdf), then mid and side as mono bands; +-- qn == 1 falls back to intensity stereo (with the inversion bit when there is room) +local function quantBandStereo(st: State, i: number, n: number, xo: number, b: number, enc: RE.Enc) + local L, R = st.X[1], st.X[2] + local pulseCap = LOGN[i + 1] + LM * 8 + local offset = (pulseCap // 2) - QTHETA_OFFSET + local qn = computeQn(n, b, offset, pulseCap) + -- stereo_itheta: the angle between mid and side energies + local emid, eside = 1e-15, 1e-15 + for j = 1, n do + local m = 0.5 * L[xo + j] + 0.5 * R[xo + j] + local sd = 0.5 * L[xo + j] - 0.5 * R[xo + j] + emid += m * m + eside += sd * sd + end + local itheta = floor(0.5 + 16384 * 0.63662 * atan2(sqrt(eside), sqrt(emid))) + local t0 = tellFrac(enc) + local function intensityStereo() + local left, right = st.bandE[i + 1], st.bandE[NB_EBANDS + i + 1] + local norm = 1e-15 + sqrt(1e-15 + left * left + right * right) + local a1, a2 = left / norm, right / norm + for j = 1, n do + L[xo + j] = a1 * L[xo + j] + a2 * R[xo + j] + end + end + if qn ~= 1 then + itheta = (itheta * qn + 8192) // 16384 + local p0 = 3 + local x0 = qn // 2 + local ft = p0 * (x0 + 1) + x0 + if itheta <= x0 then + encEncode(enc, p0 * itheta, p0 * (itheta + 1), ft) + else + encEncode(enc, (itheta - 1 - x0) + (x0 + 1) * p0, (itheta - x0) + (x0 + 1) * p0, ft) + end + itheta = (itheta * 16384) // qn + if itheta == 0 then + intensityStereo() + else + -- stereo_split: mid / side + for j = 1, n do + local l = 0.70710678 * L[xo + j] + local r = 0.70710678 * R[xo + j] + L[xo + j] = l + r + R[xo + j] = r - l + end + end + else + local inv = itheta > 8192 + if inv then + for j = 1, n do + R[xo + j] = -R[xo + j] + end + end + intensityStereo() + if b > 16 and st.remaining > 16 then + encBitLogp(enc, inv, 2) + end + itheta = 0 + end + local qalloc = tellFrac(enc) - t0 + b -= qalloc + local delta + if itheta == 0 then + delta = -16384 + elseif itheta == 16384 then + delta = 16384 + else + local imid = bitexactCos(itheta) + local iside = bitexactCos(16384 - itheta) + delta = fracMul16((n - 1) * 128, bitexactLog2tan(iside, imid)) + end + local mbits = imax(0, imin(b, tdiv(b - delta, 2))) + local sbits = b - mbits + st.remaining -= qalloc + local rebalance = st.remaining + if mbits >= sbits then + quantPartition(st, i, L, xo, n, mbits, LM, enc) + rebalance = mbits - (rebalance - st.remaining) + if rebalance > 24 and itheta ~= 0 then + sbits += rebalance - 24 + end + quantPartition(st, i, R, xo, n, sbits, LM, enc) + else + quantPartition(st, i, R, xo, n, sbits, LM, enc) + rebalance = sbits - (rebalance - st.remaining) + if rebalance > 24 and itheta ~= 16384 then + mbits += rebalance - 24 + end + quantPartition(st, i, L, xo, n, mbits, LM, enc) + end +end + +-- quant_all_bands (encoder): mono, dual stereo or mid / side stereo +local function quantAllBands(st: State, C: number, pulses: { number }, dualStereo: boolean, totalBits: number, + balance: number, enc: RE.Enc, codedBands: number, intensity: number) + for i = 0, NB_EBANDS - 1 do + local xo = M * EB[i + 1] + local nb = M * EB[i + 2] - M * EB[i + 1] + local t = tellFrac(enc) + if i ~= 0 then + balance -= t + end + local remainingBits = totalBits - t - 1 + st.remaining = remainingBits + local b + if i <= codedBands - 1 then + local currBalance = tdiv(balance, imin(3, codedBands - i)) + b = imax(0, imin(16383, imin(remainingBits + 1, pulses[i + 1] + currBalance))) + else + b = 0 + end + if dualStereo and i == intensity then + dualStereo = false + end + if C == 2 and dualStereo then + quantPartition(st, i, st.X[1], xo, nb, b // 2, LM, enc) + quantPartition(st, i, st.X[2], xo, nb, b // 2, LM, enc) + elseif C == 2 then + quantBandStereo(st, i, nb, xo, b, enc) + else + quantPartition(st, i, st.X[1], xo, nb, b, LM, enc) + end + balance += pulses[i + 1] + t + end +end + +-- ------------------------------------------------------------------------------------------------ frame +-- encodeFrame(st, pcm, base, stride, nbBytes) -> buffer: one CELT frame of nbBytes from 960 samples per channel +-- (pcm[base + k * stride + c], floats -1 .. 1, interleaved) +function CeltEncoder.encodeFrame(st: State, pcm: { number }, base: number, stride: number, nbBytes: number): buffer + local C = st.channels + local work, tmp = st.work, st.tmp + local silent = true + -- pre-emphasis, the windowed 1920-sample MDCT input, band energies, normalisation + for c = 1, C do + local inMem = st.inMem[c] + local m = st.preMem[c] + -- tmp[1..1080] = the last 120 pre-emphasised samples + this frame's 960 + for k = 1, OVERLAP do + tmp[k] = inMem[k] + end + for k = 0, N - 1 do + local x = pcm[base + k * stride + c - 1] * 32768 + if x ~= 0 then + silent = false + end + tmp[OVERLAP + k + 1] = x - m + m = PREEMPH * x + end + st.preMem[c] = m + for k = 1, OVERLAP do + inMem[k] = tmp[N + k] + end + local q = 420 -- (2N - (N + OVERLAP)) / 2 zeros at each end + for k = 1, q do + work[k] = 0 + work[2 * N - k + 1] = 0 + end + for k = 1, OVERLAP do + work[q + k] = tmp[k] * WINDOW[k] + work[q + N + k] = tmp[N + k] * WINDOW[OVERLAP - k + 1] + end + for k = OVERLAP + 1, N do + work[q + k] = tmp[k] + end + local X = st.X[c] + Mdct.forward(PLAN, work, 1, X, 1, 1, MDCT_SCALE) + for i = 0, NB_EBANDS - 1 do + local a, z = M * EB[i + 1] + 1, M * EB[i + 2] + local s = 1e-27 + for k = a, z do + s += X[k] * X[k] + end + local E = sqrt(s) + st.bandE[(c - 1) * NB_EBANDS + i + 1] = E + st.bandLogE[(c - 1) * NB_EBANDS + i + 1] = log(E) / log(2) - E_MEANS[i + 1] + local g = 1 / (1e-27 + E) + for k = a, z do + X[k] *= g + end + end + end + local enc = RE.new(nbBytes) + local totalBits = nbBytes * 8 + local oldE = st.oldBandE + -- silence + if silent then + encBitLogp(enc, true, 15) + enc.nbits_total += totalBits - tell(enc) + RE.done(enc) + for i = 1, 2 * NB_EBANDS do + oldE[i] = -28 + end + st.frames += 1 + return enc.buf + end + encBitLogp(enc, false, 15) + if tell(enc) + 16 <= totalBits then + encBitLogp(enc, false, 1) -- no post-filter + end + if tell(enc) + 3 <= totalBits then + encBitLogp(enc, false, 3) -- not transient + end + local intra = st.frames == 0 + if tell(enc) + 3 <= totalBits then + encBitLogp(enc, intra, 3) + else + intra = false + end + if C == 1 then + for i = 1, NB_EBANDS do + oldE[i] = max(oldE[i], oldE[NB_EBANDS + i]) + end + end + quantCoarseEnergy(st, intra, enc, C, totalBits, nbBytes) + -- tf_encode: no changes + do + local budget = totalBits + local tt = tell(enc) + local logp = 4 + if tt + logp + 1 <= budget then + budget -= 1 + end + for _ = 0, NB_EBANDS - 1 do + if tt + logp <= budget then + encBitLogp(enc, false, logp) + tt = tell(enc) + end + logp = 5 + end + -- tf_select is only coded when it changes something: not for LM 3 without changes + local _ = TF_SELECT + end + if tell(enc) + 4 <= totalBits then + encIcdf(enc, st.spread, SPREAD_ICDF, 5) + end + local cap = {} + for i = 0, NB_EBANDS - 1 do + local Nw = (EB[i + 2] - EB[i + 1]) * 2 ^ LM + cap[i + 1] = rshift((CACHE_CAPS[NB_EBANDS * (2 * LM + C - 1) + i + 1] + 64) * C * Nw, 2) + end + local offsets = table.create(NB_EBANDS, 0) + local total8 = totalBits * 8 + local t = tellFrac(enc) + for i = 0, NB_EBANDS - 1 do + if t + 6 * 8 < total8 and 0 < cap[i + 1] then + encBitLogp(enc, false, 6) -- no dynamic allocation boost + t = tellFrac(enc) + end + end + if t + 48 <= total8 then + encIcdf(enc, 5, TRIM_ICDF, 7) + end + local bits = nbBytes * 64 - tellFrac(enc) - 1 + local pulses, fineQuant, finePriority = table.create(NB_EBANDS, 0), table.create(NB_EBANDS, 0), table.create(NB_EBANDS, 0) + local codedBands, balance, intensity, dualStereo = computeAllocation(offsets, cap, 5, bits, pulses, fineQuant, finePriority, C, enc, st.dual) + quantFineEnergy(st, fineQuant, enc, C) + quantAllBands(st, C, pulses, dualStereo, nbBytes * 64, balance, enc, codedBands, intensity) + quantEnergyFinalise(st, fineQuant, finePriority, totalBits - tell(enc), enc, C) + RE.done(enc) + if C == 1 then + for i = 1, NB_EBANDS do + oldE[NB_EBANDS + i] = oldE[i] + end + end + st.frames += 1 + st.lastError = enc.error + return enc.buf +end + +CeltEncoder.FRAME = N +CeltEncoder.DELAY = OVERLAP -- the decoder's output lags the input by the MDCT overlap +return CeltEncoder diff --git a/src/Formats/audio/opus/Encode.luau b/src/Formats/audio/opus/Encode.luau new file mode 100644 index 0000000..13e4c05 --- /dev/null +++ b/src/Formats/audio/opus/Encode.luau @@ -0,0 +1,181 @@ +--!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 diff --git a/src/Formats/audio/opus/RangeEncoder.luau b/src/Formats/audio/opus/RangeEncoder.luau new file mode 100644 index 0000000..13bf3c6 --- /dev/null +++ b/src/Formats/audio/opus/RangeEncoder.luau @@ -0,0 +1,252 @@ +--!strict +--!native +--!optimize 2 +-- audio/opus/RangeEncoder: the range encoder (RFC 6716 section 5.1), a port of libopus celt/entenc.c (BSD: +-- licenses/libopus-BSD.txt), the mirror of audio/opus/RangeDecoder. Writes one fixed-size frame: the range-coded +-- symbols from the front, the raw bits (ec_enc_bits) from the back, zeros between. Values stay below 2^32 as plain +-- numbers. Never throws: running out of room sets `error`. +local RangeEncoder = {} + +export type Enc = { + buf: buffer, + storage: number, + offs: number, + end_offs: number, + end_window: number, + nend_bits: number, + nbits_total: number, + rng: number, + val: number, + rem: number, + ext: number, + error: number, +} + +local CODE_TOP = 2147483648 -- 1 << 31 +local CODE_BOT = 8388608 -- CODE_TOP >> 8 +local CODE_SHIFT = 23 +local SYM_MAX = 255 + +local countlz = bit32.countlz +local band = bit32.band +local readu8, writeu8 = buffer.readu8, buffer.writeu8 +local floor = math.floor + +local function ilog(x: number): number + return 32 - countlz(x) +end +RangeEncoder.ilog = ilog + +-- new(storage) -> Enc over a fresh zeroed buffer of storage bytes +function RangeEncoder.new(storage: number): Enc + return { + buf = buffer.create(math.max(storage, 1)), + storage = storage, + offs = 0, + end_offs = 0, + end_window = 0, + nend_bits = 0, + nbits_total = 33, -- EC_CODE_BITS + 1 + rng = CODE_TOP, + val = 0, + rem = -1, + ext = 0, + error = 0, + } +end + +local function writeByte(e: Enc, v: number) + if e.offs + e.end_offs >= e.storage then + e.error = -1 + return + end + writeu8(e.buf, e.offs, band(v, 255)) + e.offs += 1 +end + +local function writeByteAtEnd(e: Enc, v: number) + if e.offs + e.end_offs >= e.storage then + e.error = -1 + return + end + e.end_offs += 1 + writeu8(e.buf, e.storage - e.end_offs, band(v, 255)) +end + +local function carryOut(e: Enc, c: number) + if c ~= SYM_MAX then + local carry = if c >= 256 then 1 else 0 + if e.rem >= 0 then + writeByte(e, e.rem + carry) + end + if e.ext > 0 then + local sym = band(SYM_MAX + carry, 255) + repeat + writeByte(e, sym) + e.ext -= 1 + until e.ext <= 0 + end + e.rem = band(c, 255) + else + e.ext += 1 + end +end + +local function normalize(e: Enc) + while e.rng <= CODE_BOT do + carryOut(e, floor(e.val / 8388608)) + e.val = (e.val * 256) % CODE_TOP + e.rng *= 256 + e.nbits_total += 8 + end +end + +-- encode(fl, fh, ft): the symbol [fl, fh) of ft +function RangeEncoder.encode(e: Enc, fl: number, fh: number, ft: number) + local r = floor(e.rng / ft) + if fl > 0 then + e.val += e.rng - r * (ft - fl) + e.rng = r * (fh - fl) + else + e.rng -= r * (ft - fh) + end + normalize(e) +end + +-- encodeBin(fl, fh, bits): ft = 2^bits +function RangeEncoder.encodeBin(e: Enc, fl: number, fh: number, bits: number) + local ft = 2 ^ bits + local r = floor(e.rng / ft) + if fl > 0 then + e.val += e.rng - r * (ft - fl) + e.rng = r * (fh - fl) + else + e.rng -= r * (ft - fh) + end + normalize(e) +end + +-- bitLogp(v, logp): a bit whose probability of being 1 is 2^-logp +function RangeEncoder.bitLogp(e: Enc, v: boolean, logp: number) + local r = e.rng + local s = floor(r / 2 ^ logp) + r -= s + if v then + e.val += r + e.rng = s + else + e.rng = r + end + normalize(e) +end + +-- icdf(s, icdf, ftb): symbol s (0-based) of an inverse CDF table (1-based Luau array) with 2^ftb total +function RangeEncoder.icdf(e: Enc, s: number, icdf: { number }, ftb: number) + local r = floor(e.rng / 2 ^ ftb) + if s > 0 then + e.val += e.rng - r * icdf[s] + e.rng = r * (icdf[s] - icdf[s + 1]) + else + e.rng -= r * icdf[s + 1] + end + normalize(e) +end + +-- bits(fl, n): n raw bits (n <= 25), written from the end of the frame +function RangeEncoder.bits(e: Enc, fl: number, n: number) + local window = e.end_window + local used = e.nend_bits + if used + n > 32 then + repeat + writeByteAtEnd(e, window % 256) + window = floor(window / 256) + used -= 8 + until used < 8 + end + window += fl * 2 ^ used + used += n + e.end_window = window + e.nend_bits = used + e.nbits_total += n +end + +-- uint(fl, ft): fl uniformly in [0, ft), ft up to 2^32 +function RangeEncoder.uint(e: Enc, fl: number, ft: number) + ft -= 1 + local ftb = ilog(ft) + if ftb > 8 then + ftb -= 8 + local sh = 2 ^ ftb + local ft1 = floor(ft / sh) + 1 + local hi = floor(fl / sh) + RangeEncoder.encode(e, hi, hi + 1, ft1) + RangeEncoder.bits(e, fl - hi * sh, ftb) + else + RangeEncoder.encode(e, fl, fl + 1, ft + 1) + end +end + +function RangeEncoder.tell(e: Enc): number + return e.nbits_total - ilog(e.rng) +end + +local CORRECTION = { 35733, 38967, 42495, 46340, 50535, 55109, 60097, 65535 } +function RangeEncoder.tellFrac(e: Enc): number + local nbits = e.nbits_total * 8 + local l = ilog(e.rng) + local r = floor(e.rng / 2 ^ (l - 16)) + local b = floor(r / 4096) - 8 + if r > CORRECTION[b + 1] then + b += 1 + end + return nbits - (l * 8 + b) +end + +-- done(): flush; the frame is e.buf (storage bytes) +function RangeEncoder.done(e: Enc) + local l = 32 - ilog(e.rng) + local msk = floor((CODE_TOP - 1) / 2 ^ l) + local stop = floor((e.val + msk) / (msk + 1)) * (msk + 1) + if stop + msk >= e.val + e.rng then + l += 1 + msk = floor(msk / 2) + stop = floor((e.val + msk) / (msk + 1)) * (msk + 1) + end + while l > 0 do + carryOut(e, floor(stop / 8388608)) + stop = (stop * 256) % CODE_TOP + l -= 8 + end + if e.rem >= 0 or e.ext > 0 then + carryOut(e, 0) + end + local window = e.end_window + local used = e.nend_bits + while used >= 8 do + writeByteAtEnd(e, window % 256) + window = floor(window / 256) + used -= 8 + end + if e.error == 0 then + local a, b = e.offs, e.storage - e.end_offs + if b > a then + buffer.fill(e.buf, a, 0, b - a) + end + if used > 0 then + if e.end_offs >= e.storage then + e.error = -1 + else + l = -l + if e.offs + e.end_offs >= e.storage and l < used then + window = window % 2 ^ l + e.error = -1 + end + local p = e.storage - e.end_offs - 1 + writeu8(e.buf, p, bit32.bor(readu8(e.buf, p), window)) + end + end + end +end + +local _ = CODE_SHIFT +return RangeEncoder diff --git a/src/Formats/audio/opus/init.luau b/src/Formats/audio/opus/init.luau index 08852eb..2d80432 100644 --- a/src/Formats/audio/opus/init.luau +++ b/src/Formats/audio/opus/init.luau @@ -5,14 +5,17 @@ -- 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. --- Not supported: encoding, mapping family 3 (ambisonics projection), chained streams (the first Opus stream is --- decoded), CELT pitch PLC (noise PLC only). +-- 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") @@ -24,6 +27,7 @@ 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 = { @@ -31,8 +35,8 @@ local Opus = { category = "audio", extensions = { "opus" }, mime = { "audio/opus", "audio/ogg" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" }, - caps = { decode = true, encode = false, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 } }, + 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 @@ -213,6 +217,12 @@ function Opus.decode(r: any, opts: OpenOptions?): (Types.Audio?, Err.Err?) 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 diff --git a/tests/audio/_opus_cases.luau b/tests/audio/_opus_cases.luau new file mode 100644 index 0000000..1163827 --- /dev/null +++ b/tests/audio/_opus_cases.luau @@ -0,0 +1,42 @@ +-- tests/audio/_opus_cases: the inputs of the CELT encoder reference check (tools/fixtures/opus_celt.py runs +-- tools/fixtures/_opus_encode.luau over them; tests/audio/opus_encode.luau re-encodes and compares): a deterministic +-- music-like signal (chord + vibrato + chirp + clicks + a silent stretch) at a given rate / channel count. +local Types = require("@formats/Types") + +local Cases = {} + +Cases.list = { + { name = "celt_mono_64k", rate = 48000, channels = 1, seconds = 1.5, bitrate = 64000, minSnr = 15 }, + { name = "celt_stereo_128k", rate = 48000, channels = 2, seconds = 1.5, bitrate = 128000, minSnr = 15 }, + { name = "celt_stereo_256k", rate = 48000, channels = 2, seconds = 1, bitrate = 256000, minSnr = 22 }, + { name = "celt_mono_24k", rate = 48000, channels = 1, seconds = 1, bitrate = 24000, minSnr = 8 }, + { name = "celt_44k_stereo_96k", rate = 44100, channels = 2, seconds = 1, bitrate = 96000, minSnr = 0, tags = { title = "Celt \u{e9}", artist = "formats-luau", album = "Opus" } }, + { name = "celt_short", rate = 48000, channels = 1, seconds = 0.01, bitrate = 48000, minSnr = -100 }, +} + +function Cases.signal(c: any): Types.Audio + local n = math.floor(c.seconds * c.rate + 0.5) + local a = Types.Audio.new(c.rate, c.channels, n) + local s = 7 + for i = 0, n - 1 do + local t = i / c.rate + for ch = 0, c.channels - 1 do + s = (s * 48271) % 2147483647 + local v = 0.18 * math.sin(2 * math.pi * 220 * t + 2 * math.sin(2 * math.pi * 5 * t)) + v += 0.12 * math.sin(2 * math.pi * (277.2 + ch * 2) * t) + 0.1 * math.sin(2 * math.pi * 329.6 * t) + v += 0.08 * math.sin(2 * math.pi * (1000 + 3000 * t) * t) + v += 0.01 * (s / 2147483647 - 0.5) + if i % (c.rate // 4) < 30 then + v += 0.4 * (if (i // 5) % 2 == 0 then 1 else -1) + end + if t > 0.6 and t < 0.75 then + v = 0 -- digital silence (the encoder's silence frames) + end + buffer.writef32(a.samples, (i * c.channels + ch) * 4, v) + end + end + a.tags = c.tags or {} + return a +end + +return Cases diff --git a/tests/audio/opus.luau b/tests/audio/opus.luau index c876dce..8403251 100644 --- a/tests/audio/opus.luau +++ b/tests/audio/opus.luau @@ -81,7 +81,7 @@ end -- ------------------------------------------------------------------------------------------------ contract t:eq(Opus.name, "opus", "name") t:eq(Opus.category, "audio", "category") -t:check(Opus.caps.decode and not Opus.caps.encode and Opus.open ~= nil and Opus.decode ~= nil, "caps") +t:check(Opus.caps.decode and Opus.caps.encode and Opus.open ~= nil and Opus.decode ~= nil and Opus.encode ~= nil, "caps (the CELT encoder: tests/audio/opus_encode.luau)") t:eq(Opus.sniff(Bytes.reader(FX.celt_st_128.data)), 1, "sniff an Opus file") t:eq(Opus.sniff(Bytes.reader(buffer.fromstring("OggS" .. string.rep("\0", 40)))), 0, "sniff another Ogg") t:eq(Opus.sniff(Bytes.reader(buffer.create(0))), 0, "sniff nothing") diff --git a/tests/audio/opus_encode.luau b/tests/audio/opus_encode.luau new file mode 100644 index 0000000..c3aeff4 --- /dev/null +++ b/tests/audio/opus_encode.luau @@ -0,0 +1,114 @@ +-- audio/opus encoder tests (the CELT-only writer, ws-m4a; mono and mid / side stereo): our Ogg Opus files (re-encoded here, compared with the bytes +-- checked in the fixture step) decode in libopus' opusdec to the input's exact length (pre-skip + end trimming) with a +-- minimum SNR, opusinfo finds no problem, ffmpeg reads them, OpusTags carry the tags; our decoder agrees with opusdec; +-- resampled 44.1 kHz input; silence frames; streaming input; errors; a fuzz no-throw pass over our files. +-- Fixtures: tools/fixtures/opus_celt.py. +local T = require("@tests/T") +local Opus = require("@formats/audio/opus") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Cases = require("@tests/audio/_opus_cases") +local Fx = require("@tests/gen/opus_celt") + +local t = T.suite("opus-encode") + +t:check(Opus.caps.encode and Opus.encode ~= nil, "caps: encode") + +local byName = {} +for _, f in Fx do + byName[f.name] = f +end + +local function snr(ref: buffer, refBase: number, got: buffer, n: number): number + local s, e = 0, 0 + for i = 0, n - 1 do + local x = buffer.readf32(ref, (refBase + i) * 4) + local d = buffer.readf32(got, (refBase + i) * 4) - x + s += x * x + e += d * d + end + return if e == 0 then math.huge else 10 * math.log10(s / math.max(e, 1e-30)) +end + +local files = {} +for _, c in Cases.list do + local fx = byName[c.name] + t:check(fx, c.name .. ": fixture") + local input = Cases.signal(c) + local file, err = Opus.encode(input, { bitrate = c.bitrate }) + t:check(file, c.name .. ": encode: " .. tostring(err)) + table.insert(files, file) + t:eq(string.format("%08x", Crc32.of(file :: buffer)), string.format("%08x", fx.crc), c.name .. ": the bytes the reference tools checked") + t:check(fx.opusinfo, c.name .. ": opusinfo reports no problem") + t:check(fx.ffmpeg, c.name .. ": ffmpeg decodes it") + local frames48 = math.floor(input.frames * 48000 / c.rate + 0.5) + local ch = c.channels + t:eq(#fx.opusdec // (4 * ch), frames48, c.name .. ": opusdec length = the input's (pre-skip + end trimming)") + t:eq(fx.ffmpegFrames, frames48, c.name .. ": ffmpeg length") + -- our decoder vs opusdec + local ours = Opus.decode(Bytes.reader(file :: buffer)) :: any + t:eq(ours.frames, frames48, c.name .. ": our decoder's length") + local ref = buffer.fromstring(fx.opusdec) + local agree = snr(ref, 0, ours.samples, frames48 * ch) + t:check(agree > 60, string.format("%s: our decoder vs opusdec %.1f dB", c.name, agree)) + -- quality vs the input (48 kHz inputs; skip the edges) + if c.rate == 48000 and frames48 > 4000 then + local s = snr(input.samples, 960 * ch, ref, (frames48 - 1920) * ch) + t:check(s >= c.minSnr, string.format("%s: SNR %.1f dB (minimum %d)", c.name, s, c.minSnr)) + t:note("%s: %d bytes, SNR %.1f dB vs the input, our decoder vs opusdec %.1f dB", c.name, buffer.len(file :: buffer), s, agree) + end + if c.tags then + for k, v in c.tags do + t:eq(fx.comments[k], v, c.name .. ": opusinfo comment " .. k) + t:eq(ours.tags[k], v, c.name .. ": our tag " .. k) + end + end +end + +-- silence frames decode to silence +do + local c = Cases.list[1] + local ref = buffer.fromstring(byName[c.name].opusdec) + local peak = 0 + for i = math.floor(0.62 * 48000), math.floor(0.73 * 48000) do + peak = math.max(peak, math.abs(buffer.readf32(ref, i * 4))) + end + t:check(peak < 1e-3, "digital silence stays silent (peak " .. peak .. ")") +end + +-- a streaming decoder as the input +do + local c = Cases.list[1] + local dec = Opus.open(Bytes.reader(files[1] :: buffer)) :: any + local again, err = Opus.encode(dec, { bitrate = 64000 }) + t:check(again, "encode from a decoder: " .. tostring(err)) + local back = Opus.decode(Bytes.reader(again :: buffer)) :: any + t:eq(back.frames, math.floor(c.seconds * 48000 + 0.5), "re-encoded length") +end + +-- errors +do + local three = Cases.signal({ rate = 48000, channels = 3, seconds = 0.05 }) + local _, e = Opus.encode(three) + t:check(e and e.code == Err.UNSUPPORTED, "3 channels: " .. tostring(e)) + local _, e2 = Opus.encode(Cases.signal(Cases.list[6]), { bitrate = 1000 }) + t:check(e2 and e2.code == Err.ARG, "bitrate too low") + local _, e3 = Opus.encode({} :: any) + t:check(e3 and e3.code == Err.ARG, "not audio") +end + +-- fuzz the decoder over our files +do + local samples = {} + for i, f in files do + if i <= 3 then + table.insert(samples, string.sub(buffer.tostring(f :: buffer), 1, 4000)) + end + end + t:fuzz("decode our files", function(b: buffer) + return Opus.decode(Bytes.reader(b)) + end, samples, { mutations = 10, garbage = 30 }) +end + +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index b2eea5d..1f5ed5f 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -184,3 +184,13 @@ do end end) end +do + local Opus = require("@formats/audio/opus") + local Cases = require("@tests/audio/_opus_cases") + local c = Cases.list[2] + local a = Cases.signal(c) + local dt = bench("opus celt encode 128k (1.5 s st)", 2, a.frames * a.channels * 2, function() + Opus.encode(a, { bitrate = 128000 }) + end) + local _ = dt +end diff --git a/tools/fixtures/_opus_encode.luau b/tools/fixtures/_opus_encode.luau new file mode 100644 index 0000000..a974148 --- /dev/null +++ b/tools/fixtures/_opus_encode.luau @@ -0,0 +1,17 @@ +-- tools/fixtures/_opus_encode: run by tools/fixtures/opus_celt.py (luau, from the repo root): encodes +-- tests/audio/_opus_cases with audio/opus's CELT encoder and prints " " lines for opusdec / ffmpeg. +local Opus = require("@formats/audio/opus") +local Cases = require("@tests/audio/_opus_cases") + +for _, c in Cases.list do + local out, err = Opus.encode(Cases.signal(c), { bitrate = c.bitrate }) + if not out then + print(c.name .. " ERROR " .. tostring(err)) + else + local t = table.create(buffer.len(out)) + for i = 0, buffer.len(out) - 1 do + t[i + 1] = string.format("%02x", buffer.readu8(out, i)) + end + print(c.name .. " " .. table.concat(t)) + end +end diff --git a/tools/fixtures/opus_celt.py b/tools/fixtures/opus_celt.py new file mode 100644 index 0000000..5db280b --- /dev/null +++ b/tools/fixtures/opus_celt.py @@ -0,0 +1,48 @@ +# The CELT encoder reference check (tools/fixtures.py): runs tools/fixtures/_opus_encode.luau (our encoder over +# tests/audio/_opus_cases.luau), then the reference tools through nix: opusdec --float (libopus), opusinfo (stream +# structure), ffmpeg (an independent Ogg / Opus reader). +# tests/gen/opus_celt.luau { { name, crc (of our bytes), opusdec (f32le 48 kHz decode), opusinfo (exit 0), +# ffmpeg (decoded), ffmpegFrames, comments (opusinfo's user comments) } } +import os, re, shutil, subprocess, tempfile, zlib + +INPUTS = ["src/Formats/audio/opus", "src/Formats/codecs/Mdct", "src/Formats/containers/Ogg", + "tests/audio/_opus_cases.luau", "tools/fixtures/_opus_encode.luau"] + + +def generate(ctx): + luau = os.environ.get("LUAU") or shutil.which("luau") + script = os.path.join(ctx.root, "tools/fixtures/_opus_encode.luau") + if luau: + out = subprocess.run([luau, script], capture_output=True, check=True, cwd=ctx.root).stdout + else: + out = ctx.nix("luau", ["luau", script]) + d = tempfile.mkdtemp(prefix="opus-celt-fx-") + try: + cases = [] + for line in out.decode().split("\n"): + if not line.strip(): + continue + name, hx = line.split(" ", 1) + if hx.startswith("ERROR"): + raise RuntimeError("opus_celt fixtures: our encoder failed on %s: %s" % (name, hx)) + data = bytes.fromhex(hx) + path = os.path.join(d, name + ".opus") + with open(path, "wb") as f: + f.write(data) + raw = os.path.join(d, name + ".f32") + ctx.nix("opus-tools", ["opusdec", "--quiet", "--float", "--rate", "48000", path, raw]) + with open(raw, "rb") as f: + pcm = f.read() + info = subprocess.run(["nix", "shell", "nixpkgs#opus-tools", "-c", "opusinfo", path], capture_output=True) + text = info.stdout.decode(errors="replace") + comments = {} + for m in re.finditer(r"^\s*([A-Za-z]+)=(.*)$", text, re.M): + comments[m.group(1).lower()] = m.group(2) + ok = info.returncode == 0 and "WARNING" not in text and "ERROR" not in text.upper().replace("ERRORS", "") + ff = subprocess.run(["nix", "shell", "nixpkgs#ffmpeg", "-c", "ffmpeg", "-v", "error", "-i", path, "-f", "f32le", "-ac", "1", "-"], capture_output=True) + cases.append({"name": name, "crc": zlib.crc32(data), "opusdec": pcm, "opusinfo": ok, + "ffmpeg": ff.returncode == 0 and len(ff.stderr) == 0, "ffmpegFrames": len(ff.stdout) // 4, + "comments": comments}) + ctx.emit("opus_celt", cases) + finally: + shutil.rmtree(d, ignore_errors=True)