New shared modules under codecs/audio/Aac: Sbr (bitstream, band tables, delta decoding), SbrBits, SbrQmf (32-band analysis / 64-band synthesis QMF through DCT-IV), SbrHf (HF generation and adjustment), Ps (baseline PS), SbrTables (ISO tables, from syom 0.8.1, MIT). Explicit signalling enables SBR at construction; implicit SBR / PS is found by Decoder:probe / Aac.probeFrames. audio/aac and audio/m4a report the output rate and take opts.sbr = false for the core only; m4a scales iTunSMPB by the media tick. Outside the folder: containers/AudioWrap writes an AAC-LC ADTS header for HE-AAC AudioSpecificConfigs (the decoder finds SBR in the stream); the api's default openAudio hook forwards opts.sbr.
342 lines
11 KiB
Luau
342 lines
11 KiB
Luau
--!strict
|
|
--!optimize 2
|
|
-- audio/m4a: MPEG-4 audio (M4A / M4B / MP4 / MOV audio tracks) via containers/IsoBmff. Supports: AAC-LC, HE-AAC /
|
|
-- HE-AACv2 (explicit or implicit SBR / PS; opts.sbr = false keeps the AAC-LC core), ALAC, edit-list gapless trimming,
|
|
-- seeking, iTunes tags and cover art; encode ALAC (16 / 20 / 24-bit, 1-8 channels). Not supported: writing AAC, other codecs in MP4 (UNSUPPORTED), encrypted files.
|
|
|
|
-- ------------------------------------------------------------------------------------------------ requires
|
|
local Err = require("@rosetta/core/Err")
|
|
local Bytes = require("@rosetta/core/Bytes")
|
|
local Types = require("@rosetta/Types")
|
|
local Pcm = require("@rosetta/codecs/audio/Pcm")
|
|
local Stream = require("@rosetta/codecs/audio/Stream")
|
|
local IsoBmff = require("@rosetta/containers/IsoBmff")
|
|
local Aac = require("@rosetta/codecs/audio/Aac")
|
|
local Alac = require("@rosetta/codecs/audio/Alac")
|
|
|
|
-- ------------------------------------------------------------------------------------------------ contract
|
|
local M4a = {
|
|
name = "m4a",
|
|
category = "audio",
|
|
extensions = { "m4a", "m4b", "m4r" },
|
|
mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" },
|
|
deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/audio/Aac", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream" },
|
|
caps = { decode = true, encode = true, codecs = { "aac", "alac" }, encodeCodecs = { "alac" }, tags = true, streaming = true },
|
|
}
|
|
|
|
-- ------------------------------------------------------------------------------------------------ types
|
|
export type DecodeOptions = {
|
|
track: number?, -- the track id to play (default: the first AAC / ALAC track)
|
|
gapless: boolean?, -- apply the edit list (default true)
|
|
maxSamples: number?, -- default 2^25
|
|
sbr: boolean?, -- false: decode only the AAC-LC core of HE-AAC (half rate, faster); default true
|
|
}
|
|
export type EncodeOptions = {
|
|
bitDepth: number?, -- 16 (default), 20 or 24
|
|
frameLength: number?, -- samples per packet, default 4096
|
|
tags: Types.Tags?, -- default: the audio's tags
|
|
pictures: { { mime: string, data: buffer } }?, -- default: audio.meta.pictures
|
|
}
|
|
|
|
-- ------------------------------------------------------------------------------------------------ constants
|
|
local AUDIO_BRANDS: { [string]: number } = { ["M4A "] = 1, ["M4B "] = 1, ["M4P "] = 1, ["M4V "] = 0.3 }
|
|
|
|
-- ------------------------------------------------------------------------------------------------ sniff
|
|
function M4a.sniff(r: Bytes.Reader): number
|
|
local brand = IsoBmff.sniff(r)
|
|
if brand == nil then
|
|
return 0
|
|
end
|
|
if AUDIO_BRANDS[brand] then
|
|
return AUDIO_BRANDS[brand]
|
|
end
|
|
if brand == "avif" or brand == "avis" or brand == "heic" or brand == "heix" or brand == "mif1" or brand == "msf1" or brand == "crx " then
|
|
return 0
|
|
end
|
|
return 0.4 -- an MP4 / MOV that may hold audio; a video format claims it more strongly
|
|
end
|
|
|
|
-- ------------------------------------------------------------------------------------------------ decode
|
|
type PacketDecoder = {
|
|
channels: number,
|
|
sampleRate: number,
|
|
frameSize: number,
|
|
pcm: { number },
|
|
decode: (buf: buffer, off: number, len: number) -> (number?, Err.Err?),
|
|
reset: () -> (),
|
|
sbr: boolean?,
|
|
}
|
|
|
|
local function packetDecoder(t: IsoBmff.Track, buf: buffer, sbr: boolean?): (PacketDecoder?, Err.Err?)
|
|
if not t.config then
|
|
return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " (" .. t.codec .. ") has no codec configuration")
|
|
end
|
|
if t.codec == "alac" then
|
|
local cfg, err = Alac.config(t.config :: buffer)
|
|
if not cfg then
|
|
return nil, err
|
|
end
|
|
local dec = Alac.decoder(cfg)
|
|
local pcm = table.create(cfg.frameLength * cfg.channels, 0)
|
|
local scale = 1 / 2 ^ (cfg.bitDepth - 1)
|
|
local pd: PacketDecoder = {
|
|
channels = cfg.channels,
|
|
sampleRate = if cfg.sampleRate > 0 then cfg.sampleRate else (t.sampleRate or 44100),
|
|
frameSize = cfg.frameLength,
|
|
pcm = pcm,
|
|
decode = function(buf: buffer, off: number, len: number): (number?, Err.Err?)
|
|
local n, e = dec:decode(buf, off, len)
|
|
if not n then
|
|
return nil, e
|
|
end
|
|
local src = dec.pcm
|
|
for i = 1, n * cfg.channels do
|
|
pcm[i] = src[i] * scale
|
|
end
|
|
return n, nil
|
|
end,
|
|
reset = function() end,
|
|
}
|
|
return pd, nil
|
|
elseif t.codec == "aac" then
|
|
local dec, err = Aac.decoder(t.config :: buffer, { sbr = sbr })
|
|
if not dec then
|
|
return nil, err
|
|
end
|
|
local d = dec :: Aac.Decoder
|
|
if Aac.probeFrames(d, buf, t.offsets, t.sizes) then
|
|
d:reset()
|
|
end
|
|
local pd: PacketDecoder = {
|
|
channels = d.channels,
|
|
sampleRate = d.sampleRate,
|
|
frameSize = d.frameLength,
|
|
pcm = d.pcm,
|
|
decode = function(buf: buffer, off: number, len: number): (number?, Err.Err?)
|
|
return d:decode(buf, off, len)
|
|
end,
|
|
reset = function()
|
|
d:reset()
|
|
end,
|
|
sbr = d.sbrOutput,
|
|
}
|
|
return pd, nil
|
|
end
|
|
return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. t.codec .. " in MP4")
|
|
end
|
|
|
|
function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
|
|
local o: DecodeOptions = opts or {}
|
|
local movie, err = IsoBmff.parse(r, { maxSamples = o.maxSamples })
|
|
if not movie then
|
|
return nil, err
|
|
end
|
|
local track: IsoBmff.Track? = nil
|
|
local other: IsoBmff.Track? = nil
|
|
for _, t in movie.tracks do
|
|
if t.kind == "audio" then
|
|
if o.track and t.id ~= o.track then
|
|
continue
|
|
end
|
|
if t.codec == "aac" or t.codec == "alac" then
|
|
track = t
|
|
break
|
|
end
|
|
other = other or t
|
|
end
|
|
end
|
|
if not track then
|
|
if other then
|
|
return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. other.codec .. " in MP4")
|
|
end
|
|
return nil, Err.new(Err.CORRUPT, "no audio track")
|
|
end
|
|
local t = track :: IsoBmff.Track
|
|
local pd, perr = packetDecoder(t, r.buf, o.sbr)
|
|
if not pd then
|
|
return nil, perr
|
|
end
|
|
local p = pd :: PacketDecoder
|
|
local channels, sr = p.channels, p.sampleRate
|
|
local tickScale = sr / t.timescale
|
|
local gapless = o.gapless ~= false
|
|
local skip = if gapless then math.floor(t.skip * tickScale + 0.5) else 0
|
|
local total = 0
|
|
for i = 1, t.sampleCount do
|
|
total += t.durations[i]
|
|
end
|
|
total = math.floor(total * tickScale + 0.5)
|
|
if gapless and t.playDuration then
|
|
total = math.min(total, skip + math.floor(t.playDuration * tickScale + 0.5))
|
|
end
|
|
local tags, pictures = IsoBmff.tags(r, movie)
|
|
-- iTunes gapless info (fdkaac, iTunes) when there is no edit list: " 0 <priming> <padding> <samples> ..." (hex)
|
|
local smpb = tags.itunsmpb
|
|
if gapless and not t.edits and smpb then
|
|
local f: { number } = {}
|
|
for w in string.gmatch(smpb, "%x+") do
|
|
table.insert(f, tonumber(w, 16) :: number)
|
|
end
|
|
-- in media ticks (the core rate of HE-AAC, as ffmpeg reads it)
|
|
local pre, len = math.floor((f[2] or 0) * tickScale + 0.5), math.floor((f[4] or 0) * tickScale + 0.5)
|
|
if #f >= 4 and len > 0 and pre + len <= total then
|
|
skip = pre
|
|
total = pre + len
|
|
end
|
|
end
|
|
local frames = math.max(0, total - skip)
|
|
local buf = r.buf
|
|
local dec: any = {
|
|
sampleRate = sr,
|
|
channels = channels,
|
|
frames = frames,
|
|
duration = frames / sr,
|
|
bitrate = 0,
|
|
tags = tags,
|
|
pictures = pictures,
|
|
codec = t.codec,
|
|
track = t,
|
|
movie = movie,
|
|
}
|
|
local bytes = 0
|
|
for i = 1, t.sampleCount do
|
|
bytes += t.sizes[i]
|
|
end
|
|
dec.bitrate = if frames > 0 then math.floor(bytes * 8 * sr / frames) else (t.bitrate or 0)
|
|
-- packet start frames (media ticks -> frames); one AAC packet of pre-roll for the overlap when seeking
|
|
return Stream.packets(dec, {
|
|
count = t.sampleCount,
|
|
start = function(i: number): number
|
|
return math.floor((t.dts[i] or (t.dts[t.sampleCount] or 0) + (t.durations[t.sampleCount] or 0)) * tickScale + 0.5)
|
|
end,
|
|
decode = function(i: number): (number?, Err.Err?)
|
|
return p.decode(buf, t.offsets[i], t.sizes[i])
|
|
end,
|
|
pcm = function(): { number }
|
|
return p.pcm
|
|
end,
|
|
reset = p.reset,
|
|
skip = skip,
|
|
stop = total,
|
|
preroll = if p.sbr then 3 elseif t.codec == "aac" then 1 else 0,
|
|
cumulative = true,
|
|
})
|
|
end
|
|
|
|
function M4a.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
|
|
local dec, err = M4a.open(r, opts)
|
|
if not dec then
|
|
return nil, err
|
|
end
|
|
local d: any = dec
|
|
local audio, derr = Pcm.drain(d, { format = "m4a", codec = d.codec, bitsPerSample = d.track.bitsPerSample, brand = d.movie.brand })
|
|
if audio and #d.pictures > 0 then
|
|
audio.meta.pictures = d.pictures
|
|
end
|
|
return audio, derr
|
|
end
|
|
|
|
-- ------------------------------------------------------------------------------------------------ encode
|
|
function M4a.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
|
local o: EncodeOptions = opts or {}
|
|
if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then
|
|
return nil, Err.new(Err.ARG, "expected an Audio or a Decoder")
|
|
end
|
|
local sr, ch = value.sampleRate, value.channels
|
|
local enc, eerr = Alac.encoder({ sampleRate = sr, channels = ch, bitDepth = o.bitDepth or 16, frameLength = o.frameLength })
|
|
if not enc then
|
|
return nil, eerr
|
|
end
|
|
local e = enc :: Alac.Encoder
|
|
local depth = e.config.bitDepth
|
|
local fl = e.config.frameLength
|
|
local peak = 2 ^ (depth - 1)
|
|
local packets: { buffer } = {}
|
|
local durations: { number } = {}
|
|
local ints = table.create(fl * ch, 0)
|
|
local floor = math.floor
|
|
local readf32 = buffer.readf32
|
|
local src: buffer, srcFrames = nil :: any, 0
|
|
local isAudio = value.kind == "audio" and type(value.samples) == "buffer"
|
|
if isAudio then
|
|
src, srcFrames = value.samples, value.frames
|
|
if buffer.len(src) < srcFrames * ch * 4 then
|
|
return nil, Err.new(Err.ARG, "audio.samples is shorter than frames * channels")
|
|
end
|
|
elseif type(value.read) ~= "function" then
|
|
return nil, Err.new(Err.ARG, "expected an Audio or a Decoder")
|
|
end
|
|
local done = 0
|
|
local chunk: buffer? = nil
|
|
while true do
|
|
local n, b, base
|
|
if isAudio then
|
|
n = math.min(fl, srcFrames - done)
|
|
b, base = src, done * ch * 4
|
|
else
|
|
local got
|
|
b, got = value:read(fl, chunk)
|
|
chunk = b
|
|
n, base = got, 0
|
|
end
|
|
if n <= 0 then
|
|
break
|
|
end
|
|
for i = 0, n * ch - 1 do
|
|
local v = floor(readf32(b, base + i * 4) * peak + 0.5)
|
|
if v >= peak then
|
|
v = peak - 1
|
|
elseif v < -peak then
|
|
v = -peak
|
|
end
|
|
ints[i + 1] = v
|
|
end
|
|
local pkt, perr = e:encode(ints, 1, n)
|
|
if not pkt then
|
|
return nil, perr
|
|
end
|
|
table.insert(packets, pkt)
|
|
table.insert(durations, n)
|
|
done += n
|
|
if isAudio and done >= srcFrames then
|
|
break
|
|
end
|
|
end
|
|
local tags = o.tags or value.tags or {}
|
|
local pictures = o.pictures or (value.meta and value.meta.pictures) or nil
|
|
local timescale = if sr < 65536 then sr else 0
|
|
local file, merr = IsoBmff.mux({
|
|
brand = "M4A ",
|
|
minor = 0,
|
|
compatible = { "M4A ", "mp42", "isom" },
|
|
timescale = 1000,
|
|
tracks = {
|
|
{
|
|
kind = "audio",
|
|
entry = "alac",
|
|
timescale = if timescale > 0 then timescale else 48000,
|
|
samples = packets,
|
|
durations = if timescale > 0 then durations else (function()
|
|
local d = {}
|
|
for i, v in durations do
|
|
d[i] = math.floor(v * 48000 / sr + 0.5)
|
|
end
|
|
return d
|
|
end)(),
|
|
sampleRate = sr,
|
|
channels = ch,
|
|
bitsPerSample = depth,
|
|
config = Alac.cookie(e.config),
|
|
},
|
|
},
|
|
tags = tags,
|
|
pictures = pictures,
|
|
})
|
|
if not file then
|
|
return nil, merr
|
|
end
|
|
return file, nil
|
|
end
|
|
|
|
return M4a
|