442 lines
14 KiB
Luau
442 lines
14 KiB
Luau
--!strict
|
|
-- audio/m4a: MPEG-4 audio files (M4A / M4B / MP4 / MOV audio tracks) through containers/IsoBmff. Supports: reading
|
|
-- AAC-LC (codecs/Aac; HE-AAC files play their AAC-LC core at the core rate) and ALAC (codecs/Alac) tracks, gapless
|
|
-- trimming through the edit list (encoder priming / padding), seeking, iTunes tags and cover art (dec.pictures);
|
|
-- writing ALAC (16 / 20 / 24-bit, 1 - 8 channels) with tags and cover art. Not supported: writing AAC, other codecs
|
|
-- inside MP4 (MP3 / Opus / FLAC / AC-3: UNSUPPORTED), encrypted files.
|
|
|
|
-- ------------------------------------------------------------------------------------------------ requires
|
|
local Err = require("@formats/core/Err")
|
|
local Bytes = require("@formats/core/Bytes")
|
|
local Types = require("@formats/Types")
|
|
local IsoBmff = require("@formats/containers/IsoBmff")
|
|
local Aac = require("@formats/codecs/Aac")
|
|
local Alac = require("@formats/codecs/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/Aac", "codecs/Alac" },
|
|
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?, -- sample table limit (default 2^25)
|
|
}
|
|
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 } }?, -- cover art (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
|
|
-- the packet decoder of a track: decode(buf, off, len) -> frames | nil, Err; pcm: interleaved floats
|
|
type PacketDecoder = {
|
|
channels: number,
|
|
sampleRate: number,
|
|
frameSize: number,
|
|
pcm: { number },
|
|
decode: (buf: buffer, off: number, len: number) -> (number?, Err.Err?),
|
|
reset: () -> (),
|
|
}
|
|
|
|
local function packetDecoder(t: IsoBmff.Track): (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)
|
|
if not dec then
|
|
return nil, err
|
|
end
|
|
local d = dec :: Aac.Decoder
|
|
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,
|
|
}
|
|
return pd, nil
|
|
end
|
|
return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. t.codec .. " in MP4")
|
|
end
|
|
|
|
-- open(r, opts?) -> Types.Decoder | nil, Err
|
|
function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
|
|
local o = 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)
|
|
if not pd then
|
|
return nil, perr
|
|
end
|
|
local p = pd :: PacketDecoder
|
|
local channels, sr = p.channels, p.sampleRate
|
|
-- media ticks -> sample frames
|
|
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 = {}
|
|
for w in string.gmatch(smpb, "%x+") do
|
|
table.insert(f, tonumber(w, 16))
|
|
end
|
|
if #f >= 4 and f[2] and f[4] and f[4] > 0 and f[2] + f[4] <= total then
|
|
skip = f[2]
|
|
total = f[2] + f[4]
|
|
end
|
|
end
|
|
local frames = math.max(0, total - skip)
|
|
local buf = r.buf
|
|
-- streaming state
|
|
local nextPacket = 1
|
|
local decoded = 0 -- frames produced by the packets decoded so far (before trimming)
|
|
local pend, pendPos, pendN = p.pcm, 0, 0 -- the current packet: frames pendPos .. pendN - 1 not yet returned
|
|
local dropUntil = skip -- absolute frame index of the first frame to return
|
|
local stopAt = total
|
|
local pos = 0 -- frames returned
|
|
local failed: Err.Err? = nil
|
|
|
|
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,
|
|
error = nil,
|
|
}
|
|
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)
|
|
|
|
-- decode the next packet into pend; false at the end / on an error
|
|
local function fill(): boolean
|
|
while true do
|
|
if nextPacket > t.sampleCount or decoded >= stopAt then
|
|
return false
|
|
end
|
|
local i = nextPacket
|
|
nextPacket += 1
|
|
local start = decoded
|
|
local n, e = p.decode(buf, t.offsets[i], t.sizes[i])
|
|
if not n then
|
|
failed = e
|
|
dec.error = e
|
|
return false
|
|
end
|
|
decoded += n
|
|
-- the part of this packet inside [dropUntil, stopAt)
|
|
local a = math.max(start, dropUntil)
|
|
local b = math.min(decoded, stopAt)
|
|
if b > a then
|
|
pendPos = a - start
|
|
pendN = b - start
|
|
return true
|
|
end
|
|
end
|
|
end
|
|
|
|
function dec.read(_self: any, n: number, out: buffer?): (buffer, number)
|
|
local want = math.max(0, math.floor(n))
|
|
local need = want * channels * 4
|
|
local ob = if out and buffer.len(out) >= need then out else buffer.create(need)
|
|
local got = 0
|
|
local writef32 = buffer.writef32
|
|
while got < want do
|
|
if pendPos >= pendN then
|
|
if failed or not fill() then
|
|
break
|
|
end
|
|
end
|
|
local take = math.min(want - got, pendN - pendPos)
|
|
local src = pend
|
|
local o = got * channels * 4
|
|
local s = pendPos * channels
|
|
for k = 1, take * channels do
|
|
writef32(ob, o, src[s + k])
|
|
o += 4
|
|
end
|
|
pendPos += take
|
|
got += take
|
|
end
|
|
pos += got
|
|
return ob, got
|
|
end
|
|
|
|
function dec.seek(_self: any, seconds: number)
|
|
local target = math.clamp(math.floor(seconds * sr + 0.5), 0, frames) + skip -- absolute frame
|
|
-- the last packet starting at or before the target, minus one for the codec's overlap (AAC)
|
|
local ticks = target / tickScale
|
|
local lo, hi, found = 1, t.sampleCount, 1
|
|
while lo <= hi do
|
|
local mid = (lo + hi) // 2
|
|
if t.dts[mid] <= ticks then
|
|
found = mid
|
|
lo = mid + 1
|
|
else
|
|
hi = mid - 1
|
|
end
|
|
end
|
|
local startPacket = if t.codec == "aac" then math.max(1, found - 1) else found
|
|
p.reset()
|
|
nextPacket = startPacket
|
|
decoded = math.floor((t.dts[startPacket] or 0) * tickScale + 0.5)
|
|
dropUntil = math.max(target, skip)
|
|
pendPos, pendN = 0, 0
|
|
failed = nil
|
|
pos = target - skip
|
|
end
|
|
|
|
function dec.position(_self: any): number
|
|
return pos / sr
|
|
end
|
|
|
|
-- prime: surface a broken first packet as an open error
|
|
if t.sampleCount > 0 and frames > 0 then
|
|
if not fill() and failed then
|
|
return nil, failed
|
|
end
|
|
end
|
|
return dec, nil
|
|
end
|
|
|
|
-- decode(r, opts?) -> Types.Audio | nil, Err (the whole stream, tags, cover pictures in meta.pictures)
|
|
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 = Types.Audio.new(d.sampleRate, d.channels, d.frames)
|
|
local done = 0
|
|
local chunk = buffer.create(65536 * d.channels * 4)
|
|
while done < d.frames do
|
|
local b, n = d:read(math.min(65536, d.frames - done), chunk)
|
|
if n == 0 then
|
|
break
|
|
end
|
|
buffer.copy(audio.samples, done * d.channels * 4, b, 0, n * d.channels * 4)
|
|
done += n
|
|
end
|
|
if d.error then
|
|
return nil, d.error
|
|
end
|
|
if done < d.frames then
|
|
local short = buffer.create(done * d.channels * 4)
|
|
buffer.copy(short, 0, audio.samples, 0, buffer.len(short))
|
|
audio.samples = short
|
|
audio.frames = done
|
|
end
|
|
audio.tags = d.tags
|
|
audio.meta.source = { format = "m4a", codec = d.codec, bitsPerSample = d.track.bitsPerSample, brand = d.movie.brand }
|
|
if #d.pictures > 0 then
|
|
audio.meta.pictures = d.pictures
|
|
end
|
|
return audio, nil
|
|
end
|
|
|
|
-- ------------------------------------------------------------------------------------------------ encode
|
|
-- encode(audio | decoder, opts?) -> buffer | nil, Err: an ALAC M4A
|
|
function M4a.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
|
local o = 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
|
|
-- frames from an Audio buffer or a streaming Decoder
|
|
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
|