--!strict --!native --!optimize 2 -- audio/mp3/Encode2: an MPEG audio layer II (MP2) encoder: constant bit rate, MPEG-1 (32 / 44.1 / 48 kHz) and MPEG-2 -- low sampling frequencies (16 / 22.05 / 24 kHz), mono or stereo. New code written from ISO/IEC 11172-3 (2.4.2.3, -- C.1.5.2): the polyphase analysis (audio/mp3/Analysis), one scalefactor per 12-sample part (scfsi 0: all three are -- sent), the standard bit allocation tables (in minimp3's compact form, CC0: licenses/minimp3-CC0.txt, as the decoder -- in this folder reads them), a greedy allocation that always gives the next step to the band with the most noise -- (signal level minus the quantizer's SNR; no psychoacoustic model), uniform midtread quantization and grouping of -- 3 / 5 / 9-level samples. Never throws. local T = require("@formats/audio/mp3/Tables") local Analysis = require("@formats/audio/mp3/Analysis") local Encode2 = {} local floor, log = math.floor, math.log local writeu8 = buffer.writeu8 local POW = table.create(40, 0) for i = 0, 39 do POW[i + 1] = 2 ^ i end -- the allocation tables: { bit-allocation-code offset into g_bitalloc_code_tab, bits, band count } runs (minimp3) local ALLOC_L2M1 = { 0, 4, 3, 16, 4, 8, 32, 3, 12, 40, 2, 7 } local ALLOC_L2M1_LOW = { 44, 4, 2, 44, 3, 10 } local ALLOC_L2M2 = { 60, 4, 4, 44, 3, 7, 44, 2, 19 } local CODE = T.g_bitalloc_code_tab -- quantizer classes (minimp3's ba): 1..16 -> 2^ba - 1 levels in ba bits; 17 / 18 / 19 -> 3 / 5 / 9 levels grouped local function levels(ba: number): number if ba >= 17 then return if ba == 17 then 3 elseif ba == 18 then 5 else 9 end return POW[ba + 1] - 1 end -- bits for the 3 samples of one granule local function tripleBits(ba: number): number if ba >= 17 then return if ba == 17 then 5 elseif ba == 18 then 7 else 10 end return 3 * ba end -- the quantizer's signal-to-noise ratio in dB (ISO 11172-3 table C.5) local SNR: { [number]: number } = {} do local byLevels = { [3] = 7.00, [5] = 11.00, [7] = 16.00, [9] = 20.84, [15] = 25.28, [31] = 31.59, [63] = 37.75, [127] = 43.84, [255] = 49.89, [511] = 55.93, [1023] = 61.96, [2047] = 67.98, [4095] = 74.01, [8191] = 80.03, [16383] = 86.05, [32767] = 92.01, [65535] = 98.01, } for ba = 1, 19 do SNR[ba] = byLevels[levels(ba)] or (6.02 * ba) end end -- scalefactors 2^(1 - i/3), i = 0 .. 62 local SCF = table.create(63, 0) for i = 0, 62 do SCF[i + 1] = 2 ^ (1 - i / 3) end local RATES = { [44100] = { 3, 0 }, [48000] = { 3, 1 }, [32000] = { 3, 2 }, [22050] = { 2, 0 }, [24000] = { 2, 1 }, [16000] = { 2, 2 }, } Encode2.RATES = RATES local BITRATES_V1 = { 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384 } local BITRATES_V2 = { 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 } Encode2.BITRATES = { [1] = BITRATES_V1, [2] = BITRATES_V2 } type W = { buf: buffer, pos: number, acc: number, cnt: number } local function put(w: W, v: number, n: number) if n == 0 then return end local acc = w.acc * POW[n + 1] + v local cnt = w.cnt + n local b, p = w.buf, w.pos while cnt >= 8 do cnt -= 8 local m = POW[cnt + 1] local byte = floor(acc / m) writeu8(b, p, byte) p += 1 acc -= byte * m end w.acc, w.cnt, w.pos = acc, cnt, p end export type Source = { sampleRate: number, channels: number, frames: number, read: (self: any, n: number, out: buffer?) -> (buffer, number), err: any, } export type Options = { bitrate: number, mode: string, prefix: buffer? } -- encode(src, opts) -> buffer | nil, message function Encode2.encode(src: Source, opts: Options): (buffer?, string?) local rate = src.sampleRate local info = RATES[rate] if not info then return nil, "unsupported sample rate" end local version, srIndex = info[1], info[2] local mpeg1 = version == 3 local inCh = src.channels local nch = if opts.mode == "mono" then 1 else 2 local kbps = opts.bitrate local list = if mpeg1 then BITRATES_V1 else BITRATES_V2 local brIndex = table.find(list, kbps) if not brIndex then return nil, "unsupported bit rate" end -- the allocation table (the decoder's choice from the header) local alloc, nbands if not mpeg1 then alloc, nbands = ALLOC_L2M2, 30 else local perCh = if nch == 2 then kbps // 2 else kbps alloc, nbands = ALLOC_L2M1, 27 if perCh < 56 then alloc, nbands = ALLOC_L2M1_LOW, if srIndex == 2 then 12 else 8 elseif perCh >= 96 and srIndex ~= 1 then nbands = 30 end end local bandOff, bandBits = table.create(nbands, 0), table.create(nbands, 0) do local k, ai = 0, 1 local off, bits = 0, 0 for i = 0, nbands - 1 do if i == k then off, bits, k = alloc[ai], alloc[ai + 1], k + alloc[ai + 2] ai += 3 end bandOff[i + 1], bandBits[i + 1] = off, bits end end -- per band: the classes it can take, in increasing order (index into the code table = the value written) local steps: { { { number } } } = {} for i = 1, nbands do local s = {} for v = 1, POW[bandBits[i] + 1] - 1 do local ba = CODE[bandOff[i] + v] if ba and ba > 0 then table.insert(s, { v, ba }) end end steps[i] = s end local w: W = { buf = buffer.create(65536), pos = 0, acc = 0, cnt = 0 } if opts.prefix then local pf = opts.prefix :: buffer if buffer.len(pf) > buffer.len(w.buf) - 16 then w.buf = buffer.create(buffer.len(pf) + 65536) end buffer.copy(w.buf, 0, pf, 0, buffer.len(pf)) w.pos = buffer.len(pf) end local ana = { Analysis.new(), Analysis.new() } local pcm = { table.create(1152, 0), table.create(1152, 0) } -- subband samples: sb[c][band * 36 + t + 1], t = 0 .. 35 local sbs = { table.create(32 * 36, 0), table.create(32 * 36, 0) } local sub = table.create(32, 0) local scf = { table.create(32 * 3, 0), table.create(32 * 3, 0) } -- scalefactor index per band and part local bal = { table.create(32, 0), table.create(32, 0) } -- allocation step (0 = none) per band local slot = 144000 * kbps local rest = 0 local tmp: buffer? = nil local pending: buffer? = nil local pendN, pendOff = 0, 0 local srcDone, flushed = false, false while true do local got = 0 while got < 1152 and not srcDone do if pendN == 0 then local b, n = src:read(4096, tmp) if n <= 0 then srcDone = true break end tmp = b pending, pendN, pendOff = b, n, 0 end local take = math.min(1152 - got, pendN) local pb = pending :: buffer for i = 0, take - 1 do local base = (pendOff + i) * inCh * 4 local l = buffer.readf32(pb, base) local r = if inCh > 1 then buffer.readf32(pb, base + 4) else l if nch == 1 then pcm[1][got + i + 1] = if inCh > 1 then (l + r) * 0.5 else l else pcm[1][got + i + 1] = l pcm[2][got + i + 1] = r end end got += take pendN -= take pendOff += take end if got == 0 then if flushed then break end flushed = true end for c = 1, nch do local s = pcm[c] for i = got + 1, 1152 do s[i] = 0 end local sb = sbs[c] for t = 0, 35 do Analysis.run(ana[c], s, t * 32 + 1, sub, 1) for b = 0, 31 do sb[b * 36 + t + 1] = sub[b + 1] end end -- scalefactors: the smallest scalefactor (largest index) still >= the part's peak local sc = scf[c] for b = 0, nbands - 1 do for part = 0, 2 do local m = 0 local o = b * 36 + part * 12 for t = 1, 12 do local v = math.abs(sb[o + t]) if v > m then m = v end end local idx = 62 if m > 0 then idx = math.clamp(floor(3 * (1 - log(m) / log(2))), 0, 62) while idx > 0 and SCF[idx + 1] < m do idx -= 1 end while idx < 62 and SCF[idx + 2] >= m do idx += 1 end end sc[b * 3 + part + 1] = idx end end end -- the frame size and the bits left for scalefactors and samples local frameBytes = slot // rate rest += slot % rate local padding = 0 if rest >= rate then rest -= rate padding = 1 frameBytes += 1 end local avail = frameBytes * 8 - 32 for b = 1, nbands do avail -= bandBits[b] * nch end -- greedy allocation: the band with the most noise gets its next step while it fits local level = { table.create(nbands, 0), table.create(nbands, 0) } -- signal level (dB) per band for c = 1, nch do local sc = scf[c] for b = 1, nbands do local best = math.min(sc[(b - 1) * 3 + 1], sc[(b - 1) * 3 + 2], sc[(b - 1) * 3 + 3]) level[c][b] = 20 * math.log10(SCF[best + 1]) bal[c][b] = 0 end end while true do local bestC, bestB, bestNoise, bestCost = 0, 0, -math.huge, 0 for c = 1, nch do for b = 1, nbands do local st = bal[c][b] local s = steps[b] if st < #s and level[c][b] > -110 then local cur = if st == 0 then 0 else s[st][2] local nxt = s[st + 1][2] local noise = level[c][b] - (if st == 0 then 0 else SNR[cur]) local cost = 12 * tripleBits(nxt) - (if st == 0 then 0 else 12 * tripleBits(cur)) if st == 0 then cost += 2 + 18 -- scfsi + three scalefactors end if cost <= avail and noise > bestNoise then bestC, bestB, bestNoise, bestCost = c, b, noise, cost end end end end if bestC == 0 then break end bal[bestC][bestB] += 1 avail -= bestCost end -- write the frame if w.pos + frameBytes + 64 > buffer.len(w.buf) then local nb = buffer.create(buffer.len(w.buf) * 2 + frameBytes) buffer.copy(nb, 0, w.buf, 0, w.pos) w.buf = nb end local start = w.pos put(w, 0x7FF, 11) put(w, version, 2) put(w, 2, 2) -- layer II put(w, 1, 1) -- no CRC put(w, brIndex, 4) put(w, srIndex, 2) put(w, padding, 1) put(w, 0, 1) put(w, if nch == 1 then 3 else 0, 2) put(w, 0, 2) put(w, 0, 1) put(w, 1, 1) put(w, 0, 2) -- bit allocation for b = 1, nbands do for c = 1, nch do local st = bal[c][b] put(w, if st == 0 then 0 else steps[b][st][1], bandBits[b]) end end -- scfsi (0: three scalefactors) and the scalefactors for b = 1, nbands do for c = 1, nch do if bal[c][b] > 0 then put(w, 0, 2) end end end for b = 1, nbands do for c = 1, nch do if bal[c][b] > 0 then for part = 1, 3 do put(w, scf[c][(b - 1) * 3 + part], 6) end end end end -- samples: 12 granules of 3, band by band, channel by channel for gr = 0, 11 do local part = gr // 4 for b = 1, nbands do for c = 1, nch do local st = bal[c][b] if st > 0 then local ba = steps[b][st][2] local L = levels(ba) local inv = 1 / SCF[scf[c][(b - 1) * 3 + part + 1] + 1] local o = (b - 1) * 36 + gr * 3 local sb = sbs[c] local q0, q1, q2 do local function quant(x: number): number local q = floor((x * inv + 1) * L / 2) return if q < 0 then 0 elseif q > L - 1 then L - 1 else q end q0 = quant(sb[o + 1]) q1 = quant(sb[o + 2]) q2 = quant(sb[o + 3]) end if ba >= 17 then put(w, q0 + L * (q1 + L * q2), tripleBits(ba)) else put(w, q0, ba) put(w, q1, ba) put(w, q2, ba) end end end end end if w.cnt > 0 then put(w, 0, 8 - w.cnt) end while w.pos < start + frameBytes do writeu8(w.buf, w.pos, 0) w.pos += 1 end end if src.err then return nil, tostring(src.err) end local out = buffer.create(w.pos) buffer.copy(out, 0, w.buf, 0, w.pos) return out, nil end return Encode2