ws-audio: MP3 layer III encoder (Encode3: shine-style CBR, MPEG-1/2/2.5, mono/stereo/joint MS, global-gain rate loop, region/table choice, count1 A/B) + MP2 layer II encoder (Encode2: standard alloc tables, greedy noise allocation, grouping), shared polyphase Analysis, EncTables (PDMP3 public-domain window + Huffman trees -> codeword tables); mp3 init encode() with ID3v2.4; fixtures decode with ffmpeg + lame (no errors, SNR floors); bench lines

This commit is contained in:
4DBug committed 2026-10-31 09:18:23 -05:00
1 parent 3f2be59a65
commit 929b5d6d53
14 files changed
+1859 -12

No files matched your search

+124 -4
View File
@@ -4,8 +4,9 @@
-- 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.
-- Float output (minimp3's MINIMP3_FLOAT_OUTPUT scalar path). Encode (ws-audio, audio/mp3/Encode3 + Encode2): layer III
-- (shine-style CBR, MPEG-1 / 2 / 2.5) and layer II (MPEG-1 / 2), mono / stereo / joint stereo, an ID3v2.4 tag from
-- the tags. Not supported: MPEG-2 multichannel extension, CRC checks, VBR / Xing output, encoder resampling.
--
-- 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())
@@ -19,6 +20,9 @@ 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")
local Encode3 = require("@formats/audio/mp3/Encode3")
local Encode2 = require("@formats/audio/mp3/Encode2")
local Pcm = require("@formats/codecs/Pcm")
-- ------------------------------------------------------------------------------------------------ contract
local Mp3 = {
@@ -26,8 +30,8 @@ local 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 },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 },
}
-- ------------------------------------------------------------------------------------------------ types
@@ -35,6 +39,13 @@ export type OpenOptions = {
maxFrames: number?, -- refuse streams longer than this many sample frames per channel (default 2^31)
}
export type Decoder = Stream.Decoder
export type EncodeOptions = {
layer: number?, -- 3 (MP3, default) or 2 (MP2)
bitrate: number?, -- kbps, constant (default 128 for layer III, 192 for layer II; MPEG-2 / 2.5 rates: 64 / 96)
mode: ("stereo" | "joint" | "mono")?, -- default "joint" (mid / side) for stereo layer III, "stereo" for layer II,
-- "mono" for mono input; layer II has no joint stereo (intensity) and writes "joint" as "stereo"
id3: boolean?, -- write an ID3v2.4 tag from the tags (default true when there are tags)
}
-- ------------------------------------------------------------------------------------------------ constants
local MAX_FRAMES = 2 ^ 31
@@ -85,6 +96,115 @@ function Mp3.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err
return a, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local ID3_FRAMES = {
{ "title", "TIT2" },
{ "artist", "TPE1" },
{ "album", "TALB" },
{ "albumArtist", "TPE2" },
{ "year", "TDRC" },
{ "date", "TDRC" },
{ "track", "TRCK" },
{ "genre", "TCON" },
{ "composer", "TCOM" },
}
-- an ID3v2.4 tag (UTF-8 text frames + a COMM frame) | nil when there is nothing to write
local function id3Tag(tags: { [string]: any }): buffer?
local w = Bytes.writer(256)
local seen: { [string]: boolean } = {}
local function syncsafe(v: number)
w:u8((v // 2097152) % 128)
w:u8((v // 16384) % 128)
w:u8((v // 128) % 128)
w:u8(v % 128)
end
for _, f in ID3_FRAMES do
local v = tags[f[1]]
if type(v) == "string" and #v > 0 and not seen[f[2]] then
seen[f[2]] = true
w:string(f[2])
syncsafe(#v + 1)
w:u16be(0)
w:u8(3) -- UTF-8
w:string(v)
end
end
if type(tags.comment) == "string" and #tags.comment > 0 then
local v = tags.comment
w:string("COMM")
syncsafe(#v + 5)
w:u16be(0)
w:u8(3)
w:string("eng")
w:u8(0) -- empty description
w:string(v)
end
local body = w:finish()
if buffer.len(body) == 0 then
return nil
end
local out = Bytes.writer(buffer.len(body) + 10)
out:string("ID3")
out:u8(4)
out:u8(0)
out:u8(0)
local n = buffer.len(body)
out:u8((n // 2097152) % 128)
out:u8((n // 16384) % 128)
out:u8((n // 128) % 128)
out:u8(n % 128)
out:bytes(body)
return out:finish()
end
-- encode(audioOrDecoder, opts?) -> an MP3 (layer III) or MP2 (layer II) file | nil, Err
function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local src, serr = Pcm.source(value)
if not src then
return nil, serr
end
local o: EncodeOptions = opts or {}
local layer = o.layer or 3
if layer ~= 2 and layer ~= 3 then
return nil, Err.new(Err.ARG, "layer must be 2 or 3")
end
local Enc = if layer == 3 then Encode3 else Encode2
local info = Enc.RATES[src.sampleRate]
if not info then
return nil, Err.new(Err.ARG, string.format("layer %d cannot hold %s Hz (no resampling)", layer, tostring(src.sampleRate)))
end
local mpeg1 = info[1] == 3
local mode = o.mode or (if src.channels == 1 then "mono" elseif layer == 3 then "joint" else "stereo")
if mode ~= "stereo" and mode ~= "joint" and mode ~= "mono" then
return nil, Err.new(Err.ARG, "mode must be stereo, joint or mono")
end
if src.channels > 2 then
return nil, Err.new(Err.ARG, "MPEG audio holds 1 or 2 channels")
end
if layer == 2 and mode == "joint" then
mode = "stereo"
end
local bitrate = o.bitrate or (if mpeg1 then (if layer == 3 then 128 else 192) else (if layer == 3 then 64 else 96))
if not table.find(Enc.BITRATES[if mpeg1 then 1 else 2], bitrate) then
return nil, Err.new(Err.ARG, string.format("%s kbps is not a layer %d bit rate at %d Hz", tostring(bitrate), layer, src.sampleRate))
end
if layer == 2 and mpeg1 then
-- the standard's allowed bit rate / mode combinations
if mode == "mono" and bitrate > 192 then
return nil, Err.new(Err.ARG, "layer II mono is at most 192 kbps")
elseif mode ~= "mono" and (bitrate == 32 or bitrate == 48 or bitrate == 56 or bitrate == 80) then
return nil, Err.new(Err.ARG, "layer II stereo needs 64 kbps or more (and not 80)")
end
end
local prefix = if o.id3 == false then nil else id3Tag(src.tags)
local out, msg = Enc.encode(src :: any, { bitrate = bitrate, mode = mode, prefix = prefix })
if not out then
return nil, Err.new(Err.ARG, tostring(msg))
end
return out, 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 }