rename: src/Formats -> src/Rosetta, @formats -> @rosetta requires, build/luajit/rosetta + rosetta._compat, build/roblox/Rosetta, ROSETTA_* env/globals, writer vendor strings

This commit is contained in:
4DBug committed 2026-11-01 01:19:16 -05:00
1 parent 2956576d7f
commit 22ddcd78fa
941 files changed
+3364 -3364

No files matched your search

+209
View File
@@ -0,0 +1,209 @@
--!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/audio/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("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Pcm = require("@rosetta/codecs/audio/Pcm")
local Stream = require("@rosetta/codecs/audio/Stream")
local Aac = require("@rosetta/codecs/audio/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/audio/Aac", "codecs/audio/Pcm", "codecs/audio/Stream" },
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: DecodeOptions = 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 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",
}
-- 1024 frames per ADTS frame; one frame of pre-roll for the overlap when seeking
return Stream.packets(out, {
count = nframes,
start = function(i: number): number
return (i - 1) * 1024
end,
decode = function(i: number): (number?, Err.Err?)
return d:decode(buf, offs[i], sizes[i])
end,
pcm = function(): { number }
return d.pcm
end,
reset = function()
d:reset()
end,
preroll = 1,
})
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
return Pcm.drain(d, { format = "aac", codec = "aac", bitrate = d.bitrate })
end
return AacFormat
+147
View File
@@ -0,0 +1,147 @@
--!strict
-- audio/ac3: raw AC-3 (Dolby Digital, ATSC A/52) elementary streams, the .ac3 files of DVD / broadcast rips, through
-- codecs/audio/Ac3 (written from the A/52 specification). Supports: every channel layout (1+1, 1/0 .. 3/2, LFE)
-- output in WAVE order without downmixing, 32 / 44.1 / 48 kHz, every bit rate, coupling, rematrixing, block
-- switching, delta bit allocation, the CRC check, resync over garbage, a truncated last frame (dropped), streaming and
-- exact seeking (one frame of pre-roll for the overlap). Dynamic range control is off by default (`drc` = 0 .. 1).
-- Not supported: writing, E-AC-3 / Dolby Digital Plus (UNSUPPORTED), bsid 9 / 10 reduced-rate streams.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Pcm = require("@rosetta/codecs/audio/Pcm")
local Stream = require("@rosetta/codecs/audio/Stream")
local Ac3 = require("@rosetta/codecs/audio/Ac3")
-- ------------------------------------------------------------------------------------------------ contract
local Ac3Format = {
name = "ac3",
category = "audio",
extensions = { "ac3", "a52" },
mime = { "audio/ac3", "audio/x-ac3" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Ac3" },
caps = { decode = true, encode = false, codecs = { "ac3" }, channels = 6, streaming = true, lossy = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxFrames: number?, -- refuse streams with more syncframes (default 2^22)
drc: number?, -- dynamic range control scale: 0 = off (default), 1 = full
crc: boolean?, -- check every syncframe's CRC (default true; a bad frame ends the stream with Err.CHECKSUM)
}
-- ------------------------------------------------------------------------------------------------ sniff
-- (E-AC-3 streams sniff too, so loading one says UNSUPPORTED instead of an unknown format)
function Ac3Format.sniff(r: Bytes.Reader): number
local b, p, limit = r.buf, r.pos, r.limit
local h = Ac3.header(b, p, limit)
if not h then
return 0
end
local h2 = Ac3.header(b, p + h.frameSize, limit)
if h2 and h2.sampleRate == h.sampleRate then
return 0.9
end
return if p + h.frameSize >= limit then 0.6 else 0.3
end
-- ------------------------------------------------------------------------------------------------ decode
-- the syncframe index (resyncing over garbage: a header counts when the next one follows it, or the data ends)
local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number }, Ac3.Header?, Err.Err?)
local b, limit = r.buf, r.limit
local p = r.base
local offs, sizes = {}, {}
local first: Ac3.Header? = nil
while p + 8 <= limit do
local h = Ac3.header(b, p, limit)
if h and first and (h.sampleRate ~= first.sampleRate or h.bsid > 10) then
h = nil
end
if h and not first and p + h.frameSize + 8 <= limit then
local h2 = Ac3.header(b, p + h.frameSize, limit)
if not h2 then
h = nil -- a false sync word
end
end
if not h then
p += 1
continue
end
if not first then
first = h
if h.bsid > 10 then
return offs, sizes, first, Err.new(Err.UNSUPPORTED, "E-AC-3 (Dolby Digital Plus)", p)
elseif h.bsid > 8 then
return offs, sizes, first, Err.new(Err.UNSUPPORTED, "reduced sample rate AC-3 (bsid " .. h.bsid .. ")", p)
end
end
if p + h.frameSize > limit then
break -- a truncated last frame
end
table.insert(offs, p)
table.insert(sizes, h.frameSize)
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 Ac3Format.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
local o: DecodeOptions = opts or {}
local offs, sizes, first, ierr = index(r, o.maxFrames or 2 ^ 22)
if ierr then
return nil, ierr
end
if not first or #offs == 0 then
return nil, Err.new(Err.CORRUPT, "no AC-3 syncframe", r.base)
end
local h = first :: Ac3.Header
local d = Ac3.decoder({ drc = o.drc, crc = o.crc })
local buf = r.buf
local n = #offs
local out = {
sampleRate = h.sampleRate,
channels = h.channels,
frames = n * 1536,
duration = n * 1536 / h.sampleRate,
bitrate = h.bitrate,
tags = {},
codec = "ac3",
acmod = h.acmod,
lfe = h.lfeon,
}
return Stream.packets(out, {
count = n,
start = function(i: number): number
return (i - 1) * 1536
end,
decode = function(i: number): (number?, Err.Err?)
local frames, err = d:decode(buf, offs[i], sizes[i])
if frames and d.channels ~= h.channels then
return nil, Err.new(Err.UNSUPPORTED, "channel layout change inside the stream", offs[i])
end
return frames, err
end,
pcm = function(): { number }
return d.pcm
end,
reset = function()
d:reset()
end,
preroll = 1,
})
end
function Ac3Format.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
local dec, err = Ac3Format.open(r, opts)
if not dec then
return nil, err
end
local d: any = dec
return Pcm.drain(d, { format = "ac3", codec = "ac3", acmod = d.acmod, lfe = d.lfe, bitrate = d.bitrate })
end
return Ac3Format
+155
View File
@@ -0,0 +1,155 @@
--!strict
-- audio/adpcm: headerless ADPCM streams (.adpcm / .ima / .vox-style dumps), over codecs/audio/Adpcm. New in
-- rosetta. A raw stream has no header, so nothing identifies it: sniff is always 0, F.detect only finds it by
-- extension, and the layout comes from the options (codec, sampleRate, channels, blockAlign). vgmstream plays such
-- files only through a .txth description and ffmpeg not at all (its adpcm_* codecs need a container), so the codecs
-- here are the layouts those containers use:
-- "ima" IMA nibbles from predictor 0 / step index 0, channels interleaved by nibble, the high nibble first
-- (DVI order, as KVAG / adpcm_ima_ssi); lowFirst = true for the other order
-- "ima_wav" Microsoft IMA blocks (the WAV / AVI data chunk), blockAlign bytes each (default 1024)
-- "ms" Microsoft ADPCM blocks with the 7 standard coefficient pairs (default blockAlign 1024)
-- "ima_qt" Apple ima4 packets (34 bytes per channel, 64 frames), as in AIFF-C / CAF / QuickTime
-- "psx" Sony PS-ADPCM frames (16 bytes, 28 samples), channels interleaved every `interleave` bytes (default 16)
-- Encode: "ima", "ima_wav" and "ms" (from an Audio or a Decoder). Not supported: raw DSP / ADX (their coefficients
-- live in a header: see audio/brstm and audio/adx).
--
-- local a = Adpcm.decode(Bytes.reader(buf), { codec = "ms", sampleRate = 22050, channels = 2, blockAlign = 512 })
-- local raw = Adpcm.encode(a, { codec = "ima" })
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Pcm = require("@rosetta/codecs/audio/Pcm")
local Adpcm = require("@rosetta/codecs/audio/Adpcm")
local Decoder = require("@rosetta/codecs/audio/Adpcm/Decoder")
-- ------------------------------------------------------------------------------------------------ contract
local Raw = {
name = "adpcm",
category = "audio",
extensions = { "adpcm", "ima" },
mime = { "audio/x-adpcm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" },
caps = { decode = true, encode = true, streaming = true, lossy = true, headerless = true, codecs = { "ima", "ima_wav", "ms", "ima_qt", "psx" } },
}
-- ------------------------------------------------------------------------------------------------ types
export type Codec = "ima" | "ima_wav" | "ms" | "ima_qt" | "psx"
export type Options = {
codec: Codec?, -- default "ima"
sampleRate: number?, -- default 22050 (decode)
channels: number?, -- default 1 (decode)
blockAlign: number?, -- ima_wav / ms: bytes per block (default 1024 when decoding; 256 * channels when encoding)
lowFirst: boolean?, -- ima: the low nibble first
interleave: number?, -- psx: bytes per channel before the next channel (default 16)
maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28)
}
-- ------------------------------------------------------------------------------------------------ constants
local CODECS = { ima = true, ima_wav = true, ms = true, ima_qt = true, psx = true }
-- ------------------------------------------------------------------------------------------------ sniff
function Raw.sniff(_r: Bytes.Reader): number
return 0 -- no header: found by extension or opts.format only
end
-- ------------------------------------------------------------------------------------------------ decode
function Raw.decode(r: Bytes.Reader, opts: Options?): (Types.Audio?, Err.Err?)
local dec, err = Raw.open(r, opts)
if not dec then
return nil, err
end
local limit = opts and opts.maxFrames or 2 ^ 28
if dec.frames > limit or dec.frames * dec.channels > 2 ^ 28 then
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", dec.frames))
end
return Pcm.drain(dec, { format = "adpcm", codec = (dec :: any).codec }, limit)
end
-- ------------------------------------------------------------------------------------------------ encode
function Raw.encode(value: any, opts: Options?): (buffer?, Err.Err?)
local o: Options = opts or {}
local codec = o.codec or "ima"
if codec ~= "ima" and codec ~= "ima_wav" and codec ~= "ms" then
return nil, Err.new(Err.ARG, "encode: codec must be ima, ima_wav or ms")
end
local src, serr = Pcm.source(value)
if not src then
return nil, serr
end
local a, cerr = Pcm.collect(src)
if not a then
return nil, cerr
end
local ch, n, x = a.channels, a.frames, a.samples
if codec == "ima" then
local out = buffer.create((n * ch + 1) // 2)
local st = buffer.create(8 * ch)
for c = 0, ch - 1 do
Adpcm.imaEncode(x, c, ch, n, st, c * 8, out, 0, c, ch, not o.lowFirst)
end
return out, nil
end
local ba = o.blockAlign or 256 * ch
local spb = Decoder.blockFrames(codec, ba, ch)
if type(ba) ~= "number" or ba ~= math.floor(ba) or ba > 65535 or not spb or spb < 2 then
return nil, Err.new(Err.ARG, "bad blockAlign " .. tostring(ba))
end
if codec == "ima_wav" and (ba % (4 * ch) ~= 0) then
return nil, Err.new(Err.ARG, "ima_wav: blockAlign must be a multiple of 4 * channels")
end
local blocks = (n + spb - 1) // spb
local out = buffer.create(blocks * ba)
local st = buffer.create(8 * ch)
for b = 0, blocks - 1 do
local f0 = b * spb
if codec == "ms" then
Adpcm.msEncode(x, f0, n - f0, ch, spb, out, b * ba)
else
Adpcm.imaWavEncode(x, f0, n - f0, ch, spb, st, out, b * ba)
end
end
return out, nil
end
-- ------------------------------------------------------------------------------------------------ open
function Raw.open(r: Bytes.Reader, opts: Options?): (Types.Decoder?, Err.Err?)
if type(r) ~= "table" or type(r.buf) ~= "buffer" then
return nil, Err.new(Err.ARG, "open: expected a Reader")
end
local o: Options = opts or {}
local codec = o.codec or "ima"
local rate, ch = o.sampleRate or 22050, o.channels or 1
if not CODECS[codec] then
return nil, Err.new(Err.ARG, "unknown codec " .. tostring(codec))
end
if type(rate) ~= "number" or rate <= 0 or rate ~= rate or type(ch) ~= "number" or ch < 1 or ch > 255 or ch ~= math.floor(ch) then
return nil, Err.new(Err.ARG, "bad sampleRate or channels")
end
local size = r.limit - r.base
local dec: any = { sampleRate = rate, channels = ch, tags = {}, codec = codec, frames = 0, duration = 0 }
local d, err
if codec == "ima" then
d, err = Decoder.nibbles(dec, { buf = r.buf, offset = r.base, size = size, hi = not o.lowFirst })
elseif codec == "psx" then
local il = o.interleave or 16
if type(il) ~= "number" or il < 16 or il % 16 ~= 0 then
return nil, Err.new(Err.ARG, "interleave must be a multiple of 16")
end
d, err = Decoder.interleaved(dec, { kind = "psx", buf = r.buf, offset = r.base, size = size, interleave = if ch == 1 then 16 else il })
else
local ba = o.blockAlign or 1024
if type(ba) ~= "number" or ba < 1 or ba ~= math.floor(ba) then
return nil, Err.new(Err.ARG, "bad blockAlign")
end
d, err = Decoder.blocks(dec, { kind = codec :: any, buf = r.buf, offset = r.base, size = size, blockAlign = ba })
end
if not d then
return nil, err
end
d.bitrate = if d.duration > 0 then math.floor(size * 8 / d.duration) else 0
return d, nil
end
return Raw
+237
View File
@@ -0,0 +1,237 @@
--!strict
-- audio/adx: CRI ADX (.adx), the game-audio ADPCM of Sega / CRI Middleware, over codecs/audio/Adpcm. New in
-- rosetta; the header layout and the decoder details follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt),
-- whose output it matches bit for bit (the scale + 1 of CRI's decoders, the version 3 rounding; ffmpeg's ADX decoder
-- differs slightly on both). Supports: encoding type 3 (the standard predictor from the header's high-pass cutoff),
-- versions 3, 4 and 5, 1-8 channels, the initial history of version 4, loop points (dec.loop and
-- meta.source.loop = { start, stop } in frames, stop exclusive). Encode (Audio or Decoder): version 4, 1-8 channels,
-- loop points from opts.loop. Not supported: encrypted ADX (versions 0x0408 / 0x0409, keys needed), the fixed (2) and
-- exponential (4) encoding types, AHX.
--
-- local dec = Adx.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, version, cutoff)
-- local file = Adx.encode(audio, { loop = { start = 44100, stop = 441000 } })
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Pcm = require("@rosetta/codecs/audio/Pcm")
local Adpcm = require("@rosetta/codecs/audio/Adpcm")
local Decoder = require("@rosetta/codecs/audio/Adpcm/Decoder")
-- ------------------------------------------------------------------------------------------------ contract
local Adx = {
name = "adx",
category = "audio",
extensions = { "adx" },
mime = { "audio/x-adx" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" },
caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 8 },
}
-- ------------------------------------------------------------------------------------------------ types
export type Loop = { start: number, stop: number }
export type DecodeOptions = {
maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28)
}
export type EncodeOptions = {
loop: Loop?, -- loop points in frames (stop exclusive); default: the source's meta.source.loop / loop, else none
cutoff: number?, -- the predictor's high-pass cutoff in Hz (default 500, as CRI's encoders)
}
-- ------------------------------------------------------------------------------------------------ constants
local FRAME = 18
-- ------------------------------------------------------------------------------------------------ sniff
function Adx.sniff(r: Bytes.Reader): number
if r:peekU8(0) ~= 0x80 or r:peekU8(1) ~= 0 then
return 0
end
local off = r:peekU8(2) * 256 + r:peekU8(3)
return if r:peek(6, off - 2) == "(c)CRI" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Adx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
local dec, err = Adx.open(r)
if not dec then
return nil, err
end
local d = dec :: any
local limit = opts and opts.maxFrames or 2 ^ 28
if d.frames > limit or d.frames * d.channels > 2 ^ 28 then
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames))
end
return Pcm.drain(d, { format = "adx", version = d.version, cutoff = d.cutoff, loop = d.loop }, limit)
end
-- ------------------------------------------------------------------------------------------------ encode
function Adx.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: EncodeOptions = opts or {}
local src, serr = Pcm.source(value)
if not src then
return nil, serr
end
local ch, rate = src.channels, src.sampleRate
if ch > 8 then
return nil, Err.new(Err.ARG, "ADX holds at most 8 channels")
end
if rate ~= math.floor(rate) or rate < 1 or rate >= 2 ^ 31 then
return nil, Err.new(Err.ARG, "the sample rate must be a positive integer")
end
local loop = o.loop
if loop == nil then
local v = value :: any
local m = type(v.meta) == "table" and type(v.meta.source) == "table" and v.meta.source.loop
loop = if type(m) == "table" then m else (if type(v.loop) == "table" then v.loop else nil)
end
local a, cerr = Pcm.collect(src)
if not a then
return nil, cerr
end
local n = a.frames
if loop and (type(loop.start) ~= "number" or type(loop.stop) ~= "number" or loop.start < 0 or loop.stop <= loop.start or loop.stop > n) then
return nil, Err.new(Err.ARG, "loop must be { start, stop } inside the audio")
end
local cutoff = o.cutoff or 500
if type(cutoff) ~= "number" or cutoff < 1 or cutoff >= rate / 2 or cutoff > 65535 then
return nil, Err.new(Err.ARG, "bad cutoff")
end
cutoff = math.floor(cutoff)
local c1, c2 = Adpcm.adxCoefs(cutoff, rate)
local hist = if ch > 1 then 4 * ch else 8
local start = 0x18 + hist + (if loop then 0x18 else 0) + 6
start = (start + 3) // 4 * 4
local nframes = (n + 31) // 32
local w = Bytes.writer(start + (nframes + 1) * FRAME * ch)
w:u16be(0x8000)
w:u16be(start - 4)
w:u8(3)
w:u8(FRAME)
w:u8(4)
w:u8(ch)
w:u32be(rate)
w:u32be(n)
w:u16be(cutoff)
w:u16be(0x0400)
w:u32be(0)
w:fill(0, hist)
if loop then
local bytesAt = function(f: number): number
return start + (f // 32) * FRAME * ch
end
w:u16be(0)
w:u16be(1)
w:u32be(1)
w:u32be(loop.start)
w:u32be(bytesAt(loop.start))
w:u32be(loop.stop)
w:u32be(bytesAt(loop.stop + 31))
end
w:fill(0, start - 6 - w.pos)
w:string("(c)CRI")
local at = w:reserve(nframes * FRAME * ch)
local st = buffer.create(8 * ch)
for c = 0, ch - 1 do
Adpcm.adxEncode(a.samples, c, ch, n, c1, c2, st, c * 8, w.buf, at + c * FRAME, FRAME * ch)
end
w.pos = at + nframes * FRAME * ch
-- the end marker: scale 0x8001, then the padding size
w:u16be(0x8001)
w:u16be(FRAME - 4)
w:fill(0, FRAME - 4)
return w:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ open
function Adx.open(r: Bytes.Reader, _opts: any?): (Types.Decoder?, Err.Err?)
if type(r) ~= "table" or type(r.buf) ~= "buffer" then
return nil, Err.new(Err.ARG, "open: expected a Reader")
end
if Adx.sniff(r) == 0 then
return nil, Err.new(Err.CORRUPT, "not an ADX file")
end
local h = r:sub(0)
local copyright = (h:seek(2) and h:u16be()) or 0
local start = copyright + 4
local enc, fsize, bits, ch = h:u8(), h:u8(), h:u8(), h:u8()
local rate, frames, cutoff, version = h:u32be(), h:u32be(), h:u16be(), h:u16be()
if h.err then
return nil, h.err
end
if version == 0x0408 or version == 0x0409 then
return nil, Err.new(Err.UNSUPPORTED, "encrypted ADX (keys needed)")
end
if enc ~= 3 then
return nil, Err.new(Err.UNSUPPORTED, "encoding type " .. enc .. (if enc == 0x10 or enc == 0x11 then " (AHX)" else ""))
end
if fsize ~= FRAME or bits ~= 4 then
return nil, Err.new(Err.UNSUPPORTED, string.format("frame size %d, %d bits", fsize, bits))
end
if ch < 1 or ch > 8 then
return nil, Err.new(Err.CORRUPT, "bad channel count " .. ch)
end
if rate < 1 or rate >= 2 ^ 31 then
return nil, Err.new(Err.CORRUPT, "bad sample rate " .. rate)
end
if version ~= 0x0300 and version ~= 0x0400 and version ~= 0x0500 then
return nil, Err.new(Err.UNSUPPORTED, string.format("version 0x%04X", version))
end
local size = r.limit - r.base - start
if size < 0 then
return nil, Err.new(Err.TRUNCATED, "the header runs past the end")
end
-- loop points and the initial history (vgmstream's reading of the extra header fields)
local hist: { number }? = nil
local loopsAt: number? = nil
if version == 0x0300 then
if start - 6 >= 0x14 + 0x18 then
loopsAt = 0x14
end
elseif version == 0x0400 then
local hsize = if ch > 1 then 4 * ch else 8
hist = {}
for c = 0, ch - 1 do
local hh = r:sub(0x18 + c * 4, 4)
local h1, h2 = hh:i16be(), hh:i16be()
hist[c * 2 + 1], hist[c * 2 + 2] = if hh.err then 0 else h1, if hh.err then 0 else h2
end
local ainf = 0
local ai = r:sub(0x18 + hsize + 4, 8)
if ai:string(4) == "AINF" then
ainf = ai:u32be()
end
if start - ainf - 6 >= 0x18 + hsize + 0x18 then
loopsAt = 0x18 + hsize
end
end
local loopTable: { start: number, stop: number }? = nil
if loopsAt then
local l = r:sub(loopsAt + 4, 0x14)
local flag, ls, _, le = l:u32be(), l:u32be(), l:u32be(), l:u32be()
if not l.err and flag ~= 0 and le > ls then
loopTable = { start = ls, stop = le }
end
end
local c1, c2 = Adpcm.adxCoefs(cutoff, rate)
local dec: any = { sampleRate = rate, channels = ch, tags = {}, version = version, cutoff = cutoff, loop = loopTable }
local d, err = Decoder.interleaved(dec, {
kind = "adx",
buf = r.buf,
offset = r.base + start,
size = size,
interleave = FRAME,
frames = frames,
c1 = c1,
c2 = c2,
v3 = version == 0x0300,
hist = hist,
})
if not d then
return nil, err
end
d.bitrate = rate * FRAME * ch * 8 // 32
return d, nil
end
return Adx
+400
View File
@@ -0,0 +1,400 @@
--!strict
-- audio/aiff: AIFF and AIFF-C (Apple Audio Interchange File Format 1.3, AIFF-C draft 1991). New code from the specs.
-- Supports: decode / open of AIFF PCM (1..32 bits, big endian) and AIFF-C NONE / twos / sowt (little endian) / raw
-- (unsigned 8-bit) / in24 / in32 / fl32 / fl64 / ulaw / alaw; NAME / AUTH / (c) / ANNO chunks as tags; truncated
-- SSND data (the frames present are decoded, meta.source.truncated). Encode (Audio or Decoder, streamed) to AIFF 8 /
-- 16 / 24 / 32-bit, or AIFF-C sowt / fl32 / fl64 / ulaw / alaw. AIFF-C ima4 (Apple IMA ADPCM, codecs/audio/Adpcm;
-- COMM counts packets of 64 frames) decodes too. Not supported: the other compressed AIFF-C codecs (MAC3 / MAC6,
-- Qclp, ...: Err.UNSUPPORTED), MARK / INST loops (ignored), the ID3 chunk.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Chunks = require("@rosetta/containers/Chunks")
local Pcm = require("@rosetta/codecs/audio/Pcm")
local Adpcm = require("@rosetta/codecs/audio/Adpcm/Decoder")
-- ------------------------------------------------------------------------------------------------ contract
local Aiff = {
name = "aiff",
category = "audio",
extensions = { "aiff", "aif", "aifc", "afc" },
mime = { "audio/aiff", "audio/x-aiff" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder", "containers/Chunks" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false },
}
export type DecodeOptions = {
maxFrames: number?, -- refuse more sample frames (default 2^28)
}
export type EncodeOptions = {
sampleFormat: ("s8" | "s16" | "s24" | "s32" | "f32" | "f64" | "ulaw" | "alaw")?, -- default "s16"
littleEndian: boolean?, -- 16-bit samples as AIFF-C "sowt" (default false: big endian; readers such as ffmpeg only
-- take 16-bit sowt, so other formats return Err.ARG)
aifc: boolean?, -- always write AIFF-C (default: only when the sample format needs it)
}
-- ------------------------------------------------------------------------------------------------ constants
local TEXT_TAGS = { NAME = "title", AUTH = "artist", ["(c) "] = "copyright", ANNO = "comment" }
local TEXT_ORDER = { { "NAME", "title" }, { "AUTH", "artist" }, { "(c) ", "copyright" }, { "ANNO", "comment" } }
local AIFC_VERSION = 0xA2805140
-- ext80(b, o) -> the 80-bit IEEE extended float at b[o] (big endian)
local function ext80(b: buffer, o: number): number
local se = buffer.readu8(b, o) * 256 + buffer.readu8(b, o + 1)
local hi = bit32.byteswap(buffer.readu32(b, o + 2))
local lo = bit32.byteswap(buffer.readu32(b, o + 6))
local e = bit32.band(se, 0x7FFF)
if e == 0 and hi == 0 and lo == 0 then
return 0
end
if e == 0x7FFF then
return math.huge
end
local v = (hi * 4294967296 + lo) * 2 ^ (e - 16383 - 63)
return if se >= 0x8000 then -v else v
end
-- the 10 bytes of x (> 0) as an 80-bit extended float
local function writeExt80(w: Bytes.Writer, x: number)
if x <= 0 or x ~= x then
w:fill(0, 10)
return
end
local e = 0
while x >= 2 ^ (e + 1) do
e += 1
end
while x < 2 ^ e do
e -= 1
end
local m = x * 2 ^ (63 - e) -- in [2^63, 2^64)
local hi = math.floor(m / 4294967296)
local lo = m - hi * 4294967296
w:u16be(e + 16383)
w:u32be(hi)
w:u32be(math.floor(lo))
end
-- the sample format of a COMM chunk: Pcm format name | nil, message
local function sampleFormat(comp: string, bits: number): (string?, string?)
if comp == "NONE" or comp == "twos" or comp == "" then
if bits >= 1 and bits <= 8 then
return "s8", nil
elseif bits <= 16 then
return "s16be", nil
elseif bits <= 24 then
return "s24be", nil
elseif bits <= 32 then
return "s32be", nil
end
return nil, "bad sample size " .. bits
elseif comp == "sowt" then
if bits >= 1 and bits <= 8 then
return "s8", nil
elseif bits <= 16 then
return "s16le", nil
elseif bits <= 24 then
return "s24le", nil
elseif bits <= 32 then
return "s32le", nil
end
return nil, "bad sample size " .. bits
elseif comp == "raw " then
return "u8", nil
elseif comp == "in24" then
return "s24be", nil
elseif comp == "in32" then
return "s32be", nil
elseif comp == "42ni" then
return "s32le", nil
elseif comp == "fl32" or comp == "FL32" then
return "f32be", nil
elseif comp == "fl64" or comp == "FL64" then
return "f64be", nil
elseif comp == "ulaw" or comp == "ULAW" then
return "ulaw", nil
elseif comp == "alaw" or comp == "ALAW" then
return "alaw", nil
elseif comp == "ima4" then
return "ima4", nil -- not a Pcm format: Adpcm/Decoder.blocks
end
return nil, "compression " .. string.format("%q", comp)
end
-- ------------------------------------------------------------------------------------------------ sniff
function Aiff.sniff(r: Bytes.Reader): number
if r:remaining() < 12 or r:peek(4) ~= "FORM" then
return 0
end
local form = buffer.readstring(r.buf, r.pos + 8, 4)
return if form == "AIFF" or form == "AIFC" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
type Info = {
channels: number,
frames: number,
sampleRate: number,
bits: number,
format: string,
compression: string,
aifc: boolean,
dataOffset: number, -- absolute in r.buf
dataSize: number, -- bytes of sample data present
truncated: boolean,
tags: Types.Tags,
}
-- parse(r) -> Info | nil, Err (walks the chunks; does not decode samples)
local function parse(r: Bytes.Reader): (Info?, Err.Err?)
local b = r.buf
local base, limit = r.base, r.limit
if limit - base < 12 or buffer.readstring(b, base, 4) ~= "FORM" then
return nil, Err.new(Err.CORRUPT, "not a FORM file", base)
end
local form = buffer.readstring(b, base + 8, 4)
if form ~= "AIFF" and form ~= "AIFC" then
return nil, Err.new(Err.CORRUPT, "FORM type " .. string.format("%q", form) .. " is not AIFF / AIFC", base + 8)
end
local aifc = form == "AIFC"
local formEnd = math.min(limit, base + 8 + bit32.byteswap(buffer.readu32(b, base + 4)))
local info: Info? = nil
local comm = false
local ssnd: number? = nil
local ssndLen = 0
local tags: Types.Tags = {}
-- (walked to the end of the data: a FORM size that undercounts still reads the last chunk's body)
for _, c in Chunks.walk(b, base + 12, limit, Chunks.IFF) do
local id, len, d, avail, p = c.id, c.declared, c.offset, c.avail, c.start
if p + 8 > formEnd then
break
end
if id == "COMM" then
if avail < 18 or (aifc and avail < 22) then
return nil, Err.new(Err.TRUNCATED, "COMM chunk too short", p)
end
local ch = buffer.readu8(b, d) * 256 + buffer.readu8(b, d + 1)
local frames = bit32.byteswap(buffer.readu32(b, d + 2))
local bits = buffer.readu8(b, d + 6) * 256 + buffer.readu8(b, d + 7)
local rate = ext80(b, d + 8)
local comp = if aifc then buffer.readstring(b, d + 18, 4) else "NONE"
if ch < 1 then
return nil, Err.new(Err.CORRUPT, "no channels", d)
end
if not (rate > 0 and rate < 2 ^ 31) then
return nil, Err.new(Err.CORRUPT, "bad sample rate", d + 8)
end
local fmt, why = sampleFormat(comp, bits)
if not fmt then
return nil, Err.new(if comp == "NONE" or comp == "twos" or comp == "sowt" then Err.CORRUPT else Err.UNSUPPORTED, why :: string, d + 18)
end
info = {
channels = ch,
frames = frames,
sampleRate = rate,
bits = bits,
format = fmt,
compression = comp,
aifc = aifc,
dataOffset = 0,
dataSize = 0,
truncated = false,
tags = tags,
}
comm = true
elseif id == "SSND" then
if avail < 8 then
return nil, Err.new(Err.TRUNCATED, "SSND chunk too short", p)
end
local off = bit32.byteswap(buffer.readu32(b, d))
ssnd = d + 8 + off
ssndLen = math.max(0, avail - 8 - off)
if len >= 8 + off then
ssndLen = math.min(ssndLen, len - 8 - off)
end
elseif TEXT_TAGS[id] then
local s = buffer.readstring(b, d, avail)
local z = string.find(s, "\0", 1, true)
if z then
s = string.sub(s, 1, z - 1)
end
local key = TEXT_TAGS[id]
tags[key] = if tags[key] then tags[key] .. "\n" .. s else s
end
if len > formEnd - d then
break
end
end
if not comm or not info then
return nil, Err.new(Err.CORRUPT, "no COMM chunk", base)
end
local fi = info :: Info
if fi.frames > 0 and not ssnd then
return nil, Err.new(Err.TRUNCATED, "no SSND chunk", base)
end
local present
if fi.format == "ima4" then
fi.frames *= 64 -- COMM counts packets
present = if ssnd then ssndLen // (34 * fi.channels) * 64 else 0
else
present = if ssnd then ssndLen // (fi.channels * Pcm.Convert.SIZE[fi.format]) else 0
end
if present < fi.frames then
fi.frames = present
fi.truncated = true
end
fi.dataOffset = ssnd or base
fi.dataSize = ssndLen
return fi, nil
end
-- info(r) -> { channels, frames, sampleRate, bits, format, compression, aifc, tags } | nil, Err
function Aiff.info(r: Bytes.Reader): (Info?, Err.Err?)
return parse(r)
end
function Aiff.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
local dec, err = Aiff.open(r, opts)
if not dec then
return nil, err
end
return Pcm.drain(dec)
end
-- ------------------------------------------------------------------------------------------------ encode
local FORMATS = {
s8 = { "s8", 8, "NONE" },
s16 = { "s16be", 16, "NONE" },
s24 = { "s24be", 24, "NONE" },
s32 = { "s32be", 32, "NONE" },
f32 = { "f32be", 32, "fl32" },
f64 = { "f64be", 64, "fl64" },
ulaw = { "ulaw", 16, "ulaw" },
alaw = { "alaw", 16, "alaw" },
}
local LE = { s16be = "s16le" }
local COMP_NAMES = { NONE = "not compressed", sowt = "", fl32 = "32-bit floating point", fl64 = "64-bit floating point", ulaw = "\181Law 2:1", alaw = "ALaw 2:1" }
function Aiff.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local src, serr = Pcm.source(value)
if not src then
return nil, serr
end
local o: EncodeOptions = opts or {}
local spec = FORMATS[o.sampleFormat or "s16"]
if not spec then
return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat))
end
local fmt, bits, comp = spec[1], spec[2], spec[3]
if o.littleEndian then
if not LE[fmt] then
return nil, Err.new(Err.ARG, "littleEndian needs 16-bit samples")
end
fmt, comp = LE[fmt], "sowt"
end
if src.channels > 65535 then
return nil, Err.new(Err.ARG, "too many channels")
end
local aifc = o.aifc or comp ~= "NONE"
local w = Bytes.writer(65536)
w:string("FORM")
w:u32be(0) -- patched
w:string(if aifc then "AIFC" else "AIFF")
if aifc then
w:string("FVER")
w:u32be(4)
w:u32be(AIFC_VERSION)
end
-- text chunks from the tags
for _, pair in TEXT_ORDER do
local id, key = pair[1], pair[2]
local s = src.tags[key]
if type(s) == "string" and #s > 0 then
w:string(id)
w:u32be(#s)
w:string(s)
if #s % 2 == 1 then
w:u8(0)
end
end
end
local commAt = w:tell()
w:string("COMM")
if aifc then
local name = COMP_NAMES[comp] or ""
local plen = 1 + #name
plen += plen % 2
w:u32be(22 + plen)
else
w:u32be(18)
end
w:u16be(src.channels)
w:u32be(0) -- frames, patched
w:u16be(bits)
writeExt80(w, src.sampleRate)
if aifc then
w:string(comp)
local name = COMP_NAMES[comp] or ""
w:u8(#name)
w:string(name)
if (1 + #name) % 2 == 1 then
w:u8(0)
end
end
local ssndAt = w:tell()
w:string("SSND")
w:u32be(0) -- patched
w:u32be(0) -- offset
w:u32be(0) -- block size
local frames, perr = Pcm.encode(src, fmt, w)
if not frames then
return nil, perr
end
local dataLen = w:tell() - ssndAt - 16
if dataLen % 2 == 1 then
w:u8(0)
end
w:setU32be(ssndAt + 4, dataLen + 8)
w:setU32be(commAt + 10, frames)
w:setU32be(4, w:tell() - 8)
return w:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ open
function Aiff.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
local info, err = parse(r)
if not info then
return nil, err
end
local maxFrames = opts and opts.maxFrames or 2 ^ 28
if info.frames > maxFrames then
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the %d frame limit", info.frames, maxFrames))
end
local dec, derr
if info.format == "ima4" then
local base = { sampleRate = info.sampleRate, channels = info.channels, tags = info.tags }
dec, derr = Adpcm.blocks(base, { kind = "ima_qt", buf = r.buf, offset = info.dataOffset, size = info.dataSize, frames = info.frames })
if dec then
(dec :: any).bitrate = math.floor(info.sampleRate * 34 * 8 * info.channels / 64)
end
else
dec, derr = Pcm.rawDecoder(r.buf, info.dataOffset, info.frames, info.channels, info.sampleRate, info.format, info.tags)
end
if not dec then
return nil, derr
end
local d = dec :: any
d.source = {
format = "aiff",
aifc = info.aifc,
compression = info.compression,
bitDepth = info.bits,
sampleFormat = info.format,
truncated = info.truncated or nil,
}
return dec, nil
end
return Aiff
+134
View File
@@ -0,0 +1,134 @@
--!strict
-- audio/ape: Monkey's Audio (.ape) files around codecs/audio/Ape: the header in front (after an optional ID3v2 tag),
-- the frames (each independent: sample-accurate seeking through the seek table), APEv2 tags at the end
-- (codecs/audio/ApeTag). Written from the Monkey's Audio SDK 13.28 (BSD 3-clause, licenses/monkeys-audio-LICENSE.txt).
-- Supports file versions 3.95 and later, every compression level, 8 - 32-bit integer and 32-bit float, 1 - 32
-- channels (as the source WAV ordered them). Not supported: files before 3.95, encoding.
--
-- local dec = Ape.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, level, version, float, md5
-- local i32, n = dec:readInt(4096) -- integer files: the samples as `mac -d` writes them
-- local audio = Ape.decode(Bytes.reader(buf)) -- Types.Audio
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Pcm = require("@rosetta/codecs/audio/Pcm")
local Stream = require("@rosetta/codecs/audio/Stream")
local ApeTag = require("@rosetta/codecs/audio/ApeTag")
local ApeCodec = require("@rosetta/codecs/audio/Ape")
-- ------------------------------------------------------------------------------------------------ contract
local Ape = {
name = "ape",
category = "audio",
extensions = { "ape" },
mime = { "audio/ape", "audio/x-ape", "audio/x-monkeys-audio" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Ape" },
caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, float = true, depths = { 8, 16, 24, 32 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
maxFrames: number?, -- decode(): refuse longer streams (default 2^28)
}
-- ------------------------------------------------------------------------------------------------ constants
local LEVELS = { [1000] = "fast", [2000] = "normal", [3000] = "high", [4000] = "extra high", [5000] = "insane" }
-- ------------------------------------------------------------------------------------------------ sniff
function Ape.sniff(r: Bytes.Reader): number
local head = r:peek(4)
if head == "MAC " or head == "MACF" then -- MACF: float samples
return 1
end
if string.sub(head, 1, 3) == "ID3" then
local sz = 0
for i = 6, 9 do
local v = r:peekU8(i)
if v < 0 then
return 0
end
sz = sz * 128 + bit32.band(v, 127)
end
local footer = bit32.band(math.max(r:peekU8(5), 0), 0x10) ~= 0
local id = r:peek(4, 10 + sz + (if footer then 10 else 0))
return if id == "MAC " or id == "MACF" then 1 else 0
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream
function Ape.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?)
local dec, err = Ape.open(r, opts)
if not dec then
return nil, err
end
local d = dec :: any
local limit = opts and opts.maxFrames or 2 ^ 28
if d.frames > limit or d.frames * d.channels > 2 ^ 28 then
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames))
end
return Pcm.drain(d, d.source, limit)
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts?) -> Decoder | nil, Err
function Ape.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?)
if type(r) == "buffer" then
r = Bytes.reader(r :: any)
end
if type(r) ~= "table" or type(r.buf) ~= "buffer" then
return nil, Err.new(Err.ARG, "open: expected a Reader")
end
local buf, base, limit = r.buf, r.base, r.limit
local tags, tagInfo = ApeTag.find(buf, base, limit)
local stop = if tagInfo then tagInfo.start else limit
local info, err = ApeCodec.info(buf, base, stop)
if not info then
return nil, err
end
if info.channels * info.blocksPerFrame > 2 ^ 24 then
return nil, Err.new(Err.LIMIT, "frames of " .. info.blocksPerFrame .. " blocks")
end
local codec, cerr = ApeCodec.decoder(info)
if not codec then
return nil, cerr
end
local frames = info.totalBlocks
local bpf = info.blocksPerFrame
local dec: any = {
sampleRate = info.sampleRate,
channels = info.channels,
frames = frames,
duration = frames / info.sampleRate,
bitrate = if frames > 0 then math.floor((stop - base) * 8 * info.sampleRate / frames) else 0,
tags = tags or {},
bitsPerSample = info.bitsPerSample,
float = info.float,
level = LEVELS[info.level] or tostring(info.level),
version = info.version,
md5 = info.md5,
source = { format = "ape", bitDepth = info.bitsPerSample, float = info.float, level = info.level, version = info.version, programVersion = info.programVersion, tags = tagInfo and tagInfo.items },
}
local count = info.totalFrames
return Stream.packets(dec, {
count = count,
start = function(i: number): number
return if i > count then frames else (i - 1) * bpf
end,
decode = function(i: number): (number?, Err.Err?)
return codec:frame(buf, i)
end,
pcm = function(): { number }
return codec.pcm
end,
reset = function() end,
stop = frames,
scale = if info.float then 1 else 1 / 2 ^ (info.bitsPerSample - 1),
ints = not info.float,
})
end
return Ape
+161
View File
@@ -0,0 +1,161 @@
--!strict
-- audio/au: Sun / NeXT audio (.au / .snd), big endian. New code from the Sun audio file format description.
-- Supports: decode / open of encodings 1 (G.711 mu-law), 2 (8-bit), 3 (16-bit), 4 (24-bit), 5 (32-bit linear),
-- 6 (32-bit float), 7 (64-bit float), 27 (G.711 A-law); an unknown data size (0xFFFFFFFF: to the end of the file);
-- the annotation as tags.comment. Encode (Audio or Decoder, streamed) to any of those encodings (default 16-bit).
-- Not supported: G.721 / G.722 / G.723 ADPCM and the other NeXT encodings (Err.UNSUPPORTED).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Pcm = require("@rosetta/codecs/audio/Pcm")
-- ------------------------------------------------------------------------------------------------ contract
local Au = {
name = "au",
category = "audio",
extensions = { "au", "snd" },
mime = { "audio/basic", "audio/x-au" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false },
}
export type DecodeOptions = {
maxFrames: number?, -- refuse more sample frames (default 2^28)
}
export type EncodeOptions = {
sampleFormat: ("s8" | "s16" | "s24" | "s32" | "f32" | "f64" | "ulaw" | "alaw")?, -- default "s16"
}
-- ------------------------------------------------------------------------------------------------ constants
local ENCODINGS: { [number]: string } = {
[1] = "ulaw",
[2] = "s8",
[3] = "s16be",
[4] = "s24be",
[5] = "s32be",
[6] = "f32be",
[7] = "f64be",
[27] = "alaw",
}
local WRITE = {
ulaw = { 1, "ulaw" },
s8 = { 2, "s8" },
s16 = { 3, "s16be" },
s24 = { 4, "s24be" },
s32 = { 5, "s32be" },
f32 = { 6, "f32be" },
f64 = { 7, "f64be" },
alaw = { 27, "alaw" },
}
local BITS = { ulaw = 8, alaw = 8, s8 = 8, s16be = 16, s24be = 24, s32be = 32, f32be = 32, f64be = 64 }
local function be32(b: buffer, o: number): number
return bit32.byteswap(buffer.readu32(b, o))
end
-- ------------------------------------------------------------------------------------------------ sniff
function Au.sniff(r: Bytes.Reader): number
return if r:peek(4) == ".snd" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Au.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
local dec, err = Au.open(r, opts)
if not dec then
return nil, err
end
return Pcm.drain(dec)
end
-- ------------------------------------------------------------------------------------------------ encode
function Au.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local src, serr = Pcm.source(value)
if not src then
return nil, serr
end
local o: EncodeOptions = opts or {}
local spec = WRITE[o.sampleFormat or "s16"]
if not spec then
return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat))
end
if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate >= 2 ^ 32 then
return nil, Err.new(Err.ARG, "the sample rate must be an integer")
end
-- annotation: the comment tag, NUL-terminated, padded to a multiple of 8 (at least 4 bytes, as Sun requires)
local note = if type(src.tags.comment) == "string" then src.tags.comment else ""
local alen = #note + 1
alen = math.max(8, alen + (8 - alen % 8) % 8)
local w = Bytes.writer(65536)
w:string(".snd")
w:u32be(24 + alen)
w:u32be(0xFFFFFFFF) -- patched
w:u32be(spec[1])
w:u32be(src.sampleRate)
w:u32be(src.channels)
w:string(note)
w:fill(0, alen - #note)
local frames, perr = Pcm.encode(src, spec[2], w)
if not frames then
return nil, perr
end
w:setU32be(8, w:tell() - 24 - alen)
return w:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ open
function Au.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
local b, base, limit = r.buf, r.base, r.limit
if limit - base < 24 or buffer.readstring(b, base, 4) ~= ".snd" then
return nil, Err.new(Err.CORRUPT, "bad magic", base)
end
local off, size, enc, rate, ch = be32(b, base + 4), be32(b, base + 8), be32(b, base + 12), be32(b, base + 16), be32(b, base + 20)
local fmt = ENCODINGS[enc]
if not fmt then
return nil, Err.new(Err.UNSUPPORTED, "encoding " .. enc, base + 12)
end
if ch < 1 or ch > 65535 then
return nil, Err.new(Err.CORRUPT, "bad channel count " .. ch, base + 20)
end
if rate < 1 then
return nil, Err.new(Err.CORRUPT, "bad sample rate", base + 16)
end
if off < 24 or off > limit - base then
return nil, Err.new(Err.CORRUPT, "bad data offset", base + 4)
end
local tags: Types.Tags = {}
if off > 24 then
local s = buffer.readstring(b, base + 24, off - 24)
local z = string.find(s, "\0", 1, true)
if z then
s = string.sub(s, 1, z - 1)
end
if #s > 0 then
tags.comment = s
end
end
local avail = limit - base - off
local truncated = false
if size == 0xFFFFFFFF then
size = avail
elseif size > avail then
size = avail
truncated = true
end
local frameBytes = ch * Pcm.Convert.SIZE[fmt]
local frames = size // frameBytes
local maxFrames = opts and opts.maxFrames or 2 ^ 28
if frames > maxFrames then
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the %d frame limit", frames, maxFrames))
end
local dec, derr = Pcm.rawDecoder(b, base + off, frames, ch, rate, fmt, tags)
if not dec then
return nil, derr
end
local d = dec :: any
d.source = { format = "au", encoding = enc, sampleFormat = fmt, bitDepth = BITS[fmt], truncated = truncated or nil }
return dec, nil
end
return Au
+298
View File
@@ -0,0 +1,298 @@
--!strict
-- audio/brstm: Nintendo's streamed audio: BRSTM (Wii, "RSTM", big-endian), BCSTM (3DS, "CSTM", little-endian) and
-- BFSTM (Wii U big-endian / Switch little-endian, "FSTM"), over codecs/audio/Adpcm. New in rosetta; the layouts
-- follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), whose output it matches bit for bit. Supports: DSP
-- ADPCM (with the header's initial history; seeks into blocks not yet played use the ADPC / SEEK history table), PCM16
-- and PCM8, 1-255 channels in block-interleaved layout, the loop start (dec.loop and meta.source.loop = { start, stop }
-- in frames, stop exclusive). Read only. Not supported: BCSTM IMA ADPCM, BRSTM version 0.1 (beta), BFSTM regions
-- (the whole stream plays), the track table (channels are not grouped).
--
-- local dec = Brstm.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, container, codec)
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Pcm = require("@rosetta/codecs/audio/Pcm")
local Decoder = require("@rosetta/codecs/audio/Adpcm/Decoder")
-- ------------------------------------------------------------------------------------------------ contract
local Brstm = {
name = "brstm",
category = "audio",
extensions = { "brstm", "bcstm", "bfstm" },
mime = { "audio/x-brstm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder" },
caps = { decode = true, encode = false, streaming = true, lossy = true, loops = true, containers = { "RSTM", "CSTM", "FSTM" } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28)
}
-- ------------------------------------------------------------------------------------------------ constants
local CODECS = { [0] = "pcm8", [1] = "pcm16", [2] = "dsp", [3] = "ima" }
-- ------------------------------------------------------------------------------------------------ sniff
function Brstm.sniff(r: Bytes.Reader): number
local m = r:peek(4)
if m ~= "RSTM" and m ~= "CSTM" and m ~= "FSTM" then
return 0
end
local bom = r:peek(2, 4)
return if bom == "\254\255" or bom == "\255\254" then 1 else 0
end
-- variant(r) -> "brstm" / "bcstm" / "bfstm": the flavour, for F.detect
function Brstm.variant(r: Bytes.Reader): string?
local m = r:peek(4)
return if m == "RSTM" then "brstm" elseif m == "CSTM" then "bcstm" elseif m == "FSTM" then "bfstm" else nil
end
-- ------------------------------------------------------------------------------------------------ decode
function Brstm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
local dec, err = Brstm.open(r)
if not dec then
return nil, err
end
local d = dec :: any
local limit = opts and opts.maxFrames or 2 ^ 28
if d.frames > limit or d.frames * d.channels > 2 ^ 28 then
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames))
end
return Pcm.drain(d, { format = "brstm", container = d.container, codec = d.codec, loop = d.loop }, limit)
end
-- ------------------------------------------------------------------------------------------------ open
-- a reader of the whole file in its byte order: u8 / u16 / u32 / i16 / i32 at absolute offsets (relative to the file
-- start); a read out of range records the error in .err and returns 0
local function view(r: Bytes.Reader, be: boolean)
local v = { err = nil :: string? }
local size = r.limit - r.base
local function at(o: number, n: number): Bytes.Reader?
if o < 0 or o + n > size then
v.err = "an offset points past the end"
return nil
end
return r:sub(o, n)
end
function v.u8(o: number): number
local s = at(o, 1)
return if s then s:u8() else 0
end
function v.u16(o: number): number
local s = at(o, 2)
return if s then (if be then s:u16be() else s:u16le()) else 0
end
function v.i16(o: number): number
local s = at(o, 2)
return if s then (if be then s:i16be() else s:i16le()) else 0
end
function v.u32(o: number): number
local s = at(o, 4)
return if s then (if be then s:u32be() else s:u32le()) else 0
end
function v.i32(o: number): number
local s = at(o, 4)
return if s then (if be then s:i32be() else s:i32le()) else 0
end
return v
end
type Layout = {
codec: number,
loop: boolean,
ch: number,
rate: number,
loopStart: number,
frames: number,
blockSize: number,
lastPadded: number,
data: number, -- the first block (absolute in the file)
adp: { number }, -- each channel's DSP info offset (coefficients, then gain, ps, yn1, yn2)
hist: number?, -- the per-block history table: (yn1, yn2) per channel per block
histEntries: number,
}
local function parseRstm(v: any): (Layout?, string?)
if v.u16(0x06) ~= 0x0100 then
return nil, string.format("unsupported: BRSTM version %d.%d", v.u8(0x06), v.u8(0x07))
end
local head = v.u32(0x10)
local adpc = v.u32(0x18)
if v.u32(head) ~= 0x48454144 then -- "HEAD", read big-endian
return nil, "no HEAD chunk"
end
local base = head + 8
local info = base + v.u32(base + 4)
local chans = base + v.u32(base + 20)
local ch = v.u8(info + 2)
local L: Layout = {
codec = v.u8(info),
loop = v.u8(info + 1) ~= 0,
ch = ch,
rate = v.u16(info + 4),
loopStart = v.u32(info + 8),
frames = v.u32(info + 12),
data = v.u32(info + 16),
blockSize = v.u32(info + 24),
lastPadded = v.u32(info + 40),
adp = {},
hist = nil,
histEntries = 0,
}
for c = 0, ch - 1 do
local ci = base + v.u32(chans + 4 + c * 8 + 4)
L.adp[c + 1] = base + v.u32(ci + 4)
end
if adpc > 0 and v.u32(adpc) == 0x41445043 then -- "ADPC"
L.hist = adpc + 8
L.histEntries = (v.u32(adpc + 4) - 8) // math.max(1, 4 * ch)
end
return L, nil
end
local function parseFstm(v: any): (Layout?, string?)
local info: number, seek: number, data: number = 0, 0, 0
local seekSize: number = 0
for i = 0, math.min(v.u16(0x10), 16) - 1 do
local id, off = v.u16(0x14 + i * 12), v.u32(0x14 + i * 12 + 4)
if id == 0x4000 then
info = off
elseif id == 0x4001 then
seek = off
seekSize = v.u32(0x14 + i * 12 + 8) :: number
elseif id == 0x4002 then
data = off
end
end
if info == 0 or data == 0 then
return nil, "no INFO or DATA block"
end
local stream = info + 8 + v.i32(info + 0x0C)
local chans = info + 8 + v.i32(info + 0x1C)
local ch = v.u8(stream + 2)
local dataRef = stream + 0x30
local L: Layout = {
codec = v.u8(stream),
loop = v.u8(stream + 1) ~= 0,
ch = ch,
rate = v.u32(stream + 4),
loopStart = v.u32(stream + 8),
frames = v.u32(stream + 12),
blockSize = v.u32(stream + 20),
lastPadded = v.u32(stream + 36),
data = if v.u16(dataRef) == 0x1F00 then data + 8 + v.i32(dataRef + 4) else data + 0x20,
adp = {},
hist = nil,
histEntries = 0,
}
for c = 0, ch - 1 do
local ci = chans + v.i32(chans + 4 + c * 8 + 4)
L.adp[c + 1] = ci + v.i32(ci + 4)
end
if seek > 0 and seekSize > 8 then
L.hist = seek + 8
L.histEntries = (seekSize - 8) // math.max(1, 4 * ch)
end
return L, nil
end
function Brstm.open(r: Bytes.Reader, _opts: any?): (Types.Decoder?, Err.Err?)
if type(r) ~= "table" or type(r.buf) ~= "buffer" then
return nil, Err.new(Err.ARG, "open: expected a Reader")
end
if r.limit - r.base < 0x40 then
return nil, Err.new(Err.TRUNCATED, "the header runs past the end")
end
if Brstm.sniff(r) == 0 then
return nil, Err.new(Err.CORRUPT, "not a BRSTM / BCSTM / BFSTM file")
end
local magic = r:peek(4)
local be = r:peek(2, 4) == "\254\255"
local v = view(r, be)
local parsed: Layout?, msg: string?
if magic == "RSTM" then
if not be then
return nil, Err.new(Err.CORRUPT, "a little-endian BRSTM")
end
parsed, msg = parseRstm(v)
else
parsed, msg = parseFstm(v)
end
if v.err then
return nil, Err.new(Err.TRUNCATED, v.err)
elseif not parsed then
return nil, Err.from(msg)
end
local L = parsed :: Layout
local codec = CODECS[L.codec]
if not codec then
return nil, Err.new(Err.CORRUPT, "codec " .. L.codec)
elseif codec == "ima" then
return nil, Err.new(Err.UNSUPPORTED, "IMA ADPCM streams")
end
local ch = L.ch
if ch < 1 or L.rate < 1 then
return nil, Err.new(Err.CORRUPT, "bad channel count or sample rate")
end
local size = r.limit - r.base - L.data
if L.data < 0 or size < 0 then
return nil, Err.new(Err.TRUNCATED, "the data starts past the end")
end
local kind = if codec == "dsp" then "dsp" elseif codec == "pcm8" then "s8" elseif be then "s16be" else "s16le"
local coefs: buffer? = nil
local hist: { number }? = nil
if codec == "dsp" then
coefs = buffer.create(64 * ch)
hist = {}
for c = 0, ch - 1 do
local adp = L.adp[c + 1]
for k = 0, 15 do
buffer.writei32(coefs :: buffer, c * 64 + k * 4, v.i16(adp + k * 2))
end
hist[c * 2 + 1], hist[c * 2 + 2] = v.i16(adp + 36), v.i16(adp + 38)
end
if v.err then
return nil, Err.new(Err.TRUNCATED, v.err)
end
end
local histAt, entries = L.hist, L.histEntries
local loop = if L.loop and L.loopStart < L.frames then { start = L.loopStart, stop = L.frames } else nil
local dec: any = { sampleRate = L.rate, channels = ch, tags = {}, container = magic, codec = codec, loop = loop }
local block = L.blockSize
if block < 1 or (kind == "dsp" and block % 8 ~= 0) or (kind ~= "s8" and block % 2 ~= 0) then
return nil, Err.new(Err.CORRUPT, "bad block size " .. block)
end
local d, err = Decoder.interleaved(dec, {
kind = kind :: any,
buf = r.buf,
offset = r.base + L.data,
size = size,
interleave = block,
lastInterleave = if L.lastPadded > 0 and L.lastPadded <= block then L.lastPadded else block,
frames = L.frames,
coefs = coefs,
hist = hist,
restore = if codec == "dsp" and histAt
then function(row: number, st: buffer): boolean
if row >= entries then
return false
end
for c = 0, ch - 1 do
local p = (histAt :: number) + (row * ch + c) * 4
buffer.writei32(st, c * 8, v.i16(p))
buffer.writei32(st, c * 8 + 4, v.i16(p + 2))
end
return v.err == nil
end
else nil,
})
if d then
d.bitrate = if d.duration > 0 then math.floor(size * 8 / d.duration) else 0
end
return d, err
end
return Brstm
+668
View File
@@ -0,0 +1,668 @@
--!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/audio/Alac), AAC-LC (codecs/audio/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. IMA4 (Apple IMA ADPCM, codecs/audio/Adpcm) decodes too, with exact seeking. Not supported:
-- other compressed formats (UNSUPPORTED).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Chunks = require("@rosetta/containers/Chunks")
local Pcm = require("@rosetta/codecs/audio/Pcm")
local Stream = require("@rosetta/codecs/audio/Stream")
local Aac = require("@rosetta/codecs/audio/Aac")
local Alac = require("@rosetta/codecs/audio/Alac")
local Adpcm = require("@rosetta/codecs/audio/Adpcm/Decoder")
-- ------------------------------------------------------------------------------------------------ contract
local Caf = {
name = "caf",
category = "audio",
extensions = { "caf", "caff" },
mime = { "audio/x-caf" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Adpcm/Decoder", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream", "containers/Chunks" },
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
local p: Parsed = { desc = nil :: any, dataStart = 0, dataEnd = 0, priming = 0, remainder = 0, tags = {} }
local haveData = false
-- 64-bit big-endian chunk sizes; the data chunk may say -1 (= to the end) or run past a truncated file
for _, ch in Chunks.walk(r.buf, r.base + 8, r.limit, { bigEndian = true, sizeBytes = 8, openEnded = { data = true } }) do
local typ, start = ch.id, ch.offset
if ch.truncated and typ ~= "data" then
return nil, Err.new(Err.TRUNCATED, "chunk '" .. typ .. "' runs past the end", ch.start)
end
local stop = start + ch.avail
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 string.lower(k)] = v
end
end
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 or (#sizes == 0 and d.bytesPerPacket > 0) then -- constant packets: pakt may list none
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 :: { number }), 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 pp = p :: Parsed
if pp.desc.format == "ima4" then
-- Apple IMA ADPCM: 34-byte packets per channel, 64 frames; the predictor carries across packets
local ch = pp.desc.channels
local packets = (pp.dataEnd - pp.dataStart) // (34 * ch)
local frames = packets * 64
if pp.validFrames and pp.validFrames >= 0 then
frames = math.min(frames, pp.validFrames)
end
local dec: any = { sampleRate = pp.desc.rate, channels = ch, tags = pp.tags, codec = "ima4", bitsPerSample = 16 }
local d, derr = Adpcm.blocks(dec, { kind = "ima_qt", buf = r.buf, offset = pp.dataStart, size = pp.dataEnd - pp.dataStart, frames = frames })
if d then
d.bitrate = math.floor(pp.desc.rate * 34 * 8 * ch / 64)
end
return d, derr
end
local s, serr = source(r, pp)
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 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,
}
return Stream.packets(dec, {
count = src.packetCount,
start = function(i: number): number
return starts[i]
end,
decode = src.decode,
pcm = function(): { number }
return src.pcm
end,
reset = src.reset,
skip = skip,
stop = stopAt,
preroll = if src.codec == "aac" then 1 else 0,
})
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
return Pcm.drain(d, { format = "caf", codec = d.codec, bitsPerSample = d.bitsPerSample })
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: EncodeOptions = opts or {}
if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then
return nil, Err.new(Err.ARG, "expected an Audio or a Decoder")
end
local 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
+223
View File
@@ -0,0 +1,223 @@
--!strict
--!native
--!optimize 2
-- audio/flac/Meta: FLAC metadata blocks: STREAMINFO, SEEKTABLE, VORBIS_COMMENT and PICTURE (its fields are listed, the image is
-- left in place); every other block is skipped. Nothing throws: bad data gives nil, err.
-- Absorbed from flac-luau 7083d0d (same author, no third-party code).
local VorbisComment = require("@rosetta/codecs/audio/VorbisComment")
local readu8, readu32 = buffer.readu8, buffer.readu32
local Meta = {}
local function be16(b: buffer, p: number): number
return readu8(b, p) * 256 + readu8(b, p + 1)
end
local function be24(b: buffer, p: number): number
return readu8(b, p) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2)
end
local function be32(b: buffer, p: number): number
return be16(b, p) * 65536 + be16(b, p + 2)
end
export type StreamInfo = {
minBlockSize: number,
maxBlockSize: number,
minFrameSize: number, -- 0 = unknown
maxFrameSize: number,
sampleRate: number,
channels: number,
bitsPerSample: number,
totalSamples: number, -- 0 = unknown
md5: string, -- 32 hex digits (all zero = not set)
}
export type SeekPoint = { sample: number, offset: number, samples: number }
export type Picture = {
type: number,
mime: string,
description: string,
width: number,
height: number,
depth: number,
colors: number,
offset: number, -- the image bytes are buf[offset .. offset + size - 1]
size: number,
}
export type Info = {
streamInfo: StreamInfo,
seekTable: { SeekPoint },
vendor: string,
tags: { [string]: string }, -- upper-case keys; repeated keys are joined with "; "
comments: { { key: string, value: string } }, -- every comment in order
pictures: { Picture },
firstFrame: number, -- byte offset just after the last metadata block
}
local function streamInfo(b: buffer, p: number): StreamInfo
local b12, b13 = readu8(b, p + 12), readu8(b, p + 13)
local hex = table.create(16)
for i = 0, 15 do
hex[i + 1] = string.format("%02x", readu8(b, p + 18 + i))
end
return {
minBlockSize = be16(b, p),
maxBlockSize = be16(b, p + 2),
minFrameSize = be24(b, p + 4),
maxFrameSize = be24(b, p + 7),
sampleRate = readu8(b, p + 10) * 4096 + readu8(b, p + 11) * 16 + bit32.rshift(b12, 4),
channels = bit32.band(bit32.rshift(b12, 1), 7) + 1,
bitsPerSample = bit32.band(b12, 1) * 16 + bit32.rshift(b13, 4) + 1,
totalSamples = bit32.band(b13, 15) * 4294967296 + be32(b, p + 14),
md5 = table.concat(hex),
}
end
local function vorbisComment(b: buffer, p: number, e: number, info: Info): boolean
if p + 4 > e then
return false
end
local vl = readu32(b, p)
p += 4
if p + vl > e then
return false
end
info.vendor = buffer.readstring(b, p, vl)
p += vl
if p + 4 > e then
return false
end
local n = readu32(b, p)
p += 4
for _ = 1, n do
if p + 4 > e then
return false
end
local l = readu32(b, p)
p += 4
if p + l > e then
return false
end
local s = buffer.readstring(b, p, l)
p += l
local eq = string.find(s, "=", 1, true)
if eq then
local name, value = string.sub(s, 1, eq - 1), string.sub(s, eq + 1)
table.insert(info.comments, { key = string.upper(name), value = value })
local key = VorbisComment.tagKey(name)
local old = info.tags[key]
info.tags[key] = if old then old .. "; " .. value else value
end
end
return true
end
local function picture(b: buffer, p: number, e: number): Picture?
if p + 8 > e then
return nil
end
local typ = be32(b, p)
local ml = be32(b, p + 4)
p += 8
if p + ml + 4 > e then
return nil
end
local mime = buffer.readstring(b, p, ml)
p += ml
local dl = be32(b, p)
p += 4
if p + dl + 20 > e then
return nil
end
local desc = buffer.readstring(b, p, dl)
p += dl
local pic = {
type = typ,
mime = mime,
description = desc,
width = be32(b, p),
height = be32(b, p + 4),
depth = be32(b, p + 8),
colors = be32(b, p + 12),
offset = p + 20,
size = be32(b, p + 16),
}
if pic.offset + pic.size > e then
return nil
end
return pic
end
-- Parse the metadata blocks that follow "fLaC" at pos (data ends at len)
function Meta.parse(b: buffer, pos: number, len: number): (Info?, string?)
if pos + 4 > len or buffer.readstring(b, pos, 4) ~= "fLaC" then
return nil, "Flac: no fLaC marker"
end
local info: Info = {
streamInfo = nil :: any,
seekTable = {},
vendor = "",
tags = {},
comments = {},
pictures = {},
firstFrame = 0,
}
local p = pos + 4
while true do
if p + 4 > len then
return nil, "Flac: truncated metadata"
end
local h = readu8(b, p)
local last = h >= 128
local typ = bit32.band(h, 127)
local size = be24(b, p + 1)
p += 4
local e = p + size
if e > len then
return nil, "Flac: truncated metadata block"
end
if typ == 0 then
if size < 34 then
return nil, "Flac: bad STREAMINFO"
end
info.streamInfo = streamInfo(b, p)
elseif typ == 3 then
for q = p, e - 18, 18 do
local hi = be32(b, q)
if hi ~= 0xFFFFFFFF then -- placeholder points are all ones
table.insert(info.seekTable, {
sample = hi * 4294967296 + be32(b, q + 4),
offset = be32(b, q + 8) * 4294967296 + be32(b, q + 12),
samples = be16(b, q + 16),
})
end
end
elseif typ == 4 then
vorbisComment(b, p, e, info) -- a broken comment block leaves what was read
elseif typ == 6 then
local pic = picture(b, p, e)
if pic then
table.insert(info.pictures, pic)
end
elseif typ == 127 then
return nil, "Flac: invalid metadata block type"
end
p = e
if last then
break
end
end
if not info.streamInfo then
return nil, "Flac: no STREAMINFO"
end
local si = info.streamInfo
if si.sampleRate == 0 then
return nil, "Flac: bad STREAMINFO values"
end
info.firstFrame = p
return info, nil
end
return Meta
+383
View File
@@ -0,0 +1,383 @@
--!strict
--!native
--!optimize 2
-- audio/flac/Stream: the streaming FLAC decoder (native FLAC with an optional ID3v2 tag in front, and Ogg FLAC through
-- containers/Ogg): stream setup, read / readInt with resync past corrupt frames, sample-accurate seeking (seek table,
-- byte bisection by sync search, then a frame walk), length from the last frame when STREAMINFO has none. Absorbed
-- from flac-luau 7083d0d (same author, no third-party code; the Ogg demuxer is now a direct require instead of an
-- injected module). Nothing throws: open returns nil, message, code.
local Bytes = require("@rosetta/core/Bytes")
local Ogg = require("@rosetta/containers/Ogg")
local Frame = require("@rosetta/codecs/audio/Flac/Frame")
local Meta = require("@rosetta/audio/flac/Meta")
local Stream = {}
local writef32, writei32 = buffer.writef32, buffer.writei32
type Header = any -- Frame.Header
local PAD = Frame.PAD
export type Decoder = {
sampleRate: number,
channels: number,
bitsPerSample: number,
frames: number, -- total sample frames (per channel); 0 if unknown and not found
duration: number, -- seconds
bitrate: number, -- average bits per second of the audio data
tags: { [string]: string },
comments: { { key: string, value: string } },
vendor: string,
md5: string,
seekTable: { any },
pictures: { any },
container: string, -- "flac" | "ogg"
read: (Decoder, number, buffer?) -> (buffer, number),
readInt: (Decoder, number, buffer?) -> (buffer, number),
seek: (Decoder, number) -> boolean,
seekSample: (Decoder, number) -> boolean,
position: (Decoder) -> (number, number),
}
local Dec = {}
Dec.__index = Dec
-- the sample number of a frame
local function sampleOf(self: any, h: Header): number
return if h.variable then h.number else h.number * self._nominal
end
-- a header that also matches the stream (guards the sync search against false syncs)
local function plausible(self: any, h: Header): boolean
if h.channels ~= self.channels or h.bps ~= self.bitsPerSample or h.blockSize > 65536 then
return false
end
if self.frames > 0 and sampleOf(self, h) >= self.frames then
return false
end
return true
end
local function findFrame(self: any, pos: number, limit: number): Header?
local b, len, si = self._b, self._len, self._si
while true do
local h = Frame.find(b, pos, limit, len, si)
if not h then
return nil
end
if plausible(self, h) then
return h
end
pos = h.offset + 1
end
end
local function ensure(self: any, n: number)
if n > self._cap then
for c = 1, self.channels do
self._chans[c] = table.create(n, 0)
end
self._cap = n
end
end
-- Decode the frame at or after pos (resyncing past corrupt data). Sets the current frame; false at the end.
local function decodeAt(self: any, pos: number): boolean
local b, len = self._b, self._len
while true do
local h = Frame.header(b, pos, len, self._si)
if not h or not plausible(self, h) then
h = findFrame(self, pos, len)
if not h then
self._pos = len
return false
end
end
ensure(self, h.blockSize)
local nextPos = Frame.decode(b, len, h, self._chans, self._cf, self._crc)
if nextPos then
local s = sampleOf(self, h)
local n = h.blockSize
if self.frames > 0 and s + n > self.frames then
n = math.max(0, self.frames - s)
end
self._pos = nextPos
self._fs = s
self._fn = n
self._cur = 0
return true
end
pos = h.offset + 1
end
end
local function pull(self: any, maxFrames: number, asInt: boolean, dst: buffer?): (buffer, number)
local ch = self.channels
local want = math.floor(tonumber(maxFrames) or 0)
if not (want >= 0) then
want = 0 -- negative or NaN
end
want = math.min(want, 2 ^ 26 // ch) -- keeps the output buffer under 256 MB
local reuse = dst ~= nil and type(dst) == "buffer" and buffer.len(dst) >= want * ch * 4
local out = if reuse then dst :: buffer else buffer.create(want * ch * 4)
local got = 0
local scale = 1 / 2 ^ (self.bitsPerSample - 1)
local stride = ch * 4
while got < want do
if self._cur >= self._fn then
if self._pos >= self._len or not decodeAt(self, self._pos) then
self._fs += self._cur
self._cur, self._fn = 0, 0
break
end
end
local take = math.min(want - got, self._fn - self._cur)
local from = self._cur + 1
local to = self._cur + take
for c = 1, ch do
local s = self._chans[c]
local o = (got * ch + c - 1) * 4
if asInt then
for i = from, to do
writei32(out, o, s[i])
o += stride
end
else
for i = from, to do
writef32(out, o, s[i] * scale)
o += stride
end
end
end
self._cur += take
got += take
end
if got < want and not reuse then
local short = buffer.create(got * ch * 4)
buffer.copy(short, 0, out, 0, got * ch * 4)
out = short
end
return out, got
end
-- Up to maxFrames sample frames as interleaved f32 (sample / 2^(bps-1)); 0 frames = end of stream. out (if given) is
-- reused when big enough.
function Dec.read(self: any, maxFrames: number, out: buffer?): (buffer, number)
return pull(self, maxFrames, false, out)
end
-- The same as interleaved i32 integer samples (bit-exact, right-aligned)
function Dec.readInt(self: any, maxFrames: number, out: buffer?): (buffer, number)
return pull(self, maxFrames, true, out)
end
-- seconds, sample frame of the next frame read() returns
function Dec.position(self: any): (number, number)
local s = self._fs + self._cur
return s / self.sampleRate, s
end
-- Seek so the next read starts exactly at sample frame t. Uses the seek table to bracket t, bisects byte offsets
-- by sync search, then walks frame headers forward. Returns false if the stream has no frame there.
function Dec.seekSample(self: any, t: number): boolean
t = math.floor(tonumber(t) or 0)
if not (t >= 0) then
t = 0 -- negative or NaN
end
if self.frames > 0 and t >= self.frames then
self._pos, self._fs, self._fn, self._cur = self._len, self.frames, 0, 0
return true
end
if self._fn > 0 and t >= self._fs and t < self._fs + self._fn then
self._cur = t - self._fs
return true
end
local first, len = self._first, self._len
local lo, hi = first, len
for _, sp in self.seekTable do
local o = first + sp.offset
if o < len then
if sp.sample <= t then
lo = math.max(lo, o)
else
hi = math.min(hi, o)
break
end
end
end
local window = math.max(16384, 2 * self._si.maxFrameSize)
while hi - lo > window do
local mid = (lo + hi) // 2
local h = findFrame(self, mid, hi)
if h and sampleOf(self, h) <= t then
lo = h.offset
else
hi = mid
end
end
local pos = lo
while true do
local h = findFrame(self, pos, len)
if not h then
self._pos, self._fs, self._fn, self._cur = len, math.max(t, self.frames), 0, 0
return false
end
local s = sampleOf(self, h)
if s + h.blockSize > t then
if decodeAt(self, h.offset) then
if self._fs <= t and t < self._fs + self._fn then
self._cur = t - self._fs
return true
elseif self._fs > t then
return false -- a hole in the stream: we are at the next frame
end
pos = self._pos
else
return false
end
else
pos = h.offset + h.size
end
end
end
function Dec.seek(self: any, seconds: number): boolean
return self:seekSample(math.floor((tonumber(seconds) or 0) * self.sampleRate + 0.5))
end
-- Find the total length from the last frame (when STREAMINFO does not give it)
local function scanLength(self: any): number
local len = self._len
local step = math.max(65536, 2 * self._si.maxFrameSize)
local from = len
while from > self._first do
local start = math.max(self._first, from - step)
local best: Header? = nil
local pos = start
while true do
local h = findFrame(self, pos, from)
if not h then
break
end
best = h
pos = h.offset + 1
end
if best then
local s = sampleOf(self, best)
-- the last frame may be shorter than its header claims only via STREAMINFO, which is unknown here
return s + best.blockSize
end
from = start
end
return 0
end
local function skipId3(b: buffer, base: number, len: number): number
local p = 0
while p + 10 <= len and buffer.readstring(b, base + p, 3) == "ID3" do
local sz = 0
for i = 6, 9 do
sz = sz * 128 + bit32.band(buffer.readu8(b, base + p + i), 127)
end
local footer = bit32.band(buffer.readu8(b, base + p + 5), 0x10) ~= 0
p += 10 + sz + (if footer then 10 else 0)
end
return p
end
-- opts.crc16 = false skips the per-frame CRC-16 check
function Stream.open(buf: buffer, base: number, srcLen: number, opts: { crc16: boolean? }?): (Decoder?, string?, string?)
local b, len, container
if srcLen >= 4 and buffer.readstring(buf, base, 4) == "OggS" then
local demux, err = Ogg.open(Bytes.reader(buf, base, srcLen))
if not demux then
return nil, (err :: any).message, "CORRUPT"
end
local serial = demux:find("flac")
if not serial then
return nil, "no FLAC stream in the Ogg file", "CORRUPT"
end
-- rebuild a native stream: "fLaC" + metadata (from the header packets) + frames (one per packet)
local packets, total = {}, 0
for p in demux:packets(serial) do
local off, size = p.offset, p.size
if #packets == 0 then
if size < 13 then
return nil, "bad Ogg FLAC header", "CORRUPT"
end
off += 9
size -= 9
end
table.insert(packets, { p.data, off, size })
total += size
end
b = buffer.create(total + PAD)
local o = 0
for _, p in packets do
buffer.copy(b, o, p[1], p[2], p[3])
o += p[3]
end
len = total
container = "ogg"
else
local start = skipId3(buf, base, srcLen)
if start + 4 > srcLen or buffer.readstring(buf, base + start, 4) ~= "fLaC" then
return nil, "not a FLAC file", "CORRUPT"
end
len = srcLen - start
b = buffer.create(len + PAD)
buffer.copy(b, 0, buf, base + start, len)
container = "flac"
end
local info, err = Meta.parse(b, 0, len)
if not info then
return nil, err, "CORRUPT"
end
local si = info.streamInfo
local self = setmetatable({
sampleRate = si.sampleRate,
channels = si.channels,
bitsPerSample = si.bitsPerSample,
frames = si.totalSamples,
duration = 0,
bitrate = 0,
tags = info.tags,
comments = info.comments,
vendor = info.vendor,
md5 = si.md5,
seekTable = info.seekTable,
pictures = info.pictures,
container = container,
_b = b,
_len = len,
_si = si,
_first = info.firstFrame,
_pos = info.firstFrame,
_chans = {},
_cap = 0,
_cf = table.create(32, 0),
_crc = not (opts and opts.crc16 == false),
_fs = 0,
_fn = 0,
_cur = 0,
_nominal = math.max(si.maxBlockSize, 1),
}, Dec)
ensure(self, math.max(si.maxBlockSize, 16))
local h = findFrame(self, info.firstFrame, len)
if h then
if not h.variable then
self._nominal = h.blockSize
end
end
if self.frames == 0 then
self.frames = scanLength(self)
end
self.duration = self.frames / self.sampleRate
if self.duration > 0 then
self.bitrate = (len - info.firstFrame) * 8 / self.duration
end
return self :: any, nil
end
Stream.Dec = Dec
return Stream
+161
View File
@@ -0,0 +1,161 @@
--!strict
-- audio/flac: FLAC (RFC 9639), native and in Ogg (the Ogg FLAC mapping). Absorbed from flac-luau 7083d0d (same author,
-- no third-party code); the Ogg demuxer is now a direct require of containers/Ogg instead of an injected module.
-- Supports: every subframe type (constant, verbatim, fixed, LPC up to order 32, wasted bits), Rice / Rice2 residuals
-- with escapes, every stereo mode, 4-32 bits, 1-8 channels, any sample rate, fixed and variable block sizes, frame
-- CRC-16 checks with resync past corrupt frames, sample-accurate seeking (seek table + bisection), an ID3v2 tag in
-- front, STREAMINFO / SEEKTABLE / VORBIS_COMMENT / PICTURE metadata, the total length from the last frame when
-- STREAMINFO has none. Encode (codecs/audio/Flac/Encode, ws-audio): native FLAC from an Audio or a streamed Decoder, levels
-- 0-8 like libFLAC's presets, 4-24 bits, 1-8 channels, MD5, VORBIS_COMMENT, SEEKTABLE. Not supported: MD5
-- verification on decode, chained Ogg streams, Ogg FLAC output.
-- The codec itself is codecs/audio/Flac; this folder maps it onto the file (container, tags, seeking, writing).
--
-- local dec = Flac.open(Bytes.reader(buf)) -- the Types.Decoder (+ bitsPerSample, readInt, seekSample, ...)
-- local f32, n = dec:read(4096) -- interleaved f32 in [-1, 1); n = 0 at the end
-- local i32, n = dec:readInt(4096) -- bit-exact integer samples
-- local audio = Flac.decode(Bytes.reader(buf)) -- Types.Audio
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Ogg = require("@rosetta/containers/Ogg")
local Stream = require("@rosetta/audio/flac/Stream")
local Encode = require("@rosetta/codecs/audio/Flac/Encode")
local Pcm = require("@rosetta/codecs/audio/Pcm")
-- ------------------------------------------------------------------------------------------------ contract
local Flac = {
name = "flac",
category = "audio",
extensions = { "flac", "oga" },
mime = { "audio/flac", "audio/x-flac" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/audio/Pcm", "codecs/audio/VorbisComment", "codecs/audio/Flac/Frame", "codecs/audio/Flac/Encode" },
caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type Decoder = Stream.Decoder
export type OpenOptions = {
crc16: boolean?, -- check every frame's CRC-16 (default true; a bad frame is skipped by resyncing)
maxFrames: number?, -- decode(): refuse streams longer than this many sample frames (default 2^28)
}
export type EncodeOptions = {
level: number?, -- 0..8 like libFLAC's -0 .. -8 (default 5)
bits: number?, -- bits per sample 4..24 (default: the source's meta.source.bitDepth / bitsPerSample if 4..24, else 16)
blockSize: number?, -- 16..65535 (default: the level's, 1152 or 4096)
seekInterval: number?, -- seconds between SEEKTABLE points when the length is known (default 10; 0 = none)
padding: number?, -- bytes of PADDING after the metadata (default 0)
}
-- ------------------------------------------------------------------------------------------------ sniff
function Flac.sniff(r: Bytes.Reader): number
local head = r:peek(4)
if head == "fLaC" then
return 1
end
if head == "OggS" then
-- the first page's packet: 0x7F "FLAC" (the Ogg FLAC mapping)
local nseg = r:peekU8(26)
if nseg > 0 and r:peek(5, 27 + nseg) == "\127FLAC" then
return 1
end
return 0
end
if string.sub(head, 1, 3) == "ID3" then
-- an ID3v2 tag, then fLaC (mp3 files start with ID3 too)
local sz = 0
for i = 6, 9 do
local v = r:peekU8(i)
if v < 0 then
return 0
end
sz = sz * 128 + bit32.band(v, 127)
end
local footer = bit32.band(math.max(r:peekU8(5), 0), 0x10) ~= 0
return if r:peek(4, 10 + sz + (if footer then 10 else 0)) == "fLaC" then 1 else 0
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream
function Flac.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?)
local dec, err = Flac.open(r, opts)
if not dec then
return nil, err
end
local d = dec :: any
local limit = opts and opts.maxFrames or 2 ^ 28
if d.frames > limit or d.frames * d.channels > 2 ^ 28 then
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames))
end
return Pcm.drain(d, { format = "flac", bitDepth = d.bitsPerSample, container = d.container, vendor = d.vendor, md5 = d.md5, pictures = d.pictures, comments = d.comments }, limit)
end
-- ------------------------------------------------------------------------------------------------ encode
-- encode(audioOrDecoder, opts?) -> FLAC file buffer | nil, Err
function Flac.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local src, serr = Pcm.source(value)
if not src then
return nil, serr
end
local o: EncodeOptions = opts or {}
local level = o.level or 5
if type(level) ~= "number" or level ~= math.floor(level) or level < 0 or level > 8 then
return nil, Err.new(Err.ARG, "level must be 0..8")
end
local bits = o.bits
if bits == nil then
local v = value :: any
local sb = (type(v.meta) == "table" and type(v.meta.source) == "table" and v.meta.source.bitDepth) or v.bitsPerSample
bits = if type(sb) == "number" and sb >= 4 and sb <= 24 then sb else 16
end
if type(bits) ~= "number" or bits ~= math.floor(bits) or bits < 4 or bits > 24 then
return nil, Err.new(Err.ARG, "bits must be 4..24")
end
local bs = o.blockSize
if bs ~= nil and (type(bs) ~= "number" or bs ~= math.floor(bs) or bs < 16 or bs > 65535) then
return nil, Err.new(Err.ARG, "blockSize must be 16..65535")
end
if src.channels > 8 then
return nil, Err.new(Err.ARG, "FLAC holds at most 8 channels")
end
if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate < 1 or src.sampleRate >= 2 ^ 20 then
return nil, Err.new(Err.ARG, "the sample rate must be an integer below 2^20")
end
local out, msg = Encode.encode(src :: any, {
level = level,
bits = bits :: number,
blockSize = bs,
seekInterval = math.max(0, o.seekInterval or 10),
padding = math.clamp(math.floor(o.padding or 0), 0, 0xFFFFFF),
vendor = "rosetta",
})
if not out then
return nil, Err.new(Err.CORRUPT, tostring(msg))
end
return out, nil
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts?) -> Decoder | nil, Err
function Flac.open(r: Bytes.Reader, opts: OpenOptions?): (Decoder?, Err.Err?)
if type(r) == "buffer" then
r = Bytes.reader(r :: any)
end
if type(r) ~= "table" or type(r.buf) ~= "buffer" then
return nil, Err.new(Err.ARG, "open: expected a Reader")
end
local dec, msg, code = Stream.open(r.buf, r.base, r.limit - r.base, opts)
if not dec then
return nil, Err.new(code or Err.CORRUPT, tostring(msg))
end
return dec, nil
end
-- ------------------------------------------------------------------------------------------------ extras
Flac.Stream = Stream
Flac.Ogg = Ogg
return Flac
+340
View File
@@ -0,0 +1,340 @@
--!strict
-- audio/m4a: MPEG-4 audio files (M4A / M4B / MP4 / MOV audio tracks) through containers/IsoBmff. Supports: reading
-- AAC-LC (codecs/audio/Aac; HE-AAC files play their AAC-LC core at the core rate) and ALAC (codecs/audio/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("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Pcm = require("@rosetta/codecs/audio/Pcm")
local Stream = require("@rosetta/codecs/audio/Stream")
local IsoBmff = require("@rosetta/containers/IsoBmff")
local Aac = require("@rosetta/codecs/audio/Aac")
local Alac = require("@rosetta/codecs/audio/Alac")
-- ------------------------------------------------------------------------------------------------ contract
local M4a = {
name = "m4a",
category = "audio",
extensions = { "m4a", "m4b", "m4r" },
mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" },
deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/audio/Aac", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream" },
caps = { decode = true, encode = true, codecs = { "aac", "alac" }, encodeCodecs = { "alac" }, tags = true, streaming = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
track: number?, -- the track id to play (default: the first AAC / ALAC track)
gapless: boolean?, -- apply the edit list (default true)
maxSamples: number?, -- 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: DecodeOptions = opts or {}
local movie, err = IsoBmff.parse(r, { maxSamples = o.maxSamples })
if not movie then
return nil, err
end
local track: IsoBmff.Track? = nil
local other: IsoBmff.Track? = nil
for _, t in movie.tracks do
if t.kind == "audio" then
if o.track and t.id ~= o.track then
continue
end
if t.codec == "aac" or t.codec == "alac" then
track = t
break
end
other = other or t
end
end
if not track then
if other then
return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. other.codec .. " in MP4")
end
return nil, Err.new(Err.CORRUPT, "no audio track")
end
local t = track :: IsoBmff.Track
local pd, perr = packetDecoder(t)
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: { number } = {}
for w in string.gmatch(smpb, "%x+") do
table.insert(f, tonumber(w, 16) :: number)
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
local dec: any = {
sampleRate = sr,
channels = channels,
frames = frames,
duration = frames / sr,
bitrate = 0,
tags = tags,
pictures = pictures,
codec = t.codec,
track = t,
movie = movie,
}
local bytes = 0
for i = 1, t.sampleCount do
bytes += t.sizes[i]
end
dec.bitrate = if frames > 0 then math.floor(bytes * 8 * sr / frames) else (t.bitrate or 0)
-- packet start frames (media ticks -> frames); one AAC packet of pre-roll for the overlap when seeking
return Stream.packets(dec, {
count = t.sampleCount,
start = function(i: number): number
return math.floor((t.dts[i] or (t.dts[t.sampleCount] or 0) + (t.durations[t.sampleCount] or 0)) * tickScale + 0.5)
end,
decode = function(i: number): (number?, Err.Err?)
return p.decode(buf, t.offsets[i], t.sizes[i])
end,
pcm = function(): { number }
return p.pcm
end,
reset = p.reset,
skip = skip,
stop = total,
preroll = if t.codec == "aac" then 1 else 0,
cumulative = true,
})
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, derr = Pcm.drain(d, { format = "m4a", codec = d.codec, bitsPerSample = d.track.bitsPerSample, brand = d.movie.brand })
if audio and #d.pictures > 0 then
audio.meta.pictures = d.pictures
end
return audio, derr
end
-- ------------------------------------------------------------------------------------------------ encode
-- encode(audio | decoder, opts?) -> buffer | nil, Err: an ALAC M4A
function M4a.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: EncodeOptions = opts or {}
if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then
return nil, Err.new(Err.ARG, "expected an Audio or a Decoder")
end
local sr, ch = value.sampleRate, value.channels
local enc, eerr = Alac.encoder({ sampleRate = sr, channels = ch, bitDepth = o.bitDepth or 16, frameLength = o.frameLength })
if not enc then
return nil, eerr
end
local e = enc :: Alac.Encoder
local depth = e.config.bitDepth
local fl = e.config.frameLength
local peak = 2 ^ (depth - 1)
local packets: { buffer } = {}
local durations: { number } = {}
local ints = table.create(fl * ch, 0)
local floor = math.floor
local readf32 = buffer.readf32
-- 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
+194
View File
@@ -0,0 +1,194 @@
--!strict
--!native
--!optimize 2
-- audio/mp3/Index: the frame index of a stream, built once on open. It follows minimp3_ex's mp3dec_load_buf frame by frame
-- (same sync, resync and Xing / LAME handling), and simulates the layer III bit reservoir from the side info, so
-- it knows in advance which frames give output and where each one's samples land. That makes the total length
-- exact and seeking sample-accurate. Never throws.
local Header = require("@rosetta/codecs/audio/Mpa/Header")
local Core = require("@rosetta/codecs/audio/Mpa/Core")
local band, rshift = bit32.band, bit32.rshift
local ru8 = buffer.readu8
local min, max = math.min, math.max
local compare, frameBytes, padding, findFrame =
Header.compare, Header.frameBytes, Header.padding, Header.findFrame
local Index = {}
Index.FLAG_RESET = 1 -- decoder state is zeroed before this frame (minimp3 re-synced here)
Index.FLAG_OUTPUT = 2 -- this frame gives samples in a continuous decode
export type Index = {
n: number, -- frames
off: buffer, -- u32 byte offset per frame
size: buffer, -- u16 byte size per frame (header and padding included)
flags: buffer, -- u8 FLAG_*
out: buffer, -- u32 first output sample (before the encoder delay is cut) per frame
main: buffer, -- u16 layer III main data bytes per frame (0 for layers I / II)
outTotal: number, -- samples (per channel) of a continuous decode, delay not cut
bytes: number, -- audio bytes in indexed frames
-- format of the first frame
sampleRate: number,
channels: number, -- the most channels of any frame
layer: number,
version: number, -- 1, 2 or 2.5
spf: number, -- samples per frame
-- Xing / Info / LAME
vbrTag: number, -- mp3dec_check_vbrtag result of the first frame (0 = none)
tagFrames: number,
delay: number,
padding: number,
skipped: number, -- frames with another sample rate or layer, left out
}
local function grow(b: buffer, n: number): buffer
local nb = buffer.create(n)
buffer.copy(nb, 0, b, 0, math.min(buffer.len(b), n))
return nb
end
function Index.build(b: buffer, start: number, stop: number): Index?
local cap = 1024
local OFF, SIZE, FLAGS, OUT, MAIN = buffer.create(cap * 4), buffer.create(cap * 2), buffer.create(cap), buffer.create(cap * 4), buffer.create(cap * 2)
local n = 0
local pos = start
local prev = -1 -- offset of the last decoded header (dec->header), -1 = none
local ffb = 0 -- free format bytes
local reserv = 0
local outTotal = 0
local bytes = 0
local first = true
local skipped = 0
local outCh = 0 -- the most channels of a frame that gives output
local hz, nch, layer, spf, version = 0, 0, 0, 0, 0
local vbr, tagFrames, delay, pad = 0, 0, 0, 0
while true do
local remaining = stop - pos
if remaining <= 0 then
break
end
local fs = 0
local reset = false
if remaining > 4 and prev >= 0 and compare(b, prev, pos) then
fs = frameBytes(b, pos, ffb) + padding(b, pos)
if fs ~= remaining and (fs + 4 > remaining or not compare(b, pos, pos + fs)) then
fs = 0
end
end
if fs == 0 then
reset = true
reserv = 0
local i
i, fs, ffb = findFrame(b, pos, remaining, 0)
if fs == 0 or i + fs > remaining then
break
end
pos += i
end
if fs < 4 or fs > Core.MAX_FRAME then
-- cannot happen with a well-formed header, but never index an impossible frame
prev = -1
pos += max(fs, 1)
continue
end
local h1, h2, h3 = ru8(b, pos + 1), ru8(b, pos + 2), ru8(b, pos + 3)
local fLayer = 4 - band(rshift(h1, 1), 3)
local fHz = Header.sampleRate(h1, h2)
local fCh = if band(h3, 0xC0) == 0xC0 then 1 else 2
if first then
first = false
hz, nch, layer, spf = fHz, fCh, fLayer, Header.frameSamples(h1) :: number
version = if band(h1, 8) ~= 0 then 1 elseif band(h1, 0x10) ~= 0 then 2 else 2.5
if fLayer == 3 then
local ret, frames, d, p = Core.vbrTag(b, pos, fs)
if ret ~= 0 then
vbr, tagFrames, delay, pad = ret, frames, d, p
if ret < 0 then
delay, pad = 0, 0
end
-- the tag frame is not audio; the next frame is found again from scratch
prev = -1
pos += fs
continue
end
end
elseif fHz ~= hz or fLayer ~= layer then
skipped += 1
prev = pos
pos += fs
continue
end
local output = true
local mainBytes = 0
local nextPrev = pos
if fLayer == 3 then
local mdb, p23, mb = Core.probeL3(b, pos, fs)
if mdb < 0 then
output = false
nextPrev = -1 -- mp3dec_init: the next frame re-syncs
else
mainBytes = mb
local have = min(reserv, mdb)
output = reserv >= mdb
local remains = have + mb - (if output then (p23 + 7) // 8 else 0)
reserv = max(0, min(remains, 511))
end
else
output = Core.probeL12(b, pos, fs)
if not output then
nextPrev = -1
end
end
if output and fCh > outCh then
outCh = fCh -- mono / stereo switches: the stream is stereo, mono frames are duplicated
end
if n == cap then
cap *= 2
OFF, SIZE, FLAGS, OUT, MAIN = grow(OFF, cap * 4), grow(SIZE, cap * 2), grow(FLAGS, cap), grow(OUT, cap * 4), grow(MAIN, cap * 2) :: buffer
end
buffer.writeu32(OFF, n * 4, pos)
buffer.writeu16(SIZE, n * 2, fs)
buffer.writeu8(FLAGS, n, (if reset then Index.FLAG_RESET else 0) + (if output then Index.FLAG_OUTPUT else 0))
buffer.writeu32(OUT, n * 4, outTotal)
buffer.writeu16(MAIN, n * 2, min(mainBytes, 65535))
n += 1
bytes += fs
if output then
outTotal += spf
end
prev = nextPrev
pos += fs
end
if first then
return nil
end
return {
n = n,
off = OFF,
size = SIZE,
flags = FLAGS,
out = OUT,
main = MAIN,
outTotal = outTotal,
bytes = bytes,
sampleRate = hz,
channels = if outCh > 0 then outCh else nch,
layer = layer,
version = version,
spf = spf,
vbrTag = vbr,
tagFrames = tagFrames,
delay = delay,
padding = pad,
skipped = skipped,
}
end
return Index
+233
View File
@@ -0,0 +1,233 @@
--!strict
--!optimize 2
-- audio/mp3/Stream: the streaming Decoder (Types.Decoder) over a frame index: gapless (LAME delay / padding), exact
-- length, sample-accurate seeking. From mp3-luau's Mp3.open / Decoder (same author). Never throws.
local Core = require("@rosetta/codecs/audio/Mpa/Core")
local Index = require("@rosetta/audio/mp3/Index")
local FLAG_RESET, FLAG_OUTPUT = Index.FLAG_RESET, Index.FLAG_OUTPUT
local ru8, ru16, ru32 = buffer.readu8, buffer.readu16, buffer.readu32
local band = bit32.band
local min, max, floor = math.min, math.max, math.floor
local Stream = {}
local Decoder = {}
Decoder.__index = Decoder
export type Decoder = typeof(setmetatable(
{} :: {
sampleRate: number,
channels: number,
frames: number,
duration: number,
bitrate: number,
tags: { [string]: string },
id3: any,
layer: number,
version: number,
vbr: boolean,
delay: number,
padding: number,
mpegFrames: number,
_buf: buffer,
_idx: any,
_st: any,
_pcm: buffer,
_cur: number,
_pcmPos: number,
_pcmEnd: number,
_minAbs: number,
_endAbs: number,
_pos: number,
},
Decoder
))
-- new(b, idx, tags, id3) -> Decoder over the whole buffer b, with its frame index (Index.build)
function Stream.new(b: buffer, idx: any, tags: { [string]: string }, id3: any): Decoder
local spf, hz, nch = idx.spf, idx.sampleRate, idx.channels
-- gapless: minimp3_ex cuts delay samples off the start and caps the length at the Xing / LAME count
local delay = 0
local total = idx.outTotal
if idx.vbrTag > 0 then
delay = idx.delay
local detected = spf * idx.tagFrames
if detected >= delay then
detected -= delay
end
if idx.padding > 0 and detected >= idx.padding then
detected -= idx.padding
end
total = max(0, total - delay)
total = min(total, detected)
end
delay = min(delay, idx.outTotal)
local self = setmetatable({
sampleRate = hz,
channels = nch,
frames = total,
duration = total / hz,
bitrate = if idx.n > 0 then floor(idx.bytes * 8 * hz / (idx.n * spf) + 0.5) else 0, -- bit/s
tags = tags,
id3 = id3,
layer = idx.layer,
version = idx.version,
vbr = idx.vbrTag ~= 0,
delay = delay,
padding = if idx.vbrTag > 0 then max(0, idx.padding) else 0,
mpegFrames = idx.n,
_buf = b,
_idx = idx,
_st = Core.newState(),
_pcm = buffer.create(1152 * 2 * 4),
_cur = 0,
_pcmPos = 0,
_pcmEnd = 0,
_minAbs = delay,
_endAbs = delay + total,
_pos = 0,
}, Decoder)
return self
end
-- decodes frames until one has samples inside [minAbs, endAbs); false at the end
local function fill(self: Decoder): boolean
local idx = self._idx
local n = idx.n
local spf = idx.spf
local st = self._st
while self._cur < n do
local f = self._cur
self._cur = f + 1
local flags = ru8(idx.flags, f)
if band(flags, FLAG_RESET) ~= 0 then
Core.reset(st)
end
local a = ru32(idx.out, f * 4)
if a >= self._endAbs then
self._cur = n
return false
end
local got = Core.decodeFrame(st, self._buf, ru32(idx.off, f * 4), ru16(idx.size, f * 2), self._pcm)
if got > 0 and band(flags, FLAG_OUTPUT) ~= 0 then
if Core.lastChannels < self.channels then
Core.upmix(self._pcm, got)
end
local lo = max(a, self._minAbs)
local hi = min(a + spf, self._endAbs)
if hi > lo then
self._pcmPos = lo - a
self._pcmEnd = hi - a
return true
end
end
end
return false
end
-- Reads up to maxFrames sample frames: (buffer of interleaved f32, frames read); 0 frames = end of stream.
-- With out (a buffer of at least maxFrames * channels * 4 bytes) the samples go there and out is returned; a
-- smaller out is ignored.
function Decoder.read(self: Decoder, maxFrames: number?, out: buffer?): (buffer, number)
local ch = self.channels
local want = tonumber(maxFrames) or 4096
if want ~= want then
want = 0
end
want = floor(max(0, min(want, self.frames - self._pos)))
if out and buffer.len(out) < want * ch * 4 then
out = nil -- too small: a new buffer (Types.Decoder: out is reused when big enough)
end
local dst = out or buffer.create(want * ch * 4)
local got = 0
local pcm = self._pcm
while got < want do
if self._pcmPos >= self._pcmEnd then
if not fill(self) then
break
end
end
local k = min(want - got, self._pcmEnd - self._pcmPos)
buffer.copy(dst, got * ch * 4, pcm, self._pcmPos * ch * 4, k * ch * 4)
got += k
self._pcmPos += k
end
self._pos += got
if not out and got < want then
local r = buffer.create(got * ch * 4)
buffer.copy(r, 0, dst, 0, got * ch * 4)
dst = r
end
return dst, got
end
-- Seeks to a time in seconds (clamped to the stream). Sample-accurate: decoding restarts a few frames earlier
-- (enough to refill the bit reservoir and the filter history) and the output before the target is dropped.
function Decoder.seek(self: Decoder, seconds: number)
local hz = self.sampleRate
local target = floor((tonumber(seconds) or 0) * hz + 0.5)
target = max(0, min(target, self.frames))
self:seekFrame(target)
end
-- Seeks to a sample frame (0 .. frames).
function Decoder.seekFrame(self: Decoder, target: number)
target = tonumber(target) or 0
if target ~= target then
target = 0
end
target = max(0, min(floor(target), self.frames))
local idx = self._idx
local abs = self.delay + target
self._pos = target
self._minAbs = abs
self._pcmPos, self._pcmEnd = 0, 0
Core.reset(self._st)
local n = idx.n
if abs >= self._endAbs or n == 0 then
self._cur = n
return
end
-- last frame starting at or before abs
local lo, hi = 0, n - 1
while lo < hi do
local mid = (lo + hi + 1) // 2
if ru32(idx.out, mid * 4) <= abs then
lo = mid
else
hi = mid - 1
end
end
local j = lo
-- go back >= 2 frames (layer I needs 2 for the polyphase history), and for layer III until the main data
-- before frame j - 1 covers the largest reservoir (511 bytes), stopping at a frame where the decoder resets
local need = if idx.layer == 3 then 511 else 0
local s, back, acc = j, 0, 0
while s > 0 and band(ru8(idx.flags, s), FLAG_RESET) == 0 do
if back >= 2 and acc >= need then
break
end
s -= 1
back += 1
if back >= 2 then
acc += ru16(idx.main, s * 2)
end
end
self._cur = s
end
-- Current position: (seconds, sample frame)
function Decoder.position(self: Decoder): (number, number)
return self._pos / self.sampleRate, self._pos
end
-- Decodes everything from the current position to the end: (buffer of interleaved f32, frames)
function Decoder.readAll(self: Decoder): (buffer, number)
return self:read(max(0, self.frames - self._pos))
end
Stream.Decoder = Decoder
return Stream
+317
View File
@@ -0,0 +1,317 @@
--!strict
--!optimize 2
-- audio/mp3/Tags: ID3 tags: ID3v2.2 / 2.3 / 2.4 at the start (text frames, COMM, unsynchronisation, extended header) and ID3v1 /
-- ID3v1.1 at the end; APEv2 tags are only skipped. Also finds the byte range that holds the audio, the same way
-- minimp3_ex does (mp3dec_skip_id3). Text is returned as UTF-8. Never throws: malformed tags are cut short.
local band, bor, lshift = bit32.band, bit32.bor, bit32.lshift
local ru8 = buffer.readu8
local Tags = {}
-- ID3v1 genres 0..147 (the original 80 + the Winamp extensions)
local GENRES = {
[0] = "Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", "Grunge", "Hip-Hop", "Jazz", "Metal",
"New Age", "Oldies", "Other", "Pop", "R&B", "Rap", "Reggae", "Rock", "Techno", "Industrial", "Alternative",
"Ska", "Death Metal", "Pranks", "Soundtrack", "Euro-Techno", "Ambient", "Trip-Hop", "Vocal", "Jazz+Funk",
"Fusion", "Trance", "Classical", "Instrumental", "Acid", "House", "Game", "Sound Clip", "Gospel", "Noise",
"AlternRock", "Bass", "Soul", "Punk", "Space", "Meditative", "Instrumental Pop", "Instrumental Rock", "Ethnic",
"Gothic", "Darkwave", "Techno-Industrial", "Electronic", "Pop-Folk", "Eurodance", "Dream", "Southern Rock",
"Comedy", "Cult", "Gangsta", "Top 40", "Christian Rap", "Pop/Funk", "Jungle", "Native American", "Cabaret",
"New Wave", "Psychadelic", "Rave", "Showtunes", "Trailer", "Lo-Fi", "Tribal", "Acid Punk", "Acid Jazz", "Polka",
"Retro", "Musical", "Rock & Roll", "Hard Rock", "Folk", "Folk-Rock", "National Folk", "Swing", "Fast Fusion",
"Bebob", "Latin", "Revival", "Celtic", "Bluegrass", "Avantgarde", "Gothic Rock", "Progressive Rock",
"Psychedelic Rock", "Symphonic Rock", "Slow Rock", "Big Band", "Chorus", "Easy Listening", "Acoustic", "Humour",
"Speech", "Chanson", "Opera", "Chamber Music", "Sonata", "Symphony", "Booty Bass", "Primus", "Porn Groove",
"Satire", "Slow Jam", "Club", "Tango", "Samba", "Folklore", "Ballad", "Power Ballad", "Rhythmic Soul",
"Freestyle", "Duet", "Punk Rock", "Drum Solo", "A capella", "Euro-House", "Dance Hall", "Goa", "Drum & Bass",
"Club-House", "Hardcore", "Terror", "Indie", "BritPop", "Negerpunk", "Polsk Punk", "Beat",
"Christian Gangsta Rap", "Heavy Metal", "Black Metal", "Crossover", "Contemporary Christian", "Christian Rock",
"Merengue", "Salsa", "Thrash Metal", "Anime", "JPop", "Synthpop",
}
Tags.GENRES = GENRES
-- frame id -> field name (v2.3/2.4 ids and their v2.2 equivalents)
local FIELDS = {
TIT2 = "title", TT2 = "title",
TPE1 = "artist", TP1 = "artist",
TALB = "album", TAL = "album",
TPE2 = "albumartist", TP2 = "albumartist",
TYER = "date", TYE = "date", TDRC = "date",
TRCK = "track", TRK = "track",
TPOS = "disc", TPA = "disc",
TCON = "genre", TCO = "genre",
TCOM = "composer", TCM = "composer",
COMM = "comment", COM = "comment",
}
local function utf8char(cp: number): string
if cp < 0 or cp > 0x10FFFF or (cp >= 0xD800 and cp <= 0xDFFF) then
cp = 0xFFFD
end
return utf8.char(cp)
end
-- bytes [i, j) of b, decoded from ID3 text encoding enc (0 latin-1, 1 UTF-16 + BOM, 2 UTF-16BE, 3 UTF-8)
local function decodeText(b: buffer, i: number, j: number, enc: number): string
local out = {}
if enc == 1 or enc == 2 then
local le = false
if enc == 1 and j - i >= 2 then
local b0, b1 = ru8(b, i), ru8(b, i + 1)
if b0 == 0xFF and b1 == 0xFE then
le = true
i += 2
elseif b0 == 0xFE and b1 == 0xFF then
i += 2
else
le = true -- no BOM: assume little-endian (what most taggers write)
end
end
local pending = 0
while i + 1 < j do
local u = if le then bor(ru8(b, i), lshift(ru8(b, i + 1), 8)) else bor(lshift(ru8(b, i), 8), ru8(b, i + 1))
i += 2
if u >= 0xD800 and u <= 0xDBFF then
pending = u
else
if u >= 0xDC00 and u <= 0xDFFF and pending ~= 0 then
u = 0x10000 + lshift(pending - 0xD800, 10) + (u - 0xDC00)
end
pending = 0
table.insert(out, if u == 0 then "\0" else utf8char(u))
end
end
elseif enc == 3 then
local s = buffer.readstring(b, i, j - i)
if utf8.len(s) then
return s
end
enc = 0 -- invalid UTF-8: fall back to latin-1
end
if enc == 0 then
for k = i, j - 1 do
local c = ru8(b, k)
table.insert(out, if c < 0x80 then string.char(c) else utf8char(c))
end
end
return table.concat(out)
end
-- trim trailing NULs / spaces, join multi-value NUL separators with " / "
local function clean(s: string): string
s = string.gsub(s, "[%z%s]+$", "")
s = string.gsub(s, "%z+", " / ")
return s
end
-- "(17)", "(17)Rock", "17" -> "Rock"
local function genreName(s: string): string
local n = tonumber(string.match(s, "^%((%d+)%)$") or string.match(s, "^(%d+)$"))
if n and GENRES[n] then
return GENRES[n]
end
local rest = string.match(s, "^%(%d+%)(.+)$")
return rest or s
end
local function syncsafe(b: buffer, o: number): number
return bor(lshift(band(ru8(b, o), 0x7F), 21), lshift(band(ru8(b, o + 1), 0x7F), 14), lshift(band(ru8(b, o + 2), 0x7F), 7), band(ru8(b, o + 3), 0x7F))
end
local function be32(b: buffer, o: number): number
return bor(lshift(ru8(b, o), 24), lshift(ru8(b, o + 1), 16), lshift(ru8(b, o + 2), 8), ru8(b, o + 3))
end
-- undo unsynchronisation (FF 00 -> FF) of b[i, j) into a new buffer
local function deunsync(b: buffer, i: number, j: number): buffer
local out = buffer.create(math.max(0, j - i))
local n = 0
local k = i
while k < j do
local c = ru8(b, k)
buffer.writeu8(out, n, c)
n += 1
k += if c == 0xFF and k + 1 < j and ru8(b, k + 1) == 0 then 2 else 1
end
local r = buffer.create(n)
buffer.copy(r, 0, out, 0, n)
return r
end
-- minimp3's ID3v2 detection: total tag size (header + body + footer) or 0
function Tags.id3v2Size(b: buffer, o: number, len: number): number
if len - o < 10 or buffer.readstring(b, o, 3) ~= "ID3" then
return 0
end
if band(ru8(b, o + 5), 15) ~= 0 then
return 0
end
for k = 6, 9 do
if band(ru8(b, o + k), 0x80) ~= 0 then
return 0
end
end
local size = syncsafe(b, o + 6) + 10
if band(ru8(b, o + 5), 16) ~= 0 then
size += 10
end
return size
end
local function setField(tags: any, id: string, text: string)
tags.raw[id] = text
local f = FIELDS[id]
if f and tags[f] == nil and text ~= "" then
tags[f] = if f == "genre" then genreName(text) else text
end
end
-- parse an ID3v2 tag at b[o ..] (o .. o + size within the buffer) into tags
local function parseV2(b: buffer, o: number, size: number, tags: any)
local ver = ru8(b, o + 3)
local flags = ru8(b, o + 5)
if ver < 2 or ver > 4 then
return
end
tags.id3v2 = "2." .. ver
local bodyEnd = math.min(o + 10 + syncsafe(b, o + 6), buffer.len(b))
local body = b
local p, e = o + 10, bodyEnd
if band(flags, 0x80) ~= 0 and ver < 4 then
body = deunsync(b, p, e)
p = 0
e = buffer.len(body)
end
if band(flags, 0x40) ~= 0 and ver >= 3 and p + 4 <= e then
-- extended header: v2.3 size excludes its own 4 bytes, v2.4 includes them (syncsafe)
p += if ver == 3 then be32(body, p) + 4 else syncsafe(body, p)
end
local hdr = if ver == 2 then 6 else 10
while p + hdr <= e do
local c0 = ru8(body, p)
if c0 == 0 then
break -- padding
end
local id, fsize, fflags
if ver == 2 then
id = buffer.readstring(body, p, 3)
fsize = bor(lshift(ru8(body, p + 3), 16), lshift(ru8(body, p + 4), 8), ru8(body, p + 5))
fflags = 0
else
id = buffer.readstring(body, p, 4)
fsize = if ver == 4 then syncsafe(body, p + 4) else be32(body, p + 4)
fflags = bor(lshift(ru8(body, p + 8), 8), ru8(body, p + 9))
end
if not string.match(id, "^[A-Z0-9]+$") or fsize <= 0 or p + hdr + fsize > e then
break
end
local fs, fe = p + hdr, p + hdr + fsize
local fb = body
local skip = false
if ver == 3 then
skip = band(fflags, 0x00C0) ~= 0 -- compressed / encrypted
elseif ver == 4 then
skip = band(fflags, 0x000C) ~= 0
if not skip and band(fflags, 0x0001) ~= 0 then
fs += 4 -- data length indicator
end
if not skip and band(fflags, 0x0002) ~= 0 and fs < fe then
fb = deunsync(body, fs, fe)
fs = 0
fe = buffer.len(fb)
end
end
if not skip and fs < fe then
local first = string.sub(id, 1, 1)
local enc = ru8(fb, fs)
if first == "T" and id ~= "TXXX" and id ~= "TXX" then
setField(tags, id, clean(decodeText(fb, fs + 1, fe, enc)))
elseif (id == "COMM" or id == "COM") and fe - fs >= 4 then
-- encoding, language[3], short description (NUL-terminated in the encoding), text
local q = fs + 4
local wide = enc == 1 or enc == 2
while q < fe do
if wide then
if q + 1 < fe and ru8(fb, q) == 0 and ru8(fb, q + 1) == 0 then
q += 2
break
end
q += 2
else
if ru8(fb, q) == 0 then
q += 1
break
end
q += 1
end
end
if q <= fe then
setField(tags, id, clean(decodeText(fb, q, fe, enc)))
end
end
end
p += hdr + fsize
end
end
local function v1String(b: buffer, o: number, n: number): string
return (string.gsub(decodeText(b, o, o + n, 0), "[%z%s]+$", ""))
end
-- Parses tags and returns (tags, audio start, audio end) for the buffer b.
-- tags = { title?, artist?, album?, albumartist?, date?, track?, disc?, genre?, composer?, comment?,
-- raw = { [frame id] = text }, id3v2 = "2.3"?, id3v1 = true? }
function Tags.parse(b: buffer): (any, number, number)
local len = buffer.len(b)
local tags: any = { raw = {} }
local start, stop = 0, len
local v2 = Tags.id3v2Size(b, 0, len)
if v2 > 0 then
pcall(parseV2, b, 0, v2, tags)
start = math.min(v2, len)
end
-- mp3dec_skip_id3v1 on what follows the ID3v2 tag
local size = stop - start
if size >= 128 and buffer.readstring(b, start + size - 128, 3) == "TAG" then
local o = start + size - 128
tags.id3v1 = true
local v1: { [string]: any } = {
title = v1String(b, o + 3, 30),
artist = v1String(b, o + 33, 30),
album = v1String(b, o + 63, 30),
date = v1String(b, o + 93, 4),
}
if ru8(b, o + 125) == 0 and ru8(b, o + 126) ~= 0 then
v1.comment = v1String(b, o + 97, 28)
v1.track = tostring(ru8(b, o + 126))
else
v1.comment = v1String(b, o + 97, 30)
end
local g = ru8(b, o + 127)
if GENRES[g] then
v1.genre = GENRES[g]
end
for k, v in v1 do
if tags[k] == nil and v ~= "" then
tags[k] = v
end
end
size -= 128
if size >= 227 and buffer.readstring(b, start + size - 227, 4) == "TAG+" then
size -= 227
end
end
if size > 32 and buffer.readstring(b, start + size - 32, 8) == "APETAGEX" then
size -= 32
local t = start + size + 12
local tagSize = bor(ru8(b, t), lshift(ru8(b, t + 1), 8), lshift(ru8(b, t + 2), 16), lshift(ru8(b, t + 3), 24))
if size >= tagSize then
size -= tagSize
end
tags.ape = true
end
stop = start + size
return tags, start, stop
end
return Tags
+278
View File
@@ -0,0 +1,278 @@
--!strict
-- audio/mp3: MPEG audio (ISO/IEC 11172-3, 13818-3; MPEG-2.5), layers I, II and III. Absorbed from mp3-luau c755bbf
-- (same author; a port of minimp3 by lieff, CC0: licenses/minimp3-CC0.txt). Supports: decode of MPEG-1 / 2 / 2.5
-- layers I / II / III, mono / stereo / joint stereo / dual channel, CBR / VBR / free format, gapless playback (Xing /
-- Info + LAME delay and padding), exact length and sample-accurate seeking from a frame index built on open, resync
-- past garbage, mono / stereo switches (upmixed), ID3v2.2 / 2.3 / 2.4 and ID3v1 / 1.1 tags (APEv2 skipped).
-- Float output (minimp3's MINIMP3_FLOAT_OUTPUT scalar path). Encode (ws-audio, codecs/audio/Mpa/Encode3 + Encode2): layer III
-- (shine-style CBR, MPEG-1 / 2 / 2.5) and layer II (MPEG-1 / 2), mono / stereo / joint stereo, an ID3v2.4 tag from
-- the tags; input at rates the layer cannot hold is resampled (codecs/audio/Resample). Not supported: MPEG-2 multichannel
-- extension, CRC checks, VBR / Xing output.
-- The codec itself is codecs/audio/Mpa; this folder maps it onto the file (container, tags, seeking, writing).
--
-- local dec = Mp3.open(Bytes.reader(buf)) -- the streaming Types.Decoder (+ layer, version, vbr, delay,
-- local pcm, n = dec:read(4096) -- padding, mpegFrames, id3, :seekFrame(i), :readAll())
-- local audio = Mp3.decode(Bytes.reader(buf)) -- a Types.Audio (the whole file)
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Header = require("@rosetta/codecs/audio/Mpa/Header")
local Index = require("@rosetta/audio/mp3/Index")
local Tags = require("@rosetta/audio/mp3/Tags")
local Stream = require("@rosetta/audio/mp3/Stream")
local Encode3 = require("@rosetta/codecs/audio/Mpa/Encode3")
local Encode2 = require("@rosetta/codecs/audio/Mpa/Encode2")
local Pcm = require("@rosetta/codecs/audio/Pcm")
local Resample = require("@rosetta/codecs/audio/Resample")
-- ------------------------------------------------------------------------------------------------ contract
local Mp3 = {
name = "mp3",
category = "audio",
extensions = { "mp3", "mp2", "mp1", "mpga" },
mime = { "audio/mpeg", "audio/mp3", "audio/mpa" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Resample", "codecs/audio/Mpa/Header", "codecs/audio/Mpa/Core", "codecs/audio/Mpa/Encode3", "codecs/audio/Mpa/Encode2" },
caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, encodeLayers = { 2, 3 }, channels = 2 },
}
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
maxFrames: number?, -- refuse streams longer than this many sample frames per channel (default 2^31)
}
export type Decoder = Stream.Decoder
export type EncodeOptions = {
layer: number?, -- 3 (MP3, default) or 2 (MP2)
bitrate: number?, -- bits per second, constant: one of the layer's rates (default 128000 for layer III, 192000 for
-- layer II; MPEG-2 / 2.5 rates: 64000 / 96000); values below 1000 are kbit/s (128 = 128000, the old unit)
mode: ("stereo" | "joint" | "mono")?, -- default "joint" (mid / side) for stereo layer III, "stereo" for layer II,
-- "mono" for mono input; layer II has no joint stereo (intensity) and writes "joint" as "stereo"
id3: boolean?, -- write an ID3v2.4 tag from the tags (default true when there are tags)
sampleRate: number?, -- output rate (one the layer holds); default the input rate if possible, else the nearest
-- higher one (input at other rates is resampled through codecs/audio/Resample)
resampleQuality: ("low" | "medium" | "high")?, -- codecs/audio/Resample quality (default "medium")
}
-- ------------------------------------------------------------------------------------------------ constants
local MAX_FRAMES = 2 ^ 31
-- ------------------------------------------------------------------------------------------------ sniff
-- an ID3v2 tag and / or a valid frame header at the start, more when the next frame chains on
function Mp3.sniff(r: Bytes.Reader): number
local b, p, lim = r.buf, r.pos, r.limit
local id3 = false
for _ = 1, 4 do -- (ffmpeg writes a tag even when the input had one: tags can follow each other)
local n = if p + 3 <= lim and buffer.readstring(b, p, 3) == "ID3" then Tags.id3v2Size(b, p, lim) else 0
if n <= 0 then
break
end
id3 = true
p += n
end
if p + 4 > lim or not Header.valid(b, p) then
return if id3 then 0.5 else 0
end
local fb = Header.frameBytes(b, p, 0)
if fb > 0 then
fb += Header.padding(b, p)
if p + fb + 4 <= lim and Header.compare(b, p, p + fb) then
return 0.9
end
if p + fb == lim then
return 0.6
end
end
return if id3 then 0.7 else 0.25
end
-- ------------------------------------------------------------------------------------------------ decode
-- decode(r, opts) -> Types.Audio (the whole stream, through open)
function Mp3.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?)
local dec, err = Mp3.open(r, opts)
if not dec then
return nil, err
end
local a, derr = Pcm.drain(dec, { format = "mp3", layer = dec.layer, version = dec.version, bitrate = dec.bitrate, vbr = dec.vbr })
if a and a.frames < dec.frames then
return nil, Err.new(Err.CORRUPT, string.format("decoded %d of %d frames", a.frames, dec.frames))
end
return a, derr
end
-- ------------------------------------------------------------------------------------------------ encode
local ID3_FRAMES = {
{ "title", "TIT2" },
{ "artist", "TPE1" },
{ "album", "TALB" },
{ "albumartist", "TPE2" },
{ "year", "TDRC" },
{ "date", "TDRC" },
{ "track", "TRCK" },
{ "genre", "TCON" },
{ "composer", "TCOM" },
}
-- an ID3v2.4 tag (UTF-8 text frames + a COMM frame) | nil when there is nothing to write
local function id3Tag(tags: { [string]: any }): buffer?
local w = Bytes.writer(256)
local seen: { [string]: boolean } = {}
local function syncsafe(v: number)
w:u8((v // 2097152) % 128)
w:u8((v // 16384) % 128)
w:u8((v // 128) % 128)
w:u8(v % 128)
end
for _, f in ID3_FRAMES do
local v = tags[f[1]]
if type(v) == "string" and #v > 0 and not seen[f[2]] then
seen[f[2]] = true
w:string(f[2])
syncsafe(#v + 1)
w:u16be(0)
w:u8(3) -- UTF-8
w:string(v)
end
end
if type(tags.comment) == "string" and #tags.comment > 0 then
local v = tags.comment
w:string("COMM")
syncsafe(#v + 5)
w:u16be(0)
w:u8(3)
w:string("eng")
w:u8(0) -- empty description
w:string(v)
end
local body = w:finish()
if buffer.len(body) == 0 then
return nil
end
local out = Bytes.writer(buffer.len(body) + 10)
out:string("ID3")
out:u8(4)
out:u8(0)
out:u8(0)
local n = buffer.len(body)
out:u8((n // 2097152) % 128)
out:u8((n // 16384) % 128)
out:u8((n // 128) % 128)
out:u8(n % 128)
out:bytes(body)
return out:finish()
end
-- encode(audioOrDecoder, opts?) -> an MP3 (layer III) or MP2 (layer II) file | nil, Err
function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local src, serr = Pcm.source(value)
if not src then
return nil, serr
end
local o: EncodeOptions = opts or {}
local layer = o.layer or 3
if layer ~= 2 and layer ~= 3 then
return nil, Err.new(Err.ARG, "layer must be 2 or 3")
end
local Enc = if layer == 3 then Encode3 else Encode2
-- the output rate: opts.sampleRate, else the input's when the layer has it, else the nearest rate above it (else
-- the highest); other input rates go through codecs/audio/Resample
local rate = o.sampleRate or src.sampleRate
if o.sampleRate and not Enc.RATES[o.sampleRate] then
return nil, Err.new(Err.ARG, string.format("layer %d cannot hold %s Hz", layer, tostring(o.sampleRate)))
end
if not Enc.RATES[rate] then
local best, top = nil, 0
for r in Enc.RATES do
top = math.max(top, r)
if r >= rate and (best == nil or r < best) then
best = r
end
end
rate = best or top
end
if rate ~= src.sampleRate then
local rs, rerr = Resample.source(src, rate, { quality = o.resampleQuality })
if not rs then
return nil, Err.new(Err.ARG, tostring(rerr))
end
src = rs
end
local info = Enc.RATES[rate]
local mpeg1 = info[1] == 3
local mode = o.mode or (if src.channels == 1 then "mono" elseif layer == 3 then "joint" else "stereo")
if mode ~= "stereo" and mode ~= "joint" and mode ~= "mono" then
return nil, Err.new(Err.ARG, "mode must be stereo, joint or mono")
end
if src.channels > 2 then
return nil, Err.new(Err.ARG, "MPEG audio holds 1 or 2 channels")
end
if layer == 2 and mode == "joint" then
mode = "stereo"
end
-- bitrate: bit/s, or kbit/s below 1000; the encoder works in kbit/s
local bitrate = o.bitrate or (if mpeg1 then (if layer == 3 then 128 else 192) else (if layer == 3 then 64 else 96))
if type(bitrate) == "number" and bitrate >= 1000 then
bitrate /= 1000
end
if not table.find(Enc.BITRATES[if mpeg1 then 1 else 2], bitrate) then
return nil, Err.new(Err.ARG, string.format("%s bit/s is not a layer %d bit rate at %d Hz", tostring(if type(o.bitrate) == "number" and o.bitrate < 1000 then o.bitrate * 1000 else o.bitrate), layer, rate))
end
if layer == 2 and mpeg1 then
-- the standard's allowed bit rate / mode combinations
if mode == "mono" and bitrate > 192 then
return nil, Err.new(Err.ARG, "layer II mono is at most 192 kbps")
elseif mode ~= "mono" and (bitrate == 32 or bitrate == 48 or bitrate == 56 or bitrate == 80) then
return nil, Err.new(Err.ARG, "layer II stereo needs 64 kbps or more (and not 80)")
end
end
local prefix = if o.id3 == false then nil else id3Tag(src.tags)
local out, msg = Enc.encode(src :: any, { bitrate = bitrate, mode = mode, prefix = prefix })
if not out then
return nil, Err.new(Err.ARG, tostring(msg))
end
return out, nil
end
-- ------------------------------------------------------------------------------------------------ open
-- the string-valued tag fields (title, artist, album, albumartist, date, track, disc, genre, composer, comment)
local function stringTags(t: any): { [string]: string }
local out: { [string]: string } = {}
for k, v in t do
if type(k) == "string" and type(v) == "string" and k ~= "id3v2" then
out[k] = v
end
end
return out
end
-- open(r, opts) -> the streaming Decoder (Types.Decoder) | nil, Err
function Mp3.open(r: Bytes.Reader, opts: OpenOptions?): (Decoder?, Err.Err?)
local b = r.buf
if r.base ~= 0 or r.limit ~= buffer.len(b) then
b = buffer.create(r.limit - r.base) -- the core indexes from offset 0
buffer.copy(b, 0, r.buf, r.base, r.limit - r.base)
end
local okTags, tags, start, stop = pcall(Tags.parse, b)
if not okTags then
tags, start, stop = { raw = {} }, 0, buffer.len(b)
end
local idx = Index.build(b, start, stop)
if not idx then
return nil, Err.new(Err.CORRUPT, "no MPEG audio frames found")
end
local dec = Stream.new(b, idx, stringTags(tags), {
raw = tags.raw,
id3v2 = tags.id3v2,
id3v1 = tags.id3v1 == true,
ape = tags.ape == true,
})
if dec.frames > (opts and opts.maxFrames or MAX_FRAMES) then
return nil, Err.new(Err.LIMIT, string.format("%d sample frames is over the limit", dec.frames))
end
return dec, nil
end
-- ------------------------------------------------------------------------------------------------ extras
Mp3.Tags = Tags -- Tags.parse(buf) -> (tags, audio start, audio end)
return Mp3
+96
View File
@@ -0,0 +1,96 @@
--!strict
-- audio/mpc: Musepack (.mpc / .mp+ / .mpp), stream versions 7 and 8, through codecs/audio/Musepack (a libmpcdec
-- port). Supports: SV7 (mppenc 1.x) and SV8 (mpcenc 1.30) streams, mono / stereo, every rate (32 / 37.8 / 44.1 /
-- 48 kHz), gapless length (the synthesis delay, SV8 leading silence and the last frame's length are honoured), seeking
-- (SV8: by audio packet, exact; SV7: by frame with 32 frames of pre-roll, as libmpcdec), APEv2 tags
-- (codecs/audio/ApeTag), a leading ID3v2 tag (skipped), ReplayGain values in meta (not applied). Not supported:
-- writing, SV4 - SV6 (UNSUPPORTED), chapters.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Pcm = require("@rosetta/codecs/audio/Pcm")
local Stream = require("@rosetta/codecs/audio/Stream")
local ApeTag = require("@rosetta/codecs/audio/ApeTag")
local Musepack = require("@rosetta/codecs/audio/Musepack")
-- ------------------------------------------------------------------------------------------------ contract
local Mpc = {
name = "mpc",
category = "audio",
extensions = { "mpc", "mp+", "mpp" },
mime = { "audio/x-musepack", "audio/musepack" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Musepack" },
caps = { decode = true, encode = false, codecs = { "musepack" }, versions = { 7, 8 }, streaming = true, lossy = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxFrames: number?, -- Err.LIMIT past this many output sample frames (default 2^31)
}
-- ------------------------------------------------------------------------------------------------ constants
-- the size of an ID3v2 tag at p (0 if none)
local function id3v2(b: buffer, p: number, limit: number): number
if p + 10 > limit or buffer.readstring(b, p, 3) ~= "ID3" then
return 0
end
local n = 10
for i = 6, 9 do
n += bit32.band(buffer.readu8(b, p + i), 127) * 128 ^ (9 - i)
end
return n + (if bit32.band(buffer.readu8(b, p + 5), 0x10) ~= 0 then 10 else 0)
end
-- ------------------------------------------------------------------------------------------------ sniff
function Mpc.sniff(r: Bytes.Reader): number
local b, p, limit = r.buf, r.pos, r.limit
p += id3v2(b, p, limit)
local v = Musepack.magic(b, p, limit)
if v == 8 then
return 1
end
return if v == 7 then 0.9 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Mpc.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
local o: DecodeOptions = opts or {}
local b, base, limit = r.buf, r.base, r.limit
local start = base + id3v2(b, base, limit)
local tags, info = ApeTag.find(b, start, limit)
local stop = if info and info.start > start then info.start else limit
local s, err = Musepack.open(b, start, stop)
if not s then
return nil, err
end
if s.frames > (o.maxFrames or 2 ^ 31) then
return nil, Err.new(Err.LIMIT, "more than " .. (o.maxFrames or 2 ^ 31) .. " frames")
end
local duration = s.frames / s.sampleRate
local dec = {
sampleRate = s.sampleRate,
channels = s.channels,
frames = s.frames,
duration = duration,
bitrate = if duration > 0 then math.floor(s.bytes * 8 / duration + 0.5) else 0,
tags = tags or {},
codec = "musepack",
version = s.version,
profile = s.profile,
gain = s.gain,
}
return Stream.packets(dec, s :: any)
end
function Mpc.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
local dec, err = Mpc.open(r, opts)
if not dec then
return nil, err
end
local d: any = dec
return Pcm.drain(d, { format = "mpc", codec = "musepack", version = d.version, profile = d.profile, gain = d.gain, bitrate = d.bitrate })
end
return Mpc
+117
View File
@@ -0,0 +1,117 @@
--!strict
-- audio/opus/Encode: Ogg Opus writing (RFC 7845) around codecs/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 (codecs/audio/Resample); the input is a Types.Audio or a Decoder (codecs/audio/Pcm). New in
-- rosetta.
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Ogg = require("@rosetta/containers/Ogg")
local Pcm = require("@rosetta/codecs/audio/Pcm")
local Resample = require("@rosetta/codecs/audio/Resample")
local VorbisComment = require("@rosetta/codecs/audio/VorbisComment")
local CeltEncoder = require("@rosetta/codecs/audio/Opus/CeltEncoder")
local Encode = {}
export type Options = {
bitrate: number?, -- bits per second (default 64000 per channel; 6000 .. 510000, constant); values below 1000
-- are kbit/s (96 = 96000), as for every encoder's bitrate option
tags: { [string]: string }?, -- default: the audio's tags
vendor: string?, -- OpusTags vendor (default "rosetta")
serial: number?, -- Ogg stream serial (default 0x4f707573)
}
local floor = math.floor
-- encode(audio | decoder, opts) -> buffer | nil, Err
function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?)
local o: Options = opts or {}
local src, serr = Pcm.source(value)
if not src then
return nil, serr
end
local ch = src.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 = src.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" and bitrate > 0 and bitrate < 1000 then
bitrate *= 1000 -- kbit/s
end
if type(bitrate) ~= "number" or bitrate < 6000 or bitrate > 510000 then
return nil, Err.new(Err.ARG, "bitrate 6000 .. 510000")
end
-- the whole input at 48 kHz (codecs/audio/Resample for other rates), then as floats
if rate ~= 48000 then
local rs, rerr = Resample.source(src, 48000)
if not rs then
return nil, Err.new(Err.ARG, tostring(rerr))
end
src = rs
end
local all, aerr = Pcm.collect(src :: Pcm.Source)
if not all then
return nil, aerr
end
local n48 = all.frames
local samples = all.samples
local pcm: { number } = table.create(n48 * ch, 0)
local readf32 = buffer.readf32
for i = 1, n48 * ch do
pcm[i] = readf32(samples, (i - 1) * 4)
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 src.tags or {}
local tw = Bytes.writer(256)
tw:string("OpusTags")
local vendor = o.vendor or "rosetta"
tw:u32le(#vendor)
tw:string(vendor)
local fields = VorbisComment.fields(tags)
tw:u32le(#fields)
for _, field in fields do
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
+402
View File
@@ -0,0 +1,402 @@
--!strict
-- audio/opus: Ogg Opus (RFC 6716 codec, RFC 7845 encapsulation). Absorbed from opus-luau dd2b4e5 (same author; a
-- port of the libopus 1.6 decoder, BSD: licenses/libopus-BSD.txt): the range decoder, CELT (float), SILK
-- (bit-exact fixed point), hybrid, mode transitions, PLC, multistream (mapping families 0, 1, 255).
-- 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.
-- 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.
-- The codec itself is codecs/audio/Opus; this folder maps it onto the file (container, tags, seeking, writing).
--
-- 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("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Ogg = require("@rosetta/containers/Ogg")
local Decoder = require("@rosetta/codecs/audio/Opus/Decoder")
local Packet = require("@rosetta/codecs/audio/Opus/Packet")
local VorbisComment = require("@rosetta/codecs/audio/VorbisComment")
local Pcm = require("@rosetta/codecs/audio/Pcm")
local RangeDecoder = require("@rosetta/codecs/entropy/RangeCoder/Decoder")
local Celt = require("@rosetta/codecs/audio/Opus/Celt")
local Silk = require("@rosetta/codecs/audio/Opus/Silk")
local Encode = require("@rosetta/audio/opus/Encode")
-- ------------------------------------------------------------------------------------------------ contract
local Opus = {
name = "opus",
category = "audio",
extensions = { "opus" },
mime = { "audio/opus", "audio/ogg" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/entropy/RangeCoder/Decoder", "codecs/audio/Pcm", "codecs/audio/Resample", "codecs/audio/VorbisComment", "codecs/audio/Opus/CeltEncoder", "codecs/audio/Opus/Decoder", "codecs/audio/Opus/Packet", "codecs/audio/Opus/Celt", "codecs/audio/Opus/Silk" },
caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" }, encodeChannels = 2 },
}
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
verify: boolean?, -- check the Ogg page CRCs (default true; false decodes damaged files)
stereo: boolean?, -- downmix more than 2 channels to stereo (default false; dec.channels is then 2)
}
-- ------------------------------------------------------------------------------------------------ constants
local SAMPLE_RATE = 48000
-- stereo downmix weights for the Vorbis channel orders of mapping family 1 (3 to 8 channels), as in opusfile
local DOWNMIX = {
[3] = { 0.5858, 0, 0.4142, 0.4142, 0, 0.5858 },
[4] = { 0.4226, 0, 0, 0.4226, 0.366, 0.2114, 0.2114, 0.366 },
[5] = { 0.651, 0, 0.46, 0.46, 0, 0.651, 0.5636, 0.3254, 0.3254, 0.5636 },
[6] = { 0.529, 0, 0.3741, 0.3741, 0, 0.529, 0.4582, 0.2645, 0.2645, 0.4582, 0.3741, 0.3741 },
[7] = { 0.4553, 0, 0.322, 0.322, 0, 0.4553, 0.3943, 0.2277, 0.2277, 0.3943, 0.2788, 0.2788, 0.322, 0.322 },
[8] = { 0.3886, 0, 0.2748, 0.2748, 0, 0.3886, 0.3366, 0.1943, 0.1943, 0.3366, 0.3366, 0.1943, 0.1943, 0.3366, 0.2748, 0.2748 },
}
local PREROLL = 3840 -- 80 ms, RFC 7845 section 4.6
local MAX_PACKET = 5760 -- 120 ms
export type Head = {
version: number,
channels: number,
preSkip: number,
inputSampleRate: number,
outputGain: number, -- Q7.8 dB
mappingFamily: number,
streams: number,
coupled: number,
mapping: { number },
}
-- OpusHead (RFC 7845 section 5.1). Returns the header or nil, message.
local function parseHead(b: buffer, off: number, size: number): (Head?, string?)
if size < 19 or buffer.readstring(b, off, 8) ~= "OpusHead" then
return nil, "not an OpusHead packet"
end
local version = buffer.readu8(b, off + 8)
if bit32.rshift(version, 4) ~= 0 then
return nil, "unsupported OpusHead version " .. version
end
local channels = buffer.readu8(b, off + 9)
if channels < 1 then
return nil, "OpusHead: zero channels"
end
local head: Head = {
version = version,
channels = channels,
preSkip = buffer.readu16(b, off + 10),
inputSampleRate = buffer.readu32(b, off + 12),
outputGain = buffer.readi16(b, off + 16),
mappingFamily = buffer.readu8(b, off + 18),
streams = 1,
coupled = channels - 1,
mapping = {},
}
if head.mappingFamily == 0 then
if channels > 2 then
return nil, "OpusHead: mapping family 0 with more than 2 channels"
end
head.mapping = if channels == 2 then { 0, 1 } else { 0 }
else
if head.mappingFamily == 3 then
return nil, "unsupported channel mapping family 3 (projection)"
end
if size < 21 + channels then
return nil, "OpusHead: truncated channel mapping table"
end
head.streams = buffer.readu8(b, off + 19)
head.coupled = buffer.readu8(b, off + 20)
if head.streams < 1 or head.coupled > head.streams or head.streams + head.coupled > 255 then
return nil, "OpusHead: bad stream counts"
end
for c = 0, channels - 1 do
local m = buffer.readu8(b, off + 21 + c)
if m ~= 255 and m >= head.streams + head.coupled then
return nil, "OpusHead: bad channel mapping"
end
head.mapping[c + 1] = m
end
end
return head, nil
end
-- OpusTags (RFC 7845 section 5.2) -> vendor, tags (codecs/audio/VorbisComment: lower-case keys, repeated fields joined
-- with "; "), the raw fields
local function parseTags(b: buffer, off: number, size: number): (string, { [string]: string }, { VorbisComment.Field })
if size < 16 or buffer.readstring(b, off, 8) ~= "OpusTags" then
return "", {}, {}
end
local p = off + 8
local e = off + size
local vlen = buffer.readu32(b, p)
p += 4
if p + vlen > e then
return "", {}, {}
end
local vendor = buffer.readstring(b, p, vlen)
p += vlen
local list = {}
if p + 4 <= e then
local n = buffer.readu32(b, p)
p += 4
for _ = 1, n do
if p + 4 > e then
break
end
local l = buffer.readu32(b, p)
p += 4
if p + l > e then
break
end
table.insert(list, buffer.readstring(b, p, l))
p += l
end
end
local tags, raw = VorbisComment.tags(list)
return vendor, tags, raw
end
Opus.Decoder = Decoder
Opus.Packet = Packet
Opus.RangeDecoder = RangeDecoder
Opus.Celt = Celt
Opus.Silk = Silk
Opus.parseHead = parseHead
Opus.parseTags = parseTags
Opus.SAMPLE_RATE = SAMPLE_RATE
-- ------------------------------------------------------------------------------------------------ sniff
-- 1 when the file starts with an Ogg page whose first packet is an OpusHead
function Opus.sniff(r: Bytes.Reader): number
if r:peek(4) ~= "OggS" then
return 0
end
local nseg = r:peekU8(26)
if nseg < 1 then
return 0
end
return if r:peek(8, 27 + nseg) == "OpusHead" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- decode(r, opts?) -> Audio | nil, Err: the whole stream (48 kHz f32)
function Opus.decode(r: any, opts: OpenOptions?): (Types.Audio?, Err.Err?)
local dec, err = Opus.open(r, opts)
if not dec then
return nil, err
end
return Pcm.drain(dec, { format = "opus", channels = dec.sourceChannels, preSkip = dec.preSkip, vendor = dec.vendor, comments = dec.comments, mappingFamily = dec.head.mappingFamily, inputSampleRate = dec.head.inputSampleRate })
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
-- Decodes the next packet into the pending buffer. Returns false at the end of the stream.
local function decodeNext(self: any): boolean
local p = self.demux:nextPacket(self.serial)
if p == nil then
return false
end
local n
if p.size > 0 then
n = Decoder.decodeMultistream(self.ms, p.data, p.offset, p.size, self.pend, 1, MAX_PACKET)
else
n = -1
end
if n < 0 then
-- corrupt or empty packet: conceal for its nominal duration
local dur = if p.size > 0 then Packet.samples(p.data, p.offset, p.size) else -1
if dur <= 0 then
dur = self.lastDuration
end
n = Decoder.decodeMultistream(self.ms, nil, 0, 0, self.pend, 1, dur)
if n < 0 then
n = dur
for i = 1, n * self.channels do
self.pend[i] = 0
end
end
end
self.lastDuration = n
self.pendStart = self.decoded
self.pendLen = n
self.pendPos = 0
self.decoded += n
return true
end
-- dec:read(maxFrames, out?) -> buffer of interleaved f32 samples, frames read (0 at the end of the stream). out (if
-- given and big enough) is filled instead of a new buffer.
function Stream.read(self: any, maxFrames: number, into: buffer?): (buffer, number)
local ch = self.channels
local mf = if type(maxFrames) == "number" and maxFrames == maxFrames then maxFrames else 0
local want = math.max(0, math.min(math.floor(mf), self.endSample - self.next))
local reuse = into ~= nil and buffer.len(into) >= want * ch * 4
local out = if reuse then into :: buffer else buffer.create(want * ch * 4)
local got = 0
local gain = self.gain
while got < want do
if self.pendPos >= self.pendLen then
if not decodeNext(self) then
break
end
end
-- skip decoded samples before the next wanted one (pre-skip, seek pre-roll)
local s = self.pendStart + self.pendPos
if s < self.next then
self.pendPos = math.min(self.pendLen, self.pendPos + (self.next - s))
continue
end
local n = math.min(self.pendLen - self.pendPos, want - got)
if self.downmix then
Decoder.writeDownmix(self.pend, self.pendPos * self.sourceChannels, n, self.sourceChannels, self.downmix, gain, out, got * 8)
else
Decoder.writeF32(self.pend, self.pendPos * ch, n * ch, gain, out, got * ch * 4)
if self.order then
Pcm.reorder(out, got * ch * 4, n, ch, self.order)
end
end
self.pendPos += n
got += n
self.next += n
end
if got < want then
if not reuse then
local trimmed = buffer.create(got * ch * 4)
buffer.copy(trimmed, 0, out, 0, got * ch * 4)
out = trimmed
end
self.endSample = self.next -- the stream ended early (truncated file)
end
return out, got
end
-- current playback position in seconds
function Stream.position(self: any): number
return (self.next - self.preSkip) / SAMPLE_RATE
end
-- seek to a time in seconds (clamped to the stream): granule bisection with 80 ms pre-roll
function Stream.seek(self: any, seconds: number)
local sec = if type(seconds) == "number" and seconds == seconds then seconds else 0
local p = math.floor(math.max(0, math.min(sec, 1e12)) * SAMPLE_RATE + 0.5)
p = math.min(p, self.frames)
local target = p + self.preSkip -- decoded-sample index of the wanted sample
Decoder.resetMultistream(self.ms)
self.pendLen, self.pendPos = 0, 0
local g = target - PREROLL + self.startGranule
local start = -1
if g > self.startGranule then
start = self.demux:seekGranule(self.serial, g) or -1
end
if start < 0 then
self.demux:rewind(self.serial)
self.demux:nextPacket(self.serial) -- OpusHead
self.demux:nextPacket(self.serial) -- OpusTags
self.decoded = 0
else
self.decoded = start - self.startGranule
end
self.pendStart = self.decoded
self.next = target
end
-- open(r, opts?) -> Decoder | nil, Err (r: a core/Bytes Reader, or a buffer)
function Opus.open(r: any, opts: OpenOptions?): (any, Err.Err?)
local demux, derr = Ogg.open(r, if opts and opts.verify == false then { verify = false } else nil)
if not demux then
return nil, derr
end
local serial = demux:find("opus")
if serial == nil then
return nil, Err.new(Err.CORRUPT, "no Opus stream in the Ogg file")
end
local hp = demux:nextPacket(serial)
if hp == nil then
return nil, Err.new(Err.TRUNCATED, "missing OpusHead")
end
local head, herr = parseHead(hp.data, hp.offset, hp.size)
if not head then
return nil, Err.new(if string.find(herr or "", "unsupported", 1, true) then Err.UNSUPPORTED else Err.CORRUPT, herr or "bad OpusHead")
end
local tp = demux:nextPacket(serial)
if tp == nil then
return nil, Err.new(Err.TRUNCATED, "missing OpusTags")
end
local vendor, tags, rawTags = parseTags(tp.data, tp.offset, tp.size)
-- granule of the first audio sample: first page granule minus the packets that end on it
local startGranule = 0
local sum = 0
while true do
local p = demux:nextPacket(serial)
if p == nil then
break
end
local d = if p.size > 0 then Packet.samples(p.data, p.offset, p.size) else 0
sum += math.max(d, 0)
if p.granule ~= -1 then
startGranule = math.max(0, p.granule - sum)
break
end
end
demux:rewind(serial)
demux:nextPacket(serial)
demux:nextPacket(serial)
local info = demux:stream(serial)
local last = if info and info.lastGranule and info.lastGranule >= 0 then info.lastGranule else startGranule
local frames = math.max(0, last - startGranule - head.preSkip)
local downmix = nil
if opts and opts.stereo and head.channels > 2 then
downmix = DOWNMIX[head.channels]
if downmix == nil or head.mappingFamily ~= 1 then -- unknown layout: every channel to both sides, equally
downmix = table.create(head.channels * 2, 1 / head.channels)
end
end
local self = setmetatable({
demux = demux,
serial = serial,
head = head,
vendor = vendor,
tags = tags,
comments = rawTags,
-- mapping family 1 is in Vorbis channel order; the output is WAVE order (codecs/audio/Pcm)
order = if not downmix and head.mappingFamily == 1 and head.channels > 2 then Pcm.WAVE_FROM_VORBIS[head.channels] else nil,
sampleRate = SAMPLE_RATE,
channels = if downmix then 2 else head.channels,
sourceChannels = head.channels,
downmix = downmix,
frames = frames,
duration = frames / SAMPLE_RATE,
bitrate = if frames > 0 then math.floor(demux.size * 8 / (frames / SAMPLE_RATE)) else 0,
preSkip = head.preSkip,
startGranule = startGranule,
gain = 10 ^ (head.outputGain / (20 * 256)),
ms = Decoder.newMultistream(head.channels, head.streams, head.coupled, head.mapping),
pend = table.create(MAX_PACKET * head.channels, 0),
pendStart = 0,
pendLen = 0,
pendPos = 0,
decoded = 0, -- decoded-sample index of the next packet's first sample
next = head.preSkip, -- decoded-sample index of the next sample read() returns
endSample = head.preSkip + frames,
lastDuration = 960,
}, Stream)
return self, nil
end
return Opus
+185
View File
@@ -0,0 +1,185 @@
--!strict
-- audio/qoa: QOA, "Quite OK Audio" (.qoa), over codecs/audio/Qoa (a port of qoa.h, phoboslab, MIT). New in
-- rosetta. Decode / open: static files and streaming files (total 0 in the header), 1-255 channels (WAVE order
-- for 1-8, as the spec lays them out), any rate up to 16777215 Hz, frame-accurate seeking (every frame carries its
-- own predictor state), a truncated file decodes its whole frames. Encode (Audio or Decoder, streamed frame by frame):
-- byte-for-byte what qoa.h's qoa_encode writes, 1-8 channels (qoa.h's limit). Not supported: frames whose channel
-- count or rate change mid-stream (Err.UNSUPPORTED).
--
-- local dec = Qoa.open(Bytes.reader(buf)) -- Types.Decoder
-- local file = Qoa.encode(audio)
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Pcm = require("@rosetta/codecs/audio/Pcm")
local Stream = require("@rosetta/codecs/audio/Stream")
local Codec = require("@rosetta/codecs/audio/Qoa")
-- ------------------------------------------------------------------------------------------------ contract
local Qoa = {
name = "qoa",
category = "audio",
extensions = { "qoa" },
mime = { "audio/qoa" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Qoa" },
caps = { decode = true, encode = true, streaming = true, lossy = true, seek = true, channels = 8 },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxFrames: number?, -- decode(): Err.LIMIT past this many sample frames (default 2^28)
}
-- ------------------------------------------------------------------------------------------------ sniff
function Qoa.sniff(r: Bytes.Reader): number
return if r:peek(4) == "qoaf" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Qoa.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
local dec, err = Qoa.open(r)
if not dec then
return nil, err
end
local d = dec :: any
local limit = opts and opts.maxFrames or 2 ^ 28
if d.frames > limit or d.frames * d.channels > 2 ^ 28 then
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames))
end
return Pcm.drain(d, { format = "qoa", streaming = d.streaming }, limit)
end
-- ------------------------------------------------------------------------------------------------ encode
function Qoa.encode(value: any, _opts: any?): (buffer?, Err.Err?)
local src, serr = Pcm.source(value)
if not src then
return nil, serr
end
local ch, rate = src.channels, src.sampleRate
if ch > 8 then
return nil, Err.new(Err.ARG, "QOA (qoa.h) holds at most 8 channels")
end
if rate ~= math.floor(rate) or rate < 1 or rate > 0xFFFFFF then
return nil, Err.new(Err.ARG, "the sample rate must be an integer in 1 .. 16777215")
end
local FL = Codec.FRAME_LEN
local w = Bytes.writer(8 + (if src.frames > 0 then Codec.frameSize(ch, (src.frames + 19) // 20) + 24 * ch * (src.frames // FL + 1) else 65536))
w:string("qoaf")
w:u32be(0)
local lms = Codec.newLms(ch)
local fb = buffer.create(FL * ch * 4)
local tmp: buffer? = nil
local total = 0
while true do
-- one frame: 5120 sample frames (the last may be shorter), as qoa.h cuts them
local have = 0
while have < FL do
local b, n = src:read(FL - have, tmp)
if n <= 0 then
break
end
tmp = b
buffer.copy(fb, have * ch * 4, b, 0, n * ch * 4)
have += n
end
if have == 0 then
break
end
local at = w:reserve(Codec.frameSize(ch, (have + 19) // 20))
w.pos = at + Codec.encodeFrame(fb, 0, have, ch, rate, lms, w.buf, at)
total += have
if have < FL then
break
end
end
if src.err then
return nil, src.err
end
if total == 0 then
return nil, Err.new(Err.ARG, "QOA needs at least one sample")
end
if total >= 2 ^ 32 then
return nil, Err.new(Err.ARG, "too many samples for QOA")
end
local out = w:finish()
buffer.writeu32(out, 4, bit32.byteswap(total))
return out, nil
end
-- ------------------------------------------------------------------------------------------------ open
function Qoa.open(r: Bytes.Reader, _opts: any?): (Types.Decoder?, Err.Err?)
if type(r) ~= "table" or type(r.buf) ~= "buffer" then
return nil, Err.new(Err.ARG, "open: expected a Reader")
end
local h = r:sub(0)
if h:string(4) ~= "qoaf" then
return nil, Err.new(Err.CORRUPT, "not a QOA file")
end
local declared = h:u32be()
if h.err then
return nil, h.err
end
local buf = r.buf
-- the frame index: offsets, first frames
local offs, starts = {}, {}
local p, total = r.base + 8, 0
local ch, rate = 0, 0
while p < r.limit do
local info, msg = Codec.frameInfo(buf, p, r.limit - p)
if not info then
if #offs == 0 then
return nil, Err.from(msg, p - r.base)
end
break -- a cut or damaged tail: keep the whole frames
end
if #offs == 0 then
ch, rate = info.channels, info.rate
elseif info.channels ~= ch or info.rate ~= rate then
return nil, Err.new(Err.UNSUPPORTED, "the channel count or rate changes mid-stream", p - r.base)
end
table.insert(offs, p)
table.insert(starts, total)
total += info.samples
p += info.size
if declared > 0 and total >= declared then
break
end
end
if #offs == 0 then
return nil, Err.new(Err.TRUNCATED, "no frames")
end
local frames = if declared > 0 then math.min(declared, total) else total
local pcm = buffer.create(Codec.FRAME_LEN * ch * 4)
local dec: any = {
sampleRate = rate,
channels = ch,
frames = frames,
duration = frames / rate,
bitrate = math.floor((p - r.base) * 8 / math.max(frames / rate, 1e-9)),
tags = {},
streaming = declared == 0,
}
local limit = r.limit
return Stream.packets(dec, {
count = #offs,
start = function(i: number): number
return if i > #offs then total else starts[i]
end,
decode = function(i: number): (number?, Err.Err?)
local n, msg = Codec.decodeFrame(buf, offs[i], limit - offs[i], pcm, 0)
if not n then
return nil, Err.from(msg, offs[i] - r.base)
end
return n, nil
end,
pcm = function(): buffer
return pcm
end,
reset = function() end,
stop = frames,
})
end
return Qoa
+123
View File
@@ -0,0 +1,123 @@
--!strict
-- audio/tta: True Audio (.tta, TTA1) files around codecs/audio/Tta: an optional ID3v2 tag in front (skipped), the
-- header and seek table, independent frames (sample-accurate seeking), APEv2 tags at the end (codecs/audio/ApeTag).
-- Written from the TTA1 format description; no libtta / ffmpeg code. Supports 8 / 16 / 24 bits, any channel count.
-- Not supported: password-protected files (Err.UNSUPPORTED), TTA2, ID3v2 tag contents, encoding.
--
-- local dec = Tta.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, readInt
-- local audio = Tta.decode(Bytes.reader(buf)) -- Types.Audio
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Pcm = require("@rosetta/codecs/audio/Pcm")
local Stream = require("@rosetta/codecs/audio/Stream")
local ApeTag = require("@rosetta/codecs/audio/ApeTag")
local TtaCodec = require("@rosetta/codecs/audio/Tta")
-- ------------------------------------------------------------------------------------------------ contract
local Tta = {
name = "tta",
category = "audio",
extensions = { "tta" },
mime = { "audio/x-tta", "audio/tta" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Tta" },
caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, depths = { 8, 16, 24 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
maxFrames: number?, -- decode(): refuse longer streams (default 2^28)
}
-- ------------------------------------------------------------------------------------------------ sniff
-- the size of an ID3v2 tag at the reader's start (0 when none)
local function id3Size(r: Bytes.Reader): number
if r:peek(3) ~= "ID3" then
return 0
end
local sz = 0
for i = 6, 9 do
local v = r:peekU8(i)
if v < 0 then
return 0
end
sz = sz * 128 + bit32.band(v, 127)
end
local footer = bit32.band(math.max(r:peekU8(5), 0), 0x10) ~= 0
return 10 + sz + (if footer then 10 else 0)
end
function Tta.sniff(r: Bytes.Reader): number
return if r:peek(4, id3Size(r)) == "TTA1" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream
function Tta.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?)
local dec, err = Tta.open(r, opts)
if not dec then
return nil, err
end
local d = dec :: any
local limit = opts and opts.maxFrames or 2 ^ 28
if d.frames > limit or d.frames * d.channels > 2 ^ 28 then
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames))
end
return Pcm.drain(d, d.source, limit)
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts?) -> Decoder | nil, Err
function Tta.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?)
if type(r) == "buffer" then
r = Bytes.reader(r :: any)
end
if type(r) ~= "table" or type(r.buf) ~= "buffer" then
return nil, Err.new(Err.ARG, "open: expected a Reader")
end
local buf, base, limit = r.buf, r.base, r.limit
local at = base + id3Size(r)
local tags, tagInfo = ApeTag.find(buf, at, limit)
local stop = if tagInfo then tagInfo.start else limit
local info, err = TtaCodec.info(buf, at, stop)
if not info then
return nil, err
end
if info.channels * info.frameLength > 2 ^ 24 then
return nil, Err.new(Err.LIMIT, info.channels .. " channels of " .. info.frameLength .. "-sample frames")
end
local codec = TtaCodec.decoder(info, stop)
local frames = info.samples
local dec: any = {
sampleRate = info.sampleRate,
channels = info.channels,
frames = frames,
duration = frames / info.sampleRate,
bitrate = if frames > 0 then math.floor((stop - base) * 8 * info.sampleRate / frames) else 0,
tags = tags or {},
bitsPerSample = info.bitsPerSample,
float = false,
source = { format = "tta", bitDepth = info.bitsPerSample, tags = tagInfo and tagInfo.items },
}
local fl, count = info.frameLength, info.frames
return Stream.packets(dec, {
count = count,
start = function(i: number): number
return if i > count then frames else (i - 1) * fl
end,
decode = function(i: number): (number?, Err.Err?)
return codec:frame(buf, i)
end,
pcm = function(): { number }
return codec.pcm
end,
reset = function() end,
stop = frames,
scale = 1 / 2 ^ (info.bitsPerSample - 1),
ints = true,
})
end
return Tta
+231
View File
@@ -0,0 +1,231 @@
--!strict
-- audio/vag: Sony VAG (PlayStation SPU PS-ADPCM, .vag), and Simon & Schuster / Hyperscan KVAG (IMA ADPCM, the same
-- extension), over codecs/audio/Adpcm. New in rosetta; the header variants and the PS-ADPCM decoding follow
-- vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), whose output it matches bit for bit. Supports: "VAGp" mono
-- (versions 0, 2, 3, 4, 6, 0x20; the name field as tags.title; loop points from the frame flags, as dec.loop and
-- meta.source.loop = { start, stop } in frames, stop exclusive), "VAGi" stereo (interleaved blocks), "KVAG" mono /
-- stereo IMA. The output starts with the blank frame Sony's tools put first (28 silent samples), as vgmstream plays it.
-- Encode (Audio or Decoder): mono to VAGp, stereo to VAGi (2048-byte interleave), loop points from opts.loop (frame
-- aligned: 28 samples). Not supported: HEVAG (VAGp versions 0x00020001 / 0x00030000, Vita / PS4), the many game
-- specific variants vgmstream knows (pGAV, VAG1 / VAG2, Jak, ...).
--
-- local dec = Vag.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, variant)
-- local file = Vag.encode(audio, { loop = { start = 0, stop = audio.frames } })
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Pcm = require("@rosetta/codecs/audio/Pcm")
local Adpcm = require("@rosetta/codecs/audio/Adpcm")
local Decoder = require("@rosetta/codecs/audio/Adpcm/Decoder")
-- ------------------------------------------------------------------------------------------------ contract
local Vag = {
name = "vag",
category = "audio",
extensions = { "vag" },
mime = { "audio/x-vag" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" },
caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 2 },
}
-- ------------------------------------------------------------------------------------------------ types
export type Loop = { start: number, stop: number }
export type DecodeOptions = {
maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28)
}
export type EncodeOptions = {
loop: Loop?, -- loop points in frames of the input (stop exclusive), rounded out to 28-sample frames; default: the
-- source's meta.source.loop, else none
name: string?, -- the 16-byte name field (default: tags.title)
interleave: number?, -- stereo: bytes per channel block (default 2048, a multiple of 16)
}
-- ------------------------------------------------------------------------------------------------ constants
local HEVAG = { [0x00020001] = true, [0x00030000] = true }
-- ------------------------------------------------------------------------------------------------ sniff
function Vag.sniff(r: Bytes.Reader): number
local m = r:peek(4)
return if m == "VAGp" or m == "VAGi" or m == "KVAG" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Vag.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
local dec, err = Vag.open(r)
if not dec then
return nil, err
end
local d = dec :: any
local limit = opts and opts.maxFrames or 2 ^ 28
if d.frames > limit or d.frames * d.channels > 2 ^ 28 then
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames))
end
return Pcm.drain(d, { format = "vag", variant = d.variant, codec = d.codec, loop = d.loop }, limit)
end
-- ------------------------------------------------------------------------------------------------ encode
function Vag.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: EncodeOptions = opts or {}
local src, serr = Pcm.source(value)
if not src then
return nil, serr
end
local ch, rate = src.channels, src.sampleRate
if ch > 2 then
return nil, Err.new(Err.ARG, "VAG holds mono or stereo")
end
if rate ~= math.floor(rate) or rate < 1 or rate >= 2 ^ 32 then
return nil, Err.new(Err.ARG, "the sample rate must be a positive integer")
end
local il = o.interleave or 2048
if type(il) ~= "number" or il < 16 or il % 16 ~= 0 then
return nil, Err.new(Err.ARG, "interleave must be a multiple of 16")
end
local loop = o.loop
local v = value :: any
if loop == nil and type(v.meta) == "table" and type(v.meta.source) == "table" and type(v.meta.source.loop) == "table" then
loop = v.meta.source.loop
end
local a, cerr = Pcm.collect(src)
if not a then
return nil, cerr
end
local n = a.frames
local nf = (n + 27) // 28 -- data frames (after the blank one)
local ls, le = -1, -1
if loop then
if type(loop.start) ~= "number" or type(loop.stop) ~= "number" or loop.start < 0 or loop.stop > n then
return nil, Err.new(Err.ARG, "loop must be { start, stop } inside the audio")
end
ls, le = loop.start // 28, (loop.stop + 27) // 28 - 1
if le <= ls then
return nil, Err.new(Err.ARG, "the loop must span two 28-sample frames")
end
end
local chBytes = (nf + 1) * 16
local stride = if ch == 1 then chBytes else (chBytes + il - 1) // il * il
local start = if ch == 1 then 0x30 else 0x800
local out = buffer.create(start + stride * ch)
local title = o.name or (a.tags and a.tags.title) or ""
buffer.writestring(out, 0, if ch == 1 then "VAGp" else "VAGi")
buffer.writeu32(out, 4, bit32.byteswap(0x20))
if ch == 2 then
buffer.writeu32(out, 8, il)
end
buffer.writeu32(out, 0x0C, bit32.byteswap(if ch == 1 then chBytes else stride))
buffer.writeu32(out, 0x10, bit32.byteswap(rate))
buffer.writestring(out, 0x20, string.sub(title, 1, 16))
local st = buffer.create(8 * ch)
local plane = buffer.create(chBytes)
for c = 0, ch - 1 do
buffer.fill(plane, 0, 0)
Adpcm.psxEncode(a.samples, c, ch, n, st, c * 8, plane, 16, 16)
for k = 0, nf - 1 do
local flag = if k == ls then 6 elseif k == le then 3 elseif k > ls and k < le then 2 else 0
if not loop and k == nf - 1 then
flag = 1
end
buffer.writeu8(plane, 16 + k * 16 + 1, flag)
end
if ch == 1 then
buffer.copy(out, start, plane, 0, chBytes)
else
for b = 0, stride // il - 1 do
local take = math.clamp(chBytes - b * il, 0, il)
if take > 0 then
buffer.copy(out, start + (b * ch + c) * il, plane, b * il, take)
end
end
end
end
return out, nil
end
-- ------------------------------------------------------------------------------------------------ open
-- the loop from the PS-ADPCM frame flags of channel 0 (vgmstream's reading: the first start flag 6, the first end
-- flag 3), or nil
local function findLoop(buf: buffer, p: number, frames: number, il: number, ch: number): Loop?
local ls, le = -1, -1
for k = 0, frames - 1 do
local off = p + (k * 16) // il * il * ch + (k * 16) % il
local flag = bit32.band(buffer.readu8(buf, off + 1), 15)
if flag == 6 and ls < 0 then
ls = k * 28
elseif flag == 3 and le < 0 then
le = k * 28 + 28
if ls >= 0 then
break
end
end
end
return if ls >= 0 and le > ls then { start = ls, stop = le } else nil
end
function Vag.open(r: Bytes.Reader, _opts: any?): (Types.Decoder?, Err.Err?)
if type(r) ~= "table" or type(r.buf) ~= "buffer" then
return nil, Err.new(Err.ARG, "open: expected a Reader")
end
local h = r:sub(0)
local magic = h:string(4)
local total = r.limit - r.base
if magic == "KVAG" then
local size, rate, stereo = h:u32le(), h:u32le(), h:u16le()
if h.err then
return nil, h.err
end
if rate < 1 or stereo > 1 then
return nil, Err.new(Err.CORRUPT, "bad KVAG header")
end
local dec: any = { sampleRate = rate, channels = stereo + 1, tags = {}, variant = "KVAG", codec = "ima" }
local d, err = Decoder.nibbles(dec, { buf = r.buf, offset = r.base + 14, size = math.min(size, total - 14), hi = true })
if d then
d.bitrate = rate * 4 * (stereo + 1)
end
return d, err
end
if magic ~= "VAGp" and magic ~= "VAGi" then
return nil, Err.new(Err.CORRUPT, "not a VAG file")
end
local version, il = h:u32be(), h:u32le()
local chSize, rate = h:u32be(), h:u32be()
local name = r:sub(0x20, 16):cstring(16)
if h.err then
return nil, h.err
end
if HEVAG[version] then
return nil, Err.new(Err.UNSUPPORTED, "HEVAG (Vita / PS4 VAG)")
end
if rate < 1 or rate >= 2 ^ 31 then
return nil, Err.new(Err.CORRUPT, "bad sample rate " .. rate)
end
local ch, start = 1, 0x30
if magic == "VAGi" then
ch, start = 2, 0x800
if il < 16 or il % 16 ~= 0 then
return nil, Err.new(Err.CORRUPT, "bad interleave " .. il)
end
else
il = 16
end
if total < start then
return nil, Err.new(Err.TRUNCATED, "the header runs past the end")
end
local size = math.min(chSize * ch, total - start)
local p = r.base + start
local frames = math.min(chSize // 16, (size // (il * ch)) * (il // 16) + math.clamp(size % (il * ch) - (ch - 1) * il, 0, il) // 16)
local loop = if magic == "VAGp" then findLoop(r.buf, p, frames, il, ch) else nil -- vgmstream: VAGi never loops
local tags = {}
if name ~= "" then
tags.title = name
end
local dec: any = { sampleRate = rate, channels = ch, tags = tags, variant = magic, codec = "psx", loop = loop }
local d, err = Decoder.interleaved(dec, { kind = "psx", buf = r.buf, offset = p, size = size, interleave = il, frames = frames * 28 })
if d then
d.bitrate = rate * 16 * 8 * ch // 28
end
return d, err
end
return Vag
+278
View File
@@ -0,0 +1,278 @@
--!strict
-- audio/voc: Creative Voice File (.voc, Sound Blaster). New code from the Creative file format description.
-- Supports: decode / open of block types 1 (sound data: 8-bit unsigned, 16-bit), 2 (continuation), 3 (silence),
-- 5 (text: tags.comment), 8 (extended: stereo / high rates for the next type 1 block), 9 (new sound data: 8-bit
-- unsigned, 16-bit signed, A-law, mu-law, any rate / channel count); markers and repeat loops are skipped (played
-- once, as ffmpeg does); truncated files decode the data present. Encode (Audio or Decoder, streamed) as version
-- 1.20 type 9 blocks of u8 / s16 (default) / alaw / ulaw. Not supported: Creative 4 / 2.6 / 2-bit ADPCM
-- (Err.UNSUPPORTED), blocks that change the channel count mid-file (the sample rate of the first block is used).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Pcm = require("@rosetta/codecs/audio/Pcm")
-- ------------------------------------------------------------------------------------------------ contract
local Voc = {
name = "voc",
category = "audio",
extensions = { "voc" },
mime = { "audio/x-voc" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16 }, lossy = false },
}
export type DecodeOptions = {
maxFrames: number?, -- refuse more sample frames (default 2^28)
}
export type EncodeOptions = {
sampleFormat: ("u8" | "s16" | "alaw" | "ulaw")?, -- default "s16"
}
-- ------------------------------------------------------------------------------------------------ constants
local MAGIC = "Creative Voice File\26"
local T9_CODECS: { [number]: string } = { [0] = "u8", [4] = "s16le", [6] = "alaw", [7] = "ulaw" }
local T1_CODECS: { [number]: string } = { [0] = "u8", [4] = "s16le" }
local WRITE = { u8 = { 0, "u8", 8 }, s16 = { 4, "s16le", 16 }, alaw = { 6, "alaw", 8 }, ulaw = { 7, "ulaw", 8 } }
local MAX_BLOCK = 0xFFFFFF - 12 -- payload bytes of one type 9 block (a 24-bit size, 12 header bytes)
local readu8 = buffer.readu8
local function u16(b: buffer, o: number): number
return readu8(b, o) + readu8(b, o + 1) * 256
end
local function u24(b: buffer, o: number): number
return readu8(b, o) + readu8(b, o + 1) * 256 + readu8(b, o + 2) * 65536
end
-- ------------------------------------------------------------------------------------------------ sniff
function Voc.sniff(r: Bytes.Reader): number
return if r:peek(20) == MAGIC then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
type Segment = { at: number, frames: number, fmt: string? } -- fmt nil: silence
function Voc.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
local b, base, limit = r.buf, r.base, r.limit
if limit - base < 26 or buffer.readstring(b, base, 20) ~= MAGIC then
return nil, Err.new(Err.CORRUPT, "bad magic", base)
end
local hsize = u16(b, base + 20)
local version = u16(b, base + 22)
if hsize < 26 or hsize > limit - base then
return nil, Err.new(Err.CORRUPT, "bad header size", base + 20)
end
local maxFrames = opts and opts.maxFrames or 2 ^ 28
local rate, channels = 0, 0
local extRate, extChannels = 0, 0 -- a type 8 block's settings for the next type 1 block
local lastFmt: string? = nil
local codec = -1
local segments: { Segment } = {}
local total = 0
local truncated = false
local tags: Types.Tags = {}
local p = base + hsize
-- add(at, bytes, fmt, ch, sr): a run of samples (or silence when fmt is nil and bytes = frames)
local function add(at: number, bytes: number, fmt: string?, ch: number, sr: number): Err.Err?
if channels == 0 then
channels, rate = ch, sr
elseif ch ~= channels then
return Err.new(Err.UNSUPPORTED, "the channel count changes mid-file", at)
end
local frames = if fmt then bytes // (ch * Pcm.Convert.SIZE[fmt]) else bytes
if frames > 0 then
total += frames
if total > maxFrames then
return Err.new(Err.LIMIT, string.format("over the %d frame limit", maxFrames))
end
table.insert(segments, { at = at, frames = frames, fmt = fmt })
end
return nil
end
while p < limit do
local t = readu8(b, p)
if t == 0 then
break
end
if p + 4 > limit then
truncated = true
break
end
local size = u24(b, p + 1)
local d = p + 4
local avail = math.min(size, limit - d)
if avail < size then
truncated = true
end
local err: Err.Err? = nil
if t == 1 then
if avail < 2 then
break
end
local div, c = readu8(b, d), readu8(b, d + 1)
local fmt = T1_CODECS[c]
if not fmt then
return nil, Err.new(Err.UNSUPPORTED, "Creative ADPCM (codec " .. c .. ")", d + 1)
end
local ch, sr = 1, 1000000 // (256 - div)
if extChannels > 0 then
ch, sr = extChannels, extRate
extChannels = 0
end
lastFmt, codec = fmt, c
err = add(d + 2, avail - 2, fmt, ch, sr)
elseif t == 2 then
if lastFmt == nil then
return nil, Err.new(Err.CORRUPT, "continuation block before any sound data", p)
end
err = add(d, avail, lastFmt, channels, rate)
elseif t == 3 then
if avail < 3 then
break
end
local len, div = u16(b, d) + 1, readu8(b, d + 2)
err = add(d, len, nil, if channels > 0 then channels else 1, if rate > 0 then rate else 1000000 // (256 - div))
elseif t == 5 then
local s = buffer.readstring(b, d, avail)
local z = string.find(s, "\0", 1, true)
if z then
s = string.sub(s, 1, z - 1)
end
tags.comment = if tags.comment then tags.comment .. "\n" .. s else s
elseif t == 8 then
if avail < 4 then
break
end
local tc, mode = u16(b, d), readu8(b, d + 3)
extChannels = mode + 1
extRate = 256000000 // (extChannels * (65536 - tc))
elseif t == 9 then
if avail < 12 then
break
end
local sr = readu8(b, d) + readu8(b, d + 1) * 256 + readu8(b, d + 2) * 65536 + readu8(b, d + 3) * 16777216
local ch, c = readu8(b, d + 5), u16(b, d + 6)
local fmt = T9_CODECS[c]
if not fmt then
return nil, Err.new(Err.UNSUPPORTED, "codec " .. c, d + 6)
end
if ch < 1 or sr < 1 then
return nil, Err.new(Err.CORRUPT, "bad channels or sample rate", d)
end
lastFmt, codec = fmt, c
err = add(d + 12, avail - 12, fmt, ch, sr)
end
if err then
return nil, err
end
p = d + size
end
if channels == 0 then
return nil, Err.new(if truncated then Err.TRUNCATED else Err.CORRUPT, "no sound data", p)
end
local a = Types.Audio.new(rate, channels, total)
local o = 0
for _, s in segments do
local n = s.frames * channels
if s.fmt then
Pcm.Convert.decode(b, s.at, s.fmt :: string, n, a.samples, o)
end -- silence: the buffer is already zero
o += n * 4
end
a.tags = tags
a.meta.source = {
format = "voc",
version = string.format("%d.%02d", version // 256, version % 256),
codec = codec,
sampleFormat = lastFmt,
bitDepth = if lastFmt == "s16le" then 16 else 8,
truncated = truncated or nil,
}
return a, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Voc.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local src, serr = Pcm.source(value)
if not src then
return nil, serr
end
local o: EncodeOptions = opts or {}
local spec = WRITE[o.sampleFormat or "s16"]
if not spec then
return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat))
end
if src.channels > 255 then
return nil, Err.new(Err.ARG, "at most 255 channels")
end
if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate >= 2 ^ 32 then
return nil, Err.new(Err.ARG, "the sample rate must be an integer")
end
local w = Bytes.writer(65536)
w:string(MAGIC)
w:u16le(26)
w:u16le(0x0114)
w:u16le((0xFFFF - 0x0114 + 0x1234 + 1) % 65536) -- ~version + 0x1234
if type(src.tags.comment) == "string" and #src.tags.comment > 0 then
local s = string.sub(src.tags.comment, 1, 0xFFFFFE)
w:u8(5)
w:u24le(#s + 1)
w:string(s)
w:u8(0)
end
local size = Pcm.Convert.SIZE[spec[2]]
local frameBytes = size * src.channels
local framesPerBlock = MAX_BLOCK // frameBytes
local blockAt, blockFrames = -1, 0
local tmp: buffer? = nil
while true do
local bf, n = src:read(math.min(8192, framesPerBlock), tmp)
if n <= 0 then
break
end
tmp = bf
local i = 0
while i < n do
if blockAt < 0 or blockFrames == framesPerBlock then
blockAt = w:tell()
blockFrames = 0
w:u8(9)
w:u24le(0) -- patched
w:u32le(src.sampleRate)
w:u8(spec[3])
w:u8(src.channels)
w:u16le(spec[1])
w:u32le(0)
end
local take = math.min(n - i, framesPerBlock - blockFrames)
local at = w:reserve(take * frameBytes)
Pcm.Convert.encode(bf, i * src.channels * 4, take * src.channels, spec[2], w.buf, at)
w.pos = at + take * frameBytes
blockFrames += take
i += take
local len = blockFrames * frameBytes + 12
w:setU8(blockAt + 1, len % 256)
w:setU8(blockAt + 2, (len // 256) % 256)
w:setU8(blockAt + 3, len // 65536)
end
end
if src.err then
return nil, src.err
end
w:u8(0) -- terminator
return w:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ open
function Voc.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
local a, err = Voc.decode(r, opts)
if not a then
return nil, err
end
local dec = Pcm.audioDecoder(a) :: any
dec.source = a.meta.source
return dec, nil
end
return Voc
+827
View File
@@ -0,0 +1,827 @@
--!strict
--!native
--!optimize 2
-- audio/vorbis/Encode: a basic but valid Vorbis I encoder in Ogg. New code written from the Vorbis I specification
-- (no libvorbis code). Design: long blocks only (2048 samples; blocksize 0 is declared as 256 but never used), the
-- Vorbis window, the MDCT (codecs/audio/Mdct, scale 4/N for the decoder's unscaled IMDCT); one floor 1 per channel with a
-- fixed post list of 30 points (bisection order, multiplier 2) fitted to the spectral envelope minus a quality-
-- dependent SNR, so the residue is quantized in steps of the floor; stereo square-polar coupling of the integer
-- residues (lossless); residue type 2 with 16-values-per-channel partitions and six classes (silent, |v| <= 1, 4, 15, then
-- cascades of x16 / x256 books for larger values); a fixed codebook set whose Huffman lengths come from Laplacian
-- models computed at load time (codewords assigned exactly as the spec's decoder does). Granules are sample-exact
-- (frames centred on multiples of 1024 from sample 0; the last page's granule trims the end). Never throws.
local Mdct = require("@rosetta/codecs/audio/Mdct")
local Pcm = require("@rosetta/codecs/audio/Pcm")
local VorbisComment = require("@rosetta/codecs/audio/VorbisComment")
local Ogg = require("@rosetta/containers/Ogg")
local Tables = require("@rosetta/codecs/audio/Vorbis/Tables")
local Encode = {}
local floor, log, exp, abs = math.floor, math.log, math.exp, math.abs
local writeu8 = buffer.writeu8
local POW = table.create(40, 0)
for i = 0, 39 do
POW[i + 1] = 2 ^ i
end
local N = 2048
local N2 = 1024
local PSIZE_PER_CHANNEL = 16 -- residue partitions hold 16 values per channel (libvorbis needs a multiple of ch)
local MULT = 2 -- floor1 multiplier (range 128)
local RANGE = 128
local NCLASS = 6
-- ------------------------------------------------------------------------------------------------ LSB-first bit writer
type W = { buf: buffer, pos: number, acc: number, cnt: number }
local function newW(size: number): W
return { buf = buffer.create(size), pos = 0, acc = 0, cnt = 0 }
end
local function put(w: W, v: number, n: number)
if n == 0 then
return
end
local acc = w.acc + v * POW[w.cnt + 1]
local cnt = w.cnt + n
local b, p = w.buf, w.pos
if p + 8 > buffer.len(b) then
local nb = buffer.create(buffer.len(b) * 2 + 64)
buffer.copy(nb, 0, b, 0, p)
b = nb
w.buf = nb
end
while cnt >= 8 do
local byte = acc % 256
writeu8(b, p, byte)
p += 1
acc = (acc - byte) / 256
cnt -= 8
end
w.acc, w.cnt, w.pos = acc, cnt, p
end
local function finish(w: W): buffer
if w.cnt > 0 then
put(w, 0, 8 - w.cnt)
end
local out = buffer.create(w.pos)
buffer.copy(out, 0, w.buf, 0, w.pos)
return out
end
local function putString(w: W, s: string)
for i = 1, #s do
put(w, string.byte(s, i), 8)
end
end
local function ilog(x: number): number
local n = 0
while x > 0 do
n += 1
x = floor(x / 2)
end
return n
end
-- ------------------------------------------------------------------------------------------------ codebooks
type Book = {
dims: number,
entries: number,
lengths: { number },
codes: { number }, -- bit-reversed codewords (ready for the LSB-first writer)
lookup: number, -- 0 or 1
minimum: number,
delta: number,
values: number, -- lookup1 values per dimension
}
-- Huffman code lengths for weights w[1..n] (all > 0), at most 24 bits long (weights are floored to keep it so)
local function huffmanLengths(w: { number }): { number }
local n = #w
local total = 0
for i = 1, n do
total += w[i]
end
local lens = table.create(n, 0)
if n == 1 then
lens[1] = 1
return lens
end
local minw = total * 2 ^ -20
-- nodes: leaves 1..n then internal; a simple O(n^2)-free approach with two sorted queues
local order = table.create(n, 0)
for i = 1, n do
order[i] = i
end
local weight = table.create(2 * n, 0)
local parent = table.create(2 * n, 0)
for i = 1, n do
weight[i] = math.max(w[i], minw)
end
table.sort(order, function(a: number, b: number): boolean
if weight[a] ~= weight[b] then
return weight[a] < weight[b]
end
return a < b
end)
local q1, h1 = order, 1 -- leaves, ascending
local q2, h2, t2 = table.create(n, 0), 1, 0 -- internal nodes, created in ascending weight order
local nextId = n
local function pop(): number
local a = if h1 <= n then q1[h1] else nil
local b = if h2 <= t2 then q2[h2] else nil
if a and (not b or weight[a] <= weight[b]) then
h1 += 1
return a
end
h2 += 1
return b :: number
end
for _ = 1, n - 1 do
local a = pop()
local b = pop()
nextId += 1
weight[nextId] = weight[a] + weight[b]
parent[a], parent[b] = nextId, nextId
t2 += 1
q2[t2] = nextId
end
for i = 1, n do
local d, x = 0, i
while parent[x] ~= 0 do
x = parent[x]
d += 1
end
lens[i] = d
end
return lens
end
-- the spec's codeword assignment (lowest free leaf, in entry order); returns bit-reversed codes
local function assign(lens: { number }): { number }
local codes = table.create(#lens, 0)
local available = table.create(33, 0)
local first = true
for i, len in lens do
if len > 0 then
local code
if first then
first = false
code = 0
for l = 1, len do
available[l + 1] = POW[33 - l] + 1
end
else
local z = len
while z > 0 and available[z + 1] == 0 do
z -= 1
end
code = available[z + 1] - 1
available[z + 1] = 0
for y = len, z + 1, -1 do
available[y + 1] = code + POW[33 - y] + 1
end
end
-- the top len bits of the 32-bit left-aligned code, MSB first, reversed for the LSB-first writer
local msb = floor(code / POW[33 - len])
local rev = 0
for _ = 1, len do
rev = rev * 2 + msb % 2
msb = floor(msb / 2)
end
codes[i] = rev
end
end
return codes
end
local function makeBook(dims: number, entries: number, weight: (number) -> number, lookup: number, minimum: number, delta: number, values: number): Book
local w = table.create(entries, 0)
for e = 0, entries - 1 do
w[e + 1] = weight(e)
end
local lens = huffmanLengths(w)
return { dims = dims, entries = entries, lengths = lens, codes = assign(lens), lookup = lookup, minimum = minimum, delta = delta, values = values }
end
-- a VQ book of `dims` dimensions over integer values -h .. h times `scale`, Laplacian weights exp(-|v| / s)
local function vqBook(dims: number, h: number, scale: number, s: number, zeroBoost: number): Book
local values = 2 * h + 1
local entries = values ^ dims
return makeBook(dims, entries, function(e: number): number
local wt = 1
local x = e
for _ = 1, dims do
local v = x % values - h
x = x // values
wt *= exp(-abs(v) / s) * (if v == 0 then zeroBoost else 1)
end
return wt
end, 1, -h * scale, scale, values)
end
local BOOK_FLOOR = makeBook(1, RANGE, function(e: number): number
return exp(-e / 7) + 0.002
end, 0, 0, 0, 0)
local CLASS_W = { 0.30, 0.30, 0.20, 0.12, 0.06, 0.02 }
local BOOK_CLASS = makeBook(2, NCLASS * NCLASS, function(e: number): number
return CLASS_W[e % NCLASS + 1] * CLASS_W[e // NCLASS + 1]
end, 0, 0, 0, 0)
local BOOK_A = vqBook(4, 1, 1, 0.6, 2.5) -- |v| <= 1, 4 at a time (mostly zeros)
local BOOK_B = vqBook(2, 4, 1, 1.4, 1) -- |v| <= 4
local BOOK_C = vqBook(2, 15, 1, 4, 1) -- |v| <= 15
local BOOK_D = vqBook(2, 15, 16, 3, 1) -- multiples of 16 up to 240
local BOOK_E = vqBook(2, 15, 256, 3, 1) -- multiples of 256 up to 3840
local BOOKS = { BOOK_FLOOR, BOOK_CLASS, BOOK_A, BOOK_B, BOOK_C, BOOK_D, BOOK_E }
local FLOOR_BOOK, CLASS_BOOK, A_BOOK, B_BOOK, C_BOOK, D_BOOK, E_BOOK = 0, 1, 2, 3, 4, 5, 6
-- the books of each residue class per pass (book numbers; -1 = none)
local CLASS_BOOKS = {
{ -1, -1, -1 },
{ A_BOOK, -1, -1 },
{ B_BOOK, -1, -1 },
{ C_BOOK, -1, -1 },
{ D_BOOK, C_BOOK, -1 },
{ E_BOOK, D_BOOK, C_BOOK },
}
local CLASS_MAX = { 0, 1, 4, 15, 255, 4095 }
-- float32_pack (spec 9.2.2) of an integer-valued x
local function float32Pack(x: number): number
local sign = if x < 0 then 2147483648 else 0
local m = abs(x)
local e = 788
while m >= 2097152 do
m /= 2
e += 1
end
return sign + e * 2097152 + floor(m)
end
local function writeBook(w: W, b: Book)
put(w, 0x564342, 24)
put(w, b.dims, 16)
put(w, b.entries, 24)
put(w, 0, 1) -- not ordered
put(w, 0, 1) -- not sparse
for i = 1, b.entries do
put(w, b.lengths[i] - 1, 5)
end
put(w, b.lookup, 4)
if b.lookup == 1 then
put(w, float32Pack(b.minimum), 32)
put(w, float32Pack(b.delta), 32)
local vb = ilog(b.values - 1)
put(w, vb - 1, 4)
put(w, 0, 1) -- sequence_p
for j = 0, b.values - 1 do
put(w, j, vb)
end
end
end
local function putEntry(w: W, b: Book, e: number)
put(w, b.codes[e + 1], b.lengths[e + 1])
end
-- ------------------------------------------------------------------------------------------------ floor posts
-- x positions: 0, 1024, then 28 log-spaced points in bisection order (coarse first) so predictions are good
local POSTS: { number } = { 0, N2 }
do
local xs = {}
local seen = { [0] = true, [N2] = true }
for j = 0, 27 do
local x = floor(3 + 957 * (j / 27) ^ 2.2 + 0.5) -- 3 .. 960, denser at low frequencies
while seen[x] do
x += 1
end
seen[x] = true
table.insert(xs, x)
end
table.sort(xs)
-- bisection order over the sorted list
local queue = { { 1, #xs } }
local qh = 1
while qh <= #queue do
local r = queue[qh]
qh += 1
if r[1] <= r[2] then
local m = (r[1] + r[2]) // 2
table.insert(POSTS, xs[m])
table.insert(queue, { r[1], m - 1 })
table.insert(queue, { m + 1, r[2] })
end
end
end
local NPOSTS = #POSTS -- 30
local FLOOR_PARTS = (NPOSTS - 2) // 4 -- 7 partitions of one class with 4 dimensions
local SORTED: { number } = table.create(NPOSTS, 0) -- post indices (1-based) by increasing x
for i = 1, NPOSTS do
SORTED[i] = i
end
table.sort(SORTED, function(a: number, b: number): boolean
return POSTS[a] < POSTS[b]
end)
local LOW, HIGH = table.create(NPOSTS, 0), table.create(NPOSTS, 0)
for j = 3, NPOSTS do
local lo, hi = -1, 65536
local x = POSTS[j]
for k = 1, j - 1 do
local xv = POSTS[k]
if xv > lo and xv < x then
LOW[j], lo = k, xv
end
if xv < hi and xv > x then
HIGH[j], hi = k, xv
end
end
end
-- the floor value (0..127) closest to an amplitude, through the spec's inverse dB table
local DB = table.create(RANGE, 0)
for y = 0, RANGE - 1 do
DB[y + 1] = 20 * math.log10(Tables[y * MULT + 1])
end
local function yOf(db: number): number
local y = floor((db - DB[1]) / (DB[RANGE] - DB[1]) * (RANGE - 1) + 0.5)
return math.clamp(y, 0, RANGE - 1)
end
local function predict(x: number, x0: number, x1: number, y0: number, y1: number): number
local dy = y1 - y0
local adx = x1 - x0
local off = (abs(dy) * (x - x0)) // adx
return if dy < 0 then y0 - off else y0 + off
end
-- render the decoder's floor curve for final Y values into F[1..N2] (only the posts the decoder marks used)
local function renderFloor(Y: { number }, used: { boolean }, F: { number })
local lx, ly = 0, Y[1] * MULT
for q = 2, NPOSTS do
local j = SORTED[q]
if not used[j] then
continue
end
local hx, hy = POSTS[j], Y[j] * MULT
-- draw_line(lx, ly, hx, hy)
local dy = hy - ly
local adx = hx - lx
local ady = abs(dy)
local base = if dy < 0 then -(ady // adx) else ady // adx
local sy = if dy < 0 then base - 1 else base + 1
ady -= abs(base) * adx
local x, y, err = lx, ly, 0
local x1 = math.min(hx, N2)
if x < x1 then
F[x + 1] = Tables[y % 256 + 1]
x += 1
while x < x1 do
err += ady
if err >= adx then
err -= adx
y += sy
else
y += base
end
F[x + 1] = Tables[y % 256 + 1]
x += 1
end
end
lx, ly = hx, hy
end
for x = lx + 1, N2 do
F[x] = Tables[ly % 256 + 1]
end
end
-- the coded value for target t at post j given the final values of its neighbours (spec 7.2.4 step 1, inverted)
local function floorVal(Y: { number }, j: number): number
local lo, hi = LOW[j], HIGH[j]
local pred = predict(POSTS[j], POSTS[lo], POSTS[hi], Y[lo], Y[hi])
local t = Y[j]
local d = t - pred
if d == 0 then
return 0
end
local highroom = RANGE - pred
local lowroom = pred
local room = if highroom < lowroom then highroom * 2 else lowroom * 2
local cands = { if d > 0 then 2 * d else -2 * d - 1, d + lowroom, -d + highroom - 1 }
for _, v in cands do
if v > 0 and v < RANGE then
local got
if v >= room then
got = if highroom > lowroom then v - lowroom + pred else pred - v + highroom - 1
elseif v % 2 == 1 then
got = pred - (v + 1) // 2
else
got = pred + v // 2
end
if got == t then
return v
end
end
end
return 0 -- unreachable for t in range; fall back to the prediction
end
-- ------------------------------------------------------------------------------------------------ headers
local function identHeader(ch: number, rate: number, nominal: number): buffer
local w = newW(64)
put(w, 1, 8)
putString(w, "vorbis")
put(w, 0, 32)
put(w, ch, 8)
put(w, rate, 32)
put(w, 0, 32)
put(w, nominal, 32)
put(w, 0, 32)
put(w, 8, 4) -- blocksize 0: 256
put(w, 11, 4) -- blocksize 1: 2048
put(w, 1, 1)
return finish(w)
end
local function commentHeader(vendor: string, tags: { [string]: string }): buffer
local w = newW(256)
put(w, 3, 8)
putString(w, "vorbis")
put(w, #vendor, 32)
putString(w, vendor)
local fields = VorbisComment.fields(tags)
put(w, #fields, 32)
for _, s in fields do
put(w, #s, 32)
putString(w, s)
end
put(w, 1, 1)
return finish(w)
end
local function setupHeader(ch: number): buffer
local w = newW(8192)
put(w, 5, 8)
putString(w, "vorbis")
-- codebooks
put(w, #BOOKS - 1, 8)
for _, b in BOOKS do
writeBook(w, b)
end
-- time domain placeholders
put(w, 0, 6)
put(w, 0, 16)
-- one floor 1
put(w, 0, 6)
put(w, 1, 16)
put(w, FLOOR_PARTS, 5)
for _ = 1, FLOOR_PARTS do
put(w, 0, 4) -- class 0
end
put(w, 3, 3) -- class 0: 4 dimensions
put(w, 0, 2) -- no subclasses
put(w, FLOOR_BOOK + 1, 8) -- its one subclass book (+1)
put(w, MULT - 1, 2)
put(w, 10, 4) -- rangebits: x in 0 .. 1024
for j = 3, NPOSTS do
put(w, POSTS[j], 10)
end
-- one residue 2
put(w, 0, 6)
put(w, 2, 16)
put(w, 0, 24) -- begin
put(w, N2 * ch, 24) -- end
put(w, PSIZE_PER_CHANNEL * ch - 1, 24)
put(w, NCLASS - 1, 6)
put(w, CLASS_BOOK, 8)
for c = 1, NCLASS do
local bits = 0
for pass = 1, 3 do
if CLASS_BOOKS[c][pass] >= 0 then
bits += POW[pass]
end
end
put(w, bits % 8, 3)
if bits >= 8 then
put(w, 1, 1)
put(w, bits // 8, 5)
else
put(w, 0, 1)
end
end
for c = 1, NCLASS do
for pass = 1, 3 do
local b = CLASS_BOOKS[c][pass]
if b >= 0 then
put(w, b, 8)
end
end
end
-- one mapping
put(w, 0, 6)
put(w, 0, 16)
put(w, 0, 1) -- one submap
if ch == 2 then
put(w, 1, 1)
put(w, 0, 8) -- one coupling step
put(w, 0, 1) -- magnitude: channel 0
put(w, 1, 1) -- angle: channel 1
else
put(w, 0, 1)
end
put(w, 0, 2)
put(w, 0, 8) -- submap 0: time (unused)
put(w, 0, 8) -- floor 0
put(w, 0, 8) -- residue 0
-- one mode: long blocks
put(w, 0, 6)
put(w, 1, 1)
put(w, 0, 16)
put(w, 0, 16)
put(w, 0, 8)
put(w, 1, 1) -- framing
return finish(w)
end
-- ------------------------------------------------------------------------------------------------ encoder
export type Source = {
sampleRate: number,
channels: number,
frames: number,
tags: { [string]: string },
read: (self: any, n: number, out: buffer?) -> (buffer, number),
err: any,
}
export type Options = {
quality: number, -- -1 .. 10
vendor: string,
serial: number,
}
-- the residue of one partition: vectors of each pass for class c
local function writePartition(w: W, v: { number }, o: number, psize: number, c: number, pass: number)
local b = CLASS_BOOKS[c][pass]
if b < 0 then
return
end
local book = BOOKS[b + 1]
local dims, h = book.dims, (book.values - 1) // 2
local scale = book.delta
local values = book.values
local i = 0
while i < psize do
local e = 0
local m = 1
for k = 0, dims - 1 do
local x = v[o + i + k + 1]
-- the part of x this pass carries (coarse passes take the rounded multiple of their scale)
local q
if pass < 3 and CLASS_BOOKS[c][pass + 1] >= 0 then
q = math.clamp(floor(x / scale + 0.5), -h, h)
else
q = math.clamp(x // scale, -h, h)
end
v[o + i + k + 1] = x - q * scale
e += (q + h) * m
m *= values
end
putEntry(w, book, e)
i += dims
end
end
function Encode.encode(src: Source, opts: Options): (buffer?, string?)
local ch, rate = src.channels, src.sampleRate
local q = math.clamp(opts.quality, -1, 10)
local snrDb = 2 * q - 1 -- floor level below the band energy (at low frequencies; 8 dB less at the top)
local mux = Ogg.muxer({ pageSize = 4096 })
local stream = mux:stream(opts.serial)
local nominal = floor(math.clamp(rate * ch * (0.6 + 0.12 * q), 32000, 500000))
stream:packet(identHeader(ch, rate, nominal), 0, { flush = true })
stream:packet(commentHeader(opts.vendor, src.tags), 0)
stream:packet(setupHeader(ch), 0, { flush = true })
local plan = Mdct.new(N) :: Mdct.Plan
local win = Mdct.window("vorbis", N) :: { number }
-- input ring: per channel the samples of the current frame [k*1024 - 1024, k*1024 + 1024)
local frame: { { number } } = table.create(ch) :: any
for c = 1, ch do
frame[c] = table.create(N, 0)
end
-- the input is in WAVE channel order; input channel c goes to Vorbis channel order[c]
local order = Pcm.WAVE_FROM_VORBIS[ch] or {}
if #order ~= ch then
order = table.create(ch, 0)
for c = 1, ch do
order[c] = c
end
end
local blk = table.create(N, 0)
local X: { { number } } = table.create(ch) :: any
local R: { { number } } = table.create(ch) :: any
for c = 1, ch do
X[c] = table.create(N2, 0)
R[c] = table.create(N2, 0)
end
local F = table.create(N2, 0)
local Y = table.create(NPOSTS, 0)
local vals = table.create(NPOSTS, 0)
local used = table.create(NPOSTS, false)
local inter = table.create(N2 * ch, 0)
local psize = PSIZE_PER_CHANNEL * ch
local npart = N2 * ch // psize
local classes = table.create(npart + 2, 0)
local total = 0
local srcDone = false
local tmp: buffer? = nil
local pending: buffer? = nil
local pendN, pendOff = 0, 0
local k = 0
local lastWanted = -1 -- the last packet index needed (known once the input ends)
while true do
-- shift in the next 1024 input samples (zeros past the end)
for c = 1, ch do
local fr = frame[c]
table.move(fr, N2 + 1, N, 1)
end
local got = 0
while got < N2 and not srcDone do
if pendN == 0 then
local b, n = src:read(4096, tmp)
if n <= 0 then
srcDone = true
break
end
tmp = b
pending, pendN, pendOff = b, n, 0
end
local take = math.min(N2 - got, pendN)
local pb = pending :: buffer
for i = 0, take - 1 do
local base = (pendOff + i) * ch * 4
for c = 1, ch do
frame[order[c]][N2 + got + i + 1] = buffer.readf32(pb, base + (c - 1) * 4)
end
end
got += take
pendN -= take
pendOff += take
end
for c = 1, ch do
local fr = frame[c]
for i = N2 + got + 1, N do
fr[i] = 0
end
end
total += got
if srcDone and lastWanted < 0 then
lastWanted = (total + N2 - 1) // N2 -- packets 0 .. lastWanted (packet j returns [(j-1)*1024, j*1024))
end
-- this frame is centred on k*1024; its first half is [k*1024 - 1024, k*1024)
-- (frame k holds input [(k - 1) * 1024, (k + 1) * 1024): the shift above moved the window by 1024)
-- MDCT per channel
local energy = 0
for c = 1, ch do
local fr = frame[c]
for i = 1, N do
blk[i] = fr[i] * win[i]
end
Mdct.forward(plan, blk, 1, X[c], 1, 1, 4 / N)
local xc = X[c]
for i = 1, N2 do
energy += xc[i] * xc[i]
end
end
local w = newW(2048)
put(w, 0, 1) -- audio packet
-- (one mode: 0 bits) long block, previous and next long
put(w, 1, 1)
put(w, 1, 1)
local silent = energy < 1e-18
if silent then
for _ = 1, ch do
put(w, 0, 1) -- no floor: the channel is zero
end
else
-- the floor from the loudest channel's band energies at each post
for j = 1, NPOSTS do
local x = POSTS[j]
-- the band around x: halfway to the neighbouring posts in x order
local idx = table.find(SORTED, j) :: number
local lo = if idx > 1 then (POSTS[SORTED[idx - 1]] + x) // 2 else 0
local hi = if idx < NPOSTS then (POSTS[SORTED[idx + 1]] + x) // 2 else N2 - 1
if hi < lo then
hi = lo
end
local e = 0
for c = 1, ch do
local xc = X[c]
local s = 0
for i = lo + 1, math.min(hi + 1, N2) do
s += xc[i] * xc[i]
end
s /= (hi - lo + 1)
if s > e then
e = s
end
end
local db = if e > 0 then 10 * math.log10(e) - snrDb + 8 * x / N2 else -200
Y[j] = yOf(db)
end
-- the decoder's step 2 flags: a point is drawn when its value or a later neighbour's value is nonzero
used[1], used[2] = true, true
for j = 3, NPOSTS do
local v = floorVal(Y, j)
vals[j] = v
used[j] = v ~= 0
if v ~= 0 then
used[LOW[j]], used[HIGH[j]] = true, true
end
end
renderFloor(Y, used, F)
-- residues: X / F rounded, then coupling, then interleaving
for c = 1, ch do
local xc, rc = X[c], R[c]
for i = 1, N2 do
local v = floor(xc[i] / F[i] + 0.5)
rc[i] = math.clamp(v, -4095, 4095)
end
end
if ch == 2 then
local l, r = R[1], R[2]
for i = 1, N2 do
local a, b = l[i], r[i]
local m, an
if abs(a) > abs(b) then
m = a
an = if a > 0 then a - b else b - a
else
m = b
an = if b > 0 then a - b else b - a
end
-- keep the angle inside the books' range
l[i], r[i] = m, math.clamp(an, -4095, 4095)
end
end
for c = 1, ch do
local rc = R[c]
for i = 1, N2 do
inter[(i - 1) * ch + c] = rc[i]
end
end
-- floors
for _ = 1, ch do
put(w, 1, 1)
put(w, Y[1], 7)
put(w, Y[2], 7)
for j = 3, NPOSTS do
putEntry(w, BOOK_FLOOR, vals[j])
end
end
-- residue classes
for p = 0, npart - 1 do
local m = 0
for i = 1, psize do
local a = abs(inter[p * psize + i])
if a > m then
m = a
end
end
local c = 1
while CLASS_MAX[c] < m do
c += 1
end
classes[p + 1] = c
end
classes[npart + 1] = 1
for pass = 1, 3 do
for p = 0, npart - 1, 2 do
if pass == 1 then
putEntry(w, BOOK_CLASS, (classes[p + 1] - 1) * NCLASS + (classes[p + 2] - 1)) -- first partition: the high digit
end
writePartition(w, inter, p * psize, psize, classes[p + 1], pass)
if p + 1 < npart then
writePartition(w, inter, (p + 1) * psize, psize, classes[p + 2], pass)
end
end
end
end
local pk = finish(w)
local last = lastWanted >= 0 and k >= lastWanted
local granule = if k == 0 then 0 else math.min(k * N2, if lastWanted >= 0 then total else math.huge)
stream:packet(pk, granule, if last then { eos = true } else nil)
if last then
break
end
k += 1
end
if src.err then
return nil, tostring(src.err)
end
return mux:finish(), nil
end
-- the codebooks (tests check the Huffman lengths are a valid prefix code)
Encode.BOOKS = BOOKS
return Encode
+470
View File
@@ -0,0 +1,470 @@
--!strict
-- audio/vorbis: Ogg Vorbis (Vorbis I specification, Xiph.Org; RFC 5215 for the Ogg mapping). The decoder is a Luau
-- port of stb_vorbis 1.22 (public domain / MIT, licenses/stb_vorbis-LICENSE.txt) on containers/Ogg and codecs/audio/Mdct,
-- with libvorbis' sample-exact timing: start trimming from the first page's granule, end trimming from the last
-- page's, granule-exact seeking (bisection, then decoding forward to a page boundary to recover the position).
-- Supports: decode / open of any channel count (1..255), rates, block sizes 64..8192, floor 1, residues 0 / 1 / 2,
-- coupling, sparse / ordered codebooks, lookup types 1 / 2; comment-header tags (lower-cased keys); a packet-level
-- decoder (Vorbis.packetDecoder) for Vorbis in Matroska / WebM / MP4. Encode (audio/vorbis/Encode, new code): a basic
-- Ogg Vorbis encoder from an Audio or a streamed Decoder (long blocks, floor 1, coupled residue 2, a fixed codebook
-- set, quality -1 .. 10). Not supported: floor 0 (Err.UNSUPPORTED, as in stb_vorbis; no encoder has produced it since
-- 2000), chained streams (the first logical Vorbis stream is decoded), short blocks in the encoder.
-- The codec itself is codecs/audio/Vorbis; this folder maps it onto the file (container, tags, seeking, writing).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Ogg = require("@rosetta/containers/Ogg")
local Setup = require("@rosetta/codecs/audio/Vorbis/Setup")
local Packet = require("@rosetta/codecs/audio/Vorbis/Packet")
local Encode = require("@rosetta/audio/vorbis/Encode")
local Pcm = require("@rosetta/codecs/audio/Pcm")
local VorbisComment = require("@rosetta/codecs/audio/VorbisComment")
-- ------------------------------------------------------------------------------------------------ contract
local Vorbis = {
name = "vorbis",
category = "audio",
extensions = { "ogg", "oga" },
mime = { "audio/ogg", "audio/vorbis" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/audio/Mdct", "codecs/audio/Pcm", "codecs/audio/VorbisComment", "codecs/audio/Vorbis/Tables", "codecs/audio/Vorbis/Setup", "codecs/audio/Vorbis/Packet" },
caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255 },
}
export type OpenOptions = {
verify: boolean?, -- check the Ogg page CRCs (default true)
}
export type EncodeOptions = {
quality: number?, -- -1 .. 10 (default 3): the floor sits 2 * quality - 1 dB under the band energies (8 dB
-- less at the top of the spectrum), which sets the residue's quantization step
serial: number?, -- the Ogg stream serial number (default 0x464C5541)
}
-- ------------------------------------------------------------------------------------------------ constants
-- waveOrder(channels) -> output channel c is Vorbis channel order[c] (codecs/audio/Pcm; identity past 8 channels)
local function waveOrder(ch: number): { number }
local m = Pcm.WAVE_FROM_VORBIS[ch]
if m then
return m
end
local id = table.create(ch, 0)
for c = 1, ch do
id[c] = c
end
return id
end
-- the three headers -> ident, setup, vendor, tags, raw comment fields | nil, Err
local function headers(h1: any, h2: any, h3: any): (any, any, string?, Types.Tags?, { VorbisComment.Field }?, Err.Err?)
local id, ierr = Setup.ident(h1.data, h1.offset, h1.size)
if not id then
return nil, nil, nil, nil, nil, Err.new(Err.CORRUPT, ierr or "bad identification header")
end
local vendor, comments = Setup.comment(h2.data, h2.offset, h2.size)
if not vendor then
return nil, nil, nil, nil, nil, Err.new(Err.CORRUPT, "bad comment header")
end
local setup, serr = Setup.setup(h3.data, h3.offset, h3.size, id)
if not setup then
local code = if serr == "floor 0" then Err.UNSUPPORTED else Err.CORRUPT
return nil, nil, nil, nil, nil, Err.new(code, serr or "bad setup header")
end
local tags, raw = VorbisComment.tags(comments or {})
return id, setup, vendor, tags, raw, nil
end
-- ------------------------------------------------------------------------------------------------ sniff
function Vorbis.sniff(r: Bytes.Reader): number
if r:remaining() < 35 or r:peek(4) ~= "OggS" then
return 0
end
local b, p = r.buf, r.pos
local nseg = buffer.readu8(b, p + 26)
local d = p + 27 + nseg
if d + 7 > r.limit then
return 0
end
return if buffer.readu8(b, d) == 1 and buffer.readstring(b, d + 1, 6) == "vorbis" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Vorbis.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?)
local dec, err = Vorbis.open(r, opts)
if not dec then
return nil, err
end
return Pcm.drain(dec)
end
-- ------------------------------------------------------------------------------------------------ encode
-- encode(audioOrDecoder, opts?) -> an Ogg Vorbis file | nil, Err
function Vorbis.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local src, serr = Pcm.source(value)
if not src then
return nil, serr
end
local o: EncodeOptions = opts or {}
local q = o.quality or 3
if type(q) ~= "number" or q ~= q or q < -1 or q > 10 then
return nil, Err.new(Err.ARG, "quality must be -1 .. 10")
end
if src.channels > 255 then
return nil, Err.new(Err.ARG, "at most 255 channels")
end
if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate < 1 or src.sampleRate >= 2 ^ 32 then
return nil, Err.new(Err.ARG, "the sample rate must be a positive integer")
end
local serial = o.serial or 0x464C5541
if type(serial) ~= "number" or serial ~= math.floor(serial) or serial < 0 or serial >= 2 ^ 32 then
return nil, Err.new(Err.ARG, "serial must be a 32-bit unsigned integer")
end
local out, msg = Encode.encode(src :: any, { quality = q, vendor = "rosetta Vorbis encoder", serial = serial })
if not out then
return nil, Err.new(Err.CORRUPT, tostring(msg))
end
return out, nil
end
-- ------------------------------------------------------------------------------------------------ open
local Stream = {}
Stream.__index = Stream
-- queue the chunk arrays[first .. first + count - 1] whose first sample has granule g0, trimmed to [lo, hi)
local function push(self: any, arrays: { { number } }, g0: number, count: number, hi: number)
local lo = math.max(g0, self.startG, self.skipTo)
if hi > g0 + count then
hi = g0 + count
end
if hi > lo then
table.insert(self.queue, { arrays, lo - g0 + 1, hi - g0, lo })
end
end
local function copyOut(self: any, count: number): { { number } }
local t = table.create(self.channels)
for c = 1, self.channels do
local src = self.st.out[c]
local a = table.create(count, 0)
table.move(src, 1, count, 1, a)
t[c] = a
end
return t
end
-- decode packets until something is queued; false at the end of the stream
local function decodeMore(self: any): boolean
local reader, st = self.reader, self.st
while not self.ended do
local p = reader:nextPacket()
if p == nil then
self.ended = true
break
end
if p.gap then
Packet.reset(st)
self.syncing, self.pend, self.pendCount = true, {}, 0
end
local count = Packet.decode(st, p.data, p.offset, p.size)
if count >= 0 then
local endG = if p.eos and p.granule >= 0 then p.granule else math.huge
if self.syncing then
if count > 0 then
table.insert(self.pend, { copyOut(self, count), count })
self.pendCount += count
end
if p.granule >= 0 then
-- the position is known again: this packet's output ends at its granule
local g = p.granule - self.pendCount
if p.eos and self.pendCount > 0 then
g = math.max(g, self.pos) -- an end-trimmed last page: keep the running position
end
for _, c in self.pend do
push(self, c[1], g, c[2], endG)
g += c[2]
end
self.pos = g
self.syncing, self.pend, self.pendCount = false, {}, 0
end
else
local g0 = self.pos
self.pos += count
if count > 0 then
push(self, st.out, g0, count, endG)
end
if p.granule >= 0 and not p.eos then
self.pos = p.granule
end
end
if p.eos then
self.ended = true
end
if #self.queue > 0 then
return true
end
end
end
return #self.queue > 0
end
function Stream.read(self: any, n: number, out: buffer?): (buffer, number)
local ch = self.channels
n = math.max(0, math.floor(n))
local b = if out and buffer.len(out) >= n * ch * 4 then out else buffer.create(n * ch * 4)
local got = 0
local writef32 = buffer.writef32
while got < n do
local q = self.queue[1]
if q == nil then
if not decodeMore(self) then
break
end
q = self.queue[1]
end
local arrays, first, last = q[1], q[2], q[3]
local take = math.min(n - got, last - first + 1)
local order = self.order
for c = 1, ch do
local a = arrays[order[c]]
local o = got * ch * 4 + (c - 1) * 4
for i = first, first + take - 1 do
writef32(b, o, a[i])
o += ch * 4
end
end
got += take
self.next = q[4] + take
if first + take > last then
table.remove(self.queue, 1)
else
q[2] = first + take
q[4] += take
end
end
if got > 0 then
self.skipTo = -math.huge
end
return b, got
end
function Stream.position(self: any): number
return (self.next - self.startG) / self.sampleRate
end
-- back to the first audio packet
local function restart(self: any)
local r = self.reader
r:rewind()
for _ = 1, 3 do
r:nextPacket()
end
Packet.reset(self.st)
self.pos = self.base
self.syncing, self.pend, self.pendCount = false, {}, 0
self.ended = false
self.queue = {}
end
function Stream.seek(self: any, seconds: number)
local target = self.startG + math.floor(math.max(0, seconds) * self.sampleRate + 0.5)
if target ~= target then
target = self.startG
end
if self.lastG >= 0 and target > self.lastG then
target = self.lastG
end
self.skipTo = target
self.next = target
local r = self.reader
local g = target - self.st.n1
for _ = 1, 16 do
if g <= self.startG then
break
end
local G = r:seekGranule(g)
if G == nil or G < 0 then
break
end
-- decode forward to the next page boundary to learn the exact position
Packet.reset(self.st)
self.queue = {}
self.ended = false
self.syncing, self.pend, self.pendCount = true, {}, 0
self.pos = G
local ok = false
while true do
local p = r:nextPacket()
if p == nil then
break
end
local count = Packet.decode(self.st, p.data, p.offset, p.size)
if count > 0 then
table.insert(self.pend, { copyOut(self, count), count })
self.pendCount += count
end
if p.granule >= 0 then
if not p.eos then
local g0 = p.granule - self.pendCount
for _, c in self.pend do
push(self, c[1], g0, c[2], math.huge)
g0 += c[2]
end
self.pos = p.granule
self.syncing, self.pend, self.pendCount = false, {}, 0
ok = true
end
break
end
end
if ok then
return
end
g = G - 1 -- the last page: start one page earlier
end
restart(self)
self.skipTo = target
self.next = target
end
function Vorbis.open(r: any, opts: OpenOptions?): (Types.Decoder?, Err.Err?)
local demux, derr = Ogg.open(r, if opts and opts.verify == false then { verify = false } else nil)
if not demux then
return nil, derr
end
local serial = demux:find("vorbis")
if serial == nil then
return nil, Err.new(Err.CORRUPT, "no Vorbis stream in the Ogg file")
end
local reader = demux:reader(serial)
local h1 = reader:nextPacket()
if h1 == nil then
return nil, Err.new(Err.TRUNCATED, "missing identification header")
end
local id0, ierr = Setup.ident(h1.data, h1.offset, h1.size)
if not id0 then
return nil, Err.new(Err.CORRUPT, ierr or "bad identification header")
end
local h2 = reader:nextPacket()
if h2 == nil then
return nil, Err.new(Err.TRUNCATED, "missing comment header")
end
local h2copy = { data = Ogg.copy(h2), offset = 0, size = h2.size }
local h3 = reader:nextPacket()
if h3 == nil then
return nil, Err.new(Err.TRUNCATED, "missing setup header")
end
local id, setup, vendor, tags, raw, herr = headers(h1, h2copy, h3)
if not id then
return nil, herr
end
local st = Packet.new(id, setup)
if not st then
return nil, Err.new(Err.CORRUPT, "bad block sizes")
end
-- the granule of the first returned sample: the first granule page minus what its packets return
local base = 0
do
local prev, sum = 0, 0
while true do
local p = reader:nextPacket()
if p == nil then
break
end
local bs = Packet.blocksize(st, p.data, p.offset, p.size)
if bs > 0 then
if prev > 0 then
sum += prev // 4 + bs // 4
end
prev = bs
end
if p.granule >= 0 then
base = p.granule - sum
if p.eos then
base = 0 -- one page holds the whole stream: the spec trims its end, not its start
end
break
end
end
end
local info = demux:stream(serial)
local lastG = if info and info.lastGranule and info.lastGranule >= 0 then info.lastGranule else -1
local startG = math.max(base, 0)
local frames = if lastG >= 0 then math.max(0, lastG - startG) else 0
local rate = id.sampleRate
local self = setmetatable({
sampleRate = rate,
channels = id.channels,
frames = frames,
duration = frames / rate,
bitrate = if frames > 0 then math.floor(demux.size * 8 / (frames / rate)) else id.bitrateNominal,
tags = tags,
vendor = vendor,
ident = id,
-- WAVE channel order out (codecs/audio/Pcm): output channel c is Vorbis channel order[c]
order = waveOrder(id.channels),
source = {
format = "vorbis",
codec = "vorbis",
vendor = vendor,
comments = raw,
blocksizes = { id.blocksize0, id.blocksize1 },
nominalBitrate = id.bitrateNominal,
},
demux = demux,
reader = reader,
st = st,
base = base,
startG = startG,
lastG = lastG,
pos = base,
next = startG,
skipTo = -math.huge,
queue = {},
syncing = false,
pend = {},
pendCount = 0,
ended = false,
}, Stream)
restart(self)
return self :: any, nil
end
-- ------------------------------------------------------------------------------------------------ extras
-- packetDecoder(ident, comment, setup) -> a decoder of raw Vorbis packets (Matroska / WebM / MP4 carry the three
-- headers in their codec private data) | nil, Err. Each argument is a buffer holding one header packet.
-- local pd = Vorbis.packetDecoder(h1, h2, h3)
-- local n = pd:decode(buf, offset, size) -- frames returned (first packet 0; -1 = not audio); pd.out[ch][1 .. n]
-- pd:reset() -- after a seek
function Vorbis.packetDecoder(h1: buffer, h2: buffer, h3: buffer): (any, Err.Err?)
local function pk(b: buffer): any
return { data = b, offset = 0, size = buffer.len(b) }
end
local id, setup, vendor, tags, _, err = headers(pk(h1), pk(h2), pk(h3))
if not id then
return nil, err
end
local st = Packet.new(id, setup)
if not st then
return nil, Err.new(Err.CORRUPT, "bad block sizes")
end
return {
sampleRate = id.sampleRate,
channels = id.channels,
vendor = vendor,
tags = tags,
out = st.out, -- per Vorbis channel; WAVE-order channel c is out[order[c]]
order = waveOrder(id.channels),
decode = function(_self: any, b: buffer, offset: number, size: number): number
if offset < 0 or size < 0 or offset + size > buffer.len(b) then
return -1
end
return Packet.decode(st, b, offset, size)
end,
reset = function(_self: any)
Packet.reset(st)
end,
},
nil
end
return Vorbis
+173
View File
@@ -0,0 +1,173 @@
--!strict
--!native
--!optimize 2
-- audio/wav/Codecs: sample conversion loops (native) into interleaved f32, and back (the encoder's quantizers). The
-- ADPCM block decoders moved to codecs/audio/Adpcm.
-- Absorbed from wav-luau fd9a909 (same author); the encoder loops are new. They never throw: audio/wav (init.luau)
-- only calls them with ranges it has checked against the source length and the output size.
local readu8, readi8, readu16, readi16, readu32, readi32 =
buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32
local readf32, readf64, writef32, writeu32 = buffer.readf32, buffer.readf64, buffer.writef32, buffer.writeu32
local band, rshift, byteswap = bit32.band, bit32.rshift, bit32.byteswap
local writeu8, writeu16, writei16, writei32 = buffer.writeu8, buffer.writeu16, buffer.writei16, buffer.writei32
local Codecs = {}
-- Integer PCM: count samples of `bytes` bytes each (1 = unsigned 8-bit, 2 / 3 / 4 = signed), little- or big-endian,
-- from src[off] to dst (f32) starting at sample index d.
function Codecs.int(src: buffer, off: number, dst: buffer, d: number, count: number, bytes: number, be: boolean)
local o = d * 4
if bytes == 1 then
for i = 0, count - 1 do
writef32(dst, o + i * 4, (readu8(src, off + i) - 128) / 128)
end
elseif bytes == 2 then
if be then
for i = 0, count - 1 do
local s = off + i * 2
local v = readi8(src, s) * 256 + readu8(src, s + 1)
writef32(dst, o + i * 4, v / 32768)
end
else
for i = 0, count - 1 do
writef32(dst, o + i * 4, readi16(src, off + i * 2) / 32768)
end
end
elseif bytes == 3 then
if be then
for i = 0, count - 1 do
local s = off + i * 3
local v = readi8(src, s) * 65536 + readu8(src, s + 1) * 256 + readu8(src, s + 2)
writef32(dst, o + i * 4, v / 8388608)
end
else
for i = 0, count - 1 do
local s = off + i * 3
local v = readi8(src, s + 2) * 65536 + readu16(src, s)
writef32(dst, o + i * 4, v / 8388608)
end
end
else
if be then
for i = 0, count - 1 do
local v = byteswap(readu32(src, off + i * 4))
if v >= 0x80000000 then
v -= 0x100000000
end
writef32(dst, o + i * 4, v / 2147483648)
end
else
for i = 0, count - 1 do
writef32(dst, o + i * 4, readi32(src, off + i * 4) / 2147483648)
end
end
end
end
-- IEEE float, 4 or 8 bytes. tmp: an 8-byte scratch buffer for byte-swapping big-endian values.
function Codecs.float(src: buffer, off: number, dst: buffer, d: number, count: number, bytes: number, be: boolean,
tmp: buffer)
local o = d * 4
if bytes == 4 then
if be then
for i = 0, count - 1 do
writeu32(tmp, 0, byteswap(readu32(src, off + i * 4)))
writef32(dst, o + i * 4, readf32(tmp, 0))
end
else
for i = 0, count - 1 do
writef32(dst, o + i * 4, readf32(src, off + i * 4))
end
end
else
if be then
for i = 0, count - 1 do
local s = off + i * 8
writeu32(tmp, 0, byteswap(readu32(src, s + 4)))
writeu32(tmp, 4, byteswap(readu32(src, s)))
writef32(dst, o + i * 4, readf64(tmp, 0))
end
else
for i = 0, count - 1 do
writef32(dst, o + i * 4, readf64(src, off + i * 8))
end
end
end
end
-- 8-bit companded (A-law / mu-law) through a 256-entry f32 table
function Codecs.law(src: buffer, off: number, dst: buffer, d: number, count: number, tbl: buffer)
local o = d * 4
for i = 0, count - 1 do
writef32(dst, o + i * 4, readf32(tbl, readu8(src, off + i) * 4))
end
end
-- copy frames from a block cache into the output: count f32 values
function Codecs.copy(src: buffer, sOff: number, dst: buffer, dOff: number, count: number)
buffer.copy(dst, dOff * 4, src, sOff * 4, count * 4)
end
-- Encoder: count f32 samples from src (sample index s) to dst[off] as `kind` ("u8", "s16", "s24", "s32", "f32"),
-- little-endian, rounding to nearest and clamping to the integer range. Ranges are checked by the caller.
function Codecs.quantize(src: buffer, s: number, dst: buffer, off: number, count: number, kind: string)
local so = s * 4
if kind == "f32" then
buffer.copy(dst, off, src, so, count * 4)
elseif kind == "s16" then
for i = 0, count - 1 do
local v = math.floor(readf32(src, so + i * 4) * 32768 + 0.5)
if v > 32767 then
v = 32767
elseif v < -32768 then
v = -32768
elseif v ~= v then
v = 0
end
writei16(dst, off + i * 2, v)
end
elseif kind == "s24" then
for i = 0, count - 1 do
local v = math.floor(readf32(src, so + i * 4) * 8388608 + 0.5)
if v > 8388607 then
v = 8388607
elseif v < -8388608 then
v = -8388608
elseif v ~= v then
v = 0
end
if v < 0 then
v += 16777216
end
local o = off + i * 3
writeu16(dst, o, v % 65536)
writeu8(dst, o + 2, v // 65536)
end
elseif kind == "s32" then
for i = 0, count - 1 do
local v = math.floor(readf32(src, so + i * 4) * 2147483648 + 0.5)
if v > 2147483647 then
v = 2147483647
elseif v < -2147483648 then
v = -2147483648
elseif v ~= v then
v = 0
end
writei32(dst, off + i * 4, v)
end
else -- u8
for i = 0, count - 1 do
local v = math.floor(readf32(src, so + i * 4) * 128 + 0.5)
if v > 127 then
v = 127
elseif v < -128 then
v = -128
elseif v ~= v then
v = 0
end
writeu8(dst, off + i, v + 128)
end
end
end
return Codecs
+643
View File
@@ -0,0 +1,643 @@
--!strict
--!optimize 2
-- audio/wav: WAVE in RIFF / RIFX (big-endian) / RF64 / BW64. Absorbed from wav-luau fd9a909 (same author, no
-- third-party code; the streaming decoder) on the shared containers/Riff, plus a new encoder.
-- Decode: PCM 8 / 16 / 24 / 32 bit, IEEE float 32 / 64, A-law, mu-law, IMA ADPCM, MS ADPCM, WAVE_FORMAT_EXTENSIBLE
-- wrapping any of them; odd-sized chunks with or without the pad byte; LIST/INFO tags; a data size of 0 or 0xFFFFFFFF
-- (streamed output) or past the end means "up to the end of the file" (a truncated file decodes what it has).
-- Encode: PCM u8 / s16 / s24 / s32 and float32 from an Audio or a streaming Decoder, WAVE_FORMAT_EXTENSIBLE when
-- there are more than 2 channels, more than 16 bits or over 48 kHz (as ffmpeg), fact for float, LIST/INFO tags,
-- RF64 (ds64) automatically past 4 GiB (Wav.encodeParts streams files over the 1 GiB buffer limit) or on request.
-- Not supported: encoding ADPCM / A-law / mu-law / f64, RIFX output.
--
-- local dec = Wav.open(Bytes.reader(buf)) -- the Types.Decoder: dec:read(4096) -> f32 buffer, frames
-- local audio = Wav.decode(Bytes.reader(buf)) -- Types.Audio
-- local file = Wav.encode(audio, { sampleFormat = "s24" })
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Pcm = require("@rosetta/codecs/audio/Pcm")
local Riff = require("@rosetta/containers/Riff")
local Codecs = require("@rosetta/audio/wav/Codecs")
local Adpcm = require("@rosetta/codecs/audio/Adpcm")
-- ------------------------------------------------------------------------------------------------ contract
local Wav = {
name = "wav",
category = "audio",
extensions = { "wav", "wave", "rf64", "bw64" },
mime = { "audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/audio/Pcm", "codecs/audio/Adpcm" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type Tags = { [string]: string }
export type OpenOptions = {
maxBytes: number?, -- unused (the file is already in memory); kept for symmetry
}
export type EncodeOptions = {
sampleFormat: ("u8" | "s16" | "s24" | "s32" | "f32")?, -- default "s16"
rf64: (boolean | "auto")?, -- default "auto": RF64 only when the file passes 4 GiB
extensible: boolean?, -- force (true) or forbid (false) WAVE_FORMAT_EXTENSIBLE; default as ffmpeg
channelMask: number?, -- the EXTENSIBLE speaker mask (default: ffmpeg's default layout for the channel count)
tags: Tags?, -- default: the Audio's tags (title, artist, album, comment, date, genre, track, ...)
rf64Threshold: number?, -- testing: the RIFF size past which "auto" switches to RF64 (default 0xFFFFFFFF)
}
-- ------------------------------------------------------------------------------------------------ constants
Wav.FORMAT_PCM = 1
Wav.FORMAT_MS_ADPCM = 2
Wav.FORMAT_FLOAT = 3
Wav.FORMAT_ALAW = 6
Wav.FORMAT_MULAW = 7
Wav.FORMAT_IMA_ADPCM = 0x11
Wav.FORMAT_EXTENSIBLE = 0xFFFE
local FORMAT_NAMES = {
[1] = "pcm",
[2] = "ms_adpcm",
[3] = "float",
[6] = "alaw",
[7] = "mulaw",
[0x11] = "ima_adpcm",
}
-- LIST/INFO ids -> tag names
local INFO_TAGS = {
INAM = "title",
IART = "artist",
IPRD = "album",
ICMT = "comment",
ICRD = "date",
IGNR = "genre",
ITRK = "track",
IPRT = "track",
ISFT = "encoder",
ICOP = "copyright",
IENG = "engineer",
ISBJ = "subject",
IKEY = "keywords",
}
-- A-law / mu-law -> f32 tables (G.711, as ffmpeg's alaw2linear / ulaw2linear)
local ALAW, MULAW = buffer.create(1024), buffer.create(1024)
do
for i = 0, 255 do
local a = bit32.bxor(i, 0x55)
local t = bit32.band(a, 15)
local seg = bit32.rshift(bit32.band(a, 0x70), 4)
if seg > 0 then
t = bit32.lshift(t * 2 + 1 + 32, seg + 2)
else
t = bit32.lshift(t * 2 + 1, 3)
end
if bit32.band(a, 0x80) == 0 then
t = -t
end
buffer.writef32(ALAW, i * 4, t / 32768)
local u = bit32.band(bit32.bnot(i), 255)
local m = bit32.lshift(bit32.lshift(bit32.band(u, 15), 3) + 0x84, bit32.rshift(bit32.band(u, 0x70), 4))
local v = if bit32.band(u, 0x80) ~= 0 then 0x84 - m else m - 0x84
buffer.writef32(MULAW, i * 4, v / 32768)
end
end
local Decoder = {}
Decoder.__index = Decoder
export type Decoder = typeof(setmetatable(
{} :: {
sampleRate: number,
channels: number,
frames: number,
duration: number,
bitrate: number,
tags: Tags,
format: string,
formatTag: number,
bitsPerSample: number,
blockAlign: number,
container: string,
dataOffset: number,
dataSize: number,
truncated: boolean,
channelMask: number?,
validBits: number?,
_buf: buffer,
_pos: number,
_be: boolean,
_bytes: number,
_kind: string,
_spb: number,
_cache: buffer?,
_cacheBlock: number,
_cacheFrames: number,
_coefs: buffer?,
_ncoef: number,
_state: buffer?,
_tmp: buffer,
},
Decoder
))
local function trimTag(s: string): string
-- strip trailing NULs / spaces
local e = #s
while e > 0 do
local c = string.byte(s, e)
if c ~= 0 and c ~= 32 then
break
end
e -= 1
end
local z = string.find(s, "\0", 1, true)
if z and z <= e then
e = z - 1
end
return string.sub(s, 1, e)
end
-- ------------------------------------------------------------------------------------------------ sniff
function Wav.sniff(r: Bytes.Reader): number
return if Riff.sniff(r) == "WAVE" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- decode(r, opts?) -> Types.Audio | nil, Err: the whole file
function Wav.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?)
local dec, err = Wav.open(r, opts)
if not dec then
return nil, err
end
return Pcm.drain(dec, {
format = "wav",
codec = dec.format,
bitDepth = dec.bitsPerSample,
container = dec.container,
channelMask = dec.channelMask,
truncated = dec.truncated,
})
end
-- ------------------------------------------------------------------------------------------------ encode
local SAMPLE_BYTES = { u8 = 1, s16 = 2, s24 = 3, s32 = 4, f32 = 4 }
-- ffmpeg's default speaker masks per channel count (av_channel_layout_default)
local MASKS = { [1] = 0x4, [2] = 0x3, [3] = 0xB, [4] = 0x107, [5] = 0x37, [6] = 0x3F, [7] = 0x70F, [8] = 0x63F }
local GUID_TAIL = "\0\0\0\0\16\0\128\0\0\170\0\56\155\113" -- KSDATAFORMAT_SUBTYPE_* after the 2-byte format tag
-- tags -> LIST/INFO ids (the first id per name)
local TAG_IDS = { title = "INAM", artist = "IART", album = "IPRD", comment = "ICMT", date = "ICRD", genre = "IGNR", track = "ITRK", encoder = "ISFT", copyright = "ICOP", engineer = "IENG", subject = "ISBJ", keywords = "IKEY" }
local BLOCK = 65536 -- frames per data piece when streaming a Decoder
-- the body of the encoder: { buffer } pieces of the file | nil, Err
local function encodeParts(value: any, opts: EncodeOptions?, asParts: boolean): (any, Err.Err?)
if type(value) ~= "table" then
return nil, Err.new(Err.ARG, "encode: needs an Audio or a Decoder")
end
local o: EncodeOptions = opts or {}
local kind = o.sampleFormat or "s16"
local bytes: number? = SAMPLE_BYTES[kind]
if not bytes then
return nil, Err.new(Err.ARG, "encode: sampleFormat must be u8, s16, s24, s32 or f32")
end
local rate: number, ch: number = value.sampleRate, value.channels
if type(rate) ~= "number" or rate < 1 or rate > 4294967295 or rate % 1 ~= 0 then
return nil, Err.new(Err.ARG, "encode: bad sample rate")
end
if type(ch) ~= "number" or ch < 1 or ch > 65535 or ch % 1 ~= 0 then
return nil, Err.new(Err.ARG, "encode: bad channel count")
end
local isAudio = type(value.samples) == "buffer"
if not isAudio and type(value.read) ~= "function" then
return nil, Err.new(Err.ARG, "encode: needs an Audio (samples) or a Decoder (read)")
end
local frameBytes = bytes * ch
local pieces: { buffer } = {}
local frames: number = 0
if isAudio then
frames = (value.frames :: number?) or (buffer.len(value.samples) // (ch * 4))
if type(frames) ~= "number" or frames < 0 or buffer.len(value.samples) < frames * ch * 4 then
return nil, Err.new(Err.ARG, "encode: the samples buffer is shorter than frames * channels")
end
if not asParts and frames * frameBytes > 0x3FFFFF00 then
return nil, Err.new(Err.LIMIT, "encode: over 1 GiB of samples (use Wav.encodeParts)")
end
-- pieces of at most 256 MiB
local per = math.max(1, 0x10000000 // frameBytes)
local f0 = 0
while f0 < frames do
local n = math.min(per, frames - f0)
local b = buffer.create(n * frameBytes)
Codecs.quantize(value.samples, f0 * ch, b, 0, n * ch, kind)
table.insert(pieces, b)
f0 += n
end
else
local tmp = buffer.create(BLOCK * ch * 4)
while true do
local ok, out, n = pcall(value.read, value, BLOCK, tmp)
if not ok then
return nil, Err.new(Err.ARG, "encode: the decoder failed: " .. tostring(out))
end
if type(n) ~= "number" or n <= 0 or type(out) ~= "buffer" then
break
end
n = math.min(n, buffer.len(out) // (ch * 4))
local b = buffer.create(n * frameBytes)
Codecs.quantize(out, 0, b, 0, n * ch, kind)
table.insert(pieces, b)
frames += n
if not asParts and frames * frameBytes > 0x3FFFFF00 then
return nil, Err.new(Err.LIMIT, "encode: over 1 GiB of samples (use Wav.encodeParts)")
end
end
end
local dataSize = frames * frameBytes
local bits = bytes * 8
local float = kind == "f32"
local tag = if float then 3 else 1
local extensible = ch > 2 or rate > 48000 or (not float and bits > 16)
if o.extensible ~= nil then
extensible = o.extensible
end
local w = Riff.writer("WAVE", { rf64 = if o.rf64 ~= nil then o.rf64 else "auto", sampleCount = frames, rf64Threshold = o.rf64Threshold })
local fmt = Bytes.writer(40)
fmt:u16le(if extensible then 0xFFFE else tag)
fmt:u16le(ch)
fmt:u32le(rate)
fmt:u32le(rate * frameBytes)
fmt:u16le(frameBytes)
fmt:u16le(bits)
if extensible then
fmt:u16le(22)
fmt:u16le(bits)
fmt:u32le(o.channelMask or MASKS[ch] or 0)
fmt:u16le(tag)
fmt:string(GUID_TAIL)
elseif float then
fmt:u16le(0) -- cbSize
end
w:chunk("fmt ", fmt:finish())
if float then
local fact = Bytes.writer(4)
fact:u32le(if w.rf64 == true or frames > 0xFFFFFFFF then 0xFFFFFFFF else frames) -- RF64: in ds64 (as ffmpeg)
w:chunk("fact", fact:finish())
end
local tags = o.tags or value.tags
if type(tags) == "table" then
local items = {}
local keys = {}
for k in tags do
if type(k) == "string" then
table.insert(keys, k)
end
end
table.sort(keys)
for _, k in keys do
local v = tags[k]
-- other RIFF INFO ids come back as their lower-cased id ("ixyz") and are written as such
local id = TAG_IDS[k] or (if string.match(string.lower(k), "^i[%l%d][%l%d][%l%d]$") then string.upper(k) else nil)
if id and type(v) == "string" and v ~= "" then
table.insert(items, { id, v })
end
end
if #items > 0 then
w:list("INFO", items)
end
end
w:chunk("data", pieces)
local _ = dataSize
return w:finish({ parts = asParts })
end
-- encode(audio or decoder, opts?) -> buffer | nil, Err
function Wav.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
return encodeParts(value, opts, false)
end
-- encodeParts(audio or decoder, opts?) -> { buffer } | nil, Err: the file as pieces to write one after the other
-- (header, sample blocks, ...), without the 1 GiB single-buffer limit; RF64 past 4 GiB
function Wav.encodeParts(value: any, opts: EncodeOptions?): ({ buffer }?, Err.Err?)
return encodeParts(value, opts, true)
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts?) -> Decoder | nil, Err: the streaming decoder (Types.Decoder) over the file in r's range
function Wav.open(r: Bytes.Reader, _opts: OpenOptions?): (Decoder?, Err.Err?)
if type(r) == "buffer" or type(r) == "string" then
r = Bytes.reader(if type(r) == "string" then buffer.fromstring(r) else r :: any)
end
local f, ferr = Riff.read(r, { openEnded = { data = true } })
if not f then
return nil, ferr
end
if f.form ~= "WAVE" then
return nil, Err.new(Err.CORRUPT, "not a WAVE file (" .. f.form .. ")", f.base + 8)
end
local buf = f.buf
local magic = f.container
local be = f.bigEndian
local fmt: any = nil
local tags: Tags = {}
local dataOff, dataSize = -1, 0
local truncated = false
local ds64Frames: number? = if f.ds64 and f.ds64.sampleCount > 0 then f.ds64.sampleCount else nil
local factFrames: number? = nil
local function u16(o: number): number
return Riff.u16(f, o)
end
local function u32(o: number): number
return Riff.u32(f, o)
end
local function i16(o: number): number
local v = u16(o)
return if v >= 32768 then v - 65536 else v
end
for _, c in f.chunks do
local id, size, body, avail = c.id, c.size, c.offset, c.avail
if id == "fmt " and avail >= 14 then
fmt = {
tag = u16(body),
channels = u16(body + 2),
rate = u32(body + 4),
byteRate = u32(body + 8),
blockAlign = u16(body + 12),
bits = if avail >= 16 then u16(body + 14) else 8,
body = body,
avail = avail,
}
elseif id == "fact" and avail >= 4 then
factFrames = u32(body)
elseif id == "LIST" and Riff.listType(f, c) == "INFO" then
for _, sc in Riff.list(f, c) do
local name = INFO_TAGS[sc.id]
if sc.avail > 0 then
local v = trimTag(buffer.readstring(buf, sc.offset, sc.avail))
if v ~= "" then
tags[name or string.lower(sc.id)] = v
end
end
end
elseif id == "data" and dataOff < 0 then
dataOff = body
dataSize = avail
truncated = c.truncated
end
local _ = size
end
if not fmt then
return nil, Err.new(Err.CORRUPT, "no fmt chunk")
end
if dataOff < 0 then
return nil, Err.new(Err.CORRUPT, "no data chunk")
end
local tag, ch, rate, bits = fmt.tag, fmt.channels, fmt.rate, fmt.bits
local channelMask: number? = nil
local validBits: number? = nil
if tag == 0xFFFE then
if fmt.avail < 40 then
return nil, Err.new(Err.CORRUPT, "WAVE_FORMAT_EXTENSIBLE without its extension")
end
local valid = u16(fmt.body + 18)
channelMask = u32(fmt.body + 20)
tag = u16(fmt.body + 24) -- the GUID's first two bytes are the format tag
-- valid bits < container bits: the samples are left-justified, so decoding the container is right
validBits = valid
end
if ch < 1 or ch > 255 then
return nil, Err.new(Err.CORRUPT, "bad channel count " .. ch)
end
if rate < 1 or rate > 4000000 then
return nil, Err.new(Err.CORRUPT, "bad sample rate " .. rate)
end
local name: string? = FORMAT_NAMES[tag]
if not name then
return nil, Err.new(Err.UNSUPPORTED, string.format("format 0x%04X", tag))
end
local dec = setmetatable({}, Decoder) :: any
dec.sampleRate = rate
dec.channels = ch
dec.tags = tags
dec.format = name
dec.formatTag = tag
dec.bitsPerSample = bits
dec.container = magic
dec.dataOffset = dataOff
dec.dataSize = dataSize
dec.channelMask = channelMask
dec._buf = buf
dec._pos = 0
dec._be = be
dec._tmp = buffer.create(8)
dec._cacheBlock = -1
dec._cacheFrames = 0
dec._ncoef = 0
local blockAlign: number = fmt.blockAlign
local frames: number
if name == "pcm" or name == "float" or name == "alaw" or name == "mulaw" then
local bytes
if name == "alaw" or name == "mulaw" then
bytes = 1
elseif name == "float" then
if bits ~= 32 and bits ~= 64 then
return nil, Err.new(Err.UNSUPPORTED, "float size " .. bits)
end
bytes = bits // 8
else
if bits < 1 or bits > 32 then
return nil, Err.new(Err.UNSUPPORTED, "PCM size " .. bits)
end
-- container: from blockAlign when it is consistent, else from the bit depth
bytes = (bits + 7) // 8
if blockAlign >= ch and blockAlign % ch == 0 and blockAlign // ch >= bytes and blockAlign // ch <= 4 then
bytes = blockAlign // ch
end
end
blockAlign = bytes * ch
dec._bytes = bytes
dec._kind = name
frames = dataSize // blockAlign
dec._spb = 1
elseif name == "ima_adpcm" or name == "ms_adpcm" then
if blockAlign < 1 then
return nil, Err.new(Err.CORRUPT, "ADPCM with blockAlign 0")
end
local spb = if fmt.avail >= 20 then u16(fmt.body + 18) else 0
if name == "ima_adpcm" then
if bits ~= 4 then
return nil, Err.new(Err.UNSUPPORTED, "IMA ADPCM size " .. bits)
end
if blockAlign < 4 * ch then
return nil, Err.new(Err.CORRUPT, "IMA ADPCM block too small")
end
local computed = (blockAlign - 4 * ch) * 2 // ch + 1
if spb < 1 or spb > computed then
spb = computed
end
else
if blockAlign < 7 * ch then
return nil, Err.new(Err.CORRUPT, "MS ADPCM block too small")
end
local computed = (blockAlign - 7 * ch) * 2 // ch + 2
if spb < 2 or spb > computed then
spb = computed
end
-- coefficients from the fmt extension, else the 7 standard pairs
local c1, c2 = Adpcm.MS_COEF1, Adpcm.MS_COEF2
local ncoef = 7
if fmt.avail >= 22 then
local k = u16(fmt.body + 20)
if k >= 1 and k <= 256 and fmt.avail >= 22 + 4 * k then
ncoef = k
c1, c2 = {}, {}
for i = 1, k do
c1[i] = i16(fmt.body + 22 + (i - 1) * 4)
c2[i] = i16(fmt.body + 24 + (i - 1) * 4)
end
end
end
local coefs = buffer.create(ncoef * 8)
for i = 1, ncoef do
buffer.writei32(coefs, (i - 1) * 8, c1[i])
buffer.writei32(coefs, (i - 1) * 8 + 4, c2[i])
end
dec._coefs = coefs
dec._ncoef = ncoef
dec._state = buffer.create(20 * ch)
end
if spb * ch > 2 ^ 20 then
return nil, Err.new(Err.LIMIT, "ADPCM block too large")
end
dec._kind = name
dec._spb = spb
dec._cache = buffer.create(spb * ch * 4)
local full = dataSize // blockAlign
frames = full * spb
local rest = dataSize - full * blockAlign
if rest > 0 then
-- a partial last block: the frames it holds whole
if name == "ima_adpcm" then
if rest >= 4 * ch then
frames += math.min(spb, 1 + ((rest - 4 * ch) // (4 * ch)) * 8)
end
elseif rest >= 7 * ch then
frames += math.min(spb, 2 + ((rest - 7 * ch) * 2) // ch)
end
end
-- fact: the true length (the last block is padded)
if factFrames and factFrames > 0 and factFrames < frames then
frames = factFrames
end
else
return nil, Err.new(Err.UNSUPPORTED, "format " .. name)
end
if ds64Frames and ds64Frames > 0 and ds64Frames < frames then
frames = ds64Frames
end
dec.blockAlign = blockAlign
dec.frames = frames
dec.duration = frames / rate
dec.truncated = truncated
dec.validBits = validBits
dec.bitrate = if fmt.byteRate > 0 then fmt.byteRate * 8 else math.floor(rate * blockAlign * 8 / dec._spb)
return dec, nil
end
-- ------------------------------------------------------------------------------------------------ extras
-- Decodes up to maxFrames frames from the current position. Returns a buffer of interleaved f32 samples
-- (frames * channels values; `out` is reused when given and large enough) and the frame count (0 = end).
function Decoder.read(self: Decoder, maxFrames: number, out: buffer?): (buffer, number)
local ch = self.channels
local req = math.floor(tonumber(maxFrames) or 0)
if req ~= req then -- NaN (math.min / max treat it differently on LuaJIT)
req = 0
end
local want = math.max(0, math.min(req, self.frames - self._pos))
local dst: buffer = if out and type(out) == "buffer" and buffer.len(out) >= want * ch * 4
then out
else buffer.create(want * ch * 4)
if want == 0 then
return dst, 0
end
local kind = self._kind
if self._spb == 1 then
local off = self.dataOffset + self._pos * self.blockAlign
local count = want * ch
if kind == "pcm" then
Codecs.int(self._buf, off, dst, 0, count, self._bytes, self._be)
elseif kind == "float" then
Codecs.float(self._buf, off, dst, 0, count, self._bytes, self._be, self._tmp)
elseif kind == "alaw" then
Codecs.law(self._buf, off, dst, 0, count, ALAW)
else
Codecs.law(self._buf, off, dst, 0, count, MULAW)
end
self._pos += want
return dst, want
end
-- block formats: decode a block into the cache, copy out of it
local spb, ba = self._spb, self.blockAlign
local cache = self._cache :: buffer
local done = 0
while done < want do
local block = self._pos // spb
if block ~= self._cacheBlock then
local off = self.dataOffset + block * ba
local avail = math.min(ba, self.dataOffset + self.dataSize - off)
local got
if kind == "ima_adpcm" then
got = Adpcm.imaWav(self._buf, off, avail, ch, spb, cache, 0)
else
got = Adpcm.msBlock(self._buf, off, avail, ch, spb, cache, 0, self._coefs :: buffer, self._ncoef,
self._state :: buffer)
end
self._cacheBlock = block
self._cacheFrames = got
end
local inBlock = self._pos - block * spb
local k = math.min(want - done, self._cacheFrames - inBlock)
if k <= 0 then
break
end
Codecs.copy(cache, inBlock * ch, dst, done * ch, k * ch)
done += k
self._pos += k
end
return dst, done
end
-- Moves to a time in seconds (clamped to the stream).
function Decoder.seek(self: Decoder, seconds: number)
local f = math.floor((tonumber(seconds) or 0) * self.sampleRate + 0.5)
if f ~= f then
f = 0
end
self._pos = math.clamp(f, 0, self.frames)
end
-- Moves to a frame index (clamped).
function Decoder.seekFrame(self: Decoder, frame: number)
local f = math.floor(tonumber(frame) or 0)
if f ~= f then
f = 0
end
self._pos = math.clamp(f, 0, self.frames)
end
-- Current position in seconds.
function Decoder.position(self: Decoder): number
return self._pos / self.sampleRate
end
-- Current position in frames.
function Decoder.tell(self: Decoder): number
return self._pos
end
return Wav
+219
View File
@@ -0,0 +1,219 @@
--!strict
-- audio/wavpack: WavPack (.wv) files: the block sequence around codecs/audio/WavPack, APEv2 tags, the .wvc correction
-- file of hybrid lossless files. Written from the WavPack 5 file format document (David Bryant) and the WavPack 5.9.0
-- library's file handling (open_utils.c; BSD 3-clause, licenses/wavpack-LICENSE.txt).
-- Supports: lossless and hybrid streams, integer 8 - 32 bit and 32-bit float, 1 - 4096 channels (WAV order, as the
-- encoder stores them), non-standard sample rates, the correction file (opts.correction, else opts.resolve("<name>c")
-- on hosts with files) which makes a hybrid file lossless, garbage between blocks (resync), sample-accurate seeking
-- (every block is independent), APEv2 tags at the end (codecs/audio/ApeTag). Without a correction file a hybrid file
-- decodes lossy (as wvunpack does). Not supported: DSD (Err.UNSUPPORTED), WavPack 1 - 3 files, encoding.
--
-- local dec = WavPack.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, float, hybrid, lossless, ...
-- local f32, n = dec:read(4096)
-- local i32, n = dec:readInt(4096) -- integer streams: the samples as wvunpack writes them
-- local audio = WavPack.decode(Bytes.reader(buf)) -- Types.Audio
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Pcm = require("@rosetta/codecs/audio/Pcm")
local Stream = require("@rosetta/codecs/audio/Stream")
local ApeTag = require("@rosetta/codecs/audio/ApeTag")
local WavPackCodec = require("@rosetta/codecs/audio/WavPack")
-- ------------------------------------------------------------------------------------------------ contract
local WavPack = {
name = "wavpack",
category = "audio",
extensions = { "wv" },
mime = { "audio/x-wavpack", "audio/wavpack" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/WavPack" },
caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, hybrid = true, float = true, depths = { 8, 12, 16, 20, 24, 32 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
correction: (buffer | string)?, -- the .wvc file of a hybrid file (default: opts.resolve(name .. "c") when given)
resolve: ((uri: string) -> buffer?)?, -- sibling files (the api passes it for paths)
name: string?, -- the file name (the api passes it)
maxFrames: number?, -- decode(): refuse longer streams (default 2^28)
}
-- ------------------------------------------------------------------------------------------------ sniff
function WavPack.sniff(r: Bytes.Reader): number
if r:peek(4) ~= "wvpk" then
return 0
end
local v = r:peekU8(9)
return if v == 4 then 1 else 0.5
end
-- ------------------------------------------------------------------------------------------------ decode
-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream
function WavPack.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?)
local dec, err = WavPack.open(r, opts)
if not dec then
return nil, err
end
local d = dec :: any
local limit = opts and opts.maxFrames or 2 ^ 28
if d.frames > limit or d.frames * d.channels > 2 ^ 28 then
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames))
end
return Pcm.drain(d, d.source, limit)
end
-- ------------------------------------------------------------------------------------------------ open
type Index = { offsets: { { number } }, starts: { number }, samples: { number }, total: number, first: number, md5: string? }
-- index(buf, base, limit) -> the frames (block offsets per frame) of a .wv / .wvc block sequence
local function index(buf: buffer, base: number, limit: number): (Index?, string?)
local at = base
local idx: Index = { offsets = {}, starts = {}, samples = {}, total = -1, first = -1 }
local cur: { number }? = nil
local initial = -1
local resyncs = 0
while at + 32 <= limit do
local h = WavPackCodec.header(buf, at, limit)
if not h then
-- garbage (or a tag) between blocks: search the next header
if resyncs > 64 then
break
end
local s = buffer.readstring(buf, at + 1, math.min(limit - at - 1, 1048576))
local k = string.find(s, "wvpk", 1, true)
if not k then
break
end
at = at + k
resyncs += 1
continue
end
if initial < 0 then
initial = h.index
idx.total = h.total
end
if h.samples > 0 then
if bit32.band(h.flags, WavPackCodec.INITIAL) ~= 0 or not cur then
cur = { at }
table.insert(idx.offsets, cur)
table.insert(idx.starts, h.index - initial)
table.insert(idx.samples, h.samples)
if idx.first < 0 then
idx.first = at
end
else
table.insert(cur, at)
end
if bit32.band(h.flags, WavPackCodec.FINAL) ~= 0 then
cur = nil
end
else
idx.md5 = idx.md5 or WavPackCodec.md5(buf, at, limit)
end
at += h.size
end
if idx.first < 0 then
return nil, "no audio blocks"
end
return idx, nil
end
local function correctionFile(opts: OpenOptions?): buffer?
if not opts then
return nil
end
local c = opts.correction
if type(c) == "string" then
return buffer.fromstring(c)
elseif type(c) == "buffer" then
return c
end
if type(opts.resolve) == "function" and type(opts.name) == "string" then
local base = string.match(opts.name, "([^/\\]+)$")
if base then
local ok, b = pcall(opts.resolve, base .. "c")
if ok and type(b) == "buffer" then
return b
end
end
end
return nil
end
-- open(r, opts?) -> Decoder | nil, Err
function WavPack.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?)
if type(r) == "buffer" then
r = Bytes.reader(r :: any)
end
if type(r) ~= "table" or type(r.buf) ~= "buffer" then
return nil, Err.new(Err.ARG, "open: expected a Reader")
end
local buf, base, limit = r.buf, r.base, r.limit
local tags, tagInfo = ApeTag.find(buf, base, limit)
local stop = if tagInfo then tagInfo.start else limit
local idx, ierr = index(buf, base, stop)
if not idx then
return nil, Err.from(ierr, base)
end
local info, err = WavPackCodec.info(buf, idx.first, stop)
if not info then
return nil, err
end
if info.channels > 256 then
return nil, Err.new(Err.LIMIT, info.channels .. " channels")
end
local count = #idx.offsets
local last = idx.starts[count] + idx.samples[count]
local frames = if idx.total >= 0 then math.min(idx.total, last) else last
-- the correction file: its frames by start sample
local cbuf = if info.hybrid then correctionFile(opts) else nil
local cfor: { [number]: { number } } = {}
if cbuf then
local cidx = index(cbuf, 0, buffer.len(cbuf))
if cidx then
for i, offs in cidx.offsets do
cfor[cidx.starts[i]] = offs
end
else
cbuf = nil
end
end
local codec = WavPackCodec.decoder(info.channels)
local dec: any = {
sampleRate = info.sampleRate,
channels = info.channels,
frames = frames,
duration = frames / info.sampleRate,
bitrate = if frames > 0 then math.floor((stop - base) * 8 * info.sampleRate / frames) else 0,
tags = tags or {},
bitsPerSample = info.bitsPerSample,
float = info.float,
hybrid = info.hybrid,
lossless = not info.hybrid or cbuf ~= nil,
channelMask = info.channelMask,
md5 = idx.md5,
source = { format = "wavpack", bitDepth = info.bitsPerSample, float = info.float, hybrid = info.hybrid, correction = cbuf ~= nil, version = info.version, tags = tagInfo and tagInfo.items },
}
local starts, offsets = idx.starts, idx.offsets
return Stream.packets(dec, {
count = count,
start = function(i: number): number
return if i > count then last else starts[i]
end,
decode = function(i: number): (number?, Err.Err?)
local co = if cbuf then cfor[starts[i]] else nil
return codec:frame(buf, offsets[i], if co then cbuf else nil, co)
end,
pcm = function(): { number }
return codec.pcm
end,
reset = function() end,
stop = frames,
scale = if info.float then 1 else 1 / 2 ^ (info.bytesPerSample * 8 - 1),
ints = not info.float,
})
end
return WavPack