--!strict --!native --!optimize 2 -- audio/mp3/Analysis: the MPEG audio polyphase analysis filterbank (ISO/IEC 11172-3 section C.1.3, figure C.4): 32 -- input samples -> one sample in each of the 32 subbands, with the standard's 512-tap window C = D / 32 (D from -- audio/mp3/EncTables) and the matrixing M[k][i] = cos((2k + 1)(i - 16) pi / 64). Shared by the layer II and layer III -- encoders. New code from the standard's flow chart. Never throws. -- -- local st = Analysis.new() -- Analysis.run(st, samples, start, out, outStart) -- samples[start .. start + 31] -> out[outStart .. outStart + 31] local E = require("@formats/audio/mp3/EncTables") local Analysis = {} local C = table.create(512, 0) for i = 1, 512 do C[i] = E.D[i] / 32 end local M = table.create(32 * 64, 0) -- M[k * 64 + i + 1] for k = 0, 31 do for i = 0, 63 do M[k * 64 + i + 1] = math.cos((2 * k + 1) * (i - 16) * math.pi / 64) end end export type State = { x: { number }, off: number, y: { number } } function Analysis.new(): State return { x = table.create(1024, 0), off = 0, y = table.create(64, 0) } end -- run(st, s, si, out, oi): s[si .. si + 31] (oldest first) -> out[oi .. oi + 31] (subbands 0 .. 31) function Analysis.run(st: State, s: { number }, si: number, out: { number }, oi: number) -- the window X is kept twice (x[p] and x[p + 512]) so X[i] = x[off + i + 1] without a modulo local x = st.x local off = (st.off - 32) % 512 st.off = off for j = 0, 31 do local v = s[si + j] local p = (off + 31 - j) % 512 + 1 -- X[31 - j]: the first new sample goes to X[31], the newest to X[0] x[p] = v x[p + 512] = v end local y = st.y for i = 0, 63 do local acc = 0 local b = off + i + 1 for j = 0, 7 do acc += C[i + 64 * j + 1] * x[b + 64 * j] end y[i + 1] = acc end for k = 0, 31 do local acc = 0 local mb = k * 64 for i = 1, 64 do acc += M[mb + i] * y[i] end out[oi + k] = acc end end return Analysis