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.
509 lines
15 KiB
Luau
509 lines
15 KiB
Luau
--!strict
|
|
-- containers/AudioWrap: a video container's audio track as a stream an audio format reads (a format never requires
|
|
-- another). New in rosetta. PCM / WAVEFORMATEX -> WAV, adpcm_swf -> f32 WAV, mp1-3 / ac3 -> frames back to back,
|
|
-- flac -> fLaC + metadata blocks, opus / vorbis -> Ogg, aac -> ADTS. E-AC-3 is UNSUPPORTED.
|
|
local Err = require("@rosetta/core/Err")
|
|
local Bytes = require("@rosetta/core/Bytes")
|
|
local Types = require("@rosetta/Types")
|
|
local Mux = require("@rosetta/containers/Ogg/Mux")
|
|
local Adpcm = require("@rosetta/codecs/audio/Adpcm")
|
|
|
|
local AudioWrap = {}
|
|
|
|
type PacketSource = {
|
|
count: ((self: any, track: number) -> number)?,
|
|
get: ((self: any, track: number, k: number) -> Types.Packet?)?,
|
|
}
|
|
|
|
local function allPackets(dmx: PacketSource, track: Types.Track): { Types.Packet }
|
|
local out: { Types.Packet } = {}
|
|
local n = if dmx.count then dmx:count(track.id) else 0
|
|
if n > 0 and dmx.get then
|
|
for k = 1, n do
|
|
local p = dmx:get(track.id, k)
|
|
if p then
|
|
table.insert(out, p)
|
|
end
|
|
end
|
|
end
|
|
return out
|
|
end
|
|
|
|
local function concat(packets: { Types.Packet }, prefix: buffer?): buffer
|
|
local total = if prefix then buffer.len(prefix) else 0
|
|
for _, p in packets do
|
|
total += buffer.len(p.data)
|
|
end
|
|
local out = buffer.create(total)
|
|
local o = 0
|
|
if prefix then
|
|
buffer.copy(out, 0, prefix)
|
|
o = buffer.len(prefix)
|
|
end
|
|
for _, p in packets do
|
|
buffer.copy(out, o, p.data)
|
|
o += buffer.len(p.data)
|
|
end
|
|
return out
|
|
end
|
|
|
|
local PCM: { [string]: { number } } = { -- tag, bits, bytes swapped (big-endian source)
|
|
pcm_u8 = { 1, 8, 0 },
|
|
pcm_s8 = { 1, 8, 0 },
|
|
pcm_s16le = { 1, 16, 0 },
|
|
pcm_s24le = { 1, 24, 0 },
|
|
pcm_s32le = { 1, 32, 0 },
|
|
pcm_s16be = { 1, 16, 1 },
|
|
pcm_s24be = { 1, 24, 1 },
|
|
pcm_s32be = { 1, 32, 1 },
|
|
pcm_f32le = { 3, 32, 0 },
|
|
pcm_f64le = { 3, 64, 0 },
|
|
pcm_f32be = { 3, 32, 1 },
|
|
pcm_f64be = { 3, 64, 1 },
|
|
pcm_alaw = { 6, 8, 0 },
|
|
pcm_mulaw = { 7, 8, 0 },
|
|
}
|
|
|
|
local function wav(fmt: buffer, data: buffer): buffer
|
|
local w = Bytes.writer(buffer.len(data) + buffer.len(fmt) + 64)
|
|
local fl = buffer.len(fmt)
|
|
local dl = buffer.len(data)
|
|
w:string("RIFF")
|
|
w:u32le(4 + 8 + fl + (fl % 2) + 8 + dl + (dl % 2))
|
|
w:string("WAVE")
|
|
w:string("fmt ")
|
|
w:u32le(fl)
|
|
w:bytes(fmt)
|
|
if fl % 2 == 1 then
|
|
w:u8(0)
|
|
end
|
|
w:string("data")
|
|
w:u32le(dl)
|
|
w:bytes(data)
|
|
if dl % 2 == 1 then
|
|
w:u8(0)
|
|
end
|
|
return w:finish()
|
|
end
|
|
|
|
local function pcmWav(track: Types.Track, packets: { Types.Packet }): (buffer?, Err.Err?)
|
|
local spec = PCM[track.codec]
|
|
local ch = track.channels or 1
|
|
local rate = math.floor((track.sampleRate or 0) + 0.5)
|
|
if ch < 1 or rate <= 0 then
|
|
return nil, Err.new(Err.CORRUPT, "PCM track without channels / sample rate")
|
|
end
|
|
local bits = spec[2]
|
|
local data = concat(packets)
|
|
if spec[3] == 1 then
|
|
local bps = bits // 8
|
|
for i = 0, buffer.len(data) - bps, bps do
|
|
for k = 0, bps // 2 - 1 do
|
|
local a, b = buffer.readu8(data, i + k), buffer.readu8(data, i + bps - 1 - k)
|
|
buffer.writeu8(data, i + k, b)
|
|
buffer.writeu8(data, i + bps - 1 - k, a)
|
|
end
|
|
end
|
|
end
|
|
if track.codec == "pcm_s8" then
|
|
for i = 0, buffer.len(data) - 1 do
|
|
buffer.writeu8(data, i, (buffer.readu8(data, i) + 128) % 256)
|
|
end
|
|
end
|
|
local f = Bytes.writer(16)
|
|
local align = ch * bits // 8
|
|
f:u16le(spec[1])
|
|
f:u16le(ch)
|
|
f:u32le(rate)
|
|
f:u32le(rate * align)
|
|
f:u16le(align)
|
|
f:u16le(bits)
|
|
return wav(f:finish(), data), nil
|
|
end
|
|
|
|
-- Flash ADPCM packets decode on their own (each starts with its code size and block headers): f32 samples in a WAV
|
|
local function swfWav(track: Types.Track, packets: { Types.Packet }): (buffer?, Err.Err?)
|
|
local ch = track.channels or 1
|
|
local rate = math.floor((track.sampleRate or 0) + 0.5)
|
|
if ch < 1 or ch > 2 or rate <= 0 then
|
|
return nil, Err.new(Err.CORRUPT, "Flash ADPCM track without channels / sample rate")
|
|
end
|
|
local frames = 0
|
|
for _, pk in packets do
|
|
frames += Adpcm.swfFrames(pk.data, 0, buffer.len(pk.data), ch)
|
|
end
|
|
local data = buffer.create(frames * ch * 4)
|
|
local d = 0
|
|
for _, pk in packets do
|
|
d += Adpcm.swf(pk.data, 0, buffer.len(pk.data), ch, data, d) * ch
|
|
end
|
|
local f = Bytes.writer(16)
|
|
f:u16le(3)
|
|
f:u16le(ch)
|
|
f:u32le(rate)
|
|
f:u32le(rate * ch * 4)
|
|
f:u16le(ch * 4)
|
|
f:u16le(32)
|
|
return wav(f:finish(), data), nil
|
|
end
|
|
|
|
-- the number of 48 kHz samples in an Opus packet (RFC 6716 section 3.1)
|
|
local function opusSamples(b: buffer): number
|
|
local n = buffer.len(b)
|
|
if n < 1 then
|
|
return 0
|
|
end
|
|
local toc = buffer.readu8(b, 0)
|
|
local config = toc // 8
|
|
local fs: number
|
|
if config < 12 then
|
|
fs = ({ 480, 960, 1920, 2880 })[config % 4 + 1]
|
|
elseif config < 16 then
|
|
fs = if config % 2 == 0 then 480 else 960
|
|
else
|
|
fs = ({ 120, 240, 480, 960 })[config % 4 + 1]
|
|
end
|
|
local c = toc % 4
|
|
local frames = if c == 0 then 1 elseif c == 3 then (if n >= 2 then buffer.readu8(b, 1) % 64 else 0) else 2
|
|
return fs * frames
|
|
end
|
|
|
|
local function opusHead(track: Types.Track): buffer
|
|
local c = track.config
|
|
if c and buffer.len(c) >= 19 and buffer.readstring(c, 0, 8) == "OpusHead" then
|
|
return c
|
|
end
|
|
local w = Bytes.writer(19)
|
|
w:string("OpusHead")
|
|
w:u8(1)
|
|
w:u8(math.clamp(track.channels or 2, 1, 2))
|
|
w:u16le(math.floor((track.codecDelay or 0) * 48000 + 0.5))
|
|
w:u32le(math.floor(track.sampleRate or 48000))
|
|
w:u16le(0)
|
|
w:u8(0)
|
|
return w:finish()
|
|
end
|
|
|
|
local function opusTags(): buffer
|
|
local w = Bytes.writer(32)
|
|
w:string("OpusTags")
|
|
local vendor = "rosetta"
|
|
w:u32le(#vendor)
|
|
w:string(vendor)
|
|
w:u32le(0)
|
|
return w:finish()
|
|
end
|
|
|
|
local function ogg(headers: { buffer }, packets: { Types.Packet }, granuleOf: (p: Types.Packet, i: number) -> number): buffer
|
|
local mux = Mux.new({ pageSize = 4096 })
|
|
local s = mux:stream(1)
|
|
for i, h in headers do
|
|
s:packet(h, 0, { flush = i == 1 or i == #headers })
|
|
end
|
|
for i, p in packets do
|
|
s:packet(p.data, granuleOf(p, i), { eos = i == #packets })
|
|
end
|
|
return mux:finish()
|
|
end
|
|
|
|
-- Matroska's Vorbis CodecPrivate: Xiph-laced headers (count - 1, sizes, data)
|
|
local function xiphHeaders(c: buffer): { buffer }?
|
|
local n = buffer.len(c)
|
|
if n < 3 then
|
|
return nil
|
|
end
|
|
local count = buffer.readu8(c, 0) + 1
|
|
local p = 1
|
|
local sizes = {}
|
|
local total = 0
|
|
for k = 1, count - 1 do
|
|
local s = 0
|
|
while true do
|
|
if p >= n then
|
|
return nil
|
|
end
|
|
local b = buffer.readu8(c, p)
|
|
p += 1
|
|
s += b
|
|
if b ~= 255 then
|
|
break
|
|
end
|
|
end
|
|
sizes[k] = s
|
|
total += s
|
|
end
|
|
sizes[count] = n - p - total
|
|
if sizes[count] < 0 then
|
|
return nil
|
|
end
|
|
local out = {}
|
|
for k = 1, count do
|
|
local b = buffer.create(sizes[k])
|
|
buffer.copy(b, 0, c, p, sizes[k])
|
|
p += sizes[k]
|
|
out[k] = b
|
|
end
|
|
return out
|
|
end
|
|
|
|
-- Vorbis packet sizes: the block sizes from the identification header and each mode's block flag from the end of the
|
|
-- setup header (read backwards from its framing bit: mode entries are 41 bits whose window / transform types are 0,
|
|
-- preceded by the 6-bit mode count), so the Ogg granules are exact: a packet yields (previous + current block) / 4
|
|
-- samples (the first one as if its previous block had its own size, as ffmpeg times it).
|
|
local function bit(b: buffer, k: number): number
|
|
return bit32.extract(buffer.readu8(b, k // 8), k % 8, 1)
|
|
end
|
|
local function bits(b: buffer, k: number, n: number): number
|
|
local v = 0
|
|
for i = n - 1, 0, -1 do
|
|
v = v * 2 + bit(b, k + i)
|
|
end
|
|
return v
|
|
end
|
|
|
|
local function vorbisModes(id: buffer, setup: buffer): ({ number }?, { boolean }?)
|
|
if buffer.len(id) < 30 or buffer.len(setup) < 8 then
|
|
return nil, nil
|
|
end
|
|
local bs = buffer.readu8(id, 28)
|
|
local sizes = { 2 ^ (bs % 16), 2 ^ (bs // 16) }
|
|
-- the framing bit: the highest set bit of the last non-zero byte
|
|
local last = buffer.len(setup) - 1
|
|
while last > 0 and buffer.readu8(setup, last) == 0 do
|
|
last -= 1
|
|
end
|
|
local v = buffer.readu8(setup, last)
|
|
local hb = 7
|
|
while hb > 0 and bit32.extract(v, hb, 1) == 0 do
|
|
hb -= 1
|
|
end
|
|
local f = last * 8 + hb
|
|
local flags: { boolean } = {}
|
|
local pos = f
|
|
while #flags < 64 and pos - 41 >= 7 * 8 do
|
|
local s0 = pos - 41
|
|
if bits(setup, s0 + 1, 16) ~= 0 or bits(setup, s0 + 17, 16) ~= 0 then
|
|
break
|
|
end
|
|
table.insert(flags, 1, bit(setup, s0) == 1)
|
|
pos = s0
|
|
end
|
|
-- the largest count whose 6-bit field matches
|
|
for n = #flags, 1, -1 do
|
|
local start = f - 41 * n
|
|
if start - 6 >= 0 and bits(setup, start - 6, 6) == n - 1 then
|
|
local out = {}
|
|
for i = #flags - n + 1, #flags do
|
|
table.insert(out, flags[i])
|
|
end
|
|
return sizes, out
|
|
end
|
|
end
|
|
return nil, nil
|
|
end
|
|
|
|
local function adts(track: Types.Track, packets: { Types.Packet }): (buffer?, Err.Err?)
|
|
local c = track.config
|
|
local profile, rateIndex, chanConfig
|
|
if c and buffer.len(c) >= 2 then
|
|
local b0, b1 = buffer.readu8(c, 0), buffer.readu8(c, 1)
|
|
profile = b0 // 8 -- audio object type
|
|
rateIndex = (b0 % 8) * 2 + b1 // 128
|
|
chanConfig = (b1 // 8) % 16
|
|
-- HE-AAC (5) / HE-AACv2 (29), 14496-3 1.6.2.1: ADTS carries the AAC-LC core (the decoder finds SBR / PS in it)
|
|
if (profile == 5 or profile == 29) and rateIndex ~= 15 and buffer.len(c) >= 4 then
|
|
local v = buffer.readu8(c, 1) * 65536 + buffer.readu8(c, 2) * 256 + buffer.readu8(c, 3)
|
|
local extIndex = (v // 2 ^ 15) % 16 -- after aot (5), sfi (4), channels (4): bits 13 .. 16
|
|
local core = if extIndex == 15 then -1 else (v // 2 ^ 10) % 32 -- bits 17 .. 21
|
|
profile = if core == 2 then 2 else -1
|
|
end
|
|
else
|
|
local rates = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 }
|
|
profile = 2
|
|
rateIndex = 4
|
|
for i, r in rates do
|
|
if r == math.floor((track.sampleRate or 44100) + 0.5) then
|
|
rateIndex = i - 1
|
|
end
|
|
end
|
|
chanConfig = track.channels or 2
|
|
end
|
|
if profile < 1 or profile > 4 or rateIndex > 12 then
|
|
return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. tostring(profile) .. " in ADTS")
|
|
end
|
|
local w = Bytes.writer(64)
|
|
for _, p in packets do
|
|
local len = buffer.len(p.data) + 7
|
|
w:u8(0xFF)
|
|
w:u8(0xF1)
|
|
w:u8((profile - 1) * 64 + rateIndex * 4 + chanConfig // 4)
|
|
w:u8((chanConfig % 4) * 64 + (len // 2048) % 4)
|
|
w:u8((len // 8) % 256)
|
|
w:u8((len % 8) * 32 + 0x1F)
|
|
w:u8(0xFC)
|
|
w:bytes(p.data)
|
|
end
|
|
return w:finish(), nil
|
|
end
|
|
|
|
-- trim: a container's codec delay (Matroska CodecDelay, an MP4 edit's media time for MP2 / MP3 / AAC, as ffmpeg)
|
|
-- and end padding
|
|
function AudioWrap.trim(dec: any, skip: number, length: number?): any
|
|
if skip <= 0 and length == nil then
|
|
return dec
|
|
end
|
|
skip = math.max(0, skip)
|
|
local rate = dec.sampleRate
|
|
local w: any = setmetatable({}, { __index = dec })
|
|
w.frames = math.max(0, (dec.frames or 0) - skip)
|
|
if length then
|
|
w.frames = if (dec.frames or 0) > 0 then math.min(w.frames, length) else length
|
|
end
|
|
w.duration = w.frames / rate
|
|
local cap = length or math.huge
|
|
local delivered = 0
|
|
local function drop()
|
|
local left = skip
|
|
while left > 0 do
|
|
local _, n = dec:read(math.min(left, 4096))
|
|
if not n or n <= 0 then
|
|
break
|
|
end
|
|
left -= n
|
|
end
|
|
end
|
|
local started = false
|
|
function w.read(_: any, n: number, out: buffer?): (buffer, number)
|
|
if not started then
|
|
started = true
|
|
drop()
|
|
end
|
|
local want = math.min(n, cap - delivered)
|
|
if want <= 0 then
|
|
return out or buffer.create(0), 0
|
|
end
|
|
local b, got = dec:read(want, out)
|
|
delivered += got
|
|
return b, got
|
|
end
|
|
function w.seek(_: any, seconds: number)
|
|
started = true
|
|
if seconds <= 0 then
|
|
dec:seek(0)
|
|
drop()
|
|
delivered = 0
|
|
else
|
|
dec:seek(seconds + skip / rate)
|
|
delivered = math.floor(seconds * rate + 0.5)
|
|
end
|
|
end
|
|
function w.position(_: any): number
|
|
return math.max(0, dec:position() - skip / rate)
|
|
end
|
|
return w
|
|
end
|
|
|
|
function AudioWrap.wrap(dmx: any, track: Types.Track): (buffer?, string?, Err.Err?)
|
|
if type(track) ~= "table" or track.kind ~= "audio" then
|
|
return nil, nil, Err.new(Err.ARG, "not an audio track")
|
|
end
|
|
if track.unsupported then
|
|
return nil, nil, Err.new(Err.UNSUPPORTED, track.unsupported)
|
|
end
|
|
local codec = track.codec
|
|
local packets = allPackets(dmx, track)
|
|
if #packets == 0 then
|
|
return nil, nil, Err.new(Err.CORRUPT, "audio track without packets")
|
|
end
|
|
if track.waveFormat and string.sub(codec, 1, 6) == "adpcm_" then
|
|
return wav(track.waveFormat, concat(packets)), "wav", nil
|
|
end
|
|
if codec == "adpcm_swf" then
|
|
local b, err = swfWav(track, packets)
|
|
return b, if b then "wav" else nil, err
|
|
end
|
|
if PCM[codec] then
|
|
local b, err = pcmWav(track, packets)
|
|
return b, if b then "wav" else nil, err
|
|
end
|
|
if codec == "mp3" or codec == "mp2" or codec == "mp1" then
|
|
return concat(packets), "mp3", nil
|
|
end
|
|
if codec == "ac3" then
|
|
return concat(packets), "ac3", nil
|
|
end
|
|
if codec == "flac" then
|
|
local c = track.config
|
|
local prefix: buffer? = nil
|
|
if c and buffer.len(c) >= 4 and buffer.readstring(c, 0, 4) == "fLaC" then
|
|
prefix = c
|
|
elseif c and buffer.len(c) >= 34 then
|
|
-- metadata blocks without the marker (MP4 dfLa payload after version / flags)
|
|
local start = if buffer.len(c) >= 38 and buffer.readu8(c, 0) == 0 and buffer.readu8(c, 4) % 128 == 0 then 4 else 0
|
|
local b = buffer.create(4 + buffer.len(c) - start)
|
|
buffer.writestring(b, 0, "fLaC")
|
|
buffer.copy(b, 4, c, start)
|
|
prefix = b
|
|
else
|
|
return nil, nil, Err.new(Err.CORRUPT, "FLAC track without its STREAMINFO")
|
|
end
|
|
return concat(packets, prefix), "flac", nil
|
|
end
|
|
if codec == "opus" then
|
|
local head = opusHead(track)
|
|
local pre = buffer.readu16(head, 10)
|
|
local g = pre
|
|
local out = ogg({ head, opusTags() }, packets, function(p: Types.Packet): number
|
|
g += opusSamples(p.data)
|
|
local d = (p :: any).discardPadding
|
|
if type(d) == "number" and d > 0 then
|
|
return g - math.floor(d * 48000 + 0.5) -- the end trimming (WebM DiscardPadding)
|
|
end
|
|
return g
|
|
end)
|
|
return out, "opus", nil
|
|
end
|
|
if codec == "vorbis" then
|
|
local c = track.config
|
|
local headers = c and xiphHeaders(c)
|
|
if not headers or #headers ~= 3 then
|
|
return nil, nil, Err.new(Err.CORRUPT, "Vorbis track without its three headers")
|
|
end
|
|
local sizes, modes = vorbisModes(headers[1], headers[3])
|
|
local granule, prev = 0, nil :: number?
|
|
local rate = track.sampleRate or 44100
|
|
local scale = track.timescale
|
|
local out = ogg(headers, packets, function(p: Types.Packet): number
|
|
if not sizes or not modes then
|
|
return math.floor((p.pts + (p.duration or 0)) / scale * rate + 0.5) -- from the container's times
|
|
end
|
|
local d = p.data
|
|
if buffer.len(d) == 0 or buffer.readu8(d, 0) % 2 ~= 0 then
|
|
return granule
|
|
end
|
|
local mb = 0
|
|
while 2 ^ mb < #(modes :: { boolean }) do
|
|
mb += 1
|
|
end
|
|
local m = if mb > 0 and buffer.len(d) * 8 > mb then bits(d, 1, mb) else 0
|
|
local cur = sizes[if (modes :: { boolean })[m + 1] then 2 else 1]
|
|
if prev then
|
|
granule += (prev + cur) // 4
|
|
end
|
|
prev = cur
|
|
return granule
|
|
end)
|
|
return out, "vorbis", nil
|
|
end
|
|
if codec == "aac" then
|
|
if track.adts then
|
|
return concat(packets), "aac", nil -- already ADTS (MPEG-TS)
|
|
end
|
|
local b, err = adts(track, packets)
|
|
return b, if b then "aac" else nil, err
|
|
end
|
|
return nil, nil, Err.new(Err.UNSUPPORTED, "no audio format for codec " .. tostring(codec))
|
|
end
|
|
|
|
return AudioWrap
|