From d20ffd7388387def22a8c8c1f97d7ed3cdc7b550 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:33:32 -0500 Subject: [PATCH] absorb: opus (audio/opus from opus-luau dd2b4e5, libopus port: direct containers/Ogg require, Types.Decoder open + decode to Audio, Err values); tests vs opusdec --float on 24 generated streams, CELT / SILK alone, PLC, seek, downmix, fuzz; bench lines --- docs/FORMATS.md | 1 + licenses/NOTICE.md | 1 + licenses/libopus-BSD.txt | 44 + src/Formats/Registry.luau | 12 + src/Formats/audio/opus/Celt.luau | 1864 +++++++++++++++++++ src/Formats/audio/opus/CeltTables.luau | 58 + src/Formats/audio/opus/Decoder.luau | 466 +++++ src/Formats/audio/opus/Mdct.luau | 342 ++++ src/Formats/audio/opus/Packet.luau | 235 +++ src/Formats/audio/opus/RangeDecoder.luau | 214 +++ src/Formats/audio/opus/Silk.luau | 2070 ++++++++++++++++++++++ src/Formats/audio/opus/SilkTables.luau | 372 ++++ src/Formats/audio/opus/init.luau | 408 +++++ tests/audio/opus.luau | 445 +++++ tools/bench.luau | 13 +- tools/bench.sh | 2 +- tools/fixtures/opus.py | 66 + 17 files changed, 6611 insertions(+), 2 deletions(-) create mode 100644 licenses/libopus-BSD.txt create mode 100644 src/Formats/audio/opus/Celt.luau create mode 100644 src/Formats/audio/opus/CeltTables.luau create mode 100644 src/Formats/audio/opus/Decoder.luau create mode 100644 src/Formats/audio/opus/Mdct.luau create mode 100644 src/Formats/audio/opus/Packet.luau create mode 100644 src/Formats/audio/opus/RangeDecoder.luau create mode 100644 src/Formats/audio/opus/Silk.luau create mode 100644 src/Formats/audio/opus/SilkTables.luau create mode 100644 src/Formats/audio/opus/init.luau create mode 100644 tests/audio/opus.luau create mode 100644 tools/fixtures/opus.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 181230b..0100028 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -6,6 +6,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | Category | Format | Extensions | Read | Write | Capabilities | Test | |---|---|---|---|---|---|---| | image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | +| audio | opus | .opus | yes | - | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000 | `tests/audio/opus.luau` | Codecs (layer 1, shared by formats; not loadable on their own): diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index bc841c1..a879c6e 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -5,6 +5,7 @@ | `src/Formats/codecs/Deflate/` (Inflate, init), `src/Formats/core/Crc32.luau`, `src/Formats/core/Adler32.luau`, `src/Formats/core/Huffman.luau` (table builder) | deflate-luau 1.0.0 (same author), written from RFC 1950-1952 | no licence chosen yet; no third-party code: [deflate-luau-NOTICE.txt](deflate-luau-NOTICE.txt) | | `src/Formats/image/png/` (init, Decode) | png-luau 1.0.0 (same author), written from the PNG specification | no licence chosen yet; no third-party code | | `src/Formats/containers/Ogg/` (init, Page) | ogg-luau be9f604 (same author), written from RFC 3533 | no licence chosen yet; no third-party code | +| `src/Formats/audio/opus/` (Decoder, Celt, Silk, Mdct, RangeDecoder, Packet, CeltTables, SilkTables) | opus-luau dd2b4e5 (same author): a port of the libopus 1.6 decoder (git bafd40dcbd50; tables generated from its sources); the stereo downmix weights follow opusfile | libopus BSD 3-clause (Xiph.Org, Skype, Octasic, J.-M. Valin, T. B. Terriberry, CSIRO, G. Maxwell, M. Borgerding, E. de Castro Lopo, Mozilla, Amazon), opusfile 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/licenses/libopus-BSD.txt b/licenses/libopus-BSD.txt new file mode 100644 index 0000000..7571146 --- /dev/null +++ b/licenses/libopus-BSD.txt @@ -0,0 +1,44 @@ +Copyright 2001-2023 Xiph.Org, Skype Limited, Octasic, + Jean-Marc Valin, Timothy B. Terriberry, + CSIRO, Gregory Maxwell, Mark Borgerding, + Erik de Castro Lopo, Mozilla, Amazon + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +- Neither the name of Internet Society, IETF or IETF Trust, nor the +names of specific contributors, may be used to endorse or promote +products derived from this software without specific prior written +permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Opus is subject to the royalty-free patent licenses which are +specified at: + +Xiph.Org Foundation: +https://datatracker.ietf.org/ipr/1524/ + +Microsoft Corporation: +https://datatracker.ietf.org/ipr/1914/ + +Broadcom Corporation: +https://datatracker.ietf.org/ipr/1526/ diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index ba09f70..f4ba167 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -26,6 +26,18 @@ local list: { Entry } = { return require("@formats/image/png") end, }, + { + name = "opus", + category = "audio", + 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 } }, + load = function() + return require("@formats/audio/opus") + end, + }, } return list diff --git a/src/Formats/audio/opus/Celt.luau b/src/Formats/audio/opus/Celt.luau new file mode 100644 index 0000000..7bdbc15 --- /dev/null +++ b/src/Formats/audio/opus/Celt.luau @@ -0,0 +1,1864 @@ +--!strict +--!native +--!optimize 2 +-- audio/opus/Celt: CELT decoder (RFC 6716 section 4.3), a port of the libopus float decoder: celt/celt_decoder.c, bands.c, vq.c, +-- cwrs.c, rate.c, quant_bands.c, laplace.c, celt.c (comb filter). Only the standard 48 kHz / 960-sample mode is +-- needed by Opus. Packet loss concealment is the noise-based variant only (no pitch PLC). +-- +-- Arrays are Luau tables of numbers. All normalised-band data (X, Y, the folding memory `norm` and the scratch +-- copies) lives in one table W, and the "pointers" of the C code are 0-based offsets into it. +local RD = require("@formats/audio/opus/RangeDecoder") +local Mdct = require("@formats/audio/opus/Mdct") +local T = require("@formats/audio/opus/CeltTables") + +local Celt = {} + +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift +local min, max, sqrt, floor, exp, cos = math.min, math.max, math.sqrt, math.floor, math.exp, math.cos +local decBitLogp, decIcdf, decBits, decUint = RD.bitLogp, RD.icdf, RD.bits, RD.uint +local decDecode, decDecodeBin, decUpdate = RD.decode, RD.decodeBin, RD.update +local tell, tellFrac = RD.tell, RD.tellFrac + +local NB_EBANDS = 21 +local EFF_EBANDS = 21 +local OVERLAP = 120 +local SHORT_MDCT = 120 +local MAX_LM = 3 +local DECODE_BUFFER_SIZE = 2048 +local BITRES = 3 +local MAX_FINE_BITS = 8 +local FINE_OFFSET = 21 +local QTHETA_OFFSET = 4 +local QTHETA_OFFSET_TWOPHASE = 16 +local SPREAD_AGGRESSIVE = 3 +local PREEMPH = 0.85000610 +local COMBFILTER_MINPERIOD = 15 +local FRAME_NONE, FRAME_NORMAL, FRAME_PLC_NOISE = 0, 1, 2 + +-- eBands (1-based: EB[i + 1] is eBands[i]) +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, 3.750000, 3.750000, 3.750000, 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 = { -- [LM][4 * isTransient + 2 * tf_select + flag] + { 0, -1, 0, -1, 0, -1, 0, -1 }, + { 0, -1, 0, -2, 1, 0, 1, -1 }, + { 0, -2, 0, -3, 2, 0, 1, -1 }, + { 0, -2, 0, -3, 3, 0, 1, -1 }, +} +local TRIM_ICDF = { 126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0 } +local SPREAD_ICDF = { 25, 23, 2, 0 } +local TAPSET_ICDF = { 2, 1, 0 } +local SMALL_ENERGY_ICDF = { 2, 1, 0 } +local EXP2_TABLE8 = { 16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048 } +local ORDERY = { 1, 0, 3, 0, 2, 1, 7, 0, 4, 3, 6, 1, 5, 2, 15, 0, 8, 7, 12, 3, 11, 4, 14, 1, 9, 6, 13, 2, 10, 5 } +local BIT_INTERLEAVE = { 0, 1, 1, 1, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3 } +local BIT_DEINTERLEAVE = { 0x00, 0x03, 0x0C, 0x0F, 0x30, 0x33, 0x3C, 0x3F, 0xC0, 0xC3, 0xCC, 0xCF, 0xF0, 0xF3, 0xFC, 0xFF } +local COMB_GAINS = { + { 0.3066406250, 0.2170410156, 0.1296386719 }, + { 0.4638671875, 0.2680664062, 0.0 }, + { 0.7998046875, 0.1000976562, 0.0 }, +} + +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 +Celt.window = WINDOW + +-- PVQ codebook sizes U(n, k) (cwrs.c), flat: U[n * UK + k + 1], n, k in 0 .. 176 +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 + +-- shared workspace (decoding is not re-entrant) +local NORM_BASE = 1920 +local W = table.create(4096, 0) +local TMP = table.create(256, 0) +local IY = table.create(256, 0) +local FREQ = table.create(960, 0) +local FREQ2 = table.create(960, 0) +local COLLAPSE = table.create(42, 0) +local TF_RES = table.create(21, 0) +local CAP = table.create(21, 0) +local OFFSETS = table.create(21, 0) +local FINE_QUANT = table.create(21, 0) +local PULSES = table.create(21, 0) +local FINE_PRIORITY = table.create(21, 0) +local BITS1 = table.create(21, 0) +local BITS2 = table.create(21, 0) +local THRESH = table.create(21, 0) +local TRIM_OFFSET = table.create(21, 0) + +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 +-- C integer division (truncates toward zero) +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 exp2(x: number): number + return exp(0.6931471805599453094 * x) +end + +local function lcg(seed: number): number + return (1664525 * seed + 1013904223) % 4294967296 +end + +local function signed32(x: number): number + return if x >= 2147483648 then x - 4294967296 else x +end + +local function fracMul16(a: number, b: number): number + return (16384 + a * b) // 32768 +end + +local function bitexactCos(x: number): number + local tmp = (4096 + x * x) // 8192 + local x2 = tmp + 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 = RD.ilog(icos) + local ls = RD.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 (quant_bands.c, laplace.c) + +local function laplaceDecode(dec: RD.Dec, fs: number, decay: number): number + local val = 0 + local fm = decDecodeBin(dec, 15) + local fl = 0 + if fm >= fs then + val += 1 + fl = fs + fs = ((32768 - 32 - fs) * (16384 - decay)) // 32768 + 1 + while fs > 1 and fm >= fl + 2 * fs do + fs *= 2 + fl += fs + fs = ((fs - 2) * decay) // 32768 + fs += 1 + val += 1 + end + if fs <= 1 then + local di = rshift(fm - fl, 1) + val += di + fl += 2 * di + end + if fm < fl + fs then + val = -val + else + fl += fs + end + end + decUpdate(dec, fl, imin(fl + fs, 32768), 32768) + return val +end + +local function unquantCoarseEnergy(st: any, start: number, endb: number, intra: boolean, dec: RD.Dec, C: number, LM: number) + local oldE = st.oldBandE + local probBase = LM * 84 + (if intra then 42 else 0) -- e_prob_model[LM][intra], 0-based + local coef, beta + if intra then + coef = 0 + beta = BETA_INTRA + else + beta = BETA_COEF[LM + 1] + coef = PRED_COEF[LM + 1] + end + local prev0, prev1 = 0, 0 + local budget = dec.storage * 8 + for i = start, endb - 1 do + for c = 0, C - 1 do + local t = tell(dec) + local qi + if budget - t >= 15 then + local pi = 2 * imin(i, 20) + qi = laplaceDecode(dec, E_PROB[probBase + pi + 1] * 128, E_PROB[probBase + pi + 2] * 64) + elseif budget - t >= 2 then + qi = decIcdf(dec, SMALL_ENERGY_ICDF, 1, 2) + qi = if band(qi, 1) ~= 0 then -rshift(qi, 1) - 1 else rshift(qi, 1) + elseif budget - t >= 1 then + qi = if decBitLogp(dec, 1) then -1 else 0 + else + qi = -1 + end + local q = qi + local k = i + c * NB_EBANDS + 1 + local e = max(-9, oldE[k]) + local prev = if c == 0 then prev0 else prev1 + oldE[k] = coef * e + prev + q + prev = prev + q - beta * q + if c == 0 then + prev0 = prev + else + prev1 = prev + end + end + end +end + +local function unquantFineEnergy(st: any, start: number, endb: number, fineQuant: { number }, dec: RD.Dec, C: number) + local oldE = st.oldBandE + for i = start, endb - 1 do + local extra = fineQuant[i + 1] + if extra <= 0 then + continue + end + if tell(dec) + C * extra > dec.storage * 8 then + continue + end + for c = 0, C - 1 do + local q2 = decBits(dec, extra) + local offset = (q2 + 0.5) * 2 ^ (14 - extra) * (1 / 16384) - 0.5 + oldE[i + c * NB_EBANDS + 1] += offset + end + end +end + +local function unquantEnergyFinalise(st: any, start: number, endb: number, fineQuant: { number }, finePriority: { number }, bitsLeft: number, dec: RD.Dec, C: number) + local oldE = st.oldBandE + for prio = 0, 1 do + local i = start + while i < endb 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 q2 = decBits(dec, 1) + local offset = (q2 - 0.5) * 2 ^ (14 - fineQuant[i + 1] - 1) * (1 / 16384) + oldE[i + c * NB_EBANDS + 1] += offset + bitsLeft -= 1 + end + i += 1 + end + end +end + +-- --------------------------------------------------------------------------------------------------------------- +-- bit allocation (rate.c) + +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 + interp_bits2pulses (decoder side). Returns codedBands, balance, intensity, dualStereo. +local function computeAllocation(start: number, endb: number, offsets: { number }, cap: { number }, allocTrim: number, + total: number, pulses: { number }, ebits: { number }, finePriority: { number }, C: number, LM: number, ec: RD.Dec) + 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 = BITS1, BITS2, THRESH, TRIM_OFFSET + 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 N = EB[j + 2] - EB[j + 1] + local bitsj = (C * N * 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 N = EB[j + 2] - EB[j + 1] + local bits1j = (C * N * ALLOC[lo * len + j + 1] * 2 ^ LM) // 4 + local bits2j = if hi >= NB_ALLOC_VECTORS then cap[j + 1] else (C * N * 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 + if decBitLogp(ec, 1) then + break + end + psum += 8 + bandBits -= 8 + 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 = start + decUint(ec, codedBands + 1 - start) + end + if intensity <= start then + total += dualStereoRsv + dualStereoRsv = 0 + end + if dualStereoRsv > 0 then + dualStereo = decBitLogp(ec, 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 N = N0 * 2 ^ LM + local bit = bits[j + 1] + balance + local excess + if N > 1 then + excess = imax(bit - cap[j + 1], 0) + bits[j + 1] = bit - excess + local den = C * N + (if C == 2 and N > 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 N == 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 (cwrs.c, vq.c) + +local function cwrsi(n: number, k: number, i: number, iy: { number }): number + local yy = 0 + local idx = 1 + local p, k0, val + while n > 2 do + if k >= n then + local rowBase = n * UK + 1 + p = U[rowBase + k + 1] + local neg = i >= p + if neg then + i -= p + end + k0 = k + local q = U[rowBase + n] + if q > i then + k = n + repeat + k -= 1 + p = U[k * UK + n + 1] + until p <= i + else + p = U[rowBase + k] + while p > i do + k -= 1 + p = U[rowBase + k] + end + end + i -= p + val = if neg then k - k0 else k0 - k + iy[idx] = val + idx += 1 + yy += val * val + else + p = U[k * UK + n + 1] + local q = U[(k + 1) * UK + n + 1] + if p <= i and i < q then + i -= p + iy[idx] = 0 + idx += 1 + else + local neg = i >= q + if neg then + i -= q + end + k0 = k + repeat + k -= 1 + p = U[k * UK + n + 1] + until p <= i + i -= p + val = if neg then k - k0 else k0 - k + iy[idx] = val + idx += 1 + yy += val * val + end + end + n -= 1 + end + -- n == 2 + p = 2 * k + 1 + local neg = i >= p + if neg then + i -= p + end + k0 = k + k = rshift(i + 1, 1) + if k ~= 0 then + i -= 2 * k - 1 + end + val = if neg then k - k0 else k0 - k + iy[idx] = val + yy += val * val + -- n == 1 + val = if i ~= 0 then -k else k + iy[idx + 1] = val + yy += val * val + return yy +end + +local function expRotation1(X: number, len: number, stride: number, c: number, s: number) + local ms = -s + local p = X + 1 + for _ = 0, len - stride - 1 do + local x1 = W[p] + local x2 = W[p + stride] + W[p + stride] = c * x2 + s * x1 + W[p] = c * x1 + ms * x2 + p += 1 + end + p = X + len - 2 * stride + for _ = len - 2 * stride - 1, 0, -1 do + local x1 = W[p] + local x2 = W[p + stride] + W[p + stride] = c * x2 + s * x1 + W[p] = c * x1 + ms * x2 + p -= 1 + end +end + +local SPREAD_FACTOR = { 15, 10, 5 } +local function expRotation(X: number, len: number, dir: 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 = X + i * len + if dir < 0 then + if stride2 ~= 0 then + expRotation1(x, len, stride2, s, c) + end + expRotation1(x, len, 1, c, s) + else + expRotation1(x, len, 1, c, -s) + if stride2 ~= 0 then + expRotation1(x, len, stride2, s, -c) + end + end + end +end + +local function renormaliseVector(X: number, N: number, gain: number) + local E = 1e-15 + for i = X + 1, X + N do + local v = W[i] + E += v * v + end + local g = gain / sqrt(E) + for i = X + 1, X + N do + W[i] *= g + end +end + +local function algUnquant(X: number, N: number, K: number, spread: number, B: number, dec: RD.Dec, gain: number): number + local iy = IY + local ft = U[N * UK + K + 1] + U[N * UK + K + 2] + local Ryy = cwrsi(N, K, decUint(dec, ft), iy) + local g = gain / sqrt(Ryy) + for i = 1, N do + W[X + i] = iy[i] * g + end + expRotation(X, N, -1, B, K, spread) + if B <= 1 then + return 1 + end + local N0 = N // B + local mask = 0 + for i = 0, B - 1 do + for j = 1, N0 do + if iy[i * N0 + j] ~= 0 then + mask = bor(mask, lshift(1, i)) + break + end + end + end + return mask +end + +-- --------------------------------------------------------------------------------------------------------------- +-- bands (bands.c) + +type Ctx = { + i: number, + intensity: number, + spread: number, + tf_change: number, + ec: RD.Dec, + remaining_bits: number, + seed: number, + disable_inv: boolean, + avoid_split_noise: boolean, +} +local ctx: Ctx = { + i = 0, + intensity = 0, + spread = 0, + tf_change = 0, + ec = (nil :: any), + remaining_bits = 0, + seed = 0, + disable_inv = false, + avoid_split_noise = false, +} + +local function haar1(X: number, N0: number, stride: number) + N0 = rshift(N0, 1) + local s = 0.70710678 + for i = 0, stride - 1 do + for j = 0, N0 - 1 do + local a = X + stride * 2 * j + i + 1 + local b = a + stride + local t1 = s * W[a] + local t2 = s * W[b] + W[a] = t1 + t2 + W[b] = t1 - t2 + end + end +end + +local function deinterleaveHadamard(X: number, N0: number, stride: number, hadamard: boolean) + local N = N0 * stride + local tmp = TMP + if hadamard then + local ob = stride - 2 + for i = 0, stride - 1 do + local o = ORDERY[ob + i + 1] * N0 + for j = 0, N0 - 1 do + tmp[o + j + 1] = W[X + j * stride + i + 1] + end + end + else + for i = 0, stride - 1 do + for j = 0, N0 - 1 do + tmp[i * N0 + j + 1] = W[X + j * stride + i + 1] + end + end + end + for k = 1, N do + W[X + k] = tmp[k] + end +end + +local function interleaveHadamard(X: number, N0: number, stride: number, hadamard: boolean) + local N = N0 * stride + local tmp = TMP + if hadamard then + local ob = stride - 2 + for i = 0, stride - 1 do + local o = ORDERY[ob + i + 1] * N0 + for j = 0, N0 - 1 do + tmp[j * stride + i + 1] = W[X + o + j + 1] + end + end + else + for i = 0, stride - 1 do + for j = 0, N0 - 1 do + tmp[j * stride + i + 1] = W[X + i * N0 + j + 1] + end + end + end + for k = 1, N do + W[X + k] = tmp[k] + end +end + +local function computeQn(N: number, b: number, offset: number, pulseCap: number, stereo: boolean): number + local N2 = 2 * N - 1 + if stereo and N == 2 then + N2 -= 1 + end + 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 + +-- returns b, fill, inv, imid, iside, delta, itheta, qalloc +local function computeTheta(N: number, b: number, B: number, B0: number, LM: number, stereo: boolean, fill: number) + local i = ctx.i + local ec = ctx.ec + local pulseCap = LOGN[i + 1] + LM * 8 + local offset = (pulseCap // 2) - (if stereo and N == 2 then QTHETA_OFFSET_TWOPHASE else QTHETA_OFFSET) + local qn = computeQn(N, b, offset, pulseCap, stereo) + if stereo and i >= ctx.intensity then + qn = 1 + end + local t0 = tellFrac(ec) + local itheta = 0 + local inv = false + if qn ~= 1 then + if stereo and N > 2 then + local p0 = 3 + local x0 = qn // 2 + local ft = p0 * (x0 + 1) + x0 + local fs = decDecode(ec, ft) + local x + if fs < (x0 + 1) * p0 then + x = fs // p0 + else + x = x0 + 1 + (fs - (x0 + 1) * p0) + end + if x <= x0 then + decUpdate(ec, p0 * x, p0 * (x + 1), ft) + else + decUpdate(ec, (x - 1 - x0) + (x0 + 1) * p0, (x - x0) + (x0 + 1) * p0, ft) + end + itheta = x + elseif B0 > 1 or stereo then + itheta = decUint(ec, qn + 1) + else + local h = rshift(qn, 1) + local ft = (h + 1) * (h + 1) + local fm = decDecode(ec, ft) + local fs, fl + if fm < rshift(h * (h + 1), 1) then + itheta = rshift(floor(sqrt(8 * fm + 1)) - 1, 1) + fs = itheta + 1 + fl = rshift(itheta * (itheta + 1), 1) + else + itheta = rshift(2 * (qn + 1) - floor(sqrt(8 * (ft - fm - 1) + 1)), 1) + fs = qn + 1 - itheta + fl = ft - rshift((qn + 1 - itheta) * (qn + 2 - itheta), 1) + end + decUpdate(ec, fl, fl + fs, ft) + end + itheta = (itheta * 16384) // qn + elseif stereo then + if b > 16 and ctx.remaining_bits > 16 then + inv = decBitLogp(ec, 2) + end + if ctx.disable_inv then + inv = false + end + itheta = 0 + end + local qalloc = tellFrac(ec) - t0 + b -= qalloc + local imid, iside, delta + if itheta == 0 then + imid = 32767 + iside = 0 + fill = band(fill, lshift(1, B) - 1) + delta = -16384 + elseif itheta == 16384 then + imid = 0 + iside = 32767 + fill = band(fill, lshift(lshift(1, B) - 1, B)) + delta = 16384 + else + imid = bitexactCos(itheta) + iside = bitexactCos(16384 - itheta) + delta = fracMul16((N - 1) * 128, bitexactLog2tan(iside, imid)) + end + return b, fill, inv, imid, iside, delta, itheta, qalloc +end + +local function quantBandN1(X: number, Y: number, lowbandOut: number): number + local x = X + local ec = ctx.ec + for _ = 0, (if Y >= 0 then 1 else 0) do + local sign = 0 + if ctx.remaining_bits >= 8 then + sign = decBits(ec, 1) + ctx.remaining_bits -= 8 + end + W[x + 1] = if sign ~= 0 then -1 else 1 + x = Y + end + if lowbandOut >= 0 then + W[lowbandOut + 1] = W[X + 1] + end + return 1 +end + +local function quantPartition(X: number, N: number, b: number, B: number, lowband: number, LM: number, gain: number, fill: number): number + local i = ctx.i + local B0 = B + local cm = 0 + local split = false + if LM ~= -1 and N > 2 then + local base = CACHE_INDEX[(LM + 1) * NB_EBANDS + i + 1] + split = b > CACHE_BITS[base + CACHE_BITS[base + 1] + 1] + 12 + end + if split then + N = rshift(N, 1) + local Y = X + N + LM -= 1 + if B == 1 then + fill = bor(band(fill, 1), lshift(fill, 1)) + end + B = rshift(B + 1, 1) + local _inv, imid, iside, delta, itheta, qalloc + b, fill, _inv, imid, iside, delta, itheta, qalloc = computeTheta(N, b, B, B0, LM, false, fill) + local mid = imid / 32768 + local side = iside / 32768 + if B0 > 1 and band(itheta, 0x3fff) ~= 0 then + if itheta > 8192 then + delta -= delta // 2 ^ (4 - LM) + else + delta = imin(0, delta + (N * 8) // 2 ^ (5 - LM)) + end + end + local mbits = imax(0, imin(b, tdiv(b - delta, 2))) + local sbits = b - mbits + ctx.remaining_bits -= qalloc + local nextLowband2 = if lowband >= 0 then lowband + N else -1 + local rebalance = ctx.remaining_bits + if mbits >= sbits then + cm = quantPartition(X, N, mbits, B, lowband, LM, gain * mid, fill) + rebalance = mbits - (rebalance - ctx.remaining_bits) + if rebalance > 24 and itheta ~= 0 then + sbits += rebalance - 24 + end + cm = bor(cm, lshift(quantPartition(Y, N, sbits, B, nextLowband2, LM, gain * side, rshift(fill, B)), rshift(B0, 1))) + else + cm = lshift(quantPartition(Y, N, sbits, B, nextLowband2, LM, gain * side, rshift(fill, B)), rshift(B0, 1)) + rebalance = sbits - (rebalance - ctx.remaining_bits) + if rebalance > 24 and itheta ~= 16384 then + mbits += rebalance - 24 + end + cm = bor(cm, quantPartition(X, N, mbits, B, lowband, LM, gain * mid, fill)) + end + else + local q = bits2pulses(i, LM, b) + local currBits = pulses2bits(i, LM, q) + ctx.remaining_bits -= currBits + while ctx.remaining_bits < 0 and q > 0 do + ctx.remaining_bits += currBits + q -= 1 + currBits = pulses2bits(i, LM, q) + ctx.remaining_bits -= currBits + end + if q ~= 0 then + cm = algUnquant(X, N, getPulses(q), ctx.spread, B, ctx.ec, gain) + else + local cmMask = lshift(1, B) - 1 + fill = band(fill, cmMask) + if fill == 0 then + for j = X + 1, X + N do + W[j] = 0 + end + else + local seed = ctx.seed + if lowband < 0 then + for j = X + 1, X + N do + seed = lcg(seed) + W[j] = signed32(seed) // 1048576 + end + cm = cmMask + else + for j = 0, N - 1 do + seed = lcg(seed) + local tmp = if band(seed, 0x8000) ~= 0 then 1 / 256 else -1 / 256 + W[X + j + 1] = W[lowband + j + 1] + tmp + end + cm = fill + end + ctx.seed = seed + renormaliseVector(X, N, gain) + end + end + end + return cm +end + +local function quantBand(X: number, N: number, b: number, B: number, lowband: number, LM: number, lowbandOut: number, + gain: number, lowbandScratch: number, fill: number): number + local N0 = N + local NB = N + local B0 = B + local timeDivide = 0 + local recombine = 0 + local longBlocks = B0 == 1 + local tfChange = ctx.tf_change + NB = NB // B + if N == 1 then + return quantBandN1(X, -1, lowbandOut) + end + if tfChange > 0 then + recombine = tfChange + end + if lowbandScratch >= 0 and lowband >= 0 and (recombine ~= 0 or (band(NB, 1) == 0 and tfChange < 0) or B0 > 1) then + for j = 1, N do + W[lowbandScratch + j] = W[lowband + j] + end + lowband = lowbandScratch + end + for k = 0, recombine - 1 do + if lowband >= 0 then + haar1(lowband, rshift(N, k), lshift(1, k)) + end + fill = bor(BIT_INTERLEAVE[band(fill, 0xF) + 1], lshift(BIT_INTERLEAVE[rshift(fill, 4) + 1], 2)) + end + B = rshift(B, recombine) + NB = lshift(NB, recombine) + while band(NB, 1) == 0 and tfChange < 0 do + if lowband >= 0 then + haar1(lowband, NB, B) + end + fill = bor(fill, lshift(fill, B)) + B = lshift(B, 1) + NB = rshift(NB, 1) + timeDivide += 1 + tfChange += 1 + end + B0 = B + local NB0 = NB + if B0 > 1 and lowband >= 0 then + deinterleaveHadamard(lowband, rshift(NB, recombine), lshift(B0, recombine), longBlocks) + end + local cm = quantPartition(X, N, b, B, lowband, LM, gain, fill) + if B0 > 1 then + interleaveHadamard(X, rshift(NB, recombine), lshift(B0, recombine), longBlocks) + end + NB = NB0 + B = B0 + for _ = 0, timeDivide - 1 do + B = rshift(B, 1) + NB = lshift(NB, 1) + cm = bor(cm, rshift(cm, B)) + haar1(X, NB, B) + end + for k = 0, recombine - 1 do + cm = BIT_DEINTERLEAVE[cm + 1] + haar1(X, rshift(N0, k), lshift(1, k)) + end + B = lshift(B, recombine) + if lowbandOut >= 0 then + local n = sqrt(N0) + for j = 1, N0 do + W[lowbandOut + j] = n * W[X + j] + end + end + return band(cm, lshift(1, B) - 1) +end + +local function stereoMerge(X: number, Y: number, mid: number, N: number) + local xp, side = 0, 0 + for j = 1, N do + local y = W[Y + j] + xp += y * W[X + j] + side += y * y + end + xp = mid * xp + local mm = mid * mid + local El = mm + side - 2 * xp + local Er = mm + side + 2 * xp + if Er < 6e-4 or El < 6e-4 then + for j = 1, N do + W[Y + j] = W[X + j] + end + return + end + local lgain = 1 / sqrt(El) + local rgain = 1 / sqrt(Er) + for j = 1, N do + local l = mid * W[X + j] + local r = W[Y + j] + W[X + j] = lgain * (l - r) + W[Y + j] = rgain * (l + r) + end +end + +local function quantBandStereo(X: number, Y: number, N: number, b: number, B: number, lowband: number, LM: number, + lowbandOut: number, lowbandScratch: number, fill: number): number + if N == 1 then + return quantBandN1(X, Y, lowbandOut) + end + local origFill = fill + local inv, imid, iside, delta, itheta, qalloc + b, fill, inv, imid, iside, delta, itheta, qalloc = computeTheta(N, b, B, B, LM, true, fill) + local mid = imid / 32768 + local side = iside / 32768 + local cm + if N == 2 then + local mbits = b + local sbits = 0 + if itheta ~= 0 and itheta ~= 16384 then + sbits = 8 + end + mbits -= sbits + local c = itheta > 8192 + ctx.remaining_bits -= qalloc + sbits + local x2, y2 = X, Y + if c then + x2, y2 = Y, X + end + local sign = 0 + if sbits ~= 0 then + sign = decBits(ctx.ec, 1) + end + sign = 1 - 2 * sign + cm = quantBand(x2, N, mbits, B, lowband, LM, lowbandOut, 1, lowbandScratch, origFill) + W[y2 + 1] = -sign * W[x2 + 2] + W[y2 + 2] = sign * W[x2 + 1] + local x0, x1 = mid * W[X + 1], mid * W[X + 2] + local y0, y1 = side * W[Y + 1], side * W[Y + 2] + W[X + 1] = x0 - y0 + W[Y + 1] = x0 + y0 + W[X + 2] = x1 - y1 + W[Y + 2] = x1 + y1 + else + local mbits = imax(0, imin(b, tdiv(b - delta, 2))) + local sbits = b - mbits + ctx.remaining_bits -= qalloc + local rebalance = ctx.remaining_bits + if mbits >= sbits then + cm = quantBand(X, N, mbits, B, lowband, LM, lowbandOut, 1, lowbandScratch, fill) + rebalance = mbits - (rebalance - ctx.remaining_bits) + if rebalance > 24 and itheta ~= 0 then + sbits += rebalance - 24 + end + cm = bor(cm, quantBand(Y, N, sbits, B, -1, LM, -1, side, -1, rshift(fill, B))) + else + cm = quantBand(Y, N, sbits, B, -1, LM, -1, side, -1, rshift(fill, B)) + rebalance = sbits - (rebalance - ctx.remaining_bits) + if rebalance > 24 and itheta ~= 16384 then + mbits += rebalance - 24 + end + cm = bor(cm, quantBand(X, N, mbits, B, lowband, LM, lowbandOut, 1, lowbandScratch, fill)) + end + end + if N ~= 2 then + stereoMerge(X, Y, mid, N) + end + if inv then + for j = Y + 1, Y + N do + W[j] = -W[j] + end + end + return cm +end + +local function quantAllBands(start: number, endb: number, hasY: boolean, N: number, collapse: { number }, + pulses: { number }, shortBlocks: boolean, spread: number, dualStereo: boolean, intensity: number, + tfRes: { number }, totalBits: number, balance: number, ec: RD.Dec, LM: number, codedBands: number, + seed: number, disableInv: boolean): number + local M = lshift(1, LM) + local B = if shortBlocks then M else 1 + local normOffset = M * EB[start + 1] + local C = if hasY then 2 else 1 + local norm = NORM_BASE + local norm2 = NORM_BASE + M * EB[NB_EBANDS] - normOffset + local lowbandScratch = M * EB[EFF_EBANDS] + local lowbandOffset = 0 + local updateLowband = true + ctx.ec = ec + ctx.intensity = intensity + ctx.seed = seed + ctx.spread = spread + ctx.disable_inv = disableInv + ctx.avoid_split_noise = B > 1 + for i = start, endb - 1 do + ctx.i = i + local last = i == endb - 1 + local X = M * EB[i + 1] + local Y = if hasY then N + M * EB[i + 1] else -1 + local Nb = M * EB[i + 2] - M * EB[i + 1] + local t = tellFrac(ec) + if i ~= start then + balance -= t + end + local remainingBits = totalBits - t - 1 + ctx.remaining_bits = 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 (M * EB[i + 1] - Nb >= M * EB[start + 1] or i == start + 1) and (updateLowband or lowbandOffset == 0) then + lowbandOffset = i + end + if i == start + 1 then + local n1 = M * (EB[start + 2] - EB[start + 1]) + local n2 = M * (EB[start + 3] - EB[start + 2]) + for k = 0, n2 - n1 - 1 do + W[norm + n1 + k + 1] = W[norm + 2 * n1 - n2 + k + 1] + end + if dualStereo then + for k = 0, n2 - n1 - 1 do + W[norm2 + n1 + k + 1] = W[norm2 + 2 * n1 - n2 + k + 1] + end + end + end + local tfChange = tfRes[i + 1] + ctx.tf_change = tfChange + if last then + lowbandScratch = -1 + end + local effectiveLowband = -1 + local xcm, ycm + if lowbandOffset ~= 0 and (spread ~= SPREAD_AGGRESSIVE or B > 1 or tfChange < 0) then + effectiveLowband = imax(0, M * EB[lowbandOffset + 1] - normOffset - Nb) + local foldStart = lowbandOffset + repeat + foldStart -= 1 + until M * EB[foldStart + 1] <= effectiveLowband + normOffset + local foldEnd = lowbandOffset - 1 + repeat + foldEnd += 1 + until not (foldEnd < i and M * EB[foldEnd + 1] < effectiveLowband + normOffset + Nb) + xcm, ycm = 0, 0 + local fi = foldStart + repeat + xcm = bor(xcm, collapse[fi * C + 1]) + ycm = bor(ycm, collapse[fi * C + C]) + fi += 1 + until fi >= foldEnd + else + xcm = lshift(1, B) - 1 + ycm = xcm + end + if dualStereo and i == intensity then + dualStereo = false + for j = 1, M * EB[i + 1] - normOffset do + W[norm + j] = 0.5 * (W[norm + j] + W[norm2 + j]) + end + end + if dualStereo then + xcm = quantBand(X, Nb, b // 2, B, if effectiveLowband ~= -1 then norm + effectiveLowband else -1, LM, + if last then -1 else norm + M * EB[i + 1] - normOffset, 1, lowbandScratch, xcm) + ycm = quantBand(Y, Nb, b // 2, B, if effectiveLowband ~= -1 then norm2 + effectiveLowband else -1, LM, + if last then -1 else norm2 + M * EB[i + 1] - normOffset, 1, lowbandScratch, ycm) + else + local lb = if effectiveLowband ~= -1 then norm + effectiveLowband else -1 + local lo = if last then -1 else norm + M * EB[i + 1] - normOffset + if hasY then + xcm = quantBandStereo(X, Y, Nb, b, B, lb, LM, lo, lowbandScratch, bor(xcm, ycm)) + else + xcm = quantBand(X, Nb, b, B, lb, LM, lo, 1, lowbandScratch, bor(xcm, ycm)) + end + ycm = xcm + end + collapse[i * C + 1] = band(xcm, 255) + collapse[i * C + C] = band(ycm, 255) + balance += pulses[i + 1] + t + updateLowband = b > Nb * 8 + ctx.avoid_split_noise = false + end + return ctx.seed +end + +local function antiCollapse(st: any, C: number, size: number, LM: number, start: number, endb: number, + collapse: { number }, pulses: { number }, seed: number) + local logE, prev1logE, prev2logE = st.oldBandE, st.oldLogE, st.oldLogE2 + for i = start, endb - 1 do + local N0 = EB[i + 2] - EB[i + 1] + local depth = rshift((1 + pulses[i + 1]) // N0, LM) + local thresh = 0.5 * exp2(-0.125 * depth) + local sqrt1 = 1 / sqrt(N0 * 2 ^ LM) + for c = 0, C - 1 do + local k0 = c * NB_EBANDS + i + 1 + local prev1 = prev1logE[k0] + local prev2 = prev2logE[k0] + if C == 1 then + prev1 = max(prev1, prev1logE[NB_EBANDS + i + 1]) + prev2 = max(prev2, prev2logE[NB_EBANDS + i + 1]) + end + local Ediff = max(0, logE[k0] - min(prev1, prev2)) + local r = 2 * exp2(-Ediff) + if LM == 3 then + r *= 1.41421356 + end + r = min(thresh, r) * sqrt1 + local X = c * size + EB[i + 1] * 2 ^ LM + local renorm = false + local cmask = collapse[i * C + c + 1] + for k = 0, 2 ^ LM - 1 do + if band(cmask, lshift(1, k)) == 0 then + for j = 0, N0 - 1 do + seed = lcg(seed) + W[X + j * 2 ^ LM + k + 1] = if band(seed, 0x8000) ~= 0 then r else -r + end + renorm = true + end + end + if renorm then + renormaliseVector(X, N0 * 2 ^ LM, 1) + end + end + end +end + +-- --------------------------------------------------------------------------------------------------------------- +-- synthesis + +local function denormaliseBands(X: number, freq: { number }, logE: { number }, eoff: number, start: number, endb: number, M: number, silence: boolean) + local N = M * SHORT_MDCT + local bound = M * EB[endb + 1] + if silence then + bound = 0 + start = 0 + endb = 0 + end + local f = 1 + local x = X + M * EB[start + 1] + if start ~= 0 then + for _ = 1, M * EB[start + 1] do + freq[f] = 0 + f += 1 + end + end + for i = start, endb - 1 do + local bandEnd = M * EB[i + 2] + local lg = logE[eoff + i + 1] + E_MEANS[i + 1] + local g = exp2(min(32, lg)) + for _ = M * EB[i + 1], bandEnd - 1 do + freq[f] = W[x + 1] * g + f += 1 + x += 1 + end + end + for k = bound + 1, N do + freq[k] = 0 + end +end + +local function celtSynthesis(st: any, C: number, CC: number, start: number, effEnd: number, isTransient: boolean, LM: number, silence: boolean, N: number) + local M = lshift(1, LM) + local B, NB, shift + if isTransient then + B = M + NB = SHORT_MDCT + shift = MAX_LM + else + B = 1 + NB = SHORT_MDCT * M + shift = MAX_LM - LM + end + local outBase = DECODE_BUFFER_SIZE - N + 1 + local oldE = st.oldBandE + local freq = FREQ + if CC == 2 and C == 1 then + denormaliseBands(0, freq, oldE, 0, start, effEnd, M, silence) + for c = 1, 2 do + local mem = st.mem[c] + for b = 0, B - 1 do + Mdct.backward(freq, b + 1, mem, outBase + NB * b, WINDOW, OVERLAP, shift, B) + end + end + elseif CC == 1 and C == 2 then + denormaliseBands(0, freq, oldE, 0, start, effEnd, M, silence) + denormaliseBands(N, FREQ2, oldE, NB_EBANDS, start, effEnd, M, silence) + local f2 = FREQ2 + for k = 1, N do + freq[k] = 0.5 * freq[k] + 0.5 * f2[k] + end + local mem = st.mem[1] + for b = 0, B - 1 do + Mdct.backward(freq, b + 1, mem, outBase + NB * b, WINDOW, OVERLAP, shift, B) + end + else + for c = 0, CC - 1 do + denormaliseBands(c * N, freq, oldE, c * NB_EBANDS, start, effEnd, M, silence) + local mem = st.mem[c + 1] + for b = 0, B - 1 do + Mdct.backward(freq, b + 1, mem, outBase + NB * b, WINDOW, OVERLAP, shift, B) + end + end + end +end + +-- comb_filter, in place on mem (1-based base index of sample 0) +local function combFilter(mem: { number }, base: number, T0: number, T1: number, N: number, g0: number, g1: number, + tapset0: number, tapset1: number, overlap: number) + if g0 == 0 and g1 == 0 then + return + end + T0 = imax(T0, COMBFILTER_MINPERIOD) + T1 = imax(T1, COMBFILTER_MINPERIOD) + local ga, gb = COMB_GAINS[tapset0 + 1], COMB_GAINS[tapset1 + 1] + local g00, g01, g02 = g0 * ga[1], g0 * ga[2], g0 * ga[3] + local g10, g11, g12 = g1 * gb[1], g1 * gb[2], g1 * gb[3] + local x1 = mem[base - T1 + 1] + local x2 = mem[base - T1] + local x3 = mem[base - T1 - 1] + local x4 = mem[base - T1 - 2] + if g0 == g1 and T0 == T1 and tapset0 == tapset1 then + overlap = 0 + end + local i = 0 + while i < overlap do + local p = base + i + local x0 = mem[p - T1 + 2] + local w = WINDOW[i + 1] + local f = w * w + local of = 1 - f + mem[p] = mem[p] + (of * g00) * mem[p - T0] + (of * g01) * (mem[p - T0 + 1] + mem[p - T0 - 1]) + + (of * g02) * (mem[p - T0 + 2] + mem[p - T0 - 2]) + (f * g10) * x2 + (f * g11) * (x1 + x3) + + (f * g12) * (x0 + x4) + x4 = x3 + x3 = x2 + x2 = x1 + x1 = x0 + i += 1 + end + if g1 == 0 then + return + end + -- constant part (comb_filter_const) + local p = base + i + x4 = mem[p - T1 - 2] + x3 = mem[p - T1 - 1] + x2 = mem[p - T1] + x1 = mem[p - T1 + 1] + for q = p, base + N - 1 do + local x0 = mem[q - T1 + 2] + mem[q] = mem[q] + g10 * x2 + g11 * (x1 + x3) + g12 * (x0 + x4) + x4 = x3 + x3 = x2 + x2 = x1 + x1 = x0 + end +end + +local function deemphasis(st: any, CC: number, N: number, pcm: { number }, pbase: number, accum: boolean) + local coef0 = PREEMPH + local xbase = DECODE_BUFFER_SIZE - N + for c = 0, CC - 1 do + local x = st.mem[c + 1] + local m = st.preemph[c + 1] + local y = pbase + c + if accum then + for j = 1, N do + local tmp = x[xbase + j] + 1e-30 + m + m = coef0 * tmp + pcm[y] += tmp * (1 / 32768) + y += CC + end + else + for j = 1, N do + local tmp = x[xbase + j] + 1e-30 + m + m = coef0 * tmp + pcm[y] = tmp * (1 / 32768) + y += CC + end + end + st.preemph[c + 1] = m + end +end + +-- --------------------------------------------------------------------------------------------------------------- +-- decoder state + +local function resetState(st: any) + st.rng = 0 + st.error = 0 + st.loss_duration = 0 + st.plc_duration = 0 + st.last_frame_type = FRAME_NONE + st.skip_plc = true + st.postfilter_period = 0 + st.postfilter_period_old = 0 + st.postfilter_gain = 0 + st.postfilter_gain_old = 0 + st.postfilter_tapset = 0 + st.postfilter_tapset_old = 0 + st.preemph[1] = 0 + st.preemph[2] = 0 + for c = 1, st.channels do + local m = st.mem[c] + for k = 1, DECODE_BUFFER_SIZE + OVERLAP do + m[k] = 0 + end + end + for k = 1, 2 * NB_EBANDS do + st.oldBandE[k] = 0 + st.oldLogE[k] = -28 + st.oldLogE2[k] = -28 + st.backgroundLogE[k] = 0 + end +end + +-- celt_decoder_init(48000, channels) +function Celt.new(channels: number): any + local st = { + channels = channels, + stream_channels = channels, + start = 0, + ["end"] = EFF_EBANDS, + disable_inv = channels == 1, + mem = {}, + preemph = { 0, 0 }, + oldBandE = table.create(2 * NB_EBANDS, 0), + oldLogE = table.create(2 * NB_EBANDS, -28), + oldLogE2 = table.create(2 * NB_EBANDS, -28), + backgroundLogE = table.create(2 * NB_EBANDS, 0), + } + for c = 1, channels do + st.mem[c] = table.create(DECODE_BUFFER_SIZE + OVERLAP, 0) + end + resetState(st) + return st +end + +Celt.reset = resetState + +-- noise-based concealment (celt_decode_lost, FRAME_PLC_NOISE) +local function decodeLost(st: any, N: number, LM: number) + local C = st.channels + local start = st.start + local endb = st["end"] + local effEnd = imax(start, imin(endb, EFF_EBANDS)) + for c = 1, C do + table.move(st.mem[c], N + 1, DECODE_BUFFER_SIZE + OVERLAP, 1) + end + local decay = 2 ^ LM * 0.0625 + if st.last_frame_type ~= FRAME_PLC_NOISE then + decay += max(1, imin(160, st.loss_duration) * 0.0625) + end + local oldE, bg = st.oldBandE, st.backgroundLogE + for c = 0, C - 1 do + for i = start, endb - 1 do + local k = c * NB_EBANDS + i + 1 + oldE[k] = max(bg[k], oldE[k] - decay) + end + end + local seed = st.rng + for c = 0, C - 1 do + for i = start, effEnd - 1 do + local boffs = N * c + EB[i + 1] * 2 ^ LM + local blen = (EB[i + 2] - EB[i + 1]) * 2 ^ LM + for j = 1, blen do + seed = lcg(seed) + W[boffs + j] = signed32(seed) // 1048576 + end + renormaliseVector(boffs, blen, 1) + end + end + st.rng = seed + celtSynthesis(st, C, C, start, effEnd, false, LM, false, N) + local base = DECODE_BUFFER_SIZE - N + 1 + for c = 1, C do + st.postfilter_period = imax(st.postfilter_period, COMBFILTER_MINPERIOD) + st.postfilter_period_old = imax(st.postfilter_period_old, COMBFILTER_MINPERIOD) + combFilter(st.mem[c], base, st.postfilter_period_old, st.postfilter_period, SHORT_MDCT, st.postfilter_gain_old, + st.postfilter_gain, st.postfilter_tapset_old, st.postfilter_tapset, OVERLAP) + if LM ~= 0 then + combFilter(st.mem[c], base + SHORT_MDCT, st.postfilter_period, st.postfilter_period, N - SHORT_MDCT, + st.postfilter_gain, st.postfilter_gain, st.postfilter_tapset, st.postfilter_tapset, OVERLAP) + end + end + st.postfilter_period_old = st.postfilter_period + st.postfilter_gain_old = st.postfilter_gain + st.postfilter_tapset_old = st.postfilter_tapset + st.skip_plc = true + st.loss_duration = imin(10000, st.loss_duration + 2 ^ LM) + st.plc_duration = imin(10000, st.plc_duration + 2 ^ LM) + st.last_frame_type = FRAME_PLC_NOISE +end + +-- celt_decode_with_ec. pcm[pbase + j * channels + c]; frameSize at 48 kHz. dec may be nil (a new range decoder over +-- buf[off, off + len)). buf == nil or len <= 1 conceals. Returns the samples per channel, or < 0 on error. +function Celt.decode(st: any, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number, + dec: RD.Dec?, accum: boolean): number + local CC = st.channels + local C = st.stream_channels + local start = st.start + local endb = st["end"] + local LM = 0 + while LM <= MAX_LM and lshift(SHORT_MDCT, LM) ~= frameSize do + LM += 1 + end + if LM > MAX_LM then + return -1 + end + local M = lshift(1, LM) + if len < 0 or len > 1275 then + return -1 + end + local N = M * SHORT_MDCT + local effEnd = imin(endb, EFF_EBANDS) + if buf == nil or len <= 1 then + decodeLost(st, N, LM) + deemphasis(st, CC, N, pcm, pbase, accum) + return frameSize + end + if st.loss_duration == 0 then + st.skip_plc = false + end + if dec == nil then + dec = RD.new(buf :: buffer, off, len) + end + local ec = dec :: RD.Dec + local oldBandE, oldLogE, oldLogE2, bgLogE = st.oldBandE, st.oldLogE, st.oldLogE2, st.backgroundLogE + if C == 1 then + for i = 1, NB_EBANDS do + oldBandE[i] = max(oldBandE[i], oldBandE[NB_EBANDS + i]) + end + end + local totalBits = len * 8 + local t = tell(ec) + local silence + if t >= totalBits then + silence = true + elseif t == 1 then + silence = decBitLogp(ec, 15) + else + silence = false + end + if silence then + t = len * 8 + ec.nbits_total += t - tell(ec) + end + local postfilterGain, postfilterPitch, postfilterTapset = 0, 0, 0 + if start == 0 and t + 16 <= totalBits then + if decBitLogp(ec, 1) then + local octave = decUint(ec, 6) + postfilterPitch = lshift(16, octave) + decBits(ec, 4 + octave) - 1 + local qg = decBits(ec, 3) + if tell(ec) + 2 <= totalBits then + postfilterTapset = decIcdf(ec, TAPSET_ICDF, 1, 2) + end + postfilterGain = 0.09375 * (qg + 1) + end + t = tell(ec) + end + local isTransient = false + if LM > 0 and t + 3 <= totalBits then + isTransient = decBitLogp(ec, 3) + t = tell(ec) + end + local shortBlocks = isTransient + local intraEner = if t + 3 <= totalBits then decBitLogp(ec, 3) else false + if not intraEner and st.loss_duration ~= 0 then + local missing = imin(10, rshift(st.loss_duration, LM)) + local safety = if LM == 0 then 1.5 elseif LM == 1 then 0.5 else 0 + for c = 0, 1 do + for i = start, endb - 1 do + local k = c * NB_EBANDS + i + 1 + if oldBandE[k] < max(oldLogE[k], oldLogE2[k]) then + local E0, E1, E2 = oldBandE[k], oldLogE[k], oldLogE2[k] + local slope = max(E1 - E0, 0.5 * (E2 - E0)) + slope = min(slope, 2) + E0 -= max(0, (1 + missing) * slope) + oldBandE[k] = max(-20, E0) + else + oldBandE[k] = min(min(oldBandE[k], oldLogE[k]), oldLogE2[k]) + end + oldBandE[k] -= safety + end + end + end + unquantCoarseEnergy(st, start, endb, intraEner, ec, C, LM) + + -- tf_decode + local tfRes = TF_RES + do + local budget = ec.storage * 8 + local tt = tell(ec) + local logp = if isTransient then 2 else 4 + local tfSelectRsv = LM > 0 and tt + logp + 1 <= budget + if tfSelectRsv then + budget -= 1 + end + local tfChanged, curr = 0, 0 + for i = start, endb - 1 do + if tt + logp <= budget then + if decBitLogp(ec, logp) then + curr = bit32.bxor(curr, 1) + end + tt = tell(ec) + tfChanged = bor(tfChanged, curr) + end + tfRes[i + 1] = curr + logp = if isTransient then 4 else 5 + end + local tfSelect = 0 + local row = TF_SELECT[LM + 1] + local ti = if isTransient then 4 else 0 + if tfSelectRsv and row[ti + tfChanged + 1] ~= row[ti + 2 + tfChanged + 1] then + tfSelect = if decBitLogp(ec, 1) then 1 else 0 + end + for i = start, endb - 1 do + tfRes[i + 1] = row[ti + 2 * tfSelect + tfRes[i + 1] + 1] + end + end + + t = tell(ec) + local spread = 2 + if t + 4 <= totalBits then + spread = decIcdf(ec, SPREAD_ICDF, 1, 5) + end + local cap = 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 = OFFSETS + local dynallocLogp = 6 + totalBits *= 8 + t = tellFrac(ec) + for i = start, endb - 1 do + local width = C * (EB[i + 2] - EB[i + 1]) * 2 ^ LM + local quanta = imin(width * 8, imax(48, width)) + local loopLogp = dynallocLogp + local boost = 0 + while t + loopLogp * 8 < totalBits and boost < cap[i + 1] do + local flag = decBitLogp(ec, loopLogp) + t = tellFrac(ec) + if not flag then + break + end + boost += quanta + totalBits -= quanta + loopLogp = 1 + end + offsets[i + 1] = boost + if boost > 0 then + dynallocLogp = imax(2, dynallocLogp - 1) + end + end + local allocTrim = if t + 48 <= totalBits then decIcdf(ec, TRIM_ICDF, 1, 7) else 5 + local bits = len * 64 - tellFrac(ec) - 1 + local antiCollapseRsv = if isTransient and LM >= 2 and bits >= (LM + 2) * 8 then 8 else 0 + bits -= antiCollapseRsv + local pulses, fineQuant, finePriority = PULSES, FINE_QUANT, FINE_PRIORITY + local codedBands, balance, intensity, dualStereo = computeAllocation(start, endb, offsets, cap, allocTrim, bits, + pulses, fineQuant, finePriority, C, LM, ec) + unquantFineEnergy(st, start, endb, fineQuant, ec, C) + + -- shift the decoder memory by one frame + for c = 1, CC do + table.move(st.mem[c], N + 1, DECODE_BUFFER_SIZE + OVERLAP, 1) + end + + local collapse = COLLAPSE + st.rng = quantAllBands(start, endb, C == 2, N, collapse, pulses, shortBlocks, spread, dualStereo, intensity, tfRes, + len * 64 - antiCollapseRsv, balance, ec, LM, codedBands, st.rng, st.disable_inv) + + local antiCollapseOn = false + if antiCollapseRsv > 0 then + antiCollapseOn = decBits(ec, 1) ~= 0 + end + unquantEnergyFinalise(st, start, endb, fineQuant, finePriority, len * 8 - tell(ec), ec, C) + if antiCollapseOn then + antiCollapse(st, C, N, LM, start, endb, collapse, pulses, st.rng) + end + if silence then + for i = 1, C * NB_EBANDS do + oldBandE[i] = -28 + end + end + + celtSynthesis(st, C, CC, start, effEnd, isTransient, LM, silence, N) + + local base = DECODE_BUFFER_SIZE - N + 1 + for c = 1, CC do + st.postfilter_period = imax(st.postfilter_period, COMBFILTER_MINPERIOD) + st.postfilter_period_old = imax(st.postfilter_period_old, COMBFILTER_MINPERIOD) + combFilter(st.mem[c], base, st.postfilter_period_old, st.postfilter_period, SHORT_MDCT, st.postfilter_gain_old, + st.postfilter_gain, st.postfilter_tapset_old, st.postfilter_tapset, OVERLAP) + if LM ~= 0 then + combFilter(st.mem[c], base + SHORT_MDCT, st.postfilter_period, postfilterPitch, N - SHORT_MDCT, + st.postfilter_gain, postfilterGain, st.postfilter_tapset, postfilterTapset, OVERLAP) + end + end + st.postfilter_period_old = st.postfilter_period + st.postfilter_gain_old = st.postfilter_gain + st.postfilter_tapset_old = st.postfilter_tapset + st.postfilter_period = postfilterPitch + st.postfilter_gain = postfilterGain + st.postfilter_tapset = postfilterTapset + if LM ~= 0 then + st.postfilter_period_old = st.postfilter_period + st.postfilter_gain_old = st.postfilter_gain + st.postfilter_tapset_old = st.postfilter_tapset + end + + if C == 1 then + for i = 1, NB_EBANDS do + oldBandE[NB_EBANDS + i] = oldBandE[i] + end + end + if not isTransient then + for i = 1, 2 * NB_EBANDS do + oldLogE2[i] = oldLogE[i] + oldLogE[i] = oldBandE[i] + end + else + for i = 1, 2 * NB_EBANDS do + oldLogE[i] = min(oldLogE[i], oldBandE[i]) + end + end + local maxBgIncrease = imin(160, st.loss_duration + M) * 0.001 + for i = 1, 2 * NB_EBANDS do + bgLogE[i] = min(bgLogE[i] + maxBgIncrease, oldBandE[i]) + end + for c = 0, 1 do + for i = 0, start - 1 do + local k = c * NB_EBANDS + i + 1 + oldBandE[k] = 0 + oldLogE[k] = -28 + oldLogE2[k] = -28 + end + for i = endb, NB_EBANDS - 1 do + local k = c * NB_EBANDS + i + 1 + oldBandE[k] = 0 + oldLogE[k] = -28 + oldLogE2[k] = -28 + end + end + st.rng = ec.rng + deemphasis(st, CC, N, pcm, pbase, accum) + st.loss_duration = 0 + st.plc_duration = 0 + st.last_frame_type = FRAME_NORMAL + if tell(ec) > 8 * len then + return -3 + end + if ec.error ~= 0 then + st.error = 1 + end + return frameSize +end + +return Celt diff --git a/src/Formats/audio/opus/CeltTables.luau b/src/Formats/audio/opus/CeltTables.luau new file mode 100644 index 0000000..5dd247f --- /dev/null +++ b/src/Formats/audio/opus/CeltTables.luau @@ -0,0 +1,58 @@ +--!strict +-- audio/opus/CeltTables: Generated from libopus celt/static_modes_float.h and celt/quant_bands.c (BSD, see licenses/). 1-based arrays. +return { +logN400 = { + 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 16, 16, 16, 21, 21, 24, 29, 34, 36, +}, +cache_index50 = { + -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 41, 41, 41, 82, 82, 123, 164, 200, 222, 0, 0, 0, + 0, 0, 0, 0, 0, 41, 41, 41, 41, 123, 123, 123, 164, 164, 240, 266, 283, 295, 41, 41, 41, 41, 41, 41, + 41, 41, 123, 123, 123, 123, 240, 240, 240, 266, 266, 305, 318, 328, 336, 123, 123, 123, 123, 123, 123, 123, 123, 240, + 240, 240, 240, 305, 305, 305, 318, 318, 343, 351, 358, 364, 240, 240, 240, 240, 240, 240, 240, 240, 305, 305, 305, 305, + 343, 343, 343, 351, 351, 370, 376, 382, 387, +}, +cache_bits50 = { + 40, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 40, 15, 23, 28, 31, 34, 36, + 38, 39, 41, 42, 43, 44, 45, 46, 47, 47, 49, 50, 51, 52, 53, 54, 55, 55, 57, 58, 59, 60, 61, 62, + 63, 63, 65, 66, 67, 68, 69, 70, 71, 71, 40, 20, 33, 41, 48, 53, 57, 61, 64, 66, 69, 71, 73, 75, + 76, 78, 80, 82, 85, 87, 89, 91, 92, 94, 96, 98, 101, 103, 105, 107, 108, 110, 112, 114, 117, 119, 121, 123, + 124, 126, 128, 40, 23, 39, 51, 60, 67, 73, 79, 83, 87, 91, 94, 97, 100, 102, 105, 107, 111, 115, 118, 121, + 124, 126, 129, 131, 135, 139, 142, 145, 148, 150, 153, 155, 159, 163, 166, 169, 172, 174, 177, 179, 35, 28, 49, 65, + 78, 89, 99, 107, 114, 120, 126, 132, 136, 141, 145, 149, 153, 159, 165, 171, 176, 180, 185, 189, 192, 199, 205, 211, + 216, 220, 225, 229, 232, 239, 245, 251, 21, 33, 58, 79, 97, 112, 125, 137, 148, 157, 166, 174, 182, 189, 195, 201, + 207, 217, 227, 235, 243, 251, 17, 35, 63, 86, 106, 123, 139, 152, 165, 177, 187, 197, 206, 214, 222, 230, 237, 250, + 25, 31, 55, 75, 91, 105, 117, 128, 138, 146, 154, 161, 168, 174, 180, 185, 190, 200, 208, 215, 222, 229, 235, 240, + 245, 255, 16, 36, 65, 89, 110, 128, 144, 159, 173, 185, 196, 207, 217, 226, 234, 242, 250, 11, 41, 74, 103, 128, + 151, 172, 191, 209, 225, 241, 255, 9, 43, 79, 110, 138, 163, 186, 207, 227, 246, 12, 39, 71, 99, 123, 144, 164, + 182, 198, 214, 228, 241, 253, 9, 44, 81, 113, 142, 168, 192, 214, 235, 255, 7, 49, 90, 127, 160, 191, 220, 247, + 6, 51, 95, 134, 170, 203, 234, 7, 47, 87, 123, 155, 184, 212, 237, 6, 52, 97, 137, 174, 208, 240, 5, 57, + 106, 151, 192, 231, 5, 59, 111, 158, 202, 243, 5, 55, 103, 147, 187, 224, 5, 60, 113, 161, 206, 248, 4, 65, + 122, 175, 224, 4, 67, 127, 182, 234, +}, +cache_caps50 = { + 224, 224, 224, 224, 224, 224, 224, 224, 160, 160, 160, 160, 185, 185, 185, 178, 178, 168, 134, 61, 37, 224, 224, 224, + 224, 224, 224, 224, 224, 240, 240, 240, 240, 207, 207, 207, 198, 198, 183, 144, 66, 40, 160, 160, 160, 160, 160, 160, + 160, 160, 185, 185, 185, 185, 193, 193, 193, 183, 183, 172, 138, 64, 38, 240, 240, 240, 240, 240, 240, 240, 240, 207, + 207, 207, 207, 204, 204, 204, 193, 193, 180, 143, 66, 40, 185, 185, 185, 185, 185, 185, 185, 185, 193, 193, 193, 193, + 193, 193, 193, 183, 183, 172, 138, 65, 39, 207, 207, 207, 207, 207, 207, 207, 207, 204, 204, 204, 204, 201, 201, 201, + 188, 188, 176, 141, 66, 40, 193, 193, 193, 193, 193, 193, 193, 193, 193, 193, 193, 193, 194, 194, 194, 184, 184, 173, + 139, 65, 39, 204, 204, 204, 204, 204, 204, 204, 204, 201, 201, 201, 201, 198, 198, 198, 187, 187, 175, 140, 66, 40, +}, +e_prob_model = { + 72, 127, 65, 129, 66, 128, 65, 128, 64, 128, 62, 128, 64, 128, 64, 128, 92, 78, 92, 79, 92, 78, 90, 79, + 116, 41, 115, 40, 114, 40, 132, 26, 132, 26, 145, 17, 161, 12, 176, 10, 177, 11, 24, 179, 48, 138, 54, 135, + 54, 132, 53, 134, 56, 133, 55, 132, 55, 132, 61, 114, 70, 96, 74, 88, 75, 88, 87, 74, 89, 66, 91, 67, + 100, 59, 108, 50, 120, 40, 122, 37, 97, 43, 78, 50, 83, 78, 84, 81, 88, 75, 86, 74, 87, 71, 90, 73, + 93, 74, 93, 74, 109, 40, 114, 36, 117, 34, 117, 34, 143, 17, 145, 18, 146, 19, 162, 12, 165, 10, 178, 7, + 189, 6, 190, 8, 177, 9, 23, 178, 54, 115, 63, 102, 66, 98, 69, 99, 74, 89, 71, 91, 73, 91, 78, 89, + 86, 80, 92, 66, 93, 64, 102, 59, 103, 60, 104, 60, 117, 52, 123, 44, 138, 35, 133, 31, 97, 38, 77, 45, + 61, 90, 93, 60, 105, 42, 107, 41, 110, 45, 116, 38, 113, 38, 112, 38, 124, 26, 132, 27, 136, 19, 140, 20, + 155, 14, 159, 16, 158, 18, 170, 13, 177, 10, 187, 8, 192, 6, 175, 9, 159, 10, 21, 178, 59, 110, 71, 86, + 75, 85, 84, 83, 91, 66, 88, 73, 87, 72, 92, 75, 98, 72, 105, 58, 107, 54, 115, 52, 114, 55, 112, 56, + 129, 51, 132, 40, 150, 33, 140, 29, 98, 35, 77, 42, 42, 121, 96, 66, 108, 43, 111, 40, 117, 44, 123, 32, + 120, 36, 119, 33, 127, 33, 134, 34, 139, 21, 147, 23, 152, 20, 158, 25, 154, 26, 166, 21, 173, 16, 184, 13, + 184, 10, 150, 13, 139, 15, 22, 178, 63, 114, 74, 82, 84, 83, 92, 82, 103, 62, 96, 72, 96, 67, 101, 73, + 107, 72, 113, 55, 118, 52, 125, 52, 118, 52, 117, 55, 135, 49, 137, 39, 157, 32, 145, 29, 97, 33, 77, 40, +}, +} diff --git a/src/Formats/audio/opus/Decoder.luau b/src/Formats/audio/opus/Decoder.luau new file mode 100644 index 0000000..88e1b22 --- /dev/null +++ b/src/Formats/audio/opus/Decoder.luau @@ -0,0 +1,466 @@ +--!strict +--!native +--!optimize 2 +-- audio/opus/Decoder: The Opus decoder proper (libopus src/opus_decoder.c and opus_multistream_decoder.c): per-frame mode switching +-- between SILK, hybrid and CELT, the redundant CELT frames of mode transitions, cross-fades, PLC fallbacks, the +-- multi-frame packet loop and multistream (channel mapping) decoding. Output is 48 kHz float in Luau arrays. +local RD = require("@formats/audio/opus/RangeDecoder") +local Packet = require("@formats/audio/opus/Packet") +local Celt = require("@formats/audio/opus/Celt") +local Silk = require("@formats/audio/opus/Silk") + +local Decoder = {} + +local MODE_SILK, MODE_HYBRID, MODE_CELT = Packet.MODE_SILK_ONLY, Packet.MODE_HYBRID, Packet.MODE_CELT_ONLY +local BW_NB, BW_MB, BW_WB, BW_SWB = Packet.BW_NB, Packet.BW_MB, Packet.BW_WB, Packet.BW_SWB +local F20, F10, F5, F2_5 = 960, 480, 240, 120 +local min, max = math.min, math.max +local readu8 = buffer.readu8 + +local WINDOW = Celt.window +local TRANS = table.create(F5 * 2, 0) +local REDUND = table.create(F5 * 2, 0) +local SILKTMP = table.create(F10 * 2, 0) +local SILENCE = buffer.create(2) +buffer.writeu8(SILENCE, 0, 0xFF) +buffer.writeu8(SILENCE, 1, 0xFF) +local EMPTY_EC = RD.new(buffer.create(0), 0, 0) +local OFFS = table.create(48, 0) +local SIZES = table.create(48, 0) + +export type State = { + channels: number, + celt: any, + silk: any, + ctrl: any, + stream_channels: number, + frame_size: number, + mode: number, + bandwidth: number, + prev_mode: number, + prev_redundancy: boolean, + last_packet_duration: number, + rangeFinal: number, +} + +function Decoder.new(channels: number): State + return { + channels = channels, + celt = Celt.new(channels), + silk = Silk.new(channels), + ctrl = { + nChannelsAPI = channels, + nChannelsInternal = channels, + API_sampleRate = 48000, + internalSampleRate = 16000, + payloadSize_ms = 20, + }, + stream_channels = channels, + frame_size = 120, + mode = 0, + bandwidth = 0, + prev_mode = 0, + prev_redundancy = false, + last_packet_duration = 0, + rangeFinal = 0, + } +end + +function Decoder.reset(st: State) + Celt.reset(st.celt) + Silk.reset(st.silk) + st.stream_channels = st.channels + st.frame_size = 120 + st.mode = 0 + st.bandwidth = 0 + st.prev_mode = 0 + st.prev_redundancy = false + st.last_packet_duration = 0 + st.rangeFinal = 0 +end + +-- out = w^2 * in2 + (1 - w^2) * in1 over `overlap` samples per channel +local function smoothFade(in1: { number }, b1: number, in2: { number }, b2: number, out: { number }, bo: number, overlap: number, ch: number) + for c = 0, ch - 1 do + for i = 0, overlap - 1 do + local w = WINDOW[i + 1] + w *= w + local k = i * ch + c + out[bo + k] = w * in2[b2 + k] + (1 - w) * in1[b1 + k] + end + end +end + +local function decodeFrame(st: State, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number): number + local ch = st.channels + local celt = st.celt + if frameSize < F2_5 then + return -2 + end + frameSize = min(frameSize, 2880) + local data = buf + if len <= 1 then + data = nil + frameSize = min(frameSize, st.frame_size) + end + local audiosize, mode, bandwidth + local dec = EMPTY_EC + if data then + audiosize = st.frame_size + mode = st.mode + bandwidth = st.bandwidth + dec = RD.new(data, off, len) + else + audiosize = frameSize + mode = if st.prev_redundancy then MODE_CELT else st.prev_mode + bandwidth = 0 + if mode == 0 then + for i = 0, audiosize * ch - 1 do + pcm[pbase + i] = 0 + end + return audiosize + end + if audiosize > F20 then + repeat + local ret = decodeFrame(st, nil, 0, 0, pcm, pbase, min(audiosize, F20)) + if ret < 0 then + return ret + end + pbase += ret * ch + audiosize -= ret + until audiosize <= 0 + return frameSize + elseif audiosize < F20 then + if audiosize > F10 then + audiosize = F10 + elseif mode ~= MODE_SILK and audiosize > F5 and audiosize < F10 then + audiosize = F5 + end + end + end + local celtAccum = mode ~= MODE_CELT + local transition = false + if data and st.prev_mode > 0 + and ((mode == MODE_CELT and st.prev_mode ~= MODE_CELT and not st.prev_redundancy) + or (mode ~= MODE_CELT and st.prev_mode == MODE_CELT)) then + transition = true + end + if transition and mode == MODE_CELT then + decodeFrame(st, nil, 0, 0, TRANS, 1, min(F5, audiosize)) + end + if audiosize > frameSize then + return -1 + end + frameSize = audiosize + + -- SILK + if mode ~= MODE_CELT then + local tooSmall = frameSize < F10 + local sarr, sbase = pcm, pbase + if tooSmall then + sarr, sbase = SILKTMP, 1 + end + if st.prev_mode == MODE_CELT then + Silk.reset(st.silk) + end + local ctrl = st.ctrl + ctrl.payloadSize_ms = max(10, 1000 * audiosize // 48000) + if data then + ctrl.nChannelsInternal = st.stream_channels + if mode == MODE_SILK then + ctrl.internalSampleRate = if bandwidth == BW_NB then 8000 elseif bandwidth == BW_MB then 12000 else 16000 + else + ctrl.internalSampleRate = 16000 + end + end + local lost = if data == nil then 1 else 0 + local decoded = 0 + repeat + local ret, n = Silk.decode(st.silk, ctrl, lost, decoded == 0, dec, sarr, sbase + decoded * ch) + if ret ~= 0 or n <= 0 then + if lost ~= 0 or n <= 0 then + n = frameSize - decoded + for i = 0, n * ch - 1 do + sarr[sbase + decoded * ch + i] = 0 + end + else + return -3 + end + end + decoded += n + until decoded >= frameSize + if tooSmall then + for i = 0, frameSize * ch - 1 do + pcm[pbase + i] = SILKTMP[i + 1] + end + end + end + + local startBand = 0 + local redundancy, celtToSilk = false, false + local redundancyBytes = 0 + if mode ~= MODE_CELT and data and RD.tell(dec) + 17 + (if mode == MODE_HYBRID then 20 else 0) <= 8 * len then + if mode == MODE_HYBRID then + redundancy = RD.bitLogp(dec, 12) + else + redundancy = true + end + if redundancy then + celtToSilk = RD.bitLogp(dec, 1) + redundancyBytes = if mode == MODE_HYBRID then RD.uint(dec, 256) + 2 else len - bit32.rshift(RD.tell(dec) + 7, 3) + len -= redundancyBytes + if len * 8 < RD.tell(dec) then + len = 0 + redundancyBytes = 0 + redundancy = false + end + dec.storage -= redundancyBytes + end + end + if mode ~= MODE_CELT then + startBand = 17 + end + if redundancy then + transition = false + end + if transition and mode ~= MODE_CELT then + decodeFrame(st, nil, 0, 0, TRANS, 1, min(F5, audiosize)) + end + if bandwidth ~= 0 then + celt["end"] = if bandwidth == BW_NB then 13 elseif bandwidth == BW_MB or bandwidth == BW_WB then 17 elseif bandwidth == BW_SWB then 19 else 21 + end + celt.stream_channels = st.stream_channels + local redundantRng = 0 + if redundancy and celtToSilk then + celt.start = 0 + Celt.decode(celt, data, off + len, redundancyBytes, REDUND, 1, F5, nil, false) + redundantRng = celt.rng + end + celt.start = startBand + local celtRet = 0 + if mode ~= MODE_SILK then + local celtFrameSize = min(F20, frameSize) + if mode ~= st.prev_mode and st.prev_mode > 0 and not st.prev_redundancy then + Celt.reset(celt) + end + celtRet = Celt.decode(celt, data, off, len, pcm, pbase, celtFrameSize, if data then dec else nil, celtAccum) + st.rangeFinal = celt.rng + else + if st.prev_mode == MODE_HYBRID and not (redundancy and celtToSilk and st.prev_redundancy) then + celt.start = 0 + Celt.decode(celt, SILENCE, 0, 2, pcm, pbase, F2_5, nil, celtAccum) + end + st.rangeFinal = if data then dec.rng else 0 + end + if redundancy and not celtToSilk then + Celt.reset(celt) + celt.start = 0 + Celt.decode(celt, data, off + len, redundancyBytes, REDUND, 1, F5, nil, false) + redundantRng = celt.rng + local b = pbase + ch * (frameSize - F2_5) + smoothFade(pcm, b, REDUND, 1 + ch * F2_5, pcm, b, F2_5, ch) + end + if redundancy and celtToSilk and (st.prev_mode ~= MODE_SILK or st.prev_redundancy) then + for i = 0, F2_5 * ch - 1 do + pcm[pbase + i] = REDUND[1 + i] + end + smoothFade(REDUND, 1 + ch * F2_5, pcm, pbase + ch * F2_5, pcm, pbase + ch * F2_5, F2_5, ch) + end + if transition then + if audiosize >= F5 then + for i = 0, ch * F2_5 - 1 do + pcm[pbase + i] = TRANS[1 + i] + end + smoothFade(TRANS, 1 + ch * F2_5, pcm, pbase + ch * F2_5, pcm, pbase + ch * F2_5, F2_5, ch) + else + smoothFade(TRANS, 1, pcm, pbase, pcm, pbase, F2_5, ch) + end + end + if len <= 1 then + st.rangeFinal = 0 + else + st.rangeFinal = bit32.bxor(st.rangeFinal, redundantRng) + end + st.prev_mode = mode + st.prev_redundancy = redundancy and not celtToSilk + if celtRet < 0 then + return celtRet + end + return audiosize +end + +-- opus_decode_native: decodes one packet (buf == nil or len == 0: conceal frameSize samples). pcm[pbase + i * ch + c]. +-- Returns the samples per channel (or < 0 on error) and the packet's size (self-delimited packets). +function Decoder.decode(st: State, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number, selfDelimited: boolean?): (number, number) + local ch = st.channels + if buf == nil or len == 0 then + if frameSize % 120 ~= 0 then + return -1, 0 + end + local count = 0 + repeat + local ret = decodeFrame(st, nil, 0, 0, pcm, pbase + count * ch, frameSize - count) + if ret <= 0 then + return if ret < 0 then ret else -3, 0 + end + count += ret + until count >= frameSize + st.last_packet_duration = count + return count, 0 + end + local b = buf :: buffer + local toc = readu8(b, off) + local packetMode = Packet.mode(toc) + local packetBandwidth = Packet.bandwidth(toc) + local packetFrameSize = Packet.samplesPerFrame(toc, 48000) + local packetChannels = Packet.channels(toc) + local count, _, packetOffset = Packet.parse(b, off, len, OFFS, SIZES, selfDelimited) + if count < 0 then + return -4, 0 + end + if count * packetFrameSize > frameSize then + return -2, 0 + end + st.mode = packetMode + st.bandwidth = packetBandwidth + st.frame_size = packetFrameSize + st.stream_channels = packetChannels + local nb = 0 + for i = 1, count do + local ret = decodeFrame(st, b, OFFS[i], SIZES[i], pcm, pbase + nb * ch, frameSize - nb) + if ret < 0 then + return ret, 0 + end + nb += ret + end + st.last_packet_duration = nb + return nb, packetOffset +end + +-- --------------------------------------------------------------------------------------------------------------- +-- multistream (channel mapping families 0 / 1 / 255) + +export type MS = { + channels: number, + streams: number, + coupled: number, + mapping: { number }, + decoders: { State }, + tmp: { number }, +} + +function Decoder.newMultistream(channels: number, streams: number, coupled: number, mapping: { number }): MS + local decs = {} + for s = 0, streams - 1 do + decs[s + 1] = Decoder.new(if s < coupled then 2 else 1) + end + return { + channels = channels, + streams = streams, + coupled = coupled, + mapping = mapping, + decoders = decs, + tmp = table.create(5760 * 2, 0), + } +end + +function Decoder.resetMultistream(ms: MS) + for _, d in ms.decoders do + Decoder.reset(d) + end +end + +-- copies channel `sc` of src (stride sstride) into every output channel mapped to stream channel index `id` +local function copyOut(ms: MS, id: number, src: { number }, sc: number, sstride: number, pcm: { number }, pbase: number, n: number) + local nch = ms.channels + for c = 0, nch - 1 do + if ms.mapping[c + 1] == id then + local o = pbase + c + local s = 1 + sc + for _ = 1, n do + pcm[o] = src[s] + o += nch + s += sstride + end + end + end +end + +-- opus_multistream_decode_native (float). Returns the samples per channel, or < 0 on error. +function Decoder.decodeMultistream(ms: MS, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number): number + local doPlc = buf == nil or len == 0 + frameSize = min(frameSize, 5760) + if not doPlc and len < 2 * ms.streams - 1 then + return -4 + end + local tmp = ms.tmp + for s = 0, ms.streams - 1 do + local d = ms.decoders[s + 1] + if not doPlc and len <= 0 then + return -3 + end + local ret, packetOffset = Decoder.decode(d, if doPlc then nil else buf, off, if doPlc then 0 else len, tmp, 1, frameSize, s ~= ms.streams - 1) + if not doPlc then + off += packetOffset + len -= packetOffset + end + if ret <= 0 then + return if ret < 0 then ret else -3 + end + frameSize = ret + if s < ms.coupled then + copyOut(ms, s * 2, tmp, 0, 2, pcm, pbase, frameSize) + copyOut(ms, s * 2 + 1, tmp, 1, 2, pcm, pbase, frameSize) + else + copyOut(ms, s + ms.coupled, tmp, 0, 1, pcm, pbase, frameSize) + end + end + local nch = ms.channels + for c = 0, nch - 1 do + if ms.mapping[c + 1] == 255 then + local o = pbase + c + for _ = 1, frameSize do + pcm[o] = 0 + o += nch + end + end + end + return frameSize +end + +-- writes src[base + 1 .. base + count] * gain to out as f32 from byte offset o +function Decoder.writeF32(src: { number }, base: number, count: number, gain: number, out: buffer, o: number) + local writef32 = buffer.writef32 + if gain == 1 then + for i = base + 1, base + count do + writef32(out, o, src[i]) + o += 4 + end + else + for i = base + 1, base + count do + writef32(out, o, src[i] * gain) + o += 4 + end + end +end + +-- Stereo downmix of n frames of srcCh-channel audio (src[base + 1 ..], interleaved): matrix[c * 2 + 1 / + 2] are the +-- left / right weights of channel c. Writes f32 to out from byte offset o. +function Decoder.writeDownmix(src: { number }, base: number, n: number, srcCh: number, matrix: { number }, gain: number, out: buffer, o: number) + local writef32 = buffer.writef32 + local p = base + for _ = 1, n do + local l, r = 0, 0 + for c = 0, srcCh - 1 do + local v = src[p + c + 1] + l += v * matrix[c * 2 + 1] + r += v * matrix[c * 2 + 2] + end + writef32(out, o, l * gain) + writef32(out, o + 4, r * gain) + o += 8 + p += srcCh + end +end + +return Decoder diff --git a/src/Formats/audio/opus/Mdct.luau b/src/Formats/audio/opus/Mdct.luau new file mode 100644 index 0000000..43557fe --- /dev/null +++ b/src/Formats/audio/opus/Mdct.luau @@ -0,0 +1,342 @@ +--!strict +--!native +--!optimize 2 +-- audio/opus/Mdct: CELT inverse MDCT (libopus celt/mdct.c clt_mdct_backward) over a mixed-radix complex FFT (a port of the +-- kiss_fft stages used by libopus: radix 5, 3, 4 and 2). The 48 kHz mode uses N = 1920 >> shift for +-- shift = 0..3 (FFT sizes 480, 240, 120, 60). Arrays are Luau tables of numbers, 1-based. +local Mdct = {} + +local sin, cos, pi = math.sin, math.cos, math.pi + +type Plan = { + n: number, -- FFT size (N / 4) + factors: { number }, + bitrev: { number }, + twr: { number }, + twi: { number }, + trig: { number }, -- MDCT twiddles: (-sin, cos) pairs, N / 2 values + fr: { number }, + fi: { number }, +} + +local FACTORS = { + [0] = { 5, 96, 3, 32, 4, 8, 2, 4, 4, 1 }, + [1] = { 5, 48, 3, 16, 4, 4, 4, 1 }, + [2] = { 5, 24, 3, 8, 2, 4, 4, 1 }, + [3] = { 5, 12, 3, 4, 4, 1 }, +} + +local function bitrevTable(f: { number }, fout: number, fpos: number, fstride: number, factors: { number }, fi: number) + local p = factors[fi] + local m = factors[fi + 1] + if m == 1 then + for j = 0, p - 1 do + f[fpos + 1] = fout + j + fpos += fstride + end + else + for j = 0, p - 1 do + bitrevTable(f, fout, fpos, fstride * p, factors, fi + 2) + fpos += fstride + fout += m + end + end +end + +local plans: { Plan } = {} +for shift = 0, 3 do + local N = 1920 // 2 ^ shift + local n = N // 4 + local factors = FACTORS[shift] + local bitrev = table.create(n, 0) + bitrevTable(bitrev, 0, 0, 1, factors, 1) + local twr, twi = table.create(n, 0), table.create(n, 0) + for k = 0, n - 1 do + local ph = -2 * pi * k / n + twr[k + 1] = cos(ph) + twi[k + 1] = sin(ph) + end + local N2, N4 = N // 2, N // 4 + local trig = table.create(N2, 0) + for i = 0, N4 - 1 do + trig[2 * i + 1] = -sin(2 * pi * (i + 0.125) / N) + trig[2 * i + 2] = cos(2 * pi * (i + 0.125) / N) + end + plans[shift + 1] = { + n = n, + factors = factors, + bitrev = bitrev, + twr = twr, + twi = twi, + trig = trig, + fr = table.create(n, 0), + fi = table.create(n, 0), + } +end + +local function bfly2(fr: { number }, fi: { number }, N: number) + local tw = 0.7071067812 + local p = 1 + for _ = 1, N do + -- k = 0 + local tr, ti = fr[p + 4], fi[p + 4] + fr[p + 4] = fr[p] - tr + fi[p + 4] = fi[p] - ti + fr[p] += tr + fi[p] += ti + -- k = 1 + local a, b = fr[p + 5], fi[p + 5] + tr = (a + b) * tw + ti = (b - a) * tw + fr[p + 5] = fr[p + 1] - tr + fi[p + 5] = fi[p + 1] - ti + fr[p + 1] += tr + fi[p + 1] += ti + -- k = 2 + tr = fi[p + 6] + ti = -fr[p + 6] + fr[p + 6] = fr[p + 2] - tr + fi[p + 6] = fi[p + 2] - ti + fr[p + 2] += tr + fi[p + 2] += ti + -- k = 3 + a, b = fr[p + 7], fi[p + 7] + tr = (b - a) * tw + ti = -(b + a) * tw + fr[p + 7] = fr[p + 3] - tr + fi[p + 7] = fi[p + 3] - ti + fr[p + 3] += tr + fi[p + 3] += ti + p += 8 + end +end + +local function bfly4(fr: { number }, fi: { number }, fstride: number, twr: { number }, twi: { number }, m: number, N: number, mm: number) + if m == 1 then + local p = 1 + for _ = 1, N do + local r0, i0 = fr[p], fi[p] + local r1, i1 = fr[p + 1], fi[p + 1] + local r2, i2 = fr[p + 2], fi[p + 2] + local r3, i3 = fr[p + 3], fi[p + 3] + local s0r, s0i = r0 - r2, i0 - i2 + r0 += r2 + i0 += i2 + local s1r, s1i = r1 + r3, i1 + i3 + fr[p + 2] = r0 - s1r + fi[p + 2] = i0 - s1i + fr[p] = r0 + s1r + fi[p] = i0 + s1i + s1r, s1i = r1 - r3, i1 - i3 + fr[p + 1] = s0r + s1i + fi[p + 1] = s0i - s1r + fr[p + 3] = s0r - s1i + fi[p + 3] = s0i + s1r + p += 4 + end + else + local m2, m3 = 2 * m, 3 * m + for i = 0, N - 1 do + local p = i * mm + 1 + local t1, t2, t3 = 1, 1, 1 + for _ = 0, m - 1 do + local ar, ai = fr[p + m], fi[p + m] + local wr, wi = twr[t1], twi[t1] + local s0r, s0i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p + m2], fi[p + m2] + wr, wi = twr[t2], twi[t2] + local s1r, s1i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p + m3], fi[p + m3] + wr, wi = twr[t3], twi[t3] + local s2r, s2i = ar * wr - ai * wi, ar * wi + ai * wr + local f0r, f0i = fr[p], fi[p] + local s5r, s5i = f0r - s1r, f0i - s1i + f0r += s1r + f0i += s1i + local s3r, s3i = s0r + s2r, s0i + s2i + local s4r, s4i = s0r - s2r, s0i - s2i + fr[p + m2] = f0r - s3r + fi[p + m2] = f0i - s3i + t1 += fstride + t2 += fstride * 2 + t3 += fstride * 3 + fr[p] = f0r + s3r + fi[p] = f0i + s3i + fr[p + m] = s5r + s4i + fi[p + m] = s5i - s4r + fr[p + m3] = s5r - s4i + fi[p + m3] = s5i + s4r + p += 1 + end + end + end +end + +local function bfly3(fr: { number }, fi: { number }, fstride: number, twr: { number }, twi: { number }, m: number, N: number, mm: number) + local m2 = 2 * m + local epi3i = twi[fstride * m + 1] + for i = 0, N - 1 do + local p = i * mm + 1 + local t1, t2 = 1, 1 + for _ = 1, m do + local ar, ai = fr[p + m], fi[p + m] + local wr, wi = twr[t1], twi[t1] + local s1r, s1i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p + m2], fi[p + m2] + wr, wi = twr[t2], twi[t2] + local s2r, s2i = ar * wr - ai * wi, ar * wi + ai * wr + local s3r, s3i = s1r + s2r, s1i + s2i + local s0r, s0i = s1r - s2r, s1i - s2i + t1 += fstride + t2 += fstride * 2 + local f0r, f0i = fr[p], fi[p] + local fmr, fmi = f0r - s3r * 0.5, f0i - s3i * 0.5 + s0r *= epi3i + s0i *= epi3i + fr[p] = f0r + s3r + fi[p] = f0i + s3i + fr[p + m2] = fmr + s0i + fi[p + m2] = fmi - s0r + fr[p + m] = fmr - s0i + fi[p + m] = fmi + s0r + p += 1 + end + end +end + +local function bfly5(fr: { number }, fi: { number }, fstride: number, twr: { number }, twi: { number }, m: number, N: number, mm: number) + local yar, yai = twr[fstride * m + 1], twi[fstride * m + 1] + local ybr, ybi = twr[fstride * 2 * m + 1], twi[fstride * 2 * m + 1] + for i = 0, N - 1 do + local p0 = i * mm + 1 + local p1, p2, p3, p4 = p0 + m, p0 + 2 * m, p0 + 3 * m, p0 + 4 * m + for u = 0, m - 1 do + local s0r, s0i = fr[p0], fi[p0] + local k = u * fstride + local ar, ai = fr[p1], fi[p1] + local wr, wi = twr[k + 1], twi[k + 1] + local s1r, s1i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p2], fi[p2] + wr, wi = twr[2 * k + 1], twi[2 * k + 1] + local s2r, s2i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p3], fi[p3] + wr, wi = twr[3 * k + 1], twi[3 * k + 1] + local s3r, s3i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p4], fi[p4] + wr, wi = twr[4 * k + 1], twi[4 * k + 1] + local s4r, s4i = ar * wr - ai * wi, ar * wi + ai * wr + + local s7r, s7i = s1r + s4r, s1i + s4i + local s10r, s10i = s1r - s4r, s1i - s4i + local s8r, s8i = s2r + s3r, s2i + s3i + local s9r, s9i = s2r - s3r, s2i - s3i + + fr[p0] = s0r + (s7r + s8r) + fi[p0] = s0i + (s7i + s8i) + + local s5r = s0r + (s7r * yar + s8r * ybr) + local s5i = s0i + (s7i * yar + s8i * ybr) + local s6r = s10i * yai + s9i * ybi + local s6i = -(s10r * yai + s9r * ybi) + fr[p1] = s5r - s6r + fi[p1] = s5i - s6i + fr[p4] = s5r + s6r + fi[p4] = s5i + s6i + + local s11r = s0r + (s7r * ybr + s8r * yar) + local s11i = s0i + (s7i * ybr + s8i * yar) + local s12r = s9i * yai - s10i * ybi + local s12i = s10r * ybi - s9r * yai + fr[p2] = s11r + s12r + fi[p2] = s11i + s12i + fr[p3] = s11r - s12r + fi[p3] = s11i - s12i + + p0 += 1 + p1 += 1 + p2 += 1 + p3 += 1 + p4 += 1 + end + end +end + +-- in-place forward FFT of bit-reversed input (opus_fft_impl) +local function fftImpl(pl: Plan) + local factors = pl.factors + local fr, fi, twr, twi = pl.fr, pl.fi, pl.twr, pl.twi + local fstride = { 1 } + local L = 0 + local m + repeat + local p = factors[2 * L + 1] + m = factors[2 * L + 2] + fstride[L + 2] = fstride[L + 1] * p + L += 1 + until m == 1 + m = factors[2 * L] + for i = L - 1, 0, -1 do + local m2 = if i ~= 0 then factors[2 * i] else 1 + local radix = factors[2 * i + 1] + if radix == 2 then + bfly2(fr, fi, fstride[i + 1]) + elseif radix == 4 then + bfly4(fr, fi, fstride[i + 1], twr, twi, m, fstride[i + 1], m2) + elseif radix == 3 then + bfly3(fr, fi, fstride[i + 1], twr, twi, m, fstride[i + 1], m2) + else + bfly5(fr, fi, fstride[i + 1], twr, twi, m, fstride[i + 1], m2) + end + m = m2 + end +end + +-- clt_mdct_backward: input coefficients inp[inBase + k*stride] (k = 0 .. N/2-1, inBase is the 1-based index of +-- coefficient 0), output written to out[outBase .. outBase + N/2 + overlap/2) with TDAC windowing of the first +-- `overlap` samples (out[outBase] is sample 0). +function Mdct.backward(inp: { number }, inBase: number, out: { number }, outBase: number, window: { number }, overlap: number, shift: number, stride: number) + local pl = plans[shift + 1] + local N4 = pl.n + local N2 = N4 * 2 + local trig = pl.trig + local bitrev = pl.bitrev + local fr, fi = pl.fr, pl.fi + -- pre-rotate, storing in bit-reversed order (real and imaginary swapped: an FFT is used instead of an IFFT) + local xp1 = inBase + local xp2 = inBase + stride * (N2 - 1) + for i = 0, N4 - 1 do + local x1 = inp[xp1] + local x2 = inp[xp2] + local t0, t1 = trig[2 * i + 1], trig[2 * i + 2] + local rev = bitrev[i + 1] + 1 + fi[rev] = x2 * t1 + x1 * t0 + fr[rev] = x1 * t1 - x2 * t0 + xp1 += 2 * stride + xp2 -= 2 * stride + end + fftImpl(pl) + -- post-rotate + local h = outBase + (overlap // 2) + for k = 0, N4 - 1 do + local re = fi[k + 1] + local im = fr[k + 1] + local t0, t1 = trig[2 * k + 1], trig[2 * k + 2] + out[h + 2 * k] = re * t1 + im * t0 + out[h + N2 - 1 - 2 * k] = re * t0 - im * t1 + end + -- mirror on both sides for TDAC + local xp = outBase + overlap - 1 + local yp = outBase + for i = 0, overlap // 2 - 1 do + local x1 = out[xp] + local x2 = out[yp] + local w1 = window[i + 1] + local w2 = window[overlap - i] + out[yp] = x2 * w2 - x1 * w1 + out[xp] = x2 * w1 + x1 * w2 + xp -= 1 + yp += 1 + end +end + +return Mdct diff --git a/src/Formats/audio/opus/Packet.luau b/src/Formats/audio/opus/Packet.luau new file mode 100644 index 0000000..e8b5749 --- /dev/null +++ b/src/Formats/audio/opus/Packet.luau @@ -0,0 +1,235 @@ +--!strict +--!native +--!optimize 2 +-- audio/opus/Packet: Opus packet framing (RFC 6716 section 3): the TOC byte and frame packing codes 0-3, with padding. +local Packet = {} + +local readu8 = buffer.readu8 +local band, rshift = bit32.band, bit32.rshift + +Packet.MODE_SILK_ONLY = 1000 +Packet.MODE_HYBRID = 1001 +Packet.MODE_CELT_ONLY = 1002 + +-- bandwidths as in libopus (OPUS_BANDWIDTH_NARROWBAND .. FULLBAND) +Packet.BW_NB = 1101 +Packet.BW_MB = 1102 +Packet.BW_WB = 1103 +Packet.BW_SWB = 1104 +Packet.BW_FB = 1105 + +function Packet.mode(toc: number): number + if band(toc, 0x80) ~= 0 then + return Packet.MODE_CELT_ONLY + elseif band(toc, 0x60) == 0x60 then + return Packet.MODE_HYBRID + else + return Packet.MODE_SILK_ONLY + end +end + +function Packet.bandwidth(toc: number): number + if band(toc, 0x80) ~= 0 then + local bw = 1102 + band(rshift(toc, 5), 3) + if bw == 1102 then + bw = 1101 + end + return bw + elseif band(toc, 0x60) == 0x60 then + return if band(toc, 0x10) ~= 0 then 1105 else 1104 + else + return 1101 + band(rshift(toc, 5), 3) + end +end + +function Packet.channels(toc: number): number + return if band(toc, 4) ~= 0 then 2 else 1 +end + +-- samples per frame at rate Fs +function Packet.samplesPerFrame(toc: number, Fs: number): number + if band(toc, 0x80) ~= 0 then + local a = band(rshift(toc, 3), 3) + return bit32.lshift(Fs, a) // 400 + elseif band(toc, 0x60) == 0x60 then + return if band(toc, 0x08) ~= 0 then Fs // 50 else Fs // 100 + else + local a = band(rshift(toc, 3), 3) + if a == 3 then + return Fs * 60 // 1000 + end + return bit32.lshift(Fs, a) // 100 + end +end + +-- total samples of a packet at 48 kHz, or -1 if invalid +function Packet.samples(buf: buffer, off: number, len: number): number + if len < 1 then + return -1 + end + local toc = readu8(buf, off) + local c = band(toc, 3) + local count + if c == 0 then + count = 1 + elseif c ~= 3 then + count = 2 + else + if len < 2 then + return -1 + end + count = band(readu8(buf, off + 1), 0x3F) + end + local n = count * Packet.samplesPerFrame(toc, 48000) + if n * 25 > 48000 * 3 then + return -1 + end + return n +end + +local function parseSize(buf: buffer, p: number, len: number): (number, number) + if len < 1 then + return -1, -1 + end + local b0 = readu8(buf, p) + if b0 < 252 then + return 1, b0 + elseif len < 2 then + return -1, -1 + end + return 2, 4 * readu8(buf, p + 1) + b0 +end + +-- Splits a packet (opus_packet_parse_impl). Fills offsets[i] / sizes[i] (1-based, absolute buffer offsets) and +-- returns the frame count, the TOC byte and the packet's total size including padding (self-delimited packets, as in +-- multistream, carry an explicit size for the last frame). The count is -1 for an invalid packet. +function Packet.parse(buf: buffer, off: number, len: number, offsets: { number }, sizes: { number }, selfDelimited: boolean?): (number, number, number) + if len < 1 then + return -1, 0, 0 + end + local toc = readu8(buf, off) + local framesize = Packet.samplesPerFrame(toc, 48000) + local p = off + 1 + len -= 1 + local lastSize = len + local count + local cbr = false + local pad = 0 + local c = band(toc, 3) + if c == 0 then + count = 1 + elseif c == 1 then + count = 2 + cbr = true + if not selfDelimited then + if band(len, 1) ~= 0 then + return -1, toc, 0 + end + lastSize = len // 2 + sizes[1] = lastSize + end + elseif c == 2 then + count = 2 + local bytes, s = parseSize(buf, p, len) + if bytes < 0 then + return -1, toc, 0 + end + len -= bytes + if s < 0 or s > len then + return -1, toc, 0 + end + sizes[1] = s + p += bytes + lastSize = len - s + else + if len < 1 then + return -1, toc, 0 + end + local ch = readu8(buf, p) + p += 1 + count = band(ch, 0x3F) + if count <= 0 or framesize * count > 5760 then + return -1, toc, 0 + end + len -= 1 + if band(ch, 0x40) ~= 0 then + local pb + repeat + if len <= 0 then + return -1, toc, 0 + end + pb = readu8(buf, p) + p += 1 + len -= 1 + local tmp = if pb == 255 then 254 else pb + len -= tmp + pad += tmp + until pb ~= 255 + end + if len < 0 then + return -1, toc, 0 + end + cbr = band(ch, 0x80) == 0 + if not cbr then + lastSize = len + for i = 1, count - 1 do + local bytes, s = parseSize(buf, p, len) + if bytes < 0 then + return -1, toc, 0 + end + len -= bytes + if s < 0 or s > len then + return -1, toc, 0 + end + sizes[i] = s + p += bytes + lastSize -= bytes + s + end + if lastSize < 0 then + return -1, toc, 0 + end + elseif not selfDelimited then + lastSize = len // count + if lastSize * count ~= len then + return -1, toc, 0 + end + for i = 1, count - 1 do + sizes[i] = lastSize + end + end + end + if selfDelimited then + local bytes, s = parseSize(buf, p, len) + if bytes < 0 then + return -1, toc, 0 + end + len -= bytes + if s < 0 or s > len then + return -1, toc, 0 + end + p += bytes + sizes[count] = s + if cbr then + if s * count > len then + return -1, toc, 0 + end + for i = 1, count - 1 do + sizes[i] = s + end + elseif bytes + s > lastSize then + return -1, toc, 0 + end + else + if lastSize > 1275 then + return -1, toc, 0 + end + sizes[count] = lastSize + end + for i = 1, count do + offsets[i] = p + p += sizes[i] + end + return count, toc, pad + (p - off) +end + +return Packet diff --git a/src/Formats/audio/opus/RangeDecoder.luau b/src/Formats/audio/opus/RangeDecoder.luau new file mode 100644 index 0000000..23d96ce --- /dev/null +++ b/src/Formats/audio/opus/RangeDecoder.luau @@ -0,0 +1,214 @@ +--!strict +--!native +--!optimize 2 +-- audio/opus/RangeDecoder: Range decoder (RFC 6716 section 4.1, libopus celt/entdec.c). Reads one Opus frame from a `buffer` slice +-- [base, base + storage). Raw bits (ec_dec_bits) are read from the end of the slice backwards. +-- All values stay below 2^32, so plain Luau numbers hold them exactly; floor division is exact below 2^52. +local RangeDecoder = {} + +export type Dec = { + buf: buffer, + base: number, + 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 SYM_BITS = 8 +local CODE_BITS = 32 +local CODE_TOP = 2147483648 -- 1 << 31 +local CODE_BOT = 8388608 -- CODE_TOP >> 8 +local CODE_EXTRA = 7 -- (CODE_BITS - 2) % SYM_BITS + 1 +local SYM_MAX = 255 +local UINT_BITS = 8 +local WINDOW_SIZE = 32 + +local countlz = bit32.countlz +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift +local readu8 = buffer.readu8 + +local function ilog(x: number): number + return 32 - countlz(x) +end +RangeDecoder.ilog = ilog + +local function normalize(d: Dec) + local rng, val, rem = d.rng, d.val, d.rem + while rng <= CODE_BOT do + d.nbits_total += SYM_BITS + rng = rng * 256 + local sym = rem + local offs = d.offs + if offs < d.storage then + rem = readu8(d.buf, d.base + offs) + d.offs = offs + 1 + else + rem = 0 + end + sym = rshift(bor(lshift(sym, 8), rem), SYM_BITS - CODE_EXTRA) -- (sym << 8 | rem) >> 1 + val = band(val * 256 + band(SYM_MAX, bit32.bnot(sym)), CODE_TOP - 1) + end + d.rng, d.val, d.rem = rng, val, rem +end + +function RangeDecoder.new(buf: buffer, base: number, storage: number): Dec + local d: Dec = { + buf = buf, + base = base, + storage = storage, + offs = 0, + end_offs = 0, + end_window = 0, + nend_bits = 0, + nbits_total = CODE_BITS + 1 - ((CODE_BITS - CODE_EXTRA) // SYM_BITS) * SYM_BITS, + rng = 128, -- 1 << CODE_EXTRA + val = 0, + rem = 0, + ext = 0, + error = 0, + } + local rem = 0 + if storage > 0 then + rem = readu8(buf, base) + d.offs = 1 + end + d.rem = rem + d.val = d.rng - 1 - rshift(rem, SYM_BITS - CODE_EXTRA) + normalize(d) + return d +end + +-- ec_decode: the cumulative frequency of the next symbol, for a total of ft +function RangeDecoder.decode(d: Dec, ft: number): number + local ext = d.rng // ft + d.ext = ext + local s = d.val // ext + return ft - math.min(s + 1, ft) +end + +function RangeDecoder.decodeBin(d: Dec, bits: number): number + local ext = rshift(d.rng, bits) + d.ext = ext + local s = d.val // ext + local ft = lshift(1, bits) + return ft - math.min(s + 1, ft) +end + +function RangeDecoder.update(d: Dec, fl: number, fh: number, ft: number) + local s = d.ext * (ft - fh) + d.val = band(d.val - s, 0xFFFFFFFF) -- uint32 wrap (corrupt streams only) + if fl > 0 then + d.rng = d.ext * (fh - fl) + else + d.rng -= s + end + normalize(d) +end + +function RangeDecoder.bitLogp(d: Dec, logp: number): boolean + local r = d.rng + local v = d.val + local s = rshift(r, logp) + local ret = v < s + if ret then + d.rng = s + else + d.val = v - s + d.rng = r - s + end + normalize(d) + return ret +end + +-- ec_dec_icdf over a Luau array (1-based) starting at index `off` (icdf[off] is entry 0) +function RangeDecoder.icdf(d: Dec, icdf: { number }, off: number, ftb: number): number + local s = d.rng + local v = d.val + local r = rshift(s, ftb) + local ret = -1 + local t + repeat + t = s + ret += 1 + s = r * icdf[off + ret] + until v >= s + d.val = v - s + d.rng = t - s + normalize(d) + return ret +end + +function RangeDecoder.bits(d: Dec, bits: number): number + local window = d.end_window + local available = d.nend_bits + if available < bits then + repeat + local b = 0 + local eo = d.end_offs + if eo < d.storage then + eo += 1 + d.end_offs = eo + b = readu8(d.buf, d.base + d.storage - eo) + end + window = bor(window, lshift(b, available)) + available += SYM_BITS + until available > WINDOW_SIZE - SYM_BITS + end + local ret = band(window, lshift(1, bits) - 1) + if bits == 32 then + ret = window + end + window = rshift(window, bits) + available -= bits + d.end_window = window + d.nend_bits = available + d.nbits_total += bits + return ret +end + +function RangeDecoder.uint(d: Dec, ft0: number): number + local ft = ft0 - 1 + local ftb = ilog(ft) + if ftb > UINT_BITS then + ftb -= UINT_BITS + local ft1 = rshift(ft, ftb) + 1 + local s = RangeDecoder.decode(d, ft1) + RangeDecoder.update(d, s, s + 1, ft1) + local t = bor(lshift(s, ftb), RangeDecoder.bits(d, ftb)) + if t <= ft then + return t + end + d.error = 1 + return ft + else + local s = RangeDecoder.decode(d, ft0) + RangeDecoder.update(d, s, s + 1, ft0) + return s + end +end + +function RangeDecoder.tell(d: Dec): number + return d.nbits_total - ilog(d.rng) +end + +local correction = { 35733, 38967, 42495, 46340, 50535, 55109, 60097, 65535 } +function RangeDecoder.tellFrac(d: Dec): number + local nbits = d.nbits_total * 8 + local l = ilog(d.rng) + local r = rshift(d.rng, l - 16) + local b = rshift(r, 12) - 8 + if r > correction[b + 1] then + b += 1 + end + return nbits - (l * 8 + b) +end + +return RangeDecoder diff --git a/src/Formats/audio/opus/Silk.luau b/src/Formats/audio/opus/Silk.luau new file mode 100644 index 0000000..428b06b --- /dev/null +++ b/src/Formats/audio/opus/Silk.luau @@ -0,0 +1,2070 @@ +--!strict +--!native +--!optimize 2 +-- audio/opus/Silk: SILK decoder: a bit-exact port of the libopus fixed-point SILK decoder (silk/dec_API.c and what it calls: +-- decode_frame, decode_indices, decode_pulses, shell_coder, code_signs, decode_parameters, gain_quant, NLSF_*, +-- LPC_fit, LPC_inv_pred_gain, decode_core, stereo_*, CNG, PLC, resampler_private_up2_HQ / IIR_FIR). BSD, see +-- licenses/. +-- +-- local st = Silk.new(apiChannels) +-- local ret, n = Silk.decode(st, ctrl, lostFlag, firstFrame, ec, out, outBase) +-- ctrl = { nChannelsAPI, nChannelsInternal, API_sampleRate, internalSampleRate, payloadSize_ms } +-- decodes one 10 / 20 ms SILK frame and writes n samples per channel (at API_sampleRate) to the Luau array +-- `out`, interleaved by nChannelsAPI: out[outBase + i * nChannelsAPI + c], scaled int16 / 32768. +-- +-- Fixed-point emulation: all values are Luau numbers holding C int32 / int16 values. Products of two int32 values +-- (64-bit in C) are split so that every intermediate stays below 2^53 and therefore exact. +local RD = require("@formats/audio/opus/RangeDecoder") +local T = require("@formats/audio/opus/SilkTables") + +local icdf = RD.icdf +local bitLogp = RD.bitLogp +local countlz = bit32.countlz +local floor = math.floor + +local Silk = {} + +local P2 = table.create(64, 0) -- P2[s] = 2^s (1-based by s: P2[s] for s >= 1, P2_0 = 1) +for s = 1, 63 do + P2[s] = 2 ^ s +end +local function p2(s: number): number + if s == 0 then + return 1 + end + return P2[s] +end + +-- C helpers ----------------------------------------------------------------------------------------------------- + +local function s16(x: number): number + x = x % 65536 + if x >= 32768 then + return x - 65536 + end + return x +end + +local function i32(x: number): number + x = x % 4294967296 + if x >= 2147483648 then + return x - 4294967296 + end + return x +end + +local function sat16(x: number): number + if x > 32767 then + return 32767 + elseif x < -32768 then + return -32768 + end + return x +end + +local function addSat32(a: number, b: number): number + local s = a + b + if s > 2147483647 then + return 2147483647 + elseif s < -2147483648 then + return -2147483648 + end + return s +end + +local function subSat32(a: number, b: number): number + local s = a - b + if s > 2147483647 then + return 2147483647 + elseif s < -2147483648 then + return -2147483648 + end + return s +end + +-- silk_CLZ32 of a non-negative int32 +local function clz32(x: number): number + return countlz(x) +end + +-- silk_SMULWW (64-bit form): (a * b) >> 16, exact +local function mulww(a: number, b: number): number + return a * (b // 65536) + (a * (b % 65536)) // 65536 +end + +-- floor(a * b / 2^s) for int32 a, b and s >= 16, exact +local function mulshr(a: number, b: number, s: number): number + local t = a * (b // 65536) + (a * (b % 65536)) // 65536 + if s == 16 then + return t + end + return t // P2[s - 16] +end + +local function smmul(a: number, b: number): number + return mulshr(a, b, 32) +end + +-- silk_RSHIFT_ROUND (shift >= 1) +local function rround(a: number, s: number): number + return (a + p2(s - 1)) // P2[s] +end + +local function lshiftSat32(a: number, sh: number): number + if sh == 0 then + return a + end + local m = P2[sh] + local lo, hi = -2147483648 // m, 2147483647 // m + if a < lo then + a = lo + elseif a > hi then + a = hi + end + return a * m +end + +-- C integer division (truncation toward zero) +local function tdiv(a: number, b: number): number + local q = a / b + if q >= 0 then + return floor(q) + end + return -floor(-q) +end + +-- low 32 bits of a * b, as int32 +local function imul32(a: number, b: number): number + a = a % 4294967296 + local ah, al = a // 65536, a % 65536 + return i32(((ah * b) % 65536) * 65536 + al * b) +end + +local function silkRand(seed: number): number + return i32(907633515 + imul32(seed, 196314165)) +end + +local function rshift(a: number, s: number): number + if s == 0 then + return a + end + return a // P2[s] +end + +local function silkINVERSE32_varQ(b32: number, Qres: number): number + local b_headrm = clz32(math.abs(b32)) - 1 + local b32_nrm = b32 * p2(b_headrm) + local b32_inv = tdiv(536870911, b32_nrm // 65536) + local result = b32_inv * 65536 + local err_Q32 = i32((536870912 - (b32_nrm * b32_inv) // 65536) * 8) + result = i32(result + mulww(err_Q32, b32_inv)) + local lshift = 61 - b_headrm - Qres + if lshift <= 0 then + return lshiftSat32(result, -lshift) + elseif lshift < 32 then + return result // P2[lshift] + end + return 0 +end + +local function silkDIV32_varQ(a32: number, b32: number, Qres: number): number + local a_headrm = clz32(math.abs(a32)) - 1 + local a32_nrm = a32 * p2(a_headrm) + local b_headrm = clz32(math.abs(b32)) - 1 + local b32_nrm = b32 * p2(b_headrm) + local b32_inv = tdiv(536870911, b32_nrm // 65536) + local result = (a32_nrm * s16(b32_inv)) // 65536 + a32_nrm = i32(a32_nrm - i32(smmul(b32_nrm, result) * 8)) + result = result + (a32_nrm * s16(b32_inv)) // 65536 + local lshift = 29 + a_headrm - b_headrm - Qres + if lshift < 0 then + return lshiftSat32(result, -lshift) + elseif lshift < 32 then + return rshift(result, lshift) + end + return 0 +end + +local function silkLog2lin(inLog_Q7: number): number + if inLog_Q7 < 0 then + return 0 + elseif inLog_Q7 >= 3967 then + return 2147483647 + end + local out = p2(inLog_Q7 // 128) + local frac_Q7 = inLog_Q7 % 128 + local t = frac_Q7 + (frac_Q7 * (128 - frac_Q7) * -174) // 65536 + if inLog_Q7 < 2048 then + out = out + (out * t) // 128 + else + out = out + (out // 128) * t + end + return out +end + +local function silkSQRT_APPROX(x: number): number + if x <= 0 then + return 0 + end + local lz = clz32(x) + local rot = 24 - lz + local r + if rot == 0 then + r = x + elseif rot < 0 then + r = bit32.lrotate(x, -rot) + else + r = bit32.rrotate(x, rot) + end + local frac_Q7 = bit32.band(r, 0x7f) + local y = if bit32.band(lz, 1) ~= 0 then 32768 else 46214 + y = y // p2(lz // 2) + y = y + (y * (213 * frac_Q7)) // 65536 + return y +end + +-- silk_sum_sqr_shift: energy, shift +local function sumSqrShift(x: { number }, xo: number, len: number): (number, number) + local shft = 31 - clz32(len) + local nrg = len + local i = 0 + while i < len - 1 do + local a, b = x[xo + i], x[xo + i + 1] + nrg = i32(nrg + rshift(a * a + b * b, shft)) + i += 2 + end + if i < len then + local a = x[xo + i] + nrg = i32(nrg + rshift(a * a, shft)) + end + shft = math.max(0, shft + 3 - clz32(nrg)) + nrg = 0 + i = 0 + while i < len - 1 do + local a, b = x[xo + i], x[xo + i + 1] + nrg = i32(nrg + rshift(a * a + b * b, shft)) + i += 2 + end + if i < len then + local a = x[xo + i] + nrg = i32(nrg + rshift(a * a, shft)) + end + return nrg, shft +end + +-- LPC helpers --------------------------------------------------------------------------------------------------- + +-- silk_bwexpander (int16 coefficients), ar 1-based +local function bwexpander(ar: { number }, d: number, chirp_Q16: number) + local chirp_minus_one_Q16 = chirp_Q16 - 65536 + for i = 1, d - 1 do + ar[i] = s16((chirp_Q16 * ar[i] + 32768) // 65536) + chirp_Q16 += (chirp_Q16 * chirp_minus_one_Q16 + 32768) // 65536 + end + ar[d] = s16((chirp_Q16 * ar[d] + 32768) // 65536) +end + +local function bwexpander32(ar: { number }, d: number, chirp_Q16: number) + local chirp_minus_one_Q16 = chirp_Q16 - 65536 + for i = 1, d - 1 do + ar[i] = i32(mulww(chirp_Q16, ar[i])) + chirp_Q16 += (chirp_Q16 * chirp_minus_one_Q16 + 32768) // 65536 + end + ar[d] = i32(mulww(chirp_Q16, ar[d])) +end + +-- silk_LPC_fit: a_QIN (int32, QIN) -> a_QOUT (int16, QOUT) +local function lpcFit(a_QOUT: { number }, a_QIN: { number }, QOUT: number, QIN: number, d: number) + local sh = QIN - QOUT + local idx = 0 + local i = 0 + while i < 10 do + local maxabs = 0 + for k = 1, d do + local absval = math.abs(a_QIN[k]) + if absval > maxabs then + maxabs = absval + idx = k - 1 + end + end + maxabs = rround(maxabs, sh) + if maxabs > 32767 then + maxabs = math.min(maxabs, 163838) + local chirp_Q16 = 65470 - tdiv((maxabs - 32767) * 16384, (maxabs * (idx + 1)) // 4) + bwexpander32(a_QIN, d, chirp_Q16) + else + break + end + i += 1 + end + if i == 10 then + for k = 1, d do + a_QOUT[k] = sat16(rround(a_QIN[k], sh)) + a_QIN[k] = a_QOUT[k] * P2[sh] + end + else + for k = 1, d do + a_QOUT[k] = s16(rround(a_QIN[k], sh)) + end + end +end + +local A_LIMIT = 16773022 +local INV_GAIN_MIN = 107374 +local Atmp_QA = table.create(16, 0) + +-- RSHIFT_ROUND64(SMULL(a, b), Q) +local function mulRound(a: number, b: number, Q: number): number + if Q == 1 then + local p = a * b + return p // 2 + p % 2 + end + if Q - 1 >= 16 then + return (mulshr(a, b, Q - 1) + 1) // 2 + end + return ((a * b) // P2[Q - 1] + 1) // 2 +end + +local function lpcInversePredGainQA(A_QA: { number }, order: number): number + local invGain_Q30 = 1073741824 + local k = order - 1 + while k > 0 do + local ak = A_QA[k + 1] + if ak > A_LIMIT or ak < -A_LIMIT then + return 0 + end + local rc_Q31 = -(ak * 128) + local rc_mult1_Q30 = 1073741824 - smmul(rc_Q31, rc_Q31) + invGain_Q30 = smmul(invGain_Q30, rc_mult1_Q30) * 4 + if invGain_Q30 < INV_GAIN_MIN then + return 0 + end + local mult2Q = 32 - clz32(math.abs(rc_mult1_Q30)) + local rc_mult2 = silkINVERSE32_varQ(rc_mult1_Q30, mult2Q + 30) + for n = 0, (k + 1) // 2 - 1 do + local tmp1 = A_QA[n + 1] + local tmp2 = A_QA[k - n] + local t64 = mulRound(subSat32(tmp1, mulRound(tmp2, rc_Q31, 31)), rc_mult2, mult2Q) + if t64 > 2147483647 or t64 < -2147483648 then + return 0 + end + A_QA[n + 1] = t64 + t64 = mulRound(subSat32(tmp2, mulRound(tmp1, rc_Q31, 31)), rc_mult2, mult2Q) + if t64 > 2147483647 or t64 < -2147483648 then + return 0 + end + A_QA[k - n] = t64 + end + k -= 1 + end + local a0 = A_QA[1] + if a0 > A_LIMIT or a0 < -A_LIMIT then + return 0 + end + local rc_Q31 = -(a0 * 128) + local rc_mult1_Q30 = 1073741824 - smmul(rc_Q31, rc_Q31) + invGain_Q30 = smmul(invGain_Q30, rc_mult1_Q30) * 4 + if invGain_Q30 < INV_GAIN_MIN then + return 0 + end + return invGain_Q30 +end + +local function lpcInversePredGain(A_Q12: { number }, order: number): number + local DC_resp = 0 + for k = 1, order do + DC_resp += A_Q12[k] + Atmp_QA[k] = A_Q12[k] * 4096 + end + if DC_resp >= 4096 then + return 0 + end + return lpcInversePredGainQA(Atmp_QA, order) +end + +local ordering16 = { 0, 15, 8, 7, 4, 11, 12, 3, 2, 13, 10, 5, 6, 9, 14, 1 } +local ordering10 = { 0, 9, 6, 3, 4, 5, 8, 1, 2, 7 } +local cos_LSF_QA = table.create(16, 0) +local polyP = table.create(9, 0) +local polyQ = table.create(9, 0) +local a32_QA1 = table.create(16, 0) +local LSFCos = T.LSFCosTab_FIX_Q12 + +-- out[0..dd] (1-based storage), from interleaved cLSF starting at C index c0 +local function findPoly(out: { number }, cLSF: { number }, c0: number, dd: number) + out[1] = 65536 + out[2] = -cLSF[c0 + 1] + for k = 1, dd - 1 do + local ftmp = cLSF[c0 + 2 * k + 1] + out[k + 2] = out[k] * 2 - (ftmp * out[k + 1] + 32768) // 65536 + for n = k, 2, -1 do + out[n + 1] += out[n - 1] - (ftmp * out[n] + 32768) // 65536 + end + out[2] -= ftmp + end +end + +-- silk_NLSF2A: a_Q12 (1-based, d entries) from NLSF (1-based) +local function nlsf2a(a_Q12: { number }, NLSF: { number }, d: number) + local ordering = if d == 16 then ordering16 else ordering10 + for k = 1, d do + local nl = NLSF[k] + local f_int = nl // 256 + local f_frac = nl - f_int * 256 + local cos_val = LSFCos[f_int + 1] + local delta = LSFCos[f_int + 2] - cos_val + cos_LSF_QA[ordering[k] + 1] = (cos_val * 256 + delta * f_frac + 8) // 16 + end + local dd = d // 2 + findPoly(polyP, cos_LSF_QA, 0, dd) + findPoly(polyQ, cos_LSF_QA, 1, dd) + for k = 0, dd - 1 do + local Ptmp = polyP[k + 2] + polyP[k + 1] + local Qtmp = polyQ[k + 2] - polyQ[k + 1] + a32_QA1[k + 1] = -Qtmp - Ptmp + a32_QA1[d - k] = Qtmp - Ptmp + end + lpcFit(a_Q12, a32_QA1, 12, 17, d) + local i = 0 + while lpcInversePredGain(a_Q12, d) == 0 and i < 16 do + bwexpander32(a32_QA1, d, 65536 - P2[i + 1]) + for k = 1, d do + a_Q12[k] = s16((a32_QA1[k] + 16) // 32) + end + i += 1 + end +end + +-- silk_LPC_analysis_filter: out[oo + ix] for ix in [0, len), from inp[io + ix]; B 1-based Q12 +local function lpcAnalysisFilter(out: { number }, oo: number, inp: { number }, io: number, B: { number }, len: number, d: number) + for ix = d, len - 1 do + local base = io + ix - 1 + local acc = 0 + for j = 0, d - 1 do + acc += inp[base - j] * B[j + 1] + end + local out32_Q12 = i32(inp[base + 1] * 4096 - acc) + out[oo + ix] = sat16((out32_Q12 + 2048) // 4096) + end + for j = 0, d - 1 do + out[oo + j] = 0 + end +end + +-- NLSF ---------------------------------------------------------------------------------------------------------- + +local CB_NB_MB = { + nVectors = 32, + order = 10, + quantStepSize_Q16 = 11796, + CB1_NLSF_Q8 = T.NLSF_CB1_NB_MB_Q8, + CB1_Wght_Q9 = T.NLSF_CB1_Wght_Q9, + CB1_iCDF = T.NLSF_CB1_iCDF_NB_MB, + pred_Q8 = T.NLSF_PRED_NB_MB_Q8, + ec_sel = T.NLSF_CB2_SELECT_NB_MB, + ec_iCDF = T.NLSF_CB2_iCDF_NB_MB, + deltaMin_Q15 = T.NLSF_DELTA_MIN_NB_MB_Q15, +} +local CB_WB = { + nVectors = 32, + order = 16, + quantStepSize_Q16 = 9830, + CB1_NLSF_Q8 = T.NLSF_CB1_WB_Q8, + CB1_Wght_Q9 = T.NLSF_CB1_WB_Wght_Q9, + CB1_iCDF = T.NLSF_CB1_iCDF_WB, + pred_Q8 = T.NLSF_PRED_WB_Q8, + ec_sel = T.NLSF_CB2_SELECT_WB, + ec_iCDF = T.NLSF_CB2_iCDF_WB, + deltaMin_Q15 = T.NLSF_DELTA_MIN_WB_Q15, +} + +local ec_ix = table.create(16, 0) +local pred_Q8 = table.create(16, 0) +local res_Q10 = table.create(16, 0) + +local function nlsfUnpack(CB: any, CB1_index: number) + local order = CB.order + local sel = CB.ec_sel + local pq = CB.pred_Q8 + local p = CB1_index * order // 2 + for i = 0, order - 1, 2 do + p += 1 + local entry = sel[p] + ec_ix[i + 1] = (bit32.band(entry // 2, 7)) * 9 + pred_Q8[i + 1] = pq[i + bit32.band(entry, 1) * (order - 1) + 1] + ec_ix[i + 2] = (bit32.band(entry // 32, 7)) * 9 + pred_Q8[i + 2] = pq[i + bit32.band(entry // 16, 1) * (order - 1) + 2] + end +end + +local function nlsfStabilize(NLSF: { number }, NDeltaMin: { number }, L: number) + local loops = 0 + while loops < 20 do + local min_diff = NLSF[1] - NDeltaMin[1] + local I = 0 + for i = 1, L - 1 do + local diff = NLSF[i + 1] - (NLSF[i] + NDeltaMin[i + 1]) + if diff < min_diff then + min_diff = diff + I = i + end + end + local diff = 32768 - (NLSF[L] + NDeltaMin[L + 1]) + if diff < min_diff then + min_diff = diff + I = L + end + if min_diff >= 0 then + return + end + if I == 0 then + NLSF[1] = NDeltaMin[1] + elseif I == L then + NLSF[L] = 32768 - NDeltaMin[L + 1] + else + local min_center = 0 + for k = 0, I - 1 do + min_center += NDeltaMin[k + 1] + end + min_center += NDeltaMin[I + 1] // 2 + local max_center = 32768 + for k = L, I + 1, -1 do + max_center -= NDeltaMin[k + 1] + end + max_center -= NDeltaMin[I + 1] // 2 + local c = (NLSF[I] + NLSF[I + 1] + 1) // 2 + -- silk_LIMIT_32(c, min_center, max_center) + if min_center > max_center then + if c > min_center then + c = min_center + elseif c < max_center then + c = max_center + end + else + if c > max_center then + c = max_center + elseif c < min_center then + c = min_center + end + end + c = s16(c) + NLSF[I] = s16(c - NDeltaMin[I + 1] // 2) + NLSF[I + 1] = s16(NLSF[I] + NDeltaMin[I + 1]) + end + loops += 1 + end + -- fall back: insertion sort, then clamp + for i = 2, L do + local value = NLSF[i] + local j = i - 1 + while j >= 1 and value < NLSF[j] do + NLSF[j + 1] = NLSF[j] + j -= 1 + end + NLSF[j + 1] = value + end + NLSF[1] = math.max(NLSF[1], NDeltaMin[1]) + for i = 2, L do + NLSF[i] = math.max(NLSF[i], sat16(NLSF[i - 1] + NDeltaMin[i])) + end + NLSF[L] = math.min(NLSF[L], 32768 - NDeltaMin[L + 1]) + for i = L - 1, 1, -1 do + NLSF[i] = math.min(NLSF[i], NLSF[i + 1] - NDeltaMin[i + 1]) + end +end + +-- silk_NLSF_decode: pNLSF_Q15 (1-based) from indices (1-based: [1] = CB1 index) +local function nlsfDecode(pNLSF_Q15: { number }, NLSFIndices: { number }, CB: any) + nlsfUnpack(CB, NLSFIndices[1]) + local order = CB.order + local step = CB.quantStepSize_Q16 + local out_Q10 = 0 + for i = order - 1, 0, -1 do + local pred = (out_Q10 * pred_Q8[i + 1]) // 256 + out_Q10 = NLSFIndices[i + 2] * 1024 + if out_Q10 > 0 then + out_Q10 -= 102 + elseif out_Q10 < 0 then + out_Q10 += 102 + end + out_Q10 = pred + (out_Q10 * step) // 65536 + res_Q10[i + 1] = out_Q10 + end + local base = NLSFIndices[1] * order + local cb, w = CB.CB1_NLSF_Q8, CB.CB1_Wght_Q9 + for i = 1, order do + local v = tdiv(res_Q10[i] * 16384, w[base + i]) + cb[base + i] * 128 + if v < 0 then + v = 0 + elseif v > 32767 then + v = 32767 + end + pNLSF_Q15[i] = v + end + nlsfStabilize(pNLSF_Q15, CB.deltaMin_Q15, order) +end + +-- Resampler (decoder side: 8 / 12 / 16 kHz up to the API rate) ---------------------------------------------------- + +local RES_COPY, RES_UP2, RES_IIR_FIR = 0, 1, 2 +local up2_hq_0 = { 1746, 14986, 39083 - 65536 } +local up2_hq_1 = { 6854, 25769, 55542 - 65536 } +local FIR12 = T.resampler_frac_FIR_12 +local delay_matrix_dec = { + { 4, 0, 2, 0, 0, 0 }, + { 0, 9, 4, 7, 4, 4 }, + { 0, 3, 12, 7, 7, 7 }, +} + +local function rateID(R: number): number + local a = R // 4096 - (if R > 16000 then 1 else 0) + if R > 24000 then + a = a // 2 + end + return math.min(5, a - 1) +end + +local function newResampler(): any + return { + sIIR = table.create(6, 0), + sFIR = table.create(8, 0), + delayBuf = table.create(96, 0), + buf = table.create(2 * 160 + 8, 0), + resampler_function = RES_COPY, + batchSize = 0, + invRatio_Q16 = 0, + inputDelay = 0, + Fs_in_kHz = 0, + Fs_out_kHz = 0, + } +end + +local function copyResampler(dst: any, src: any) + for i = 1, 6 do + dst.sIIR[i] = src.sIIR[i] + end + for i = 1, 8 do + dst.sFIR[i] = src.sFIR[i] + end + for i = 1, 96 do + dst.delayBuf[i] = src.delayBuf[i] + end + dst.resampler_function = src.resampler_function + dst.batchSize = src.batchSize + dst.invRatio_Q16 = src.invRatio_Q16 + dst.inputDelay = src.inputDelay + dst.Fs_in_kHz = src.Fs_in_kHz + dst.Fs_out_kHz = src.Fs_out_kHz +end + +local function resamplerInit(S: any, Fs_Hz_in: number, Fs_Hz_out: number): number + table.clear(S.sIIR) + table.clear(S.sFIR) + table.clear(S.delayBuf) + for i = 1, 6 do + S.sIIR[i] = 0 + end + for i = 1, 8 do + S.sFIR[i] = 0 + end + for i = 1, 96 do + S.delayBuf[i] = 0 + end + if (Fs_Hz_in ~= 8000 and Fs_Hz_in ~= 12000 and Fs_Hz_in ~= 16000) or Fs_Hz_out < Fs_Hz_in then + return -1 -- the decoder only upsamples (or copies) + end + S.inputDelay = delay_matrix_dec[rateID(Fs_Hz_in) + 1][rateID(Fs_Hz_out) + 1] or 0 + S.Fs_in_kHz = Fs_Hz_in // 1000 + S.Fs_out_kHz = Fs_Hz_out // 1000 + S.batchSize = S.Fs_in_kHz * 10 + local up2x = 0 + if Fs_Hz_out > Fs_Hz_in then + if Fs_Hz_out == Fs_Hz_in * 2 then + S.resampler_function = RES_UP2 + else + S.resampler_function = RES_IIR_FIR + up2x = 1 + end + else + S.resampler_function = RES_COPY + end + local inv = (Fs_Hz_in * p2(14 + up2x)) // Fs_Hz_out * 4 + while mulww(inv, Fs_Hz_out) < Fs_Hz_in * p2(up2x) do + inv += 1 + end + S.invRatio_Q16 = inv + return 0 +end + +-- silk_resampler_private_up2_HQ: out[oo + 2k], out[oo + 2k + 1] from inp[io + k] +local function up2HQ(S: { number }, out: { number }, oo: number, inp: { number }, io: number, len: number) + local s0, s1, s2, s3, s4, s5 = S[1], S[2], S[3], S[4], S[5], S[6] + local c00, c01, c02 = up2_hq_0[1], up2_hq_0[2], up2_hq_0[3] + local c10, c11, c12 = up2_hq_1[1], up2_hq_1[2], up2_hq_1[3] + for k = 0, len - 1 do + local in32 = inp[io + k] * 1024 + local Y = in32 - s0 + local X = (Y * c00) // 65536 + local out32_1 = s0 + X + s0 = in32 + X + Y = out32_1 - s1 + X = (Y * c01) // 65536 + local out32_2 = s1 + X + s1 = out32_1 + X + Y = out32_2 - s2 + X = Y + (Y * c02) // 65536 + out32_1 = s2 + X + s2 = out32_2 + X + out[oo + 2 * k] = sat16((out32_1 + 512) // 1024) + Y = in32 - s3 + X = (Y * c10) // 65536 + out32_1 = s3 + X + s3 = in32 + X + Y = out32_1 - s4 + X = (Y * c11) // 65536 + out32_2 = s4 + X + s4 = out32_1 + X + Y = out32_2 - s5 + X = Y + (Y * c12) // 65536 + out32_1 = s5 + X + s5 = out32_2 + X + out[oo + 2 * k + 1] = sat16((out32_1 + 512) // 1024) + end + S[1], S[2], S[3], S[4], S[5], S[6] = s0, s1, s2, s3, s4, s5 +end + +-- returns the next output index +local function iirFirInterpol(out: { number }, oo: number, buf: { number }, max_index_Q16: number, incr: number): number + local index_Q16 = 0 + while index_Q16 < max_index_Q16 do + local ti = ((index_Q16 % 65536) * 12) // 65536 + local b = index_Q16 // 65536 + 1 -- buf is 1-based + local f0 = ti * 4 + local f1 = (11 - ti) * 4 + local res_Q15 = buf[b] * FIR12[f0 + 1] + + buf[b + 1] * FIR12[f0 + 2] + + buf[b + 2] * FIR12[f0 + 3] + + buf[b + 3] * FIR12[f0 + 4] + + buf[b + 4] * FIR12[f1 + 4] + + buf[b + 5] * FIR12[f1 + 3] + + buf[b + 6] * FIR12[f1 + 2] + + buf[b + 7] * FIR12[f1 + 1] + out[oo] = sat16((res_Q15 + 16384) // 32768) + oo += 1 + index_Q16 += incr + end + return oo +end + +local function iirFir(S: any, out: { number }, oo: number, inp: { number }, io: number, inLen: number) + local buf = S.buf + local sFIR = S.sFIR + for i = 1, 8 do + buf[i] = sFIR[i] + end + local incr = S.invRatio_Q16 + local nSamplesIn + while true do + nSamplesIn = math.min(inLen, S.batchSize) + up2HQ(S.sIIR, buf, 9, inp, io, nSamplesIn) + oo = iirFirInterpol(out, oo, buf, nSamplesIn * 131072, incr) + io += nSamplesIn + inLen -= nSamplesIn + if inLen > 0 then + local o = nSamplesIn * 2 + for i = 1, 8 do + buf[i] = buf[o + i] + end + else + break + end + end + local o = nSamplesIn * 2 + for i = 1, 8 do + sFIR[i] = buf[o + i] + end +end + +local function resampleBlock(S: any, out: { number }, oo: number, inp: { number }, io: number, len: number) + local f = S.resampler_function + if f == RES_IIR_FIR then + iirFir(S, out, oo, inp, io, len) + elseif f == RES_UP2 then + up2HQ(S.sIIR, out, oo, inp, io, len) + else + for i = 0, len - 1 do + out[oo + i] = inp[io + i] + end + end +end + +-- silk_resampler: out[1..] from inp[io .. io + inLen - 1] +local function resampler(S: any, out: { number }, inp: { number }, io: number, inLen: number) + local fin = S.Fs_in_kHz + local delay = S.inputDelay + local nSamples = fin - delay + local db = S.delayBuf + for i = 0, nSamples - 1 do + db[delay + i + 1] = inp[io + i] + end + resampleBlock(S, out, 1, db, 1, fin) + resampleBlock(S, out, 1 + S.Fs_out_kHz, inp, io + nSamples, inLen - fin) + for i = 0, delay - 1 do + db[i + 1] = inp[io + inLen - delay + i] + end +end + +-- Decoder state ------------------------------------------------------------------------------------------------- + +local function newChannel(): any + return { + prev_gain_Q16 = 65536, + exc_Q14 = table.create(320, 0), + sLPC_Q14_buf = table.create(16, 0), + outBuf = table.create(480, 0), + lagPrev = 0, + LastGainIndex = 0, + fs_kHz = 0, + fs_API_hz = 0, + nb_subfr = 0, + frame_length = 0, + subfr_length = 0, + ltp_mem_length = 0, + LPC_order = 0, + prevNLSF_Q15 = table.create(16, 0), + first_frame_after_reset = 1, + pitch_lag_low_bits_iCDF = T.uniform4_iCDF, + pitch_contour_iCDF = T.pitch_contour_iCDF, + nFramesDecoded = 0, + nFramesPerPacket = 0, + ec_prevSignalType = 0, + ec_prevLagIndex = 0, + VAD_flags = { 0, 0, 0 }, + LBRR_flag = 0, + LBRR_flags = { 0, 0, 0 }, + resampler_state = newResampler(), + psNLSF_CB = CB_NB_MB, + indices = { + signalType = 0, + quantOffsetType = 0, + GainsIndices = { 0, 0, 0, 0 }, + NLSFIndices = table.create(17, 0), + NLSFInterpCoef_Q2 = 0, + lagIndex = 0, + contourIndex = 0, + PERIndex = 0, + LTPIndex = { 0, 0, 0, 0 }, + LTP_scaleIndex = 0, + Seed = 0, + }, + sCNG = { + CNG_exc_buf_Q14 = table.create(320, 0), + CNG_smth_NLSF_Q15 = table.create(16, 0), + CNG_synth_state = table.create(16, 0), + CNG_smth_Gain_Q16 = 0, + rand_seed = 3176576, + fs_kHz = 0, + }, + lossCnt = 0, + prevSignalType = 0, + sPLC = { + pitchL_Q8 = 0, + LTPCoef_Q14 = table.create(5, 0), + prevLPC_Q12 = table.create(16, 0), + last_frame_lost = 0, + rand_seed = 0, + randScale_Q14 = 0, + conc_energy = 0, + conc_energy_shift = 0, + prevLTP_scale_Q14 = 0, + prevGain_Q16 = { 65536, 65536 }, + fs_kHz = 0, + nb_subfr = 2, + subfr_length = 20, + }, + -- per-frame decoder control (silk_decoder_control) and scratch + ctrl = { + pitchL = { 0, 0, 0, 0 }, + Gains_Q16 = { 0, 0, 0, 0 }, + PredCoef_Q12 = { table.create(16, 0), table.create(16, 0) }, + LTPCoef_Q14 = table.create(20, 0), + LTP_scale_Q14 = 0, + }, + pulses = table.create(336, 0), + out = table.create(322, 0), -- samplesOut1_tmp: [1], [2] = the 2 buffered samples, frame from [3] + } +end + +local function decoderSetFs(ch: any, fs_kHz: number, fs_API_Hz: number): number + local ret = 0 + ch.subfr_length = 5 * fs_kHz + local frame_length = ch.nb_subfr * ch.subfr_length + if ch.fs_kHz ~= fs_kHz or ch.fs_API_hz ~= fs_API_Hz then + ret += resamplerInit(ch.resampler_state, fs_kHz * 1000, fs_API_Hz) + ch.fs_API_hz = fs_API_Hz + end + if ch.fs_kHz ~= fs_kHz or frame_length ~= ch.frame_length then + if fs_kHz == 8 then + ch.pitch_contour_iCDF = if ch.nb_subfr == 4 then T.pitch_contour_NB_iCDF else T.pitch_contour_10_ms_NB_iCDF + else + ch.pitch_contour_iCDF = if ch.nb_subfr == 4 then T.pitch_contour_iCDF else T.pitch_contour_10_ms_iCDF + end + if ch.fs_kHz ~= fs_kHz then + ch.ltp_mem_length = 20 * fs_kHz + if fs_kHz == 8 or fs_kHz == 12 then + ch.LPC_order = 10 + ch.psNLSF_CB = CB_NB_MB + else + ch.LPC_order = 16 + ch.psNLSF_CB = CB_WB + end + if fs_kHz == 16 then + ch.pitch_lag_low_bits_iCDF = T.uniform8_iCDF + elseif fs_kHz == 12 then + ch.pitch_lag_low_bits_iCDF = T.uniform6_iCDF + else + ch.pitch_lag_low_bits_iCDF = T.uniform4_iCDF + end + ch.first_frame_after_reset = 1 + ch.lagPrev = 100 + ch.LastGainIndex = 10 + ch.prevSignalType = 0 + local ob, sl = ch.outBuf, ch.sLPC_Q14_buf + for i = 1, 480 do + ob[i] = 0 + end + for i = 1, 16 do + sl[i] = 0 + end + end + ch.fs_kHz = fs_kHz + ch.frame_length = frame_length + end + return ret +end + +-- Bitstream: indices and pulses --------------------------------------------------------------------------------- + +local LTP_gain_iCDF = { T.LTP_gain_iCDF_0, T.LTP_gain_iCDF_1, T.LTP_gain_iCDF_2 } +local LTP_vq_Q7 = { T.LTP_gain_vq_0, T.LTP_gain_vq_1, T.LTP_gain_vq_2 } +local LBRR_flags_iCDF = { T.LBRR_flags_2_iCDF, T.LBRR_flags_3_iCDF } + +local function decodeIndices(ch: any, d: any, FrameIndex: number, decode_LBRR: boolean, condCoding: number) + local ind = ch.indices + local Ix + if decode_LBRR or ch.VAD_flags[FrameIndex + 1] ~= 0 then + Ix = icdf(d, T.type_offset_VAD_iCDF, 1, 8) + 2 + else + Ix = icdf(d, T.type_offset_no_VAD_iCDF, 1, 8) + end + local signalType = Ix // 2 + ind.signalType = signalType + ind.quantOffsetType = Ix % 2 + local gi = ind.GainsIndices + if condCoding == 2 then + gi[1] = icdf(d, T.delta_gain_iCDF, 1, 8) + else + gi[1] = icdf(d, T.gain_iCDF, signalType * 8 + 1, 8) * 8 + gi[1] += icdf(d, T.uniform8_iCDF, 1, 8) + end + for i = 2, ch.nb_subfr do + gi[i] = icdf(d, T.delta_gain_iCDF, 1, 8) + end + local CB = ch.psNLSF_CB + local ni = ind.NLSFIndices + ni[1] = icdf(d, CB.CB1_iCDF, (signalType // 2) * CB.nVectors + 1, 8) + nlsfUnpack(CB, ni[1]) + for i = 1, CB.order do + Ix = icdf(d, CB.ec_iCDF, ec_ix[i] + 1, 8) + if Ix == 0 then + Ix -= icdf(d, T.NLSF_EXT_iCDF, 1, 8) + elseif Ix == 8 then + Ix += icdf(d, T.NLSF_EXT_iCDF, 1, 8) + end + ni[i + 1] = Ix - 4 + end + if ch.nb_subfr == 4 then + ind.NLSFInterpCoef_Q2 = icdf(d, T.NLSF_interpolation_factor_iCDF, 1, 8) + else + ind.NLSFInterpCoef_Q2 = 4 + end + if signalType == 2 then + local absolute = true + if condCoding == 2 and ch.ec_prevSignalType == 2 then + local delta = icdf(d, T.pitch_delta_iCDF, 1, 8) + if delta > 0 then + ind.lagIndex = s16(ch.ec_prevLagIndex + delta - 9) + absolute = false + end + end + if absolute then + ind.lagIndex = icdf(d, T.pitch_lag_iCDF, 1, 8) * (ch.fs_kHz // 2) + ind.lagIndex += icdf(d, ch.pitch_lag_low_bits_iCDF, 1, 8) + end + ch.ec_prevLagIndex = ind.lagIndex + ind.contourIndex = icdf(d, ch.pitch_contour_iCDF, 1, 8) + ind.PERIndex = icdf(d, T.LTP_per_index_iCDF, 1, 8) + local tab = LTP_gain_iCDF[ind.PERIndex + 1] + for k = 1, ch.nb_subfr do + ind.LTPIndex[k] = icdf(d, tab, 1, 8) + end + if condCoding == 0 then + ind.LTP_scaleIndex = icdf(d, T.LTPscale_iCDF, 1, 8) + else + ind.LTP_scaleIndex = 0 + end + end + ch.ec_prevSignalType = signalType + ind.Seed = icdf(d, T.uniform4_iCDF, 1, 8) +end + +local shell0, shell1, shell2, shell3 = T.shell_code_table0, T.shell_code_table1, T.shell_code_table2, T.shell_code_table3 +local shellOff = T.shell_code_table_offsets + +local function split(d: any, p: number, tab: { number }): (number, number) + if p > 0 then + local a = icdf(d, tab, shellOff[p + 1] + 1, 8) + return a, p - a + end + return 0, 0 +end + +local function shellDecoder(out: { number }, o: number, d: any, pulses4: number) + local p3a, p3b = split(d, pulses4, shell3) + local p2a, p2b = split(d, p3a, shell2) + local p1a, p1b = split(d, p2a, shell1) + out[o], out[o + 1] = split(d, p1a, shell0) + out[o + 2], out[o + 3] = split(d, p1b, shell0) + p1a, p1b = split(d, p2b, shell1) + out[o + 4], out[o + 5] = split(d, p1a, shell0) + out[o + 6], out[o + 7] = split(d, p1b, shell0) + p2a, p2b = split(d, p3b, shell2) + p1a, p1b = split(d, p2a, shell1) + out[o + 8], out[o + 9] = split(d, p1a, shell0) + out[o + 10], out[o + 11] = split(d, p1b, shell0) + p1a, p1b = split(d, p2b, shell1) + out[o + 12], out[o + 13] = split(d, p1a, shell0) + out[o + 14], out[o + 15] = split(d, p1b, shell0) +end + +local sum_pulses = table.create(20, 0) +local nLshifts = table.create(20, 0) +local signIcdf = { 0, 0 } + +-- pulses[1 .. frame_length (rounded up to 16)] +local function decodePulses(d: any, pulses: { number }, signalType: number, quantOffsetType: number, frame_length: number) + local RateLevelIndex = icdf(d, T.rate_levels_iCDF, (signalType // 2) * 9 + 1, 8) + local iter = frame_length // 16 + if iter * 16 < frame_length then + iter += 1 + end + local ppb = T.pulses_per_block_iCDF + for i = 1, iter do + nLshifts[i] = 0 + local s = icdf(d, ppb, RateLevelIndex * 18 + 1, 8) + while s == 17 do + nLshifts[i] += 1 + s = icdf(d, ppb, 9 * 18 + 1 + (if nLshifts[i] == 10 then 1 else 0), 8) + if nLshifts[i] > 30 then + break -- corrupt stream guard + end + end + sum_pulses[i] = s + end + for i = 1, iter do + local o = (i - 1) * 16 + 1 + if sum_pulses[i] > 0 then + shellDecoder(pulses, o, d, sum_pulses[i]) + else + for k = 0, 15 do + pulses[o + k] = 0 + end + end + end + local lsb = T.lsb_iCDF + for i = 1, iter do + local nLS = nLshifts[i] + if nLS > 0 then + local o = (i - 1) * 16 + 1 + for k = 0, 15 do + local abs_q = pulses[o + k] + for _ = 1, nLS do + abs_q = abs_q * 2 + icdf(d, lsb, 1, 8) + end + pulses[o + k] = abs_q + end + sum_pulses[i] += nLS * 32 + end + end + -- silk_decode_signs + local signTab = T.sign_iCDF + local base = 7 * (quantOffsetType + signalType * 2) + local blocks = (frame_length + 8) // 16 + for i = 1, blocks do + local p = sum_pulses[i] + if p > 0 then + signIcdf[1] = signTab[base + math.min(p % 32, 6) + 1] + local o = (i - 1) * 16 + 1 + for j = 0, 15 do + local q = pulses[o + j] + if q > 0 then + pulses[o + j] = q * (icdf(d, signIcdf, 1, 8) * 2 - 1) + end + end + end + end +end + +-- Parameters ---------------------------------------------------------------------------------------------------- + +local pNLSF_Q15 = table.create(16, 0) +local pNLSF0_Q15 = table.create(16, 0) + +local function gainsDequant(gain_Q16: { number }, ind: { number }, ch: any, conditional: boolean, nb_subfr: number) + local prev = ch.LastGainIndex + for k = 1, nb_subfr do + if k == 1 and not conditional then + prev = math.max(ind[k], prev - 16) + else + local ind_tmp = ind[k] - 4 + local thr = 8 + prev + if ind_tmp > thr then + prev += ind_tmp * 2 - thr + else + prev += ind_tmp + end + end + if prev < 0 then + prev = 0 + elseif prev > 63 then + prev = 63 + end + gain_Q16[k] = silkLog2lin(math.min((1907825 * prev) // 65536 + 2090, 3967)) + end + ch.LastGainIndex = prev +end + +local CB_lags = { + [8] = { [4] = { T.CB_lags_stage2, 11 }, [2] = { T.CB_lags_stage2_10_ms, 3 } }, + [0] = { [4] = { T.CB_lags_stage3, 34 }, [2] = { T.CB_lags_stage3_10_ms, 12 } }, +} + +local function decodeParameters(ch: any, ctrl: any, condCoding: number) + local ind = ch.indices + gainsDequant(ctrl.Gains_Q16, ind.GainsIndices, ch, condCoding == 2, ch.nb_subfr) + local order = ch.LPC_order + nlsfDecode(pNLSF_Q15, ind.NLSFIndices, ch.psNLSF_CB) + nlsf2a(ctrl.PredCoef_Q12[2], pNLSF_Q15, order) + if ch.first_frame_after_reset == 1 then + ind.NLSFInterpCoef_Q2 = 4 + end + local prevNLSF = ch.prevNLSF_Q15 + if ind.NLSFInterpCoef_Q2 < 4 then + local c = ind.NLSFInterpCoef_Q2 + for i = 1, order do + pNLSF0_Q15[i] = prevNLSF[i] + (c * (pNLSF_Q15[i] - prevNLSF[i])) // 4 + end + nlsf2a(ctrl.PredCoef_Q12[1], pNLSF0_Q15, order) + else + local a, b = ctrl.PredCoef_Q12[1], ctrl.PredCoef_Q12[2] + for i = 1, order do + a[i] = b[i] + end + end + for i = 1, order do + prevNLSF[i] = pNLSF_Q15[i] + end + if ch.lossCnt ~= 0 then + bwexpander(ctrl.PredCoef_Q12[1], order, 63570) + bwexpander(ctrl.PredCoef_Q12[2], order, 63570) + end + if ind.signalType == 2 then + -- silk_decode_pitch + local fs = ch.fs_kHz + local cbinfo = CB_lags[if fs == 8 then 8 else 0][ch.nb_subfr] + local cb, cbk_size = cbinfo[1], cbinfo[2] + local min_lag, max_lag = 2 * fs, 18 * fs + local lag = min_lag + ind.lagIndex + for k = 0, ch.nb_subfr - 1 do + local v = lag + cb[k * cbk_size + ind.contourIndex + 1] + if v < min_lag then + v = min_lag + elseif v > max_lag then + v = max_lag + end + ctrl.pitchL[k + 1] = v + end + local vq = LTP_vq_Q7[ind.PERIndex + 1] + for k = 0, ch.nb_subfr - 1 do + local Ix = ind.LTPIndex[k + 1] + for i = 1, 5 do + ctrl.LTPCoef_Q14[k * 5 + i] = vq[Ix * 5 + i] * 128 + end + end + ctrl.LTP_scale_Q14 = T.LTPScales_table_Q14[ind.LTP_scaleIndex + 1] + else + for k = 1, ch.nb_subfr do + ctrl.pitchL[k] = 0 + end + for k = 1, 5 * ch.nb_subfr do + ctrl.LTPCoef_Q14[k] = 0 + end + ind.PERIndex = 0 + ctrl.LTP_scale_Q14 = 0 + end +end + +-- Core synthesis ------------------------------------------------------------------------------------------------ + +local sLTP = table.create(320, 0) +local sLTP_Q15 = table.create(640, 0) +local res_Q14 = table.create(80, 0) +local sLPC_Q14 = table.create(96, 0) +local A_Q12_tmp = table.create(16, 0) +local QuantOffsets = { { 100, 240 }, { 32, 100 } } + +-- silk_decode_core: xq[xo .. xo + frame_length - 1] +local function decodeCore(ch: any, ctrl: any, xq: { number }, xo: number, pulses: { number }) + local ind = ch.indices + local exc = ch.exc_Q14 + local offset_Q10 = QuantOffsets[ind.signalType // 2 + 1][ind.quantOffsetType + 1] + local NLSF_interpolation_flag = ind.NLSFInterpCoef_Q2 < 4 + local frame_length = ch.frame_length + local subfr_length = ch.subfr_length + local ltp_mem_length = ch.ltp_mem_length + local order = ch.LPC_order + local outBuf = ch.outBuf + + local rand_seed = ind.Seed + for i = 1, frame_length do + rand_seed = silkRand(rand_seed) + local p = pulses[i] + local e = p * 16384 + if e > 0 then + e -= 1280 + elseif e < 0 then + e += 1280 + end + e += offset_Q10 * 16 + if rand_seed < 0 then + e = -e + end + exc[i] = e + rand_seed = i32(rand_seed + p) + end + + local sl = ch.sLPC_Q14_buf + for i = 1, 16 do + sLPC_Q14[i] = sl[i] + end + local pexc = 0 -- C offset into exc + local pxq = xo + local sLTP_buf_idx = ltp_mem_length -- C index into sLTP_Q15 + local lag = 0 + for k = 0, ch.nb_subfr - 1 do + local A_Q12 = ctrl.PredCoef_Q12[k // 2 + 1] + for i = 1, order do + A_Q12_tmp[i] = A_Q12[i] + end + local Bo = k * 5 -- C offset into LTPCoef_Q14 + local B = ctrl.LTPCoef_Q14 + local signalType = ind.signalType + local gain = ctrl.Gains_Q16[k + 1] + local Gain_Q10 = gain // 64 + local inv_gain_Q31 = silkINVERSE32_varQ(gain, 47) + local gain_adj_Q16 + if gain ~= ch.prev_gain_Q16 then + gain_adj_Q16 = silkDIV32_varQ(ch.prev_gain_Q16, gain, 16) + for i = 1, 16 do + sLPC_Q14[i] = i32(mulww(gain_adj_Q16, sLPC_Q14[i])) + end + else + gain_adj_Q16 = 65536 + end + ch.prev_gain_Q16 = gain + if ch.lossCnt ~= 0 and ch.prevSignalType == 2 and ind.signalType ~= 2 and k < 2 then + for i = 1, 5 do + B[Bo + i] = 0 + end + B[Bo + 3] = 4096 + signalType = 2 + ctrl.pitchL[k + 1] = ch.lagPrev + end + if signalType == 2 then + lag = ctrl.pitchL[k + 1] + if k == 0 or (k == 2 and NLSF_interpolation_flag) then + local start_idx = ltp_mem_length - lag - order - 2 + if start_idx < 1 then + start_idx = 1 -- corrupt stream guard (C asserts start_idx > 0) + end + if k == 2 then + for i = 0, 2 * subfr_length - 1 do + outBuf[ltp_mem_length + i + 1] = xq[xo + i] + end + end + lpcAnalysisFilter(sLTP, start_idx + 1, outBuf, start_idx + k * subfr_length + 1, A_Q12, ltp_mem_length - start_idx, order) + if k == 0 then + inv_gain_Q31 = ((inv_gain_Q31 * ctrl.LTP_scale_Q14) // 65536) * 4 + end + for i = 0, lag + 1 do + sLTP_Q15[sLTP_buf_idx - i] = (inv_gain_Q31 * sLTP[ltp_mem_length - i]) // 65536 + end + else + if gain_adj_Q16 ~= 65536 then + for i = 0, lag + 1 do + local j = sLTP_buf_idx - i + sLTP_Q15[j] = i32(mulww(gain_adj_Q16, sLTP_Q15[j])) + end + end + end + end + local presArr, presOff + if signalType == 2 then + local b0, b1, b2, b3, b4 = B[Bo + 1], B[Bo + 2], B[Bo + 3], B[Bo + 4], B[Bo + 5] + local pl = sLTP_buf_idx - lag + 2 + 1 -- 1-based index of pred_lag_ptr[0] + for i = 1, subfr_length do + local pred = 2 + pred += (sLTP_Q15[pl] * b0) // 65536 + pred += (sLTP_Q15[pl - 1] * b1) // 65536 + pred += (sLTP_Q15[pl - 2] * b2) // 65536 + pred += (sLTP_Q15[pl - 3] * b3) // 65536 + pred += (sLTP_Q15[pl - 4] * b4) // 65536 + pl += 1 + local r = exc[pexc + i] + pred * 2 + res_Q14[i] = r + sLTP_buf_idx += 1 + sLTP_Q15[sLTP_buf_idx] = r * 2 + end + presArr, presOff = res_Q14, 0 + else + presArr, presOff = exc, pexc + end + local a0, a1, a2, a3, a4, a5, a6, a7, a8, a9 = + A_Q12_tmp[1], A_Q12_tmp[2], A_Q12_tmp[3], A_Q12_tmp[4], A_Q12_tmp[5], + A_Q12_tmp[6], A_Q12_tmp[7], A_Q12_tmp[8], A_Q12_tmp[9], A_Q12_tmp[10] + local wide = order == 16 + local a10, a11, a12, a13, a14, a15 = A_Q12_tmp[11], A_Q12_tmp[12], A_Q12_tmp[13], A_Q12_tmp[14], A_Q12_tmp[15], A_Q12_tmp[16] + for i = 1, subfr_length do + local j = 16 + i -- 1-based index of sLPC_Q14[MAX_LPC_ORDER + i - 1 (C)] + 1 + local pred = order // 2 + pred += (sLPC_Q14[j - 1] * a0) // 65536 + pred += (sLPC_Q14[j - 2] * a1) // 65536 + pred += (sLPC_Q14[j - 3] * a2) // 65536 + pred += (sLPC_Q14[j - 4] * a3) // 65536 + pred += (sLPC_Q14[j - 5] * a4) // 65536 + pred += (sLPC_Q14[j - 6] * a5) // 65536 + pred += (sLPC_Q14[j - 7] * a6) // 65536 + pred += (sLPC_Q14[j - 8] * a7) // 65536 + pred += (sLPC_Q14[j - 9] * a8) // 65536 + pred += (sLPC_Q14[j - 10] * a9) // 65536 + if wide then + pred += (sLPC_Q14[j - 11] * a10) // 65536 + pred += (sLPC_Q14[j - 12] * a11) // 65536 + pred += (sLPC_Q14[j - 13] * a12) // 65536 + pred += (sLPC_Q14[j - 14] * a13) // 65536 + pred += (sLPC_Q14[j - 15] * a14) // 65536 + pred += (sLPC_Q14[j - 16] * a15) // 65536 + end + pred = i32(pred) + local v = addSat32(presArr[presOff + i], lshiftSat32(pred, 4)) + sLPC_Q14[j] = v + xq[pxq + i - 1] = sat16((mulww(v, Gain_Q10) + 128) // 256) + end + for i = 1, 16 do + sLPC_Q14[i] = sLPC_Q14[subfr_length + i] + end + pexc += subfr_length + pxq += subfr_length + end + for i = 1, 16 do + sl[i] = sLPC_Q14[i] + end +end + +-- PLC / CNG ----------------------------------------------------------------------------------------------------- + +local HARM_ATT_Q15 = { 32440, 31130 } +local PLC_RAND_ATTENUATE_V_Q15 = { 31130, 26214 } +local PLC_RAND_ATTENUATE_UV_Q15 = { 32440, 29491 } + +local function plcReset(ch: any) + local plc = ch.sPLC + plc.pitchL_Q8 = ch.frame_length * 128 + plc.prevGain_Q16[1] = 65536 + plc.prevGain_Q16[2] = 65536 + plc.subfr_length = 20 + plc.nb_subfr = 2 +end + +local function cngReset(ch: any) + local step = tdiv(32767, ch.LPC_order + 1) + local acc = 0 + local cng = ch.sCNG + for i = 1, ch.LPC_order do + acc += step + cng.CNG_smth_NLSF_Q15[i] = acc + end + cng.CNG_smth_Gain_Q16 = 0 + cng.rand_seed = 3176576 +end + +local function plcUpdate(ch: any, ctrl: any) + local plc = ch.sPLC + local nb = ch.nb_subfr + ch.prevSignalType = ch.indices.signalType + local LTP_Gain_Q14 = 0 + local coef = plc.LTPCoef_Q14 + if ch.indices.signalType == 2 then + local j = 0 + while j * ch.subfr_length < ctrl.pitchL[nb] do + if j == nb then + break + end + local t = 0 + local o = (nb - 1 - j) * 5 + for i = 1, 5 do + t += ctrl.LTPCoef_Q14[o + i] + end + if t > LTP_Gain_Q14 then + LTP_Gain_Q14 = t + for i = 1, 5 do + coef[i] = ctrl.LTPCoef_Q14[o + i] + end + plc.pitchL_Q8 = ctrl.pitchL[nb - j] * 256 + end + j += 1 + end + for i = 1, 5 do + coef[i] = 0 + end + coef[3] = LTP_Gain_Q14 + if LTP_Gain_Q14 < 11469 then + local scale_Q10 = tdiv(11469 * 1024, math.max(LTP_Gain_Q14, 1)) + for i = 1, 5 do + coef[i] = (s16(coef[i]) * s16(scale_Q10)) // 1024 + end + elseif LTP_Gain_Q14 > 15565 then + local scale_Q14 = tdiv(15565 * 16384, math.max(LTP_Gain_Q14, 1)) + for i = 1, 5 do + coef[i] = (s16(coef[i]) * s16(scale_Q14)) // 16384 + end + end + else + plc.pitchL_Q8 = ch.fs_kHz * 18 * 256 + for i = 1, 5 do + coef[i] = 0 + end + end + local p = ctrl.PredCoef_Q12[2] + for i = 1, ch.LPC_order do + plc.prevLPC_Q12[i] = p[i] + end + plc.prevLTP_scale_Q14 = ctrl.LTP_scale_Q14 + plc.prevGain_Q16[1] = ctrl.Gains_Q16[nb - 1] + plc.prevGain_Q16[2] = ctrl.Gains_Q16[nb] + plc.subfr_length = ch.subfr_length + plc.nb_subfr = nb +end + +local excBuf = table.create(160, 0) +local plcLTP = table.create(320, 0) +local plcLTP_Q14 = table.create(640, 0) +local A_plc = table.create(16, 0) + +local function plcConceal(ch: any, ctrl: any, frame: { number }, fo: number) + local plc = ch.sPLC + local ltp_mem_length = ch.ltp_mem_length + local order = ch.LPC_order + local prevGain_Q10_0 = plc.prevGain_Q16[1] // 64 + local prevGain_Q10_1 = plc.prevGain_Q16[2] // 64 + if ch.first_frame_after_reset ~= 0 then + for i = 1, 16 do + plc.prevLPC_Q12[i] = 0 + end + end + -- silk_PLC_energy + local sl, nb = ch.subfr_length, ch.nb_subfr + local exc = ch.exc_Q14 + for k = 0, 1 do + local g = if k == 0 then prevGain_Q10_0 else prevGain_Q10_1 + for i = 0, sl - 1 do + excBuf[k * sl + i + 1] = sat16(i32(mulww(exc[i + (k + nb - 2) * sl + 1], g)) // 256) + end + end + local energy1, shift1 = sumSqrShift(excBuf, 1, sl) + local energy2, shift2 = sumSqrShift(excBuf, sl + 1, sl) + local rand_off -- C offset into exc_Q14 + if rshift(energy1, shift2) < rshift(energy2, shift1) then + rand_off = math.max(0, (plc.nb_subfr - 1) * plc.subfr_length - 128) + else + rand_off = math.max(0, plc.nb_subfr * plc.subfr_length - 128) + end + local B = plc.LTPCoef_Q14 + local rand_scale_Q14 = plc.randScale_Q14 + local att = math.min(1, ch.lossCnt) + 1 + local harm_Gain_Q15 = HARM_ATT_Q15[att] + local rand_Gain_Q15 = if ch.prevSignalType == 2 then PLC_RAND_ATTENUATE_V_Q15[att] else PLC_RAND_ATTENUATE_UV_Q15[att] + bwexpander(plc.prevLPC_Q12, order, 64881) + for i = 1, order do + A_plc[i] = plc.prevLPC_Q12[i] + end + if ch.lossCnt == 0 then + rand_scale_Q14 = 16384 + if ch.prevSignalType == 2 then + for i = 1, 5 do + rand_scale_Q14 -= B[i] + end + rand_scale_Q14 = math.max(3277, s16(rand_scale_Q14)) + rand_scale_Q14 = s16((rand_scale_Q14 * s16(plc.prevLTP_scale_Q14)) // 16384) + else + local invGain_Q30 = lpcInversePredGain(plc.prevLPC_Q12, order) + local down = math.min(1073741824 // 8, invGain_Q30) + down = math.max(1073741824 // 256, down) + down = down * 8 + rand_Gain_Q15 = ((down * s16(rand_Gain_Q15)) // 65536) // 16384 + end + end + local rand_seed = plc.rand_seed + local lag = (plc.pitchL_Q8 + 128) // 256 + local sLTP_buf_idx = ltp_mem_length + local idx = ltp_mem_length - lag - order - 2 + if idx < 1 then + idx = 1 + end + lpcAnalysisFilter(plcLTP, idx + 1, ch.outBuf, idx + 1, A_plc, ltp_mem_length - idx, order) + local inv_gain_Q30 = silkINVERSE32_varQ(plc.prevGain_Q16[2], 46) + inv_gain_Q30 = math.min(inv_gain_Q30, 1073741823) + for i = idx + order, ltp_mem_length - 1 do + plcLTP_Q14[i + 1] = (inv_gain_Q30 * plcLTP[i + 1]) // 65536 + end + for _ = 0, ch.nb_subfr - 1 do + local pl = sLTP_buf_idx - lag + 2 + 1 + local b0, b1, b2, b3, b4 = B[1], B[2], B[3], B[4], B[5] + for _ = 1, sl do + local pred = 2 + pred += (plcLTP_Q14[pl] * b0) // 65536 + pred += (plcLTP_Q14[pl - 1] * b1) // 65536 + pred += (plcLTP_Q14[pl - 2] * b2) // 65536 + pred += (plcLTP_Q14[pl - 3] * b3) // 65536 + pred += (plcLTP_Q14[pl - 4] * b4) // 65536 + pl += 1 + rand_seed = silkRand(rand_seed) + local ri = (rand_seed // 33554432) % 128 + sLTP_buf_idx += 1 + plcLTP_Q14[sLTP_buf_idx] = i32((pred + (exc[rand_off + ri + 1] * s16(rand_scale_Q14)) // 65536) * 4) + end + for j = 1, 5 do + B[j] = (harm_Gain_Q15 * s16(B[j])) // 32768 + end + rand_scale_Q14 = (s16(rand_scale_Q14) * s16(rand_Gain_Q15)) // 32768 + plc.pitchL_Q8 = plc.pitchL_Q8 + (plc.pitchL_Q8 * 655) // 65536 + plc.pitchL_Q8 = math.min(plc.pitchL_Q8, 18 * ch.fs_kHz * 256) + lag = (plc.pitchL_Q8 + 128) // 256 + end + -- LPC synthesis in place over plcLTP_Q14, starting at C offset ltp_mem_length - 16 + local base = ltp_mem_length - 16 -- C offset of sLPC_Q14_ptr + local slb = ch.sLPC_Q14_buf + for i = 1, 16 do + plcLTP_Q14[base + i] = slb[i] + end + for i = 0, ch.frame_length - 1 do + local j = base + 16 + i + 1 -- 1-based index of sLPC_Q14_ptr[16 + i] + local pred = order // 2 + for t = 1, order do + pred += (plcLTP_Q14[j - t] * A_plc[t]) // 65536 + end + pred = i32(pred) + local v = addSat32(plcLTP_Q14[j], lshiftSat32(pred, 4)) + plcLTP_Q14[j] = v + frame[fo + i] = sat16((mulww(v, prevGain_Q10_1) + 128) // 256) + end + for i = 1, 16 do + slb[i] = plcLTP_Q14[base + ch.frame_length + i] + end + plc.rand_seed = rand_seed + plc.randScale_Q14 = s16(rand_scale_Q14) + for i = 1, 4 do + ctrl.pitchL[i] = lag + end +end + +local function plcGlueFrames(ch: any, frame: { number }, fo: number, length: number) + local plc = ch.sPLC + if ch.lossCnt ~= 0 then + plc.conc_energy, plc.conc_energy_shift = sumSqrShift(frame, fo, length) + plc.last_frame_lost = 1 + else + if plc.last_frame_lost ~= 0 then + local energy, energy_shift = sumSqrShift(frame, fo, length) + if energy_shift > plc.conc_energy_shift then + plc.conc_energy = rshift(plc.conc_energy, energy_shift - plc.conc_energy_shift) + elseif energy_shift < plc.conc_energy_shift then + energy = rshift(energy, plc.conc_energy_shift - energy_shift) + end + if energy > plc.conc_energy then + local LZ = clz32(plc.conc_energy) - 1 + plc.conc_energy = i32(plc.conc_energy * p2(LZ)) + energy = rshift(energy, math.max(24 - LZ, 0)) + local frac_Q24 = tdiv(plc.conc_energy, math.max(energy, 1)) + local gain_Q16 = silkSQRT_APPROX(frac_Q24) * 16 + local slope_Q16 = tdiv(65536 - gain_Q16, length) * 4 + for i = 0, length - 1 do + frame[fo + i] = (gain_Q16 * frame[fo + i]) // 65536 + gain_Q16 += slope_Q16 + if gain_Q16 > 65536 then + break + end + end + end + end + plc.last_frame_lost = 0 + end +end + +local A_cng = table.create(16, 0) +local CNG_sig = table.create(336, 0) + +local function cng(ch: any, ctrl: any, frame: { number }, fo: number, length: number) + local c = ch.sCNG + if ch.fs_kHz ~= c.fs_kHz then + cngReset(ch) + c.fs_kHz = ch.fs_kHz + end + local order = ch.LPC_order + if ch.lossCnt == 0 and ch.prevSignalType == 0 then + local sm = c.CNG_smth_NLSF_Q15 + for i = 1, order do + sm[i] += ((ch.prevNLSF_Q15[i] - sm[i]) * 16348) // 65536 + end + local max_Gain_Q16, subfr = 0, 0 + for i = 0, ch.nb_subfr - 1 do + if ctrl.Gains_Q16[i + 1] > max_Gain_Q16 then + max_Gain_Q16 = ctrl.Gains_Q16[i + 1] + subfr = i + end + end + local eb = c.CNG_exc_buf_Q14 + local sl = ch.subfr_length + for i = (ch.nb_subfr - 1) * sl, 1, -1 do + eb[sl + i] = eb[i] + end + for i = 1, sl do + eb[i] = ch.exc_Q14[subfr * sl + i] + end + for i = 1, ch.nb_subfr do + local g = ctrl.Gains_Q16[i] + c.CNG_smth_Gain_Q16 += ((g - c.CNG_smth_Gain_Q16) * 4634) // 65536 + if mulww(c.CNG_smth_Gain_Q16, 46396) > g then + c.CNG_smth_Gain_Q16 = g + end + end + end + if ch.lossCnt ~= 0 then + local gain_Q16 = i32(mulww(ch.sPLC.randScale_Q14, ch.sPLC.prevGain_Q16[2])) + if gain_Q16 >= 2097152 or c.CNG_smth_Gain_Q16 > 8388608 then + gain_Q16 = (gain_Q16 // 65536) * (gain_Q16 // 65536) + gain_Q16 = i32((c.CNG_smth_Gain_Q16 // 65536) * (c.CNG_smth_Gain_Q16 // 65536) - gain_Q16 * 32) + gain_Q16 = i32(silkSQRT_APPROX(gain_Q16) * 65536) + else + gain_Q16 = i32(mulww(gain_Q16, gain_Q16)) + gain_Q16 = i32(i32(mulww(c.CNG_smth_Gain_Q16, c.CNG_smth_Gain_Q16)) - gain_Q16 * 32) + gain_Q16 = i32(silkSQRT_APPROX(gain_Q16) * 256) + end + local gain_Q10 = gain_Q16 // 64 + -- silk_CNG_exc + local exc_mask = 255 + while exc_mask > length do + exc_mask //= 2 + end + local seed = c.rand_seed + for i = 1, length do + seed = silkRand(seed) + local idx = bit32.band((seed // 16777216) % 256, exc_mask) + CNG_sig[16 + i] = c.CNG_exc_buf_Q14[idx + 1] + end + c.rand_seed = seed + nlsf2a(A_cng, c.CNG_smth_NLSF_Q15, order) + for i = 1, 16 do + CNG_sig[i] = c.CNG_synth_state[i] + end + for i = 0, length - 1 do + local j = 16 + i + 1 + local pred = order // 2 + for t = 1, order do + pred += (CNG_sig[j - t] * A_cng[t]) // 65536 + end + pred = i32(pred) + local v = addSat32(CNG_sig[j], lshiftSat32(pred, 4)) + CNG_sig[j] = v + frame[fo + i] = sat16(frame[fo + i] + sat16((mulww(v, gain_Q10) + 128) // 256)) + end + for i = 1, 16 do + c.CNG_synth_state[i] = CNG_sig[length + i] + end + else + for i = 1, order do + c.CNG_synth_state[i] = 0 + end + end +end + +-- Frame decode -------------------------------------------------------------------------------------------------- + +-- silk_decode_frame: writes frame_length samples to out[fo ..] +local function decodeFrame(ch: any, d: any, out: { number }, fo: number, lostFlag: number, condCoding: number): number + local L = ch.frame_length + local ctrl = ch.ctrl + ctrl.LTP_scale_Q14 = 0 + if lostFlag == 0 or (lostFlag == 2 and ch.LBRR_flags[ch.nFramesDecoded + 1] == 1) then + local pulses = ch.pulses + decodeIndices(ch, d, ch.nFramesDecoded, lostFlag ~= 0, condCoding) + decodePulses(d, pulses, ch.indices.signalType, ch.indices.quantOffsetType, L) + decodeParameters(ch, ctrl, condCoding) + decodeCore(ch, ctrl, out, fo, pulses) + local mv_len = ch.ltp_mem_length - L + local ob = ch.outBuf + for i = 1, mv_len do + ob[i] = ob[L + i] + end + for i = 0, L - 1 do + ob[mv_len + i + 1] = out[fo + i] + end + -- silk_PLC (update) + if ch.fs_kHz ~= ch.sPLC.fs_kHz then + plcReset(ch) + ch.sPLC.fs_kHz = ch.fs_kHz + end + plcUpdate(ch, ctrl) + ch.lossCnt = 0 + ch.prevSignalType = ch.indices.signalType + ch.first_frame_after_reset = 0 + else + if ch.fs_kHz ~= ch.sPLC.fs_kHz then + plcReset(ch) + ch.sPLC.fs_kHz = ch.fs_kHz + end + plcConceal(ch, ctrl, out, fo) + ch.lossCnt += 1 + local mv_len = ch.ltp_mem_length - L + local ob = ch.outBuf + for i = 1, mv_len do + ob[i] = ob[L + i] + end + for i = 0, L - 1 do + ob[mv_len + i + 1] = out[fo + i] + end + end + cng(ch, ctrl, out, fo, L) + plcGlueFrames(ch, out, fo, L) + ch.lagPrev = ctrl.pitchL[ch.nb_subfr] + return L +end + +-- Stereo -------------------------------------------------------------------------------------------------------- + +local function stereoDecodePred(d: any, pred_Q13: { number }) + local n = icdf(d, T.stereo_pred_joint_iCDF, 1, 8) + local ix02 = n // 5 + local ix12 = n - 5 * ix02 + local ix00 = icdf(d, T.uniform3_iCDF, 1, 8) + local ix01 = icdf(d, T.uniform5_iCDF, 1, 8) + local ix10 = icdf(d, T.uniform3_iCDF, 1, 8) + local ix11 = icdf(d, T.uniform5_iCDF, 1, 8) + local q = T.stereo_pred_quant_Q13 + for c = 1, 2 do + local a = if c == 1 then ix00 + 3 * ix02 else ix10 + 3 * ix12 + local b = if c == 1 then ix01 else ix11 + local low_Q13 = q[a + 1] + local step_Q13 = ((q[a + 2] - low_Q13) * 6554) // 65536 + pred_Q13[c] = low_Q13 + s16(step_Q13) * (2 * b + 1) + end + pred_Q13[1] -= pred_Q13[2] +end + +-- x1, x2: samplesOut1_tmp arrays (C index j at [j + 1]) +local function stereoMSToLR(state: any, x1: { number }, x2: { number }, pred_Q13: { number }, fs_kHz: number, frame_length: number) + x1[1], x1[2] = state.sMid[1], state.sMid[2] + x2[1], x2[2] = state.sSide[1], state.sSide[2] + state.sMid[1], state.sMid[2] = x1[frame_length + 1], x1[frame_length + 2] + state.sSide[1], state.sSide[2] = x2[frame_length + 1], x2[frame_length + 2] + local pred0 = state.pred_prev_Q13[1] + local pred1 = state.pred_prev_Q13[2] + local interp = 8 * fs_kHz + local denom_Q16 = tdiv(65536, interp) + local delta0 = (s16(pred_Q13[1] - pred0) * s16(denom_Q16) + 32768) // 65536 + local delta1 = (s16(pred_Q13[2] - pred1) * s16(denom_Q16) + 32768) // 65536 + for n = 0, frame_length - 1 do + if n < interp then + pred0 += delta0 + pred1 += delta1 + elseif n == interp then + pred0 = pred_Q13[1] + pred1 = pred_Q13[2] + end + local sum = (x1[n + 1] + x1[n + 3] + x1[n + 2] * 2) * 512 + sum = x2[n + 2] * 256 + (sum * s16(pred0)) // 65536 + sum = sum + ((x1[n + 2] * 2048) * s16(pred1)) // 65536 + x2[n + 2] = sat16((sum + 128) // 256) + end + if frame_length <= interp then + -- the second loop never ran; the C code still ends with pred = pred_Q13 + end + state.pred_prev_Q13[1] = pred_Q13[1] + state.pred_prev_Q13[2] = pred_Q13[2] + for n = 0, frame_length - 1 do + local a, b = x1[n + 2], x2[n + 2] + x1[n + 2] = sat16(a + b) + x2[n + 2] = sat16(a - b) + end +end + +-- API ----------------------------------------------------------------------------------------------------------- + +export type State = any + +function Silk.new(apiChannels: number): State + return { + ch = { newChannel(), newChannel() }, + sStereo = { pred_prev_Q13 = { 0, 0 }, sMid = { 0, 0 }, sSide = { 0, 0 } }, + nChannelsAPI = 0, + nChannelsInternal = 0, + prev_decode_only_middle = 0, + MS_pred_Q13 = { 0, 0 }, + resampOut = table.create(960, 0), + apiChannels = apiChannels, + } +end + +-- silk_ResetDecoder (keeps nChannelsAPI / nChannelsInternal, like libopus) +function Silk.reset(st: State) + st.ch[1] = newChannel() + st.ch[2] = newChannel() + for _, ch in st.ch do + cngReset(ch) + plcReset(ch) + end + st.sStereo = { pred_prev_Q13 = { 0, 0 }, sMid = { 0, 0 }, sSide = { 0, 0 } } + st.prev_decode_only_middle = 0 +end + +local function initChannel(st: State, n: number) + local ch = newChannel() + cngReset(ch) + plcReset(ch) + st.ch[n] = ch +end + +function Silk.decode(st: State, ctrl: any, lostFlag: number, firstFrame: boolean, d: any, out: { number }, outBase: number): (number, number) + local ret = 0 + local nInt = ctrl.nChannelsInternal + local nAPI = ctrl.nChannelsAPI + local chs = st.ch + local decode_only_middle = 0 + local MS_pred_Q13 = st.MS_pred_Q13 + MS_pred_Q13[1], MS_pred_Q13[2] = 0, 0 + if nInt ~= 1 and nInt ~= 2 then + return -200, 0 + end + if firstFrame then + for n = 1, nInt do + chs[n].nFramesDecoded = 0 + end + end + if nInt > st.nChannelsInternal then + initChannel(st, 2) + end + local ch1 = chs[1] + local stereo_to_mono = nInt == 1 and st.nChannelsInternal == 2 and ctrl.internalSampleRate == 1000 * ch1.fs_kHz + if ch1.nFramesDecoded == 0 then + for n = 1, nInt do + local ch = chs[n] + local ms = ctrl.payloadSize_ms + if ms == 0 or ms == 10 then + ch.nFramesPerPacket = 1 + ch.nb_subfr = 2 + elseif ms == 20 then + ch.nFramesPerPacket = 1 + ch.nb_subfr = 4 + elseif ms == 40 then + ch.nFramesPerPacket = 2 + ch.nb_subfr = 4 + elseif ms == 60 then + ch.nFramesPerPacket = 3 + ch.nb_subfr = 4 + else + return -203, 0 + end + local fs_kHz_dec = ctrl.internalSampleRate // 1024 + 1 + if fs_kHz_dec ~= 8 and fs_kHz_dec ~= 12 and fs_kHz_dec ~= 16 then + return -200, 0 + end + ret += decoderSetFs(ch, fs_kHz_dec, ctrl.API_sampleRate) + end + end + if nAPI == 2 and nInt == 2 and (st.nChannelsAPI == 1 or st.nChannelsInternal == 1) then + local s = st.sStereo + s.pred_prev_Q13[1], s.pred_prev_Q13[2] = 0, 0 + s.sSide[1], s.sSide[2] = 0, 0 + copyResampler(chs[2].resampler_state, ch1.resampler_state) + end + st.nChannelsAPI = nAPI + st.nChannelsInternal = nInt + if ctrl.API_sampleRate > 48000 or ctrl.API_sampleRate < 8000 then + return -200, 0 + end + if lostFlag ~= 1 and ch1.nFramesDecoded == 0 then + for n = 1, nInt do + local ch = chs[n] + for i = 1, ch.nFramesPerPacket do + ch.VAD_flags[i] = if bitLogp(d, 1) then 1 else 0 + end + ch.LBRR_flag = if bitLogp(d, 1) then 1 else 0 + end + for n = 1, nInt do + local ch = chs[n] + ch.LBRR_flags[1], ch.LBRR_flags[2], ch.LBRR_flags[3] = 0, 0, 0 + if ch.LBRR_flag ~= 0 then + if ch.nFramesPerPacket == 1 then + ch.LBRR_flags[1] = 1 + else + local sym = icdf(d, LBRR_flags_iCDF[ch.nFramesPerPacket - 1], 1, 8) + 1 + for i = 0, ch.nFramesPerPacket - 1 do + ch.LBRR_flags[i + 1] = bit32.band(bit32.rshift(sym, i), 1) + end + end + end + end + if lostFlag == 0 then + -- skip all LBRR data + for i = 0, ch1.nFramesPerPacket - 1 do + for n = 1, nInt do + local ch = chs[n] + if ch.LBRR_flags[i + 1] ~= 0 then + if nInt == 2 and n == 1 then + stereoDecodePred(d, MS_pred_Q13) + if chs[2].LBRR_flags[i + 1] == 0 then + decode_only_middle = icdf(d, T.stereo_only_code_mid_iCDF, 1, 8) + end + end + local condCoding = if i > 0 and ch.LBRR_flags[i] ~= 0 then 2 else 0 + decodeIndices(ch, d, i, true, condCoding) + decodePulses(d, ch.pulses, ch.indices.signalType, ch.indices.quantOffsetType, ch.frame_length) + end + end + end + end + end + if nInt == 2 then + local fd = ch1.nFramesDecoded + if lostFlag == 0 or (lostFlag == 2 and ch1.LBRR_flags[fd + 1] == 1) then + stereoDecodePred(d, MS_pred_Q13) + if (lostFlag == 0 and chs[2].VAD_flags[fd + 1] == 0) or (lostFlag == 2 and chs[2].LBRR_flags[fd + 1] == 0) then + decode_only_middle = icdf(d, T.stereo_only_code_mid_iCDF, 1, 8) + else + decode_only_middle = 0 + end + else + MS_pred_Q13[1] = st.sStereo.pred_prev_Q13[1] + MS_pred_Q13[2] = st.sStereo.pred_prev_Q13[2] + end + end + if nInt == 2 and decode_only_middle == 0 and st.prev_decode_only_middle == 1 then + local c2 = chs[2] + for i = 1, 480 do + c2.outBuf[i] = 0 + end + for i = 1, 16 do + c2.sLPC_Q14_buf[i] = 0 + end + c2.lagPrev = 100 + c2.LastGainIndex = 10 + c2.prevSignalType = 0 + c2.first_frame_after_reset = 1 + end + local has_side + if lostFlag == 0 then + has_side = decode_only_middle == 0 + else + has_side = st.prev_decode_only_middle == 0 + or (nInt == 2 and lostFlag == 2 and chs[2].LBRR_flags[chs[2].nFramesDecoded + 1] == 1) + end + local nSamplesOutDec = ch1.frame_length + for n = 1, nInt do + local ch = chs[n] + if n == 1 or has_side then + local FrameIndex = ch1.nFramesDecoded - (n - 1) + local condCoding + if FrameIndex <= 0 then + condCoding = 0 + elseif lostFlag == 2 then + condCoding = if ch.LBRR_flags[FrameIndex] ~= 0 then 2 else 0 + elseif n > 1 and st.prev_decode_only_middle ~= 0 then + condCoding = 1 + else + condCoding = 2 + end + nSamplesOutDec = decodeFrame(ch, d, ch.out, 3, lostFlag, condCoding) + else + local o = ch.out + for i = 3, nSamplesOutDec + 2 do + o[i] = 0 + end + end + ch.nFramesDecoded += 1 + end + local o1 = ch1.out + if nAPI == 2 and nInt == 2 then + stereoMSToLR(st.sStereo, o1, chs[2].out, MS_pred_Q13, ch1.fs_kHz, nSamplesOutDec) + else + local sMid = st.sStereo.sMid + o1[1], o1[2], sMid[1], sMid[2] = sMid[1], sMid[2], o1[nSamplesOutDec + 1], o1[nSamplesOutDec + 2] + end + local nSamplesOut = (nSamplesOutDec * ctrl.API_sampleRate) // (ch1.fs_kHz * 1000) + local ro = st.resampOut + local scale = 1 / 32768 + for n = 1, math.min(nAPI, nInt) do + resampler(chs[n].resampler_state, ro, chs[n].out, 2, nSamplesOutDec) + if nAPI == 2 then + local b = outBase + n - 1 + for i = 0, nSamplesOut - 1 do + out[b + 2 * i] = ro[i + 1] * scale + end + else + for i = 0, nSamplesOut - 1 do + out[outBase + i] = ro[i + 1] * scale + end + end + end + if nAPI == 2 and nInt == 1 then + if stereo_to_mono then + resampler(chs[2].resampler_state, ro, o1, 2, nSamplesOutDec) + for i = 0, nSamplesOut - 1 do + out[outBase + 1 + 2 * i] = ro[i + 1] * scale + end + else + for i = 0, nSamplesOut - 1 do + out[outBase + 1 + 2 * i] = out[outBase + 2 * i] + end + end + end + if lostFlag == 1 then + for i = 1, st.nChannelsInternal do + chs[i].LastGainIndex = 10 + end + else + st.prev_decode_only_middle = decode_only_middle + end + return ret, nSamplesOut +end + +-- the pitch lag of the last frame at 48 kHz (decControl->prevPitchLag), 0 when unvoiced +function Silk.prevPitchLag(st: State): number + local ch = st.ch[1] + if ch.prevSignalType == 2 then + local mult = { 6, 4, 3 } + return ch.lagPrev * mult[(ch.fs_kHz - 8) // 4 + 1] + end + return 0 +end + +return Silk diff --git a/src/Formats/audio/opus/SilkTables.luau b/src/Formats/audio/opus/SilkTables.luau new file mode 100644 index 0000000..0322c48 --- /dev/null +++ b/src/Formats/audio/opus/SilkTables.luau @@ -0,0 +1,372 @@ +--!strict +--!optimize 2 +-- audio/opus/SilkTables: SILK decoder tables (generated from libopus silk/tables_*.c, pitch_est_tables.c, resampler_rom.c; BSD, see +-- licenses/). Multi-dimensional C arrays are flattened row-major; every array is 1-based. +local T = {} +T.LTP_per_index_iCDF = { + 179, 99, 0, +} +T.LTP_gain_iCDF_0 = { + 71, 56, 43, 30, 21, 12, 6, 0, +} +T.LTP_gain_iCDF_1 = { + 199, 165, 144, 124, 109, 96, 84, 71, 61, 51, 42, 32, 23, 15, 8, 0, +} +T.LTP_gain_iCDF_2 = { + 241, 225, 211, 199, 187, 175, 164, 153, 142, 132, 123, 114, 105, 96, 88, 80, 72, 64, 57, 50, + 44, 38, 33, 29, 24, 20, 16, 12, 9, 5, 2, 0, +} +T.LTP_gain_vq_0 = { + 4, 6, 24, 7, 5, 0, 0, 2, 0, 0, 12, 28, 41, 13, -4, -9, 15, 42, 25, 14, + 1, -2, 62, 41, -9, -10, 37, 65, -4, 3, -6, 4, 66, 7, -8, 16, 14, 38, -3, 33, +} +T.LTP_gain_vq_1 = { + 13, 22, 39, 23, 12, -1, 36, 64, 27, -6, -7, 10, 55, 43, 17, 1, 1, 8, 1, 1, + 6, -11, 74, 53, -9, -12, 55, 76, -12, 8, -3, 3, 93, 27, -4, 26, 39, 59, 3, -8, + 2, 0, 77, 11, 9, -8, 22, 44, -6, 7, 40, 9, 26, 3, 9, -7, 20, 101, -7, 4, + 3, -8, 42, 26, 0, -15, 33, 68, 2, 23, -2, 55, 46, -2, 15, 3, -1, 21, 16, 41, +} +T.LTP_gain_vq_2 = { + -6, 27, 61, 39, 5, -11, 42, 88, 4, 1, -2, 60, 65, 6, -4, -1, -5, 73, 56, 1, + -9, 19, 94, 29, -9, 0, 12, 99, 6, 4, 8, -19, 102, 46, -13, 3, 2, 13, 3, 2, + 9, -21, 84, 72, -18, -11, 46, 104, -22, 8, 18, 38, 48, 23, 0, -16, 70, 83, -21, 11, + 5, -11, 117, 22, -8, -6, 23, 117, -12, 3, 3, -8, 95, 28, 4, -10, 15, 77, 60, -15, + -1, 4, 124, 2, -4, 3, 38, 84, 24, -25, 2, 13, 42, 13, 31, 21, -4, 56, 46, -1, + -1, 35, 79, -13, 19, -7, 65, 88, -9, -14, 20, 4, 81, 49, -29, 20, 0, 75, 3, -17, + 5, -9, 44, 92, -8, 1, -3, 22, 69, 31, -6, 95, 41, -12, 5, 39, 67, 16, -4, 1, + 0, -6, 120, 55, -36, -13, 44, 122, 4, -24, 81, 5, 11, 3, 7, 2, 0, 9, 10, 88, +} +T.NLSF_CB1_WB_Q8 = { + 7, 23, 38, 54, 69, 85, 100, 116, 131, 147, 162, 178, 193, 208, 223, 239, 13, 25, 41, 55, + 69, 83, 98, 112, 127, 142, 157, 171, 187, 203, 220, 236, 15, 21, 34, 51, 61, 78, 92, 106, + 126, 136, 152, 167, 185, 205, 225, 240, 10, 21, 36, 50, 63, 79, 95, 110, 126, 141, 157, 173, + 189, 205, 221, 237, 17, 20, 37, 51, 59, 78, 89, 107, 123, 134, 150, 164, 184, 205, 224, 240, + 10, 15, 32, 51, 67, 81, 96, 112, 129, 142, 158, 173, 189, 204, 220, 236, 8, 21, 37, 51, + 65, 79, 98, 113, 126, 138, 155, 168, 179, 192, 209, 218, 12, 15, 34, 55, 63, 78, 87, 108, + 118, 131, 148, 167, 185, 203, 219, 236, 16, 19, 32, 36, 56, 79, 91, 108, 118, 136, 154, 171, + 186, 204, 220, 237, 11, 28, 43, 58, 74, 89, 105, 120, 135, 150, 165, 180, 196, 211, 226, 241, + 6, 16, 33, 46, 60, 75, 92, 107, 123, 137, 156, 169, 185, 199, 214, 225, 11, 19, 30, 44, + 57, 74, 89, 105, 121, 135, 152, 169, 186, 202, 218, 234, 12, 19, 29, 46, 57, 71, 88, 100, + 120, 132, 148, 165, 182, 199, 216, 233, 17, 23, 35, 46, 56, 77, 92, 106, 123, 134, 152, 167, + 185, 204, 222, 237, 14, 17, 45, 53, 63, 75, 89, 107, 115, 132, 151, 171, 188, 206, 221, 240, + 9, 16, 29, 40, 56, 71, 88, 103, 119, 137, 154, 171, 189, 205, 222, 237, 16, 19, 36, 48, + 57, 76, 87, 105, 118, 132, 150, 167, 185, 202, 218, 236, 12, 17, 29, 54, 71, 81, 94, 104, + 126, 136, 149, 164, 182, 201, 221, 237, 15, 28, 47, 62, 79, 97, 115, 129, 142, 155, 168, 180, + 194, 208, 223, 238, 8, 14, 30, 45, 62, 78, 94, 111, 127, 143, 159, 175, 192, 207, 223, 239, + 17, 30, 49, 62, 79, 92, 107, 119, 132, 145, 160, 174, 190, 204, 220, 235, 14, 19, 36, 45, + 61, 76, 91, 108, 121, 138, 154, 172, 189, 205, 222, 238, 12, 18, 31, 45, 60, 76, 91, 107, + 123, 138, 154, 171, 187, 204, 221, 236, 13, 17, 31, 43, 53, 70, 83, 103, 114, 131, 149, 167, + 185, 203, 220, 237, 17, 22, 35, 42, 58, 78, 93, 110, 125, 139, 155, 170, 188, 206, 224, 240, + 8, 15, 34, 50, 67, 83, 99, 115, 131, 146, 162, 178, 193, 209, 224, 239, 13, 16, 41, 66, + 73, 86, 95, 111, 128, 137, 150, 163, 183, 206, 225, 241, 17, 25, 37, 52, 63, 75, 92, 102, + 119, 132, 144, 160, 175, 191, 212, 231, 19, 31, 49, 65, 83, 100, 117, 133, 147, 161, 174, 187, + 200, 213, 227, 242, 18, 31, 52, 68, 88, 103, 117, 126, 138, 149, 163, 177, 192, 207, 223, 239, + 16, 29, 47, 61, 76, 90, 106, 119, 133, 147, 161, 176, 193, 209, 224, 240, 15, 21, 35, 50, + 61, 73, 86, 97, 110, 119, 129, 141, 175, 198, 218, 237, +} +T.NLSF_CB1_WB_Wght_Q9 = { + 3657, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2963, 2963, 2925, 2846, 3216, 3085, 2972, 3056, + 3056, 3010, 3010, 3010, 2963, 2963, 3010, 2972, 2888, 2846, 2846, 2726, 3920, 4014, 2981, 3207, 3207, 2934, 3056, 2846, + 3122, 3244, 2925, 2846, 2620, 2553, 2780, 2925, 3516, 3197, 3010, 3103, 3019, 2888, 2925, 2925, 2925, 2925, 2888, 2888, + 2888, 2888, 2888, 2753, 5054, 5054, 2934, 3573, 3385, 3056, 3085, 2793, 3160, 3160, 2972, 2846, 2513, 2540, 2753, 2888, + 4428, 4149, 2700, 2753, 2972, 3010, 2925, 2846, 2981, 3019, 2925, 2925, 2925, 2925, 2888, 2726, 3620, 3019, 2972, 3056, + 3056, 2873, 2806, 3056, 3216, 3047, 2981, 3291, 3291, 2981, 3310, 2991, 5227, 5014, 2540, 3338, 3526, 3385, 3197, 3094, + 3376, 2981, 2700, 2647, 2687, 2793, 2846, 2673, 5081, 5174, 4615, 4428, 2460, 2897, 3047, 3207, 3169, 2687, 2740, 2888, + 2846, 2793, 2846, 2700, 3122, 2888, 2963, 2925, 2925, 2925, 2925, 2963, 2963, 2963, 2963, 2925, 2925, 2963, 2963, 2963, + 4202, 3207, 2981, 3103, 3010, 2888, 2888, 2925, 2972, 2873, 2916, 3019, 2972, 3010, 3197, 2873, 3760, 3760, 3244, 3103, + 2981, 2888, 2925, 2888, 2972, 2934, 2793, 2793, 2846, 2888, 2888, 2660, 3854, 4014, 3207, 3122, 3244, 2934, 3047, 2963, + 2963, 3085, 2846, 2793, 2793, 2793, 2793, 2580, 3845, 4080, 3357, 3516, 3094, 2740, 3010, 2934, 3122, 3085, 2846, 2846, + 2647, 2647, 2846, 2806, 5147, 4894, 3225, 3845, 3441, 3169, 2897, 3413, 3451, 2700, 2580, 2673, 2740, 2846, 2806, 2753, + 4109, 3789, 3291, 3160, 2925, 2888, 2888, 2925, 2793, 2740, 2793, 2740, 2793, 2846, 2888, 2806, 5081, 5054, 3047, 3545, + 3244, 3056, 3085, 2944, 3103, 2897, 2740, 2740, 2740, 2846, 2793, 2620, 4309, 4309, 2860, 2527, 3207, 3376, 3376, 3075, + 3075, 3376, 3056, 2846, 2647, 2580, 2726, 2753, 3056, 2916, 2806, 2888, 2740, 2687, 2897, 3103, 3150, 3150, 3216, 3169, + 3056, 3010, 2963, 2846, 4375, 3882, 2925, 2888, 2846, 2888, 2846, 2846, 2888, 2888, 2888, 2846, 2888, 2925, 2888, 2846, + 2981, 2916, 2916, 2981, 2981, 3056, 3122, 3216, 3150, 3056, 3010, 2972, 2972, 2972, 2925, 2740, 4229, 4149, 3310, 3347, + 2925, 2963, 2888, 2981, 2981, 2846, 2793, 2740, 2846, 2846, 2846, 2793, 4080, 4014, 3103, 3010, 2925, 2925, 2925, 2888, + 2925, 2925, 2846, 2846, 2846, 2793, 2888, 2780, 4615, 4575, 3169, 3441, 3207, 2981, 2897, 3038, 3122, 2740, 2687, 2687, + 2687, 2740, 2793, 2700, 4149, 4269, 3789, 3657, 2726, 2780, 2888, 2888, 3010, 2972, 2925, 2846, 2687, 2687, 2793, 2888, + 4215, 3554, 2753, 2846, 2846, 2888, 2888, 2888, 2925, 2925, 2888, 2925, 2925, 2925, 2963, 2888, 5174, 4921, 2261, 3432, + 3789, 3479, 3347, 2846, 3310, 3479, 3150, 2897, 2460, 2487, 2753, 2925, 3451, 3685, 3122, 3197, 3357, 3047, 3207, 3207, + 2981, 3216, 3085, 2925, 2925, 2687, 2540, 2434, 2981, 3010, 2793, 2793, 2740, 2793, 2846, 2972, 3056, 3103, 3150, 3150, + 3150, 3103, 3010, 3010, 2944, 2873, 2687, 2726, 2780, 3010, 3432, 3545, 3357, 3244, 3056, 3010, 2963, 2925, 2888, 2846, + 3019, 2944, 2897, 3010, 3010, 2972, 3019, 3103, 3056, 3056, 3010, 2888, 2846, 2925, 2925, 2888, 3920, 3967, 3010, 3197, + 3357, 3216, 3291, 3291, 3479, 3704, 3441, 2726, 2181, 2460, 2580, 2607, +} +T.NLSF_CB1_iCDF_WB = { + 225, 204, 201, 184, 183, 175, 158, 154, 153, 135, 119, 115, 113, 110, 109, 99, 98, 95, 79, 68, + 52, 50, 48, 45, 43, 32, 31, 27, 18, 10, 3, 0, 255, 251, 235, 230, 212, 201, 196, 182, + 167, 166, 163, 151, 138, 124, 110, 104, 90, 78, 76, 70, 69, 57, 45, 34, 24, 21, 11, 6, + 5, 4, 3, 0, +} +T.NLSF_CB2_SELECT_WB = { + 0, 0, 0, 0, 0, 0, 0, 1, 100, 102, 102, 68, 68, 36, 34, 96, 164, 107, 158, 185, + 180, 185, 139, 102, 64, 66, 36, 34, 34, 0, 1, 32, 208, 139, 141, 191, 152, 185, 155, 104, + 96, 171, 104, 166, 102, 102, 102, 132, 1, 0, 0, 0, 0, 16, 16, 0, 80, 109, 78, 107, + 185, 139, 103, 101, 208, 212, 141, 139, 173, 153, 123, 103, 36, 0, 0, 0, 0, 0, 0, 1, + 48, 0, 0, 0, 0, 0, 0, 32, 68, 135, 123, 119, 119, 103, 69, 98, 68, 103, 120, 118, + 118, 102, 71, 98, 134, 136, 157, 184, 182, 153, 139, 134, 208, 168, 248, 75, 189, 143, 121, 107, + 32, 49, 34, 34, 34, 0, 17, 2, 210, 235, 139, 123, 185, 137, 105, 134, 98, 135, 104, 182, + 100, 183, 171, 134, 100, 70, 68, 70, 66, 66, 34, 131, 64, 166, 102, 68, 36, 2, 1, 0, + 134, 166, 102, 68, 34, 34, 66, 132, 212, 246, 158, 139, 107, 107, 87, 102, 100, 219, 125, 122, + 137, 118, 103, 132, 114, 135, 137, 105, 171, 106, 50, 34, 164, 214, 141, 143, 185, 151, 121, 103, + 192, 34, 0, 0, 0, 0, 0, 1, 208, 109, 74, 187, 134, 249, 159, 137, 102, 110, 154, 118, + 87, 101, 119, 101, 0, 2, 0, 36, 36, 66, 68, 35, 96, 164, 102, 100, 36, 0, 2, 33, + 167, 138, 174, 102, 100, 84, 2, 2, 100, 107, 120, 119, 36, 197, 24, 0, +} +T.NLSF_CB2_iCDF_WB = { + 255, 254, 253, 244, 12, 3, 2, 1, 0, 255, 254, 252, 224, 38, 3, 2, 1, 0, 255, 254, + 251, 209, 57, 4, 2, 1, 0, 255, 254, 244, 195, 69, 4, 2, 1, 0, 255, 251, 232, 184, + 84, 7, 2, 1, 0, 255, 254, 240, 186, 86, 14, 2, 1, 0, 255, 254, 239, 178, 91, 30, + 5, 1, 0, 255, 248, 227, 177, 100, 19, 2, 1, 0, +} +T.NLSF_PRED_WB_Q8 = { + 175, 148, 160, 176, 178, 173, 174, 164, 177, 174, 196, 182, 198, 192, 182, 68, 62, 66, 60, 72, + 117, 85, 90, 118, 136, 151, 142, 160, 142, 155, +} +T.NLSF_DELTA_MIN_WB_Q15 = { + 100, 3, 40, 3, 3, 3, 5, 14, 14, 10, 11, 3, 8, 9, 7, 3, 347, +} +T.NLSF_CB1_NB_MB_Q8 = { + 12, 35, 60, 83, 108, 132, 157, 180, 206, 228, 15, 32, 55, 77, 101, 125, 151, 175, 201, 225, + 19, 42, 66, 89, 114, 137, 162, 184, 209, 230, 12, 25, 50, 72, 97, 120, 147, 172, 200, 223, + 26, 44, 69, 90, 114, 135, 159, 180, 205, 225, 13, 22, 53, 80, 106, 130, 156, 180, 205, 228, + 15, 25, 44, 64, 90, 115, 142, 168, 196, 222, 19, 24, 62, 82, 100, 120, 145, 168, 190, 214, + 22, 31, 50, 79, 103, 120, 151, 170, 203, 227, 21, 29, 45, 65, 106, 124, 150, 171, 196, 224, + 30, 49, 75, 97, 121, 142, 165, 186, 209, 229, 19, 25, 52, 70, 93, 116, 143, 166, 192, 219, + 26, 34, 62, 75, 97, 118, 145, 167, 194, 217, 25, 33, 56, 70, 91, 113, 143, 165, 196, 223, + 21, 34, 51, 72, 97, 117, 145, 171, 196, 222, 20, 29, 50, 67, 90, 117, 144, 168, 197, 221, + 22, 31, 48, 66, 95, 117, 146, 168, 196, 222, 24, 33, 51, 77, 116, 134, 158, 180, 200, 224, + 21, 28, 70, 87, 106, 124, 149, 170, 194, 217, 26, 33, 53, 64, 83, 117, 152, 173, 204, 225, + 27, 34, 65, 95, 108, 129, 155, 174, 210, 225, 20, 26, 72, 99, 113, 131, 154, 176, 200, 219, + 34, 43, 61, 78, 93, 114, 155, 177, 205, 229, 23, 29, 54, 97, 124, 138, 163, 179, 209, 229, + 30, 38, 56, 89, 118, 129, 158, 178, 200, 231, 21, 29, 49, 63, 85, 111, 142, 163, 193, 222, + 27, 48, 77, 103, 133, 158, 179, 196, 215, 232, 29, 47, 74, 99, 124, 151, 176, 198, 220, 237, + 33, 42, 61, 76, 93, 121, 155, 174, 207, 225, 29, 53, 87, 112, 136, 154, 170, 188, 208, 227, + 24, 30, 52, 84, 131, 150, 166, 186, 203, 229, 37, 48, 64, 84, 104, 118, 156, 177, 201, 230, +} +T.NLSF_CB1_Wght_Q9 = { + 2897, 2314, 2314, 2314, 2287, 2287, 2314, 2300, 2327, 2287, 2888, 2580, 2394, 2367, 2314, 2274, 2274, 2274, 2274, 2194, + 2487, 2340, 2340, 2314, 2314, 2314, 2340, 2340, 2367, 2354, 3216, 2766, 2340, 2340, 2314, 2274, 2221, 2207, 2261, 2194, + 2460, 2474, 2367, 2394, 2394, 2394, 2394, 2367, 2407, 2314, 3479, 3056, 2127, 2207, 2274, 2274, 2274, 2287, 2314, 2261, + 3282, 3141, 2580, 2394, 2247, 2221, 2207, 2194, 2194, 2114, 4096, 3845, 2221, 2620, 2620, 2407, 2314, 2394, 2367, 2074, + 3178, 3244, 2367, 2221, 2553, 2434, 2340, 2314, 2167, 2221, 3338, 3488, 2726, 2194, 2261, 2460, 2354, 2367, 2207, 2101, + 2354, 2420, 2327, 2367, 2394, 2420, 2420, 2420, 2460, 2367, 3779, 3629, 2434, 2527, 2367, 2274, 2274, 2300, 2207, 2048, + 3254, 3225, 2713, 2846, 2447, 2327, 2300, 2300, 2274, 2127, 3263, 3300, 2753, 2806, 2447, 2261, 2261, 2247, 2127, 2101, + 2873, 2981, 2633, 2367, 2407, 2354, 2194, 2247, 2247, 2114, 3225, 3197, 2633, 2580, 2274, 2181, 2247, 2221, 2221, 2141, + 3178, 3310, 2740, 2407, 2274, 2274, 2274, 2287, 2194, 2114, 3141, 3272, 2460, 2061, 2287, 2500, 2367, 2487, 2434, 2181, + 3507, 3282, 2314, 2700, 2647, 2474, 2367, 2394, 2340, 2127, 3423, 3535, 3038, 3056, 2300, 1950, 2221, 2274, 2274, 2274, + 3404, 3366, 2087, 2687, 2873, 2354, 2420, 2274, 2474, 2540, 3760, 3488, 1950, 2660, 2897, 2527, 2394, 2367, 2460, 2261, + 3028, 3272, 2740, 2888, 2740, 2154, 2127, 2287, 2234, 2247, 3695, 3657, 2025, 1969, 2660, 2700, 2580, 2500, 2327, 2367, + 3207, 3413, 2354, 2074, 2888, 2888, 2340, 2487, 2247, 2167, 3338, 3366, 2846, 2780, 2327, 2154, 2274, 2287, 2114, 2061, + 2327, 2300, 2181, 2167, 2181, 2367, 2633, 2700, 2700, 2553, 2407, 2434, 2221, 2261, 2221, 2221, 2340, 2420, 2607, 2700, + 3038, 3244, 2806, 2888, 2474, 2074, 2300, 2314, 2354, 2380, 2221, 2154, 2127, 2287, 2500, 2793, 2793, 2620, 2580, 2367, + 3676, 3713, 2234, 1838, 2181, 2753, 2726, 2673, 2513, 2207, 2793, 3160, 2726, 2553, 2846, 2513, 2181, 2394, 2221, 2181, +} +T.NLSF_CB1_iCDF_NB_MB = { + 212, 178, 148, 129, 108, 96, 85, 82, 79, 77, 61, 59, 57, 56, 51, 49, 48, 45, 42, 41, + 40, 38, 36, 34, 31, 30, 21, 12, 10, 3, 1, 0, 255, 245, 244, 236, 233, 225, 217, 203, + 190, 176, 175, 161, 149, 136, 125, 114, 102, 91, 81, 71, 60, 52, 43, 35, 28, 20, 19, 18, + 12, 11, 5, 0, +} +T.NLSF_CB2_SELECT_NB_MB = { + 16, 0, 0, 0, 0, 99, 66, 36, 36, 34, 36, 34, 34, 34, 34, 83, 69, 36, 52, 34, + 116, 102, 70, 68, 68, 176, 102, 68, 68, 34, 65, 85, 68, 84, 36, 116, 141, 152, 139, 170, + 132, 187, 184, 216, 137, 132, 249, 168, 185, 139, 104, 102, 100, 68, 68, 178, 218, 185, 185, 170, + 244, 216, 187, 187, 170, 244, 187, 187, 219, 138, 103, 155, 184, 185, 137, 116, 183, 155, 152, 136, + 132, 217, 184, 184, 170, 164, 217, 171, 155, 139, 244, 169, 184, 185, 170, 164, 216, 223, 218, 138, + 214, 143, 188, 218, 168, 244, 141, 136, 155, 170, 168, 138, 220, 219, 139, 164, 219, 202, 216, 137, + 168, 186, 246, 185, 139, 116, 185, 219, 185, 138, 100, 100, 134, 100, 102, 34, 68, 68, 100, 68, + 168, 203, 221, 218, 168, 167, 154, 136, 104, 70, 164, 246, 171, 137, 139, 137, 155, 218, 219, 139, +} +T.NLSF_CB2_iCDF_NB_MB = { + 255, 254, 253, 238, 14, 3, 2, 1, 0, 255, 254, 252, 218, 35, 3, 2, 1, 0, 255, 254, + 250, 208, 59, 4, 2, 1, 0, 255, 254, 246, 194, 71, 10, 2, 1, 0, 255, 252, 236, 183, + 82, 8, 2, 1, 0, 255, 252, 235, 180, 90, 17, 2, 1, 0, 255, 248, 224, 171, 97, 30, + 4, 1, 0, 255, 254, 236, 173, 95, 37, 7, 1, 0, +} +T.NLSF_PRED_NB_MB_Q8 = { + 179, 138, 140, 148, 151, 149, 153, 151, 163, 116, 67, 82, 59, 92, 72, 100, 89, 92, +} +T.NLSF_DELTA_MIN_NB_MB_Q15 = { + 250, 3, 6, 3, 3, 3, 4, 3, 3, 3, 461, +} +T.pitch_lag_iCDF = { + 253, 250, 244, 233, 212, 182, 150, 131, 120, 110, 98, 85, 72, 60, 49, 40, 32, 25, 19, 15, + 13, 11, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, +} +T.pitch_delta_iCDF = { + 210, 208, 206, 203, 199, 193, 183, 168, 142, 104, 74, 52, 37, 27, 20, 14, 10, 6, 4, 2, + 0, +} +T.pitch_contour_iCDF = { + 223, 201, 183, 167, 152, 138, 124, 111, 98, 88, 79, 70, 62, 56, 50, 44, 39, 35, 31, 27, + 24, 21, 18, 16, 14, 12, 10, 8, 6, 4, 3, 2, 1, 0, +} +T.pitch_contour_NB_iCDF = { + 188, 176, 155, 138, 119, 97, 67, 43, 26, 10, 0, +} +T.pitch_contour_10_ms_iCDF = { + 165, 119, 80, 61, 47, 35, 27, 20, 14, 9, 4, 0, +} +T.pitch_contour_10_ms_NB_iCDF = { + 113, 63, 0, +} +T.stereo_pred_quant_Q13 = { + -13732, -10050, -8266, -7526, -6500, -5000, -2950, -820, 820, 2950, 5000, 6500, 7526, 8266, 10050, 13732, +} +T.stereo_pred_joint_iCDF = { + 249, 247, 246, 245, 244, 234, 210, 202, 201, 200, 197, 174, 82, 59, 56, 55, 54, 46, 22, 12, + 11, 10, 9, 7, 0, +} +T.stereo_only_code_mid_iCDF = { + 64, 0, +} +T.LBRR_flags_2_iCDF = { + 203, 150, 0, +} +T.LBRR_flags_3_iCDF = { + 215, 195, 166, 125, 110, 82, 0, +} +T.lsb_iCDF = { + 120, 0, +} +T.LTPscale_iCDF = { + 128, 64, 0, +} +T.type_offset_VAD_iCDF = { + 232, 158, 10, 0, +} +T.type_offset_no_VAD_iCDF = { + 230, 0, +} +T.NLSF_interpolation_factor_iCDF = { + 243, 221, 192, 181, 0, +} +T.LTPScales_table_Q14 = { + 15565, 12288, 8192, +} +T.uniform3_iCDF = { + 171, 85, 0, +} +T.uniform4_iCDF = { + 192, 128, 64, 0, +} +T.uniform5_iCDF = { + 205, 154, 102, 51, 0, +} +T.uniform6_iCDF = { + 213, 171, 128, 85, 43, 0, +} +T.uniform8_iCDF = { + 224, 192, 160, 128, 96, 64, 32, 0, +} +T.NLSF_EXT_iCDF = { + 100, 40, 16, 7, 3, 1, 0, +} +T.gain_iCDF = { + 224, 112, 44, 15, 3, 2, 1, 0, 254, 237, 192, 132, 70, 23, 4, 0, 255, 252, 226, 155, + 61, 11, 2, 0, +} +T.delta_gain_iCDF = { + 250, 245, 234, 203, 71, 50, 42, 38, 35, 33, 31, 29, 28, 27, 26, 25, 24, 23, 22, 21, + 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, + 0, +} +T.LSFCosTab_FIX_Q12 = { + 8192, 8190, 8182, 8170, 8152, 8130, 8104, 8072, 8034, 7994, 7946, 7896, 7840, 7778, 7714, 7644, 7568, 7490, 7406, 7318, + 7226, 7128, 7026, 6922, 6812, 6698, 6580, 6458, 6332, 6204, 6070, 5934, 5792, 5648, 5502, 5352, 5198, 5040, 4880, 4718, + 4552, 4382, 4212, 4038, 3862, 3684, 3502, 3320, 3136, 2948, 2760, 2570, 2378, 2186, 1990, 1794, 1598, 1400, 1202, 1002, + 802, 602, 402, 202, 0, -202, -402, -602, -802, -1002, -1202, -1400, -1598, -1794, -1990, -2186, -2378, -2570, -2760, -2948, + -3136, -3320, -3502, -3684, -3862, -4038, -4212, -4382, -4552, -4718, -4880, -5040, -5198, -5352, -5502, -5648, -5792, -5934, -6070, -6204, + -6332, -6458, -6580, -6698, -6812, -6922, -7026, -7128, -7226, -7318, -7406, -7490, -7568, -7644, -7714, -7778, -7840, -7896, -7946, -7994, + -8034, -8072, -8104, -8130, -8152, -8170, -8182, -8190, -8192, +} +T.pulses_per_block_iCDF = { + 125, 51, 26, 18, 15, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 198, 105, + 45, 22, 15, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 213, 162, 116, 83, + 59, 43, 32, 24, 18, 15, 12, 9, 7, 6, 5, 3, 2, 0, 239, 187, 116, 59, 28, 16, + 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 250, 229, 188, 135, 86, 51, 30, 19, + 13, 10, 8, 6, 5, 4, 3, 2, 1, 0, 249, 235, 213, 185, 156, 128, 103, 83, 66, 53, + 42, 33, 26, 21, 17, 13, 10, 0, 254, 249, 235, 206, 164, 118, 77, 46, 27, 16, 10, 7, + 5, 4, 3, 2, 1, 0, 255, 253, 249, 239, 220, 191, 156, 119, 85, 57, 37, 23, 15, 10, + 6, 4, 2, 0, 255, 253, 251, 246, 237, 223, 203, 179, 152, 124, 98, 75, 55, 40, 29, 21, + 15, 0, 255, 254, 253, 247, 220, 162, 106, 67, 42, 28, 18, 12, 9, 6, 4, 3, 2, 0, +} +T.rate_levels_iCDF = { + 241, 190, 178, 132, 87, 74, 41, 14, 0, 223, 193, 157, 140, 106, 57, 39, 18, 0, +} +T.shell_code_table0 = { + 128, 0, 214, 42, 0, 235, 128, 21, 0, 244, 184, 72, 11, 0, 248, 214, 128, 42, 7, 0, + 248, 225, 170, 80, 25, 5, 0, 251, 236, 198, 126, 54, 18, 3, 0, 250, 238, 211, 159, 82, + 35, 15, 5, 0, 250, 231, 203, 168, 128, 88, 53, 25, 6, 0, 252, 238, 216, 185, 148, 108, + 71, 40, 18, 4, 0, 253, 243, 225, 199, 166, 128, 90, 57, 31, 13, 3, 0, 254, 246, 233, + 212, 183, 147, 109, 73, 44, 23, 10, 2, 0, 255, 250, 240, 223, 198, 166, 128, 90, 58, 33, + 16, 6, 1, 0, 255, 251, 244, 231, 210, 181, 146, 110, 75, 46, 25, 12, 5, 1, 0, 255, + 253, 248, 238, 221, 196, 164, 128, 92, 60, 35, 18, 8, 3, 1, 0, 255, 253, 249, 242, 229, + 208, 180, 146, 110, 76, 48, 27, 14, 7, 3, 1, 0, +} +T.shell_code_table1 = { + 129, 0, 207, 50, 0, 236, 129, 20, 0, 245, 185, 72, 10, 0, 249, 213, 129, 42, 6, 0, + 250, 226, 169, 87, 27, 4, 0, 251, 233, 194, 130, 62, 20, 4, 0, 250, 236, 207, 160, 99, + 47, 17, 3, 0, 255, 240, 217, 182, 131, 81, 41, 11, 1, 0, 255, 254, 233, 201, 159, 107, + 61, 20, 2, 1, 0, 255, 249, 233, 206, 170, 128, 86, 50, 23, 7, 1, 0, 255, 250, 238, + 217, 186, 148, 108, 70, 39, 18, 6, 1, 0, 255, 252, 243, 226, 200, 166, 128, 90, 56, 30, + 13, 4, 1, 0, 255, 252, 245, 231, 209, 180, 146, 110, 76, 47, 25, 11, 4, 1, 0, 255, + 253, 248, 237, 219, 194, 163, 128, 93, 62, 37, 19, 8, 3, 1, 0, 255, 254, 250, 241, 226, + 205, 177, 145, 111, 79, 51, 30, 15, 6, 2, 1, 0, +} +T.shell_code_table2 = { + 129, 0, 203, 54, 0, 234, 129, 23, 0, 245, 184, 73, 10, 0, 250, 215, 129, 41, 5, 0, + 252, 232, 173, 86, 24, 3, 0, 253, 240, 200, 129, 56, 15, 2, 0, 253, 244, 217, 164, 94, + 38, 10, 1, 0, 253, 245, 226, 189, 132, 71, 27, 7, 1, 0, 253, 246, 231, 203, 159, 105, + 56, 23, 6, 1, 0, 255, 248, 235, 213, 179, 133, 85, 47, 19, 5, 1, 0, 255, 254, 243, + 221, 194, 159, 117, 70, 37, 12, 2, 1, 0, 255, 254, 248, 234, 208, 171, 128, 85, 48, 22, + 8, 2, 1, 0, 255, 254, 250, 240, 220, 189, 149, 107, 67, 36, 16, 6, 2, 1, 0, 255, + 254, 251, 243, 227, 201, 166, 128, 90, 55, 29, 13, 5, 2, 1, 0, 255, 254, 252, 246, 234, + 213, 183, 147, 109, 73, 43, 22, 10, 4, 2, 1, 0, +} +T.shell_code_table3 = { + 130, 0, 200, 58, 0, 231, 130, 26, 0, 244, 184, 76, 12, 0, 249, 214, 130, 43, 6, 0, + 252, 232, 173, 87, 24, 3, 0, 253, 241, 203, 131, 56, 14, 2, 0, 254, 246, 221, 167, 94, + 35, 8, 1, 0, 254, 249, 232, 193, 130, 65, 23, 5, 1, 0, 255, 251, 239, 211, 162, 99, + 45, 15, 4, 1, 0, 255, 251, 243, 223, 186, 131, 74, 33, 11, 3, 1, 0, 255, 252, 245, + 230, 202, 158, 105, 57, 24, 8, 2, 1, 0, 255, 253, 247, 235, 214, 179, 132, 84, 44, 19, + 7, 2, 1, 0, 255, 254, 250, 240, 223, 196, 159, 112, 69, 36, 15, 6, 2, 1, 0, 255, + 254, 253, 245, 231, 209, 176, 136, 93, 55, 27, 11, 3, 2, 1, 0, 255, 254, 253, 252, 239, + 221, 194, 158, 117, 76, 42, 18, 4, 3, 2, 1, 0, +} +T.shell_code_table_offsets = { + 0, 0, 2, 5, 9, 14, 20, 27, 35, 44, 54, 65, 77, 90, 104, 119, 135, +} +T.sign_iCDF = { + 254, 49, 67, 77, 82, 93, 99, 198, 11, 18, 24, 31, 36, 45, 255, 46, 66, 78, 87, 94, + 104, 208, 14, 21, 32, 42, 51, 66, 255, 94, 104, 109, 112, 115, 118, 248, 53, 69, 80, 88, + 95, 102, +} +T.CB_lags_stage2_10_ms = { + 0, 1, 0, 0, 0, 1, +} +T.CB_lags_stage3_10_ms = { + 0, 0, 1, -1, 1, -1, 2, -2, 2, -2, 3, -3, 0, 1, 0, 1, -1, 2, -1, 2, + -2, 3, -2, 3, +} +T.CB_lags_stage2 = { + 0, 2, -1, -1, -1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, + 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, -1, 2, 1, 0, 1, 1, + 0, 0, -1, -1, +} +T.CB_lags_stage3 = { + 0, 0, 1, -1, 0, 1, -1, 0, -1, 1, -2, 2, -2, -2, 2, -3, 2, 3, -3, -4, + 3, -4, 4, 4, -5, 5, -6, -5, 6, -7, 6, 5, 8, -9, 0, 0, 1, 0, 0, 0, + 0, 0, 0, 0, -1, 1, 0, 0, 1, -1, 0, 1, -1, -1, 1, -1, 2, 1, -1, 2, + -2, -2, 2, -2, 2, 2, 3, -3, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, + 0, 1, -1, 1, 0, 0, 2, 1, -1, 2, -1, -1, 2, -1, 2, 2, -1, 3, -2, -2, + -2, 3, 0, 1, 0, 0, 1, 0, 1, -1, 2, -1, 2, -1, 2, 3, -2, 3, -2, -2, + 4, 4, -3, 5, -3, -4, 6, -4, 6, 5, -5, 8, -6, -5, -7, 9, +} +T.resampler_frac_FIR_12 = { + 189, -600, 617, 30567, 117, -159, -1070, 29704, 52, 221, -2392, 28276, -4, 529, -3350, 26341, -48, 758, -3956, 23973, + -80, 905, -4235, 21254, -99, 972, -4222, 18278, -107, 967, -3957, 15143, -103, 896, -3487, 11950, -91, 773, -2865, 8798, + -71, 611, -2143, 5784, -46, 425, -1375, 2996, +} +return T diff --git a/src/Formats/audio/opus/init.luau b/src/Formats/audio/opus/init.luau new file mode 100644 index 0000000..08852eb --- /dev/null +++ b/src/Formats/audio/opus/init.luau @@ -0,0 +1,408 @@ +--!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. +-- Not supported: encoding, 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 + +-- ------------------------------------------------------------------------------------------------ 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") + +-- ------------------------------------------------------------------------------------------------ contract +local Opus = { + name = "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 } }, +} + +-- ------------------------------------------------------------------------------------------------ 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 + +-- ------------------------------------------------------------------------------------------------ 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 diff --git a/tests/audio/opus.luau b/tests/audio/opus.luau new file mode 100644 index 0000000..c876dce --- /dev/null +++ b/tests/audio/opus.luau @@ -0,0 +1,445 @@ +-- audio/opus tests: every fixture (opusenc / ffmpeg libopus: CELT frame sizes and bitrates, SILK NB / MB / WB, hybrid, +-- mode transitions, 5.1 multistream, a long tagged file) through open / read against opusdec --float (frame counts, +-- SNR per fixture), CELT-only and SILK-only decoding with the private decoders alone, SILK packet loss concealment, +-- tags, seeking, the stereo downmix, decode() to an Audio, the contract, sniff, error codes, random / bit-flipped +-- packets through the packet decoder, and the fuzz no-throw pass over whole files. +-- Ported from opus-luau tests/opus.luau, celt.luau, silk.luau, fuzz.luau. Fixtures: tools/fixtures/opus.py. +local T = require("@tests/T") +local Opus = require("@formats/audio/opus") +local Packet = require("@formats/audio/opus/Packet") +local Celt = require("@formats/audio/opus/Celt") +local Silk = require("@formats/audio/opus/Silk") +local RD = require("@formats/audio/opus/RangeDecoder") +local Decoder = require("@formats/audio/opus/Decoder") +local Ogg = require("@formats/containers/Ogg") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") + +local t = T.suite("opus") + +local FX: { [string]: any } = {} +for _, f in + { + require("@tests/gen/opus_celt_st_128"), + require("@tests/gen/opus_celt_st_32"), + require("@tests/gen/opus_celt_st_64"), + require("@tests/gen/opus_celt_st_256"), + require("@tests/gen/opus_celt_mono_64"), + require("@tests/gen/opus_celt_fs2_5"), + require("@tests/gen/opus_celt_fs5"), + require("@tests/gen/opus_celt_fs10"), + require("@tests/gen/opus_celt_fs40"), + require("@tests/gen/opus_celt_fs60"), + require("@tests/gen/opus_silk_nb"), + require("@tests/gen/opus_silk_mb"), + require("@tests/gen/opus_silk_wb"), + require("@tests/gen/opus_silk_wb_st"), + require("@tests/gen/opus_silk_nb_st"), + require("@tests/gen/opus_hybrid_swb"), + require("@tests/gen/opus_hybrid_fb"), + require("@tests/gen/opus_hybrid_st"), + require("@tests/gen/opus_mix_st_24"), + require("@tests/gen/opus_surround51"), + require("@tests/gen/opus_long_128"), + require("@tests/gen/opus_ff_cbr"), + require("@tests/gen/opus_ff_voip"), + require("@tests/gen/opus_ff_lowdelay"), + } +do + FX[f.name] = { data = buffer.fromstring(f.data), ref = buffer.fromstring(f.ref), raw = f.data } +end + +-- SNR in dB of f32 samples against a reference over n samples; returns snr, max abs error +local function snr(out: buffer, ref: buffer, n: number, outOff: number?, refOff: number?): (number, number) + local oo, ro = outOff or 0, refOff or 0 + local sig, err, maxe = 0, 0, 0 + for i = 0, n - 1 do + local r = buffer.readf32(ref, ro + i * 4) + local e = buffer.readf32(out, oo + i * 4) - r + sig += r * r + err += e * e + if math.abs(e) > maxe then + maxe = math.abs(e) + end + end + if err == 0 then + return 999, 0 + end + return 10 * math.log10(sig / err), maxe +end + +-- the packets of the first stream: { data, offset, size } +local function packets(buf: buffer): { any } + local d = Ogg.open(buf) + local out = {} + for p in d:packets(d:streams()[1].serial) do + table.insert(out, p) + end + return out +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: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") + +-- ------------------------------------------------------------------------------------------------ open / read vs opusdec +-- name, minimum SNR (dB). CELT is float-exact (> 130 dB in practice), SILK bit-exact; hybrid / transitions mix both. +local cases = { + { "celt_st_128", 100 }, { "celt_st_32", 100 }, { "celt_st_64", 100 }, { "celt_st_256", 100 }, + { "celt_mono_64", 100 }, { "celt_fs2_5", 100 }, { "celt_fs5", 100 }, { "celt_fs10", 100 }, + { "celt_fs40", 100 }, { "celt_fs60", 100 }, { "ff_cbr", 100 }, { "ff_lowdelay", 100 }, + { "silk_nb", 90 }, { "silk_nb_st", 90 }, { "silk_mb", 90 }, { "silk_wb", 90 }, { "silk_wb_st", 90 }, + { "hybrid_swb", 60 }, { "hybrid_fb", 60 }, { "hybrid_st", 60 }, { "mix_st_24", 60 }, { "ff_voip", 60 }, + { "surround51", 100 }, { "long_128", 100 }, +} +for _, case in cases do + local name, minSnr = case[1], case[2] + local fx = FX[name] + local dec, err = Opus.open(Bytes.reader(fx.data)) + t:check(dec, name .. ": open: " .. tostring(err)) + local ch = dec.channels + local refFrames = buffer.len(fx.ref) // 4 // ch + t:eq(dec.frames, refFrames, name .. ": frames") + t:check(dec.sampleRate == 48000 and type(dec.duration) == "number" and type(dec.bitrate) == "number" and type(dec.tags) == "table", name .. ": Decoder fields") + local out = buffer.create(dec.frames * ch * 4 + 4096) + local total = 0 + local t0 = os.clock() + while true do + local pcm, n = dec:read(1000 + total % 3001) + if n == 0 then + break + end + t:eq(buffer.len(pcm), n * ch * 4, name .. ": read buffer size") + buffer.copy(out, total * ch * 4, pcm, 0, n * ch * 4) + total += n + end + local dt = os.clock() - t0 + t:eq(total, refFrames, name .. ": decoded frames") + local db, maxe = snr(out, fx.ref, refFrames * ch) + t:note("%-12s %d ch %7d frames SNR %6.1f dB max err %.2g %.0fx real time", name, ch, total, db, maxe, dec.duration / math.max(dt, 1e-6)) + t:check(db >= minSnr, string.format("%s: SNR %.1f >= %d dB", name, db, minSnr)) + t:check(math.abs(dec:position() - dec.duration) < 1e-9, name .. ": position at end") +end + +-- read into a caller buffer, decode() to an Audio, a sub-range Reader +do + local fx = FX.hybrid_st + local dec = Opus.open(Bytes.reader(fx.data)) + local into = buffer.create(4096 * 2 * 4) + local pcm, n = dec:read(4096, into) + t:check(pcm == into and n == 4096, "read(n, out) reuses out") + local big = buffer.create(buffer.len(fx.data) + 33) + buffer.copy(big, 17, fx.data) + local a, err = Opus.decode(Bytes.reader(big, 17, buffer.len(fx.data))) + t:check(a, "decode from a sub-range: " .. tostring(err)) + t:check(a.kind == "audio" and a.sampleRate == 48000 and a.channels == 2, "decode: an Audio") + t:eq(a.frames, buffer.len(fx.ref) // 8, "decode: frames") + t:check(snr(a.samples, fx.ref, a.frames * 2) >= 60, "decode: samples") + t:eq(a.meta.source.format, "opus", "decode: meta.source") +end + +-- ------------------------------------------------------------------------------------------------ tags, seeking +do + local dec = Opus.open(Bytes.reader(FX.long_128.data)) + t:eq(dec.tags.title, "Long Test", "tags: title") + t:eq(dec.tags.artist, "opus-luau", "tags: artist") + t:check(dec.sampleRate == 48000 and dec.channels == 2, "info") + t:check(math.abs(dec.duration - 12) < 0.01, "duration ~12 s") + t:check(dec.bitrate > 100000 and dec.bitrate < 200000, "bitrate ~128 kbps: " .. dec.bitrate) + -- 80 ms pre-roll makes the decoder state converge after a seek + local ref = FX.long_128.ref + for _, s in { 0, 0.001, 1.5, 3.21, 6.0, 9.99, 11.7, 2.0, 0.05 } do + dec:seek(s) + local p = math.floor(s * 48000 + 0.5) + t:check(math.abs(dec:position() - p / 48000) < 1e-9, string.format("seek %.3f: position", s)) + local pcm, n = dec:read(12000) + t:eq(n, math.min(12000, dec.frames - p), string.format("seek %.3f: read", s)) + local db = snr(pcm, ref, n * 2, 0, p * 2 * 4) + t:check(db > 50, string.format("seek %.3f: SNR %.1f > 50 dB", s, db)) + end + dec:seek(100) + local _, n = dec:read(100) + t:eq(n, 0, "seek past the end reads nothing") + dec:seek(0) + local _, n2 = dec:read(100) + t:eq(n2, 100, "seek back to 0") + dec:seek(0 / 0) + t:eq(dec:position(), 0, "seek(nan) goes to 0") +end + +-- stereo downmix of the 5.1 file: the same matrix applied to the reference +do + local fx = FX.surround51 + local dec = Opus.open(Bytes.reader(fx.data), { stereo = true }) + t:check(dec.channels == 2 and dec.sourceChannels == 6, "downmix: 2 output channels") + local pcm, n = dec:read(dec.frames) + t:eq(n, dec.frames, "downmix: all frames") + local m = { 0.529, 0, 0.3741, 0.3741, 0, 0.529, 0.4582, 0.2645, 0.2645, 0.4582, 0.3741, 0.3741 } + local exp = buffer.create(n * 8) + for i = 0, n - 1 do + local l, r = 0, 0 + for c = 0, 5 do + local v = buffer.readf32(fx.ref, (i * 6 + c) * 4) + l += v * m[c * 2 + 1] + r += v * m[c * 2 + 2] + end + buffer.writef32(exp, i * 8, l) + buffer.writef32(exp, i * 8 + 4, r) + end + local db = snr(pcm, exp, n * 2) + t:check(db > 100, string.format("downmix SNR %.1f", db)) +end + +-- ------------------------------------------------------------------------------------------------ CELT alone +do + local endbands = { [Packet.BW_NB] = 13, [Packet.BW_MB] = 17, [Packet.BW_WB] = 17, [Packet.BW_SWB] = 19, [Packet.BW_FB] = 21 } + for _, name in { "celt_st_128", "celt_st_32", "celt_st_64", "celt_st_256", "celt_mono_64", "celt_fs2_5", "celt_fs5", "celt_fs10", "celt_fs40", "celt_fs60", "ff_cbr", "ff_lowdelay" } do + local fx = FX[name] + local pk = packets(fx.data) + local head = pk[1] + local channels = buffer.readu8(head.data, head.offset + 9) + local preskip = buffer.readu16(head.data, head.offset + 10) + local st = Celt.new(channels) + local out = {} + local total = 0 + local offs, sizes = {}, {} + local allOk = true + for p = 3, #pk do + local P = pk[p] + local count, toc = Packet.parse(P.data, P.offset, P.size, offs, sizes) + allOk = allOk and count > 0 and Packet.mode(toc) == Packet.MODE_CELT_ONLY + local fs48 = Packet.samplesPerFrame(toc, 48000) + st["end"] = endbands[Packet.bandwidth(toc)] + st.stream_channels = Packet.channels(toc) + for f = 1, count do + local ret = Celt.decode(st, P.data, offs[f], sizes[f], out, 1 + total * channels, fs48, nil, false) + allOk = allOk and ret == fs48 + total += fs48 + end + end + t:check(allOk, name .. ": every packet is CELT-only and decodes") + local refFrames = buffer.len(fx.ref) // 4 // channels + t:check(total - preskip >= refFrames and total - preskip - refFrames < 960 * 3, name .. ": CELT sample count") + local n = refFrames * channels + local ob = buffer.create(n * 4) + for i = 0, n - 1 do + buffer.writef32(ob, i * 4, out[preskip * channels + i + 1]) + end + local db = snr(ob, fx.ref, n) + t:check(db > 60, string.format("%s: CELT alone SNR %.1f > 60 dB", name, db)) + end +end + +-- ------------------------------------------------------------------------------------------------ SILK alone +do + local rates = { [Packet.BW_NB] = 8000, [Packet.BW_MB] = 12000, [Packet.BW_WB] = 16000 } + local function decodeSilk(name: string, hybridOk: boolean?, lose: boolean?): ({ number }, number, number, number) + local pk = packets(FX[name].data) + local channels = buffer.readu8(pk[1].data, pk[1].offset + 9) + local preskip = buffer.readu16(pk[1].data, pk[1].offset + 10) + local st = Silk.new(channels) + local out = {} + local total = 0 + local offs, sizes = {}, {} + local allOk = true + for p = 3, #pk do + local P = pk[p] + local count, toc = Packet.parse(P.data, P.offset, P.size, offs, sizes) + local mode = Packet.mode(toc) + allOk = allOk and count > 0 and (mode == Packet.MODE_SILK_ONLY or (hybridOk == true and mode == Packet.MODE_HYBRID)) + local fs48 = Packet.samplesPerFrame(toc, 48000) + local lostPacket = lose and p % 7 == 0 and p < #pk - 80 + local ctrl = { + nChannelsAPI = channels, + nChannelsInternal = Packet.channels(toc), + API_sampleRate = 48000, + internalSampleRate = if mode == Packet.MODE_HYBRID then 16000 else rates[Packet.bandwidth(toc)], + payloadSize_ms = math.max(10, fs48 // 48), + } + for f = 1, count do + local lost = if lostPacket or sizes[f] <= 1 then 1 else 0 + local ec = RD.new(P.data, offs[f], sizes[f]) + local decoded = 0 + repeat + local ret, n = Silk.decode(st, ctrl, lost, decoded == 0, ec, out, 1 + (total + decoded) * channels) + allOk = allOk and ret == 0 + decoded += n + until decoded >= fs48 or n <= 0 + total += decoded + end + end + t:check(allOk, name .. ": every packet is SILK and decodes") + return out, total, channels, preskip + end + for _, name in { "silk_nb", "silk_nb_st", "silk_mb", "silk_wb", "silk_wb_st" } do + local out, total, channels, preskip = decodeSilk(name) + local ref = FX[name].ref + local refFrames = buffer.len(ref) // 4 // channels + t:check(total - preskip >= refFrames and total - preskip - refFrames < 960 * 3, name .. ": SILK sample count") + local n = refFrames * channels + local ob = buffer.create(n * 4) + for i = 0, n - 1 do + buffer.writef32(ob, i * 4, out[preskip * channels + i + 1]) + end + local db = snr(ob, ref, n) + t:check(db > 90, string.format("%s: SILK alone SNR %.1f > 90 dB", name, db)) + end + local _, total = decodeSilk("hybrid_swb", true) + t:check(total > 0, "hybrid_swb: SILK layer decodes") + -- packet loss concealment: every 7th packet lost; output bounded, the last second matches again + for _, name in { "silk_nb", "silk_wb_st" } do + local out, tot, channels, preskip = decodeSilk(name, false, true) + local finite = true + for i = 1, tot * channels do + local v = out[i] + if v ~= v or math.abs(v) > 1 then + finite = false + end + end + t:check(finite, name .. ": PLC output bounded") + local ref = FX[name].ref + local refFrames = buffer.len(ref) // 4 // channels + local n = 48000 * channels + local from = (refFrames - 48000) * channels + local ob = buffer.create(n * 4) + for i = 0, n - 1 do + buffer.writef32(ob, i * 4, out[preskip * channels + from + i + 1]) + end + local db = snr(ob, ref, n, 0, from * 4) + t:check(db > 15, string.format("%s: recovers after losses (last second SNR %.1f)", name, db)) + end +end + +-- ------------------------------------------------------------------------------------------------ errors +do + local d, err = Opus.open(Bytes.reader(buffer.fromstring("not an ogg file at all"))) + t:check(d == nil and err and err.code == Err.CORRUPT, "garbage is CORRUPT: " .. tostring(err)) + local _, e2 = Opus.open(Bytes.reader(FX.celt_st_128.data, 0, 40)) + t:check(e2 and Err.is(e2), "a cut header is an Err: " .. tostring(e2)) + local _, e3 = Opus.decode(Bytes.reader(buffer.create(0))) + t:check(e3 and Err.is(e3), "empty decode is an Err") + -- a truncated file opens and decodes its first half + local file = FX.hybrid_st.data + local cut = buffer.create(buffer.len(file) // 2) + buffer.copy(cut, 0, file, 0, buffer.len(cut)) + local dec = Opus.open(Bytes.reader(cut)) + t:check(dec, "truncated file opens") + local total = 0 + while true do + local _, n = dec:read(4096) + if n == 0 then + break + end + total += n + end + t:check(total > 0, "truncated file decodes its first half") + local a = Opus.decode(Bytes.reader(cut)) + t:check(a and a.frames == total, "decode of a truncated file keeps what decoded") + -- damaged packets (CRC checks off, so they reach the decoder) never throw + for _, name in { "celt_st_128", "hybrid_st", "silk_wb_st", "surround51" } do + local g = buffer.create(buffer.len(FX[name].data)) + buffer.copy(g, 0, FX[name].data) + local seed = 12345 + for i = 400, buffer.len(g) - 1, 97 do + seed = (seed * 1103515245 + 12345) % 2147483648 + buffer.writeu8(g, i, bit32.bxor(buffer.readu8(g, i), seed % 256)) + end + local dd = Opus.open(Bytes.reader(g), { verify = false }) + t:check(dd, name .. ": damaged file opens") + local ok, e = pcall(function() + while true do + local _, n = dd:read(4096) + if n == 0 then + break + end + end + end) + t:check(ok, name .. ": damaged data decodes without error: " .. tostring(e)) + end +end + +-- ------------------------------------------------------------------------------------------------ packet fuzz +-- random packets (every TOC config, random payloads) and bit-flipped real packets: never throw, output finite +do + local rand = T.rng(987654321) + local pcm = table.create(5760 * 2, 0) + local decoded, rejected, bad = 0, 0, 0 + local function run(dec: any, b: buffer, len: number) + local ok, n = pcall(Decoder.decode, dec, b, 0, len, pcm, 1, 5760) + if not ok then + bad += 1 + return + end + if n > 0 then + decoded += 1 + for i = 1, n * dec.channels do + local v = pcm[i] + if v ~= v or v == math.huge or v == -math.huge then + bad += 1 + break + end + end + else + rejected += 1 + end + end + for _, ch in { 1, 2 } do + local dec = Decoder.new(ch) + for i = 1, 1500 do + local len = 1 + rand(if rand(4) == 0 then 1275 else 120) + local b = buffer.create(len) + for k = 0, len - 1 do + buffer.writeu8(b, k, rand(256)) + end + buffer.writeu8(b, 0, (i * 7 + ch) % 256) -- cycle through every TOC + run(dec, b, len) + if rand(50) == 0 then + Decoder.decode(dec, nil, 0, 0, pcm, 1, 960) -- concealment in between + end + end + end + for _, name in { "celt_st_128", "hybrid_st", "silk_wb_st", "mix_st_24", "celt_fs2_5" } do + local pk = packets(FX[name].data) + local dec = Decoder.new(2) + for p = 3, #pk do + local P = pk[p] + local b = buffer.create(P.size) + buffer.copy(b, 0, P.data, P.offset, P.size) + for _ = 1, 1 + rand(4) do + local k = 1 + rand(math.max(1, P.size - 1)) + if k < P.size then + buffer.writeu8(b, k, bit32.bxor(buffer.readu8(b, k), bit32.lshift(1, rand(8)))) + end + end + run(dec, b, P.size) + end + end + t:eq(bad, 0, "packet fuzz: no throws, finite output") + t:note("packet fuzz: %d packets decoded, %d rejected", decoded, rejected) +end + +-- ------------------------------------------------------------------------------------------------ fuzz (whole files) +do + local samples = {} + for _, name in { "hybrid_fb", "silk_nb", "celt_fs5" } do + table.insert(samples, string.sub(FX[name].raw, 1, 6000)) + end + t:fuzz("open + read", function(b: buffer) + local dec = Opus.open(Bytes.reader(b), { verify = false }) + if dec then + dec:read(2000) + dec:seek(0.01) + dec:read(500) + end + return dec + end, samples, { mutations = 12, keepHeader = 4 }) + t:fuzz("decode", function(b: buffer) + return Opus.decode(Bytes.reader(b)) + end, samples, { mutations = 4, garbage = 50 }) +end + +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index 9f6aef7..74af2d5 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -1,11 +1,16 @@ -- Throughput (bash tools/bench.sh): codec MB/s under both runtimes. MB/s are of decompressed output, best of n runs. --- Fixtures: tools/fixtures/deflate.py (a 6 MB corpus) and tools/fixtures/png.py (1024 x 768 images). +-- Fixtures: tools/fixtures/deflate.py (a 6 MB corpus), tools/fixtures/png.py (1024 x 768 images), tools/fixtures/opus.py +-- (3 s stereo files; MB/s of f32 output, 48 kHz stereo f32 is 0.384 MB/s of real time). local Deflate = require("@formats/codecs/Deflate") local Crc32 = require("@formats/core/Crc32") local Bytes = require("@formats/core/Bytes") local Png = require("@formats/image/png") local B = require("@tests/gen/deflate_bench") local PB = require("@tests/gen/png_bench") +local Opus = require("@formats/audio/opus") +local OpusCelt = require("@tests/gen/opus_celt_st_128") +local OpusSilk = require("@tests/gen/opus_silk_wb_st") +local OpusHybrid = require("@tests/gen/opus_hybrid_st") local runtime = if (_G :: any).jit ~= nil then "luajit" else "luau" @@ -56,3 +61,9 @@ do Png.encode(img) end) end +for _, c in { { "celt 128k", OpusCelt }, { "silk wb", OpusSilk }, { "hybrid", OpusHybrid } } do + local b = buffer.fromstring(c[2].data) + bench("opus decode " .. c[1] .. " (3 s st)", 3, #c[2].ref, function() + Opus.decode(Bytes.reader(b)) + end) +end diff --git a/tools/bench.sh b/tools/bench.sh index c5dea4a..26508ca 100644 --- a/tools/bench.sh +++ b/tools/bench.sh @@ -3,7 +3,7 @@ cd "$(dirname "$0")/.." || exit 1 LUAU=${LUAU:-$(command -v luau || nix shell nixpkgs#luau -c sh -c 'command -v luau')} LUAJIT=${LUAJIT:-$(command -v luajit || nix shell nixpkgs#luajit -c sh -c 'command -v luajit')} -python3 -I tools/fixtures.py deflate png > /dev/null || exit 1 +python3 -I tools/fixtures.py deflate png opus > /dev/null || exit 1 python3 -I tools/build.py luajit > /dev/null || exit 1 "$LUAU" --codegen -O2 tools/bench.luau "$LUAJIT" -e 'package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path' build/luajit/tools/bench.lua diff --git a/tools/fixtures/opus.py b/tools/fixtures/opus.py new file mode 100644 index 0000000..a442852 --- /dev/null +++ b/tools/fixtures/opus.py @@ -0,0 +1,66 @@ +# Opus fixtures (tools/fixtures.py): audio/opus. Ported from opus-luau tools/fixtures.sh. +# tests/gen/opus_.luau { name, data = the .opus file, ref = opusdec --float output (f32 LE interleaved) } +# Sources: 48 kHz signals synthesised by ffmpeg (aevalsrc: tones, vibrato, chirps, noise bursts, clicks, a speech-like +# harmonic source with moving formants), encoded by opusenc (CELT-only frame sizes / bitrates, forced SILK NB / MB / +# WB, hybrid SWB / FB, a 5.1 mapping-family-1 stream, a long tagged file) and ffmpeg libopus (CBR, voip, lowdelay). +import os, tempfile + +MUSIC = ("0.25*sin(2*PI*(220+30*sin(2*PI*5*t))*t)+0.15*sin(2*PI*(100*t+700*t*t))+0.3*exp(-25*mod(t,0.375))*(random(0)-0.5)" + "+0.4*lt(mod(t,0.5),0.0006)") +MUSIC2 = ("0.2*sin(2*PI*330*t)+0.1*sin(2*PI*1320*t)*lt(mod(t,0.25),0.125)+0.25*exp(-40*mod(t+0.1,0.375))*(random(1)-0.5)" + "+0.12*sin(2*PI*(3000-2500*t/3)*t)") +F0 = "(120+40*sin(2*PI*0.7*t))" +FM = "(600+300*sin(2*PI*1.3*t))" +SPEECH = ("(0.5+0.5*sin(2*PI*2.1*t))*(sin(2*PI*{f0}*t)*0.3+sin(2*PI*2*{f0}*t)*0.25+sin(2*PI*3*{f0}*t)*0.2*exp(-abs(3*{f0}-{fm})/400)" + "+sin(2*PI*5*{f0}*t)*0.15*exp(-abs(5*{f0}-{fm}*2)/400)+sin(2*PI*8*{f0}*t)*0.08+0.02*(random(2)-0.5))").format(f0=F0, fm=FM) +SOURCES = { + "music": (MUSIC + "|" + MUSIC2, 3), + "mono": (MUSIC + "+0.5*" + SPEECH, 3), + "speech": (SPEECH, 3), + "speechst": (SPEECH + "|0.7*" + SPEECH + "+0.1*sin(2*PI*440*t)", 3), + "mixst": (MUSIC + "+" + SPEECH + "|" + MUSIC2 + "+0.6*" + SPEECH, 3), + "surround": (MUSIC + "|" + MUSIC2 + "|" + SPEECH + "|0.3*sin(2*PI*55*t)|0.5*" + MUSIC2 + "|0.5*" + MUSIC, 2), + "long": (MUSIC + "+0.3*" + SPEECH + "|" + MUSIC2 + "+0.3*" + SPEECH, 12), +} +# name, source, encoder ("enc" = opusenc, "ff" = ffmpeg libopus), arguments +CASES = [ + ("celt_st_128", "music", "enc", ["--music", "--bitrate", "128"]), + ("celt_st_32", "music", "enc", ["--music", "--bitrate", "32"]), + ("celt_st_64", "mixst", "enc", ["--music", "--bitrate", "64"]), + ("celt_st_256", "music", "enc", ["--music", "--bitrate", "256"]), + ("celt_mono_64", "mono", "enc", ["--music", "--bitrate", "64"]), + ("celt_fs2_5", "music", "enc", ["--music", "--bitrate", "96", "--framesize", "2.5"]), + ("celt_fs5", "music", "enc", ["--music", "--bitrate", "96", "--framesize", "5"]), + ("celt_fs10", "mixst", "enc", ["--music", "--bitrate", "96", "--framesize", "10"]), + ("celt_fs40", "music", "enc", ["--music", "--bitrate", "96", "--framesize", "40"]), + ("celt_fs60", "mixst", "enc", ["--music", "--bitrate", "160", "--framesize", "60"]), + ("silk_nb", "speech", "enc", ["--speech", "--bitrate", "8", "--max-delay", "0"]), + ("silk_mb", "speech", "enc", ["--speech", "--bitrate", "12", "--set-ctl-int", "4008=1102"]), + ("silk_wb", "speech", "enc", ["--speech", "--bitrate", "20", "--framesize", "40", "--set-ctl-int", "4008=1103"]), + ("silk_wb_st", "speechst", "enc", ["--speech", "--bitrate", "28", "--framesize", "60", "--set-ctl-int", "4008=1103"]), + ("silk_nb_st", "speechst", "enc", ["--speech", "--bitrate", "12", "--framesize", "10", "--set-ctl-int", "4008=1101"]), + ("hybrid_swb", "speech", "enc", ["--speech", "--bitrate", "24"]), + ("hybrid_fb", "speech", "enc", ["--speech", "--bitrate", "36", "--framesize", "10"]), + ("hybrid_st", "speechst", "enc", ["--speech", "--bitrate", "40"]), + ("mix_st_24", "mixst", "enc", ["--bitrate", "24"]), + ("surround51", "surround", "enc", ["--bitrate", "192"]), + ("long_128", "long", "enc", ["--bitrate", "128", "--comment", "TITLE=Long Test", "--artist", "opus-luau"]), + ("ff_cbr", "mixst", "ff", ["-b:a", "96k", "-vbr", "off"]), + ("ff_voip", "speechst", "ff", ["-b:a", "32k", "-application", "voip"]), + ("ff_lowdelay", "music", "ff", ["-b:a", "128k", "-application", "lowdelay", "-frame_duration", "5"]), +] + + +def generate(ctx): + tmp = tempfile.mkdtemp() + for name, (expr, secs) in SOURCES.items(): + ctx.nix("ffmpeg", ["ffmpeg", "-loglevel", "error", "-y", "-f", "lavfi", "-i", "aevalsrc='%s':s=48000:d=%d" % (expr, secs), + "-c:a", "pcm_s16le", os.path.join(tmp, name + ".wav")]) + for name, src, enc, args in CASES: + wav, opus, ref = (os.path.join(tmp, x) for x in (src + ".wav", name + ".opus", name + ".f32")) + if enc == "enc": + ctx.nix("opus-tools", ["opusenc", "--quiet"] + args + [wav, opus]) + else: + ctx.nix("ffmpeg", ["ffmpeg", "-loglevel", "error", "-y", "-i", wav, "-c:a", "libopus"] + args + [opus]) + ctx.nix("opus-tools", ["opusdec", "--quiet", "--float", opus, ref]) + ctx.emit("opus_" + name, {"name": name, "data": open(opus, "rb").read(), "ref": open(ref, "rb").read()})