- core/Err.from(message, offset?, kind?): the private-submodule -> Err plumbing (a kind, or a 'code: ' prefix / 'truncated' / 'past the end' in the message) that Brotli, Bzip2, Zstd, Jpeg, WOFF2, FBX, plist, msgpack and bmfont each wrote. - core/Sniff (new): Sniff.text(r, n, trim?) (the start of a text file without its BOM), Sniff.dropBom(s), Sniff.magic(r, s); 13 text formats' sniff / decode BOM handling goes through it. - codecs/Pcm.drain(dec, source?, maxFrames?): a format's decode() through its open(); the collect-the-Decoder loops of aac, aiff, au, caf, flac, m4a, mp3, opus, vorbis and wav are one call each. - core/Bits.msbPut: the MSB-first bit writer the MP3 / MP2 / FLAC encoders each copied. - tools/lint_rules.py DUP: a function body of 12+ code lines repeated token for token in another module fails. - tools/move.py: moves a module and rewrites every reference (requires, deps, headers, fixture INPUTS, docs). - tools/fixtures/zstd.py: the incompressible corpus is smaller (zstd.luau 15.1 -> 13.4 MB; every fixture module is now under 14.3 MB). - tools/bench.luau: MPEG-1 also runs with the api's LuaJIT trace limits; the sections that compare tuned / default limits set them explicitly (jitTune), so the order of sections no longer leaks the tuning.
273 lines
11 KiB
Luau
273 lines
11 KiB
Luau
--!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). 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; input at rates the layer cannot hold is resampled (codecs/Resample). Not supported: MPEG-2 multichannel
|
|
-- extension, CRC checks, VBR / Xing output.
|
|
--
|
|
-- 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")
|
|
local Encode3 = require("@formats/audio/mp3/Encode3")
|
|
local Encode2 = require("@formats/audio/mp3/Encode2")
|
|
local Pcm = require("@formats/codecs/Pcm")
|
|
local Resample = require("@formats/codecs/Resample")
|
|
|
|
-- ------------------------------------------------------------------------------------------------ contract
|
|
local Mp3 = {
|
|
name = "mp3",
|
|
category = "audio",
|
|
extensions = { "mp3", "mp2", "mp1", "mpga" },
|
|
mime = { "audio/mpeg", "audio/mp3", "audio/mpa" },
|
|
deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "codecs/Pcm", "codecs/Resample" },
|
|
caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, encodeLayers = { 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
|
|
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)
|
|
sampleRate: number?, -- output rate (one the layer holds); default the input rate if possible, else the nearest
|
|
-- higher one (input at other rates is resampled through codecs/Resample)
|
|
resampleQuality: ("low" | "medium" | "high")?, -- codecs/Resample quality (default "medium")
|
|
}
|
|
|
|
-- ------------------------------------------------------------------------------------------------ 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, derr = Pcm.drain(dec, { format = "mp3", layer = dec.layer, version = dec.version, bitrate = dec.bitrate, vbr = dec.vbr })
|
|
if a and a.frames < dec.frames then
|
|
return nil, Err.new(Err.CORRUPT, string.format("decoded %d of %d frames", a.frames, dec.frames))
|
|
end
|
|
return a, derr
|
|
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
|
|
-- the output rate: opts.sampleRate, else the input's when the layer has it, else the nearest rate above it (else
|
|
-- the highest); other input rates go through codecs/Resample
|
|
local rate = o.sampleRate or src.sampleRate
|
|
if o.sampleRate and not Enc.RATES[o.sampleRate] then
|
|
return nil, Err.new(Err.ARG, string.format("layer %d cannot hold %s Hz", layer, tostring(o.sampleRate)))
|
|
end
|
|
if not Enc.RATES[rate] then
|
|
local best, top = nil, 0
|
|
for r in Enc.RATES do
|
|
top = math.max(top, r)
|
|
if r >= rate and (best == nil or r < best) then
|
|
best = r
|
|
end
|
|
end
|
|
rate = best or top
|
|
end
|
|
if rate ~= src.sampleRate then
|
|
local rs, rerr = Resample.source(src, rate, { quality = o.resampleQuality })
|
|
if not rs then
|
|
return nil, Err.new(Err.ARG, tostring(rerr))
|
|
end
|
|
src = rs
|
|
end
|
|
local info = Enc.RATES[rate]
|
|
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, rate))
|
|
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, date, 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
|