diff --git a/docs/FORMATS.md b/docs/FORMATS.md
index 181230b..2c616d7 100644
--- a/docs/FORMATS.md
+++ b/docs/FORMATS.md
@@ -6,6 +6,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| Category | Format | Extensions | Read | Write | Capabilities | Test |
|---|---|---|---|---|---|---|
| image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` |
+| audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | - | streaming: true, seek: true, layers: 1, 2, 3, channels: 2 | `tests/audio/mp3.luau` |
Codecs (layer 1, shared by formats; not loadable on their own):
diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md
index 5d28e73..d70594a 100644
--- a/licenses/NOTICE.md
+++ b/licenses/NOTICE.md
@@ -4,6 +4,8 @@
|---|---|---|
| `src/Formats/codecs/Deflate/` (Inflate, init), `src/Formats/core/Crc32.luau`, `src/Formats/core/Adler32.luau`, `src/Formats/core/Huffman.luau` (table builder) | deflate-luau 1.0.0 (same author), written from RFC 1950-1952 | no licence chosen yet; no third-party code: [deflate-luau-NOTICE.txt](deflate-luau-NOTICE.txt) |
| `src/Formats/image/png/` (init, Decode) | png-luau 1.0.0 (same author), written from the PNG specification | no licence chosen yet; no third-party code |
+| `src/Formats/audio/mp3/` | mp3-luau c755bbf (same author), a port of minimp3 by lieff (https://github.com/lieff/minimp3) | minimp3: CC0 1.0, [minimp3-CC0.txt](minimp3-CC0.txt) |
+| `tests/fixtures/mp3/` | made by ffmpeg (libmp3lame / mp2) from a synthetic signal; `*.ref` are minimp3 decodes of them | test data, no third-party content |
| `tests/fixtures/pngsuite/` | PngSuite by Willem van Schaik | [PngSuite-LICENSE.txt](PngSuite-LICENSE.txt) |
Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this
diff --git a/licenses/minimp3-CC0.txt b/licenses/minimp3-CC0.txt
new file mode 100644
index 0000000..2c4afab
--- /dev/null
+++ b/licenses/minimp3-CC0.txt
@@ -0,0 +1,117 @@
+CC0 1.0 Universal
+
+Statement of Purpose
+
+The laws of most jurisdictions throughout the world automatically confer
+exclusive Copyright and Related Rights (defined below) upon the creator and
+subsequent owner(s) (each and all, an "owner") of an original work of
+authorship and/or a database (each, a "Work").
+
+Certain owners wish to permanently relinquish those rights to a Work for the
+purpose of contributing to a commons of creative, cultural and scientific
+works ("Commons") that the public can reliably and without fear of later
+claims of infringement build upon, modify, incorporate in other works, reuse
+and redistribute as freely as possible in any form whatsoever and for any
+purposes, including without limitation commercial purposes. These owners may
+contribute to the Commons to promote the ideal of a free culture and the
+further production of creative, cultural and scientific works, or to gain
+reputation or greater distribution for their Work in part through the use and
+efforts of others.
+
+For these and/or other purposes and motivations, and without any expectation
+of additional consideration or compensation, the person associating CC0 with a
+Work (the "Affirmer"), to the extent that he or she is an owner of Copyright
+and Related Rights in the Work, voluntarily elects to apply CC0 to the Work
+and publicly distribute the Work under its terms, with knowledge of his or her
+Copyright and Related Rights in the Work and the meaning and intended legal
+effect of CC0 on those rights.
+
+1. Copyright and Related Rights. A Work made available under CC0 may be
+protected by copyright and related or neighboring rights ("Copyright and
+Related Rights"). Copyright and Related Rights include, but are not limited
+to, the following:
+
+ i. the right to reproduce, adapt, distribute, perform, display, communicate,
+ and translate a Work;
+
+ ii. moral rights retained by the original author(s) and/or performer(s);
+
+ iii. publicity and privacy rights pertaining to a person's image or likeness
+ depicted in a Work;
+
+ iv. rights protecting against unfair competition in regards to a Work,
+ subject to the limitations in paragraph 4(a), below;
+
+ v. rights protecting the extraction, dissemination, use and reuse of data in
+ a Work;
+
+ vi. database rights (such as those arising under Directive 96/9/EC of the
+ European Parliament and of the Council of 11 March 1996 on the legal
+ protection of databases, and under any national implementation thereof,
+ including any amended or successor version of such directive); and
+
+ vii. other similar, equivalent or corresponding rights throughout the world
+ based on applicable law or treaty, and any national implementations thereof.
+
+2. Waiver. To the greatest extent permitted by, but not in contravention of,
+applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and
+unconditionally waives, abandons, and surrenders all of Affirmer's Copyright
+and Related Rights and associated claims and causes of action, whether now
+known or unknown (including existing as well as future claims and causes of
+action), in the Work (i) in all territories worldwide, (ii) for the maximum
+duration provided by applicable law or treaty (including future time
+extensions), (iii) in any current or future medium and for any number of
+copies, and (iv) for any purpose whatsoever, including without limitation
+commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes
+the Waiver for the benefit of each member of the public at large and to the
+detriment of Affirmer's heirs and successors, fully intending that such Waiver
+shall not be subject to revocation, rescission, cancellation, termination, or
+any other legal or equitable action to disrupt the quiet enjoyment of the Work
+by the public as contemplated by Affirmer's express Statement of Purpose.
+
+3. Public License Fallback. Should any part of the Waiver for any reason be
+judged legally invalid or ineffective under applicable law, then the Waiver
+shall be preserved to the maximum extent permitted taking into account
+Affirmer's express Statement of Purpose. In addition, to the extent the Waiver
+is so judged Affirmer hereby grants to each affected person a royalty-free,
+non transferable, non sublicensable, non exclusive, irrevocable and
+unconditional license to exercise Affirmer's Copyright and Related Rights in
+the Work (i) in all territories worldwide, (ii) for the maximum duration
+provided by applicable law or treaty (including future time extensions), (iii)
+in any current or future medium and for any number of copies, and (iv) for any
+purpose whatsoever, including without limitation commercial, advertising or
+promotional purposes (the "License"). The License shall be deemed effective as
+of the date CC0 was applied by Affirmer to the Work. Should any part of the
+License for any reason be judged legally invalid or ineffective under
+applicable law, such partial invalidity or ineffectiveness shall not
+invalidate the remainder of the License, and in such case Affirmer hereby
+affirms that he or she will not (i) exercise any of his or her remaining
+Copyright and Related Rights in the Work or (ii) assert any associated claims
+and causes of action with respect to the Work, in either case contrary to
+Affirmer's express Statement of Purpose.
+
+4. Limitations and Disclaimers.
+
+ a. No trademark or patent rights held by Affirmer are waived, abandoned,
+ surrendered, licensed or otherwise affected by this document.
+
+ b. Affirmer offers the Work as-is and makes no representations or warranties
+ of any kind concerning the Work, express, implied, statutory or otherwise,
+ including without limitation warranties of title, merchantability, fitness
+ for a particular purpose, non infringement, or the absence of latent or
+ other defects, accuracy, or the present or absence of errors, whether or not
+ discoverable, all to the greatest extent permissible under applicable law.
+
+ c. Affirmer disclaims responsibility for clearing rights of other persons
+ that may apply to the Work or any use thereof, including without limitation
+ any person's Copyright and Related Rights in the Work. Further, Affirmer
+ disclaims responsibility for obtaining any necessary consents, permissions
+ or other rights required for any use of the Work.
+
+ d. Affirmer understands and acknowledges that Creative Commons is not a
+ party to this document and has no duty or obligation with respect to this
+ CC0 or use of the Work.
+
+For more information, please see
+
+
diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau
index ba09f70..c8037bd 100644
--- a/src/Formats/Registry.luau
+++ b/src/Formats/Registry.luau
@@ -26,6 +26,18 @@ local list: { Entry } = {
return require("@formats/image/png")
end,
},
+ {
+ name = "mp3",
+ category = "audio",
+ path = "audio/mp3",
+ extensions = { "mp3", "mp2", "mp1", "mpga" },
+ mime = { "audio/mpeg", "audio/mp3", "audio/mpa" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = false, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 },
+ load = function()
+ return require("@formats/audio/mp3")
+ end,
+ },
}
return list
diff --git a/src/Formats/audio/mp3/Core.luau b/src/Formats/audio/mp3/Core.luau
new file mode 100644
index 0000000..a7bb0a7
--- /dev/null
+++ b/src/Formats/audio/mp3/Core.luau
@@ -0,0 +1,1628 @@
+--!strict
+--!native
+--!optimize 2
+-- audio/mp3/Core: a line-by-line port of minimp3's mp3dec_decode_frame (https://github.com/lieff/minimp3,
+-- CC0) for layers I, II and III, using its scalar (non-SIMD) code paths and float output.
+-- State that must survive between frames (MDCT overlap, polyphase history, bit reservoir) lives in a per-stream
+-- state from Core.newState(); everything else is module scratch, so decoding is synchronous and allocation free.
+-- All buffer accesses stay in bounds by construction (padded scratch, bounded loops): native code must not throw.
+local T = require("@formats/audio/mp3/Tables")
+
+local band, bor, lshift, rshift, arshift, bswap = bit32.band, bit32.bor, bit32.lshift, bit32.rshift, bit32.arshift, bit32.byteswap
+local ru8, wu8, ru32, ri16 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.readi16
+local rf, wf = buffer.readf32, buffer.writef32
+local bcopy, bfill, bcreate = buffer.copy, buffer.fill, buffer.create
+local min, max = math.min, math.max
+
+local MAX_BITRESERVOIR_BYTES = 511
+local MAX_FRAME = 2304 + 8 -- largest frame (free format) incl. padding, rounded up
+local SCALE = 1 / 32768
+
+----------------------------------------------------------------------------------------------------------------
+-- tables (floats rounded to f32 like the C arrays)
+
+local F32 = bcreate(4)
+local function f32(x: number): number
+ wf(F32, 0, x)
+ return rf(F32, 0)
+end
+
+local function fbuf(list: { [number]: number }, n: number): buffer
+ local b = bcreate(n * 4)
+ for i = 0, n - 1 do
+ wf(b, i * 4, list[i])
+ end
+ return b
+end
+
+-- scalefactor band widths: long (8 x 23) | short (8 x 40) | mixed (8 x 40), one u8 buffer
+local SFB_LONG, SFB_SHORT, SFB_MIXED = 0, 184, 504
+local SFB = bcreate(824 + 8)
+for i = 0, 183 do
+ wu8(SFB, SFB_LONG + i, T.g_scf_long[i])
+end
+for i = 0, 319 do
+ wu8(SFB, SFB_SHORT + i, T.g_scf_short[i])
+ wu8(SFB, SFB_MIXED + i, T.g_scf_mixed[i])
+end
+
+local TABS = bcreate(2164 * 2)
+for i = 0, 2163 do
+ buffer.writei16(TABS, i * 2, T.tabs[i])
+end
+local TAB32, TAB33 = T.tab32, T.tab33
+local TABINDEX, LINBITS = T.tabindex, T.g_linbits
+local SCF_PARTITIONS, SCFC_DECODE, GMOD, PREAMP = T.g_scf_partitions, T.g_scfc_decode, T.g_mod, T.g_preamp
+local EXPFRAC = { [0] = f32(T.g_expfrac[0]), f32(T.g_expfrac[1]), f32(T.g_expfrac[2]), f32(T.g_expfrac[3]) }
+local PAN = {}
+for i = 0, 13 do
+ PAN[i] = f32(T.g_pan[i])
+end
+local BITALLOC_CODE = T.g_bitalloc_code_tab
+local HALFRATE = T.halfrate
+
+-- L3_pow_43 for every value a Huffman pair can give (15 + 8191 linbits), evaluated in f32 like the C code
+local POW43 = bcreate(8207 * 4)
+do
+ local g = {}
+ for i = 0, 144 do
+ g[i] = f32(T.g_pow43[i])
+ end
+ local c43, c29 = f32(4 / 3), f32(2 / 9)
+ for x0 = 0, 8206 do
+ local v
+ if x0 < 129 then
+ v = g[16 + x0]
+ else
+ local x, mult = x0, 256
+ if x < 1024 then
+ mult = 16
+ x *= 8
+ end
+ local sign = band(2 * x, 64)
+ local frac = f32((band(x, 63) - sign) / (band(x, bit32.bnot(63)) + sign))
+ v = f32(f32(g[16 + rshift(x + sign, 6)] * f32(1 + f32(frac * f32(c43 + f32(frac * c29))))) * mult)
+ end
+ wf(POW43, x0 * 4, v)
+ end
+end
+
+-- L12 dequantizer: 9.53674316e-07f / x (and two more steps of 2^(-1/3)) for 3, 7, ..., 65535, 3, 5, 9
+local DEQ_L12 = {}
+do
+ local div = { 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535, 3, 5, 9 }
+ local base = { f32(9.53674316e-07), f32(7.56931807e-07), f32(6.00777173e-07) }
+ for i = 0, 17 do
+ for j = 0, 2 do
+ DEQ_L12[i * 3 + j] = f32(base[j + 1] / div[i + 1])
+ end
+ end
+end
+
+local AA = fbuf(T.g_aa, 16)
+local TWID3 = fbuf(T.g_twid3, 6)
+local MDCT_WIN0, MDCT_WIN1 = table.create(18, 0), table.create(18, 0) -- g_mdct_window[2][18], 1-based
+for i = 0, 17 do
+ MDCT_WIN0[i + 1] = f32(T.g_mdct_window[i])
+ MDCT_WIN1[i + 1] = f32(T.g_mdct_window[18 + i])
+end
+local WINT = table.create(240, 0) -- g_win as a 1-based Luau array (f32 values)
+for i = 0, 239 do
+ WINT[i + 1] = f32(T.g_win[i])
+end
+
+----------------------------------------------------------------------------------------------------------------
+-- scratch
+
+local FRAME = bcreate(MAX_FRAME + 64) -- the current frame, copied (bit reader reads up to 4 bytes ahead)
+local MAIN = bcreate(MAX_BITRESERVOIR_BYTES + MAX_FRAME + 4096) -- layer III main data (reservoir + frame)
+local GRBUF = bcreate(576 * 2 * 4) -- [ch][576] f32
+local SCF = bcreate(40 * 4) -- layer III scalefactor gains, f32
+local SYN = bcreate((18 + 15) * 64 * 4) -- synthesis lines / reorder scratch, f32
+local IST = bcreate(2 * 39 + 8) -- ist_pos[2][39], u8
+local ISCF = bcreate(48) -- integer scalefactors, u8
+local TMP = bcreate(18 * 4 * 2) -- imdct scratch: co[9] si[9] / short block copy[18]
+local L12SCF = bcreate(192 * 4) -- L12 scalefactors [band*2 + ch][3], f32
+local BA = bcreate(64) -- L12 bit allocation
+local SCFCOD = bcreate(64)
+
+-- layer III side info, per granule x channel (0..3)
+local GR_P23, GR_BV, GR_SFC, GR_GAIN, GR_BT, GR_MIXED = {}, {}, {}, {}, {}, {}
+local GR_NLONG, GR_NSHORT, GR_SFB, GR_PRE, GR_SCALE, GR_C1, GR_SCFSI = {}, {}, {}, {}, {}, {}, {}
+local GR_TS, GR_RC, GR_SBG = {}, {}, {} -- [gr * 3 + k]
+for i = 0, 3 do
+ GR_P23[i], GR_BV[i], GR_SFC[i], GR_GAIN[i], GR_BT[i], GR_MIXED[i] = 0, 0, 0, 0, 0, 0
+ GR_NLONG[i], GR_NSHORT[i], GR_SFB[i], GR_PRE[i], GR_SCALE[i], GR_C1[i], GR_SCFSI[i] = 0, 0, 0, 0, 0, 0, 0
+ for k = 0, 2 do
+ GR_TS[i * 3 + k], GR_RC[i * 3 + k], GR_SBG[i * 3 + k] = 0, 0, 0
+ end
+end
+local MAXB = { [0] = -1, -1, -1 }
+local SCFSIZE = { [0] = 0, 0, 0, 0 }
+
+-- per-stream state of the frame being decoded (set by decodeFrame)
+local OVL: buffer = bcreate(4) -- mdct_overlap[2][9*32]
+local QMF: buffer = bcreate(4) -- qmf_state[15*2*32]
+local PCM: buffer = bcreate(4)
+
+----------------------------------------------------------------------------------------------------------------
+-- bit reader (bs_t): position and limit in bits
+
+local bsBuf: buffer = FRAME
+local bsPos = 0
+local bsLimit = 0
+
+-- n <= 25
+local function getBits(n: number): number
+ local pos = bsPos
+ bsPos = pos + n
+ if pos + n > bsLimit then
+ return 0
+ end
+ local w = lshift(bswap(ru32(bsBuf, rshift(pos, 3))), band(pos, 7))
+ return rshift(w, 32 - n)
+end
+
+----------------------------------------------------------------------------------------------------------------
+-- layer III side info (L3_read_side_info): fills GR_*, returns main_data_begin or -1
+
+local function readSideInfo(h1: number, h2: number, h3: number): number
+ local mono = band(h3, 0xC0) == 0xC0
+ local mpeg1 = band(h1, 8) ~= 0
+ local srIdx = band(rshift(h2, 2), 3) + (band(rshift(h1, 3), 1) + band(rshift(h1, 4), 1)) * 3
+ if srIdx ~= 0 then
+ srIdx -= 1
+ end
+ local grCount = if mono then 1 else 2
+ local scfsi = 0
+ local mdb
+ if mpeg1 then
+ grCount *= 2
+ mdb = getBits(9)
+ scfsi = getBits(7 + grCount)
+ else
+ mdb = rshift(getBits(8 + grCount), grCount)
+ end
+ local part23sum = 0
+ for gr = 0, grCount - 1 do
+ if mono then
+ scfsi = lshift(scfsi, 4)
+ end
+ local p23 = getBits(12)
+ GR_P23[gr] = p23
+ part23sum += p23
+ local bv = getBits(9)
+ if bv > 288 then
+ return -1
+ end
+ GR_BV[gr] = bv
+ GR_GAIN[gr] = getBits(8)
+ local sfc = getBits(if mpeg1 then 4 else 9)
+ GR_SFC[gr] = sfc
+ GR_SFB[gr] = SFB_LONG + srIdx * 23
+ GR_NLONG[gr] = 22
+ GR_NSHORT[gr] = 0
+ local tables
+ local g3 = gr * 3
+ if getBits(1) ~= 0 then
+ local bt = getBits(2)
+ if bt == 0 then
+ return -1
+ end
+ GR_BT[gr] = bt
+ local mixed = getBits(1)
+ GR_MIXED[gr] = mixed
+ GR_RC[g3] = 7
+ GR_RC[g3 + 1] = 255
+ if bt == 2 then
+ scfsi = band(scfsi, 0x0F0F)
+ if mixed == 0 then
+ GR_RC[g3] = 8
+ GR_SFB[gr] = SFB_SHORT + srIdx * 40
+ GR_NLONG[gr] = 0
+ GR_NSHORT[gr] = 39
+ else
+ GR_SFB[gr] = SFB_MIXED + srIdx * 40
+ GR_NLONG[gr] = if mpeg1 then 8 else 6
+ GR_NSHORT[gr] = 30
+ end
+ end
+ tables = lshift(getBits(10), 5)
+ GR_SBG[g3] = getBits(3)
+ GR_SBG[g3 + 1] = getBits(3)
+ GR_SBG[g3 + 2] = getBits(3)
+ else
+ GR_BT[gr] = 0
+ GR_MIXED[gr] = 0
+ tables = getBits(15)
+ GR_RC[g3] = getBits(4)
+ GR_RC[g3 + 1] = getBits(3)
+ GR_RC[g3 + 2] = 255
+ end
+ GR_TS[g3] = rshift(tables, 10)
+ GR_TS[g3 + 1] = band(rshift(tables, 5), 31)
+ GR_TS[g3 + 2] = band(tables, 31)
+ GR_PRE[gr] = if mpeg1 then getBits(1) elseif sfc >= 500 then 1 else 0
+ GR_SCALE[gr] = getBits(1)
+ GR_C1[gr] = getBits(1)
+ GR_SCFSI[gr] = band(rshift(scfsi, 12), 15)
+ scfsi = lshift(scfsi, 4)
+ end
+ if part23sum + bsPos > bsLimit + mdb * 8 then
+ return -1
+ end
+ return mdb
+end
+
+----------------------------------------------------------------------------------------------------------------
+-- layer III scalefactors
+
+local function ldexpQ2(y: number, e: number): number
+ repeat
+ local s = if e < 120 then e else 120
+ y = f32(y * EXPFRAC[band(s, 3)] * lshift(1, 30 - arshift(s, 2)))
+ e -= s
+ until e <= 0
+ return y
+end
+
+-- L3_read_scalefactors + L3_decode_scalefactors -> SCF[0 .. nLong + nShort)
+local function decodeScalefactors(h1: number, h3: number, istOff: number, gr: number, ch: number)
+ local mpeg1 = band(h1, 8) ~= 0
+ local nLong, nShort = GR_NLONG[gr], GR_NSHORT[gr]
+ local part = ((if nShort ~= 0 then 1 else 0) + (if nLong == 0 then 1 else 0)) * 28
+ local scfShift = GR_SCALE[gr] + 1
+ local scfsi = GR_SCFSI[gr]
+ if mpeg1 then
+ local p = SCFC_DECODE[GR_SFC[gr]]
+ local hi, lo = rshift(p, 2), band(p, 3)
+ SCFSIZE[0], SCFSIZE[1], SCFSIZE[2], SCFSIZE[3] = hi, hi, lo, lo
+ else
+ local ist = if band(h3, 0x10) ~= 0 and ch ~= 0 then 1 else 0
+ local sfc = rshift(GR_SFC[gr], ist)
+ local k = ist * 12
+ while sfc >= 0 do
+ local modprod = 1
+ for i = 3, 0, -1 do
+ SCFSIZE[i] = (sfc // modprod) % GMOD[k + i]
+ modprod *= GMOD[k + i]
+ end
+ sfc -= modprod
+ k += 4
+ end
+ part += k
+ end
+ -- L3_read_scalefactors
+ local sp, ip = 0, istOff
+ for i = 0, 3 do
+ local cnt = SCF_PARTITIONS[part + i]
+ if cnt == 0 then
+ break
+ end
+ if mpeg1 and band(scfsi, 8) ~= 0 then
+ bcopy(ISCF, sp, IST, ip, cnt)
+ else
+ local bits = SCFSIZE[i]
+ if bits == 0 then
+ bfill(ISCF, sp, 0, cnt)
+ bfill(IST, ip, 0, cnt)
+ else
+ local maxScf = if mpeg1 then -1 else lshift(1, bits) - 1
+ for k = 0, cnt - 1 do
+ local s = getBits(bits)
+ wu8(IST, ip + k, if s == maxScf then 255 else s)
+ wu8(ISCF, sp + k, s)
+ end
+ end
+ end
+ sp += cnt
+ ip += cnt
+ scfsi *= 2
+ end
+ wu8(ISCF, sp, 0)
+ wu8(ISCF, sp + 1, 0)
+ wu8(ISCF, sp + 2, 0)
+
+ if nShort ~= 0 then
+ local sh = 3 - scfShift
+ local g3 = gr * 3
+ local s0, s1, s2 = lshift(GR_SBG[g3], sh), lshift(GR_SBG[g3 + 1], sh), lshift(GR_SBG[g3 + 2], sh)
+ for i = 0, nShort - 1, 3 do
+ local o = nLong + i
+ wu8(ISCF, o, band(ru8(ISCF, o) + s0, 255))
+ wu8(ISCF, o + 1, band(ru8(ISCF, o + 1) + s1, 255))
+ wu8(ISCF, o + 2, band(ru8(ISCF, o + 2) + s2, 255))
+ end
+ elseif GR_PRE[gr] ~= 0 then
+ for i = 0, 9 do
+ wu8(ISCF, 11 + i, band(ru8(ISCF, 11 + i) + PREAMP[i], 255))
+ end
+ end
+
+ local gainExp = GR_GAIN[gr] - 4 - 210 - (if band(h3, 0xE0) == 0x60 then 2 else 0)
+ local gain = ldexpQ2(2048, 44 - gainExp)
+ for i = 0, nLong + nShort - 1 do
+ wf(SCF, i * 4, ldexpQ2(gain, lshift(ru8(ISCF, i), scfShift)))
+ end
+end
+
+----------------------------------------------------------------------------------------------------------------
+-- layer III Huffman decoding (L3_huffman) into GRBUF[dst ..], reads MAIN through a 32-bit cache
+
+local function huffman(dst: number, gr: number, limit: number)
+ local b = bsBuf
+ local one = 0.0
+ local ireg = 0
+ local bigValCnt = GR_BV[gr]
+ local sfb = GR_SFB[gr]
+ local scf = 0
+ local pos = bsPos
+ local nextPtr = rshift(pos, 3)
+ local cache = lshift(bswap(ru32(b, nextPtr)), band(pos, 7))
+ local sh = band(pos, 7) - 8
+ nextPtr += 4
+ local g3 = gr * 3
+ local d = dst * 4
+
+ while bigValCnt > 0 do
+ if ireg > 2 then
+ break
+ end
+ local tabNum = GR_TS[g3 + ireg]
+ local sfbCnt = GR_RC[g3 + ireg]
+ ireg += 1
+ local cb = TABINDEX[tabNum]
+ local linbits = LINBITS[tabNum]
+ repeat
+ local np = rshift(ru8(SFB, sfb), 1)
+ sfb += 1
+ if np == 0 then
+ bigValCnt = 0
+ break
+ end
+ local pairs = if bigValCnt < np then bigValCnt else np
+ one = rf(SCF, scf)
+ scf += 4
+ for _ = 1, pairs do
+ local w = 5
+ local leaf = ri16(TABS, (cb + rshift(cache, 27)) * 2)
+ while leaf < 0 do
+ cache = lshift(cache, w)
+ sh += w
+ w = band(leaf, 7)
+ leaf = ri16(TABS, (cb + rshift(cache, 32 - w) - leaf // 8) * 2)
+ end
+ local l = rshift(leaf, 8)
+ cache = lshift(cache, l)
+ sh += l
+ for _ = 1, 2 do
+ local lsb = band(leaf, 15)
+ if lsb == 15 and linbits ~= 0 then
+ lsb += rshift(cache, 32 - linbits)
+ cache = lshift(cache, linbits)
+ sh += linbits
+ while sh >= 0 do
+ cache = bor(cache, lshift(ru8(b, nextPtr), sh))
+ nextPtr += 1
+ sh -= 8
+ end
+ end
+ local v = rf(POW43, lsb * 4) * one
+ if lsb ~= 0 then
+ if cache >= 0x80000000 then
+ v = -v
+ end
+ cache = lshift(cache, 1)
+ sh += 1
+ end
+ wf(GRBUF, d, v)
+ d += 4
+ leaf = rshift(leaf, 4)
+ end
+ while sh >= 0 do
+ cache = bor(cache, lshift(ru8(b, nextPtr), sh))
+ nextPtr += 1
+ sh -= 8
+ end
+ end
+ bigValCnt -= np
+ sfbCnt -= 1
+ until not (bigValCnt > 0 and sfbCnt >= 0)
+ end
+
+ -- count1 quadruples
+ local np = 1 - bigValCnt
+ local cb1 = if GR_C1[gr] ~= 0 then TAB33 else TAB32
+ local dend = 576 * 4 * 2
+ while true do
+ local leaf = cb1[rshift(cache, 28)]
+ if band(leaf, 8) == 0 then
+ leaf = cb1[rshift(leaf, 3) + rshift(lshift(cache, 4), 32 - band(leaf, 3))]
+ end
+ local l = band(leaf, 7)
+ cache = lshift(cache, l)
+ sh += l
+ if nextPtr * 8 - 24 + sh > limit or d + 16 > dend then
+ break
+ end
+ np -= 1
+ if np == 0 then
+ np = rshift(ru8(SFB, sfb), 1)
+ sfb += 1
+ if np == 0 then
+ break
+ end
+ one = rf(SCF, scf)
+ scf += 4
+ end
+ if band(leaf, 128) ~= 0 then
+ wf(GRBUF, d, if cache >= 0x80000000 then -one else one)
+ cache = lshift(cache, 1)
+ sh += 1
+ end
+ if band(leaf, 64) ~= 0 then
+ wf(GRBUF, d + 4, if cache >= 0x80000000 then -one else one)
+ cache = lshift(cache, 1)
+ sh += 1
+ end
+ np -= 1
+ if np == 0 then
+ np = rshift(ru8(SFB, sfb), 1)
+ sfb += 1
+ if np == 0 then
+ break
+ end
+ one = rf(SCF, scf)
+ scf += 4
+ end
+ if band(leaf, 32) ~= 0 then
+ wf(GRBUF, d + 8, if cache >= 0x80000000 then -one else one)
+ cache = lshift(cache, 1)
+ sh += 1
+ end
+ if band(leaf, 16) ~= 0 then
+ wf(GRBUF, d + 12, if cache >= 0x80000000 then -one else one)
+ cache = lshift(cache, 1)
+ sh += 1
+ end
+ while sh >= 0 do
+ cache = bor(cache, lshift(ru8(b, nextPtr), sh))
+ nextPtr += 1
+ sh -= 8
+ end
+ d += 16
+ end
+ bsPos = limit
+end
+
+----------------------------------------------------------------------------------------------------------------
+-- layer III stereo
+
+-- L3_midside_stereo on GRBUF[left .. left + n) and its right channel at + 576
+local function midside(left: number, n: number)
+ for i = left * 4, (left + n - 1) * 4, 4 do
+ local a, c = rf(GRBUF, i), rf(GRBUF, i + 2304)
+ wf(GRBUF, i, a + c)
+ wf(GRBUF, i + 2304, a - c)
+ end
+end
+
+local function intensityStereo(h1: number, h3: number, gr: number)
+ local mpeg1 = band(h1, 8) ~= 0
+ local ms = band(h3, 0x20) ~= 0
+ local nLong, nShort = GR_NLONG[gr], GR_NSHORT[gr]
+ local nSfb = nLong + nShort
+ local maxBlocks = if nShort ~= 0 then 3 else 1
+ local sfb0 = GR_SFB[gr]
+ -- L3_stereo_top_band on the right channel
+ MAXB[0], MAXB[1], MAXB[2] = -1, -1, -1
+ local right = 576
+ for i = 0, nSfb - 1 do
+ local n = ru8(SFB, sfb0 + i)
+ for k = right, right + n - 1, 2 do
+ if rf(GRBUF, k * 4) ~= 0 or rf(GRBUF, k * 4 + 4) ~= 0 then
+ MAXB[i % 3] = i
+ break
+ end
+ end
+ right += n
+ end
+ if nLong ~= 0 then
+ local m = max(MAXB[0], MAXB[1], MAXB[2])
+ MAXB[0], MAXB[1], MAXB[2] = m, m, m
+ end
+ for i = 0, maxBlocks - 1 do
+ local defaultPos = if mpeg1 then 3 else 0
+ local itop = nSfb - maxBlocks + i
+ local prev = itop - maxBlocks
+ wu8(IST, 39 + itop, if MAXB[i] >= prev then defaultPos else ru8(IST, 39 + prev))
+ end
+ -- L3_stereo_process
+ local mpeg2sh = band(GR_SFC[gr + 1], 1)
+ local maxPos = if mpeg1 then 7 else 64
+ local s = if ms then f32(1.41421356) else 1
+ local left = 0
+ local i = 0
+ while true do
+ local n = ru8(SFB, sfb0 + i)
+ if n == 0 then
+ break
+ end
+ local ipos = ru8(IST, 39 + i)
+ if i > MAXB[i % 3] and ipos < maxPos then
+ local kl, kr
+ if mpeg1 then
+ kl, kr = PAN[2 * ipos], PAN[2 * ipos + 1]
+ else
+ kl = 1
+ kr = ldexpQ2(1, lshift(rshift(ipos + 1, 1), mpeg2sh))
+ if band(ipos, 1) ~= 0 then
+ kl = kr
+ kr = 1
+ end
+ end
+ kl, kr = f32(kl * s), f32(kr * s)
+ for k = left * 4, (left + n - 1) * 4, 4 do
+ local v = rf(GRBUF, k)
+ wf(GRBUF, k + 2304, v * kr)
+ wf(GRBUF, k, v * kl)
+ end
+ elseif ms then
+ midside(left, n)
+ end
+ left += n
+ i += 1
+ end
+end
+
+----------------------------------------------------------------------------------------------------------------
+-- layer III reorder, antialias, IMDCT
+
+local function reorder(g: number, sfb: number)
+ local src, dst = g, 0
+ while true do
+ local len = ru8(SFB, sfb)
+ if len == 0 then
+ break
+ end
+ for i = 0, len - 1 do
+ local s = (src + i) * 4
+ wf(SYN, dst, rf(GRBUF, s))
+ wf(SYN, dst + 4, rf(GRBUF, s + len * 4))
+ wf(SYN, dst + 8, rf(GRBUF, s + len * 8))
+ dst += 12
+ end
+ src += 3 * len
+ sfb += 3
+ end
+ bcopy(GRBUF, g * 4, SYN, 0, dst)
+end
+
+local AA0 = table.create(8, 0)
+local AA1 = table.create(8, 0)
+for i = 0, 7 do
+ AA0[i + 1] = rf(AA, i * 4)
+ AA1[i + 1] = rf(AA, 32 + i * 4)
+end
+
+local function antialias(g: number, nbands: number)
+ local o = g * 4
+ for _ = 1, nbands do
+ for i = 0, 7 do
+ local ui, di = o + (18 + i) * 4, o + (17 - i) * 4
+ local u, d = rf(GRBUF, ui), rf(GRBUF, di)
+ local c0, c1 = AA0[i + 1], AA1[i + 1]
+ wf(GRBUF, ui, u * c0 - d * c1)
+ wf(GRBUF, di, u * c1 + d * c0)
+ end
+ o += 72
+ end
+end
+
+-- BEGIN generated by tools/gen_dsp.py
+
+-- L3_dct3_9 on 9 values
+local function dct3_9(s0: number, s1: number, s2: number, s3: number, s4: number, s5: number, s6: number, s7: number, s8: number)
+ local t0 = s0 + s6 * 0.5
+ s0 -= s6
+ local t4 = (s4 + s2) * 0.939692616
+ local t2 = (s8 + s2) * 0.766044438
+ s6 = (s4 - s8) * 0.173648179
+ s4 += s8 - s2
+ s2 = s0 - s4 * 0.5
+ local y4 = s4 + s0
+ s8 = t0 - t2 + s6
+ s0 = t0 - t4 + t2
+ s4 = t0 + t4 - s6
+ s3 *= 0.866025388
+ t0 = (s5 + s1) * 0.98480773
+ t4 = (s5 - s7) * 0.342020154
+ t2 = (s1 + s7) * 0.642787635
+ s1 = (s1 - s5 - s7) * 0.866025388
+ s5 = t0 - s3 - t2
+ s7 = t4 - s3 - t0
+ s3 = t4 + s3 - t2
+ return s4 - s7, s2 + s1, s0 - s3, s8 + s5, y4, s8 - s5, s0 + s3, s2 - s1, s4 + s7
+end
+
+-- L3_imdct36: GRBUF[g ..], OVL[ov ..] (float indices), window W (1-based, 18 values)
+local function imdct36(g: number, ov: number, W: { number }, nbands: number)
+ local w0 = W[1]
+ local w1 = W[2]
+ local w2 = W[3]
+ local w3 = W[4]
+ local w4 = W[5]
+ local w5 = W[6]
+ local w6 = W[7]
+ local w7 = W[8]
+ local w8 = W[9]
+ local w9 = W[10]
+ local w10 = W[11]
+ local w11 = W[12]
+ local w12 = W[13]
+ local w13 = W[14]
+ local w14 = W[15]
+ local w15 = W[16]
+ local w16 = W[17]
+ local w17 = W[18]
+ for _ = 1, nbands do
+ local gb = g * 4
+ local g0 = rf(GRBUF, gb + 0)
+ local g1 = rf(GRBUF, gb + 4)
+ local g2 = rf(GRBUF, gb + 8)
+ local g3 = rf(GRBUF, gb + 12)
+ local g4 = rf(GRBUF, gb + 16)
+ local g5 = rf(GRBUF, gb + 20)
+ local g6 = rf(GRBUF, gb + 24)
+ local g7 = rf(GRBUF, gb + 28)
+ local g8 = rf(GRBUF, gb + 32)
+ local g9 = rf(GRBUF, gb + 36)
+ local g10 = rf(GRBUF, gb + 40)
+ local g11 = rf(GRBUF, gb + 44)
+ local g12 = rf(GRBUF, gb + 48)
+ local g13 = rf(GRBUF, gb + 52)
+ local g14 = rf(GRBUF, gb + 56)
+ local g15 = rf(GRBUF, gb + 60)
+ local g16 = rf(GRBUF, gb + 64)
+ local g17 = rf(GRBUF, gb + 68)
+ local c0, c1, c2, c3, c4, c5, c6, c7, c8 = dct3_9(-g0, g1 + g2, -(g3 + g4), g5 + g6, -(g7 + g8), g9 + g10, -(g11 + g12), g13 + g14, -(g15 + g16))
+ local s0, s1, s2, s3, s4, s5, s6, s7, s8 = dct3_9(g17, g16 - g15, g13 - g14, g12 - g11, g9 - g10, g8 - g7, g5 - g6, g4 - g3, g1 - g2)
+ s1, s3, s5, s7 = -s1, -s3, -s5, -s7
+ local ob = ov * 4
+ do
+ local ovl = rf(OVL, ob + 0)
+ local sum = c0 * 0.675590217 + s0 * 0.737277329
+ wf(OVL, ob + 0, c0 * 0.737277329 - s0 * 0.675590217)
+ wf(GRBUF, gb + 0, ovl * w0 - sum * w9)
+ wf(GRBUF, gb + 68, ovl * w9 + sum * w0)
+ end
+ do
+ local ovl = rf(OVL, ob + 4)
+ local sum = c1 * 0.60876143 + s1 * 0.793353319
+ wf(OVL, ob + 4, c1 * 0.793353319 - s1 * 0.60876143)
+ wf(GRBUF, gb + 4, ovl * w1 - sum * w10)
+ wf(GRBUF, gb + 64, ovl * w10 + sum * w1)
+ end
+ do
+ local ovl = rf(OVL, ob + 8)
+ local sum = c2 * 0.537299633 + s2 * 0.843391478
+ wf(OVL, ob + 8, c2 * 0.843391478 - s2 * 0.537299633)
+ wf(GRBUF, gb + 8, ovl * w2 - sum * w11)
+ wf(GRBUF, gb + 60, ovl * w11 + sum * w2)
+ end
+ do
+ local ovl = rf(OVL, ob + 12)
+ local sum = c3 * 0.4617486 + s3 * 0.887010813
+ wf(OVL, ob + 12, c3 * 0.887010813 - s3 * 0.4617486)
+ wf(GRBUF, gb + 12, ovl * w3 - sum * w12)
+ wf(GRBUF, gb + 56, ovl * w12 + sum * w3)
+ end
+ do
+ local ovl = rf(OVL, ob + 16)
+ local sum = c4 * 0.382683426 + s4 * 0.923879504
+ wf(OVL, ob + 16, c4 * 0.923879504 - s4 * 0.382683426)
+ wf(GRBUF, gb + 16, ovl * w4 - sum * w13)
+ wf(GRBUF, gb + 52, ovl * w13 + sum * w4)
+ end
+ do
+ local ovl = rf(OVL, ob + 20)
+ local sum = c5 * 0.300705791 + s5 * 0.953716934
+ wf(OVL, ob + 20, c5 * 0.953716934 - s5 * 0.300705791)
+ wf(GRBUF, gb + 20, ovl * w5 - sum * w14)
+ wf(GRBUF, gb + 48, ovl * w14 + sum * w5)
+ end
+ do
+ local ovl = rf(OVL, ob + 24)
+ local sum = c6 * 0.216439605 + s6 * 0.976296008
+ wf(OVL, ob + 24, c6 * 0.976296008 - s6 * 0.216439605)
+ wf(GRBUF, gb + 24, ovl * w6 - sum * w15)
+ wf(GRBUF, gb + 44, ovl * w15 + sum * w6)
+ end
+ do
+ local ovl = rf(OVL, ob + 28)
+ local sum = c7 * 0.130526185 + s7 * 0.991444886
+ wf(OVL, ob + 28, c7 * 0.991444886 - s7 * 0.130526185)
+ wf(GRBUF, gb + 28, ovl * w7 - sum * w16)
+ wf(GRBUF, gb + 40, ovl * w16 + sum * w7)
+ end
+ do
+ local ovl = rf(OVL, ob + 32)
+ local sum = c8 * 0.0436193794 + s8 * 0.999048233
+ wf(OVL, ob + 32, c8 * 0.999048233 - s8 * 0.0436193794)
+ wf(GRBUF, gb + 32, ovl * w8 - sum * w17)
+ wf(GRBUF, gb + 36, ovl * w17 + sum * w8)
+ end
+ g += 18
+ ov += 9
+ end
+end
+
+-- mp3d_DCT_II (scalar path) over the n time slots of a channel at GRBUF[g ..]: t[4][8] in locals
+local function dctII(g: number, n: number)
+ for k = 0, n - 1 do
+ local y = (g + k) * 4
+ local t0_0, t1_0, t2_0, t3_0
+ do
+ local x0, x1, x2, x3 = rf(GRBUF, y + 0), rf(GRBUF, y + 1080), rf(GRBUF, y + 1152), rf(GRBUF, y + 2232)
+ local a, b = x0 + x3, x1 + x2
+ local c, d = (x1 - x2) * 10.1900082, (x0 - x3) * 0.50060302
+ t0_0 = a + b
+ t1_0 = (a - b) * 0.502419293
+ t2_0 = d + c
+ t3_0 = (d - c) * 0.502419293
+ end
+ local t0_1, t1_1, t2_1, t3_1
+ do
+ local x0, x1, x2, x3 = rf(GRBUF, y + 72), rf(GRBUF, y + 1008), rf(GRBUF, y + 1224), rf(GRBUF, y + 2160)
+ local a, b = x0 + x3, x1 + x2
+ local c, d = (x1 - x2) * 3.40760851, (x0 - x3) * 0.505470932
+ t0_1 = a + b
+ t1_1 = (a - b) * 0.522498608
+ t2_1 = d + c
+ t3_1 = (d - c) * 0.522498608
+ end
+ local t0_2, t1_2, t2_2, t3_2
+ do
+ local x0, x1, x2, x3 = rf(GRBUF, y + 144), rf(GRBUF, y + 936), rf(GRBUF, y + 1296), rf(GRBUF, y + 2088)
+ local a, b = x0 + x3, x1 + x2
+ local c, d = (x1 - x2) * 2.05778098, (x0 - x3) * 0.515447319
+ t0_2 = a + b
+ t1_2 = (a - b) * 0.566944063
+ t2_2 = d + c
+ t3_2 = (d - c) * 0.566944063
+ end
+ local t0_3, t1_3, t2_3, t3_3
+ do
+ local x0, x1, x2, x3 = rf(GRBUF, y + 216), rf(GRBUF, y + 864), rf(GRBUF, y + 1368), rf(GRBUF, y + 2016)
+ local a, b = x0 + x3, x1 + x2
+ local c, d = (x1 - x2) * 1.4841646, (x0 - x3) * 0.531042576
+ t0_3 = a + b
+ t1_3 = (a - b) * 0.646821797
+ t2_3 = d + c
+ t3_3 = (d - c) * 0.646821797
+ end
+ local t0_4, t1_4, t2_4, t3_4
+ do
+ local x0, x1, x2, x3 = rf(GRBUF, y + 288), rf(GRBUF, y + 792), rf(GRBUF, y + 1440), rf(GRBUF, y + 1944)
+ local a, b = x0 + x3, x1 + x2
+ local c, d = (x1 - x2) * 1.16943991, (x0 - x3) * 0.553103924
+ t0_4 = a + b
+ t1_4 = (a - b) * 0.788154602
+ t2_4 = d + c
+ t3_4 = (d - c) * 0.788154602
+ end
+ local t0_5, t1_5, t2_5, t3_5
+ do
+ local x0, x1, x2, x3 = rf(GRBUF, y + 360), rf(GRBUF, y + 720), rf(GRBUF, y + 1512), rf(GRBUF, y + 1872)
+ local a, b = x0 + x3, x1 + x2
+ local c, d = (x1 - x2) * 0.972568214, (x0 - x3) * 0.582934976
+ t0_5 = a + b
+ t1_5 = (a - b) * 1.06067765
+ t2_5 = d + c
+ t3_5 = (d - c) * 1.06067765
+ end
+ local t0_6, t1_6, t2_6, t3_6
+ do
+ local x0, x1, x2, x3 = rf(GRBUF, y + 432), rf(GRBUF, y + 648), rf(GRBUF, y + 1584), rf(GRBUF, y + 1800)
+ local a, b = x0 + x3, x1 + x2
+ local c, d = (x1 - x2) * 0.839349627, (x0 - x3) * 0.622504115
+ t0_6 = a + b
+ t1_6 = (a - b) * 1.72244716
+ t2_6 = d + c
+ t3_6 = (d - c) * 1.72244716
+ end
+ local t0_7, t1_7, t2_7, t3_7
+ do
+ local x0, x1, x2, x3 = rf(GRBUF, y + 504), rf(GRBUF, y + 576), rf(GRBUF, y + 1656), rf(GRBUF, y + 1728)
+ local a, b = x0 + x3, x1 + x2
+ local c, d = (x1 - x2) * 0.744536281, (x0 - x3) * 0.674808323
+ t0_7 = a + b
+ t1_7 = (a - b) * 5.10114861
+ t2_7 = d + c
+ t3_7 = (d - c) * 5.10114861
+ end
+ do -- row 0
+ local x0, x1, x2, x3, x4, x5, x6, x7 = t0_0, t0_1, t0_2, t0_3, t0_4, t0_5, t0_6, t0_7
+ local xt = x0 - x7
+ x0 += x7
+ x7 = x1 - x6
+ x1 += x6
+ x6 = x2 - x5
+ x2 += x5
+ x5 = x3 - x4
+ x3 += x4
+ x4 = x0 - x3
+ x0 += x3
+ x3 = x1 - x2
+ x1 += x2
+ t0_0 = x0 + x1
+ t0_4 = (x0 - x1) * 0.707106769
+ x5 += x6
+ x6 = (x6 + x7) * 0.707106769
+ x7 += xt
+ x3 = (x3 + x4) * 0.707106769
+ x5 -= x7 * 0.198912367
+ x7 += x5 * 0.382683426
+ x5 -= x7 * 0.198912367
+ x0 = xt - x6
+ xt += x6
+ t0_1 = (xt + x7) * 0.509795606
+ t0_2 = (x4 + x3) * 0.541196108
+ t0_3 = (x0 - x5) * 0.601344883
+ t0_5 = (x0 + x5) * 0.899976194
+ t0_6 = (x4 - x3) * 1.30656302
+ t0_7 = (xt - x7) * 2.56291556
+ end
+ do -- row 1
+ local x0, x1, x2, x3, x4, x5, x6, x7 = t1_0, t1_1, t1_2, t1_3, t1_4, t1_5, t1_6, t1_7
+ local xt = x0 - x7
+ x0 += x7
+ x7 = x1 - x6
+ x1 += x6
+ x6 = x2 - x5
+ x2 += x5
+ x5 = x3 - x4
+ x3 += x4
+ x4 = x0 - x3
+ x0 += x3
+ x3 = x1 - x2
+ x1 += x2
+ t1_0 = x0 + x1
+ t1_4 = (x0 - x1) * 0.707106769
+ x5 += x6
+ x6 = (x6 + x7) * 0.707106769
+ x7 += xt
+ x3 = (x3 + x4) * 0.707106769
+ x5 -= x7 * 0.198912367
+ x7 += x5 * 0.382683426
+ x5 -= x7 * 0.198912367
+ x0 = xt - x6
+ xt += x6
+ t1_1 = (xt + x7) * 0.509795606
+ t1_2 = (x4 + x3) * 0.541196108
+ t1_3 = (x0 - x5) * 0.601344883
+ t1_5 = (x0 + x5) * 0.899976194
+ t1_6 = (x4 - x3) * 1.30656302
+ t1_7 = (xt - x7) * 2.56291556
+ end
+ do -- row 2
+ local x0, x1, x2, x3, x4, x5, x6, x7 = t2_0, t2_1, t2_2, t2_3, t2_4, t2_5, t2_6, t2_7
+ local xt = x0 - x7
+ x0 += x7
+ x7 = x1 - x6
+ x1 += x6
+ x6 = x2 - x5
+ x2 += x5
+ x5 = x3 - x4
+ x3 += x4
+ x4 = x0 - x3
+ x0 += x3
+ x3 = x1 - x2
+ x1 += x2
+ t2_0 = x0 + x1
+ t2_4 = (x0 - x1) * 0.707106769
+ x5 += x6
+ x6 = (x6 + x7) * 0.707106769
+ x7 += xt
+ x3 = (x3 + x4) * 0.707106769
+ x5 -= x7 * 0.198912367
+ x7 += x5 * 0.382683426
+ x5 -= x7 * 0.198912367
+ x0 = xt - x6
+ xt += x6
+ t2_1 = (xt + x7) * 0.509795606
+ t2_2 = (x4 + x3) * 0.541196108
+ t2_3 = (x0 - x5) * 0.601344883
+ t2_5 = (x0 + x5) * 0.899976194
+ t2_6 = (x4 - x3) * 1.30656302
+ t2_7 = (xt - x7) * 2.56291556
+ end
+ do -- row 3
+ local x0, x1, x2, x3, x4, x5, x6, x7 = t3_0, t3_1, t3_2, t3_3, t3_4, t3_5, t3_6, t3_7
+ local xt = x0 - x7
+ x0 += x7
+ x7 = x1 - x6
+ x1 += x6
+ x6 = x2 - x5
+ x2 += x5
+ x5 = x3 - x4
+ x3 += x4
+ x4 = x0 - x3
+ x0 += x3
+ x3 = x1 - x2
+ x1 += x2
+ t3_0 = x0 + x1
+ t3_4 = (x0 - x1) * 0.707106769
+ x5 += x6
+ x6 = (x6 + x7) * 0.707106769
+ x7 += xt
+ x3 = (x3 + x4) * 0.707106769
+ x5 -= x7 * 0.198912367
+ x7 += x5 * 0.382683426
+ x5 -= x7 * 0.198912367
+ x0 = xt - x6
+ xt += x6
+ t3_1 = (xt + x7) * 0.509795606
+ t3_2 = (x4 + x3) * 0.541196108
+ t3_3 = (x0 - x5) * 0.601344883
+ t3_5 = (x0 + x5) * 0.899976194
+ t3_6 = (x4 - x3) * 1.30656302
+ t3_7 = (xt - x7) * 2.56291556
+ end
+ wf(GRBUF, y + 0, t0_0)
+ wf(GRBUF, y + 72, t2_0 + t3_0 + t3_1)
+ wf(GRBUF, y + 144, t1_0 + t1_1)
+ wf(GRBUF, y + 216, t2_1 + t3_0 + t3_1)
+ wf(GRBUF, y + 288, t0_1)
+ wf(GRBUF, y + 360, t2_1 + t3_1 + t3_2)
+ wf(GRBUF, y + 432, t1_1 + t1_2)
+ wf(GRBUF, y + 504, t2_2 + t3_1 + t3_2)
+ wf(GRBUF, y + 576, t0_2)
+ wf(GRBUF, y + 648, t2_2 + t3_2 + t3_3)
+ wf(GRBUF, y + 720, t1_2 + t1_3)
+ wf(GRBUF, y + 792, t2_3 + t3_2 + t3_3)
+ wf(GRBUF, y + 864, t0_3)
+ wf(GRBUF, y + 936, t2_3 + t3_3 + t3_4)
+ wf(GRBUF, y + 1008, t1_3 + t1_4)
+ wf(GRBUF, y + 1080, t2_4 + t3_3 + t3_4)
+ wf(GRBUF, y + 1152, t0_4)
+ wf(GRBUF, y + 1224, t2_4 + t3_4 + t3_5)
+ wf(GRBUF, y + 1296, t1_4 + t1_5)
+ wf(GRBUF, y + 1368, t2_5 + t3_4 + t3_5)
+ wf(GRBUF, y + 1440, t0_5)
+ wf(GRBUF, y + 1512, t2_5 + t3_5 + t3_6)
+ wf(GRBUF, y + 1584, t1_5 + t1_6)
+ wf(GRBUF, y + 1656, t2_6 + t3_5 + t3_6)
+ wf(GRBUF, y + 1728, t0_6)
+ wf(GRBUF, y + 1800, t2_6 + t3_6 + t3_7)
+ wf(GRBUF, y + 1872, t1_6 + t1_7)
+ wf(GRBUF, y + 1944, t2_7 + t3_6 + t3_7)
+ wf(GRBUF, y + 2016, t0_7)
+ wf(GRBUF, y + 2088, t2_7 + t3_7)
+ wf(GRBUF, y + 2160, t1_7)
+ wf(GRBUF, y + 2232, t3_7)
+ end
+end
+
+-- END generated
+
+
+-- L3_imdct12: x = TMP f32 index (stride 3), dst buffer + float index, ov = OVL float index
+local function imdct12(x: number, dst: buffer, d: number, ov: number)
+ local xb = x * 4
+ local x0, x3, x6, x9, x12, x15 =
+ rf(TMP, xb), rf(TMP, xb + 12), rf(TMP, xb + 24), rf(TMP, xb + 36), rf(TMP, xb + 48), rf(TMP, xb + 60)
+ -- L3_idct3(-x0, x6 + x3, x12 + x9) -> co
+ local c0, c1, c2 = -x0, (x6 + x3), (x12 + x9)
+ local m1 = (c1 * 0.86602540)
+ local a1 = (c0 - c2 * 0.5)
+ local co1 = c0 + c2
+ local co0, co2 = a1 + m1, a1 - m1
+ -- L3_idct3(x15, x12 - x9, x6 - x3) -> si
+ c0, c1, c2 = x15, (x12 - x9), (x6 - x3)
+ m1 = (c1 * 0.86602540)
+ a1 = (c0 - c2 * 0.5)
+ local si1 = -(c0 + c2)
+ local si0, si2 = a1 + m1, a1 - m1
+ local ob, db = ov * 4, d * 4
+ for i = 0, 2 do
+ local co = if i == 0 then co0 elseif i == 1 then co1 else co2
+ local si = if i == 0 then si0 elseif i == 1 then si1 else si2
+ local ovl = rf(OVL, ob + i * 4)
+ local sum = (co * rf(TWID3, (3 + i) * 4) + si * rf(TWID3, i * 4))
+ wf(OVL, ob + i * 4, co * rf(TWID3, i * 4) - si * rf(TWID3, (3 + i) * 4))
+ wf(dst, db + i * 4, ovl * rf(TWID3, (2 - i) * 4) - sum * rf(TWID3, (5 - i) * 4))
+ wf(dst, db + (5 - i) * 4, ovl * rf(TWID3, (5 - i) * 4) + sum * rf(TWID3, (2 - i) * 4))
+ end
+end
+
+local function imdctShort(g: number, ov: number, nbands: number)
+ for _ = 1, nbands do
+ bcopy(TMP, 0, GRBUF, g * 4, 72)
+ bcopy(GRBUF, g * 4, OVL, ov * 4, 24)
+ imdct12(0, GRBUF, g + 6, ov + 6)
+ imdct12(1, GRBUF, g + 12, ov + 6)
+ imdct12(2, OVL, ov, ov + 6)
+ g += 18
+ ov += 9
+ end
+end
+
+local function changeSign(g: number)
+ local o = (g + 18) * 4
+ for _ = 0, 15 do
+ for i = 1, 17, 2 do
+ wf(GRBUF, o + i * 4, -rf(GRBUF, o + i * 4))
+ end
+ o += 144
+ end
+end
+
+local function imdctGr(g: number, ov: number, bt: number, nLongBands: number)
+ if nLongBands ~= 0 then
+ imdct36(g, ov, MDCT_WIN0, nLongBands)
+ g += 18 * nLongBands
+ ov += 9 * nLongBands
+ end
+ if bt == 2 then
+ imdctShort(g, ov, 32 - nLongBands)
+ else
+ imdct36(g, ov, if bt == 3 then MDCT_WIN1 else MDCT_WIN0, 32 - nLongBands)
+ end
+end
+
+-- L3_decode: one granule, side info at gr = grBase + ch
+local function l3Decode(h1: number, h2: number, h3: number, grBase: number, nch: number)
+ for ch = 0, nch - 1 do
+ local gr = grBase + ch
+ local limit = bsPos + GR_P23[gr]
+ decodeScalefactors(h1, h3, ch * 39, gr, ch)
+ huffman(ch * 576, gr, limit)
+ end
+ if band(h3, 0x10) ~= 0 then
+ intensityStereo(h1, h3, grBase)
+ elseif band(h3, 0xE0) == 0x60 then
+ midside(0, 576)
+ end
+ local mySr = band(rshift(h2, 2), 3) + (band(rshift(h1, 3), 1) + band(rshift(h1, 4), 1)) * 3
+ for ch = 0, nch - 1 do
+ local gr = grBase + ch
+ local aaBands = 31
+ local nLongBands = if GR_MIXED[gr] ~= 0 then (if mySr == 2 then 4 else 2) else 0
+ local g = ch * 576
+ if GR_NSHORT[gr] ~= 0 then
+ aaBands = nLongBands - 1
+ reorder(g + nLongBands * 18, GR_SFB[gr] + GR_NLONG[gr])
+ end
+ antialias(g, aaBands)
+ imdctGr(g, ch * 288, GR_BT[gr], nLongBands)
+ changeSign(g)
+ end
+end
+
+----------------------------------------------------------------------------------------------------------------
+-- polyphase synthesis (mp3d_DCT_II, mp3d_synth, mp3d_synth_granule)
+
+
+-- mp3d_synth_pair: z = SYN float index, dst = PCM float index
+local function synthPair(dst: number, nch: number, z: number)
+ local zb = z * 4
+ local a = (rf(SYN, zb + 14 * 256) - rf(SYN, zb)) * 29
+ a += (rf(SYN, zb + 1 * 256) + rf(SYN, zb + 13 * 256)) * 213
+ a += (rf(SYN, zb + 12 * 256) - rf(SYN, zb + 2 * 256)) * 459
+ a += (rf(SYN, zb + 3 * 256) + rf(SYN, zb + 11 * 256)) * 2037
+ a += (rf(SYN, zb + 10 * 256) - rf(SYN, zb + 4 * 256)) * 5153
+ a += (rf(SYN, zb + 5 * 256) + rf(SYN, zb + 9 * 256)) * 6574
+ a += (rf(SYN, zb + 8 * 256) - rf(SYN, zb + 6 * 256)) * 37489
+ a += rf(SYN, zb + 7 * 256) * 75038
+ wf(PCM, dst * 4, a * SCALE)
+ zb += 8
+ a = rf(SYN, zb + 14 * 256) * 104
+ a += rf(SYN, zb + 12 * 256) * 1567
+ a += rf(SYN, zb + 10 * 256) * 9727
+ a += rf(SYN, zb + 8 * 256) * 64019
+ a += rf(SYN, zb + 6 * 256) * -9975
+ a += rf(SYN, zb + 4 * 256) * -45
+ a += rf(SYN, zb + 2 * 256) * 146
+ a += rf(SYN, zb) * -5
+ wf(PCM, (dst + 16 * nch) * 4, a * SCALE)
+end
+
+-- mp3d_synth: two time slots of 32 subbands -> 64 samples per channel. xl = GRBUF float index of the left
+-- channel's slot, dstl = PCM float index, lins = SYN float index
+local function synth(xl: number, dstl: number, nch: number, lins: number)
+ local xr = xl + 576 * (nch - 1)
+ local dstr = dstl + (nch - 1)
+ local zlin = lins + 15 * 64
+ local zb = zlin * 4
+ local xlb, xrb = xl * 4, xr * 4
+ wf(SYN, zb + 60 * 4, rf(GRBUF, xlb + 288 * 4))
+ wf(SYN, zb + 61 * 4, rf(GRBUF, xrb + 288 * 4))
+ wf(SYN, zb + 62 * 4, rf(GRBUF, xlb))
+ wf(SYN, zb + 63 * 4, rf(GRBUF, xrb))
+ wf(SYN, zb + 124 * 4, rf(GRBUF, xlb + 289 * 4))
+ wf(SYN, zb + 125 * 4, rf(GRBUF, xrb + 289 * 4))
+ wf(SYN, zb + 126 * 4, rf(GRBUF, xlb + 4))
+ wf(SYN, zb + 127 * 4, rf(GRBUF, xrb + 4))
+ if nch == 2 then
+ synthPair(dstr, nch, lins + 4 * 15 + 1)
+ synthPair(dstr + 32 * nch, nch, lins + 4 * 15 + 64 + 1)
+ end
+ synthPair(dstl, nch, lins + 4 * 15)
+ synthPair(dstl + 32 * nch, nch, lins + 4 * 15 + 64)
+
+ local w = 1
+ for i = 14, 0, -1 do
+ local zi = zb + 16 * i
+ local s1 = (18 * (31 - i)) * 4
+ local s2 = (18 * (1 + i)) * 4
+ wf(SYN, zi, rf(GRBUF, xlb + s1))
+ wf(SYN, zi + 4, rf(GRBUF, xrb + s1))
+ wf(SYN, zi + 8, rf(GRBUF, xlb + s1 + 4))
+ wf(SYN, zi + 12, rf(GRBUF, xrb + s1 + 4))
+ wf(SYN, zi + 256, rf(GRBUF, xlb + s2 + 4))
+ wf(SYN, zi + 260, rf(GRBUF, xrb + s2 + 4))
+ wf(SYN, zi - 248, rf(GRBUF, xlb + s2))
+ wf(SYN, zi - 244, rf(GRBUF, xrb + s2))
+ -- the 8 window steps, even k (a += z w0 - y w1) and odd k (a += y w1 - z w0) in pairs; mono needs lanes 0, 2
+ local a0, a1, a2, a3, b0, b1, b2, b3 = 0, 0, 0, 0, 0, 0, 0, 0
+ local vz, vy = zi, zi - 15 * 256
+ if nch == 2 then
+ for _ = 0, 3 do
+ local w0, w1, w2, w3 = WINT[w], WINT[w + 1], WINT[w + 2], WINT[w + 3]
+ w += 4
+ local z0, z1, z2, z3 = rf(SYN, vz), rf(SYN, vz + 4), rf(SYN, vz + 8), rf(SYN, vz + 12)
+ local y0, y1, y2, y3 = rf(SYN, vy), rf(SYN, vy + 4), rf(SYN, vy + 8), rf(SYN, vy + 12)
+ b0 += z0 * w1 + y0 * w0
+ b1 += z1 * w1 + y1 * w0
+ b2 += z2 * w1 + y2 * w0
+ b3 += z3 * w1 + y3 * w0
+ a0 += z0 * w0 - y0 * w1
+ a1 += z1 * w0 - y1 * w1
+ a2 += z2 * w0 - y2 * w1
+ a3 += z3 * w0 - y3 * w1
+ vz -= 256
+ vy += 256
+ z0, z1, z2, z3 = rf(SYN, vz), rf(SYN, vz + 4), rf(SYN, vz + 8), rf(SYN, vz + 12)
+ y0, y1, y2, y3 = rf(SYN, vy), rf(SYN, vy + 4), rf(SYN, vy + 8), rf(SYN, vy + 12)
+ b0 += z0 * w3 + y0 * w2
+ b1 += z1 * w3 + y1 * w2
+ b2 += z2 * w3 + y2 * w2
+ b3 += z3 * w3 + y3 * w2
+ a0 += y0 * w3 - z0 * w2
+ a1 += y1 * w3 - z1 * w2
+ a2 += y2 * w3 - z2 * w2
+ a3 += y3 * w3 - z3 * w2
+ vz -= 256
+ vy += 256
+ end
+ wf(PCM, (dstr + (15 - i) * 2) * 4, a1 * SCALE)
+ wf(PCM, (dstr + (17 + i) * 2) * 4, b1 * SCALE)
+ wf(PCM, (dstr + (47 - i) * 2) * 4, a3 * SCALE)
+ wf(PCM, (dstr + (49 + i) * 2) * 4, b3 * SCALE)
+ else
+ for _ = 0, 3 do
+ local w0, w1, w2, w3 = WINT[w], WINT[w + 1], WINT[w + 2], WINT[w + 3]
+ w += 4
+ local z0, z2 = rf(SYN, vz), rf(SYN, vz + 8)
+ local y0, y2 = rf(SYN, vy), rf(SYN, vy + 8)
+ b0 += z0 * w1 + y0 * w0
+ b2 += z2 * w1 + y2 * w0
+ a0 += z0 * w0 - y0 * w1
+ a2 += z2 * w0 - y2 * w1
+ vz -= 256
+ vy += 256
+ z0, z2 = rf(SYN, vz), rf(SYN, vz + 8)
+ y0, y2 = rf(SYN, vy), rf(SYN, vy + 8)
+ b0 += z0 * w3 + y0 * w2
+ b2 += z2 * w3 + y2 * w2
+ a0 += y0 * w3 - z0 * w2
+ a2 += y2 * w3 - z2 * w2
+ vz -= 256
+ vy += 256
+ end
+ end
+ wf(PCM, (dstl + (15 - i) * nch) * 4, a0 * SCALE)
+ wf(PCM, (dstl + (17 + i) * nch) * 4, b0 * SCALE)
+ wf(PCM, (dstl + (47 - i) * nch) * 4, a2 * SCALE)
+ wf(PCM, (dstl + (49 + i) * nch) * 4, b2 * SCALE)
+ end
+end
+
+local function synthGranule(nbands: number, nch: number, pcm: number)
+ for ch = 0, nch - 1 do
+ dctII(576 * ch, nbands)
+ end
+ bcopy(SYN, 0, QMF, 0, 15 * 64 * 4)
+ for i = 0, nbands - 1, 2 do
+ synth(i, pcm + 32 * nch * i, nch, i * 64)
+ end
+ if nch == 1 then
+ local src = nbands * 64 * 4
+ for i = 0, 15 * 64 * 4 - 8, 8 do
+ wf(QMF, i, rf(SYN, src + i))
+ end
+ else
+ bcopy(QMF, 0, SYN, nbands * 64 * 4, 15 * 64 * 4)
+ end
+end
+
+----------------------------------------------------------------------------------------------------------------
+-- layers I and II
+
+local ALLOC_L1 = { 76, 4, 32 }
+local ALLOC_L2M2 = { 60, 4, 4, 44, 3, 7, 44, 2, 19 }
+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 totalBands, stereoBands = 0, 0
+
+local function l12ReadScaleInfo(h1: number, h2: number, h3: number, kbpsHdr: number)
+ local mode = rshift(h3, 6)
+ local sb = if mode == 3 then 0 elseif mode == 1 then band(rshift(h3, 4), 3) * 4 + 4 else 32
+ local layer1 = band(h1, 6) == 6
+ local alloc, nbands
+ if layer1 then
+ alloc, nbands = ALLOC_L1, 32
+ elseif band(h1, 8) == 0 then
+ alloc, nbands = ALLOC_L2M2, 30
+ else
+ local srIdx = band(rshift(h2, 2), 3)
+ local kbps = if mode ~= 3 then rshift(kbpsHdr, 1) else kbpsHdr
+ if kbps == 0 then
+ kbps = 192
+ end
+ alloc, nbands = ALLOC_L2M1, 27
+ if kbps < 56 then
+ alloc, nbands = ALLOC_L2M1_LOW, if srIdx == 2 then 12 else 8
+ elseif kbps >= 96 and srIdx ~= 1 then
+ nbands = 30
+ end
+ end
+ totalBands = nbands
+ stereoBands = min(sb, nbands)
+ local k, baBits, codeOff, ai = 0, 0, 0, 1
+ for i = 0, nbands - 1 do
+ if i == k then
+ codeOff, baBits, k = alloc[ai], alloc[ai + 1], k + alloc[ai + 2]
+ ai += 3
+ end
+ local ba = BITALLOC_CODE[codeOff + getBits(baBits)]
+ wu8(BA, 2 * i, ba)
+ if i < stereoBands then
+ ba = BITALLOC_CODE[codeOff + getBits(baBits)]
+ end
+ wu8(BA, 2 * i + 1, if stereoBands ~= 0 then ba else 0)
+ end
+ for i = 0, 2 * nbands - 1 do
+ wu8(SCFCOD, i, if ru8(BA, i) ~= 0 then (if layer1 then 2 else getBits(2)) else 6)
+ end
+ -- L12_read_scalefactors
+ local so = 0
+ for i = 0, 2 * nbands - 1 do
+ local s = 0
+ local ba = ru8(BA, i)
+ local mask = if ba ~= 0 then 4 + band(rshift(19, ru8(SCFCOD, i)), 3) else 0
+ local m = 4
+ while m ~= 0 do
+ if band(mask, m) ~= 0 then
+ local b = getBits(6)
+ s = f32(DEQ_L12[ba * 3 - 6 + b % 3] * rshift(lshift(1, 21), b // 3))
+ end
+ wf(L12SCF, so, s)
+ so += 4
+ m = rshift(m, 1)
+ end
+ end
+ for i = stereoBands, nbands - 1 do
+ wu8(BA, 2 * i + 1, 0)
+ end
+end
+
+local function l12Dequantize(g: number, groupSize: number): number
+ local choff = 576
+ for j = 0, 3 do
+ local dst = g + groupSize * j
+ for i = 0, 2 * totalBands - 1 do
+ local ba = ru8(BA, i)
+ if ba ~= 0 then
+ if ba < 17 then
+ local half = lshift(1, ba - 1) - 1
+ for k = 0, groupSize - 1 do
+ wf(GRBUF, (dst + k) * 4, getBits(ba) - half)
+ end
+ else
+ local mod = lshift(2, ba - 17) + 1
+ local code = getBits(mod + 2 - rshift(mod, 3))
+ for k = 0, groupSize - 1 do
+ wf(GRBUF, (dst + k) * 4, code % mod - mod // 2)
+ code //= mod
+ end
+ end
+ end
+ dst += choff
+ choff = 18 - choff
+ end
+ end
+ return groupSize * 4
+end
+
+local function l12ApplyScf(scfOff: number)
+ local sb, tb = stereoBands, totalBands
+ bcopy(GRBUF, (576 + sb * 18) * 4, GRBUF, sb * 18 * 4, (tb - sb) * 18 * 4)
+ for i = 0, tb - 1 do
+ local d = i * 72
+ local s0 = rf(L12SCF, (scfOff + i * 6) * 4)
+ local s1 = rf(L12SCF, (scfOff + i * 6 + 3) * 4)
+ for k = 0, 11 do
+ local p = d + k * 4
+ wf(GRBUF, p, rf(GRBUF, p) * s0)
+ wf(GRBUF, p + 2304, rf(GRBUF, p + 2304) * s1)
+ end
+ end
+end
+
+----------------------------------------------------------------------------------------------------------------
+-- API
+
+local Core = {}
+
+Core.MAX_FRAME = MAX_FRAME
+
+export type State = {
+ overlap: buffer,
+ qmf: buffer,
+ reserv: buffer,
+ reservLen: number,
+ needReset: boolean,
+}
+
+function Core.newState(): State
+ return {
+ overlap = bcreate(2 * 9 * 32 * 4),
+ qmf = bcreate(15 * 2 * 32 * 4),
+ reserv = bcreate(MAX_BITRESERVOIR_BYTES + 8),
+ reservLen = 0,
+ needReset = false,
+ }
+end
+
+-- memset(dec, 0): what minimp3 does whenever it has to re-sync
+function Core.reset(st: State)
+ bfill(st.overlap, 0, 0)
+ bfill(st.qmf, 0, 0)
+ st.reservLen = 0
+ st.needReset = false
+end
+
+Core.lastChannels = 0
+
+-- pcm holds n mono samples: spread them to n interleaved stereo pairs (in place)
+function Core.upmix(pcm: buffer, n: number)
+ if buffer.len(pcm) < n * 8 then
+ return
+ end
+ for i = n - 1, 0, -1 do
+ local v = rf(pcm, i * 4)
+ wf(pcm, i * 8, v)
+ wf(pcm, i * 8 + 4, v)
+ end
+end
+
+-- Decodes the frame b[off, off + size) (a whole frame found by the index, header included) into pcm
+-- (interleaved f32, frame samples x channels) and returns the samples per channel (0 = no output: an
+-- unfilled bit reservoir, or corrupt data). Core.lastChannels = the frame's channel count.
+function Core.decodeFrame(st: State, b: buffer, off: number, size: number, pcm: buffer): number
+ if size < 4 or size > MAX_FRAME or off < 0 or off + size > buffer.len(b) then
+ st.needReset = true
+ return 0
+ end
+ if st.needReset then
+ Core.reset(st)
+ end
+ bcopy(FRAME, 0, b, off, size)
+ bfill(FRAME, size, 0, 8)
+ OVL, QMF, PCM = st.overlap, st.qmf, pcm
+ local h1, h2, h3 = ru8(FRAME, 1), ru8(FRAME, 2), ru8(FRAME, 3)
+ local nch = if band(h3, 0xC0) == 0xC0 then 1 else 2
+ Core.lastChannels = nch
+ local layer = 4 - band(rshift(h1, 1), 3)
+ local spf = if band(h1, 6) == 6 then 384 elseif band(h1, 14) == 2 then 576 else 1152
+ if buffer.len(pcm) < spf * nch * 4 then
+ return 0
+ end
+ bsBuf, bsPos, bsLimit = FRAME, 32, size * 8
+ if band(h1, 1) == 0 then
+ getBits(16) -- CRC
+ end
+ if layer == 3 then
+ local mdb = readSideInfo(h1, h2, h3)
+ if mdb < 0 or bsPos > bsLimit then
+ st.needReset = true
+ return 0
+ end
+ -- L3_restore_reservoir
+ local frameBytes = (bsLimit - bsPos) // 8
+ local reserv = st.reservLen
+ local have = min(reserv, mdb)
+ if have > 0 then
+ bcopy(MAIN, 0, st.reserv, max(0, reserv - mdb), have)
+ end
+ bcopy(MAIN, have, FRAME, bsPos // 8, frameBytes)
+ bfill(MAIN, have + frameBytes, 0, 8)
+ local success = reserv >= mdb
+ bsBuf, bsPos, bsLimit = MAIN, 0, (have + frameBytes) * 8
+ if success then
+ local ngr = if band(h1, 8) ~= 0 then 2 else 1
+ local p = 0
+ for igr = 0, ngr - 1 do
+ bfill(GRBUF, 0, 0)
+ l3Decode(h1, h2, h3, igr * nch, nch)
+ synthGranule(18, nch, p)
+ p += 576 * nch
+ end
+ end
+ -- L3_save_reservoir
+ local pos = (bsPos + 7) // 8
+ local remains = bsLimit // 8 - pos
+ if remains > MAX_BITRESERVOIR_BYTES then
+ pos += remains - MAX_BITRESERVOIR_BYTES
+ remains = MAX_BITRESERVOIR_BYTES
+ end
+ if remains > 0 and pos >= 0 then
+ bcopy(st.reserv, 0, MAIN, pos, remains)
+ end
+ st.reservLen = max(0, remains)
+ bsBuf = FRAME
+ return if success then spf else 0
+ end
+ -- layers I / II
+ local kbps = 2 * HALFRATE[(if band(h1, 8) ~= 0 then 45 else 0) + (band(rshift(h1, 1), 3) - 1) * 15 + rshift(h2, 4)]
+ l12ReadScaleInfo(h1, h2, h3, kbps)
+ bfill(GRBUF, 0, 0)
+ local i = 0
+ local p = 0
+ local group = bor(layer, 1)
+ for igr = 0, 2 do
+ i += l12Dequantize(i, group)
+ if i == 12 then
+ i = 0
+ l12ApplyScf(igr)
+ synthGranule(12, nch, p)
+ bfill(GRBUF, 0, 0)
+ p += 384 * nch
+ end
+ if bsPos > bsLimit then
+ st.needReset = true
+ return 0
+ end
+ end
+ return spf
+end
+
+-- Layer III side info of the frame b[off, off + size): main_data_begin (-1 = corrupt), the sum of its
+-- part2_3 lengths in bits, and the main data bytes in the frame. Used by the stream index.
+function Core.probeL3(b: buffer, off: number, size: number): (number, number, number)
+ local n = min(size, 64)
+ if size < 4 or off + n > buffer.len(b) then
+ return -1, 0, 0
+ end
+ bcopy(FRAME, 0, b, off, n)
+ local h1, h2, h3 = ru8(FRAME, 1), ru8(FRAME, 2), ru8(FRAME, 3)
+ bsBuf, bsPos, bsLimit = FRAME, 32, size * 8
+ if band(h1, 1) == 0 then
+ getBits(16)
+ end
+ local mdb = readSideInfo(h1, h2, h3)
+ if mdb < 0 or bsPos > bsLimit then
+ return -1, 0, 0
+ end
+ local ngr = (if band(h3, 0xC0) == 0xC0 then 1 else 2) * (if band(h1, 8) ~= 0 then 2 else 1)
+ local sum = 0
+ for gr = 0, ngr - 1 do
+ sum += GR_P23[gr]
+ end
+ return mdb, sum, (bsLimit - bsPos) // 8
+end
+
+-- Layer I / II: false when the frame b[off, off + size) needs more bits than it has (minimp3 then drops it).
+function Core.probeL12(b: buffer, off: number, size: number): boolean
+ if size < 4 or size > MAX_FRAME or off + size > buffer.len(b) then
+ return false
+ end
+ bcopy(FRAME, 0, b, off, size)
+ bfill(FRAME, size, 0, 8)
+ local h1, h2, h3 = ru8(FRAME, 1), ru8(FRAME, 2), ru8(FRAME, 3)
+ bsBuf, bsPos, bsLimit = FRAME, 32, size * 8
+ if band(h1, 1) == 0 then
+ getBits(16)
+ end
+ local layer = 4 - band(rshift(h1, 1), 3)
+ local kbps = 2 * HALFRATE[(if band(h1, 8) ~= 0 then 45 else 0) + (band(rshift(h1, 1), 3) - 1) * 15 + rshift(h2, 4)]
+ l12ReadScaleInfo(h1, h2, h3, kbps)
+ -- the samples: 3 calls of l12Dequantize, each 4 groups of (layer | 1) samples per allocated band
+ local group = bor(layer, 1)
+ local bits = 0
+ for i = 0, 2 * totalBands - 1 do
+ local ba = ru8(BA, i)
+ if ba ~= 0 then
+ if ba < 17 then
+ bits += ba * group
+ else
+ local mod = lshift(2, ba - 17) + 1
+ bits += mod + 2 - rshift(mod, 3)
+ end
+ end
+ end
+ return bsPos + 12 * bits <= bsLimit
+end
+
+-- mp3dec_check_vbrtag on the frame b[off, off + size): 0 = no tag, -1 = a Xing / Info tag without a frame
+-- count, 1 = tag; then frames, encoder delay + 529, padding - 529 (both 0 without a LAME extension)
+function Core.vbrTag(b: buffer, off: number, size: number): (number, number, number, number)
+ if size < 12 or size > MAX_FRAME or off + size > buffer.len(b) then
+ return 0, 0, 0, 0
+ end
+ bcopy(FRAME, 0, b, off, size)
+ bfill(FRAME, size, 0, 8)
+ local h1, h2, h3 = ru8(FRAME, 1), ru8(FRAME, 2), ru8(FRAME, 3)
+ bsBuf, bsPos, bsLimit = FRAME, 32, size * 8
+ if band(h1, 1) == 0 then
+ getBits(16)
+ end
+ if readSideInfo(h1, h2, h3) < 0 then
+ return 0, 0, 0, 0
+ end
+ local t = bsPos // 8
+ if t > size or size - t < 8 then
+ return 0, 0, 0, 0
+ end
+ local tag = buffer.readstring(FRAME, t, 4)
+ if tag ~= "Xing" and tag ~= "Info" then
+ return 0, 0, 0, 0
+ end
+ local flags = ru8(FRAME, t + 7)
+ if band(flags, 1) == 0 then
+ return -1, 0, 0, 0
+ end
+ t += 8
+ if size - t < 4 then
+ return 0, 0, 0, 0
+ end
+ local frames = bswap(ru32(FRAME, t))
+ t += 4
+ if band(flags, 2) ~= 0 then
+ if size - t < 4 then
+ return 0, 0, 0, 0
+ end
+ t += 4
+ end
+ if band(flags, 4) ~= 0 then
+ if size - t < 100 then
+ return 0, 0, 0, 0
+ end
+ t += 100
+ end
+ if band(flags, 8) ~= 0 then
+ if size - t < 4 then
+ return 0, 0, 0, 0
+ end
+ t += 4
+ end
+ if size - t < 1 then
+ return 0, 0, 0, 0
+ end
+ local delay, padding = 0, 0
+ if ru8(FRAME, t) ~= 0 then
+ if size - t <= 35 then
+ return 0, 0, 0, 0
+ end
+ t += 21
+ local t0, t1, t2 = ru8(FRAME, t), ru8(FRAME, t + 1), ru8(FRAME, t + 2)
+ delay = bor(lshift(t0, 4), rshift(t1, 4)) + 529
+ padding = bor(lshift(band(t1, 15), 8), t2) - 529
+ end
+ return 1, frames, delay, padding
+end
+
+return Core
diff --git a/src/Formats/audio/mp3/Header.luau b/src/Formats/audio/mp3/Header.luau
new file mode 100644
index 0000000..456f171
--- /dev/null
+++ b/src/Formats/audio/mp3/Header.luau
@@ -0,0 +1,140 @@
+--!strict
+--!native
+--!optimize 2
+-- audio/mp3/Header: MPEG audio frame headers (minimp3's hdr_* macros and functions), frame sync (mp3d_find_frame /
+-- mp3d_match_frame). Every function reads 4 header bytes at a byte offset of a buffer; callers keep offset + 4
+-- inside the buffer. Never throws.
+local T = require("@formats/audio/mp3/Tables")
+
+local band, bxor, rshift = bit32.band, bit32.bxor, bit32.rshift
+local ru8 = buffer.readu8
+
+local HALFRATE = T.halfrate
+local HZ = { [0] = 44100, 48000, 32000 }
+
+local H = {}
+
+H.MAX_FREE_FORMAT_FRAME_SIZE = 2304
+H.MAX_FRAME_SYNC_MATCHES = 10
+
+-- hdr_valid
+function H.valid(b: buffer, o: number): boolean
+ if ru8(b, o) ~= 0xFF then
+ return false
+ end
+ local h1, h2 = ru8(b, o + 1), ru8(b, o + 2)
+ return (band(h1, 0xF0) == 0xF0 or band(h1, 0xFE) == 0xE2)
+ and band(rshift(h1, 1), 3) ~= 0
+ and rshift(h2, 4) ~= 15
+ and band(rshift(h2, 2), 3) ~= 3
+end
+local valid = H.valid
+
+-- hdr_compare: h2 is a valid header of the same version / layer / sample rate / free-format-ness as h1
+function H.compare(b: buffer, o1: number, o2: number): boolean
+ if not valid(b, o2) then
+ return false
+ end
+ local a1, a2 = ru8(b, o1 + 1), ru8(b, o1 + 2)
+ local c1, c2 = ru8(b, o2 + 1), ru8(b, o2 + 2)
+ return band(bxor(a1, c1), 0xFE) == 0
+ and band(bxor(a2, c2), 0x0C) == 0
+ and (band(a2, 0xF0) == 0) == (band(c2, 0xF0) == 0)
+end
+local compare = H.compare
+
+-- from the header bytes h1 = byte 1, h2 = byte 2
+function H.bitrateKbps(h1: number, h2: number): number
+ local mpeg1 = if band(h1, 8) ~= 0 then 1 else 0
+ local layer = band(rshift(h1, 1), 3)
+ return 2 * HALFRATE[mpeg1 * 45 + (layer - 1) * 15 + rshift(h2, 4)]
+end
+local bitrateKbps = H.bitrateKbps
+
+function H.sampleRate(h1: number, h2: number): number
+ local hz = HZ[band(rshift(h2, 2), 3)]
+ if band(h1, 8) == 0 then
+ hz //= 2
+ end
+ if band(h1, 0x10) == 0 then
+ hz //= 2
+ end
+ return hz
+end
+local sampleRate = H.sampleRate
+
+function H.frameSamples(h1: number): number
+ if band(h1, 6) == 6 then
+ return 384
+ elseif band(h1, 14) == 2 then
+ return 576
+ end
+ return 1152
+end
+local frameSamples = H.frameSamples
+
+-- hdr_frame_bytes (without padding); free format = 0 -> freeSize
+function H.frameBytes(b: buffer, o: number, freeSize: number): number
+ local h1, h2 = ru8(b, o + 1), ru8(b, o + 2)
+ local hz = sampleRate(h1, h2)
+ local fb = frameSamples(h1) * bitrateKbps(h1, h2) * 125 // hz
+ if band(h1, 6) == 6 then
+ fb = band(fb, 0xFFFFFFFC)
+ end
+ return if fb ~= 0 then fb else freeSize
+end
+local frameBytes = H.frameBytes
+
+function H.padding(b: buffer, o: number): number
+ if band(ru8(b, o + 2), 2) == 0 then
+ return 0
+ end
+ return if band(ru8(b, o + 1), 6) == 6 then 4 else 1
+end
+local padding = H.padding
+
+-- mp3d_match_frame: the frames chained after o (n bytes left) keep comparing equal
+local function matchFrame(b: buffer, o: number, n: number, fb: number): boolean
+ local i = 0
+ for nmatch = 0, H.MAX_FRAME_SYNC_MATCHES - 1 do
+ i += frameBytes(b, o + i, fb) + padding(b, o + i)
+ if i + 4 > n then
+ return nmatch > 0
+ end
+ if not compare(b, o, o + i) then
+ return false
+ end
+ end
+ return true
+end
+
+-- mp3d_find_frame over b[base, base + n): returns (skip, frame bytes incl. padding or 0, free format size)
+function H.findFrame(b: buffer, base: number, n: number, ffb: number): (number, number, number)
+ for i = 0, n - 5 do
+ local o = base + i
+ if valid(b, o) then
+ local fb = frameBytes(b, o, ffb)
+ local fap = fb + padding(b, o)
+ local k = 4
+ while fb == 0 and k < H.MAX_FREE_FORMAT_FRAME_SIZE and i + 2 * k < n - 4 do
+ if compare(b, o, o + k) then
+ local f = k - padding(b, o)
+ local nextfb = f + padding(b, o + k)
+ if not (i + k + nextfb + 4 > n or not compare(b, o, o + k + nextfb)) then
+ fap = k
+ fb = f
+ ffb = f
+ end
+ end
+ k += 1
+ end
+ if (fb ~= 0 and i + fap <= n and matchFrame(b, o, n - i, fb)) or (i == 0 and fap == n) then
+ return i, fap, ffb
+ end
+ ffb = 0
+ end
+ end
+ return n, 0, ffb
+end
+
+return H
diff --git a/src/Formats/audio/mp3/Index.luau b/src/Formats/audio/mp3/Index.luau
new file mode 100644
index 0000000..97ca48f
--- /dev/null
+++ b/src/Formats/audio/mp3/Index.luau
@@ -0,0 +1,194 @@
+--!strict
+--!native
+--!optimize 2
+-- audio/mp3/Index: the frame index of a stream, built once on open. It follows minimp3_ex's mp3dec_load_buf frame by frame
+-- (same sync, resync and Xing / LAME handling), and simulates the layer III bit reservoir from the side info, so
+-- it knows in advance which frames give output and where each one's samples land. That makes the total length
+-- exact and seeking sample-accurate. Never throws.
+local Header = require("@formats/audio/mp3/Header")
+local Core = require("@formats/audio/mp3/Core")
+
+local band, rshift = bit32.band, bit32.rshift
+local ru8 = buffer.readu8
+local min, max = math.min, math.max
+
+local compare, frameBytes, padding, findFrame =
+ Header.compare, Header.frameBytes, Header.padding, Header.findFrame
+
+local Index = {}
+
+Index.FLAG_RESET = 1 -- decoder state is zeroed before this frame (minimp3 re-synced here)
+Index.FLAG_OUTPUT = 2 -- this frame gives samples in a continuous decode
+
+export type Index = {
+ n: number, -- frames
+ off: buffer, -- u32 byte offset per frame
+ size: buffer, -- u16 byte size per frame (header and padding included)
+ flags: buffer, -- u8 FLAG_*
+ out: buffer, -- u32 first output sample (before the encoder delay is cut) per frame
+ main: buffer, -- u16 layer III main data bytes per frame (0 for layers I / II)
+ outTotal: number, -- samples (per channel) of a continuous decode, delay not cut
+ bytes: number, -- audio bytes in indexed frames
+ -- format of the first frame
+ sampleRate: number,
+ channels: number, -- the most channels of any frame
+ layer: number,
+ version: number, -- 1, 2 or 2.5
+ spf: number, -- samples per frame
+ -- Xing / Info / LAME
+ vbrTag: number, -- mp3dec_check_vbrtag result of the first frame (0 = none)
+ tagFrames: number,
+ delay: number,
+ padding: number,
+ skipped: number, -- frames with another sample rate or layer, left out
+}
+
+local function grow(b: buffer, n: number): buffer
+ local nb = buffer.create(n)
+ buffer.copy(nb, 0, b, 0, math.min(buffer.len(b), n))
+ return nb
+end
+
+function Index.build(b: buffer, start: number, stop: number): Index?
+ local cap = 1024
+ local OFF, SIZE, FLAGS, OUT, MAIN = buffer.create(cap * 4), buffer.create(cap * 2), buffer.create(cap), buffer.create(cap * 4), buffer.create(cap * 2)
+ local n = 0
+ local pos = start
+ local prev = -1 -- offset of the last decoded header (dec->header), -1 = none
+ local ffb = 0 -- free format bytes
+ local reserv = 0
+ local outTotal = 0
+ local bytes = 0
+ local first = true
+ local skipped = 0
+ local outCh = 0 -- the most channels of a frame that gives output
+ local hz, nch, layer, spf, version = 0, 0, 0, 0, 0
+ local vbr, tagFrames, delay, pad = 0, 0, 0, 0
+
+ while true do
+ local remaining = stop - pos
+ if remaining <= 0 then
+ break
+ end
+ local fs = 0
+ local reset = false
+ if remaining > 4 and prev >= 0 and compare(b, prev, pos) then
+ fs = frameBytes(b, pos, ffb) + padding(b, pos)
+ if fs ~= remaining and (fs + 4 > remaining or not compare(b, pos, pos + fs)) then
+ fs = 0
+ end
+ end
+ if fs == 0 then
+ reset = true
+ reserv = 0
+ local i
+ i, fs, ffb = findFrame(b, pos, remaining, 0)
+ if fs == 0 or i + fs > remaining then
+ break
+ end
+ pos += i
+ end
+ if fs < 4 or fs > Core.MAX_FRAME then
+ -- cannot happen with a well-formed header, but never index an impossible frame
+ prev = -1
+ pos += max(fs, 1)
+ continue
+ end
+ local h1, h2, h3 = ru8(b, pos + 1), ru8(b, pos + 2), ru8(b, pos + 3)
+ local fLayer = 4 - band(rshift(h1, 1), 3)
+ local fHz = Header.sampleRate(h1, h2)
+ local fCh = if band(h3, 0xC0) == 0xC0 then 1 else 2
+
+ if first then
+ first = false
+ hz, nch, layer, spf = fHz, fCh, fLayer, Header.frameSamples(h1)
+ version = if band(h1, 8) ~= 0 then 1 elseif band(h1, 0x10) ~= 0 then 2 else 2.5
+ if fLayer == 3 then
+ local ret, frames, d, p = Core.vbrTag(b, pos, fs)
+ if ret ~= 0 then
+ vbr, tagFrames, delay, pad = ret, frames, d, p
+ if ret < 0 then
+ delay, pad = 0, 0
+ end
+ -- the tag frame is not audio; the next frame is found again from scratch
+ prev = -1
+ pos += fs
+ continue
+ end
+ end
+ elseif fHz ~= hz or fLayer ~= layer then
+ skipped += 1
+ prev = pos
+ pos += fs
+ continue
+ end
+
+ local output = true
+ local mainBytes = 0
+ local nextPrev = pos
+ if fLayer == 3 then
+ local mdb, p23, mb = Core.probeL3(b, pos, fs)
+ if mdb < 0 then
+ output = false
+ nextPrev = -1 -- mp3dec_init: the next frame re-syncs
+ else
+ mainBytes = mb
+ local have = min(reserv, mdb)
+ output = reserv >= mdb
+ local remains = have + mb - (if output then (p23 + 7) // 8 else 0)
+ reserv = max(0, min(remains, 511))
+ end
+ else
+ output = Core.probeL12(b, pos, fs)
+ if not output then
+ nextPrev = -1
+ end
+ end
+
+ if output and fCh > outCh then
+ outCh = fCh -- mono / stereo switches: the stream is stereo, mono frames are duplicated
+ end
+ if n == cap then
+ cap *= 2
+ OFF, SIZE, FLAGS, OUT, MAIN = grow(OFF, cap * 4), grow(SIZE, cap * 2), grow(FLAGS, cap), grow(OUT, cap * 4), grow(MAIN, cap * 2)
+ end
+ buffer.writeu32(OFF, n * 4, pos)
+ buffer.writeu16(SIZE, n * 2, fs)
+ buffer.writeu8(FLAGS, n, (if reset then Index.FLAG_RESET else 0) + (if output then Index.FLAG_OUTPUT else 0))
+ buffer.writeu32(OUT, n * 4, outTotal)
+ buffer.writeu16(MAIN, n * 2, min(mainBytes, 65535))
+ n += 1
+ bytes += fs
+ if output then
+ outTotal += spf
+ end
+ prev = nextPrev
+ pos += fs
+ end
+
+ if first then
+ return nil
+ end
+ return {
+ n = n,
+ off = OFF,
+ size = SIZE,
+ flags = FLAGS,
+ out = OUT,
+ main = MAIN,
+ outTotal = outTotal,
+ bytes = bytes,
+ sampleRate = hz,
+ channels = if outCh > 0 then outCh else nch,
+ layer = layer,
+ version = version,
+ spf = spf,
+ vbrTag = vbr,
+ tagFrames = tagFrames,
+ delay = delay,
+ padding = pad,
+ skipped = skipped,
+ }
+end
+
+return Index
diff --git a/src/Formats/audio/mp3/Stream.luau b/src/Formats/audio/mp3/Stream.luau
new file mode 100644
index 0000000..4bf0414
--- /dev/null
+++ b/src/Formats/audio/mp3/Stream.luau
@@ -0,0 +1,233 @@
+--!strict
+--!optimize 2
+-- audio/mp3/Stream: the streaming Decoder (Types.Decoder) over a frame index: gapless (LAME delay / padding), exact
+-- length, sample-accurate seeking. From mp3-luau's Mp3.open / Decoder (same author). Never throws.
+local Core = require("@formats/audio/mp3/Core")
+local Index = require("@formats/audio/mp3/Index")
+
+local FLAG_RESET, FLAG_OUTPUT = Index.FLAG_RESET, Index.FLAG_OUTPUT
+local ru8, ru16, ru32 = buffer.readu8, buffer.readu16, buffer.readu32
+local band = bit32.band
+local min, max, floor = math.min, math.max, math.floor
+
+local Stream = {}
+
+local Decoder = {}
+Decoder.__index = Decoder
+
+export type Decoder = typeof(setmetatable(
+ {} :: {
+ sampleRate: number,
+ channels: number,
+ frames: number,
+ duration: number,
+ bitrate: number,
+ tags: { [string]: string },
+ id3: any,
+ layer: number,
+ version: number,
+ vbr: boolean,
+ delay: number,
+ padding: number,
+ mpegFrames: number,
+ _buf: buffer,
+ _idx: any,
+ _st: any,
+ _pcm: buffer,
+ _cur: number,
+ _pcmPos: number,
+ _pcmEnd: number,
+ _minAbs: number,
+ _endAbs: number,
+ _pos: number,
+ },
+ Decoder
+))
+
+-- new(b, idx, tags, id3) -> Decoder over the whole buffer b, with its frame index (Index.build)
+function Stream.new(b: buffer, idx: any, tags: { [string]: string }, id3: any): Decoder
+ local spf, hz, nch = idx.spf, idx.sampleRate, idx.channels
+ -- gapless: minimp3_ex cuts delay samples off the start and caps the length at the Xing / LAME count
+ local delay = 0
+ local total = idx.outTotal
+ if idx.vbrTag > 0 then
+ delay = idx.delay
+ local detected = spf * idx.tagFrames
+ if detected >= delay then
+ detected -= delay
+ end
+ if idx.padding > 0 and detected >= idx.padding then
+ detected -= idx.padding
+ end
+ total = max(0, total - delay)
+ total = min(total, detected)
+ end
+ delay = min(delay, idx.outTotal)
+ local self = setmetatable({
+ sampleRate = hz,
+ channels = nch,
+ frames = total,
+ duration = total / hz,
+ bitrate = if idx.n > 0 then floor(idx.bytes * 8 * hz / (idx.n * spf) / 1000 + 0.5) else 0,
+ tags = tags,
+ id3 = id3,
+ layer = idx.layer,
+ version = idx.version,
+ vbr = idx.vbrTag ~= 0,
+ delay = delay,
+ padding = if idx.vbrTag > 0 then max(0, idx.padding) else 0,
+ mpegFrames = idx.n,
+ _buf = b,
+ _idx = idx,
+ _st = Core.newState(),
+ _pcm = buffer.create(1152 * 2 * 4),
+ _cur = 0,
+ _pcmPos = 0,
+ _pcmEnd = 0,
+ _minAbs = delay,
+ _endAbs = delay + total,
+ _pos = 0,
+ }, Decoder)
+ return self
+end
+
+
+-- decodes frames until one has samples inside [minAbs, endAbs); false at the end
+local function fill(self: Decoder): boolean
+ local idx = self._idx
+ local n = idx.n
+ local spf = idx.spf
+ local st = self._st
+ while self._cur < n do
+ local f = self._cur
+ self._cur = f + 1
+ local flags = ru8(idx.flags, f)
+ if band(flags, FLAG_RESET) ~= 0 then
+ Core.reset(st)
+ end
+ local a = ru32(idx.out, f * 4)
+ if a >= self._endAbs then
+ self._cur = n
+ return false
+ end
+ local got = Core.decodeFrame(st, self._buf, ru32(idx.off, f * 4), ru16(idx.size, f * 2), self._pcm)
+ if got > 0 and band(flags, FLAG_OUTPUT) ~= 0 then
+ if Core.lastChannels < self.channels then
+ Core.upmix(self._pcm, got)
+ end
+ local lo = max(a, self._minAbs)
+ local hi = min(a + spf, self._endAbs)
+ if hi > lo then
+ self._pcmPos = lo - a
+ self._pcmEnd = hi - a
+ return true
+ end
+ end
+ end
+ return false
+end
+
+-- Reads up to maxFrames sample frames: (buffer of interleaved f32, frames read); 0 frames = end of stream.
+-- With out (a buffer of at least maxFrames * channels * 4 bytes) the samples go there and out is returned; a
+-- smaller out is ignored.
+function Decoder.read(self: Decoder, maxFrames: number?, out: buffer?): (buffer, number)
+ local ch = self.channels
+ local want = tonumber(maxFrames) or 4096
+ if want ~= want then
+ want = 0
+ end
+ want = floor(max(0, min(want, self.frames - self._pos)))
+ if out and buffer.len(out) < want * ch * 4 then
+ out = nil -- too small: a new buffer (Types.Decoder: out is reused when big enough)
+ end
+ local dst = out or buffer.create(want * ch * 4)
+ local got = 0
+ local pcm = self._pcm
+ while got < want do
+ if self._pcmPos >= self._pcmEnd then
+ if not fill(self) then
+ break
+ end
+ end
+ local k = min(want - got, self._pcmEnd - self._pcmPos)
+ buffer.copy(dst, got * ch * 4, pcm, self._pcmPos * ch * 4, k * ch * 4)
+ got += k
+ self._pcmPos += k
+ end
+ self._pos += got
+ if not out and got < want then
+ local r = buffer.create(got * ch * 4)
+ buffer.copy(r, 0, dst, 0, got * ch * 4)
+ dst = r
+ end
+ return dst, got
+end
+
+-- Seeks to a time in seconds (clamped to the stream). Sample-accurate: decoding restarts a few frames earlier
+-- (enough to refill the bit reservoir and the filter history) and the output before the target is dropped.
+function Decoder.seek(self: Decoder, seconds: number)
+ local hz = self.sampleRate
+ local target = floor((tonumber(seconds) or 0) * hz + 0.5)
+ target = max(0, min(target, self.frames))
+ self:seekFrame(target)
+end
+
+-- Seeks to a sample frame (0 .. frames).
+function Decoder.seekFrame(self: Decoder, target: number)
+ target = tonumber(target) or 0
+ if target ~= target then
+ target = 0
+ end
+ target = max(0, min(floor(target), self.frames))
+ local idx = self._idx
+ local abs = self.delay + target
+ self._pos = target
+ self._minAbs = abs
+ self._pcmPos, self._pcmEnd = 0, 0
+ Core.reset(self._st)
+ local n = idx.n
+ if abs >= self._endAbs or n == 0 then
+ self._cur = n
+ return
+ end
+ -- last frame starting at or before abs
+ local lo, hi = 0, n - 1
+ while lo < hi do
+ local mid = (lo + hi + 1) // 2
+ if ru32(idx.out, mid * 4) <= abs then
+ lo = mid
+ else
+ hi = mid - 1
+ end
+ end
+ local j = lo
+ -- go back >= 2 frames (layer I needs 2 for the polyphase history), and for layer III until the main data
+ -- before frame j - 1 covers the largest reservoir (511 bytes), stopping at a frame where the decoder resets
+ local need = if idx.layer == 3 then 511 else 0
+ local s, back, acc = j, 0, 0
+ while s > 0 and band(ru8(idx.flags, s), FLAG_RESET) == 0 do
+ if back >= 2 and acc >= need then
+ break
+ end
+ s -= 1
+ back += 1
+ if back >= 2 then
+ acc += ru16(idx.main, s * 2)
+ end
+ end
+ self._cur = s
+end
+
+-- Current position: (seconds, sample frame)
+function Decoder.position(self: Decoder): (number, number)
+ return self._pos / self.sampleRate, self._pos
+end
+
+-- Decodes everything from the current position to the end: (buffer of interleaved f32, frames)
+function Decoder.readAll(self: Decoder): (buffer, number)
+ return self:read(max(0, self.frames - self._pos))
+end
+
+Stream.Decoder = Decoder
+
+return Stream
diff --git a/src/Formats/audio/mp3/Tables.luau b/src/Formats/audio/mp3/Tables.luau
new file mode 100644
index 0000000..40d661d
--- /dev/null
+++ b/src/Formats/audio/mp3/Tables.luau
@@ -0,0 +1,224 @@
+--!strict
+-- audio/mp3/Tables: constant tables of minimp3 (https://github.com/lieff/minimp3, CC0), generated by tools/gen_tables.py.
+-- Every list is flattened row-major and 0-based (t[0] is the first element), like the C arrays.
+local T = {}
+T.halfrate = { [0] = 0,
+ 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 56, 64, 72, 80, 0, 4, 8, 12, 16, 20, 24, 28, 32, 40,
+ 48, 56, 64, 72, 80, 0, 16, 24, 28, 32, 40, 48, 56, 64, 72, 80, 88, 96, 112, 128, 0, 16, 20, 24,
+ 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 0, 16, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128,
+ 160, 192, 0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224,
+}
+T.g_bitalloc_code_tab = { [0] = 0,
+ 17, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0, 17, 18, 3, 19, 4, 5, 6, 7,
+ 8, 9, 10, 11, 12, 13, 16, 0, 17, 18, 3, 19, 4, 5, 16, 0, 17, 18, 16, 0, 17, 18, 19, 4,
+ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 17, 18, 3, 19, 4, 5, 6, 7, 8, 9, 10, 11,
+ 12, 13, 14, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
+}
+T.g_scf_long = { [0] = 6,
+ 6, 6, 6, 6, 6, 8, 10, 12, 14, 16, 20, 24, 28, 32, 38, 46, 52, 60, 68, 58, 54, 0, 12, 12,
+ 12, 12, 12, 12, 16, 20, 24, 28, 32, 40, 48, 56, 64, 76, 90, 2, 2, 2, 2, 2, 0, 6, 6, 6,
+ 6, 6, 6, 8, 10, 12, 14, 16, 20, 24, 28, 32, 38, 46, 52, 60, 68, 58, 54, 0, 6, 6, 6, 6,
+ 6, 6, 8, 10, 12, 14, 16, 18, 22, 26, 32, 38, 46, 54, 62, 70, 76, 36, 0, 6, 6, 6, 6, 6,
+ 6, 8, 10, 12, 14, 16, 20, 24, 28, 32, 38, 46, 52, 60, 68, 58, 54, 0, 4, 4, 4, 4, 4, 4,
+ 6, 6, 8, 8, 10, 12, 16, 20, 24, 28, 34, 42, 50, 54, 76, 158, 0, 4, 4, 4, 4, 4, 4, 6,
+ 6, 6, 8, 10, 12, 16, 18, 22, 28, 34, 40, 46, 54, 54, 192, 0, 4, 4, 4, 4, 4, 4, 6, 6,
+ 8, 10, 12, 16, 20, 24, 30, 38, 46, 56, 68, 84, 102, 26, 0,
+}
+T.g_scf_short = { [0] = 4,
+ 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18,
+ 18, 18, 24, 24, 24, 30, 30, 30, 40, 40, 40, 18, 18, 18, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+ 12, 12, 12, 16, 16, 16, 20, 20, 20, 24, 24, 24, 28, 28, 28, 36, 36, 36, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 26, 26, 26, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, 8, 8,
+ 8, 10, 10, 10, 14, 14, 14, 18, 18, 18, 26, 26, 26, 32, 32, 32, 42, 42, 42, 18, 18, 18, 0, 4,
+ 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18,
+ 18, 18, 24, 24, 24, 32, 32, 32, 44, 44, 44, 12, 12, 12, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4,
+ 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, 24, 24, 30, 30, 30,
+ 40, 40, 40, 18, 18, 18, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 8,
+ 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 22, 22, 22, 30, 30, 30, 56, 56, 56, 0, 4,
+ 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, 10, 10, 10, 12, 12, 12, 14,
+ 14, 14, 16, 16, 16, 20, 20, 20, 26, 26, 26, 66, 66, 66, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4,
+ 4, 4, 4, 6, 6, 6, 8, 8, 8, 12, 12, 12, 16, 16, 16, 20, 20, 20, 26, 26, 26, 34, 34, 34,
+ 42, 42, 42, 12, 12, 12, 0,
+}
+T.g_scf_mixed = { [0] = 6,
+ 6, 6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24,
+ 24, 24, 30, 30, 30, 40, 40, 40, 18, 18, 18, 0, 0, 0, 0, 12, 12, 12, 4, 4, 4, 8, 8, 8,
+ 12, 12, 12, 16, 16, 16, 20, 20, 20, 24, 24, 24, 28, 28, 28, 36, 36, 36, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 26, 26, 26, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 10, 10,
+ 10, 14, 14, 14, 18, 18, 18, 26, 26, 26, 32, 32, 32, 42, 42, 42, 18, 18, 18, 0, 0, 0, 0, 6,
+ 6, 6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24,
+ 24, 24, 32, 32, 32, 44, 44, 44, 12, 12, 12, 0, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6,
+ 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, 24, 24, 30, 30, 30, 40, 40, 40,
+ 18, 18, 18, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 6, 6, 4, 4, 4, 6, 6, 6, 8, 8, 8,
+ 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 22, 22, 22, 30, 30, 30, 56, 56, 56, 0, 0, 4,
+ 4, 4, 4, 4, 4, 6, 6, 4, 4, 4, 6, 6, 6, 6, 6, 6, 10, 10, 10, 12, 12, 12, 14, 14,
+ 14, 16, 16, 16, 20, 20, 20, 26, 26, 26, 66, 66, 66, 0, 0, 4, 4, 4, 4, 4, 4, 6, 6, 4,
+ 4, 4, 6, 6, 6, 8, 8, 8, 12, 12, 12, 16, 16, 16, 20, 20, 20, 26, 26, 26, 34, 34, 34, 42,
+ 42, 42, 12, 12, 12, 0, 0,
+}
+T.g_expfrac = { [0] = 9.31322575e-10,
+ 7.83145814e-10, 6.58544508e-10, 5.53767716e-10,
+}
+T.g_scf_partitions = { [0] = 6,
+ 5, 5, 5, 6, 5, 5, 5, 6, 5, 7, 3, 11, 10, 0, 0, 7, 7, 7, 0, 6, 6, 6, 3, 8,
+ 8, 5, 0, 8, 9, 6, 12, 6, 9, 9, 9, 6, 9, 12, 6, 15, 18, 0, 0, 6, 15, 12, 0, 6,
+ 12, 9, 6, 6, 18, 9, 0, 9, 9, 6, 12, 9, 9, 9, 9, 9, 9, 12, 6, 18, 18, 0, 0, 12,
+ 12, 12, 0, 12, 9, 9, 6, 15, 12, 9, 0,
+}
+T.g_scfc_decode = { [0] = 0,
+ 1, 2, 3, 12, 5, 6, 7, 9, 10, 11, 13, 14, 15, 18, 19,
+}
+T.g_mod = { [0] = 5,
+ 5, 4, 4, 5, 5, 4, 1, 4, 3, 1, 1, 5, 6, 6, 1, 4, 4, 4, 1, 4, 3, 1, 1,
+}
+T.g_preamp = { [0] = 1,
+ 1, 1, 1, 2, 2, 3, 3, 3, 2,
+}
+T.g_pow43 = { [0] = 0,
+ -1, -2.519842, -4.326749, -6.349604, -8.549880, -10.902724, -13.390518, -16.000000, -18.720754, -21.544347, -24.463781, -27.473142, -30.567351, -33.741992, -36.993181, 0, 1, 2.519842, 4.326749, 6.349604, 8.549880, 10.902724, 13.390518, 16.000000,
+ 18.720754, 21.544347, 24.463781, 27.473142, 30.567351, 33.741992, 36.993181, 40.317474, 43.711787, 47.173345, 50.699631, 54.288352, 57.937408, 61.644865, 65.408941, 69.227979, 73.100443, 77.024898, 81.000000, 85.024491, 89.097188, 93.216975, 97.382800, 101.593667,
+ 105.848633, 110.146801, 114.487321, 118.869381, 123.292209, 127.755065, 132.257246, 136.798076, 141.376907, 145.993119, 150.646117, 155.335327, 160.060199, 164.820202, 169.614826, 174.443577, 179.305980, 184.201575, 189.129918, 194.090580, 199.083145, 204.107210, 209.162385, 214.248292,
+ 219.364564, 224.510845, 229.686789, 234.892058, 240.126328, 245.389280, 250.680604, 256.000000, 261.347174, 266.721841, 272.123723, 277.552547, 283.008049, 288.489971, 293.998060, 299.532071, 305.091761, 310.676898, 316.287249, 321.922592, 327.582707, 333.267377, 338.976394, 344.709550,
+ 350.466646, 356.247482, 362.051866, 367.879608, 373.730522, 379.604427, 385.501143, 391.420496, 397.362314, 403.326427, 409.312672, 415.320884, 421.350905, 427.402579, 433.475750, 439.570269, 445.685987, 451.822757, 457.980436, 464.158883, 470.357960, 476.577530, 482.817459, 489.077615,
+ 495.357868, 501.658090, 507.978156, 514.317941, 520.677324, 527.056184, 533.454404, 539.871867, 546.308458, 552.764065, 559.238575, 565.731879, 572.243870, 578.774440, 585.323483, 591.890898, 598.476581, 605.080431, 611.702349, 618.342238, 625.000000, 631.675540, 638.368763, 645.079578,
+}
+T.tabs = { [0] = 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 785, 785, 785, 785, 784, 784, 784, 784, 513, 513, 513, 513, 513, 513, 513, 513, 256,
+ 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, -255, 1313, 1298, 1282, 785, 785, 785, 785, 784,
+ 784, 784, 784, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 290,
+ 288, -255, 1313, 1298, 1282, 769, 769, 769, 769, 529, 529, 529, 529, 529, 529, 529, 529, 528, 528, 528, 528, 528, 528, 528,
+ 528, 512, 512, 512, 512, 512, 512, 512, 512, 290, 288, -253, -318, -351, -367, 785, 785, 785, 785, 784, 784, 784, 784, 769,
+ 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 819, 818, 547, 547, 275,
+ 275, 275, 275, 561, 560, 515, 546, 289, 274, 288, 258, -254, -287, 1329, 1299, 1314, 1312, 1057, 1057, 1042, 1042, 1026, 1026, 784,
+ 784, 784, 784, 529, 529, 529, 529, 529, 529, 529, 529, 769, 769, 769, 769, 768, 768, 768, 768, 563, 560, 306, 306, 291,
+ 259, -252, -413, -477, -542, 1298, -575, 1041, 1041, 784, 784, 784, 784, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256,
+ 256, 256, 256, 256, 256, 256, 256, 256, 256, -383, -399, 1107, 1092, 1106, 1061, 849, 849, 789, 789, 1104, 1091, 773, 773, 1076,
+ 1075, 341, 340, 325, 309, 834, 804, 577, 577, 532, 532, 516, 516, 832, 818, 803, 816, 561, 561, 531, 531, 515, 546, 289,
+ 289, 288, 258, -252, -429, -493, -559, 1057, 1057, 1042, 1042, 529, 529, 529, 529, 529, 529, 529, 529, 784, 784, 784, 784, 769,
+ 769, 769, 769, 512, 512, 512, 512, 512, 512, 512, 512, -382, 1077, -415, 1106, 1061, 1104, 849, 849, 789, 789, 1091, 1076, 1029,
+ 1075, 834, 834, 597, 581, 340, 340, 339, 324, 804, 833, 532, 532, 832, 772, 818, 803, 817, 787, 816, 771, 290, 290, 290,
+ 290, 288, 258, -253, -349, -414, -447, -463, 1329, 1299, -479, 1314, 1312, 1057, 1057, 1042, 1042, 1026, 1026, 785, 785, 785, 785, 784,
+ 784, 784, 784, 769, 769, 769, 769, 768, 768, 768, 768, -319, 851, 821, -335, 836, 850, 805, 849, 341, 340, 325, 336, 533,
+ 533, 579, 579, 564, 564, 773, 832, 578, 548, 563, 516, 321, 276, 306, 291, 304, 259, -251, -572, -733, -830, -863, -879, 1041,
+ 1041, 784, 784, 784, 784, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256,
+ 256, -511, -527, -543, 1396, 1351, 1381, 1366, 1395, 1335, 1380, -559, 1334, 1138, 1138, 1063, 1063, 1350, 1392, 1031, 1031, 1062, 1062, 1364,
+ 1363, 1120, 1120, 1333, 1348, 881, 881, 881, 881, 375, 374, 359, 373, 343, 358, 341, 325, 791, 791, 1123, 1122, -703, 1105, 1045,
+ -719, 865, 865, 790, 790, 774, 774, 1104, 1029, 338, 293, 323, 308, -799, -815, 833, 788, 772, 818, 803, 816, 322, 292, 307,
+ 320, 561, 531, 515, 546, 289, 274, 288, 258, -251, -525, -605, -685, -765, -831, -846, 1298, 1057, 1057, 1312, 1282, 785, 785, 785,
+ 785, 784, 784, 784, 784, 769, 769, 769, 769, 512, 512, 512, 512, 512, 512, 512, 512, 1399, 1398, 1383, 1367, 1382, 1396, 1351,
+ -511, 1381, 1366, 1139, 1139, 1079, 1079, 1124, 1124, 1364, 1349, 1363, 1333, 882, 882, 882, 882, 807, 807, 807, 807, 1094, 1094, 1136,
+ 1136, 373, 341, 535, 535, 881, 775, 867, 822, 774, -591, 324, 338, -671, 849, 550, 550, 866, 864, 609, 609, 293, 336, 534,
+ 534, 789, 835, 773, -751, 834, 804, 308, 307, 833, 788, 832, 772, 562, 562, 547, 547, 305, 275, 560, 515, 290, 290, -252,
+ -397, -477, -557, -622, -653, -719, -735, -750, 1329, 1299, 1314, 1057, 1057, 1042, 1042, 1312, 1282, 1024, 1024, 785, 785, 785, 785, 784,
+ 784, 784, 784, 769, 769, 769, 769, -383, 1127, 1141, 1111, 1126, 1140, 1095, 1110, 869, 869, 883, 883, 1079, 1109, 882, 882, 375,
+ 374, 807, 868, 838, 881, 791, -463, 867, 822, 368, 263, 852, 837, 836, -543, 610, 610, 550, 550, 352, 336, 534, 534, 865,
+ 774, 851, 821, 850, 805, 593, 533, 579, 564, 773, 832, 578, 578, 548, 548, 577, 577, 307, 276, 306, 291, 516, 560, 259,
+ 259, -250, -2107, -2507, -2764, -2909, -2974, -3007, -3023, 1041, 1041, 1040, 1040, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256,
+ 256, 256, 256, 256, 256, 256, 256, 256, 256, -767, -1052, -1213, -1277, -1358, -1405, -1469, -1535, -1550, -1582, -1614, -1647, -1662, -1694, -1726,
+ -1759, -1774, -1807, -1822, -1854, -1886, 1565, -1919, -1935, -1951, -1967, 1731, 1730, 1580, 1717, -1983, 1729, 1564, -1999, 1548, -2015, -2031, 1715, 1595,
+ -2047, 1714, -2063, 1610, -2079, 1609, -2095, 1323, 1323, 1457, 1457, 1307, 1307, 1712, 1547, 1641, 1700, 1699, 1594, 1685, 1625, 1442, 1442, 1322,
+ 1322, -780, -973, -910, 1279, 1278, 1277, 1262, 1276, 1261, 1275, 1215, 1260, 1229, -959, 974, 974, 989, 989, -943, 735, 478, 478, 495,
+ 463, 506, 414, -1039, 1003, 958, 1017, 927, 942, 987, 957, 431, 476, 1272, 1167, 1228, -1183, 1256, -1199, 895, 895, 941, 941, 1242,
+ 1227, 1212, 1135, 1014, 1014, 490, 489, 503, 487, 910, 1013, 985, 925, 863, 894, 970, 955, 1012, 847, -1343, 831, 755, 755, 984,
+ 909, 428, 366, 754, 559, -1391, 752, 486, 457, 924, 997, 698, 698, 983, 893, 740, 740, 908, 877, 739, 739, 667, 667, 953,
+ 938, 497, 287, 271, 271, 683, 606, 590, 712, 726, 574, 302, 302, 738, 736, 481, 286, 526, 725, 605, 711, 636, 724, 696,
+ 651, 589, 681, 666, 710, 364, 467, 573, 695, 466, 466, 301, 465, 379, 379, 709, 604, 665, 679, 316, 316, 634, 633, 436,
+ 436, 464, 269, 424, 394, 452, 332, 438, 363, 347, 408, 393, 448, 331, 422, 362, 407, 392, 421, 346, 406, 391, 376, 375,
+ 359, 1441, 1306, -2367, 1290, -2383, 1337, -2399, -2415, 1426, 1321, -2431, 1411, 1336, -2447, -2463, -2479, 1169, 1169, 1049, 1049, 1424, 1289, 1412,
+ 1352, 1319, -2495, 1154, 1154, 1064, 1064, 1153, 1153, 416, 390, 360, 404, 403, 389, 344, 374, 373, 343, 358, 372, 327, 357, 342,
+ 311, 356, 326, 1395, 1394, 1137, 1137, 1047, 1047, 1365, 1392, 1287, 1379, 1334, 1364, 1349, 1378, 1318, 1363, 792, 792, 792, 792, 1152,
+ 1152, 1032, 1032, 1121, 1121, 1046, 1046, 1120, 1120, 1030, 1030, -2895, 1106, 1061, 1104, 849, 849, 789, 789, 1091, 1076, 1029, 1090, 1060,
+ 1075, 833, 833, 309, 324, 532, 532, 832, 772, 818, 803, 561, 561, 531, 560, 515, 546, 289, 274, 288, 258, -250, -1179, -1579,
+ -1836, -1996, -2124, -2253, -2333, -2413, -2477, -2542, -2574, -2607, -2622, -2655, 1314, 1313, 1298, 1312, 1282, 785, 785, 785, 785, 1040, 1040, 1025,
+ 1025, 768, 768, 768, 768, -766, -798, -830, -862, -895, -911, -927, -943, -959, -975, -991, -1007, -1023, -1039, -1055, -1070, 1724, 1647, -1103,
+ -1119, 1631, 1767, 1662, 1738, 1708, 1723, -1135, 1780, 1615, 1779, 1599, 1677, 1646, 1778, 1583, -1151, 1777, 1567, 1737, 1692, 1765, 1722, 1707,
+ 1630, 1751, 1661, 1764, 1614, 1736, 1676, 1763, 1750, 1645, 1598, 1721, 1691, 1762, 1706, 1582, 1761, 1566, -1167, 1749, 1629, 767, 766, 751,
+ 765, 494, 494, 735, 764, 719, 749, 734, 763, 447, 447, 748, 718, 477, 506, 431, 491, 446, 476, 461, 505, 415, 430, 475,
+ 445, 504, 399, 460, 489, 414, 503, 383, 474, 429, 459, 502, 502, 746, 752, 488, 398, 501, 473, 413, 472, 486, 271, 480,
+ 270, -1439, -1455, 1357, -1471, -1487, -1503, 1341, 1325, -1519, 1489, 1463, 1403, 1309, -1535, 1372, 1448, 1418, 1476, 1356, 1462, 1387, -1551, 1475,
+ 1340, 1447, 1402, 1386, -1567, 1068, 1068, 1474, 1461, 455, 380, 468, 440, 395, 425, 410, 454, 364, 467, 466, 464, 453, 269, 409,
+ 448, 268, 432, 1371, 1473, 1432, 1417, 1308, 1460, 1355, 1446, 1459, 1431, 1083, 1083, 1401, 1416, 1458, 1445, 1067, 1067, 1370, 1457, 1051,
+ 1051, 1291, 1430, 1385, 1444, 1354, 1415, 1400, 1443, 1082, 1082, 1173, 1113, 1186, 1066, 1185, 1050, -1967, 1158, 1128, 1172, 1097, 1171, 1081,
+ -1983, 1157, 1112, 416, 266, 375, 400, 1170, 1142, 1127, 1065, 793, 793, 1169, 1033, 1156, 1096, 1141, 1111, 1155, 1080, 1126, 1140, 898,
+ 898, 808, 808, 897, 897, 792, 792, 1095, 1152, 1032, 1125, 1110, 1139, 1079, 1124, 882, 807, 838, 881, 853, 791, -2319, 867, 368,
+ 263, 822, 852, 837, 866, 806, 865, -2399, 851, 352, 262, 534, 534, 821, 836, 594, 594, 549, 549, 593, 593, 533, 533, 848,
+ 773, 579, 579, 564, 578, 548, 563, 276, 276, 577, 576, 306, 291, 516, 560, 305, 305, 275, 259, -251, -892, -2058, -2620, -2828,
+ -2957, -3023, -3039, 1041, 1041, 1040, 1040, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256,
+ 256, 256, 256, -511, -527, -543, -559, 1530, -575, -591, 1528, 1527, 1407, 1526, 1391, 1023, 1023, 1023, 1023, 1525, 1375, 1268, 1268, 1103,
+ 1103, 1087, 1087, 1039, 1039, 1523, -604, 815, 815, 815, 815, 510, 495, 509, 479, 508, 463, 507, 447, 431, 505, 415, 399, -734,
+ -782, 1262, -815, 1259, 1244, -831, 1258, 1228, -847, -863, 1196, -879, 1253, 987, 987, 748, -767, 493, 493, 462, 477, 414, 414, 686,
+ 669, 478, 446, 461, 445, 474, 429, 487, 458, 412, 471, 1266, 1264, 1009, 1009, 799, 799, -1019, -1276, -1452, -1581, -1677, -1757, -1821,
+ -1886, -1933, -1997, 1257, 1257, 1483, 1468, 1512, 1422, 1497, 1406, 1467, 1496, 1421, 1510, 1134, 1134, 1225, 1225, 1466, 1451, 1374, 1405, 1252,
+ 1252, 1358, 1480, 1164, 1164, 1251, 1251, 1238, 1238, 1389, 1465, -1407, 1054, 1101, -1423, 1207, -1439, 830, 830, 1248, 1038, 1237, 1117, 1223,
+ 1148, 1236, 1208, 411, 426, 395, 410, 379, 269, 1193, 1222, 1132, 1235, 1221, 1116, 976, 976, 1192, 1162, 1177, 1220, 1131, 1191, 963,
+ 963, -1647, 961, 780, -1663, 558, 558, 994, 993, 437, 408, 393, 407, 829, 978, 813, 797, 947, -1743, 721, 721, 377, 392, 844,
+ 950, 828, 890, 706, 706, 812, 859, 796, 960, 948, 843, 934, 874, 571, 571, -1919, 690, 555, 689, 421, 346, 539, 539, 944,
+ 779, 918, 873, 932, 842, 903, 888, 570, 570, 931, 917, 674, 674, -2575, 1562, -2591, 1609, -2607, 1654, 1322, 1322, 1441, 1441, 1696,
+ 1546, 1683, 1593, 1669, 1624, 1426, 1426, 1321, 1321, 1639, 1680, 1425, 1425, 1305, 1305, 1545, 1668, 1608, 1623, 1667, 1592, 1638, 1666, 1320,
+ 1320, 1652, 1607, 1409, 1409, 1304, 1304, 1288, 1288, 1664, 1637, 1395, 1395, 1335, 1335, 1622, 1636, 1394, 1394, 1319, 1319, 1606, 1621, 1392,
+ 1392, 1137, 1137, 1137, 1137, 345, 390, 360, 375, 404, 373, 1047, -2751, -2767, -2783, 1062, 1121, 1046, -2799, 1077, -2815, 1106, 1061, 789,
+ 789, 1105, 1104, 263, 355, 310, 340, 325, 354, 352, 262, 339, 324, 1091, 1076, 1029, 1090, 1060, 1075, 833, 833, 788, 788, 1088,
+ 1028, 818, 818, 803, 803, 561, 561, 531, 531, 816, 771, 546, 546, 289, 274, 288, 258, -253, -317, -381, -446, -478, -509, 1279,
+ 1279, -811, -1179, -1451, -1756, -1900, -2028, -2189, -2253, -2333, -2414, -2445, -2511, -2526, 1313, 1298, -2559, 1041, 1041, 1040, 1040, 1025, 1025, 1024,
+ 1024, 1022, 1007, 1021, 991, 1020, 975, 1019, 959, 687, 687, 1018, 1017, 671, 671, 655, 655, 1016, 1015, 639, 639, 758, 758, 623,
+ 623, 757, 607, 756, 591, 755, 575, 754, 559, 543, 543, 1009, 783, -575, -621, -685, -749, 496, -590, 750, 749, 734, 748, 974,
+ 989, 1003, 958, 988, 973, 1002, 942, 987, 957, 972, 1001, 926, 986, 941, 971, 956, 1000, 910, 985, 925, 999, 894, 970, -1071,
+ -1087, -1102, 1390, -1135, 1436, 1509, 1451, 1374, -1151, 1405, 1358, 1480, 1420, -1167, 1507, 1494, 1389, 1342, 1465, 1435, 1450, 1326, 1505, 1310,
+ 1493, 1373, 1479, 1404, 1492, 1464, 1419, 428, 443, 472, 397, 736, 526, 464, 464, 486, 457, 442, 471, 484, 482, 1357, 1449, 1434,
+ 1478, 1388, 1491, 1341, 1490, 1325, 1489, 1463, 1403, 1309, 1477, 1372, 1448, 1418, 1433, 1476, 1356, 1462, 1387, -1439, 1475, 1340, 1447, 1402,
+ 1474, 1324, 1461, 1371, 1473, 269, 448, 1432, 1417, 1308, 1460, -1711, 1459, -1727, 1441, 1099, 1099, 1446, 1386, 1431, 1401, -1743, 1289, 1083,
+ 1083, 1160, 1160, 1458, 1445, 1067, 1067, 1370, 1457, 1307, 1430, 1129, 1129, 1098, 1098, 268, 432, 267, 416, 266, 400, -1887, 1144, 1187,
+ 1082, 1173, 1113, 1186, 1066, 1050, 1158, 1128, 1143, 1172, 1097, 1171, 1081, 420, 391, 1157, 1112, 1170, 1142, 1127, 1065, 1169, 1049, 1156,
+ 1096, 1141, 1111, 1155, 1080, 1126, 1154, 1064, 1153, 1140, 1095, 1048, -2159, 1125, 1110, 1137, -2175, 823, 823, 1139, 1138, 807, 807, 384,
+ 264, 368, 263, 868, 838, 853, 791, 867, 822, 852, 837, 866, 806, 865, 790, -2319, 851, 821, 836, 352, 262, 850, 805, 849,
+ -2399, 533, 533, 835, 820, 336, 261, 578, 548, 563, 577, 532, 532, 832, 772, 562, 562, 547, 547, 305, 275, 560, 515, 290,
+ 290, 288, 258,
+}
+T.tab32 = { [0] = 130,
+ 162, 193, 209, 44, 28, 76, 140, 9, 9, 9, 9, 9, 9, 9, 9, 190, 254, 222, 238, 126, 94, 157, 157, 109,
+ 61, 173, 205,
+}
+T.tab33 = { [0] = 252,
+ 236, 220, 204, 188, 172, 156, 140, 124, 108, 92, 76, 60, 44, 28, 12,
+}
+T.tabindex = { [0] = 0,
+ 32, 64, 98, 0, 132, 180, 218, 292, 364, 426, 538, 648, 746, 0, 1126, 1460, 1460, 1460, 1460, 1460, 1460, 1460, 1460, 1842,
+ 1842, 1842, 1842, 1842, 1842, 1842, 1842,
+}
+T.g_linbits = { [0] = 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 8, 10, 13, 4,
+ 5, 6, 7, 8, 9, 11, 13,
+}
+T.g_pan = { [0] = 0,
+ 1, 0.21132487, 0.78867513, 0.36602540, 0.63397460, 0.5, 0.5, 0.63397460, 0.36602540, 0.78867513, 0.21132487, 1, 0,
+}
+T.g_aa = { [0] = 0.85749293,
+ 0.88174200, 0.94962865, 0.98331459, 0.99551782, 0.99916056, 0.99989920, 0.99999316, 0.51449576, 0.47173197, 0.31337745, 0.18191320, 0.09457419, 0.04096558, 0.01419856, 0.00369997,
+}
+T.g_twid9 = { [0] = 0.73727734,
+ 0.79335334, 0.84339145, 0.88701083, 0.92387953, 0.95371695, 0.97629601, 0.99144486, 0.99904822, 0.67559021, 0.60876143, 0.53729961, 0.46174861, 0.38268343, 0.30070580, 0.21643961, 0.13052619, 0.04361938,
+}
+T.g_twid3 = { [0] = 0.79335334,
+ 0.92387953, 0.99144486, 0.60876143, 0.38268343, 0.13052619,
+}
+T.g_mdct_window = { [0] = 0.99904822,
+ 0.99144486, 0.97629601, 0.95371695, 0.92387953, 0.88701083, 0.84339145, 0.79335334, 0.73727734, 0.04361938, 0.13052619, 0.21643961, 0.30070580, 0.38268343, 0.46174861, 0.53729961, 0.60876143, 0.67559021, 1, 1, 1, 1, 1, 1, 0.99144486,
+ 0.92387953, 0.79335334, 0, 0, 0, 0, 0, 0, 0.13052619, 0.38268343, 0.60876143,
+}
+T.g_sec = { [0] = 10.19000816,
+ 0.50060302, 0.50241929, 3.40760851, 0.50547093, 0.52249861, 2.05778098, 0.51544732, 0.56694406, 1.48416460, 0.53104258, 0.64682180, 1.16943991, 0.55310392, 0.78815460, 0.97256821, 0.58293498, 1.06067765, 0.83934963, 0.62250412, 1.72244716, 0.74453628, 0.67480832, 5.10114861,
+}
+T.g_win = { [0] = -1,
+ 26, -31, 208, 218, 401, -519, 2063, 2000, 4788, -5517, 7134, 5959, 35640, -39336, 74992, -1, 24, -35, 202, 222, 347, -581, 2080, 1952,
+ 4425, -5879, 7640, 5288, 33791, -41176, 74856, -1, 21, -38, 196, 225, 294, -645, 2087, 1893, 4063, -6237, 8092, 4561, 31947, -43006, 74630, -1,
+ 19, -41, 190, 227, 244, -711, 2085, 1822, 3705, -6589, 8492, 3776, 30112, -44821, 74313, -1, 17, -45, 183, 228, 197, -779, 2075, 1739,
+ 3351, -6935, 8840, 2935, 28289, -46617, 73908, -1, 16, -49, 176, 228, 153, -848, 2057, 1644, 3004, -7271, 9139, 2037, 26482, -48390, 73415, -2,
+ 14, -53, 169, 227, 111, -919, 2032, 1535, 2663, -7597, 9389, 1082, 24694, -50137, 72835, -2, 13, -58, 161, 224, 72, -991, 2001, 1414,
+ 2330, -7910, 9592, 70, 22929, -51853, 72169, -2, 11, -63, 154, 221, 36, -1064, 1962, 1280, 2006, -8209, 9750, -998, 21189, -53534, 71420, -2,
+ 10, -68, 147, 215, 2, -1137, 1919, 1131, 1692, -8491, 9863, -2122, 19478, -55178, 70590, -3, 9, -73, 139, 208, -29, -1210, 1870, 970,
+ 1388, -8755, 9935, -3300, 17799, -56778, 69679, -3, 8, -79, 132, 200, -57, -1283, 1817, 794, 1095, -8998, 9966, -4533, 16155, -58333, 68692, -4,
+ 7, -85, 125, 189, -83, -1356, 1759, 605, 814, -9219, 9959, -5818, 14548, -59838, 67629, -4, 7, -91, 117, 177, -106, -1428, 1698, 402,
+ 545, -9416, 9916, -7154, 12980, -61289, 66494, -5, 6, -97, 111, 163, -127, -1498, 1634, 185, 288, -9585, 9838, -8540, 11455, -62684, 65290,
+}
+return T
diff --git a/src/Formats/audio/mp3/Tags.luau b/src/Formats/audio/mp3/Tags.luau
new file mode 100644
index 0000000..329c297
--- /dev/null
+++ b/src/Formats/audio/mp3/Tags.luau
@@ -0,0 +1,315 @@
+--!strict
+--!optimize 2
+-- audio/mp3/Tags: ID3 tags: ID3v2.2 / 2.3 / 2.4 at the start (text frames, COMM, unsynchronisation, extended header) and ID3v1 /
+-- ID3v1.1 at the end; APEv2 tags are only skipped. Also finds the byte range that holds the audio, the same way
+-- minimp3_ex does (mp3dec_skip_id3). Text is returned as UTF-8. Never throws: malformed tags are cut short.
+local band, bor, lshift = bit32.band, bit32.bor, bit32.lshift
+local ru8 = buffer.readu8
+
+local Tags = {}
+
+-- ID3v1 genres 0..147 (the original 80 + the Winamp extensions)
+local GENRES = {
+ [0] = "Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", "Grunge", "Hip-Hop", "Jazz", "Metal",
+ "New Age", "Oldies", "Other", "Pop", "R&B", "Rap", "Reggae", "Rock", "Techno", "Industrial", "Alternative",
+ "Ska", "Death Metal", "Pranks", "Soundtrack", "Euro-Techno", "Ambient", "Trip-Hop", "Vocal", "Jazz+Funk",
+ "Fusion", "Trance", "Classical", "Instrumental", "Acid", "House", "Game", "Sound Clip", "Gospel", "Noise",
+ "AlternRock", "Bass", "Soul", "Punk", "Space", "Meditative", "Instrumental Pop", "Instrumental Rock", "Ethnic",
+ "Gothic", "Darkwave", "Techno-Industrial", "Electronic", "Pop-Folk", "Eurodance", "Dream", "Southern Rock",
+ "Comedy", "Cult", "Gangsta", "Top 40", "Christian Rap", "Pop/Funk", "Jungle", "Native American", "Cabaret",
+ "New Wave", "Psychadelic", "Rave", "Showtunes", "Trailer", "Lo-Fi", "Tribal", "Acid Punk", "Acid Jazz", "Polka",
+ "Retro", "Musical", "Rock & Roll", "Hard Rock", "Folk", "Folk-Rock", "National Folk", "Swing", "Fast Fusion",
+ "Bebob", "Latin", "Revival", "Celtic", "Bluegrass", "Avantgarde", "Gothic Rock", "Progressive Rock",
+ "Psychedelic Rock", "Symphonic Rock", "Slow Rock", "Big Band", "Chorus", "Easy Listening", "Acoustic", "Humour",
+ "Speech", "Chanson", "Opera", "Chamber Music", "Sonata", "Symphony", "Booty Bass", "Primus", "Porn Groove",
+ "Satire", "Slow Jam", "Club", "Tango", "Samba", "Folklore", "Ballad", "Power Ballad", "Rhythmic Soul",
+ "Freestyle", "Duet", "Punk Rock", "Drum Solo", "A capella", "Euro-House", "Dance Hall", "Goa", "Drum & Bass",
+ "Club-House", "Hardcore", "Terror", "Indie", "BritPop", "Negerpunk", "Polsk Punk", "Beat",
+ "Christian Gangsta Rap", "Heavy Metal", "Black Metal", "Crossover", "Contemporary Christian", "Christian Rock",
+ "Merengue", "Salsa", "Thrash Metal", "Anime", "JPop", "Synthpop",
+}
+Tags.GENRES = GENRES
+
+-- frame id -> field name (v2.3/2.4 ids and their v2.2 equivalents)
+local FIELDS = {
+ TIT2 = "title", TT2 = "title",
+ TPE1 = "artist", TP1 = "artist",
+ TALB = "album", TAL = "album",
+ TPE2 = "albumArtist", TP2 = "albumArtist",
+ TYER = "year", TYE = "year", TDRC = "year",
+ TRCK = "track", TRK = "track",
+ TPOS = "disc", TPA = "disc",
+ TCON = "genre", TCO = "genre",
+ TCOM = "composer", TCM = "composer",
+ COMM = "comment", COM = "comment",
+}
+
+local function utf8char(cp: number): string
+ if cp < 0 or cp > 0x10FFFF or (cp >= 0xD800 and cp <= 0xDFFF) then
+ cp = 0xFFFD
+ end
+ return utf8.char(cp)
+end
+
+-- bytes [i, j) of b, decoded from ID3 text encoding enc (0 latin-1, 1 UTF-16 + BOM, 2 UTF-16BE, 3 UTF-8)
+local function decodeText(b: buffer, i: number, j: number, enc: number): string
+ local out = {}
+ if enc == 1 or enc == 2 then
+ local le = false
+ if enc == 1 and j - i >= 2 then
+ local b0, b1 = ru8(b, i), ru8(b, i + 1)
+ if b0 == 0xFF and b1 == 0xFE then
+ le = true
+ i += 2
+ elseif b0 == 0xFE and b1 == 0xFF then
+ i += 2
+ else
+ le = true -- no BOM: assume little-endian (what most taggers write)
+ end
+ end
+ local pending = 0
+ while i + 1 < j do
+ local u = if le then bor(ru8(b, i), lshift(ru8(b, i + 1), 8)) else bor(lshift(ru8(b, i), 8), ru8(b, i + 1))
+ i += 2
+ if u >= 0xD800 and u <= 0xDBFF then
+ pending = u
+ else
+ if u >= 0xDC00 and u <= 0xDFFF and pending ~= 0 then
+ u = 0x10000 + lshift(pending - 0xD800, 10) + (u - 0xDC00)
+ end
+ pending = 0
+ table.insert(out, if u == 0 then "\0" else utf8char(u))
+ end
+ end
+ elseif enc == 3 then
+ local s = buffer.readstring(b, i, j - i)
+ if utf8.len(s) then
+ return s
+ end
+ enc = 0 -- invalid UTF-8: fall back to latin-1
+ end
+ if enc == 0 then
+ for k = i, j - 1 do
+ local c = ru8(b, k)
+ table.insert(out, if c < 0x80 then string.char(c) else utf8char(c))
+ end
+ end
+ return table.concat(out)
+end
+
+-- trim trailing NULs / spaces, join multi-value NUL separators with " / "
+local function clean(s: string): string
+ s = string.gsub(s, "[%z%s]+$", "")
+ s = string.gsub(s, "%z+", " / ")
+ return s
+end
+
+-- "(17)", "(17)Rock", "17" -> "Rock"
+local function genreName(s: string): string
+ local n = tonumber(string.match(s, "^%((%d+)%)$") or string.match(s, "^(%d+)$"))
+ if n and GENRES[n] then
+ return GENRES[n]
+ end
+ local rest = string.match(s, "^%(%d+%)(.+)$")
+ return rest or s
+end
+
+local function syncsafe(b: buffer, o: number): number
+ return bor(lshift(band(ru8(b, o), 0x7F), 21), lshift(band(ru8(b, o + 1), 0x7F), 14), lshift(band(ru8(b, o + 2), 0x7F), 7), band(ru8(b, o + 3), 0x7F))
+end
+
+local function be32(b: buffer, o: number): number
+ return bor(lshift(ru8(b, o), 24), lshift(ru8(b, o + 1), 16), lshift(ru8(b, o + 2), 8), ru8(b, o + 3))
+end
+
+-- undo unsynchronisation (FF 00 -> FF) of b[i, j) into a new buffer
+local function deunsync(b: buffer, i: number, j: number): buffer
+ local out = buffer.create(math.max(0, j - i))
+ local n = 0
+ local k = i
+ while k < j do
+ local c = ru8(b, k)
+ buffer.writeu8(out, n, c)
+ n += 1
+ k += if c == 0xFF and k + 1 < j and ru8(b, k + 1) == 0 then 2 else 1
+ end
+ local r = buffer.create(n)
+ buffer.copy(r, 0, out, 0, n)
+ return r
+end
+
+-- minimp3's ID3v2 detection: total tag size (header + body + footer) or 0
+function Tags.id3v2Size(b: buffer, o: number, len: number): number
+ if len - o < 10 or buffer.readstring(b, o, 3) ~= "ID3" then
+ return 0
+ end
+ if band(ru8(b, o + 5), 15) ~= 0 then
+ return 0
+ end
+ for k = 6, 9 do
+ if band(ru8(b, o + k), 0x80) ~= 0 then
+ return 0
+ end
+ end
+ local size = syncsafe(b, o + 6) + 10
+ if band(ru8(b, o + 5), 16) ~= 0 then
+ size += 10
+ end
+ return size
+end
+
+local function setField(tags: any, id: string, text: string)
+ tags.raw[id] = text
+ local f = FIELDS[id]
+ if f and tags[f] == nil and text ~= "" then
+ tags[f] = if f == "genre" then genreName(text) else text
+ end
+end
+
+-- parse an ID3v2 tag at b[o ..] (o .. o + size within the buffer) into tags
+local function parseV2(b: buffer, o: number, size: number, tags: any)
+ local ver = ru8(b, o + 3)
+ local flags = ru8(b, o + 5)
+ if ver < 2 or ver > 4 then
+ return
+ end
+ tags.id3v2 = "2." .. ver
+ local bodyEnd = math.min(o + 10 + syncsafe(b, o + 6), buffer.len(b))
+ local body = b
+ local p, e = o + 10, bodyEnd
+ if band(flags, 0x80) ~= 0 and ver < 4 then
+ body = deunsync(b, p, e)
+ p, e = 0, buffer.len(body)
+ end
+ if band(flags, 0x40) ~= 0 and ver >= 3 and p + 4 <= e then
+ -- extended header: v2.3 size excludes its own 4 bytes, v2.4 includes them (syncsafe)
+ p += if ver == 3 then be32(body, p) + 4 else syncsafe(body, p)
+ end
+ local hdr = if ver == 2 then 6 else 10
+ while p + hdr <= e do
+ local c0 = ru8(body, p)
+ if c0 == 0 then
+ break -- padding
+ end
+ local id, fsize, fflags
+ if ver == 2 then
+ id = buffer.readstring(body, p, 3)
+ fsize = bor(lshift(ru8(body, p + 3), 16), lshift(ru8(body, p + 4), 8), ru8(body, p + 5))
+ fflags = 0
+ else
+ id = buffer.readstring(body, p, 4)
+ fsize = if ver == 4 then syncsafe(body, p + 4) else be32(body, p + 4)
+ fflags = bor(lshift(ru8(body, p + 8), 8), ru8(body, p + 9))
+ end
+ if not string.match(id, "^[A-Z0-9]+$") or fsize <= 0 or p + hdr + fsize > e then
+ break
+ end
+ local fs, fe = p + hdr, p + hdr + fsize
+ local fb = body
+ local skip = false
+ if ver == 3 then
+ skip = band(fflags, 0x00C0) ~= 0 -- compressed / encrypted
+ elseif ver == 4 then
+ skip = band(fflags, 0x000C) ~= 0
+ if not skip and band(fflags, 0x0001) ~= 0 then
+ fs += 4 -- data length indicator
+ end
+ if not skip and band(fflags, 0x0002) ~= 0 and fs < fe then
+ fb = deunsync(body, fs, fe)
+ fs, fe = 0, buffer.len(fb)
+ end
+ end
+ if not skip and fs < fe then
+ local first = string.sub(id, 1, 1)
+ local enc = ru8(fb, fs)
+ if first == "T" and id ~= "TXXX" and id ~= "TXX" then
+ setField(tags, id, clean(decodeText(fb, fs + 1, fe, enc)))
+ elseif (id == "COMM" or id == "COM") and fe - fs >= 4 then
+ -- encoding, language[3], short description (NUL-terminated in the encoding), text
+ local q = fs + 4
+ local wide = enc == 1 or enc == 2
+ while q < fe do
+ if wide then
+ if q + 1 < fe and ru8(fb, q) == 0 and ru8(fb, q + 1) == 0 then
+ q += 2
+ break
+ end
+ q += 2
+ else
+ if ru8(fb, q) == 0 then
+ q += 1
+ break
+ end
+ q += 1
+ end
+ end
+ if q <= fe then
+ setField(tags, id, clean(decodeText(fb, q, fe, enc)))
+ end
+ end
+ end
+ p += hdr + fsize
+ end
+end
+
+local function v1String(b: buffer, o: number, n: number): string
+ return (string.gsub(decodeText(b, o, o + n, 0), "[%z%s]+$", ""))
+end
+
+-- Parses tags and returns (tags, audio start, audio end) for the buffer b.
+-- tags = { title?, artist?, album?, albumArtist?, year?, track?, disc?, genre?, composer?, comment?,
+-- raw = { [frame id] = text }, id3v2 = "2.3"?, id3v1 = true? }
+function Tags.parse(b: buffer): (any, number, number)
+ local len = buffer.len(b)
+ local tags: any = { raw = {} }
+ local start, stop = 0, len
+ local v2 = Tags.id3v2Size(b, 0, len)
+ if v2 > 0 then
+ pcall(parseV2, b, 0, v2, tags)
+ start = math.min(v2, len)
+ end
+ -- mp3dec_skip_id3v1 on what follows the ID3v2 tag
+ local size = stop - start
+ if size >= 128 and buffer.readstring(b, start + size - 128, 3) == "TAG" then
+ local o = start + size - 128
+ tags.id3v1 = true
+ local v1 = {
+ title = v1String(b, o + 3, 30),
+ artist = v1String(b, o + 33, 30),
+ album = v1String(b, o + 63, 30),
+ year = v1String(b, o + 93, 4),
+ }
+ if ru8(b, o + 125) == 0 and ru8(b, o + 126) ~= 0 then
+ v1.comment = v1String(b, o + 97, 28)
+ v1.track = tostring(ru8(b, o + 126))
+ else
+ v1.comment = v1String(b, o + 97, 30)
+ end
+ local g = ru8(b, o + 127)
+ if GENRES[g] then
+ v1.genre = GENRES[g]
+ end
+ for k, v in v1 do
+ if tags[k] == nil and v ~= "" then
+ tags[k] = v
+ end
+ end
+ size -= 128
+ if size >= 227 and buffer.readstring(b, start + size - 227, 4) == "TAG+" then
+ size -= 227
+ end
+ end
+ if size > 32 and buffer.readstring(b, start + size - 32, 8) == "APETAGEX" then
+ size -= 32
+ local t = start + size + 12
+ local tagSize = bor(ru8(b, t), lshift(ru8(b, t + 1), 8), lshift(ru8(b, t + 2), 16), lshift(ru8(b, t + 3), 24))
+ if size >= tagSize then
+ size -= tagSize
+ end
+ tags.ape = true
+ end
+ stop = start + size
+ return tags, start, stop
+end
+
+return Tags
diff --git a/src/Formats/audio/mp3/init.luau b/src/Formats/audio/mp3/init.luau
new file mode 100644
index 0000000..649970d
--- /dev/null
+++ b/src/Formats/audio/mp3/init.luau
@@ -0,0 +1,130 @@
+--!strict
+-- audio/mp3: MPEG audio (ISO/IEC 11172-3, 13818-3; MPEG-2.5), layers I, II and III. Absorbed from mp3-luau c755bbf
+-- (same author; a port of minimp3 by lieff, CC0: licenses/minimp3-CC0.txt). Supports: decode of MPEG-1 / 2 / 2.5
+-- layers I / II / III, mono / stereo / joint stereo / dual channel, CBR / VBR / free format, gapless playback (Xing /
+-- Info + LAME delay and padding), exact length and sample-accurate seeking from a frame index built on open, resync
+-- past garbage, mono / stereo switches (upmixed), ID3v2.2 / 2.3 / 2.4 and ID3v1 / 1.1 tags (APEv2 skipped).
+-- Float output (minimp3's MINIMP3_FLOAT_OUTPUT scalar path). Not supported: encoding (see the mp3 encoder in the
+-- audio workstream), MPEG-2 multichannel extension, CRC checks.
+--
+-- local dec = Mp3.open(Bytes.reader(buf)) -- the streaming Types.Decoder (+ layer, version, vbr, delay,
+-- local pcm, n = dec:read(4096) -- padding, mpegFrames, id3, :seekFrame(i), :readAll())
+-- local audio = Mp3.decode(Bytes.reader(buf)) -- a Types.Audio (the whole file)
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Header = require("@formats/audio/mp3/Header")
+local Index = require("@formats/audio/mp3/Index")
+local Tags = require("@formats/audio/mp3/Tags")
+local Stream = require("@formats/audio/mp3/Stream")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Mp3 = {
+ name = "mp3",
+ category = "audio",
+ extensions = { "mp3", "mp2", "mp1", "mpga" },
+ mime = { "audio/mpeg", "audio/mp3", "audio/mpa" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = false, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 },
+}
+
+-- ------------------------------------------------------------------------------------------------ types
+export type OpenOptions = {
+ maxFrames: number?, -- refuse streams longer than this many sample frames per channel (default 2^31)
+}
+export type Decoder = Stream.Decoder
+
+-- ------------------------------------------------------------------------------------------------ constants
+local MAX_FRAMES = 2 ^ 31
+
+-- ------------------------------------------------------------------------------------------------ sniff
+-- an ID3v2 tag and / or a valid frame header at the start, more when the next frame chains on
+function Mp3.sniff(r: Bytes.Reader): number
+ local b, p, lim = r.buf, r.pos, r.limit
+ local id3 = false
+ for _ = 1, 4 do -- (ffmpeg writes a tag even when the input had one: tags can follow each other)
+ local n = if p + 3 <= lim and buffer.readstring(b, p, 3) == "ID3" then Tags.id3v2Size(b, p, lim) else 0
+ if n <= 0 then
+ break
+ end
+ id3 = true
+ p += n
+ end
+ if p + 4 > lim or not Header.valid(b, p) then
+ return if id3 then 0.5 else 0
+ end
+ local fb = Header.frameBytes(b, p, 0)
+ if fb > 0 then
+ fb += Header.padding(b, p)
+ if p + fb + 4 <= lim and Header.compare(b, p, p + fb) then
+ return 0.9
+ end
+ if p + fb == lim then
+ return 0.6
+ end
+ end
+ return if id3 then 0.7 else 0.25
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+-- decode(r, opts) -> Types.Audio (the whole stream, through open)
+function Mp3.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?)
+ local dec, err = Mp3.open(r, opts)
+ if not dec then
+ return nil, err
+ end
+ local a = Types.Audio.new(dec.sampleRate, dec.channels, dec.frames)
+ local _, n = dec:read(dec.frames, a.samples)
+ if n < dec.frames then
+ return nil, Err.new(Err.CORRUPT, string.format("decoded %d of %d frames", n, dec.frames))
+ end
+ a.tags = dec.tags
+ a.meta.source = { format = "mp3", layer = dec.layer, version = dec.version, bitrate = dec.bitrate, vbr = dec.vbr }
+ return a, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ open
+-- the string-valued tag fields (title, artist, album, albumArtist, year, track, disc, genre, composer, comment)
+local function stringTags(t: any): { [string]: string }
+ local out: { [string]: string } = {}
+ for k, v in t do
+ if type(k) == "string" and type(v) == "string" and k ~= "id3v2" then
+ out[k] = v
+ end
+ end
+ return out
+end
+
+-- open(r, opts) -> the streaming Decoder (Types.Decoder) | nil, Err
+function Mp3.open(r: Bytes.Reader, opts: OpenOptions?): (Decoder?, Err.Err?)
+ local b = r.buf
+ if r.base ~= 0 or r.limit ~= buffer.len(b) then
+ b = buffer.create(r.limit - r.base) -- the core indexes from offset 0
+ buffer.copy(b, 0, r.buf, r.base, r.limit - r.base)
+ end
+ local okTags, tags, start, stop = pcall(Tags.parse, b)
+ if not okTags then
+ tags, start, stop = { raw = {} }, 0, buffer.len(b)
+ end
+ local idx = Index.build(b, start, stop)
+ if not idx then
+ return nil, Err.new(Err.CORRUPT, "no MPEG audio frames found")
+ end
+ local dec = Stream.new(b, idx, stringTags(tags), {
+ raw = tags.raw,
+ id3v2 = tags.id3v2,
+ id3v1 = tags.id3v1 == true,
+ ape = tags.ape == true,
+ })
+ if dec.frames > (opts and opts.maxFrames or MAX_FRAMES) then
+ return nil, Err.new(Err.LIMIT, string.format("%d sample frames is over the limit", dec.frames))
+ end
+ return dec, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ extras
+Mp3.Tags = Tags -- Tags.parse(buf) -> (tags, audio start, audio end)
+
+return Mp3
diff --git a/tests/audio/mp3.luau b/tests/audio/mp3.luau
new file mode 100644
index 0000000..f973803
--- /dev/null
+++ b/tests/audio/mp3.luau
@@ -0,0 +1,518 @@
+-- audio/mp3 tests: every fixture against its minimp3 reference decode (exact length, SNR > 90 dB on windows, block
+-- energies) and against ffmpeg (length, SNR > 75 dB), lame-written streams against ffmpeg; chunked reads, reads into
+-- a caller buffer, sample-accurate seeking; robustness (garbage, corruption, truncation, mono / stereo switches, API
+-- misuse); ID3v1 / v2.2 / 2.3 / 2.4 and APE tags; the contract, sniff, decode to Audio, the fuzz no-throw pass.
+-- Ported from mp3-luau tests/decode.luau, robust.luau, tags.luau. Fixtures: tools/fixtures/mp3.py.
+local T = require("@tests/T")
+local Mp3 = require("@formats/audio/mp3")
+local Bytes = require("@formats/core/Bytes")
+local Err = require("@formats/core/Err")
+local Cases = require("@tests/gen/mp3_cases")
+
+local t = T.suite("mp3")
+
+local function open(b: buffer | string, opts: any?): (any, any)
+ local buf = if type(b) == "string" then buffer.fromstring(b) else b
+ return Mp3.open(Bytes.reader(buf), opts)
+end
+
+local byName: { [string]: any } = {}
+for _, c in Cases do
+ byName[c.name] = c
+end
+local function file(name: string): buffer
+ return buffer.fromstring(byName[name].data)
+end
+
+-- the reference format written by the minimp3 harness (see tools/fixtures/mp3.py)
+local function parseRef(s: string): any
+ local b = buffer.fromstring(s)
+ local hz, ch, frames, W, N = buffer.readu32(b, 8), buffer.readu32(b, 12), buffer.readu32(b, 16), buffer.readu32(b, 20), buffer.readu32(b, 24)
+ local p = 28
+ local windows = {}
+ for _ = 1, N do
+ local start = buffer.readu32(b, p)
+ p += 4
+ local pcm = buffer.create(W * ch * 4)
+ buffer.copy(pcm, 0, b, p, W * ch * 4)
+ p += W * ch * 4
+ table.insert(windows, { start = start, pcm = pcm })
+ end
+ local B, nb = buffer.readu32(b, p), buffer.readu32(b, p + 4)
+ p += 8
+ local energies = {}
+ for i = 1, nb do
+ energies[i] = buffer.readf64(b, p)
+ p += 8
+ end
+ return { hz = hz, channels = ch, frames = frames, W = W, windows = windows, block = B, energies = energies }
+end
+
+local function snr(x: buffer, xo: number, ref: buffer, ro: number, n: number): number
+ local sig, err = 0, 0
+ for i = 0, n - 1 do
+ local r = buffer.readf32(ref, (ro + i) * 4)
+ local d = buffer.readf32(x, (xo + i) * 4) - r
+ sig += r * r
+ err += d * d
+ end
+ if err == 0 then
+ return math.huge
+ end
+ if sig == 0 then
+ return -math.huge
+ end
+ return 10 * math.log10(sig / err)
+end
+
+local function maxDiff(x: buffer, xo: number, y: buffer, yo: number, n: number): number
+ local m = 0
+ for i = 0, n - 1 do
+ local d = math.abs(buffer.readf32(x, (xo + i) * 4) - buffer.readf32(y, (yo + i) * 4))
+ if d > m then
+ m = d
+ end
+ end
+ return m
+end
+
+local rand = T.rng(12345)
+
+-- ------------------------------------------------------------------------------------------------ contract
+t:eq(Mp3.name, "mp3", "name")
+t:eq(Mp3.category, "audio", "category")
+t:check(table.find(Mp3.extensions, "mp3") ~= nil and table.find(Mp3.extensions, "mp2") ~= nil, "extensions")
+t:check(Mp3.caps.decode and not Mp3.caps.encode and Mp3.open ~= nil, "caps")
+
+-- ------------------------------------------------------------------------------------------------ decode vs references
+for _, c in Cases do
+ local name = c.name
+ local buf = buffer.fromstring(c.data)
+ local dec, err = open(buf)
+ t:check(dec, name .. ": open (" .. tostring(err) .. ")")
+ local ch = dec.channels
+ local ref = if c.ref then parseRef(c.ref) else nil
+ if ref then
+ t:eq(dec.sampleRate, ref.hz, name .. ": sample rate")
+ t:eq(ch, ref.channels, name .. ": channels")
+ t:eq(dec.frames, ref.frames, name .. ": frames vs minimp3")
+ t:check(math.abs(dec.duration - ref.frames / ref.hz) < 1e-9, name .. ": duration")
+ else
+ t:eq(dec.sampleRate, c.rate, name .. ": sample rate")
+ t:eq(ch, c.channels, name .. ": channels")
+ t:eq(dec.frames, c.srcFrames, name .. ": gapless length = the encoder's input")
+ end
+ t:eq(dec.frames, c.ffFrames, name .. ": frames vs ffmpeg")
+ t:check(dec.bitrate > 0, name .. ": bitrate")
+
+ -- whole decode in chunks of varied sizes
+ local all = buffer.create(dec.frames * ch * 4)
+ local total = 0
+ while true do
+ local pcm, n = dec:read(1 + rand(3000))
+ if n == 0 then
+ break
+ end
+ t:check(buffer.len(pcm) == n * ch * 4, name .. ": chunk size")
+ buffer.copy(all, total * ch * 4, pcm, 0, n * ch * 4)
+ total += n
+ end
+ t:eq(total, dec.frames, name .. ": decoded frames")
+ t:eq(dec:position(), total / dec.sampleRate, name .. ": position at the end")
+ local _, n0 = dec:read(100)
+ t:eq(n0, 0, name .. ": read after the end")
+
+ local worst, worstFF = math.huge, math.huge
+ if ref then
+ for _, w in ref.windows do
+ local s = snr(all, w.start * ch, w.pcm, 0, ref.W * ch)
+ worst = math.min(worst, s)
+ t:check(s > 90, string.format("%s: window at %d SNR %.1f dB vs minimp3", name, w.start, s))
+ end
+ for bi, e in ref.energies do
+ local a = (bi - 1) * ref.block
+ local bEnd = math.min(ref.frames, a + ref.block)
+ local sum = 0
+ for i = a * ch, bEnd * ch - 1 do
+ local v = buffer.readf32(all, i * 4)
+ sum += v * v
+ end
+ t:check(math.abs(sum - e) <= 1e-5 * e + 1e-9, string.format("%s: block %d energy", name, bi))
+ end
+ end
+ for _, w in c.ff do
+ local pcm = buffer.fromstring(w.pcm)
+ local s = snr(all, w.start * ch, pcm, 0, buffer.len(pcm) // 4)
+ worstFF = math.min(worstFF, s)
+ t:check(s > 75, string.format("%s: window at %d SNR %.1f dB vs ffmpeg", name, w.start, s))
+ end
+
+ -- reading into a caller buffer (reused when big enough, ignored when too small)
+ dec:seek(0)
+ local out = buffer.create(500 * ch * 4)
+ local got, n1 = dec:read(500, out)
+ t:check(got == out and n1 == 500, name .. ": read into out")
+ t:eq(maxDiff(out, 0, all, 0, 500 * ch), 0, name .. ": out matches")
+ local got2, n2 = dec:read(600, out)
+ t:check(got2 ~= out and n2 == 600 and maxDiff(got2, 0, all, 500 * ch, 600 * ch) == 0, name .. ": small out ignored")
+
+ -- seeks: every window, then random targets, compared with the straight decode (bit-identical)
+ local targets = {}
+ for _, w in c.ff do
+ table.insert(targets, w.start)
+ end
+ for _ = 1, 12 do
+ table.insert(targets, rand(dec.frames))
+ end
+ table.insert(targets, dec.frames - 1)
+ for _, tg in targets do
+ dec:seekFrame(tg)
+ local _, pf = dec:position()
+ t:eq(pf, tg, name .. ": position after seek")
+ local want = math.min(1152, dec.frames - tg)
+ local pcm, n = dec:read(want)
+ t:eq(n, want, string.format("%s: read after seek to %d", name, tg))
+ t:eq(maxDiff(pcm, 0, all, tg * ch, n * ch), 0, string.format("%s: seek to %d bit-identical", name, tg))
+ end
+ dec:seek(dec.duration / 3)
+ local _, pf = dec:position()
+ local pcm, n = dec:read(64)
+ t:check(n == 64 and maxDiff(pcm, 0, all, pf * ch, 64 * ch) == 0, name .. ": seek seconds")
+ dec:seek(1e9)
+ t:eq(select(2, dec:read(10)), 0, name .. ": seek past the end")
+ dec:seek(-5)
+ local pcm0, n3 = dec:read(256)
+ t:check(n3 == 256 and maxDiff(pcm0, 0, all, 0, 256 * ch) == 0, name .. ": seek back to the start")
+
+ -- decode to Audio, also from a sub-range of a bigger buffer
+ local big = buffer.create(buffer.len(buf) + 17)
+ buffer.copy(big, 9, buf)
+ local a, aerr = Mp3.decode(Bytes.reader(big, 9, buffer.len(buf)))
+ t:check(a and a.kind == "audio" and a.frames == dec.frames and a.channels == ch, name .. ": decode (" .. tostring(aerr) .. ")")
+ t:eq(maxDiff(a.samples, 0, all, 0, dec.frames * ch), 0, name .. ": decode = stream")
+ t:check(a.meta.source.format == "mp3" and a.meta.source.layer == dec.layer, name .. ": meta.source")
+ t:eq(Mp3.sniff(Bytes.reader(buf)) > 0.5, true, name .. ": sniff")
+
+ t:note("%-20s L%d MPEG-%s %5d Hz %d ch %6d frames %3d kbps SNR minimp3 %s, ffmpeg %.1f dB", name, dec.layer, tostring(dec.version), dec.sampleRate, ch, dec.frames, dec.bitrate, if ref then string.format("%.1f", worst) else "-", worstFF)
+end
+
+-- ------------------------------------------------------------------------------------------------ robustness
+local function concat(...: buffer): buffer
+ local n = 0
+ for _, b in { ... } do
+ n += buffer.len(b)
+ end
+ local out = buffer.create(n)
+ local o = 0
+ for _, b in { ... } do
+ buffer.copy(out, o, b, 0)
+ o += buffer.len(b)
+ end
+ return out
+end
+local function slice(b: buffer, i: number, j: number): buffer
+ local out = buffer.create(j - i)
+ buffer.copy(out, 0, b, i, j - i)
+ return out
+end
+-- decodes everything; checks every sample is finite; returns pcm, frames, decoder
+local function decodeAll(b: buffer, label: string): (buffer?, number, any)
+ local ok, dec, err = pcall(open, b)
+ t:check(ok, label .. ": open does not throw (" .. tostring(dec) .. ")")
+ if not dec then
+ return nil, 0, err
+ end
+ local ok2, pcm, n = pcall(dec.readAll, dec)
+ t:check(ok2, label .. ": decode does not throw (" .. tostring(pcm) .. ")")
+ local bad = 0
+ for i = 0, n * dec.channels - 1 do
+ local v = buffer.readf32(pcm, i * 4)
+ if v ~= v or v == math.huge or v == -math.huge then
+ bad += 1
+ end
+ end
+ t:eq(bad, 0, label .. ": finite samples")
+ return pcm, n, dec
+end
+
+-- the same pseudo-random sequence as mp3-luau's robust.luau (its junk is known not to chain into frames)
+local orandRaw = T.rng(777)
+local function orand(n: number): number -- 1..n
+ return orandRaw(n) + 1
+end
+local base = file("l3_cbr128_js")
+local refPcm, refN, refDec = decodeAll(base, "base")
+assert(refPcm)
+
+-- garbage before the first frame (with fake sync words): same output, bit for bit
+do
+ local junk = buffer.create(5000)
+ for i = 0, 4999 do
+ buffer.writeu8(junk, i, (orand(256) - 1))
+ end
+ for i = 0, 4999, 97 do
+ buffer.writeu8(junk, i, 0xFF)
+ if i + 1 < 5000 then
+ buffer.writeu8(junk, i + 1, 0xFB)
+ end
+ end
+ local pcm, n, dec = decodeAll(concat(junk, base), "garbage prefix")
+ t:check(n == refN and dec.frames == refN, string.format("garbage prefix: same length (%d %d vs %d)", n, dec.frames, refN))
+ t:check(pcm and maxDiff(pcm, 0, refPcm, 0, n * 2) == 0, "garbage prefix: same samples")
+end
+-- garbage in the middle: re-syncs, keeps going
+do
+ local half = buffer.len(base) // 2
+ local junk = buffer.create(3333)
+ for i = 0, 3332 do
+ buffer.writeu8(junk, i, (orand(256) - 1))
+ end
+ local _, n = decodeAll(concat(slice(base, 0, half), junk, slice(base, half, buffer.len(base))), "garbage middle")
+ t:check(math.abs(n - refN) <= 4 * 1152, string.format("garbage middle: %d frames vs %d", n, refN))
+end
+-- corrupt bytes all over the stream
+do
+ local b = buffer.create(buffer.len(base))
+ buffer.copy(b, 0, base)
+ for _ = 1, 60 do
+ buffer.writeu8(b, 1000 + orand(buffer.len(b) - 1001), (orand(256) - 1))
+ end
+ local _, n = decodeAll(b, "corrupt bytes")
+ t:check(n > refN // 2, "corrupt bytes: most frames decode")
+end
+-- truncated anywhere
+for _ = 1, 25 do
+ local cut = orand(buffer.len(base))
+ local _, n = decodeAll(slice(base, 0, cut), "truncated at " .. cut)
+ t:check(n <= refN, "truncated: not longer")
+end
+-- a stereo stream (no Xing tag) then a mono one of the same rate -> stereo, the mono part in both channels
+do
+ local stereo = file("l3_noreservoir")
+ local mono = file("l3_vbr_v7_mono")
+ local _, stereoN = decodeAll(stereo, "stereo alone")
+ local _, monoN = decodeAll(mono, "mono alone")
+ local pcm, n, dec = decodeAll(concat(stereo, mono), "stereo then mono")
+ t:check(dec and dec.channels == 2, "switch: stereo output")
+ t:check(n >= stereoN + monoN, "switch: both parts decode")
+ local same = true
+ for i = n - 3000, n - 2000 do
+ if buffer.readf32(pcm :: buffer, i * 8) ~= buffer.readf32(pcm :: buffer, i * 8 + 4) then
+ same = false
+ end
+ end
+ t:check(same, "switch: mono part duplicated")
+end
+-- bad input and API misuse
+do
+ local d, err = open(buffer.create(0))
+ t:check(d == nil and Err.is(err) and err.code == Err.CORRUPT, "empty buffer")
+ d = open(string.rep("not an mp3 file at all ", 500))
+ t:check(d == nil, "text")
+ t:check(open(buffer.create(100000)) == nil, "zeros")
+ local ffs = buffer.create(100000)
+ buffer.fill(ffs, 0, 0xFF)
+ t:check(pcall(function()
+ local dd = open(ffs)
+ if dd then
+ dd:readAll()
+ end
+ end), "all 0xFF")
+ local _, lerr = open(base, { maxFrames = 1000 })
+ t:check(lerr and lerr.code == Err.LIMIT, "maxFrames")
+ local dec = refDec
+ dec:seek(0)
+ t:eq(select(2, dec:read(-5)), 0, "read(-5)")
+ t:eq(select(2, dec:read(nil :: any)), 4096, "read(nil) = 4096 frames")
+ dec:seek(nil :: any)
+ t:eq(select(2, dec:position()), 0, "seek(nil)")
+ dec:seek(0 / 0)
+ t:check(select(2, dec:position()) >= 0, "seek(nan)")
+ t:eq(select(2, dec:read(0 / 0)), 0, "read(nan)")
+ t:eq(Mp3.sniff(Bytes.reader(buffer.fromstring("RIFF....WAVEfmt "))), 0, "sniff a WAV")
+ t:eq(Mp3.sniff(Bytes.reader(buffer.create(0))), 0, "sniff nothing")
+end
+
+-- ------------------------------------------------------------------------------------------------ tags
+local function eq(a: any, b: any, label: string)
+ t:eq(a, b, label)
+end
+do
+ local dec = assert(open(file("l3_tags")))
+ local tg = dec.tags
+ eq(dec.id3.id3v2, "2.3", "fixture id3v2")
+ eq(tg.title, "Test Title", "fixture title")
+ eq(tg.artist, "Some Artist", "fixture artist")
+ eq(tg.album, "An Album", "fixture album")
+ eq(tg.year, "2001", "fixture year")
+ eq(tg.track, "7", "fixture track")
+ eq(tg.genre, "Rock", "fixture genre")
+ eq(tg.comment, "hello", "fixture comment")
+ t:check(dec.id3.id3v1, "fixture id3v1")
+ for k, v in tg do
+ t:check(type(k) == "string" and type(v) == "string", "tags are strings")
+ end
+end
+
+local audio = file("l3_mpeg25_8k")
+local plain = assert(open(audio))
+local plainPcm, plainN = plain:readAll()
+
+local function syncsafe(n: number): string
+ return string.char(bit32.band(bit32.rshift(n, 21), 127), bit32.band(bit32.rshift(n, 14), 127), bit32.band(bit32.rshift(n, 7), 127), bit32.band(n, 127))
+end
+local function be32(n: number): string
+ return string.char(bit32.rshift(n, 24), bit32.band(bit32.rshift(n, 16), 255), bit32.band(bit32.rshift(n, 8), 255), bit32.band(n, 255))
+end
+local function le32(n: number): string
+ return string.char(bit32.band(n, 255), bit32.band(bit32.rshift(n, 8), 255), bit32.band(bit32.rshift(n, 16), 255), bit32.rshift(n, 24))
+end
+local function be24(n: number): string
+ return string.char(bit32.rshift(n, 16), bit32.band(bit32.rshift(n, 8), 255), bit32.band(n, 255))
+end
+local function utf16le(s: string): string
+ local out = { "\xFF\xFE" }
+ for _, cp in utf8.codes(s) do
+ if cp >= 0x10000 then
+ local v = cp - 0x10000
+ local hi, lo = 0xD800 + bit32.rshift(v, 10), 0xDC00 + bit32.band(v, 0x3FF)
+ table.insert(out, string.char(bit32.band(hi, 255), bit32.rshift(hi, 8), bit32.band(lo, 255), bit32.rshift(lo, 8)))
+ else
+ table.insert(out, string.char(bit32.band(cp, 255), bit32.rshift(cp, 8)))
+ end
+ end
+ return table.concat(out)
+end
+local function withAudio(prefix: string, suffix: string?): buffer
+ return buffer.fromstring(prefix .. buffer.tostring(audio) .. (suffix or ""))
+end
+local function sameAudio(dec: any, label: string)
+ eq(dec.frames, plain.frames, label .. ": frames")
+ local pcm, n = dec:readAll()
+ t:check(n == plainN and maxDiff(pcm, 0, plainPcm, 0, n) == 0, label .. ": same samples")
+end
+
+-- ID3v2.4: UTF-8, syncsafe frame sizes, an extended header, multi-value TPE1, numeric TCON, padding
+do
+ local function frame(id: string, body: string): string
+ return id .. syncsafe(#body) .. "\0\0" .. body
+ end
+ local frames = frame("TIT2", "\3Ünïcödé ★ title") .. frame("TPE1", "\3One\0Two") .. frame("TCON", "\3(17)") .. frame("TDRC", "\0" .. "1999-05-01") .. frame("COMM", "\3eng\0a comment") .. string.rep("\0", 64)
+ local body = syncsafe(6) .. "\1\0" .. frames
+ local tag = "ID3\4\0\x40" .. syncsafe(#body) .. body
+ local dec = assert(open(withAudio(tag)))
+ eq(dec.id3.id3v2, "2.4", "v2.4 version")
+ eq(dec.tags.title, "Ünïcödé ★ title", "v2.4 title")
+ eq(dec.tags.artist, "One / Two", "v2.4 multi-value")
+ eq(dec.tags.genre, "Rock", "v2.4 genre")
+ eq(dec.tags.year, "1999-05-01", "v2.4 TDRC")
+ eq(dec.tags.comment, "a comment", "v2.4 COMM")
+ sameAudio(dec, "v2.4")
+ t:check(Mp3.sniff(Bytes.reader(withAudio(tag))) >= 0.7, "sniff behind an ID3v2 tag")
+end
+-- ID3v2.3: UTF-16 with BOM (incl. a surrogate pair), latin-1, whole-tag unsynchronisation
+do
+ local function frame(id: string, body: string): string
+ return id .. be32(#body) .. "\0\0" .. body
+ end
+ local frames = frame("TIT2", "\1" .. utf16le("Grüße 𝄞")) .. frame("TALB", "\0Caf\xE9") .. frame("TRCK", "\0" .. "3/12") .. frame("TCON", "\0" .. "Electronic")
+ local unsync = string.gsub(frames, "\xFF", "\xFF\0")
+ local tag = "ID3\3\0\x80" .. syncsafe(#unsync) .. unsync
+ local dec = assert(open(withAudio(tag)))
+ eq(dec.id3.id3v2, "2.3", "v2.3 version")
+ eq(dec.tags.title, "Grüße 𝄞", "v2.3 UTF-16 title")
+ eq(dec.tags.album, "Café", "v2.3 latin-1 album")
+ eq(dec.tags.track, "3/12", "v2.3 track")
+ eq(dec.tags.genre, "Electronic", "v2.3 genre")
+ eq(dec.id3.raw.TALB, "Café", "raw frame")
+ sameAudio(dec, "v2.3")
+end
+-- ID3v2.2: 3-character ids, 24-bit sizes
+do
+ local function frame(id: string, body: string): string
+ return id .. be24(#body) .. body
+ end
+ local frames = frame("TT2", "\0Old Title") .. frame("TP1", "\0Old Artist") .. frame("TCO", "\0(8)") .. frame("COM", "\0eng\0old comment")
+ local tag = "ID3\2\0\0" .. syncsafe(#frames) .. frames
+ local dec = assert(open(withAudio(tag)))
+ eq(dec.id3.id3v2, "2.2", "v2.2 version")
+ eq(dec.tags.title, "Old Title", "v2.2 title")
+ eq(dec.tags.artist, "Old Artist", "v2.2 artist")
+ eq(dec.tags.genre, "Jazz", "v2.2 genre")
+ eq(dec.tags.comment, "old comment", "v2.2 comment")
+ sameAudio(dec, "v2.2")
+end
+-- ID3v1.1 alone (track byte), then APEv2 + ID3v1 at the end
+do
+ local function pad(s: string, n: number): string
+ return s .. string.rep("\0", n - #s)
+ end
+ local v1 = "TAG" .. pad("V1 Title", 30) .. pad("V1 Artist", 30) .. pad("V1 Album", 30) .. "1987" .. pad("v1 comment", 28) .. "\0\9" .. "\17"
+ local dec = assert(open(withAudio("", v1)))
+ t:check(dec.id3.id3v1, "v1 flag")
+ eq(dec.tags.title, "V1 Title", "v1 title")
+ eq(dec.tags.artist, "V1 Artist", "v1 artist")
+ eq(dec.tags.album, "V1 Album", "v1 album")
+ eq(dec.tags.year, "1987", "v1 year")
+ eq(dec.tags.comment, "v1 comment", "v1 comment")
+ eq(dec.tags.track, "9", "v1.1 track")
+ eq(dec.tags.genre, "Rock", "v1 genre")
+ sameAudio(dec, "v1")
+ local item = "\5\0\0\0" .. "\0\0\0\0" .. "Title\0" .. "hello"
+ local size = #item + 32
+ local function apeHdr(isHeader: boolean): string
+ local flags = if isHeader then "\0\0\0\xA0" else "\0\0\0\x80"
+ return "APETAGEX" .. "\xD0\7\0\0" .. le32(size) .. "\1\0\0\0" .. flags .. string.rep("\0", 8)
+ end
+ local ape = apeHdr(true) .. item .. apeHdr(false)
+ local dec2 = assert(open(withAudio("", ape .. v1)))
+ t:check(dec2.id3.ape, "ape flag")
+ eq(dec2.tags.title, "V1 Title", "ape + v1 title")
+ sameAudio(dec2, "ape + v1")
+end
+-- a truncated ID3v2 tag never throws
+do
+ local tag = "ID3\3\0\0" .. syncsafe(5000) .. "TIT2" .. be32(4000) .. "\0\0\0abc"
+ local ok, dec = pcall(open, withAudio(tag))
+ t:check(ok, "truncated tag does not throw")
+ t:check(dec == nil or dec.frames <= plain.frames, "truncated tag")
+end
+
+-- ------------------------------------------------------------------------------------------------ through the api
+do
+ local F = require("@formats")
+ local data = byName.l3_tags.data
+ t:eq(F.detect(data), "mp3", "F.detect")
+ local a, err = F.audio.load(data)
+ t:check(a and a.kind == "audio" and a.frames == 22050 and a.tags.title == "Test Title", "F.audio.load: " .. tostring(err))
+ local dec = F.audio.open(data)
+ t:check(dec and dec.sampleRate == 44100 and dec.frames == 22050, "F.audio.open")
+ local _, serr = F.save(a, nil, { format = "mp3" })
+ t:check(serr and serr.code == Err.UNSUPPORTED, "F.save mp3: read-only")
+end
+
+-- ------------------------------------------------------------------------------------------------ fuzz
+do
+ local samples = {}
+ for _, name in { "l3_cbr32_mono", "l3_mpeg2_22k", "l3_mpeg25_8k", "l2_64_mono", "l2_mpeg2_24k", "l3_tags", "lame_cbr64_mono_22k" } do
+ local s = byName[name].data
+ table.insert(samples, string.sub(s, 1, math.min(#s, 6000)))
+ end
+ t:fuzz("open + read + seek", function(b: buffer)
+ local dec = Mp3.open(Bytes.reader(b))
+ if dec then
+ dec:read(1 + rand(5000))
+ dec:seek(dec.duration * rand(100) / 100)
+ dec:read(1 + rand(5000))
+ dec:seekFrame(rand(dec.frames + 1))
+ dec:readAll()
+ end
+ Mp3.sniff(Bytes.reader(b))
+ return dec
+ end, samples, { mutations = 12 })
+ t:fuzz("decode", function(b: buffer)
+ return Mp3.decode(Bytes.reader(b))
+ end, samples, { mutations = 4, garbage = 50 })
+end
+
+t:done()
diff --git a/tests/fixtures/mp3/l2_192_st.mp2 b/tests/fixtures/mp3/l2_192_st.mp2
new file mode 100644
index 0000000..1f21386
Binary files /dev/null and b/tests/fixtures/mp3/l2_192_st.mp2 differ
diff --git a/tests/fixtures/mp3/l2_192_st.ref b/tests/fixtures/mp3/l2_192_st.ref
new file mode 100644
index 0000000..242de95
Binary files /dev/null and b/tests/fixtures/mp3/l2_192_st.ref differ
diff --git a/tests/fixtures/mp3/l2_32k_st.mp2 b/tests/fixtures/mp3/l2_32k_st.mp2
new file mode 100644
index 0000000..883fd29
Binary files /dev/null and b/tests/fixtures/mp3/l2_32k_st.mp2 differ
diff --git a/tests/fixtures/mp3/l2_32k_st.ref b/tests/fixtures/mp3/l2_32k_st.ref
new file mode 100644
index 0000000..93442bd
Binary files /dev/null and b/tests/fixtures/mp3/l2_32k_st.ref differ
diff --git a/tests/fixtures/mp3/l2_64_mono.mp2 b/tests/fixtures/mp3/l2_64_mono.mp2
new file mode 100644
index 0000000..1fade63
Binary files /dev/null and b/tests/fixtures/mp3/l2_64_mono.mp2 differ
diff --git a/tests/fixtures/mp3/l2_64_mono.ref b/tests/fixtures/mp3/l2_64_mono.ref
new file mode 100644
index 0000000..16a7899
Binary files /dev/null and b/tests/fixtures/mp3/l2_64_mono.ref differ
diff --git a/tests/fixtures/mp3/l2_mpeg2_24k.mp2 b/tests/fixtures/mp3/l2_mpeg2_24k.mp2
new file mode 100644
index 0000000..5d1b4d4
Binary files /dev/null and b/tests/fixtures/mp3/l2_mpeg2_24k.mp2 differ
diff --git a/tests/fixtures/mp3/l2_mpeg2_24k.ref b/tests/fixtures/mp3/l2_mpeg2_24k.ref
new file mode 100644
index 0000000..ffd2f5d
Binary files /dev/null and b/tests/fixtures/mp3/l2_mpeg2_24k.ref differ
diff --git a/tests/fixtures/mp3/l3_cbr128_js.mp3 b/tests/fixtures/mp3/l3_cbr128_js.mp3
new file mode 100644
index 0000000..c05f3a2
Binary files /dev/null and b/tests/fixtures/mp3/l3_cbr128_js.mp3 differ
diff --git a/tests/fixtures/mp3/l3_cbr128_js.ref b/tests/fixtures/mp3/l3_cbr128_js.ref
new file mode 100644
index 0000000..1504f13
Binary files /dev/null and b/tests/fixtures/mp3/l3_cbr128_js.ref differ
diff --git a/tests/fixtures/mp3/l3_cbr320_st.mp3 b/tests/fixtures/mp3/l3_cbr320_st.mp3
new file mode 100644
index 0000000..9482361
Binary files /dev/null and b/tests/fixtures/mp3/l3_cbr320_st.mp3 differ
diff --git a/tests/fixtures/mp3/l3_cbr320_st.ref b/tests/fixtures/mp3/l3_cbr320_st.ref
new file mode 100644
index 0000000..0947033
Binary files /dev/null and b/tests/fixtures/mp3/l3_cbr320_st.ref differ
diff --git a/tests/fixtures/mp3/l3_cbr32_mono.mp3 b/tests/fixtures/mp3/l3_cbr32_mono.mp3
new file mode 100644
index 0000000..686399b
Binary files /dev/null and b/tests/fixtures/mp3/l3_cbr32_mono.mp3 differ
diff --git a/tests/fixtures/mp3/l3_cbr32_mono.ref b/tests/fixtures/mp3/l3_cbr32_mono.ref
new file mode 100644
index 0000000..74289d1
Binary files /dev/null and b/tests/fixtures/mp3/l3_cbr32_mono.ref differ
diff --git a/tests/fixtures/mp3/l3_mpeg25_11k_st.mp3 b/tests/fixtures/mp3/l3_mpeg25_11k_st.mp3
new file mode 100644
index 0000000..0414318
Binary files /dev/null and b/tests/fixtures/mp3/l3_mpeg25_11k_st.mp3 differ
diff --git a/tests/fixtures/mp3/l3_mpeg25_11k_st.ref b/tests/fixtures/mp3/l3_mpeg25_11k_st.ref
new file mode 100644
index 0000000..dfc30a1
Binary files /dev/null and b/tests/fixtures/mp3/l3_mpeg25_11k_st.ref differ
diff --git a/tests/fixtures/mp3/l3_mpeg25_8k.mp3 b/tests/fixtures/mp3/l3_mpeg25_8k.mp3
new file mode 100644
index 0000000..df4f89a
Binary files /dev/null and b/tests/fixtures/mp3/l3_mpeg25_8k.mp3 differ
diff --git a/tests/fixtures/mp3/l3_mpeg25_8k.ref b/tests/fixtures/mp3/l3_mpeg25_8k.ref
new file mode 100644
index 0000000..297f56f
Binary files /dev/null and b/tests/fixtures/mp3/l3_mpeg25_8k.ref differ
diff --git a/tests/fixtures/mp3/l3_mpeg2_16k_mono.mp3 b/tests/fixtures/mp3/l3_mpeg2_16k_mono.mp3
new file mode 100644
index 0000000..9dce08a
Binary files /dev/null and b/tests/fixtures/mp3/l3_mpeg2_16k_mono.mp3 differ
diff --git a/tests/fixtures/mp3/l3_mpeg2_16k_mono.ref b/tests/fixtures/mp3/l3_mpeg2_16k_mono.ref
new file mode 100644
index 0000000..30a8ce3
Binary files /dev/null and b/tests/fixtures/mp3/l3_mpeg2_16k_mono.ref differ
diff --git a/tests/fixtures/mp3/l3_mpeg2_22k.mp3 b/tests/fixtures/mp3/l3_mpeg2_22k.mp3
new file mode 100644
index 0000000..1ca1882
Binary files /dev/null and b/tests/fixtures/mp3/l3_mpeg2_22k.mp3 differ
diff --git a/tests/fixtures/mp3/l3_mpeg2_22k.ref b/tests/fixtures/mp3/l3_mpeg2_22k.ref
new file mode 100644
index 0000000..33e441e
Binary files /dev/null and b/tests/fixtures/mp3/l3_mpeg2_22k.ref differ
diff --git a/tests/fixtures/mp3/l3_noreservoir.mp3 b/tests/fixtures/mp3/l3_noreservoir.mp3
new file mode 100644
index 0000000..4b1808b
Binary files /dev/null and b/tests/fixtures/mp3/l3_noreservoir.mp3 differ
diff --git a/tests/fixtures/mp3/l3_noreservoir.ref b/tests/fixtures/mp3/l3_noreservoir.ref
new file mode 100644
index 0000000..1436d63
Binary files /dev/null and b/tests/fixtures/mp3/l3_noreservoir.ref differ
diff --git a/tests/fixtures/mp3/l3_tags.mp3 b/tests/fixtures/mp3/l3_tags.mp3
new file mode 100644
index 0000000..2366d67
Binary files /dev/null and b/tests/fixtures/mp3/l3_tags.mp3 differ
diff --git a/tests/fixtures/mp3/l3_tags.ref b/tests/fixtures/mp3/l3_tags.ref
new file mode 100644
index 0000000..250a1f7
Binary files /dev/null and b/tests/fixtures/mp3/l3_tags.ref differ
diff --git a/tests/fixtures/mp3/l3_vbr_v2_48k.mp3 b/tests/fixtures/mp3/l3_vbr_v2_48k.mp3
new file mode 100644
index 0000000..9d9048b
Binary files /dev/null and b/tests/fixtures/mp3/l3_vbr_v2_48k.mp3 differ
diff --git a/tests/fixtures/mp3/l3_vbr_v2_48k.ref b/tests/fixtures/mp3/l3_vbr_v2_48k.ref
new file mode 100644
index 0000000..26f9031
Binary files /dev/null and b/tests/fixtures/mp3/l3_vbr_v2_48k.ref differ
diff --git a/tests/fixtures/mp3/l3_vbr_v7_mono.mp3 b/tests/fixtures/mp3/l3_vbr_v7_mono.mp3
new file mode 100644
index 0000000..2291d6b
Binary files /dev/null and b/tests/fixtures/mp3/l3_vbr_v7_mono.mp3 differ
diff --git a/tests/fixtures/mp3/l3_vbr_v7_mono.ref b/tests/fixtures/mp3/l3_vbr_v7_mono.ref
new file mode 100644
index 0000000..12ed1a2
Binary files /dev/null and b/tests/fixtures/mp3/l3_vbr_v7_mono.ref differ
diff --git a/tools/bench.luau b/tools/bench.luau
index 9f6aef7..32a4fe4 100644
--- a/tools/bench.luau
+++ b/tools/bench.luau
@@ -1,11 +1,13 @@
-- Throughput (bash tools/bench.sh): codec MB/s under both runtimes. MB/s are of decompressed output, best of n runs.
--- Fixtures: tools/fixtures/deflate.py (a 6 MB corpus) and tools/fixtures/png.py (1024 x 768 images).
+-- Fixtures: tools/fixtures/deflate.py (a 6 MB corpus), tools/fixtures/png.py (1024 x 768 images), tools/fixtures/mp3.py.
local Deflate = require("@formats/codecs/Deflate")
local Crc32 = require("@formats/core/Crc32")
local Bytes = require("@formats/core/Bytes")
local Png = require("@formats/image/png")
local B = require("@tests/gen/deflate_bench")
local PB = require("@tests/gen/png_bench")
+local Mp3 = require("@formats/audio/mp3")
+local MC = require("@tests/gen/mp3_cases")
local runtime = if (_G :: any).jit ~= nil then "luajit" else "luau"
@@ -18,6 +20,7 @@ local function bench(label: string, n: number, bytes: number, f: () -> ())
dt = math.min(dt, os.clock() - t0)
end
print(string.format("%-8s %-30s %8.2f ms %7.1f MB/s", runtime, label, dt * 1000, bytes / dt / 1e6))
+ return dt
end
local z = buffer.fromstring(B.zlib)
@@ -56,3 +59,17 @@ do
Png.encode(img)
end)
end
+for _, name in { "l3_cbr128_js", "l3_vbr_v2_48k", "l2_192_st" } do
+ for _, c in MC do
+ if c.name == name then
+ local b = buffer.fromstring(c.data)
+ local dec = assert(Mp3.open(Bytes.reader(b)))
+ local secs = dec.duration
+ local dt = bench("mp3 decode " .. name, 5, dec.frames * dec.channels * 4, function()
+ local d = assert(Mp3.open(Bytes.reader(b)))
+ d:readAll()
+ end)
+ print(string.format("%-8s %-30s %8.0fx real time", runtime, "", secs / dt))
+ end
+ end
+end
diff --git a/tools/bench.sh b/tools/bench.sh
index c5dea4a..fc2dc7b 100644
--- a/tools/bench.sh
+++ b/tools/bench.sh
@@ -3,7 +3,7 @@
cd "$(dirname "$0")/.." || exit 1
LUAU=${LUAU:-$(command -v luau || nix shell nixpkgs#luau -c sh -c 'command -v luau')}
LUAJIT=${LUAJIT:-$(command -v luajit || nix shell nixpkgs#luajit -c sh -c 'command -v luajit')}
-python3 -I tools/fixtures.py deflate png > /dev/null || exit 1
+python3 -I tools/fixtures.py deflate png mp3 > /dev/null || exit 1
python3 -I tools/build.py luajit > /dev/null || exit 1
"$LUAU" --codegen -O2 tools/bench.luau
"$LUAJIT" -e 'package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path' build/luajit/tools/bench.lua
diff --git a/tools/fixtures/mp3.py b/tools/fixtures/mp3.py
new file mode 100644
index 0000000..f69d502
--- /dev/null
+++ b/tools/fixtures/mp3.py
@@ -0,0 +1,75 @@
+# MP3 fixtures (tools/fixtures.py). Ported from mp3-luau tools/make_fixtures.sh + make_refs.py.
+# tests/gen/mp3_cases.luau the committed streams in tests/fixtures/mp3/ (made by ffmpeg's libmp3lame / mp2 encoders
+# from a synthetic test signal: tones, a chirp, noise, clicks) with their minimp3 reference
+# decodes (*.ref, from the minimp3 C harness: see the format below), plus streams lame
+# encodes here; each with ffmpeg's decode of three windows and its length.
+# .ref layout (little-endian): "MP3REF1\0", u32 hz, channels, frames, window frames W, window count N, then
+# N x (u32 start frame, W x channels f32), then u32 block size B, u32 block count, f64 sum of squares per block.
+import math, os, random, struct, tempfile
+
+INPUTS = ["tests/fixtures/mp3"]
+DIR = os.path.join("tests", "fixtures", "mp3")
+
+
+def ffmpeg_windows(ctx, data, ch, starts, W):
+ with tempfile.TemporaryDirectory() as tmp: # a file, not a pipe: ffmpeg applies the LAME gapless info only when it can seek
+ path = os.path.join(tmp, "in.mp3")
+ with open(path, "wb") as f:
+ f.write(data)
+ out = ctx.nix("ffmpeg", ["ffmpeg", "-v", "error", "-i", path, "-f", "f32le", "-ac", str(ch), "pipe:1"])
+ frames = len(out) // (4 * ch)
+ wins = []
+ for s in starts:
+ s = max(0, min(frames - W, s))
+ wins.append({"start": s, "pcm": out[s * ch * 4:(s + W) * ch * 4]})
+ return frames, wins
+
+
+def ref_windows(ref):
+ hz, ch, frames, W, N = struct.unpack_from("<5I", ref, 8)
+ p, starts = 28, []
+ for _ in range(N):
+ starts.append(struct.unpack_from("