ws-audio: merge master (ws/m4a codecs/Mdct already in use since 6535a3c; audio/opus encoder, data, vec, 3d, webp)

This commit is contained in:
4DBug committed 2026-10-31 09:29:36 -05:00
commit 43b8f4b4f5
400 files changed
+82546 -38

No files matched your search

+277
View File
@@ -0,0 +1,277 @@
--!strict
-- audio/aac: raw AAC in ADTS framing (ISO/IEC 13818-7 / 14496-3 1.A.3), the .aac files encoders and radio streams
-- write. Supports: reading AAC-LC through codecs/Aac (1 - 8 channels, every rate, multi-block frames, CRC-protected
-- headers skipped), a leading ID3v2 tag (skipped; its text frames become tags), resync after garbage, seeking (by
-- frame), HE-AAC streams play their AAC-LC core. Not supported: writing (AAC encoding is out of scope), ADIF, LATM.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Aac = require("@formats/codecs/Aac")
-- ------------------------------------------------------------------------------------------------ contract
local AacFormat = {
name = "aac",
category = "audio",
extensions = { "aac", "adts" },
mime = { "audio/aac", "audio/aacp", "audio/x-aac" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac" },
caps = { decode = true, encode = false, codecs = { "aac" }, streaming = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxFrames: number?, -- refuse streams with more ADTS frames (default 2^22)
}
-- ------------------------------------------------------------------------------------------------ constants
local readu8 = buffer.readu8
-- the size of an ID3v2 tag at p (0 if none)
local function id3Size(b: buffer, p: number, limit: number): number
if p + 10 > limit or buffer.readstring(b, p, 3) ~= "ID3" then
return 0
end
local s = 0
for i = 6, 9 do
s = s * 128 + bit32.band(readu8(b, p + i), 127)
end
local footer = if bit32.band(readu8(b, p + 5), 0x10) ~= 0 then 10 else 0
return 10 + s + footer
end
-- a few ID3v2.3 / 2.4 text frames -> tags
local ID3_TAGS: { [string]: string } = {
TIT2 = "title", TPE1 = "artist", TALB = "album", TYER = "date", TDRC = "date", TCON = "genre", TRCK = "track",
COMM = "comment", TCOM = "composer", TPE2 = "albumartist",
}
local function id3Tags(b: buffer, p: number, size: number): Types.Tags
local tags: Types.Tags = {}
local ver = readu8(b, p + 3)
if ver < 3 then
return tags
end
local q, stop = p + 10, p + size
while q + 10 <= stop do
local id = buffer.readstring(b, q, 4)
if not string.match(id, "^[A-Z0-9][A-Z0-9][A-Z0-9][A-Z0-9]$") then
break
end
local n = 0
for i = 4, 7 do
n = if ver == 4 then n * 128 + bit32.band(readu8(b, q + i), 127) else n * 256 + readu8(b, q + i)
end
if n < 1 or q + 10 + n > stop then
break
end
local key = ID3_TAGS[id]
local enc = readu8(b, q + 10)
if key and (enc == 0 or enc == 3) then
local s = buffer.readstring(b, q + 11, n - 1)
if id == "COMM" and #s > 3 then
s = string.sub(s, 4)
local z = string.find(s, "\0", 1, true)
if z then
s = string.sub(s, z + 1)
end
end
s = (string.gsub(s, "%z+$", ""))
tags[key] = s
end
q += 10 + n
end
return tags
end
-- ------------------------------------------------------------------------------------------------ sniff
function AacFormat.sniff(r: Bytes.Reader): number
local b, p, limit = r.buf, r.pos, r.limit
p += id3Size(b, p, limit)
local h = Aac.adts(b, p, limit)
if not h then
return 0
end
-- a second header right after the first makes it certain
local h2 = Aac.adts(b, p + h.frameSize, limit)
if h2 and h2.sfIndex == h.sfIndex and h2.channelConfig == h.channelConfig then
return 0.9
end
return if p + h.frameSize >= limit then 0.7 else 0.4
end
-- ------------------------------------------------------------------------------------------------ decode
-- the frame index: offsets of every ADTS frame (resyncing over garbage)
local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number }, Aac.Adts?, Err.Err?)
local b, limit = r.buf, r.limit
local p = r.base + id3Size(b, r.base, limit)
local offs, sizes = {}, {}
local first: Aac.Adts? = nil
while p + 7 <= limit do
local h = Aac.adts(b, p, limit)
if h and first and (h.sfIndex ~= first.sfIndex or h.channelConfig ~= first.channelConfig) then
h = nil -- a false sync inside the data
end
if not h then
p += 1
continue
end
if p + h.frameSize > limit then
break -- a truncated last frame
end
if not first then
first = h
end
if h.blocks ~= 1 then
return offs, sizes, first, Err.new(Err.UNSUPPORTED, "ADTS frames with " .. h.blocks .. " raw data blocks", p)
end
table.insert(offs, p + h.headerSize)
table.insert(sizes, h.frameSize - h.headerSize)
if #offs > maxFrames then
return offs, sizes, first, Err.new(Err.LIMIT, "more than " .. maxFrames .. " frames")
end
p += h.frameSize
end
return offs, sizes, first, nil
end
function AacFormat.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
local o = opts or {}
local offs, sizes, first, ierr = index(r, o.maxFrames or 2 ^ 22)
if ierr then
return nil, ierr
end
if not first then
return nil, Err.new(Err.CORRUPT, "no ADTS frame", r.base)
end
local h = first :: Aac.Adts
if h.objectType ~= 2 then
return nil, Err.new(Err.UNSUPPORTED, "ADTS profile " .. h.objectType .. " (only AAC-LC)")
end
if h.channelConfig == 0 then
return nil, Err.new(Err.UNSUPPORTED, "ADTS with a program config element (channel configuration 0)")
end
local channels = ({ 1, 2, 3, 4, 5, 6, 8 })[h.channelConfig] :: number
local dec, derr = Aac.decoder({ sfIndex = h.sfIndex, channels = channels, channelConfig = h.channelConfig })
if not dec then
return nil, derr
end
local d = dec :: Aac.Decoder
local sr = d.sampleRate
local nframes = #offs
local total = nframes * 1024
local bytes = 0
for _, s in sizes do
bytes += s
end
local id3 = id3Size(r.buf, r.base, r.limit)
local tags = if id3 > 0 then id3Tags(r.buf, r.base, id3) else {}
local buf = r.buf
local nextFrame = 1
local pendPos, pendN = 0, 0
local drop = 0
local pos = 0
local failed: Err.Err? = nil
local out: any = {
sampleRate = sr,
channels = channels,
frames = total,
duration = total / sr,
bitrate = if total > 0 then math.floor(bytes * 8 * sr / total) else 0,
tags = tags,
codec = "aac",
error = nil,
}
local function fill(): boolean
while true do
if nextFrame > nframes then
return false
end
local i = nextFrame
nextFrame += 1
local n, e = d:decode(buf, offs[i], sizes[i])
if not n then
failed = e
out.error = e
return false
end
if drop >= n then
drop -= n
else
pendPos, pendN = drop, n
drop = 0
return true
end
end
end
function out.read(_self: any, n: number, ob: buffer?): (buffer, number)
local want = math.max(0, math.floor(n))
local need = want * channels * 4
local res = if ob and buffer.len(ob) >= need then ob 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 = d.pcm
local q = got * channels * 4
local s = pendPos * channels
for k = 1, take * channels do
writef32(res, q, src[s + k])
q += 4
end
pendPos += take
got += take
end
pos += got
return res, got
end
function out.seek(_self: any, seconds: number)
local target = math.clamp(math.floor(seconds * sr + 0.5), 0, total)
local f = target // 1024 -- frame holding the target (0-based)
local start = math.max(0, f - 1) -- one frame of pre-roll for the overlap
d:reset()
nextFrame = start + 1
drop = target - start * 1024
pendPos, pendN = 0, 0
failed = nil
pos = target
end
function out.position(_self: any): number
return pos / sr
end
if nframes > 0 and not fill() and failed then
return nil, failed
end
return out, nil
end
function AacFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
local dec, err = AacFormat.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
while done < d.frames do
local b, n = d:read(math.min(65536, d.frames - done))
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
audio.tags = d.tags
audio.meta.source = { format = "aac", codec = "aac", bitrate = d.bitrate }
return audio, nil
end
return AacFormat
+746
View File
@@ -0,0 +1,746 @@
--!strict
-- audio/caf: Apple Core Audio Format (CAF 1.0, Apple's "Core Audio Format Specification"). Supports reading linear
-- PCM (8 / 16 / 24 / 32-bit integer, 32 / 64-bit float, big / little endian), ALAC (codecs/Alac), AAC-LC (codecs/Aac,
-- kuki esds), mu-law and A-law; the packet table (pakt) with priming / remainder trimming, a data chunk of unknown
-- size (-1), info chunk tags; seeking. Writing linear PCM (16 / 24-bit big endian, 32-bit float) and ALAC (16 / 20 /
-- 24-bit) with info tags. Not supported: IMA4, other compressed formats (UNSUPPORTED).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Aac = require("@formats/codecs/Aac")
local Alac = require("@formats/codecs/Alac")
-- ------------------------------------------------------------------------------------------------ contract
local Caf = {
name = "caf",
category = "audio",
extensions = { "caf", "caff" },
mime = { "audio/x-caf" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Alac" },
caps = { decode = true, encode = true, codecs = { "pcm", "alac", "aac", "ulaw", "alaw" }, encodeCodecs = { "pcm", "alac" }, tags = true, streaming = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxPackets: number?, -- packet table limit (default 2^24)
}
export type EncodeOptions = {
codec: ("pcm" | "alac")?, -- default "alac"
bitDepth: number?, -- pcm: 16 (default), 24, 32 (float); alac: 16 (default), 20, 24
tags: Types.Tags?, -- default: the audio's tags
}
-- ------------------------------------------------------------------------------------------------ constants
local INFO_TAGS: { [string]: string } = {
title = "title", artist = "artist", album = "album", year = "date", genre = "genre", ["track number"] = "track",
comments = "comment", composer = "composer", copyright = "copyright", lyricist = "lyricist",
["encoding application"] = "encoder", ["recorded date"] = "recorded", tempo = "bpm",
}
local TAG_INFO: { [string]: string } = {}
for k, v in INFO_TAGS do
TAG_INFO[v] = k
end
-- mu-law / A-law -> linear 16-bit
local ULAW, ALAW = table.create(256, 0), table.create(256, 0)
for i = 0, 255 do
local u = 255 - i
local t = (bit32.band(u, 15) * 8 + 132) * 2 ^ bit32.band(bit32.rshift(u, 4), 7)
ULAW[i + 1] = if bit32.band(u, 128) ~= 0 then 132 - t else t - 132
local a = bit32.bxor(i, 0x55)
local seg = bit32.band(bit32.rshift(a, 4), 7)
local m = bit32.band(a, 15) * 16 + 8
if seg > 0 then
m = (m + 256) * 2 ^ (seg - 1)
end
ALAW[i + 1] = if bit32.band(a, 128) ~= 0 then m else -m
end
-- ------------------------------------------------------------------------------------------------ sniff
function Caf.sniff(r: Bytes.Reader): number
local h = r:peek(8)
if #h == 8 and string.sub(h, 1, 4) == "caff" and string.byte(h, 5) == 0 and string.byte(h, 6) == 1 then
return 1
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
type Desc = { rate: number, format: string, flags: number, bytesPerPacket: number, framesPerPacket: number, channels: number, bits: number }
type Parsed = {
desc: Desc,
dataStart: number, -- absolute offset of the audio data
dataEnd: number,
cookie: buffer?,
packets: { number }?, -- sizes (pakt)
packetFrames: { number }?,
priming: number,
remainder: number,
validFrames: number?,
tags: Types.Tags,
}
-- the esds payload in a kuki (version / flags, then the ES_Descriptor) -> the DecoderSpecificInfo
local function esdsConfig(b: buffer): buffer?
local r = Bytes.reader(b)
if r:peekU8() ~= 3 then
r:skip(4) -- the esds atom's version / flags
end
local function len(): number
local n = 0
for _ = 1, 4 do
local c = r:u8()
n = n * 128 + bit32.band(c, 127)
if c < 128 then
break
end
end
return n
end
while not r:eof() and not r.err do
local tag = r:u8()
local n = len()
if tag == 3 then
r:skip(2)
local f = r:u8()
if bit32.band(f, 0x80) ~= 0 then
r:skip(2)
end
if bit32.band(f, 0x40) ~= 0 then
r:skip(r:u8())
end
if bit32.band(f, 0x20) ~= 0 then
r:skip(2)
end
elseif tag == 4 then
r:skip(13)
elseif tag == 5 then
if n > 0 and r:need(n) then
return r:bytes(n)
end
return nil
else
r:skip(n)
end
end
return nil
end
local function vlq(r: Bytes.Reader): number
local v = 0
for _ = 1, 8 do
local c = r:u8()
v = v * 128 + bit32.band(c, 127)
if c < 128 then
return v
end
end
r:fail(Err.CORRUPT, "bad packet table entry")
return 0
end
local function parse(r: Bytes.Reader, o: DecodeOptions): (Parsed?, Err.Err?)
if Caf.sniff(r) == 0 then
return nil, Err.new(Err.CORRUPT, "not a CAF file", r.base)
end
r:seek(8)
local p: Parsed = { desc = nil :: any, dataStart = 0, dataEnd = 0, priming = 0, remainder = 0, tags = {} }
local haveData = false
while r:remaining() >= 12 do
local typ = r:string(4)
local size = r:i64be()
local start = r.pos
if size == -1 and typ == "data" then
size = r.limit - start
end
if size < 0 then
return nil, Err.new(Err.CORRUPT, "bad chunk size", start - 12)
end
local stop = start + size
if stop > r.limit then
if typ ~= "data" then
return nil, Err.new(Err.TRUNCATED, "chunk '" .. typ .. "' runs past the end", start - 12)
end
stop = r.limit -- a truncated data chunk: play what is there
end
local c = Bytes.reader(r.buf, start, stop - start)
if typ == "desc" then
p.desc = {
rate = c:f64be(),
format = c:string(4),
flags = c:u32be(),
bytesPerPacket = c:u32be(),
framesPerPacket = c:u32be(),
channels = c:u32be(),
bits = c:u32be(),
}
if c.err then
return nil, c.err
end
elseif typ == "data" then
p.dataStart = start + 4 -- edit count
p.dataEnd = stop
haveData = true
elseif typ == "kuki" then
p.cookie = c:bytes(stop - start)
elseif typ == "pakt" then
local n = c:i64be()
p.validFrames = c:i64be()
p.priming = c:i32be()
p.remainder = c:i32be()
if c.err then
return nil, c.err
end
if n < 0 or n > (o.maxPackets or 2 ^ 24) or n > c:remaining() then
return nil, Err.new(Err.LIMIT, "packet table of " .. n .. " entries", start)
end
local d = p.desc
if not d then
return nil, Err.new(Err.CORRUPT, "pakt before desc", start)
end
local sizes, frames = table.create(n, 0), nil
if d.framesPerPacket == 0 then
frames = table.create(n, 0)
end
for i = 1, n do
sizes[i] = if d.bytesPerPacket == 0 then vlq(c) else d.bytesPerPacket
if frames then
frames[i] = vlq(c)
end
end
if c.err then
return nil, c.err
end
p.packets, p.packetFrames = sizes, frames
elseif typ == "info" then
local n = c:u32be()
for _ = 1, math.min(n, 1000) do
local k = c:cstring()
local v = c:cstring()
if c.err then
break
end
p.tags[INFO_TAGS[string.lower(k)] or k] = v
end
end
r.pos = stop
if typ == "data" and stop >= r.limit then
break
end
end
if not p.desc then
return nil, Err.new(Err.CORRUPT, "no desc chunk", r.base)
end
if not haveData then
return nil, Err.new(Err.CORRUPT, "no data chunk", r.base)
end
local d = p.desc
if d.channels < 1 or d.channels > 64 or d.rate <= 0 or d.rate ~= d.rate or d.rate > 1e7 then
return nil, Err.new(Err.CORRUPT, "bad stream description")
end
return p, nil
end
-- the packet decoder: decode(i) -> frames into pcm (interleaved floats) | nil, Err
type Source = {
channels: number,
rate: number,
packetCount: number,
packetFrames: (number) -> number,
decode: (number) -> (number?, Err.Err?),
pcm: { number },
reset: () -> (),
codec: string,
bits: number?,
}
local function source(r: Bytes.Reader, p: Parsed): (Source?, Err.Err?)
local d = p.desc
local b = r.buf
local ch = d.channels
local fmt = d.format
if fmt == "lpcm" or fmt == "ulaw" or fmt == "alaw" then
local bits = if fmt == "lpcm" then d.bits else 8
local float = fmt == "lpcm" and bit32.band(d.flags, 1) ~= 0
local little = fmt == "lpcm" and bit32.band(d.flags, 2) ~= 0
local bpf = d.bytesPerPacket
if bpf == 0 then
bpf = ch * (bits // 8)
end
if not (bits == 8 or bits == 16 or bits == 24 or bits == 32 or (bits == 64 and float)) or (float and bits < 32) then
return nil, Err.new(Err.UNSUPPORTED, "linear PCM with " .. bits .. " bits")
end
local bps = bits // 8
if bpf < ch * bps then
return nil, Err.new(Err.CORRUPT, "bytes per packet smaller than a frame")
end
local total = (p.dataEnd - p.dataStart) // bpf
local per = 1024
local pcm = table.create(per * ch, 0)
local scale = 1 / 2 ^ (bits - 1)
local readu8, readi8 = buffer.readu8, buffer.readi8
local src: Source = {
channels = ch,
rate = d.rate,
packetCount = (total + per - 1) // per,
packetFrames = function(i: number): number
return math.min(per, total - (i - 1) * per)
end,
pcm = pcm,
reset = function() end,
codec = if fmt == "lpcm" then "pcm" else fmt,
bits = bits,
decode = function(i: number): (number?, Err.Err?)
local f0 = (i - 1) * per
local n = math.min(per, total - f0)
local k = 1
for f = f0, f0 + n - 1 do
local q = p.dataStart + f * bpf
for _ = 1, ch do
local v
if fmt == "ulaw" then
v = ULAW[readu8(b, q) + 1] / 32768
elseif fmt == "alaw" then
v = ALAW[readu8(b, q) + 1] / 32768
elseif float then
if bits == 32 then
v = if little then buffer.readf32(b, q) else Bytes.reader(b, q, 4):f32be()
else
v = if little then buffer.readf64(b, q) else Bytes.reader(b, q, 8):f64be()
end
elseif bits == 8 then
v = readi8(b, q) * scale
elseif bits == 16 then
v = if little then buffer.readi16(b, q) else readi8(b, q) * 256 + readu8(b, q + 1)
v *= scale
elseif bits == 24 then
if little then
v = readi8(b, q + 2) * 65536 + readu8(b, q + 1) * 256 + readu8(b, q)
else
v = readi8(b, q) * 65536 + readu8(b, q + 1) * 256 + readu8(b, q + 2)
end
v *= scale
else
if little then
v = buffer.readi32(b, q)
else
v = readi8(b, q) * 16777216 + readu8(b, q + 1) * 65536 + readu8(b, q + 2) * 256 + readu8(b, q + 3)
end
v *= scale
end
pcm[k] = v
k += 1
q += bps
end
end
return n, nil
end,
}
return src, nil
end
-- packetised codecs
local sizes = p.packets
if not sizes then
if d.bytesPerPacket > 0 then
local n = (p.dataEnd - p.dataStart) // d.bytesPerPacket
sizes = table.create(n, d.bytesPerPacket)
else
return nil, Err.new(Err.CORRUPT, "compressed CAF without a packet table")
end
end
local offsets = table.create(#sizes, 0)
local o = p.dataStart
for i, s in sizes :: { number } do
offsets[i] = o
o += s
if o > p.dataEnd then
-- a truncated file: keep the whole packets
offsets[i] = nil :: any
sizes = table.move(sizes :: { number }, 1, i - 1, 1, {})
break
end
end
local count = #(sizes :: { number })
local fpp = d.framesPerPacket
local pf = p.packetFrames
local function framesOf(i: number): number
return if pf then pf[i] else fpp
end
local cookie = p.cookie
if fmt == "alac" then
if not cookie then
return nil, Err.new(Err.CORRUPT, "ALAC without a magic cookie")
end
local cfg, err = Alac.config(cookie :: 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)
return {
channels = cfg.channels,
rate = d.rate,
packetCount = count,
packetFrames = framesOf,
pcm = pcm,
reset = function() end,
codec = "alac",
bits = cfg.bitDepth,
decode = function(i: number): (number?, Err.Err?)
local n, e = dec:decode(b, offsets[i], (sizes :: { number })[i])
if not n then
return nil, e
end
local src = dec.pcm
for k = 1, n * cfg.channels do
pcm[k] = src[k] * scale
end
return n, nil
end,
}, nil
elseif fmt == "aac " then
local asc = if cookie then esdsConfig(cookie :: buffer) else nil
if not asc then
return nil, Err.new(Err.CORRUPT, "AAC without an esds magic cookie")
end
local dec, err = Aac.decoder(asc :: buffer)
if not dec then
return nil, err
end
local ad = dec :: Aac.Decoder
return {
channels = ad.channels,
rate = d.rate,
packetCount = count,
packetFrames = framesOf,
pcm = ad.pcm,
reset = function()
ad:reset()
end,
codec = "aac",
decode = function(i: number): (number?, Err.Err?)
return ad:decode(b, offsets[i], (sizes :: { number })[i])
end,
}, nil
end
return nil, Err.new(Err.UNSUPPORTED, "CAF format '" .. fmt .. "'")
end
function Caf.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
local p, err = parse(r, opts or {})
if not p then
return nil, err
end
local s, serr = source(r, p :: Parsed)
if not s then
return nil, serr
end
local src = s :: Source
local ch, rate = src.channels, src.rate
local starts = table.create(src.packetCount + 1, 0)
local total = 0
for i = 1, src.packetCount do
starts[i] = total
total += src.packetFrames(i)
end
starts[src.packetCount + 1] = total
local skip = math.max(0, p.priming)
local stopAt = total
if p.validFrames and p.validFrames >= 0 then
stopAt = math.min(total, skip + p.validFrames)
elseif p.remainder > 0 then
stopAt = math.max(skip, total - p.remainder)
end
local frames = math.max(0, stopAt - skip)
local nextPacket = 1
local decoded = 0
local pendPos, pendN = 0, 0
local dropUntil = skip
local pos = 0
local failed: Err.Err? = nil
local dec: any = {
sampleRate = rate,
channels = ch,
frames = frames,
duration = frames / rate,
bitrate = if frames > 0 then math.floor((p.dataEnd - p.dataStart) * 8 * rate / frames) else 0,
tags = p.tags,
codec = src.codec,
bitsPerSample = src.bits,
error = nil,
}
local function fill(): boolean
while true do
if nextPacket > src.packetCount or decoded >= stopAt then
return false
end
local i = nextPacket
nextPacket += 1
local start = starts[i]
local n, e = src.decode(i)
if not n then
failed = e
dec.error = e
return false
end
decoded = start + n
local a = math.max(start, dropUntil)
local b = math.min(decoded, stopAt)
if b > a then
pendPos, pendN = a - start, 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 * ch * 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 q = got * ch * 4
local sidx = pendPos * ch
local pcm = src.pcm
for k = 1, take * ch do
writef32(ob, q, pcm[sidx + k])
q += 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 * rate + 0.5), 0, frames) + skip
local lo, hi, found = 1, src.packetCount, 1
while lo <= hi do
local mid = (lo + hi) // 2
if starts[mid] <= target then
found = mid
lo = mid + 1
else
hi = mid - 1
end
end
if src.codec == "aac" then
found = math.max(1, found - 1)
end
src.reset()
nextPacket = found
decoded = starts[found]
dropUntil = target
pendPos, pendN = 0, 0
failed = nil
pos = target - skip
end
function dec.position(_self: any): number
return pos / rate
end
if src.packetCount > 0 and frames > 0 and not fill() and failed then
return nil, failed
end
return dec, nil
end
function Caf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
local dec, err = Caf.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
while done < d.frames do
local b, n = d:read(math.min(65536, d.frames - done))
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
audio.tags = d.tags
audio.meta.source = { format = "caf", codec = d.codec, bitsPerSample = d.bitsPerSample }
return audio, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function chunk(w: Bytes.Writer, typ: string, size: number)
w:string(typ)
w:i64be(size)
end
-- encode(audio | decoder, opts?) -> buffer | nil, Err
function Caf.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 codec = o.codec or "alac"
if codec ~= "alac" and codec ~= "pcm" then
return nil, Err.new(Err.ARG, "codec must be 'alac' or 'pcm'")
end
local sr, ch = value.sampleRate, value.channels
local depth = o.bitDepth or 16
if codec == "pcm" and depth ~= 16 and depth ~= 24 and depth ~= 32 then
return nil, Err.new(Err.ARG, "pcm bitDepth 16, 24 or 32 (float)")
end
if ch < 1 or ch > 64 or sr <= 0 then
return nil, Err.new(Err.ARG, "bad sample rate / channels")
end
-- the source frames
local isAudio = value.kind == "audio" and type(value.samples) == "buffer"
if not isAudio and type(value.read) ~= "function" then
return nil, Err.new(Err.ARG, "expected an Audio or a Decoder")
end
if isAudio and buffer.len(value.samples) < value.frames * ch * 4 then
return nil, Err.new(Err.ARG, "audio.samples is shorter than frames * channels")
end
local done = 0
local chunkBuf: buffer? = nil
local function nextBlock(n: number): (buffer?, number, number)
if isAudio then
local k = math.min(n, value.frames - done)
local base = done * ch * 4
done += k
return value.samples, base, k
end
local b, got = value:read(n, chunkBuf)
chunkBuf = b
done += got
return b, 0, got
end
local readf32 = buffer.readf32
local data = Bytes.writer(65536)
local sizes: { number } = {}
local enc: Alac.Encoder? = nil
if codec == "alac" then
local e, err = Alac.encoder({ sampleRate = math.floor(sr), channels = ch, bitDepth = depth })
if not e then
return nil, err
end
enc = e
local ints = table.create(4096 * ch, 0)
local peak = 2 ^ (depth - 1)
while true do
local b, base, n = nextBlock(4096)
if not b or n <= 0 then
break
end
for i = 0, n * ch - 1 do
local v = math.floor(readf32(b, base + i * 4) * peak + 0.5)
ints[i + 1] = math.clamp(v, -peak, peak - 1)
end
local pkt, perr = (e :: Alac.Encoder):encode(ints, 1, n)
if not pkt then
return nil, perr
end
data:bytes(pkt)
table.insert(sizes, buffer.len(pkt))
end
else
local peak = 2 ^ (depth - 1)
while true do
local b, base, n = nextBlock(4096)
if not b or n <= 0 then
break
end
for i = 0, n * ch - 1 do
local f = readf32(b, base + i * 4)
if depth == 32 then
data:f32be(f)
else
local v = math.clamp(math.floor(f * peak + 0.5), -peak, peak - 1)
if depth == 16 then
data:u16be(v % 65536)
else
data:u24be(v % 16777216)
end
end
end
end
end
local frames = done
local w = Bytes.writer(data:tell() + 1024)
w:string("caff")
w:u16be(1)
w:u16be(0)
chunk(w, "desc", 32)
w:f64be(sr)
if codec == "alac" then
w:string("alac")
w:u32be(({ [16] = 1, [20] = 2, [24] = 3, [32] = 4 })[depth] or 1)
w:u32be(0)
w:u32be(4096)
w:u32be(ch)
w:u32be(0)
else
w:string("lpcm")
w:u32be(if depth == 32 then 1 else 0) -- float / big-endian integer
w:u32be(ch * depth // 8)
w:u32be(1)
w:u32be(ch)
w:u32be(depth)
end
local tags = o.tags or value.tags or {}
local keys = {}
for k, v in tags do
if type(v) == "string" then
table.insert(keys, k)
end
end
table.sort(keys)
if #keys > 0 then
local info = Bytes.writer(256)
info:u32be(#keys)
for _, k in keys do
info:cstring(TAG_INFO[k] or k)
info:cstring(tags[k])
end
chunk(w, "info", info:tell())
w:bytes(info.buf, 0, info:tell())
end
if enc then
local cookie = Alac.cookie(enc.config)
chunk(w, "kuki", buffer.len(cookie))
w:bytes(cookie)
local pk = Bytes.writer(64 + #sizes * 2)
pk:i64be(#sizes)
pk:i64be(frames)
pk:u32be(0)
pk:u32be(#sizes * 4096 - frames)
for _, s in sizes do
-- BER variable-length integer
local bytes = { s % 128 }
local v = s // 128
while v > 0 do
table.insert(bytes, 1, 128 + v % 128)
v //= 128
end
for _, x in bytes do
pk:u8(x)
end
end
chunk(w, "pakt", pk:tell())
w:bytes(pk.buf, 0, pk:tell())
end
chunk(w, "data", data:tell() + 4)
w:u32be(0) -- edit count
w:bytes(data.buf, 0, data:tell())
return w:finish(), nil
end
return Caf
+441
View File
@@ -0,0 +1,441 @@
--!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
File diff suppressed because it is too large. Load diff
+181
View File
@@ -0,0 +1,181 @@
--!strict
-- audio/opus/Encode: Ogg Opus writing (RFC 7845) around audio/opus/CeltEncoder: CELT-only packets (TOC config 31:
-- full band, 20 ms, code 0), OpusHead (mapping family 0, the pre-skip = the encoder's delay), OpusTags (vendor +
-- the tags as Vorbis comments), granule positions with end trimming, pages through containers/Ogg's muxer. Input at
-- other rates is resampled to 48 kHz (a Kaiser-windowed sinc; quality enough for a codec input). New in formats-luau.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Ogg = require("@formats/containers/Ogg")
local CeltEncoder = require("@formats/audio/opus/CeltEncoder")
local Encode = {}
export type Options = {
bitrate: number?, -- bits per second (default 64000 per channel; 6000 .. 510000, constant)
tags: { [string]: string }?, -- default: the audio's tags
vendor: string?, -- OpusTags vendor (default "formats-luau")
serial: number?, -- Ogg stream serial (default 0x4f707573)
}
local floor, sin, pi, sqrt = math.floor, math.sin, math.pi, math.sqrt
local function besselI0(x: number): number
local sum, term = 1, 1
for k = 1, 60 do
term *= (x / (2 * k)) ^ 2
sum += term
if term < sum * 1e-15 then
break
end
end
return sum
end
-- resample(src (interleaved f32 buffer), frames, channels, from, to) -> { number } interleaved, frames out
local function resample(src: buffer, frames: number, channels: number, from: number, to: number): ({ number }, number)
local outFrames = floor(frames * to / from + 0.5)
local out = table.create(outFrames * channels, 0)
local ratio = to / from
local cutoff = 0.97 * math.min(1, ratio) -- of the input Nyquist
local half = 16 -- zero crossings each side (at the cutoff)
local width = half / cutoff
local beta = 8
local i0b = besselI0(beta)
local readf32 = buffer.readf32
for j = 0, outFrames - 1 do
local t = j / ratio -- the input position
local first = math.max(0, floor(t - width) + 1)
local last = math.min(frames - 1, floor(t + width))
for c = 0, channels - 1 do
local acc, wsum = 0, 0
for i = first, last do
local d = i - t
local x = d * cutoff
local s = if x == 0 then 1 else sin(pi * x) / (pi * x)
local r = d / width
local w = besselI0(beta * sqrt(math.max(0, 1 - r * r))) / i0b
local h = s * w
acc += readf32(src, (i * channels + c) * 4) * h
wsum += h
end
out[j * channels + c + 1] = if wsum ~= 0 then acc / wsum else 0
end
end
return out, outFrames
end
local TAG_NAMES: { [string]: string } = {
title = "TITLE", artist = "ARTIST", album = "ALBUM", albumartist = "ALBUMARTIST", date = "DATE", genre = "GENRE",
track = "TRACKNUMBER", tracktotal = "TRACKTOTAL", disc = "DISCNUMBER", comment = "COMMENT", composer = "COMPOSER",
}
-- encode(audio | decoder, opts) -> buffer | nil, Err
function Encode.encode(value: any, opts: Options?): (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 ch = value.channels
if ch ~= 1 and ch ~= 2 then
return nil, Err.new(Err.UNSUPPORTED, "the CELT encoder writes mono or stereo (got " .. ch .. " channels)")
end
local rate = value.sampleRate
if rate < 1000 or rate > 768000 then
return nil, Err.new(Err.ARG, "bad sample rate " .. tostring(rate))
end
local bitrate = o.bitrate or 64000 * ch
if type(bitrate) ~= "number" or bitrate < 6000 or bitrate > 510000 then
return nil, Err.new(Err.ARG, "bitrate 6000 .. 510000")
end
-- the whole input as an interleaved f32 buffer
local samples: buffer, frames: number
if value.kind == "audio" and type(value.samples) == "buffer" then
samples, frames = value.samples, value.frames
if buffer.len(samples) < frames * ch * 4 then
return nil, Err.new(Err.ARG, "audio.samples is shorter than frames * channels")
end
elseif type(value.read) == "function" then
local w = Bytes.writer(65536)
frames = 0
local chunk: buffer? = nil
while true do
local b, n = value:read(16384, chunk)
chunk = b
if n <= 0 then
break
end
w:bytes(b, 0, n * ch * 4)
frames += n
end
samples = w:finish()
else
return nil, Err.new(Err.ARG, "expected an Audio or a Decoder")
end
-- 48 kHz floats
local pcm: { number }, n48: number
if rate == 48000 then
n48 = frames
pcm = table.create(frames * ch, 0)
for i = 1, frames * ch do
pcm[i] = buffer.readf32(samples, (i - 1) * 4)
end
else
pcm, n48 = resample(samples, frames, ch, rate, 48000)
end
local FRAME = CeltEncoder.FRAME
local preSkip = CeltEncoder.DELAY
local packets = (n48 + preSkip + FRAME - 1) // FRAME
-- zero padding to whole frames
for i = n48 * ch + 1, packets * FRAME * ch do
pcm[i] = 0
end
local bytes = math.clamp(floor(bitrate * FRAME / 48000 / 8), if ch == 2 then 40 else 20, 1275 - 1)
local st = CeltEncoder.new(ch)
local mux = Ogg.muxer({ pageSize = 4096 })
local s = mux:stream(o.serial or 0x4f707573)
-- OpusHead
local head = Bytes.writer(19)
head:string("OpusHead")
head:u8(1)
head:u8(ch)
head:u16le(preSkip)
head:u32le(floor(rate))
head:u16le(0)
head:u8(0)
s:packet(head:finish(), 0, { flush = true })
-- OpusTags
local tags = o.tags or value.tags or {}
local tw = Bytes.writer(256)
tw:string("OpusTags")
local vendor = o.vendor or "formats-luau"
tw:u32le(#vendor)
tw:string(vendor)
local keys = {}
for k, v in tags do
if type(k) == "string" and type(v) == "string" then
table.insert(keys, k)
end
end
table.sort(keys)
tw:u32le(#keys)
for _, k in keys do
local field = (TAG_NAMES[k] or string.upper(k)) .. "=" .. tags[k]
tw:u32le(#field)
tw:string(field)
end
s:packet(tw:finish(), 0, { flush = true })
-- audio
local toc = 31 * 8 + (if ch == 2 then 4 else 0)
for p = 0, packets - 1 do
local frame = CeltEncoder.encodeFrame(st, pcm, p * FRAME * ch + 1, ch, bytes)
local pkt = buffer.create(bytes + 1)
buffer.writeu8(pkt, 0, toc)
buffer.copy(pkt, 1, frame, 0, bytes)
local last = p == packets - 1
local granule = if last then preSkip + n48 else (p + 1) * FRAME
s:packet(pkt, granule, { eos = last })
end
return mux:finish(), nil
end
return Encode
+252
View File
@@ -0,0 +1,252 @@
--!strict
--!native
--!optimize 2
-- audio/opus/RangeEncoder: the range encoder (RFC 6716 section 5.1), a port of libopus celt/entenc.c (BSD:
-- licenses/libopus-BSD.txt), the mirror of audio/opus/RangeDecoder. Writes one fixed-size frame: the range-coded
-- symbols from the front, the raw bits (ec_enc_bits) from the back, zeros between. Values stay below 2^32 as plain
-- numbers. Never throws: running out of room sets `error`.
local RangeEncoder = {}
export type Enc = {
buf: buffer,
storage: number,
offs: number,
end_offs: number,
end_window: number,
nend_bits: number,
nbits_total: number,
rng: number,
val: number,
rem: number,
ext: number,
error: number,
}
local CODE_TOP = 2147483648 -- 1 << 31
local CODE_BOT = 8388608 -- CODE_TOP >> 8
local CODE_SHIFT = 23
local SYM_MAX = 255
local countlz = bit32.countlz
local band = bit32.band
local readu8, writeu8 = buffer.readu8, buffer.writeu8
local floor = math.floor
local function ilog(x: number): number
return 32 - countlz(x)
end
RangeEncoder.ilog = ilog
-- new(storage) -> Enc over a fresh zeroed buffer of storage bytes
function RangeEncoder.new(storage: number): Enc
return {
buf = buffer.create(math.max(storage, 1)),
storage = storage,
offs = 0,
end_offs = 0,
end_window = 0,
nend_bits = 0,
nbits_total = 33, -- EC_CODE_BITS + 1
rng = CODE_TOP,
val = 0,
rem = -1,
ext = 0,
error = 0,
}
end
local function writeByte(e: Enc, v: number)
if e.offs + e.end_offs >= e.storage then
e.error = -1
return
end
writeu8(e.buf, e.offs, band(v, 255))
e.offs += 1
end
local function writeByteAtEnd(e: Enc, v: number)
if e.offs + e.end_offs >= e.storage then
e.error = -1
return
end
e.end_offs += 1
writeu8(e.buf, e.storage - e.end_offs, band(v, 255))
end
local function carryOut(e: Enc, c: number)
if c ~= SYM_MAX then
local carry = if c >= 256 then 1 else 0
if e.rem >= 0 then
writeByte(e, e.rem + carry)
end
if e.ext > 0 then
local sym = band(SYM_MAX + carry, 255)
repeat
writeByte(e, sym)
e.ext -= 1
until e.ext <= 0
end
e.rem = band(c, 255)
else
e.ext += 1
end
end
local function normalize(e: Enc)
while e.rng <= CODE_BOT do
carryOut(e, floor(e.val / 8388608))
e.val = (e.val * 256) % CODE_TOP
e.rng *= 256
e.nbits_total += 8
end
end
-- encode(fl, fh, ft): the symbol [fl, fh) of ft
function RangeEncoder.encode(e: Enc, fl: number, fh: number, ft: number)
local r = floor(e.rng / ft)
if fl > 0 then
e.val += e.rng - r * (ft - fl)
e.rng = r * (fh - fl)
else
e.rng -= r * (ft - fh)
end
normalize(e)
end
-- encodeBin(fl, fh, bits): ft = 2^bits
function RangeEncoder.encodeBin(e: Enc, fl: number, fh: number, bits: number)
local ft = 2 ^ bits
local r = floor(e.rng / ft)
if fl > 0 then
e.val += e.rng - r * (ft - fl)
e.rng = r * (fh - fl)
else
e.rng -= r * (ft - fh)
end
normalize(e)
end
-- bitLogp(v, logp): a bit whose probability of being 1 is 2^-logp
function RangeEncoder.bitLogp(e: Enc, v: boolean, logp: number)
local r = e.rng
local s = floor(r / 2 ^ logp)
r -= s
if v then
e.val += r
e.rng = s
else
e.rng = r
end
normalize(e)
end
-- icdf(s, icdf, ftb): symbol s (0-based) of an inverse CDF table (1-based Luau array) with 2^ftb total
function RangeEncoder.icdf(e: Enc, s: number, icdf: { number }, ftb: number)
local r = floor(e.rng / 2 ^ ftb)
if s > 0 then
e.val += e.rng - r * icdf[s]
e.rng = r * (icdf[s] - icdf[s + 1])
else
e.rng -= r * icdf[s + 1]
end
normalize(e)
end
-- bits(fl, n): n raw bits (n <= 25), written from the end of the frame
function RangeEncoder.bits(e: Enc, fl: number, n: number)
local window = e.end_window
local used = e.nend_bits
if used + n > 32 then
repeat
writeByteAtEnd(e, window % 256)
window = floor(window / 256)
used -= 8
until used < 8
end
window += fl * 2 ^ used
used += n
e.end_window = window
e.nend_bits = used
e.nbits_total += n
end
-- uint(fl, ft): fl uniformly in [0, ft), ft up to 2^32
function RangeEncoder.uint(e: Enc, fl: number, ft: number)
ft -= 1
local ftb = ilog(ft)
if ftb > 8 then
ftb -= 8
local sh = 2 ^ ftb
local ft1 = floor(ft / sh) + 1
local hi = floor(fl / sh)
RangeEncoder.encode(e, hi, hi + 1, ft1)
RangeEncoder.bits(e, fl - hi * sh, ftb)
else
RangeEncoder.encode(e, fl, fl + 1, ft + 1)
end
end
function RangeEncoder.tell(e: Enc): number
return e.nbits_total - ilog(e.rng)
end
local CORRECTION = { 35733, 38967, 42495, 46340, 50535, 55109, 60097, 65535 }
function RangeEncoder.tellFrac(e: Enc): number
local nbits = e.nbits_total * 8
local l = ilog(e.rng)
local r = floor(e.rng / 2 ^ (l - 16))
local b = floor(r / 4096) - 8
if r > CORRECTION[b + 1] then
b += 1
end
return nbits - (l * 8 + b)
end
-- done(): flush; the frame is e.buf (storage bytes)
function RangeEncoder.done(e: Enc)
local l = 32 - ilog(e.rng)
local msk = floor((CODE_TOP - 1) / 2 ^ l)
local stop = floor((e.val + msk) / (msk + 1)) * (msk + 1)
if stop + msk >= e.val + e.rng then
l += 1
msk = floor(msk / 2)
stop = floor((e.val + msk) / (msk + 1)) * (msk + 1)
end
while l > 0 do
carryOut(e, floor(stop / 8388608))
stop = (stop * 256) % CODE_TOP
l -= 8
end
if e.rem >= 0 or e.ext > 0 then
carryOut(e, 0)
end
local window = e.end_window
local used = e.nend_bits
while used >= 8 do
writeByteAtEnd(e, window % 256)
window = floor(window / 256)
used -= 8
end
if e.error == 0 then
local a, b = e.offs, e.storage - e.end_offs
if b > a then
buffer.fill(e.buf, a, 0, b - a)
end
if used > 0 then
if e.end_offs >= e.storage then
e.error = -1
else
l = -l
if e.offs + e.end_offs >= e.storage and l < used then
window = window % 2 ^ l
e.error = -1
end
local p = e.storage - e.end_offs - 1
writeu8(e.buf, p, bit32.bor(readu8(e.buf, p), window))
end
end
end
end
local _ = CODE_SHIFT
return RangeEncoder
+14 -4
View File
@@ -5,14 +5,17 @@
-- Supports: decode of every Opus mode / bandwidth / frame size, mono, stereo and surround (optional stereo downmix,
-- opts.stereo), pre-skip, end trimming, output gain, OpusTags, sample-accurate seeking (granule bisection + 80 ms
-- pre-roll), damaged files (concealment). Output is always 48 kHz f32.
-- Not supported: encoding, mapping family 3 (ambisonics projection), chained streams (the first Opus stream is
-- decoded), CELT pitch PLC (noise PLC only).
-- Encoding (audio/opus/Encode + CeltEncoder, ws-m4a): a CELT-only fixed-frame encoder (20 ms, full band, constant
-- bit rate, mono or dual stereo; other input rates resampled to 48 kHz) writing Ogg Opus with OpusTags.
-- Not supported: SILK / hybrid encoding, transients / pitch pre-filter in the encoder, mapping family 3 (ambisonics
-- projection), chained streams (the first Opus stream is decoded), CELT pitch PLC (noise PLC only).
-- Changes from opus-luau: the injected Ogg demuxer is containers/Ogg; errors are core/Err values; read() takes an
-- optional output buffer; decode() fully decodes to an Audio.
--
-- local dec, err = Opus.open(Bytes.reader(buf)) -- the Types.Decoder: dec:read(n, out?), dec:seek(s), ...
-- local audio = Opus.decode(Bytes.reader(buf)) -- a Types.Audio
-- Opus.Decoder.new(channels) + Opus.Decoder.decode(st, buf, off, len, pcm, base, maxFrames) -- raw packets
-- local file = Opus.encode(audio, { bitrate = 96000 }) -- Ogg Opus (CELT only)
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
@@ -24,6 +27,7 @@ local Packet = require("@formats/audio/opus/Packet")
local RangeDecoder = require("@formats/audio/opus/RangeDecoder")
local Celt = require("@formats/audio/opus/Celt")
local Silk = require("@formats/audio/opus/Silk")
local Encode = require("@formats/audio/opus/Encode")
-- ------------------------------------------------------------------------------------------------ contract
local Opus = {
@@ -31,8 +35,8 @@ local Opus = {
category = "audio",
extensions = { "opus" },
mime = { "audio/opus", "audio/ogg" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" },
caps = { decode = true, encode = false, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 } },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct" },
caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" } },
}
-- ------------------------------------------------------------------------------------------------ types
@@ -213,6 +217,12 @@ function Opus.decode(r: any, opts: OpenOptions?): (Types.Audio?, Err.Err?)
return a, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- encode(audio | decoder, opts?) -> Ogg Opus buffer | nil, Err (CELT only; see audio/opus/Encode)
function Opus.encode(value: any, opts: Encode.Options?): (buffer?, Err.Err?)
return Encode.encode(value, opts)
end
-- ------------------------------------------------------------------------------------------------ open
local Stream = {}
Stream.__index = Stream