ws-video: merge master (m4a, music, ...)
This commit is contained in:
commit
e044209ab1
118 files changed
+29274
-28
No files matched your search
@@ -0,0 +1,903 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/Aac/Decode: the AAC-LC raw_data_block decoder (ISO/IEC 14496-3 subpart 4): SCE / CPE / LFE / DSE / PCE /
|
||||
-- FIL / END elements, ics_info with window grouping, section data, scalefactors (with noise energies and intensity
|
||||
-- positions), pulse data, TNS, the eleven spectral codebooks with escapes, dequantisation, M/S and intensity stereo,
|
||||
-- perceptual noise substitution (FFmpeg's LCG so the noise matches it), the filterbank (sine / KBD windows, the four
|
||||
-- window sequences, IMDCT through codecs/Mdct, overlap-add). FIL extension payloads (SBR / PS) are reported to a hook
|
||||
-- and otherwise skipped. Written from the standard; no third-party code. Never throws: returns nil, message.
|
||||
local Mdct = require("@formats/codecs/Mdct")
|
||||
local Tables = require("@formats/codecs/Aac/Tables")
|
||||
|
||||
local readu32, byteswap, lshift, rshift, band = buffer.readu32, bit32.byteswap, bit32.lshift, bit32.rshift, bit32.band
|
||||
local floor, sqrt, abs = math.floor, math.sqrt, math.abs
|
||||
|
||||
local Decode = {}
|
||||
|
||||
local ONLY_LONG, LONG_START, EIGHT_SHORT, LONG_STOP = 0, 1, 2, 3
|
||||
local ZERO_HCB, ESC_HCB, NOISE_HCB, INTENSITY_HCB2, INTENSITY_HCB = 0, 11, 13, 14, 15
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ bit reader
|
||||
-- one packet at a time: module-level cursor over a zero-padded copy (a frame decode never yields)
|
||||
local B: buffer = buffer.create(16)
|
||||
local BP = 0 -- bit position
|
||||
local BL = 0 -- bit limit
|
||||
local OVER = false
|
||||
|
||||
local function getBits(n: number): number -- 1 .. 25
|
||||
local p = BP
|
||||
BP = p + n
|
||||
if p > BL then
|
||||
OVER = true
|
||||
return 0
|
||||
end
|
||||
return rshift(lshift(byteswap(readu32(B, rshift(p, 3))), band(p, 7)), 32 - n)
|
||||
end
|
||||
local function peekBits(n: number): number
|
||||
local p = BP
|
||||
if p > BL then
|
||||
return 0
|
||||
end
|
||||
return rshift(lshift(byteswap(readu32(B, rshift(p, 3))), band(p, 7)), 32 - n)
|
||||
end
|
||||
local function getLong(n: number): number
|
||||
if n > 24 then
|
||||
local hi = getBits(n - 16)
|
||||
return hi * 65536 + getBits(16)
|
||||
end
|
||||
return getBits(n)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ Huffman
|
||||
local PEEK = 10
|
||||
type Book = { tab: { number }, map: { [number]: number }, maxLen: number }
|
||||
|
||||
local function book(codes: { number }, bits: { number }): Book
|
||||
local tab = table.create(2 ^ PEEK, 0)
|
||||
local map = {}
|
||||
local maxLen = 0
|
||||
for s = 1, #codes do
|
||||
local c, l = codes[s], bits[s]
|
||||
maxLen = math.max(maxLen, l)
|
||||
if l <= PEEK then
|
||||
local shift = 2 ^ (PEEK - l)
|
||||
for k = 0, shift - 1 do
|
||||
tab[c * shift + k + 1] = (s - 1) * 32 + l
|
||||
end
|
||||
else
|
||||
map[l * 2 ^ 20 + c] = s - 1
|
||||
end
|
||||
end
|
||||
return { tab = tab, map = map, maxLen = maxLen }
|
||||
end
|
||||
|
||||
local SF_BOOK = book(Tables.SF_CODES, Tables.SF_BITS)
|
||||
local SPEC_BOOK: { Book } = {}
|
||||
for i = 1, 11 do
|
||||
SPEC_BOOK[i] = book(Tables.SPEC_CODES[i], Tables.SPEC_BITS[i])
|
||||
end
|
||||
|
||||
-- the next symbol of a book, -1 for an invalid code
|
||||
local function huff(bk: Book): number
|
||||
local e = bk.tab[peekBits(PEEK) + 1]
|
||||
if e > 0 then
|
||||
BP += band(e, 31)
|
||||
return rshift(e, 5)
|
||||
end
|
||||
-- a code longer than PEEK bits
|
||||
local code = getBits(PEEK)
|
||||
local map = bk.map
|
||||
for l = PEEK + 1, bk.maxLen do
|
||||
code = code * 2 + getBits(1)
|
||||
local s = map[l * 1048576 + code]
|
||||
if s then
|
||||
return s
|
||||
end
|
||||
end
|
||||
return -1
|
||||
end
|
||||
|
||||
-- per codebook: dimension, unsigned, modulus, offset
|
||||
local DIM = { 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2 }
|
||||
local UNSIGNED = { false, false, true, true, false, false, true, true, true, true, true }
|
||||
local MOD = { 3, 3, 3, 3, 9, 9, 8, 8, 13, 13, 17 }
|
||||
local OFF = { 1, 1, 0, 0, 4, 4, 0, 0, 0, 0, 0 }
|
||||
|
||||
-- |q|^(4/3)
|
||||
local POW43 = table.create(8192, 0)
|
||||
for i = 0, 8191 do
|
||||
POW43[i + 1] = i ^ (4 / 3)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ windows
|
||||
local SINE_LONG = Mdct.window("sine", 2048) :: { number }
|
||||
local KBD_LONG = Mdct.window("kbd", 2048, 4) :: { number }
|
||||
local SINE_SHORT = Mdct.window("sine", 256) :: { number }
|
||||
local KBD_SHORT = Mdct.window("kbd", 256, 6) :: { number }
|
||||
local PLAN_LONG = Mdct.new(2048) :: Mdct.Plan
|
||||
local PLAN_SHORT = Mdct.new(256) :: Mdct.Plan
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ state
|
||||
export type Channel = {
|
||||
spec: { number }, -- 1024 dequantised coefficients (8 x 128 for short windows)
|
||||
overlap: { number }, -- 1024 samples carried to the next frame
|
||||
prevShape: number,
|
||||
-- this frame's ics
|
||||
windowSequence: number,
|
||||
windowShape: number,
|
||||
maxSfb: number,
|
||||
numGroups: number,
|
||||
groupLen: { number },
|
||||
bandType: { number }, -- [g * maxSfb + sfb + 1]
|
||||
sf: { number },
|
||||
-- tns
|
||||
tnsFilters: { { number } }, -- per window: { length, order, direction, coefs ... } flattened per filter
|
||||
}
|
||||
|
||||
export type State = {
|
||||
sfIndex: number,
|
||||
channels: number, -- configured channels (0: as found)
|
||||
frameLength: number,
|
||||
ch: { Channel },
|
||||
pcm: { number }, -- interleaved output floats
|
||||
random: number, -- PNS generator state
|
||||
time: { number }, -- 2048 IMDCT scratch
|
||||
frame: { number }, -- 2048 windowed frame scratch
|
||||
short: { number }, -- 256 scratch
|
||||
onExtension: ((kind: number, element: number, buf: buffer, bitPos: number, bits: number) -> ())?,
|
||||
extensions: number, -- extension payloads seen (SBR / PS / ...)
|
||||
sbr: boolean, -- an SBR payload was seen
|
||||
map: { number }?, -- element channel order -> output channel (1-based)
|
||||
}
|
||||
|
||||
local function newChannel(): Channel
|
||||
return {
|
||||
spec = table.create(1024, 0),
|
||||
overlap = table.create(1024, 0),
|
||||
prevShape = 0,
|
||||
windowSequence = 0,
|
||||
windowShape = 0,
|
||||
maxSfb = 0,
|
||||
numGroups = 1,
|
||||
groupLen = { 1, 0, 0, 0, 0, 0, 0, 0 },
|
||||
bandType = table.create(8 * 64, 0),
|
||||
sf = table.create(8 * 64, 0),
|
||||
tnsFilters = {},
|
||||
}
|
||||
end
|
||||
Decode.newChannel = newChannel
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ ics
|
||||
local function icsInfo(st: State, c: Channel): string?
|
||||
if getBits(1) ~= 0 then
|
||||
return "reserved ics bit set"
|
||||
end
|
||||
c.windowSequence = getBits(2)
|
||||
c.windowShape = getBits(1)
|
||||
if c.windowSequence == EIGHT_SHORT then
|
||||
c.maxSfb = getBits(4)
|
||||
local grouping = getBits(7)
|
||||
local ng = 1
|
||||
local gl = c.groupLen
|
||||
gl[1] = 1
|
||||
for w = 1, 7 do
|
||||
if band(grouping, 2 ^ (6 - (w - 1))) ~= 0 then
|
||||
gl[ng] += 1
|
||||
else
|
||||
ng += 1
|
||||
gl[ng] = 1
|
||||
end
|
||||
end
|
||||
c.numGroups = ng
|
||||
if c.maxSfb > Tables.NUM_SWB_SHORT[st.sfIndex + 1] then
|
||||
return "max_sfb over the short band count"
|
||||
end
|
||||
else
|
||||
c.maxSfb = getBits(6)
|
||||
c.numGroups = 1
|
||||
c.groupLen[1] = 1
|
||||
if getBits(1) ~= 0 then
|
||||
return "prediction (AAC Main / LTP) is not supported"
|
||||
end
|
||||
if c.maxSfb > Tables.NUM_SWB_LONG[st.sfIndex + 1] then
|
||||
return "max_sfb over the long band count"
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function sectionData(c: Channel): string?
|
||||
local long = c.windowSequence ~= EIGHT_SHORT
|
||||
local bits = if long then 5 else 3
|
||||
local esc = 2 ^ bits - 1
|
||||
local maxSfb = c.maxSfb
|
||||
local bt = c.bandType
|
||||
for g = 0, c.numGroups - 1 do
|
||||
local k = 0
|
||||
while k < maxSfb do
|
||||
local cb = getBits(4)
|
||||
if cb == 12 then
|
||||
return "reserved codebook 12"
|
||||
end
|
||||
local len = 0
|
||||
while true do
|
||||
local inc = getBits(bits)
|
||||
len += inc
|
||||
if inc ~= esc then
|
||||
break
|
||||
end
|
||||
if OVER then
|
||||
return "section data runs past the end"
|
||||
end
|
||||
end
|
||||
if k + len > maxSfb then
|
||||
return "section runs past max_sfb"
|
||||
end
|
||||
for s = k, k + len - 1 do
|
||||
bt[g * maxSfb + s + 1] = cb
|
||||
end
|
||||
k += len
|
||||
if OVER then
|
||||
return "section data runs past the end"
|
||||
end
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function scaleFactors(c: Channel, globalGain: number): string?
|
||||
local sfv = globalGain
|
||||
local noise = globalGain - 90
|
||||
local is = 0
|
||||
local firstNoise = true
|
||||
local maxSfb = c.maxSfb
|
||||
local bt, sf = c.bandType, c.sf
|
||||
for g = 0, c.numGroups - 1 do
|
||||
for s = 0, maxSfb - 1 do
|
||||
local i = g * maxSfb + s + 1
|
||||
local cb = bt[i]
|
||||
if cb == ZERO_HCB then
|
||||
sf[i] = 0
|
||||
elseif cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then
|
||||
local d = huff(SF_BOOK)
|
||||
if d < 0 then
|
||||
return "bad scalefactor code"
|
||||
end
|
||||
is += d - 60
|
||||
sf[i] = math.clamp(is, -155, 100)
|
||||
elseif cb == NOISE_HCB then
|
||||
if firstNoise then
|
||||
noise += getBits(9) - 256
|
||||
firstNoise = false
|
||||
else
|
||||
local d = huff(SF_BOOK)
|
||||
if d < 0 then
|
||||
return "bad scalefactor code"
|
||||
end
|
||||
noise += d - 60
|
||||
end
|
||||
sf[i] = math.clamp(noise, -100, 155)
|
||||
else
|
||||
local d = huff(SF_BOOK)
|
||||
if d < 0 then
|
||||
return "bad scalefactor code"
|
||||
end
|
||||
sfv += d - 60
|
||||
if sfv < 0 or sfv > 255 then
|
||||
return "scalefactor out of range"
|
||||
end
|
||||
sf[i] = sfv
|
||||
end
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function tnsData(st: State, c: Channel): string?
|
||||
local short = c.windowSequence == EIGHT_SHORT
|
||||
local nw = if short then 8 else 1
|
||||
local filters = {}
|
||||
for w = 1, nw do
|
||||
local list = {}
|
||||
local nFilt = getBits(if short then 1 else 2)
|
||||
if nFilt > 0 then
|
||||
local coefRes = getBits(1)
|
||||
for _ = 1, nFilt do
|
||||
local length = getBits(if short then 4 else 6)
|
||||
local order = getBits(if short then 3 else 5)
|
||||
local f = { length, order, 0 }
|
||||
if order > (if short then 7 else 12) then
|
||||
return "TNS order too high"
|
||||
end
|
||||
if order > 0 then
|
||||
f[3] = getBits(1)
|
||||
local compress = getBits(1)
|
||||
local resBits = coefRes + 3
|
||||
local nb = resBits - compress
|
||||
local iq = ((2 ^ (resBits - 1)) - 0.5) / (math.pi / 2)
|
||||
local iqm = ((2 ^ (resBits - 1)) + 0.5) / (math.pi / 2)
|
||||
local tmp = table.create(order, 0)
|
||||
for k = 1, order do
|
||||
local v = getBits(nb)
|
||||
if v >= 2 ^ (nb - 1) then
|
||||
v -= 2 ^ nb
|
||||
end
|
||||
tmp[k] = math.sin(v / (if v >= 0 then iq else iqm))
|
||||
end
|
||||
-- parcor -> LPC
|
||||
local a = table.create(order + 1, 0)
|
||||
local b = table.create(order + 1, 0)
|
||||
a[1] = 1
|
||||
for m = 1, order do
|
||||
for i = 1, m - 1 do
|
||||
b[i + 1] = a[i + 1] + tmp[m] * a[m - i + 1]
|
||||
end
|
||||
for i = 1, m - 1 do
|
||||
a[i + 1] = b[i + 1]
|
||||
end
|
||||
a[m + 1] = tmp[m]
|
||||
end
|
||||
for k = 1, order do
|
||||
f[3 + k] = a[k + 1]
|
||||
end
|
||||
end
|
||||
table.insert(list, f)
|
||||
end
|
||||
end
|
||||
filters[w] = list
|
||||
end
|
||||
c.tnsFilters = filters
|
||||
local _ = st
|
||||
return nil
|
||||
end
|
||||
|
||||
local function applyTns(st: State, c: Channel)
|
||||
local short = c.windowSequence == EIGHT_SHORT
|
||||
local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1]
|
||||
local numSwb = if short then Tables.NUM_SWB_SHORT[st.sfIndex + 1] else Tables.NUM_SWB_LONG[st.sfIndex + 1]
|
||||
local maxBands = if short then Tables.TNS_MAX_BANDS_SHORT[st.sfIndex + 1] else Tables.TNS_MAX_BANDS_LONG[st.sfIndex + 1]
|
||||
local mmm = math.min(maxBands, c.maxSfb)
|
||||
if mmm == 0 then
|
||||
return
|
||||
end
|
||||
local spec = c.spec
|
||||
for w, list in c.tnsFilters do
|
||||
local bottom = numSwb
|
||||
for _, f in list do
|
||||
local top = bottom
|
||||
bottom = math.max(0, top - f[1])
|
||||
local order = f[2]
|
||||
if order > 0 then
|
||||
local start = swb[math.min(bottom, mmm) + 1]
|
||||
local stop = swb[math.min(top, mmm) + 1]
|
||||
local size = stop - start
|
||||
if size > 0 then
|
||||
local inc = 1
|
||||
local p = (w - 1) * 128 + start + 1
|
||||
if f[3] == 1 then
|
||||
inc = -1
|
||||
p = (w - 1) * 128 + stop
|
||||
end
|
||||
for m = 0, size - 1 do
|
||||
local y = spec[p]
|
||||
local lim = if m < order then m else order
|
||||
for i = 1, lim do
|
||||
y -= spec[p - i * inc] * f[3 + i]
|
||||
end
|
||||
spec[p] = y
|
||||
p += inc
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- the spectral data of one channel, dequantised into c.spec (also pulses, noise, intensity zeros)
|
||||
local function spectralData(st: State, c: Channel, pulses: { number }?): string?
|
||||
local short = c.windowSequence == EIGHT_SHORT
|
||||
local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1]
|
||||
local spec = c.spec
|
||||
for i = 1, 1024 do
|
||||
spec[i] = 0
|
||||
end
|
||||
local maxSfb = c.maxSfb
|
||||
local bt, sf = c.bandType, c.sf
|
||||
local win = 0
|
||||
for g = 0, c.numGroups - 1 do
|
||||
local glen = c.groupLen[g + 1]
|
||||
for s = 0, maxSfb - 1 do
|
||||
local idx = g * maxSfb + s + 1
|
||||
local cb = bt[idx]
|
||||
local lo, hi = swb[s + 1], swb[s + 2]
|
||||
local width = hi - lo
|
||||
if cb == ZERO_HCB or cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then
|
||||
-- zeros (intensity bands are filled from the other channel later)
|
||||
continue
|
||||
elseif cb == NOISE_HCB then
|
||||
local scale = 2 ^ (0.25 * sf[idx])
|
||||
for w = 0, glen - 1 do
|
||||
local base = (win + w) * 128 + lo
|
||||
local energy = 0
|
||||
local r = st.random
|
||||
for k = 1, width do
|
||||
r = (r * 1664525 + 1013904223) % 4294967296
|
||||
local v = if r >= 2147483648 then r - 4294967296 else r
|
||||
spec[base + k] = v
|
||||
energy += v * v
|
||||
end
|
||||
st.random = r
|
||||
local m = if energy > 0 then scale / sqrt(energy) else 0
|
||||
for k = 1, width do
|
||||
spec[base + k] *= m
|
||||
end
|
||||
end
|
||||
continue
|
||||
end
|
||||
local bk = SPEC_BOOK[cb]
|
||||
local dim, uns, mod, off = DIM[cb], UNSIGNED[cb], MOD[cb], OFF[cb]
|
||||
local gain = 2 ^ (0.25 * (sf[idx] - 100))
|
||||
for w = 0, glen - 1 do
|
||||
local base = (win + w) * 128 + lo
|
||||
local k = 0
|
||||
while k < width do
|
||||
local sym = huff(bk)
|
||||
if sym < 0 then
|
||||
return "bad spectral code"
|
||||
end
|
||||
-- unpack the symbol into dim values (first value most significant)
|
||||
local vals1, vals2, vals3, vals4
|
||||
if dim == 4 then
|
||||
vals4 = sym % mod - off
|
||||
sym = (sym - (sym % mod)) / mod
|
||||
vals3 = sym % mod - off
|
||||
sym = (sym - (sym % mod)) / mod
|
||||
vals2 = sym % mod - off
|
||||
sym = (sym - (sym % mod)) / mod
|
||||
vals1 = sym % mod - off
|
||||
else
|
||||
vals2 = sym % mod - off
|
||||
vals1 = (sym - (sym % mod)) / mod - off
|
||||
end
|
||||
if uns then
|
||||
if vals1 ~= 0 and getBits(1) == 1 then
|
||||
vals1 = -vals1
|
||||
end
|
||||
if vals2 ~= 0 and getBits(1) == 1 then
|
||||
vals2 = -vals2
|
||||
end
|
||||
if dim == 4 then
|
||||
if vals3 ~= 0 and getBits(1) == 1 then
|
||||
vals3 = -vals3
|
||||
end
|
||||
if vals4 ~= 0 and getBits(1) == 1 then
|
||||
vals4 = -vals4
|
||||
end
|
||||
end
|
||||
if cb == ESC_HCB then
|
||||
for e = 1, 2 do
|
||||
local v = if e == 1 then vals1 else vals2
|
||||
if v == 16 or v == -16 then
|
||||
local n = 0
|
||||
while getBits(1) == 1 do
|
||||
n += 1
|
||||
if n > 8 or OVER then
|
||||
return "bad escape"
|
||||
end
|
||||
end
|
||||
local esc = 2 ^ (n + 4) + getBits(n + 4)
|
||||
if v < 0 then
|
||||
esc = -esc
|
||||
end
|
||||
if e == 1 then
|
||||
vals1 = esc
|
||||
else
|
||||
vals2 = esc
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local p = base + k + 1
|
||||
spec[p] = vals1
|
||||
spec[p + 1] = vals2
|
||||
if dim == 4 then
|
||||
spec[p + 2] = vals3
|
||||
spec[p + 3] = vals4
|
||||
end
|
||||
k += dim
|
||||
end
|
||||
if OVER then
|
||||
return "spectral data runs past the end"
|
||||
end
|
||||
end
|
||||
-- dequantise (pulses are added to the quantised values first: long windows only, applied below)
|
||||
if not pulses then
|
||||
for w = 0, glen - 1 do
|
||||
local base = (win + w) * 128 + lo
|
||||
for k = 1, width do
|
||||
local q = spec[base + k]
|
||||
if q ~= 0 then
|
||||
local aq = if q < 0 then -q else q
|
||||
local v = (POW43[aq + 1] or aq ^ (4 / 3)) * gain
|
||||
spec[base + k] = if q < 0 then -v else v
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
win += glen
|
||||
end
|
||||
if pulses then
|
||||
-- long window: add the pulses to the quantised values, then dequantise every band
|
||||
for i = 1, #pulses, 2 do
|
||||
local pos = pulses[i] + 1
|
||||
if pos <= 1024 then
|
||||
local q = spec[pos]
|
||||
spec[pos] = if q > 0 then q + pulses[i + 1] else q - pulses[i + 1]
|
||||
end
|
||||
end
|
||||
for s = 0, maxSfb - 1 do
|
||||
local idx = s + 1
|
||||
local cb = bt[idx]
|
||||
if cb ~= ZERO_HCB and cb < NOISE_HCB then
|
||||
local gain = 2 ^ (0.25 * (sf[idx] - 100))
|
||||
for k = swb[s + 1] + 1, swb[s + 2] do
|
||||
local q = spec[k]
|
||||
if q ~= 0 then
|
||||
local aq = if q < 0 then -q else q
|
||||
local v = (POW43[aq + 1] or aq ^ (4 / 3)) * gain
|
||||
spec[k] = if q < 0 then -v else v
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- individual_channel_stream
|
||||
local function ics(st: State, c: Channel, commonWindow: boolean): string?
|
||||
local globalGain = getBits(8)
|
||||
if not commonWindow then
|
||||
local e = icsInfo(st, c)
|
||||
if e then
|
||||
return e
|
||||
end
|
||||
end
|
||||
local e = sectionData(c)
|
||||
if e then
|
||||
return e
|
||||
end
|
||||
e = scaleFactors(c, globalGain)
|
||||
if e then
|
||||
return e
|
||||
end
|
||||
local pulses: { number }? = nil
|
||||
if getBits(1) == 1 then
|
||||
if c.windowSequence == EIGHT_SHORT then
|
||||
return "pulse data in a short window"
|
||||
end
|
||||
local n = getBits(2) + 1
|
||||
local startSfb = getBits(6)
|
||||
if startSfb >= Tables.NUM_SWB_LONG[st.sfIndex + 1] then
|
||||
return "bad pulse start band"
|
||||
end
|
||||
local pos = Tables.SWB_LONG[st.sfIndex + 1][startSfb + 1]
|
||||
local list = {}
|
||||
for _ = 1, n do
|
||||
pos += getBits(5)
|
||||
table.insert(list, pos)
|
||||
table.insert(list, getBits(4))
|
||||
end
|
||||
pulses = list
|
||||
end
|
||||
c.tnsFilters = {}
|
||||
if getBits(1) == 1 then
|
||||
e = tnsData(st, c)
|
||||
if e then
|
||||
return e
|
||||
end
|
||||
end
|
||||
if getBits(1) == 1 then
|
||||
return "gain control (AAC SSR) is not supported"
|
||||
end
|
||||
if OVER then
|
||||
return "channel stream runs past the end"
|
||||
end
|
||||
return spectralData(st, c, pulses)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ stereo
|
||||
local function msStereo(st: State, l: Channel, r: Channel, mask: { number })
|
||||
local short = l.windowSequence == EIGHT_SHORT
|
||||
local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1]
|
||||
local maxSfb = l.maxSfb
|
||||
local a, b = l.spec, r.spec
|
||||
local win = 0
|
||||
for g = 0, l.numGroups - 1 do
|
||||
local glen = l.groupLen[g + 1]
|
||||
for s = 0, maxSfb - 1 do
|
||||
local idx = g * maxSfb + s + 1
|
||||
if mask[idx] == 1 and l.bandType[idx] < NOISE_HCB and r.bandType[idx] < NOISE_HCB then
|
||||
for w = 0, glen - 1 do
|
||||
local base = (win + w) * 128
|
||||
for k = base + swb[s + 1] + 1, base + swb[s + 2] do
|
||||
local m, sd = a[k], b[k]
|
||||
a[k], b[k] = m + sd, m - sd
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
win += glen
|
||||
end
|
||||
end
|
||||
|
||||
local function intensity(st: State, l: Channel, r: Channel, mask: { number }, msPresent: number)
|
||||
local short = r.windowSequence == EIGHT_SHORT
|
||||
local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1]
|
||||
local maxSfb = r.maxSfb
|
||||
local a, b = l.spec, r.spec
|
||||
local win = 0
|
||||
for g = 0, r.numGroups - 1 do
|
||||
local glen = r.groupLen[g + 1]
|
||||
for s = 0, maxSfb - 1 do
|
||||
local idx = g * maxSfb + s + 1
|
||||
local cb = r.bandType[idx]
|
||||
if cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then
|
||||
local sign = if cb == INTENSITY_HCB then 1 else -1
|
||||
if msPresent ~= 0 and mask[idx] == 1 then
|
||||
sign = -sign
|
||||
end
|
||||
local scale = sign * 0.5 ^ (0.25 * r.sf[idx])
|
||||
for w = 0, glen - 1 do
|
||||
local base = (win + w) * 128
|
||||
for k = base + swb[s + 1] + 1, base + swb[s + 2] do
|
||||
b[k] = a[k] * scale
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
win += glen
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ filterbank
|
||||
local function filterbank(st: State, c: Channel, out: { number }, stride: number, offset: number)
|
||||
local seq, shape, prev = c.windowSequence, c.windowShape, c.prevShape
|
||||
local spec, overlap = c.spec, c.overlap
|
||||
local frame = st.frame
|
||||
local scale = 1 / 32768
|
||||
if seq == EIGHT_SHORT then
|
||||
for i = 1, 2048 do
|
||||
frame[i] = 0
|
||||
end
|
||||
local tmp = st.short
|
||||
local rise0 = if prev == 1 then KBD_SHORT else SINE_SHORT
|
||||
local wcur = if shape == 1 then KBD_SHORT else SINE_SHORT
|
||||
for w = 0, 7 do
|
||||
Mdct.inverse(PLAN_SHORT, spec, w * 128 + 1, 1, tmp, 1, 2 / 256)
|
||||
local rise = if w == 0 then rise0 else wcur
|
||||
local base = 448 + w * 128
|
||||
for n = 1, 128 do
|
||||
frame[base + n] += tmp[n] * rise[n]
|
||||
frame[base + 128 + n] += tmp[128 + n] * wcur[128 + n]
|
||||
end
|
||||
end
|
||||
else
|
||||
local t = st.time
|
||||
Mdct.inverse(PLAN_LONG, spec, 1, 1, t, 1, 2 / 2048)
|
||||
-- left half
|
||||
if seq == LONG_STOP then
|
||||
local rise = if prev == 1 then KBD_SHORT else SINE_SHORT
|
||||
for n = 1, 448 do
|
||||
frame[n] = 0
|
||||
end
|
||||
for n = 1, 128 do
|
||||
frame[448 + n] = t[448 + n] * rise[n]
|
||||
end
|
||||
for n = 577, 1024 do
|
||||
frame[n] = t[n]
|
||||
end
|
||||
else
|
||||
local rise = if prev == 1 then KBD_LONG else SINE_LONG
|
||||
for n = 1, 1024 do
|
||||
frame[n] = t[n] * rise[n]
|
||||
end
|
||||
end
|
||||
-- right half
|
||||
if seq == LONG_START then
|
||||
local fall = if shape == 1 then KBD_SHORT else SINE_SHORT
|
||||
for n = 1025, 1472 do
|
||||
frame[n] = t[n]
|
||||
end
|
||||
for n = 1, 128 do
|
||||
frame[1472 + n] = t[1472 + n] * fall[128 + n]
|
||||
end
|
||||
for n = 1601, 2048 do
|
||||
frame[n] = 0
|
||||
end
|
||||
else
|
||||
local fall = if shape == 1 then KBD_LONG else SINE_LONG
|
||||
for n = 1025, 2048 do
|
||||
frame[n] = t[n] * fall[n]
|
||||
end
|
||||
end
|
||||
end
|
||||
local p = offset
|
||||
for n = 1, 1024 do
|
||||
out[p] = (frame[n] + overlap[n]) * scale
|
||||
overlap[n] = frame[1024 + n]
|
||||
p += stride
|
||||
end
|
||||
c.prevShape = shape
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ frame
|
||||
-- frame(st, buf, off, len) -> channels decoded | nil, message. Output: st.pcm, 1024 frames interleaved.
|
||||
function Decode.frame(st: State, buf: buffer, off: number, len: number): (number?, string?)
|
||||
if buffer.len(B) < len + 16 then
|
||||
B = buffer.create(len + 256)
|
||||
end
|
||||
buffer.copy(B, 0, buf, off, len)
|
||||
buffer.fill(B, len, 0, 16)
|
||||
BP, BL, OVER = 0, len * 8, false
|
||||
local chans = st.ch
|
||||
local nextCh = 1
|
||||
local order: { Channel } = {}
|
||||
local lastElement = -1
|
||||
while true do
|
||||
if BP + 3 > BL then
|
||||
break -- tolerate a missing END
|
||||
end
|
||||
local id = getBits(3)
|
||||
if id == 7 then
|
||||
break
|
||||
end
|
||||
if id == 0 or id == 3 then -- SCE / LFE
|
||||
getBits(4)
|
||||
local c = chans[nextCh]
|
||||
if not c then
|
||||
c = newChannel()
|
||||
chans[nextCh] = c
|
||||
end
|
||||
local e = ics(st, c, false)
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
applyTns(st, c)
|
||||
table.insert(order, c)
|
||||
nextCh += 1
|
||||
lastElement = id
|
||||
elseif id == 1 then -- CPE
|
||||
getBits(4)
|
||||
local l, r = chans[nextCh], chans[nextCh + 1]
|
||||
if not l then
|
||||
l = newChannel()
|
||||
chans[nextCh] = l
|
||||
end
|
||||
if not r then
|
||||
r = newChannel()
|
||||
chans[nextCh + 1] = r
|
||||
end
|
||||
local common = getBits(1) == 1
|
||||
local msPresent = 0
|
||||
local mask = table.create(8 * 64, 0)
|
||||
if common then
|
||||
local e = icsInfo(st, l)
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
r.windowSequence, r.windowShape, r.maxSfb, r.numGroups = l.windowSequence, l.windowShape, l.maxSfb, l.numGroups
|
||||
for i = 1, 8 do
|
||||
r.groupLen[i] = l.groupLen[i]
|
||||
end
|
||||
msPresent = getBits(2)
|
||||
if msPresent == 1 then
|
||||
for i = 1, l.numGroups * l.maxSfb do
|
||||
mask[i] = getBits(1)
|
||||
end
|
||||
elseif msPresent == 2 then
|
||||
for i = 1, l.numGroups * l.maxSfb do
|
||||
mask[i] = 1
|
||||
end
|
||||
elseif msPresent == 3 then
|
||||
return nil, "reserved ms_mask_present"
|
||||
end
|
||||
end
|
||||
local e = ics(st, l, common)
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
e = ics(st, r, common)
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
if common and msPresent ~= 0 then
|
||||
msStereo(st, l, r, mask)
|
||||
end
|
||||
if common then
|
||||
intensity(st, l, r, mask, msPresent)
|
||||
end
|
||||
applyTns(st, l)
|
||||
applyTns(st, r)
|
||||
table.insert(order, l)
|
||||
table.insert(order, r)
|
||||
nextCh += 2
|
||||
lastElement = id
|
||||
elseif id == 2 then
|
||||
return nil, "coupling channel elements are not supported"
|
||||
elseif id == 4 then -- DSE
|
||||
getBits(4)
|
||||
local align = getBits(1)
|
||||
local count = getBits(8)
|
||||
if count == 255 then
|
||||
count += getBits(8)
|
||||
end
|
||||
if align == 1 then
|
||||
BP = (BP + 7) // 8 * 8
|
||||
end
|
||||
BP += count * 8
|
||||
elseif id == 5 then -- PCE: skipped here (parsed from the configuration)
|
||||
return nil, "program config element inside the stream is not supported"
|
||||
elseif id == 6 then -- FIL
|
||||
local count = getBits(4)
|
||||
if count == 15 then
|
||||
count += getBits(8) - 1
|
||||
end
|
||||
if count > 0 then
|
||||
local start = BP
|
||||
local kind = getBits(4)
|
||||
if kind == 13 or kind == 14 then -- EXT_SBR_DATA / EXT_SBR_DATA_CRC
|
||||
st.sbr = true
|
||||
end
|
||||
st.extensions += 1
|
||||
local hook = st.onExtension
|
||||
if hook then
|
||||
hook(kind, lastElement, B, start, count * 8)
|
||||
end
|
||||
BP = start + count * 8
|
||||
end
|
||||
end
|
||||
if OVER or BP > BL then
|
||||
return nil, "frame runs past the end"
|
||||
end
|
||||
if nextCh > 9 then
|
||||
return nil, "more than 8 channels"
|
||||
end
|
||||
end
|
||||
local n = #order
|
||||
if n == 0 then
|
||||
return 0, nil
|
||||
end
|
||||
local pcm = st.pcm
|
||||
local map = st.map
|
||||
for i, c in order do
|
||||
local o = if map and map[i] then map[i] else i
|
||||
filterbank(st, c, pcm, n, o)
|
||||
end
|
||||
return n, nil
|
||||
end
|
||||
|
||||
function Decode.state(sfIndex: number): State
|
||||
return {
|
||||
sfIndex = sfIndex,
|
||||
channels = 0,
|
||||
frameLength = 1024,
|
||||
ch = {},
|
||||
pcm = table.create(1024 * 8, 0),
|
||||
random = 0x1f2e3d4c,
|
||||
time = table.create(2048, 0),
|
||||
frame = table.create(2048, 0),
|
||||
short = table.create(256, 0),
|
||||
onExtension = nil,
|
||||
extensions = 0,
|
||||
sbr = false,
|
||||
map = nil,
|
||||
}
|
||||
end
|
||||
|
||||
local _ = abs
|
||||
local _2 = floor
|
||||
return Decode
|
||||
@@ -0,0 +1,335 @@
|
||||
--!strict
|
||||
-- codecs/Aac/Tables: the AAC-LC tables of ISO/IEC 14496-3 (subpart 4, Annex 4.A): the scalefactor and the eleven
|
||||
-- spectral Huffman codebooks (code, length per symbol), the scalefactor band offsets per sampling rate (1024 and 128
|
||||
-- lines) and the TNS band limits. Transcribed from FFmpeg libavcodec/aactab.c (tables of the standard, no code;
|
||||
-- see licenses/NOTICE.md). Generated; do not edit.
|
||||
local Tables = {}
|
||||
|
||||
Tables.SF_CODES = {
|
||||
262120, 262118, 262119, 262117, 524277, 524273, 524269, 524278, 524270, 524271, 524272, 524284, 524285, 524287, 524286, 524279,
|
||||
524280, 524283, 524281, 262116, 524282, 262115, 131055, 131056, 65525, 131054, 65522, 65523, 65524, 65521, 32758, 32759,
|
||||
16377, 16373, 16375, 16371, 16374, 16370, 8183, 8181, 4089, 4087, 4086, 2041, 4084, 2040, 1017, 1015,
|
||||
1013, 504, 503, 250, 248, 246, 121, 58, 56, 26, 11, 4, 0, 10, 12, 27,
|
||||
57, 59, 120, 122, 247, 249, 502, 505, 1012, 1014, 1016, 2037, 2036, 2038, 2039, 4085,
|
||||
4088, 8180, 8182, 8184, 16376, 16372, 65520, 32756, 65526, 32757, 262114, 524249, 524250, 524251, 524252, 524253,
|
||||
524254, 524248, 524242, 524243, 524244, 524245, 524246, 524274, 524255, 524263, 524264, 524265, 524266, 524267, 524262, 524256,
|
||||
524257, 524258, 524259, 524260, 524261, 524247, 524268, 524276, 524275,
|
||||
}
|
||||
|
||||
Tables.SF_BITS = {
|
||||
18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 18, 19, 18, 17, 17, 16, 17, 16, 16, 16, 16,
|
||||
15, 15, 14, 14, 14, 14, 14, 14, 13, 13, 12, 12, 12, 11, 12, 11, 10, 10, 10, 9, 9, 8, 8, 8, 7, 6, 6, 5, 4, 3,
|
||||
1, 4, 4, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 10, 11, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 16, 15, 16, 15,
|
||||
18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
|
||||
19,
|
||||
}
|
||||
|
||||
Tables.SPEC_CODES = {
|
||||
{
|
||||
2040, 497, 2045, 1013, 104, 1008, 2039, 492, 2037, 1009, 114, 1012, 116, 17, 118, 491,
|
||||
108, 1014, 2044, 481, 2033, 496, 97, 502, 2034, 490, 2043, 498, 105, 493, 119, 23,
|
||||
111, 486, 100, 485, 103, 21, 98, 18, 0, 20, 101, 22, 109, 489, 99, 484,
|
||||
107, 19, 113, 483, 112, 499, 2046, 487, 2035, 495, 96, 494, 2032, 482, 2042, 1011,
|
||||
106, 488, 117, 16, 115, 500, 110, 1015, 2038, 480, 2041, 1010, 102, 501, 2047, 503,
|
||||
2036,
|
||||
},
|
||||
{
|
||||
499, 111, 509, 235, 35, 234, 503, 232, 506, 242, 45, 112, 32, 6, 43, 110,
|
||||
40, 233, 505, 102, 248, 231, 27, 241, 500, 107, 501, 236, 42, 108, 44, 10,
|
||||
39, 103, 26, 245, 36, 8, 31, 9, 0, 7, 29, 11, 48, 239, 28, 100,
|
||||
30, 12, 41, 243, 47, 240, 508, 113, 498, 244, 33, 230, 247, 104, 504, 238,
|
||||
34, 101, 49, 2, 38, 237, 37, 106, 507, 114, 510, 105, 46, 246, 511, 109,
|
||||
502,
|
||||
},
|
||||
{
|
||||
0, 9, 239, 11, 25, 240, 491, 486, 1010, 10, 53, 495, 52, 55, 489, 493,
|
||||
487, 1011, 494, 1005, 8186, 492, 498, 2041, 2040, 1016, 4088, 8, 56, 1014, 54, 117,
|
||||
1009, 1003, 1004, 4084, 24, 118, 2036, 57, 116, 1007, 499, 500, 2038, 488, 1002, 8188,
|
||||
242, 497, 4091, 1013, 2035, 4092, 238, 1015, 32766, 496, 2037, 32765, 8187, 16378, 65535, 241,
|
||||
1008, 16380, 490, 1006, 16379, 4086, 4090, 32764, 2034, 4085, 65534, 1012, 2039, 32763, 4087, 4089,
|
||||
32762,
|
||||
},
|
||||
{
|
||||
7, 22, 246, 24, 8, 239, 495, 243, 2040, 25, 23, 237, 21, 1, 226, 240,
|
||||
112, 1008, 494, 241, 2042, 238, 228, 1010, 2038, 1007, 2045, 5, 20, 242, 9, 4,
|
||||
229, 244, 232, 1012, 6, 2, 231, 3, 0, 107, 227, 105, 499, 235, 230, 1014,
|
||||
110, 106, 500, 1004, 496, 1017, 245, 236, 2043, 234, 111, 1015, 2041, 1011, 4095, 233,
|
||||
109, 1016, 108, 104, 501, 1006, 498, 2036, 2039, 1009, 4094, 1005, 497, 2037, 2046, 1013,
|
||||
2044,
|
||||
},
|
||||
{
|
||||
8191, 4087, 2036, 2024, 1009, 2030, 2041, 4088, 8189, 4093, 2033, 1000, 488, 240, 492, 1006,
|
||||
2034, 4090, 4084, 1007, 498, 232, 112, 236, 496, 1002, 2035, 2027, 491, 234, 26, 8,
|
||||
25, 238, 495, 2029, 1008, 242, 115, 11, 0, 10, 113, 243, 2025, 2031, 494, 239,
|
||||
24, 9, 27, 235, 489, 2028, 2038, 1003, 499, 237, 114, 233, 497, 1005, 2039, 4086,
|
||||
2032, 1001, 493, 241, 490, 1004, 2040, 4089, 8188, 4092, 4085, 2026, 1011, 1010, 2037, 4091,
|
||||
8190,
|
||||
},
|
||||
{
|
||||
2046, 1021, 497, 491, 500, 490, 496, 1020, 2045, 1014, 485, 234, 108, 113, 104, 240,
|
||||
486, 1015, 499, 239, 50, 39, 40, 38, 49, 235, 503, 488, 111, 46, 8, 4,
|
||||
6, 41, 107, 494, 495, 114, 45, 2, 0, 3, 47, 115, 506, 487, 110, 43,
|
||||
7, 1, 5, 44, 109, 492, 505, 238, 48, 36, 42, 37, 51, 236, 498, 1016,
|
||||
484, 237, 106, 112, 105, 116, 241, 1018, 2047, 1017, 502, 493, 504, 489, 501, 1019,
|
||||
2044,
|
||||
},
|
||||
{
|
||||
0, 5, 55, 116, 242, 491, 1005, 2039, 4, 12, 53, 113, 236, 238, 494, 501,
|
||||
54, 52, 114, 234, 241, 489, 499, 1013, 115, 112, 235, 240, 497, 496, 1004, 1018,
|
||||
243, 237, 488, 495, 1007, 1009, 1017, 2043, 493, 239, 490, 498, 1011, 1016, 2041, 2044,
|
||||
1006, 492, 500, 1012, 1015, 2040, 4093, 4094, 2038, 1008, 1010, 1014, 2042, 2045, 4092, 4095,
|
||||
},
|
||||
{
|
||||
14, 5, 16, 48, 111, 241, 506, 1022, 3, 0, 4, 18, 44, 106, 117, 248,
|
||||
15, 2, 6, 20, 46, 105, 114, 245, 47, 17, 19, 42, 50, 108, 236, 250,
|
||||
113, 43, 45, 49, 109, 112, 242, 505, 239, 104, 51, 107, 110, 238, 249, 1020,
|
||||
504, 116, 115, 237, 240, 246, 502, 509, 1021, 243, 244, 247, 503, 507, 508, 1023,
|
||||
},
|
||||
{
|
||||
0, 5, 55, 231, 478, 974, 985, 1992, 1997, 4040, 4061, 8164, 8172, 4, 12, 53,
|
||||
114, 234, 237, 482, 977, 979, 992, 2008, 4047, 4053, 54, 52, 113, 232, 236, 481,
|
||||
975, 989, 987, 2000, 4039, 4052, 4068, 230, 112, 233, 477, 483, 978, 988, 1996, 1994,
|
||||
2014, 4056, 4074, 8155, 479, 235, 476, 486, 981, 990, 1995, 2013, 2012, 4045, 4066, 4071,
|
||||
8161, 976, 480, 484, 982, 1989, 2001, 2011, 4050, 2016, 4057, 4075, 8163, 8169, 1988, 485,
|
||||
983, 1990, 1999, 2010, 4043, 4058, 4067, 4073, 8166, 8179, 8183, 2003, 984, 993, 2004, 2009,
|
||||
4051, 4062, 8157, 8153, 8162, 8170, 8177, 8182, 2002, 980, 986, 1991, 2007, 2018, 4046, 4059,
|
||||
8152, 8174, 16368, 8180, 16370, 2017, 991, 1993, 2006, 4042, 4048, 4069, 4070, 8171, 8175, 16371,
|
||||
16372, 16373, 4064, 1998, 2005, 4038, 4049, 4065, 8160, 8168, 8176, 16369, 16376, 16374, 32764, 4072,
|
||||
2015, 4041, 4055, 4060, 8156, 8159, 8173, 8181, 16377, 16379, 32765, 32766, 8167, 4044, 4054, 4063,
|
||||
8158, 8154, 8165, 8178, 16378, 16375, 16380, 16381, 32767,
|
||||
},
|
||||
{
|
||||
34, 8, 29, 38, 95, 211, 463, 976, 983, 1005, 2032, 2038, 4093, 7, 0, 1,
|
||||
9, 32, 84, 96, 213, 220, 468, 973, 990, 2023, 28, 2, 6, 12, 30, 40,
|
||||
91, 205, 217, 462, 476, 985, 1009, 37, 11, 10, 13, 36, 87, 97, 204, 221,
|
||||
460, 478, 979, 999, 93, 33, 31, 35, 39, 89, 100, 216, 223, 466, 482, 989,
|
||||
1006, 209, 85, 41, 86, 88, 98, 206, 224, 226, 474, 980, 995, 2027, 457, 94,
|
||||
90, 92, 99, 202, 218, 455, 458, 480, 987, 1000, 2028, 483, 210, 203, 208, 215,
|
||||
219, 454, 469, 472, 970, 986, 2026, 2033, 481, 212, 207, 214, 222, 225, 464, 470,
|
||||
977, 981, 1010, 2030, 2043, 1001, 461, 456, 459, 465, 471, 479, 975, 992, 1007, 2022,
|
||||
2040, 4090, 1003, 477, 467, 473, 475, 978, 972, 988, 1002, 2029, 2035, 2041, 4089, 2034,
|
||||
974, 484, 971, 984, 982, 994, 997, 2024, 2036, 2037, 2039, 4091, 2042, 1004, 991, 993,
|
||||
996, 998, 1008, 2025, 2031, 4088, 4094, 4092, 4095,
|
||||
},
|
||||
{
|
||||
0, 6, 25, 61, 156, 198, 423, 912, 962, 991, 2022, 2035, 4091, 2028, 4090, 4094,
|
||||
910, 5, 1, 8, 20, 55, 66, 146, 175, 401, 421, 437, 926, 960, 930, 973,
|
||||
2006, 174, 23, 7, 9, 24, 57, 64, 142, 163, 184, 409, 428, 449, 945, 918,
|
||||
958, 970, 157, 60, 21, 22, 26, 59, 68, 145, 165, 190, 406, 430, 441, 929,
|
||||
913, 933, 981, 148, 154, 54, 56, 58, 65, 140, 155, 176, 195, 414, 427, 444,
|
||||
927, 911, 937, 975, 147, 191, 62, 63, 67, 69, 158, 167, 185, 404, 418, 442,
|
||||
451, 934, 935, 955, 980, 159, 416, 143, 141, 144, 152, 166, 182, 196, 415, 431,
|
||||
447, 921, 959, 948, 969, 999, 168, 438, 171, 164, 170, 178, 194, 197, 408, 420,
|
||||
440, 908, 932, 964, 966, 989, 1000, 173, 943, 402, 189, 188, 398, 407, 410, 419,
|
||||
433, 909, 920, 951, 979, 977, 987, 2013, 180, 990, 425, 411, 412, 417, 426, 429,
|
||||
435, 907, 946, 952, 974, 993, 992, 2002, 2021, 183, 2019, 443, 424, 422, 432, 434,
|
||||
439, 923, 922, 954, 949, 982, 2007, 996, 2008, 2026, 186, 2024, 928, 445, 436, 906,
|
||||
452, 914, 938, 944, 956, 983, 2004, 2012, 2011, 2005, 2032, 193, 2043, 968, 931, 917,
|
||||
925, 940, 942, 965, 984, 994, 998, 2020, 2023, 2016, 2025, 2039, 400, 2034, 915, 446,
|
||||
448, 916, 919, 941, 963, 961, 978, 2010, 2009, 2015, 2027, 2036, 2042, 405, 2040, 957,
|
||||
924, 939, 936, 947, 953, 976, 995, 997, 2018, 2014, 2029, 2033, 2041, 2044, 403, 4093,
|
||||
988, 950, 967, 972, 971, 985, 986, 2003, 2017, 2030, 2031, 2037, 2038, 4092, 4095, 413,
|
||||
450, 181, 161, 150, 151, 149, 153, 160, 162, 172, 169, 177, 179, 187, 192, 399,
|
||||
4,
|
||||
},
|
||||
}
|
||||
|
||||
Tables.SPEC_BITS = {
|
||||
{
|
||||
11, 9, 11, 10, 7, 10, 11, 9, 11, 10, 7, 10, 7, 5, 7, 9, 7, 10, 11, 9, 11, 9, 7, 9, 11, 9, 11, 9, 7, 9,
|
||||
7, 5, 7, 9, 7, 9, 7, 5, 7, 5, 1, 5, 7, 5, 7, 9, 7, 9, 7, 5, 7, 9, 7, 9, 11, 9, 11, 9, 7, 9,
|
||||
11, 9, 11, 10, 7, 9, 7, 5, 7, 9, 7, 10, 11, 9, 11, 10, 7, 9, 11, 9, 11,
|
||||
},
|
||||
{
|
||||
9, 7, 9, 8, 6, 8, 9, 8, 9, 8, 6, 7, 6, 5, 6, 7, 6, 8, 9, 7, 8, 8, 6, 8, 9, 7, 9, 8, 6, 7,
|
||||
6, 5, 6, 7, 6, 8, 6, 5, 6, 5, 3, 5, 6, 5, 6, 8, 6, 7, 6, 5, 6, 8, 6, 8, 9, 7, 9, 8, 6, 8,
|
||||
8, 7, 9, 8, 6, 7, 6, 4, 6, 8, 6, 7, 9, 7, 9, 7, 6, 8, 9, 7, 9,
|
||||
},
|
||||
{
|
||||
1, 4, 8, 4, 5, 8, 9, 9, 10, 4, 6, 9, 6, 6, 9, 9, 9, 10, 9, 10, 13, 9, 9, 11, 11, 10, 12, 4, 6, 10,
|
||||
6, 7, 10, 10, 10, 12, 5, 7, 11, 6, 7, 10, 9, 9, 11, 9, 10, 13, 8, 9, 12, 10, 11, 12, 8, 10, 15, 9, 11, 15,
|
||||
13, 14, 16, 8, 10, 14, 9, 10, 14, 12, 12, 15, 11, 12, 16, 10, 11, 15, 12, 12, 15,
|
||||
},
|
||||
{
|
||||
4, 5, 8, 5, 4, 8, 9, 8, 11, 5, 5, 8, 5, 4, 8, 8, 7, 10, 9, 8, 11, 8, 8, 10, 11, 10, 11, 4, 5, 8,
|
||||
4, 4, 8, 8, 8, 10, 4, 4, 8, 4, 4, 7, 8, 7, 9, 8, 8, 10, 7, 7, 9, 10, 9, 10, 8, 8, 11, 8, 7, 10,
|
||||
11, 10, 12, 8, 7, 10, 7, 7, 9, 10, 9, 11, 11, 10, 12, 10, 9, 11, 11, 10, 11,
|
||||
},
|
||||
{
|
||||
13, 12, 11, 11, 10, 11, 11, 12, 13, 12, 11, 10, 9, 8, 9, 10, 11, 12, 12, 10, 9, 8, 7, 8, 9, 10, 11, 11, 9, 8,
|
||||
5, 4, 5, 8, 9, 11, 10, 8, 7, 4, 1, 4, 7, 8, 11, 11, 9, 8, 5, 4, 5, 8, 9, 11, 11, 10, 9, 8, 7, 8,
|
||||
9, 10, 11, 12, 11, 10, 9, 8, 9, 10, 11, 12, 13, 12, 12, 11, 10, 10, 11, 12, 13,
|
||||
},
|
||||
{
|
||||
11, 10, 9, 9, 9, 9, 9, 10, 11, 10, 9, 8, 7, 7, 7, 8, 9, 10, 9, 8, 6, 6, 6, 6, 6, 8, 9, 9, 7, 6,
|
||||
4, 4, 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 8, 6, 6, 6, 6,
|
||||
6, 8, 9, 10, 9, 8, 7, 7, 7, 7, 8, 10, 11, 10, 9, 9, 9, 9, 9, 10, 11,
|
||||
},
|
||||
{
|
||||
1, 3, 6, 7, 8, 9, 10, 11, 3, 4, 6, 7, 8, 8, 9, 9, 6, 6, 7, 8, 8, 9, 9, 10, 7, 7, 8, 8, 9, 9,
|
||||
10, 10, 8, 8, 9, 9, 10, 10, 10, 11, 9, 8, 9, 9, 10, 10, 11, 11, 10, 9, 9, 10, 10, 11, 12, 12, 11, 10, 10, 10,
|
||||
11, 11, 12, 12,
|
||||
},
|
||||
{
|
||||
5, 4, 5, 6, 7, 8, 9, 10, 4, 3, 4, 5, 6, 7, 7, 8, 5, 4, 4, 5, 6, 7, 7, 8, 6, 5, 5, 6, 6, 7,
|
||||
8, 8, 7, 6, 6, 6, 7, 7, 8, 9, 8, 7, 6, 7, 7, 8, 8, 10, 9, 7, 7, 8, 8, 8, 9, 9, 10, 8, 8, 8,
|
||||
9, 9, 9, 10,
|
||||
},
|
||||
{
|
||||
1, 3, 6, 8, 9, 10, 10, 11, 11, 12, 12, 13, 13, 3, 4, 6, 7, 8, 8, 9, 10, 10, 10, 11, 12, 12, 6, 6, 7, 8,
|
||||
8, 9, 10, 10, 10, 11, 12, 12, 12, 8, 7, 8, 9, 9, 10, 10, 11, 11, 11, 12, 12, 13, 9, 8, 9, 9, 10, 10, 11, 11,
|
||||
11, 12, 12, 12, 13, 10, 9, 9, 10, 11, 11, 11, 12, 11, 12, 12, 13, 13, 11, 9, 10, 11, 11, 11, 12, 12, 12, 12, 13, 13,
|
||||
13, 11, 10, 10, 11, 11, 12, 12, 13, 13, 13, 13, 13, 13, 11, 10, 10, 11, 11, 11, 12, 12, 13, 13, 14, 13, 14, 11, 10, 11,
|
||||
11, 12, 12, 12, 12, 13, 13, 14, 14, 14, 12, 11, 11, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 12, 11, 12, 12, 12, 13, 13,
|
||||
13, 13, 14, 14, 15, 15, 13, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15,
|
||||
},
|
||||
{
|
||||
6, 5, 6, 6, 7, 8, 9, 10, 10, 10, 11, 11, 12, 5, 4, 4, 5, 6, 7, 7, 8, 8, 9, 10, 10, 11, 6, 4, 5, 5,
|
||||
6, 6, 7, 8, 8, 9, 9, 10, 10, 6, 5, 5, 5, 6, 7, 7, 8, 8, 9, 9, 10, 10, 7, 6, 6, 6, 6, 7, 7, 8,
|
||||
8, 9, 9, 10, 10, 8, 7, 6, 7, 7, 7, 8, 8, 8, 9, 10, 10, 11, 9, 7, 7, 7, 7, 8, 8, 9, 9, 9, 10, 10,
|
||||
11, 9, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 9, 8, 8, 8, 8, 8, 9, 9, 10, 10, 10, 11, 11, 10, 9, 9,
|
||||
9, 9, 9, 9, 10, 10, 10, 11, 11, 12, 10, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 12, 11, 10, 9, 10, 10, 10, 10,
|
||||
10, 11, 11, 11, 11, 12, 11, 10, 10, 10, 10, 10, 10, 11, 11, 12, 12, 12, 12,
|
||||
},
|
||||
{
|
||||
4, 5, 6, 7, 8, 8, 9, 10, 10, 10, 11, 11, 12, 11, 12, 12, 10, 5, 4, 5, 6, 7, 7, 8, 8, 9, 9, 9, 10, 10,
|
||||
10, 10, 11, 8, 6, 5, 5, 6, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 7, 6, 6, 6, 7, 7, 8, 8, 8,
|
||||
9, 9, 9, 10, 10, 10, 10, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 8, 7, 7, 7, 7,
|
||||
8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 8, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 10, 8, 9,
|
||||
8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 10, 10, 8, 10, 9, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10,
|
||||
10, 11, 8, 10, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 8, 11, 9, 9, 9, 9, 9, 9, 10, 10, 10,
|
||||
10, 10, 11, 10, 11, 11, 8, 11, 10, 9, 9, 10, 9, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 8, 11, 10, 10, 10, 10, 10,
|
||||
10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 9, 11, 10, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 11, 10,
|
||||
10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 12, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 12,
|
||||
12, 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 5,
|
||||
},
|
||||
}
|
||||
|
||||
Tables.SWB_LONG = {
|
||||
{
|
||||
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96,
|
||||
108, 120, 132, 144, 156, 172, 188, 212, 240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896,
|
||||
960, 1024,
|
||||
},
|
||||
{
|
||||
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96,
|
||||
108, 120, 132, 144, 156, 172, 188, 212, 240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896,
|
||||
960, 1024,
|
||||
},
|
||||
{
|
||||
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 100,
|
||||
112, 124, 140, 156, 172, 192, 216, 240, 268, 304, 344, 384, 424, 464, 504, 544, 584, 624, 664, 704,
|
||||
744, 784, 824, 864, 904, 944, 984, 1024,
|
||||
},
|
||||
{
|
||||
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120,
|
||||
132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640,
|
||||
672, 704, 736, 768, 800, 832, 864, 896, 928, 1024,
|
||||
},
|
||||
{
|
||||
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120,
|
||||
132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640,
|
||||
672, 704, 736, 768, 800, 832, 864, 896, 928, 1024,
|
||||
},
|
||||
{
|
||||
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120,
|
||||
132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640,
|
||||
672, 704, 736, 768, 800, 832, 864, 896, 928, 960, 992, 1024,
|
||||
},
|
||||
{
|
||||
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, 84, 92, 100, 108,
|
||||
116, 124, 136, 148, 160, 172, 188, 204, 220, 240, 260, 284, 308, 336, 364, 396, 432, 468, 508, 552,
|
||||
600, 652, 704, 768, 832, 896, 960, 1024,
|
||||
},
|
||||
{
|
||||
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, 84, 92, 100, 108,
|
||||
116, 124, 136, 148, 160, 172, 188, 204, 220, 240, 260, 284, 308, 336, 364, 396, 432, 468, 508, 552,
|
||||
600, 652, 704, 768, 832, 896, 960, 1024,
|
||||
},
|
||||
{
|
||||
0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184,
|
||||
196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772,
|
||||
832, 896, 960, 1024,
|
||||
},
|
||||
{
|
||||
0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184,
|
||||
196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772,
|
||||
832, 896, 960, 1024,
|
||||
},
|
||||
{
|
||||
0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184,
|
||||
196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772,
|
||||
832, 896, 960, 1024,
|
||||
},
|
||||
{
|
||||
0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188, 204, 220, 236, 252,
|
||||
268, 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544, 580, 620, 664, 712, 764, 820, 880, 944,
|
||||
1024,
|
||||
},
|
||||
{
|
||||
0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188, 204, 220, 236, 252,
|
||||
268, 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544, 580, 620, 664, 712, 764, 820, 880, 944,
|
||||
1024,
|
||||
},
|
||||
}
|
||||
|
||||
Tables.SWB_SHORT = {
|
||||
{
|
||||
0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128,
|
||||
},
|
||||
{
|
||||
0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128,
|
||||
},
|
||||
{
|
||||
0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128,
|
||||
},
|
||||
{
|
||||
0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128,
|
||||
},
|
||||
{
|
||||
0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128,
|
||||
},
|
||||
{
|
||||
0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128,
|
||||
},
|
||||
{
|
||||
0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128,
|
||||
},
|
||||
{
|
||||
0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128,
|
||||
},
|
||||
{
|
||||
0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128,
|
||||
},
|
||||
{
|
||||
0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128,
|
||||
},
|
||||
{
|
||||
0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128,
|
||||
},
|
||||
{
|
||||
0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 60, 72, 88, 108, 128,
|
||||
},
|
||||
{
|
||||
0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 60, 72, 88, 108, 128,
|
||||
},
|
||||
}
|
||||
|
||||
Tables.NUM_SWB_LONG = {
|
||||
41, 41, 47, 49, 49, 51, 47, 47, 43, 43, 43, 40, 40,
|
||||
}
|
||||
|
||||
Tables.NUM_SWB_SHORT = {
|
||||
12, 12, 12, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15,
|
||||
}
|
||||
|
||||
Tables.TNS_MAX_BANDS_LONG = {
|
||||
31, 31, 34, 40, 42, 51, 46, 46, 42, 42, 42, 39, 39,
|
||||
}
|
||||
|
||||
Tables.TNS_MAX_BANDS_SHORT = {
|
||||
9, 9, 10, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
|
||||
}
|
||||
|
||||
return Tables
|
||||
|
||||
@@ -0,0 +1,336 @@
|
||||
--!strict
|
||||
-- codecs/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program
|
||||
-- config element, explicit and backward-compatible SBR signalling), ADTS headers, and raw_data_block decoding
|
||||
-- (codecs/Aac/Decode). A codec (layer 1): audio/m4a, audio/aac (ADTS), and later MP4 / MKV / MPEG-TS video build on it.
|
||||
-- Written from the standard (tables: codecs/Aac/Tables); no third-party code.
|
||||
-- Supports: AAC-LC (object type 2) 1 - 8 channels, all sampling rates, long / short / start / stop windows, sine and KBD
|
||||
-- windows, M/S, intensity stereo, PNS, TNS, pulses. HE-AAC (SBR, PS: object types 5 / 29, or implicit SBR payloads)
|
||||
-- decodes its AAC-LC core at the core rate; `decoder.onExtension` receives every FIL extension payload (the hook for a
|
||||
-- later SBR / PS module), `decoder.sbr` says whether one was seen. Not supported: AAC Main prediction, LTP, SSR gain
|
||||
-- control, coupling channels, 960-sample frames, ER / USAC object types (UNSUPPORTED).
|
||||
--
|
||||
-- local Aac = require("@formats/codecs/Aac")
|
||||
-- local dec, err = Aac.decoder(asc) -- an AudioSpecificConfig (buffer) or { objectType, sfIndex, channels }
|
||||
-- local frames, err = dec:decode(buf, offset, length) -- one raw_data_block -> dec.pcm (frames * channels floats)
|
||||
-- local h = Aac.adts(buf, offset, limit) -- an ADTS header: { headerSize, frameSize, objectType, sfIndex, ... }
|
||||
--
|
||||
-- Never throws: bad data returns nil, Err.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bits = require("@formats/core/Bits")
|
||||
local Decode = require("@formats/codecs/Aac/Decode")
|
||||
|
||||
local Aac = {}
|
||||
|
||||
Aac.RATES = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 }
|
||||
local CONFIG_CHANNELS = { 1, 2, 3, 4, 5, 6, 8 }
|
||||
-- element order (AAC: C, L, R, ...) -> WAV order (L, R, C, LFE, ...) for channel configurations 3 .. 7
|
||||
local CONFIG_MAP: { [number]: { number } } = {
|
||||
[3] = { 3, 1, 2 },
|
||||
[4] = { 3, 1, 2, 4 },
|
||||
[5] = { 3, 1, 2, 4, 5 },
|
||||
[6] = { 3, 1, 2, 5, 6, 4 },
|
||||
[7] = { 3, 7, 8, 1, 2, 5, 6, 4 },
|
||||
}
|
||||
|
||||
export type Config = {
|
||||
objectType: number, -- 2 = AAC-LC (the core object type when SBR / PS is signalled)
|
||||
sfIndex: number,
|
||||
sampleRate: number, -- the core rate
|
||||
channelConfig: number,
|
||||
channels: number,
|
||||
sbr: boolean, -- SBR signalled (explicitly or backward-compatibly)
|
||||
ps: boolean,
|
||||
extensionRate: number?, -- the SBR output rate
|
||||
frameLength: number,
|
||||
}
|
||||
|
||||
local function rateIndex(rate: number): number
|
||||
-- the nearest standard rate (ISO 14496-3 table 4.82 mapping for explicit frequencies)
|
||||
local best, bi = math.huge, 4
|
||||
for i, r in Aac.RATES do
|
||||
if math.abs(r - rate) < best then
|
||||
best, bi = math.abs(r - rate), i - 1
|
||||
end
|
||||
end
|
||||
return bi
|
||||
end
|
||||
|
||||
local function objectType(br: Bits.BitReader): number
|
||||
local t = br:read(5)
|
||||
if t == 31 then
|
||||
t = 32 + br:read(6)
|
||||
end
|
||||
return t
|
||||
end
|
||||
|
||||
local function frequency(br: Bits.BitReader): (number, number)
|
||||
local i = br:read(4)
|
||||
if i == 15 then
|
||||
local f = br:read(24)
|
||||
return rateIndex(f), f
|
||||
end
|
||||
return i, Aac.RATES[i + 1] or 0
|
||||
end
|
||||
|
||||
-- pce(br) -> channels (program_config_element)
|
||||
local function pce(br: Bits.BitReader): number
|
||||
br:read(4 + 2 + 4)
|
||||
local front, side, back = br:read(4), br:read(4), br:read(4)
|
||||
local lfe, assoc, cc = br:read(2), br:read(3), br:read(4)
|
||||
if br:read(1) == 1 then
|
||||
br:read(4)
|
||||
end
|
||||
if br:read(1) == 1 then
|
||||
br:read(4)
|
||||
end
|
||||
if br:read(1) == 1 then
|
||||
br:read(3)
|
||||
end
|
||||
local channels = 0
|
||||
for _ = 1, front + side + back do
|
||||
channels += if br:read(1) == 1 then 2 else 1
|
||||
br:read(4)
|
||||
end
|
||||
channels += lfe
|
||||
br:skip(lfe * 4 + assoc * 4 + cc * 5)
|
||||
br:align()
|
||||
br:skip(br:read(8) * 8)
|
||||
return channels
|
||||
end
|
||||
|
||||
-- config(asc) -> Config | nil, Err: parse an AudioSpecificConfig
|
||||
function Aac.config(asc: buffer): (Config?, Err.Err?)
|
||||
if type(asc) ~= "buffer" or buffer.len(asc) < 2 then
|
||||
return nil, Err.new(Err.TRUNCATED, "AudioSpecificConfig is shorter than 2 bytes")
|
||||
end
|
||||
local br = Bits.msbReader(asc)
|
||||
local aot = objectType(br)
|
||||
local sfi, rate = frequency(br)
|
||||
local chcfg = br:read(4)
|
||||
local sbr, ps = false, false
|
||||
local extRate: number? = nil
|
||||
if aot == 5 or aot == 29 then
|
||||
sbr = true
|
||||
ps = aot == 29
|
||||
local _, er = frequency(br)
|
||||
extRate = er
|
||||
aot = objectType(br)
|
||||
if aot == 22 then
|
||||
br:read(4)
|
||||
end
|
||||
end
|
||||
if aot ~= 2 and aot ~= 1 and aot ~= 4 then
|
||||
if aot == 0 or br.err then
|
||||
return nil, Err.new(Err.CORRUPT, "bad AudioSpecificConfig")
|
||||
end
|
||||
return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. aot .. " (only AAC-LC)")
|
||||
end
|
||||
if aot ~= 2 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, if aot == 1 then "AAC Main" else "AAC LTP")
|
||||
end
|
||||
-- GASpecificConfig
|
||||
local frameLengthFlag = br:read(1)
|
||||
if br:read(1) == 1 then
|
||||
br:read(14)
|
||||
end
|
||||
local ext = br:read(1)
|
||||
local channels = CONFIG_CHANNELS[chcfg] or 0
|
||||
if chcfg == 0 then
|
||||
channels = pce(br)
|
||||
elseif chcfg > 7 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "channel configuration " .. chcfg)
|
||||
end
|
||||
if ext == 1 then
|
||||
br:read(1) -- extensionFlag3
|
||||
end
|
||||
-- backward-compatible SBR signalling
|
||||
if not sbr and br:bitsLeft() >= 16 then
|
||||
if br:read(11) == 0x2b7 then
|
||||
local et = objectType(br)
|
||||
if et == 5 and br:read(1) == 1 then
|
||||
sbr = true
|
||||
local _, er = frequency(br)
|
||||
extRate = er
|
||||
if br:bitsLeft() >= 12 and br:read(11) == 0x548 then
|
||||
ps = br:read(1) == 1
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if br.err and channels == 0 then
|
||||
return nil, br.err
|
||||
end
|
||||
if sfi > 12 or rate <= 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad sampling frequency index " .. sfi)
|
||||
end
|
||||
if frameLengthFlag == 1 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "960-sample AAC frames")
|
||||
end
|
||||
if channels < 1 or channels > 8 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, channels .. " channels")
|
||||
end
|
||||
return {
|
||||
objectType = aot,
|
||||
sfIndex = sfi,
|
||||
sampleRate = rate,
|
||||
channelConfig = chcfg,
|
||||
channels = channels,
|
||||
sbr = sbr,
|
||||
ps = ps,
|
||||
extensionRate = extRate,
|
||||
frameLength = 1024,
|
||||
}, nil
|
||||
end
|
||||
|
||||
-- asc(objectType, sfIndex, channelConfig) -> a 2-byte AudioSpecificConfig
|
||||
function Aac.asc(aot: number, sfIndex: number, channelConfig: number): buffer
|
||||
local b = buffer.create(2)
|
||||
local v = aot * 2048 + sfIndex * 128 + channelConfig * 8
|
||||
buffer.writeu8(b, 0, bit32.rshift(v, 8))
|
||||
buffer.writeu8(b, 1, bit32.band(v, 255))
|
||||
return b
|
||||
end
|
||||
|
||||
export type Adts = {
|
||||
headerSize: number, -- 7, or 9 with a CRC
|
||||
frameSize: number, -- the whole frame, header included
|
||||
objectType: number,
|
||||
sfIndex: number,
|
||||
sampleRate: number,
|
||||
channelConfig: number,
|
||||
blocks: number, -- raw_data_blocks in the frame (1 .. 4)
|
||||
protected: boolean,
|
||||
}
|
||||
|
||||
-- adts(buf, offset, limit) -> Adts | nil (not a valid header at offset)
|
||||
function Aac.adts(b: buffer, o: number, limit: number): Adts?
|
||||
if o < 0 or o + 7 > limit or o + 7 > buffer.len(b) then
|
||||
return nil
|
||||
end
|
||||
local b0, b1, b2, b3, b4, b5, b6 = buffer.readu8(b, o), buffer.readu8(b, o + 1), buffer.readu8(b, o + 2), buffer.readu8(b, o + 3), buffer.readu8(b, o + 4), buffer.readu8(b, o + 5), buffer.readu8(b, o + 6)
|
||||
if b0 ~= 0xFF or bit32.band(b1, 0xF6) ~= 0xF0 then -- sync, layer 0
|
||||
return nil
|
||||
end
|
||||
local protected = bit32.band(b1, 1) == 0
|
||||
local profile = bit32.rshift(b2, 6)
|
||||
local sfi = bit32.band(bit32.rshift(b2, 2), 15)
|
||||
local ch = bit32.band(b2, 1) * 4 + bit32.rshift(b3, 6)
|
||||
local size = bit32.band(b3, 3) * 2048 + b4 * 8 + bit32.rshift(b5, 5)
|
||||
local blocks = bit32.band(b6, 3) + 1
|
||||
local hs = if protected then 9 else 7
|
||||
if sfi > 12 or size < hs then
|
||||
return nil
|
||||
end
|
||||
return {
|
||||
headerSize = hs,
|
||||
frameSize = size,
|
||||
objectType = profile + 1,
|
||||
sfIndex = sfi,
|
||||
sampleRate = Aac.RATES[sfi + 1],
|
||||
channelConfig = ch,
|
||||
blocks = blocks,
|
||||
protected = protected,
|
||||
}
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decoder
|
||||
export type Decoder = {
|
||||
config: Config,
|
||||
channels: number,
|
||||
sampleRate: number,
|
||||
frameLength: number,
|
||||
pcm: { number }, -- the last frame: 1024 * channels interleaved floats (-1 .. 1), WAV channel order
|
||||
sbr: boolean, -- SBR payloads seen in the stream (implicit signalling) or signalled
|
||||
onExtension: ((kind: number, element: number, buf: buffer, bitPos: number, bits: number) -> ())?,
|
||||
decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?),
|
||||
reset: (self: Decoder) -> (),
|
||||
state: Decode.State,
|
||||
}
|
||||
|
||||
local function decode(self: Decoder, buf: buffer, offset: number?, length: number?): (number?, Err.Err?)
|
||||
local o = offset or 0
|
||||
local n = length or (buffer.len(buf) - o)
|
||||
if type(buf) ~= "buffer" or o < 0 or n < 0 or o + n > buffer.len(buf) then
|
||||
return nil, Err.new(Err.ARG, "packet range out of the buffer")
|
||||
end
|
||||
local st = self.state
|
||||
st.onExtension = self.onExtension
|
||||
local chans, msg = Decode.frame(st, buf, o, n)
|
||||
if not chans then
|
||||
return nil, Err.new(Err.CORRUPT, msg or "bad frame", o)
|
||||
end
|
||||
if st.sbr then
|
||||
self.sbr = true
|
||||
end
|
||||
if chans == 0 then
|
||||
-- an empty frame (only fill elements): silence
|
||||
for i = 1, 1024 * self.channels do
|
||||
st.pcm[i] = 0
|
||||
end
|
||||
return 1024, nil
|
||||
end
|
||||
if chans ~= self.channels then
|
||||
return nil, Err.new(Err.CORRUPT, string.format("frame has %d channels, the configuration %d", chans, self.channels), o)
|
||||
end
|
||||
return 1024, nil
|
||||
end
|
||||
|
||||
local function reset(self: Decoder)
|
||||
for _, c in self.state.ch do
|
||||
for i = 1, 1024 do
|
||||
c.overlap[i] = 0
|
||||
end
|
||||
c.prevShape = 0
|
||||
end
|
||||
end
|
||||
|
||||
-- decoder(asc | { objectType?, sfIndex, channels }) -> Decoder | nil, Err
|
||||
function Aac.decoder(asc: any): (Decoder?, Err.Err?)
|
||||
local cfg: Config
|
||||
if type(asc) == "buffer" then
|
||||
local c, err = Aac.config(asc)
|
||||
if not c then
|
||||
return nil, err
|
||||
end
|
||||
cfg = c
|
||||
elseif type(asc) == "table" and type(asc.sfIndex) == "number" and type(asc.channels) == "number" then
|
||||
local sfi = asc.sfIndex
|
||||
if sfi < 0 or sfi > 12 or asc.channels < 1 or asc.channels > 8 then
|
||||
return nil, Err.new(Err.ARG, "bad sampling index / channels")
|
||||
end
|
||||
if (asc.objectType or 2) ~= 2 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. asc.objectType .. " (only AAC-LC)")
|
||||
end
|
||||
cfg = {
|
||||
objectType = 2,
|
||||
sfIndex = sfi,
|
||||
sampleRate = Aac.RATES[sfi + 1],
|
||||
channelConfig = asc.channelConfig or asc.channels,
|
||||
channels = asc.channels,
|
||||
sbr = false,
|
||||
ps = false,
|
||||
frameLength = 1024,
|
||||
}
|
||||
else
|
||||
return nil, Err.new(Err.ARG, "decoder: expected an AudioSpecificConfig buffer")
|
||||
end
|
||||
local st = Decode.state(cfg.sfIndex)
|
||||
st.channels = cfg.channels
|
||||
if cfg.channelConfig >= 3 then
|
||||
st.map = CONFIG_MAP[cfg.channelConfig]
|
||||
end
|
||||
return {
|
||||
config = cfg,
|
||||
channels = cfg.channels,
|
||||
sampleRate = cfg.sampleRate,
|
||||
frameLength = 1024,
|
||||
pcm = st.pcm,
|
||||
sbr = cfg.sbr,
|
||||
onExtension = nil,
|
||||
decode = decode,
|
||||
reset = reset,
|
||||
state = st,
|
||||
}, nil
|
||||
end
|
||||
|
||||
return Aac
|
||||
@@ -0,0 +1,427 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/Alac/Decode: the ALAC frame decoder: elements SCE / CPE / LFE / DSE / FIL / END, the adaptive Golomb-Rice
|
||||
-- residuals with zero runs, the adaptive FIR predictor (orders 0, 31 and 1 .. 30), stereo unmixing, shifted low bytes,
|
||||
-- uncompressed (escape) frames, 16 / 20 / 24 / 32-bit samples. Written from the ALAC format as published by Apple
|
||||
-- (ALACDecoder / ag_dec / dp_dec, Apache 2.0; behaviour, not code). Never throws: returns nil, message.
|
||||
local readu32, readu8 = buffer.readu32, buffer.readu8
|
||||
local byteswap, lshift, rshift, band, countlz, bnot = bit32.byteswap, bit32.lshift, bit32.rshift, bit32.band, bit32.countlz, bit32.bnot
|
||||
local floor = math.floor
|
||||
|
||||
local Decode = {}
|
||||
|
||||
export type State = {
|
||||
frameLength: number,
|
||||
bitDepth: number,
|
||||
pb: number,
|
||||
mb: number,
|
||||
kb: number,
|
||||
channels: number,
|
||||
maxRun: number,
|
||||
scratch: buffer, -- the packet + 16 zero bytes (reads past the end are safe; the overrun is checked)
|
||||
pred: { { number } }, -- per element channel (0, 1): residuals / predictor output
|
||||
mix: { { number } },
|
||||
shift: { number },
|
||||
out: { number }, -- interleaved output samples (integers), frames * channels
|
||||
}
|
||||
|
||||
local POW = table.create(64, 0)
|
||||
for i = 0, 63 do
|
||||
POW[i + 1] = 2 ^ i
|
||||
end
|
||||
|
||||
-- bit reader over st.scratch: pos = bit position. bits(n) for n <= 25.
|
||||
local function bitsAt(b: buffer, pos: number, n: number): number
|
||||
local w = byteswap(readu32(b, rshift(pos, 3)))
|
||||
return rshift(lshift(w, band(pos, 7)), 32 - n)
|
||||
end
|
||||
|
||||
local function signExtend(v: number, bits: number): number
|
||||
local m = POW[bits + 1]
|
||||
v = v % m
|
||||
if v >= m / 2 then
|
||||
v -= m
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
-- the adaptive Golomb-Rice value: unary prefix (escape after 9 ones: `bps` raw bits), then k bits
|
||||
local function scalar(b: buffer, pos: number, k: number, m: number, bps: number): (number, number)
|
||||
local w = lshift(byteswap(readu32(b, rshift(pos, 3))), band(pos, 7))
|
||||
local pre = countlz(bnot(w))
|
||||
if pre >= 9 then
|
||||
pos += 9
|
||||
local v
|
||||
if bps > 25 then
|
||||
v = bitsAt(b, pos, bps - 16) * 65536 + bitsAt(b, pos + bps - 16, 16)
|
||||
else
|
||||
v = bitsAt(b, pos, bps)
|
||||
end
|
||||
return v, pos + bps
|
||||
end
|
||||
pos += pre + 1
|
||||
if k == 1 then
|
||||
return pre, pos
|
||||
end
|
||||
local v = bitsAt(b, pos, k)
|
||||
local x = pre * m
|
||||
if v > 1 then
|
||||
return x + v - 1, pos + k
|
||||
end
|
||||
return x, pos + k - 1
|
||||
end
|
||||
|
||||
-- residuals: n values into out[1..n]; returns the new bit position or -1
|
||||
local function rice(b: buffer, pos: number, limit: number, out: { number }, n: number, bps: number, mult: number, st: State): number
|
||||
local history = st.mb
|
||||
local kb = st.kb
|
||||
local signMod = 0
|
||||
local i = 1
|
||||
while i <= n do
|
||||
if pos > limit then
|
||||
return -1 -- each value reads at most 41 bits past here: inside the 16 padding bytes
|
||||
end
|
||||
local k = 31 - countlz(floor(history / 512) + 3)
|
||||
if k > kb then
|
||||
k = kb
|
||||
end
|
||||
local x
|
||||
x, pos = scalar(b, pos, k, POW[k + 1] - 1, bps)
|
||||
x += signMod
|
||||
signMod = 0
|
||||
out[i] = if x % 2 == 0 then x / 2 else -(x + 1) / 2
|
||||
if x > 0xFFFF then
|
||||
history = 0xFFFF
|
||||
else
|
||||
history += x * mult - floor(history * mult / 512)
|
||||
end
|
||||
if history < 128 and i < n then
|
||||
if pos > limit then
|
||||
return -1
|
||||
end
|
||||
local lg = if history > 0 then 31 - countlz(history) else 0
|
||||
k = 7 - lg + floor((history + 16) / 64)
|
||||
if k > kb then
|
||||
k = kb
|
||||
end
|
||||
local run
|
||||
run, pos = scalar(b, pos, k, POW[k + 1] - 1, 16)
|
||||
if run > 0 then
|
||||
if run > n - i then
|
||||
return -1
|
||||
end
|
||||
for j = i + 1, i + run do
|
||||
out[j] = 0
|
||||
end
|
||||
i += run
|
||||
end
|
||||
if run < 0xFFFF then
|
||||
signMod = 1 -- the next value is not 0 (unless the run hit its maximum)
|
||||
end
|
||||
history = 0
|
||||
end
|
||||
i += 1
|
||||
end
|
||||
return pos
|
||||
end
|
||||
|
||||
-- the adaptive FIR predictor: err[1..n] -> out[1..n] (may be the same array); coefs adapt in place
|
||||
local function predict(err: { number }, out: { number }, n: number, bps: number, coefs: { number }, order: number, quant: number)
|
||||
out[1] = err[1]
|
||||
if n <= 1 then
|
||||
return
|
||||
end
|
||||
if order == 0 then
|
||||
if out ~= err then
|
||||
for i = 2, n do
|
||||
out[i] = err[i]
|
||||
end
|
||||
end
|
||||
return
|
||||
end
|
||||
if order == 31 then
|
||||
for i = 2, n do
|
||||
out[i] = signExtend(out[i - 1] + err[i], bps)
|
||||
end
|
||||
return
|
||||
end
|
||||
local i = 2
|
||||
while i <= order + 1 and i <= n do
|
||||
out[i] = signExtend(out[i - 1] + err[i], bps)
|
||||
i += 1
|
||||
end
|
||||
local half = if quant > 0 then POW[quant] else 0
|
||||
local qd = POW[quant + 1]
|
||||
-- coefs[1] multiplies the most recent sample
|
||||
while i <= n do
|
||||
local d = out[i - order - 1]
|
||||
local val = 0
|
||||
for j = 1, order do
|
||||
val += (out[i - j] - d) * coefs[j]
|
||||
end
|
||||
val = floor((val + half) / qd)
|
||||
local e = err[i]
|
||||
out[i] = signExtend(val + d + e, bps)
|
||||
if e ~= 0 then
|
||||
local es = if e > 0 then 1 else -1
|
||||
-- adapt from the oldest sample to the newest while the error keeps its sign
|
||||
for j = order, 1, -1 do
|
||||
if e * es <= 0 then
|
||||
break
|
||||
end
|
||||
local v = d - out[i - j]
|
||||
local sgn = if v > 0 then es elseif v < 0 then -es else 0
|
||||
coefs[j] -= sgn
|
||||
e -= floor(v * sgn / qd) * (order - j + 1)
|
||||
end
|
||||
end
|
||||
i += 1
|
||||
end
|
||||
end
|
||||
|
||||
-- decode(st, buf, off, len) -> frames | nil, message. Samples land interleaved in st.out (integers), channels in the
|
||||
-- ALAC element order.
|
||||
function Decode.frame(st: State, buf: buffer, off: number, len: number): (number?, string?)
|
||||
if len <= 0 then
|
||||
return nil, "empty packet"
|
||||
end
|
||||
local b = st.scratch
|
||||
if buffer.len(b) < len + 16 then
|
||||
b = buffer.create(len + 64)
|
||||
st.scratch = b
|
||||
end
|
||||
buffer.copy(b, 0, buf, off, len)
|
||||
buffer.fill(b, len, 0, 16)
|
||||
local limit = len * 8
|
||||
local pos = 0
|
||||
local channels = st.channels
|
||||
local ch = 0 -- next output channel
|
||||
local frames = -1
|
||||
local out = st.out
|
||||
while true do
|
||||
if pos + 3 > limit then
|
||||
return nil, "frame runs past the end"
|
||||
end
|
||||
local tag = bitsAt(b, pos, 3)
|
||||
pos += 3
|
||||
if tag == 7 then -- END
|
||||
break
|
||||
elseif tag == 0 or tag == 1 or tag == 3 then -- SCE / CPE / LFE
|
||||
local nch = if tag == 1 then 2 else 1
|
||||
if ch + nch > channels then
|
||||
return nil, "more channels than the configuration"
|
||||
end
|
||||
pos += 4 -- element instance tag
|
||||
if bitsAt(b, pos, 12) ~= 0 then
|
||||
return nil, "bad element header"
|
||||
end
|
||||
pos += 12
|
||||
local h = bitsAt(b, pos, 4)
|
||||
pos += 4
|
||||
local partial = rshift(h, 3)
|
||||
local shiftBytes = band(rshift(h, 1), 3)
|
||||
local escape = band(h, 1)
|
||||
if shiftBytes == 3 then
|
||||
return nil, "bad shift"
|
||||
end
|
||||
local n = st.frameLength
|
||||
if partial == 1 then
|
||||
n = bitsAt(b, pos, 16) * 65536 + bitsAt(b, pos + 16, 16)
|
||||
pos += 32
|
||||
end
|
||||
if n < 1 or n > st.frameLength then
|
||||
return nil, "bad frame length " .. n
|
||||
end
|
||||
if frames >= 0 and n ~= frames then
|
||||
return nil, "elements of different lengths"
|
||||
end
|
||||
frames = n
|
||||
if #out < n * channels then
|
||||
for k = #out + 1, n * channels do
|
||||
out[k] = 0
|
||||
end
|
||||
end
|
||||
local shift = shiftBytes * 8
|
||||
local bps = st.bitDepth - shift + nch - 1
|
||||
if bps > 32 or bps < 1 then
|
||||
return nil, "bad sample size"
|
||||
end
|
||||
if pos > limit then
|
||||
return nil, "frame runs past the end"
|
||||
end
|
||||
local mixBits, mixRes = 0, 0
|
||||
local p0, p1 = st.pred[1], st.pred[2]
|
||||
local m0, m1 = st.mix[1], st.mix[2]
|
||||
local shiftBuf = st.shift
|
||||
if escape == 0 then
|
||||
mixBits = bitsAt(b, pos, 8)
|
||||
mixRes = bitsAt(b, pos + 8, 8)
|
||||
pos += 16
|
||||
if mixRes >= 128 then
|
||||
mixRes -= 256
|
||||
end
|
||||
local mode, denShift, pbFactor, order = {}, {}, {}, {}
|
||||
local coefs = { {}, {} }
|
||||
for c = 1, nch do
|
||||
local x = bitsAt(b, pos, 8)
|
||||
local y = bitsAt(b, pos + 8, 8)
|
||||
pos += 16
|
||||
mode[c], denShift[c] = rshift(x, 4), band(x, 15)
|
||||
pbFactor[c], order[c] = rshift(y, 5), band(y, 31)
|
||||
if pos + order[c] * 16 > limit then
|
||||
return nil, "frame runs past the end"
|
||||
end
|
||||
for j = 1, order[c] do
|
||||
local v = bitsAt(b, pos, 16)
|
||||
pos += 16
|
||||
coefs[c][j] = if v >= 32768 then v - 65536 else v
|
||||
end
|
||||
end
|
||||
if pos > limit then
|
||||
return nil, "frame runs past the end"
|
||||
end
|
||||
local shiftPos = pos
|
||||
if shift > 0 then
|
||||
pos += shift * n * nch
|
||||
end
|
||||
for c = 1, nch do
|
||||
local p = if c == 1 then p0 else p1
|
||||
local mb = if c == 1 then m0 else m1
|
||||
pos = rice(b, pos, limit, p, n, bps, floor(st.pb * pbFactor[c] / 4), st)
|
||||
if pos < 0 or pos > limit then
|
||||
return nil, "bad residuals"
|
||||
end
|
||||
if mode[c] == 15 then
|
||||
predict(p, p, n, bps, {}, 31, 0)
|
||||
elseif mode[c] ~= 0 then
|
||||
return nil, "unknown prediction mode " .. mode[c]
|
||||
end
|
||||
predict(p, mb, n, bps, coefs[c], order[c], denShift[c])
|
||||
end
|
||||
if shift > 0 then
|
||||
local sp = shiftPos
|
||||
for i = 1, n * nch do
|
||||
shiftBuf[i] = bitsAt(b, sp, shift)
|
||||
sp += shift
|
||||
end
|
||||
end
|
||||
else
|
||||
-- uncompressed: interleaved samples of bitDepth bits
|
||||
local bits = st.bitDepth
|
||||
if pos + n * nch * bits > limit then
|
||||
return nil, "frame runs past the end"
|
||||
end
|
||||
for i = 1, n do
|
||||
for c = 1, nch do
|
||||
local v
|
||||
if bits > 25 then
|
||||
v = bitsAt(b, pos, bits - 16) * 65536 + bitsAt(b, pos + bits - 16, 16)
|
||||
else
|
||||
v = bitsAt(b, pos, bits)
|
||||
end
|
||||
pos += bits
|
||||
v = signExtend(v, bits)
|
||||
if c == 1 then
|
||||
m0[i] = v
|
||||
else
|
||||
m1[i] = v
|
||||
end
|
||||
end
|
||||
end
|
||||
shift = 0
|
||||
end
|
||||
-- unmix + shifted bytes -> interleaved output
|
||||
local sm = POW[shift + 1]
|
||||
if nch == 2 then
|
||||
local den = POW[mixBits + 1]
|
||||
for i = 1, n do
|
||||
local u, v = m0[i], m1[i]
|
||||
local l, r
|
||||
if mixRes ~= 0 then
|
||||
l = u + v - floor(mixRes * v / den)
|
||||
r = l - v
|
||||
else
|
||||
l, r = u, v
|
||||
end
|
||||
if shift > 0 then
|
||||
l = l * sm + shiftBuf[2 * i - 1]
|
||||
r = r * sm + shiftBuf[2 * i]
|
||||
end
|
||||
local o = (i - 1) * channels + ch + 1
|
||||
out[o] = l
|
||||
out[o + 1] = r
|
||||
end
|
||||
else
|
||||
for i = 1, n do
|
||||
local v = m0[i]
|
||||
if shift > 0 then
|
||||
v = v * sm + shiftBuf[i]
|
||||
end
|
||||
out[(i - 1) * channels + ch + 1] = v
|
||||
end
|
||||
end
|
||||
ch += nch
|
||||
elseif tag == 4 then -- DSE
|
||||
pos += 4
|
||||
local align = bitsAt(b, pos, 1)
|
||||
local count = bitsAt(b, pos + 1, 8)
|
||||
pos += 9
|
||||
if count == 255 then
|
||||
count += bitsAt(b, pos, 8)
|
||||
pos += 8
|
||||
end
|
||||
if align == 1 then
|
||||
pos = (pos + 7) // 8 * 8
|
||||
end
|
||||
pos += count * 8
|
||||
elseif tag == 6 then -- FIL
|
||||
local count = bitsAt(b, pos, 4)
|
||||
pos += 4
|
||||
if count == 15 then
|
||||
count += bitsAt(b, pos, 8) - 1
|
||||
pos += 8
|
||||
end
|
||||
pos += count * 8
|
||||
else
|
||||
return nil, "unsupported element " .. tag
|
||||
end
|
||||
if pos > limit then
|
||||
return nil, "frame runs past the end"
|
||||
end
|
||||
end
|
||||
if frames < 0 then
|
||||
return 0, nil
|
||||
end
|
||||
if ch < channels then
|
||||
-- missing channels: silence
|
||||
for i = 1, frames do
|
||||
for c = ch + 1, channels do
|
||||
out[(i - 1) * channels + c] = 0
|
||||
end
|
||||
end
|
||||
end
|
||||
return frames, nil
|
||||
end
|
||||
|
||||
-- the scratch state for a configuration
|
||||
function Decode.state(cfg: any): State
|
||||
local n = cfg.frameLength
|
||||
return {
|
||||
frameLength = n,
|
||||
bitDepth = cfg.bitDepth,
|
||||
pb = cfg.pb,
|
||||
mb = cfg.mb,
|
||||
kb = cfg.kb,
|
||||
channels = cfg.channels,
|
||||
maxRun = cfg.maxRun,
|
||||
scratch = buffer.create(math.max(64, cfg.maxFrameBytes or 0) + 64),
|
||||
pred = { table.create(n, 0), table.create(n, 0) },
|
||||
mix = { table.create(n, 0), table.create(n, 0) },
|
||||
shift = table.create(n * 2, 0),
|
||||
out = table.create(n * cfg.channels, 0),
|
||||
}
|
||||
end
|
||||
|
||||
local _ = readu8
|
||||
return Decode
|
||||
@@ -0,0 +1,427 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/Alac/Encode: an ALAC frame encoder: per element (SCE / CPE) the stereo mix (mixBits 2, the best mixRes of
|
||||
-- 0 .. 4 by first-difference energy), per channel LPC coefficients (Levinson-Durbin on a windowed autocorrelation,
|
||||
-- orders 4 and 8 tried, quantised with denShift 9), residuals through the same adaptive FIR the decoder runs, the
|
||||
-- adaptive Golomb-Rice code with zero runs; an uncompressed (escape) frame when that is smaller. 16 / 20 / 24-bit
|
||||
-- input. Written for this library from the ALAC format; no third-party code. Never throws.
|
||||
local band, rshift, bor, lshift, countlz = bit32.band, bit32.rshift, bit32.bor, bit32.lshift, bit32.countlz
|
||||
local readu8, writeu8 = buffer.readu8, buffer.writeu8
|
||||
local floor, abs = math.floor, math.abs
|
||||
|
||||
local Encode = {}
|
||||
|
||||
local POW = table.create(64, 0)
|
||||
for i = 0, 63 do
|
||||
POW[i + 1] = 2 ^ i
|
||||
end
|
||||
|
||||
local DENSHIFT = 9
|
||||
local PB_FACTOR = 4
|
||||
|
||||
export type State = {
|
||||
frameLength: number,
|
||||
bitDepth: number,
|
||||
pb: number,
|
||||
mb: number,
|
||||
kb: number,
|
||||
channels: number,
|
||||
out: buffer, -- packet scratch
|
||||
pos: number, -- bit position in out
|
||||
cap: number, -- bits available
|
||||
u: { number },
|
||||
v: { number },
|
||||
err: { number },
|
||||
work: { number },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ bit writer
|
||||
local function put(st: State, v: number, n: number)
|
||||
local pos = st.pos
|
||||
if pos + n > st.cap then
|
||||
st.pos = st.cap + 1 -- overflow: the caller falls back to an uncompressed frame
|
||||
return
|
||||
end
|
||||
local b = st.out
|
||||
while n > 0 do
|
||||
local byte = rshift(pos, 3)
|
||||
local free = 8 - band(pos, 7)
|
||||
local take = if n < free then n else free
|
||||
local bits = band(rshift(v, n - take), POW[take + 1] - 1)
|
||||
writeu8(b, byte, bor(readu8(b, byte), lshift(bits, free - take)))
|
||||
pos += take
|
||||
n -= take
|
||||
end
|
||||
st.pos = pos
|
||||
end
|
||||
|
||||
local function putBig(st: State, v: number, n: number)
|
||||
if n > 24 then
|
||||
local lo = v % 65536
|
||||
put(st, (v - lo) / 65536, n - 16)
|
||||
put(st, lo, 16)
|
||||
else
|
||||
put(st, v, n)
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ rice code
|
||||
local function signExtend(v: number, bits: number): number
|
||||
local m = POW[bits + 1]
|
||||
v = v % m
|
||||
if v >= m / 2 then
|
||||
v -= m
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
-- the bits of one scalar (no writing)
|
||||
local function scalarBits(x: number, k: number, m: number, bps: number): number
|
||||
local pre = if k == 1 then x else floor(x / m)
|
||||
if pre >= 9 then
|
||||
return 9 + bps
|
||||
end
|
||||
if k == 1 then
|
||||
return pre + 1
|
||||
end
|
||||
local r = x - pre * m
|
||||
return pre + 1 + (if r == 0 then k - 1 else k)
|
||||
end
|
||||
|
||||
local function scalar(st: State, x: number, k: number, m: number, bps: number)
|
||||
local pre = if k == 1 then x else floor(x / m)
|
||||
if pre >= 9 then
|
||||
put(st, 511, 9)
|
||||
putBig(st, x, bps)
|
||||
return
|
||||
end
|
||||
-- pre ones and a zero
|
||||
put(st, POW[pre + 2] - 2, pre + 1)
|
||||
if k ~= 1 then
|
||||
local r = x - pre * m
|
||||
if r == 0 then
|
||||
put(st, 0, k - 1)
|
||||
else
|
||||
put(st, r + 1, k)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- code the residuals e[1..n] (write = false: just count the bits)
|
||||
local function rice(st: State, e: { number }, n: number, bps: number, mult: number, write: boolean): number
|
||||
local history = st.mb
|
||||
local kb = st.kb
|
||||
local signMod = 0
|
||||
local bits = 0
|
||||
local i = 1
|
||||
while i <= n do
|
||||
local k = 31 - countlz(floor(history / 512) + 3)
|
||||
if k > kb then
|
||||
k = kb
|
||||
end
|
||||
local v = e[i]
|
||||
local zz = if v >= 0 then 2 * v else -2 * v - 1
|
||||
local x = zz - signMod
|
||||
signMod = 0
|
||||
local m = POW[k + 1] - 1
|
||||
if write then
|
||||
scalar(st, x, k, m, bps)
|
||||
else
|
||||
bits += scalarBits(x, k, m, bps)
|
||||
end
|
||||
if zz > 0xFFFF then -- the decoder adapts on the value with its sign modifier added back
|
||||
history = 0xFFFF
|
||||
else
|
||||
history += zz * mult - floor(history * mult / 512)
|
||||
end
|
||||
if history < 128 and i < n then
|
||||
local lg = if history > 0 then 31 - countlz(history) else 0
|
||||
k = 7 - lg + floor((history + 16) / 64)
|
||||
if k > kb then
|
||||
k = kb
|
||||
end
|
||||
local run = 0
|
||||
while i + run < n and e[i + run + 1] == 0 and run < 0xFFFF do
|
||||
run += 1
|
||||
end
|
||||
m = POW[k + 1] - 1
|
||||
if write then
|
||||
scalar(st, run, k, m, 16)
|
||||
else
|
||||
bits += scalarBits(run, k, m, 16)
|
||||
end
|
||||
i += run
|
||||
if run < 0xFFFF then
|
||||
signMod = 1
|
||||
end
|
||||
history = 0
|
||||
end
|
||||
i += 1
|
||||
end
|
||||
return bits
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ prediction
|
||||
-- residuals of x[1..n] under the decoder's adaptive FIR starting from coefs (adapted in place, like the decoder)
|
||||
local function residuals(x: { number }, e: { number }, n: number, bps: number, coefs: { number }, order: number, quant: number)
|
||||
e[1] = x[1]
|
||||
if n <= 1 then
|
||||
return
|
||||
end
|
||||
local i = 2
|
||||
while i <= order + 1 and i <= n do
|
||||
e[i] = signExtend(x[i] - x[i - 1], bps)
|
||||
i += 1
|
||||
end
|
||||
local half = POW[quant]
|
||||
local qd = POW[quant + 1]
|
||||
while i <= n do
|
||||
local d = x[i - order - 1]
|
||||
local val = 0
|
||||
for j = 1, order do
|
||||
val += (x[i - j] - d) * coefs[j]
|
||||
end
|
||||
val = floor((val + half) / qd)
|
||||
local r = signExtend(x[i] - val - d, bps)
|
||||
e[i] = r
|
||||
if r ~= 0 then
|
||||
local es = if r > 0 then 1 else -1
|
||||
for j = order, 1, -1 do
|
||||
if r * es <= 0 then
|
||||
break
|
||||
end
|
||||
local v = d - x[i - j]
|
||||
local sgn = if v > 0 then es elseif v < 0 then -es else 0
|
||||
coefs[j] -= sgn
|
||||
r -= floor(v * sgn / qd) * (order - j + 1)
|
||||
end
|
||||
end
|
||||
i += 1
|
||||
end
|
||||
end
|
||||
|
||||
-- LPC coefficients of x[1..n] for the given order (Levinson-Durbin on a Welch-windowed autocorrelation), quantised
|
||||
local function lpc(x: { number }, n: number, order: number, work: { number }): { number }
|
||||
local ac = table.create(order + 1, 0)
|
||||
for i = 1, n do
|
||||
local t = (2 * (i - 1) - (n - 1)) / (n + 1)
|
||||
work[i] = x[i] * (1 - t * t)
|
||||
end
|
||||
for lag = 0, order do
|
||||
local s = 0
|
||||
for i = lag + 1, n do
|
||||
s += work[i] * work[i - lag]
|
||||
end
|
||||
ac[lag + 1] = s
|
||||
end
|
||||
local coefs = table.create(order, 0)
|
||||
if ac[1] <= 0 then
|
||||
return coefs
|
||||
end
|
||||
ac[1] *= 1.0001 -- a little white noise: keeps the recursion stable
|
||||
local a = table.create(order + 1, 0)
|
||||
local tmp = table.create(order + 1, 0)
|
||||
local errv = ac[1]
|
||||
for i = 1, order do
|
||||
local acc = ac[i + 1]
|
||||
for j = 1, i - 1 do
|
||||
acc -= a[j] * ac[i - j + 1]
|
||||
end
|
||||
local kc = acc / errv
|
||||
for j = 1, i - 1 do
|
||||
tmp[j] = a[j] - kc * a[i - j]
|
||||
end
|
||||
for j = 1, i - 1 do
|
||||
a[j] = tmp[j]
|
||||
end
|
||||
a[i] = kc
|
||||
errv *= (1 - kc * kc)
|
||||
if errv <= 0 then
|
||||
break
|
||||
end
|
||||
end
|
||||
local scale = POW[DENSHIFT + 1]
|
||||
for j = 1, order do
|
||||
coefs[j] = math.clamp(floor(a[j] * scale + 0.5), -32768, 32767)
|
||||
end
|
||||
return coefs
|
||||
end
|
||||
|
||||
-- choose order / coefficients for one channel: returns order, coefs (as transmitted), bits
|
||||
local function analyse(st: State, x: { number }, n: number, bps: number): (number, { number }, number)
|
||||
local mult = floor(st.pb * PB_FACTOR / 4)
|
||||
local bestOrder, bestCoefs, bestBits = 0, {}, math.huge
|
||||
for _, order in { 4, 8 } do
|
||||
if order >= n then
|
||||
continue
|
||||
end
|
||||
local coefs = lpc(x, n, order, st.work)
|
||||
local trial = table.clone(coefs)
|
||||
residuals(x, st.err, n, bps, trial, order, DENSHIFT)
|
||||
local bits = rice(st, st.err, n, bps, mult, false) + order * 16
|
||||
if bits < bestBits then
|
||||
bestOrder, bestCoefs, bestBits = order, coefs, bits
|
||||
end
|
||||
end
|
||||
if bestBits == math.huge then
|
||||
-- tiny frames: first-order prediction (order 31 is only a decoder mode; order 0 = no prediction)
|
||||
for i = 1, n do
|
||||
st.err[i] = x[i]
|
||||
end
|
||||
return 0, {}, rice(st, st.err, n, bps, mult, false)
|
||||
end
|
||||
return bestOrder, bestCoefs, bestBits
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ frame
|
||||
-- frame(st, samples, first, frames, map) -> buffer: samples interleaved (integers, WAV channel order) from index
|
||||
-- `first`; map[k] = the input channel (1-based) of ALAC channel k; elements: list of 1 / 2 channel counts
|
||||
function Encode.frame(st: State, samples: { number }, first: number, frames: number, map: { number }, elements: { number }): buffer
|
||||
local channels, depth = st.channels, st.bitDepth
|
||||
local n = frames
|
||||
local partial = n ~= st.frameLength
|
||||
local rawBits = n * channels * depth
|
||||
local need = rawBits + 64 * #elements + 64
|
||||
if st.cap < need + 8 * 32 * 2 * #elements * 16 then
|
||||
local bytes = (need + 8 * 32 * 2 * #elements * 16) // 8 + 16
|
||||
st.out = buffer.create(bytes)
|
||||
st.cap = bytes * 8
|
||||
end
|
||||
buffer.fill(st.out, 0, 0)
|
||||
st.pos = 0
|
||||
local u, v = st.u, st.v
|
||||
local mult = floor(st.pb * PB_FACTOR / 4)
|
||||
local compressed = true
|
||||
local ch = 1
|
||||
for _, nch in elements do
|
||||
local a, b = map[ch], map[ch + 1]
|
||||
local bps = depth + nch - 1
|
||||
local mixRes = 0
|
||||
if nch == 2 then
|
||||
-- the mix with the smallest first-difference energy
|
||||
local best = math.huge
|
||||
for res = 0, 4 do
|
||||
local cost = 0
|
||||
local pu, pv = 0, 0
|
||||
for i = 0, n - 1 do
|
||||
local l = samples[first + i * channels + a - 1]
|
||||
local r = samples[first + i * channels + b - 1]
|
||||
local uu, vv
|
||||
if res == 0 then
|
||||
uu, vv = l, r
|
||||
else
|
||||
uu, vv = floor((res * l + (4 - res) * r) / 4), l - r
|
||||
end
|
||||
cost += abs(uu - pu) + abs(vv - pv)
|
||||
pu, pv = uu, vv
|
||||
end
|
||||
if cost < best then
|
||||
best, mixRes = cost, res
|
||||
end
|
||||
end
|
||||
for i = 1, n do
|
||||
local l = samples[first + (i - 1) * channels + a - 1]
|
||||
local r = samples[first + (i - 1) * channels + b - 1]
|
||||
if mixRes == 0 then
|
||||
u[i], v[i] = l, r
|
||||
else
|
||||
u[i], v[i] = floor((mixRes * l + (4 - mixRes) * r) / 4), l - r
|
||||
end
|
||||
end
|
||||
else
|
||||
for i = 1, n do
|
||||
u[i] = samples[first + (i - 1) * channels + a - 1]
|
||||
end
|
||||
end
|
||||
-- header
|
||||
put(st, if nch == 2 then 1 else 0, 3)
|
||||
put(st, 0, 4)
|
||||
put(st, 0, 12)
|
||||
put(st, if partial then 1 else 0, 1)
|
||||
put(st, 0, 2)
|
||||
put(st, 0, 1)
|
||||
if partial then
|
||||
putBig(st, n, 32)
|
||||
end
|
||||
put(st, if mixRes == 0 then 0 else 2, 8)
|
||||
put(st, mixRes, 8)
|
||||
local orders, coefsList = {}, {}
|
||||
for c = 1, nch do
|
||||
local x = if c == 1 then u else v
|
||||
local order, coefs = analyse(st, x, n, bps)
|
||||
orders[c], coefsList[c] = order, coefs
|
||||
put(st, 0 * 16 + DENSHIFT, 8) -- mode 0, denShift
|
||||
put(st, PB_FACTOR * 32 + order, 8)
|
||||
for j = 1, order do
|
||||
put(st, coefs[j] % 65536, 16)
|
||||
end
|
||||
end
|
||||
for c = 1, nch do
|
||||
local x = if c == 1 then u else v
|
||||
local order = orders[c]
|
||||
if order == 0 then
|
||||
for i = 1, n do
|
||||
st.err[i] = x[i]
|
||||
end
|
||||
else
|
||||
residuals(x, st.err, n, bps, table.clone(coefsList[c]), order, DENSHIFT)
|
||||
end
|
||||
rice(st, st.err, n, bps, mult, true)
|
||||
end
|
||||
ch += nch
|
||||
if st.pos > rawBits + 64 * #elements then
|
||||
compressed = false
|
||||
break
|
||||
end
|
||||
end
|
||||
if not compressed then
|
||||
-- uncompressed frame
|
||||
buffer.fill(st.out, 0, 0)
|
||||
st.pos = 0
|
||||
ch = 1
|
||||
for _, nch in elements do
|
||||
put(st, if nch == 2 then 1 else 0, 3)
|
||||
put(st, 0, 4)
|
||||
put(st, 0, 12)
|
||||
put(st, if partial then 1 else 0, 1)
|
||||
put(st, 0, 2)
|
||||
put(st, 1, 1)
|
||||
if partial then
|
||||
putBig(st, n, 32)
|
||||
end
|
||||
for i = 0, n - 1 do
|
||||
for c = 0, nch - 1 do
|
||||
putBig(st, samples[first + i * channels + map[ch + c] - 1] % POW[depth + 1], depth)
|
||||
end
|
||||
end
|
||||
ch += nch
|
||||
end
|
||||
end
|
||||
put(st, 7, 3) -- END
|
||||
local bytes = (st.pos + 7) // 8
|
||||
local pkt = buffer.create(bytes)
|
||||
buffer.copy(pkt, 0, st.out, 0, bytes)
|
||||
return pkt
|
||||
end
|
||||
|
||||
function Encode.state(cfg: any): State
|
||||
local n = cfg.frameLength
|
||||
return {
|
||||
frameLength = n,
|
||||
bitDepth = cfg.bitDepth,
|
||||
pb = cfg.pb,
|
||||
mb = cfg.mb,
|
||||
kb = cfg.kb,
|
||||
channels = cfg.channels,
|
||||
out = buffer.create(16),
|
||||
pos = 0,
|
||||
cap = 0,
|
||||
u = table.create(n, 0),
|
||||
v = table.create(n, 0),
|
||||
err = table.create(n, 0),
|
||||
work = table.create(n, 0),
|
||||
}
|
||||
end
|
||||
|
||||
return Encode
|
||||
@@ -0,0 +1,251 @@
|
||||
--!strict
|
||||
-- codecs/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1).
|
||||
-- Written from the ALAC format as Apple published it (ALACSpecificConfig, the element syntax, adaptive Golomb-Rice
|
||||
-- residuals, the adaptive FIR predictor); no third-party code. 1 - 8 channels, 16 / 20 / 24 / 32-bit decode, 16 / 20 /
|
||||
-- 24-bit encode. Channels come out (and go in) in WAV order (ALAC stores C L R ... for 3+ channels).
|
||||
--
|
||||
-- local Alac = require("@formats/codecs/Alac")
|
||||
-- local cfg, err = Alac.config(cookie) -- the 24-byte ALACSpecificConfig (frma / alac atoms skipped)
|
||||
-- local dec = Alac.decoder(cfg)
|
||||
-- local frames, err = dec:decode(buf, offset, length) -- one packet -> dec.pcm (interleaved integers, WAV order)
|
||||
-- local enc = Alac.encoder({ sampleRate = 44100, channels = 2, bitDepth = 16 })
|
||||
-- local packet = enc:encode(samples, first, frames) -- interleaved integers -> one packet (frames <= 4096)
|
||||
-- local cookie = Alac.cookie(enc.config) -- after encoding: maxFrameBytes / avgBitRate filled
|
||||
--
|
||||
-- Never throws: bad data returns nil, Err (CORRUPT / TRUNCATED / UNSUPPORTED), bad arguments Err.ARG.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Decode = require("@formats/codecs/Alac/Decode")
|
||||
local Encode = require("@formats/codecs/Alac/Encode")
|
||||
|
||||
local Alac = {}
|
||||
|
||||
export type Config = {
|
||||
frameLength: number, -- samples per packet (4096)
|
||||
compatibleVersion: number,
|
||||
bitDepth: number,
|
||||
pb: number, -- 40
|
||||
mb: number, -- 10
|
||||
kb: number, -- 14
|
||||
channels: number,
|
||||
maxRun: number, -- 255
|
||||
maxFrameBytes: number,
|
||||
avgBitRate: number,
|
||||
sampleRate: number,
|
||||
}
|
||||
|
||||
-- ALAC channel k (1-based) -> WAV channel (1-based), per channel count
|
||||
local TO_WAV: { { number } } = {
|
||||
{ 1 },
|
||||
{ 1, 2 },
|
||||
{ 3, 1, 2 },
|
||||
{ 3, 1, 2, 4 },
|
||||
{ 3, 1, 2, 4, 5 },
|
||||
{ 3, 1, 2, 5, 6, 4 },
|
||||
{ 3, 1, 2, 5, 6, 7, 4 },
|
||||
{ 3, 7, 8, 1, 2, 5, 6, 4 },
|
||||
}
|
||||
-- the element layout (channels per element) the encoder writes
|
||||
local ELEMENTS: { { number } } = {
|
||||
{ 1 },
|
||||
{ 2 },
|
||||
{ 1, 2 },
|
||||
{ 1, 2, 1 },
|
||||
{ 1, 2, 2 },
|
||||
{ 1, 2, 2, 1 },
|
||||
{ 1, 2, 2, 1, 1 },
|
||||
{ 1, 2, 2, 2, 1 },
|
||||
}
|
||||
Alac.TO_WAV = TO_WAV
|
||||
|
||||
-- config(buf, offset?, length?) -> Config | nil, Err
|
||||
function Alac.config(buf: buffer, offset: number?, length: number?): (Config?, Err.Err?)
|
||||
local r = Bytes.reader(buf, offset, length)
|
||||
-- a QuickTime 'wave' payload may hold frma + alac atoms ahead of the cookie
|
||||
for _ = 1, 2 do
|
||||
local typ = r:peek(4, 4)
|
||||
if typ == "frma" then
|
||||
r:skip(12)
|
||||
elseif typ == "alac" then
|
||||
r:skip(12)
|
||||
end
|
||||
end
|
||||
if r:remaining() < 24 then
|
||||
return nil, Err.new(Err.TRUNCATED, "ALAC configuration is shorter than 24 bytes")
|
||||
end
|
||||
local c: Config = {
|
||||
frameLength = r:u32be(),
|
||||
compatibleVersion = r:u8(),
|
||||
bitDepth = r:u8(),
|
||||
pb = r:u8(),
|
||||
mb = r:u8(),
|
||||
kb = r:u8(),
|
||||
channels = r:u8(),
|
||||
maxRun = r:u16be(),
|
||||
maxFrameBytes = r:u32be(),
|
||||
avgBitRate = r:u32be(),
|
||||
sampleRate = r:u32be(),
|
||||
}
|
||||
if c.compatibleVersion ~= 0 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "ALAC version " .. c.compatibleVersion)
|
||||
end
|
||||
if c.frameLength < 1 or c.frameLength > 65536 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad ALAC frame length " .. c.frameLength)
|
||||
end
|
||||
if c.bitDepth ~= 16 and c.bitDepth ~= 20 and c.bitDepth ~= 24 and c.bitDepth ~= 32 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "ALAC bit depth " .. c.bitDepth)
|
||||
end
|
||||
if c.channels < 1 or c.channels > 8 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "ALAC with " .. c.channels .. " channels")
|
||||
end
|
||||
if c.kb < 1 or c.kb > 24 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad ALAC rice limit " .. c.kb)
|
||||
end
|
||||
return c, nil
|
||||
end
|
||||
|
||||
-- cookie(cfg) -> the 24-byte ALACSpecificConfig
|
||||
function Alac.cookie(c: Config): buffer
|
||||
local w = Bytes.writer(24)
|
||||
w:u32be(c.frameLength)
|
||||
w:u8(0)
|
||||
w:u8(c.bitDepth)
|
||||
w:u8(c.pb)
|
||||
w:u8(c.mb)
|
||||
w:u8(c.kb)
|
||||
w:u8(c.channels)
|
||||
w:u16be(c.maxRun)
|
||||
w:u32be(c.maxFrameBytes)
|
||||
w:u32be(c.avgBitRate)
|
||||
w:u32be(c.sampleRate)
|
||||
return w:finish()
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decoder
|
||||
export type Decoder = {
|
||||
config: Config,
|
||||
pcm: { number }, -- the last packet's samples, interleaved, WAV order (integers of config.bitDepth bits)
|
||||
decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?),
|
||||
state: Decode.State,
|
||||
}
|
||||
|
||||
local function decode(self: Decoder, buf: buffer, offset: number?, length: number?): (number?, Err.Err?)
|
||||
local o = offset or 0
|
||||
local n = length or (buffer.len(buf) - o)
|
||||
if o < 0 or n < 0 or o + n > buffer.len(buf) then
|
||||
return nil, Err.new(Err.ARG, "packet range out of the buffer")
|
||||
end
|
||||
local frames, msg = Decode.frame(self.state, buf, o, n)
|
||||
if not frames then
|
||||
return nil, Err.new(Err.CORRUPT, msg or "bad packet", o)
|
||||
end
|
||||
local ch = self.config.channels
|
||||
local src, dst = self.state.out, self.pcm
|
||||
if ch <= 2 then
|
||||
for i = 1, frames * ch do
|
||||
dst[i] = src[i]
|
||||
end
|
||||
else
|
||||
local map = TO_WAV[ch]
|
||||
for f = 0, frames - 1 do
|
||||
local base = f * ch
|
||||
for k = 1, ch do
|
||||
dst[base + map[k]] = src[base + k]
|
||||
end
|
||||
end
|
||||
end
|
||||
return frames, nil
|
||||
end
|
||||
|
||||
-- decoder(cfg) -> Decoder
|
||||
function Alac.decoder(cfg: Config): Decoder
|
||||
return {
|
||||
config = cfg,
|
||||
pcm = table.create(cfg.frameLength * cfg.channels, 0),
|
||||
decode = decode,
|
||||
state = Decode.state(cfg),
|
||||
}
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encoder
|
||||
export type Encoder = {
|
||||
config: Config,
|
||||
encode: (self: Encoder, samples: { number }, first: number, frames: number) -> (buffer?, Err.Err?),
|
||||
state: Encode.State,
|
||||
bytes: number,
|
||||
frames: number,
|
||||
}
|
||||
|
||||
local function encode(self: Encoder, samples: { number }, first: number, frames: number): (buffer?, Err.Err?)
|
||||
local cfg = self.config
|
||||
if type(samples) ~= "table" or frames < 1 or frames > cfg.frameLength or frames % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "encode: 1 .. " .. cfg.frameLength .. " frames of interleaved integer samples")
|
||||
end
|
||||
if first < 1 or first + frames * cfg.channels - 1 > #samples then
|
||||
return nil, Err.new(Err.ARG, "encode: the samples end early")
|
||||
end
|
||||
local ch = cfg.channels
|
||||
local pkt = Encode.frame(self.state, samples, first, frames, TO_WAV[ch], ELEMENTS[ch])
|
||||
local n = buffer.len(pkt)
|
||||
self.bytes += n
|
||||
self.frames += frames
|
||||
if n > cfg.maxFrameBytes then
|
||||
cfg.maxFrameBytes = n
|
||||
end
|
||||
if self.frames > 0 then
|
||||
cfg.avgBitRate = math.floor(self.bytes * 8 * cfg.sampleRate / self.frames)
|
||||
end
|
||||
return pkt, nil
|
||||
end
|
||||
|
||||
export type EncoderOptions = {
|
||||
sampleRate: number,
|
||||
channels: number, -- 1 .. 8
|
||||
bitDepth: number?, -- 16 (default), 20 or 24
|
||||
frameLength: number?, -- default 4096
|
||||
}
|
||||
|
||||
-- encoder(opts) -> Encoder | nil, Err
|
||||
function Alac.encoder(opts: EncoderOptions): (Encoder?, Err.Err?)
|
||||
if type(opts) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "encoder: expected options")
|
||||
end
|
||||
local depth = opts.bitDepth or 16
|
||||
local ch = opts.channels
|
||||
if depth ~= 16 and depth ~= 20 and depth ~= 24 then
|
||||
return nil, Err.new(Err.ARG, "encoder: bitDepth 16, 20 or 24")
|
||||
end
|
||||
if type(ch) ~= "number" or ch < 1 or ch > 8 or ch % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "encoder: 1 .. 8 channels")
|
||||
end
|
||||
local sr = opts.sampleRate
|
||||
if type(sr) ~= "number" or sr < 1 or sr % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "encoder: bad sampleRate")
|
||||
end
|
||||
local fl = opts.frameLength or 4096
|
||||
if fl < 16 or fl > 16384 or fl % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "encoder: frameLength 16 .. 16384")
|
||||
end
|
||||
local cfg: Config = {
|
||||
frameLength = fl,
|
||||
compatibleVersion = 0,
|
||||
bitDepth = depth,
|
||||
pb = 40,
|
||||
mb = 10,
|
||||
kb = 14,
|
||||
channels = ch,
|
||||
maxRun = 255,
|
||||
maxFrameBytes = 0,
|
||||
avgBitRate = 0,
|
||||
sampleRate = sr,
|
||||
}
|
||||
return {
|
||||
config = cfg,
|
||||
encode = encode,
|
||||
state = Encode.state(cfg),
|
||||
bytes = 0,
|
||||
frames = 0,
|
||||
}, nil
|
||||
end
|
||||
|
||||
return Alac
|
||||
@@ -0,0 +1,211 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/Mdct/Fft: mixed-radix complex FFT of any size (radix 4, 2, 3, 5 butterflies, a generic odd-radix pass for
|
||||
-- other primes), self-sorting Stockham passes ping-ponging between the data and a scratch array (the FFTPACK /
|
||||
-- pocketfft pass structure, written from the textbook decimation-in-frequency derivation; no third-party code).
|
||||
-- Data are separate real / imaginary arrays, 1-based. Never throws.
|
||||
local Fft = {}
|
||||
|
||||
export type Plan = {
|
||||
n: number,
|
||||
factors: { number },
|
||||
-- per pass: twiddles exp(-2 pi i u i l1 / n) for u = 1 .. p - 1, i = 0 .. ido - 1 at [(u - 1) * ido + i + 1]
|
||||
twr: { { number } },
|
||||
twi: { { number } },
|
||||
-- per pass, generic odd radix: exp(-2 pi i k / p) for k = 0 .. p - 1
|
||||
rr: { { number } },
|
||||
ri: { { number } },
|
||||
sre: { number }, -- scratch
|
||||
sim: { number },
|
||||
}
|
||||
|
||||
local cos, sin, pi = math.cos, math.sin, math.pi
|
||||
|
||||
-- new(n) -> Plan | nil (n < 1 or not an integer)
|
||||
function Fft.new(n: number): Plan?
|
||||
if type(n) ~= "number" or n < 1 or n % 1 ~= 0 or n > 2 ^ 24 then
|
||||
return nil
|
||||
end
|
||||
local factors = {}
|
||||
local m = n
|
||||
while m % 4 == 0 do
|
||||
table.insert(factors, 4)
|
||||
m //= 4
|
||||
end
|
||||
while m % 2 == 0 do
|
||||
table.insert(factors, 2)
|
||||
m //= 2
|
||||
end
|
||||
local f = 3
|
||||
while m > 1 do
|
||||
while m % f == 0 do
|
||||
table.insert(factors, f)
|
||||
m //= f
|
||||
end
|
||||
f += 2
|
||||
if f * f > m and m > 1 then
|
||||
table.insert(factors, m)
|
||||
m = 1
|
||||
end
|
||||
end
|
||||
local twr, twi, rr, ri = {}, {}, {}, {}
|
||||
local l1 = 1
|
||||
for k, p in factors do
|
||||
local ido = n // (l1 * p)
|
||||
local tr, ti = table.create((p - 1) * ido, 0), table.create((p - 1) * ido, 0)
|
||||
for u = 1, p - 1 do
|
||||
for i = 0, ido - 1 do
|
||||
local a = -2 * pi * u * i * l1 / n
|
||||
tr[(u - 1) * ido + i + 1] = cos(a)
|
||||
ti[(u - 1) * ido + i + 1] = sin(a)
|
||||
end
|
||||
end
|
||||
twr[k], twi[k] = tr, ti
|
||||
local cr, ci = table.create(p, 0), table.create(p, 0)
|
||||
for j = 0, p - 1 do
|
||||
cr[j + 1] = cos(-2 * pi * j / p)
|
||||
ci[j + 1] = sin(-2 * pi * j / p)
|
||||
end
|
||||
rr[k], ri[k] = cr, ci
|
||||
l1 *= p
|
||||
end
|
||||
return {
|
||||
n = n,
|
||||
factors = factors,
|
||||
twr = twr,
|
||||
twi = twi,
|
||||
rr = rr,
|
||||
ri = ri,
|
||||
sre = table.create(n, 0),
|
||||
sim = table.create(n, 0),
|
||||
}
|
||||
end
|
||||
|
||||
-- one pass of radix p: cc (i, v, k) = src[1 + i + ido * (v + p * k)] -> ch (i, k, u) = dst[1 + i + ido * (k + l1 * u)]
|
||||
local function pass(p: number, ido: number, l1: number, ar: { number }, ai: { number }, br: { number }, bi: { number }, tr: { number }, ti: { number }, cr: { number }, ci: { number })
|
||||
local lp = ido * l1
|
||||
if p == 4 then
|
||||
for k = 0, l1 - 1 do
|
||||
for i = 0, ido - 1 do
|
||||
local s = 1 + i + ido * 4 * k
|
||||
local a0r, a0i = ar[s], ai[s]
|
||||
local a1r, a1i = ar[s + ido], ai[s + ido]
|
||||
local a2r, a2i = ar[s + 2 * ido], ai[s + 2 * ido]
|
||||
local a3r, a3i = ar[s + 3 * ido], ai[s + 3 * ido]
|
||||
local t0r, t0i = a0r + a2r, a0i + a2i
|
||||
local t1r, t1i = a0r - a2r, a0i - a2i
|
||||
local t2r, t2i = a1r + a3r, a1i + a3i
|
||||
local t3r, t3i = a1r - a3r, a1i - a3i
|
||||
local d = 1 + i + ido * k
|
||||
br[d], bi[d] = t0r + t2r, t0i + t2i
|
||||
local y1r, y1i = t1r + t3i, t1i - t3r
|
||||
local y2r, y2i = t0r - t2r, t0i - t2i
|
||||
local y3r, y3i = t1r - t3i, t1i + t3r
|
||||
if i == 0 then
|
||||
br[d + lp], bi[d + lp] = y1r, y1i
|
||||
br[d + 2 * lp], bi[d + 2 * lp] = y2r, y2i
|
||||
br[d + 3 * lp], bi[d + 3 * lp] = y3r, y3i
|
||||
else
|
||||
local w1r, w1i = tr[i + 1], ti[i + 1]
|
||||
local w2r, w2i = tr[ido + i + 1], ti[ido + i + 1]
|
||||
local w3r, w3i = tr[2 * ido + i + 1], ti[2 * ido + i + 1]
|
||||
br[d + lp], bi[d + lp] = y1r * w1r - y1i * w1i, y1r * w1i + y1i * w1r
|
||||
br[d + 2 * lp], bi[d + 2 * lp] = y2r * w2r - y2i * w2i, y2r * w2i + y2i * w2r
|
||||
br[d + 3 * lp], bi[d + 3 * lp] = y3r * w3r - y3i * w3i, y3r * w3i + y3i * w3r
|
||||
end
|
||||
end
|
||||
end
|
||||
elseif p == 2 then
|
||||
for k = 0, l1 - 1 do
|
||||
for i = 0, ido - 1 do
|
||||
local s = 1 + i + ido * 2 * k
|
||||
local a0r, a0i = ar[s], ai[s]
|
||||
local a1r, a1i = ar[s + ido], ai[s + ido]
|
||||
local d = 1 + i + ido * k
|
||||
br[d], bi[d] = a0r + a1r, a0i + a1i
|
||||
local yr, yi = a0r - a1r, a0i - a1i
|
||||
if i == 0 then
|
||||
br[d + lp], bi[d + lp] = yr, yi
|
||||
else
|
||||
local wr, wi = tr[i + 1], ti[i + 1]
|
||||
br[d + lp], bi[d + lp] = yr * wr - yi * wi, yr * wi + yi * wr
|
||||
end
|
||||
end
|
||||
end
|
||||
elseif p == 3 then
|
||||
local c = 0.86602540378443864676 -- sin(pi / 3)
|
||||
for k = 0, l1 - 1 do
|
||||
for i = 0, ido - 1 do
|
||||
local s = 1 + i + ido * 3 * k
|
||||
local a0r, a0i = ar[s], ai[s]
|
||||
local a1r, a1i = ar[s + ido], ai[s + ido]
|
||||
local a2r, a2i = ar[s + 2 * ido], ai[s + 2 * ido]
|
||||
local tr_, ti_ = a1r + a2r, a1i + a2i
|
||||
local sr, si = a1r - a2r, a1i - a2i
|
||||
local d = 1 + i + ido * k
|
||||
br[d], bi[d] = a0r + tr_, a0i + ti_
|
||||
local mr, mi = a0r - 0.5 * tr_, a0i - 0.5 * ti_
|
||||
local y1r, y1i = mr + c * si, mi - c * sr
|
||||
local y2r, y2i = mr - c * si, mi + c * sr
|
||||
if i == 0 then
|
||||
br[d + lp], bi[d + lp] = y1r, y1i
|
||||
br[d + 2 * lp], bi[d + 2 * lp] = y2r, y2i
|
||||
else
|
||||
local w1r, w1i = tr[i + 1], ti[i + 1]
|
||||
local w2r, w2i = tr[ido + i + 1], ti[ido + i + 1]
|
||||
br[d + lp], bi[d + lp] = y1r * w1r - y1i * w1i, y1r * w1i + y1i * w1r
|
||||
br[d + 2 * lp], bi[d + 2 * lp] = y2r * w2r - y2i * w2i, y2r * w2i + y2i * w2r
|
||||
end
|
||||
end
|
||||
end
|
||||
else
|
||||
-- generic radix: y_u = sum_v a_v exp(-2 pi i u v / p), then the twiddle
|
||||
for k = 0, l1 - 1 do
|
||||
for i = 0, ido - 1 do
|
||||
local s = 1 + i + ido * p * k
|
||||
local d = 1 + i + ido * k
|
||||
for u = 0, p - 1 do
|
||||
local yr, yi = 0, 0
|
||||
local j = 0
|
||||
for v = 0, p - 1 do
|
||||
local xr, xi = ar[s + v * ido], ai[s + v * ido]
|
||||
local wr, wi = cr[j + 1], ci[j + 1]
|
||||
yr += xr * wr - xi * wi
|
||||
yi += xr * wi + xi * wr
|
||||
j += u
|
||||
if j >= p then
|
||||
j -= p
|
||||
end
|
||||
end
|
||||
if u > 0 and i > 0 then
|
||||
local wr, wi = tr[(u - 1) * ido + i + 1], ti[(u - 1) * ido + i + 1]
|
||||
yr, yi = yr * wr - yi * wi, yr * wi + yi * wr
|
||||
end
|
||||
br[d + u * lp], bi[d + u * lp] = yr, yi
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- forward(plan, re, im): in-place forward DFT X[k] = sum x[j] exp(-2 pi i j k / n) of re[1..n], im[1..n].
|
||||
-- The inverse (without the 1 / n) is forward(plan, im, re).
|
||||
function Fft.forward(plan: Plan, re: { number }, im: { number })
|
||||
local n = plan.n
|
||||
local ar, ai, br, bi = re, im, plan.sre, plan.sim
|
||||
local l1 = 1
|
||||
for k, p in plan.factors do
|
||||
local ido = n // (l1 * p)
|
||||
pass(p, ido, l1, ar, ai, br, bi, plan.twr[k], plan.twi[k], plan.rr[k], plan.ri[k])
|
||||
ar, ai, br, bi = br, bi, ar, ai
|
||||
l1 *= p
|
||||
end
|
||||
if ar ~= re then
|
||||
for j = 1, n do
|
||||
re[j], im[j] = ar[j], ai[j]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return Fft
|
||||
@@ -0,0 +1,203 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point
|
||||
-- complex FFT (codecs/Mdct/Fft, mixed radix: AAC 2048 / 256, Vorbis 64 .. 8192, CELT 1920 / 240 / ...), plus the
|
||||
-- DCT-IV, a plain FFT and the sine / KBD / Vorbis windows. Shared by AAC, Vorbis and Opus (decoders and encoders).
|
||||
-- Written from the textbook definitions (MDCT = DCT-IV of the folded input; DCT-IV through a half-size complex FFT
|
||||
-- with pre / post twiddles); no third-party code.
|
||||
--
|
||||
-- X[k] = sum_{j=0}^{N-1} x[j] cos(2 pi / N (j + 1/2 + N/4) (k + 1/2)) forward, k = 0 .. N/2 - 1
|
||||
-- y[j] = sum_{k=0}^{N/2-1} X[k] cos(2 pi / N (j + 1/2 + N/4) (k + 1/2)) inverse, j = 0 .. N - 1
|
||||
--
|
||||
-- Both are unnormalised (times `scale`, default 1): windowed forward + inverse + overlap-add with a Princen-Bradley
|
||||
-- window gives the input times N / 4 (AAC: the spec IMDCT is inverse(..., 2 / N), its MDCT has a factor 2). Arrays
|
||||
-- are Luau arrays; `xi` / `yi` are the 1-based index of element 0, coefficient arrays may be strided (CELT
|
||||
-- interleaves its short blocks).
|
||||
--
|
||||
-- local Mdct = require("@formats/codecs/Mdct")
|
||||
-- local plan = Mdct.new(2048) -- nil when N is not a multiple of 4
|
||||
-- Mdct.forward(plan, x, 1, X, 1) -- 2048 samples -> 1024 coefficients
|
||||
-- Mdct.inverse(plan, X, 1, 1, y, 1, 2 / 2048) -- 1024 coefficients -> 2048 samples
|
||||
-- local w = Mdct.window("sine", 2048) -- or "kbd" (alpha), "vorbis": N values
|
||||
--
|
||||
-- Never throws: bad sizes return nil from new(); the transforms trust the plan and the array ranges (the caller
|
||||
-- sizes them).
|
||||
local Fft = require("@formats/codecs/Mdct/Fft")
|
||||
|
||||
local cos, sin, pi, sqrt = math.cos, math.sin, math.pi, math.sqrt
|
||||
|
||||
local Mdct = {}
|
||||
Mdct.Fft = Fft
|
||||
|
||||
export type Plan = {
|
||||
n: number, -- window length N
|
||||
m: number, -- coefficients N / 2
|
||||
fft: Fft.Plan, -- N / 4 points
|
||||
twc: { number }, -- cos / sin (pi (p + 1/8) / M), p = 0 .. N/4 - 1
|
||||
tws: { number },
|
||||
re: { number }, -- scratch
|
||||
im: { number },
|
||||
c: { number }, -- DCT-IV output scratch (M)
|
||||
}
|
||||
|
||||
-- new(N) -> Plan | nil
|
||||
function Mdct.new(n: number): Plan?
|
||||
if type(n) ~= "number" or n < 4 or n % 4 ~= 0 or n > 2 ^ 24 then
|
||||
return nil
|
||||
end
|
||||
local m = n // 2
|
||||
local q = n // 4
|
||||
local fft = Fft.new(q)
|
||||
if not fft then
|
||||
return nil
|
||||
end
|
||||
local twc, tws = table.create(q, 0), table.create(q, 0)
|
||||
for p = 0, q - 1 do
|
||||
local a = pi * (p + 0.125) / m
|
||||
twc[p + 1], tws[p + 1] = cos(a), sin(a)
|
||||
end
|
||||
return {
|
||||
n = n,
|
||||
m = m,
|
||||
fft = fft,
|
||||
twc = twc,
|
||||
tws = tws,
|
||||
re = table.create(q, 0),
|
||||
im = table.create(q, 0),
|
||||
c = table.create(m, 0),
|
||||
}
|
||||
end
|
||||
|
||||
-- the DCT-IV of the M values u (already in plan.re / plan.im as the pre-twiddled pairs) into out[oi + k * os]
|
||||
local function dct4Post(plan: Plan, out: { number }, oi: number, os: number, scale: number)
|
||||
local q, m = plan.n // 4, plan.m
|
||||
local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws
|
||||
Fft.forward(plan.fft, re, im)
|
||||
for k = 0, q - 1 do
|
||||
local c, s = twc[k + 1], tws[k + 1]
|
||||
local tr, ti = re[k + 1], im[k + 1]
|
||||
out[oi + 2 * k * os] = (tr * c + ti * s) * scale
|
||||
out[oi + (m - 1 - 2 * k) * os] = -(ti * c - tr * s) * scale
|
||||
end
|
||||
end
|
||||
|
||||
-- dct4(plan, u, ui, us, out, oi, os, scale?): C[k] = sum_{n=0}^{M-1} u[n] cos(pi / M (n + 1/2) (k + 1/2)) for the
|
||||
-- plan's M = N / 2 (its own inverse up to 2 / M)
|
||||
function Mdct.dct4(plan: Plan, u: { number }, ui: number, us: number, out: { number }, oi: number, os: number, scale: number?)
|
||||
local q, m = plan.n // 4, plan.m
|
||||
local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws
|
||||
for p = 0, q - 1 do
|
||||
local a, b = u[ui + 2 * p * us], u[ui + (m - 1 - 2 * p) * us]
|
||||
local c, s = twc[p + 1], tws[p + 1]
|
||||
re[p + 1] = a * c + b * s
|
||||
im[p + 1] = b * c - a * s
|
||||
end
|
||||
dct4Post(plan, out, oi, os, scale or 1)
|
||||
end
|
||||
|
||||
-- forward(plan, x, xi, X, Xi, Xs?, scale?): N samples x[xi ..] -> N / 2 coefficients X[Xi + k * Xs]
|
||||
function Mdct.forward(plan: Plan, x: { number }, xi: number, out: { number }, oi: number, os: number?, scale: number?)
|
||||
local q, m = plan.n // 4, plan.m
|
||||
local h = m // 2 -- N / 4
|
||||
local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws
|
||||
-- fold: u[j] = -x[3M/2 - 1 - j] - x[3M/2 + j] (j < M/2), x[j - M/2] - x[3M/2 - 1 - j] (j >= M/2)
|
||||
local b3 = xi + 3 * h
|
||||
for p = 0, q - 1 do
|
||||
local j = 2 * p
|
||||
local a
|
||||
if j < h then
|
||||
a = -x[b3 - 1 - j] - x[b3 + j]
|
||||
else
|
||||
a = x[xi + j - h] - x[b3 - 1 - j]
|
||||
end
|
||||
j = m - 1 - 2 * p
|
||||
local b
|
||||
if j < h then
|
||||
b = -x[b3 - 1 - j] - x[b3 + j]
|
||||
else
|
||||
b = x[xi + j - h] - x[b3 - 1 - j]
|
||||
end
|
||||
local c, s = twc[p + 1], tws[p + 1]
|
||||
re[p + 1] = a * c + b * s
|
||||
im[p + 1] = b * c - a * s
|
||||
end
|
||||
dct4Post(plan, out, oi, os or 1, scale or 1)
|
||||
end
|
||||
|
||||
-- inverse(plan, X, Xi, Xs?, y, yi, scale?): N / 2 coefficients X[Xi + k * Xs] -> N samples y[yi ..] (no window)
|
||||
function Mdct.inverse(plan: Plan, inp: { number }, ii: number, is: number?, y: { number }, yi: number, scale: number?)
|
||||
local m = plan.m
|
||||
local h = m // 2
|
||||
local c = plan.c
|
||||
Mdct.dct4(plan, inp, ii, is or 1, c, 1, 1, scale)
|
||||
-- unfold: y = (C2, -C2 reversed, -C1 reversed, -C1)
|
||||
for j = 0, h - 1 do
|
||||
y[yi + j] = c[h + j + 1]
|
||||
y[yi + h + j] = -c[m - j]
|
||||
y[yi + m + j] = -c[h - j]
|
||||
y[yi + 3 * h + j] = -c[j + 1]
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ windows
|
||||
local function besselI0(x: number): number
|
||||
local sum, term = 1, 1
|
||||
local k = 1
|
||||
while k < 200 do
|
||||
term *= (x / (2 * k)) ^ 2
|
||||
sum += term
|
||||
if term < sum * 1e-17 then
|
||||
break
|
||||
end
|
||||
k += 1
|
||||
end
|
||||
return sum
|
||||
end
|
||||
Mdct.besselI0 = besselI0
|
||||
|
||||
-- window(kind, N, alpha?) -> N values: "sine" sin(pi (n + 1/2) / N); "kbd" Kaiser-Bessel-derived (alpha: AAC uses 4
|
||||
-- for long, 6 for short windows); "vorbis" sin(pi / 2 sin^2(pi (n + 1/2) / N)). All satisfy w[n]^2 + w[n + N/2]^2 = 1.
|
||||
function Mdct.window(kind: string, n: number, alpha: number?): { number }?
|
||||
if type(n) ~= "number" or n < 2 or n % 2 ~= 0 then
|
||||
return nil
|
||||
end
|
||||
local w = table.create(n, 0)
|
||||
if kind == "sine" then
|
||||
for i = 0, n - 1 do
|
||||
w[i + 1] = sin(pi * (i + 0.5) / n)
|
||||
end
|
||||
elseif kind == "vorbis" then
|
||||
for i = 0, n - 1 do
|
||||
local s = sin(pi * (i + 0.5) / n)
|
||||
w[i + 1] = sin(pi / 2 * s * s)
|
||||
end
|
||||
elseif kind == "kbd" then
|
||||
local half = n // 2
|
||||
local a = alpha or 4
|
||||
local kais = table.create(half + 1, 0)
|
||||
local total = 0
|
||||
for i = 0, half do
|
||||
local r = 2 * i / half - 1
|
||||
kais[i + 1] = besselI0(pi * a * sqrt(math.max(0, 1 - r * r)))
|
||||
total += kais[i + 1]
|
||||
end
|
||||
local acc = 0
|
||||
for i = 0, half - 1 do
|
||||
acc += kais[i + 1]
|
||||
local v = sqrt(acc / total)
|
||||
w[i + 1] = v
|
||||
w[n - i] = v
|
||||
end
|
||||
else
|
||||
return nil
|
||||
end
|
||||
return w
|
||||
end
|
||||
|
||||
-- fft(n) -> an Fft plan (Fft.forward(plan, re, im) transforms in place)
|
||||
function Mdct.fft(n: number): Fft.Plan?
|
||||
return Fft.new(n)
|
||||
end
|
||||
|
||||
return Mdct
|
||||
@@ -0,0 +1,308 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/Pcm/Convert: raw sample formats <-> interleaved f32 (the hot loops of codecs/Pcm). Integers map to
|
||||
-- v / 2^(bits-1) (as ffmpeg does); encoding rounds to nearest and clips. G.711 A-law / mu-law per ITU-T G.711 (the
|
||||
-- classic Sun g711.c algorithm, written from the spec).
|
||||
--
|
||||
-- Formats: u8 s8 s16le s16be s24le s24be s32le s32be f32le f32be f64le f64be alaw ulaw (u8: offset binary).
|
||||
-- Never throws: callers check ranges (Convert.SIZE[fmt] * count bytes) before calling.
|
||||
local Convert = {}
|
||||
|
||||
local readu8, readi8, readi16, readi32, readu32 = buffer.readu8, buffer.readi8, buffer.readi16, buffer.readi32, buffer.readu32
|
||||
local readf32, readf64, writef32, writef64 = buffer.readf32, buffer.readf64, buffer.writef32, buffer.writef64
|
||||
local writeu8, writeu16, writeu32, writei16, writei32 = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writei16, buffer.writei32
|
||||
local floor = math.floor
|
||||
local byteswap = bit32.byteswap
|
||||
|
||||
local SIZE: { [string]: number } = {
|
||||
u8 = 1,
|
||||
s8 = 1,
|
||||
s16le = 2,
|
||||
s16be = 2,
|
||||
s24le = 3,
|
||||
s24be = 3,
|
||||
s32le = 4,
|
||||
s32be = 4,
|
||||
f32le = 4,
|
||||
f32be = 4,
|
||||
f64le = 8,
|
||||
f64be = 8,
|
||||
alaw = 1,
|
||||
ulaw = 1,
|
||||
}
|
||||
Convert.SIZE = SIZE
|
||||
-- the integer bit depth of each format (float: 32 / 64; G.711: 16 after expansion)
|
||||
Convert.BITS = {
|
||||
u8 = 8,
|
||||
s8 = 8,
|
||||
s16le = 16,
|
||||
s16be = 16,
|
||||
s24le = 24,
|
||||
s24be = 24,
|
||||
s32le = 32,
|
||||
s32be = 32,
|
||||
f32le = 32,
|
||||
f32be = 32,
|
||||
f64le = 64,
|
||||
f64be = 64,
|
||||
alaw = 16,
|
||||
ulaw = 16,
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ G.711
|
||||
local ALAW = table.create(256, 0) -- code -> linear s16
|
||||
local ULAW = table.create(256, 0)
|
||||
for code = 0, 255 do
|
||||
-- A-law
|
||||
local a = bit32.bxor(code, 0x55)
|
||||
local t = bit32.band(a, 0x0F) * 16
|
||||
local seg = bit32.rshift(bit32.band(a, 0x70), 4)
|
||||
if seg == 0 then
|
||||
t += 8
|
||||
elseif seg == 1 then
|
||||
t += 0x108
|
||||
else
|
||||
t = (t + 0x108) * 2 ^ (seg - 1)
|
||||
end
|
||||
ALAW[code + 1] = if bit32.band(a, 0x80) ~= 0 then t else -t
|
||||
-- mu-law
|
||||
local u = bit32.bxor(code, 0xFF)
|
||||
local m = (bit32.band(u, 0x0F) * 8 + 0x84) * 2 ^ bit32.rshift(bit32.band(u, 0x70), 4)
|
||||
ULAW[code + 1] = if bit32.band(u, 0x80) ~= 0 then 0x84 - m else m - 0x84
|
||||
end
|
||||
|
||||
local SEG_AEND = { 0x1F, 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF }
|
||||
local SEG_UEND = { 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF }
|
||||
local function segment(v: number, ends: { number }): number
|
||||
for i = 1, 8 do
|
||||
if v <= ends[i] then
|
||||
return i - 1
|
||||
end
|
||||
end
|
||||
return 8
|
||||
end
|
||||
|
||||
-- linear s16 -> A-law code
|
||||
local function alawEncode(pcm: number): number
|
||||
local mask
|
||||
local v = floor(pcm / 8) -- 13-bit magnitude domain
|
||||
if v >= 0 then
|
||||
mask = 0xD5
|
||||
else
|
||||
mask = 0x55
|
||||
v = -v - 1
|
||||
end
|
||||
local seg = segment(v, SEG_AEND)
|
||||
local aval
|
||||
if seg >= 8 then
|
||||
aval = 0x7F
|
||||
else
|
||||
aval = seg * 16
|
||||
if seg < 2 then
|
||||
aval += bit32.band(floor(v / 2), 0x0F)
|
||||
else
|
||||
aval += bit32.band(floor(v / 2 ^ seg), 0x0F)
|
||||
end
|
||||
end
|
||||
return bit32.bxor(aval, mask)
|
||||
end
|
||||
|
||||
-- linear s16 -> mu-law code
|
||||
local function ulawEncode(pcm: number): number
|
||||
local v = floor(pcm / 4) -- 14-bit
|
||||
local mask
|
||||
if v < 0 then
|
||||
v = -v
|
||||
mask = 0x7F
|
||||
else
|
||||
mask = 0xFF
|
||||
end
|
||||
if v > 8159 then
|
||||
v = 8159
|
||||
end
|
||||
v += 0x21
|
||||
local seg = segment(v, SEG_UEND)
|
||||
local uval
|
||||
if seg >= 8 then
|
||||
uval = 0x7F
|
||||
else
|
||||
uval = seg * 16 + bit32.band(floor(v / 2 ^ (seg + 1)), 0x0F)
|
||||
end
|
||||
return bit32.bxor(uval, mask)
|
||||
end
|
||||
Convert.alawEncode = alawEncode
|
||||
Convert.ulawEncode = ulawEncode
|
||||
Convert.ALAW = ALAW
|
||||
Convert.ULAW = ULAW
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- decode(src, so, fmt, count, dst, do_) -> true | false (unknown fmt): count samples at src[so] -> f32 at dst[do_]
|
||||
function Convert.decode(src: buffer, so: number, fmt: string, count: number, dst: buffer, d: number): boolean
|
||||
if fmt == "s16le" then
|
||||
for i = 0, count - 1 do
|
||||
writef32(dst, d + i * 4, readi16(src, so + i * 2) / 32768)
|
||||
end
|
||||
elseif fmt == "s16be" then
|
||||
for i = 0, count - 1 do
|
||||
local p = so + i * 2
|
||||
local v = readu8(src, p) * 256 + readu8(src, p + 1)
|
||||
if v >= 32768 then
|
||||
v -= 65536
|
||||
end
|
||||
writef32(dst, d + i * 4, v / 32768)
|
||||
end
|
||||
elseif fmt == "u8" then
|
||||
for i = 0, count - 1 do
|
||||
writef32(dst, d + i * 4, (readu8(src, so + i) - 128) / 128)
|
||||
end
|
||||
elseif fmt == "s8" then
|
||||
for i = 0, count - 1 do
|
||||
writef32(dst, d + i * 4, readi8(src, so + i) / 128)
|
||||
end
|
||||
elseif fmt == "s24le" then
|
||||
for i = 0, count - 1 do
|
||||
local p = so + i * 3
|
||||
local v = readu8(src, p) + readu8(src, p + 1) * 256 + readi8(src, p + 2) * 65536
|
||||
writef32(dst, d + i * 4, v / 8388608)
|
||||
end
|
||||
elseif fmt == "s24be" then
|
||||
for i = 0, count - 1 do
|
||||
local p = so + i * 3
|
||||
local v = readi8(src, p) * 65536 + readu8(src, p + 1) * 256 + readu8(src, p + 2)
|
||||
writef32(dst, d + i * 4, v / 8388608)
|
||||
end
|
||||
elseif fmt == "s32le" then
|
||||
for i = 0, count - 1 do
|
||||
writef32(dst, d + i * 4, readi32(src, so + i * 4) / 2147483648)
|
||||
end
|
||||
elseif fmt == "s32be" then
|
||||
for i = 0, count - 1 do
|
||||
local v = byteswap(readu32(src, so + i * 4))
|
||||
if v >= 2147483648 then
|
||||
v -= 4294967296
|
||||
end
|
||||
writef32(dst, d + i * 4, v / 2147483648)
|
||||
end
|
||||
elseif fmt == "f32le" then
|
||||
buffer.copy(dst, d, src, so, count * 4)
|
||||
elseif fmt == "f32be" then
|
||||
for i = 0, count - 1 do
|
||||
writeu32(dst, d + i * 4, byteswap(readu32(src, so + i * 4)))
|
||||
end
|
||||
elseif fmt == "f64le" then
|
||||
for i = 0, count - 1 do
|
||||
writef32(dst, d + i * 4, readf64(src, so + i * 8))
|
||||
end
|
||||
elseif fmt == "f64be" then
|
||||
local tmp = buffer.create(8)
|
||||
for i = 0, count - 1 do
|
||||
local p = so + i * 8
|
||||
writeu32(tmp, 0, byteswap(readu32(src, p + 4)))
|
||||
writeu32(tmp, 4, byteswap(readu32(src, p)))
|
||||
writef32(dst, d + i * 4, readf64(tmp, 0))
|
||||
end
|
||||
elseif fmt == "alaw" then
|
||||
for i = 0, count - 1 do
|
||||
writef32(dst, d + i * 4, ALAW[readu8(src, so + i) + 1] / 32768)
|
||||
end
|
||||
elseif fmt == "ulaw" then
|
||||
for i = 0, count - 1 do
|
||||
writef32(dst, d + i * 4, ULAW[readu8(src, so + i) + 1] / 32768)
|
||||
end
|
||||
else
|
||||
return false
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local function q(x: number, s: number): number
|
||||
local v = floor(x * s + 0.5)
|
||||
if v ~= v then
|
||||
return 0
|
||||
end
|
||||
if v >= s then
|
||||
return s - 1
|
||||
elseif v < -s then
|
||||
return -s
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
-- encode(src, so, count, fmt, dst, do_) -> true | false: count f32 samples at src[so] -> fmt at dst[do_]
|
||||
function Convert.encode(src: buffer, so: number, count: number, fmt: string, dst: buffer, d: number): boolean
|
||||
if fmt == "s16le" then
|
||||
for i = 0, count - 1 do
|
||||
writei16(dst, d + i * 2, q(readf32(src, so + i * 4), 32768))
|
||||
end
|
||||
elseif fmt == "s16be" then
|
||||
for i = 0, count - 1 do
|
||||
local v = q(readf32(src, so + i * 4), 32768) % 65536
|
||||
writeu16(dst, d + i * 2, (v % 256) * 256 + v // 256)
|
||||
end
|
||||
elseif fmt == "u8" then
|
||||
for i = 0, count - 1 do
|
||||
writeu8(dst, d + i, q(readf32(src, so + i * 4), 128) + 128)
|
||||
end
|
||||
elseif fmt == "s8" then
|
||||
for i = 0, count - 1 do
|
||||
writeu8(dst, d + i, q(readf32(src, so + i * 4), 128) % 256)
|
||||
end
|
||||
elseif fmt == "s24le" then
|
||||
for i = 0, count - 1 do
|
||||
local v = q(readf32(src, so + i * 4), 8388608) % 16777216
|
||||
local p = d + i * 3
|
||||
writeu8(dst, p, v % 256)
|
||||
writeu8(dst, p + 1, (v // 256) % 256)
|
||||
writeu8(dst, p + 2, v // 65536)
|
||||
end
|
||||
elseif fmt == "s24be" then
|
||||
for i = 0, count - 1 do
|
||||
local v = q(readf32(src, so + i * 4), 8388608) % 16777216
|
||||
local p = d + i * 3
|
||||
writeu8(dst, p, v // 65536)
|
||||
writeu8(dst, p + 1, (v // 256) % 256)
|
||||
writeu8(dst, p + 2, v % 256)
|
||||
end
|
||||
elseif fmt == "s32le" then
|
||||
for i = 0, count - 1 do
|
||||
writei32(dst, d + i * 4, q(readf32(src, so + i * 4), 2147483648))
|
||||
end
|
||||
elseif fmt == "s32be" then
|
||||
for i = 0, count - 1 do
|
||||
writeu32(dst, d + i * 4, byteswap(q(readf32(src, so + i * 4), 2147483648) % 4294967296))
|
||||
end
|
||||
elseif fmt == "f32le" then
|
||||
buffer.copy(dst, d, src, so, count * 4)
|
||||
elseif fmt == "f32be" then
|
||||
for i = 0, count - 1 do
|
||||
writeu32(dst, d + i * 4, byteswap(readu32(src, so + i * 4)))
|
||||
end
|
||||
elseif fmt == "f64le" then
|
||||
for i = 0, count - 1 do
|
||||
writef64(dst, d + i * 8, readf32(src, so + i * 4))
|
||||
end
|
||||
elseif fmt == "f64be" then
|
||||
local tmp = buffer.create(8)
|
||||
for i = 0, count - 1 do
|
||||
writef64(tmp, 0, readf32(src, so + i * 4))
|
||||
local p = d + i * 8
|
||||
writeu32(dst, p, byteswap(readu32(tmp, 4)))
|
||||
writeu32(dst, p + 4, byteswap(readu32(tmp, 0)))
|
||||
end
|
||||
elseif fmt == "alaw" then
|
||||
for i = 0, count - 1 do
|
||||
writeu8(dst, d + i, alawEncode(q(readf32(src, so + i * 4), 32768)))
|
||||
end
|
||||
elseif fmt == "ulaw" then
|
||||
for i = 0, count - 1 do
|
||||
writeu8(dst, d + i, ulawEncode(q(readf32(src, so + i * 4), 32768)))
|
||||
end
|
||||
else
|
||||
return false
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
return Convert
|
||||
@@ -0,0 +1,234 @@
|
||||
--!strict
|
||||
-- codecs/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources.
|
||||
-- An encoder accepts a Types.Audio (fully decoded) or a Types.Decoder (streamed); Pcm.source turns either into one
|
||||
-- pull interface, so encoders stream in blocks without caring which they got. Uncompressed containers (aiff, au,
|
||||
-- voc, ...) get their Decoder from Pcm.rawDecoder (over a sample region of the file) or Pcm.audioDecoder.
|
||||
--
|
||||
-- local src, err = Pcm.source(audioOrDecoder) -- nil, Err.ARG for anything else
|
||||
-- local buf, n = src:read(4096) -- interleaved f32, n frames (0 at the end), like Decoder:read
|
||||
-- local audio = Pcm.collect(src) -- read everything into a Types.Audio
|
||||
-- local dec = Pcm.rawDecoder(buf, offset, frames, channels, rate, "s16be", tags?) -- a Types.Decoder
|
||||
-- local dec = Pcm.audioDecoder(audio) -- a Types.Decoder over a decoded Audio
|
||||
-- local raw = Pcm.encode(src, "s24le", writer) -- every frame of src appended to a core/Bytes Writer
|
||||
-- Pcm.Convert.decode / encode / SIZE / BITS -- the raw sample loops (codecs/Pcm/Convert)
|
||||
-- local s16 = Pcm.toInt(x, 16) -- round, clip to [-32768, 32767]
|
||||
-- local x = Pcm.fromInt(s16, 16) -- s / 32768
|
||||
--
|
||||
-- Sample formats: u8 s8 s16le s16be s24le s24be s32le s32be f32le f32be f64le f64be alaw ulaw.
|
||||
-- Never throws (a decoder's read that throws is caught and ends the stream).
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Convert = require("@formats/codecs/Pcm/Convert")
|
||||
|
||||
local Pcm = {}
|
||||
Pcm.Convert = Convert
|
||||
|
||||
export type Source = {
|
||||
sampleRate: number,
|
||||
channels: number,
|
||||
frames: number, -- total frames, 0 = unknown (a streaming decoder without an index)
|
||||
tags: Types.Tags,
|
||||
-- read(n, out?) -> interleaved f32 buffer, frames read (0 at the end)
|
||||
read: (self: Source, n: number, out: buffer?) -> (buffer, number),
|
||||
err: Err.Err?, -- set when the underlying decoder failed mid-stream
|
||||
}
|
||||
|
||||
local function audioRead(self: any, n: number, out: buffer?): (buffer, number)
|
||||
local a = self._audio
|
||||
local ch = a.channels
|
||||
local left = a.frames - self._pos
|
||||
if n > left then
|
||||
n = left
|
||||
end
|
||||
if n <= 0 then
|
||||
return out or buffer.create(0), 0
|
||||
end
|
||||
local bytes = n * ch * 4
|
||||
local b = if out and buffer.len(out) >= bytes then out else buffer.create(bytes)
|
||||
buffer.copy(b, 0, a.samples, self._pos * ch * 4, bytes)
|
||||
self._pos += n
|
||||
return b, n
|
||||
end
|
||||
|
||||
local function decoderRead(self: any, n: number, out: buffer?): (buffer, number)
|
||||
if self._done then
|
||||
return out or buffer.create(0), 0
|
||||
end
|
||||
local ok, b, got = pcall(self._dec.read, self._dec, n, out)
|
||||
if not ok then
|
||||
self._done = true
|
||||
self.err = Err.new(Err.CORRUPT, "source decoder failed: " .. tostring(b))
|
||||
return out or buffer.create(0), 0
|
||||
end
|
||||
if type(b) ~= "buffer" or type(got) ~= "number" or got <= 0 then
|
||||
self._done = true
|
||||
return out or buffer.create(0), 0
|
||||
end
|
||||
local ch = self.channels
|
||||
if buffer.len(b) < got * ch * 4 then
|
||||
got = buffer.len(b) // (ch * 4)
|
||||
end
|
||||
return b, got
|
||||
end
|
||||
|
||||
-- source(v) -> Source | nil, Err.ARG: v is a Types.Audio or a Types.Decoder (anything with sampleRate, channels, read)
|
||||
function Pcm.source(v: any): (Source?, Err.Err?)
|
||||
if type(v) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder")
|
||||
end
|
||||
local sr, ch = v.sampleRate, v.channels
|
||||
if type(sr) ~= "number" or sr <= 0 or sr ~= sr or type(ch) ~= "number" or ch < 1 or ch ~= math.floor(ch) then
|
||||
return nil, Err.new(Err.ARG, "bad sampleRate or channels")
|
||||
end
|
||||
if v.kind == "audio" and type(v.samples) == "buffer" then
|
||||
local frames = v.frames
|
||||
if type(frames) ~= "number" or frames < 0 or buffer.len(v.samples) < frames * ch * 4 then
|
||||
return nil, Err.new(Err.ARG, "the Audio's samples buffer is shorter than frames * channels * 4")
|
||||
end
|
||||
return { sampleRate = sr, channels = ch, frames = frames, tags = v.tags or {}, read = audioRead, _audio = v, _pos = 0 } :: any, nil
|
||||
end
|
||||
if type(v.read) == "function" then
|
||||
local frames = if type(v.frames) == "number" and v.frames > 0 then v.frames else 0
|
||||
return { sampleRate = sr, channels = ch, frames = frames, tags = v.tags or {}, read = decoderRead, _dec = v, _done = false } :: any, nil
|
||||
end
|
||||
return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder")
|
||||
end
|
||||
|
||||
-- collect(src, maxFrames?) -> Types.Audio | nil, Err (everything the source has; Err.LIMIT past maxFrames)
|
||||
function Pcm.collect(src: Source, maxFrames: number?): (Types.Audio?, Err.Err?)
|
||||
local ch = src.channels
|
||||
local cap = math.max(src.frames, 4096)
|
||||
local data = buffer.create(cap * ch * 4)
|
||||
local total = 0
|
||||
local limit = maxFrames or 2 ^ 31
|
||||
local tmp: buffer? = nil
|
||||
while true do
|
||||
local b, n = src:read(16384, tmp)
|
||||
if n <= 0 then
|
||||
break
|
||||
end
|
||||
tmp = b
|
||||
if total + n > limit then
|
||||
return nil, Err.new(Err.LIMIT, string.format("more than %d frames", limit))
|
||||
end
|
||||
if total + n > cap then
|
||||
cap = math.max(cap * 2, total + n)
|
||||
local nd = buffer.create(cap * ch * 4)
|
||||
buffer.copy(nd, 0, data, 0, total * ch * 4)
|
||||
data = nd
|
||||
end
|
||||
buffer.copy(data, total * ch * 4, b, 0, n * ch * 4)
|
||||
total += n
|
||||
end
|
||||
if src.err then
|
||||
return nil, src.err
|
||||
end
|
||||
local a = Types.Audio.new(src.sampleRate, ch, 0)
|
||||
a.frames = total
|
||||
if buffer.len(data) == total * ch * 4 then
|
||||
a.samples = data
|
||||
else
|
||||
a.samples = buffer.create(total * ch * 4)
|
||||
buffer.copy(a.samples, 0, data, 0, total * ch * 4)
|
||||
end
|
||||
a.tags = table.clone(src.tags)
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decoders
|
||||
-- rawDecoder(buf, offset, frames, channels, sampleRate, fmt, tags?) -> Types.Decoder | nil, Err.ARG: a streaming
|
||||
-- decoder over frames * channels samples of fmt at buf[offset] (the caller has checked the range is inside buf)
|
||||
function Pcm.rawDecoder(buf: buffer, offset: number, frames: number, channels: number, sampleRate: number, fmt: string, tags: Types.Tags?): (Types.Decoder?, Err.Err?)
|
||||
local size = Convert.SIZE[fmt]
|
||||
if not size then
|
||||
return nil, Err.new(Err.ARG, "unknown sample format " .. tostring(fmt))
|
||||
end
|
||||
if channels < 1 or sampleRate <= 0 or frames < 0 or offset < 0 or offset + frames * channels * size > buffer.len(buf) then
|
||||
return nil, Err.new(Err.ARG, "bad raw PCM layout")
|
||||
end
|
||||
local pos = 0
|
||||
local frameBytes = channels * size
|
||||
local dec = {
|
||||
sampleRate = sampleRate,
|
||||
channels = channels,
|
||||
frames = frames,
|
||||
duration = frames / sampleRate,
|
||||
bitrate = sampleRate * frameBytes * 8,
|
||||
tags = tags or {},
|
||||
}
|
||||
function dec.read(_self: any, n: number, out: buffer?): (buffer, number)
|
||||
n = math.clamp(math.floor(n), 0, frames - pos)
|
||||
local bytes = n * channels * 4
|
||||
local b = if out and buffer.len(out) >= bytes then out else buffer.create(bytes)
|
||||
if n > 0 then
|
||||
Convert.decode(buf, offset + pos * frameBytes, fmt, n * channels, b, 0)
|
||||
pos += n
|
||||
end
|
||||
return b, n
|
||||
end
|
||||
function dec.seek(_self: any, seconds: number)
|
||||
local f = math.floor(seconds * sampleRate + 0.5)
|
||||
pos = if f ~= f then 0 else math.clamp(f, 0, frames)
|
||||
end
|
||||
function dec.position(_self: any): number
|
||||
return pos / sampleRate
|
||||
end
|
||||
return dec :: any, nil
|
||||
end
|
||||
|
||||
-- audioDecoder(audio) -> Types.Decoder over a decoded Audio (no copy of the samples)
|
||||
function Pcm.audioDecoder(a: Types.Audio): Types.Decoder
|
||||
local d = Pcm.rawDecoder(a.samples, 0, a.frames, a.channels, a.sampleRate, "f32le", a.tags) :: any
|
||||
d.bitrate = a.sampleRate * a.channels * 32
|
||||
return d
|
||||
end
|
||||
|
||||
-- encode(src, fmt, w) -> frames written | nil, Err: drains src into the Writer w as fmt samples
|
||||
function Pcm.encode(src: Source, fmt: string, w: Bytes.Writer): (number?, Err.Err?)
|
||||
local size = Convert.SIZE[fmt]
|
||||
if not size then
|
||||
return nil, Err.new(Err.ARG, "unknown sample format " .. tostring(fmt))
|
||||
end
|
||||
local ch = src.channels
|
||||
local total = 0
|
||||
local tmp: buffer? = nil
|
||||
while true do
|
||||
local b, n = src:read(8192, tmp)
|
||||
if n <= 0 then
|
||||
break
|
||||
end
|
||||
tmp = b
|
||||
local at = w:reserve(n * ch * size)
|
||||
Convert.encode(b, 0, n * ch, fmt, w.buf, at)
|
||||
w.pos = at + n * ch * size
|
||||
total += n
|
||||
end
|
||||
if src.err then
|
||||
return nil, src.err
|
||||
end
|
||||
return total, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ conversions
|
||||
-- toInt(x, bits) -> the nearest bits-wide signed integer to x * 2^(bits-1), clipped (NaN -> 0)
|
||||
function Pcm.toInt(x: number, bits: number): number
|
||||
local s = 2 ^ (bits - 1)
|
||||
local v = math.floor(x * s + 0.5)
|
||||
if v ~= v then
|
||||
return 0
|
||||
end
|
||||
if v >= s then
|
||||
return s - 1
|
||||
elseif v < -s then
|
||||
return -s
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
-- fromInt(v, bits) -> v / 2^(bits-1)
|
||||
function Pcm.fromInt(v: number, bits: number): number
|
||||
return v / 2 ^ (bits - 1)
|
||||
end
|
||||
|
||||
return Pcm
|
||||
@@ -0,0 +1,149 @@
|
||||
--!strict
|
||||
-- codecs/SoundFont/Fallback: the built-in General MIDI set used when no SoundFont is given. A generated SoundFont
|
||||
-- (the same shape Parse returns, so the same synth plays it): single-cycle sine / triangle / square / saw waves and a
|
||||
-- looped noise sample, one preset per GM family of 8 programs (piano, chromatic percussion, organ, guitar, bass,
|
||||
-- strings, ensemble, brass, reed, pipe, lead, pad, synth fx, ethnic, percussive, sound fx) with family envelopes,
|
||||
-- filters and vibrato, plus a drum kit on bank 128 (pitch-swept sine kicks and toms, filtered noise snares, hats with
|
||||
-- an exclusive class, cymbals). Written for this library (no third-party code).
|
||||
local Parse = require("@formats/codecs/SoundFont/Parse")
|
||||
|
||||
local Fallback = {}
|
||||
|
||||
local CYCLE = 256
|
||||
local NOISE = 32768
|
||||
local C4 = 261.6255653005986
|
||||
|
||||
local function hzToCents(hz: number): number
|
||||
return 1200 * math.log(hz / 8.176, 2)
|
||||
end
|
||||
|
||||
local cached: any = nil
|
||||
|
||||
-- build() -> a SoundFont value (kind "soundfont"); built once, shared (the synth never writes to it)
|
||||
function Fallback.build(): any
|
||||
if cached then
|
||||
return cached
|
||||
end
|
||||
local waves = { "sine", "triangle", "square", "saw" }
|
||||
local count = #waves * CYCLE + NOISE
|
||||
local samples = buffer.create((count + 1) * 4)
|
||||
local starts: { [string]: number } = {}
|
||||
for w, name in waves do
|
||||
local base = (w - 1) * CYCLE
|
||||
starts[name] = base
|
||||
for i = 0, CYCLE - 1 do
|
||||
local ph = i / CYCLE
|
||||
local v
|
||||
if name == "sine" then
|
||||
v = math.sin(2 * math.pi * ph)
|
||||
elseif name == "triangle" then
|
||||
v = if ph < 0.25 then 4 * ph elseif ph < 0.75 then 2 - 4 * ph else 4 * ph - 4
|
||||
elseif name == "square" then
|
||||
v = if ph < 0.5 then 0.6 else -0.6
|
||||
else
|
||||
v = (1 - 2 * ph) * 0.7
|
||||
end
|
||||
buffer.writef32(samples, (base + i) * 4, v)
|
||||
end
|
||||
end
|
||||
local noiseStart = #waves * CYCLE
|
||||
starts.noise = noiseStart
|
||||
local seed = 12345
|
||||
for i = 0, NOISE - 1 do
|
||||
seed = (seed * 1103515245 + 12345) % 2147483648
|
||||
buffer.writef32(samples, (noiseStart + i) * 4, (seed / 1073741824 - 1) * 0.7)
|
||||
end
|
||||
|
||||
local function region(wave: string, fields: { [string]: number }): { [string]: number }
|
||||
local r = Parse.defaultRegion()
|
||||
local s = starts[wave]
|
||||
r.offset = s
|
||||
r.loopMode = 1
|
||||
r.loopStart = s
|
||||
if wave == "noise" then
|
||||
r.stop, r.loopEnd, r.sampleRate, r.keycenter = s + NOISE, s + NOISE - 1, 44100, 60
|
||||
else
|
||||
r.stop, r.loopEnd, r.sampleRate, r.keycenter = s + CYCLE, s + CYCLE - 1, CYCLE * C4, 60
|
||||
end
|
||||
r.aRelease = 0.08
|
||||
for k, v in fields do
|
||||
r[k] = v
|
||||
end
|
||||
return r
|
||||
end
|
||||
|
||||
-- the 16 GM families: wave + envelope / filter / vibrato
|
||||
local families: { { any } } = {
|
||||
{ "piano", "triangle", { aDecay = 2.5, aSustain = 0, aRelease = 0.25 } },
|
||||
{ "chromatic", "sine", { aDecay = 1.2, aSustain = 0, aRelease = 0.3 } },
|
||||
{ "organ", "square", { aAttack = 0.005, aRelease = 0.05, filterFc = hzToCents(5000) } },
|
||||
{ "guitar", "saw", { aDecay = 1.5, aSustain = 0, aRelease = 0.15, filterFc = hzToCents(3000) } },
|
||||
{ "bass", "triangle", { aDecay = 1.5, aSustain = 0.4, aRelease = 0.1 } },
|
||||
{ "strings", "saw", { aAttack = 0.08, aRelease = 0.3, filterFc = hzToCents(4000), freqVibLFO = hzToCents(5.5), vibLfoToPitch = 8, delayVibLFO = 0.2 } },
|
||||
{ "ensemble", "saw", { aAttack = 0.12, aRelease = 0.4, filterFc = hzToCents(3500), freqVibLFO = hzToCents(5), vibLfoToPitch = 10 } },
|
||||
{ "brass", "saw", { aAttack = 0.03, aRelease = 0.12, filterFc = hzToCents(1200), mAttack = 0.05, mDecay = 0.3, mSustain = 0.4, modEnvToFilterFc = 2400 } },
|
||||
{ "reed", "square", { aAttack = 0.02, aRelease = 0.08, filterFc = hzToCents(2500) } },
|
||||
{ "pipe", "sine", { aAttack = 0.04, aRelease = 0.12, freqVibLFO = hzToCents(5), vibLfoToPitch = 12, delayVibLFO = 0.3 } },
|
||||
{ "lead", "square", { aAttack = 0.005, aRelease = 0.1, filterFc = hzToCents(6000) } },
|
||||
{ "pad", "saw", { aAttack = 0.4, aRelease = 0.8, filterFc = hzToCents(1800), freqModLFO = hzToCents(0.5), modLfoToFilterFc = 600 } },
|
||||
{ "synthfx", "triangle", { aAttack = 0.2, aRelease = 1.0, freqModLFO = hzToCents(3), modLfoToVolume = 60 } },
|
||||
{ "ethnic", "saw", { aDecay = 1.0, aSustain = 0, aRelease = 0.2, filterFc = hzToCents(3000) } },
|
||||
{ "percussive", "sine", { aDecay = 0.4, aSustain = 0, aRelease = 0.1, mDecay = 0.1, mSustain = 0, modEnvToPitch = 1200 } },
|
||||
{ "sfx", "noise", { aAttack = 0.05, aRelease = 0.5, filterFc = hzToCents(3000) } },
|
||||
}
|
||||
local presets = {}
|
||||
for program = 0, 127 do
|
||||
local f = families[program // 8 + 1]
|
||||
table.insert(presets, { name = "fallback " .. f[1], preset = program, bank = 0, regions = { region(f[2], f[3]) } })
|
||||
end
|
||||
|
||||
-- the drum kit (bank 128, every program): one region per key
|
||||
local kit = {}
|
||||
-- fields.semis: the pitch (semitones from the sample's natural pitch) at keytrack 0
|
||||
local function drum(lo: number, hi: number, wave: string, fields: { [string]: number })
|
||||
local r = region(wave, fields)
|
||||
r.lokey, r.hikey = lo, hi
|
||||
r.sampleRate *= 2 ^ ((fields.semis or 0) / 12)
|
||||
r.semis = nil :: any
|
||||
table.insert(kit, r)
|
||||
end
|
||||
local sweep = { mDecay = 0.06, mSustain = 0, modEnvToPitch = 2400 }
|
||||
local function with(a: { [string]: number }, b: { [string]: number }): { [string]: number }
|
||||
local c = table.clone(a)
|
||||
for k, v in b do
|
||||
c[k] = v
|
||||
end
|
||||
return c
|
||||
end
|
||||
drum(0, 34, "noise", { aDecay = 0.1, aSustain = 0, keytrack = 0, filterFc = hzToCents(4000) })
|
||||
drum(35, 36, "sine", with(sweep, { aDecay = 0.35, aSustain = 0, aRelease = 0.05, keytrack = 0, semis = -26 }))
|
||||
drum(37, 37, "noise", { aDecay = 0.05, aSustain = 0, keytrack = 0, filterFc = hzToCents(5000) })
|
||||
drum(38, 38, "noise", { aDecay = 0.2, aSustain = 0, keytrack = 0, filterFc = hzToCents(6000) })
|
||||
drum(39, 39, "noise", { aDecay = 0.15, aSustain = 0, keytrack = 0, filterFc = hzToCents(8000) })
|
||||
drum(40, 40, "noise", { aDecay = 0.18, aSustain = 0, keytrack = 0, filterFc = hzToCents(7000) })
|
||||
for _, k in { 41, 43, 45, 47, 48, 50 } do
|
||||
drum(k, k, "sine", with(sweep, { aDecay = 0.4, aSustain = 0, semis = (k - 41) - 12, keytrack = 0 }))
|
||||
end
|
||||
drum(42, 42, "noise", { aDecay = 0.05, aSustain = 0, group = 1, keytrack = 0, semis = 12 })
|
||||
drum(44, 44, "noise", { aDecay = 0.08, aSustain = 0, group = 1, keytrack = 0, semis = 12 })
|
||||
drum(46, 46, "noise", { aDecay = 0.45, aSustain = 0, group = 1, keytrack = 0, semis = 12 })
|
||||
drum(49, 49, "noise", { aDecay = 1.5, aSustain = 0, keytrack = 0, semis = 7 })
|
||||
drum(51, 51, "noise", { aDecay = 1.0, aSustain = 0, keytrack = 0, semis = 10, filterFc = hzToCents(9000) })
|
||||
drum(52, 59, "noise", { aDecay = 1.2, aSustain = 0, keytrack = 0, semis = 5 })
|
||||
drum(60, 127, "noise", { aDecay = 0.12, aSustain = 0, keytrack = 30, filterFc = hzToCents(5000) })
|
||||
table.insert(presets, { name = "fallback drums", preset = 0, bank = 128, regions = kit })
|
||||
|
||||
cached = {
|
||||
kind = "soundfont",
|
||||
info = { name = "formats-luau fallback" },
|
||||
samples = samples,
|
||||
sampleCount = count,
|
||||
presets = presets,
|
||||
sampleHeaders = {},
|
||||
instruments = {},
|
||||
meta = { source = { format = "fallback" } },
|
||||
}
|
||||
return cached
|
||||
end
|
||||
|
||||
return Fallback
|
||||
@@ -0,0 +1,523 @@
|
||||
--!strict
|
||||
-- codecs/SoundFont/Parse: SoundFont 2.0x (sfbk RIFF) reader. The INFO list, the sdta samples (smpl 16-bit, + sm24
|
||||
-- when present) as one f32 buffer, and the pdta "hydra" (phdr pbag pmod pgen inst ibag imod igen shdr), flattened
|
||||
-- into playable regions per preset: the instrument global zone, the preset global zone and the preset zone's
|
||||
-- generators merged the way TinySoundFont (tsf.h v0.9, MIT, (c) Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt)
|
||||
-- does (tsf_load_presets / tsf_region_operator / tsf_region_envtosecs), with every index and sample offset clamped
|
||||
-- so the synth never reads outside the sample buffer.
|
||||
-- Differences from tsf.h: initialAttenuation is cB * 0.04 dB (FluidSynth's EMU-compatible scale; tsf uses 0.01);
|
||||
-- SF3 (Ogg samples) is not supported; modulators (pmod / imod) are read but not applied (as in tsf.h).
|
||||
-- Never throws: a bad file returns nil, Err.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
|
||||
local Parse = {}
|
||||
|
||||
-- a region (one sample zone of a preset), in "absolute" form: envelope / LFO times in seconds, sustain as a level
|
||||
export type Region = { [string]: number }
|
||||
|
||||
export type Preset = { name: string, preset: number, bank: number, regions: { Region } }
|
||||
|
||||
export type SoundFont = {
|
||||
kind: "soundfont",
|
||||
info: { [string]: string },
|
||||
samples: buffer, -- f32 mono, sampleCount + 1 floats (a zero pad sample past the end)
|
||||
sampleCount: number,
|
||||
presets: { Preset }, -- sorted by bank, then preset number
|
||||
sampleHeaders: { { [string]: any } },
|
||||
instruments: { { name: string, zones: number } },
|
||||
meta: { [string]: any },
|
||||
}
|
||||
|
||||
local GEN_INSTRUMENT, GEN_SAMPLEID = 41, 53
|
||||
|
||||
-- generator op -> { field, mode, limit }. modes: f / i (value, merged by adding then clamping), a (sample address
|
||||
-- add), a15 (coarse address add: * 32768), kr / vr (key / velocity range), loop, group, key (overriding root key)
|
||||
local LIM12K5K = { 1, -12000, 5000 }
|
||||
local LIM12K8K = { 1, -12000, 8000 }
|
||||
local LIM1200 = { 1, -1200, 1200 }
|
||||
local GEN: { [number]: { any } } = {
|
||||
[0] = { "offset", "a" },
|
||||
[1] = { "stop", "a" },
|
||||
[2] = { "loopStart", "a" },
|
||||
[3] = { "loopEnd", "a" },
|
||||
[4] = { "offset", "a15" },
|
||||
[5] = { "modLfoToPitch", "i", { 1, -12000, 12000 } },
|
||||
[6] = { "vibLfoToPitch", "i", { 1, -12000, 12000 } },
|
||||
[7] = { "modEnvToPitch", "i", { 1, -12000, 12000 } },
|
||||
[8] = { "filterFc", "i", { 1, 1500, 13500 } },
|
||||
[9] = { "filterQ", "i", { 1, 0, 960 } },
|
||||
[10] = { "modLfoToFilterFc", "i", { 1, -12000, 12000 } },
|
||||
[11] = { "modEnvToFilterFc", "i", { 1, -12000, 12000 } },
|
||||
[12] = { "stop", "a15" },
|
||||
[13] = { "modLfoToVolume", "i", { 1, -960, 960 } },
|
||||
[17] = { "pan", "f", { 0.001, -0.5, 0.5 } },
|
||||
[21] = { "delayModLFO", "f", LIM12K5K },
|
||||
[22] = { "freqModLFO", "i", { 1, -16000, 4500 } },
|
||||
[23] = { "delayVibLFO", "f", LIM12K5K },
|
||||
[24] = { "freqVibLFO", "i", { 1, -16000, 4500 } },
|
||||
[25] = { "mDelay", "f", LIM12K5K },
|
||||
[26] = { "mAttack", "f", LIM12K8K },
|
||||
[27] = { "mHold", "f", LIM12K5K },
|
||||
[28] = { "mDecay", "f", LIM12K8K },
|
||||
[29] = { "mSustain", "f", { 1, 0, 1000 } },
|
||||
[30] = { "mRelease", "f", LIM12K8K },
|
||||
[31] = { "mKeyHold", "f", LIM1200 },
|
||||
[32] = { "mKeyDecay", "f", LIM1200 },
|
||||
[33] = { "aDelay", "f", LIM12K5K },
|
||||
[34] = { "aAttack", "f", LIM12K8K },
|
||||
[35] = { "aHold", "f", LIM12K5K },
|
||||
[36] = { "aDecay", "f", LIM12K8K },
|
||||
[37] = { "aSustain", "f", { 1, 0, 1440 } },
|
||||
[38] = { "aRelease", "f", LIM12K8K },
|
||||
[39] = { "aKeyHold", "f", LIM1200 },
|
||||
[40] = { "aKeyDecay", "f", LIM1200 },
|
||||
[43] = { "", "kr" },
|
||||
[44] = { "", "vr" },
|
||||
[45] = { "loopStart", "a15" },
|
||||
[48] = { "attenuation", "f", { 0.04, 0, 57.6 } },
|
||||
[50] = { "loopEnd", "a15" },
|
||||
[51] = { "transpose", "i" },
|
||||
[52] = { "tune", "i" },
|
||||
[54] = { "loopMode", "loop" },
|
||||
[56] = { "keytrack", "i" },
|
||||
[57] = { "group", "group" },
|
||||
[58] = { "keycenter", "key" },
|
||||
}
|
||||
-- the merged fields: value generators once each (several ops share a field), then the four address fields
|
||||
local MERGE: { { any } } = {}
|
||||
do
|
||||
local seen: { [string]: boolean } = {}
|
||||
for op = 0, 58 do
|
||||
local g = GEN[op]
|
||||
if g and (g[2] == "f" or g[2] == "i" or g[2] == "a") and not seen[g[1]] then
|
||||
seen[g[1]] = true
|
||||
table.insert(MERGE, g)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local FIELDS = {
|
||||
"loopMode", "sampleRate", "lokey", "hikey", "lovel", "hivel", "group", "offset", "stop", "loopStart", "loopEnd",
|
||||
"transpose", "tune", "keycenter", "keytrack", "attenuation", "pan", "filterQ", "filterFc", "modEnvToPitch",
|
||||
"modEnvToFilterFc", "modLfoToFilterFc", "modLfoToVolume", "delayModLFO", "freqModLFO", "modLfoToPitch",
|
||||
"delayVibLFO", "freqVibLFO", "vibLfoToPitch", "aDelay", "aAttack", "aHold", "aDecay", "aSustain", "aRelease",
|
||||
"aKeyHold", "aKeyDecay", "mDelay", "mAttack", "mHold", "mDecay", "mSustain", "mRelease", "mKeyHold", "mKeyDecay",
|
||||
"sampleIndex",
|
||||
}
|
||||
|
||||
-- clear(relative): tsf_region_clear. relative = a preset zone (all zero: values add to the instrument's)
|
||||
local function clear(relative: boolean): Region
|
||||
local r: Region = {}
|
||||
for _, f in FIELDS do
|
||||
r[f] = 0
|
||||
end
|
||||
r.hikey, r.hivel, r.keycenter = 127, 127, 60
|
||||
if relative then
|
||||
return r
|
||||
end
|
||||
r.keytrack = 100
|
||||
r.keycenter = -1
|
||||
for _, p in { "a", "m" } do
|
||||
for _, s in { "Delay", "Attack", "Hold", "Decay", "Release" } do
|
||||
r[p .. s] = -12000
|
||||
end
|
||||
end
|
||||
r.filterFc = 13500
|
||||
r.delayModLFO, r.delayVibLFO = -12000, -12000
|
||||
return r
|
||||
end
|
||||
|
||||
local function copy(r: Region): Region
|
||||
local c: Region = {}
|
||||
for k, v in r do
|
||||
c[k] = v
|
||||
end
|
||||
return c
|
||||
end
|
||||
|
||||
-- the region defaults in absolute form (seconds, levels): what Fallback builds its regions from
|
||||
function Parse.defaultRegion(): Region
|
||||
local r = clear(false)
|
||||
r.keycenter = 60
|
||||
for _, p in { "a", "m" } do
|
||||
for _, s in { "Delay", "Attack", "Hold", "Decay", "Release" } do
|
||||
r[p .. s] = 0
|
||||
end
|
||||
end
|
||||
r.aSustain, r.mSustain = 1, 1
|
||||
r.delayModLFO, r.delayVibLFO = 0, 0
|
||||
return r
|
||||
end
|
||||
|
||||
-- set one generator (tsf_region_operator with an amount); lo / hi = the two bytes, s = signed 16, w = unsigned 16
|
||||
local function operator(r: Region, op: number, lo: number, hi: number, s: number, w: number)
|
||||
local g = GEN[op]
|
||||
if not g then
|
||||
return
|
||||
end
|
||||
local mode = g[2]
|
||||
if mode == "f" or mode == "i" then
|
||||
r[g[1]] = s
|
||||
elseif mode == "a" then
|
||||
r[g[1]] += s
|
||||
elseif mode == "a15" then
|
||||
r[g[1]] += s * 32768
|
||||
elseif mode == "kr" then
|
||||
r.lokey, r.hikey = lo, hi
|
||||
elseif mode == "vr" then
|
||||
r.lovel, r.hivel = lo, hi
|
||||
elseif mode == "loop" then
|
||||
local m = w % 4
|
||||
r.loopMode = if m == 3 then 2 elseif m == 1 then 1 else 0
|
||||
elseif mode == "group" then
|
||||
r.group = w
|
||||
elseif mode == "key" then
|
||||
r.keycenter = s
|
||||
end
|
||||
end
|
||||
|
||||
-- merge(zone, preset): zone += preset, then clamp (tsf_region_operator without an amount)
|
||||
local function merge(z: Region, p: Region)
|
||||
for _, g in MERGE do
|
||||
local f = g[1]
|
||||
local v = z[f] + p[f]
|
||||
local lim = g[3]
|
||||
if lim then
|
||||
v *= lim[1]
|
||||
v = math.clamp(v, lim[2], lim[3])
|
||||
end
|
||||
z[f] = v
|
||||
end
|
||||
end
|
||||
|
||||
local function tc2s(tc: number): number
|
||||
return 2 ^ (tc / 1200)
|
||||
end
|
||||
|
||||
-- envtosecs (tsf_region_envtosecs): timecents to seconds; hold / decay stay in timecents when they scale by key
|
||||
local function envToSecs(r: Region, p: string, sustainIsGain: boolean)
|
||||
for _, s in { "Delay", "Attack", "Release" } do
|
||||
local v = r[p .. s]
|
||||
r[p .. s] = if v < -11950 then 0 else tc2s(v)
|
||||
end
|
||||
if r[p .. "KeyHold"] == 0 then
|
||||
local v = r[p .. "Hold"]
|
||||
r[p .. "Hold"] = if v < -11950 then 0 else tc2s(v)
|
||||
end
|
||||
if r[p .. "KeyDecay"] == 0 then
|
||||
local v = r[p .. "Decay"]
|
||||
r[p .. "Decay"] = if v < -11950 then 0 else tc2s(v)
|
||||
end
|
||||
local sus = r[p .. "Sustain"]
|
||||
if sus < 0 then
|
||||
sus = 0
|
||||
elseif sustainIsGain then
|
||||
sus = if -sus / 10 > -100 then 10 ^ (-sus / 10 * 0.05) else 0
|
||||
else
|
||||
sus = 1 - sus / 1000
|
||||
end
|
||||
r[p .. "Sustain"] = sus
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ RIFF
|
||||
type Hydra = { [string]: { { number } } }
|
||||
|
||||
-- record layouts: field byte widths (2 / 4 = little endian unsigned, -2 signed, 20 = name, 1 = byte, -1 = signed byte)
|
||||
local LAYOUT: { [string]: { number } } = {
|
||||
phdr = { 20, 2, 2, 2, 4, 4, 4 },
|
||||
pbag = { 2, 2 },
|
||||
pmod = { 2, 2, -2, 2, 2 },
|
||||
pgen = { 2, 2 },
|
||||
inst = { 20, 2 },
|
||||
ibag = { 2, 2 },
|
||||
imod = { 2, 2, -2, 2, 2 },
|
||||
igen = { 2, 2 },
|
||||
shdr = { 20, 4, 4, 4, 4, 4, 1, -1, 2, 2 },
|
||||
}
|
||||
local RECSIZE: { [string]: number } = { phdr = 38, pbag = 4, pmod = 10, pgen = 4, inst = 22, ibag = 4, imod = 10, igen = 4, shdr = 46 }
|
||||
|
||||
local INFO_NAMES = {
|
||||
isng = "engine", INAM = "name", irom = "rom", ICRD = "date", IENG = "author", IPRD = "product",
|
||||
ICOP = "copyright", ICMT = "comment", ISFT = "software",
|
||||
}
|
||||
|
||||
export type Options = { maxRegions: number?, maxSamples: number? }
|
||||
|
||||
-- parse(r, opts?) -> SoundFont | nil, Err
|
||||
function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?)
|
||||
local maxRegions = opts and opts.maxRegions or 1000000
|
||||
local maxSamples = opts and opts.maxSamples or 2 ^ 28
|
||||
if r:string(4) ~= "RIFF" then
|
||||
return r:fail(Err.CORRUPT, "not a RIFF file")
|
||||
end
|
||||
local riffSize = r:u32le()
|
||||
if r:string(4) ~= "sfbk" then
|
||||
return r:fail(Err.CORRUPT, "not a SoundFont (no sfbk)")
|
||||
end
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
local body = r:sub(12, math.max(0, riffSize - 4))
|
||||
local info: { [string]: string } = {}
|
||||
local hydra: Hydra = {}
|
||||
local smpl: Bytes.Reader? = nil
|
||||
local sm24: Bytes.Reader? = nil
|
||||
local version = ""
|
||||
while body:remaining() >= 8 do
|
||||
local id, size = body:string(4), body:u32le()
|
||||
local chunk = body:slice(size)
|
||||
if size % 2 == 1 and body:remaining() > 0 then
|
||||
body:skip(1)
|
||||
end
|
||||
if id == "LIST" and chunk:remaining() >= 4 then
|
||||
local kind = chunk:string(4)
|
||||
while chunk:remaining() >= 8 do
|
||||
local sid, ssize = chunk:string(4), chunk:u32le()
|
||||
local sub = chunk:slice(ssize)
|
||||
if ssize % 2 == 1 and chunk:remaining() > 0 then
|
||||
chunk:skip(1)
|
||||
end
|
||||
if kind == "INFO" then
|
||||
if sid == "ifil" and sub:remaining() >= 4 then
|
||||
local major, minor = sub:u16le(), sub:u16le()
|
||||
version = string.format("%d.%02d", major, minor)
|
||||
elseif INFO_NAMES[sid] then
|
||||
info[INFO_NAMES[sid]] = sub:fixed(sub:remaining())
|
||||
end
|
||||
elseif kind == "sdta" then
|
||||
if sid == "smpl" and not smpl then
|
||||
smpl = sub
|
||||
elseif sid == "sm24" then
|
||||
sm24 = sub
|
||||
end
|
||||
elseif kind == "pdta" then
|
||||
local layout = LAYOUT[sid]
|
||||
if layout and not hydra[sid] then
|
||||
local rs = RECSIZE[sid]
|
||||
local n = sub:remaining() // rs
|
||||
local recs: { { number } } = table.create(n)
|
||||
for i = 1, n do
|
||||
local rec = {}
|
||||
for _, w in layout do
|
||||
if w == 20 then
|
||||
table.insert(rec, 0) -- the name is read separately
|
||||
sub:skip(20)
|
||||
elseif w == 4 then
|
||||
table.insert(rec, sub:u32le())
|
||||
elseif w == 2 then
|
||||
table.insert(rec, sub:u16le())
|
||||
elseif w == -2 then
|
||||
table.insert(rec, sub:i16le())
|
||||
elseif w == 1 then
|
||||
table.insert(rec, sub:u8())
|
||||
else
|
||||
table.insert(rec, sub:i8())
|
||||
end
|
||||
end
|
||||
recs[i] = rec
|
||||
end
|
||||
hydra[sid] = recs
|
||||
if sid == "phdr" or sid == "inst" or sid == "shdr" then
|
||||
local names = table.create(n)
|
||||
for i = 0, n - 1 do
|
||||
names[i + 1] = sub:sub(i * rs, 20):fixed(20)
|
||||
end
|
||||
hydra[sid .. "Names"] = names :: any
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if not smpl then
|
||||
return nil, Err.new(Err.CORRUPT, "no sample data (sdta smpl)")
|
||||
end
|
||||
for _, k in { "phdr", "pbag", "pgen", "inst", "ibag", "igen", "shdr" } do
|
||||
if not hydra[k] or #hydra[k] == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "incomplete hydra: no " .. k .. " records")
|
||||
end
|
||||
end
|
||||
-- samples
|
||||
local sr = smpl :: Bytes.Reader
|
||||
local count = sr:remaining() // 2
|
||||
if count > maxSamples then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d samples is over the %d sample limit", count, maxSamples))
|
||||
end
|
||||
local samples = buffer.create((count + 1) * 4)
|
||||
do
|
||||
local b, p = sr.buf, sr.pos
|
||||
local readi16, writef32 = buffer.readi16, buffer.writef32
|
||||
local s24 = sm24
|
||||
if s24 and s24:remaining() >= count then
|
||||
local q = s24.pos
|
||||
local readu8 = buffer.readu8
|
||||
for i = 0, count - 1 do
|
||||
writef32(samples, i * 4, (readi16(b, p + i * 2) * 256 + readu8(s24.buf, q + i)) / 8388607)
|
||||
end
|
||||
else
|
||||
s24 = nil
|
||||
for i = 0, count - 1 do
|
||||
writef32(samples, i * 4, readi16(b, p + i * 2) / 32767)
|
||||
end
|
||||
end
|
||||
sm24 = s24
|
||||
end
|
||||
-- presets (tsf_load_presets)
|
||||
local phdr, pbag, pgen = hydra.phdr, hydra.pbag, hydra.pgen
|
||||
local inst, ibag, igen, shdr = hydra.inst, hydra.ibag, hydra.igen, hydra.shdr
|
||||
local phdrNames, instNames, shdrNames = (hydra :: any).phdrNames, (hydra :: any).instNames, (hydra :: any).shdrNames
|
||||
local nInst = #inst - 1 -- the last record of each list is the terminal one
|
||||
local nShdr = #shdr - 1
|
||||
local function range(list: { { number } }, i: number, field: number, limit: number): (number, number)
|
||||
-- [list[i][field], list[i + 1][field]) clamped to [1, limit] (1-based record indexes)
|
||||
local a = list[i][field] + 1
|
||||
local b = if list[i + 1] then list[i + 1][field] + 1 else a
|
||||
return math.max(1, a), math.min(b, limit + 1)
|
||||
end
|
||||
local presets: { Preset } = {}
|
||||
local regionTotal = 0
|
||||
for pi = 1, #phdr - 1 do
|
||||
local ph = phdr[pi]
|
||||
local preset: Preset = { name = phdrNames[pi], preset = ph[2], bank = ph[3], regions = {} }
|
||||
local globalRegion = clear(true)
|
||||
local b0, b1 = range(phdr, pi, 4, #pbag)
|
||||
for bi = b0, b1 - 1 do
|
||||
local presetRegion = copy(globalRegion)
|
||||
local hadInstrument = false
|
||||
local g0, g1 = range(pbag, bi, 1, #pgen)
|
||||
for gi = g0, g1 - 1 do
|
||||
local pg = pgen[gi]
|
||||
local op, amount = pg[1], pg[2]
|
||||
local lo, hi = amount % 256, amount // 256
|
||||
local s = if amount >= 32768 then amount - 65536 else amount
|
||||
if op == GEN_INSTRUMENT then
|
||||
hadInstrument = true
|
||||
if amount < nInst then
|
||||
local instRegion = clear(false)
|
||||
local ib0, ib1 = range(inst, amount + 1, 2, #ibag)
|
||||
for ibi = ib0, ib1 - 1 do
|
||||
local zone = copy(instRegion)
|
||||
local hadSample = false
|
||||
local ig0, ig1 = range(ibag, ibi, 1, #igen)
|
||||
for igi = ig0, ig1 - 1 do
|
||||
local ig = igen[igi]
|
||||
local iop, iamt = ig[1], ig[2]
|
||||
if iop == GEN_SAMPLEID then
|
||||
hadSample = true
|
||||
if iamt >= nShdr then
|
||||
break
|
||||
end
|
||||
local ok = not (zone.hikey < presetRegion.lokey or zone.lokey > presetRegion.hikey)
|
||||
and not (zone.hivel < presetRegion.lovel or zone.lovel > presetRegion.hivel)
|
||||
if ok then
|
||||
local z = copy(zone)
|
||||
z.lokey = math.max(z.lokey, presetRegion.lokey)
|
||||
z.hikey = math.min(z.hikey, presetRegion.hikey)
|
||||
z.lovel = math.max(z.lovel, presetRegion.lovel)
|
||||
z.hivel = math.min(z.hivel, presetRegion.hivel)
|
||||
merge(z, presetRegion)
|
||||
envToSecs(z, "a", true)
|
||||
envToSecs(z, "m", false)
|
||||
z.delayModLFO = if z.delayModLFO < -11950 then 0 else tc2s(z.delayModLFO)
|
||||
z.delayVibLFO = if z.delayVibLFO < -11950 then 0 else tc2s(z.delayVibLFO)
|
||||
local sh = shdr[iamt + 1]
|
||||
local sStart, sEnd, sLoopStart, sLoopEnd = sh[2], sh[3], sh[4], sh[5]
|
||||
z.offset = math.clamp(z.offset + sStart, 0, count)
|
||||
local stop = z.stop + sEnd
|
||||
if stop > 0 and stop < count then
|
||||
stop += 1
|
||||
else
|
||||
stop = count
|
||||
end
|
||||
z.stop = math.clamp(stop, 0, count)
|
||||
z.loopStart = math.clamp(z.loopStart + sLoopStart, 0, count)
|
||||
local le = z.loopEnd + sLoopEnd
|
||||
if sLoopEnd > 0 then
|
||||
le -= 1
|
||||
end
|
||||
z.loopEnd = math.clamp(le, 0, count)
|
||||
if z.keycenter == -1 then
|
||||
z.keycenter = sh[7]
|
||||
end
|
||||
z.tune += sh[8]
|
||||
z.sampleRate = sh[6]
|
||||
z.sampleIndex = iamt
|
||||
regionTotal += 1
|
||||
if regionTotal > maxRegions then
|
||||
return nil, Err.new(Err.LIMIT, "over " .. maxRegions .. " regions")
|
||||
end
|
||||
table.insert(preset.regions, z)
|
||||
end
|
||||
break -- sampleID ends a zone's generator list
|
||||
else
|
||||
local ilo, ihi = iamt % 256, iamt // 256
|
||||
operator(zone, iop, ilo, ihi, if iamt >= 32768 then iamt - 65536 else iamt, iamt)
|
||||
end
|
||||
end
|
||||
if ibi == ib0 and not hadSample then
|
||||
instRegion = zone -- the instrument's global zone
|
||||
end
|
||||
end
|
||||
end
|
||||
break -- instrument ends a preset zone's generator list
|
||||
else
|
||||
operator(presetRegion, op, lo, hi, s, amount)
|
||||
end
|
||||
end
|
||||
if bi == b0 and not hadInstrument then
|
||||
globalRegion = presetRegion -- the preset's global zone
|
||||
end
|
||||
end
|
||||
table.insert(presets, preset)
|
||||
end
|
||||
-- sorted by bank, then preset, then file order (tsf's sortedIndex)
|
||||
for i, p in presets do
|
||||
(p :: any)._order = i
|
||||
end
|
||||
table.sort(presets, function(a: Preset, b: Preset): boolean
|
||||
if a.bank ~= b.bank then
|
||||
return a.bank < b.bank
|
||||
end
|
||||
if a.preset ~= b.preset then
|
||||
return a.preset < b.preset
|
||||
end
|
||||
return (a :: any)._order < (b :: any)._order
|
||||
end)
|
||||
for _, p in presets do
|
||||
(p :: any)._order = nil
|
||||
end
|
||||
local headers: { { [string]: any } } = table.create(nShdr)
|
||||
for i = 1, nShdr do
|
||||
local sh = shdr[i]
|
||||
headers[i] = {
|
||||
name = shdrNames[i],
|
||||
start = sh[2],
|
||||
stop = sh[3],
|
||||
loopStart = sh[4],
|
||||
loopEnd = sh[5],
|
||||
sampleRate = sh[6],
|
||||
originalPitch = sh[7],
|
||||
pitchCorrection = sh[8],
|
||||
link = sh[9],
|
||||
type = sh[10],
|
||||
}
|
||||
end
|
||||
local instruments: { { name: string, zones: number } } = table.create(nInst)
|
||||
for i = 1, nInst do
|
||||
instruments[i] = { name = instNames[i], zones = math.max(0, (inst[i + 1][2] or 0) - inst[i][2]) }
|
||||
end
|
||||
local sf: SoundFont = {
|
||||
kind = "soundfont",
|
||||
info = info,
|
||||
samples = samples,
|
||||
sampleCount = count,
|
||||
presets = presets,
|
||||
sampleHeaders = headers,
|
||||
instruments = instruments,
|
||||
meta = { source = { format = "sf2", version = version, sm24 = sm24 ~= nil } },
|
||||
}
|
||||
return sf, nil
|
||||
end
|
||||
|
||||
return Parse
|
||||
@@ -0,0 +1,803 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- codecs/SoundFont/Synth: a SoundFont 2 sample synthesizer with MIDI channels. A port of TinySoundFont (tsf.h v0.9,
|
||||
-- MIT, (c) 2017-2025 Bernhard Schelling, based on SFZero (c) 2012 Steve Folta; licenses/TinySoundFont-LICENSE.txt):
|
||||
-- voices with the DAHDSR volume envelope (exponential decay / release), the modulation envelope to pitch and filter
|
||||
-- cutoff, the modulation and vibrato LFOs (triangle) to pitch / filter / volume, a resonant biquad low-pass, linear
|
||||
-- interpolation, loop modes (none / continuous / until release), 3 dB pan law, exclusive classes; channels with
|
||||
-- program / bank select (CC0 / CC32), drums (bank 128), pitch bend with RPN 0 range and RPN 1 / 2 tuning, CC7 volume,
|
||||
-- CC10 pan, CC11 expression, CC64 sustain, CC120 / 121 / 123. Effects (reverb, chorus) and modulators are not
|
||||
-- implemented (as in tsf.h). Output: interleaved stereo f32, mixed into the caller's buffer.
|
||||
-- Differences from tsf.h: the envelope gain is ramped across each 64-sample block (tsf.h steps it); a voice limit (oldest release voice stolen, else the note is dropped), channels 0..15 only.
|
||||
-- Native, never throws: every buffer index is in range by construction (the regions are clamped by Parse / Fallback,
|
||||
-- the sample buffer has a zero pad sample, the output range is checked before mixing).
|
||||
local Synth = {}
|
||||
|
||||
local readf32, writef32, blen = buffer.readf32, buffer.writef32, buffer.len
|
||||
local exp, log, sqrt, tan, floor = math.exp, math.log, math.sqrt, math.tan, math.floor
|
||||
|
||||
local NONE, DELAY, ATTACK, HOLD, DECAY, SUSTAIN, RELEASE, DONE = 0, 1, 2, 3, 4, 5, 6, 7
|
||||
local BLOCK = 64 -- TSF_RENDER_EFFECTSAMPLEBLOCK: envelopes / LFOs / filter cutoff update per block
|
||||
local FASTRELEASE = 0.01
|
||||
local PI = math.pi
|
||||
local LOOP_NONE, LOOP_SUSTAIN = 0, 2
|
||||
|
||||
type Env = {
|
||||
segment: number,
|
||||
isExp: boolean,
|
||||
isAmp: boolean,
|
||||
vel: number,
|
||||
level: number,
|
||||
slope: number,
|
||||
untilNext: number,
|
||||
delay: number,
|
||||
attack: number,
|
||||
hold: number,
|
||||
decay: number,
|
||||
sustain: number,
|
||||
release: number,
|
||||
}
|
||||
type Lfo = { untilStart: number, level: number, delta: number }
|
||||
export type Voice = {
|
||||
preset: number, -- 1-based preset index, -1 = idle
|
||||
key: number,
|
||||
channel: number,
|
||||
held: boolean, -- note off while sustain was down
|
||||
region: { [string]: number },
|
||||
pitchIn: number, -- timecents
|
||||
pitchOut: number,
|
||||
pos: number,
|
||||
gainDB: number,
|
||||
panL: number,
|
||||
panR: number,
|
||||
playIndex: number,
|
||||
loopStart: number,
|
||||
loopEnd: number,
|
||||
amp: Env,
|
||||
mod: Env,
|
||||
lpActive: boolean,
|
||||
qinv: number,
|
||||
a0: number,
|
||||
a1: number,
|
||||
b1: number,
|
||||
b2: number,
|
||||
z1: number,
|
||||
z2: number,
|
||||
modlfo: Lfo,
|
||||
viblfo: Lfo,
|
||||
}
|
||||
export type Channel = {
|
||||
preset: number,
|
||||
bank: number,
|
||||
pitchWheel: number,
|
||||
midiPan: number,
|
||||
midiVolume: number,
|
||||
midiExpression: number,
|
||||
midiRPN: number,
|
||||
midiData: number,
|
||||
sustain: boolean,
|
||||
panOffset: number,
|
||||
gainDB: number,
|
||||
pitchRange: number,
|
||||
tuning: number,
|
||||
}
|
||||
export type State = {
|
||||
presets: { { regions: { { [string]: number } }, preset: number, bank: number } },
|
||||
lookup: { [number]: number }, -- bank * 128 + preset -> preset index
|
||||
samples: buffer,
|
||||
rate: number,
|
||||
gainDB: number,
|
||||
voices: { Voice },
|
||||
maxVoices: number,
|
||||
playIndex: number,
|
||||
channels: { Channel }, -- [1..16] = MIDI channels 0..15
|
||||
}
|
||||
|
||||
local function tc2s(tc: number): number
|
||||
return 2 ^ (tc / 1200)
|
||||
end
|
||||
local function cents2Hz(c: number): number
|
||||
return 8.176 * 2 ^ (c / 1200)
|
||||
end
|
||||
local function db2gain(db: number): number
|
||||
return if db > -100 then 10 ^ (db * 0.05) else 0
|
||||
end
|
||||
local function gain2db(g: number): number
|
||||
return if g <= 0.00001 then -100 else 20 * math.log10(g)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ envelope
|
||||
local function releaseSamples(e: Env, rate: number): number
|
||||
return floor((if e.release <= 0 then FASTRELEASE else e.release) * rate)
|
||||
end
|
||||
|
||||
local function nextSegment(e: Env, active: number, rate: number)
|
||||
local seg = active
|
||||
if seg == NONE then
|
||||
e.untilNext = floor(e.delay * rate)
|
||||
if e.untilNext > 0 then
|
||||
e.segment, e.isExp, e.level, e.slope = DELAY, false, 0, 0
|
||||
return
|
||||
end
|
||||
seg = DELAY
|
||||
end
|
||||
if seg == DELAY then
|
||||
e.untilNext = floor(e.attack * rate)
|
||||
if e.untilNext > 0 then
|
||||
if not e.isAmp then
|
||||
-- the mod env attack scales with velocity (1 = full duration, 127 = 0.125 x)
|
||||
e.untilNext = floor(e.attack * ((145 - e.vel) / 144) * rate)
|
||||
end
|
||||
e.segment, e.isExp, e.level = ATTACK, false, 0
|
||||
e.slope = if e.untilNext > 0 then 1 / e.untilNext else 1
|
||||
return
|
||||
end
|
||||
seg = ATTACK
|
||||
end
|
||||
if seg == ATTACK then
|
||||
e.untilNext = floor(e.hold * rate)
|
||||
if e.untilNext > 0 then
|
||||
e.segment, e.isExp, e.level, e.slope = HOLD, false, 1, 0
|
||||
return
|
||||
end
|
||||
seg = HOLD
|
||||
end
|
||||
if seg == HOLD then
|
||||
e.untilNext = floor(e.decay * rate)
|
||||
if e.untilNext > 0 then
|
||||
e.segment, e.level = DECAY, 1
|
||||
if e.isAmp then
|
||||
local mystery = -9.226 / e.untilNext -- LinuxSampler's decay curve (as tsf.h)
|
||||
e.slope = exp(mystery)
|
||||
e.isExp = true
|
||||
if e.sustain > 0 then
|
||||
e.untilNext = floor(log(e.sustain) / mystery)
|
||||
end
|
||||
else
|
||||
e.slope = -1 / e.untilNext
|
||||
e.untilNext = floor(e.decay * (1 - e.sustain) * rate)
|
||||
e.isExp = false
|
||||
end
|
||||
return
|
||||
end
|
||||
seg = DECAY
|
||||
end
|
||||
if seg == DECAY then
|
||||
e.segment, e.level, e.slope, e.untilNext, e.isExp = SUSTAIN, e.sustain, 0, 0x7FFFFFFF, false
|
||||
return
|
||||
end
|
||||
if seg == SUSTAIN then
|
||||
e.segment = RELEASE
|
||||
e.untilNext = math.max(1, releaseSamples(e, rate))
|
||||
if e.isAmp then
|
||||
e.slope = exp(-9.226 / e.untilNext)
|
||||
e.isExp = true
|
||||
else
|
||||
e.slope = -e.level / e.untilNext
|
||||
e.isExp = false
|
||||
end
|
||||
return
|
||||
end
|
||||
e.segment, e.isExp, e.level, e.slope, e.untilNext = DONE, false, 0, 0, 0x7FFFFFF
|
||||
end
|
||||
|
||||
local function envSetup(e: Env, r: { [string]: number }, p: string, key: number, vel: number, isAmp: boolean, rate: number)
|
||||
e.delay, e.attack, e.hold, e.decay = r[p .. "Delay"], r[p .. "Attack"], r[p .. "Hold"], r[p .. "Decay"]
|
||||
e.sustain, e.release = r[p .. "Sustain"], r[p .. "Release"]
|
||||
local kh, kd = r[p .. "KeyHold"], r[p .. "KeyDecay"]
|
||||
if kh ~= 0 then
|
||||
local h = e.hold + kh * (60 - key)
|
||||
e.hold = if h < -10000 then 0 else tc2s(h)
|
||||
end
|
||||
if kd ~= 0 then
|
||||
local d = e.decay + kd * (60 - key)
|
||||
e.decay = if d < -10000 then 0 else tc2s(d)
|
||||
end
|
||||
e.vel, e.isAmp = vel, isAmp
|
||||
nextSegment(e, NONE, rate)
|
||||
end
|
||||
|
||||
local function envProcess(e: Env, n: number, rate: number)
|
||||
local slope = e.slope
|
||||
if slope ~= 0 then
|
||||
if e.isExp then
|
||||
e.level *= slope ^ n
|
||||
else
|
||||
e.level += slope * n
|
||||
end
|
||||
end
|
||||
e.untilNext -= n
|
||||
if e.untilNext <= 0 then
|
||||
nextSegment(e, e.segment, rate)
|
||||
end
|
||||
end
|
||||
|
||||
local function newEnv(): Env
|
||||
return { segment = DONE, isExp = false, isAmp = false, vel = 0, level = 0, slope = 0, untilNext = 0, delay = 0, attack = 0, hold = 0, decay = 0, sustain = 0, release = 0 }
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ filter / lfo
|
||||
local function lowpassSetup(v: Voice, fc: number)
|
||||
-- the biquad from earlevel.com (as tsf.h)
|
||||
local k = tan(PI * fc)
|
||||
local kk = k * k
|
||||
local norm = 1 / (1 + k * v.qinv + kk)
|
||||
v.a0 = kk * norm
|
||||
v.a1 = 2 * v.a0
|
||||
v.b1 = 2 * (kk - 1) * norm
|
||||
v.b2 = (1 - k * v.qinv + kk) * norm
|
||||
end
|
||||
|
||||
local function lfoSetup(l: Lfo, delay: number, freqCents: number, rate: number)
|
||||
l.untilStart = floor(delay * rate)
|
||||
l.delta = 4 * cents2Hz(freqCents) / rate
|
||||
l.level = 0
|
||||
end
|
||||
|
||||
local function lfoProcess(l: Lfo, n: number)
|
||||
if l.untilStart > n then
|
||||
l.untilStart -= n
|
||||
return
|
||||
end
|
||||
l.level += l.delta * n
|
||||
if l.level > 1 then
|
||||
l.delta = -l.delta
|
||||
l.level = 2 - l.level
|
||||
elseif l.level < -1 then
|
||||
l.delta = -l.delta
|
||||
l.level = -2 - l.level
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ voices
|
||||
local function calcPitch(v: Voice, shift: number, rate: number)
|
||||
local r = v.region
|
||||
local note = v.key + r.transpose + r.tune / 100
|
||||
local adjusted = r.keycenter + (note - r.keycenter) * (r.keytrack / 100) + shift
|
||||
v.pitchIn = adjusted * 100
|
||||
v.pitchOut = r.sampleRate / (tc2s(r.keycenter * 100) * rate)
|
||||
end
|
||||
|
||||
local function setPan(v: Voice, pan: number)
|
||||
if pan <= -0.5 then
|
||||
v.panL, v.panR = 1, 0
|
||||
elseif pan >= 0.5 then
|
||||
v.panL, v.panR = 0, 1
|
||||
else
|
||||
v.panL, v.panR = sqrt(0.5 - pan), sqrt(0.5 + pan)
|
||||
end
|
||||
end
|
||||
|
||||
local function channelShift(c: Channel): number
|
||||
return if c.pitchWheel == 8192 then c.tuning else (c.pitchWheel / 16383 * c.pitchRange * 2) - c.pitchRange + c.tuning
|
||||
end
|
||||
|
||||
local function voiceEnd(s: State, v: Voice)
|
||||
nextSegment(v.amp, SUSTAIN, s.rate)
|
||||
nextSegment(v.mod, SUSTAIN, s.rate)
|
||||
if v.region.loopMode == LOOP_SUSTAIN then
|
||||
v.loopEnd = v.loopStart -- keep playing, stop looping
|
||||
end
|
||||
end
|
||||
|
||||
local function voiceEndQuick(s: State, v: Voice)
|
||||
v.amp.release = 0
|
||||
nextSegment(v.amp, SUSTAIN, s.rate)
|
||||
v.mod.release = 0
|
||||
nextSegment(v.mod, SUSTAIN, s.rate)
|
||||
end
|
||||
|
||||
local function newVoice(): Voice
|
||||
return {
|
||||
preset = -1, key = 0, channel = 0, held = false, region = {}, pitchIn = 0, pitchOut = 0, pos = 0, gainDB = 0,
|
||||
panL = 0, panR = 0, playIndex = 0, loopStart = 0, loopEnd = 0, amp = newEnv(), mod = newEnv(),
|
||||
lpActive = false, qinv = 0, a0 = 0, a1 = 0, b1 = 0, b2 = 0, z1 = 0, z2 = 0,
|
||||
modlfo = { untilStart = 0, level = 0, delta = 0 }, viblfo = { untilStart = 0, level = 0, delta = 0 },
|
||||
}
|
||||
end
|
||||
|
||||
local function newChannel(): Channel
|
||||
return {
|
||||
preset = 1, bank = 0, pitchWheel = 8192, midiPan = 8192, midiVolume = 16383, midiExpression = 16383,
|
||||
midiRPN = 0xFFFF, midiData = 0, sustain = false, panOffset = 0, gainDB = 0, pitchRange = 2, tuning = 0,
|
||||
}
|
||||
end
|
||||
|
||||
-- new(sf, sampleRate, opts) -> State. sf: { presets, samples } (Parse.parse or Fallback.build).
|
||||
-- opts.gain: output gain (linear, default 0.5); opts.maxVoices (default 256)
|
||||
function Synth.new(sf: any, rate: number, gain: number?, maxVoices: number?): State
|
||||
local lookup: { [number]: number } = {}
|
||||
for i, p in sf.presets do
|
||||
local k = p.bank * 128 + p.preset
|
||||
if lookup[k] == nil then
|
||||
lookup[k] = i
|
||||
end
|
||||
end
|
||||
local s: State = {
|
||||
presets = sf.presets,
|
||||
lookup = lookup,
|
||||
samples = sf.samples,
|
||||
rate = rate,
|
||||
gainDB = gain2db(gain or 0.5),
|
||||
voices = {},
|
||||
maxVoices = maxVoices or 256,
|
||||
playIndex = 0,
|
||||
channels = {},
|
||||
}
|
||||
for ch = 1, 16 do
|
||||
s.channels[ch] = newChannel()
|
||||
end
|
||||
for ch = 0, 15 do
|
||||
Synth.program(s, ch, 0)
|
||||
end
|
||||
return s
|
||||
end
|
||||
|
||||
local function presetIndex(s: State, bank: number, preset: number): number
|
||||
return s.lookup[bank * 128 + preset] or -1
|
||||
end
|
||||
|
||||
-- noteOn(s, channel, key, velocity 0..127)
|
||||
function Synth.noteOn(s: State, ch: number, key: number, velocity: number)
|
||||
local c = s.channels[ch + 1]
|
||||
if not c then
|
||||
return
|
||||
end
|
||||
if velocity <= 0 then
|
||||
Synth.noteOff(s, ch, key)
|
||||
return
|
||||
end
|
||||
local pi = c.preset
|
||||
local preset = s.presets[pi]
|
||||
if not preset then
|
||||
return
|
||||
end
|
||||
local vel = math.min(velocity, 127) / 127
|
||||
local midiVel = floor(vel * 127)
|
||||
local rate = s.rate
|
||||
local voices = s.voices
|
||||
local playIndex = s.playIndex
|
||||
s.playIndex += 1
|
||||
for _, region in preset.regions do
|
||||
if key < region.lokey or key > region.hikey or midiVel < region.lovel or midiVel > region.hivel then
|
||||
continue
|
||||
end
|
||||
local voice: Voice? = nil
|
||||
if region.group ~= 0 then
|
||||
for _, v in voices do
|
||||
if v.preset == pi and v.region.group == region.group then
|
||||
voiceEndQuick(s, v)
|
||||
elseif v.preset == -1 and not voice then
|
||||
voice = v
|
||||
end
|
||||
end
|
||||
else
|
||||
for _, v in voices do
|
||||
if v.preset == -1 then
|
||||
voice = v
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
if not voice then
|
||||
if #voices < s.maxVoices then
|
||||
local v = newVoice()
|
||||
table.insert(voices, v)
|
||||
voice = v
|
||||
else
|
||||
local best = -1e18
|
||||
for _, v in voices do
|
||||
if v.amp.segment == RELEASE then
|
||||
local done = releaseSamples(v.amp, rate) - v.amp.untilNext
|
||||
if done > best then
|
||||
best, voice = done, v
|
||||
end
|
||||
end
|
||||
end
|
||||
if not voice then
|
||||
continue
|
||||
end
|
||||
end
|
||||
end
|
||||
local v = voice :: Voice
|
||||
v.region = region
|
||||
v.preset = pi
|
||||
v.key = key
|
||||
v.channel = ch
|
||||
v.playIndex = playIndex
|
||||
v.held = false
|
||||
v.gainDB = s.gainDB - region.attenuation - gain2db(1 / vel) + c.gainDB
|
||||
calcPitch(v, channelShift(c), rate)
|
||||
setPan(v, region.pan + c.panOffset)
|
||||
v.pos = region.offset
|
||||
local doLoop = region.loopMode ~= LOOP_NONE and region.loopStart < region.loopEnd
|
||||
v.loopStart = if doLoop then region.loopStart else 0
|
||||
v.loopEnd = if doLoop then region.loopEnd else 0
|
||||
envSetup(v.amp, region, "a", key, midiVel, true, rate)
|
||||
envSetup(v.mod, region, "m", key, midiVel, false, rate)
|
||||
local fc = if region.filterFc <= 13500 then cents2Hz(region.filterFc) / rate else 1
|
||||
v.qinv = 1 / 10 ^ ((region.filterQ / 10) / 20)
|
||||
v.z1, v.z2 = 0, 0
|
||||
v.lpActive = fc < 0.499
|
||||
if v.lpActive then
|
||||
lowpassSetup(v, fc)
|
||||
end
|
||||
lfoSetup(v.modlfo, region.delayModLFO, region.freqModLFO, rate)
|
||||
lfoSetup(v.viblfo, region.delayVibLFO, region.freqVibLFO, rate)
|
||||
end
|
||||
end
|
||||
|
||||
-- noteOff(s, channel, key): ends the oldest matching note (all its regions); held while sustain is down
|
||||
function Synth.noteOff(s: State, ch: number, key: number)
|
||||
local c = s.channels[ch + 1]
|
||||
if not c then
|
||||
return
|
||||
end
|
||||
local first = -1
|
||||
for _, v in s.voices do
|
||||
if v.preset ~= -1 and v.channel == ch and v.key == key and v.amp.segment < RELEASE and not v.held then
|
||||
if first == -1 or v.playIndex < first then
|
||||
first = v.playIndex
|
||||
end
|
||||
end
|
||||
end
|
||||
if first == -1 then
|
||||
return
|
||||
end
|
||||
for _, v in s.voices do
|
||||
if v.preset ~= -1 and v.channel == ch and v.key == key and v.amp.segment < RELEASE and not v.held and v.playIndex == first then
|
||||
if c.sustain then
|
||||
v.held = true
|
||||
else
|
||||
voiceEnd(s, v)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function applyPitch(s: State, ch: number, c: Channel)
|
||||
local shift = channelShift(c)
|
||||
for _, v in s.voices do
|
||||
if v.preset ~= -1 and v.channel == ch then
|
||||
calcPitch(v, shift, s.rate)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function setVolume(s: State, ch: number, c: Channel, volume: number)
|
||||
local db = gain2db(volume)
|
||||
if db == c.gainDB then
|
||||
return
|
||||
end
|
||||
local change = db - c.gainDB
|
||||
for _, v in s.voices do
|
||||
if v.preset ~= -1 and v.channel == ch then
|
||||
v.gainDB += change
|
||||
end
|
||||
end
|
||||
c.gainDB = db
|
||||
end
|
||||
|
||||
local function setChannelPan(s: State, ch: number, c: Channel, pan: number)
|
||||
for _, v in s.voices do
|
||||
if v.preset ~= -1 and v.channel == ch then
|
||||
setPan(v, v.region.pan + pan - 0.5)
|
||||
end
|
||||
end
|
||||
c.panOffset = pan - 0.5
|
||||
end
|
||||
|
||||
local function setTuning(s: State, ch: number, c: Channel, tuning: number)
|
||||
if c.tuning ~= tuning then
|
||||
c.tuning = tuning
|
||||
applyPitch(s, ch, c)
|
||||
end
|
||||
end
|
||||
|
||||
local function setPitchRange(s: State, ch: number, c: Channel, range: number)
|
||||
if c.pitchRange ~= range then
|
||||
c.pitchRange = range
|
||||
if c.pitchWheel ~= 8192 then
|
||||
applyPitch(s, ch, c)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function setSustain(s: State, ch: number, c: Channel, on: boolean)
|
||||
if c.sustain == on then
|
||||
return
|
||||
end
|
||||
c.sustain = on
|
||||
if on then
|
||||
return
|
||||
end
|
||||
for _, v in s.voices do
|
||||
if v.preset ~= -1 and v.channel == ch and v.amp.segment < RELEASE and v.held then
|
||||
voiceEnd(s, v)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- program(s, channel, program): bank select + program change (channel 9: drums, bank 128)
|
||||
function Synth.program(s: State, ch: number, program: number)
|
||||
local c = s.channels[ch + 1]
|
||||
if not c then
|
||||
return
|
||||
end
|
||||
local bank = c.bank % 32768
|
||||
local idx
|
||||
if ch == 9 then
|
||||
idx = presetIndex(s, 128 + bank, program)
|
||||
if idx == -1 then
|
||||
idx = presetIndex(s, 128, program)
|
||||
end
|
||||
if idx == -1 then
|
||||
idx = presetIndex(s, 128, 0)
|
||||
end
|
||||
if idx == -1 then
|
||||
idx = presetIndex(s, bank, program)
|
||||
end
|
||||
else
|
||||
idx = presetIndex(s, bank, program)
|
||||
end
|
||||
if idx == -1 then
|
||||
idx = presetIndex(s, 0, program)
|
||||
end
|
||||
if idx ~= -1 then
|
||||
c.preset = idx
|
||||
end
|
||||
end
|
||||
|
||||
-- pitchBend(s, channel, 0..16383)
|
||||
function Synth.pitchBend(s: State, ch: number, value: number)
|
||||
local c = s.channels[ch + 1]
|
||||
if not c or c.pitchWheel == value then
|
||||
return
|
||||
end
|
||||
c.pitchWheel = value
|
||||
applyPitch(s, ch, c)
|
||||
end
|
||||
|
||||
-- control(s, channel, controller, value 0..127)
|
||||
function Synth.control(s: State, ch: number, cc: number, value: number)
|
||||
local c = s.channels[ch + 1]
|
||||
if not c then
|
||||
return
|
||||
end
|
||||
local volume, pan, data = false, false, false
|
||||
if cc == 7 then
|
||||
c.midiVolume = c.midiVolume % 128 + value * 128
|
||||
volume = true
|
||||
elseif cc == 39 then
|
||||
c.midiVolume = c.midiVolume - c.midiVolume % 128 + value
|
||||
volume = true
|
||||
elseif cc == 11 then
|
||||
c.midiExpression = c.midiExpression % 128 + value * 128
|
||||
volume = true
|
||||
elseif cc == 43 then
|
||||
c.midiExpression = c.midiExpression - c.midiExpression % 128 + value
|
||||
volume = true
|
||||
elseif cc == 10 then
|
||||
c.midiPan = c.midiPan % 128 + value * 128
|
||||
pan = true
|
||||
elseif cc == 42 then
|
||||
c.midiPan = c.midiPan - c.midiPan % 128 + value
|
||||
pan = true
|
||||
elseif cc == 6 then
|
||||
c.midiData = c.midiData % 128 + value * 128
|
||||
data = true
|
||||
elseif cc == 38 then
|
||||
c.midiData = c.midiData - c.midiData % 128 + value
|
||||
data = true
|
||||
elseif cc == 0 then
|
||||
c.bank = 0x8000 + value -- bank select MSB alone acts like LSB (as tsf.h)
|
||||
elseif cc == 32 then
|
||||
c.bank = (if c.bank >= 0x8000 then (c.bank % 128) * 128 else 0) + value
|
||||
elseif cc == 101 then
|
||||
local rpn = if c.midiRPN == 0xFFFF then 0 else c.midiRPN
|
||||
c.midiRPN = rpn % 128 + value * 128
|
||||
elseif cc == 100 then
|
||||
local rpn = if c.midiRPN == 0xFFFF then 0 else c.midiRPN
|
||||
c.midiRPN = rpn - rpn % 128 + value
|
||||
elseif cc == 98 or cc == 99 then
|
||||
c.midiRPN = 0xFFFF
|
||||
elseif cc == 64 then
|
||||
setSustain(s, ch, c, value >= 64)
|
||||
elseif cc == 120 then
|
||||
for _, v in s.voices do
|
||||
if v.preset ~= -1 and v.channel == ch and (v.amp.segment < RELEASE or v.amp.release ~= 0) then
|
||||
voiceEndQuick(s, v)
|
||||
end
|
||||
end
|
||||
elseif cc == 123 then
|
||||
for _, v in s.voices do
|
||||
if v.preset ~= -1 and v.channel == ch and v.amp.segment < RELEASE then
|
||||
voiceEnd(s, v)
|
||||
end
|
||||
end
|
||||
elseif cc == 121 then
|
||||
c.midiVolume, c.midiExpression, c.midiPan, c.bank, c.midiRPN, c.midiData = 16383, 16383, 8192, 0, 0xFFFF, 0
|
||||
setVolume(s, ch, c, 1)
|
||||
setChannelPan(s, ch, c, 0.5)
|
||||
setPitchRange(s, ch, c, 2)
|
||||
setTuning(s, ch, c, 0)
|
||||
end
|
||||
if volume then
|
||||
-- the cube gives a decent MIDI volume curve (tsf.h)
|
||||
setVolume(s, ch, c, ((c.midiVolume / 16383) * (c.midiExpression / 16383)) ^ 3)
|
||||
elseif pan then
|
||||
setChannelPan(s, ch, c, c.midiPan / 16383)
|
||||
elseif data then
|
||||
if c.midiRPN == 0 then
|
||||
setPitchRange(s, ch, c, c.midiData // 128 + 0.01 * (c.midiData % 128))
|
||||
elseif c.midiRPN == 1 then
|
||||
local t = c.tuning
|
||||
setTuning(s, ch, c, (if t < 0 then math.ceil(t) else floor(t)) + (c.midiData - 8192) / 8192)
|
||||
elseif c.midiRPN == 2 and cc == 6 then
|
||||
local t = c.tuning
|
||||
setTuning(s, ch, c, (value - 64) + (t - (if t < 0 then math.ceil(t) else floor(t))))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- midi(s, status, d1, d2): one channel message
|
||||
function Synth.midi(s: State, status: number, d1: number, d2: number)
|
||||
local kind, ch = status // 16, status % 16
|
||||
if kind == 9 then
|
||||
Synth.noteOn(s, ch, d1, d2)
|
||||
elseif kind == 8 then
|
||||
Synth.noteOff(s, ch, d1)
|
||||
elseif kind == 11 then
|
||||
Synth.control(s, ch, d1, d2)
|
||||
elseif kind == 12 then
|
||||
Synth.program(s, ch, d1)
|
||||
elseif kind == 14 then
|
||||
Synth.pitchBend(s, ch, d1 + d2 * 128)
|
||||
end
|
||||
end
|
||||
|
||||
-- reset(s): all voices off, channels back to their defaults
|
||||
function Synth.reset(s: State)
|
||||
for _, v in s.voices do
|
||||
v.preset = -1
|
||||
end
|
||||
for ch = 1, 16 do
|
||||
s.channels[ch] = newChannel()
|
||||
end
|
||||
for ch = 0, 15 do
|
||||
Synth.program(s, ch, 0)
|
||||
end
|
||||
end
|
||||
|
||||
-- active(s) -> the number of sounding voices
|
||||
function Synth.active(s: State): number
|
||||
local n = 0
|
||||
for _, v in s.voices do
|
||||
if v.preset ~= -1 then
|
||||
n += 1
|
||||
end
|
||||
end
|
||||
return n
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ render
|
||||
local function voiceRender(s: State, v: Voice, out: buffer, frame: number, numSamples: number)
|
||||
local region = v.region
|
||||
local input = s.samples
|
||||
local rate = s.rate
|
||||
local modEnvToPitch, modEnvToFilterFc = region.modEnvToPitch, region.modEnvToFilterFc
|
||||
local modLfoToPitch, modLfoToFilterFc, modLfoToVolume = region.modLfoToPitch, region.modLfoToFilterFc, region.modLfoToVolume
|
||||
local vibLfoToPitch = region.vibLfoToPitch
|
||||
local updateModEnv = modEnvToPitch ~= 0 or modEnvToFilterFc ~= 0
|
||||
local updateModLfo = v.modlfo.delta ~= 0 and (modLfoToPitch ~= 0 or modLfoToFilterFc ~= 0 or modLfoToVolume ~= 0)
|
||||
local updateVibLfo = v.viblfo.delta ~= 0 and vibLfoToPitch ~= 0
|
||||
local loopStart, loopEnd = v.loopStart, v.loopEnd
|
||||
local isLooping = loopStart < loopEnd
|
||||
local endD = region.stop
|
||||
local loopEndD = loopEnd + 1
|
||||
local loopLen = loopEnd - loopStart + 1
|
||||
local pos = v.pos
|
||||
local lpActive, a0, a1, b1, b2, z1, z2 = v.lpActive, v.a0, v.a1, v.b1, v.b2, v.z1, v.z2
|
||||
local dynamicLowpass = modLfoToFilterFc ~= 0 or modEnvToFilterFc ~= 0
|
||||
local dynamicPitch = modLfoToPitch ~= 0 or modEnvToPitch ~= 0 or vibLfoToPitch ~= 0
|
||||
local dynamicGain = modLfoToVolume ~= 0
|
||||
local filterFc = region.filterFc
|
||||
local pitchRatio = if dynamicPitch then 0 else tc2s(v.pitchIn) * v.pitchOut
|
||||
local noteGain = if dynamicGain then 0 else db2gain(v.gainDB)
|
||||
local o = frame * 8
|
||||
while numSamples > 0 do
|
||||
local block = if numSamples > BLOCK then BLOCK else numSamples
|
||||
numSamples -= block
|
||||
if dynamicLowpass then
|
||||
local fres = filterFc + v.modlfo.level * modLfoToFilterFc + v.mod.level * modEnvToFilterFc
|
||||
local fc = if fres <= 13500 then cents2Hz(fres) / rate else 1
|
||||
lpActive = fc < 0.499
|
||||
if lpActive then
|
||||
lowpassSetup(v, fc)
|
||||
a0, a1, b1, b2 = v.a0, v.a1, v.b1, v.b2
|
||||
end
|
||||
end
|
||||
if dynamicPitch then
|
||||
pitchRatio = tc2s(v.pitchIn + (v.modlfo.level * modLfoToPitch + v.viblfo.level * vibLfoToPitch + v.mod.level * modEnvToPitch)) * v.pitchOut
|
||||
end
|
||||
if dynamicGain then
|
||||
noteGain = db2gain(v.gainDB + v.modlfo.level * modLfoToVolume * 0.1)
|
||||
end
|
||||
local gainMono = noteGain * v.amp.level
|
||||
envProcess(v.amp, block, rate)
|
||||
if updateModEnv then
|
||||
envProcess(v.mod, block, rate)
|
||||
end
|
||||
if updateModLfo then
|
||||
lfoProcess(v.modlfo, block)
|
||||
end
|
||||
if updateVibLfo then
|
||||
lfoProcess(v.viblfo, block)
|
||||
end
|
||||
-- ramp the gain across the block to the envelope's next level (tsf.h steps it per block: zipper noise)
|
||||
local gainNext = noteGain * v.amp.level
|
||||
local step = (gainNext - gainMono) / block
|
||||
local panL, panR = v.panL, v.panR
|
||||
local g = gainMono
|
||||
local k = block
|
||||
while k > 0 and pos < endD do
|
||||
k -= 1
|
||||
local ip = floor(pos)
|
||||
local np = if ip >= loopEnd and isLooping then loopStart else ip + 1
|
||||
local s0 = readf32(input, ip * 4)
|
||||
local val = s0 + (readf32(input, np * 4) - s0) * (pos - ip)
|
||||
if lpActive then
|
||||
local y = val * a0 + z1
|
||||
z1 = val * a1 + z2 - b1 * y
|
||||
z2 = val * a0 - b2 * y
|
||||
val = y
|
||||
end
|
||||
val *= g
|
||||
g += step
|
||||
writef32(out, o, readf32(out, o) + val * panL)
|
||||
writef32(out, o + 4, readf32(out, o + 4) + val * panR)
|
||||
o += 8
|
||||
pos += pitchRatio
|
||||
if pos >= loopEndD and isLooping then
|
||||
pos -= loopLen
|
||||
end
|
||||
end
|
||||
o += k * 8
|
||||
if not (pos < endD) or v.amp.segment == DONE then
|
||||
v.preset = -1
|
||||
return
|
||||
end
|
||||
end
|
||||
v.pos = pos
|
||||
v.lpActive, v.z1, v.z2 = lpActive, z1, z2
|
||||
end
|
||||
|
||||
-- render(s, out, frame, n): mixes n stereo frames into out (interleaved f32) starting at frame; out-of-range
|
||||
-- requests are clipped to the buffer
|
||||
function Synth.render(s: State, out: buffer, frame: number, n: number)
|
||||
local room = blen(out) // 8 - frame
|
||||
if frame < 0 or room <= 0 then
|
||||
return
|
||||
end
|
||||
if n > room then
|
||||
n = room
|
||||
end
|
||||
if n <= 0 then
|
||||
return
|
||||
end
|
||||
-- the sample buffer must hold every region's range + the pad sample (Parse / Fallback guarantee it; checked here
|
||||
-- once so a hand-made SoundFont cannot index outside it)
|
||||
local count = blen(s.samples) // 4 - 1
|
||||
for _, v in s.voices do
|
||||
if v.preset ~= -1 then
|
||||
local r = v.region
|
||||
if r.stop > count or r.loopEnd > count or r.offset < 0 or r.loopStart < 0 or v.pos < 0 then
|
||||
v.preset = -1
|
||||
else
|
||||
voiceRender(s, v, out, frame, n)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return Synth
|
||||
@@ -0,0 +1,69 @@
|
||||
--!strict
|
||||
-- codecs/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by
|
||||
-- music/sf2 (the file format) and music/midi (rendering). The synth is a port of TinySoundFont (tsf.h v0.9, MIT,
|
||||
-- (c) 2017-2025 Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt); see Parse / Synth for what is covered.
|
||||
-- Without a bank, fallback() is a generated General MIDI set of simple waveforms (sine / triangle / square / saw /
|
||||
-- noise) with a drum kit.
|
||||
--
|
||||
-- local SoundFont = require("@formats/codecs/SoundFont")
|
||||
-- local sf, err = SoundFont.parse(buf) -- buffer | string | core/Bytes Reader -> SoundFont | nil, Err
|
||||
-- local sf = SoundFont.fallback() -- the built-in waveform set
|
||||
-- local s = SoundFont.synth(sf, 44100, { gain = 0.5 }) -- a synth State; SoundFont.Synth.midi(s, 0x90, 60, 100)
|
||||
-- SoundFont.Synth.render(s, out, frame, n) -- mix n stereo f32 frames into out at frame
|
||||
--
|
||||
-- Never throws: bad data returns nil, Err.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Parse = require("@formats/codecs/SoundFont/Parse")
|
||||
local Synth = require("@formats/codecs/SoundFont/Synth")
|
||||
local Fallback = require("@formats/codecs/SoundFont/Fallback")
|
||||
|
||||
local SoundFont = {}
|
||||
|
||||
export type SoundFont = Parse.SoundFont
|
||||
export type State = Synth.State
|
||||
|
||||
SoundFont.Synth = Synth
|
||||
SoundFont.defaultRegion = Parse.defaultRegion
|
||||
|
||||
-- sniff(r) -> true when r starts with RIFF....sfbk
|
||||
function SoundFont.sniff(r: Bytes.Reader): boolean
|
||||
return r:peek(4) == "RIFF" and r:peek(4, 8) == "sfbk"
|
||||
end
|
||||
|
||||
-- parse(src, opts?) -> SoundFont | nil, Err. src: buffer | string | Reader. opts.maxRegions (default 10^6),
|
||||
-- opts.maxSamples (default 2^28)
|
||||
function SoundFont.parse(src: any, opts: Parse.Options?): (SoundFont?, Err.Err?)
|
||||
local r: Bytes.Reader
|
||||
if type(src) == "string" then
|
||||
r = Bytes.reader(buffer.fromstring(src))
|
||||
elseif type(src) == "buffer" then
|
||||
r = Bytes.reader(src)
|
||||
elseif type(src) == "table" and type(src.buf) == "buffer" then
|
||||
r = Bytes.reader(src.buf, src.pos, src.limit - src.pos)
|
||||
else
|
||||
return nil, Err.new(Err.ARG, "soundfont: expected a buffer, string or Reader")
|
||||
end
|
||||
local ok, sf, err = pcall(Parse.parse, r, opts)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "soundfont parser failed: " .. tostring(sf))
|
||||
end
|
||||
return sf, err
|
||||
end
|
||||
|
||||
-- fallback() -> the built-in General MIDI waveform set
|
||||
function SoundFont.fallback(): SoundFont
|
||||
return Fallback.build()
|
||||
end
|
||||
|
||||
-- isSoundFont(v) -> true for a parsed / fallback SoundFont value
|
||||
function SoundFont.isSoundFont(v: any): boolean
|
||||
return type(v) == "table" and v.kind == "soundfont" and type(v.samples) == "buffer" and type(v.presets) == "table"
|
||||
end
|
||||
|
||||
-- synth(sf?, sampleRate?, opts?) -> State. opts.gain (linear, default 0.5), opts.maxVoices (default 256)
|
||||
function SoundFont.synth(sf: SoundFont?, sampleRate: number?, opts: { gain: number?, maxVoices: number? }?): State
|
||||
return Synth.new(sf or Fallback.build(), sampleRate or 44100, opts and opts.gain, opts and opts.maxVoices)
|
||||
end
|
||||
|
||||
return SoundFont
|
||||
@@ -0,0 +1,173 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- codecs/Tracker/Mixer: mixes the player's active voices into an interleaved stereo f32 buffer. Per voice: sample
|
||||
-- loops (forward, ping-pong, IT sustain loops while the key is held), linear or no interpolation, the IT two-pole
|
||||
-- resonant filter, and a short gain ramp per tick against clicks. Written for this library (no third-party code).
|
||||
--
|
||||
-- Never throws: sample indexes are clamped to the sample, every loop is bounded, and the caller (codecs/Tracker)
|
||||
-- validates the sample buffers' sizes.
|
||||
local floor, ceil, min = math.floor, math.ceil, math.min
|
||||
local readf32, writef32 = buffer.readf32, buffer.writef32
|
||||
|
||||
local Mixer = {}
|
||||
|
||||
-- mixVoice(v, out?, off, n, linear, ramp): n frames of voice v added at frame off of out (nil: only advance)
|
||||
local function mixVoice(v: any, out: buffer?, off: number, n: number, linear: boolean, ramp: number)
|
||||
local data: buffer = v.data
|
||||
local nch = v.nch
|
||||
local inc = v.inc
|
||||
if not (inc > 0 and inc < 1e6) then
|
||||
return
|
||||
end
|
||||
local len = v.len
|
||||
local hi = len - 1
|
||||
local i = 0
|
||||
local guard = 0
|
||||
while i < n do
|
||||
guard += 1
|
||||
if guard > n + 64 then
|
||||
return
|
||||
end
|
||||
local s, e, t
|
||||
if v.keyOn and v.susT > 0 then
|
||||
s, e, t = v.susS, v.susE, v.susT
|
||||
elseif v.loopT > 0 then
|
||||
s, e, t = v.loopS, v.loopE, v.loopT
|
||||
else
|
||||
s, e, t = 0, len, 0
|
||||
end
|
||||
local p = v.p
|
||||
local dir = v.dir
|
||||
local count
|
||||
if dir > 0 then
|
||||
local lim = if t == 2 then e - 1 else e
|
||||
if p >= lim then
|
||||
if t == 0 then
|
||||
v.active = false
|
||||
return
|
||||
elseif t == 1 then
|
||||
p = s + (p - e) % (e - s)
|
||||
else
|
||||
p = 2 * (e - 1) - p
|
||||
if p < s then
|
||||
p = s
|
||||
end
|
||||
v.dir = -1
|
||||
end
|
||||
v.p = p
|
||||
continue
|
||||
end
|
||||
count = ceil((lim - p) / inc)
|
||||
else
|
||||
if p < s then
|
||||
p = 2 * s - p
|
||||
if p > e - 1 then
|
||||
p = e - 1
|
||||
end
|
||||
v.p = p
|
||||
v.dir = 1
|
||||
continue
|
||||
end
|
||||
count = floor((p - s) / inc) + 1
|
||||
end
|
||||
if count < 1 then
|
||||
count = 1
|
||||
end
|
||||
local m = min(n - i, count)
|
||||
local step = inc * dir
|
||||
if out == nil then
|
||||
v.p = p + step * m
|
||||
i += m
|
||||
continue
|
||||
end
|
||||
local wrapJ = if t == 1 then s else e - 1
|
||||
local gl, gr = v.gl, v.gr
|
||||
local rl = v.rampN
|
||||
local dl, dr = 0, 0
|
||||
local tl, tr = v.tl, v.tr
|
||||
if rl > 0 then
|
||||
dl, dr = (tl - gl) / rl, (tr - gr) / rl
|
||||
end
|
||||
local fOn = v.fOn
|
||||
local fa, fb0, fb1 = v.fa, v.fb0, v.fb1
|
||||
local y1l, y2l, y1r, y2r = v.y1l, v.y2l, v.y1r, v.y2r
|
||||
local o = (off + i) * 8
|
||||
for _ = 1, m do
|
||||
local idx = floor(p)
|
||||
if idx > hi then
|
||||
idx = hi
|
||||
elseif idx < 0 then
|
||||
idx = 0
|
||||
end
|
||||
local j = idx + 1
|
||||
if j >= e then
|
||||
j = wrapJ
|
||||
end
|
||||
if j > hi then
|
||||
j = hi
|
||||
end
|
||||
local xl, xr
|
||||
if nch == 1 then
|
||||
local a = readf32(data, idx * 4)
|
||||
if linear then
|
||||
local b = readf32(data, j * 4)
|
||||
xl = a + (b - a) * (p - idx)
|
||||
else
|
||||
xl = a
|
||||
end
|
||||
if fOn then
|
||||
local y = xl * fa + y1l * fb0 + y2l * fb1
|
||||
y2l, y1l = y1l, y
|
||||
xl = y
|
||||
end
|
||||
xr = xl
|
||||
else
|
||||
local al = readf32(data, idx * 8)
|
||||
local ar = readf32(data, idx * 8 + 4)
|
||||
if linear then
|
||||
local f = p - idx
|
||||
xl = al + (readf32(data, j * 8) - al) * f
|
||||
xr = ar + (readf32(data, j * 8 + 4) - ar) * f
|
||||
else
|
||||
xl, xr = al, ar
|
||||
end
|
||||
if fOn then
|
||||
local y = xl * fa + y1l * fb0 + y2l * fb1
|
||||
y2l, y1l = y1l, y
|
||||
xl = y
|
||||
y = xr * fa + y1r * fb0 + y2r * fb1
|
||||
y2r, y1r = y1r, y
|
||||
xr = y
|
||||
end
|
||||
end
|
||||
if rl > 0 then
|
||||
gl += dl
|
||||
gr += dr
|
||||
rl -= 1
|
||||
if rl == 0 then
|
||||
gl, gr = tl, tr
|
||||
end
|
||||
end
|
||||
writef32(out, o, readf32(out, o) + xl * gl)
|
||||
writef32(out, o + 4, readf32(out, o + 4) + xr * gr)
|
||||
o += 8
|
||||
p += step
|
||||
end
|
||||
v.p = p
|
||||
v.gl, v.gr, v.rampN = gl, gr, rl
|
||||
v.y1l, v.y2l, v.y1r, v.y2r = y1l, y2l, y1r, y2r
|
||||
i += m
|
||||
end
|
||||
local _ = ramp
|
||||
end
|
||||
|
||||
-- mix(st, out?, off, n, linear): every active voice of player st; out nil only advances the sample positions
|
||||
function Mixer.mix(st: any, out: buffer?, off: number, n: number, linear: boolean)
|
||||
for _, v in st.voices do
|
||||
if v.active and v.data then
|
||||
mixVoice(v, out, off, n, linear, 0)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return Mixer
|
||||
@@ -0,0 +1,132 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- codecs/Tracker/Pcm: sample data conversions shared by the tracker formats. Raw 8 / 16-bit PCM (signed or unsigned,
|
||||
-- plain or delta coded as in XM / IT 2.15, interleaved or planar stereo) to the engine's f32 samples, and back.
|
||||
--
|
||||
-- Never throws: reads past the source are refused up front (decode returns nil).
|
||||
local readu8, readi8, readu16, readi16 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16
|
||||
local writef32, readf32, writeu8, writei16 = buffer.writef32, buffer.readf32, buffer.writeu8, buffer.writei16
|
||||
local floor = math.floor
|
||||
|
||||
local Pcm = {}
|
||||
|
||||
export type Spec = {
|
||||
bits: number, -- 8 | 16
|
||||
signed: boolean,
|
||||
delta: boolean?, -- each value is the difference to the previous one (XM, IT 2.15 "delta" flag)
|
||||
channels: number?, -- 1 (default) | 2
|
||||
planar: boolean?, -- stereo stored as all left then all right (XM, IT); default interleaved
|
||||
bigEndian: boolean?,
|
||||
}
|
||||
|
||||
-- bytes(frames, spec) -> the size of the raw data
|
||||
function Pcm.bytes(frames: number, spec: Spec): number
|
||||
return frames * (spec.channels or 1) * (spec.bits // 8)
|
||||
end
|
||||
|
||||
-- decode(buf, off, frames, spec) -> f32 buffer (frames * channels, interleaved) | nil when the source is too short
|
||||
function Pcm.decode(buf: buffer, off: number, frames: number, spec: Spec): buffer?
|
||||
local nch = spec.channels or 1
|
||||
local bps = spec.bits // 8
|
||||
local total = frames * nch
|
||||
if frames < 0 or off < 0 or off + total * bps > buffer.len(buf) then
|
||||
return nil
|
||||
end
|
||||
local out = buffer.create(total * 4)
|
||||
local planar = spec.planar and nch == 2
|
||||
for c = 0, nch - 1 do
|
||||
local acc = 0
|
||||
for i = 0, frames - 1 do
|
||||
local k = if planar then c * frames + i else i * nch + c
|
||||
local v
|
||||
if bps == 1 then
|
||||
if spec.signed then
|
||||
v = readi8(buf, off + k)
|
||||
else
|
||||
v = readu8(buf, off + k) - 128
|
||||
end
|
||||
if spec.delta then
|
||||
acc = (acc + v + 128) % 256 - 128
|
||||
v = acc
|
||||
end
|
||||
writef32(out, (i * nch + c) * 4, v / 128)
|
||||
else
|
||||
local p = off + k * 2
|
||||
if spec.bigEndian then
|
||||
v = readu8(buf, p) * 256 + readu8(buf, p + 1)
|
||||
if spec.signed and v >= 32768 then
|
||||
v -= 65536
|
||||
end
|
||||
elseif spec.signed then
|
||||
v = readi16(buf, p)
|
||||
else
|
||||
v = readu16(buf, p)
|
||||
end
|
||||
if not spec.signed then
|
||||
v -= 32768
|
||||
end
|
||||
if spec.delta then
|
||||
acc = (acc + v + 32768) % 65536 - 32768
|
||||
v = acc
|
||||
end
|
||||
writef32(out, (i * nch + c) * 4, v / 32768)
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- encode(samples, frames, spec) -> raw PCM (signed or unsigned, optional delta, interleaved or planar)
|
||||
function Pcm.encode(samples: buffer, frames: number, spec: Spec): buffer
|
||||
local nch = spec.channels or 1
|
||||
local bps = spec.bits // 8
|
||||
local out = buffer.create(frames * nch * bps)
|
||||
local planar = spec.planar and nch == 2
|
||||
local avail = buffer.len(samples) // 4
|
||||
for c = 0, nch - 1 do
|
||||
local prev = 0
|
||||
for i = 0, frames - 1 do
|
||||
local si = i * nch + c
|
||||
local x = if si < avail then readf32(samples, si * 4) else 0
|
||||
local k = if planar then c * frames + i else i * nch + c
|
||||
if bps == 1 then
|
||||
local v = math.clamp(floor(x * 128 + 0.5), -128, 127)
|
||||
local w = v
|
||||
if spec.delta then
|
||||
w = (v - prev) % 256
|
||||
prev = v
|
||||
else
|
||||
w = if spec.signed then v % 256 else v + 128
|
||||
end
|
||||
writeu8(out, k, w)
|
||||
else
|
||||
local v = math.clamp(floor(x * 32768 + 0.5), -32768, 32767)
|
||||
local w = v
|
||||
if spec.delta then
|
||||
w = (v - prev + 32768) % 65536 - 32768
|
||||
prev = v
|
||||
elseif not spec.signed then
|
||||
w = v + 32768
|
||||
if w >= 32768 then
|
||||
w -= 65536
|
||||
end
|
||||
end
|
||||
writei16(out, k * 2, w)
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- bits(samples) -> 8 when every value is exactly representable in 8 bits (data loaded from 8-bit), else 16
|
||||
function Pcm.bitsNeeded(samples: buffer): number
|
||||
for i = 0, buffer.len(samples) // 4 - 1 do
|
||||
local x = readf32(samples, i * 4) * 128
|
||||
if x ~= floor(x) then
|
||||
return 16
|
||||
end
|
||||
end
|
||||
return 8
|
||||
end
|
||||
|
||||
return Pcm
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,113 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- codecs/Tracker/Tables: lookup tables of the tracker engine. Waveforms for vibrato / tremolo / panbrello and the
|
||||
-- auto-vibrato, the ProTracker period table (finetune 0, used to map MOD periods to notes and back) and the IT / S3M
|
||||
-- volume-column tone-portamento and retrigger tables. All values are from the public format documents (ProTracker
|
||||
-- 2.3 effect docs, FT2 / XM spec, ST3 TECH.DOC, ITTECH.TXT).
|
||||
local Tables = {}
|
||||
|
||||
-- the ProTracker half-sine (32 steps, 0..255)
|
||||
local SINE32 = { 0, 24, 49, 74, 97, 120, 141, 161, 180, 197, 212, 224, 235, 244, 250, 253, 255, 253, 250, 244, 235, 224, 212, 197, 180, 161, 141, 120, 97, 74, 49, 24 }
|
||||
|
||||
-- wave64(type, pos) -> -255..255 for pos 0..63: 0 sine, 1 ramp down, 2 square, 3 random (deterministic)
|
||||
local RANDOM: { number } = {}
|
||||
do
|
||||
local s = 12345
|
||||
for i = 1, 64 do
|
||||
s = (s * 1103515245 + 12345) % 2147483648
|
||||
RANDOM[i] = (s // 65536) % 511 - 255
|
||||
end
|
||||
end
|
||||
function Tables.wave64(kind: number, pos: number): number
|
||||
local p = pos % 64
|
||||
if kind == 1 then
|
||||
return 255 - p * 8
|
||||
elseif kind == 2 then
|
||||
return if p < 32 then 255 else -255
|
||||
elseif kind == 3 then
|
||||
return RANDOM[p + 1]
|
||||
end
|
||||
local v = SINE32[(p % 32) + 1]
|
||||
return if p >= 32 then -v else v
|
||||
end
|
||||
|
||||
-- autoWave(type, pos, it) -> -64..64 for pos 0..255. XM: 0 sine, 1 square, 2 ramp down, 3 ramp up.
|
||||
-- IT: 0 sine, 1 ramp down, 2 square, 3 random.
|
||||
local SINE256: { number } = {}
|
||||
for i = 0, 255 do
|
||||
SINE256[i + 1] = math.floor(math.sin(i * math.pi / 128) * 64 + 0.5)
|
||||
end
|
||||
function Tables.autoWave(kind: number, pos: number, it: boolean): number
|
||||
local p = pos % 256
|
||||
if it then
|
||||
if kind == 1 then
|
||||
return 64 - (p + 1) // 2
|
||||
elseif kind == 2 then
|
||||
return if p < 128 then 64 else -64
|
||||
elseif kind == 3 then
|
||||
return RANDOM[(p % 64) + 1] // 4
|
||||
end
|
||||
return SINE256[p + 1]
|
||||
end
|
||||
if kind == 1 then
|
||||
return if p < 128 then 64 else -64
|
||||
elseif kind == 2 then
|
||||
return 64 - (p + 1) // 2
|
||||
elseif kind == 3 then
|
||||
return (p + 1) // 2 - 64
|
||||
end
|
||||
return SINE256[p + 1]
|
||||
end
|
||||
|
||||
-- ProTracker periods, finetune 0, C-0 .. B-4 (60 notes; ProTracker itself uses C-1 .. B-3). Our note numbers:
|
||||
-- 1 = C-0 (FT2 numbering), so ProTracker C-1 (856) = note 37 and C-2 (428) = note 49, the note that plays a sample at
|
||||
-- its base rate (8363 Hz).
|
||||
local PERIODS = {
|
||||
3424, 3232, 3048, 2880, 2712, 2560, 2416, 2280, 2152, 2032, 1920, 1812,
|
||||
1712, 1616, 1524, 1440, 1356, 1280, 1208, 1140, 1076, 1016, 960, 906,
|
||||
856, 808, 762, 720, 678, 640, 604, 570, 538, 508, 480, 453,
|
||||
428, 404, 381, 360, 339, 320, 302, 285, 269, 254, 240, 226,
|
||||
214, 202, 190, 180, 170, 160, 151, 143, 135, 127, 120, 113,
|
||||
107, 101, 95, 90, 85, 80, 75, 71, 67, 63, 60, 56,
|
||||
}
|
||||
Tables.PERIODS = PERIODS
|
||||
Tables.PERIOD_FIRST_NOTE = 13 -- PERIODS[1] is note 13 (C-1 in FT2 numbering = ProTracker octave -1)
|
||||
|
||||
-- periodToNote(period) -> note (1..120), 0 for period 0
|
||||
function Tables.periodToNote(period: number): number
|
||||
if period <= 0 then
|
||||
return 0
|
||||
end
|
||||
-- exact match first, then the nearest note on a log scale
|
||||
for i = 1, #PERIODS do
|
||||
if PERIODS[i] == period then
|
||||
return i + Tables.PERIOD_FIRST_NOTE - 1
|
||||
end
|
||||
end
|
||||
local n = 49 + math.floor(12 * math.log(428 / period) / math.log(2) + 0.5)
|
||||
return math.clamp(n, 1, 120)
|
||||
end
|
||||
|
||||
-- noteToPeriod(note) -> ProTracker period (finetune 0) for a note, computed past the table's ends
|
||||
function Tables.noteToPeriod(note: number): number
|
||||
local i = note - Tables.PERIOD_FIRST_NOTE + 1
|
||||
if i >= 1 and i <= #PERIODS then
|
||||
return PERIODS[i]
|
||||
end
|
||||
return math.max(1, math.floor(428 * 2 ^ ((49 - note) / 12) + 0.5))
|
||||
end
|
||||
|
||||
-- IT volume column "g" (tone portamento) speeds
|
||||
Tables.IT_VOLPORTA = { 0, 1, 4, 8, 16, 32, 64, 96, 128, 255 }
|
||||
|
||||
-- XM Rxy / S3M-IT Qxy volume changes: kind 0 add, 1 multiply; value
|
||||
Tables.RETRIG_ADD = { 0, -1, -2, -4, -8, -16, 0, 0, 0, 1, 2, 4, 8, 16, 0, 0 }
|
||||
Tables.RETRIG_MUL = { 1, 1, 1, 1, 1, 1, 2 / 3, 0.5, 1, 1, 1, 1, 1, 1, 1.5, 2 }
|
||||
|
||||
-- the Amiga clock constant: frequency = AMIGA / period, with period 1712 playing an 8363 Hz sample at its base rate
|
||||
-- (FT2 / ST3 period units, 4x ProTracker's)
|
||||
Tables.AMIGA = 8363 * 1712
|
||||
-- MOD: the PAL Amiga clock (7093789.2 Hz / 2 per ProTracker period unit; period 428 plays at 8287 Hz)
|
||||
Tables.AMIGA_PAL = 7093789.2 / 2 * 4
|
||||
|
||||
return Tables
|
||||
@@ -0,0 +1,516 @@
|
||||
--!strict
|
||||
-- codecs/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read
|
||||
-- their files into one Module structure (below); render(module, opts) plays any of them through the standard audio
|
||||
-- Decoder (Types.Decoder: stereo f32). Written for this library from the format documents (ProTracker 2.3, the XM
|
||||
-- spec + FT2 behaviour, ST3 TECH.DOC, ITTECH.TXT); libxmp / OpenMPT were used only as reference players for tests.
|
||||
--
|
||||
-- local Tracker = require("@formats/codecs/Tracker")
|
||||
-- local dec, err = Tracker.render(module, { sampleRate = 44100 }) -- a Types.Decoder
|
||||
-- local seconds = Tracker.duration(module) -- one pass, song loops detected
|
||||
--
|
||||
-- Module (Types.Module plus the engine fields; pattern / instrument / sample numbers are as in the file):
|
||||
-- format "mod" | "s3m" | "xm" | "it": selects the effect family and the format quirks
|
||||
-- title, channels, speed (ticks per row), tempo (BPM: a tick lasts 2.5 / tempo s)
|
||||
-- globalVolume 0..128 (S3M / XM 0..64 are stored doubled), mixVolume 0..128 (IT mix volume, S3M master volume)
|
||||
-- order { pattern number (0-based) | 254 skip ("+++") | 255 end ("---") }, restart (0-based order index)
|
||||
-- linear linear frequency slides (XM / IT flag) or Amiga periods
|
||||
-- instrumentMode XM, IT with instruments: notes go through Instrument keymaps; otherwise the instrument column
|
||||
-- is a sample number (MOD, S3M, IT sample mode)
|
||||
-- flags { oldEffects, compatGxx (IT), fastSlides (ST3.00 volume slides), amigaLimits (MOD) }
|
||||
-- channelPan { 0..256 per channel (128 centre; 512 = surround); MOD: 64 / 192 (Amiga L R R L at half width,
|
||||
-- as OpenMPT plays it; set 0 / 256 or render with stereoSeparation = 200 for hard panning) }, channelVolume { 0..64 }, channelMute { bool }
|
||||
-- patterns { Pattern } (pattern n at patterns[n + 1]); Pattern = { rows, data }: data holds rows * channels
|
||||
-- cells of 5 bytes: note, instrument, volume column, effect, parameter. Notes: 0 none, 1..120 (1 =
|
||||
-- C-0; C-4 = 49 plays an XM / MOD sample at its base rate, C-5 = 61 an S3M / IT sample at its C5
|
||||
-- speed), 253 note fade, 254 note cut, 255 key off. The volume column and effects are kept in the
|
||||
-- file's own coding: MOD / XM effects 0..35 (XM letters G.. = 16..), XM volume byte as stored;
|
||||
-- S3M / IT effects 1..26 (A = 1), S3M volume 0 = none else volume + 1, IT volume byte + 1
|
||||
-- (0 = none). Tracker.cell / Tracker.setCell read and write cells.
|
||||
-- samples { Sample }: { name, data (f32, interleaved when stereo), length (frames), channels, bits (8 | 16,
|
||||
-- for writers), loopStart, loopEnd (frames, end exclusive), loopType (0 none, 1 forward, 2 ping-pong),
|
||||
-- susStart, susEnd, susType (IT sustain loop), volume 0..64, globalVolume 0..64, pan (0..256 or nil),
|
||||
-- c5speed (S3M / IT), relativeNote, finetune -128..127 (MOD / XM), vibType / vibSweep / vibDepth /
|
||||
-- vibRate (IT auto-vibrato) }
|
||||
-- instruments { Instrument }: { name, sampleMap = { [note] = sample number }, noteMap = { [note] = note },
|
||||
-- volEnv / panEnv / pitchEnv (Envelope?), fadeout (as stored: XM 0..4095, IT 0..1024), nna (0 cut,
|
||||
-- 1 continue, 2 note off, 3 fade), dct (0 off, 1 note, 2 sample, 3 instrument), dca (0 cut, 1 off,
|
||||
-- 2 fade), globalVolume 0..128, pan (0..256 or nil), pps, ppc (pitch-pan separation / centre),
|
||||
-- cutoff, resonance (0..127 or nil), vibType / vibSweep / vibDepth / vibRate (XM auto-vibrato) }
|
||||
-- Envelope { enabled, ticks = { tick }, values = { volume 0..64 | pan / pitch -32..32 }, loop, loopStart,
|
||||
-- loopEnd, sustain, susStart, susEnd (1-based point indexes), filter (IT pitch envelope as filter) }
|
||||
--
|
||||
-- Pitch: two period spaces. Linear: P = (ref - note) * 64 - transpose (64 per semitone), frequency = base * 2^(-P/768).
|
||||
-- Amiga: P = 1712 * 8363 / base * 2^(Plinear / 768), frequency = 8363 * 1712 / P (FT2 / ST3 period units; slides add
|
||||
-- 4 per effect unit in both). MOD / XM: base 8363, ref 49, transpose = relativeNote * 64 + finetune / 2; S3M / IT:
|
||||
-- base = c5speed, ref 61.
|
||||
--
|
||||
-- Not supported: MIDI macros other than IT's default filter macros (Z00..Z8F), glissando, ST3 / IT finetune effects
|
||||
-- (S2x), random volume / pan variation, OPL (AdLib) instruments, MOD Amiga low-pass filter emulation.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Player = require("@formats/codecs/Tracker/Player")
|
||||
local Mixer = require("@formats/codecs/Tracker/Mixer")
|
||||
local Pcm = require("@formats/codecs/Tracker/Pcm")
|
||||
local Tables = require("@formats/codecs/Tracker/Tables")
|
||||
|
||||
local Tracker = {}
|
||||
|
||||
Tracker.Pcm = Pcm
|
||||
Tracker.Tables = Tables
|
||||
|
||||
export type Envelope = {
|
||||
enabled: boolean,
|
||||
ticks: { number },
|
||||
values: { number },
|
||||
loop: boolean,
|
||||
loopStart: number,
|
||||
loopEnd: number,
|
||||
sustain: boolean,
|
||||
susStart: number,
|
||||
susEnd: number,
|
||||
carry: boolean?,
|
||||
filter: boolean?,
|
||||
raw: any?, -- format-specific fields kept for a faithful re-save (XM)
|
||||
}
|
||||
|
||||
export type Pattern = { rows: number, data: buffer }
|
||||
|
||||
export type RenderOptions = {
|
||||
sampleRate: number?, -- default 44100
|
||||
interpolation: ("linear" | "none")?, -- default "linear"
|
||||
stereoSeparation: number?, -- 0..200 % (default 100: the panning as stored; 200 doubles every distance from centre)
|
||||
loop: boolean?, -- keep playing past the song's end (frames / duration still give one pass); default false
|
||||
maxDuration: number?, -- seconds; the render stops there (default 3600)
|
||||
}
|
||||
|
||||
local CELL = 5
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constructors
|
||||
-- newModule(format, channels) -> an empty Module (no patterns / samples) with the format's defaults
|
||||
function Tracker.newModule(format: string, channels: number): any
|
||||
local m = {
|
||||
kind = "music",
|
||||
format = format,
|
||||
title = "",
|
||||
channels = channels,
|
||||
speed = 6,
|
||||
tempo = 125,
|
||||
globalVolume = 128,
|
||||
mixVolume = 48,
|
||||
order = {},
|
||||
restart = 0,
|
||||
linear = format == "xm" or format == "it",
|
||||
instrumentMode = format == "xm" or format == "it",
|
||||
flags = {},
|
||||
channelPan = {},
|
||||
channelVolume = {},
|
||||
channelMute = {},
|
||||
patterns = {},
|
||||
instruments = {},
|
||||
samples = {},
|
||||
meta = {},
|
||||
render = Tracker.renderMethod,
|
||||
}
|
||||
for i = 1, channels do
|
||||
m.channelVolume[i] = 64
|
||||
if format == "mod" then
|
||||
local k = (i - 1) % 4
|
||||
m.channelPan[i] = if k == 0 or k == 3 then 64 else 192 -- the Amiga's L R R L, at OpenMPT's default width
|
||||
else
|
||||
m.channelPan[i] = 128
|
||||
end
|
||||
end
|
||||
return m
|
||||
end
|
||||
|
||||
-- newPattern(rows, channels) -> an empty Pattern
|
||||
function Tracker.newPattern(rows: number, channels: number): Pattern
|
||||
return { rows = rows, data = buffer.create(rows * channels * CELL) }
|
||||
end
|
||||
|
||||
-- newSample() -> an empty Sample
|
||||
function Tracker.newSample(name: string?): any
|
||||
return {
|
||||
name = name or "",
|
||||
data = buffer.create(0),
|
||||
length = 0,
|
||||
channels = 1,
|
||||
bits = 8,
|
||||
loopStart = 0,
|
||||
loopEnd = 0,
|
||||
loopType = 0,
|
||||
susStart = 0,
|
||||
susEnd = 0,
|
||||
susType = 0,
|
||||
volume = 64,
|
||||
globalVolume = 64,
|
||||
pan = nil :: number?,
|
||||
c5speed = 8363,
|
||||
relativeNote = 0,
|
||||
finetune = 0,
|
||||
vibType = 0,
|
||||
vibSweep = 0,
|
||||
vibDepth = 0,
|
||||
vibRate = 0,
|
||||
}
|
||||
end
|
||||
|
||||
function Tracker.newEnvelope(): Envelope
|
||||
return { enabled = false, ticks = {}, values = {}, loop = false, loopStart = 1, loopEnd = 1, sustain = false, susStart = 1, susEnd = 1 }
|
||||
end
|
||||
|
||||
-- newInstrument() -> an Instrument mapping every note to sample 0 (none)
|
||||
function Tracker.newInstrument(name: string?): any
|
||||
local sm, nm = table.create(120, 0), table.create(120, 0)
|
||||
for i = 1, 120 do
|
||||
nm[i] = i
|
||||
end
|
||||
return {
|
||||
name = name or "",
|
||||
sampleMap = sm,
|
||||
noteMap = nm,
|
||||
volEnv = nil :: Envelope?,
|
||||
panEnv = nil :: Envelope?,
|
||||
pitchEnv = nil :: Envelope?,
|
||||
fadeout = 0,
|
||||
nna = 0,
|
||||
dct = 0,
|
||||
dca = 0,
|
||||
globalVolume = 128,
|
||||
pan = nil :: number?,
|
||||
pps = 0,
|
||||
ppc = 60,
|
||||
cutoff = nil :: number?,
|
||||
resonance = nil :: number?,
|
||||
vibType = 0,
|
||||
vibSweep = 0,
|
||||
vibDepth = 0,
|
||||
vibRate = 0,
|
||||
}
|
||||
end
|
||||
|
||||
-- cell(module, pattern, row, channel) -> note, instrument, volume, effect, parameter (pattern 0-based, row 0-based,
|
||||
-- channel 1-based); nil when out of range
|
||||
function Tracker.cell(m: any, pattern: number, row: number, channel: number): (number?, number, number, number, number)
|
||||
local p = m.patterns[pattern + 1]
|
||||
if not p or row < 0 or row >= p.rows or channel < 1 or channel > m.channels then
|
||||
return nil, 0, 0, 0, 0
|
||||
end
|
||||
local o = (row * m.channels + channel - 1) * CELL
|
||||
local d = p.data
|
||||
return buffer.readu8(d, o), buffer.readu8(d, o + 1), buffer.readu8(d, o + 2), buffer.readu8(d, o + 3), buffer.readu8(d, o + 4)
|
||||
end
|
||||
|
||||
-- setCell(module, pattern, row, channel, note, instrument, volume, effect, parameter) -> true | false (out of range)
|
||||
function Tracker.setCell(m: any, pattern: number, row: number, channel: number, note: number, ins: number, vol: number, fx: number, param: number): boolean
|
||||
local p = m.patterns[pattern + 1]
|
||||
if not p or row < 0 or row >= p.rows or channel < 1 or channel > m.channels then
|
||||
return false
|
||||
end
|
||||
local o = (row * m.channels + channel - 1) * CELL
|
||||
local d = p.data
|
||||
buffer.writeu8(d, o, note % 256)
|
||||
buffer.writeu8(d, o + 1, ins % 256)
|
||||
buffer.writeu8(d, o + 2, vol % 256)
|
||||
buffer.writeu8(d, o + 3, fx % 256)
|
||||
buffer.writeu8(d, o + 4, param % 256)
|
||||
return true
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ validation
|
||||
local function num(v: any, lo: number, hi: number): boolean
|
||||
return type(v) == "number" and v == v and v >= lo and v <= hi
|
||||
end
|
||||
|
||||
local function fixEnvelope(e: any): (any, string?)
|
||||
if e == nil then
|
||||
return nil
|
||||
end
|
||||
if type(e) ~= "table" or type(e.ticks) ~= "table" or type(e.values) ~= "table" then
|
||||
return nil, "bad envelope"
|
||||
end
|
||||
local n = math.min(#e.ticks, #e.values)
|
||||
local last = -1
|
||||
for i = 1, n do
|
||||
local t, v = e.ticks[i], e.values[i]
|
||||
if not num(t, 0, 1e6) or not num(v, -64, 64) or t <= last then
|
||||
-- points must go forward: keep the valid prefix
|
||||
n = i - 1
|
||||
break
|
||||
end
|
||||
last = t
|
||||
end
|
||||
for i = #e.ticks, n + 1, -1 do
|
||||
e.ticks[i] = nil
|
||||
end
|
||||
for i = #e.values, n + 1, -1 do
|
||||
e.values[i] = nil
|
||||
end
|
||||
if n == 0 then
|
||||
e.enabled = false
|
||||
end
|
||||
local function idx(v: any): number
|
||||
return if num(v, 1, math.max(1, n)) then math.floor(v) else 1
|
||||
end
|
||||
e.loopStart, e.loopEnd = idx(e.loopStart), idx(e.loopEnd)
|
||||
e.susStart, e.susEnd = idx(e.susStart), idx(e.susEnd)
|
||||
if e.loopEnd < e.loopStart then
|
||||
e.loop = false
|
||||
end
|
||||
if e.susEnd < e.susStart then
|
||||
e.sustain = false
|
||||
end
|
||||
return e
|
||||
end
|
||||
|
||||
local function fixLoop(s0: any, e0: any, t0: any, len: number): (number, number, number)
|
||||
if not num(t0, 0, 2) or t0 == 0 or not num(s0, -2 ^ 52, 2 ^ 52) or not num(e0, -2 ^ 52, 2 ^ 52) then
|
||||
return 0, 0, 0
|
||||
end
|
||||
local s: number = math.floor(math.clamp(s0, 0, len))
|
||||
local e: number = math.floor(math.clamp(e0, 0, len))
|
||||
local t: number = math.floor(t0)
|
||||
if e - s < 1 or t == 0 then
|
||||
return 0, 0, 0
|
||||
end
|
||||
if t == 2 and e - s < 2 then
|
||||
t = 1
|
||||
end
|
||||
return s, e, t
|
||||
end
|
||||
|
||||
-- validate(module) -> true | nil, Err: checks the structure the engine relies on, clamps loops, envelopes and
|
||||
-- numbers into range (in place)
|
||||
function Tracker.validate(m: any): (boolean?, Err.Err?)
|
||||
if type(m) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "not a module")
|
||||
end
|
||||
if m.format ~= "mod" and m.format ~= "s3m" and m.format ~= "xm" and m.format ~= "it" then
|
||||
return nil, Err.new(Err.ARG, "unknown tracker format " .. tostring(m.format))
|
||||
end
|
||||
if not num(m.channels, 1, 128) or m.channels % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "bad channel count")
|
||||
end
|
||||
if type(m.order) ~= "table" or type(m.patterns) ~= "table" or type(m.samples) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "module without order / patterns / samples")
|
||||
end
|
||||
m.instruments = if type(m.instruments) == "table" then m.instruments else {}
|
||||
m.flags = if type(m.flags) == "table" then m.flags else {}
|
||||
m.channelPan = if type(m.channelPan) == "table" then m.channelPan else {}
|
||||
m.channelVolume = if type(m.channelVolume) == "table" then m.channelVolume else {}
|
||||
m.channelMute = if type(m.channelMute) == "table" then m.channelMute else {}
|
||||
for i = 1, m.channels do
|
||||
local p = m.channelPan[i]
|
||||
if p ~= 512 and not num(p, 0, 256) then
|
||||
m.channelPan[i] = 128
|
||||
end
|
||||
if not num(m.channelVolume[i], 0, 64) then
|
||||
m.channelVolume[i] = 64
|
||||
end
|
||||
end
|
||||
m.speed = if num(m.speed, 1, 255) then math.floor(m.speed) else 6
|
||||
m.tempo = if num(m.tempo, 1, 1000) then m.tempo else 125
|
||||
m.globalVolume = if num(m.globalVolume, 0, 128) then m.globalVolume else 128
|
||||
m.mixVolume = if num(m.mixVolume, 0, 256) then m.mixVolume else 48
|
||||
m.restart = if num(m.restart, 0, 1e6) then math.floor(m.restart) else 0
|
||||
for i, o in m.order do
|
||||
if not num(o, 0, 255) then
|
||||
return nil, Err.new(Err.ARG, "bad order entry " .. i)
|
||||
end
|
||||
end
|
||||
for i, p in m.patterns do
|
||||
if type(p) ~= "table" or not num(p.rows, 1, 1024) or type(p.data) ~= "buffer" or buffer.len(p.data) < p.rows * m.channels * CELL then
|
||||
return nil, Err.new(Err.ARG, "bad pattern " .. (i - 1))
|
||||
end
|
||||
end
|
||||
for i, s in m.samples do
|
||||
if type(s) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "bad sample " .. i)
|
||||
end
|
||||
local nch = if s.channels == 2 then 2 else 1
|
||||
s.channels = nch
|
||||
if not num(s.length, 0, 2 ^ 31) or type(s.data) ~= "buffer" or buffer.len(s.data) < math.floor(s.length) * nch * 4 then
|
||||
return nil, Err.new(Err.ARG, "sample " .. i .. ": data shorter than its length")
|
||||
end
|
||||
s.length = math.floor(s.length)
|
||||
s.loopStart, s.loopEnd, s.loopType = fixLoop(s.loopStart or 0, s.loopEnd or 0, s.loopType or 0, s.length)
|
||||
s.susStart, s.susEnd, s.susType = fixLoop(s.susStart or 0, s.susEnd or 0, s.susType or 0, s.length)
|
||||
s.volume = if num(s.volume, 0, 64) then s.volume else 64
|
||||
s.globalVolume = if num(s.globalVolume, 0, 64) then s.globalVolume else 64
|
||||
if s.pan ~= nil and not num(s.pan, 0, 256) then
|
||||
s.pan = nil
|
||||
end
|
||||
s.c5speed = if num(s.c5speed, 1, 1e7) then s.c5speed else 8363
|
||||
s.relativeNote = if num(s.relativeNote, -128, 127) then s.relativeNote else 0
|
||||
s.finetune = if num(s.finetune, -128, 127) then s.finetune else 0
|
||||
end
|
||||
for i, ins in m.instruments do
|
||||
if type(ins) ~= "table" or type(ins.sampleMap) ~= "table" or type(ins.noteMap) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "bad instrument " .. i)
|
||||
end
|
||||
for n = 1, 120 do
|
||||
if not num(ins.sampleMap[n], 0, 1e6) then
|
||||
ins.sampleMap[n] = 0
|
||||
end
|
||||
if not num(ins.noteMap[n], 1, 120) then
|
||||
ins.noteMap[n] = n
|
||||
end
|
||||
end
|
||||
local err
|
||||
ins.volEnv, err = fixEnvelope(ins.volEnv)
|
||||
if err then
|
||||
return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err)
|
||||
end
|
||||
ins.panEnv, err = fixEnvelope(ins.panEnv)
|
||||
if err then
|
||||
return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err)
|
||||
end
|
||||
ins.pitchEnv, err = fixEnvelope(ins.pitchEnv)
|
||||
if err then
|
||||
return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err)
|
||||
end
|
||||
ins.fadeout = if num(ins.fadeout, 0, 65535) then ins.fadeout else 0
|
||||
ins.globalVolume = if num(ins.globalVolume, 0, 128) then ins.globalVolume else 128
|
||||
if ins.pan ~= nil and not num(ins.pan, 0, 256) then
|
||||
ins.pan = nil
|
||||
end
|
||||
if ins.cutoff ~= nil and not num(ins.cutoff, 0, 127) then
|
||||
ins.cutoff = nil
|
||||
end
|
||||
if ins.resonance ~= nil and not num(ins.resonance, 0, 127) then
|
||||
ins.resonance = nil
|
||||
end
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ rendering
|
||||
local Decoder = {}
|
||||
Decoder.__index = Decoder
|
||||
|
||||
-- duration(module, opts?) -> seconds of one pass (song loops and the end of the order list detected), or nil, Err
|
||||
function Tracker.duration(m: any, opts: RenderOptions?): (number?, Err.Err?)
|
||||
local ok, err = Tracker.validate(m)
|
||||
if not ok then
|
||||
return nil, err
|
||||
end
|
||||
local sr = opts and opts.sampleRate or 44100
|
||||
local maxFrames = (opts and opts.maxDuration or 3600) * sr
|
||||
local st = Player.new(m, sr, { stereoSeparation = 100 })
|
||||
local frames = 0
|
||||
while frames < maxFrames do
|
||||
local f = Player.tick(st)
|
||||
if f == 0 and st.ended then
|
||||
break
|
||||
end
|
||||
frames += f
|
||||
end
|
||||
return math.min(frames, maxFrames) / sr, nil
|
||||
end
|
||||
|
||||
local function newPlayer(self: any)
|
||||
self.st = Player.new(self.module, self.sampleRate, self.opts)
|
||||
self.st.ramp = math.max(1, math.floor(self.sampleRate * 0.0015))
|
||||
self.left = 0
|
||||
self.pos = 0
|
||||
end
|
||||
|
||||
-- render(module, opts?) -> Types.Decoder (stereo f32) | nil, Err
|
||||
function Tracker.render(m: any, opts: RenderOptions?): (Types.Decoder?, Err.Err?)
|
||||
local o: RenderOptions = opts or {}
|
||||
local sr = o.sampleRate or 44100
|
||||
if type(sr) ~= "number" or sr < 1000 or sr > 384000 then
|
||||
return nil, Err.new(Err.ARG, "sampleRate must be 1000..384000")
|
||||
end
|
||||
local seconds, err = Tracker.duration(m, o)
|
||||
if not seconds then
|
||||
return nil, err
|
||||
end
|
||||
local frames = math.floor(seconds * sr + 0.5)
|
||||
local self = setmetatable({
|
||||
sampleRate = sr,
|
||||
channels = 2,
|
||||
frames = frames,
|
||||
duration = frames / sr,
|
||||
bitrate = 0,
|
||||
tags = { title = m.title or "" },
|
||||
module = m,
|
||||
opts = o,
|
||||
linear = o.interpolation ~= "none",
|
||||
maxFrames = (o.maxDuration or 3600) * sr,
|
||||
st = nil :: any,
|
||||
left = 0,
|
||||
pos = 0,
|
||||
}, Decoder)
|
||||
newPlayer(self)
|
||||
return self :: any, nil
|
||||
end
|
||||
|
||||
-- the Module method: module:render(opts)
|
||||
function Tracker.renderMethod(self: any, opts: RenderOptions?): Types.Decoder
|
||||
local dec = Tracker.render(self, opts)
|
||||
return dec :: any
|
||||
end
|
||||
|
||||
-- run(self, out?, n) -> frames produced (out nil: advance without mixing)
|
||||
local function run(self: any, out: buffer?, n: number): number
|
||||
local st = self.st
|
||||
local done = 0
|
||||
while done < n do
|
||||
if self.left <= 0 then
|
||||
if self.pos + done >= self.maxFrames then
|
||||
break
|
||||
end
|
||||
local f = Player.tick(st)
|
||||
if f == 0 and st.ended then
|
||||
break
|
||||
end
|
||||
self.left = f
|
||||
if f == 0 then
|
||||
continue
|
||||
end
|
||||
end
|
||||
local k = math.min(self.left, n - done)
|
||||
Mixer.mix(st, out, done, k, self.linear)
|
||||
self.left -= k
|
||||
done += k
|
||||
end
|
||||
self.pos += done
|
||||
return done
|
||||
end
|
||||
|
||||
-- read(n, out?) -> interleaved stereo f32 buffer, frames read (0 at the end)
|
||||
function Decoder.read(self: any, n: number, out: buffer?): (buffer, number)
|
||||
n = math.max(0, math.floor(tonumber(n) or 0))
|
||||
local o = out
|
||||
if o == nil or buffer.len(o) < n * 8 then
|
||||
o = buffer.create(n * 8)
|
||||
else
|
||||
buffer.fill(o, 0, 0, n * 8)
|
||||
end
|
||||
local got = run(self, o, n)
|
||||
return o :: buffer, got
|
||||
end
|
||||
|
||||
-- seek(seconds): replays the song silently up to the position (sample positions included)
|
||||
function Decoder.seek(self: any, seconds: number)
|
||||
local target = math.max(0, math.floor((tonumber(seconds) or 0) * self.sampleRate))
|
||||
newPlayer(self)
|
||||
local chunk = 65536
|
||||
while self.pos < target do
|
||||
local got = run(self, nil, math.min(chunk, target - self.pos))
|
||||
if got == 0 then
|
||||
break
|
||||
end
|
||||
end
|
||||
-- the gains ramp in from silence after a seek
|
||||
for _, v in self.st.voices do
|
||||
v.gl, v.gr = 0, 0
|
||||
end
|
||||
end
|
||||
|
||||
function Decoder.position(self: any): number
|
||||
return self.pos / self.sampleRate
|
||||
end
|
||||
|
||||
return Tracker
|
||||
Reference in new issue
Block a user