Files
rosetta/src/Formats/audio/mp3/init.luau
T

131 lines
5.4 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). 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