audio formats: comments are specs only

This commit is contained in:
4DBug committed 2026-11-01 01:53:49 -05:00
1 parent 0bd7b87d2b
commit 6ffbdbe0be
29 files changed
+143 -442

No files matched your search

+7 -12
View File
@@ -1,8 +1,7 @@
--!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.
-- audio/aac: raw AAC in ADTS framing (ISO/IEC 13818-7 / 14496-3 1.A.3). Supports: AAC-LC via codecs/audio/Aac (1-8
-- channels, every rate), CRC-protected headers, a leading ID3v2 tag, resync, seeking by frame; HE-AAC plays its
-- AAC-LC core. Not supported: writing, ADIF, LATM.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -24,13 +23,12 @@ local AacFormat = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxFrames: number?, -- refuse streams with more ADTS frames (default 2^22)
maxFrames: number?, -- 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
@@ -43,7 +41,6 @@ local function id3Size(b: buffer, p: number, limit: number): number
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",
@@ -94,7 +91,6 @@ function AacFormat.sniff(r: Bytes.Reader): number
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
@@ -103,7 +99,6 @@ function AacFormat.sniff(r: Bytes.Reader): number
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)
@@ -112,14 +107,14 @@ local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number
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
h = nil
end
if not h then
p += 1
continue
end
if p + h.frameSize > limit then
break -- a truncated last frame
break
end
if not first then
first = h
@@ -178,7 +173,7 @@ function AacFormat.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?,
tags = tags,
codec = "aac",
}
-- 1024 frames per ADTS frame; one frame of pre-roll for the overlap when seeking
-- 1024 samples per ADTS frame; one frame of pre-roll for the overlap
return Stream.packets(out, {
count = nframes,
start = function(i: number): number
+10 -13
View File
@@ -1,10 +1,7 @@
--!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.
-- audio/ac3: raw AC-3 (Dolby Digital, ATSC A/52) via codecs/audio/Ac3. Supports: every channel layout (WAVE order, no
-- downmix), 32 / 44.1 / 48 kHz, every bit rate, the CRC check, resync, exact seeking; drc 0 .. 1, off by default.
-- Not supported: writing, E-AC-3 (UNSUPPORTED), bsid 9 / 10 reduced-rate streams.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -26,13 +23,13 @@ local Ac3Format = {
-- ------------------------------------------------------------------------------------------------ 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)
maxFrames: number?, -- default 2^22
drc: number?, -- 0 = off (default), 1 = full
crc: boolean?, -- 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)
-- E-AC-3 sniffs too, so it reports UNSUPPORTED rather than 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)
@@ -47,7 +44,7 @@ function Ac3Format.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- the syncframe index (resyncing over garbage: a header counts when the next one follows it, or the data ends)
-- 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
@@ -61,7 +58,7 @@ local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number
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
h = nil
end
end
if not h then
@@ -77,7 +74,7 @@ local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number
end
end
if p + h.frameSize > limit then
break -- a truncated last frame
break
end
table.insert(offs, p)
table.insert(sizes, h.frameSize)
+9 -21
View File
@@ -1,20 +1,8 @@
--!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" })
-- audio/adpcm: headerless ADPCM (.adpcm / .ima / .vox) via codecs/audio/Adpcm; sniff is 0, the layout comes from opts.
-- "ima": DVI nibbles, high first; "ima_wav": MS IMA blocks; "ms": MS ADPCM, 7 standard coefficient pairs; "ima_qt":
-- Apple ima4 (34-byte packets, 64 frames); "psx": PS-ADPCM (16-byte frames, 28 samples). Encode: ima, ima_wav, ms.
-- Not supported: raw DSP / ADX (their coefficients live in a header).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -40,10 +28,10 @@ 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)
blockAlign: number?, -- ima_wav / ms; default 1024 decoding, 256 * channels encoding
lowFirst: boolean?,
interleave: number?, -- psx: bytes per channel (default 16)
maxFrames: number?, -- default 2^28
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -51,7 +39,7 @@ local CODECS = { ima = true, ima_wav = true, ms = true, ima_qt = true, psx = tru
-- ------------------------------------------------------------------------------------------------ sniff
function Raw.sniff(_r: Bytes.Reader): number
return 0 -- no header: found by extension or opts.format only
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
+6 -14
View File
@@ -1,15 +1,7 @@
--!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 } })
-- audio/adx: CRI ADX via codecs/audio/Adpcm; header and decoder follow vgmstream r2117 (ISC,
-- licenses/vgmstream-LICENSE.txt), bit-exact with it. Supports: encoding type 3, versions 3-5, 1-8 channels, loop
-- points; encode as version 4. Not supported: encrypted ADX (0x0408 / 0x0409), encoding types 2 and 4, AHX.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -32,11 +24,11 @@ local Adx = {
-- ------------------------------------------------------------------------------------------------ types
export type Loop = { start: number, stop: number }
export type DecodeOptions = {
maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28)
maxFrames: number?, -- 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)
loop: Loop?, -- frames, stop exclusive; default the source's meta.source.loop
cutoff: number?, -- Hz, default 500 (as CRI's encoders)
}
-- ------------------------------------------------------------------------------------------------ constants
+11 -22
View File
@@ -1,11 +1,7 @@
--!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.
-- audio/aiff: AIFF / AIFF-C (Apple AIFF 1.3, AIFF-C draft 1991). Supports: PCM 1-32 bits; AIFF-C NONE / twos /
-- sowt / raw / in24 / in32 / fl32 / fl64 / ulaw / alaw / ima4; text chunks as tags; truncated SSND; encode 8-32 bit,
-- sowt, fl32, fl64, ulaw, alaw. Not supported: other compressed AIFF-C codecs, MARK / INST, the ID3 chunk.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -26,13 +22,12 @@ local Aiff = {
}
export type DecodeOptions = {
maxFrames: number?, -- refuse more sample frames (default 2^28)
maxFrames: number?, -- 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)
littleEndian: boolean?, -- 16-bit only, as AIFF-C "sowt" (ffmpeg reads no other sowt); default false
aifc: boolean?, -- default: only when the sample format needs it
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -40,7 +35,6 @@ local TEXT_TAGS = { NAME = "title", AUTH = "artist", ["(c) "] = "copyright", ANN
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))
@@ -56,7 +50,6 @@ local function ext80(b: buffer, o: number): number
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)
@@ -69,7 +62,7 @@ local function writeExt80(w: Bytes.Writer, x: number)
while x < 2 ^ e do
e -= 1
end
local m = x * 2 ^ (63 - e) -- in [2^63, 2^64)
local m = x * 2 ^ (63 - e)
local hi = math.floor(m / 4294967296)
local lo = m - hi * 4294967296
w:u16be(e + 16383)
@@ -77,7 +70,6 @@ local function writeExt80(w: Bytes.Writer, x: number)
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
@@ -118,7 +110,7 @@ local function sampleFormat(comp: string, bits: number): (string?, string?)
elseif comp == "alaw" or comp == "ALAW" then
return "alaw", nil
elseif comp == "ima4" then
return "ima4", nil -- not a Pcm format: Adpcm/Decoder.blocks
return "ima4", nil
end
return nil, "compression " .. string.format("%q", comp)
end
@@ -142,12 +134,11 @@ type Info = {
compression: string,
aifc: boolean,
dataOffset: number, -- absolute in r.buf
dataSize: number, -- bytes of sample data present
dataSize: number,
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
@@ -165,7 +156,7 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?)
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)
-- 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
@@ -250,7 +241,6 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?)
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
@@ -300,14 +290,13 @@ function Aiff.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local aifc = o.aifc or comp ~= "NONE"
local w = Bytes.writer(65536)
w:string("FORM")
w:u32be(0) -- patched
w:u32be(0)
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]
+4 -12
View File
@@ -1,13 +1,7 @@
--!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
-- audio/ape: Monkey's Audio (.ape) via codecs/audio/Ape and ApeTag, from the Monkey's Audio SDK 13.28 (BSD 3-clause,
-- licenses/monkeys-audio-LICENSE.txt). Supports: versions 3.95+, every level, 8-32-bit integer and 32-bit float, 1-32
-- channels, an ID3v2 prefix, seeking by the seek table. Not supported: files before 3.95, encoding.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -30,7 +24,7 @@ local Ape = {
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
maxFrames: number?, -- decode(): refuse longer streams (default 2^28)
maxFrames: number?, -- default 2^28
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -59,7 +53,6 @@ function Ape.sniff(r: Bytes.Reader): number
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
@@ -74,7 +67,6 @@ function Ape.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err
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)
+5 -7
View File
@@ -1,9 +1,7 @@
--!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).
-- audio/au: Sun / NeXT audio (.au / .snd), big endian. Supports: encodings 1 (mu-law), 2-5 (8-32-bit linear), 6 / 7
-- (float), 27 (A-law), data size 0xFFFFFFFF (to the end), the annotation as tags.comment; encode to any of them.
-- Not supported: G.721 / G.722 / G.723 ADPCM and the other NeXT encodings.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -22,7 +20,7 @@ local Au = {
}
export type DecodeOptions = {
maxFrames: number?, -- refuse more sample frames (default 2^28)
maxFrames: number?, -- default 2^28
}
export type EncodeOptions = {
sampleFormat: ("s8" | "s16" | "s24" | "s32" | "f32" | "f64" | "ulaw" | "alaw")?, -- default "s16"
@@ -90,7 +88,7 @@ function Au.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local w = Bytes.writer(65536)
w:string(".snd")
w:u32be(24 + alen)
w:u32be(0xFFFFFFFF) -- patched
w:u32be(0xFFFFFFFF)
w:u32be(spec[1])
w:u32be(src.sampleRate)
w:u32be(src.channels)
+5 -14
View File
@@ -1,13 +1,7 @@
--!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)
-- audio/brstm: Nintendo BRSTM (Wii, "RSTM", BE), BCSTM (3DS, "CSTM", LE), BFSTM (Wii U BE / Switch LE, "FSTM"); layouts
-- follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), bit-exact. Supports: DSP ADPCM, PCM16 / PCM8, 1-255
-- channels, loop points. Read only. Not supported: BCSTM IMA ADPCM, BRSTM 0.1, BFSTM regions, the track table.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -28,7 +22,7 @@ local Brstm = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28)
maxFrames: number?, -- default 2^28
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -44,7 +38,6 @@ function Brstm.sniff(r: Bytes.Reader): number
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
@@ -65,8 +58,6 @@ function Brstm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err
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
@@ -109,7 +100,7 @@ type Layout = {
frames: number,
blockSize: number,
lastPadded: number,
data: number, -- the first block (absolute in the file)
data: number, -- absolute
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,
+5 -13
View File
@@ -1,10 +1,7 @@
--!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).
-- audio/caf: Apple Core Audio Format (CAF 1.0 spec). Supports: linear PCM (8-32-bit integer, 32 / 64-bit float, either
-- endian), ALAC, AAC-LC (kuki esds), mu-law, A-law, IMA4; pakt trimming, data size -1, info tags, seeking; encode PCM
-- (16 / 24-bit BE, 32-bit float) and ALAC (16 / 20 / 24-bit). Not supported: other compressed formats.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -29,7 +26,7 @@ local Caf = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxPackets: number?, -- packet table limit (default 2^24)
maxPackets: number?, -- default 2^24
}
export type EncodeOptions = {
codec: ("pcm" | "alac")?, -- default "alac"
@@ -48,7 +45,6 @@ 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
@@ -76,7 +72,7 @@ end
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
dataStart: number, -- absolute
dataEnd: number,
cookie: buffer?,
packets: { number }?, -- sizes (pakt)
@@ -236,7 +232,6 @@ local function parse(r: Bytes.Reader, o: DecodeOptions): (Parsed?, Err.Err?)
return p, nil
end
-- the packet decoder: decode(i) -> frames into pcm (interleaved floats) | nil, Err
type Source = {
channels: number,
rate: number,
@@ -333,7 +328,6 @@ local function source(r: Bytes.Reader, p: Parsed): (Source?, Err.Err?)
}
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
@@ -505,7 +499,6 @@ local function chunk(w: Bytes.Writer, typ: string, size: number)
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
@@ -523,7 +516,6 @@ function Caf.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
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")
+3 -6
View File
@@ -1,9 +1,7 @@
--!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).
-- audio/flac/Meta: STREAMINFO, SEEKTABLE, VORBIS_COMMENT and PICTURE blocks; absorbed from flac-luau 7083d0d.
local VorbisComment = require("@rosetta/codecs/audio/VorbisComment")
local readu8, readu32 = buffer.readu8, buffer.readu32
@@ -51,7 +49,7 @@ export type Info = {
seekTable: { SeekPoint },
vendor: string,
tags: { [string]: string }, -- upper-case keys; repeated keys are joined with "; "
comments: { { key: string, value: string } }, -- every comment in order
comments: { { key: string, value: string } },
pictures: { Picture },
firstFrame: number, -- byte offset just after the last metadata block
}
@@ -150,7 +148,6 @@ local function picture(b: buffer, p: number, e: number): Picture?
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"
@@ -195,7 +192,7 @@ function Meta.parse(b: buffer, pos: number, len: number): (Info?, string?)
end
end
elseif typ == 4 then
vorbisComment(b, p, e, info) -- a broken comment block leaves what was read
vorbisComment(b, p, e, info)
elseif typ == 6 then
local pic = picture(b, p, e)
if pic then
+4 -19
View File
@@ -1,11 +1,7 @@
--!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.
-- audio/flac/Stream: streaming FLAC decoder (native and Ogg FLAC); absorbed from flac-luau 7083d0d (same author).
local Bytes = require("@rosetta/core/Bytes")
local Ogg = require("@rosetta/containers/Ogg")
local Frame = require("@rosetta/codecs/audio/Flac/Frame")
@@ -41,12 +37,10 @@ export type Decoder = {
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
@@ -80,7 +74,6 @@ local function ensure(self: any, n: number)
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
@@ -114,7 +107,7 @@ local function pull(self: any, maxFrames: number, asInt: boolean, dst: buffer?):
local ch = self.channels
local want = math.floor(tonumber(maxFrames) or 0)
if not (want >= 0) then
want = 0 -- negative or NaN
want = 0
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
@@ -159,29 +152,23 @@ local function pull(self: any, maxFrames: number, asInt: boolean, dst: buffer?):
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
t = 0
end
if self.frames > 0 and t >= self.frames then
self._pos, self._fs, self._fn, self._cur = self._len, self.frames, 0, 0
@@ -228,7 +215,7 @@ function Dec.seekSample(self: any, t: number): boolean
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
return false
end
pos = self._pos
else
@@ -244,7 +231,6 @@ 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)
@@ -284,7 +270,6 @@ local function skipId3(b: buffer, base: number, len: number): number
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
+6 -21
View File
@@ -1,19 +1,7 @@
--!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
-- audio/flac: FLAC (RFC 9639), native and Ogg FLAC; absorbed from flac-luau 7083d0d (same author). Supports: every
-- subframe type, Rice / Rice2, 4-32 bits, 1-8 channels, CRC-16 resync, seeking, an ID3v2 prefix, the main metadata
-- blocks; encode levels 0-8 (libFLAC presets), 4-24 bits. Not supported: MD5 check on decode, chained Ogg, Ogg output.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -37,12 +25,12 @@ local Flac = {
-- ------------------------------------------------------------------------------------------------ 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)
crc16: boolean?, -- default true; a bad frame is skipped by resyncing
maxFrames: number?, -- 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)
bits: number?, -- 4..24; default the source's bit depth 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)
@@ -79,7 +67,6 @@ function Flac.sniff(r: Bytes.Reader): number
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
@@ -94,7 +81,6 @@ function Flac.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Er
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
@@ -139,7 +125,6 @@ function Flac.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
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)
+5 -13
View File
@@ -1,9 +1,7 @@
--!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.
-- audio/m4a: MPEG-4 audio (M4A / M4B / MP4 / MOV audio tracks) via containers/IsoBmff. Supports: AAC-LC (HE-AAC plays
-- its core), ALAC, edit-list gapless trimming, seeking, iTunes tags and cover art; encode ALAC (16 / 20 / 24-bit, 1-8
-- channels). Not supported: writing AAC, other codecs in MP4 (UNSUPPORTED), encrypted files.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -29,13 +27,13 @@ local M4a = {
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)
maxSamples: number?, -- 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)
pictures: { { mime: string, data: buffer } }?, -- default: audio.meta.pictures
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -57,7 +55,6 @@ function M4a.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- the packet decoder of a track: decode(buf, off, len) -> frames | nil, Err; pcm: interleaved floats
type PacketDecoder = {
channels: number,
sampleRate: number,
@@ -121,7 +118,6 @@ local function packetDecoder(t: IsoBmff.Track): (PacketDecoder?, Err.Err?)
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 })
@@ -155,7 +151,6 @@ function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E
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
@@ -219,7 +214,6 @@ function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E
})
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
@@ -234,7 +228,6 @@ function M4a.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.E
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
@@ -254,7 +247,6 @@ function M4a.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
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
+1 -6
View File
@@ -1,10 +1,7 @@
--!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.
-- audio/mp3/Index: the frame index as minimp3_ex's mp3dec_load_buf walks it, simulating the layer III bit reservoir.
local Header = require("@rosetta/codecs/audio/Mpa/Header")
local Core = require("@rosetta/codecs/audio/Mpa/Core")
@@ -29,7 +26,6 @@ export type Index = {
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,
@@ -89,7 +85,6 @@ function Index.build(b: buffer, start: number, stop: number): Index?
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
+2 -14
View File
@@ -1,7 +1,6 @@
--!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.
-- audio/mp3/Stream: streaming Decoder over the frame index (gapless, exact seeking); from mp3-luau (same author).
local Core = require("@rosetta/codecs/audio/Mpa/Core")
local Index = require("@rosetta/audio/mp3/Index")
@@ -44,7 +43,6 @@ export type Decoder = typeof(setmetatable(
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
@@ -92,7 +90,6 @@ function Stream.new(b: buffer, idx: any, tags: { [string]: string }, id3: any):
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
@@ -127,9 +124,6 @@ local function fill(self: Decoder): boolean
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
@@ -138,7 +132,7 @@ function Decoder.read(self: Decoder, maxFrames: number?, out: buffer?): (buffer,
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)
out = nil
end
local dst = out or buffer.create(want * ch * 4)
local got = 0
@@ -163,8 +157,6 @@ function Decoder.read(self: Decoder, maxFrames: number?, out: buffer?): (buffer,
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)
@@ -172,7 +164,6 @@ function Decoder.seek(self: Decoder, seconds: number)
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
@@ -190,7 +181,6 @@ function Decoder.seekFrame(self: Decoder, target: number)
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
@@ -218,12 +208,10 @@ function Decoder.seekFrame(self: Decoder, target: number)
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
+1 -8
View File
@@ -1,8 +1,6 @@
--!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.
-- audio/mp3/Tags: ID3v2.2-2.4 and ID3v1 / 1.1 tags (APEv2 skipped); the audio range as minimp3_ex's mp3dec_skip_id3.
local band, bor, lshift = bit32.band, bit32.bor, bit32.lshift
local ru8 = buffer.readu8
@@ -97,7 +95,6 @@ local function decodeText(b: buffer, i: number, j: number, enc: number): string
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+", " / ")
@@ -166,7 +163,6 @@ local function setField(tags: any, id: string, text: string)
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)
@@ -258,9 +254,6 @@ 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 = {} }
+5 -25
View File
@@ -1,18 +1,7 @@
--!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)
-- audio/mp3: MPEG audio layers I-III (ISO/IEC 11172-3, 13818-3, MPEG-2.5); absorbed from mp3-luau c755bbf, a port of
-- minimp3 by lieff (CC0: licenses/minimp3-CC0.txt). Supports: every mode, CBR / VBR / free format, Xing / LAME gapless,
-- exact seeking, ID3v2 / ID3v1 tags; encode layers III / II (CBR). Not supported: MPEG-2 multichannel, CRC, VBR output.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -39,7 +28,7 @@ local Mp3 = {
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
maxFrames: number?, -- refuse streams longer than this many sample frames per channel (default 2^31)
maxFrames: number?, -- default 2^31
}
export type Decoder = Stream.Decoder
export type EncodeOptions = {
@@ -58,7 +47,6 @@ export type EncodeOptions = {
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
@@ -87,7 +75,6 @@ function Mp3.sniff(r: Bytes.Reader): number
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
@@ -113,7 +100,6 @@ local ID3_FRAMES = {
{ "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 } = {}
@@ -162,7 +148,6 @@ local function id3Tag(tags: { [string]: any }): buffer?
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
@@ -174,8 +159,6 @@ function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
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)))
@@ -209,7 +192,6 @@ function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
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
@@ -234,7 +216,6 @@ function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
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
@@ -245,7 +226,6 @@ local function stringTags(t: any): { [string]: string }
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
@@ -273,6 +253,6 @@ function Mp3.open(r: Bytes.Reader, opts: OpenOptions?): (Decoder?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
Mp3.Tags = Tags -- Tags.parse(buf) -> (tags, audio start, audio end)
Mp3.Tags = Tags
return Mp3
+4 -8
View File
@@ -1,10 +1,7 @@
--!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.
-- audio/mpc: Musepack (.mpc / .mp+ / .mpp) SV7 and SV8 via codecs/audio/Musepack (a libmpcdec port). Supports: mono /
-- stereo, 32-48 kHz, gapless length, seeking (SV8 exact; SV7 with 32 frames of pre-roll, as libmpcdec), APEv2 tags,
-- an ID3v2 prefix, ReplayGain in meta. Not supported: writing, SV4-SV6 (UNSUPPORTED), chapters.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -27,11 +24,10 @@ local Mpc = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxFrames: number?, -- Err.LIMIT past this many output sample frames (default 2^31)
maxFrames: number?, -- 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
+2 -10
View File
@@ -1,9 +1,5 @@
--!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.
-- audio/opus/Encode: Ogg Opus writing (RFC 7845), CELT only (TOC config 31: full band, 20 ms, code 0), family 0.
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Ogg = require("@rosetta/containers/Ogg")
@@ -24,7 +20,6 @@ export type Options = {
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)
@@ -41,12 +36,11 @@ function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?)
end
local bitrate = o.bitrate or 64000 * ch
if type(bitrate) == "number" and bitrate > 0 and bitrate < 1000 then
bitrate *= 1000 -- kbit/s
bitrate *= 1000
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
@@ -68,7 +62,6 @@ function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?)
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
@@ -100,7 +93,6 @@ function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?)
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)
+6 -32
View File
@@ -1,22 +1,7 @@
--!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)
-- audio/opus: Ogg Opus (RFC 6716, RFC 7845); absorbed from opus-luau dd2b4e5, a port of the libopus 1.6 decoder (BSD:
-- licenses/libopus-BSD.txt). Supports: every mode / bandwidth / frame size, mapping families 0 / 1 / 255, seeking, PLC;
-- encode CELT only (20 ms, full band, CBR). Not supported: SILK / hybrid encoding, mapping family 3, chained streams.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -75,7 +60,7 @@ export type Head = {
mapping: { number },
}
-- OpusHead (RFC 7845 section 5.1). Returns the header or nil, message.
-- OpusHead (RFC 7845 section 5.1)
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"
@@ -127,8 +112,7 @@ local function parseHead(b: buffer, off: number, size: number): (Head?, string?)
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
-- OpusTags (RFC 7845 section 5.2)
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 "", {}, {}
@@ -173,7 +157,6 @@ 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
@@ -186,7 +169,6 @@ function Opus.sniff(r: Bytes.Reader): number
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
@@ -196,7 +178,6 @@ function Opus.decode(r: any, opts: OpenOptions?): (Types.Audio?, Err.Err?)
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
@@ -205,7 +186,6 @@ end
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
@@ -239,8 +219,6 @@ local function decodeNext(self: any): boolean
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
@@ -255,7 +233,6 @@ function Stream.read(self: any, maxFrames: number, into: buffer?): (buffer, numb
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))
@@ -280,17 +257,15 @@ function Stream.read(self: any, maxFrames: number, into: buffer?): (buffer, numb
buffer.copy(trimmed, 0, out, 0, got * ch * 4)
out = trimmed
end
self.endSample = self.next -- the stream ended early (truncated file)
self.endSample = self.next
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)
@@ -315,7 +290,6 @@ function Stream.seek(self: any, seconds: number)
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
+4 -11
View File
@@ -1,13 +1,7 @@
--!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)
-- audio/qoa: QOA "Quite OK Audio" via codecs/audio/Qoa (a port of qoa.h, phoboslab, MIT). Supports: static and
-- streaming files, 1-255 channels, rates up to 16777215 Hz, frame-accurate seeking; encode byte-for-byte as qoa_encode,
-- 1-8 channels. Not supported: channel count or rate changes mid-stream.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -29,7 +23,7 @@ local Qoa = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxFrames: number?, -- decode(): Err.LIMIT past this many sample frames (default 2^28)
maxFrames: number?, -- default 2^28
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -122,7 +116,6 @@ function Qoa.open(r: Bytes.Reader, _opts: any?): (Types.Decoder?, Err.Err?)
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
+4 -11
View File
@@ -1,11 +1,7 @@
--!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
-- audio/tta: True Audio (.tta, TTA1) via codecs/audio/Tta, from the TTA1 format description. Supports: 8 / 16 / 24
-- bits, any channel count, seeking by the seek table, APEv2 tags, an ID3v2 prefix. Not supported: password-protected
-- files, TTA2, ID3v2 contents, encoding.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -28,11 +24,10 @@ local Tta = {
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
maxFrames: number?, -- decode(): refuse longer streams (default 2^28)
maxFrames: number?, -- 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
@@ -54,7 +49,6 @@ function Tta.sniff(r: Bytes.Reader): number
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
@@ -69,7 +63,6 @@ function Tta.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err
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)
+5 -15
View File
@@ -1,16 +1,7 @@
--!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 } })
-- audio/vag: Sony VAG (PS-ADPCM: VAGp mono, VAGi stereo) and KVAG (IMA); layouts follow vgmstream r2117 (ISC,
-- licenses/vgmstream-LICENSE.txt), bit-exact, Sony's leading blank frame included. Supports: loop points; encode VAGp /
-- VAGi. Not supported: HEVAG (0x00020001 / 0x00030000), game-specific variants (pGAV, VAG1 / VAG2, Jak, ...).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -33,7 +24,7 @@ local Vag = {
-- ------------------------------------------------------------------------------------------------ types
export type Loop = { start: number, stop: number }
export type DecodeOptions = {
maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28)
maxFrames: number?, -- 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
@@ -144,8 +135,7 @@ function Vag.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
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
-- vgmstream's loop reading: channel 0's first start flag 6 and first end flag 3
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
+6 -11
View File
@@ -1,11 +1,7 @@
--!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).
-- audio/voc: Creative Voice File (.voc), from Creative's format description. Supports: block types 1, 2, 3, 5, 8, 9
-- (8 / 16-bit, A-law, mu-law); markers and repeats played once, as ffmpeg; truncated files; encode version 1.20 type 9
-- blocks. Not supported: Creative ADPCM, channel count changes mid-file (the first block's rate is used).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -24,7 +20,7 @@ local Voc = {
}
export type DecodeOptions = {
maxFrames: number?, -- refuse more sample frames (default 2^28)
maxFrames: number?, -- default 2^28
}
export type EncodeOptions = {
sampleFormat: ("u8" | "s16" | "alaw" | "ulaw")?, -- default "s16"
@@ -73,7 +69,6 @@ function Voc.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.E
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
@@ -177,7 +172,7 @@ function Voc.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.E
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
end
o += n * 4
end
a.tags = tags
@@ -238,7 +233,7 @@ function Voc.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
blockAt = w:tell()
blockFrames = 0
w:u8(9)
w:u24le(0) -- patched
w:u24le(0)
w:u32le(src.sampleRate)
w:u8(spec[3])
w:u8(src.channels)
+6 -22
View File
@@ -1,15 +1,8 @@
--!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.
-- audio/vorbis/Encode: Vorbis I encoder in Ogg, from the Vorbis I spec (no libvorbis code): long blocks only (2048),
-- one floor 1 per channel (30 posts), square-polar coupling, residue type 2, a fixed codebook set with Laplacian lengths.
local Mdct = require("@rosetta/codecs/audio/Mdct")
local Pcm = require("@rosetta/codecs/audio/Pcm")
local VorbisComment = require("@rosetta/codecs/audio/VorbisComment")
@@ -99,7 +92,6 @@ type Book = {
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
@@ -112,7 +104,6 @@ local function huffmanLengths(w: { number }): { number }
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
@@ -128,8 +119,8 @@ local function huffmanLengths(w: { number }): { number }
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 q1, h1 = order, 1
local q2, h2, t2 = table.create(n, 0), 1, 0
local nextId = n
local function pop(): number
local a = if h1 <= n then q1[h1] else nil
@@ -161,7 +152,7 @@ local function huffmanLengths(w: { number }): { number }
return lens
end
-- the spec's codeword assignment (lowest free leaf, in entry order); returns bit-reversed codes
-- the spec's codeword assignment (lowest free leaf, in entry order)
local function assign(lens: { number }): { number }
local codes = table.create(#lens, 0)
local available = table.create(33, 0)
@@ -208,7 +199,6 @@ local function makeBook(dims: number, entries: number, weight: (number) -> numbe
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
@@ -302,7 +292,6 @@ do
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
@@ -424,7 +413,7 @@ local function floorVal(Y: { number }, j: number): number
end
end
end
return 0 -- unreachable for t in range; fall back to the prediction
return 0
end
-- ------------------------------------------------------------------------------------------------ headers
@@ -559,7 +548,6 @@ export type Options = {
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
@@ -639,7 +627,6 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?)
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)
@@ -678,8 +665,6 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?)
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]
@@ -821,7 +806,6 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?)
return mux:finish(), nil
end
-- the codebooks (tests check the Huffman lengths are a valid prefix code)
Encode.BOOKS = BOOKS
return Encode
+4 -22
View File
@@ -1,15 +1,7 @@
--!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).
-- audio/vorbis: Ogg Vorbis (Vorbis I spec; RFC 5215); the decoder is a port of stb_vorbis 1.22 (public domain / MIT,
-- licenses/stb_vorbis-LICENSE.txt) with libvorbis' sample-exact trimming and seeking. Supports: 1-255 channels,
-- floor 1, residues 0-2, packetDecoder for Matroska / MP4; an encoder. Not supported: floor 0, chained streams.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -42,7 +34,6 @@ export type EncodeOptions = {
}
-- ------------------------------------------------------------------------------------------------ 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
@@ -55,7 +46,6 @@ local function waveOrder(ch: number): { number }
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
@@ -98,7 +88,6 @@ function Vorbis.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.
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
@@ -130,7 +119,6 @@ end
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
@@ -152,7 +140,6 @@ local function copyOut(self: any, count: number): { { number } }
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
@@ -251,7 +238,6 @@ 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()
@@ -430,11 +416,7 @@ function Vorbis.open(r: any, opts: OpenOptions?): (Types.Decoder?, Err.Err?)
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
-- raw Vorbis packets: Matroska / WebM / MP4 carry the three headers in their codec private data
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) }
+2 -11
View File
@@ -1,10 +1,7 @@
--!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.
-- audio/wav/Codecs: PCM / float / G.711 sample loops into interleaved f32 and back; absorbed from wav-luau fd9a909.
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
@@ -13,8 +10,7 @@ local writeu8, writeu16, writei16, writei32 = buffer.writeu8, buffer.writeu16, b
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.
-- integer PCM: 1 byte = unsigned, 2 / 3 / 4 bytes = signed
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
@@ -64,7 +60,6 @@ function Codecs.int(src: buffer, off: number, dst: buffer, d: number, count: num
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
@@ -95,7 +90,6 @@ function Codecs.float(src: buffer, off: number, dst: buffer, d: number, count: n
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
@@ -103,13 +97,10 @@ function Codecs.law(src: buffer, off: number, dst: buffer, d: number, count: num
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
+5 -29
View File
@@ -1,18 +1,8 @@
--!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" })
-- audio/wav: WAVE in RIFF / RIFX / RF64 / BW64; absorbed from wav-luau fd9a909 (same author). Supports: PCM 8-32 bit,
-- float 32 / 64, A-law, mu-law, IMA / MS ADPCM, EXTENSIBLE, LIST/INFO tags, data size 0 / 0xFFFFFFFF (to the end);
-- encode PCM and f32, EXTENSIBLE and RF64 as ffmpeg. Not supported: encoding ADPCM / A-law / mu-law / f64, RIFX output.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -36,14 +26,14 @@ local Wav = {
-- ------------------------------------------------------------------------------------------------ types
export type Tags = { [string]: string }
export type OpenOptions = {
maxBytes: number?, -- unused (the file is already in memory); kept for symmetry
maxBytes: number?,
}
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, ...)
tags: Tags?, -- default: the Audio's tags
rf64Threshold: number?, -- testing: the RIFF size past which "auto" switches to RF64 (default 0xFFFFFFFF)
}
@@ -144,7 +134,6 @@ export type Decoder = typeof(setmetatable(
))
local function trimTag(s: string): string
-- strip trailing NULs / spaces
local e = #s
while e > 0 do
local c = string.byte(s, e)
@@ -166,7 +155,6 @@ function Wav.sniff(r: Bytes.Reader): number
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
@@ -191,7 +179,6 @@ local GUID_TAIL = "\0\0\0\0\16\0\128\0\0\170\0\56\155\113" -- KSDATAFORMAT_SUBTY
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")
@@ -312,19 +299,15 @@ local function encodeParts(value: any, opts: EncodeOptions?, asParts: boolean):
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)
@@ -550,8 +533,6 @@ function Wav.open(r: Bytes.Reader, _opts: OpenOptions?): (Decoder?, Err.Err?)
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)
@@ -581,7 +562,6 @@ function Decoder.read(self: Decoder, maxFrames: number, out: buffer?): (buffer,
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
@@ -612,7 +592,6 @@ function Decoder.read(self: Decoder, maxFrames: number, out: buffer?): (buffer,
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
@@ -621,7 +600,6 @@ function Decoder.seek(self: Decoder, seconds: number)
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
@@ -630,12 +608,10 @@ function Decoder.seekFrame(self: Decoder, frame: number)
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
+6 -20
View File
@@ -1,17 +1,7 @@
--!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
-- audio/wavpack: WavPack (.wv) via codecs/audio/WavPack, from the WavPack 5 file format document and WavPack 5.9.0's
-- open_utils.c (BSD 3-clause, licenses/wavpack-LICENSE.txt). Supports: lossless and hybrid (lossy without the .wvc, as
-- wvunpack), 8-32-bit integer and float, 1-4096 channels, seeking, APEv2. Not supported: DSD, WavPack 1-3, encoding.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -35,9 +25,9 @@ local WavPack = {
-- ------------------------------------------------------------------------------------------------ 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)
resolve: ((uri: string) -> buffer?)?,
name: string?,
maxFrames: number?, -- default 2^28
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -50,7 +40,6 @@ function WavPack.sniff(r: Bytes.Reader): number
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
@@ -67,7 +56,6 @@ 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 }
@@ -142,7 +130,6 @@ local function correctionFile(opts: OpenOptions?): buffer?
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)
@@ -167,7 +154,6 @@ function WavPack.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err
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