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

260 lines
9.4 KiB
Luau

--!strict
--!optimize 2
-- audio/mp3: MPEG audio layers I-III (ISO/IEC 11172-3, 13818-3, MPEG-2.5); absorbed from mp3-luau c755bbf, a port of
-- minimp3 by lieff (CC0: licenses/minimp3-CC0.txt). Supports: every mode, CBR / VBR / free format, Xing / LAME gapless,
-- exact seeking, ID3v2 / ID3v1 tags; encode layers III / II (CBR). Not supported: MPEG-2 multichannel, CRC, VBR output.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Header = require("@rosetta/codecs/audio/Mpa/Header")
local Index = require("@rosetta/audio/mp3/Index")
local Tags = require("@rosetta/audio/mp3/Tags")
local Stream = require("@rosetta/audio/mp3/Stream")
local Encode3 = require("@rosetta/codecs/audio/Mpa/Encode3")
local Encode2 = require("@rosetta/codecs/audio/Mpa/Encode2")
local Pcm = require("@rosetta/codecs/audio/Pcm")
local Resample = require("@rosetta/codecs/audio/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", "Types", "codecs/audio/Pcm", "codecs/audio/Resample", "codecs/audio/Mpa/Header", "codecs/audio/Mpa/Core", "codecs/audio/Mpa/Encode3", "codecs/audio/Mpa/Encode2" },
caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, encodeLayers = { 2, 3 }, channels = 2 },
}
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
maxFrames: number?, -- default 2^31
}
export type Decoder = Stream.Decoder
export type EncodeOptions = {
layer: number?, -- 3 (MP3, default) or 2 (MP2)
bitrate: number?, -- bits per second, constant: one of the layer's rates (default 128000 for layer III, 192000 for
-- layer II; MPEG-2 / 2.5 rates: 64000 / 96000); values below 1000 are kbit/s (128 = 128000, the old unit)
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/audio/Resample)
resampleQuality: ("low" | "medium" | "high")?, -- codecs/audio/Resample quality (default "medium")
}
-- ------------------------------------------------------------------------------------------------ constants
local MAX_FRAMES = 2 ^ 31
-- ------------------------------------------------------------------------------------------------ sniff
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
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" },
}
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
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 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 type(bitrate) == "number" and bitrate >= 1000 then
bitrate /= 1000
end
if not table.find(Enc.BITRATES[if mpeg1 then 1 else 2], bitrate) then
return nil, Err.new(Err.ARG, string.format("%s bit/s is not a layer %d bit rate at %d Hz", tostring(if type(o.bitrate) == "number" and o.bitrate < 1000 then o.bitrate * 1000 else o.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
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
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
return Mp3