--!strict -- containers/AudioWrap: an audio track of a video container (a Types.Demuxer track and its packets) as a standalone -- stream that an audio format reads, so the api can open it with the audio formats (a format never requires another -- format). New in formats-luau. -- PCM (pcm_u8 / s16 / s24 / s32 le and be, f32 / f64, alaw, mulaw) -> WAV (big-endian samples byte-swapped); -- an AVI audio track with its WAVEFORMATEX (track.waveFormat: IMA / MS ADPCM, ...) -> WAV with that fmt chunk; -- mp3 / mp2 / mp1 -> the frames back to back (format "mp3"); -- flac -> "fLaC" + the metadata blocks (CodecPrivate / dfLa) + the frames; -- opus -> Ogg Opus (OpusHead from the config or made up, OpusTags, packets with granules from their TOC durations); -- vorbis -> Ogg Vorbis (the three headers from Matroska's Xiph-laced CodecPrivate or MP4's esds-less layout); -- aac -> ADTS (from the AudioSpecificConfig) for audio/aac. -- -- local buf, format, err = AudioWrap.wrap(demuxer, track) -- then F.open(buf, { format = format }) local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Mux = require("@formats/containers/Ogg/Mux") local AudioWrap = {} local function allPackets(dmx: any, track: Types.Track): { Types.Packet } local out = {} 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 -- ------------------------------------------------------------------------------------------------ WAV 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 -- ------------------------------------------------------------------------------------------------ Ogg -- 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 = "formats-luau" 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 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 end -- ------------------------------------------------------------------------------------------------ ADTS 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 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 -- trim(decoder, frames) -> an audio Decoder that drops the first `frames` sample frames (a container's codec delay: -- Matroska CodecDelay for MP2 / MP3 / AAC, which ffmpeg drops too; Opus handles its pre-skip itself) function AudioWrap.trim(dec: any, skip: number): any if skip <= 0 then return dec end local rate = dec.sampleRate local w: any = setmetatable({}, { __index = dec }) w.frames = math.max(0, (dec.frames or 0) - skip) w.duration = math.max(0, (dec.duration or 0) - skip / rate) 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 return dec:read(n, out) end function w.seek(_: any, seconds: number) started = true if seconds <= 0 then dec:seek(0) drop() else dec:seek(seconds + skip / rate) end end function w.position(_: any): number return math.max(0, dec:position() - skip / rate) end return w end -- ------------------------------------------------------------------------------------------------ wrap -- wrap(demuxer, track) -> buffer, audio format name | nil, nil, Err 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 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 == "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 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[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