ws-video: merge master (m4a, music, ...)

This commit is contained in:
4DBug committed 2026-10-31 09:50:42 -05:00
commit d79ddd5c08
118 files changed
+29274 -28

No files matched your search

+162 -6
View File
@@ -146,26 +146,86 @@ local list: { Entry } = {
return require("@formats/image/webp")
end,
},
{
name = "aac",
category = "audio",
path = "audio/aac",
extensions = { "aac", "adts" },
mime = { "audio/aac", "audio/aacp", "audio/x-aac" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac" },
caps = { decode = true, encode = false, codecs = { "aac" }, streaming = true },
load = function()
return require("@formats/audio/aac")
end,
},
{
name = "aiff",
category = "audio",
path = "audio/aiff",
extensions = { "aiff", "aif", "aifc", "afc" },
mime = { "audio/aiff", "audio/x-aiff" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false },
load = function()
return require("@formats/audio/aiff")
end,
},
{
name = "au",
category = "audio",
path = "audio/au",
extensions = { "au", "snd" },
mime = { "audio/basic", "audio/x-au" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false },
load = function()
return require("@formats/audio/au")
end,
},
{
name = "caf",
category = "audio",
path = "audio/caf",
extensions = { "caf", "caff" },
mime = { "audio/x-caf" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Alac" },
caps = { decode = true, encode = true, codecs = { "pcm", "alac", "aac", "ulaw", "alaw" }, encodeCodecs = { "pcm", "alac" }, tags = true, streaming = true },
load = function()
return require("@formats/audio/caf")
end,
},
{
name = "flac",
category = "audio",
path = "audio/flac",
extensions = { "flac", "oga" },
mime = { "audio/flac", "audio/x-flac" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" },
caps = { decode = true, encode = false, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm" },
caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true },
load = function()
return require("@formats/audio/flac")
end,
},
{
name = "m4a",
category = "audio",
path = "audio/m4a",
extensions = { "m4a", "m4b", "m4r" },
mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" },
deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/Aac", "codecs/Alac" },
caps = { decode = true, encode = true, codecs = { "aac", "alac" }, encodeCodecs = { "alac" }, tags = true, streaming = true },
load = function()
return require("@formats/audio/m4a")
end,
},
{
name = "mp3",
category = "audio",
path = "audio/mp3",
extensions = { "mp3", "mp2", "mp1", "mpga" },
mime = { "audio/mpeg", "audio/mp3", "audio/mpa" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = false, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 },
load = function()
return require("@formats/audio/mp3")
end,
@@ -176,12 +236,36 @@ local list: { Entry } = {
path = "audio/opus",
extensions = { "opus" },
mime = { "audio/opus", "audio/ogg" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" },
caps = { decode = true, encode = false, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 } },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct" },
caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" } },
load = function()
return require("@formats/audio/opus")
end,
},
{
name = "voc",
category = "audio",
path = "audio/voc",
extensions = { "voc" },
mime = { "audio/x-voc" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16 }, lossy = false },
load = function()
return require("@formats/audio/voc")
end,
},
{
name = "vorbis",
category = "audio",
path = "audio/vorbis",
extensions = { "ogg", "oga" },
mime = { "audio/ogg", "audio/vorbis" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/Pcm" },
caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255 },
load = function()
return require("@formats/audio/vorbis")
end,
},
{
name = "wav",
category = "audio",
@@ -662,6 +746,78 @@ local list: { Entry } = {
return require("@formats/subtitle/vtt")
end,
},
{
name = "it",
category = "music",
path = "music/it",
extensions = { "it" },
mime = { "audio/it", "audio/x-it" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" },
caps = { decode = true, encode = false, render = true, channels = { 1, 64 }, compressedSamples = true },
load = function()
return require("@formats/music/it")
end,
},
{
name = "midi",
category = "music",
path = "music/midi",
extensions = { "mid", "midi", "smf", "kar", "rmi" },
mime = { "audio/midi", "audio/x-midi" },
deps = { "core/Err", "core/Bytes", "codecs/SoundFont", "Types" },
caps = { decode = true, encode = true, formats = { 0, 1, 2 }, render = true, streaming = true, rmid = true },
load = function()
return require("@formats/music/midi")
end,
},
{
name = "mod",
category = "music",
path = "music/mod",
extensions = { "mod", "m15", "stk", "nst" },
mime = { "audio/x-mod", "audio/mod" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" },
caps = { decode = true, encode = true, render = true, channels = { 1, 32 } },
load = function()
return require("@formats/music/mod")
end,
},
{
name = "s3m",
category = "music",
path = "music/s3m",
extensions = { "s3m" },
mime = { "audio/s3m", "audio/x-s3m" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" },
caps = { decode = true, encode = false, render = true, channels = { 1, 32 } },
load = function()
return require("@formats/music/s3m")
end,
},
{
name = "sf2",
category = "music",
path = "music/sf2",
extensions = { "sf2" },
mime = { "audio/x-soundfont" },
deps = { "core/Err", "core/Bytes", "codecs/SoundFont" },
caps = { decode = true, encode = false, sm24 = true, sf3 = false },
load = function()
return require("@formats/music/sf2")
end,
},
{
name = "xm",
category = "music",
path = "music/xm",
extensions = { "xm" },
mime = { "audio/xm", "audio/x-xm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" },
caps = { decode = true, encode = true, render = true, channels = { 1, 64 } },
load = function()
return require("@formats/music/xm")
end,
},
{
name = "m3u",
category = "playlist",
+1
View File
@@ -154,6 +154,7 @@ export type Midi = {
division: number, -- ticks per quarter note (or SMPTE, negative)
tracks: { { events: { MidiEvent }, name: string? } },
meta: { [string]: any },
render: ((self: any, opts: any?) -> Decoder)?, -- set by music/midi decode: the SoundFont synth as an audio Decoder
}
local Midi = {}
function Midi.new(division: number?): Midi
+277
View File
@@ -0,0 +1,277 @@
--!strict
-- audio/aac: raw AAC in ADTS framing (ISO/IEC 13818-7 / 14496-3 1.A.3), the .aac files encoders and radio streams
-- write. Supports: reading AAC-LC through codecs/Aac (1 - 8 channels, every rate, multi-block frames, CRC-protected
-- headers skipped), a leading ID3v2 tag (skipped; its text frames become tags), resync after garbage, seeking (by
-- frame), HE-AAC streams play their AAC-LC core. Not supported: writing (AAC encoding is out of scope), ADIF, LATM.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Aac = require("@formats/codecs/Aac")
-- ------------------------------------------------------------------------------------------------ contract
local AacFormat = {
name = "aac",
category = "audio",
extensions = { "aac", "adts" },
mime = { "audio/aac", "audio/aacp", "audio/x-aac" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac" },
caps = { decode = true, encode = false, codecs = { "aac" }, streaming = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxFrames: number?, -- refuse streams with more ADTS frames (default 2^22)
}
-- ------------------------------------------------------------------------------------------------ constants
local readu8 = buffer.readu8
-- the size of an ID3v2 tag at p (0 if none)
local function id3Size(b: buffer, p: number, limit: number): number
if p + 10 > limit or buffer.readstring(b, p, 3) ~= "ID3" then
return 0
end
local s = 0
for i = 6, 9 do
s = s * 128 + bit32.band(readu8(b, p + i), 127)
end
local footer = if bit32.band(readu8(b, p + 5), 0x10) ~= 0 then 10 else 0
return 10 + s + footer
end
-- a few ID3v2.3 / 2.4 text frames -> tags
local ID3_TAGS: { [string]: string } = {
TIT2 = "title", TPE1 = "artist", TALB = "album", TYER = "date", TDRC = "date", TCON = "genre", TRCK = "track",
COMM = "comment", TCOM = "composer", TPE2 = "albumartist",
}
local function id3Tags(b: buffer, p: number, size: number): Types.Tags
local tags: Types.Tags = {}
local ver = readu8(b, p + 3)
if ver < 3 then
return tags
end
local q, stop = p + 10, p + size
while q + 10 <= stop do
local id = buffer.readstring(b, q, 4)
if not string.match(id, "^[A-Z0-9][A-Z0-9][A-Z0-9][A-Z0-9]$") then
break
end
local n = 0
for i = 4, 7 do
n = if ver == 4 then n * 128 + bit32.band(readu8(b, q + i), 127) else n * 256 + readu8(b, q + i)
end
if n < 1 or q + 10 + n > stop then
break
end
local key = ID3_TAGS[id]
local enc = readu8(b, q + 10)
if key and (enc == 0 or enc == 3) then
local s = buffer.readstring(b, q + 11, n - 1)
if id == "COMM" and #s > 3 then
s = string.sub(s, 4)
local z = string.find(s, "\0", 1, true)
if z then
s = string.sub(s, z + 1)
end
end
s = (string.gsub(s, "%z+$", ""))
tags[key] = s
end
q += 10 + n
end
return tags
end
-- ------------------------------------------------------------------------------------------------ sniff
function AacFormat.sniff(r: Bytes.Reader): number
local b, p, limit = r.buf, r.pos, r.limit
p += id3Size(b, p, limit)
local h = Aac.adts(b, p, limit)
if not h then
return 0
end
-- a second header right after the first makes it certain
local h2 = Aac.adts(b, p + h.frameSize, limit)
if h2 and h2.sfIndex == h.sfIndex and h2.channelConfig == h.channelConfig then
return 0.9
end
return if p + h.frameSize >= limit then 0.7 else 0.4
end
-- ------------------------------------------------------------------------------------------------ decode
-- the frame index: offsets of every ADTS frame (resyncing over garbage)
local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number }, Aac.Adts?, Err.Err?)
local b, limit = r.buf, r.limit
local p = r.base + id3Size(b, r.base, limit)
local offs, sizes = {}, {}
local first: Aac.Adts? = nil
while p + 7 <= limit do
local h = Aac.adts(b, p, limit)
if h and first and (h.sfIndex ~= first.sfIndex or h.channelConfig ~= first.channelConfig) then
h = nil -- a false sync inside the data
end
if not h then
p += 1
continue
end
if p + h.frameSize > limit then
break -- a truncated last frame
end
if not first then
first = h
end
if h.blocks ~= 1 then
return offs, sizes, first, Err.new(Err.UNSUPPORTED, "ADTS frames with " .. h.blocks .. " raw data blocks", p)
end
table.insert(offs, p + h.headerSize)
table.insert(sizes, h.frameSize - h.headerSize)
if #offs > maxFrames then
return offs, sizes, first, Err.new(Err.LIMIT, "more than " .. maxFrames .. " frames")
end
p += h.frameSize
end
return offs, sizes, first, nil
end
function AacFormat.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
local o = opts or {}
local offs, sizes, first, ierr = index(r, o.maxFrames or 2 ^ 22)
if ierr then
return nil, ierr
end
if not first then
return nil, Err.new(Err.CORRUPT, "no ADTS frame", r.base)
end
local h = first :: Aac.Adts
if h.objectType ~= 2 then
return nil, Err.new(Err.UNSUPPORTED, "ADTS profile " .. h.objectType .. " (only AAC-LC)")
end
if h.channelConfig == 0 then
return nil, Err.new(Err.UNSUPPORTED, "ADTS with a program config element (channel configuration 0)")
end
local channels = ({ 1, 2, 3, 4, 5, 6, 8 })[h.channelConfig] :: number
local dec, derr = Aac.decoder({ sfIndex = h.sfIndex, channels = channels, channelConfig = h.channelConfig })
if not dec then
return nil, derr
end
local d = dec :: Aac.Decoder
local sr = d.sampleRate
local nframes = #offs
local total = nframes * 1024
local bytes = 0
for _, s in sizes do
bytes += s
end
local id3 = id3Size(r.buf, r.base, r.limit)
local tags = if id3 > 0 then id3Tags(r.buf, r.base, id3) else {}
local buf = r.buf
local nextFrame = 1
local pendPos, pendN = 0, 0
local drop = 0
local pos = 0
local failed: Err.Err? = nil
local out: any = {
sampleRate = sr,
channels = channels,
frames = total,
duration = total / sr,
bitrate = if total > 0 then math.floor(bytes * 8 * sr / total) else 0,
tags = tags,
codec = "aac",
error = nil,
}
local function fill(): boolean
while true do
if nextFrame > nframes then
return false
end
local i = nextFrame
nextFrame += 1
local n, e = d:decode(buf, offs[i], sizes[i])
if not n then
failed = e
out.error = e
return false
end
if drop >= n then
drop -= n
else
pendPos, pendN = drop, n
drop = 0
return true
end
end
end
function out.read(_self: any, n: number, ob: buffer?): (buffer, number)
local want = math.max(0, math.floor(n))
local need = want * channels * 4
local res = if ob and buffer.len(ob) >= need then ob else buffer.create(need)
local got = 0
local writef32 = buffer.writef32
while got < want do
if pendPos >= pendN then
if failed or not fill() then
break
end
end
local take = math.min(want - got, pendN - pendPos)
local src = d.pcm
local q = got * channels * 4
local s = pendPos * channels
for k = 1, take * channels do
writef32(res, q, src[s + k])
q += 4
end
pendPos += take
got += take
end
pos += got
return res, got
end
function out.seek(_self: any, seconds: number)
local target = math.clamp(math.floor(seconds * sr + 0.5), 0, total)
local f = target // 1024 -- frame holding the target (0-based)
local start = math.max(0, f - 1) -- one frame of pre-roll for the overlap
d:reset()
nextFrame = start + 1
drop = target - start * 1024
pendPos, pendN = 0, 0
failed = nil
pos = target
end
function out.position(_self: any): number
return pos / sr
end
if nframes > 0 and not fill() and failed then
return nil, failed
end
return out, nil
end
function AacFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
local dec, err = AacFormat.open(r, opts)
if not dec then
return nil, err
end
local d: any = dec
local audio = Types.Audio.new(d.sampleRate, d.channels, d.frames)
local done = 0
while done < d.frames do
local b, n = d:read(math.min(65536, d.frames - done))
if n == 0 then
break
end
buffer.copy(audio.samples, done * d.channels * 4, b, 0, n * d.channels * 4)
done += n
end
if d.error then
return nil, d.error
end
audio.tags = d.tags
audio.meta.source = { format = "aac", codec = "aac", bitrate = d.bitrate }
return audio, nil
end
return AacFormat
+384
View File
@@ -0,0 +1,384 @@
--!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. Not supported: compressed AIFF-C codecs (ima4, MAC3 /
-- MAC6, Qclp, ...: Err.UNSUPPORTED), MARK / INST loops (ignored), the ID3 chunk.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Pcm = require("@formats/codecs/Pcm")
-- ------------------------------------------------------------------------------------------------ contract
local Aiff = {
name = "aiff",
category = "audio",
extensions = { "aiff", "aif", "aifc", "afc" },
mime = { "audio/aiff", "audio/x-aiff" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false },
}
export type DecodeOptions = {
maxFrames: number?, -- refuse more sample frames (default 2^28)
}
export type EncodeOptions = {
sampleFormat: ("s8" | "s16" | "s24" | "s32" | "f32" | "f64" | "ulaw" | "alaw")?, -- default "s16"
littleEndian: boolean?, -- 16-bit samples as AIFF-C "sowt" (default false: big endian; readers such as ffmpeg only
-- take 16-bit sowt, so other formats return Err.ARG)
aifc: boolean?, -- always write AIFF-C (default: only when the sample format needs it)
}
-- ------------------------------------------------------------------------------------------------ constants
local TEXT_TAGS = { NAME = "title", AUTH = "artist", ["(c) "] = "copyright", ANNO = "comment" }
local TEXT_ORDER = { { "NAME", "title" }, { "AUTH", "artist" }, { "(c) ", "copyright" }, { "ANNO", "comment" } }
local AIFC_VERSION = 0xA2805140
-- ext80(b, o) -> the 80-bit IEEE extended float at b[o] (big endian)
local function ext80(b: buffer, o: number): number
local se = buffer.readu8(b, o) * 256 + buffer.readu8(b, o + 1)
local hi = bit32.byteswap(buffer.readu32(b, o + 2))
local lo = bit32.byteswap(buffer.readu32(b, o + 6))
local e = bit32.band(se, 0x7FFF)
if e == 0 and hi == 0 and lo == 0 then
return 0
end
if e == 0x7FFF then
return math.huge
end
local v = (hi * 4294967296 + lo) * 2 ^ (e - 16383 - 63)
return if se >= 0x8000 then -v else v
end
-- the 10 bytes of x (> 0) as an 80-bit extended float
local function writeExt80(w: Bytes.Writer, x: number)
if x <= 0 or x ~= x then
w:fill(0, 10)
return
end
local e = 0
while x >= 2 ^ (e + 1) do
e += 1
end
while x < 2 ^ e do
e -= 1
end
local m = x * 2 ^ (63 - e) -- in [2^63, 2^64)
local hi = math.floor(m / 4294967296)
local lo = m - hi * 4294967296
w:u16be(e + 16383)
w:u32be(hi)
w:u32be(math.floor(lo))
end
-- the sample format of a COMM chunk: Pcm format name | nil, message
local function sampleFormat(comp: string, bits: number): (string?, string?)
if comp == "NONE" or comp == "twos" or comp == "" then
if bits >= 1 and bits <= 8 then
return "s8"
elseif bits <= 16 then
return "s16be"
elseif bits <= 24 then
return "s24be"
elseif bits <= 32 then
return "s32be"
end
return nil, "bad sample size " .. bits
elseif comp == "sowt" then
if bits >= 1 and bits <= 8 then
return "s8"
elseif bits <= 16 then
return "s16le"
elseif bits <= 24 then
return "s24le"
elseif bits <= 32 then
return "s32le"
end
return nil, "bad sample size " .. bits
elseif comp == "raw " then
return "u8"
elseif comp == "in24" then
return "s24be"
elseif comp == "in32" then
return "s32be"
elseif comp == "42ni" then
return "s32le"
elseif comp == "fl32" or comp == "FL32" then
return "f32be"
elseif comp == "fl64" or comp == "FL64" then
return "f64be"
elseif comp == "ulaw" or comp == "ULAW" then
return "ulaw"
elseif comp == "alaw" or comp == "ALAW" then
return "alaw"
end
return nil, "compression " .. string.format("%q", comp)
end
-- ------------------------------------------------------------------------------------------------ sniff
function Aiff.sniff(r: Bytes.Reader): number
if r:remaining() < 12 or r:peek(4) ~= "FORM" then
return 0
end
local form = buffer.readstring(r.buf, r.pos + 8, 4)
return if form == "AIFF" or form == "AIFC" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
type Info = {
channels: number,
frames: number,
sampleRate: number,
bits: number,
format: string,
compression: string,
aifc: boolean,
dataOffset: number, -- absolute in r.buf
truncated: boolean,
tags: Types.Tags,
}
-- parse(r) -> Info | nil, Err (walks the chunks; does not decode samples)
local function parse(r: Bytes.Reader): (Info?, Err.Err?)
local b = r.buf
local base, limit = r.base, r.limit
if limit - base < 12 or buffer.readstring(b, base, 4) ~= "FORM" then
return nil, Err.new(Err.CORRUPT, "not a FORM file", base)
end
local form = buffer.readstring(b, base + 8, 4)
if form ~= "AIFF" and form ~= "AIFC" then
return nil, Err.new(Err.CORRUPT, "FORM type " .. string.format("%q", form) .. " is not AIFF / AIFC", base + 8)
end
local aifc = form == "AIFC"
local formEnd = math.min(limit, base + 8 + bit32.byteswap(buffer.readu32(b, base + 4)))
local info: Info? = nil
local comm = false
local ssnd: number? = nil
local ssndLen = 0
local tags: Types.Tags = {}
local p = base + 12
while p + 8 <= formEnd do
local id = buffer.readstring(b, p, 4)
local len = bit32.byteswap(buffer.readu32(b, p + 4))
local d = p + 8
local avail = math.min(len, limit - d)
if id == "COMM" then
if avail < 18 or (aifc and avail < 22) then
return nil, Err.new(Err.TRUNCATED, "COMM chunk too short", p)
end
local ch = buffer.readu8(b, d) * 256 + buffer.readu8(b, d + 1)
local frames = bit32.byteswap(buffer.readu32(b, d + 2))
local bits = buffer.readu8(b, d + 6) * 256 + buffer.readu8(b, d + 7)
local rate = ext80(b, d + 8)
local comp = if aifc then buffer.readstring(b, d + 18, 4) else "NONE"
if ch < 1 then
return nil, Err.new(Err.CORRUPT, "no channels", d)
end
if not (rate > 0 and rate < 2 ^ 31) then
return nil, Err.new(Err.CORRUPT, "bad sample rate", d + 8)
end
local fmt, why = sampleFormat(comp, bits)
if not fmt then
return nil, Err.new(if comp == "NONE" or comp == "twos" or comp == "sowt" then Err.CORRUPT else Err.UNSUPPORTED, why :: string, d + 18)
end
info = {
channels = ch,
frames = frames,
sampleRate = rate,
bits = bits,
format = fmt,
compression = comp,
aifc = aifc,
dataOffset = 0,
truncated = false,
tags = tags,
}
comm = true
elseif id == "SSND" then
if avail < 8 then
return nil, Err.new(Err.TRUNCATED, "SSND chunk too short", p)
end
local off = bit32.byteswap(buffer.readu32(b, d))
ssnd = d + 8 + off
ssndLen = math.max(0, avail - 8 - off)
if len >= 8 + off then
ssndLen = math.min(ssndLen, len - 8 - off)
end
elseif TEXT_TAGS[id] then
local s = buffer.readstring(b, d, avail)
local z = string.find(s, "\0", 1, true)
if z then
s = string.sub(s, 1, z - 1)
end
local key = TEXT_TAGS[id]
tags[key] = if tags[key] then tags[key] .. "\n" .. s else s
end
if len > formEnd - d then
break
end
p = d + len + len % 2
end
if not comm or not info then
return nil, Err.new(Err.CORRUPT, "no COMM chunk", base)
end
local fi = info :: Info
if fi.frames > 0 and not ssnd then
return nil, Err.new(Err.TRUNCATED, "no SSND chunk", base)
end
local frameBytes = fi.channels * Pcm.Convert.SIZE[fi.format]
local present = if ssnd then ssndLen // frameBytes else 0
if present < fi.frames then
fi.frames = present
fi.truncated = true
end
fi.dataOffset = ssnd or base
return fi, nil
end
-- info(r) -> { channels, frames, sampleRate, bits, format, compression, aifc, tags } | nil, Err
function Aiff.info(r: Bytes.Reader): (Info?, Err.Err?)
return parse(r)
end
function Aiff.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
local dec, err = Aiff.open(r, opts)
if not dec then
return nil, err
end
local d = dec :: any
local a = Types.Audio.new(d.sampleRate, d.channels, d.frames)
d:read(d.frames, a.samples)
a.tags = d.tags
a.meta.source = d.source
return a, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local FORMATS = {
s8 = { "s8", 8, "NONE" },
s16 = { "s16be", 16, "NONE" },
s24 = { "s24be", 24, "NONE" },
s32 = { "s32be", 32, "NONE" },
f32 = { "f32be", 32, "fl32" },
f64 = { "f64be", 64, "fl64" },
ulaw = { "ulaw", 16, "ulaw" },
alaw = { "alaw", 16, "alaw" },
}
local LE = { s16be = "s16le" }
local COMP_NAMES = { NONE = "not compressed", sowt = "", fl32 = "32-bit floating point", fl64 = "64-bit floating point", ulaw = "\181Law 2:1", alaw = "ALaw 2:1" }
function Aiff.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local src, serr = Pcm.source(value)
if not src then
return nil, serr
end
local o: EncodeOptions = opts or {}
local spec = FORMATS[o.sampleFormat or "s16"]
if not spec then
return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat))
end
local fmt, bits, comp = spec[1], spec[2], spec[3]
if o.littleEndian then
if not LE[fmt] then
return nil, Err.new(Err.ARG, "littleEndian needs 16-bit samples")
end
fmt, comp = LE[fmt], "sowt"
end
if src.channels > 65535 then
return nil, Err.new(Err.ARG, "too many channels")
end
local aifc = o.aifc or comp ~= "NONE"
local w = Bytes.writer(65536)
w:string("FORM")
w:u32be(0) -- patched
w:string(if aifc then "AIFC" else "AIFF")
if aifc then
w:string("FVER")
w:u32be(4)
w:u32be(AIFC_VERSION)
end
-- text chunks from the tags
for _, pair in TEXT_ORDER do
local id, key = pair[1], pair[2]
local s = src.tags[key]
if type(s) == "string" and #s > 0 then
w:string(id)
w:u32be(#s)
w:string(s)
if #s % 2 == 1 then
w:u8(0)
end
end
end
local commAt = w:tell()
w:string("COMM")
if aifc then
local name = COMP_NAMES[comp] or ""
local plen = 1 + #name
plen += plen % 2
w:u32be(22 + plen)
else
w:u32be(18)
end
w:u16be(src.channels)
w:u32be(0) -- frames, patched
w:u16be(bits)
writeExt80(w, src.sampleRate)
if aifc then
w:string(comp)
local name = COMP_NAMES[comp] or ""
w:u8(#name)
w:string(name)
if (1 + #name) % 2 == 1 then
w:u8(0)
end
end
local ssndAt = w:tell()
w:string("SSND")
w:u32be(0) -- patched
w:u32be(0) -- offset
w:u32be(0) -- block size
local frames, perr = Pcm.encode(src, fmt, w)
if not frames then
return nil, perr
end
local dataLen = w:tell() - ssndAt - 16
if dataLen % 2 == 1 then
w:u8(0)
end
w:setU32be(ssndAt + 4, dataLen + 8)
w:setU32be(commAt + 10, frames)
w:setU32be(4, w:tell() - 8)
return w:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ open
function Aiff.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
local info, err = parse(r)
if not info then
return nil, err
end
local maxFrames = opts and opts.maxFrames or 2 ^ 28
if info.frames > maxFrames then
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the %d frame limit", info.frames, maxFrames))
end
local dec, derr = Pcm.rawDecoder(r.buf, info.dataOffset, info.frames, info.channels, info.sampleRate, info.format, info.tags)
if not dec then
return nil, derr
end
local d = dec :: any
d.source = {
format = "aiff",
aifc = info.aifc,
compression = info.compression,
bitDepth = info.bits,
sampleFormat = info.format,
truncated = info.truncated or nil,
}
return dec, nil
end
return Aiff
+166
View File
@@ -0,0 +1,166 @@
--!strict
-- audio/au: Sun / NeXT audio (.au / .snd), big endian. New code from the Sun audio file format description.
-- Supports: decode / open of encodings 1 (G.711 mu-law), 2 (8-bit), 3 (16-bit), 4 (24-bit), 5 (32-bit linear),
-- 6 (32-bit float), 7 (64-bit float), 27 (G.711 A-law); an unknown data size (0xFFFFFFFF: to the end of the file);
-- the annotation as tags.comment. Encode (Audio or Decoder, streamed) to any of those encodings (default 16-bit).
-- Not supported: G.721 / G.722 / G.723 ADPCM and the other NeXT encodings (Err.UNSUPPORTED).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Pcm = require("@formats/codecs/Pcm")
-- ------------------------------------------------------------------------------------------------ contract
local Au = {
name = "au",
category = "audio",
extensions = { "au", "snd" },
mime = { "audio/basic", "audio/x-au" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false },
}
export type DecodeOptions = {
maxFrames: number?, -- refuse more sample frames (default 2^28)
}
export type EncodeOptions = {
sampleFormat: ("s8" | "s16" | "s24" | "s32" | "f32" | "f64" | "ulaw" | "alaw")?, -- default "s16"
}
-- ------------------------------------------------------------------------------------------------ constants
local ENCODINGS: { [number]: string } = {
[1] = "ulaw",
[2] = "s8",
[3] = "s16be",
[4] = "s24be",
[5] = "s32be",
[6] = "f32be",
[7] = "f64be",
[27] = "alaw",
}
local WRITE = {
ulaw = { 1, "ulaw" },
s8 = { 2, "s8" },
s16 = { 3, "s16be" },
s24 = { 4, "s24be" },
s32 = { 5, "s32be" },
f32 = { 6, "f32be" },
f64 = { 7, "f64be" },
alaw = { 27, "alaw" },
}
local BITS = { ulaw = 8, alaw = 8, s8 = 8, s16be = 16, s24be = 24, s32be = 32, f32be = 32, f64be = 64 }
local function be32(b: buffer, o: number): number
return bit32.byteswap(buffer.readu32(b, o))
end
-- ------------------------------------------------------------------------------------------------ sniff
function Au.sniff(r: Bytes.Reader): number
return if r:peek(4) == ".snd" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Au.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
local dec, err = Au.open(r, opts)
if not dec then
return nil, err
end
local d = dec :: any
local a = Types.Audio.new(d.sampleRate, d.channels, d.frames)
d:read(d.frames, a.samples)
a.tags = d.tags
a.meta.source = d.source
return a, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Au.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local src, serr = Pcm.source(value)
if not src then
return nil, serr
end
local o: EncodeOptions = opts or {}
local spec = WRITE[o.sampleFormat or "s16"]
if not spec then
return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat))
end
if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate >= 2 ^ 32 then
return nil, Err.new(Err.ARG, "the sample rate must be an integer")
end
-- annotation: the comment tag, NUL-terminated, padded to a multiple of 8 (at least 4 bytes, as Sun requires)
local note = if type(src.tags.comment) == "string" then src.tags.comment else ""
local alen = #note + 1
alen = math.max(8, alen + (8 - alen % 8) % 8)
local w = Bytes.writer(65536)
w:string(".snd")
w:u32be(24 + alen)
w:u32be(0xFFFFFFFF) -- patched
w:u32be(spec[1])
w:u32be(src.sampleRate)
w:u32be(src.channels)
w:string(note)
w:fill(0, alen - #note)
local frames, perr = Pcm.encode(src, spec[2], w)
if not frames then
return nil, perr
end
w:setU32be(8, w:tell() - 24 - alen)
return w:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ open
function Au.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
local b, base, limit = r.buf, r.base, r.limit
if limit - base < 24 or buffer.readstring(b, base, 4) ~= ".snd" then
return nil, Err.new(Err.CORRUPT, "bad magic", base)
end
local off, size, enc, rate, ch = be32(b, base + 4), be32(b, base + 8), be32(b, base + 12), be32(b, base + 16), be32(b, base + 20)
local fmt = ENCODINGS[enc]
if not fmt then
return nil, Err.new(Err.UNSUPPORTED, "encoding " .. enc, base + 12)
end
if ch < 1 or ch > 65535 then
return nil, Err.new(Err.CORRUPT, "bad channel count " .. ch, base + 20)
end
if rate < 1 then
return nil, Err.new(Err.CORRUPT, "bad sample rate", base + 16)
end
if off < 24 or off > limit - base then
return nil, Err.new(Err.CORRUPT, "bad data offset", base + 4)
end
local tags: Types.Tags = {}
if off > 24 then
local s = buffer.readstring(b, base + 24, off - 24)
local z = string.find(s, "\0", 1, true)
if z then
s = string.sub(s, 1, z - 1)
end
if #s > 0 then
tags.comment = s
end
end
local avail = limit - base - off
local truncated = false
if size == 0xFFFFFFFF then
size = avail
elseif size > avail then
size = avail
truncated = true
end
local frameBytes = ch * Pcm.Convert.SIZE[fmt]
local frames = size // frameBytes
local maxFrames = opts and opts.maxFrames or 2 ^ 28
if frames > maxFrames then
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the %d frame limit", frames, maxFrames))
end
local dec, derr = Pcm.rawDecoder(b, base + off, frames, ch, rate, fmt, tags)
if not dec then
return nil, derr
end
local d = dec :: any
d.source = { format = "au", encoding = enc, sampleFormat = fmt, bitDepth = BITS[fmt], truncated = truncated or nil }
return dec, nil
end
return Au
+746
View File
@@ -0,0 +1,746 @@
--!strict
-- audio/caf: Apple Core Audio Format (CAF 1.0, Apple's "Core Audio Format Specification"). Supports reading linear
-- PCM (8 / 16 / 24 / 32-bit integer, 32 / 64-bit float, big / little endian), ALAC (codecs/Alac), AAC-LC (codecs/Aac,
-- kuki esds), mu-law and A-law; the packet table (pakt) with priming / remainder trimming, a data chunk of unknown
-- size (-1), info chunk tags; seeking. Writing linear PCM (16 / 24-bit big endian, 32-bit float) and ALAC (16 / 20 /
-- 24-bit) with info tags. Not supported: IMA4, other compressed formats (UNSUPPORTED).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Aac = require("@formats/codecs/Aac")
local Alac = require("@formats/codecs/Alac")
-- ------------------------------------------------------------------------------------------------ contract
local Caf = {
name = "caf",
category = "audio",
extensions = { "caf", "caff" },
mime = { "audio/x-caf" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Alac" },
caps = { decode = true, encode = true, codecs = { "pcm", "alac", "aac", "ulaw", "alaw" }, encodeCodecs = { "pcm", "alac" }, tags = true, streaming = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxPackets: number?, -- packet table limit (default 2^24)
}
export type EncodeOptions = {
codec: ("pcm" | "alac")?, -- default "alac"
bitDepth: number?, -- pcm: 16 (default), 24, 32 (float); alac: 16 (default), 20, 24
tags: Types.Tags?, -- default: the audio's tags
}
-- ------------------------------------------------------------------------------------------------ constants
local INFO_TAGS: { [string]: string } = {
title = "title", artist = "artist", album = "album", year = "date", genre = "genre", ["track number"] = "track",
comments = "comment", composer = "composer", copyright = "copyright", lyricist = "lyricist",
["encoding application"] = "encoder", ["recorded date"] = "recorded", tempo = "bpm",
}
local TAG_INFO: { [string]: string } = {}
for k, v in INFO_TAGS do
TAG_INFO[v] = k
end
-- mu-law / A-law -> linear 16-bit
local ULAW, ALAW = table.create(256, 0), table.create(256, 0)
for i = 0, 255 do
local u = 255 - i
local t = (bit32.band(u, 15) * 8 + 132) * 2 ^ bit32.band(bit32.rshift(u, 4), 7)
ULAW[i + 1] = if bit32.band(u, 128) ~= 0 then 132 - t else t - 132
local a = bit32.bxor(i, 0x55)
local seg = bit32.band(bit32.rshift(a, 4), 7)
local m = bit32.band(a, 15) * 16 + 8
if seg > 0 then
m = (m + 256) * 2 ^ (seg - 1)
end
ALAW[i + 1] = if bit32.band(a, 128) ~= 0 then m else -m
end
-- ------------------------------------------------------------------------------------------------ sniff
function Caf.sniff(r: Bytes.Reader): number
local h = r:peek(8)
if #h == 8 and string.sub(h, 1, 4) == "caff" and string.byte(h, 5) == 0 and string.byte(h, 6) == 1 then
return 1
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
type Desc = { rate: number, format: string, flags: number, bytesPerPacket: number, framesPerPacket: number, channels: number, bits: number }
type Parsed = {
desc: Desc,
dataStart: number, -- absolute offset of the audio data
dataEnd: number,
cookie: buffer?,
packets: { number }?, -- sizes (pakt)
packetFrames: { number }?,
priming: number,
remainder: number,
validFrames: number?,
tags: Types.Tags,
}
-- the esds payload in a kuki (version / flags, then the ES_Descriptor) -> the DecoderSpecificInfo
local function esdsConfig(b: buffer): buffer?
local r = Bytes.reader(b)
if r:peekU8() ~= 3 then
r:skip(4) -- the esds atom's version / flags
end
local function len(): number
local n = 0
for _ = 1, 4 do
local c = r:u8()
n = n * 128 + bit32.band(c, 127)
if c < 128 then
break
end
end
return n
end
while not r:eof() and not r.err do
local tag = r:u8()
local n = len()
if tag == 3 then
r:skip(2)
local f = r:u8()
if bit32.band(f, 0x80) ~= 0 then
r:skip(2)
end
if bit32.band(f, 0x40) ~= 0 then
r:skip(r:u8())
end
if bit32.band(f, 0x20) ~= 0 then
r:skip(2)
end
elseif tag == 4 then
r:skip(13)
elseif tag == 5 then
if n > 0 and r:need(n) then
return r:bytes(n)
end
return nil
else
r:skip(n)
end
end
return nil
end
local function vlq(r: Bytes.Reader): number
local v = 0
for _ = 1, 8 do
local c = r:u8()
v = v * 128 + bit32.band(c, 127)
if c < 128 then
return v
end
end
r:fail(Err.CORRUPT, "bad packet table entry")
return 0
end
local function parse(r: Bytes.Reader, o: DecodeOptions): (Parsed?, Err.Err?)
if Caf.sniff(r) == 0 then
return nil, Err.new(Err.CORRUPT, "not a CAF file", r.base)
end
r:seek(8)
local p: Parsed = { desc = nil :: any, dataStart = 0, dataEnd = 0, priming = 0, remainder = 0, tags = {} }
local haveData = false
while r:remaining() >= 12 do
local typ = r:string(4)
local size = r:i64be()
local start = r.pos
if size == -1 and typ == "data" then
size = r.limit - start
end
if size < 0 then
return nil, Err.new(Err.CORRUPT, "bad chunk size", start - 12)
end
local stop = start + size
if stop > r.limit then
if typ ~= "data" then
return nil, Err.new(Err.TRUNCATED, "chunk '" .. typ .. "' runs past the end", start - 12)
end
stop = r.limit -- a truncated data chunk: play what is there
end
local c = Bytes.reader(r.buf, start, stop - start)
if typ == "desc" then
p.desc = {
rate = c:f64be(),
format = c:string(4),
flags = c:u32be(),
bytesPerPacket = c:u32be(),
framesPerPacket = c:u32be(),
channels = c:u32be(),
bits = c:u32be(),
}
if c.err then
return nil, c.err
end
elseif typ == "data" then
p.dataStart = start + 4 -- edit count
p.dataEnd = stop
haveData = true
elseif typ == "kuki" then
p.cookie = c:bytes(stop - start)
elseif typ == "pakt" then
local n = c:i64be()
p.validFrames = c:i64be()
p.priming = c:i32be()
p.remainder = c:i32be()
if c.err then
return nil, c.err
end
if n < 0 or n > (o.maxPackets or 2 ^ 24) or n > c:remaining() then
return nil, Err.new(Err.LIMIT, "packet table of " .. n .. " entries", start)
end
local d = p.desc
if not d then
return nil, Err.new(Err.CORRUPT, "pakt before desc", start)
end
local sizes, frames = table.create(n, 0), nil
if d.framesPerPacket == 0 then
frames = table.create(n, 0)
end
for i = 1, n do
sizes[i] = if d.bytesPerPacket == 0 then vlq(c) else d.bytesPerPacket
if frames then
frames[i] = vlq(c)
end
end
if c.err then
return nil, c.err
end
p.packets, p.packetFrames = sizes, frames
elseif typ == "info" then
local n = c:u32be()
for _ = 1, math.min(n, 1000) do
local k = c:cstring()
local v = c:cstring()
if c.err then
break
end
p.tags[INFO_TAGS[string.lower(k)] or k] = v
end
end
r.pos = stop
if typ == "data" and stop >= r.limit then
break
end
end
if not p.desc then
return nil, Err.new(Err.CORRUPT, "no desc chunk", r.base)
end
if not haveData then
return nil, Err.new(Err.CORRUPT, "no data chunk", r.base)
end
local d = p.desc
if d.channels < 1 or d.channels > 64 or d.rate <= 0 or d.rate ~= d.rate or d.rate > 1e7 then
return nil, Err.new(Err.CORRUPT, "bad stream description")
end
return p, nil
end
-- the packet decoder: decode(i) -> frames into pcm (interleaved floats) | nil, Err
type Source = {
channels: number,
rate: number,
packetCount: number,
packetFrames: (number) -> number,
decode: (number) -> (number?, Err.Err?),
pcm: { number },
reset: () -> (),
codec: string,
bits: number?,
}
local function source(r: Bytes.Reader, p: Parsed): (Source?, Err.Err?)
local d = p.desc
local b = r.buf
local ch = d.channels
local fmt = d.format
if fmt == "lpcm" or fmt == "ulaw" or fmt == "alaw" then
local bits = if fmt == "lpcm" then d.bits else 8
local float = fmt == "lpcm" and bit32.band(d.flags, 1) ~= 0
local little = fmt == "lpcm" and bit32.band(d.flags, 2) ~= 0
local bpf = d.bytesPerPacket
if bpf == 0 then
bpf = ch * (bits // 8)
end
if not (bits == 8 or bits == 16 or bits == 24 or bits == 32 or (bits == 64 and float)) or (float and bits < 32) then
return nil, Err.new(Err.UNSUPPORTED, "linear PCM with " .. bits .. " bits")
end
local bps = bits // 8
if bpf < ch * bps then
return nil, Err.new(Err.CORRUPT, "bytes per packet smaller than a frame")
end
local total = (p.dataEnd - p.dataStart) // bpf
local per = 1024
local pcm = table.create(per * ch, 0)
local scale = 1 / 2 ^ (bits - 1)
local readu8, readi8 = buffer.readu8, buffer.readi8
local src: Source = {
channels = ch,
rate = d.rate,
packetCount = (total + per - 1) // per,
packetFrames = function(i: number): number
return math.min(per, total - (i - 1) * per)
end,
pcm = pcm,
reset = function() end,
codec = if fmt == "lpcm" then "pcm" else fmt,
bits = bits,
decode = function(i: number): (number?, Err.Err?)
local f0 = (i - 1) * per
local n = math.min(per, total - f0)
local k = 1
for f = f0, f0 + n - 1 do
local q = p.dataStart + f * bpf
for _ = 1, ch do
local v
if fmt == "ulaw" then
v = ULAW[readu8(b, q) + 1] / 32768
elseif fmt == "alaw" then
v = ALAW[readu8(b, q) + 1] / 32768
elseif float then
if bits == 32 then
v = if little then buffer.readf32(b, q) else Bytes.reader(b, q, 4):f32be()
else
v = if little then buffer.readf64(b, q) else Bytes.reader(b, q, 8):f64be()
end
elseif bits == 8 then
v = readi8(b, q) * scale
elseif bits == 16 then
v = if little then buffer.readi16(b, q) else readi8(b, q) * 256 + readu8(b, q + 1)
v *= scale
elseif bits == 24 then
if little then
v = readi8(b, q + 2) * 65536 + readu8(b, q + 1) * 256 + readu8(b, q)
else
v = readi8(b, q) * 65536 + readu8(b, q + 1) * 256 + readu8(b, q + 2)
end
v *= scale
else
if little then
v = buffer.readi32(b, q)
else
v = readi8(b, q) * 16777216 + readu8(b, q + 1) * 65536 + readu8(b, q + 2) * 256 + readu8(b, q + 3)
end
v *= scale
end
pcm[k] = v
k += 1
q += bps
end
end
return n, nil
end,
}
return src, nil
end
-- packetised codecs
local sizes = p.packets
if not sizes then
if d.bytesPerPacket > 0 then
local n = (p.dataEnd - p.dataStart) // d.bytesPerPacket
sizes = table.create(n, d.bytesPerPacket)
else
return nil, Err.new(Err.CORRUPT, "compressed CAF without a packet table")
end
end
local offsets = table.create(#sizes, 0)
local o = p.dataStart
for i, s in sizes :: { number } do
offsets[i] = o
o += s
if o > p.dataEnd then
-- a truncated file: keep the whole packets
offsets[i] = nil :: any
sizes = table.move(sizes :: { number }, 1, i - 1, 1, {})
break
end
end
local count = #(sizes :: { number })
local fpp = d.framesPerPacket
local pf = p.packetFrames
local function framesOf(i: number): number
return if pf then pf[i] else fpp
end
local cookie = p.cookie
if fmt == "alac" then
if not cookie then
return nil, Err.new(Err.CORRUPT, "ALAC without a magic cookie")
end
local cfg, err = Alac.config(cookie :: buffer)
if not cfg then
return nil, err
end
local dec = Alac.decoder(cfg)
local pcm = table.create(cfg.frameLength * cfg.channels, 0)
local scale = 1 / 2 ^ (cfg.bitDepth - 1)
return {
channels = cfg.channels,
rate = d.rate,
packetCount = count,
packetFrames = framesOf,
pcm = pcm,
reset = function() end,
codec = "alac",
bits = cfg.bitDepth,
decode = function(i: number): (number?, Err.Err?)
local n, e = dec:decode(b, offsets[i], (sizes :: { number })[i])
if not n then
return nil, e
end
local src = dec.pcm
for k = 1, n * cfg.channels do
pcm[k] = src[k] * scale
end
return n, nil
end,
}, nil
elseif fmt == "aac " then
local asc = if cookie then esdsConfig(cookie :: buffer) else nil
if not asc then
return nil, Err.new(Err.CORRUPT, "AAC without an esds magic cookie")
end
local dec, err = Aac.decoder(asc :: buffer)
if not dec then
return nil, err
end
local ad = dec :: Aac.Decoder
return {
channels = ad.channels,
rate = d.rate,
packetCount = count,
packetFrames = framesOf,
pcm = ad.pcm,
reset = function()
ad:reset()
end,
codec = "aac",
decode = function(i: number): (number?, Err.Err?)
return ad:decode(b, offsets[i], (sizes :: { number })[i])
end,
}, nil
end
return nil, Err.new(Err.UNSUPPORTED, "CAF format '" .. fmt .. "'")
end
function Caf.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
local p, err = parse(r, opts or {})
if not p then
return nil, err
end
local s, serr = source(r, p :: Parsed)
if not s then
return nil, serr
end
local src = s :: Source
local ch, rate = src.channels, src.rate
local starts = table.create(src.packetCount + 1, 0)
local total = 0
for i = 1, src.packetCount do
starts[i] = total
total += src.packetFrames(i)
end
starts[src.packetCount + 1] = total
local skip = math.max(0, p.priming)
local stopAt = total
if p.validFrames and p.validFrames >= 0 then
stopAt = math.min(total, skip + p.validFrames)
elseif p.remainder > 0 then
stopAt = math.max(skip, total - p.remainder)
end
local frames = math.max(0, stopAt - skip)
local nextPacket = 1
local decoded = 0
local pendPos, pendN = 0, 0
local dropUntil = skip
local pos = 0
local failed: Err.Err? = nil
local dec: any = {
sampleRate = rate,
channels = ch,
frames = frames,
duration = frames / rate,
bitrate = if frames > 0 then math.floor((p.dataEnd - p.dataStart) * 8 * rate / frames) else 0,
tags = p.tags,
codec = src.codec,
bitsPerSample = src.bits,
error = nil,
}
local function fill(): boolean
while true do
if nextPacket > src.packetCount or decoded >= stopAt then
return false
end
local i = nextPacket
nextPacket += 1
local start = starts[i]
local n, e = src.decode(i)
if not n then
failed = e
dec.error = e
return false
end
decoded = start + n
local a = math.max(start, dropUntil)
local b = math.min(decoded, stopAt)
if b > a then
pendPos, pendN = a - start, b - start
return true
end
end
end
function dec.read(_self: any, n: number, out: buffer?): (buffer, number)
local want = math.max(0, math.floor(n))
local need = want * ch * 4
local ob = if out and buffer.len(out) >= need then out else buffer.create(need)
local got = 0
local writef32 = buffer.writef32
while got < want do
if pendPos >= pendN then
if failed or not fill() then
break
end
end
local take = math.min(want - got, pendN - pendPos)
local q = got * ch * 4
local sidx = pendPos * ch
local pcm = src.pcm
for k = 1, take * ch do
writef32(ob, q, pcm[sidx + k])
q += 4
end
pendPos += take
got += take
end
pos += got
return ob, got
end
function dec.seek(_self: any, seconds: number)
local target = math.clamp(math.floor(seconds * rate + 0.5), 0, frames) + skip
local lo, hi, found = 1, src.packetCount, 1
while lo <= hi do
local mid = (lo + hi) // 2
if starts[mid] <= target then
found = mid
lo = mid + 1
else
hi = mid - 1
end
end
if src.codec == "aac" then
found = math.max(1, found - 1)
end
src.reset()
nextPacket = found
decoded = starts[found]
dropUntil = target
pendPos, pendN = 0, 0
failed = nil
pos = target - skip
end
function dec.position(_self: any): number
return pos / rate
end
if src.packetCount > 0 and frames > 0 and not fill() and failed then
return nil, failed
end
return dec, nil
end
function Caf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
local dec, err = Caf.open(r, opts)
if not dec then
return nil, err
end
local d: any = dec
local audio = Types.Audio.new(d.sampleRate, d.channels, d.frames)
local done = 0
while done < d.frames do
local b, n = d:read(math.min(65536, d.frames - done))
if n == 0 then
break
end
buffer.copy(audio.samples, done * d.channels * 4, b, 0, n * d.channels * 4)
done += n
end
if d.error then
return nil, d.error
end
audio.tags = d.tags
audio.meta.source = { format = "caf", codec = d.codec, bitsPerSample = d.bitsPerSample }
return audio, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function chunk(w: Bytes.Writer, typ: string, size: number)
w:string(typ)
w:i64be(size)
end
-- encode(audio | decoder, opts?) -> buffer | nil, Err
function Caf.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o = opts or {}
if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then
return nil, Err.new(Err.ARG, "expected an Audio or a Decoder")
end
local codec = o.codec or "alac"
if codec ~= "alac" and codec ~= "pcm" then
return nil, Err.new(Err.ARG, "codec must be 'alac' or 'pcm'")
end
local sr, ch = value.sampleRate, value.channels
local depth = o.bitDepth or 16
if codec == "pcm" and depth ~= 16 and depth ~= 24 and depth ~= 32 then
return nil, Err.new(Err.ARG, "pcm bitDepth 16, 24 or 32 (float)")
end
if ch < 1 or ch > 64 or sr <= 0 then
return nil, Err.new(Err.ARG, "bad sample rate / channels")
end
-- the source frames
local isAudio = value.kind == "audio" and type(value.samples) == "buffer"
if not isAudio and type(value.read) ~= "function" then
return nil, Err.new(Err.ARG, "expected an Audio or a Decoder")
end
if isAudio and buffer.len(value.samples) < value.frames * ch * 4 then
return nil, Err.new(Err.ARG, "audio.samples is shorter than frames * channels")
end
local done = 0
local chunkBuf: buffer? = nil
local function nextBlock(n: number): (buffer?, number, number)
if isAudio then
local k = math.min(n, value.frames - done)
local base = done * ch * 4
done += k
return value.samples, base, k
end
local b, got = value:read(n, chunkBuf)
chunkBuf = b
done += got
return b, 0, got
end
local readf32 = buffer.readf32
local data = Bytes.writer(65536)
local sizes: { number } = {}
local enc: Alac.Encoder? = nil
if codec == "alac" then
local e, err = Alac.encoder({ sampleRate = math.floor(sr), channels = ch, bitDepth = depth })
if not e then
return nil, err
end
enc = e
local ints = table.create(4096 * ch, 0)
local peak = 2 ^ (depth - 1)
while true do
local b, base, n = nextBlock(4096)
if not b or n <= 0 then
break
end
for i = 0, n * ch - 1 do
local v = math.floor(readf32(b, base + i * 4) * peak + 0.5)
ints[i + 1] = math.clamp(v, -peak, peak - 1)
end
local pkt, perr = (e :: Alac.Encoder):encode(ints, 1, n)
if not pkt then
return nil, perr
end
data:bytes(pkt)
table.insert(sizes, buffer.len(pkt))
end
else
local peak = 2 ^ (depth - 1)
while true do
local b, base, n = nextBlock(4096)
if not b or n <= 0 then
break
end
for i = 0, n * ch - 1 do
local f = readf32(b, base + i * 4)
if depth == 32 then
data:f32be(f)
else
local v = math.clamp(math.floor(f * peak + 0.5), -peak, peak - 1)
if depth == 16 then
data:u16be(v % 65536)
else
data:u24be(v % 16777216)
end
end
end
end
end
local frames = done
local w = Bytes.writer(data:tell() + 1024)
w:string("caff")
w:u16be(1)
w:u16be(0)
chunk(w, "desc", 32)
w:f64be(sr)
if codec == "alac" then
w:string("alac")
w:u32be(({ [16] = 1, [20] = 2, [24] = 3, [32] = 4 })[depth] or 1)
w:u32be(0)
w:u32be(4096)
w:u32be(ch)
w:u32be(0)
else
w:string("lpcm")
w:u32be(if depth == 32 then 1 else 0) -- float / big-endian integer
w:u32be(ch * depth // 8)
w:u32be(1)
w:u32be(ch)
w:u32be(depth)
end
local tags = o.tags or value.tags or {}
local keys = {}
for k, v in tags do
if type(v) == "string" then
table.insert(keys, k)
end
end
table.sort(keys)
if #keys > 0 then
local info = Bytes.writer(256)
info:u32be(#keys)
for _, k in keys do
info:cstring(TAG_INFO[k] or k)
info:cstring(tags[k])
end
chunk(w, "info", info:tell())
w:bytes(info.buf, 0, info:tell())
end
if enc then
local cookie = Alac.cookie(enc.config)
chunk(w, "kuki", buffer.len(cookie))
w:bytes(cookie)
local pk = Bytes.writer(64 + #sizes * 2)
pk:i64be(#sizes)
pk:i64be(frames)
pk:u32be(0)
pk:u32be(#sizes * 4096 - frames)
for _, s in sizes do
-- BER variable-length integer
local bytes = { s % 128 }
local v = s // 128
while v > 0 do
table.insert(bytes, 1, 128 + v % 128)
v //= 128
end
for _, x in bytes do
pk:u8(x)
end
end
chunk(w, "pakt", pk:tell())
w:bytes(pk.buf, 0, pk:tell())
end
chunk(w, "data", data:tell() + 4)
w:u32be(0) -- edit count
w:bytes(data.buf, 0, data:tell())
return w:finish(), nil
end
return Caf
File diff suppressed because it is too large. Load diff
+59 -3
View File
@@ -5,7 +5,9 @@
-- 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. Not supported: encoding (ws-audio), MD5 verification, chained Ogg streams.
-- STREAMINFO has none. Encode (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.
--
-- 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
@@ -18,6 +20,8 @@ local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Ogg = require("@formats/containers/Ogg")
local Stream = require("@formats/audio/flac/Stream")
local Encode = require("@formats/audio/flac/Encode")
local Pcm = require("@formats/codecs/Pcm")
-- ------------------------------------------------------------------------------------------------ contract
local Flac = {
@@ -25,8 +29,8 @@ local Flac = {
category = "audio",
extensions = { "flac", "oga" },
mime = { "audio/flac", "audio/x-flac" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" },
caps = { decode = true, encode = false, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm" },
caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true },
}
-- ------------------------------------------------------------------------------------------------ types
@@ -35,6 +39,13 @@ export type OpenOptions = {
crc16: boolean?, -- check every frame's CRC-16 (default true; a bad frame is skipped by resyncing)
maxFrames: number?, -- decode(): refuse streams longer than this many sample frames (default 2^28)
}
export type EncodeOptions = {
level: number?, -- 0..8 like libFLAC's -0 .. -8 (default 5)
bits: number?, -- bits per sample 4..24 (default: the source's meta.source.bitDepth / bitsPerSample if 4..24, else 16)
blockSize: number?, -- 16..65535 (default: the level's, 1152 or 4096)
seekInterval: number?, -- seconds between SEEKTABLE points when the length is known (default 10; 0 = none)
padding: number?, -- bytes of PADDING after the metadata (default 0)
}
-- ------------------------------------------------------------------------------------------------ sniff
function Flac.sniff(r: Bytes.Reader): number
@@ -108,6 +119,51 @@ function Flac.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Er
return a, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- encode(audioOrDecoder, opts?) -> FLAC file buffer | nil, Err
function Flac.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local src, serr = Pcm.source(value)
if not src then
return nil, serr
end
local o: EncodeOptions = opts or {}
local level = o.level or 5
if type(level) ~= "number" or level ~= math.floor(level) or level < 0 or level > 8 then
return nil, Err.new(Err.ARG, "level must be 0..8")
end
local bits = o.bits
if bits == nil then
local v = value :: any
local sb = (type(v.meta) == "table" and type(v.meta.source) == "table" and v.meta.source.bitDepth) or v.bitsPerSample
bits = if type(sb) == "number" and sb >= 4 and sb <= 24 then sb else 16
end
if type(bits) ~= "number" or bits ~= math.floor(bits) or bits < 4 or bits > 24 then
return nil, Err.new(Err.ARG, "bits must be 4..24")
end
local bs = o.blockSize
if bs ~= nil and (type(bs) ~= "number" or bs ~= math.floor(bs) or bs < 16 or bs > 65535) then
return nil, Err.new(Err.ARG, "blockSize must be 16..65535")
end
if src.channels > 8 then
return nil, Err.new(Err.ARG, "FLAC holds at most 8 channels")
end
if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate < 1 or src.sampleRate >= 2 ^ 20 then
return nil, Err.new(Err.ARG, "the sample rate must be an integer below 2^20")
end
local out, msg = Encode.encode(src :: any, {
level = level,
bits = bits :: number,
blockSize = bs,
seekInterval = math.max(0, o.seekInterval or 10),
padding = math.clamp(math.floor(o.padding or 0), 0, 0xFFFFFF),
vendor = "formats-luau",
})
if not out then
return nil, Err.new(Err.CORRUPT, tostring(msg))
end
return out, nil
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts?) -> Decoder | nil, Err
function Flac.open(r: Bytes.Reader, opts: OpenOptions?): (Decoder?, Err.Err?)
+441
View File
@@ -0,0 +1,441 @@
--!strict
-- audio/m4a: MPEG-4 audio files (M4A / M4B / MP4 / MOV audio tracks) through containers/IsoBmff. Supports: reading
-- AAC-LC (codecs/Aac; HE-AAC files play their AAC-LC core at the core rate) and ALAC (codecs/Alac) tracks, gapless
-- trimming through the edit list (encoder priming / padding), seeking, iTunes tags and cover art (dec.pictures);
-- writing ALAC (16 / 20 / 24-bit, 1 - 8 channels) with tags and cover art. Not supported: writing AAC, other codecs
-- inside MP4 (MP3 / Opus / FLAC / AC-3: UNSUPPORTED), encrypted files.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local IsoBmff = require("@formats/containers/IsoBmff")
local Aac = require("@formats/codecs/Aac")
local Alac = require("@formats/codecs/Alac")
-- ------------------------------------------------------------------------------------------------ contract
local M4a = {
name = "m4a",
category = "audio",
extensions = { "m4a", "m4b", "m4r" },
mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" },
deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/Aac", "codecs/Alac" },
caps = { decode = true, encode = true, codecs = { "aac", "alac" }, encodeCodecs = { "alac" }, tags = true, streaming = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
track: number?, -- the track id to play (default: the first AAC / ALAC track)
gapless: boolean?, -- apply the edit list (default true)
maxSamples: number?, -- sample table limit (default 2^25)
}
export type EncodeOptions = {
bitDepth: number?, -- 16 (default), 20 or 24
frameLength: number?, -- samples per packet, default 4096
tags: Types.Tags?, -- default: the audio's tags
pictures: { { mime: string, data: buffer } }?, -- cover art (default: audio.meta.pictures)
}
-- ------------------------------------------------------------------------------------------------ constants
local AUDIO_BRANDS: { [string]: number } = { ["M4A "] = 1, ["M4B "] = 1, ["M4P "] = 1, ["M4V "] = 0.3 }
-- ------------------------------------------------------------------------------------------------ sniff
function M4a.sniff(r: Bytes.Reader): number
local brand = IsoBmff.sniff(r)
if brand == nil then
return 0
end
if AUDIO_BRANDS[brand] then
return AUDIO_BRANDS[brand]
end
if brand == "avif" or brand == "avis" or brand == "heic" or brand == "heix" or brand == "mif1" or brand == "msf1" or brand == "crx " then
return 0
end
return 0.4 -- an MP4 / MOV that may hold audio; a video format claims it more strongly
end
-- ------------------------------------------------------------------------------------------------ decode
-- the packet decoder of a track: decode(buf, off, len) -> frames | nil, Err; pcm: interleaved floats
type PacketDecoder = {
channels: number,
sampleRate: number,
frameSize: number,
pcm: { number },
decode: (buf: buffer, off: number, len: number) -> (number?, Err.Err?),
reset: () -> (),
}
local function packetDecoder(t: IsoBmff.Track): (PacketDecoder?, Err.Err?)
if not t.config then
return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " (" .. t.codec .. ") has no codec configuration")
end
if t.codec == "alac" then
local cfg, err = Alac.config(t.config :: buffer)
if not cfg then
return nil, err
end
local dec = Alac.decoder(cfg)
local pcm = table.create(cfg.frameLength * cfg.channels, 0)
local scale = 1 / 2 ^ (cfg.bitDepth - 1)
local pd: PacketDecoder = {
channels = cfg.channels,
sampleRate = if cfg.sampleRate > 0 then cfg.sampleRate else (t.sampleRate or 44100),
frameSize = cfg.frameLength,
pcm = pcm,
decode = function(buf: buffer, off: number, len: number): (number?, Err.Err?)
local n, e = dec:decode(buf, off, len)
if not n then
return nil, e
end
local src = dec.pcm
for i = 1, n * cfg.channels do
pcm[i] = src[i] * scale
end
return n, nil
end,
reset = function() end,
}
return pd, nil
elseif t.codec == "aac" then
local dec, err = Aac.decoder(t.config :: buffer)
if not dec then
return nil, err
end
local d = dec :: Aac.Decoder
local pd: PacketDecoder = {
channels = d.channels,
sampleRate = d.sampleRate,
frameSize = d.frameLength,
pcm = d.pcm,
decode = function(buf: buffer, off: number, len: number): (number?, Err.Err?)
return d:decode(buf, off, len)
end,
reset = function()
d:reset()
end,
}
return pd, nil
end
return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. t.codec .. " in MP4")
end
-- open(r, opts?) -> Types.Decoder | nil, Err
function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
local o = opts or {}
local movie, err = IsoBmff.parse(r, { maxSamples = o.maxSamples })
if not movie then
return nil, err
end
local track: IsoBmff.Track? = nil
local other: IsoBmff.Track? = nil
for _, t in movie.tracks do
if t.kind == "audio" then
if o.track and t.id ~= o.track then
continue
end
if t.codec == "aac" or t.codec == "alac" then
track = t
break
end
other = other or t
end
end
if not track then
if other then
return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. other.codec .. " in MP4")
end
return nil, Err.new(Err.CORRUPT, "no audio track")
end
local t = track :: IsoBmff.Track
local pd, perr = packetDecoder(t)
if not pd then
return nil, perr
end
local p = pd :: PacketDecoder
local channels, sr = p.channels, p.sampleRate
-- media ticks -> sample frames
local tickScale = sr / t.timescale
local gapless = o.gapless ~= false
local skip = if gapless then math.floor(t.skip * tickScale + 0.5) else 0
local total = 0
for i = 1, t.sampleCount do
total += t.durations[i]
end
total = math.floor(total * tickScale + 0.5)
if gapless and t.playDuration then
total = math.min(total, skip + math.floor(t.playDuration * tickScale + 0.5))
end
local tags, pictures = IsoBmff.tags(r, movie)
-- iTunes gapless info (fdkaac, iTunes) when there is no edit list: " 0 <priming> <padding> <samples> ..." (hex)
local smpb = tags.iTunSMPB
if gapless and not t.edits and smpb then
local f = {}
for w in string.gmatch(smpb, "%x+") do
table.insert(f, tonumber(w, 16))
end
if #f >= 4 and f[2] and f[4] and f[4] > 0 and f[2] + f[4] <= total then
skip = f[2]
total = f[2] + f[4]
end
end
local frames = math.max(0, total - skip)
local buf = r.buf
-- streaming state
local nextPacket = 1
local decoded = 0 -- frames produced by the packets decoded so far (before trimming)
local pend, pendPos, pendN = p.pcm, 0, 0 -- the current packet: frames pendPos .. pendN - 1 not yet returned
local dropUntil = skip -- absolute frame index of the first frame to return
local stopAt = total
local pos = 0 -- frames returned
local failed: Err.Err? = nil
local dec: any = {
sampleRate = sr,
channels = channels,
frames = frames,
duration = frames / sr,
bitrate = 0,
tags = tags,
pictures = pictures,
codec = t.codec,
track = t,
movie = movie,
error = nil,
}
local bytes = 0
for i = 1, t.sampleCount do
bytes += t.sizes[i]
end
dec.bitrate = if frames > 0 then math.floor(bytes * 8 * sr / frames) else (t.bitrate or 0)
-- decode the next packet into pend; false at the end / on an error
local function fill(): boolean
while true do
if nextPacket > t.sampleCount or decoded >= stopAt then
return false
end
local i = nextPacket
nextPacket += 1
local start = decoded
local n, e = p.decode(buf, t.offsets[i], t.sizes[i])
if not n then
failed = e
dec.error = e
return false
end
decoded += n
-- the part of this packet inside [dropUntil, stopAt)
local a = math.max(start, dropUntil)
local b = math.min(decoded, stopAt)
if b > a then
pendPos = a - start
pendN = b - start
return true
end
end
end
function dec.read(_self: any, n: number, out: buffer?): (buffer, number)
local want = math.max(0, math.floor(n))
local need = want * channels * 4
local ob = if out and buffer.len(out) >= need then out else buffer.create(need)
local got = 0
local writef32 = buffer.writef32
while got < want do
if pendPos >= pendN then
if failed or not fill() then
break
end
end
local take = math.min(want - got, pendN - pendPos)
local src = pend
local o = got * channels * 4
local s = pendPos * channels
for k = 1, take * channels do
writef32(ob, o, src[s + k])
o += 4
end
pendPos += take
got += take
end
pos += got
return ob, got
end
function dec.seek(_self: any, seconds: number)
local target = math.clamp(math.floor(seconds * sr + 0.5), 0, frames) + skip -- absolute frame
-- the last packet starting at or before the target, minus one for the codec's overlap (AAC)
local ticks = target / tickScale
local lo, hi, found = 1, t.sampleCount, 1
while lo <= hi do
local mid = (lo + hi) // 2
if t.dts[mid] <= ticks then
found = mid
lo = mid + 1
else
hi = mid - 1
end
end
local startPacket = if t.codec == "aac" then math.max(1, found - 1) else found
p.reset()
nextPacket = startPacket
decoded = math.floor((t.dts[startPacket] or 0) * tickScale + 0.5)
dropUntil = math.max(target, skip)
pendPos, pendN = 0, 0
failed = nil
pos = target - skip
end
function dec.position(_self: any): number
return pos / sr
end
-- prime: surface a broken first packet as an open error
if t.sampleCount > 0 and frames > 0 then
if not fill() and failed then
return nil, failed
end
end
return dec, nil
end
-- decode(r, opts?) -> Types.Audio | nil, Err (the whole stream, tags, cover pictures in meta.pictures)
function M4a.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
local dec, err = M4a.open(r, opts)
if not dec then
return nil, err
end
local d: any = dec
local audio = Types.Audio.new(d.sampleRate, d.channels, d.frames)
local done = 0
local chunk = buffer.create(65536 * d.channels * 4)
while done < d.frames do
local b, n = d:read(math.min(65536, d.frames - done), chunk)
if n == 0 then
break
end
buffer.copy(audio.samples, done * d.channels * 4, b, 0, n * d.channels * 4)
done += n
end
if d.error then
return nil, d.error
end
if done < d.frames then
local short = buffer.create(done * d.channels * 4)
buffer.copy(short, 0, audio.samples, 0, buffer.len(short))
audio.samples = short
audio.frames = done
end
audio.tags = d.tags
audio.meta.source = { format = "m4a", codec = d.codec, bitsPerSample = d.track.bitsPerSample, brand = d.movie.brand }
if #d.pictures > 0 then
audio.meta.pictures = d.pictures
end
return audio, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- encode(audio | decoder, opts?) -> buffer | nil, Err: an ALAC M4A
function M4a.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o = opts or {}
if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then
return nil, Err.new(Err.ARG, "expected an Audio or a Decoder")
end
local sr, ch = value.sampleRate, value.channels
local enc, eerr = Alac.encoder({ sampleRate = sr, channels = ch, bitDepth = o.bitDepth or 16, frameLength = o.frameLength })
if not enc then
return nil, eerr
end
local e = enc :: Alac.Encoder
local depth = e.config.bitDepth
local fl = e.config.frameLength
local peak = 2 ^ (depth - 1)
local packets: { buffer } = {}
local durations: { number } = {}
local ints = table.create(fl * ch, 0)
local floor = math.floor
local readf32 = buffer.readf32
-- frames from an Audio buffer or a streaming Decoder
local src: buffer, srcFrames = nil :: any, 0
local isAudio = value.kind == "audio" and type(value.samples) == "buffer"
if isAudio then
src, srcFrames = value.samples, value.frames
if buffer.len(src) < srcFrames * ch * 4 then
return nil, Err.new(Err.ARG, "audio.samples is shorter than frames * channels")
end
elseif type(value.read) ~= "function" then
return nil, Err.new(Err.ARG, "expected an Audio or a Decoder")
end
local done = 0
local chunk: buffer? = nil
while true do
local n, b, base
if isAudio then
n = math.min(fl, srcFrames - done)
b, base = src, done * ch * 4
else
local got
b, got = value:read(fl, chunk)
chunk = b
n, base = got, 0
end
if n <= 0 then
break
end
for i = 0, n * ch - 1 do
local v = floor(readf32(b, base + i * 4) * peak + 0.5)
if v >= peak then
v = peak - 1
elseif v < -peak then
v = -peak
end
ints[i + 1] = v
end
local pkt, perr = e:encode(ints, 1, n)
if not pkt then
return nil, perr
end
table.insert(packets, pkt)
table.insert(durations, n)
done += n
if isAudio and done >= srcFrames then
break
end
end
local tags = o.tags or value.tags or {}
local pictures = o.pictures or (value.meta and value.meta.pictures) or nil
local timescale = if sr < 65536 then sr else 0
local file, merr = IsoBmff.mux({
brand = "M4A ",
minor = 0,
compatible = { "M4A ", "mp42", "isom" },
timescale = 1000,
tracks = {
{
kind = "audio",
entry = "alac",
timescale = if timescale > 0 then timescale else 48000,
samples = packets,
durations = if timescale > 0 then durations else (function()
local d = {}
for i, v in durations do
d[i] = math.floor(v * 48000 / sr + 0.5)
end
return d
end)(),
sampleRate = sr,
channels = ch,
bitsPerSample = depth,
config = Alac.cookie(e.config),
},
},
tags = tags,
pictures = pictures,
})
if not file then
return nil, merr
end
return file, nil
end
return M4a
+63
View File
@@ -0,0 +1,63 @@
--!strict
--!native
--!optimize 2
-- audio/mp3/Analysis: the MPEG audio polyphase analysis filterbank (ISO/IEC 11172-3 section C.1.3, figure C.4): 32
-- input samples -> one sample in each of the 32 subbands, with the standard's 512-tap window C = D / 32 (D from
-- audio/mp3/EncTables) and the matrixing M[k][i] = cos((2k + 1)(i - 16) pi / 64). Shared by the layer II and layer III
-- encoders. New code from the standard's flow chart. Never throws.
--
-- local st = Analysis.new()
-- Analysis.run(st, samples, start, out, outStart) -- samples[start .. start + 31] -> out[outStart .. outStart + 31]
local E = require("@formats/audio/mp3/EncTables")
local Analysis = {}
local C = table.create(512, 0)
for i = 1, 512 do
C[i] = E.D[i] / 32
end
local M = table.create(32 * 64, 0) -- M[k * 64 + i + 1]
for k = 0, 31 do
for i = 0, 63 do
M[k * 64 + i + 1] = math.cos((2 * k + 1) * (i - 16) * math.pi / 64)
end
end
export type State = { x: { number }, off: number, y: { number } }
function Analysis.new(): State
return { x = table.create(1024, 0), off = 0, y = table.create(64, 0) }
end
-- run(st, s, si, out, oi): s[si .. si + 31] (oldest first) -> out[oi .. oi + 31] (subbands 0 .. 31)
function Analysis.run(st: State, s: { number }, si: number, out: { number }, oi: number)
-- the window X is kept twice (x[p] and x[p + 512]) so X[i] = x[off + i + 1] without a modulo
local x = st.x
local off = (st.off - 32) % 512
st.off = off
for j = 0, 31 do
local v = s[si + j]
local p = (off + 31 - j) % 512 + 1 -- X[31 - j]: the first new sample goes to X[31], the newest to X[0]
x[p] = v
x[p + 512] = v
end
local y = st.y
for i = 0, 63 do
local acc = 0
local b = off + i + 1
for j = 0, 7 do
acc += C[i + 64 * j + 1] * x[b + 64 * j]
end
y[i + 1] = acc
end
for k = 0, 31 do
local acc = 0
local mb = k * 64
for i = 1, 64 do
acc += M[mb + i] * y[i]
end
out[oi + k] = acc
end
end
return Analysis
+292
View File
@@ -0,0 +1,292 @@
--!strict
-- audio/mp3/EncTables: tables for the MPEG audio encoders, from PDMP3 (public domain / unlicense, by Krister
-- Lagerstrom and contributors: licenses/PDMP3-UNLICENSE.txt), which transcribes ISO/IEC 11172-3: the synthesis window D
-- (the analysis window is C = D / 32) and the layer III Huffman code trees (the encoders derive codeword tables from
-- them). Trees use the standard's decoder layout: an entry with a high byte is a node (high byte: left offset, low
-- byte: right offset), otherwise a leaf (x << 4 | y; count1 tables: v w x y bits).
local E = {}
E.D = {
0.000000000, -0.000015259, -0.000015259, -0.000015259, -0.000015259, -0.000015259, -0.000015259, -0.000030518,
-0.000030518, -0.000030518, -0.000030518, -0.000045776, -0.000045776, -0.000061035, -0.000061035, -0.000076294,
-0.000076294, -0.000091553, -0.000106812, -0.000106812, -0.000122070, -0.000137329, -0.000152588, -0.000167847,
-0.000198364, -0.000213623, -0.000244141, -0.000259399, -0.000289917, -0.000320435, -0.000366211, -0.000396729,
-0.000442505, -0.000473022, -0.000534058, -0.000579834, -0.000625610, -0.000686646, -0.000747681, -0.000808716,
-0.000885010, -0.000961304, -0.001037598, -0.001113892, -0.001205444, -0.001296997, -0.001388550, -0.001480103,
-0.001586914, -0.001693726, -0.001785278, -0.001907349, -0.002014160, -0.002120972, -0.002243042, -0.002349854,
-0.002456665, -0.002578735, -0.002685547, -0.002792358, -0.002899170, -0.002990723, -0.003082275, -0.003173828,
0.003250122, 0.003326416, 0.003387451, 0.003433228, 0.003463745, 0.003479004, 0.003479004, 0.003463745,
0.003417969, 0.003372192, 0.003280640, 0.003173828, 0.003051758, 0.002883911, 0.002700806, 0.002487183,
0.002227783, 0.001937866, 0.001617432, 0.001266479, 0.000869751, 0.000442505, -0.000030518, -0.000549316,
-0.001098633, -0.001693726, -0.002334595, -0.003005981, -0.003723145, -0.004486084, -0.005294800, -0.006118774,
-0.007003784, -0.007919312, -0.008865356, -0.009841919, -0.010848999, -0.011886597, -0.012939453, -0.014022827,
-0.015121460, -0.016235352, -0.017349243, -0.018463135, -0.019577026, -0.020690918, -0.021789551, -0.022857666,
-0.023910522, -0.024932861, -0.025909424, -0.026840210, -0.027725220, -0.028533936, -0.029281616, -0.029937744,
-0.030532837, -0.031005859, -0.031387329, -0.031661987, -0.031814575, -0.031845093, -0.031738281, -0.031478882,
0.031082153, 0.030517578, 0.029785156, 0.028884888, 0.027801514, 0.026535034, 0.025085449, 0.023422241,
0.021575928, 0.019531250, 0.017257690, 0.014801025, 0.012115479, 0.009231567, 0.006134033, 0.002822876,
-0.000686646, -0.004394531, -0.008316040, -0.012420654, -0.016708374, -0.021179199, -0.025817871, -0.030609131,
-0.035552979, -0.040634155, -0.045837402, -0.051132202, -0.056533813, -0.061996460, -0.067520142, -0.073059082,
-0.078628540, -0.084182739, -0.089706421, -0.095169067, -0.100540161, -0.105819702, -0.110946655, -0.115921021,
-0.120697021, -0.125259399, -0.129562378, -0.133590698, -0.137298584, -0.140670776, -0.143676758, -0.146255493,
-0.148422241, -0.150115967, -0.151306152, -0.151962280, -0.152069092, -0.151596069, -0.150497437, -0.148773193,
-0.146362305, -0.143264771, -0.139450073, -0.134887695, -0.129577637, -0.123474121, -0.116577148, -0.108856201,
0.100311279, 0.090927124, 0.080688477, 0.069595337, 0.057617188, 0.044784546, 0.031082153, 0.016510010,
0.001068115, -0.015228271, -0.032379150, -0.050354004, -0.069168091, -0.088775635, -0.109161377, -0.130310059,
-0.152206421, -0.174789429, -0.198059082, -0.221984863, -0.246505737, -0.271591187, -0.297210693, -0.323318481,
-0.349868774, -0.376800537, -0.404083252, -0.431655884, -0.459472656, -0.487472534, -0.515609741, -0.543823242,
-0.572036743, -0.600219727, -0.628295898, -0.656219482, -0.683914185, -0.711318970, -0.738372803, -0.765029907,
-0.791213989, -0.816864014, -0.841949463, -0.866363525, -0.890090942, -0.913055420, -0.935195923, -0.956481934,
-0.976852417, -0.996246338, -1.014617920, -1.031936646, -1.048156738, -1.063217163, -1.077117920, -1.089782715,
-1.101211548, -1.111373901, -1.120223999, -1.127746582, -1.133926392, -1.138763428, -1.142211914, -1.144287109,
1.144989014, 1.144287109, 1.142211914, 1.138763428, 1.133926392, 1.127746582, 1.120223999, 1.111373901,
1.101211548, 1.089782715, 1.077117920, 1.063217163, 1.048156738, 1.031936646, 1.014617920, 0.996246338,
0.976852417, 0.956481934, 0.935195923, 0.913055420, 0.890090942, 0.866363525, 0.841949463, 0.816864014,
0.791213989, 0.765029907, 0.738372803, 0.711318970, 0.683914185, 0.656219482, 0.628295898, 0.600219727,
0.572036743, 0.543823242, 0.515609741, 0.487472534, 0.459472656, 0.431655884, 0.404083252, 0.376800537,
0.349868774, 0.323318481, 0.297210693, 0.271591187, 0.246505737, 0.221984863, 0.198059082, 0.174789429,
0.152206421, 0.130310059, 0.109161377, 0.088775635, 0.069168091, 0.050354004, 0.032379150, 0.015228271,
-0.001068115, -0.016510010, -0.031082153, -0.044784546, -0.057617188, -0.069595337, -0.080688477, -0.090927124,
0.100311279, 0.108856201, 0.116577148, 0.123474121, 0.129577637, 0.134887695, 0.139450073, 0.143264771,
0.146362305, 0.148773193, 0.150497437, 0.151596069, 0.152069092, 0.151962280, 0.151306152, 0.150115967,
0.148422241, 0.146255493, 0.143676758, 0.140670776, 0.137298584, 0.133590698, 0.129562378, 0.125259399,
0.120697021, 0.115921021, 0.110946655, 0.105819702, 0.100540161, 0.095169067, 0.089706421, 0.084182739,
0.078628540, 0.073059082, 0.067520142, 0.061996460, 0.056533813, 0.051132202, 0.045837402, 0.040634155,
0.035552979, 0.030609131, 0.025817871, 0.021179199, 0.016708374, 0.012420654, 0.008316040, 0.004394531,
0.000686646, -0.002822876, -0.006134033, -0.009231567, -0.012115479, -0.014801025, -0.017257690, -0.019531250,
-0.021575928, -0.023422241, -0.025085449, -0.026535034, -0.027801514, -0.028884888, -0.029785156, -0.030517578,
0.031082153, 0.031478882, 0.031738281, 0.031845093, 0.031814575, 0.031661987, 0.031387329, 0.031005859,
0.030532837, 0.029937744, 0.029281616, 0.028533936, 0.027725220, 0.026840210, 0.025909424, 0.024932861,
0.023910522, 0.022857666, 0.021789551, 0.020690918, 0.019577026, 0.018463135, 0.017349243, 0.016235352,
0.015121460, 0.014022827, 0.012939453, 0.011886597, 0.010848999, 0.009841919, 0.008865356, 0.007919312,
0.007003784, 0.006118774, 0.005294800, 0.004486084, 0.003723145, 0.003005981, 0.002334595, 0.001693726,
0.001098633, 0.000549316, 0.000030518, -0.000442505, -0.000869751, -0.001266479, -0.001617432, -0.001937866,
-0.002227783, -0.002487183, -0.002700806, -0.002883911, -0.003051758, -0.003173828, -0.003280640, -0.003372192,
-0.003417969, -0.003463745, -0.003479004, -0.003479004, -0.003463745, -0.003433228, -0.003387451, -0.003326416,
0.003250122, 0.003173828, 0.003082275, 0.002990723, 0.002899170, 0.002792358, 0.002685547, 0.002578735,
0.002456665, 0.002349854, 0.002243042, 0.002120972, 0.002014160, 0.001907349, 0.001785278, 0.001693726,
0.001586914, 0.001480103, 0.001388550, 0.001296997, 0.001205444, 0.001113892, 0.001037598, 0.000961304,
0.000885010, 0.000808716, 0.000747681, 0.000686646, 0.000625610, 0.000579834, 0.000534058, 0.000473022,
0.000442505, 0.000396729, 0.000366211, 0.000320435, 0.000289917, 0.000259399, 0.000244141, 0.000213623,
0.000198364, 0.000167847, 0.000152588, 0.000137329, 0.000122070, 0.000106812, 0.000106812, 0.000091553,
0.000076294, 0.000076294, 0.000061035, 0.000061035, 0.000045776, 0.000045776, 0.000030518, 0.000030518,
0.000030518, 0.000030518, 0.000015259, 0.000015259, 0.000015259, 0.000015259, 0.000015259, 0.000015259,
}
E.LINBITS = { [0] = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 8, 10, 13, 4, 5, 6, 7, 8, 9, 11, 13, 0, 0 }
-- trees by table number (tables 16..23 share 16's tree, 24..31 share 24's)
E.TREES = {
[1] = {
0x0201, 0x0000, 0x0201, 0x0010, 0x0201, 0x0001, 0x0011,
},
[2] = {
0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0021, 0x0201, 0x0012, 0x0201, 0x0002,
0x0022,
},
[3] = {
0x0401, 0x0201, 0x0000, 0x0001, 0x0201, 0x0011, 0x0201, 0x0010, 0x0401, 0x0201, 0x0020, 0x0021, 0x0201, 0x0012, 0x0201, 0x0002,
0x0022,
},
[5] = {
0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0801, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, 0x0012,
0x0801, 0x0401, 0x0201, 0x0022, 0x0030, 0x0201, 0x0003, 0x0013, 0x0201, 0x0031, 0x0201, 0x0032, 0x0201, 0x0023, 0x0033,
},
[6] = {
0x0601, 0x0401, 0x0201, 0x0000, 0x0010, 0x0011, 0x0601, 0x0201, 0x0001, 0x0201, 0x0020, 0x0021, 0x0601, 0x0201, 0x0012, 0x0201,
0x0002, 0x0022, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0030, 0x0032, 0x0201, 0x0023, 0x0201, 0x0003, 0x0033,
},
[7] = {
0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0801, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0021, 0x1201, 0x0601,
0x0201, 0x0012, 0x0201, 0x0022, 0x0030, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0003, 0x0032, 0x0201, 0x0023, 0x0004,
0x0a01, 0x0401, 0x0201, 0x0040, 0x0041, 0x0201, 0x0014, 0x0201, 0x0042, 0x0024, 0x0c01, 0x0601, 0x0401, 0x0201, 0x0033, 0x0043,
0x0050, 0x0401, 0x0201, 0x0034, 0x0005, 0x0051, 0x0601, 0x0201, 0x0015, 0x0201, 0x0052, 0x0025, 0x0401, 0x0201, 0x0044, 0x0035,
0x0401, 0x0201, 0x0053, 0x0054, 0x0201, 0x0045, 0x0055,
},
[8] = {
0x0601, 0x0201, 0x0000, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0401, 0x0201, 0x0021, 0x0012, 0x0e01, 0x0401, 0x0201, 0x0020,
0x0002, 0x0201, 0x0022, 0x0401, 0x0201, 0x0030, 0x0003, 0x0201, 0x0031, 0x0013, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0032, 0x0023,
0x0201, 0x0040, 0x0004, 0x0201, 0x0041, 0x0201, 0x0014, 0x0042, 0x0c01, 0x0601, 0x0201, 0x0024, 0x0201, 0x0033, 0x0050, 0x0401,
0x0201, 0x0043, 0x0034, 0x0051, 0x0601, 0x0201, 0x0015, 0x0201, 0x0005, 0x0052, 0x0601, 0x0201, 0x0025, 0x0201, 0x0044, 0x0035,
0x0201, 0x0053, 0x0201, 0x0045, 0x0201, 0x0054, 0x0055,
},
[9] = {
0x0801, 0x0401, 0x0201, 0x0000, 0x0010, 0x0201, 0x0001, 0x0011, 0x0a01, 0x0401, 0x0201, 0x0020, 0x0021, 0x0201, 0x0012, 0x0201,
0x0002, 0x0022, 0x0c01, 0x0601, 0x0401, 0x0201, 0x0030, 0x0003, 0x0031, 0x0201, 0x0013, 0x0201, 0x0032, 0x0023, 0x0c01, 0x0401,
0x0201, 0x0041, 0x0014, 0x0401, 0x0201, 0x0040, 0x0033, 0x0201, 0x0042, 0x0024, 0x0a01, 0x0601, 0x0401, 0x0201, 0x0004, 0x0050,
0x0043, 0x0201, 0x0034, 0x0051, 0x0801, 0x0401, 0x0201, 0x0015, 0x0052, 0x0201, 0x0025, 0x0044, 0x0601, 0x0401, 0x0201, 0x0005,
0x0054, 0x0053, 0x0201, 0x0035, 0x0201, 0x0045, 0x0055,
},
[10] = {
0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0a01, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, 0x0012,
0x1c01, 0x0801, 0x0401, 0x0201, 0x0022, 0x0030, 0x0201, 0x0031, 0x0013, 0x0801, 0x0401, 0x0201, 0x0003, 0x0032, 0x0201, 0x0023,
0x0040, 0x0401, 0x0201, 0x0041, 0x0014, 0x0401, 0x0201, 0x0004, 0x0033, 0x0201, 0x0042, 0x0024, 0x1c01, 0x0a01, 0x0601, 0x0401,
0x0201, 0x0050, 0x0005, 0x0060, 0x0201, 0x0061, 0x0016, 0x0c01, 0x0601, 0x0401, 0x0201, 0x0043, 0x0034, 0x0051, 0x0201, 0x0015,
0x0201, 0x0052, 0x0025, 0x0401, 0x0201, 0x0026, 0x0036, 0x0071, 0x1401, 0x0801, 0x0201, 0x0017, 0x0401, 0x0201, 0x0044, 0x0053,
0x0006, 0x0601, 0x0401, 0x0201, 0x0035, 0x0045, 0x0062, 0x0201, 0x0070, 0x0201, 0x0007, 0x0064, 0x0e01, 0x0401, 0x0201, 0x0072,
0x0027, 0x0601, 0x0201, 0x0063, 0x0201, 0x0054, 0x0055, 0x0201, 0x0046, 0x0073, 0x0801, 0x0401, 0x0201, 0x0037, 0x0065, 0x0201,
0x0056, 0x0074, 0x0601, 0x0201, 0x0047, 0x0201, 0x0066, 0x0075, 0x0401, 0x0201, 0x0057, 0x0076, 0x0201, 0x0067, 0x0077,
},
[11] = {
0x0601, 0x0201, 0x0000, 0x0201, 0x0010, 0x0001, 0x0801, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0012, 0x1801, 0x0801,
0x0201, 0x0021, 0x0201, 0x0022, 0x0201, 0x0030, 0x0003, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0032, 0x0023, 0x0401,
0x0201, 0x0040, 0x0004, 0x0201, 0x0041, 0x0014, 0x1e01, 0x1001, 0x0a01, 0x0401, 0x0201, 0x0042, 0x0024, 0x0401, 0x0201, 0x0033,
0x0043, 0x0050, 0x0401, 0x0201, 0x0034, 0x0051, 0x0061, 0x0601, 0x0201, 0x0016, 0x0201, 0x0006, 0x0026, 0x0201, 0x0062, 0x0201,
0x0015, 0x0201, 0x0005, 0x0052, 0x1001, 0x0a01, 0x0601, 0x0401, 0x0201, 0x0025, 0x0044, 0x0060, 0x0201, 0x0063, 0x0036, 0x0401,
0x0201, 0x0070, 0x0017, 0x0071, 0x1001, 0x0601, 0x0401, 0x0201, 0x0007, 0x0064, 0x0072, 0x0201, 0x0027, 0x0401, 0x0201, 0x0053,
0x0035, 0x0201, 0x0054, 0x0045, 0x0a01, 0x0401, 0x0201, 0x0046, 0x0073, 0x0201, 0x0037, 0x0201, 0x0065, 0x0056, 0x0a01, 0x0601,
0x0401, 0x0201, 0x0055, 0x0057, 0x0074, 0x0201, 0x0047, 0x0066, 0x0401, 0x0201, 0x0075, 0x0076, 0x0201, 0x0067, 0x0077,
},
[12] = {
0x0c01, 0x0401, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0201, 0x0000, 0x0201, 0x0020, 0x0002, 0x1001, 0x0401, 0x0201, 0x0021,
0x0012, 0x0401, 0x0201, 0x0022, 0x0031, 0x0201, 0x0013, 0x0201, 0x0030, 0x0201, 0x0003, 0x0040, 0x1a01, 0x0801, 0x0401, 0x0201,
0x0032, 0x0023, 0x0201, 0x0041, 0x0033, 0x0a01, 0x0401, 0x0201, 0x0014, 0x0042, 0x0201, 0x0024, 0x0201, 0x0004, 0x0050, 0x0401,
0x0201, 0x0043, 0x0034, 0x0201, 0x0051, 0x0015, 0x1c01, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0052, 0x0025, 0x0201, 0x0053, 0x0035,
0x0401, 0x0201, 0x0060, 0x0016, 0x0061, 0x0401, 0x0201, 0x0062, 0x0026, 0x0601, 0x0401, 0x0201, 0x0005, 0x0006, 0x0044, 0x0201,
0x0054, 0x0045, 0x1201, 0x0a01, 0x0401, 0x0201, 0x0063, 0x0036, 0x0401, 0x0201, 0x0070, 0x0007, 0x0071, 0x0401, 0x0201, 0x0017,
0x0064, 0x0201, 0x0046, 0x0072, 0x0a01, 0x0601, 0x0201, 0x0027, 0x0201, 0x0055, 0x0073, 0x0201, 0x0037, 0x0056, 0x0801, 0x0401,
0x0201, 0x0065, 0x0074, 0x0201, 0x0047, 0x0066, 0x0401, 0x0201, 0x0075, 0x0057, 0x0201, 0x0076, 0x0201, 0x0067, 0x0077,
},
[13] = {
0x0201, 0x0000, 0x0601, 0x0201, 0x0010, 0x0201, 0x0001, 0x0011, 0x1c01, 0x0801, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021,
0x0012, 0x0801, 0x0401, 0x0201, 0x0022, 0x0030, 0x0201, 0x0003, 0x0031, 0x0601, 0x0201, 0x0013, 0x0201, 0x0032, 0x0023, 0x0401,
0x0201, 0x0040, 0x0004, 0x0041, 0x4601, 0x1c01, 0x0e01, 0x0601, 0x0201, 0x0014, 0x0201, 0x0033, 0x0042, 0x0401, 0x0201, 0x0024,
0x0050, 0x0201, 0x0043, 0x0034, 0x0401, 0x0201, 0x0051, 0x0015, 0x0401, 0x0201, 0x0005, 0x0052, 0x0201, 0x0025, 0x0201, 0x0044,
0x0053, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0060, 0x0006, 0x0201, 0x0061, 0x0016, 0x0401, 0x0201, 0x0080, 0x0008, 0x0081, 0x1001,
0x0801, 0x0401, 0x0201, 0x0035, 0x0062, 0x0201, 0x0026, 0x0054, 0x0401, 0x0201, 0x0045, 0x0063, 0x0201, 0x0036, 0x0070, 0x0601,
0x0401, 0x0201, 0x0007, 0x0055, 0x0071, 0x0201, 0x0017, 0x0201, 0x0027, 0x0037, 0x4801, 0x1801, 0x0c01, 0x0401, 0x0201, 0x0018,
0x0082, 0x0201, 0x0028, 0x0401, 0x0201, 0x0064, 0x0046, 0x0072, 0x0801, 0x0401, 0x0201, 0x0084, 0x0048, 0x0201, 0x0090, 0x0009,
0x0201, 0x0091, 0x0019, 0x1801, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0073, 0x0065, 0x0201, 0x0056, 0x0074, 0x0401, 0x0201, 0x0047,
0x0066, 0x0083, 0x0601, 0x0201, 0x0038, 0x0201, 0x0075, 0x0057, 0x0201, 0x0092, 0x0029, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0067,
0x0085, 0x0201, 0x0058, 0x0039, 0x0201, 0x0093, 0x0201, 0x0049, 0x0086, 0x0601, 0x0201, 0x00a0, 0x0201, 0x0068, 0x000a, 0x0201,
0x00a1, 0x001a, 0x4401, 0x1801, 0x0c01, 0x0401, 0x0201, 0x00a2, 0x002a, 0x0401, 0x0201, 0x0095, 0x0059, 0x0201, 0x00a3, 0x003a,
0x0801, 0x0401, 0x0201, 0x004a, 0x0096, 0x0201, 0x00b0, 0x000b, 0x0201, 0x00b1, 0x001b, 0x1401, 0x0801, 0x0201, 0x00b2, 0x0401,
0x0201, 0x0076, 0x0077, 0x0094, 0x0601, 0x0401, 0x0201, 0x0087, 0x0078, 0x00a4, 0x0401, 0x0201, 0x0069, 0x00a5, 0x002b, 0x0c01,
0x0601, 0x0401, 0x0201, 0x005a, 0x0088, 0x00b3, 0x0201, 0x003b, 0x0201, 0x0079, 0x00a6, 0x0601, 0x0401, 0x0201, 0x006a, 0x00b4,
0x00c0, 0x0401, 0x0201, 0x000c, 0x0098, 0x00c1, 0x3c01, 0x1601, 0x0a01, 0x0601, 0x0201, 0x001c, 0x0201, 0x0089, 0x00b5, 0x0201,
0x005b, 0x00c2, 0x0401, 0x0201, 0x002c, 0x003c, 0x0401, 0x0201, 0x00b6, 0x006b, 0x0201, 0x00c4, 0x004c, 0x1001, 0x0801, 0x0401,
0x0201, 0x00a8, 0x008a, 0x0201, 0x00d0, 0x000d, 0x0201, 0x00d1, 0x0201, 0x004b, 0x0201, 0x0097, 0x00a7, 0x0c01, 0x0601, 0x0201,
0x00c3, 0x0201, 0x007a, 0x0099, 0x0401, 0x0201, 0x00c5, 0x005c, 0x00b7, 0x0401, 0x0201, 0x001d, 0x00d2, 0x0201, 0x002d, 0x0201,
0x007b, 0x00d3, 0x3401, 0x1c01, 0x0c01, 0x0401, 0x0201, 0x003d, 0x00c6, 0x0401, 0x0201, 0x006c, 0x00a9, 0x0201, 0x009a, 0x00d4,
0x0801, 0x0401, 0x0201, 0x00b8, 0x008b, 0x0201, 0x004d, 0x00c7, 0x0401, 0x0201, 0x007c, 0x00d5, 0x0201, 0x005d, 0x00e0, 0x0a01,
0x0401, 0x0201, 0x00e1, 0x001e, 0x0401, 0x0201, 0x000e, 0x002e, 0x00e2, 0x0801, 0x0401, 0x0201, 0x00e3, 0x006d, 0x0201, 0x008c,
0x00e4, 0x0401, 0x0201, 0x00e5, 0x00ba, 0x00f0, 0x2601, 0x1001, 0x0401, 0x0201, 0x00f1, 0x001f, 0x0601, 0x0401, 0x0201, 0x00aa,
0x009b, 0x00b9, 0x0201, 0x003e, 0x0201, 0x00d6, 0x00c8, 0x0c01, 0x0601, 0x0201, 0x004e, 0x0201, 0x00d7, 0x007d, 0x0201, 0x00ab,
0x0201, 0x005e, 0x00c9, 0x0601, 0x0201, 0x000f, 0x0201, 0x009c, 0x006e, 0x0201, 0x00f2, 0x002f, 0x2001, 0x1001, 0x0601, 0x0401,
0x0201, 0x00d8, 0x008d, 0x003f, 0x0601, 0x0201, 0x00f3, 0x0201, 0x00e6, 0x00ca, 0x0201, 0x00f4, 0x004f, 0x0801, 0x0401, 0x0201,
0x00bb, 0x00ac, 0x0201, 0x00e7, 0x00f5, 0x0401, 0x0201, 0x00d9, 0x009d, 0x0201, 0x005f, 0x00e8, 0x1e01, 0x0c01, 0x0601, 0x0201,
0x006f, 0x0201, 0x00f6, 0x00cb, 0x0401, 0x0201, 0x00bc, 0x00ad, 0x00da, 0x0801, 0x0201, 0x00f7, 0x0401, 0x0201, 0x007e, 0x007f,
0x008e, 0x0601, 0x0401, 0x0201, 0x009e, 0x00ae, 0x00cc, 0x0201, 0x00f8, 0x008f, 0x1201, 0x0801, 0x0401, 0x0201, 0x00db, 0x00bd,
0x0201, 0x00ea, 0x00f9, 0x0401, 0x0201, 0x009f, 0x00eb, 0x0201, 0x00be, 0x0201, 0x00cd, 0x00fa, 0x0e01, 0x0401, 0x0201, 0x00dd,
0x00ec, 0x0601, 0x0401, 0x0201, 0x00e9, 0x00af, 0x00dc, 0x0201, 0x00ce, 0x00fb, 0x0801, 0x0401, 0x0201, 0x00bf, 0x00de, 0x0201,
0x00cf, 0x00ee, 0x0401, 0x0201, 0x00df, 0x00ef, 0x0201, 0x00ff, 0x0201, 0x00ed, 0x0201, 0x00fd, 0x0201, 0x00fc, 0x00fe,
},
[15] = {
0x1001, 0x0601, 0x0201, 0x0000, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, 0x0012,
0x3201, 0x1001, 0x0601, 0x0201, 0x0022, 0x0201, 0x0030, 0x0031, 0x0601, 0x0201, 0x0013, 0x0201, 0x0003, 0x0040, 0x0201, 0x0032,
0x0023, 0x0e01, 0x0601, 0x0401, 0x0201, 0x0004, 0x0014, 0x0041, 0x0401, 0x0201, 0x0033, 0x0042, 0x0201, 0x0024, 0x0043, 0x0a01,
0x0601, 0x0201, 0x0034, 0x0201, 0x0050, 0x0005, 0x0201, 0x0051, 0x0015, 0x0401, 0x0201, 0x0052, 0x0025, 0x0401, 0x0201, 0x0044,
0x0053, 0x0061, 0x5a01, 0x2401, 0x1201, 0x0a01, 0x0601, 0x0201, 0x0035, 0x0201, 0x0060, 0x0006, 0x0201, 0x0016, 0x0062, 0x0401,
0x0201, 0x0026, 0x0054, 0x0201, 0x0045, 0x0063, 0x0a01, 0x0601, 0x0201, 0x0036, 0x0201, 0x0070, 0x0007, 0x0201, 0x0071, 0x0055,
0x0401, 0x0201, 0x0017, 0x0064, 0x0201, 0x0072, 0x0027, 0x1801, 0x1001, 0x0801, 0x0401, 0x0201, 0x0046, 0x0073, 0x0201, 0x0037,
0x0065, 0x0401, 0x0201, 0x0056, 0x0080, 0x0201, 0x0008, 0x0074, 0x0401, 0x0201, 0x0081, 0x0018, 0x0201, 0x0082, 0x0028, 0x1001,
0x0801, 0x0401, 0x0201, 0x0047, 0x0066, 0x0201, 0x0083, 0x0038, 0x0401, 0x0201, 0x0075, 0x0057, 0x0201, 0x0084, 0x0048, 0x0601,
0x0401, 0x0201, 0x0090, 0x0019, 0x0091, 0x0401, 0x0201, 0x0092, 0x0076, 0x0201, 0x0067, 0x0029, 0x5c01, 0x2401, 0x1201, 0x0a01,
0x0401, 0x0201, 0x0085, 0x0058, 0x0401, 0x0201, 0x0009, 0x0077, 0x0093, 0x0401, 0x0201, 0x0039, 0x0094, 0x0201, 0x0049, 0x0086,
0x0a01, 0x0601, 0x0201, 0x0068, 0x0201, 0x00a0, 0x000a, 0x0201, 0x00a1, 0x001a, 0x0401, 0x0201, 0x00a2, 0x002a, 0x0201, 0x0095,
0x0059, 0x1a01, 0x0e01, 0x0601, 0x0201, 0x00a3, 0x0201, 0x003a, 0x0087, 0x0401, 0x0201, 0x0078, 0x00a4, 0x0201, 0x004a, 0x0096,
0x0601, 0x0401, 0x0201, 0x0069, 0x00b0, 0x00b1, 0x0401, 0x0201, 0x001b, 0x00a5, 0x00b2, 0x0e01, 0x0801, 0x0401, 0x0201, 0x005a,
0x002b, 0x0201, 0x0088, 0x0097, 0x0201, 0x00b3, 0x0201, 0x0079, 0x003b, 0x0801, 0x0401, 0x0201, 0x006a, 0x00b4, 0x0201, 0x004b,
0x00c1, 0x0401, 0x0201, 0x0098, 0x0089, 0x0201, 0x001c, 0x00b5, 0x5001, 0x2201, 0x1001, 0x0601, 0x0401, 0x0201, 0x005b, 0x002c,
0x00c2, 0x0601, 0x0401, 0x0201, 0x000b, 0x00c0, 0x00a6, 0x0201, 0x00a7, 0x007a, 0x0a01, 0x0401, 0x0201, 0x00c3, 0x003c, 0x0401,
0x0201, 0x000c, 0x0099, 0x00b6, 0x0401, 0x0201, 0x006b, 0x00c4, 0x0201, 0x004c, 0x00a8, 0x1401, 0x0a01, 0x0401, 0x0201, 0x008a,
0x00c5, 0x0401, 0x0201, 0x00d0, 0x005c, 0x00d1, 0x0401, 0x0201, 0x00b7, 0x007b, 0x0201, 0x001d, 0x0201, 0x000d, 0x002d, 0x0c01,
0x0401, 0x0201, 0x00d2, 0x00d3, 0x0401, 0x0201, 0x003d, 0x00c6, 0x0201, 0x006c, 0x00a9, 0x0601, 0x0401, 0x0201, 0x009a, 0x00b8,
0x00d4, 0x0401, 0x0201, 0x008b, 0x004d, 0x0201, 0x00c7, 0x007c, 0x4401, 0x2201, 0x1201, 0x0a01, 0x0401, 0x0201, 0x00d5, 0x005d,
0x0401, 0x0201, 0x00e0, 0x000e, 0x00e1, 0x0401, 0x0201, 0x001e, 0x00e2, 0x0201, 0x00aa, 0x002e, 0x0801, 0x0401, 0x0201, 0x00b9,
0x009b, 0x0201, 0x00e3, 0x00d6, 0x0401, 0x0201, 0x006d, 0x003e, 0x0201, 0x00c8, 0x008c, 0x1001, 0x0801, 0x0401, 0x0201, 0x00e4,
0x004e, 0x0201, 0x00d7, 0x007d, 0x0401, 0x0201, 0x00e5, 0x00ba, 0x0201, 0x00ab, 0x005e, 0x0801, 0x0401, 0x0201, 0x00c9, 0x009c,
0x0201, 0x00f1, 0x001f, 0x0601, 0x0401, 0x0201, 0x00f0, 0x006e, 0x00f2, 0x0201, 0x002f, 0x00e6, 0x2601, 0x1201, 0x0801, 0x0401,
0x0201, 0x00d8, 0x00f3, 0x0201, 0x003f, 0x00f4, 0x0601, 0x0201, 0x004f, 0x0201, 0x008d, 0x00d9, 0x0201, 0x00bb, 0x00ca, 0x0801,
0x0401, 0x0201, 0x00ac, 0x00e7, 0x0201, 0x007e, 0x00f5, 0x0801, 0x0401, 0x0201, 0x009d, 0x005f, 0x0201, 0x00e8, 0x008e, 0x0201,
0x00f6, 0x00cb, 0x2201, 0x1201, 0x0a01, 0x0601, 0x0401, 0x0201, 0x000f, 0x00ae, 0x006f, 0x0201, 0x00bc, 0x00da, 0x0401, 0x0201,
0x00ad, 0x00f7, 0x0201, 0x007f, 0x00e9, 0x0801, 0x0401, 0x0201, 0x009e, 0x00cc, 0x0201, 0x00f8, 0x008f, 0x0401, 0x0201, 0x00db,
0x00bd, 0x0201, 0x00ea, 0x00f9, 0x1001, 0x0801, 0x0401, 0x0201, 0x009f, 0x00dc, 0x0201, 0x00cd, 0x00eb, 0x0401, 0x0201, 0x00be,
0x00fa, 0x0201, 0x00af, 0x00dd, 0x0e01, 0x0601, 0x0401, 0x0201, 0x00ec, 0x00ce, 0x00fb, 0x0401, 0x0201, 0x00bf, 0x00ed, 0x0201,
0x00de, 0x00fc, 0x0601, 0x0401, 0x0201, 0x00cf, 0x00fd, 0x00ee, 0x0401, 0x0201, 0x00df, 0x00fe, 0x0201, 0x00ef, 0x00ff,
},
[16] = {
0x0201, 0x0000, 0x0601, 0x0201, 0x0010, 0x0201, 0x0001, 0x0011, 0x2a01, 0x0801, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021,
0x0012, 0x0a01, 0x0601, 0x0201, 0x0022, 0x0201, 0x0030, 0x0003, 0x0201, 0x0031, 0x0013, 0x0a01, 0x0401, 0x0201, 0x0032, 0x0023,
0x0401, 0x0201, 0x0040, 0x0004, 0x0041, 0x0601, 0x0201, 0x0014, 0x0201, 0x0033, 0x0042, 0x0401, 0x0201, 0x0024, 0x0050, 0x0201,
0x0043, 0x0034, 0x8a01, 0x2801, 0x1001, 0x0601, 0x0401, 0x0201, 0x0005, 0x0015, 0x0051, 0x0401, 0x0201, 0x0052, 0x0025, 0x0401,
0x0201, 0x0044, 0x0035, 0x0053, 0x0a01, 0x0601, 0x0401, 0x0201, 0x0060, 0x0006, 0x0061, 0x0201, 0x0016, 0x0062, 0x0801, 0x0401,
0x0201, 0x0026, 0x0054, 0x0201, 0x0045, 0x0063, 0x0401, 0x0201, 0x0036, 0x0070, 0x0071, 0x2801, 0x1201, 0x0801, 0x0201, 0x0017,
0x0201, 0x0007, 0x0201, 0x0055, 0x0064, 0x0401, 0x0201, 0x0072, 0x0027, 0x0401, 0x0201, 0x0046, 0x0065, 0x0073, 0x0a01, 0x0601,
0x0201, 0x0037, 0x0201, 0x0056, 0x0008, 0x0201, 0x0080, 0x0081, 0x0601, 0x0201, 0x0018, 0x0201, 0x0074, 0x0047, 0x0201, 0x0082,
0x0201, 0x0028, 0x0066, 0x1801, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0083, 0x0038, 0x0201, 0x0075, 0x0084, 0x0401, 0x0201, 0x0048,
0x0090, 0x0091, 0x0601, 0x0201, 0x0019, 0x0201, 0x0009, 0x0076, 0x0201, 0x0092, 0x0029, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0085,
0x0058, 0x0201, 0x0093, 0x0039, 0x0401, 0x0201, 0x00a0, 0x000a, 0x001a, 0x0801, 0x0201, 0x00a2, 0x0201, 0x0067, 0x0201, 0x0057,
0x0049, 0x0601, 0x0201, 0x0094, 0x0201, 0x0077, 0x0086, 0x0201, 0x00a1, 0x0201, 0x0068, 0x0095, 0xdc01, 0x7e01, 0x3201, 0x1a01,
0x0c01, 0x0601, 0x0201, 0x002a, 0x0201, 0x0059, 0x003a, 0x0201, 0x00a3, 0x0201, 0x0087, 0x0078, 0x0801, 0x0401, 0x0201, 0x00a4,
0x004a, 0x0201, 0x0096, 0x0069, 0x0401, 0x0201, 0x00b0, 0x000b, 0x00b1, 0x0a01, 0x0401, 0x0201, 0x001b, 0x00b2, 0x0201, 0x002b,
0x0201, 0x00a5, 0x005a, 0x0601, 0x0201, 0x00b3, 0x0201, 0x00a6, 0x006a, 0x0401, 0x0201, 0x00b4, 0x004b, 0x0201, 0x000c, 0x00c1,
0x1e01, 0x0e01, 0x0601, 0x0401, 0x0201, 0x00b5, 0x00c2, 0x002c, 0x0401, 0x0201, 0x00a7, 0x00c3, 0x0201, 0x006b, 0x00c4, 0x0801,
0x0201, 0x001d, 0x0401, 0x0201, 0x0088, 0x0097, 0x003b, 0x0401, 0x0201, 0x00d1, 0x00d2, 0x0201, 0x002d, 0x00d3, 0x1201, 0x0601,
0x0401, 0x0201, 0x001e, 0x002e, 0x00e2, 0x0601, 0x0401, 0x0201, 0x0079, 0x0098, 0x00c0, 0x0201, 0x001c, 0x0201, 0x0089, 0x005b,
0x0e01, 0x0601, 0x0201, 0x003c, 0x0201, 0x007a, 0x00b6, 0x0401, 0x0201, 0x004c, 0x0099, 0x0201, 0x00a8, 0x008a, 0x0601, 0x0201,
0x000d, 0x0201, 0x00c5, 0x005c, 0x0401, 0x0201, 0x003d, 0x00c6, 0x0201, 0x006c, 0x009a, 0x5801, 0x5601, 0x2401, 0x1001, 0x0801,
0x0401, 0x0201, 0x008b, 0x004d, 0x0201, 0x00c7, 0x007c, 0x0401, 0x0201, 0x00d5, 0x005d, 0x0201, 0x00e0, 0x000e, 0x0801, 0x0201,
0x00e3, 0x0401, 0x0201, 0x00d0, 0x00b7, 0x007b, 0x0601, 0x0401, 0x0201, 0x00a9, 0x00b8, 0x00d4, 0x0201, 0x00e1, 0x0201, 0x00aa,
0x00b9, 0x1801, 0x0a01, 0x0601, 0x0401, 0x0201, 0x009b, 0x00d6, 0x006d, 0x0201, 0x003e, 0x00c8, 0x0601, 0x0401, 0x0201, 0x008c,
0x00e4, 0x004e, 0x0401, 0x0201, 0x00d7, 0x00e5, 0x0201, 0x00ba, 0x00ab, 0x0c01, 0x0401, 0x0201, 0x009c, 0x00e6, 0x0401, 0x0201,
0x006e, 0x00d8, 0x0201, 0x008d, 0x00bb, 0x0801, 0x0401, 0x0201, 0x00e7, 0x009d, 0x0201, 0x00e8, 0x008e, 0x0401, 0x0201, 0x00cb,
0x00bc, 0x009e, 0x00f1, 0x0201, 0x001f, 0x0201, 0x000f, 0x002f, 0x4201, 0x3801, 0x0201, 0x00f2, 0x3401, 0x3201, 0x1401, 0x0801,
0x0201, 0x00bd, 0x0201, 0x005e, 0x0201, 0x007d, 0x00c9, 0x0601, 0x0201, 0x00ca, 0x0201, 0x00ac, 0x007e, 0x0401, 0x0201, 0x00da,
0x00ad, 0x00cc, 0x0a01, 0x0601, 0x0201, 0x00ae, 0x0201, 0x00db, 0x00dc, 0x0201, 0x00cd, 0x00be, 0x0601, 0x0401, 0x0201, 0x00eb,
0x00ed, 0x00ee, 0x0601, 0x0401, 0x0201, 0x00d9, 0x00ea, 0x00e9, 0x0201, 0x00de, 0x0401, 0x0201, 0x00dd, 0x00ec, 0x00ce, 0x003f,
0x00f0, 0x0401, 0x0201, 0x00f3, 0x00f4, 0x0201, 0x004f, 0x0201, 0x00f5, 0x005f, 0x0a01, 0x0201, 0x00ff, 0x0401, 0x0201, 0x00f6,
0x006f, 0x0201, 0x00f7, 0x007f, 0x0c01, 0x0601, 0x0201, 0x008f, 0x0201, 0x00f8, 0x00f9, 0x0401, 0x0201, 0x009f, 0x00fa, 0x00af,
0x0801, 0x0401, 0x0201, 0x00fb, 0x00bf, 0x0201, 0x00fc, 0x00cf, 0x0401, 0x0201, 0x00fd, 0x00df, 0x0201, 0x00fe, 0x00ef,
},
[24] = {
0x3c01, 0x0801, 0x0401, 0x0201, 0x0000, 0x0010, 0x0201, 0x0001, 0x0011, 0x0e01, 0x0601, 0x0401, 0x0201, 0x0020, 0x0002, 0x0021,
0x0201, 0x0012, 0x0201, 0x0022, 0x0201, 0x0030, 0x0003, 0x0e01, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0032, 0x0023,
0x0401, 0x0201, 0x0040, 0x0004, 0x0041, 0x0801, 0x0401, 0x0201, 0x0014, 0x0033, 0x0201, 0x0042, 0x0024, 0x0601, 0x0401, 0x0201,
0x0043, 0x0034, 0x0051, 0x0601, 0x0401, 0x0201, 0x0050, 0x0005, 0x0015, 0x0201, 0x0052, 0x0025, 0xfa01, 0x6201, 0x2201, 0x1201,
0x0a01, 0x0401, 0x0201, 0x0044, 0x0053, 0x0201, 0x0035, 0x0201, 0x0060, 0x0006, 0x0401, 0x0201, 0x0061, 0x0016, 0x0201, 0x0062,
0x0026, 0x0801, 0x0401, 0x0201, 0x0054, 0x0045, 0x0201, 0x0063, 0x0036, 0x0401, 0x0201, 0x0071, 0x0055, 0x0201, 0x0064, 0x0046,
0x2001, 0x0e01, 0x0601, 0x0201, 0x0072, 0x0201, 0x0027, 0x0037, 0x0201, 0x0073, 0x0401, 0x0201, 0x0070, 0x0007, 0x0017, 0x0a01,
0x0401, 0x0201, 0x0065, 0x0056, 0x0401, 0x0201, 0x0080, 0x0008, 0x0081, 0x0401, 0x0201, 0x0074, 0x0047, 0x0201, 0x0018, 0x0082,
0x1001, 0x0801, 0x0401, 0x0201, 0x0028, 0x0066, 0x0201, 0x0083, 0x0038, 0x0401, 0x0201, 0x0075, 0x0057, 0x0201, 0x0084, 0x0048,
0x0801, 0x0401, 0x0201, 0x0091, 0x0019, 0x0201, 0x0092, 0x0076, 0x0401, 0x0201, 0x0067, 0x0029, 0x0201, 0x0085, 0x0058, 0x5c01,
0x2201, 0x1001, 0x0801, 0x0401, 0x0201, 0x0093, 0x0039, 0x0201, 0x0094, 0x0049, 0x0401, 0x0201, 0x0077, 0x0086, 0x0201, 0x0068,
0x00a1, 0x0801, 0x0401, 0x0201, 0x00a2, 0x002a, 0x0201, 0x0095, 0x0059, 0x0401, 0x0201, 0x00a3, 0x003a, 0x0201, 0x0087, 0x0201,
0x0078, 0x004a, 0x1601, 0x0c01, 0x0401, 0x0201, 0x00a4, 0x0096, 0x0401, 0x0201, 0x0069, 0x00b1, 0x0201, 0x001b, 0x00a5, 0x0601,
0x0201, 0x00b2, 0x0201, 0x005a, 0x002b, 0x0201, 0x0088, 0x00b3, 0x1001, 0x0a01, 0x0601, 0x0201, 0x0090, 0x0201, 0x0009, 0x00a0,
0x0201, 0x0097, 0x0079, 0x0401, 0x0201, 0x00a6, 0x006a, 0x00b4, 0x0c01, 0x0601, 0x0201, 0x001a, 0x0201, 0x000a, 0x00b0, 0x0201,
0x003b, 0x0201, 0x000b, 0x00c0, 0x0401, 0x0201, 0x004b, 0x00c1, 0x0201, 0x0098, 0x0089, 0x4301, 0x2201, 0x1001, 0x0801, 0x0401,
0x0201, 0x001c, 0x00b5, 0x0201, 0x005b, 0x00c2, 0x0401, 0x0201, 0x002c, 0x00a7, 0x0201, 0x007a, 0x00c3, 0x0a01, 0x0601, 0x0201,
0x003c, 0x0201, 0x000c, 0x00d0, 0x0201, 0x00b6, 0x006b, 0x0401, 0x0201, 0x00c4, 0x004c, 0x0201, 0x0099, 0x00a8, 0x1001, 0x0801,
0x0401, 0x0201, 0x008a, 0x00c5, 0x0201, 0x005c, 0x00d1, 0x0401, 0x0201, 0x00b7, 0x007b, 0x0201, 0x001d, 0x00d2, 0x0901, 0x0401,
0x0201, 0x002d, 0x00d3, 0x0201, 0x003d, 0x00c6, 0x55fa, 0x0401, 0x0201, 0x006c, 0x00a9, 0x0201, 0x009a, 0x00d4, 0x2001, 0x1001,
0x0801, 0x0401, 0x0201, 0x00b8, 0x008b, 0x0201, 0x004d, 0x00c7, 0x0401, 0x0201, 0x007c, 0x00d5, 0x0201, 0x005d, 0x00e1, 0x0801,
0x0401, 0x0201, 0x001e, 0x00e2, 0x0201, 0x00aa, 0x00b9, 0x0401, 0x0201, 0x009b, 0x00e3, 0x0201, 0x00d6, 0x006d, 0x1401, 0x0a01,
0x0601, 0x0201, 0x003e, 0x0201, 0x002e, 0x004e, 0x0201, 0x00c8, 0x008c, 0x0401, 0x0201, 0x00e4, 0x00d7, 0x0401, 0x0201, 0x007d,
0x00ab, 0x00e5, 0x0a01, 0x0401, 0x0201, 0x00ba, 0x005e, 0x0201, 0x00c9, 0x0201, 0x009c, 0x006e, 0x0801, 0x0201, 0x00e6, 0x0201,
0x000d, 0x0201, 0x00e0, 0x000e, 0x0401, 0x0201, 0x00d8, 0x008d, 0x0201, 0x00bb, 0x00ca, 0x4a01, 0x0201, 0x00ff, 0x4001, 0x3a01,
0x2001, 0x1001, 0x0801, 0x0401, 0x0201, 0x00ac, 0x00e7, 0x0201, 0x007e, 0x00d9, 0x0401, 0x0201, 0x009d, 0x00e8, 0x0201, 0x008e,
0x00cb, 0x0801, 0x0401, 0x0201, 0x00bc, 0x00da, 0x0201, 0x00ad, 0x00e9, 0x0401, 0x0201, 0x009e, 0x00cc, 0x0201, 0x00db, 0x00bd,
0x1001, 0x0801, 0x0401, 0x0201, 0x00ea, 0x00ae, 0x0201, 0x00dc, 0x00cd, 0x0401, 0x0201, 0x00eb, 0x00be, 0x0201, 0x00dd, 0x00ec,
0x0801, 0x0401, 0x0201, 0x00ce, 0x00ed, 0x0201, 0x00de, 0x00ee, 0x000f, 0x0401, 0x0201, 0x00f0, 0x001f, 0x00f1, 0x0401, 0x0201,
0x00f2, 0x002f, 0x0201, 0x00f3, 0x003f, 0x1201, 0x0801, 0x0401, 0x0201, 0x00f4, 0x004f, 0x0201, 0x00f5, 0x005f, 0x0401, 0x0201,
0x00f6, 0x006f, 0x0201, 0x00f7, 0x0201, 0x007f, 0x008f, 0x0a01, 0x0401, 0x0201, 0x00f8, 0x00f9, 0x0401, 0x0201, 0x009f, 0x00af,
0x00fa, 0x0801, 0x0401, 0x0201, 0x00fb, 0x00bf, 0x0201, 0x00fc, 0x00cf, 0x0401, 0x0201, 0x00fd, 0x00df, 0x0201, 0x00fe, 0x00ef,
},
[32] = {
0x0201, 0x0000, 0x0801, 0x0401, 0x0201, 0x0008, 0x0004, 0x0201, 0x0001, 0x0002, 0x0801, 0x0401, 0x0201, 0x000c, 0x000a, 0x0201,
0x0003, 0x0006, 0x0601, 0x0201, 0x0009, 0x0201, 0x0005, 0x0007, 0x0401, 0x0201, 0x000e, 0x000d, 0x0201, 0x000f, 0x000b,
},
[33] = {
0x1001, 0x0801, 0x0401, 0x0201, 0x0000, 0x0001, 0x0201, 0x0002, 0x0003, 0x0401, 0x0201, 0x0004, 0x0005, 0x0201, 0x0006, 0x0007,
0x0801, 0x0401, 0x0201, 0x0008, 0x0009, 0x0201, 0x000a, 0x000b, 0x0401, 0x0201, 0x000c, 0x000d, 0x0201, 0x000e, 0x000f,
},
}
return E
+407
View File
@@ -0,0 +1,407 @@
--!strict
--!native
--!optimize 2
-- audio/mp3/Encode2: an MPEG audio layer II (MP2) encoder: constant bit rate, MPEG-1 (32 / 44.1 / 48 kHz) and MPEG-2
-- low sampling frequencies (16 / 22.05 / 24 kHz), mono or stereo. New code written from ISO/IEC 11172-3 (2.4.2.3,
-- C.1.5.2): the polyphase analysis (audio/mp3/Analysis), one scalefactor per 12-sample part (scfsi 0: all three are
-- sent), the standard bit allocation tables (in minimp3's compact form, CC0: licenses/minimp3-CC0.txt, as the decoder
-- in this folder reads them), a greedy allocation that always gives the next step to the band with the most noise
-- (signal level minus the quantizer's SNR; no psychoacoustic model), uniform midtread quantization and grouping of
-- 3 / 5 / 9-level samples. Never throws.
local T = require("@formats/audio/mp3/Tables")
local Analysis = require("@formats/audio/mp3/Analysis")
local Encode2 = {}
local floor, log = math.floor, math.log
local writeu8 = buffer.writeu8
local POW = table.create(40, 0)
for i = 0, 39 do
POW[i + 1] = 2 ^ i
end
-- the allocation tables: { bit-allocation-code offset into g_bitalloc_code_tab, bits, band count } runs (minimp3)
local ALLOC_L2M1 = { 0, 4, 3, 16, 4, 8, 32, 3, 12, 40, 2, 7 }
local ALLOC_L2M1_LOW = { 44, 4, 2, 44, 3, 10 }
local ALLOC_L2M2 = { 60, 4, 4, 44, 3, 7, 44, 2, 19 }
local CODE = T.g_bitalloc_code_tab
-- quantizer classes (minimp3's ba): 1..16 -> 2^ba - 1 levels in ba bits; 17 / 18 / 19 -> 3 / 5 / 9 levels grouped
local function levels(ba: number): number
if ba >= 17 then
return if ba == 17 then 3 elseif ba == 18 then 5 else 9
end
return POW[ba + 1] - 1
end
-- bits for the 3 samples of one granule
local function tripleBits(ba: number): number
if ba >= 17 then
return if ba == 17 then 5 elseif ba == 18 then 7 else 10
end
return 3 * ba
end
-- the quantizer's signal-to-noise ratio in dB (ISO 11172-3 table C.5)
local SNR: { [number]: number } = {}
do
local byLevels = {
[3] = 7.00,
[5] = 11.00,
[7] = 16.00,
[9] = 20.84,
[15] = 25.28,
[31] = 31.59,
[63] = 37.75,
[127] = 43.84,
[255] = 49.89,
[511] = 55.93,
[1023] = 61.96,
[2047] = 67.98,
[4095] = 74.01,
[8191] = 80.03,
[16383] = 86.05,
[32767] = 92.01,
[65535] = 98.01,
}
for ba = 1, 19 do
SNR[ba] = byLevels[levels(ba)] or (6.02 * ba)
end
end
-- scalefactors 2^(1 - i/3), i = 0 .. 62
local SCF = table.create(63, 0)
for i = 0, 62 do
SCF[i + 1] = 2 ^ (1 - i / 3)
end
local RATES = {
[44100] = { 3, 0 },
[48000] = { 3, 1 },
[32000] = { 3, 2 },
[22050] = { 2, 0 },
[24000] = { 2, 1 },
[16000] = { 2, 2 },
}
Encode2.RATES = RATES
local BITRATES_V1 = { 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384 }
local BITRATES_V2 = { 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 }
Encode2.BITRATES = { [1] = BITRATES_V1, [2] = BITRATES_V2 }
type W = { buf: buffer, pos: number, acc: number, cnt: number }
local function put(w: W, v: number, n: number)
if n == 0 then
return
end
local acc = w.acc * POW[n + 1] + v
local cnt = w.cnt + n
local b, p = w.buf, w.pos
while cnt >= 8 do
cnt -= 8
local m = POW[cnt + 1]
local byte = floor(acc / m)
writeu8(b, p, byte)
p += 1
acc -= byte * m
end
w.acc, w.cnt, w.pos = acc, cnt, p
end
export type Source = {
sampleRate: number,
channels: number,
frames: number,
read: (self: any, n: number, out: buffer?) -> (buffer, number),
err: any,
}
export type Options = { bitrate: number, mode: string, prefix: buffer? }
-- encode(src, opts) -> buffer | nil, message
function Encode2.encode(src: Source, opts: Options): (buffer?, string?)
local rate = src.sampleRate
local info = RATES[rate]
if not info then
return nil, "unsupported sample rate"
end
local version, srIndex = info[1], info[2]
local mpeg1 = version == 3
local inCh = src.channels
local nch = if opts.mode == "mono" then 1 else 2
local kbps = opts.bitrate
local list = if mpeg1 then BITRATES_V1 else BITRATES_V2
local brIndex = table.find(list, kbps)
if not brIndex then
return nil, "unsupported bit rate"
end
-- the allocation table (the decoder's choice from the header)
local alloc, nbands
if not mpeg1 then
alloc, nbands = ALLOC_L2M2, 30
else
local perCh = if nch == 2 then kbps // 2 else kbps
alloc, nbands = ALLOC_L2M1, 27
if perCh < 56 then
alloc, nbands = ALLOC_L2M1_LOW, if srIndex == 2 then 12 else 8
elseif perCh >= 96 and srIndex ~= 1 then
nbands = 30
end
end
local bandOff, bandBits = table.create(nbands, 0), table.create(nbands, 0)
do
local k, ai = 0, 1
local off, bits = 0, 0
for i = 0, nbands - 1 do
if i == k then
off, bits, k = alloc[ai], alloc[ai + 1], k + alloc[ai + 2]
ai += 3
end
bandOff[i + 1], bandBits[i + 1] = off, bits
end
end
-- per band: the classes it can take, in increasing order (index into the code table = the value written)
local steps: { { { number } } } = {}
for i = 1, nbands do
local s = {}
for v = 1, POW[bandBits[i] + 1] - 1 do
local ba = CODE[bandOff[i] + v]
if ba and ba > 0 then
table.insert(s, { v, ba })
end
end
steps[i] = s
end
local w: W = { buf = buffer.create(65536), pos = 0, acc = 0, cnt = 0 }
if opts.prefix then
local pf = opts.prefix :: buffer
if buffer.len(pf) > buffer.len(w.buf) - 16 then
w.buf = buffer.create(buffer.len(pf) + 65536)
end
buffer.copy(w.buf, 0, pf, 0, buffer.len(pf))
w.pos = buffer.len(pf)
end
local ana = { Analysis.new(), Analysis.new() }
local pcm = { table.create(1152, 0), table.create(1152, 0) }
-- subband samples: sb[c][band * 36 + t + 1], t = 0 .. 35
local sbs = { table.create(32 * 36, 0), table.create(32 * 36, 0) }
local sub = table.create(32, 0)
local scf = { table.create(32 * 3, 0), table.create(32 * 3, 0) } -- scalefactor index per band and part
local bal = { table.create(32, 0), table.create(32, 0) } -- allocation step (0 = none) per band
local slot = 144000 * kbps
local rest = 0
local tmp: buffer? = nil
local pending: buffer? = nil
local pendN, pendOff = 0, 0
local srcDone, flushed = false, false
while true do
local got = 0
while got < 1152 and not srcDone do
if pendN == 0 then
local b, n = src:read(4096, tmp)
if n <= 0 then
srcDone = true
break
end
tmp = b
pending, pendN, pendOff = b, n, 0
end
local take = math.min(1152 - got, pendN)
local pb = pending :: buffer
for i = 0, take - 1 do
local base = (pendOff + i) * inCh * 4
local l = buffer.readf32(pb, base)
local r = if inCh > 1 then buffer.readf32(pb, base + 4) else l
if nch == 1 then
pcm[1][got + i + 1] = if inCh > 1 then (l + r) * 0.5 else l
else
pcm[1][got + i + 1] = l
pcm[2][got + i + 1] = r
end
end
got += take
pendN -= take
pendOff += take
end
if got == 0 then
if flushed then
break
end
flushed = true
end
for c = 1, nch do
local s = pcm[c]
for i = got + 1, 1152 do
s[i] = 0
end
local sb = sbs[c]
for t = 0, 35 do
Analysis.run(ana[c], s, t * 32 + 1, sub, 1)
for b = 0, 31 do
sb[b * 36 + t + 1] = sub[b + 1]
end
end
-- scalefactors: the smallest scalefactor (largest index) still >= the part's peak
local sc = scf[c]
for b = 0, nbands - 1 do
for part = 0, 2 do
local m = 0
local o = b * 36 + part * 12
for t = 1, 12 do
local v = math.abs(sb[o + t])
if v > m then
m = v
end
end
local idx = 62
if m > 0 then
idx = math.clamp(floor(3 * (1 - log(m) / log(2))), 0, 62)
while idx > 0 and SCF[idx + 1] < m do
idx -= 1
end
while idx < 62 and SCF[idx + 2] >= m do
idx += 1
end
end
sc[b * 3 + part + 1] = idx
end
end
end
-- the frame size and the bits left for scalefactors and samples
local frameBytes = slot // rate
rest += slot % rate
local padding = 0
if rest >= rate then
rest -= rate
padding = 1
frameBytes += 1
end
local avail = frameBytes * 8 - 32
for b = 1, nbands do
avail -= bandBits[b] * nch
end
-- greedy allocation: the band with the most noise gets its next step while it fits
local level = { table.create(nbands, 0), table.create(nbands, 0) } -- signal level (dB) per band
for c = 1, nch do
local sc = scf[c]
for b = 1, nbands do
local best = math.min(sc[(b - 1) * 3 + 1], sc[(b - 1) * 3 + 2], sc[(b - 1) * 3 + 3])
level[c][b] = 20 * math.log10(SCF[best + 1])
bal[c][b] = 0
end
end
while true do
local bestC, bestB, bestNoise, bestCost = 0, 0, -math.huge, 0
for c = 1, nch do
for b = 1, nbands do
local st = bal[c][b]
local s = steps[b]
if st < #s and level[c][b] > -110 then
local cur = if st == 0 then 0 else s[st][2]
local nxt = s[st + 1][2]
local noise = level[c][b] - (if st == 0 then 0 else SNR[cur])
local cost = 12 * tripleBits(nxt) - (if st == 0 then 0 else 12 * tripleBits(cur))
if st == 0 then
cost += 2 + 18 -- scfsi + three scalefactors
end
if cost <= avail and noise > bestNoise then
bestC, bestB, bestNoise, bestCost = c, b, noise, cost
end
end
end
end
if bestC == 0 then
break
end
bal[bestC][bestB] += 1
avail -= bestCost
end
-- write the frame
if w.pos + frameBytes + 64 > buffer.len(w.buf) then
local nb = buffer.create(buffer.len(w.buf) * 2 + frameBytes)
buffer.copy(nb, 0, w.buf, 0, w.pos)
w.buf = nb
end
local start = w.pos
put(w, 0x7FF, 11)
put(w, version, 2)
put(w, 2, 2) -- layer II
put(w, 1, 1) -- no CRC
put(w, brIndex, 4)
put(w, srIndex, 2)
put(w, padding, 1)
put(w, 0, 1)
put(w, if nch == 1 then 3 else 0, 2)
put(w, 0, 2)
put(w, 0, 1)
put(w, 1, 1)
put(w, 0, 2)
-- bit allocation
for b = 1, nbands do
for c = 1, nch do
local st = bal[c][b]
put(w, if st == 0 then 0 else steps[b][st][1], bandBits[b])
end
end
-- scfsi (0: three scalefactors) and the scalefactors
for b = 1, nbands do
for c = 1, nch do
if bal[c][b] > 0 then
put(w, 0, 2)
end
end
end
for b = 1, nbands do
for c = 1, nch do
if bal[c][b] > 0 then
for part = 1, 3 do
put(w, scf[c][(b - 1) * 3 + part], 6)
end
end
end
end
-- samples: 12 granules of 3, band by band, channel by channel
for gr = 0, 11 do
local part = gr // 4
for b = 1, nbands do
for c = 1, nch do
local st = bal[c][b]
if st > 0 then
local ba = steps[b][st][2]
local L = levels(ba)
local inv = 1 / SCF[scf[c][(b - 1) * 3 + part + 1] + 1]
local o = (b - 1) * 36 + gr * 3
local sb = sbs[c]
local q0, q1, q2
do
local function quant(x: number): number
local q = floor((x * inv + 1) * L / 2)
return if q < 0 then 0 elseif q > L - 1 then L - 1 else q
end
q0, q1, q2 = quant(sb[o + 1]), quant(sb[o + 2]), quant(sb[o + 3])
end
if ba >= 17 then
put(w, q0 + L * (q1 + L * q2), tripleBits(ba))
else
put(w, q0, ba)
put(w, q1, ba)
put(w, q2, ba)
end
end
end
end
end
if w.cnt > 0 then
put(w, 0, 8 - w.cnt)
end
while w.pos < start + frameBytes do
writeu8(w.buf, w.pos, 0)
w.pos += 1
end
end
if src.err then
return nil, tostring(src.err)
end
local out = buffer.create(w.pos)
buffer.copy(out, 0, w.buf, 0, w.pos)
return out, nil
end
return Encode2
+680
View File
@@ -0,0 +1,680 @@
--!strict
--!native
--!optimize 2
-- audio/mp3/Encode3: an MPEG audio layer III encoder in the spirit of shine: constant bit rate, long blocks only,
-- global-gain rate control (no psychoacoustic model, scalefactors all zero), no bit reservoir (main_data_begin = 0),
-- MPEG-1 (32 / 44.1 / 48 kHz, two granules), MPEG-2 (16 / 22.05 / 24 kHz) and MPEG-2.5 (8 / 11.025 / 12 kHz), mono,
-- stereo or joint (mid / side) stereo. New code written from ISO/IEC 11172-3 / 13818-3 (no shine / LAME code): the
-- analysis filterbank (audio/mp3/Analysis), the 36-point MDCT with the sine window, the alias-reduction butterflies,
-- the x^(3/4) quantizer, big_values / count1 partitioning with per-region Huffman table choice; the Huffman codes are
-- derived from the standard's decoder trees (audio/mp3/EncTables, from PDMP3, public domain). Never throws.
local E = require("@formats/audio/mp3/EncTables")
local T = require("@formats/audio/mp3/Tables")
local Analysis = require("@formats/audio/mp3/Analysis")
local Encode3 = {}
local floor, sqrt, cos, pi = math.floor, math.sqrt, math.cos, math.pi
local writeu8 = buffer.writeu8
local POW = table.create(40, 0)
for i = 0, 39 do
POW[i + 1] = 2 ^ i
end
-- ------------------------------------------------------------------------------------------------ Huffman codes
-- CODE[t][x * 16 + y + 1], LEN[t][...] for the pair tables 1..31 (16..23 and 24..31 share a tree); count1 tables A
-- (32) and B (33) indexed by v * 8 + w * 4 + x * 2 + y + 1
local CODE: { [number]: { number } } = {}
local LEN: { [number]: { number } } = {}
local XLEN: { [number]: number } = {}
local function walk(tree: { number }, codes: { number }, lens: { number }, p: number, code: number, len: number)
local v = tree[p + 1]
if bit32.band(v, 0xFF00) == 0 then
local idx = bit32.band(v, 0xFF) + 1
if lens[idx] == 0 then
codes[idx], lens[idx] = code, len
end
return
end
-- left (bit 0): offsets of 250+ chain
local q = p
while bit32.rshift(tree[q + 1], 8) >= 250 do
q += bit32.rshift(tree[q + 1], 8)
end
q += bit32.rshift(tree[q + 1], 8)
walk(tree, codes, lens, q, code * 2, len + 1)
q = p
while bit32.band(tree[q + 1], 0xFF) >= 250 do
q += bit32.band(tree[q + 1], 0xFF)
end
q += bit32.band(tree[q + 1], 0xFF)
walk(tree, codes, lens, q, code * 2 + 1, len + 1)
end
for t = 1, 33 do
local src = if t >= 16 and t <= 23 then 16 elseif t >= 24 and t <= 31 then 24 else t
local tree = E.TREES[src]
if tree then
local codes, lens = table.create(256, 0), table.create(256, 0)
walk(tree, codes, lens, 0, 0, 0)
-- the leaf value of pair tables is x << 4 | y: index x * 16 + y + 1 (count1: the 4-bit vwxy)
CODE[t], LEN[t] = codes, lens
local xl = 0
for idx = 1, 256 do
if lens[idx] > 0 then
local x = (idx - 1) // 16
if x + 1 > xl then
xl = x + 1
end
end
end
XLEN[t] = xl
end
end
local LINBITS = E.LINBITS
-- the tables that hold values up to m (m <= 15), smallest first
local SMALL: { [number]: { number } } = {}
for m = 0, 15 do
local list = {}
for _, t in { 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15 } do
if XLEN[t] and XLEN[t] - 1 >= m then
table.insert(list, t)
end
end
SMALL[m] = list
end
-- ------------------------------------------------------------------------------------------------ bit writer
type W = { buf: buffer, pos: number, acc: number, cnt: number }
local function put(w: W, v: number, n: number)
if n == 0 then
return
end
local acc = w.acc * POW[n + 1] + v
local cnt = w.cnt + n
local b, p = w.buf, w.pos
while cnt >= 8 do
cnt -= 8
local m = POW[cnt + 1]
local byte = floor(acc / m)
writeu8(b, p, byte)
p += 1
acc -= byte * m
end
w.acc, w.cnt, w.pos = acc, cnt, p
end
Encode3.put = put
-- ------------------------------------------------------------------------------------------------ constants
local RATES = {
-- rate -> version bits (3 MPEG-1, 2 MPEG-2, 0 MPEG-2.5), sample rate index, scalefactor band group (g_scf_long)
[44100] = { 3, 0, 5 },
[48000] = { 3, 1, 6 },
[32000] = { 3, 2, 7 },
[22050] = { 2, 0, 2 },
[24000] = { 2, 1, 3 },
[16000] = { 2, 2, 4 },
[11025] = { 0, 0, 0 },
[12000] = { 0, 1, 0 },
[8000] = { 0, 2, 1 },
}
Encode3.RATES = RATES
local BITRATES_V1 = { 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320 }
local BITRATES_V2 = { 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 }
Encode3.BITRATES = { [1] = BITRATES_V1, [2] = BITRATES_V2 }
-- the 36-point MDCT (long blocks): X[k] = 1/9 sum_i w_i z_i cos(pi/72 (2i + 19)(2k + 1)), w_i = sin(pi/36 (i + 1/2))
local MDCT = table.create(18 * 36, 0)
for k = 0, 17 do
for i = 0, 35 do
MDCT[k * 36 + i + 1] = math.sin(pi / 36 * (i + 0.5)) * cos(pi / 72 * (2 * i + 19) * (2 * k + 1)) / 9
end
end
-- alias reduction coefficients
local CI = { -0.6, -0.535, -0.33, -0.185, -0.095, -0.041, -0.0142, -0.0037 }
local CS, CA = table.create(8, 0), table.create(8, 0)
for i = 1, 8 do
local s = sqrt(1 + CI[i] * CI[i])
CS[i], CA[i] = 1 / s, CI[i] / s
end
-- ------------------------------------------------------------------------------------------------ Huffman planning
type Plan = {
bits: number,
bigValues: number, -- pairs
count1: number, -- quadruples
tables: { number }, -- 3 region tables
region0: number,
region1: number,
c1table: number, -- 0 = A (table 32), 1 = B (33)
addr1: number, -- coefficient index where region 1 starts
addr2: number,
}
local function newPlan(): Plan
return { bits = 0, bigValues = 0, count1 = 0, tables = { 0, 0, 0 }, region0 = 0, region1 = 0, c1table = 0, addr1 = 0, addr2 = 0 }
end
-- bits of the pairs ix[a .. b) with table t (ix 1-based: ix[i + 1] is coefficient i)
local function pairBits(ix: { number }, a: number, b: number, t: number): number
if t == 0 then
return 0
end
local lens = LEN[t]
local lb = LINBITS[t]
local bits = 0
for i = a, b - 1, 2 do
local x, y = ix[i + 1], ix[i + 2]
local extra = 0
if x > 14 then
x = 15
extra += lb
end
if y > 14 then
y = 15
extra += lb
end
bits += lens[x * 16 + y + 1] + extra
if x ~= 0 then
bits += 1
end
if y ~= 0 then
bits += 1
end
end
return bits
end
-- the best table for the pairs ix[a .. b): table, bits
local function chooseTable(ix: { number }, a: number, b: number): (number, number)
if b <= a then
return 0, 0
end
local m = 0
for i = a + 1, b do
local v = ix[i]
if v > m then
m = v
end
end
if m == 0 then
return 0, 0
end
if m <= 15 then
local best, bestBits = 0, math.huge
for _, t in SMALL[m] do
local bits = pairBits(ix, a, b, t)
if bits < bestBits then
best, bestBits = t, bits
end
end
return best, bestBits
end
local need = m - 15
local best, bestBits = 0, math.huge
for _, group in { 16, 24 } do
for t = group, group + 7 do
if POW[LINBITS[t] + 1] - 1 >= need then
local bits = pairBits(ix, a, b, t)
if bits < bestBits then
best, bestBits = t, bits
end
break
end
end
end
return best, bestBits
end
-- plan the Huffman coding of ix (576 values, max <= 8206) into p; bounds = scalefactor band starts (1-based list)
local function plan(ix: { number }, bounds: { number }, p: Plan)
local i = 576
while i > 1 and ix[i] == 0 and ix[i - 1] == 0 do
i -= 2
end
-- count1 region: quadruples of values <= 1
local c1 = 0
while i > 3 and ix[i] <= 1 and ix[i - 1] <= 1 and ix[i - 2] <= 1 and ix[i - 3] <= 1 do
i -= 4
c1 += 1
end
local bv = i -- big_values * 2 coefficients
p.bigValues, p.count1 = bv // 2, c1
-- count1 bits, table A vs B
local ba, bb = 0, 0
local lensA = LEN[32]
for q = 0, c1 - 1 do
local o = bv + q * 4
local v, w, x, y = ix[o + 1], ix[o + 2], ix[o + 3], ix[o + 4]
local s = v + w + x + y
ba += lensA[v * 8 + w * 4 + x * 2 + y + 1] + s
bb += 4 + s
end
p.c1table = if bb < ba then 1 else 0
local bits = if bb < ba then bb else ba
-- regions: region 0 / 1 / 2 split at scalefactor band boundaries
local j = 0
while j + 1 < #bounds and bounds[j + 2] <= bv do
j += 1
end
local r0 = math.clamp(floor((j + 1) / 3), 0, 15)
local r1 = math.clamp(floor((j + 1) / 3), 0, 7)
if r0 + r1 + 2 > 22 then
r1 = 22 - r0 - 2
end
local a1 = math.min(bounds[r0 + 2] or 576, bv)
local a2 = math.min(bounds[r0 + r1 + 3] or 576, bv)
p.region0, p.region1, p.addr1, p.addr2 = r0, r1, a1, a2
local t1, b1 = chooseTable(ix, 0, a1)
local t2, b2 = chooseTable(ix, a1, a2)
local t3, b3 = chooseTable(ix, a2, bv)
p.tables[1], p.tables[2], p.tables[3] = t1, t2, t3
p.bits = bits + b1 + b2 + b3
end
local function writePairs(w: W, ix: { number }, sign: { boolean }, a: number, b: number, t: number)
if t == 0 then
return
end
local codes, lens = CODE[t], LEN[t]
local lb = LINBITS[t]
for i = a, b - 1, 2 do
local x, y = ix[i + 1], ix[i + 2]
local cx, cy = if x > 14 then 15 else x, if y > 14 then 15 else y
local idx = cx * 16 + cy + 1
put(w, codes[idx], lens[idx])
if cx == 15 then
put(w, x - 15, lb)
end
if x ~= 0 then
put(w, if sign[i + 1] then 1 else 0, 1)
end
if cy == 15 then
put(w, y - 15, lb)
end
if y ~= 0 then
put(w, if sign[i + 2] then 1 else 0, 1)
end
end
end
local function writeHuffman(w: W, ix: { number }, sign: { boolean }, p: Plan)
local bv = p.bigValues * 2
writePairs(w, ix, sign, 0, p.addr1, p.tables[1])
writePairs(w, ix, sign, p.addr1, p.addr2, p.tables[2])
writePairs(w, ix, sign, p.addr2, bv, p.tables[3])
local codesA, lensA = CODE[32], LEN[32]
for q = 0, p.count1 - 1 do
local o = bv + q * 4
local v, ww, x, y = ix[o + 1], ix[o + 2], ix[o + 3], ix[o + 4]
local idx = v * 8 + ww * 4 + x * 2 + y
if p.c1table == 1 then
put(w, 15 - idx, 4) -- table B: the 4 bits inverted
else
put(w, codesA[idx + 1], lensA[idx + 1])
end
for k = 1, 4 do
if ix[o + k] ~= 0 then
put(w, if sign[o + k] then 1 else 0, 1)
end
end
end
end
-- ------------------------------------------------------------------------------------------------ quantization
type Unit = {
xr: { number }, -- 576 MDCT coefficients
xa: { number }, -- |xr|^(3/4)
ix: { number },
sign: { boolean },
plan: Plan,
gain: number,
}
local function newUnit(): Unit
return {
xr = table.create(576, 0),
xa = table.create(576, 0),
ix = table.create(576, 0),
sign = table.create(576, false),
plan = newPlan(),
gain = 210,
}
end
-- quantize with global gain g: false when a value overflows 8206
local function quantize(u: Unit, g: number): boolean
local step = 2 ^ (-(g - 210) * 3 / 16)
local xa, ix = u.xa, u.ix
for i = 1, 576 do
local v = floor(xa[i] * step + 0.4054)
if v > 8206 then
return false
end
ix[i] = v
end
return true
end
-- the finest global gain whose Huffman size fits budget bits
local function rateLoop(u: Unit, budget: number, bounds: { number })
local xr, xa, sign = u.xr, u.xa, u.sign
local maxa = 0
for i = 1, 576 do
local v = xr[i]
sign[i] = v < 0
local a = math.abs(v) ^ 0.75
xa[i] = a
if a > maxa then
maxa = a
end
end
local p = u.plan
if maxa < 1e-12 then
for i = 1, 576 do
u.ix[i] = 0
end
plan(u.ix, bounds, p)
u.gain = 0
return
end
-- the gain where the largest value quantizes to 0: an upper bound
local lo, hi = 0, 255
local best = -1
while lo <= hi do
local mid = (lo + hi) // 2
if quantize(u, mid) then
plan(u.ix, bounds, p)
if p.bits <= budget then
best = mid
hi = mid - 1
else
lo = mid + 1
end
else
lo = mid + 1
end
end
if best < 0 then
best = 255
end
quantize(u, best)
plan(u.ix, bounds, p)
if p.bits > budget then -- give up on this granule: silence fits any budget
for i = 1, 576 do
u.ix[i] = 0
end
plan(u.ix, bounds, p)
end
u.gain = best
end
-- ------------------------------------------------------------------------------------------------ encoder
export type Source = {
sampleRate: number,
channels: number,
frames: number,
read: (self: any, n: number, out: buffer?) -> (buffer, number),
err: any,
}
export type Options = {
bitrate: number, -- kbps, valid for the version
mode: string, -- "stereo" | "joint" | "mono"
prefix: buffer?, -- bytes written before the first frame (an ID3v2 tag)
}
-- encode(src, opts) -> buffer | nil, message
function Encode3.encode(src: Source, opts: Options): (buffer?, string?)
local rate = src.sampleRate
local info = RATES[rate]
if not info then
return nil, "unsupported sample rate"
end
local version, srIndex, group = info[1], info[2], info[3]
local mpeg1 = version == 3
local granules = if mpeg1 then 2 else 1
local spf = 576 * granules
local inCh = src.channels
local mode = opts.mode
local nch = if mode == "mono" then 1 else 2
local kbps = opts.bitrate
local list = if mpeg1 then BITRATES_V1 else BITRATES_V2
local brIndex = table.find(list, kbps)
if not brIndex then
return nil, "unsupported bit rate"
end
local sideBytes = if mpeg1 then (if nch == 1 then 17 else 32) else (if nch == 1 then 9 else 17)
local slotNum = (if mpeg1 then 144000 else 72000) * kbps -- frame bytes * rate
-- scalefactor band starts (long blocks)
local bounds = { 0 }
do
local acc = 0
for k = 0, 21 do
acc += T.g_scf_long[group * 23 + k]
table.insert(bounds, acc)
end
end
local w: W = { buf = buffer.create(65536), pos = 0, acc = 0, cnt = 0 }
if opts.prefix then
local pf = opts.prefix :: buffer
local need = buffer.len(pf)
if need > buffer.len(w.buf) - 16 then
w.buf = buffer.create(need + 65536)
end
buffer.copy(w.buf, 0, pf, 0, need)
w.pos = need
end
local ana = { Analysis.new(), Analysis.new() }
local prev = { table.create(576, 0), table.create(576, 0) } -- previous granule's subband samples [sb * 18 + k + 1]
local cur = { table.create(576, 0), table.create(576, 0) }
local units = {}
for g = 1, 2 do
units[g] = { newUnit(), newUnit() }
end
local pcm = { table.create(spf, 0), table.create(spf, 0) }
local sub = table.create(32, 0)
local z = table.create(36, 0)
local rest = 0
local tmp: buffer? = nil
local pending: buffer? = nil
local pendN, pendOff = 0, 0
local srcDone = false
local flushed = false
while true do
-- one frame of input (zero padded at the end; one more silent frame flushes the filterbank delay)
local got = 0
while got < spf and not srcDone do
if pendN == 0 then
local b, n = src:read(4096, tmp)
if n <= 0 then
srcDone = true
break
end
tmp = b
pending, pendN, pendOff = b, n, 0
end
local take = math.min(spf - got, pendN)
local pb = pending :: buffer
for i = 0, take - 1 do
local base = (pendOff + i) * inCh * 4
local l = buffer.readf32(pb, base)
local r = if inCh > 1 then buffer.readf32(pb, base + 4) else l
if nch == 1 then
if inCh > 1 then
l = (l + r) * 0.5
end
pcm[1][got + i + 1] = l
else
pcm[1][got + i + 1] = l
pcm[2][got + i + 1] = r
end
end
got += take
pendN -= take
pendOff += take
end
if got == 0 then
if flushed then
break
end
flushed = true -- one silent frame after the input pushes its tail through the filterbank delay
end
for c = 1, nch do
local s = pcm[c]
for i = got + 1, spf do
s[i] = 0
end
end
-- analysis + MDCT per granule and channel
for g = 1, granules do
for c = 1, nch do
local cu, pv = cur[c], prev[c]
local s = pcm[c]
for k = 0, 17 do
Analysis.run(ana[c], s, (g - 1) * 576 + k * 32 + 1, sub, 1)
for sb = 0, 31 do
local v = sub[sb + 1]
if sb % 2 == 1 and k % 2 == 1 then
v = -v -- frequency inversion of the odd subbands
end
cu[sb * 18 + k + 1] = v
end
end
local xr = units[g][c].xr
for sb = 0, 31 do
local o = sb * 18
for i = 1, 18 do
z[i] = pv[o + i]
z[i + 18] = cu[o + i]
end
for k = 0, 17 do
local acc = 0
local mb = k * 36
for i = 1, 36 do
acc += MDCT[mb + i] * z[i]
end
xr[o + k + 1] = acc
end
end
-- alias reduction butterflies (the inverse of the decoder's)
for sb = 1, 31 do
local o = sb * 18
for i = 0, 7 do
local a, b = xr[o - i], xr[o + i + 1]
xr[o - i] = a * CS[i + 1] + b * CA[i + 1]
xr[o + i + 1] = b * CS[i + 1] - a * CA[i + 1]
end
end
prev[c], cur[c] = cu, pv
end
if mode == "joint" then
local x0, x1 = units[g][1].xr, units[g][2].xr
local r2 = sqrt(0.5)
for i = 1, 576 do
local l, r = x0[i], x1[i]
x0[i], x1[i] = (l + r) * r2, (l - r) * r2
end
end
end
-- the frame size
local frameBytes = slotNum // rate
rest += slotNum % rate
local padding = 0
if rest >= rate then
rest -= rate
padding = 1
frameBytes += 1
end
local avail = (frameBytes - 4 - sideBytes) * 8
local left = avail
local nUnits = granules * nch
local done = 0
for g = 1, granules do
for c = 1, nch do
local budget = math.min(4095, left // (nUnits - done))
local u = units[g][c]
rateLoop(u, budget, bounds)
left -= u.plan.bits
done += 1
end
end
-- header
if w.pos + frameBytes + 64 > buffer.len(w.buf) then
local nb = buffer.create(buffer.len(w.buf) * 2 + frameBytes)
buffer.copy(nb, 0, w.buf, 0, w.pos)
w.buf = nb
end
local start = w.pos
put(w, 0x7FF, 11)
put(w, version, 2)
put(w, 1, 2) -- layer III
put(w, 1, 1) -- no CRC
put(w, brIndex, 4)
put(w, srIndex, 2)
put(w, padding, 1)
put(w, 0, 1)
put(w, if mode == "mono" then 3 elseif mode == "joint" then 1 else 0, 2)
put(w, if mode == "joint" then 2 else 0, 2) -- mode extension: mid / side on, intensity off
put(w, 0, 1)
put(w, 1, 1) -- original
put(w, 0, 2)
-- side info
if mpeg1 then
put(w, 0, 9) -- main_data_begin
put(w, 0, if nch == 1 then 5 else 3)
for _ = 1, nch do
put(w, 0, 4) -- scfsi
end
else
put(w, 0, 8)
put(w, 0, if nch == 1 then 1 else 2)
end
for g = 1, granules do
for c = 1, nch do
local u = units[g][c]
local p = u.plan
put(w, p.bits, 12) -- part2_3_length (no scalefactor bits)
put(w, p.bigValues, 9)
put(w, u.gain, 8)
put(w, 0, if mpeg1 then 4 else 9) -- scalefac_compress
put(w, 0, 1) -- window switching off
put(w, p.tables[1], 5)
put(w, p.tables[2], 5)
put(w, p.tables[3], 5)
put(w, p.region0, 4)
put(w, p.region1, 3)
if mpeg1 then
put(w, 0, 1) -- preflag
end
put(w, 0, 1) -- scalefac_scale
put(w, p.c1table, 1)
end
end
-- main data
for g = 1, granules do
for c = 1, nch do
local u = units[g][c]
writeHuffman(w, u.ix, u.sign, u.plan)
end
end
if w.cnt > 0 then
put(w, 0, 8 - w.cnt)
end
-- ancillary padding to the frame size
while w.pos < start + frameBytes do
writeu8(w.buf, w.pos, 0)
w.pos += 1
end
end
if src.err then
return nil, tostring(src.err)
end
local out = buffer.create(w.pos)
buffer.copy(out, 0, w.buf, 0, w.pos)
return out, nil
end
return Encode3
+124 -4
View File
@@ -4,8 +4,9 @@
-- 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). Not supported: encoding (see the mp3 encoder in the
-- audio workstream), MPEG-2 multichannel extension, CRC checks.
-- Float output (minimp3's MINIMP3_FLOAT_OUTPUT scalar path). Encode (ws-audio, audio/mp3/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. Not supported: MPEG-2 multichannel extension, CRC checks, VBR / Xing output, encoder resampling.
--
-- 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())
@@ -19,6 +20,9 @@ local Header = require("@formats/audio/mp3/Header")
local Index = require("@formats/audio/mp3/Index")
local Tags = require("@formats/audio/mp3/Tags")
local Stream = require("@formats/audio/mp3/Stream")
local Encode3 = require("@formats/audio/mp3/Encode3")
local Encode2 = require("@formats/audio/mp3/Encode2")
local Pcm = require("@formats/codecs/Pcm")
-- ------------------------------------------------------------------------------------------------ contract
local Mp3 = {
@@ -26,8 +30,8 @@ local Mp3 = {
category = "audio",
extensions = { "mp3", "mp2", "mp1", "mpga" },
mime = { "audio/mpeg", "audio/mp3", "audio/mpa" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = false, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 },
}
-- ------------------------------------------------------------------------------------------------ types
@@ -35,6 +39,13 @@ export type OpenOptions = {
maxFrames: number?, -- refuse streams longer than this many sample frames per channel (default 2^31)
}
export type Decoder = Stream.Decoder
export type EncodeOptions = {
layer: number?, -- 3 (MP3, default) or 2 (MP2)
bitrate: number?, -- kbps, constant (default 128 for layer III, 192 for layer II; MPEG-2 / 2.5 rates: 64 / 96)
mode: ("stereo" | "joint" | "mono")?, -- default "joint" (mid / side) for stereo layer III, "stereo" for layer II,
-- "mono" for mono input; layer II has no joint stereo (intensity) and writes "joint" as "stereo"
id3: boolean?, -- write an ID3v2.4 tag from the tags (default true when there are tags)
}
-- ------------------------------------------------------------------------------------------------ constants
local MAX_FRAMES = 2 ^ 31
@@ -85,6 +96,115 @@ function Mp3.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err
return a, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local ID3_FRAMES = {
{ "title", "TIT2" },
{ "artist", "TPE1" },
{ "album", "TALB" },
{ "albumArtist", "TPE2" },
{ "year", "TDRC" },
{ "date", "TDRC" },
{ "track", "TRCK" },
{ "genre", "TCON" },
{ "composer", "TCOM" },
}
-- an ID3v2.4 tag (UTF-8 text frames + a COMM frame) | nil when there is nothing to write
local function id3Tag(tags: { [string]: any }): buffer?
local w = Bytes.writer(256)
local seen: { [string]: boolean } = {}
local function syncsafe(v: number)
w:u8((v // 2097152) % 128)
w:u8((v // 16384) % 128)
w:u8((v // 128) % 128)
w:u8(v % 128)
end
for _, f in ID3_FRAMES do
local v = tags[f[1]]
if type(v) == "string" and #v > 0 and not seen[f[2]] then
seen[f[2]] = true
w:string(f[2])
syncsafe(#v + 1)
w:u16be(0)
w:u8(3) -- UTF-8
w:string(v)
end
end
if type(tags.comment) == "string" and #tags.comment > 0 then
local v = tags.comment
w:string("COMM")
syncsafe(#v + 5)
w:u16be(0)
w:u8(3)
w:string("eng")
w:u8(0) -- empty description
w:string(v)
end
local body = w:finish()
if buffer.len(body) == 0 then
return nil
end
local out = Bytes.writer(buffer.len(body) + 10)
out:string("ID3")
out:u8(4)
out:u8(0)
out:u8(0)
local n = buffer.len(body)
out:u8((n // 2097152) % 128)
out:u8((n // 16384) % 128)
out:u8((n // 128) % 128)
out:u8(n % 128)
out:bytes(body)
return out:finish()
end
-- encode(audioOrDecoder, opts?) -> an MP3 (layer III) or MP2 (layer II) file | nil, Err
function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local src, serr = Pcm.source(value)
if not src then
return nil, serr
end
local o: EncodeOptions = opts or {}
local layer = o.layer or 3
if layer ~= 2 and layer ~= 3 then
return nil, Err.new(Err.ARG, "layer must be 2 or 3")
end
local Enc = if layer == 3 then Encode3 else Encode2
local info = Enc.RATES[src.sampleRate]
if not info then
return nil, Err.new(Err.ARG, string.format("layer %d cannot hold %s Hz (no resampling)", layer, tostring(src.sampleRate)))
end
local mpeg1 = info[1] == 3
local mode = o.mode or (if src.channels == 1 then "mono" elseif layer == 3 then "joint" else "stereo")
if mode ~= "stereo" and mode ~= "joint" and mode ~= "mono" then
return nil, Err.new(Err.ARG, "mode must be stereo, joint or mono")
end
if src.channels > 2 then
return nil, Err.new(Err.ARG, "MPEG audio holds 1 or 2 channels")
end
if layer == 2 and mode == "joint" then
mode = "stereo"
end
local bitrate = o.bitrate or (if mpeg1 then (if layer == 3 then 128 else 192) else (if layer == 3 then 64 else 96))
if not table.find(Enc.BITRATES[if mpeg1 then 1 else 2], bitrate) then
return nil, Err.new(Err.ARG, string.format("%s kbps is not a layer %d bit rate at %d Hz", tostring(bitrate), layer, src.sampleRate))
end
if layer == 2 and mpeg1 then
-- the standard's allowed bit rate / mode combinations
if mode == "mono" and bitrate > 192 then
return nil, Err.new(Err.ARG, "layer II mono is at most 192 kbps")
elseif mode ~= "mono" and (bitrate == 32 or bitrate == 48 or bitrate == 56 or bitrate == 80) then
return nil, Err.new(Err.ARG, "layer II stereo needs 64 kbps or more (and not 80)")
end
end
local prefix = if o.id3 == false then nil else id3Tag(src.tags)
local out, msg = Enc.encode(src :: any, { bitrate = bitrate, mode = mode, prefix = prefix })
if not out then
return nil, Err.new(Err.ARG, tostring(msg))
end
return out, nil
end
-- ------------------------------------------------------------------------------------------------ open
-- the string-valued tag fields (title, artist, album, albumArtist, year, track, disc, genre, composer, comment)
local function stringTags(t: any): { [string]: string }
File diff suppressed because it is too large. Load diff
+181
View File
@@ -0,0 +1,181 @@
--!strict
-- audio/opus/Encode: Ogg Opus writing (RFC 7845) around audio/opus/CeltEncoder: CELT-only packets (TOC config 31:
-- full band, 20 ms, code 0), OpusHead (mapping family 0, the pre-skip = the encoder's delay), OpusTags (vendor +
-- the tags as Vorbis comments), granule positions with end trimming, pages through containers/Ogg's muxer. Input at
-- other rates is resampled to 48 kHz (a Kaiser-windowed sinc; quality enough for a codec input). New in formats-luau.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Ogg = require("@formats/containers/Ogg")
local CeltEncoder = require("@formats/audio/opus/CeltEncoder")
local Encode = {}
export type Options = {
bitrate: number?, -- bits per second (default 64000 per channel; 6000 .. 510000, constant)
tags: { [string]: string }?, -- default: the audio's tags
vendor: string?, -- OpusTags vendor (default "formats-luau")
serial: number?, -- Ogg stream serial (default 0x4f707573)
}
local floor, sin, pi, sqrt = math.floor, math.sin, math.pi, math.sqrt
local function besselI0(x: number): number
local sum, term = 1, 1
for k = 1, 60 do
term *= (x / (2 * k)) ^ 2
sum += term
if term < sum * 1e-15 then
break
end
end
return sum
end
-- resample(src (interleaved f32 buffer), frames, channels, from, to) -> { number } interleaved, frames out
local function resample(src: buffer, frames: number, channels: number, from: number, to: number): ({ number }, number)
local outFrames = floor(frames * to / from + 0.5)
local out = table.create(outFrames * channels, 0)
local ratio = to / from
local cutoff = 0.97 * math.min(1, ratio) -- of the input Nyquist
local half = 16 -- zero crossings each side (at the cutoff)
local width = half / cutoff
local beta = 8
local i0b = besselI0(beta)
local readf32 = buffer.readf32
for j = 0, outFrames - 1 do
local t = j / ratio -- the input position
local first = math.max(0, floor(t - width) + 1)
local last = math.min(frames - 1, floor(t + width))
for c = 0, channels - 1 do
local acc, wsum = 0, 0
for i = first, last do
local d = i - t
local x = d * cutoff
local s = if x == 0 then 1 else sin(pi * x) / (pi * x)
local r = d / width
local w = besselI0(beta * sqrt(math.max(0, 1 - r * r))) / i0b
local h = s * w
acc += readf32(src, (i * channels + c) * 4) * h
wsum += h
end
out[j * channels + c + 1] = if wsum ~= 0 then acc / wsum else 0
end
end
return out, outFrames
end
local TAG_NAMES: { [string]: string } = {
title = "TITLE", artist = "ARTIST", album = "ALBUM", albumartist = "ALBUMARTIST", date = "DATE", genre = "GENRE",
track = "TRACKNUMBER", tracktotal = "TRACKTOTAL", disc = "DISCNUMBER", comment = "COMMENT", composer = "COMPOSER",
}
-- encode(audio | decoder, opts) -> buffer | nil, Err
function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?)
local o = opts or {}
if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then
return nil, Err.new(Err.ARG, "expected an Audio or a Decoder")
end
local ch = value.channels
if ch ~= 1 and ch ~= 2 then
return nil, Err.new(Err.UNSUPPORTED, "the CELT encoder writes mono or stereo (got " .. ch .. " channels)")
end
local rate = value.sampleRate
if rate < 1000 or rate > 768000 then
return nil, Err.new(Err.ARG, "bad sample rate " .. tostring(rate))
end
local bitrate = o.bitrate or 64000 * ch
if type(bitrate) ~= "number" or bitrate < 6000 or bitrate > 510000 then
return nil, Err.new(Err.ARG, "bitrate 6000 .. 510000")
end
-- the whole input as an interleaved f32 buffer
local samples: buffer, frames: number
if value.kind == "audio" and type(value.samples) == "buffer" then
samples, frames = value.samples, value.frames
if buffer.len(samples) < frames * ch * 4 then
return nil, Err.new(Err.ARG, "audio.samples is shorter than frames * channels")
end
elseif type(value.read) == "function" then
local w = Bytes.writer(65536)
frames = 0
local chunk: buffer? = nil
while true do
local b, n = value:read(16384, chunk)
chunk = b
if n <= 0 then
break
end
w:bytes(b, 0, n * ch * 4)
frames += n
end
samples = w:finish()
else
return nil, Err.new(Err.ARG, "expected an Audio or a Decoder")
end
-- 48 kHz floats
local pcm: { number }, n48: number
if rate == 48000 then
n48 = frames
pcm = table.create(frames * ch, 0)
for i = 1, frames * ch do
pcm[i] = buffer.readf32(samples, (i - 1) * 4)
end
else
pcm, n48 = resample(samples, frames, ch, rate, 48000)
end
local FRAME = CeltEncoder.FRAME
local preSkip = CeltEncoder.DELAY
local packets = (n48 + preSkip + FRAME - 1) // FRAME
-- zero padding to whole frames
for i = n48 * ch + 1, packets * FRAME * ch do
pcm[i] = 0
end
local bytes = math.clamp(floor(bitrate * FRAME / 48000 / 8), if ch == 2 then 40 else 20, 1275 - 1)
local st = CeltEncoder.new(ch)
local mux = Ogg.muxer({ pageSize = 4096 })
local s = mux:stream(o.serial or 0x4f707573)
-- OpusHead
local head = Bytes.writer(19)
head:string("OpusHead")
head:u8(1)
head:u8(ch)
head:u16le(preSkip)
head:u32le(floor(rate))
head:u16le(0)
head:u8(0)
s:packet(head:finish(), 0, { flush = true })
-- OpusTags
local tags = o.tags or value.tags or {}
local tw = Bytes.writer(256)
tw:string("OpusTags")
local vendor = o.vendor or "formats-luau"
tw:u32le(#vendor)
tw:string(vendor)
local keys = {}
for k, v in tags do
if type(k) == "string" and type(v) == "string" then
table.insert(keys, k)
end
end
table.sort(keys)
tw:u32le(#keys)
for _, k in keys do
local field = (TAG_NAMES[k] or string.upper(k)) .. "=" .. tags[k]
tw:u32le(#field)
tw:string(field)
end
s:packet(tw:finish(), 0, { flush = true })
-- audio
local toc = 31 * 8 + (if ch == 2 then 4 else 0)
for p = 0, packets - 1 do
local frame = CeltEncoder.encodeFrame(st, pcm, p * FRAME * ch + 1, ch, bytes)
local pkt = buffer.create(bytes + 1)
buffer.writeu8(pkt, 0, toc)
buffer.copy(pkt, 1, frame, 0, bytes)
local last = p == packets - 1
local granule = if last then preSkip + n48 else (p + 1) * FRAME
s:packet(pkt, granule, { eos = last })
end
return mux:finish(), nil
end
return Encode
+252
View File
@@ -0,0 +1,252 @@
--!strict
--!native
--!optimize 2
-- audio/opus/RangeEncoder: the range encoder (RFC 6716 section 5.1), a port of libopus celt/entenc.c (BSD:
-- licenses/libopus-BSD.txt), the mirror of audio/opus/RangeDecoder. Writes one fixed-size frame: the range-coded
-- symbols from the front, the raw bits (ec_enc_bits) from the back, zeros between. Values stay below 2^32 as plain
-- numbers. Never throws: running out of room sets `error`.
local RangeEncoder = {}
export type Enc = {
buf: buffer,
storage: number,
offs: number,
end_offs: number,
end_window: number,
nend_bits: number,
nbits_total: number,
rng: number,
val: number,
rem: number,
ext: number,
error: number,
}
local CODE_TOP = 2147483648 -- 1 << 31
local CODE_BOT = 8388608 -- CODE_TOP >> 8
local CODE_SHIFT = 23
local SYM_MAX = 255
local countlz = bit32.countlz
local band = bit32.band
local readu8, writeu8 = buffer.readu8, buffer.writeu8
local floor = math.floor
local function ilog(x: number): number
return 32 - countlz(x)
end
RangeEncoder.ilog = ilog
-- new(storage) -> Enc over a fresh zeroed buffer of storage bytes
function RangeEncoder.new(storage: number): Enc
return {
buf = buffer.create(math.max(storage, 1)),
storage = storage,
offs = 0,
end_offs = 0,
end_window = 0,
nend_bits = 0,
nbits_total = 33, -- EC_CODE_BITS + 1
rng = CODE_TOP,
val = 0,
rem = -1,
ext = 0,
error = 0,
}
end
local function writeByte(e: Enc, v: number)
if e.offs + e.end_offs >= e.storage then
e.error = -1
return
end
writeu8(e.buf, e.offs, band(v, 255))
e.offs += 1
end
local function writeByteAtEnd(e: Enc, v: number)
if e.offs + e.end_offs >= e.storage then
e.error = -1
return
end
e.end_offs += 1
writeu8(e.buf, e.storage - e.end_offs, band(v, 255))
end
local function carryOut(e: Enc, c: number)
if c ~= SYM_MAX then
local carry = if c >= 256 then 1 else 0
if e.rem >= 0 then
writeByte(e, e.rem + carry)
end
if e.ext > 0 then
local sym = band(SYM_MAX + carry, 255)
repeat
writeByte(e, sym)
e.ext -= 1
until e.ext <= 0
end
e.rem = band(c, 255)
else
e.ext += 1
end
end
local function normalize(e: Enc)
while e.rng <= CODE_BOT do
carryOut(e, floor(e.val / 8388608))
e.val = (e.val * 256) % CODE_TOP
e.rng *= 256
e.nbits_total += 8
end
end
-- encode(fl, fh, ft): the symbol [fl, fh) of ft
function RangeEncoder.encode(e: Enc, fl: number, fh: number, ft: number)
local r = floor(e.rng / ft)
if fl > 0 then
e.val += e.rng - r * (ft - fl)
e.rng = r * (fh - fl)
else
e.rng -= r * (ft - fh)
end
normalize(e)
end
-- encodeBin(fl, fh, bits): ft = 2^bits
function RangeEncoder.encodeBin(e: Enc, fl: number, fh: number, bits: number)
local ft = 2 ^ bits
local r = floor(e.rng / ft)
if fl > 0 then
e.val += e.rng - r * (ft - fl)
e.rng = r * (fh - fl)
else
e.rng -= r * (ft - fh)
end
normalize(e)
end
-- bitLogp(v, logp): a bit whose probability of being 1 is 2^-logp
function RangeEncoder.bitLogp(e: Enc, v: boolean, logp: number)
local r = e.rng
local s = floor(r / 2 ^ logp)
r -= s
if v then
e.val += r
e.rng = s
else
e.rng = r
end
normalize(e)
end
-- icdf(s, icdf, ftb): symbol s (0-based) of an inverse CDF table (1-based Luau array) with 2^ftb total
function RangeEncoder.icdf(e: Enc, s: number, icdf: { number }, ftb: number)
local r = floor(e.rng / 2 ^ ftb)
if s > 0 then
e.val += e.rng - r * icdf[s]
e.rng = r * (icdf[s] - icdf[s + 1])
else
e.rng -= r * icdf[s + 1]
end
normalize(e)
end
-- bits(fl, n): n raw bits (n <= 25), written from the end of the frame
function RangeEncoder.bits(e: Enc, fl: number, n: number)
local window = e.end_window
local used = e.nend_bits
if used + n > 32 then
repeat
writeByteAtEnd(e, window % 256)
window = floor(window / 256)
used -= 8
until used < 8
end
window += fl * 2 ^ used
used += n
e.end_window = window
e.nend_bits = used
e.nbits_total += n
end
-- uint(fl, ft): fl uniformly in [0, ft), ft up to 2^32
function RangeEncoder.uint(e: Enc, fl: number, ft: number)
ft -= 1
local ftb = ilog(ft)
if ftb > 8 then
ftb -= 8
local sh = 2 ^ ftb
local ft1 = floor(ft / sh) + 1
local hi = floor(fl / sh)
RangeEncoder.encode(e, hi, hi + 1, ft1)
RangeEncoder.bits(e, fl - hi * sh, ftb)
else
RangeEncoder.encode(e, fl, fl + 1, ft + 1)
end
end
function RangeEncoder.tell(e: Enc): number
return e.nbits_total - ilog(e.rng)
end
local CORRECTION = { 35733, 38967, 42495, 46340, 50535, 55109, 60097, 65535 }
function RangeEncoder.tellFrac(e: Enc): number
local nbits = e.nbits_total * 8
local l = ilog(e.rng)
local r = floor(e.rng / 2 ^ (l - 16))
local b = floor(r / 4096) - 8
if r > CORRECTION[b + 1] then
b += 1
end
return nbits - (l * 8 + b)
end
-- done(): flush; the frame is e.buf (storage bytes)
function RangeEncoder.done(e: Enc)
local l = 32 - ilog(e.rng)
local msk = floor((CODE_TOP - 1) / 2 ^ l)
local stop = floor((e.val + msk) / (msk + 1)) * (msk + 1)
if stop + msk >= e.val + e.rng then
l += 1
msk = floor(msk / 2)
stop = floor((e.val + msk) / (msk + 1)) * (msk + 1)
end
while l > 0 do
carryOut(e, floor(stop / 8388608))
stop = (stop * 256) % CODE_TOP
l -= 8
end
if e.rem >= 0 or e.ext > 0 then
carryOut(e, 0)
end
local window = e.end_window
local used = e.nend_bits
while used >= 8 do
writeByteAtEnd(e, window % 256)
window = floor(window / 256)
used -= 8
end
if e.error == 0 then
local a, b = e.offs, e.storage - e.end_offs
if b > a then
buffer.fill(e.buf, a, 0, b - a)
end
if used > 0 then
if e.end_offs >= e.storage then
e.error = -1
else
l = -l
if e.offs + e.end_offs >= e.storage and l < used then
window = window % 2 ^ l
e.error = -1
end
local p = e.storage - e.end_offs - 1
writeu8(e.buf, p, bit32.bor(readu8(e.buf, p), window))
end
end
end
end
local _ = CODE_SHIFT
return RangeEncoder
+14 -4
View File
@@ -5,14 +5,17 @@
-- Supports: decode of every Opus mode / bandwidth / frame size, mono, stereo and surround (optional stereo downmix,
-- opts.stereo), pre-skip, end trimming, output gain, OpusTags, sample-accurate seeking (granule bisection + 80 ms
-- pre-roll), damaged files (concealment). Output is always 48 kHz f32.
-- Not supported: encoding, mapping family 3 (ambisonics projection), chained streams (the first Opus stream is
-- decoded), CELT pitch PLC (noise PLC only).
-- Encoding (audio/opus/Encode + CeltEncoder, ws-m4a): a CELT-only fixed-frame encoder (20 ms, full band, constant
-- bit rate, mono or dual stereo; other input rates resampled to 48 kHz) writing Ogg Opus with OpusTags.
-- Not supported: SILK / hybrid encoding, transients / pitch pre-filter in the encoder, mapping family 3 (ambisonics
-- projection), chained streams (the first Opus stream is decoded), CELT pitch PLC (noise PLC only).
-- Changes from opus-luau: the injected Ogg demuxer is containers/Ogg; errors are core/Err values; read() takes an
-- optional output buffer; decode() fully decodes to an Audio.
--
-- local dec, err = Opus.open(Bytes.reader(buf)) -- the Types.Decoder: dec:read(n, out?), dec:seek(s), ...
-- local audio = Opus.decode(Bytes.reader(buf)) -- a Types.Audio
-- Opus.Decoder.new(channels) + Opus.Decoder.decode(st, buf, off, len, pcm, base, maxFrames) -- raw packets
-- local file = Opus.encode(audio, { bitrate = 96000 }) -- Ogg Opus (CELT only)
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
@@ -24,6 +27,7 @@ local Packet = require("@formats/audio/opus/Packet")
local RangeDecoder = require("@formats/audio/opus/RangeDecoder")
local Celt = require("@formats/audio/opus/Celt")
local Silk = require("@formats/audio/opus/Silk")
local Encode = require("@formats/audio/opus/Encode")
-- ------------------------------------------------------------------------------------------------ contract
local Opus = {
@@ -31,8 +35,8 @@ local Opus = {
category = "audio",
extensions = { "opus" },
mime = { "audio/opus", "audio/ogg" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" },
caps = { decode = true, encode = false, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 } },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct" },
caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" } },
}
-- ------------------------------------------------------------------------------------------------ types
@@ -213,6 +217,12 @@ function Opus.decode(r: any, opts: OpenOptions?): (Types.Audio?, Err.Err?)
return a, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- encode(audio | decoder, opts?) -> Ogg Opus buffer | nil, Err (CELT only; see audio/opus/Encode)
function Opus.encode(value: any, opts: Encode.Options?): (buffer?, Err.Err?)
return Encode.encode(value, opts)
end
-- ------------------------------------------------------------------------------------------------ open
local Stream = {}
Stream.__index = Stream
+278
View File
@@ -0,0 +1,278 @@
--!strict
-- audio/voc: Creative Voice File (.voc, Sound Blaster). New code from the Creative file format description.
-- Supports: decode / open of block types 1 (sound data: 8-bit unsigned, 16-bit), 2 (continuation), 3 (silence),
-- 5 (text: tags.comment), 8 (extended: stereo / high rates for the next type 1 block), 9 (new sound data: 8-bit
-- unsigned, 16-bit signed, A-law, mu-law, any rate / channel count); markers and repeat loops are skipped (played
-- once, as ffmpeg does); truncated files decode the data present. Encode (Audio or Decoder, streamed) as version
-- 1.20 type 9 blocks of u8 / s16 (default) / alaw / ulaw. Not supported: Creative 4 / 2.6 / 2-bit ADPCM
-- (Err.UNSUPPORTED), blocks that change the channel count mid-file (the sample rate of the first block is used).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Pcm = require("@formats/codecs/Pcm")
-- ------------------------------------------------------------------------------------------------ contract
local Voc = {
name = "voc",
category = "audio",
extensions = { "voc" },
mime = { "audio/x-voc" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16 }, lossy = false },
}
export type DecodeOptions = {
maxFrames: number?, -- refuse more sample frames (default 2^28)
}
export type EncodeOptions = {
sampleFormat: ("u8" | "s16" | "alaw" | "ulaw")?, -- default "s16"
}
-- ------------------------------------------------------------------------------------------------ constants
local MAGIC = "Creative Voice File\26"
local T9_CODECS: { [number]: string } = { [0] = "u8", [4] = "s16le", [6] = "alaw", [7] = "ulaw" }
local T1_CODECS: { [number]: string } = { [0] = "u8", [4] = "s16le" }
local WRITE = { u8 = { 0, "u8", 8 }, s16 = { 4, "s16le", 16 }, alaw = { 6, "alaw", 8 }, ulaw = { 7, "ulaw", 8 } }
local MAX_BLOCK = 0xFFFFFF - 12 -- payload bytes of one type 9 block (a 24-bit size, 12 header bytes)
local readu8 = buffer.readu8
local function u16(b: buffer, o: number): number
return readu8(b, o) + readu8(b, o + 1) * 256
end
local function u24(b: buffer, o: number): number
return readu8(b, o) + readu8(b, o + 1) * 256 + readu8(b, o + 2) * 65536
end
-- ------------------------------------------------------------------------------------------------ sniff
function Voc.sniff(r: Bytes.Reader): number
return if r:peek(20) == MAGIC then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
type Segment = { at: number, frames: number, fmt: string? } -- fmt nil: silence
function Voc.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
local b, base, limit = r.buf, r.base, r.limit
if limit - base < 26 or buffer.readstring(b, base, 20) ~= MAGIC then
return nil, Err.new(Err.CORRUPT, "bad magic", base)
end
local hsize = u16(b, base + 20)
local version = u16(b, base + 22)
if hsize < 26 or hsize > limit - base then
return nil, Err.new(Err.CORRUPT, "bad header size", base + 20)
end
local maxFrames = opts and opts.maxFrames or 2 ^ 28
local rate, channels = 0, 0
local extRate, extChannels = 0, 0 -- a type 8 block's settings for the next type 1 block
local lastFmt: string? = nil
local codec = -1
local segments: { Segment } = {}
local total = 0
local truncated = false
local tags: Types.Tags = {}
local p = base + hsize
-- add(at, bytes, fmt, ch, sr): a run of samples (or silence when fmt is nil and bytes = frames)
local function add(at: number, bytes: number, fmt: string?, ch: number, sr: number): Err.Err?
if channels == 0 then
channels, rate = ch, sr
elseif ch ~= channels then
return Err.new(Err.UNSUPPORTED, "the channel count changes mid-file", at)
end
local frames = if fmt then bytes // (ch * Pcm.Convert.SIZE[fmt]) else bytes
if frames > 0 then
total += frames
if total > maxFrames then
return Err.new(Err.LIMIT, string.format("over the %d frame limit", maxFrames))
end
table.insert(segments, { at = at, frames = frames, fmt = fmt })
end
return nil
end
while p < limit do
local t = readu8(b, p)
if t == 0 then
break
end
if p + 4 > limit then
truncated = true
break
end
local size = u24(b, p + 1)
local d = p + 4
local avail = math.min(size, limit - d)
if avail < size then
truncated = true
end
local err: Err.Err? = nil
if t == 1 then
if avail < 2 then
break
end
local div, c = readu8(b, d), readu8(b, d + 1)
local fmt = T1_CODECS[c]
if not fmt then
return nil, Err.new(Err.UNSUPPORTED, "Creative ADPCM (codec " .. c .. ")", d + 1)
end
local ch, sr = 1, 1000000 // (256 - div)
if extChannels > 0 then
ch, sr = extChannels, extRate
extChannels = 0
end
lastFmt, codec = fmt, c
err = add(d + 2, avail - 2, fmt, ch, sr)
elseif t == 2 then
if lastFmt == nil then
return nil, Err.new(Err.CORRUPT, "continuation block before any sound data", p)
end
err = add(d, avail, lastFmt, channels, rate)
elseif t == 3 then
if avail < 3 then
break
end
local len, div = u16(b, d) + 1, readu8(b, d + 2)
err = add(d, len, nil, if channels > 0 then channels else 1, if rate > 0 then rate else 1000000 // (256 - div))
elseif t == 5 then
local s = buffer.readstring(b, d, avail)
local z = string.find(s, "\0", 1, true)
if z then
s = string.sub(s, 1, z - 1)
end
tags.comment = if tags.comment then tags.comment .. "\n" .. s else s
elseif t == 8 then
if avail < 4 then
break
end
local tc, mode = u16(b, d), readu8(b, d + 3)
extChannels = mode + 1
extRate = 256000000 // (extChannels * (65536 - tc))
elseif t == 9 then
if avail < 12 then
break
end
local sr = readu8(b, d) + readu8(b, d + 1) * 256 + readu8(b, d + 2) * 65536 + readu8(b, d + 3) * 16777216
local ch, c = readu8(b, d + 5), u16(b, d + 6)
local fmt = T9_CODECS[c]
if not fmt then
return nil, Err.new(Err.UNSUPPORTED, "codec " .. c, d + 6)
end
if ch < 1 or sr < 1 then
return nil, Err.new(Err.CORRUPT, "bad channels or sample rate", d)
end
lastFmt, codec = fmt, c
err = add(d + 12, avail - 12, fmt, ch, sr)
end
if err then
return nil, err
end
p = d + size
end
if channels == 0 then
return nil, Err.new(if truncated then Err.TRUNCATED else Err.CORRUPT, "no sound data", p)
end
local a = Types.Audio.new(rate, channels, total)
local o = 0
for _, s in segments do
local n = s.frames * channels
if s.fmt then
Pcm.Convert.decode(b, s.at, s.fmt :: string, n, a.samples, o)
end -- silence: the buffer is already zero
o += n * 4
end
a.tags = tags
a.meta.source = {
format = "voc",
version = string.format("%d.%02d", version // 256, version % 256),
codec = codec,
sampleFormat = lastFmt,
bitDepth = if lastFmt == "s16le" then 16 else 8,
truncated = truncated or nil,
}
return a, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Voc.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local src, serr = Pcm.source(value)
if not src then
return nil, serr
end
local o: EncodeOptions = opts or {}
local spec = WRITE[o.sampleFormat or "s16"]
if not spec then
return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat))
end
if src.channels > 255 then
return nil, Err.new(Err.ARG, "at most 255 channels")
end
if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate >= 2 ^ 32 then
return nil, Err.new(Err.ARG, "the sample rate must be an integer")
end
local w = Bytes.writer(65536)
w:string(MAGIC)
w:u16le(26)
w:u16le(0x0114)
w:u16le((0xFFFF - 0x0114 + 0x1234 + 1) % 65536) -- ~version + 0x1234
if type(src.tags.comment) == "string" and #src.tags.comment > 0 then
local s = string.sub(src.tags.comment, 1, 0xFFFFFE)
w:u8(5)
w:u24le(#s + 1)
w:string(s)
w:u8(0)
end
local size = Pcm.Convert.SIZE[spec[2]]
local frameBytes = size * src.channels
local framesPerBlock = MAX_BLOCK // frameBytes
local blockAt, blockFrames = -1, 0
local tmp: buffer? = nil
while true do
local bf, n = src:read(math.min(8192, framesPerBlock), tmp)
if n <= 0 then
break
end
tmp = bf
local i = 0
while i < n do
if blockAt < 0 or blockFrames == framesPerBlock then
blockAt = w:tell()
blockFrames = 0
w:u8(9)
w:u24le(0) -- patched
w:u32le(src.sampleRate)
w:u8(spec[3])
w:u8(src.channels)
w:u16le(spec[1])
w:u32le(0)
end
local take = math.min(n - i, framesPerBlock - blockFrames)
local at = w:reserve(take * frameBytes)
Pcm.Convert.encode(bf, i * src.channels * 4, take * src.channels, spec[2], w.buf, at)
w.pos = at + take * frameBytes
blockFrames += take
i += take
local len = blockFrames * frameBytes + 12
w:setU8(blockAt + 1, len % 256)
w:setU8(blockAt + 2, (len // 256) % 256)
w:setU8(blockAt + 3, len // 65536)
end
end
if src.err then
return nil, src.err
end
w:u8(0) -- terminator
return w:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ open
function Voc.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
local a, err = Voc.decode(r, opts)
if not a then
return nil, err
end
local dec = Pcm.audioDecoder(a) :: any
dec.source = a.meta.source
return dec, nil
end
return Voc
+394
View File
@@ -0,0 +1,394 @@
--!strict
--!native
--!optimize 2
-- audio/vorbis/Codebook: the Vorbis LSB-first packet bit reader and codebooks (Vorbis I spec sections 2 and 3):
-- reading a codebook from the setup header (ordered / sparse length lists, lookup types 1 and 2, float32_unpack),
-- the codeword assignment, and Huffman / VQ decoding. Ported from stb_vorbis 1.22 (public domain / MIT; see
-- licenses/stb_vorbis-LICENSE.txt): compute_codewords' lowest-free-leaf assignment, lookup1_values; the decode side
-- is a fast table (up to 10 bits) plus a binary tree for longer codes instead of stb's sorted binary search.
--
-- Never throws. Reading past the packet end gives zero bits and sets br.eop (the spec's end-of-packet condition);
-- an invalid codeword also sets eop and decodes to -1.
local Codebook = {}
local readu8 = buffer.readu8
local floor = math.floor
local POW = table.create(41, 0)
for i = 0, 40 do
POW[i + 1] = 2 ^ i
end
-- ------------------------------------------------------------------------------------------------ bit reader
export type Br = {
buf: buffer,
pos: number, -- next byte to load
limit: number,
acc: number, -- loaded, unread bits (LSB first)
cnt: number,
pad: number, -- how many of the top bits of acc are past the end of the packet
eop: boolean, -- read past the end of the packet
}
function Codebook.reader(buf: buffer, offset: number, size: number): Br
return { buf = buf, pos = offset, limit = offset + size, acc = 0, cnt = 0, pad = 0, eop = false }
end
-- bits(br, n) -> the next n (0..32) bits as an unsigned number
local function bits(br: Br, n: number): number
if n == 0 then
return 0
end
local acc, cnt = br.acc, br.cnt
if cnt < n then
local b, p, lim = br.buf, br.pos, br.limit
repeat
if p < lim then
acc += readu8(b, p) * POW[cnt + 1]
p += 1
else
br.pad += 8
end
cnt += 8
until cnt >= n
br.pos = p
end
local m = POW[n + 1]
local v = acc % m
br.acc = (acc - v) / m
cnt -= n
br.cnt = cnt
if cnt < br.pad then
br.eop = true
br.pad = cnt
end
return v
end
Codebook.bits = bits
-- ilog(x): the number of bits needed to hold x (0 for x <= 0)
local function ilog(x: number): number
local n = 0
while x > 0 do
n += 1
x = floor(x / 2)
end
return n
end
Codebook.ilog = ilog
-- float32_unpack (spec 9.2.2)
local function float32Unpack(x: number): number
local mantissa = x % 2097152
local sign = x >= 2147483648
local exp = floor((x % 2147483648) / 2097152)
local v = mantissa * 2 ^ (exp - 788)
return if sign then -v else v
end
-- ------------------------------------------------------------------------------------------------ codebooks
export type Book = {
dims: number,
entries: number,
fastBits: number,
fastLen: { number }, -- per fastBits-bit prefix: code length (> 0), 0 = continue in the tree, -1 = invalid
fastSym: { number }, -- symbol, or the tree node to continue from
c0: { number }, -- tree: child for bit 0 / 1: > 0 node, < 0 leaf (-symbol - 1), 0 none
c1: { number },
lookup: number, -- 0, 1, 2
vq: { number }?, -- entries * dims values (lookup 1 / 2, expanded)
used: number, -- entries with a codeword
}
local MAX_ENTRIES = 2 ^ 20
local MAX_VQ = 2 ^ 22
-- lookup1_values(entries, dims): the largest r with r^dims <= entries
local function lookup1Values(entries: number, dims: number): number
local r = floor(math.exp(math.log(entries) / dims))
if floor((r + 1) ^ dims) <= entries then
r += 1
end
if (r + 1) ^ dims <= entries then
return -1
end
if floor(r ^ dims) > entries then
return -1
end
return r
end
-- assign codewords (spec 3.2.1: in entry order, the lowest free leaf) and build the decode tree + fast table
local function build(book: Book, lengths: { number }): string?
local n = book.entries
local c0, c1 = book.c0, book.c1
local nodes = 1
c0[1], c1[1] = 0, 0
local available = table.create(33, 0) -- available[l]: the free code at depth l, as a 32-bit left-aligned value + 1 (0 = none)
local first = true
local used = 0
local maxLen = 0
for i = 0, n - 1 do
local len = lengths[i + 1]
if len > 0 then
local code: number
if first then
first = false
code = 0
for l = 1, len do
available[l + 1] = POW[33 - l] + 1
end
else
local z = len
while z > 0 and available[z + 1] == 0 do
z -= 1
end
if z == 0 then
return "over-subscribed codebook"
end
code = available[z + 1] - 1
available[z + 1] = 0
for y = len, z + 1, -1 do
available[y + 1] = code + POW[33 - y] + 1
end
end
-- walk the MSB-first code into the tree
local node = 1
for d = 1, len do
local bit = floor(code / POW[33 - d]) % 2
local child = if bit == 0 then c0[node] else c1[node]
if d == len then
if child ~= 0 then
return "ambiguous codeword"
end
if bit == 0 then
c0[node] = -(i + 1)
else
c1[node] = -(i + 1)
end
else
if child < 0 then
return "ambiguous codeword"
elseif child == 0 then
nodes += 1
c0[nodes], c1[nodes] = 0, 0
child = nodes
if bit == 0 then
c0[node] = child
else
c1[node] = child
end
end
node = child
end
end
used += 1
if len > maxLen then
maxLen = len
end
end
end
book.used = used
-- the fast table: every fastBits-bit prefix (read LSB first) walked down the tree
local fb = math.clamp(maxLen, 1, 10)
book.fastBits = fb
local size = POW[fb + 1]
local fl, fs = table.create(size, -1), table.create(size, 0)
for idx = 0, size - 1 do
local node = 1
local v = idx
for d = 1, fb do
local bit = v % 2
v = (v - bit) / 2
local child = if bit == 0 then c0[node] else c1[node]
if child < 0 then
fl[idx + 1], fs[idx + 1] = d, -child - 1
break
elseif child == 0 then
break -- invalid (-1)
end
node = child
if d == fb then
fl[idx + 1], fs[idx + 1] = 0, node
end
end
end
book.fastLen, book.fastSym = fl, fs
return nil
end
-- read(br) -> Book | nil, message: one codebook from the setup header
function Codebook.read(br: Br): (Book?, string?)
if bits(br, 24) ~= 0x564342 then
return nil, "bad codebook sync"
end
local dims = bits(br, 16)
local entries = bits(br, 24)
local ordered = bits(br, 1)
if br.eop then
return nil, "setup header ends in a codebook"
end
if dims == 0 and entries ~= 0 then
return nil, "codebook with 0 dimensions"
end
if entries > MAX_ENTRIES then
return nil, "codebook with " .. entries .. " entries"
end
local lengths = table.create(entries, 0)
if ordered == 1 then
local cur = 0
local len = bits(br, 5) + 1
while cur < entries do
local num = bits(br, ilog(entries - cur))
if len >= 32 or cur + num > entries or br.eop then
return nil, "bad ordered codebook lengths"
end
for k = cur + 1, cur + num do
lengths[k] = len
end
cur += num
len += 1
end
else
local sparse = bits(br, 1)
for j = 1, entries do
if sparse == 0 or bits(br, 1) == 1 then
local l = bits(br, 5) + 1
if l == 32 then
return nil, "codeword length 32"
end
lengths[j] = l
end
end
end
if br.eop then
return nil, "setup header ends in a codebook"
end
local book: Book = {
dims = dims,
entries = entries,
fastBits = 1,
fastLen = {},
fastSym = {},
c0 = {},
c1 = {},
lookup = 0,
vq = nil,
used = 0,
}
local err = build(book, lengths)
if err then
return nil, err
end
local lookup = bits(br, 4)
if lookup > 2 then
return nil, "lookup type " .. lookup
end
book.lookup = lookup
if lookup > 0 then
local minimum = float32Unpack(bits(br, 32))
local delta = float32Unpack(bits(br, 32))
local valueBits = bits(br, 4) + 1
local seq = bits(br, 1) == 1
local nvalues
if lookup == 1 then
nvalues = lookup1Values(entries, dims)
if nvalues < 0 then
return nil, "bad lookup1 size"
end
else
nvalues = entries * dims
end
if nvalues == 0 then
return nil, "empty lookup table"
end
if entries * dims > MAX_VQ or nvalues > MAX_VQ then
return nil, "lookup table too large"
end
local mults = table.create(nvalues, 0)
for j = 1, nvalues do
mults[j] = bits(br, valueBits)
end
if br.eop then
return nil, "setup header ends in a lookup table"
end
-- expand to one vector per entry (spec 3.2.1, "VQ lookup table vector representation")
local vq = table.create(entries * dims, 0)
for e = 0, entries - 1 do
local last = 0
local div = 1
for k = 0, dims - 1 do
local off
if lookup == 1 then
off = floor(e / div) % nvalues
div *= nvalues
else
off = e * dims + k
end
local v = mults[off + 1] * delta + minimum + last
if seq then
last = v
end
vq[e * dims + k + 1] = v
end
end
book.vq = vq
end
return book, nil
end
-- decode(br, book) -> entry number | -1 (end of packet / invalid codeword: br.eop is set)
local function decode(br: Br, book: Book): number
local fb = book.fastBits
local acc, cnt = br.acc, br.cnt
if cnt < fb then
local b, p, lim = br.buf, br.pos, br.limit
repeat
if p < lim then
acc += readu8(b, p) * POW[cnt + 1]
p += 1
else
br.pad += 8
end
cnt += 8
until cnt >= fb
br.pos = p
br.acc, br.cnt = acc, cnt
end
local idx = acc % POW[fb + 1] + 1
local l = book.fastLen[idx]
if l > 0 then
local m = POW[l + 1]
br.acc = (acc - acc % m) / m
cnt -= l
br.cnt = cnt
if cnt < br.pad then
br.eop = true
br.pad = cnt
return -1
end
return book.fastSym[idx]
elseif l == 0 then
bits(br, fb)
local node = book.fastSym[idx]
local c0, c1 = book.c0, book.c1
while true do
local child = if bits(br, 1) == 0 then c0[node] else c1[node]
if br.eop then
return -1
end
if child < 0 then
return -child - 1
elseif child == 0 then
br.eop = true
return -1
end
node = child
end
end
br.eop = true
return -1
end
Codebook.decode = decode
return Codebook
+825
View File
@@ -0,0 +1,825 @@
--!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/Mdct, scale 4/N for the decoder's unscaled IMDCT); one floor 1 per channel with a
-- fixed post list of 30 points (bisection order, multiplier 2) fitted to the spectral envelope minus a quality-
-- dependent SNR, so the residue is quantized in steps of the floor; stereo square-polar coupling of the integer
-- residues (lossless); residue type 2 with 16-values-per-channel partitions and six classes (silent, |v| <= 1, 4, 15, then
-- cascades of x16 / x256 books for larger values); a fixed codebook set whose Huffman lengths come from Laplacian
-- models computed at load time (codewords assigned exactly as the spec's decoder does). Granules are sample-exact
-- (frames centred on multiples of 1024 from sample 0; the last page's granule trims the end). Never throws.
local Mdct = require("@formats/codecs/Mdct")
local Ogg = require("@formats/containers/Ogg")
local Tables = require("@formats/audio/vorbis/Tables")
local Encode = {}
local floor, log, exp, abs = math.floor, math.log, math.exp, math.abs
local writeu8 = buffer.writeu8
local POW = table.create(40, 0)
for i = 0, 39 do
POW[i + 1] = 2 ^ i
end
local N = 2048
local N2 = 1024
local PSIZE_PER_CHANNEL = 16 -- residue partitions hold 16 values per channel (libvorbis needs a multiple of ch)
local MULT = 2 -- floor1 multiplier (range 128)
local RANGE = 128
local NCLASS = 6
-- ------------------------------------------------------------------------------------------------ LSB-first bit writer
type W = { buf: buffer, pos: number, acc: number, cnt: number }
local function newW(size: number): W
return { buf = buffer.create(size), pos = 0, acc = 0, cnt = 0 }
end
local function put(w: W, v: number, n: number)
if n == 0 then
return
end
local acc = w.acc + v * POW[w.cnt + 1]
local cnt = w.cnt + n
local b, p = w.buf, w.pos
if p + 8 > buffer.len(b) then
local nb = buffer.create(buffer.len(b) * 2 + 64)
buffer.copy(nb, 0, b, 0, p)
b = nb
w.buf = nb
end
while cnt >= 8 do
local byte = acc % 256
writeu8(b, p, byte)
p += 1
acc = (acc - byte) / 256
cnt -= 8
end
w.acc, w.cnt, w.pos = acc, cnt, p
end
local function finish(w: W): buffer
if w.cnt > 0 then
put(w, 0, 8 - w.cnt)
end
local out = buffer.create(w.pos)
buffer.copy(out, 0, w.buf, 0, w.pos)
return out
end
local function putString(w: W, s: string)
for i = 1, #s do
put(w, string.byte(s, i), 8)
end
end
local function ilog(x: number): number
local n = 0
while x > 0 do
n += 1
x = floor(x / 2)
end
return n
end
-- ------------------------------------------------------------------------------------------------ codebooks
type Book = {
dims: number,
entries: number,
lengths: { number },
codes: { number }, -- bit-reversed codewords (ready for the LSB-first writer)
lookup: number, -- 0 or 1
minimum: number,
delta: number,
values: number, -- lookup1 values per dimension
}
-- Huffman code lengths for weights w[1..n] (all > 0), at most 24 bits long (weights are floored to keep it so)
local function huffmanLengths(w: { number }): { number }
local n = #w
local total = 0
for i = 1, n do
total += w[i]
end
local lens = table.create(n, 0)
if n == 1 then
lens[1] = 1
return lens
end
local minw = total * 2 ^ -20
-- nodes: leaves 1..n then internal; a simple O(n^2)-free approach with two sorted queues
local order = table.create(n, 0)
for i = 1, n do
order[i] = i
end
local weight = table.create(2 * n, 0)
local parent = table.create(2 * n, 0)
for i = 1, n do
weight[i] = math.max(w[i], minw)
end
table.sort(order, function(a: number, b: number): boolean
if weight[a] ~= weight[b] then
return weight[a] < weight[b]
end
return a < b
end)
local q1, h1 = order, 1 -- leaves, ascending
local q2, h2, t2 = table.create(n, 0), 1, 0 -- internal nodes, created in ascending weight order
local nextId = n
local function pop(): number
local a = if h1 <= n then q1[h1] else nil
local b = if h2 <= t2 then q2[h2] else nil
if a and (not b or weight[a] <= weight[b]) then
h1 += 1
return a
end
h2 += 1
return b :: number
end
for _ = 1, n - 1 do
local a = pop()
local b = pop()
nextId += 1
weight[nextId] = weight[a] + weight[b]
parent[a], parent[b] = nextId, nextId
t2 += 1
q2[t2] = nextId
end
for i = 1, n do
local d, x = 0, i
while parent[x] ~= 0 do
x = parent[x]
d += 1
end
lens[i] = d
end
return lens
end
-- the spec's codeword assignment (lowest free leaf, in entry order); returns bit-reversed codes
local function assign(lens: { number }): { number }
local codes = table.create(#lens, 0)
local available = table.create(33, 0)
local first = true
for i, len in lens do
if len > 0 then
local code
if first then
first = false
code = 0
for l = 1, len do
available[l + 1] = POW[33 - l] + 1
end
else
local z = len
while z > 0 and available[z + 1] == 0 do
z -= 1
end
code = available[z + 1] - 1
available[z + 1] = 0
for y = len, z + 1, -1 do
available[y + 1] = code + POW[33 - y] + 1
end
end
-- the top len bits of the 32-bit left-aligned code, MSB first, reversed for the LSB-first writer
local msb = floor(code / POW[33 - len])
local rev = 0
for _ = 1, len do
rev = rev * 2 + msb % 2
msb = floor(msb / 2)
end
codes[i] = rev
end
end
return codes
end
local function makeBook(dims: number, entries: number, weight: (number) -> number, lookup: number, minimum: number, delta: number, values: number): Book
local w = table.create(entries, 0)
for e = 0, entries - 1 do
w[e + 1] = weight(e)
end
local lens = huffmanLengths(w)
return { dims = dims, entries = entries, lengths = lens, codes = assign(lens), lookup = lookup, minimum = minimum, delta = delta, values = values }
end
-- a VQ book of `dims` dimensions over integer values -h .. h times `scale`, Laplacian weights exp(-|v| / s)
local function vqBook(dims: number, h: number, scale: number, s: number, zeroBoost: number): Book
local values = 2 * h + 1
local entries = values ^ dims
return makeBook(dims, entries, function(e: number): number
local wt = 1
local x = e
for _ = 1, dims do
local v = x % values - h
x = x // values
wt *= exp(-abs(v) / s) * (if v == 0 then zeroBoost else 1)
end
return wt
end, 1, -h * scale, scale, values)
end
local BOOK_FLOOR = makeBook(1, RANGE, function(e: number): number
return exp(-e / 7) + 0.002
end, 0, 0, 0, 0)
local CLASS_W = { 0.30, 0.30, 0.20, 0.12, 0.06, 0.02 }
local BOOK_CLASS = makeBook(2, NCLASS * NCLASS, function(e: number): number
return CLASS_W[e % NCLASS + 1] * CLASS_W[e // NCLASS + 1]
end, 0, 0, 0, 0)
local BOOK_A = vqBook(4, 1, 1, 0.6, 2.5) -- |v| <= 1, 4 at a time (mostly zeros)
local BOOK_B = vqBook(2, 4, 1, 1.4, 1) -- |v| <= 4
local BOOK_C = vqBook(2, 15, 1, 4, 1) -- |v| <= 15
local BOOK_D = vqBook(2, 15, 16, 3, 1) -- multiples of 16 up to 240
local BOOK_E = vqBook(2, 15, 256, 3, 1) -- multiples of 256 up to 3840
local BOOKS = { BOOK_FLOOR, BOOK_CLASS, BOOK_A, BOOK_B, BOOK_C, BOOK_D, BOOK_E }
local FLOOR_BOOK, CLASS_BOOK, A_BOOK, B_BOOK, C_BOOK, D_BOOK, E_BOOK = 0, 1, 2, 3, 4, 5, 6
-- the books of each residue class per pass (book numbers; -1 = none)
local CLASS_BOOKS = {
{ -1, -1, -1 },
{ A_BOOK, -1, -1 },
{ B_BOOK, -1, -1 },
{ C_BOOK, -1, -1 },
{ D_BOOK, C_BOOK, -1 },
{ E_BOOK, D_BOOK, C_BOOK },
}
local CLASS_MAX = { 0, 1, 4, 15, 255, 4095 }
-- float32_pack (spec 9.2.2) of an integer-valued x
local function float32Pack(x: number): number
local sign = if x < 0 then 2147483648 else 0
local m = abs(x)
local e = 788
while m >= 2097152 do
m /= 2
e += 1
end
return sign + e * 2097152 + floor(m)
end
local function writeBook(w: W, b: Book)
put(w, 0x564342, 24)
put(w, b.dims, 16)
put(w, b.entries, 24)
put(w, 0, 1) -- not ordered
put(w, 0, 1) -- not sparse
for i = 1, b.entries do
put(w, b.lengths[i] - 1, 5)
end
put(w, b.lookup, 4)
if b.lookup == 1 then
put(w, float32Pack(b.minimum), 32)
put(w, float32Pack(b.delta), 32)
local vb = ilog(b.values - 1)
put(w, vb - 1, 4)
put(w, 0, 1) -- sequence_p
for j = 0, b.values - 1 do
put(w, j, vb)
end
end
end
local function putEntry(w: W, b: Book, e: number)
put(w, b.codes[e + 1], b.lengths[e + 1])
end
-- ------------------------------------------------------------------------------------------------ floor posts
-- x positions: 0, 1024, then 28 log-spaced points in bisection order (coarse first) so predictions are good
local POSTS: { number } = { 0, N2 }
do
local xs = {}
local seen = { [0] = true, [N2] = true }
for j = 0, 27 do
local x = floor(3 + 957 * (j / 27) ^ 2.2 + 0.5) -- 3 .. 960, denser at low frequencies
while seen[x] do
x += 1
end
seen[x] = true
table.insert(xs, x)
end
table.sort(xs)
-- bisection order over the sorted list
local queue = { { 1, #xs } }
local qh = 1
while qh <= #queue do
local r = queue[qh]
qh += 1
if r[1] <= r[2] then
local m = (r[1] + r[2]) // 2
table.insert(POSTS, xs[m])
table.insert(queue, { r[1], m - 1 })
table.insert(queue, { m + 1, r[2] })
end
end
end
local NPOSTS = #POSTS -- 30
local FLOOR_PARTS = (NPOSTS - 2) // 4 -- 7 partitions of one class with 4 dimensions
local SORTED: { number } = table.create(NPOSTS, 0) -- post indices (1-based) by increasing x
for i = 1, NPOSTS do
SORTED[i] = i
end
table.sort(SORTED, function(a: number, b: number): boolean
return POSTS[a] < POSTS[b]
end)
local LOW, HIGH = table.create(NPOSTS, 0), table.create(NPOSTS, 0)
for j = 3, NPOSTS do
local lo, hi = -1, 65536
local x = POSTS[j]
for k = 1, j - 1 do
local xv = POSTS[k]
if xv > lo and xv < x then
LOW[j], lo = k, xv
end
if xv < hi and xv > x then
HIGH[j], hi = k, xv
end
end
end
-- the floor value (0..127) closest to an amplitude, through the spec's inverse dB table
local DB = table.create(RANGE, 0)
for y = 0, RANGE - 1 do
DB[y + 1] = 20 * math.log10(Tables[y * MULT + 1])
end
local function yOf(db: number): number
local y = floor((db - DB[1]) / (DB[RANGE] - DB[1]) * (RANGE - 1) + 0.5)
return math.clamp(y, 0, RANGE - 1)
end
local function predict(x: number, x0: number, x1: number, y0: number, y1: number): number
local dy = y1 - y0
local adx = x1 - x0
local off = (abs(dy) * (x - x0)) // adx
return if dy < 0 then y0 - off else y0 + off
end
-- render the decoder's floor curve for final Y values into F[1..N2] (only the posts the decoder marks used)
local function renderFloor(Y: { number }, used: { boolean }, F: { number })
local lx, ly = 0, Y[1] * MULT
for q = 2, NPOSTS do
local j = SORTED[q]
if not used[j] then
continue
end
local hx, hy = POSTS[j], Y[j] * MULT
-- draw_line(lx, ly, hx, hy)
local dy = hy - ly
local adx = hx - lx
local ady = abs(dy)
local base = if dy < 0 then -(ady // adx) else ady // adx
local sy = if dy < 0 then base - 1 else base + 1
ady -= abs(base) * adx
local x, y, err = lx, ly, 0
local x1 = math.min(hx, N2)
if x < x1 then
F[x + 1] = Tables[y % 256 + 1]
x += 1
while x < x1 do
err += ady
if err >= adx then
err -= adx
y += sy
else
y += base
end
F[x + 1] = Tables[y % 256 + 1]
x += 1
end
end
lx, ly = hx, hy
end
for x = lx + 1, N2 do
F[x] = Tables[ly % 256 + 1]
end
end
-- the coded value for target t at post j given the final values of its neighbours (spec 7.2.4 step 1, inverted)
local function floorVal(Y: { number }, j: number): number
local lo, hi = LOW[j], HIGH[j]
local pred = predict(POSTS[j], POSTS[lo], POSTS[hi], Y[lo], Y[hi])
local t = Y[j]
local d = t - pred
if d == 0 then
return 0
end
local highroom = RANGE - pred
local lowroom = pred
local room = if highroom < lowroom then highroom * 2 else lowroom * 2
local cands = { if d > 0 then 2 * d else -2 * d - 1, d + lowroom, -d + highroom - 1 }
for _, v in cands do
if v > 0 and v < RANGE then
local got
if v >= room then
got = if highroom > lowroom then v - lowroom + pred else pred - v + highroom - 1
elseif v % 2 == 1 then
got = pred - (v + 1) // 2
else
got = pred + v // 2
end
if got == t then
return v
end
end
end
return 0 -- unreachable for t in range; fall back to the prediction
end
-- ------------------------------------------------------------------------------------------------ headers
local function identHeader(ch: number, rate: number, nominal: number): buffer
local w = newW(64)
put(w, 1, 8)
putString(w, "vorbis")
put(w, 0, 32)
put(w, ch, 8)
put(w, rate, 32)
put(w, 0, 32)
put(w, nominal, 32)
put(w, 0, 32)
put(w, 8, 4) -- blocksize 0: 256
put(w, 11, 4) -- blocksize 1: 2048
put(w, 1, 1)
return finish(w)
end
local function commentHeader(vendor: string, tags: { [string]: string }): buffer
local w = newW(256)
put(w, 3, 8)
putString(w, "vorbis")
put(w, #vendor, 32)
putString(w, vendor)
local keys = {}
for k, v in tags do
if type(k) == "string" and type(v) == "string" then
table.insert(keys, k)
end
end
table.sort(keys)
put(w, #keys, 32)
for _, k in keys do
local name = if k == "track" then "TRACKNUMBER" else string.upper(k)
local s = name .. "=" .. tags[k]
put(w, #s, 32)
putString(w, s)
end
put(w, 1, 1)
return finish(w)
end
local function setupHeader(ch: number): buffer
local w = newW(8192)
put(w, 5, 8)
putString(w, "vorbis")
-- codebooks
put(w, #BOOKS - 1, 8)
for _, b in BOOKS do
writeBook(w, b)
end
-- time domain placeholders
put(w, 0, 6)
put(w, 0, 16)
-- one floor 1
put(w, 0, 6)
put(w, 1, 16)
put(w, FLOOR_PARTS, 5)
for _ = 1, FLOOR_PARTS do
put(w, 0, 4) -- class 0
end
put(w, 3, 3) -- class 0: 4 dimensions
put(w, 0, 2) -- no subclasses
put(w, FLOOR_BOOK + 1, 8) -- its one subclass book (+1)
put(w, MULT - 1, 2)
put(w, 10, 4) -- rangebits: x in 0 .. 1024
for j = 3, NPOSTS do
put(w, POSTS[j], 10)
end
-- one residue 2
put(w, 0, 6)
put(w, 2, 16)
put(w, 0, 24) -- begin
put(w, N2 * ch, 24) -- end
put(w, PSIZE_PER_CHANNEL * ch - 1, 24)
put(w, NCLASS - 1, 6)
put(w, CLASS_BOOK, 8)
for c = 1, NCLASS do
local bits = 0
for pass = 1, 3 do
if CLASS_BOOKS[c][pass] >= 0 then
bits += POW[pass]
end
end
put(w, bits % 8, 3)
if bits >= 8 then
put(w, 1, 1)
put(w, bits // 8, 5)
else
put(w, 0, 1)
end
end
for c = 1, NCLASS do
for pass = 1, 3 do
local b = CLASS_BOOKS[c][pass]
if b >= 0 then
put(w, b, 8)
end
end
end
-- one mapping
put(w, 0, 6)
put(w, 0, 16)
put(w, 0, 1) -- one submap
if ch == 2 then
put(w, 1, 1)
put(w, 0, 8) -- one coupling step
put(w, 0, 1) -- magnitude: channel 0
put(w, 1, 1) -- angle: channel 1
else
put(w, 0, 1)
end
put(w, 0, 2)
put(w, 0, 8) -- submap 0: time (unused)
put(w, 0, 8) -- floor 0
put(w, 0, 8) -- residue 0
-- one mode: long blocks
put(w, 0, 6)
put(w, 1, 1)
put(w, 0, 16)
put(w, 0, 16)
put(w, 0, 8)
put(w, 1, 1) -- framing
return finish(w)
end
-- ------------------------------------------------------------------------------------------------ encoder
export type Source = {
sampleRate: number,
channels: number,
frames: number,
tags: { [string]: string },
read: (self: any, n: number, out: buffer?) -> (buffer, number),
err: any,
}
export type Options = {
quality: number, -- -1 .. 10
vendor: string,
serial: number,
}
-- the residue of one partition: vectors of each pass for class c
local function writePartition(w: W, v: { number }, o: number, psize: number, c: number, pass: number)
local b = CLASS_BOOKS[c][pass]
if b < 0 then
return
end
local book = BOOKS[b + 1]
local dims, h = book.dims, (book.values - 1) // 2
local scale = book.delta
local values = book.values
local i = 0
while i < psize do
local e = 0
local m = 1
for k = 0, dims - 1 do
local x = v[o + i + k + 1]
-- the part of x this pass carries (coarse passes take the rounded multiple of their scale)
local q
if pass < 3 and CLASS_BOOKS[c][pass + 1] >= 0 then
q = math.clamp(floor(x / scale + 0.5), -h, h)
else
q = math.clamp(x // scale, -h, h)
end
v[o + i + k + 1] = x - q * scale
e += (q + h) * m
m *= values
end
putEntry(w, book, e)
i += dims
end
end
function Encode.encode(src: Source, opts: Options): (buffer?, string?)
local ch, rate = src.channels, src.sampleRate
local q = math.clamp(opts.quality, -1, 10)
local snrDb = 2 * q - 1 -- floor level below the band energy (at low frequencies; 8 dB less at the top)
local mux = Ogg.muxer({ pageSize = 4096 })
local stream = mux:stream(opts.serial)
local nominal = floor(math.clamp(rate * ch * (0.6 + 0.12 * q), 32000, 500000))
stream:packet(identHeader(ch, rate, nominal), 0, { flush = true })
stream:packet(commentHeader(opts.vendor, src.tags), 0)
stream:packet(setupHeader(ch), 0, { flush = true })
local plan = Mdct.new(N) :: Mdct.Plan
local win = Mdct.window("vorbis", N) :: { number }
-- input ring: per channel the samples of the current frame [k*1024 - 1024, k*1024 + 1024)
local frame = table.create(ch)
for c = 1, ch do
frame[c] = table.create(N, 0)
end
local blk = table.create(N, 0)
local X = table.create(ch)
local R = table.create(ch)
for c = 1, ch do
X[c] = table.create(N2, 0)
R[c] = table.create(N2, 0)
end
local F = table.create(N2, 0)
local Y = table.create(NPOSTS, 0)
local vals = table.create(NPOSTS, 0)
local used = table.create(NPOSTS, false)
local inter = table.create(N2 * ch, 0)
local psize = PSIZE_PER_CHANNEL * ch
local npart = N2 * ch // psize
local classes = table.create(npart + 2, 0)
local total = 0
local srcDone = false
local tmp: buffer? = nil
local pending: buffer? = nil
local pendN, pendOff = 0, 0
local k = 0
local lastWanted = -1 -- the last packet index needed (known once the input ends)
while true do
-- shift in the next 1024 input samples (zeros past the end)
for c = 1, ch do
local fr = frame[c]
table.move(fr, N2 + 1, N, 1)
end
local got = 0
while got < N2 and not srcDone do
if pendN == 0 then
local b, n = src:read(4096, tmp)
if n <= 0 then
srcDone = true
break
end
tmp = b
pending, pendN, pendOff = b, n, 0
end
local take = math.min(N2 - got, pendN)
local pb = pending :: buffer
for i = 0, take - 1 do
local base = (pendOff + i) * ch * 4
for c = 1, ch do
frame[c][N2 + got + i + 1] = buffer.readf32(pb, base + (c - 1) * 4)
end
end
got += take
pendN -= take
pendOff += take
end
for c = 1, ch do
local fr = frame[c]
for i = N2 + got + 1, N do
fr[i] = 0
end
end
total += got
if srcDone and lastWanted < 0 then
lastWanted = (total + N2 - 1) // N2 -- packets 0 .. lastWanted (packet j returns [(j-1)*1024, j*1024))
end
-- this frame is centred on k*1024; its first half is [k*1024 - 1024, k*1024)
-- (frame k holds input [(k - 1) * 1024, (k + 1) * 1024): the shift above moved the window by 1024)
-- MDCT per channel
local energy = 0
for c = 1, ch do
local fr = frame[c]
for i = 1, N do
blk[i] = fr[i] * win[i]
end
Mdct.forward(plan, blk, 1, X[c], 1, 1, 4 / N)
local xc = X[c]
for i = 1, N2 do
energy += xc[i] * xc[i]
end
end
local w = newW(2048)
put(w, 0, 1) -- audio packet
-- (one mode: 0 bits) long block, previous and next long
put(w, 1, 1)
put(w, 1, 1)
local silent = energy < 1e-18
if silent then
for _ = 1, ch do
put(w, 0, 1) -- no floor: the channel is zero
end
else
-- the floor from the loudest channel's band energies at each post
for j = 1, NPOSTS do
local x = POSTS[j]
-- the band around x: halfway to the neighbouring posts in x order
local idx = table.find(SORTED, j) :: number
local lo = if idx > 1 then (POSTS[SORTED[idx - 1]] + x) // 2 else 0
local hi = if idx < NPOSTS then (POSTS[SORTED[idx + 1]] + x) // 2 else N2 - 1
if hi < lo then
hi = lo
end
local e = 0
for c = 1, ch do
local xc = X[c]
local s = 0
for i = lo + 1, math.min(hi + 1, N2) do
s += xc[i] * xc[i]
end
s /= (hi - lo + 1)
if s > e then
e = s
end
end
local db = if e > 0 then 10 * math.log10(e) - snrDb + 8 * x / N2 else -200
Y[j] = yOf(db)
end
-- the decoder's step 2 flags: a point is drawn when its value or a later neighbour's value is nonzero
used[1], used[2] = true, true
for j = 3, NPOSTS do
local v = floorVal(Y, j)
vals[j] = v
used[j] = v ~= 0
if v ~= 0 then
used[LOW[j]], used[HIGH[j]] = true, true
end
end
renderFloor(Y, used, F)
-- residues: X / F rounded, then coupling, then interleaving
for c = 1, ch do
local xc, rc = X[c], R[c]
for i = 1, N2 do
local v = floor(xc[i] / F[i] + 0.5)
rc[i] = math.clamp(v, -4095, 4095)
end
end
if ch == 2 then
local l, r = R[1], R[2]
for i = 1, N2 do
local a, b = l[i], r[i]
local m, an
if abs(a) > abs(b) then
m = a
an = if a > 0 then a - b else b - a
else
m = b
an = if b > 0 then a - b else b - a
end
-- keep the angle inside the books' range
l[i], r[i] = m, math.clamp(an, -4095, 4095)
end
end
for c = 1, ch do
local rc = R[c]
for i = 1, N2 do
inter[(i - 1) * ch + c] = rc[i]
end
end
-- floors
for _ = 1, ch do
put(w, 1, 1)
put(w, Y[1], 7)
put(w, Y[2], 7)
for j = 3, NPOSTS do
putEntry(w, BOOK_FLOOR, vals[j])
end
end
-- residue classes
for p = 0, npart - 1 do
local m = 0
for i = 1, psize do
local a = abs(inter[p * psize + i])
if a > m then
m = a
end
end
local c = 1
while CLASS_MAX[c] < m do
c += 1
end
classes[p + 1] = c
end
classes[npart + 1] = 1
for pass = 1, 3 do
for p = 0, npart - 1, 2 do
if pass == 1 then
putEntry(w, BOOK_CLASS, (classes[p + 1] - 1) * NCLASS + (classes[p + 2] - 1)) -- first partition: the high digit
end
writePartition(w, inter, p * psize, psize, classes[p + 1], pass)
if p + 1 < npart then
writePartition(w, inter, (p + 1) * psize, psize, classes[p + 2], pass)
end
end
end
end
local pk = finish(w)
local last = lastWanted >= 0 and k >= lastWanted
local granule = if k == 0 then 0 else math.min(k * N2, if lastWanted >= 0 then total else math.huge)
stream:packet(pk, granule, if last then { eos = true } else nil)
if last then
break
end
k += 1
end
if src.err then
return nil, tostring(src.err)
end
return mux:finish(), nil
end
-- the codebooks (tests check the Huffman lengths are a valid prefix code)
Encode.BOOKS = BOOKS
return Encode
+586
View File
@@ -0,0 +1,586 @@
--!strict
--!native
--!optimize 2
-- audio/vorbis/Packet: Vorbis audio packet decoding (Vorbis I spec sections 4.3, 7, 8): mode and window shape, floor 1
-- curves, residue types 0 / 1 / 2, inverse channel coupling, the IMDCT (codecs/Mdct), windowing and overlap-add.
-- Floors, residues and coupling are ported from stb_vorbis 1.22 vorbis_decode_packet_rest / decode_residue /
-- do_floor / draw_line (public domain / MIT; see licenses/stb_vorbis-LICENSE.txt). The overlap follows libvorbis:
-- each packet after the first returns the n_prev/4 + n_cur/4 samples between the centres of the two windows, so
-- granule positions count exactly the samples returned (the first packet returns none).
--
-- local st = Packet.new(ident, setup)
-- local n = Packet.decode(st, buf, offset, size) -- frames now in st.out[ch][1 .. n]; -1 = not an audio packet
-- Packet.reset(st) -- forget the overlap (after a seek / a gap)
-- local bs = Packet.blocksize(st, buf, offset, size) -- the packet's block size (0 = not audio), header bits only
-- Never throws: a damaged packet decodes as far as its bits go (the spec's end-of-packet rule) or returns -1.
local Codebook = require("@formats/audio/vorbis/Codebook")
local Setup = require("@formats/audio/vorbis/Setup")
local Tables = require("@formats/audio/vorbis/Tables")
local Mdct = require("@formats/codecs/Mdct")
local Packet = {}
local bits, decode = Codebook.bits, Codebook.decode
local ilog = Codebook.ilog
local INV_DB = Tables
local RANGE = { 256, 128, 86, 64 }
export type State = {
channels: number,
n0: number,
n1: number,
setup: Setup.Setup,
plans: { [number]: Mdct.Plan },
slopes: { [number]: { number } }, -- rising half-window of overlap length L (= blocksize / 2)
spec: { { number } }, -- per channel: n/2 spectral values (residue, then times the floor)
frame: { { number } }, -- per channel: n windowed time samples
tail: { { number } }, -- per channel: the previous frame from its centre on
tailLen: number,
prevN: number, -- the previous block size, 0 = no previous frame
out: { { number } }, -- per channel: the returned samples
finalY: { { number } },
step2: { number },
inter: { number }, -- residue type 2 interleaved scratch
zero: { boolean },
reallyZero: { boolean },
partClass: { { { number } } },
}
function Packet.new(id: Setup.Ident, setup: Setup.Setup): State?
local n0, n1, ch = id.blocksize0, id.blocksize1, id.channels
local plans: { [number]: Mdct.Plan } = {}
local slopes: { [number]: { number } } = {}
for _, n in { n0, n1 } do
local p = Mdct.new(n)
if not p then
return nil
end
plans[n] = p
local w = Mdct.window("vorbis", n) :: { number }
local half = table.create(n // 2, 0)
for i = 1, n // 2 do
half[i] = w[i]
end
slopes[n // 2] = half
end
local function arrays(len: number): { { number } }
local t = table.create(ch)
for c = 1, ch do
t[c] = table.create(len, 0)
end
return t
end
local partClass = table.create(ch)
for c = 1, ch do
partClass[c] = {}
end
return {
channels = ch,
n0 = n0,
n1 = n1,
setup = setup,
plans = plans,
slopes = slopes,
spec = arrays(n1 // 2),
frame = arrays(n1),
tail = arrays(n1 // 2),
tailLen = 0,
prevN = 0,
out = arrays(n1),
finalY = arrays(math.max(2, setup.maxFloorValues)),
step2 = table.create(math.max(2, setup.maxFloorValues), 0),
inter = table.create(n1 // 2 * ch, 0),
zero = table.create(ch, false),
reallyZero = table.create(ch, false),
partClass = partClass,
}
end
function Packet.reset(st: State)
st.prevN = 0
st.tailLen = 0
end
-- blocksize(st, buf, off, size) -> the block size of an audio packet (0 if not audio)
function Packet.blocksize(st: State, b: buffer, off: number, size: number): number
if size < 1 then
return 0
end
local br = Codebook.reader(b, off, size)
if bits(br, 1) ~= 0 then
return 0
end
local m = bits(br, st.setup.modeBits)
local mode = st.setup.modes[m + 1]
if not mode or br.eop then
return 0
end
return if mode.blockflag == 1 then st.n1 else st.n0
end
-- ------------------------------------------------------------------------------------------------ floor 1
local function predict(x: number, x0: number, x1: number, y0: number, y1: number): number
local dy = y1 - y0
local adx = x1 - x0
local off = ((if dy < 0 then -dy else dy) * (x - x0)) // adx
return if dy < 0 then y0 - off else y0 + off
end
-- multiply out[x0 .. x1) by the floor line from (x0, y0) to (x1, y1) (stb draw_line)
local function drawLine(out: { number }, x0: number, y0: number, x1: number, y1: number, n: number)
local dy = y1 - y0
local adx = x1 - x0
local ady = if dy < 0 then -dy else dy
local base = if dy < 0 then -(ady // adx) else ady // adx
local sy = if dy < 0 then base - 1 else base + 1
ady -= (if base < 0 then -base else base) * adx
if x1 > n then
x1 = n
end
local x, y, err = x0, y0, 0
if x < x1 then
out[x + 1] *= INV_DB[y % 256 + 1]
x += 1
while x < x1 do
err += ady
if err >= adx then
err -= adx
y += sy
else
y += base
end
out[x + 1] *= INV_DB[y % 256 + 1]
x += 1
end
end
end
-- decode the floor of one channel into finalY (-1 = unused point); false = this channel is silent
local function floorDecode(st: State, br: Codebook.Br, g: Setup.Floor1, finalY: { number }): boolean
if bits(br, 1) == 0 then
return false
end
local books = st.setup.books
local range = RANGE[g.multiplier]
local yb = ilog(range) - 1
finalY[1] = bits(br, yb)
finalY[2] = bits(br, yb)
local offset = 2
for j = 1, g.partitions do
local pclass = g.partitionClass[j] + 1
local cdim = g.classDims[pclass]
local cbits = g.classSubs[pclass]
local csub = 2 ^ cbits
local cval = 0
if cbits > 0 then
cval = decode(br, books[g.classMaster[pclass] + 1])
if cval < 0 then
return false
end
end
local subs = g.subBooks[pclass]
for _ = 1, cdim do
local book = subs[cval % csub + 1]
cval = cval // csub
if book >= 0 then
local v = decode(br, books[book + 1])
if v < 0 then
return false
end
finalY[offset + 1] = v
else
finalY[offset + 1] = 0
end
offset += 1
end
end
if br.eop then
return false
end
-- step 1: amplitude value synthesis
local step2 = st.step2
step2[1], step2[2] = 1, 1
local xl, low, high = g.xlist, g.low, g.high
for j = 2, g.values - 1 do
local lo, hi = low[j + 1], high[j + 1]
local pred = predict(xl[j + 1], xl[lo + 1], xl[hi + 1], finalY[lo + 1], finalY[hi + 1])
local val = finalY[j + 1]
local highroom = range - pred
local lowroom = pred
local room = if highroom < lowroom then highroom * 2 else lowroom * 2
if val ~= 0 then
step2[lo + 1], step2[hi + 1], step2[j + 1] = 1, 1, 1
if val >= room then
if highroom > lowroom then
finalY[j + 1] = val - lowroom + pred
else
finalY[j + 1] = pred - val + highroom - 1
end
elseif val % 2 == 1 then
finalY[j + 1] = pred - (val + 1) // 2
else
finalY[j + 1] = pred + val // 2
end
else
step2[j + 1] = 0
finalY[j + 1] = pred
end
end
for j = 1, g.values do
if step2[j] == 0 then
finalY[j] = -1
end
end
return true
end
-- multiply target[1 .. n2] by the floor curve (stb do_floor)
local function floorCurve(g: Setup.Floor1, finalY: { number }, target: { number }, n2: number)
local mult = g.multiplier
local lx, ly = 0, finalY[1] * mult
local sorted, xl = g.sorted, g.xlist
for q = 2, g.values do
local j = sorted[q] + 1
local fy = finalY[j]
if fy >= 0 then
local hy = fy * mult
local hx = xl[j]
if lx ~= hx then
drawLine(target, lx, ly, hx, hy, n2)
end
lx, ly = hx, hy
end
end
if lx < n2 then
local v = INV_DB[ly % 256 + 1]
for j = lx + 1, n2 do
target[j] *= v
end
end
end
-- ------------------------------------------------------------------------------------------------ residue
-- add the vectors of one partition to target at offset (0-based) .. offset + psize (bounded by limit)
local function partition(br: Codebook.Br, book: Codebook.Book, target: { number }, offset: number, psize: number, rtype: number, limit: number): boolean
local vq = book.vq
if not vq then
br.eop = true -- a scalar book in a vector context: invalid stream
return false
end
local dims = book.dims
if rtype == 0 then
local step = psize // dims
for k = 0, step - 1 do
local e = decode(br, book)
if e < 0 then
return false
end
local base = e * dims
for i = 0, dims - 1 do
local at = offset + k + i * step
if at < limit then
target[at + 1] += vq[base + i + 1]
end
end
end
else
local k = 0
while k < psize do
local e = decode(br, book)
if e < 0 then
return false
end
local base = e * dims
local len = math.min(dims, psize - k)
local at = offset + k
for i = 0, len - 1 do
if at + i < limit then
target[at + i + 1] += vq[base + i + 1]
end
end
k += dims
end
end
return true
end
-- decode residue r for the channels `targets` (nil = do not decode) of length n2 each
local function residue(st: State, br: Codebook.Br, r: Setup.Residue, targets: { { number } | false }, ch: number, n2: number)
local books = st.setup.books
local rtype = r.type
local cbook = books[r.classbook + 1]
local classwords = cbook.dims
for j = 1, ch do
local t = targets[j]
if t then
for i = 1, n2 do
(t :: { number })[i] = 0
end
end
end
local any = false
for j = 1, ch do
if targets[j] then
any = true
end
end
if not any then
return
end
local psize = r.partSize
local rb = r.books
local classdata = r.classdata
if rtype == 2 and ch > 1 then
local total = n2 * ch
local inter = st.inter
for i = 1, total do
inter[i] = 0
end
local lb = math.min(r.begin, total)
local le = math.min(r.finish, total)
local partRead = (le - lb) // psize
local pc = st.partClass[1]
local done = false
for pass = 1, 8 do
if done then
break
end
local pcount, classSet = 0, 1
while pcount < partRead do
if pass == 1 then
local q = decode(br, cbook)
if q < 0 then
done = true
break
end
pc[classSet] = classdata[q + 1]
end
local cls = pc[classSet]
local i = 0
while i < classwords and pcount < partRead do
local b = rb[cls[i + 1] + 1][pass]
if b >= 0 then
if not partition(br, books[b + 1], inter, r.begin + pcount * psize, psize, 1, total) then
done = true
break
end
end
i += 1
pcount += 1
end
if done then
break
end
classSet += 1
end
end
-- de-interleave into the channels that are decoded
for j = 1, ch do
local t = targets[j]
if t then
local tt = t :: { number }
local v = j
for i = 1, n2 do
tt[i] = inter[v]
v += ch
end
end
end
return
end
local lb = math.min(r.begin, n2)
local le = math.min(r.finish, n2)
local partRead = (le - lb) // psize
local pcs = st.partClass
for pass = 1, 8 do
local pcount, classSet = 0, 1
while pcount < partRead do
if pass == 1 then
for j = 1, ch do
if targets[j] then
local q = decode(br, cbook)
if q < 0 then
return
end
pcs[j][classSet] = classdata[q + 1]
end
end
end
local i = 0
while i < classwords and pcount < partRead do
for j = 1, ch do
local t = targets[j]
if t then
local c = pcs[j][classSet][i + 1]
local b = rb[c + 1][pass]
if b >= 0 then
if not partition(br, books[b + 1], t :: { number }, r.begin + pcount * psize, psize, rtype, n2) then
return
end
end
end
end
i += 1
pcount += 1
end
classSet += 1
end
end
end
-- ------------------------------------------------------------------------------------------------ packet
-- decode(st, buf, off, size) -> frames returned in st.out (0 for the first packet), -1 for a non-audio / bad packet
function Packet.decode(st: State, b: buffer, off: number, size: number): number
if size < 1 then
return -1
end
local setup = st.setup
local br = Codebook.reader(b, off, size)
if bits(br, 1) ~= 0 then
return -1
end
local mode = setup.modes[bits(br, setup.modeBits) + 1]
if not mode then
return -1
end
local n, prevLong, nextLong
if mode.blockflag == 1 then
n = st.n1
prevLong = bits(br, 1) == 1
nextLong = bits(br, 1) == 1
else
n = st.n0
prevLong, nextLong = false, false
end
if br.eop then
return -1
end
local n2 = n // 2
local n0 = st.n0
local leftStart, leftEnd, rightStart, rightEnd
if mode.blockflag == 1 and not prevLong then
leftStart, leftEnd = (n - n0) // 4, (n + n0) // 4
else
leftStart, leftEnd = 0, n2
end
if mode.blockflag == 1 and not nextLong then
rightStart, rightEnd = (n * 3 - n0) // 4, (n * 3 + n0) // 4
else
rightStart, rightEnd = n2, n
end
local map = setup.mappings[mode.mapping + 1]
local ch = st.channels
local spec, zero, reallyZero = st.spec, st.zero, st.reallyZero
-- floors
for c = 1, ch do
local s = map.mux[c] + 1
local g = setup.floors[map.submapFloor[s] + 1]
local ok = floorDecode(st, br, g, st.finalY[c])
zero[c] = not ok
reallyZero[c] = not ok
end
-- channels coupled to a non-silent channel are decoded too
for i = 1, map.couplingSteps do
local m, a = map.magnitude[i] + 1, map.angle[i] + 1
if not zero[m] or not zero[a] then
zero[m], zero[a] = false, false
end
end
-- residues, per submap
for i = 1, map.submaps do
local targets: { { number } | false } = {}
local k = 0
for c = 1, ch do
if map.mux[c] == i - 1 then
k += 1
targets[k] = if zero[c] then false else spec[c]
end
end
residue(st, br, setup.residues[map.submapResidue[i] + 1], targets, k, n2)
end
-- inverse coupling
for i = map.couplingSteps, 1, -1 do
local m, a = spec[map.magnitude[i] + 1], spec[map.angle[i] + 1]
for j = 1, n2 do
local mv, av = m[j], a[j]
local m2, a2
if mv > 0 then
if av > 0 then
m2, a2 = mv, mv - av
else
a2, m2 = mv, mv + av
end
else
if av > 0 then
m2, a2 = mv, mv + av
else
a2, m2 = mv, mv - av
end
end
m[j], a[j] = m2, a2
end
end
-- floor curves, IMDCT, windows
local plan = st.plans[n]
local lslope = st.slopes[leftEnd - leftStart]
local rslope = st.slopes[rightEnd - rightStart]
for c = 1, ch do
local sp = spec[c]
local fr = st.frame[c]
if reallyZero[c] then
for j = 1, n do
fr[j] = 0
end
else
local s = map.mux[c] + 1
floorCurve(setup.floors[map.submapFloor[s] + 1], st.finalY[c], sp, n2)
Mdct.inverse(plan, sp, 1, 1, fr, 1)
for j = 1, leftStart do
fr[j] = 0
end
local L = leftEnd - leftStart
for j = 0, L - 1 do
fr[leftStart + j + 1] *= lslope[j + 1]
end
local R = rightEnd - rightStart
for j = 0, R - 1 do
fr[rightStart + j + 1] *= rslope[R - j]
end
for j = rightEnd + 1, n do
fr[j] = 0
end
end
end
-- overlap-add with the previous frame; return the samples between the two centres
local prevN = st.prevN
local count = 0
if prevN > 0 then
count = prevN // 4 + n // 4
local o = prevN // 4 - n // 4 -- this frame starts o samples after the previous centre
local tl = st.tailLen
for c = 1, ch do
local out, tail, fr = st.out[c], st.tail[c], st.frame[c]
for j = 0, count - 1 do
local v = if j < tl then tail[j + 1] else 0
local fi = j - o
if fi >= 0 then
v += fr[fi + 1]
end
out[j + 1] = v
end
end
end
-- the new tail: this frame from its centre to the end of its window
local tl = rightEnd - n2
for c = 1, ch do
local tail, fr = st.tail[c], st.frame[c]
for j = 1, tl do
tail[j] = fr[n2 + j]
end
end
st.tailLen = tl
st.prevN = n
return count
end
return Packet
+429
View File
@@ -0,0 +1,429 @@
--!strict
--!native
-- audio/vorbis/Setup: the three Vorbis header packets (Vorbis I spec section 4.2): identification (channels, rate,
-- bitrates, blocksizes), comment (vendor + user comments -> tags) and setup (codebooks, floors, residues, mappings,
-- modes). Ported from stb_vorbis 1.22 start_decoder (public domain / MIT; see licenses/stb_vorbis-LICENSE.txt).
-- Floor 0 is rejected as unsupported, as stb_vorbis does (no encoder has produced it since 2000).
-- Never throws: every parser returns nil, message on bad data.
local Codebook = require("@formats/audio/vorbis/Codebook")
local Setup = {}
local bits, ilog = Codebook.bits, Codebook.ilog
local readu8, readu32 = buffer.readu8, buffer.readu32
export type Ident = {
channels: number,
sampleRate: number,
bitrateMax: number,
bitrateNominal: number,
bitrateMin: number,
blocksize0: number,
blocksize1: number,
}
export type Floor1 = {
partitions: number,
partitionClass: { number }, -- 1-based list of class numbers (0-based values)
classDims: { number }, -- [class + 1]
classSubs: { number },
classMaster: { number },
subBooks: { { number } }, -- [class + 1][sub + 1] = book (0-based) or -1
multiplier: number,
xlist: { number }, -- [j + 1]
values: number,
sorted: { number }, -- point indices (0-based) by increasing x
low: { number }, -- neighbours, [j + 1] (0-based indices)
high: { number },
}
export type Residue = {
type: number,
begin: number,
finish: number,
partSize: number,
classifications: number,
classbook: number,
books: { { number } }, -- [class + 1][pass + 1] = book or -1
classdata: { { number } }, -- [classbook entry + 1][k + 1] = class
}
export type Mapping = {
submaps: number,
couplingSteps: number,
magnitude: { number }, -- [step + 1] channel (0-based)
angle: { number },
mux: { number }, -- [channel + 1] submap (0-based)
submapFloor: { number },
submapResidue: { number },
}
export type Mode = { blockflag: number, mapping: number }
export type Setup = {
books: { Codebook.Book },
floors: { Floor1 },
residues: { Residue },
mappings: { Mapping },
modes: { Mode },
modeBits: number,
maxFloorValues: number,
}
local function isVorbis(b: buffer, o: number, n: number, kind: number): boolean
return n >= 7 and readu8(b, o) == kind and buffer.readstring(b, o + 1, 6) == "vorbis"
end
Setup.isVorbis = isVorbis
-- ident(buf, offset, size) -> Ident | nil, message
function Setup.ident(b: buffer, o: number, n: number): (Ident?, string?)
if not isVorbis(b, o, n, 1) then
return nil, "not a Vorbis identification header"
end
if n < 30 then
return nil, "short identification header"
end
if readu32(b, o + 7) ~= 0 then
return nil, "Vorbis version " .. readu32(b, o + 7)
end
local ch = readu8(b, o + 11)
local rate = readu32(b, o + 12)
local bs = readu8(b, o + 28)
local l0, l1 = bs % 16, bs // 16
if ch == 0 or rate == 0 then
return nil, "no channels or no sample rate"
end
if l0 < 6 or l0 > 13 or l1 < 6 or l1 > 13 or l0 > l1 then
return nil, "bad blocksizes"
end
if readu8(b, o + 29) % 2 == 0 then
return nil, "identification header framing bit not set"
end
return {
channels = ch,
sampleRate = rate,
bitrateMax = buffer.readi32(b, o + 16),
bitrateNominal = buffer.readi32(b, o + 20),
bitrateMin = buffer.readi32(b, o + 24),
blocksize0 = 2 ^ l0,
blocksize1 = 2 ^ l1,
},
nil
end
-- comment(buf, offset, size) -> vendor, { "KEY=value" } | nil, message
function Setup.comment(b: buffer, o: number, n: number): (string?, { string }?)
if not isVorbis(b, o, n, 3) then
return nil, nil
end
local p, e = o + 7, o + n
if p + 4 > e then
return nil, nil
end
local vlen = readu32(b, p)
p += 4
if vlen > e - p then
return nil, nil
end
local vendor = buffer.readstring(b, p, vlen)
p += vlen
local list = {}
if p + 4 > e then
return vendor, list
end
local count = readu32(b, p)
p += 4
for _ = 1, count do
if p + 4 > e then
break
end
local len = readu32(b, p)
p += 4
if len > e - p then
break
end
table.insert(list, buffer.readstring(b, p, len))
p += len
end
return vendor, list
end
-- setup(buf, offset, size, ident) -> Setup | nil, message
function Setup.setup(b: buffer, o: number, n: number, id: Ident): (Setup?, string?)
if not isVorbis(b, o, n, 5) then
return nil, "not a Vorbis setup header"
end
local br = Codebook.reader(b, o + 7, n - 7)
local channels = id.channels
-- codebooks
local books: { Codebook.Book } = {}
local nbooks = bits(br, 8) + 1
for i = 1, nbooks do
local book, err = Codebook.read(br)
if not book then
return nil, "codebook " .. (i - 1) .. ": " .. tostring(err)
end
books[i] = book
end
-- time domain transforms (placeholders)
local ntimes = bits(br, 6) + 1
for _ = 1, ntimes do
if bits(br, 16) ~= 0 then
return nil, "bad time domain transform"
end
end
-- floors
local floors: { Floor1 } = {}
local maxValues = 0
local nfloors = bits(br, 6) + 1
for i = 1, nfloors do
local ftype = bits(br, 16)
if ftype == 0 then
return nil, "floor 0"
elseif ftype ~= 1 then
return nil, "bad floor type " .. ftype
end
local parts = bits(br, 5)
local pclass = table.create(parts, 0)
local maxClass = -1
for j = 1, parts do
pclass[j] = bits(br, 4)
if pclass[j] > maxClass then
maxClass = pclass[j]
end
end
local cdims, csubs, cmaster, subBooks = {}, {}, {}, {}
for j = 1, maxClass + 1 do
cdims[j] = bits(br, 3) + 1
csubs[j] = bits(br, 2)
cmaster[j] = -1
if csubs[j] > 0 then
cmaster[j] = bits(br, 8)
if cmaster[j] >= nbooks then
return nil, "bad floor master book"
end
end
local sb = {}
for k = 1, 2 ^ csubs[j] do
sb[k] = bits(br, 8) - 1
if sb[k] >= nbooks then
return nil, "bad floor subclass book"
end
end
subBooks[j] = sb
end
local mult = bits(br, 2) + 1
local rangebits = bits(br, 4)
local xlist = { 0, 2 ^ rangebits }
for j = 1, parts do
local c = pclass[j]
for _ = 1, cdims[c + 1] do
table.insert(xlist, bits(br, rangebits))
end
end
local values = #xlist
if values > 65 * 8 then
return nil, "too many floor points"
end
if br.eop then
return nil, "setup header ends in a floor"
end
local order = table.create(values, 0)
for j = 1, values do
order[j] = j - 1
end
table.sort(order, function(a: number, c: number): boolean
return xlist[a + 1] < xlist[c + 1]
end)
for j = 1, values - 1 do
if xlist[order[j] + 1] == xlist[order[j + 1] + 1] then
return nil, "duplicate floor x"
end
end
local low, high = table.create(values, 0), table.create(values, 0)
for j = 2, values - 1 do
local lo, hi = -1, 65536
local x = xlist[j + 1]
for k = 0, j - 1 do
local xv = xlist[k + 1]
if xv > lo and xv < x then
low[j + 1], lo = k, xv
end
if xv < hi and xv > x then
high[j + 1], hi = k, xv
end
end
end
floors[i] = {
partitions = parts,
partitionClass = pclass,
classDims = cdims,
classSubs = csubs,
classMaster = cmaster,
subBooks = subBooks,
multiplier = mult,
xlist = xlist,
values = values,
sorted = order,
low = low,
high = high,
}
if values > maxValues then
maxValues = values
end
end
-- residues
local residues: { Residue } = {}
local nres = bits(br, 6) + 1
for i = 1, nres do
local rtype = bits(br, 16)
if rtype > 2 then
return nil, "bad residue type " .. rtype
end
local rbegin, rend = bits(br, 24), bits(br, 24)
local psize = bits(br, 24) + 1
local ncls = bits(br, 6) + 1
local cbook = bits(br, 8)
if rend < rbegin then
return nil, "residue end before begin"
end
if cbook >= nbooks then
return nil, "bad residue classbook"
end
local cascade = table.create(ncls, 0)
for j = 1, ncls do
local lowBits = bits(br, 3)
local highBits = if bits(br, 1) == 1 then bits(br, 5) else 0
cascade[j] = highBits * 8 + lowBits
end
local rbooks = {}
for j = 1, ncls do
local row = table.create(8, -1)
local c = cascade[j]
for k = 1, 8 do
if c % 2 == 1 then
row[k] = bits(br, 8)
if row[k] >= nbooks then
return nil, "bad residue book"
end
end
c = c // 2
end
rbooks[j] = row
end
if br.eop then
return nil, "setup header ends in a residue"
end
-- class numbers of each classbook entry (stb's classdata)
local cb = books[cbook + 1]
local cw = cb.dims
if cb.entries * cw > 2 ^ 22 then
return nil, "residue classbook too large"
end
local classdata = table.create(cb.entries)
for j = 0, cb.entries - 1 do
local row = table.create(cw, 0)
local tmp = j
for k = cw, 1, -1 do
row[k] = tmp % ncls
tmp = tmp // ncls
end
classdata[j + 1] = row
end
residues[i] = {
type = rtype,
begin = rbegin,
finish = rend,
partSize = psize,
classifications = ncls,
classbook = cbook,
books = rbooks,
classdata = classdata,
}
end
-- mappings
local mappings: { Mapping } = {}
local nmaps = bits(br, 6) + 1
local chBits = ilog(channels - 1)
for i = 1, nmaps do
if bits(br, 16) ~= 0 then
return nil, "bad mapping type"
end
local submaps = if bits(br, 1) == 1 then bits(br, 4) + 1 else 1
local steps = 0
local mag, ang = {}, {}
if bits(br, 1) == 1 then
steps = bits(br, 8) + 1
if steps > channels then
return nil, "too many coupling steps"
end
for k = 1, steps do
mag[k] = bits(br, chBits)
ang[k] = bits(br, chBits)
if mag[k] >= channels or ang[k] >= channels or mag[k] == ang[k] then
return nil, "bad coupling channels"
end
end
end
if bits(br, 2) ~= 0 then
return nil, "mapping reserved bits set"
end
local mux = table.create(channels, 0)
if submaps > 1 then
for j = 1, channels do
mux[j] = bits(br, 4)
if mux[j] >= submaps then
return nil, "bad channel mux"
end
end
end
local sf, sr = {}, {}
for j = 1, submaps do
bits(br, 8)
sf[j] = bits(br, 8)
sr[j] = bits(br, 8)
if sf[j] >= nfloors or sr[j] >= nres then
return nil, "bad submap floor / residue"
end
end
mappings[i] = {
submaps = submaps,
couplingSteps = steps,
magnitude = mag,
angle = ang,
mux = mux,
submapFloor = sf,
submapResidue = sr,
}
end
-- modes
local modes: { Mode } = {}
local nmodes = bits(br, 6) + 1
for i = 1, nmodes do
local bf = bits(br, 1)
local wt, tt = bits(br, 16), bits(br, 16)
local m = bits(br, 8)
if wt ~= 0 or tt ~= 0 or m >= nmaps then
return nil, "bad mode"
end
modes[i] = { blockflag = bf, mapping = m }
end
if br.eop then
return nil, "setup header truncated"
end
if bits(br, 1) ~= 1 then
return nil, "setup header framing bit not set"
end
return {
books = books,
floors = floors,
residues = residues,
mappings = mappings,
modes = modes,
modeBits = ilog(nmodes - 1),
maxFloorValues = maxValues,
},
nil
end
return Setup
+37
View File
@@ -0,0 +1,37 @@
--!strict
-- audio/vorbis/Tables: the floor 1 inverse dB table (Vorbis I specification, section 10.1, as in stb_vorbis 1.22,
-- public domain / MIT, licenses/stb_vorbis-LICENSE.txt). 256 values, index = floor value (1-based here).
return table.freeze({
1.0649863e-07, 1.1341951e-07, 1.2079015e-07, 1.2863978e-07, 1.3699951e-07, 1.4590251e-07, 1.5538408e-07, 1.6548181e-07,
1.7623575e-07, 1.8768855e-07, 1.9988561e-07, 2.1287530e-07, 2.2670913e-07, 2.4144197e-07, 2.5713223e-07, 2.7384213e-07,
2.9163793e-07, 3.1059021e-07, 3.3077411e-07, 3.5226968e-07, 3.7516214e-07, 3.9954229e-07, 4.2550680e-07, 4.5315863e-07,
4.8260743e-07, 5.1396998e-07, 5.4737065e-07, 5.8294187e-07, 6.2082472e-07, 6.6116941e-07, 7.0413592e-07, 7.4989464e-07,
7.9862701e-07, 8.5052630e-07, 9.0579828e-07, 9.6466216e-07, 1.0273513e-06, 1.0941144e-06, 1.1652161e-06, 1.2409384e-06,
1.3215816e-06, 1.4074654e-06, 1.4989305e-06, 1.5963394e-06, 1.7000785e-06, 1.8105592e-06, 1.9282195e-06, 2.0535261e-06,
2.1869758e-06, 2.3290978e-06, 2.4804557e-06, 2.6416497e-06, 2.8133190e-06, 2.9961443e-06, 3.1908506e-06, 3.3982101e-06,
3.6190449e-06, 3.8542308e-06, 4.1047004e-06, 4.3714470e-06, 4.6555282e-06, 4.9580707e-06, 5.2802740e-06, 5.6234160e-06,
5.9888572e-06, 6.3780469e-06, 6.7925283e-06, 7.2339451e-06, 7.7040476e-06, 8.2047000e-06, 8.7378876e-06, 9.3057248e-06,
9.9104632e-06, 1.0554501e-05, 1.1240392e-05, 1.1970856e-05, 1.2748789e-05, 1.3577278e-05, 1.4459606e-05, 1.5399272e-05,
1.6400004e-05, 1.7465768e-05, 1.8600792e-05, 1.9809576e-05, 2.1096914e-05, 2.2467911e-05, 2.3928002e-05, 2.5482978e-05,
2.7139006e-05, 2.8902651e-05, 3.0780908e-05, 3.2781225e-05, 3.4911534e-05, 3.7180282e-05, 3.9596466e-05, 4.2169667e-05,
4.4910090e-05, 4.7828601e-05, 5.0936773e-05, 5.4246931e-05, 5.7772202e-05, 6.1526565e-05, 6.5524908e-05, 6.9783085e-05,
7.4317983e-05, 7.9147585e-05, 8.4291040e-05, 8.9768747e-05, 9.5602426e-05, 0.00010181521, 0.00010843174, 0.00011547824,
0.00012298267, 0.00013097477, 0.00013948625, 0.00014855085, 0.00015820453, 0.00016848555, 0.00017943469, 0.00019109536,
0.00020351382, 0.00021673929, 0.00023082423, 0.00024582449, 0.00026179955, 0.00027881276, 0.00029693158, 0.00031622787,
0.00033677814, 0.00035866388, 0.00038197188, 0.00040679456, 0.00043323036, 0.00046138411, 0.00049136745, 0.00052329927,
0.00055730621, 0.00059352311, 0.00063209358, 0.00067317058, 0.00071691700, 0.00076350630, 0.00081312324, 0.00086596457,
0.00092223983, 0.00098217216, 0.0010459992, 0.0011139742, 0.0011863665, 0.0012634633, 0.0013455702, 0.0014330129,
0.0015261382, 0.0016253153, 0.0017309374, 0.0018434235, 0.0019632195, 0.0020908006, 0.0022266726, 0.0023713743,
0.0025254795, 0.0026895994, 0.0028643847, 0.0030505286, 0.0032487691, 0.0034598925, 0.0036847358, 0.0039241906,
0.0041792066, 0.0044507950, 0.0047400328, 0.0050480668, 0.0053761186, 0.0057254891, 0.0060975636, 0.0064938176,
0.0069158225, 0.0073652516, 0.0078438871, 0.0083536271, 0.0088964928, 0.009474637, 0.010090352, 0.010746080,
0.011444421, 0.012188144, 0.012980198, 0.013823725, 0.014722068, 0.015678791, 0.016697687, 0.017782797,
0.018938423, 0.020169149, 0.021479854, 0.022875735, 0.024362330, 0.025945531, 0.027631618, 0.029427276,
0.031339626, 0.033376252, 0.035545228, 0.037855157, 0.040315199, 0.042935108, 0.045725273, 0.048696758,
0.051861348, 0.055231591, 0.058820850, 0.062643361, 0.066714279, 0.071049749, 0.075666962, 0.080584227,
0.085821044, 0.091398179, 0.097337747, 0.10366330, 0.11039993, 0.11757434, 0.12521498, 0.13335215,
0.14201813, 0.15124727, 0.16107617, 0.17154380, 0.18269168, 0.19456402, 0.20720788, 0.22067342,
0.23501402, 0.25028656, 0.26655159, 0.28387361, 0.30232132, 0.32196786, 0.34289114, 0.36517414,
0.38890521, 0.41417847, 0.44109412, 0.46975890, 0.50028648, 0.53279791, 0.56742212, 0.60429640,
0.64356699, 0.68538959, 0.72993007, 0.77736504, 0.82788260, 0.88168307, 0.9389798, 1.0,
})
+486
View File
@@ -0,0 +1,486 @@
--!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/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.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Ogg = require("@formats/containers/Ogg")
local Setup = require("@formats/audio/vorbis/Setup")
local Packet = require("@formats/audio/vorbis/Packet")
local Encode = require("@formats/audio/vorbis/Encode")
local Pcm = require("@formats/codecs/Pcm")
-- ------------------------------------------------------------------------------------------------ contract
local Vorbis = {
name = "vorbis",
category = "audio",
extensions = { "ogg", "oga" },
mime = { "audio/ogg", "audio/vorbis" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/Pcm" },
caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255 },
}
export type OpenOptions = {
verify: boolean?, -- check the Ogg page CRCs (default true)
}
export type EncodeOptions = {
quality: number?, -- -1 .. 10 (default 3): the floor sits 2 * quality - 1 dB under the band energies (8 dB
-- less at the top of the spectrum), which sets the residue's quantization step
serial: number?, -- the Ogg stream serial number (default 0x464C5541)
}
-- ------------------------------------------------------------------------------------------------ constants
local TAG_KEYS = { tracknumber = "track", description = "comment" }
local function tagsOf(comments: { string }): Types.Tags
local tags: Types.Tags = {}
for _, s in comments do
local eq = string.find(s, "=", 1, true)
if eq then
local k = string.lower(string.sub(s, 1, eq - 1))
local v = string.sub(s, eq + 1)
k = TAG_KEYS[k] or k
tags[k] = if tags[k] then tags[k] .. "; " .. v else v
end
end
return tags
end
-- the three headers -> ident, setup, vendor, tags | nil, Err
local function headers(h1: any, h2: any, h3: any): (any, any, string?, Types.Tags?, Err.Err?)
local id, ierr = Setup.ident(h1.data, h1.offset, h1.size)
if not id then
return nil, nil, nil, nil, Err.new(Err.CORRUPT, ierr or "bad identification header")
end
local vendor, comments = Setup.comment(h2.data, h2.offset, h2.size)
if not vendor then
return nil, nil, nil, nil, Err.new(Err.CORRUPT, "bad comment header")
end
local setup, serr = Setup.setup(h3.data, h3.offset, h3.size, id)
if not setup then
local code = if serr == "floor 0" then Err.UNSUPPORTED else Err.CORRUPT
return nil, nil, nil, nil, Err.new(code, serr or "bad setup header")
end
return id, setup, vendor, tagsOf(comments or {}), nil
end
-- ------------------------------------------------------------------------------------------------ sniff
function Vorbis.sniff(r: Bytes.Reader): number
if r:remaining() < 35 or r:peek(4) ~= "OggS" then
return 0
end
local b, p = r.buf, r.pos
local nseg = buffer.readu8(b, p + 26)
local d = p + 27 + nseg
if d + 7 > r.limit then
return 0
end
return if buffer.readu8(b, d) == 1 and buffer.readstring(b, d + 1, 6) == "vorbis" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Vorbis.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?)
local dec, err = Vorbis.open(r, opts)
if not dec then
return nil, err
end
local d = dec :: any
local ch = d.channels
local parts, total = {}, 0
while true do
local b, n = d:read(65536)
if n == 0 then
break
end
local copy = buffer.create(n * ch * 4)
buffer.copy(copy, 0, b, 0, n * ch * 4)
table.insert(parts, copy)
total += n
end
local a = Types.Audio.new(d.sampleRate, ch, total)
local o = 0
for _, p in parts do
buffer.copy(a.samples, o, p)
o += buffer.len(p)
end
a.tags = d.tags
a.meta.source = d.source
return a, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- encode(audioOrDecoder, opts?) -> an Ogg Vorbis file | nil, Err
function Vorbis.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local src, serr = Pcm.source(value)
if not src then
return nil, serr
end
local o: EncodeOptions = opts or {}
local q = o.quality or 3
if type(q) ~= "number" or q ~= q or q < -1 or q > 10 then
return nil, Err.new(Err.ARG, "quality must be -1 .. 10")
end
if src.channels > 255 then
return nil, Err.new(Err.ARG, "at most 255 channels")
end
if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate < 1 or src.sampleRate >= 2 ^ 32 then
return nil, Err.new(Err.ARG, "the sample rate must be a positive integer")
end
local serial = o.serial or 0x464C5541
if type(serial) ~= "number" or serial ~= math.floor(serial) or serial < 0 or serial >= 2 ^ 32 then
return nil, Err.new(Err.ARG, "serial must be a 32-bit unsigned integer")
end
local out, msg = Encode.encode(src :: any, { quality = q, vendor = "formats-luau Vorbis encoder", serial = serial })
if not out then
return nil, Err.new(Err.CORRUPT, tostring(msg))
end
return out, nil
end
-- ------------------------------------------------------------------------------------------------ open
local Stream = {}
Stream.__index = Stream
-- queue the chunk arrays[first .. first + count - 1] whose first sample has granule g0, trimmed to [lo, hi)
local function push(self: any, arrays: { { number } }, g0: number, count: number, hi: number)
local lo = math.max(g0, self.startG, self.skipTo)
if hi > g0 + count then
hi = g0 + count
end
if hi > lo then
table.insert(self.queue, { arrays, lo - g0 + 1, hi - g0, lo })
end
end
local function copyOut(self: any, count: number): { { number } }
local t = table.create(self.channels)
for c = 1, self.channels do
local src = self.st.out[c]
local a = table.create(count, 0)
table.move(src, 1, count, 1, a)
t[c] = a
end
return t
end
-- decode packets until something is queued; false at the end of the stream
local function decodeMore(self: any): boolean
local reader, st = self.reader, self.st
while not self.ended do
local p = reader:nextPacket()
if p == nil then
self.ended = true
break
end
if p.gap then
Packet.reset(st)
self.syncing, self.pend, self.pendCount = true, {}, 0
end
local count = Packet.decode(st, p.data, p.offset, p.size)
if count >= 0 then
local endG = if p.eos and p.granule >= 0 then p.granule else math.huge
if self.syncing then
if count > 0 then
table.insert(self.pend, { copyOut(self, count), count })
self.pendCount += count
end
if p.granule >= 0 then
-- the position is known again: this packet's output ends at its granule
local g = p.granule - self.pendCount
if p.eos and self.pendCount > 0 then
g = math.max(g, self.pos) -- an end-trimmed last page: keep the running position
end
for _, c in self.pend do
push(self, c[1], g, c[2], endG)
g += c[2]
end
self.pos = g
self.syncing, self.pend, self.pendCount = false, {}, 0
end
else
local g0 = self.pos
self.pos += count
if count > 0 then
push(self, st.out, g0, count, endG)
end
if p.granule >= 0 and not p.eos then
self.pos = p.granule
end
end
if p.eos then
self.ended = true
end
if #self.queue > 0 then
return true
end
end
end
return #self.queue > 0
end
function Stream.read(self: any, n: number, out: buffer?): (buffer, number)
local ch = self.channels
n = math.max(0, math.floor(n))
local b = if out and buffer.len(out) >= n * ch * 4 then out else buffer.create(n * ch * 4)
local got = 0
local writef32 = buffer.writef32
while got < n do
local q = self.queue[1]
if q == nil then
if not decodeMore(self) then
break
end
q = self.queue[1]
end
local arrays, first, last = q[1], q[2], q[3]
local take = math.min(n - got, last - first + 1)
for c = 1, ch do
local a = arrays[c]
local o = got * ch * 4 + (c - 1) * 4
for i = first, first + take - 1 do
writef32(b, o, a[i])
o += ch * 4
end
end
got += take
self.next = q[4] + take
if first + take > last then
table.remove(self.queue, 1)
else
q[2] = first + take
q[4] += take
end
end
if got > 0 then
self.skipTo = -math.huge
end
return b, got
end
function Stream.position(self: any): number
return (self.next - self.startG) / self.sampleRate
end
-- back to the first audio packet
local function restart(self: any)
local r = self.reader
r:rewind()
for _ = 1, 3 do
r:nextPacket()
end
Packet.reset(self.st)
self.pos = self.base
self.syncing, self.pend, self.pendCount = false, {}, 0
self.ended = false
self.queue = {}
end
function Stream.seek(self: any, seconds: number)
local target = self.startG + math.floor(math.max(0, seconds) * self.sampleRate + 0.5)
if target ~= target then
target = self.startG
end
if self.lastG >= 0 and target > self.lastG then
target = self.lastG
end
self.skipTo = target
self.next = target
local r = self.reader
local g = target - self.st.n1
for _ = 1, 16 do
if g <= self.startG then
break
end
local G = r:seekGranule(g)
if G == nil or G < 0 then
break
end
-- decode forward to the next page boundary to learn the exact position
Packet.reset(self.st)
self.queue = {}
self.ended = false
self.syncing, self.pend, self.pendCount = true, {}, 0
self.pos = G
local ok = false
while true do
local p = r:nextPacket()
if p == nil then
break
end
local count = Packet.decode(self.st, p.data, p.offset, p.size)
if count > 0 then
table.insert(self.pend, { copyOut(self, count), count })
self.pendCount += count
end
if p.granule >= 0 then
if not p.eos then
local g0 = p.granule - self.pendCount
for _, c in self.pend do
push(self, c[1], g0, c[2], math.huge)
g0 += c[2]
end
self.pos = p.granule
self.syncing, self.pend, self.pendCount = false, {}, 0
ok = true
end
break
end
end
if ok then
return
end
g = G - 1 -- the last page: start one page earlier
end
restart(self)
self.skipTo = target
self.next = target
end
function Vorbis.open(r: any, opts: OpenOptions?): (Types.Decoder?, Err.Err?)
local demux, derr = Ogg.open(r, if opts and opts.verify == false then { verify = false } else nil)
if not demux then
return nil, derr
end
local serial = demux:find("vorbis")
if serial == nil then
return nil, Err.new(Err.CORRUPT, "no Vorbis stream in the Ogg file")
end
local reader = demux:reader(serial)
local h1 = reader:nextPacket()
if h1 == nil then
return nil, Err.new(Err.TRUNCATED, "missing identification header")
end
local id0, ierr = Setup.ident(h1.data, h1.offset, h1.size)
if not id0 then
return nil, Err.new(Err.CORRUPT, ierr or "bad identification header")
end
local h2 = reader:nextPacket()
if h2 == nil then
return nil, Err.new(Err.TRUNCATED, "missing comment header")
end
local h2copy = { data = Ogg.copy(h2), offset = 0, size = h2.size }
local h3 = reader:nextPacket()
if h3 == nil then
return nil, Err.new(Err.TRUNCATED, "missing setup header")
end
local id, setup, vendor, tags, herr = headers(h1, h2copy, h3)
if not id then
return nil, herr
end
local st = Packet.new(id, setup)
if not st then
return nil, Err.new(Err.CORRUPT, "bad block sizes")
end
-- the granule of the first returned sample: the first granule page minus what its packets return
local base = 0
do
local prev, sum = 0, 0
while true do
local p = reader:nextPacket()
if p == nil then
break
end
local bs = Packet.blocksize(st, p.data, p.offset, p.size)
if bs > 0 then
if prev > 0 then
sum += prev // 4 + bs // 4
end
prev = bs
end
if p.granule >= 0 then
base = p.granule - sum
if p.eos then
base = 0 -- one page holds the whole stream: the spec trims its end, not its start
end
break
end
end
end
local info = demux:stream(serial)
local lastG = if info and info.lastGranule and info.lastGranule >= 0 then info.lastGranule else -1
local startG = math.max(base, 0)
local frames = if lastG >= 0 then math.max(0, lastG - startG) else 0
local rate = id.sampleRate
local self = setmetatable({
sampleRate = rate,
channels = id.channels,
frames = frames,
duration = frames / rate,
bitrate = if frames > 0 then math.floor(demux.size * 8 / (frames / rate)) else id.bitrateNominal,
tags = tags,
vendor = vendor,
ident = id,
source = {
format = "vorbis",
codec = "vorbis",
vendor = vendor,
blocksizes = { id.blocksize0, id.blocksize1 },
nominalBitrate = id.bitrateNominal,
},
demux = demux,
reader = reader,
st = st,
base = base,
startG = startG,
lastG = lastG,
pos = base,
next = startG,
skipTo = -math.huge,
queue = {},
syncing = false,
pend = {},
pendCount = 0,
ended = false,
}, Stream)
restart(self)
return self :: any, nil
end
-- ------------------------------------------------------------------------------------------------ extras
-- packetDecoder(ident, comment, setup) -> a decoder of raw Vorbis packets (Matroska / WebM / MP4 carry the three
-- headers in their codec private data) | nil, Err. Each argument is a buffer holding one header packet.
-- local pd = Vorbis.packetDecoder(h1, h2, h3)
-- local n = pd:decode(buf, offset, size) -- frames returned (first packet 0; -1 = not audio); pd.out[ch][1 .. n]
-- pd:reset() -- after a seek
function Vorbis.packetDecoder(h1: buffer, h2: buffer, h3: buffer): (any, Err.Err?)
local function pk(b: buffer): any
return { data = b, offset = 0, size = buffer.len(b) }
end
local id, setup, vendor, tags, err = headers(pk(h1), pk(h2), pk(h3))
if not id then
return nil, err
end
local st = Packet.new(id, setup)
if not st then
return nil, Err.new(Err.CORRUPT, "bad block sizes")
end
return {
sampleRate = id.sampleRate,
channels = id.channels,
vendor = vendor,
tags = tags,
out = st.out,
decode = function(_self: any, b: buffer, offset: number, size: number): number
if offset < 0 or size < 0 or offset + size > buffer.len(b) then
return -1
end
return Packet.decode(st, b, offset, size)
end,
reset = function(_self: any)
Packet.reset(st)
end,
},
nil
end
return Vorbis
+903
View File
@@ -0,0 +1,903 @@
--!strict
--!native
--!optimize 2
-- codecs/Aac/Decode: the AAC-LC raw_data_block decoder (ISO/IEC 14496-3 subpart 4): SCE / CPE / LFE / DSE / PCE /
-- FIL / END elements, ics_info with window grouping, section data, scalefactors (with noise energies and intensity
-- positions), pulse data, TNS, the eleven spectral codebooks with escapes, dequantisation, M/S and intensity stereo,
-- perceptual noise substitution (FFmpeg's LCG so the noise matches it), the filterbank (sine / KBD windows, the four
-- window sequences, IMDCT through codecs/Mdct, overlap-add). FIL extension payloads (SBR / PS) are reported to a hook
-- and otherwise skipped. Written from the standard; no third-party code. Never throws: returns nil, message.
local Mdct = require("@formats/codecs/Mdct")
local Tables = require("@formats/codecs/Aac/Tables")
local readu32, byteswap, lshift, rshift, band = buffer.readu32, bit32.byteswap, bit32.lshift, bit32.rshift, bit32.band
local floor, sqrt, abs = math.floor, math.sqrt, math.abs
local Decode = {}
local ONLY_LONG, LONG_START, EIGHT_SHORT, LONG_STOP = 0, 1, 2, 3
local ZERO_HCB, ESC_HCB, NOISE_HCB, INTENSITY_HCB2, INTENSITY_HCB = 0, 11, 13, 14, 15
-- ------------------------------------------------------------------------------------------------ bit reader
-- one packet at a time: module-level cursor over a zero-padded copy (a frame decode never yields)
local B: buffer = buffer.create(16)
local BP = 0 -- bit position
local BL = 0 -- bit limit
local OVER = false
local function getBits(n: number): number -- 1 .. 25
local p = BP
BP = p + n
if p > BL then
OVER = true
return 0
end
return rshift(lshift(byteswap(readu32(B, rshift(p, 3))), band(p, 7)), 32 - n)
end
local function peekBits(n: number): number
local p = BP
if p > BL then
return 0
end
return rshift(lshift(byteswap(readu32(B, rshift(p, 3))), band(p, 7)), 32 - n)
end
local function getLong(n: number): number
if n > 24 then
local hi = getBits(n - 16)
return hi * 65536 + getBits(16)
end
return getBits(n)
end
-- ------------------------------------------------------------------------------------------------ Huffman
local PEEK = 10
type Book = { tab: { number }, map: { [number]: number }, maxLen: number }
local function book(codes: { number }, bits: { number }): Book
local tab = table.create(2 ^ PEEK, 0)
local map = {}
local maxLen = 0
for s = 1, #codes do
local c, l = codes[s], bits[s]
maxLen = math.max(maxLen, l)
if l <= PEEK then
local shift = 2 ^ (PEEK - l)
for k = 0, shift - 1 do
tab[c * shift + k + 1] = (s - 1) * 32 + l
end
else
map[l * 2 ^ 20 + c] = s - 1
end
end
return { tab = tab, map = map, maxLen = maxLen }
end
local SF_BOOK = book(Tables.SF_CODES, Tables.SF_BITS)
local SPEC_BOOK: { Book } = {}
for i = 1, 11 do
SPEC_BOOK[i] = book(Tables.SPEC_CODES[i], Tables.SPEC_BITS[i])
end
-- the next symbol of a book, -1 for an invalid code
local function huff(bk: Book): number
local e = bk.tab[peekBits(PEEK) + 1]
if e > 0 then
BP += band(e, 31)
return rshift(e, 5)
end
-- a code longer than PEEK bits
local code = getBits(PEEK)
local map = bk.map
for l = PEEK + 1, bk.maxLen do
code = code * 2 + getBits(1)
local s = map[l * 1048576 + code]
if s then
return s
end
end
return -1
end
-- per codebook: dimension, unsigned, modulus, offset
local DIM = { 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2 }
local UNSIGNED = { false, false, true, true, false, false, true, true, true, true, true }
local MOD = { 3, 3, 3, 3, 9, 9, 8, 8, 13, 13, 17 }
local OFF = { 1, 1, 0, 0, 4, 4, 0, 0, 0, 0, 0 }
-- |q|^(4/3)
local POW43 = table.create(8192, 0)
for i = 0, 8191 do
POW43[i + 1] = i ^ (4 / 3)
end
-- ------------------------------------------------------------------------------------------------ windows
local SINE_LONG = Mdct.window("sine", 2048) :: { number }
local KBD_LONG = Mdct.window("kbd", 2048, 4) :: { number }
local SINE_SHORT = Mdct.window("sine", 256) :: { number }
local KBD_SHORT = Mdct.window("kbd", 256, 6) :: { number }
local PLAN_LONG = Mdct.new(2048) :: Mdct.Plan
local PLAN_SHORT = Mdct.new(256) :: Mdct.Plan
-- ------------------------------------------------------------------------------------------------ state
export type Channel = {
spec: { number }, -- 1024 dequantised coefficients (8 x 128 for short windows)
overlap: { number }, -- 1024 samples carried to the next frame
prevShape: number,
-- this frame's ics
windowSequence: number,
windowShape: number,
maxSfb: number,
numGroups: number,
groupLen: { number },
bandType: { number }, -- [g * maxSfb + sfb + 1]
sf: { number },
-- tns
tnsFilters: { { number } }, -- per window: { length, order, direction, coefs ... } flattened per filter
}
export type State = {
sfIndex: number,
channels: number, -- configured channels (0: as found)
frameLength: number,
ch: { Channel },
pcm: { number }, -- interleaved output floats
random: number, -- PNS generator state
time: { number }, -- 2048 IMDCT scratch
frame: { number }, -- 2048 windowed frame scratch
short: { number }, -- 256 scratch
onExtension: ((kind: number, element: number, buf: buffer, bitPos: number, bits: number) -> ())?,
extensions: number, -- extension payloads seen (SBR / PS / ...)
sbr: boolean, -- an SBR payload was seen
map: { number }?, -- element channel order -> output channel (1-based)
}
local function newChannel(): Channel
return {
spec = table.create(1024, 0),
overlap = table.create(1024, 0),
prevShape = 0,
windowSequence = 0,
windowShape = 0,
maxSfb = 0,
numGroups = 1,
groupLen = { 1, 0, 0, 0, 0, 0, 0, 0 },
bandType = table.create(8 * 64, 0),
sf = table.create(8 * 64, 0),
tnsFilters = {},
}
end
Decode.newChannel = newChannel
-- ------------------------------------------------------------------------------------------------ ics
local function icsInfo(st: State, c: Channel): string?
if getBits(1) ~= 0 then
return "reserved ics bit set"
end
c.windowSequence = getBits(2)
c.windowShape = getBits(1)
if c.windowSequence == EIGHT_SHORT then
c.maxSfb = getBits(4)
local grouping = getBits(7)
local ng = 1
local gl = c.groupLen
gl[1] = 1
for w = 1, 7 do
if band(grouping, 2 ^ (6 - (w - 1))) ~= 0 then
gl[ng] += 1
else
ng += 1
gl[ng] = 1
end
end
c.numGroups = ng
if c.maxSfb > Tables.NUM_SWB_SHORT[st.sfIndex + 1] then
return "max_sfb over the short band count"
end
else
c.maxSfb = getBits(6)
c.numGroups = 1
c.groupLen[1] = 1
if getBits(1) ~= 0 then
return "prediction (AAC Main / LTP) is not supported"
end
if c.maxSfb > Tables.NUM_SWB_LONG[st.sfIndex + 1] then
return "max_sfb over the long band count"
end
end
return nil
end
local function sectionData(c: Channel): string?
local long = c.windowSequence ~= EIGHT_SHORT
local bits = if long then 5 else 3
local esc = 2 ^ bits - 1
local maxSfb = c.maxSfb
local bt = c.bandType
for g = 0, c.numGroups - 1 do
local k = 0
while k < maxSfb do
local cb = getBits(4)
if cb == 12 then
return "reserved codebook 12"
end
local len = 0
while true do
local inc = getBits(bits)
len += inc
if inc ~= esc then
break
end
if OVER then
return "section data runs past the end"
end
end
if k + len > maxSfb then
return "section runs past max_sfb"
end
for s = k, k + len - 1 do
bt[g * maxSfb + s + 1] = cb
end
k += len
if OVER then
return "section data runs past the end"
end
end
end
return nil
end
local function scaleFactors(c: Channel, globalGain: number): string?
local sfv = globalGain
local noise = globalGain - 90
local is = 0
local firstNoise = true
local maxSfb = c.maxSfb
local bt, sf = c.bandType, c.sf
for g = 0, c.numGroups - 1 do
for s = 0, maxSfb - 1 do
local i = g * maxSfb + s + 1
local cb = bt[i]
if cb == ZERO_HCB then
sf[i] = 0
elseif cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then
local d = huff(SF_BOOK)
if d < 0 then
return "bad scalefactor code"
end
is += d - 60
sf[i] = math.clamp(is, -155, 100)
elseif cb == NOISE_HCB then
if firstNoise then
noise += getBits(9) - 256
firstNoise = false
else
local d = huff(SF_BOOK)
if d < 0 then
return "bad scalefactor code"
end
noise += d - 60
end
sf[i] = math.clamp(noise, -100, 155)
else
local d = huff(SF_BOOK)
if d < 0 then
return "bad scalefactor code"
end
sfv += d - 60
if sfv < 0 or sfv > 255 then
return "scalefactor out of range"
end
sf[i] = sfv
end
end
end
return nil
end
local function tnsData(st: State, c: Channel): string?
local short = c.windowSequence == EIGHT_SHORT
local nw = if short then 8 else 1
local filters = {}
for w = 1, nw do
local list = {}
local nFilt = getBits(if short then 1 else 2)
if nFilt > 0 then
local coefRes = getBits(1)
for _ = 1, nFilt do
local length = getBits(if short then 4 else 6)
local order = getBits(if short then 3 else 5)
local f = { length, order, 0 }
if order > (if short then 7 else 12) then
return "TNS order too high"
end
if order > 0 then
f[3] = getBits(1)
local compress = getBits(1)
local resBits = coefRes + 3
local nb = resBits - compress
local iq = ((2 ^ (resBits - 1)) - 0.5) / (math.pi / 2)
local iqm = ((2 ^ (resBits - 1)) + 0.5) / (math.pi / 2)
local tmp = table.create(order, 0)
for k = 1, order do
local v = getBits(nb)
if v >= 2 ^ (nb - 1) then
v -= 2 ^ nb
end
tmp[k] = math.sin(v / (if v >= 0 then iq else iqm))
end
-- parcor -> LPC
local a = table.create(order + 1, 0)
local b = table.create(order + 1, 0)
a[1] = 1
for m = 1, order do
for i = 1, m - 1 do
b[i + 1] = a[i + 1] + tmp[m] * a[m - i + 1]
end
for i = 1, m - 1 do
a[i + 1] = b[i + 1]
end
a[m + 1] = tmp[m]
end
for k = 1, order do
f[3 + k] = a[k + 1]
end
end
table.insert(list, f)
end
end
filters[w] = list
end
c.tnsFilters = filters
local _ = st
return nil
end
local function applyTns(st: State, c: Channel)
local short = c.windowSequence == EIGHT_SHORT
local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1]
local numSwb = if short then Tables.NUM_SWB_SHORT[st.sfIndex + 1] else Tables.NUM_SWB_LONG[st.sfIndex + 1]
local maxBands = if short then Tables.TNS_MAX_BANDS_SHORT[st.sfIndex + 1] else Tables.TNS_MAX_BANDS_LONG[st.sfIndex + 1]
local mmm = math.min(maxBands, c.maxSfb)
if mmm == 0 then
return
end
local spec = c.spec
for w, list in c.tnsFilters do
local bottom = numSwb
for _, f in list do
local top = bottom
bottom = math.max(0, top - f[1])
local order = f[2]
if order > 0 then
local start = swb[math.min(bottom, mmm) + 1]
local stop = swb[math.min(top, mmm) + 1]
local size = stop - start
if size > 0 then
local inc = 1
local p = (w - 1) * 128 + start + 1
if f[3] == 1 then
inc = -1
p = (w - 1) * 128 + stop
end
for m = 0, size - 1 do
local y = spec[p]
local lim = if m < order then m else order
for i = 1, lim do
y -= spec[p - i * inc] * f[3 + i]
end
spec[p] = y
p += inc
end
end
end
end
end
end
-- the spectral data of one channel, dequantised into c.spec (also pulses, noise, intensity zeros)
local function spectralData(st: State, c: Channel, pulses: { number }?): string?
local short = c.windowSequence == EIGHT_SHORT
local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1]
local spec = c.spec
for i = 1, 1024 do
spec[i] = 0
end
local maxSfb = c.maxSfb
local bt, sf = c.bandType, c.sf
local win = 0
for g = 0, c.numGroups - 1 do
local glen = c.groupLen[g + 1]
for s = 0, maxSfb - 1 do
local idx = g * maxSfb + s + 1
local cb = bt[idx]
local lo, hi = swb[s + 1], swb[s + 2]
local width = hi - lo
if cb == ZERO_HCB or cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then
-- zeros (intensity bands are filled from the other channel later)
continue
elseif cb == NOISE_HCB then
local scale = 2 ^ (0.25 * sf[idx])
for w = 0, glen - 1 do
local base = (win + w) * 128 + lo
local energy = 0
local r = st.random
for k = 1, width do
r = (r * 1664525 + 1013904223) % 4294967296
local v = if r >= 2147483648 then r - 4294967296 else r
spec[base + k] = v
energy += v * v
end
st.random = r
local m = if energy > 0 then scale / sqrt(energy) else 0
for k = 1, width do
spec[base + k] *= m
end
end
continue
end
local bk = SPEC_BOOK[cb]
local dim, uns, mod, off = DIM[cb], UNSIGNED[cb], MOD[cb], OFF[cb]
local gain = 2 ^ (0.25 * (sf[idx] - 100))
for w = 0, glen - 1 do
local base = (win + w) * 128 + lo
local k = 0
while k < width do
local sym = huff(bk)
if sym < 0 then
return "bad spectral code"
end
-- unpack the symbol into dim values (first value most significant)
local vals1, vals2, vals3, vals4
if dim == 4 then
vals4 = sym % mod - off
sym = (sym - (sym % mod)) / mod
vals3 = sym % mod - off
sym = (sym - (sym % mod)) / mod
vals2 = sym % mod - off
sym = (sym - (sym % mod)) / mod
vals1 = sym % mod - off
else
vals2 = sym % mod - off
vals1 = (sym - (sym % mod)) / mod - off
end
if uns then
if vals1 ~= 0 and getBits(1) == 1 then
vals1 = -vals1
end
if vals2 ~= 0 and getBits(1) == 1 then
vals2 = -vals2
end
if dim == 4 then
if vals3 ~= 0 and getBits(1) == 1 then
vals3 = -vals3
end
if vals4 ~= 0 and getBits(1) == 1 then
vals4 = -vals4
end
end
if cb == ESC_HCB then
for e = 1, 2 do
local v = if e == 1 then vals1 else vals2
if v == 16 or v == -16 then
local n = 0
while getBits(1) == 1 do
n += 1
if n > 8 or OVER then
return "bad escape"
end
end
local esc = 2 ^ (n + 4) + getBits(n + 4)
if v < 0 then
esc = -esc
end
if e == 1 then
vals1 = esc
else
vals2 = esc
end
end
end
end
end
local p = base + k + 1
spec[p] = vals1
spec[p + 1] = vals2
if dim == 4 then
spec[p + 2] = vals3
spec[p + 3] = vals4
end
k += dim
end
if OVER then
return "spectral data runs past the end"
end
end
-- dequantise (pulses are added to the quantised values first: long windows only, applied below)
if not pulses then
for w = 0, glen - 1 do
local base = (win + w) * 128 + lo
for k = 1, width do
local q = spec[base + k]
if q ~= 0 then
local aq = if q < 0 then -q else q
local v = (POW43[aq + 1] or aq ^ (4 / 3)) * gain
spec[base + k] = if q < 0 then -v else v
end
end
end
end
end
win += glen
end
if pulses then
-- long window: add the pulses to the quantised values, then dequantise every band
for i = 1, #pulses, 2 do
local pos = pulses[i] + 1
if pos <= 1024 then
local q = spec[pos]
spec[pos] = if q > 0 then q + pulses[i + 1] else q - pulses[i + 1]
end
end
for s = 0, maxSfb - 1 do
local idx = s + 1
local cb = bt[idx]
if cb ~= ZERO_HCB and cb < NOISE_HCB then
local gain = 2 ^ (0.25 * (sf[idx] - 100))
for k = swb[s + 1] + 1, swb[s + 2] do
local q = spec[k]
if q ~= 0 then
local aq = if q < 0 then -q else q
local v = (POW43[aq + 1] or aq ^ (4 / 3)) * gain
spec[k] = if q < 0 then -v else v
end
end
end
end
end
return nil
end
-- individual_channel_stream
local function ics(st: State, c: Channel, commonWindow: boolean): string?
local globalGain = getBits(8)
if not commonWindow then
local e = icsInfo(st, c)
if e then
return e
end
end
local e = sectionData(c)
if e then
return e
end
e = scaleFactors(c, globalGain)
if e then
return e
end
local pulses: { number }? = nil
if getBits(1) == 1 then
if c.windowSequence == EIGHT_SHORT then
return "pulse data in a short window"
end
local n = getBits(2) + 1
local startSfb = getBits(6)
if startSfb >= Tables.NUM_SWB_LONG[st.sfIndex + 1] then
return "bad pulse start band"
end
local pos = Tables.SWB_LONG[st.sfIndex + 1][startSfb + 1]
local list = {}
for _ = 1, n do
pos += getBits(5)
table.insert(list, pos)
table.insert(list, getBits(4))
end
pulses = list
end
c.tnsFilters = {}
if getBits(1) == 1 then
e = tnsData(st, c)
if e then
return e
end
end
if getBits(1) == 1 then
return "gain control (AAC SSR) is not supported"
end
if OVER then
return "channel stream runs past the end"
end
return spectralData(st, c, pulses)
end
-- ------------------------------------------------------------------------------------------------ stereo
local function msStereo(st: State, l: Channel, r: Channel, mask: { number })
local short = l.windowSequence == EIGHT_SHORT
local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1]
local maxSfb = l.maxSfb
local a, b = l.spec, r.spec
local win = 0
for g = 0, l.numGroups - 1 do
local glen = l.groupLen[g + 1]
for s = 0, maxSfb - 1 do
local idx = g * maxSfb + s + 1
if mask[idx] == 1 and l.bandType[idx] < NOISE_HCB and r.bandType[idx] < NOISE_HCB then
for w = 0, glen - 1 do
local base = (win + w) * 128
for k = base + swb[s + 1] + 1, base + swb[s + 2] do
local m, sd = a[k], b[k]
a[k], b[k] = m + sd, m - sd
end
end
end
end
win += glen
end
end
local function intensity(st: State, l: Channel, r: Channel, mask: { number }, msPresent: number)
local short = r.windowSequence == EIGHT_SHORT
local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1]
local maxSfb = r.maxSfb
local a, b = l.spec, r.spec
local win = 0
for g = 0, r.numGroups - 1 do
local glen = r.groupLen[g + 1]
for s = 0, maxSfb - 1 do
local idx = g * maxSfb + s + 1
local cb = r.bandType[idx]
if cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then
local sign = if cb == INTENSITY_HCB then 1 else -1
if msPresent ~= 0 and mask[idx] == 1 then
sign = -sign
end
local scale = sign * 0.5 ^ (0.25 * r.sf[idx])
for w = 0, glen - 1 do
local base = (win + w) * 128
for k = base + swb[s + 1] + 1, base + swb[s + 2] do
b[k] = a[k] * scale
end
end
end
end
win += glen
end
end
-- ------------------------------------------------------------------------------------------------ filterbank
local function filterbank(st: State, c: Channel, out: { number }, stride: number, offset: number)
local seq, shape, prev = c.windowSequence, c.windowShape, c.prevShape
local spec, overlap = c.spec, c.overlap
local frame = st.frame
local scale = 1 / 32768
if seq == EIGHT_SHORT then
for i = 1, 2048 do
frame[i] = 0
end
local tmp = st.short
local rise0 = if prev == 1 then KBD_SHORT else SINE_SHORT
local wcur = if shape == 1 then KBD_SHORT else SINE_SHORT
for w = 0, 7 do
Mdct.inverse(PLAN_SHORT, spec, w * 128 + 1, 1, tmp, 1, 2 / 256)
local rise = if w == 0 then rise0 else wcur
local base = 448 + w * 128
for n = 1, 128 do
frame[base + n] += tmp[n] * rise[n]
frame[base + 128 + n] += tmp[128 + n] * wcur[128 + n]
end
end
else
local t = st.time
Mdct.inverse(PLAN_LONG, spec, 1, 1, t, 1, 2 / 2048)
-- left half
if seq == LONG_STOP then
local rise = if prev == 1 then KBD_SHORT else SINE_SHORT
for n = 1, 448 do
frame[n] = 0
end
for n = 1, 128 do
frame[448 + n] = t[448 + n] * rise[n]
end
for n = 577, 1024 do
frame[n] = t[n]
end
else
local rise = if prev == 1 then KBD_LONG else SINE_LONG
for n = 1, 1024 do
frame[n] = t[n] * rise[n]
end
end
-- right half
if seq == LONG_START then
local fall = if shape == 1 then KBD_SHORT else SINE_SHORT
for n = 1025, 1472 do
frame[n] = t[n]
end
for n = 1, 128 do
frame[1472 + n] = t[1472 + n] * fall[128 + n]
end
for n = 1601, 2048 do
frame[n] = 0
end
else
local fall = if shape == 1 then KBD_LONG else SINE_LONG
for n = 1025, 2048 do
frame[n] = t[n] * fall[n]
end
end
end
local p = offset
for n = 1, 1024 do
out[p] = (frame[n] + overlap[n]) * scale
overlap[n] = frame[1024 + n]
p += stride
end
c.prevShape = shape
end
-- ------------------------------------------------------------------------------------------------ frame
-- frame(st, buf, off, len) -> channels decoded | nil, message. Output: st.pcm, 1024 frames interleaved.
function Decode.frame(st: State, buf: buffer, off: number, len: number): (number?, string?)
if buffer.len(B) < len + 16 then
B = buffer.create(len + 256)
end
buffer.copy(B, 0, buf, off, len)
buffer.fill(B, len, 0, 16)
BP, BL, OVER = 0, len * 8, false
local chans = st.ch
local nextCh = 1
local order: { Channel } = {}
local lastElement = -1
while true do
if BP + 3 > BL then
break -- tolerate a missing END
end
local id = getBits(3)
if id == 7 then
break
end
if id == 0 or id == 3 then -- SCE / LFE
getBits(4)
local c = chans[nextCh]
if not c then
c = newChannel()
chans[nextCh] = c
end
local e = ics(st, c, false)
if e then
return nil, e
end
applyTns(st, c)
table.insert(order, c)
nextCh += 1
lastElement = id
elseif id == 1 then -- CPE
getBits(4)
local l, r = chans[nextCh], chans[nextCh + 1]
if not l then
l = newChannel()
chans[nextCh] = l
end
if not r then
r = newChannel()
chans[nextCh + 1] = r
end
local common = getBits(1) == 1
local msPresent = 0
local mask = table.create(8 * 64, 0)
if common then
local e = icsInfo(st, l)
if e then
return nil, e
end
r.windowSequence, r.windowShape, r.maxSfb, r.numGroups = l.windowSequence, l.windowShape, l.maxSfb, l.numGroups
for i = 1, 8 do
r.groupLen[i] = l.groupLen[i]
end
msPresent = getBits(2)
if msPresent == 1 then
for i = 1, l.numGroups * l.maxSfb do
mask[i] = getBits(1)
end
elseif msPresent == 2 then
for i = 1, l.numGroups * l.maxSfb do
mask[i] = 1
end
elseif msPresent == 3 then
return nil, "reserved ms_mask_present"
end
end
local e = ics(st, l, common)
if e then
return nil, e
end
e = ics(st, r, common)
if e then
return nil, e
end
if common and msPresent ~= 0 then
msStereo(st, l, r, mask)
end
if common then
intensity(st, l, r, mask, msPresent)
end
applyTns(st, l)
applyTns(st, r)
table.insert(order, l)
table.insert(order, r)
nextCh += 2
lastElement = id
elseif id == 2 then
return nil, "coupling channel elements are not supported"
elseif id == 4 then -- DSE
getBits(4)
local align = getBits(1)
local count = getBits(8)
if count == 255 then
count += getBits(8)
end
if align == 1 then
BP = (BP + 7) // 8 * 8
end
BP += count * 8
elseif id == 5 then -- PCE: skipped here (parsed from the configuration)
return nil, "program config element inside the stream is not supported"
elseif id == 6 then -- FIL
local count = getBits(4)
if count == 15 then
count += getBits(8) - 1
end
if count > 0 then
local start = BP
local kind = getBits(4)
if kind == 13 or kind == 14 then -- EXT_SBR_DATA / EXT_SBR_DATA_CRC
st.sbr = true
end
st.extensions += 1
local hook = st.onExtension
if hook then
hook(kind, lastElement, B, start, count * 8)
end
BP = start + count * 8
end
end
if OVER or BP > BL then
return nil, "frame runs past the end"
end
if nextCh > 9 then
return nil, "more than 8 channels"
end
end
local n = #order
if n == 0 then
return 0, nil
end
local pcm = st.pcm
local map = st.map
for i, c in order do
local o = if map and map[i] then map[i] else i
filterbank(st, c, pcm, n, o)
end
return n, nil
end
function Decode.state(sfIndex: number): State
return {
sfIndex = sfIndex,
channels = 0,
frameLength = 1024,
ch = {},
pcm = table.create(1024 * 8, 0),
random = 0x1f2e3d4c,
time = table.create(2048, 0),
frame = table.create(2048, 0),
short = table.create(256, 0),
onExtension = nil,
extensions = 0,
sbr = false,
map = nil,
}
end
local _ = abs
local _2 = floor
return Decode
+335
View File
@@ -0,0 +1,335 @@
--!strict
-- codecs/Aac/Tables: the AAC-LC tables of ISO/IEC 14496-3 (subpart 4, Annex 4.A): the scalefactor and the eleven
-- spectral Huffman codebooks (code, length per symbol), the scalefactor band offsets per sampling rate (1024 and 128
-- lines) and the TNS band limits. Transcribed from FFmpeg libavcodec/aactab.c (tables of the standard, no code;
-- see licenses/NOTICE.md). Generated; do not edit.
local Tables = {}
Tables.SF_CODES = {
262120, 262118, 262119, 262117, 524277, 524273, 524269, 524278, 524270, 524271, 524272, 524284, 524285, 524287, 524286, 524279,
524280, 524283, 524281, 262116, 524282, 262115, 131055, 131056, 65525, 131054, 65522, 65523, 65524, 65521, 32758, 32759,
16377, 16373, 16375, 16371, 16374, 16370, 8183, 8181, 4089, 4087, 4086, 2041, 4084, 2040, 1017, 1015,
1013, 504, 503, 250, 248, 246, 121, 58, 56, 26, 11, 4, 0, 10, 12, 27,
57, 59, 120, 122, 247, 249, 502, 505, 1012, 1014, 1016, 2037, 2036, 2038, 2039, 4085,
4088, 8180, 8182, 8184, 16376, 16372, 65520, 32756, 65526, 32757, 262114, 524249, 524250, 524251, 524252, 524253,
524254, 524248, 524242, 524243, 524244, 524245, 524246, 524274, 524255, 524263, 524264, 524265, 524266, 524267, 524262, 524256,
524257, 524258, 524259, 524260, 524261, 524247, 524268, 524276, 524275,
}
Tables.SF_BITS = {
18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 18, 19, 18, 17, 17, 16, 17, 16, 16, 16, 16,
15, 15, 14, 14, 14, 14, 14, 14, 13, 13, 12, 12, 12, 11, 12, 11, 10, 10, 10, 9, 9, 8, 8, 8, 7, 6, 6, 5, 4, 3,
1, 4, 4, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 10, 11, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 16, 15, 16, 15,
18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
19,
}
Tables.SPEC_CODES = {
{
2040, 497, 2045, 1013, 104, 1008, 2039, 492, 2037, 1009, 114, 1012, 116, 17, 118, 491,
108, 1014, 2044, 481, 2033, 496, 97, 502, 2034, 490, 2043, 498, 105, 493, 119, 23,
111, 486, 100, 485, 103, 21, 98, 18, 0, 20, 101, 22, 109, 489, 99, 484,
107, 19, 113, 483, 112, 499, 2046, 487, 2035, 495, 96, 494, 2032, 482, 2042, 1011,
106, 488, 117, 16, 115, 500, 110, 1015, 2038, 480, 2041, 1010, 102, 501, 2047, 503,
2036,
},
{
499, 111, 509, 235, 35, 234, 503, 232, 506, 242, 45, 112, 32, 6, 43, 110,
40, 233, 505, 102, 248, 231, 27, 241, 500, 107, 501, 236, 42, 108, 44, 10,
39, 103, 26, 245, 36, 8, 31, 9, 0, 7, 29, 11, 48, 239, 28, 100,
30, 12, 41, 243, 47, 240, 508, 113, 498, 244, 33, 230, 247, 104, 504, 238,
34, 101, 49, 2, 38, 237, 37, 106, 507, 114, 510, 105, 46, 246, 511, 109,
502,
},
{
0, 9, 239, 11, 25, 240, 491, 486, 1010, 10, 53, 495, 52, 55, 489, 493,
487, 1011, 494, 1005, 8186, 492, 498, 2041, 2040, 1016, 4088, 8, 56, 1014, 54, 117,
1009, 1003, 1004, 4084, 24, 118, 2036, 57, 116, 1007, 499, 500, 2038, 488, 1002, 8188,
242, 497, 4091, 1013, 2035, 4092, 238, 1015, 32766, 496, 2037, 32765, 8187, 16378, 65535, 241,
1008, 16380, 490, 1006, 16379, 4086, 4090, 32764, 2034, 4085, 65534, 1012, 2039, 32763, 4087, 4089,
32762,
},
{
7, 22, 246, 24, 8, 239, 495, 243, 2040, 25, 23, 237, 21, 1, 226, 240,
112, 1008, 494, 241, 2042, 238, 228, 1010, 2038, 1007, 2045, 5, 20, 242, 9, 4,
229, 244, 232, 1012, 6, 2, 231, 3, 0, 107, 227, 105, 499, 235, 230, 1014,
110, 106, 500, 1004, 496, 1017, 245, 236, 2043, 234, 111, 1015, 2041, 1011, 4095, 233,
109, 1016, 108, 104, 501, 1006, 498, 2036, 2039, 1009, 4094, 1005, 497, 2037, 2046, 1013,
2044,
},
{
8191, 4087, 2036, 2024, 1009, 2030, 2041, 4088, 8189, 4093, 2033, 1000, 488, 240, 492, 1006,
2034, 4090, 4084, 1007, 498, 232, 112, 236, 496, 1002, 2035, 2027, 491, 234, 26, 8,
25, 238, 495, 2029, 1008, 242, 115, 11, 0, 10, 113, 243, 2025, 2031, 494, 239,
24, 9, 27, 235, 489, 2028, 2038, 1003, 499, 237, 114, 233, 497, 1005, 2039, 4086,
2032, 1001, 493, 241, 490, 1004, 2040, 4089, 8188, 4092, 4085, 2026, 1011, 1010, 2037, 4091,
8190,
},
{
2046, 1021, 497, 491, 500, 490, 496, 1020, 2045, 1014, 485, 234, 108, 113, 104, 240,
486, 1015, 499, 239, 50, 39, 40, 38, 49, 235, 503, 488, 111, 46, 8, 4,
6, 41, 107, 494, 495, 114, 45, 2, 0, 3, 47, 115, 506, 487, 110, 43,
7, 1, 5, 44, 109, 492, 505, 238, 48, 36, 42, 37, 51, 236, 498, 1016,
484, 237, 106, 112, 105, 116, 241, 1018, 2047, 1017, 502, 493, 504, 489, 501, 1019,
2044,
},
{
0, 5, 55, 116, 242, 491, 1005, 2039, 4, 12, 53, 113, 236, 238, 494, 501,
54, 52, 114, 234, 241, 489, 499, 1013, 115, 112, 235, 240, 497, 496, 1004, 1018,
243, 237, 488, 495, 1007, 1009, 1017, 2043, 493, 239, 490, 498, 1011, 1016, 2041, 2044,
1006, 492, 500, 1012, 1015, 2040, 4093, 4094, 2038, 1008, 1010, 1014, 2042, 2045, 4092, 4095,
},
{
14, 5, 16, 48, 111, 241, 506, 1022, 3, 0, 4, 18, 44, 106, 117, 248,
15, 2, 6, 20, 46, 105, 114, 245, 47, 17, 19, 42, 50, 108, 236, 250,
113, 43, 45, 49, 109, 112, 242, 505, 239, 104, 51, 107, 110, 238, 249, 1020,
504, 116, 115, 237, 240, 246, 502, 509, 1021, 243, 244, 247, 503, 507, 508, 1023,
},
{
0, 5, 55, 231, 478, 974, 985, 1992, 1997, 4040, 4061, 8164, 8172, 4, 12, 53,
114, 234, 237, 482, 977, 979, 992, 2008, 4047, 4053, 54, 52, 113, 232, 236, 481,
975, 989, 987, 2000, 4039, 4052, 4068, 230, 112, 233, 477, 483, 978, 988, 1996, 1994,
2014, 4056, 4074, 8155, 479, 235, 476, 486, 981, 990, 1995, 2013, 2012, 4045, 4066, 4071,
8161, 976, 480, 484, 982, 1989, 2001, 2011, 4050, 2016, 4057, 4075, 8163, 8169, 1988, 485,
983, 1990, 1999, 2010, 4043, 4058, 4067, 4073, 8166, 8179, 8183, 2003, 984, 993, 2004, 2009,
4051, 4062, 8157, 8153, 8162, 8170, 8177, 8182, 2002, 980, 986, 1991, 2007, 2018, 4046, 4059,
8152, 8174, 16368, 8180, 16370, 2017, 991, 1993, 2006, 4042, 4048, 4069, 4070, 8171, 8175, 16371,
16372, 16373, 4064, 1998, 2005, 4038, 4049, 4065, 8160, 8168, 8176, 16369, 16376, 16374, 32764, 4072,
2015, 4041, 4055, 4060, 8156, 8159, 8173, 8181, 16377, 16379, 32765, 32766, 8167, 4044, 4054, 4063,
8158, 8154, 8165, 8178, 16378, 16375, 16380, 16381, 32767,
},
{
34, 8, 29, 38, 95, 211, 463, 976, 983, 1005, 2032, 2038, 4093, 7, 0, 1,
9, 32, 84, 96, 213, 220, 468, 973, 990, 2023, 28, 2, 6, 12, 30, 40,
91, 205, 217, 462, 476, 985, 1009, 37, 11, 10, 13, 36, 87, 97, 204, 221,
460, 478, 979, 999, 93, 33, 31, 35, 39, 89, 100, 216, 223, 466, 482, 989,
1006, 209, 85, 41, 86, 88, 98, 206, 224, 226, 474, 980, 995, 2027, 457, 94,
90, 92, 99, 202, 218, 455, 458, 480, 987, 1000, 2028, 483, 210, 203, 208, 215,
219, 454, 469, 472, 970, 986, 2026, 2033, 481, 212, 207, 214, 222, 225, 464, 470,
977, 981, 1010, 2030, 2043, 1001, 461, 456, 459, 465, 471, 479, 975, 992, 1007, 2022,
2040, 4090, 1003, 477, 467, 473, 475, 978, 972, 988, 1002, 2029, 2035, 2041, 4089, 2034,
974, 484, 971, 984, 982, 994, 997, 2024, 2036, 2037, 2039, 4091, 2042, 1004, 991, 993,
996, 998, 1008, 2025, 2031, 4088, 4094, 4092, 4095,
},
{
0, 6, 25, 61, 156, 198, 423, 912, 962, 991, 2022, 2035, 4091, 2028, 4090, 4094,
910, 5, 1, 8, 20, 55, 66, 146, 175, 401, 421, 437, 926, 960, 930, 973,
2006, 174, 23, 7, 9, 24, 57, 64, 142, 163, 184, 409, 428, 449, 945, 918,
958, 970, 157, 60, 21, 22, 26, 59, 68, 145, 165, 190, 406, 430, 441, 929,
913, 933, 981, 148, 154, 54, 56, 58, 65, 140, 155, 176, 195, 414, 427, 444,
927, 911, 937, 975, 147, 191, 62, 63, 67, 69, 158, 167, 185, 404, 418, 442,
451, 934, 935, 955, 980, 159, 416, 143, 141, 144, 152, 166, 182, 196, 415, 431,
447, 921, 959, 948, 969, 999, 168, 438, 171, 164, 170, 178, 194, 197, 408, 420,
440, 908, 932, 964, 966, 989, 1000, 173, 943, 402, 189, 188, 398, 407, 410, 419,
433, 909, 920, 951, 979, 977, 987, 2013, 180, 990, 425, 411, 412, 417, 426, 429,
435, 907, 946, 952, 974, 993, 992, 2002, 2021, 183, 2019, 443, 424, 422, 432, 434,
439, 923, 922, 954, 949, 982, 2007, 996, 2008, 2026, 186, 2024, 928, 445, 436, 906,
452, 914, 938, 944, 956, 983, 2004, 2012, 2011, 2005, 2032, 193, 2043, 968, 931, 917,
925, 940, 942, 965, 984, 994, 998, 2020, 2023, 2016, 2025, 2039, 400, 2034, 915, 446,
448, 916, 919, 941, 963, 961, 978, 2010, 2009, 2015, 2027, 2036, 2042, 405, 2040, 957,
924, 939, 936, 947, 953, 976, 995, 997, 2018, 2014, 2029, 2033, 2041, 2044, 403, 4093,
988, 950, 967, 972, 971, 985, 986, 2003, 2017, 2030, 2031, 2037, 2038, 4092, 4095, 413,
450, 181, 161, 150, 151, 149, 153, 160, 162, 172, 169, 177, 179, 187, 192, 399,
4,
},
}
Tables.SPEC_BITS = {
{
11, 9, 11, 10, 7, 10, 11, 9, 11, 10, 7, 10, 7, 5, 7, 9, 7, 10, 11, 9, 11, 9, 7, 9, 11, 9, 11, 9, 7, 9,
7, 5, 7, 9, 7, 9, 7, 5, 7, 5, 1, 5, 7, 5, 7, 9, 7, 9, 7, 5, 7, 9, 7, 9, 11, 9, 11, 9, 7, 9,
11, 9, 11, 10, 7, 9, 7, 5, 7, 9, 7, 10, 11, 9, 11, 10, 7, 9, 11, 9, 11,
},
{
9, 7, 9, 8, 6, 8, 9, 8, 9, 8, 6, 7, 6, 5, 6, 7, 6, 8, 9, 7, 8, 8, 6, 8, 9, 7, 9, 8, 6, 7,
6, 5, 6, 7, 6, 8, 6, 5, 6, 5, 3, 5, 6, 5, 6, 8, 6, 7, 6, 5, 6, 8, 6, 8, 9, 7, 9, 8, 6, 8,
8, 7, 9, 8, 6, 7, 6, 4, 6, 8, 6, 7, 9, 7, 9, 7, 6, 8, 9, 7, 9,
},
{
1, 4, 8, 4, 5, 8, 9, 9, 10, 4, 6, 9, 6, 6, 9, 9, 9, 10, 9, 10, 13, 9, 9, 11, 11, 10, 12, 4, 6, 10,
6, 7, 10, 10, 10, 12, 5, 7, 11, 6, 7, 10, 9, 9, 11, 9, 10, 13, 8, 9, 12, 10, 11, 12, 8, 10, 15, 9, 11, 15,
13, 14, 16, 8, 10, 14, 9, 10, 14, 12, 12, 15, 11, 12, 16, 10, 11, 15, 12, 12, 15,
},
{
4, 5, 8, 5, 4, 8, 9, 8, 11, 5, 5, 8, 5, 4, 8, 8, 7, 10, 9, 8, 11, 8, 8, 10, 11, 10, 11, 4, 5, 8,
4, 4, 8, 8, 8, 10, 4, 4, 8, 4, 4, 7, 8, 7, 9, 8, 8, 10, 7, 7, 9, 10, 9, 10, 8, 8, 11, 8, 7, 10,
11, 10, 12, 8, 7, 10, 7, 7, 9, 10, 9, 11, 11, 10, 12, 10, 9, 11, 11, 10, 11,
},
{
13, 12, 11, 11, 10, 11, 11, 12, 13, 12, 11, 10, 9, 8, 9, 10, 11, 12, 12, 10, 9, 8, 7, 8, 9, 10, 11, 11, 9, 8,
5, 4, 5, 8, 9, 11, 10, 8, 7, 4, 1, 4, 7, 8, 11, 11, 9, 8, 5, 4, 5, 8, 9, 11, 11, 10, 9, 8, 7, 8,
9, 10, 11, 12, 11, 10, 9, 8, 9, 10, 11, 12, 13, 12, 12, 11, 10, 10, 11, 12, 13,
},
{
11, 10, 9, 9, 9, 9, 9, 10, 11, 10, 9, 8, 7, 7, 7, 8, 9, 10, 9, 8, 6, 6, 6, 6, 6, 8, 9, 9, 7, 6,
4, 4, 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 8, 6, 6, 6, 6,
6, 8, 9, 10, 9, 8, 7, 7, 7, 7, 8, 10, 11, 10, 9, 9, 9, 9, 9, 10, 11,
},
{
1, 3, 6, 7, 8, 9, 10, 11, 3, 4, 6, 7, 8, 8, 9, 9, 6, 6, 7, 8, 8, 9, 9, 10, 7, 7, 8, 8, 9, 9,
10, 10, 8, 8, 9, 9, 10, 10, 10, 11, 9, 8, 9, 9, 10, 10, 11, 11, 10, 9, 9, 10, 10, 11, 12, 12, 11, 10, 10, 10,
11, 11, 12, 12,
},
{
5, 4, 5, 6, 7, 8, 9, 10, 4, 3, 4, 5, 6, 7, 7, 8, 5, 4, 4, 5, 6, 7, 7, 8, 6, 5, 5, 6, 6, 7,
8, 8, 7, 6, 6, 6, 7, 7, 8, 9, 8, 7, 6, 7, 7, 8, 8, 10, 9, 7, 7, 8, 8, 8, 9, 9, 10, 8, 8, 8,
9, 9, 9, 10,
},
{
1, 3, 6, 8, 9, 10, 10, 11, 11, 12, 12, 13, 13, 3, 4, 6, 7, 8, 8, 9, 10, 10, 10, 11, 12, 12, 6, 6, 7, 8,
8, 9, 10, 10, 10, 11, 12, 12, 12, 8, 7, 8, 9, 9, 10, 10, 11, 11, 11, 12, 12, 13, 9, 8, 9, 9, 10, 10, 11, 11,
11, 12, 12, 12, 13, 10, 9, 9, 10, 11, 11, 11, 12, 11, 12, 12, 13, 13, 11, 9, 10, 11, 11, 11, 12, 12, 12, 12, 13, 13,
13, 11, 10, 10, 11, 11, 12, 12, 13, 13, 13, 13, 13, 13, 11, 10, 10, 11, 11, 11, 12, 12, 13, 13, 14, 13, 14, 11, 10, 11,
11, 12, 12, 12, 12, 13, 13, 14, 14, 14, 12, 11, 11, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 12, 11, 12, 12, 12, 13, 13,
13, 13, 14, 14, 15, 15, 13, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15,
},
{
6, 5, 6, 6, 7, 8, 9, 10, 10, 10, 11, 11, 12, 5, 4, 4, 5, 6, 7, 7, 8, 8, 9, 10, 10, 11, 6, 4, 5, 5,
6, 6, 7, 8, 8, 9, 9, 10, 10, 6, 5, 5, 5, 6, 7, 7, 8, 8, 9, 9, 10, 10, 7, 6, 6, 6, 6, 7, 7, 8,
8, 9, 9, 10, 10, 8, 7, 6, 7, 7, 7, 8, 8, 8, 9, 10, 10, 11, 9, 7, 7, 7, 7, 8, 8, 9, 9, 9, 10, 10,
11, 9, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 9, 8, 8, 8, 8, 8, 9, 9, 10, 10, 10, 11, 11, 10, 9, 9,
9, 9, 9, 9, 10, 10, 10, 11, 11, 12, 10, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 12, 11, 10, 9, 10, 10, 10, 10,
10, 11, 11, 11, 11, 12, 11, 10, 10, 10, 10, 10, 10, 11, 11, 12, 12, 12, 12,
},
{
4, 5, 6, 7, 8, 8, 9, 10, 10, 10, 11, 11, 12, 11, 12, 12, 10, 5, 4, 5, 6, 7, 7, 8, 8, 9, 9, 9, 10, 10,
10, 10, 11, 8, 6, 5, 5, 6, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 7, 6, 6, 6, 7, 7, 8, 8, 8,
9, 9, 9, 10, 10, 10, 10, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 8, 7, 7, 7, 7,
8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 8, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 10, 8, 9,
8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 10, 10, 8, 10, 9, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10,
10, 11, 8, 10, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 8, 11, 9, 9, 9, 9, 9, 9, 10, 10, 10,
10, 10, 11, 10, 11, 11, 8, 11, 10, 9, 9, 10, 9, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 8, 11, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 9, 11, 10, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 11, 10,
10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 12, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 12,
12, 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 5,
},
}
Tables.SWB_LONG = {
{
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96,
108, 120, 132, 144, 156, 172, 188, 212, 240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896,
960, 1024,
},
{
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96,
108, 120, 132, 144, 156, 172, 188, 212, 240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896,
960, 1024,
},
{
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 100,
112, 124, 140, 156, 172, 192, 216, 240, 268, 304, 344, 384, 424, 464, 504, 544, 584, 624, 664, 704,
744, 784, 824, 864, 904, 944, 984, 1024,
},
{
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120,
132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640,
672, 704, 736, 768, 800, 832, 864, 896, 928, 1024,
},
{
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120,
132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640,
672, 704, 736, 768, 800, 832, 864, 896, 928, 1024,
},
{
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120,
132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640,
672, 704, 736, 768, 800, 832, 864, 896, 928, 960, 992, 1024,
},
{
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, 84, 92, 100, 108,
116, 124, 136, 148, 160, 172, 188, 204, 220, 240, 260, 284, 308, 336, 364, 396, 432, 468, 508, 552,
600, 652, 704, 768, 832, 896, 960, 1024,
},
{
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, 84, 92, 100, 108,
116, 124, 136, 148, 160, 172, 188, 204, 220, 240, 260, 284, 308, 336, 364, 396, 432, 468, 508, 552,
600, 652, 704, 768, 832, 896, 960, 1024,
},
{
0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184,
196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772,
832, 896, 960, 1024,
},
{
0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184,
196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772,
832, 896, 960, 1024,
},
{
0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184,
196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772,
832, 896, 960, 1024,
},
{
0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188, 204, 220, 236, 252,
268, 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544, 580, 620, 664, 712, 764, 820, 880, 944,
1024,
},
{
0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188, 204, 220, 236, 252,
268, 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544, 580, 620, 664, 712, 764, 820, 880, 944,
1024,
},
}
Tables.SWB_SHORT = {
{
0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128,
},
{
0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128,
},
{
0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128,
},
{
0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128,
},
{
0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128,
},
{
0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128,
},
{
0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128,
},
{
0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128,
},
{
0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128,
},
{
0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128,
},
{
0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128,
},
{
0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 60, 72, 88, 108, 128,
},
{
0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 60, 72, 88, 108, 128,
},
}
Tables.NUM_SWB_LONG = {
41, 41, 47, 49, 49, 51, 47, 47, 43, 43, 43, 40, 40,
}
Tables.NUM_SWB_SHORT = {
12, 12, 12, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15,
}
Tables.TNS_MAX_BANDS_LONG = {
31, 31, 34, 40, 42, 51, 46, 46, 42, 42, 42, 39, 39,
}
Tables.TNS_MAX_BANDS_SHORT = {
9, 9, 10, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
}
return Tables
+336
View File
@@ -0,0 +1,336 @@
--!strict
-- codecs/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program
-- config element, explicit and backward-compatible SBR signalling), ADTS headers, and raw_data_block decoding
-- (codecs/Aac/Decode). A codec (layer 1): audio/m4a, audio/aac (ADTS), and later MP4 / MKV / MPEG-TS video build on it.
-- Written from the standard (tables: codecs/Aac/Tables); no third-party code.
-- Supports: AAC-LC (object type 2) 1 - 8 channels, all sampling rates, long / short / start / stop windows, sine and KBD
-- windows, M/S, intensity stereo, PNS, TNS, pulses. HE-AAC (SBR, PS: object types 5 / 29, or implicit SBR payloads)
-- decodes its AAC-LC core at the core rate; `decoder.onExtension` receives every FIL extension payload (the hook for a
-- later SBR / PS module), `decoder.sbr` says whether one was seen. Not supported: AAC Main prediction, LTP, SSR gain
-- control, coupling channels, 960-sample frames, ER / USAC object types (UNSUPPORTED).
--
-- local Aac = require("@formats/codecs/Aac")
-- local dec, err = Aac.decoder(asc) -- an AudioSpecificConfig (buffer) or { objectType, sfIndex, channels }
-- local frames, err = dec:decode(buf, offset, length) -- one raw_data_block -> dec.pcm (frames * channels floats)
-- local h = Aac.adts(buf, offset, limit) -- an ADTS header: { headerSize, frameSize, objectType, sfIndex, ... }
--
-- Never throws: bad data returns nil, Err.
local Err = require("@formats/core/Err")
local Bits = require("@formats/core/Bits")
local Decode = require("@formats/codecs/Aac/Decode")
local Aac = {}
Aac.RATES = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 }
local CONFIG_CHANNELS = { 1, 2, 3, 4, 5, 6, 8 }
-- element order (AAC: C, L, R, ...) -> WAV order (L, R, C, LFE, ...) for channel configurations 3 .. 7
local CONFIG_MAP: { [number]: { number } } = {
[3] = { 3, 1, 2 },
[4] = { 3, 1, 2, 4 },
[5] = { 3, 1, 2, 4, 5 },
[6] = { 3, 1, 2, 5, 6, 4 },
[7] = { 3, 7, 8, 1, 2, 5, 6, 4 },
}
export type Config = {
objectType: number, -- 2 = AAC-LC (the core object type when SBR / PS is signalled)
sfIndex: number,
sampleRate: number, -- the core rate
channelConfig: number,
channels: number,
sbr: boolean, -- SBR signalled (explicitly or backward-compatibly)
ps: boolean,
extensionRate: number?, -- the SBR output rate
frameLength: number,
}
local function rateIndex(rate: number): number
-- the nearest standard rate (ISO 14496-3 table 4.82 mapping for explicit frequencies)
local best, bi = math.huge, 4
for i, r in Aac.RATES do
if math.abs(r - rate) < best then
best, bi = math.abs(r - rate), i - 1
end
end
return bi
end
local function objectType(br: Bits.BitReader): number
local t = br:read(5)
if t == 31 then
t = 32 + br:read(6)
end
return t
end
local function frequency(br: Bits.BitReader): (number, number)
local i = br:read(4)
if i == 15 then
local f = br:read(24)
return rateIndex(f), f
end
return i, Aac.RATES[i + 1] or 0
end
-- pce(br) -> channels (program_config_element)
local function pce(br: Bits.BitReader): number
br:read(4 + 2 + 4)
local front, side, back = br:read(4), br:read(4), br:read(4)
local lfe, assoc, cc = br:read(2), br:read(3), br:read(4)
if br:read(1) == 1 then
br:read(4)
end
if br:read(1) == 1 then
br:read(4)
end
if br:read(1) == 1 then
br:read(3)
end
local channels = 0
for _ = 1, front + side + back do
channels += if br:read(1) == 1 then 2 else 1
br:read(4)
end
channels += lfe
br:skip(lfe * 4 + assoc * 4 + cc * 5)
br:align()
br:skip(br:read(8) * 8)
return channels
end
-- config(asc) -> Config | nil, Err: parse an AudioSpecificConfig
function Aac.config(asc: buffer): (Config?, Err.Err?)
if type(asc) ~= "buffer" or buffer.len(asc) < 2 then
return nil, Err.new(Err.TRUNCATED, "AudioSpecificConfig is shorter than 2 bytes")
end
local br = Bits.msbReader(asc)
local aot = objectType(br)
local sfi, rate = frequency(br)
local chcfg = br:read(4)
local sbr, ps = false, false
local extRate: number? = nil
if aot == 5 or aot == 29 then
sbr = true
ps = aot == 29
local _, er = frequency(br)
extRate = er
aot = objectType(br)
if aot == 22 then
br:read(4)
end
end
if aot ~= 2 and aot ~= 1 and aot ~= 4 then
if aot == 0 or br.err then
return nil, Err.new(Err.CORRUPT, "bad AudioSpecificConfig")
end
return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. aot .. " (only AAC-LC)")
end
if aot ~= 2 then
return nil, Err.new(Err.UNSUPPORTED, if aot == 1 then "AAC Main" else "AAC LTP")
end
-- GASpecificConfig
local frameLengthFlag = br:read(1)
if br:read(1) == 1 then
br:read(14)
end
local ext = br:read(1)
local channels = CONFIG_CHANNELS[chcfg] or 0
if chcfg == 0 then
channels = pce(br)
elseif chcfg > 7 then
return nil, Err.new(Err.UNSUPPORTED, "channel configuration " .. chcfg)
end
if ext == 1 then
br:read(1) -- extensionFlag3
end
-- backward-compatible SBR signalling
if not sbr and br:bitsLeft() >= 16 then
if br:read(11) == 0x2b7 then
local et = objectType(br)
if et == 5 and br:read(1) == 1 then
sbr = true
local _, er = frequency(br)
extRate = er
if br:bitsLeft() >= 12 and br:read(11) == 0x548 then
ps = br:read(1) == 1
end
end
end
end
if br.err and channels == 0 then
return nil, br.err
end
if sfi > 12 or rate <= 0 then
return nil, Err.new(Err.CORRUPT, "bad sampling frequency index " .. sfi)
end
if frameLengthFlag == 1 then
return nil, Err.new(Err.UNSUPPORTED, "960-sample AAC frames")
end
if channels < 1 or channels > 8 then
return nil, Err.new(Err.UNSUPPORTED, channels .. " channels")
end
return {
objectType = aot,
sfIndex = sfi,
sampleRate = rate,
channelConfig = chcfg,
channels = channels,
sbr = sbr,
ps = ps,
extensionRate = extRate,
frameLength = 1024,
}, nil
end
-- asc(objectType, sfIndex, channelConfig) -> a 2-byte AudioSpecificConfig
function Aac.asc(aot: number, sfIndex: number, channelConfig: number): buffer
local b = buffer.create(2)
local v = aot * 2048 + sfIndex * 128 + channelConfig * 8
buffer.writeu8(b, 0, bit32.rshift(v, 8))
buffer.writeu8(b, 1, bit32.band(v, 255))
return b
end
export type Adts = {
headerSize: number, -- 7, or 9 with a CRC
frameSize: number, -- the whole frame, header included
objectType: number,
sfIndex: number,
sampleRate: number,
channelConfig: number,
blocks: number, -- raw_data_blocks in the frame (1 .. 4)
protected: boolean,
}
-- adts(buf, offset, limit) -> Adts | nil (not a valid header at offset)
function Aac.adts(b: buffer, o: number, limit: number): Adts?
if o < 0 or o + 7 > limit or o + 7 > buffer.len(b) then
return nil
end
local b0, b1, b2, b3, b4, b5, b6 = buffer.readu8(b, o), buffer.readu8(b, o + 1), buffer.readu8(b, o + 2), buffer.readu8(b, o + 3), buffer.readu8(b, o + 4), buffer.readu8(b, o + 5), buffer.readu8(b, o + 6)
if b0 ~= 0xFF or bit32.band(b1, 0xF6) ~= 0xF0 then -- sync, layer 0
return nil
end
local protected = bit32.band(b1, 1) == 0
local profile = bit32.rshift(b2, 6)
local sfi = bit32.band(bit32.rshift(b2, 2), 15)
local ch = bit32.band(b2, 1) * 4 + bit32.rshift(b3, 6)
local size = bit32.band(b3, 3) * 2048 + b4 * 8 + bit32.rshift(b5, 5)
local blocks = bit32.band(b6, 3) + 1
local hs = if protected then 9 else 7
if sfi > 12 or size < hs then
return nil
end
return {
headerSize = hs,
frameSize = size,
objectType = profile + 1,
sfIndex = sfi,
sampleRate = Aac.RATES[sfi + 1],
channelConfig = ch,
blocks = blocks,
protected = protected,
}
end
-- ------------------------------------------------------------------------------------------------ decoder
export type Decoder = {
config: Config,
channels: number,
sampleRate: number,
frameLength: number,
pcm: { number }, -- the last frame: 1024 * channels interleaved floats (-1 .. 1), WAV channel order
sbr: boolean, -- SBR payloads seen in the stream (implicit signalling) or signalled
onExtension: ((kind: number, element: number, buf: buffer, bitPos: number, bits: number) -> ())?,
decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?),
reset: (self: Decoder) -> (),
state: Decode.State,
}
local function decode(self: Decoder, buf: buffer, offset: number?, length: number?): (number?, Err.Err?)
local o = offset or 0
local n = length or (buffer.len(buf) - o)
if type(buf) ~= "buffer" or o < 0 or n < 0 or o + n > buffer.len(buf) then
return nil, Err.new(Err.ARG, "packet range out of the buffer")
end
local st = self.state
st.onExtension = self.onExtension
local chans, msg = Decode.frame(st, buf, o, n)
if not chans then
return nil, Err.new(Err.CORRUPT, msg or "bad frame", o)
end
if st.sbr then
self.sbr = true
end
if chans == 0 then
-- an empty frame (only fill elements): silence
for i = 1, 1024 * self.channels do
st.pcm[i] = 0
end
return 1024, nil
end
if chans ~= self.channels then
return nil, Err.new(Err.CORRUPT, string.format("frame has %d channels, the configuration %d", chans, self.channels), o)
end
return 1024, nil
end
local function reset(self: Decoder)
for _, c in self.state.ch do
for i = 1, 1024 do
c.overlap[i] = 0
end
c.prevShape = 0
end
end
-- decoder(asc | { objectType?, sfIndex, channels }) -> Decoder | nil, Err
function Aac.decoder(asc: any): (Decoder?, Err.Err?)
local cfg: Config
if type(asc) == "buffer" then
local c, err = Aac.config(asc)
if not c then
return nil, err
end
cfg = c
elseif type(asc) == "table" and type(asc.sfIndex) == "number" and type(asc.channels) == "number" then
local sfi = asc.sfIndex
if sfi < 0 or sfi > 12 or asc.channels < 1 or asc.channels > 8 then
return nil, Err.new(Err.ARG, "bad sampling index / channels")
end
if (asc.objectType or 2) ~= 2 then
return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. asc.objectType .. " (only AAC-LC)")
end
cfg = {
objectType = 2,
sfIndex = sfi,
sampleRate = Aac.RATES[sfi + 1],
channelConfig = asc.channelConfig or asc.channels,
channels = asc.channels,
sbr = false,
ps = false,
frameLength = 1024,
}
else
return nil, Err.new(Err.ARG, "decoder: expected an AudioSpecificConfig buffer")
end
local st = Decode.state(cfg.sfIndex)
st.channels = cfg.channels
if cfg.channelConfig >= 3 then
st.map = CONFIG_MAP[cfg.channelConfig]
end
return {
config = cfg,
channels = cfg.channels,
sampleRate = cfg.sampleRate,
frameLength = 1024,
pcm = st.pcm,
sbr = cfg.sbr,
onExtension = nil,
decode = decode,
reset = reset,
state = st,
}, nil
end
return Aac
+427
View File
@@ -0,0 +1,427 @@
--!strict
--!native
--!optimize 2
-- codecs/Alac/Decode: the ALAC frame decoder: elements SCE / CPE / LFE / DSE / FIL / END, the adaptive Golomb-Rice
-- residuals with zero runs, the adaptive FIR predictor (orders 0, 31 and 1 .. 30), stereo unmixing, shifted low bytes,
-- uncompressed (escape) frames, 16 / 20 / 24 / 32-bit samples. Written from the ALAC format as published by Apple
-- (ALACDecoder / ag_dec / dp_dec, Apache 2.0; behaviour, not code). Never throws: returns nil, message.
local readu32, readu8 = buffer.readu32, buffer.readu8
local byteswap, lshift, rshift, band, countlz, bnot = bit32.byteswap, bit32.lshift, bit32.rshift, bit32.band, bit32.countlz, bit32.bnot
local floor = math.floor
local Decode = {}
export type State = {
frameLength: number,
bitDepth: number,
pb: number,
mb: number,
kb: number,
channels: number,
maxRun: number,
scratch: buffer, -- the packet + 16 zero bytes (reads past the end are safe; the overrun is checked)
pred: { { number } }, -- per element channel (0, 1): residuals / predictor output
mix: { { number } },
shift: { number },
out: { number }, -- interleaved output samples (integers), frames * channels
}
local POW = table.create(64, 0)
for i = 0, 63 do
POW[i + 1] = 2 ^ i
end
-- bit reader over st.scratch: pos = bit position. bits(n) for n <= 25.
local function bitsAt(b: buffer, pos: number, n: number): number
local w = byteswap(readu32(b, rshift(pos, 3)))
return rshift(lshift(w, band(pos, 7)), 32 - n)
end
local function signExtend(v: number, bits: number): number
local m = POW[bits + 1]
v = v % m
if v >= m / 2 then
v -= m
end
return v
end
-- the adaptive Golomb-Rice value: unary prefix (escape after 9 ones: `bps` raw bits), then k bits
local function scalar(b: buffer, pos: number, k: number, m: number, bps: number): (number, number)
local w = lshift(byteswap(readu32(b, rshift(pos, 3))), band(pos, 7))
local pre = countlz(bnot(w))
if pre >= 9 then
pos += 9
local v
if bps > 25 then
v = bitsAt(b, pos, bps - 16) * 65536 + bitsAt(b, pos + bps - 16, 16)
else
v = bitsAt(b, pos, bps)
end
return v, pos + bps
end
pos += pre + 1
if k == 1 then
return pre, pos
end
local v = bitsAt(b, pos, k)
local x = pre * m
if v > 1 then
return x + v - 1, pos + k
end
return x, pos + k - 1
end
-- residuals: n values into out[1..n]; returns the new bit position or -1
local function rice(b: buffer, pos: number, limit: number, out: { number }, n: number, bps: number, mult: number, st: State): number
local history = st.mb
local kb = st.kb
local signMod = 0
local i = 1
while i <= n do
if pos > limit then
return -1 -- each value reads at most 41 bits past here: inside the 16 padding bytes
end
local k = 31 - countlz(floor(history / 512) + 3)
if k > kb then
k = kb
end
local x
x, pos = scalar(b, pos, k, POW[k + 1] - 1, bps)
x += signMod
signMod = 0
out[i] = if x % 2 == 0 then x / 2 else -(x + 1) / 2
if x > 0xFFFF then
history = 0xFFFF
else
history += x * mult - floor(history * mult / 512)
end
if history < 128 and i < n then
if pos > limit then
return -1
end
local lg = if history > 0 then 31 - countlz(history) else 0
k = 7 - lg + floor((history + 16) / 64)
if k > kb then
k = kb
end
local run
run, pos = scalar(b, pos, k, POW[k + 1] - 1, 16)
if run > 0 then
if run > n - i then
return -1
end
for j = i + 1, i + run do
out[j] = 0
end
i += run
end
if run < 0xFFFF then
signMod = 1 -- the next value is not 0 (unless the run hit its maximum)
end
history = 0
end
i += 1
end
return pos
end
-- the adaptive FIR predictor: err[1..n] -> out[1..n] (may be the same array); coefs adapt in place
local function predict(err: { number }, out: { number }, n: number, bps: number, coefs: { number }, order: number, quant: number)
out[1] = err[1]
if n <= 1 then
return
end
if order == 0 then
if out ~= err then
for i = 2, n do
out[i] = err[i]
end
end
return
end
if order == 31 then
for i = 2, n do
out[i] = signExtend(out[i - 1] + err[i], bps)
end
return
end
local i = 2
while i <= order + 1 and i <= n do
out[i] = signExtend(out[i - 1] + err[i], bps)
i += 1
end
local half = if quant > 0 then POW[quant] else 0
local qd = POW[quant + 1]
-- coefs[1] multiplies the most recent sample
while i <= n do
local d = out[i - order - 1]
local val = 0
for j = 1, order do
val += (out[i - j] - d) * coefs[j]
end
val = floor((val + half) / qd)
local e = err[i]
out[i] = signExtend(val + d + e, bps)
if e ~= 0 then
local es = if e > 0 then 1 else -1
-- adapt from the oldest sample to the newest while the error keeps its sign
for j = order, 1, -1 do
if e * es <= 0 then
break
end
local v = d - out[i - j]
local sgn = if v > 0 then es elseif v < 0 then -es else 0
coefs[j] -= sgn
e -= floor(v * sgn / qd) * (order - j + 1)
end
end
i += 1
end
end
-- decode(st, buf, off, len) -> frames | nil, message. Samples land interleaved in st.out (integers), channels in the
-- ALAC element order.
function Decode.frame(st: State, buf: buffer, off: number, len: number): (number?, string?)
if len <= 0 then
return nil, "empty packet"
end
local b = st.scratch
if buffer.len(b) < len + 16 then
b = buffer.create(len + 64)
st.scratch = b
end
buffer.copy(b, 0, buf, off, len)
buffer.fill(b, len, 0, 16)
local limit = len * 8
local pos = 0
local channels = st.channels
local ch = 0 -- next output channel
local frames = -1
local out = st.out
while true do
if pos + 3 > limit then
return nil, "frame runs past the end"
end
local tag = bitsAt(b, pos, 3)
pos += 3
if tag == 7 then -- END
break
elseif tag == 0 or tag == 1 or tag == 3 then -- SCE / CPE / LFE
local nch = if tag == 1 then 2 else 1
if ch + nch > channels then
return nil, "more channels than the configuration"
end
pos += 4 -- element instance tag
if bitsAt(b, pos, 12) ~= 0 then
return nil, "bad element header"
end
pos += 12
local h = bitsAt(b, pos, 4)
pos += 4
local partial = rshift(h, 3)
local shiftBytes = band(rshift(h, 1), 3)
local escape = band(h, 1)
if shiftBytes == 3 then
return nil, "bad shift"
end
local n = st.frameLength
if partial == 1 then
n = bitsAt(b, pos, 16) * 65536 + bitsAt(b, pos + 16, 16)
pos += 32
end
if n < 1 or n > st.frameLength then
return nil, "bad frame length " .. n
end
if frames >= 0 and n ~= frames then
return nil, "elements of different lengths"
end
frames = n
if #out < n * channels then
for k = #out + 1, n * channels do
out[k] = 0
end
end
local shift = shiftBytes * 8
local bps = st.bitDepth - shift + nch - 1
if bps > 32 or bps < 1 then
return nil, "bad sample size"
end
if pos > limit then
return nil, "frame runs past the end"
end
local mixBits, mixRes = 0, 0
local p0, p1 = st.pred[1], st.pred[2]
local m0, m1 = st.mix[1], st.mix[2]
local shiftBuf = st.shift
if escape == 0 then
mixBits = bitsAt(b, pos, 8)
mixRes = bitsAt(b, pos + 8, 8)
pos += 16
if mixRes >= 128 then
mixRes -= 256
end
local mode, denShift, pbFactor, order = {}, {}, {}, {}
local coefs = { {}, {} }
for c = 1, nch do
local x = bitsAt(b, pos, 8)
local y = bitsAt(b, pos + 8, 8)
pos += 16
mode[c], denShift[c] = rshift(x, 4), band(x, 15)
pbFactor[c], order[c] = rshift(y, 5), band(y, 31)
if pos + order[c] * 16 > limit then
return nil, "frame runs past the end"
end
for j = 1, order[c] do
local v = bitsAt(b, pos, 16)
pos += 16
coefs[c][j] = if v >= 32768 then v - 65536 else v
end
end
if pos > limit then
return nil, "frame runs past the end"
end
local shiftPos = pos
if shift > 0 then
pos += shift * n * nch
end
for c = 1, nch do
local p = if c == 1 then p0 else p1
local mb = if c == 1 then m0 else m1
pos = rice(b, pos, limit, p, n, bps, floor(st.pb * pbFactor[c] / 4), st)
if pos < 0 or pos > limit then
return nil, "bad residuals"
end
if mode[c] == 15 then
predict(p, p, n, bps, {}, 31, 0)
elseif mode[c] ~= 0 then
return nil, "unknown prediction mode " .. mode[c]
end
predict(p, mb, n, bps, coefs[c], order[c], denShift[c])
end
if shift > 0 then
local sp = shiftPos
for i = 1, n * nch do
shiftBuf[i] = bitsAt(b, sp, shift)
sp += shift
end
end
else
-- uncompressed: interleaved samples of bitDepth bits
local bits = st.bitDepth
if pos + n * nch * bits > limit then
return nil, "frame runs past the end"
end
for i = 1, n do
for c = 1, nch do
local v
if bits > 25 then
v = bitsAt(b, pos, bits - 16) * 65536 + bitsAt(b, pos + bits - 16, 16)
else
v = bitsAt(b, pos, bits)
end
pos += bits
v = signExtend(v, bits)
if c == 1 then
m0[i] = v
else
m1[i] = v
end
end
end
shift = 0
end
-- unmix + shifted bytes -> interleaved output
local sm = POW[shift + 1]
if nch == 2 then
local den = POW[mixBits + 1]
for i = 1, n do
local u, v = m0[i], m1[i]
local l, r
if mixRes ~= 0 then
l = u + v - floor(mixRes * v / den)
r = l - v
else
l, r = u, v
end
if shift > 0 then
l = l * sm + shiftBuf[2 * i - 1]
r = r * sm + shiftBuf[2 * i]
end
local o = (i - 1) * channels + ch + 1
out[o] = l
out[o + 1] = r
end
else
for i = 1, n do
local v = m0[i]
if shift > 0 then
v = v * sm + shiftBuf[i]
end
out[(i - 1) * channels + ch + 1] = v
end
end
ch += nch
elseif tag == 4 then -- DSE
pos += 4
local align = bitsAt(b, pos, 1)
local count = bitsAt(b, pos + 1, 8)
pos += 9
if count == 255 then
count += bitsAt(b, pos, 8)
pos += 8
end
if align == 1 then
pos = (pos + 7) // 8 * 8
end
pos += count * 8
elseif tag == 6 then -- FIL
local count = bitsAt(b, pos, 4)
pos += 4
if count == 15 then
count += bitsAt(b, pos, 8) - 1
pos += 8
end
pos += count * 8
else
return nil, "unsupported element " .. tag
end
if pos > limit then
return nil, "frame runs past the end"
end
end
if frames < 0 then
return 0, nil
end
if ch < channels then
-- missing channels: silence
for i = 1, frames do
for c = ch + 1, channels do
out[(i - 1) * channels + c] = 0
end
end
end
return frames, nil
end
-- the scratch state for a configuration
function Decode.state(cfg: any): State
local n = cfg.frameLength
return {
frameLength = n,
bitDepth = cfg.bitDepth,
pb = cfg.pb,
mb = cfg.mb,
kb = cfg.kb,
channels = cfg.channels,
maxRun = cfg.maxRun,
scratch = buffer.create(math.max(64, cfg.maxFrameBytes or 0) + 64),
pred = { table.create(n, 0), table.create(n, 0) },
mix = { table.create(n, 0), table.create(n, 0) },
shift = table.create(n * 2, 0),
out = table.create(n * cfg.channels, 0),
}
end
local _ = readu8
return Decode
+427
View File
@@ -0,0 +1,427 @@
--!strict
--!native
--!optimize 2
-- codecs/Alac/Encode: an ALAC frame encoder: per element (SCE / CPE) the stereo mix (mixBits 2, the best mixRes of
-- 0 .. 4 by first-difference energy), per channel LPC coefficients (Levinson-Durbin on a windowed autocorrelation,
-- orders 4 and 8 tried, quantised with denShift 9), residuals through the same adaptive FIR the decoder runs, the
-- adaptive Golomb-Rice code with zero runs; an uncompressed (escape) frame when that is smaller. 16 / 20 / 24-bit
-- input. Written for this library from the ALAC format; no third-party code. Never throws.
local band, rshift, bor, lshift, countlz = bit32.band, bit32.rshift, bit32.bor, bit32.lshift, bit32.countlz
local readu8, writeu8 = buffer.readu8, buffer.writeu8
local floor, abs = math.floor, math.abs
local Encode = {}
local POW = table.create(64, 0)
for i = 0, 63 do
POW[i + 1] = 2 ^ i
end
local DENSHIFT = 9
local PB_FACTOR = 4
export type State = {
frameLength: number,
bitDepth: number,
pb: number,
mb: number,
kb: number,
channels: number,
out: buffer, -- packet scratch
pos: number, -- bit position in out
cap: number, -- bits available
u: { number },
v: { number },
err: { number },
work: { number },
}
-- ------------------------------------------------------------------------------------------------ bit writer
local function put(st: State, v: number, n: number)
local pos = st.pos
if pos + n > st.cap then
st.pos = st.cap + 1 -- overflow: the caller falls back to an uncompressed frame
return
end
local b = st.out
while n > 0 do
local byte = rshift(pos, 3)
local free = 8 - band(pos, 7)
local take = if n < free then n else free
local bits = band(rshift(v, n - take), POW[take + 1] - 1)
writeu8(b, byte, bor(readu8(b, byte), lshift(bits, free - take)))
pos += take
n -= take
end
st.pos = pos
end
local function putBig(st: State, v: number, n: number)
if n > 24 then
local lo = v % 65536
put(st, (v - lo) / 65536, n - 16)
put(st, lo, 16)
else
put(st, v, n)
end
end
-- ------------------------------------------------------------------------------------------------ rice code
local function signExtend(v: number, bits: number): number
local m = POW[bits + 1]
v = v % m
if v >= m / 2 then
v -= m
end
return v
end
-- the bits of one scalar (no writing)
local function scalarBits(x: number, k: number, m: number, bps: number): number
local pre = if k == 1 then x else floor(x / m)
if pre >= 9 then
return 9 + bps
end
if k == 1 then
return pre + 1
end
local r = x - pre * m
return pre + 1 + (if r == 0 then k - 1 else k)
end
local function scalar(st: State, x: number, k: number, m: number, bps: number)
local pre = if k == 1 then x else floor(x / m)
if pre >= 9 then
put(st, 511, 9)
putBig(st, x, bps)
return
end
-- pre ones and a zero
put(st, POW[pre + 2] - 2, pre + 1)
if k ~= 1 then
local r = x - pre * m
if r == 0 then
put(st, 0, k - 1)
else
put(st, r + 1, k)
end
end
end
-- code the residuals e[1..n] (write = false: just count the bits)
local function rice(st: State, e: { number }, n: number, bps: number, mult: number, write: boolean): number
local history = st.mb
local kb = st.kb
local signMod = 0
local bits = 0
local i = 1
while i <= n do
local k = 31 - countlz(floor(history / 512) + 3)
if k > kb then
k = kb
end
local v = e[i]
local zz = if v >= 0 then 2 * v else -2 * v - 1
local x = zz - signMod
signMod = 0
local m = POW[k + 1] - 1
if write then
scalar(st, x, k, m, bps)
else
bits += scalarBits(x, k, m, bps)
end
if zz > 0xFFFF then -- the decoder adapts on the value with its sign modifier added back
history = 0xFFFF
else
history += zz * mult - floor(history * mult / 512)
end
if history < 128 and i < n then
local lg = if history > 0 then 31 - countlz(history) else 0
k = 7 - lg + floor((history + 16) / 64)
if k > kb then
k = kb
end
local run = 0
while i + run < n and e[i + run + 1] == 0 and run < 0xFFFF do
run += 1
end
m = POW[k + 1] - 1
if write then
scalar(st, run, k, m, 16)
else
bits += scalarBits(run, k, m, 16)
end
i += run
if run < 0xFFFF then
signMod = 1
end
history = 0
end
i += 1
end
return bits
end
-- ------------------------------------------------------------------------------------------------ prediction
-- residuals of x[1..n] under the decoder's adaptive FIR starting from coefs (adapted in place, like the decoder)
local function residuals(x: { number }, e: { number }, n: number, bps: number, coefs: { number }, order: number, quant: number)
e[1] = x[1]
if n <= 1 then
return
end
local i = 2
while i <= order + 1 and i <= n do
e[i] = signExtend(x[i] - x[i - 1], bps)
i += 1
end
local half = POW[quant]
local qd = POW[quant + 1]
while i <= n do
local d = x[i - order - 1]
local val = 0
for j = 1, order do
val += (x[i - j] - d) * coefs[j]
end
val = floor((val + half) / qd)
local r = signExtend(x[i] - val - d, bps)
e[i] = r
if r ~= 0 then
local es = if r > 0 then 1 else -1
for j = order, 1, -1 do
if r * es <= 0 then
break
end
local v = d - x[i - j]
local sgn = if v > 0 then es elseif v < 0 then -es else 0
coefs[j] -= sgn
r -= floor(v * sgn / qd) * (order - j + 1)
end
end
i += 1
end
end
-- LPC coefficients of x[1..n] for the given order (Levinson-Durbin on a Welch-windowed autocorrelation), quantised
local function lpc(x: { number }, n: number, order: number, work: { number }): { number }
local ac = table.create(order + 1, 0)
for i = 1, n do
local t = (2 * (i - 1) - (n - 1)) / (n + 1)
work[i] = x[i] * (1 - t * t)
end
for lag = 0, order do
local s = 0
for i = lag + 1, n do
s += work[i] * work[i - lag]
end
ac[lag + 1] = s
end
local coefs = table.create(order, 0)
if ac[1] <= 0 then
return coefs
end
ac[1] *= 1.0001 -- a little white noise: keeps the recursion stable
local a = table.create(order + 1, 0)
local tmp = table.create(order + 1, 0)
local errv = ac[1]
for i = 1, order do
local acc = ac[i + 1]
for j = 1, i - 1 do
acc -= a[j] * ac[i - j + 1]
end
local kc = acc / errv
for j = 1, i - 1 do
tmp[j] = a[j] - kc * a[i - j]
end
for j = 1, i - 1 do
a[j] = tmp[j]
end
a[i] = kc
errv *= (1 - kc * kc)
if errv <= 0 then
break
end
end
local scale = POW[DENSHIFT + 1]
for j = 1, order do
coefs[j] = math.clamp(floor(a[j] * scale + 0.5), -32768, 32767)
end
return coefs
end
-- choose order / coefficients for one channel: returns order, coefs (as transmitted), bits
local function analyse(st: State, x: { number }, n: number, bps: number): (number, { number }, number)
local mult = floor(st.pb * PB_FACTOR / 4)
local bestOrder, bestCoefs, bestBits = 0, {}, math.huge
for _, order in { 4, 8 } do
if order >= n then
continue
end
local coefs = lpc(x, n, order, st.work)
local trial = table.clone(coefs)
residuals(x, st.err, n, bps, trial, order, DENSHIFT)
local bits = rice(st, st.err, n, bps, mult, false) + order * 16
if bits < bestBits then
bestOrder, bestCoefs, bestBits = order, coefs, bits
end
end
if bestBits == math.huge then
-- tiny frames: first-order prediction (order 31 is only a decoder mode; order 0 = no prediction)
for i = 1, n do
st.err[i] = x[i]
end
return 0, {}, rice(st, st.err, n, bps, mult, false)
end
return bestOrder, bestCoefs, bestBits
end
-- ------------------------------------------------------------------------------------------------ frame
-- frame(st, samples, first, frames, map) -> buffer: samples interleaved (integers, WAV channel order) from index
-- `first`; map[k] = the input channel (1-based) of ALAC channel k; elements: list of 1 / 2 channel counts
function Encode.frame(st: State, samples: { number }, first: number, frames: number, map: { number }, elements: { number }): buffer
local channels, depth = st.channels, st.bitDepth
local n = frames
local partial = n ~= st.frameLength
local rawBits = n * channels * depth
local need = rawBits + 64 * #elements + 64
if st.cap < need + 8 * 32 * 2 * #elements * 16 then
local bytes = (need + 8 * 32 * 2 * #elements * 16) // 8 + 16
st.out = buffer.create(bytes)
st.cap = bytes * 8
end
buffer.fill(st.out, 0, 0)
st.pos = 0
local u, v = st.u, st.v
local mult = floor(st.pb * PB_FACTOR / 4)
local compressed = true
local ch = 1
for _, nch in elements do
local a, b = map[ch], map[ch + 1]
local bps = depth + nch - 1
local mixRes = 0
if nch == 2 then
-- the mix with the smallest first-difference energy
local best = math.huge
for res = 0, 4 do
local cost = 0
local pu, pv = 0, 0
for i = 0, n - 1 do
local l = samples[first + i * channels + a - 1]
local r = samples[first + i * channels + b - 1]
local uu, vv
if res == 0 then
uu, vv = l, r
else
uu, vv = floor((res * l + (4 - res) * r) / 4), l - r
end
cost += abs(uu - pu) + abs(vv - pv)
pu, pv = uu, vv
end
if cost < best then
best, mixRes = cost, res
end
end
for i = 1, n do
local l = samples[first + (i - 1) * channels + a - 1]
local r = samples[first + (i - 1) * channels + b - 1]
if mixRes == 0 then
u[i], v[i] = l, r
else
u[i], v[i] = floor((mixRes * l + (4 - mixRes) * r) / 4), l - r
end
end
else
for i = 1, n do
u[i] = samples[first + (i - 1) * channels + a - 1]
end
end
-- header
put(st, if nch == 2 then 1 else 0, 3)
put(st, 0, 4)
put(st, 0, 12)
put(st, if partial then 1 else 0, 1)
put(st, 0, 2)
put(st, 0, 1)
if partial then
putBig(st, n, 32)
end
put(st, if mixRes == 0 then 0 else 2, 8)
put(st, mixRes, 8)
local orders, coefsList = {}, {}
for c = 1, nch do
local x = if c == 1 then u else v
local order, coefs = analyse(st, x, n, bps)
orders[c], coefsList[c] = order, coefs
put(st, 0 * 16 + DENSHIFT, 8) -- mode 0, denShift
put(st, PB_FACTOR * 32 + order, 8)
for j = 1, order do
put(st, coefs[j] % 65536, 16)
end
end
for c = 1, nch do
local x = if c == 1 then u else v
local order = orders[c]
if order == 0 then
for i = 1, n do
st.err[i] = x[i]
end
else
residuals(x, st.err, n, bps, table.clone(coefsList[c]), order, DENSHIFT)
end
rice(st, st.err, n, bps, mult, true)
end
ch += nch
if st.pos > rawBits + 64 * #elements then
compressed = false
break
end
end
if not compressed then
-- uncompressed frame
buffer.fill(st.out, 0, 0)
st.pos = 0
ch = 1
for _, nch in elements do
put(st, if nch == 2 then 1 else 0, 3)
put(st, 0, 4)
put(st, 0, 12)
put(st, if partial then 1 else 0, 1)
put(st, 0, 2)
put(st, 1, 1)
if partial then
putBig(st, n, 32)
end
for i = 0, n - 1 do
for c = 0, nch - 1 do
putBig(st, samples[first + i * channels + map[ch + c] - 1] % POW[depth + 1], depth)
end
end
ch += nch
end
end
put(st, 7, 3) -- END
local bytes = (st.pos + 7) // 8
local pkt = buffer.create(bytes)
buffer.copy(pkt, 0, st.out, 0, bytes)
return pkt
end
function Encode.state(cfg: any): State
local n = cfg.frameLength
return {
frameLength = n,
bitDepth = cfg.bitDepth,
pb = cfg.pb,
mb = cfg.mb,
kb = cfg.kb,
channels = cfg.channels,
out = buffer.create(16),
pos = 0,
cap = 0,
u = table.create(n, 0),
v = table.create(n, 0),
err = table.create(n, 0),
work = table.create(n, 0),
}
end
return Encode
+251
View File
@@ -0,0 +1,251 @@
--!strict
-- codecs/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1).
-- Written from the ALAC format as Apple published it (ALACSpecificConfig, the element syntax, adaptive Golomb-Rice
-- residuals, the adaptive FIR predictor); no third-party code. 1 - 8 channels, 16 / 20 / 24 / 32-bit decode, 16 / 20 /
-- 24-bit encode. Channels come out (and go in) in WAV order (ALAC stores C L R ... for 3+ channels).
--
-- local Alac = require("@formats/codecs/Alac")
-- local cfg, err = Alac.config(cookie) -- the 24-byte ALACSpecificConfig (frma / alac atoms skipped)
-- local dec = Alac.decoder(cfg)
-- local frames, err = dec:decode(buf, offset, length) -- one packet -> dec.pcm (interleaved integers, WAV order)
-- local enc = Alac.encoder({ sampleRate = 44100, channels = 2, bitDepth = 16 })
-- local packet = enc:encode(samples, first, frames) -- interleaved integers -> one packet (frames <= 4096)
-- local cookie = Alac.cookie(enc.config) -- after encoding: maxFrameBytes / avgBitRate filled
--
-- Never throws: bad data returns nil, Err (CORRUPT / TRUNCATED / UNSUPPORTED), bad arguments Err.ARG.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Decode = require("@formats/codecs/Alac/Decode")
local Encode = require("@formats/codecs/Alac/Encode")
local Alac = {}
export type Config = {
frameLength: number, -- samples per packet (4096)
compatibleVersion: number,
bitDepth: number,
pb: number, -- 40
mb: number, -- 10
kb: number, -- 14
channels: number,
maxRun: number, -- 255
maxFrameBytes: number,
avgBitRate: number,
sampleRate: number,
}
-- ALAC channel k (1-based) -> WAV channel (1-based), per channel count
local TO_WAV: { { number } } = {
{ 1 },
{ 1, 2 },
{ 3, 1, 2 },
{ 3, 1, 2, 4 },
{ 3, 1, 2, 4, 5 },
{ 3, 1, 2, 5, 6, 4 },
{ 3, 1, 2, 5, 6, 7, 4 },
{ 3, 7, 8, 1, 2, 5, 6, 4 },
}
-- the element layout (channels per element) the encoder writes
local ELEMENTS: { { number } } = {
{ 1 },
{ 2 },
{ 1, 2 },
{ 1, 2, 1 },
{ 1, 2, 2 },
{ 1, 2, 2, 1 },
{ 1, 2, 2, 1, 1 },
{ 1, 2, 2, 2, 1 },
}
Alac.TO_WAV = TO_WAV
-- config(buf, offset?, length?) -> Config | nil, Err
function Alac.config(buf: buffer, offset: number?, length: number?): (Config?, Err.Err?)
local r = Bytes.reader(buf, offset, length)
-- a QuickTime 'wave' payload may hold frma + alac atoms ahead of the cookie
for _ = 1, 2 do
local typ = r:peek(4, 4)
if typ == "frma" then
r:skip(12)
elseif typ == "alac" then
r:skip(12)
end
end
if r:remaining() < 24 then
return nil, Err.new(Err.TRUNCATED, "ALAC configuration is shorter than 24 bytes")
end
local c: Config = {
frameLength = r:u32be(),
compatibleVersion = r:u8(),
bitDepth = r:u8(),
pb = r:u8(),
mb = r:u8(),
kb = r:u8(),
channels = r:u8(),
maxRun = r:u16be(),
maxFrameBytes = r:u32be(),
avgBitRate = r:u32be(),
sampleRate = r:u32be(),
}
if c.compatibleVersion ~= 0 then
return nil, Err.new(Err.UNSUPPORTED, "ALAC version " .. c.compatibleVersion)
end
if c.frameLength < 1 or c.frameLength > 65536 then
return nil, Err.new(Err.CORRUPT, "bad ALAC frame length " .. c.frameLength)
end
if c.bitDepth ~= 16 and c.bitDepth ~= 20 and c.bitDepth ~= 24 and c.bitDepth ~= 32 then
return nil, Err.new(Err.UNSUPPORTED, "ALAC bit depth " .. c.bitDepth)
end
if c.channels < 1 or c.channels > 8 then
return nil, Err.new(Err.UNSUPPORTED, "ALAC with " .. c.channels .. " channels")
end
if c.kb < 1 or c.kb > 24 then
return nil, Err.new(Err.CORRUPT, "bad ALAC rice limit " .. c.kb)
end
return c, nil
end
-- cookie(cfg) -> the 24-byte ALACSpecificConfig
function Alac.cookie(c: Config): buffer
local w = Bytes.writer(24)
w:u32be(c.frameLength)
w:u8(0)
w:u8(c.bitDepth)
w:u8(c.pb)
w:u8(c.mb)
w:u8(c.kb)
w:u8(c.channels)
w:u16be(c.maxRun)
w:u32be(c.maxFrameBytes)
w:u32be(c.avgBitRate)
w:u32be(c.sampleRate)
return w:finish()
end
-- ------------------------------------------------------------------------------------------------ decoder
export type Decoder = {
config: Config,
pcm: { number }, -- the last packet's samples, interleaved, WAV order (integers of config.bitDepth bits)
decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?),
state: Decode.State,
}
local function decode(self: Decoder, buf: buffer, offset: number?, length: number?): (number?, Err.Err?)
local o = offset or 0
local n = length or (buffer.len(buf) - o)
if o < 0 or n < 0 or o + n > buffer.len(buf) then
return nil, Err.new(Err.ARG, "packet range out of the buffer")
end
local frames, msg = Decode.frame(self.state, buf, o, n)
if not frames then
return nil, Err.new(Err.CORRUPT, msg or "bad packet", o)
end
local ch = self.config.channels
local src, dst = self.state.out, self.pcm
if ch <= 2 then
for i = 1, frames * ch do
dst[i] = src[i]
end
else
local map = TO_WAV[ch]
for f = 0, frames - 1 do
local base = f * ch
for k = 1, ch do
dst[base + map[k]] = src[base + k]
end
end
end
return frames, nil
end
-- decoder(cfg) -> Decoder
function Alac.decoder(cfg: Config): Decoder
return {
config = cfg,
pcm = table.create(cfg.frameLength * cfg.channels, 0),
decode = decode,
state = Decode.state(cfg),
}
end
-- ------------------------------------------------------------------------------------------------ encoder
export type Encoder = {
config: Config,
encode: (self: Encoder, samples: { number }, first: number, frames: number) -> (buffer?, Err.Err?),
state: Encode.State,
bytes: number,
frames: number,
}
local function encode(self: Encoder, samples: { number }, first: number, frames: number): (buffer?, Err.Err?)
local cfg = self.config
if type(samples) ~= "table" or frames < 1 or frames > cfg.frameLength or frames % 1 ~= 0 then
return nil, Err.new(Err.ARG, "encode: 1 .. " .. cfg.frameLength .. " frames of interleaved integer samples")
end
if first < 1 or first + frames * cfg.channels - 1 > #samples then
return nil, Err.new(Err.ARG, "encode: the samples end early")
end
local ch = cfg.channels
local pkt = Encode.frame(self.state, samples, first, frames, TO_WAV[ch], ELEMENTS[ch])
local n = buffer.len(pkt)
self.bytes += n
self.frames += frames
if n > cfg.maxFrameBytes then
cfg.maxFrameBytes = n
end
if self.frames > 0 then
cfg.avgBitRate = math.floor(self.bytes * 8 * cfg.sampleRate / self.frames)
end
return pkt, nil
end
export type EncoderOptions = {
sampleRate: number,
channels: number, -- 1 .. 8
bitDepth: number?, -- 16 (default), 20 or 24
frameLength: number?, -- default 4096
}
-- encoder(opts) -> Encoder | nil, Err
function Alac.encoder(opts: EncoderOptions): (Encoder?, Err.Err?)
if type(opts) ~= "table" then
return nil, Err.new(Err.ARG, "encoder: expected options")
end
local depth = opts.bitDepth or 16
local ch = opts.channels
if depth ~= 16 and depth ~= 20 and depth ~= 24 then
return nil, Err.new(Err.ARG, "encoder: bitDepth 16, 20 or 24")
end
if type(ch) ~= "number" or ch < 1 or ch > 8 or ch % 1 ~= 0 then
return nil, Err.new(Err.ARG, "encoder: 1 .. 8 channels")
end
local sr = opts.sampleRate
if type(sr) ~= "number" or sr < 1 or sr % 1 ~= 0 then
return nil, Err.new(Err.ARG, "encoder: bad sampleRate")
end
local fl = opts.frameLength or 4096
if fl < 16 or fl > 16384 or fl % 1 ~= 0 then
return nil, Err.new(Err.ARG, "encoder: frameLength 16 .. 16384")
end
local cfg: Config = {
frameLength = fl,
compatibleVersion = 0,
bitDepth = depth,
pb = 40,
mb = 10,
kb = 14,
channels = ch,
maxRun = 255,
maxFrameBytes = 0,
avgBitRate = 0,
sampleRate = sr,
}
return {
config = cfg,
encode = encode,
state = Encode.state(cfg),
bytes = 0,
frames = 0,
}, nil
end
return Alac
+211
View File
@@ -0,0 +1,211 @@
--!strict
--!native
--!optimize 2
-- codecs/Mdct/Fft: mixed-radix complex FFT of any size (radix 4, 2, 3, 5 butterflies, a generic odd-radix pass for
-- other primes), self-sorting Stockham passes ping-ponging between the data and a scratch array (the FFTPACK /
-- pocketfft pass structure, written from the textbook decimation-in-frequency derivation; no third-party code).
-- Data are separate real / imaginary arrays, 1-based. Never throws.
local Fft = {}
export type Plan = {
n: number,
factors: { number },
-- per pass: twiddles exp(-2 pi i u i l1 / n) for u = 1 .. p - 1, i = 0 .. ido - 1 at [(u - 1) * ido + i + 1]
twr: { { number } },
twi: { { number } },
-- per pass, generic odd radix: exp(-2 pi i k / p) for k = 0 .. p - 1
rr: { { number } },
ri: { { number } },
sre: { number }, -- scratch
sim: { number },
}
local cos, sin, pi = math.cos, math.sin, math.pi
-- new(n) -> Plan | nil (n < 1 or not an integer)
function Fft.new(n: number): Plan?
if type(n) ~= "number" or n < 1 or n % 1 ~= 0 or n > 2 ^ 24 then
return nil
end
local factors = {}
local m = n
while m % 4 == 0 do
table.insert(factors, 4)
m //= 4
end
while m % 2 == 0 do
table.insert(factors, 2)
m //= 2
end
local f = 3
while m > 1 do
while m % f == 0 do
table.insert(factors, f)
m //= f
end
f += 2
if f * f > m and m > 1 then
table.insert(factors, m)
m = 1
end
end
local twr, twi, rr, ri = {}, {}, {}, {}
local l1 = 1
for k, p in factors do
local ido = n // (l1 * p)
local tr, ti = table.create((p - 1) * ido, 0), table.create((p - 1) * ido, 0)
for u = 1, p - 1 do
for i = 0, ido - 1 do
local a = -2 * pi * u * i * l1 / n
tr[(u - 1) * ido + i + 1] = cos(a)
ti[(u - 1) * ido + i + 1] = sin(a)
end
end
twr[k], twi[k] = tr, ti
local cr, ci = table.create(p, 0), table.create(p, 0)
for j = 0, p - 1 do
cr[j + 1] = cos(-2 * pi * j / p)
ci[j + 1] = sin(-2 * pi * j / p)
end
rr[k], ri[k] = cr, ci
l1 *= p
end
return {
n = n,
factors = factors,
twr = twr,
twi = twi,
rr = rr,
ri = ri,
sre = table.create(n, 0),
sim = table.create(n, 0),
}
end
-- one pass of radix p: cc (i, v, k) = src[1 + i + ido * (v + p * k)] -> ch (i, k, u) = dst[1 + i + ido * (k + l1 * u)]
local function pass(p: number, ido: number, l1: number, ar: { number }, ai: { number }, br: { number }, bi: { number }, tr: { number }, ti: { number }, cr: { number }, ci: { number })
local lp = ido * l1
if p == 4 then
for k = 0, l1 - 1 do
for i = 0, ido - 1 do
local s = 1 + i + ido * 4 * k
local a0r, a0i = ar[s], ai[s]
local a1r, a1i = ar[s + ido], ai[s + ido]
local a2r, a2i = ar[s + 2 * ido], ai[s + 2 * ido]
local a3r, a3i = ar[s + 3 * ido], ai[s + 3 * ido]
local t0r, t0i = a0r + a2r, a0i + a2i
local t1r, t1i = a0r - a2r, a0i - a2i
local t2r, t2i = a1r + a3r, a1i + a3i
local t3r, t3i = a1r - a3r, a1i - a3i
local d = 1 + i + ido * k
br[d], bi[d] = t0r + t2r, t0i + t2i
local y1r, y1i = t1r + t3i, t1i - t3r
local y2r, y2i = t0r - t2r, t0i - t2i
local y3r, y3i = t1r - t3i, t1i + t3r
if i == 0 then
br[d + lp], bi[d + lp] = y1r, y1i
br[d + 2 * lp], bi[d + 2 * lp] = y2r, y2i
br[d + 3 * lp], bi[d + 3 * lp] = y3r, y3i
else
local w1r, w1i = tr[i + 1], ti[i + 1]
local w2r, w2i = tr[ido + i + 1], ti[ido + i + 1]
local w3r, w3i = tr[2 * ido + i + 1], ti[2 * ido + i + 1]
br[d + lp], bi[d + lp] = y1r * w1r - y1i * w1i, y1r * w1i + y1i * w1r
br[d + 2 * lp], bi[d + 2 * lp] = y2r * w2r - y2i * w2i, y2r * w2i + y2i * w2r
br[d + 3 * lp], bi[d + 3 * lp] = y3r * w3r - y3i * w3i, y3r * w3i + y3i * w3r
end
end
end
elseif p == 2 then
for k = 0, l1 - 1 do
for i = 0, ido - 1 do
local s = 1 + i + ido * 2 * k
local a0r, a0i = ar[s], ai[s]
local a1r, a1i = ar[s + ido], ai[s + ido]
local d = 1 + i + ido * k
br[d], bi[d] = a0r + a1r, a0i + a1i
local yr, yi = a0r - a1r, a0i - a1i
if i == 0 then
br[d + lp], bi[d + lp] = yr, yi
else
local wr, wi = tr[i + 1], ti[i + 1]
br[d + lp], bi[d + lp] = yr * wr - yi * wi, yr * wi + yi * wr
end
end
end
elseif p == 3 then
local c = 0.86602540378443864676 -- sin(pi / 3)
for k = 0, l1 - 1 do
for i = 0, ido - 1 do
local s = 1 + i + ido * 3 * k
local a0r, a0i = ar[s], ai[s]
local a1r, a1i = ar[s + ido], ai[s + ido]
local a2r, a2i = ar[s + 2 * ido], ai[s + 2 * ido]
local tr_, ti_ = a1r + a2r, a1i + a2i
local sr, si = a1r - a2r, a1i - a2i
local d = 1 + i + ido * k
br[d], bi[d] = a0r + tr_, a0i + ti_
local mr, mi = a0r - 0.5 * tr_, a0i - 0.5 * ti_
local y1r, y1i = mr + c * si, mi - c * sr
local y2r, y2i = mr - c * si, mi + c * sr
if i == 0 then
br[d + lp], bi[d + lp] = y1r, y1i
br[d + 2 * lp], bi[d + 2 * lp] = y2r, y2i
else
local w1r, w1i = tr[i + 1], ti[i + 1]
local w2r, w2i = tr[ido + i + 1], ti[ido + i + 1]
br[d + lp], bi[d + lp] = y1r * w1r - y1i * w1i, y1r * w1i + y1i * w1r
br[d + 2 * lp], bi[d + 2 * lp] = y2r * w2r - y2i * w2i, y2r * w2i + y2i * w2r
end
end
end
else
-- generic radix: y_u = sum_v a_v exp(-2 pi i u v / p), then the twiddle
for k = 0, l1 - 1 do
for i = 0, ido - 1 do
local s = 1 + i + ido * p * k
local d = 1 + i + ido * k
for u = 0, p - 1 do
local yr, yi = 0, 0
local j = 0
for v = 0, p - 1 do
local xr, xi = ar[s + v * ido], ai[s + v * ido]
local wr, wi = cr[j + 1], ci[j + 1]
yr += xr * wr - xi * wi
yi += xr * wi + xi * wr
j += u
if j >= p then
j -= p
end
end
if u > 0 and i > 0 then
local wr, wi = tr[(u - 1) * ido + i + 1], ti[(u - 1) * ido + i + 1]
yr, yi = yr * wr - yi * wi, yr * wi + yi * wr
end
br[d + u * lp], bi[d + u * lp] = yr, yi
end
end
end
end
end
-- forward(plan, re, im): in-place forward DFT X[k] = sum x[j] exp(-2 pi i j k / n) of re[1..n], im[1..n].
-- The inverse (without the 1 / n) is forward(plan, im, re).
function Fft.forward(plan: Plan, re: { number }, im: { number })
local n = plan.n
local ar, ai, br, bi = re, im, plan.sre, plan.sim
local l1 = 1
for k, p in plan.factors do
local ido = n // (l1 * p)
pass(p, ido, l1, ar, ai, br, bi, plan.twr[k], plan.twi[k], plan.rr[k], plan.ri[k])
ar, ai, br, bi = br, bi, ar, ai
l1 *= p
end
if ar ~= re then
for j = 1, n do
re[j], im[j] = ar[j], ai[j]
end
end
end
return Fft
+203
View File
@@ -0,0 +1,203 @@
--!strict
--!native
--!optimize 2
-- codecs/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point
-- complex FFT (codecs/Mdct/Fft, mixed radix: AAC 2048 / 256, Vorbis 64 .. 8192, CELT 1920 / 240 / ...), plus the
-- DCT-IV, a plain FFT and the sine / KBD / Vorbis windows. Shared by AAC, Vorbis and Opus (decoders and encoders).
-- Written from the textbook definitions (MDCT = DCT-IV of the folded input; DCT-IV through a half-size complex FFT
-- with pre / post twiddles); no third-party code.
--
-- X[k] = sum_{j=0}^{N-1} x[j] cos(2 pi / N (j + 1/2 + N/4) (k + 1/2)) forward, k = 0 .. N/2 - 1
-- y[j] = sum_{k=0}^{N/2-1} X[k] cos(2 pi / N (j + 1/2 + N/4) (k + 1/2)) inverse, j = 0 .. N - 1
--
-- Both are unnormalised (times `scale`, default 1): windowed forward + inverse + overlap-add with a Princen-Bradley
-- window gives the input times N / 4 (AAC: the spec IMDCT is inverse(..., 2 / N), its MDCT has a factor 2). Arrays
-- are Luau arrays; `xi` / `yi` are the 1-based index of element 0, coefficient arrays may be strided (CELT
-- interleaves its short blocks).
--
-- local Mdct = require("@formats/codecs/Mdct")
-- local plan = Mdct.new(2048) -- nil when N is not a multiple of 4
-- Mdct.forward(plan, x, 1, X, 1) -- 2048 samples -> 1024 coefficients
-- Mdct.inverse(plan, X, 1, 1, y, 1, 2 / 2048) -- 1024 coefficients -> 2048 samples
-- local w = Mdct.window("sine", 2048) -- or "kbd" (alpha), "vorbis": N values
--
-- Never throws: bad sizes return nil from new(); the transforms trust the plan and the array ranges (the caller
-- sizes them).
local Fft = require("@formats/codecs/Mdct/Fft")
local cos, sin, pi, sqrt = math.cos, math.sin, math.pi, math.sqrt
local Mdct = {}
Mdct.Fft = Fft
export type Plan = {
n: number, -- window length N
m: number, -- coefficients N / 2
fft: Fft.Plan, -- N / 4 points
twc: { number }, -- cos / sin (pi (p + 1/8) / M), p = 0 .. N/4 - 1
tws: { number },
re: { number }, -- scratch
im: { number },
c: { number }, -- DCT-IV output scratch (M)
}
-- new(N) -> Plan | nil
function Mdct.new(n: number): Plan?
if type(n) ~= "number" or n < 4 or n % 4 ~= 0 or n > 2 ^ 24 then
return nil
end
local m = n // 2
local q = n // 4
local fft = Fft.new(q)
if not fft then
return nil
end
local twc, tws = table.create(q, 0), table.create(q, 0)
for p = 0, q - 1 do
local a = pi * (p + 0.125) / m
twc[p + 1], tws[p + 1] = cos(a), sin(a)
end
return {
n = n,
m = m,
fft = fft,
twc = twc,
tws = tws,
re = table.create(q, 0),
im = table.create(q, 0),
c = table.create(m, 0),
}
end
-- the DCT-IV of the M values u (already in plan.re / plan.im as the pre-twiddled pairs) into out[oi + k * os]
local function dct4Post(plan: Plan, out: { number }, oi: number, os: number, scale: number)
local q, m = plan.n // 4, plan.m
local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws
Fft.forward(plan.fft, re, im)
for k = 0, q - 1 do
local c, s = twc[k + 1], tws[k + 1]
local tr, ti = re[k + 1], im[k + 1]
out[oi + 2 * k * os] = (tr * c + ti * s) * scale
out[oi + (m - 1 - 2 * k) * os] = -(ti * c - tr * s) * scale
end
end
-- dct4(plan, u, ui, us, out, oi, os, scale?): C[k] = sum_{n=0}^{M-1} u[n] cos(pi / M (n + 1/2) (k + 1/2)) for the
-- plan's M = N / 2 (its own inverse up to 2 / M)
function Mdct.dct4(plan: Plan, u: { number }, ui: number, us: number, out: { number }, oi: number, os: number, scale: number?)
local q, m = plan.n // 4, plan.m
local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws
for p = 0, q - 1 do
local a, b = u[ui + 2 * p * us], u[ui + (m - 1 - 2 * p) * us]
local c, s = twc[p + 1], tws[p + 1]
re[p + 1] = a * c + b * s
im[p + 1] = b * c - a * s
end
dct4Post(plan, out, oi, os, scale or 1)
end
-- forward(plan, x, xi, X, Xi, Xs?, scale?): N samples x[xi ..] -> N / 2 coefficients X[Xi + k * Xs]
function Mdct.forward(plan: Plan, x: { number }, xi: number, out: { number }, oi: number, os: number?, scale: number?)
local q, m = plan.n // 4, plan.m
local h = m // 2 -- N / 4
local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws
-- fold: u[j] = -x[3M/2 - 1 - j] - x[3M/2 + j] (j < M/2), x[j - M/2] - x[3M/2 - 1 - j] (j >= M/2)
local b3 = xi + 3 * h
for p = 0, q - 1 do
local j = 2 * p
local a
if j < h then
a = -x[b3 - 1 - j] - x[b3 + j]
else
a = x[xi + j - h] - x[b3 - 1 - j]
end
j = m - 1 - 2 * p
local b
if j < h then
b = -x[b3 - 1 - j] - x[b3 + j]
else
b = x[xi + j - h] - x[b3 - 1 - j]
end
local c, s = twc[p + 1], tws[p + 1]
re[p + 1] = a * c + b * s
im[p + 1] = b * c - a * s
end
dct4Post(plan, out, oi, os or 1, scale or 1)
end
-- inverse(plan, X, Xi, Xs?, y, yi, scale?): N / 2 coefficients X[Xi + k * Xs] -> N samples y[yi ..] (no window)
function Mdct.inverse(plan: Plan, inp: { number }, ii: number, is: number?, y: { number }, yi: number, scale: number?)
local m = plan.m
local h = m // 2
local c = plan.c
Mdct.dct4(plan, inp, ii, is or 1, c, 1, 1, scale)
-- unfold: y = (C2, -C2 reversed, -C1 reversed, -C1)
for j = 0, h - 1 do
y[yi + j] = c[h + j + 1]
y[yi + h + j] = -c[m - j]
y[yi + m + j] = -c[h - j]
y[yi + 3 * h + j] = -c[j + 1]
end
end
-- ------------------------------------------------------------------------------------------------ windows
local function besselI0(x: number): number
local sum, term = 1, 1
local k = 1
while k < 200 do
term *= (x / (2 * k)) ^ 2
sum += term
if term < sum * 1e-17 then
break
end
k += 1
end
return sum
end
Mdct.besselI0 = besselI0
-- window(kind, N, alpha?) -> N values: "sine" sin(pi (n + 1/2) / N); "kbd" Kaiser-Bessel-derived (alpha: AAC uses 4
-- for long, 6 for short windows); "vorbis" sin(pi / 2 sin^2(pi (n + 1/2) / N)). All satisfy w[n]^2 + w[n + N/2]^2 = 1.
function Mdct.window(kind: string, n: number, alpha: number?): { number }?
if type(n) ~= "number" or n < 2 or n % 2 ~= 0 then
return nil
end
local w = table.create(n, 0)
if kind == "sine" then
for i = 0, n - 1 do
w[i + 1] = sin(pi * (i + 0.5) / n)
end
elseif kind == "vorbis" then
for i = 0, n - 1 do
local s = sin(pi * (i + 0.5) / n)
w[i + 1] = sin(pi / 2 * s * s)
end
elseif kind == "kbd" then
local half = n // 2
local a = alpha or 4
local kais = table.create(half + 1, 0)
local total = 0
for i = 0, half do
local r = 2 * i / half - 1
kais[i + 1] = besselI0(pi * a * sqrt(math.max(0, 1 - r * r)))
total += kais[i + 1]
end
local acc = 0
for i = 0, half - 1 do
acc += kais[i + 1]
local v = sqrt(acc / total)
w[i + 1] = v
w[n - i] = v
end
else
return nil
end
return w
end
-- fft(n) -> an Fft plan (Fft.forward(plan, re, im) transforms in place)
function Mdct.fft(n: number): Fft.Plan?
return Fft.new(n)
end
return Mdct
+308
View File
@@ -0,0 +1,308 @@
--!strict
--!native
--!optimize 2
-- codecs/Pcm/Convert: raw sample formats <-> interleaved f32 (the hot loops of codecs/Pcm). Integers map to
-- v / 2^(bits-1) (as ffmpeg does); encoding rounds to nearest and clips. G.711 A-law / mu-law per ITU-T G.711 (the
-- classic Sun g711.c algorithm, written from the spec).
--
-- Formats: u8 s8 s16le s16be s24le s24be s32le s32be f32le f32be f64le f64be alaw ulaw (u8: offset binary).
-- Never throws: callers check ranges (Convert.SIZE[fmt] * count bytes) before calling.
local Convert = {}
local readu8, readi8, readi16, readi32, readu32 = buffer.readu8, buffer.readi8, buffer.readi16, buffer.readi32, buffer.readu32
local readf32, readf64, writef32, writef64 = buffer.readf32, buffer.readf64, buffer.writef32, buffer.writef64
local writeu8, writeu16, writeu32, writei16, writei32 = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writei16, buffer.writei32
local floor = math.floor
local byteswap = bit32.byteswap
local SIZE: { [string]: number } = {
u8 = 1,
s8 = 1,
s16le = 2,
s16be = 2,
s24le = 3,
s24be = 3,
s32le = 4,
s32be = 4,
f32le = 4,
f32be = 4,
f64le = 8,
f64be = 8,
alaw = 1,
ulaw = 1,
}
Convert.SIZE = SIZE
-- the integer bit depth of each format (float: 32 / 64; G.711: 16 after expansion)
Convert.BITS = {
u8 = 8,
s8 = 8,
s16le = 16,
s16be = 16,
s24le = 24,
s24be = 24,
s32le = 32,
s32be = 32,
f32le = 32,
f32be = 32,
f64le = 64,
f64be = 64,
alaw = 16,
ulaw = 16,
}
-- ------------------------------------------------------------------------------------------------ G.711
local ALAW = table.create(256, 0) -- code -> linear s16
local ULAW = table.create(256, 0)
for code = 0, 255 do
-- A-law
local a = bit32.bxor(code, 0x55)
local t = bit32.band(a, 0x0F) * 16
local seg = bit32.rshift(bit32.band(a, 0x70), 4)
if seg == 0 then
t += 8
elseif seg == 1 then
t += 0x108
else
t = (t + 0x108) * 2 ^ (seg - 1)
end
ALAW[code + 1] = if bit32.band(a, 0x80) ~= 0 then t else -t
-- mu-law
local u = bit32.bxor(code, 0xFF)
local m = (bit32.band(u, 0x0F) * 8 + 0x84) * 2 ^ bit32.rshift(bit32.band(u, 0x70), 4)
ULAW[code + 1] = if bit32.band(u, 0x80) ~= 0 then 0x84 - m else m - 0x84
end
local SEG_AEND = { 0x1F, 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF }
local SEG_UEND = { 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF }
local function segment(v: number, ends: { number }): number
for i = 1, 8 do
if v <= ends[i] then
return i - 1
end
end
return 8
end
-- linear s16 -> A-law code
local function alawEncode(pcm: number): number
local mask
local v = floor(pcm / 8) -- 13-bit magnitude domain
if v >= 0 then
mask = 0xD5
else
mask = 0x55
v = -v - 1
end
local seg = segment(v, SEG_AEND)
local aval
if seg >= 8 then
aval = 0x7F
else
aval = seg * 16
if seg < 2 then
aval += bit32.band(floor(v / 2), 0x0F)
else
aval += bit32.band(floor(v / 2 ^ seg), 0x0F)
end
end
return bit32.bxor(aval, mask)
end
-- linear s16 -> mu-law code
local function ulawEncode(pcm: number): number
local v = floor(pcm / 4) -- 14-bit
local mask
if v < 0 then
v = -v
mask = 0x7F
else
mask = 0xFF
end
if v > 8159 then
v = 8159
end
v += 0x21
local seg = segment(v, SEG_UEND)
local uval
if seg >= 8 then
uval = 0x7F
else
uval = seg * 16 + bit32.band(floor(v / 2 ^ (seg + 1)), 0x0F)
end
return bit32.bxor(uval, mask)
end
Convert.alawEncode = alawEncode
Convert.ulawEncode = ulawEncode
Convert.ALAW = ALAW
Convert.ULAW = ULAW
-- ------------------------------------------------------------------------------------------------ decode
-- decode(src, so, fmt, count, dst, do_) -> true | false (unknown fmt): count samples at src[so] -> f32 at dst[do_]
function Convert.decode(src: buffer, so: number, fmt: string, count: number, dst: buffer, d: number): boolean
if fmt == "s16le" then
for i = 0, count - 1 do
writef32(dst, d + i * 4, readi16(src, so + i * 2) / 32768)
end
elseif fmt == "s16be" then
for i = 0, count - 1 do
local p = so + i * 2
local v = readu8(src, p) * 256 + readu8(src, p + 1)
if v >= 32768 then
v -= 65536
end
writef32(dst, d + i * 4, v / 32768)
end
elseif fmt == "u8" then
for i = 0, count - 1 do
writef32(dst, d + i * 4, (readu8(src, so + i) - 128) / 128)
end
elseif fmt == "s8" then
for i = 0, count - 1 do
writef32(dst, d + i * 4, readi8(src, so + i) / 128)
end
elseif fmt == "s24le" then
for i = 0, count - 1 do
local p = so + i * 3
local v = readu8(src, p) + readu8(src, p + 1) * 256 + readi8(src, p + 2) * 65536
writef32(dst, d + i * 4, v / 8388608)
end
elseif fmt == "s24be" then
for i = 0, count - 1 do
local p = so + i * 3
local v = readi8(src, p) * 65536 + readu8(src, p + 1) * 256 + readu8(src, p + 2)
writef32(dst, d + i * 4, v / 8388608)
end
elseif fmt == "s32le" then
for i = 0, count - 1 do
writef32(dst, d + i * 4, readi32(src, so + i * 4) / 2147483648)
end
elseif fmt == "s32be" then
for i = 0, count - 1 do
local v = byteswap(readu32(src, so + i * 4))
if v >= 2147483648 then
v -= 4294967296
end
writef32(dst, d + i * 4, v / 2147483648)
end
elseif fmt == "f32le" then
buffer.copy(dst, d, src, so, count * 4)
elseif fmt == "f32be" then
for i = 0, count - 1 do
writeu32(dst, d + i * 4, byteswap(readu32(src, so + i * 4)))
end
elseif fmt == "f64le" then
for i = 0, count - 1 do
writef32(dst, d + i * 4, readf64(src, so + i * 8))
end
elseif fmt == "f64be" then
local tmp = buffer.create(8)
for i = 0, count - 1 do
local p = so + i * 8
writeu32(tmp, 0, byteswap(readu32(src, p + 4)))
writeu32(tmp, 4, byteswap(readu32(src, p)))
writef32(dst, d + i * 4, readf64(tmp, 0))
end
elseif fmt == "alaw" then
for i = 0, count - 1 do
writef32(dst, d + i * 4, ALAW[readu8(src, so + i) + 1] / 32768)
end
elseif fmt == "ulaw" then
for i = 0, count - 1 do
writef32(dst, d + i * 4, ULAW[readu8(src, so + i) + 1] / 32768)
end
else
return false
end
return true
end
-- ------------------------------------------------------------------------------------------------ encode
local function q(x: number, s: number): number
local v = floor(x * s + 0.5)
if v ~= v then
return 0
end
if v >= s then
return s - 1
elseif v < -s then
return -s
end
return v
end
-- encode(src, so, count, fmt, dst, do_) -> true | false: count f32 samples at src[so] -> fmt at dst[do_]
function Convert.encode(src: buffer, so: number, count: number, fmt: string, dst: buffer, d: number): boolean
if fmt == "s16le" then
for i = 0, count - 1 do
writei16(dst, d + i * 2, q(readf32(src, so + i * 4), 32768))
end
elseif fmt == "s16be" then
for i = 0, count - 1 do
local v = q(readf32(src, so + i * 4), 32768) % 65536
writeu16(dst, d + i * 2, (v % 256) * 256 + v // 256)
end
elseif fmt == "u8" then
for i = 0, count - 1 do
writeu8(dst, d + i, q(readf32(src, so + i * 4), 128) + 128)
end
elseif fmt == "s8" then
for i = 0, count - 1 do
writeu8(dst, d + i, q(readf32(src, so + i * 4), 128) % 256)
end
elseif fmt == "s24le" then
for i = 0, count - 1 do
local v = q(readf32(src, so + i * 4), 8388608) % 16777216
local p = d + i * 3
writeu8(dst, p, v % 256)
writeu8(dst, p + 1, (v // 256) % 256)
writeu8(dst, p + 2, v // 65536)
end
elseif fmt == "s24be" then
for i = 0, count - 1 do
local v = q(readf32(src, so + i * 4), 8388608) % 16777216
local p = d + i * 3
writeu8(dst, p, v // 65536)
writeu8(dst, p + 1, (v // 256) % 256)
writeu8(dst, p + 2, v % 256)
end
elseif fmt == "s32le" then
for i = 0, count - 1 do
writei32(dst, d + i * 4, q(readf32(src, so + i * 4), 2147483648))
end
elseif fmt == "s32be" then
for i = 0, count - 1 do
writeu32(dst, d + i * 4, byteswap(q(readf32(src, so + i * 4), 2147483648) % 4294967296))
end
elseif fmt == "f32le" then
buffer.copy(dst, d, src, so, count * 4)
elseif fmt == "f32be" then
for i = 0, count - 1 do
writeu32(dst, d + i * 4, byteswap(readu32(src, so + i * 4)))
end
elseif fmt == "f64le" then
for i = 0, count - 1 do
writef64(dst, d + i * 8, readf32(src, so + i * 4))
end
elseif fmt == "f64be" then
local tmp = buffer.create(8)
for i = 0, count - 1 do
writef64(tmp, 0, readf32(src, so + i * 4))
local p = d + i * 8
writeu32(dst, p, byteswap(readu32(tmp, 4)))
writeu32(dst, p + 4, byteswap(readu32(tmp, 0)))
end
elseif fmt == "alaw" then
for i = 0, count - 1 do
writeu8(dst, d + i, alawEncode(q(readf32(src, so + i * 4), 32768)))
end
elseif fmt == "ulaw" then
for i = 0, count - 1 do
writeu8(dst, d + i, ulawEncode(q(readf32(src, so + i * 4), 32768)))
end
else
return false
end
return true
end
return Convert
+234
View File
@@ -0,0 +1,234 @@
--!strict
-- codecs/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources.
-- An encoder accepts a Types.Audio (fully decoded) or a Types.Decoder (streamed); Pcm.source turns either into one
-- pull interface, so encoders stream in blocks without caring which they got. Uncompressed containers (aiff, au,
-- voc, ...) get their Decoder from Pcm.rawDecoder (over a sample region of the file) or Pcm.audioDecoder.
--
-- local src, err = Pcm.source(audioOrDecoder) -- nil, Err.ARG for anything else
-- local buf, n = src:read(4096) -- interleaved f32, n frames (0 at the end), like Decoder:read
-- local audio = Pcm.collect(src) -- read everything into a Types.Audio
-- local dec = Pcm.rawDecoder(buf, offset, frames, channels, rate, "s16be", tags?) -- a Types.Decoder
-- local dec = Pcm.audioDecoder(audio) -- a Types.Decoder over a decoded Audio
-- local raw = Pcm.encode(src, "s24le", writer) -- every frame of src appended to a core/Bytes Writer
-- Pcm.Convert.decode / encode / SIZE / BITS -- the raw sample loops (codecs/Pcm/Convert)
-- local s16 = Pcm.toInt(x, 16) -- round, clip to [-32768, 32767]
-- local x = Pcm.fromInt(s16, 16) -- s / 32768
--
-- Sample formats: u8 s8 s16le s16be s24le s24be s32le s32be f32le f32be f64le f64be alaw ulaw.
-- Never throws (a decoder's read that throws is caught and ends the stream).
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Convert = require("@formats/codecs/Pcm/Convert")
local Pcm = {}
Pcm.Convert = Convert
export type Source = {
sampleRate: number,
channels: number,
frames: number, -- total frames, 0 = unknown (a streaming decoder without an index)
tags: Types.Tags,
-- read(n, out?) -> interleaved f32 buffer, frames read (0 at the end)
read: (self: Source, n: number, out: buffer?) -> (buffer, number),
err: Err.Err?, -- set when the underlying decoder failed mid-stream
}
local function audioRead(self: any, n: number, out: buffer?): (buffer, number)
local a = self._audio
local ch = a.channels
local left = a.frames - self._pos
if n > left then
n = left
end
if n <= 0 then
return out or buffer.create(0), 0
end
local bytes = n * ch * 4
local b = if out and buffer.len(out) >= bytes then out else buffer.create(bytes)
buffer.copy(b, 0, a.samples, self._pos * ch * 4, bytes)
self._pos += n
return b, n
end
local function decoderRead(self: any, n: number, out: buffer?): (buffer, number)
if self._done then
return out or buffer.create(0), 0
end
local ok, b, got = pcall(self._dec.read, self._dec, n, out)
if not ok then
self._done = true
self.err = Err.new(Err.CORRUPT, "source decoder failed: " .. tostring(b))
return out or buffer.create(0), 0
end
if type(b) ~= "buffer" or type(got) ~= "number" or got <= 0 then
self._done = true
return out or buffer.create(0), 0
end
local ch = self.channels
if buffer.len(b) < got * ch * 4 then
got = buffer.len(b) // (ch * 4)
end
return b, got
end
-- source(v) -> Source | nil, Err.ARG: v is a Types.Audio or a Types.Decoder (anything with sampleRate, channels, read)
function Pcm.source(v: any): (Source?, Err.Err?)
if type(v) ~= "table" then
return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder")
end
local sr, ch = v.sampleRate, v.channels
if type(sr) ~= "number" or sr <= 0 or sr ~= sr or type(ch) ~= "number" or ch < 1 or ch ~= math.floor(ch) then
return nil, Err.new(Err.ARG, "bad sampleRate or channels")
end
if v.kind == "audio" and type(v.samples) == "buffer" then
local frames = v.frames
if type(frames) ~= "number" or frames < 0 or buffer.len(v.samples) < frames * ch * 4 then
return nil, Err.new(Err.ARG, "the Audio's samples buffer is shorter than frames * channels * 4")
end
return { sampleRate = sr, channels = ch, frames = frames, tags = v.tags or {}, read = audioRead, _audio = v, _pos = 0 } :: any, nil
end
if type(v.read) == "function" then
local frames = if type(v.frames) == "number" and v.frames > 0 then v.frames else 0
return { sampleRate = sr, channels = ch, frames = frames, tags = v.tags or {}, read = decoderRead, _dec = v, _done = false } :: any, nil
end
return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder")
end
-- collect(src, maxFrames?) -> Types.Audio | nil, Err (everything the source has; Err.LIMIT past maxFrames)
function Pcm.collect(src: Source, maxFrames: number?): (Types.Audio?, Err.Err?)
local ch = src.channels
local cap = math.max(src.frames, 4096)
local data = buffer.create(cap * ch * 4)
local total = 0
local limit = maxFrames or 2 ^ 31
local tmp: buffer? = nil
while true do
local b, n = src:read(16384, tmp)
if n <= 0 then
break
end
tmp = b
if total + n > limit then
return nil, Err.new(Err.LIMIT, string.format("more than %d frames", limit))
end
if total + n > cap then
cap = math.max(cap * 2, total + n)
local nd = buffer.create(cap * ch * 4)
buffer.copy(nd, 0, data, 0, total * ch * 4)
data = nd
end
buffer.copy(data, total * ch * 4, b, 0, n * ch * 4)
total += n
end
if src.err then
return nil, src.err
end
local a = Types.Audio.new(src.sampleRate, ch, 0)
a.frames = total
if buffer.len(data) == total * ch * 4 then
a.samples = data
else
a.samples = buffer.create(total * ch * 4)
buffer.copy(a.samples, 0, data, 0, total * ch * 4)
end
a.tags = table.clone(src.tags)
return a, nil
end
-- ------------------------------------------------------------------------------------------------ decoders
-- rawDecoder(buf, offset, frames, channels, sampleRate, fmt, tags?) -> Types.Decoder | nil, Err.ARG: a streaming
-- decoder over frames * channels samples of fmt at buf[offset] (the caller has checked the range is inside buf)
function Pcm.rawDecoder(buf: buffer, offset: number, frames: number, channels: number, sampleRate: number, fmt: string, tags: Types.Tags?): (Types.Decoder?, Err.Err?)
local size = Convert.SIZE[fmt]
if not size then
return nil, Err.new(Err.ARG, "unknown sample format " .. tostring(fmt))
end
if channels < 1 or sampleRate <= 0 or frames < 0 or offset < 0 or offset + frames * channels * size > buffer.len(buf) then
return nil, Err.new(Err.ARG, "bad raw PCM layout")
end
local pos = 0
local frameBytes = channels * size
local dec = {
sampleRate = sampleRate,
channels = channels,
frames = frames,
duration = frames / sampleRate,
bitrate = sampleRate * frameBytes * 8,
tags = tags or {},
}
function dec.read(_self: any, n: number, out: buffer?): (buffer, number)
n = math.clamp(math.floor(n), 0, frames - pos)
local bytes = n * channels * 4
local b = if out and buffer.len(out) >= bytes then out else buffer.create(bytes)
if n > 0 then
Convert.decode(buf, offset + pos * frameBytes, fmt, n * channels, b, 0)
pos += n
end
return b, n
end
function dec.seek(_self: any, seconds: number)
local f = math.floor(seconds * sampleRate + 0.5)
pos = if f ~= f then 0 else math.clamp(f, 0, frames)
end
function dec.position(_self: any): number
return pos / sampleRate
end
return dec :: any, nil
end
-- audioDecoder(audio) -> Types.Decoder over a decoded Audio (no copy of the samples)
function Pcm.audioDecoder(a: Types.Audio): Types.Decoder
local d = Pcm.rawDecoder(a.samples, 0, a.frames, a.channels, a.sampleRate, "f32le", a.tags) :: any
d.bitrate = a.sampleRate * a.channels * 32
return d
end
-- encode(src, fmt, w) -> frames written | nil, Err: drains src into the Writer w as fmt samples
function Pcm.encode(src: Source, fmt: string, w: Bytes.Writer): (number?, Err.Err?)
local size = Convert.SIZE[fmt]
if not size then
return nil, Err.new(Err.ARG, "unknown sample format " .. tostring(fmt))
end
local ch = src.channels
local total = 0
local tmp: buffer? = nil
while true do
local b, n = src:read(8192, tmp)
if n <= 0 then
break
end
tmp = b
local at = w:reserve(n * ch * size)
Convert.encode(b, 0, n * ch, fmt, w.buf, at)
w.pos = at + n * ch * size
total += n
end
if src.err then
return nil, src.err
end
return total, nil
end
-- ------------------------------------------------------------------------------------------------ conversions
-- toInt(x, bits) -> the nearest bits-wide signed integer to x * 2^(bits-1), clipped (NaN -> 0)
function Pcm.toInt(x: number, bits: number): number
local s = 2 ^ (bits - 1)
local v = math.floor(x * s + 0.5)
if v ~= v then
return 0
end
if v >= s then
return s - 1
elseif v < -s then
return -s
end
return v
end
-- fromInt(v, bits) -> v / 2^(bits-1)
function Pcm.fromInt(v: number, bits: number): number
return v / 2 ^ (bits - 1)
end
return Pcm
+149
View File
@@ -0,0 +1,149 @@
--!strict
-- codecs/SoundFont/Fallback: the built-in General MIDI set used when no SoundFont is given. A generated SoundFont
-- (the same shape Parse returns, so the same synth plays it): single-cycle sine / triangle / square / saw waves and a
-- looped noise sample, one preset per GM family of 8 programs (piano, chromatic percussion, organ, guitar, bass,
-- strings, ensemble, brass, reed, pipe, lead, pad, synth fx, ethnic, percussive, sound fx) with family envelopes,
-- filters and vibrato, plus a drum kit on bank 128 (pitch-swept sine kicks and toms, filtered noise snares, hats with
-- an exclusive class, cymbals). Written for this library (no third-party code).
local Parse = require("@formats/codecs/SoundFont/Parse")
local Fallback = {}
local CYCLE = 256
local NOISE = 32768
local C4 = 261.6255653005986
local function hzToCents(hz: number): number
return 1200 * math.log(hz / 8.176, 2)
end
local cached: any = nil
-- build() -> a SoundFont value (kind "soundfont"); built once, shared (the synth never writes to it)
function Fallback.build(): any
if cached then
return cached
end
local waves = { "sine", "triangle", "square", "saw" }
local count = #waves * CYCLE + NOISE
local samples = buffer.create((count + 1) * 4)
local starts: { [string]: number } = {}
for w, name in waves do
local base = (w - 1) * CYCLE
starts[name] = base
for i = 0, CYCLE - 1 do
local ph = i / CYCLE
local v
if name == "sine" then
v = math.sin(2 * math.pi * ph)
elseif name == "triangle" then
v = if ph < 0.25 then 4 * ph elseif ph < 0.75 then 2 - 4 * ph else 4 * ph - 4
elseif name == "square" then
v = if ph < 0.5 then 0.6 else -0.6
else
v = (1 - 2 * ph) * 0.7
end
buffer.writef32(samples, (base + i) * 4, v)
end
end
local noiseStart = #waves * CYCLE
starts.noise = noiseStart
local seed = 12345
for i = 0, NOISE - 1 do
seed = (seed * 1103515245 + 12345) % 2147483648
buffer.writef32(samples, (noiseStart + i) * 4, (seed / 1073741824 - 1) * 0.7)
end
local function region(wave: string, fields: { [string]: number }): { [string]: number }
local r = Parse.defaultRegion()
local s = starts[wave]
r.offset = s
r.loopMode = 1
r.loopStart = s
if wave == "noise" then
r.stop, r.loopEnd, r.sampleRate, r.keycenter = s + NOISE, s + NOISE - 1, 44100, 60
else
r.stop, r.loopEnd, r.sampleRate, r.keycenter = s + CYCLE, s + CYCLE - 1, CYCLE * C4, 60
end
r.aRelease = 0.08
for k, v in fields do
r[k] = v
end
return r
end
-- the 16 GM families: wave + envelope / filter / vibrato
local families: { { any } } = {
{ "piano", "triangle", { aDecay = 2.5, aSustain = 0, aRelease = 0.25 } },
{ "chromatic", "sine", { aDecay = 1.2, aSustain = 0, aRelease = 0.3 } },
{ "organ", "square", { aAttack = 0.005, aRelease = 0.05, filterFc = hzToCents(5000) } },
{ "guitar", "saw", { aDecay = 1.5, aSustain = 0, aRelease = 0.15, filterFc = hzToCents(3000) } },
{ "bass", "triangle", { aDecay = 1.5, aSustain = 0.4, aRelease = 0.1 } },
{ "strings", "saw", { aAttack = 0.08, aRelease = 0.3, filterFc = hzToCents(4000), freqVibLFO = hzToCents(5.5), vibLfoToPitch = 8, delayVibLFO = 0.2 } },
{ "ensemble", "saw", { aAttack = 0.12, aRelease = 0.4, filterFc = hzToCents(3500), freqVibLFO = hzToCents(5), vibLfoToPitch = 10 } },
{ "brass", "saw", { aAttack = 0.03, aRelease = 0.12, filterFc = hzToCents(1200), mAttack = 0.05, mDecay = 0.3, mSustain = 0.4, modEnvToFilterFc = 2400 } },
{ "reed", "square", { aAttack = 0.02, aRelease = 0.08, filterFc = hzToCents(2500) } },
{ "pipe", "sine", { aAttack = 0.04, aRelease = 0.12, freqVibLFO = hzToCents(5), vibLfoToPitch = 12, delayVibLFO = 0.3 } },
{ "lead", "square", { aAttack = 0.005, aRelease = 0.1, filterFc = hzToCents(6000) } },
{ "pad", "saw", { aAttack = 0.4, aRelease = 0.8, filterFc = hzToCents(1800), freqModLFO = hzToCents(0.5), modLfoToFilterFc = 600 } },
{ "synthfx", "triangle", { aAttack = 0.2, aRelease = 1.0, freqModLFO = hzToCents(3), modLfoToVolume = 60 } },
{ "ethnic", "saw", { aDecay = 1.0, aSustain = 0, aRelease = 0.2, filterFc = hzToCents(3000) } },
{ "percussive", "sine", { aDecay = 0.4, aSustain = 0, aRelease = 0.1, mDecay = 0.1, mSustain = 0, modEnvToPitch = 1200 } },
{ "sfx", "noise", { aAttack = 0.05, aRelease = 0.5, filterFc = hzToCents(3000) } },
}
local presets = {}
for program = 0, 127 do
local f = families[program // 8 + 1]
table.insert(presets, { name = "fallback " .. f[1], preset = program, bank = 0, regions = { region(f[2], f[3]) } })
end
-- the drum kit (bank 128, every program): one region per key
local kit = {}
-- fields.semis: the pitch (semitones from the sample's natural pitch) at keytrack 0
local function drum(lo: number, hi: number, wave: string, fields: { [string]: number })
local r = region(wave, fields)
r.lokey, r.hikey = lo, hi
r.sampleRate *= 2 ^ ((fields.semis or 0) / 12)
r.semis = nil :: any
table.insert(kit, r)
end
local sweep = { mDecay = 0.06, mSustain = 0, modEnvToPitch = 2400 }
local function with(a: { [string]: number }, b: { [string]: number }): { [string]: number }
local c = table.clone(a)
for k, v in b do
c[k] = v
end
return c
end
drum(0, 34, "noise", { aDecay = 0.1, aSustain = 0, keytrack = 0, filterFc = hzToCents(4000) })
drum(35, 36, "sine", with(sweep, { aDecay = 0.35, aSustain = 0, aRelease = 0.05, keytrack = 0, semis = -26 }))
drum(37, 37, "noise", { aDecay = 0.05, aSustain = 0, keytrack = 0, filterFc = hzToCents(5000) })
drum(38, 38, "noise", { aDecay = 0.2, aSustain = 0, keytrack = 0, filterFc = hzToCents(6000) })
drum(39, 39, "noise", { aDecay = 0.15, aSustain = 0, keytrack = 0, filterFc = hzToCents(8000) })
drum(40, 40, "noise", { aDecay = 0.18, aSustain = 0, keytrack = 0, filterFc = hzToCents(7000) })
for _, k in { 41, 43, 45, 47, 48, 50 } do
drum(k, k, "sine", with(sweep, { aDecay = 0.4, aSustain = 0, semis = (k - 41) - 12, keytrack = 0 }))
end
drum(42, 42, "noise", { aDecay = 0.05, aSustain = 0, group = 1, keytrack = 0, semis = 12 })
drum(44, 44, "noise", { aDecay = 0.08, aSustain = 0, group = 1, keytrack = 0, semis = 12 })
drum(46, 46, "noise", { aDecay = 0.45, aSustain = 0, group = 1, keytrack = 0, semis = 12 })
drum(49, 49, "noise", { aDecay = 1.5, aSustain = 0, keytrack = 0, semis = 7 })
drum(51, 51, "noise", { aDecay = 1.0, aSustain = 0, keytrack = 0, semis = 10, filterFc = hzToCents(9000) })
drum(52, 59, "noise", { aDecay = 1.2, aSustain = 0, keytrack = 0, semis = 5 })
drum(60, 127, "noise", { aDecay = 0.12, aSustain = 0, keytrack = 30, filterFc = hzToCents(5000) })
table.insert(presets, { name = "fallback drums", preset = 0, bank = 128, regions = kit })
cached = {
kind = "soundfont",
info = { name = "formats-luau fallback" },
samples = samples,
sampleCount = count,
presets = presets,
sampleHeaders = {},
instruments = {},
meta = { source = { format = "fallback" } },
}
return cached
end
return Fallback
+523
View File
@@ -0,0 +1,523 @@
--!strict
-- codecs/SoundFont/Parse: SoundFont 2.0x (sfbk RIFF) reader. The INFO list, the sdta samples (smpl 16-bit, + sm24
-- when present) as one f32 buffer, and the pdta "hydra" (phdr pbag pmod pgen inst ibag imod igen shdr), flattened
-- into playable regions per preset: the instrument global zone, the preset global zone and the preset zone's
-- generators merged the way TinySoundFont (tsf.h v0.9, MIT, (c) Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt)
-- does (tsf_load_presets / tsf_region_operator / tsf_region_envtosecs), with every index and sample offset clamped
-- so the synth never reads outside the sample buffer.
-- Differences from tsf.h: initialAttenuation is cB * 0.04 dB (FluidSynth's EMU-compatible scale; tsf uses 0.01);
-- SF3 (Ogg samples) is not supported; modulators (pmod / imod) are read but not applied (as in tsf.h).
-- Never throws: a bad file returns nil, Err.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Parse = {}
-- a region (one sample zone of a preset), in "absolute" form: envelope / LFO times in seconds, sustain as a level
export type Region = { [string]: number }
export type Preset = { name: string, preset: number, bank: number, regions: { Region } }
export type SoundFont = {
kind: "soundfont",
info: { [string]: string },
samples: buffer, -- f32 mono, sampleCount + 1 floats (a zero pad sample past the end)
sampleCount: number,
presets: { Preset }, -- sorted by bank, then preset number
sampleHeaders: { { [string]: any } },
instruments: { { name: string, zones: number } },
meta: { [string]: any },
}
local GEN_INSTRUMENT, GEN_SAMPLEID = 41, 53
-- generator op -> { field, mode, limit }. modes: f / i (value, merged by adding then clamping), a (sample address
-- add), a15 (coarse address add: * 32768), kr / vr (key / velocity range), loop, group, key (overriding root key)
local LIM12K5K = { 1, -12000, 5000 }
local LIM12K8K = { 1, -12000, 8000 }
local LIM1200 = { 1, -1200, 1200 }
local GEN: { [number]: { any } } = {
[0] = { "offset", "a" },
[1] = { "stop", "a" },
[2] = { "loopStart", "a" },
[3] = { "loopEnd", "a" },
[4] = { "offset", "a15" },
[5] = { "modLfoToPitch", "i", { 1, -12000, 12000 } },
[6] = { "vibLfoToPitch", "i", { 1, -12000, 12000 } },
[7] = { "modEnvToPitch", "i", { 1, -12000, 12000 } },
[8] = { "filterFc", "i", { 1, 1500, 13500 } },
[9] = { "filterQ", "i", { 1, 0, 960 } },
[10] = { "modLfoToFilterFc", "i", { 1, -12000, 12000 } },
[11] = { "modEnvToFilterFc", "i", { 1, -12000, 12000 } },
[12] = { "stop", "a15" },
[13] = { "modLfoToVolume", "i", { 1, -960, 960 } },
[17] = { "pan", "f", { 0.001, -0.5, 0.5 } },
[21] = { "delayModLFO", "f", LIM12K5K },
[22] = { "freqModLFO", "i", { 1, -16000, 4500 } },
[23] = { "delayVibLFO", "f", LIM12K5K },
[24] = { "freqVibLFO", "i", { 1, -16000, 4500 } },
[25] = { "mDelay", "f", LIM12K5K },
[26] = { "mAttack", "f", LIM12K8K },
[27] = { "mHold", "f", LIM12K5K },
[28] = { "mDecay", "f", LIM12K8K },
[29] = { "mSustain", "f", { 1, 0, 1000 } },
[30] = { "mRelease", "f", LIM12K8K },
[31] = { "mKeyHold", "f", LIM1200 },
[32] = { "mKeyDecay", "f", LIM1200 },
[33] = { "aDelay", "f", LIM12K5K },
[34] = { "aAttack", "f", LIM12K8K },
[35] = { "aHold", "f", LIM12K5K },
[36] = { "aDecay", "f", LIM12K8K },
[37] = { "aSustain", "f", { 1, 0, 1440 } },
[38] = { "aRelease", "f", LIM12K8K },
[39] = { "aKeyHold", "f", LIM1200 },
[40] = { "aKeyDecay", "f", LIM1200 },
[43] = { "", "kr" },
[44] = { "", "vr" },
[45] = { "loopStart", "a15" },
[48] = { "attenuation", "f", { 0.04, 0, 57.6 } },
[50] = { "loopEnd", "a15" },
[51] = { "transpose", "i" },
[52] = { "tune", "i" },
[54] = { "loopMode", "loop" },
[56] = { "keytrack", "i" },
[57] = { "group", "group" },
[58] = { "keycenter", "key" },
}
-- the merged fields: value generators once each (several ops share a field), then the four address fields
local MERGE: { { any } } = {}
do
local seen: { [string]: boolean } = {}
for op = 0, 58 do
local g = GEN[op]
if g and (g[2] == "f" or g[2] == "i" or g[2] == "a") and not seen[g[1]] then
seen[g[1]] = true
table.insert(MERGE, g)
end
end
end
local FIELDS = {
"loopMode", "sampleRate", "lokey", "hikey", "lovel", "hivel", "group", "offset", "stop", "loopStart", "loopEnd",
"transpose", "tune", "keycenter", "keytrack", "attenuation", "pan", "filterQ", "filterFc", "modEnvToPitch",
"modEnvToFilterFc", "modLfoToFilterFc", "modLfoToVolume", "delayModLFO", "freqModLFO", "modLfoToPitch",
"delayVibLFO", "freqVibLFO", "vibLfoToPitch", "aDelay", "aAttack", "aHold", "aDecay", "aSustain", "aRelease",
"aKeyHold", "aKeyDecay", "mDelay", "mAttack", "mHold", "mDecay", "mSustain", "mRelease", "mKeyHold", "mKeyDecay",
"sampleIndex",
}
-- clear(relative): tsf_region_clear. relative = a preset zone (all zero: values add to the instrument's)
local function clear(relative: boolean): Region
local r: Region = {}
for _, f in FIELDS do
r[f] = 0
end
r.hikey, r.hivel, r.keycenter = 127, 127, 60
if relative then
return r
end
r.keytrack = 100
r.keycenter = -1
for _, p in { "a", "m" } do
for _, s in { "Delay", "Attack", "Hold", "Decay", "Release" } do
r[p .. s] = -12000
end
end
r.filterFc = 13500
r.delayModLFO, r.delayVibLFO = -12000, -12000
return r
end
local function copy(r: Region): Region
local c: Region = {}
for k, v in r do
c[k] = v
end
return c
end
-- the region defaults in absolute form (seconds, levels): what Fallback builds its regions from
function Parse.defaultRegion(): Region
local r = clear(false)
r.keycenter = 60
for _, p in { "a", "m" } do
for _, s in { "Delay", "Attack", "Hold", "Decay", "Release" } do
r[p .. s] = 0
end
end
r.aSustain, r.mSustain = 1, 1
r.delayModLFO, r.delayVibLFO = 0, 0
return r
end
-- set one generator (tsf_region_operator with an amount); lo / hi = the two bytes, s = signed 16, w = unsigned 16
local function operator(r: Region, op: number, lo: number, hi: number, s: number, w: number)
local g = GEN[op]
if not g then
return
end
local mode = g[2]
if mode == "f" or mode == "i" then
r[g[1]] = s
elseif mode == "a" then
r[g[1]] += s
elseif mode == "a15" then
r[g[1]] += s * 32768
elseif mode == "kr" then
r.lokey, r.hikey = lo, hi
elseif mode == "vr" then
r.lovel, r.hivel = lo, hi
elseif mode == "loop" then
local m = w % 4
r.loopMode = if m == 3 then 2 elseif m == 1 then 1 else 0
elseif mode == "group" then
r.group = w
elseif mode == "key" then
r.keycenter = s
end
end
-- merge(zone, preset): zone += preset, then clamp (tsf_region_operator without an amount)
local function merge(z: Region, p: Region)
for _, g in MERGE do
local f = g[1]
local v = z[f] + p[f]
local lim = g[3]
if lim then
v *= lim[1]
v = math.clamp(v, lim[2], lim[3])
end
z[f] = v
end
end
local function tc2s(tc: number): number
return 2 ^ (tc / 1200)
end
-- envtosecs (tsf_region_envtosecs): timecents to seconds; hold / decay stay in timecents when they scale by key
local function envToSecs(r: Region, p: string, sustainIsGain: boolean)
for _, s in { "Delay", "Attack", "Release" } do
local v = r[p .. s]
r[p .. s] = if v < -11950 then 0 else tc2s(v)
end
if r[p .. "KeyHold"] == 0 then
local v = r[p .. "Hold"]
r[p .. "Hold"] = if v < -11950 then 0 else tc2s(v)
end
if r[p .. "KeyDecay"] == 0 then
local v = r[p .. "Decay"]
r[p .. "Decay"] = if v < -11950 then 0 else tc2s(v)
end
local sus = r[p .. "Sustain"]
if sus < 0 then
sus = 0
elseif sustainIsGain then
sus = if -sus / 10 > -100 then 10 ^ (-sus / 10 * 0.05) else 0
else
sus = 1 - sus / 1000
end
r[p .. "Sustain"] = sus
end
-- ------------------------------------------------------------------------------------------------ RIFF
type Hydra = { [string]: { { number } } }
-- record layouts: field byte widths (2 / 4 = little endian unsigned, -2 signed, 20 = name, 1 = byte, -1 = signed byte)
local LAYOUT: { [string]: { number } } = {
phdr = { 20, 2, 2, 2, 4, 4, 4 },
pbag = { 2, 2 },
pmod = { 2, 2, -2, 2, 2 },
pgen = { 2, 2 },
inst = { 20, 2 },
ibag = { 2, 2 },
imod = { 2, 2, -2, 2, 2 },
igen = { 2, 2 },
shdr = { 20, 4, 4, 4, 4, 4, 1, -1, 2, 2 },
}
local RECSIZE: { [string]: number } = { phdr = 38, pbag = 4, pmod = 10, pgen = 4, inst = 22, ibag = 4, imod = 10, igen = 4, shdr = 46 }
local INFO_NAMES = {
isng = "engine", INAM = "name", irom = "rom", ICRD = "date", IENG = "author", IPRD = "product",
ICOP = "copyright", ICMT = "comment", ISFT = "software",
}
export type Options = { maxRegions: number?, maxSamples: number? }
-- parse(r, opts?) -> SoundFont | nil, Err
function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?)
local maxRegions = opts and opts.maxRegions or 1000000
local maxSamples = opts and opts.maxSamples or 2 ^ 28
if r:string(4) ~= "RIFF" then
return r:fail(Err.CORRUPT, "not a RIFF file")
end
local riffSize = r:u32le()
if r:string(4) ~= "sfbk" then
return r:fail(Err.CORRUPT, "not a SoundFont (no sfbk)")
end
if r.err then
return nil, r.err
end
local body = r:sub(12, math.max(0, riffSize - 4))
local info: { [string]: string } = {}
local hydra: Hydra = {}
local smpl: Bytes.Reader? = nil
local sm24: Bytes.Reader? = nil
local version = ""
while body:remaining() >= 8 do
local id, size = body:string(4), body:u32le()
local chunk = body:slice(size)
if size % 2 == 1 and body:remaining() > 0 then
body:skip(1)
end
if id == "LIST" and chunk:remaining() >= 4 then
local kind = chunk:string(4)
while chunk:remaining() >= 8 do
local sid, ssize = chunk:string(4), chunk:u32le()
local sub = chunk:slice(ssize)
if ssize % 2 == 1 and chunk:remaining() > 0 then
chunk:skip(1)
end
if kind == "INFO" then
if sid == "ifil" and sub:remaining() >= 4 then
local major, minor = sub:u16le(), sub:u16le()
version = string.format("%d.%02d", major, minor)
elseif INFO_NAMES[sid] then
info[INFO_NAMES[sid]] = sub:fixed(sub:remaining())
end
elseif kind == "sdta" then
if sid == "smpl" and not smpl then
smpl = sub
elseif sid == "sm24" then
sm24 = sub
end
elseif kind == "pdta" then
local layout = LAYOUT[sid]
if layout and not hydra[sid] then
local rs = RECSIZE[sid]
local n = sub:remaining() // rs
local recs: { { number } } = table.create(n)
for i = 1, n do
local rec = {}
for _, w in layout do
if w == 20 then
table.insert(rec, 0) -- the name is read separately
sub:skip(20)
elseif w == 4 then
table.insert(rec, sub:u32le())
elseif w == 2 then
table.insert(rec, sub:u16le())
elseif w == -2 then
table.insert(rec, sub:i16le())
elseif w == 1 then
table.insert(rec, sub:u8())
else
table.insert(rec, sub:i8())
end
end
recs[i] = rec
end
hydra[sid] = recs
if sid == "phdr" or sid == "inst" or sid == "shdr" then
local names = table.create(n)
for i = 0, n - 1 do
names[i + 1] = sub:sub(i * rs, 20):fixed(20)
end
hydra[sid .. "Names"] = names :: any
end
end
end
end
end
end
if not smpl then
return nil, Err.new(Err.CORRUPT, "no sample data (sdta smpl)")
end
for _, k in { "phdr", "pbag", "pgen", "inst", "ibag", "igen", "shdr" } do
if not hydra[k] or #hydra[k] == 0 then
return nil, Err.new(Err.CORRUPT, "incomplete hydra: no " .. k .. " records")
end
end
-- samples
local sr = smpl :: Bytes.Reader
local count = sr:remaining() // 2
if count > maxSamples then
return nil, Err.new(Err.LIMIT, string.format("%d samples is over the %d sample limit", count, maxSamples))
end
local samples = buffer.create((count + 1) * 4)
do
local b, p = sr.buf, sr.pos
local readi16, writef32 = buffer.readi16, buffer.writef32
local s24 = sm24
if s24 and s24:remaining() >= count then
local q = s24.pos
local readu8 = buffer.readu8
for i = 0, count - 1 do
writef32(samples, i * 4, (readi16(b, p + i * 2) * 256 + readu8(s24.buf, q + i)) / 8388607)
end
else
s24 = nil
for i = 0, count - 1 do
writef32(samples, i * 4, readi16(b, p + i * 2) / 32767)
end
end
sm24 = s24
end
-- presets (tsf_load_presets)
local phdr, pbag, pgen = hydra.phdr, hydra.pbag, hydra.pgen
local inst, ibag, igen, shdr = hydra.inst, hydra.ibag, hydra.igen, hydra.shdr
local phdrNames, instNames, shdrNames = (hydra :: any).phdrNames, (hydra :: any).instNames, (hydra :: any).shdrNames
local nInst = #inst - 1 -- the last record of each list is the terminal one
local nShdr = #shdr - 1
local function range(list: { { number } }, i: number, field: number, limit: number): (number, number)
-- [list[i][field], list[i + 1][field]) clamped to [1, limit] (1-based record indexes)
local a = list[i][field] + 1
local b = if list[i + 1] then list[i + 1][field] + 1 else a
return math.max(1, a), math.min(b, limit + 1)
end
local presets: { Preset } = {}
local regionTotal = 0
for pi = 1, #phdr - 1 do
local ph = phdr[pi]
local preset: Preset = { name = phdrNames[pi], preset = ph[2], bank = ph[3], regions = {} }
local globalRegion = clear(true)
local b0, b1 = range(phdr, pi, 4, #pbag)
for bi = b0, b1 - 1 do
local presetRegion = copy(globalRegion)
local hadInstrument = false
local g0, g1 = range(pbag, bi, 1, #pgen)
for gi = g0, g1 - 1 do
local pg = pgen[gi]
local op, amount = pg[1], pg[2]
local lo, hi = amount % 256, amount // 256
local s = if amount >= 32768 then amount - 65536 else amount
if op == GEN_INSTRUMENT then
hadInstrument = true
if amount < nInst then
local instRegion = clear(false)
local ib0, ib1 = range(inst, amount + 1, 2, #ibag)
for ibi = ib0, ib1 - 1 do
local zone = copy(instRegion)
local hadSample = false
local ig0, ig1 = range(ibag, ibi, 1, #igen)
for igi = ig0, ig1 - 1 do
local ig = igen[igi]
local iop, iamt = ig[1], ig[2]
if iop == GEN_SAMPLEID then
hadSample = true
if iamt >= nShdr then
break
end
local ok = not (zone.hikey < presetRegion.lokey or zone.lokey > presetRegion.hikey)
and not (zone.hivel < presetRegion.lovel or zone.lovel > presetRegion.hivel)
if ok then
local z = copy(zone)
z.lokey = math.max(z.lokey, presetRegion.lokey)
z.hikey = math.min(z.hikey, presetRegion.hikey)
z.lovel = math.max(z.lovel, presetRegion.lovel)
z.hivel = math.min(z.hivel, presetRegion.hivel)
merge(z, presetRegion)
envToSecs(z, "a", true)
envToSecs(z, "m", false)
z.delayModLFO = if z.delayModLFO < -11950 then 0 else tc2s(z.delayModLFO)
z.delayVibLFO = if z.delayVibLFO < -11950 then 0 else tc2s(z.delayVibLFO)
local sh = shdr[iamt + 1]
local sStart, sEnd, sLoopStart, sLoopEnd = sh[2], sh[3], sh[4], sh[5]
z.offset = math.clamp(z.offset + sStart, 0, count)
local stop = z.stop + sEnd
if stop > 0 and stop < count then
stop += 1
else
stop = count
end
z.stop = math.clamp(stop, 0, count)
z.loopStart = math.clamp(z.loopStart + sLoopStart, 0, count)
local le = z.loopEnd + sLoopEnd
if sLoopEnd > 0 then
le -= 1
end
z.loopEnd = math.clamp(le, 0, count)
if z.keycenter == -1 then
z.keycenter = sh[7]
end
z.tune += sh[8]
z.sampleRate = sh[6]
z.sampleIndex = iamt
regionTotal += 1
if regionTotal > maxRegions then
return nil, Err.new(Err.LIMIT, "over " .. maxRegions .. " regions")
end
table.insert(preset.regions, z)
end
break -- sampleID ends a zone's generator list
else
local ilo, ihi = iamt % 256, iamt // 256
operator(zone, iop, ilo, ihi, if iamt >= 32768 then iamt - 65536 else iamt, iamt)
end
end
if ibi == ib0 and not hadSample then
instRegion = zone -- the instrument's global zone
end
end
end
break -- instrument ends a preset zone's generator list
else
operator(presetRegion, op, lo, hi, s, amount)
end
end
if bi == b0 and not hadInstrument then
globalRegion = presetRegion -- the preset's global zone
end
end
table.insert(presets, preset)
end
-- sorted by bank, then preset, then file order (tsf's sortedIndex)
for i, p in presets do
(p :: any)._order = i
end
table.sort(presets, function(a: Preset, b: Preset): boolean
if a.bank ~= b.bank then
return a.bank < b.bank
end
if a.preset ~= b.preset then
return a.preset < b.preset
end
return (a :: any)._order < (b :: any)._order
end)
for _, p in presets do
(p :: any)._order = nil
end
local headers: { { [string]: any } } = table.create(nShdr)
for i = 1, nShdr do
local sh = shdr[i]
headers[i] = {
name = shdrNames[i],
start = sh[2],
stop = sh[3],
loopStart = sh[4],
loopEnd = sh[5],
sampleRate = sh[6],
originalPitch = sh[7],
pitchCorrection = sh[8],
link = sh[9],
type = sh[10],
}
end
local instruments: { { name: string, zones: number } } = table.create(nInst)
for i = 1, nInst do
instruments[i] = { name = instNames[i], zones = math.max(0, (inst[i + 1][2] or 0) - inst[i][2]) }
end
local sf: SoundFont = {
kind = "soundfont",
info = info,
samples = samples,
sampleCount = count,
presets = presets,
sampleHeaders = headers,
instruments = instruments,
meta = { source = { format = "sf2", version = version, sm24 = sm24 ~= nil } },
}
return sf, nil
end
return Parse
+803
View File
@@ -0,0 +1,803 @@
--!strict
--!native
-- codecs/SoundFont/Synth: a SoundFont 2 sample synthesizer with MIDI channels. A port of TinySoundFont (tsf.h v0.9,
-- MIT, (c) 2017-2025 Bernhard Schelling, based on SFZero (c) 2012 Steve Folta; licenses/TinySoundFont-LICENSE.txt):
-- voices with the DAHDSR volume envelope (exponential decay / release), the modulation envelope to pitch and filter
-- cutoff, the modulation and vibrato LFOs (triangle) to pitch / filter / volume, a resonant biquad low-pass, linear
-- interpolation, loop modes (none / continuous / until release), 3 dB pan law, exclusive classes; channels with
-- program / bank select (CC0 / CC32), drums (bank 128), pitch bend with RPN 0 range and RPN 1 / 2 tuning, CC7 volume,
-- CC10 pan, CC11 expression, CC64 sustain, CC120 / 121 / 123. Effects (reverb, chorus) and modulators are not
-- implemented (as in tsf.h). Output: interleaved stereo f32, mixed into the caller's buffer.
-- Differences from tsf.h: the envelope gain is ramped across each 64-sample block (tsf.h steps it); a voice limit (oldest release voice stolen, else the note is dropped), channels 0..15 only.
-- Native, never throws: every buffer index is in range by construction (the regions are clamped by Parse / Fallback,
-- the sample buffer has a zero pad sample, the output range is checked before mixing).
local Synth = {}
local readf32, writef32, blen = buffer.readf32, buffer.writef32, buffer.len
local exp, log, sqrt, tan, floor = math.exp, math.log, math.sqrt, math.tan, math.floor
local NONE, DELAY, ATTACK, HOLD, DECAY, SUSTAIN, RELEASE, DONE = 0, 1, 2, 3, 4, 5, 6, 7
local BLOCK = 64 -- TSF_RENDER_EFFECTSAMPLEBLOCK: envelopes / LFOs / filter cutoff update per block
local FASTRELEASE = 0.01
local PI = math.pi
local LOOP_NONE, LOOP_SUSTAIN = 0, 2
type Env = {
segment: number,
isExp: boolean,
isAmp: boolean,
vel: number,
level: number,
slope: number,
untilNext: number,
delay: number,
attack: number,
hold: number,
decay: number,
sustain: number,
release: number,
}
type Lfo = { untilStart: number, level: number, delta: number }
export type Voice = {
preset: number, -- 1-based preset index, -1 = idle
key: number,
channel: number,
held: boolean, -- note off while sustain was down
region: { [string]: number },
pitchIn: number, -- timecents
pitchOut: number,
pos: number,
gainDB: number,
panL: number,
panR: number,
playIndex: number,
loopStart: number,
loopEnd: number,
amp: Env,
mod: Env,
lpActive: boolean,
qinv: number,
a0: number,
a1: number,
b1: number,
b2: number,
z1: number,
z2: number,
modlfo: Lfo,
viblfo: Lfo,
}
export type Channel = {
preset: number,
bank: number,
pitchWheel: number,
midiPan: number,
midiVolume: number,
midiExpression: number,
midiRPN: number,
midiData: number,
sustain: boolean,
panOffset: number,
gainDB: number,
pitchRange: number,
tuning: number,
}
export type State = {
presets: { { regions: { { [string]: number } }, preset: number, bank: number } },
lookup: { [number]: number }, -- bank * 128 + preset -> preset index
samples: buffer,
rate: number,
gainDB: number,
voices: { Voice },
maxVoices: number,
playIndex: number,
channels: { Channel }, -- [1..16] = MIDI channels 0..15
}
local function tc2s(tc: number): number
return 2 ^ (tc / 1200)
end
local function cents2Hz(c: number): number
return 8.176 * 2 ^ (c / 1200)
end
local function db2gain(db: number): number
return if db > -100 then 10 ^ (db * 0.05) else 0
end
local function gain2db(g: number): number
return if g <= 0.00001 then -100 else 20 * math.log10(g)
end
-- ------------------------------------------------------------------------------------------------ envelope
local function releaseSamples(e: Env, rate: number): number
return floor((if e.release <= 0 then FASTRELEASE else e.release) * rate)
end
local function nextSegment(e: Env, active: number, rate: number)
local seg = active
if seg == NONE then
e.untilNext = floor(e.delay * rate)
if e.untilNext > 0 then
e.segment, e.isExp, e.level, e.slope = DELAY, false, 0, 0
return
end
seg = DELAY
end
if seg == DELAY then
e.untilNext = floor(e.attack * rate)
if e.untilNext > 0 then
if not e.isAmp then
-- the mod env attack scales with velocity (1 = full duration, 127 = 0.125 x)
e.untilNext = floor(e.attack * ((145 - e.vel) / 144) * rate)
end
e.segment, e.isExp, e.level = ATTACK, false, 0
e.slope = if e.untilNext > 0 then 1 / e.untilNext else 1
return
end
seg = ATTACK
end
if seg == ATTACK then
e.untilNext = floor(e.hold * rate)
if e.untilNext > 0 then
e.segment, e.isExp, e.level, e.slope = HOLD, false, 1, 0
return
end
seg = HOLD
end
if seg == HOLD then
e.untilNext = floor(e.decay * rate)
if e.untilNext > 0 then
e.segment, e.level = DECAY, 1
if e.isAmp then
local mystery = -9.226 / e.untilNext -- LinuxSampler's decay curve (as tsf.h)
e.slope = exp(mystery)
e.isExp = true
if e.sustain > 0 then
e.untilNext = floor(log(e.sustain) / mystery)
end
else
e.slope = -1 / e.untilNext
e.untilNext = floor(e.decay * (1 - e.sustain) * rate)
e.isExp = false
end
return
end
seg = DECAY
end
if seg == DECAY then
e.segment, e.level, e.slope, e.untilNext, e.isExp = SUSTAIN, e.sustain, 0, 0x7FFFFFFF, false
return
end
if seg == SUSTAIN then
e.segment = RELEASE
e.untilNext = math.max(1, releaseSamples(e, rate))
if e.isAmp then
e.slope = exp(-9.226 / e.untilNext)
e.isExp = true
else
e.slope = -e.level / e.untilNext
e.isExp = false
end
return
end
e.segment, e.isExp, e.level, e.slope, e.untilNext = DONE, false, 0, 0, 0x7FFFFFF
end
local function envSetup(e: Env, r: { [string]: number }, p: string, key: number, vel: number, isAmp: boolean, rate: number)
e.delay, e.attack, e.hold, e.decay = r[p .. "Delay"], r[p .. "Attack"], r[p .. "Hold"], r[p .. "Decay"]
e.sustain, e.release = r[p .. "Sustain"], r[p .. "Release"]
local kh, kd = r[p .. "KeyHold"], r[p .. "KeyDecay"]
if kh ~= 0 then
local h = e.hold + kh * (60 - key)
e.hold = if h < -10000 then 0 else tc2s(h)
end
if kd ~= 0 then
local d = e.decay + kd * (60 - key)
e.decay = if d < -10000 then 0 else tc2s(d)
end
e.vel, e.isAmp = vel, isAmp
nextSegment(e, NONE, rate)
end
local function envProcess(e: Env, n: number, rate: number)
local slope = e.slope
if slope ~= 0 then
if e.isExp then
e.level *= slope ^ n
else
e.level += slope * n
end
end
e.untilNext -= n
if e.untilNext <= 0 then
nextSegment(e, e.segment, rate)
end
end
local function newEnv(): Env
return { segment = DONE, isExp = false, isAmp = false, vel = 0, level = 0, slope = 0, untilNext = 0, delay = 0, attack = 0, hold = 0, decay = 0, sustain = 0, release = 0 }
end
-- ------------------------------------------------------------------------------------------------ filter / lfo
local function lowpassSetup(v: Voice, fc: number)
-- the biquad from earlevel.com (as tsf.h)
local k = tan(PI * fc)
local kk = k * k
local norm = 1 / (1 + k * v.qinv + kk)
v.a0 = kk * norm
v.a1 = 2 * v.a0
v.b1 = 2 * (kk - 1) * norm
v.b2 = (1 - k * v.qinv + kk) * norm
end
local function lfoSetup(l: Lfo, delay: number, freqCents: number, rate: number)
l.untilStart = floor(delay * rate)
l.delta = 4 * cents2Hz(freqCents) / rate
l.level = 0
end
local function lfoProcess(l: Lfo, n: number)
if l.untilStart > n then
l.untilStart -= n
return
end
l.level += l.delta * n
if l.level > 1 then
l.delta = -l.delta
l.level = 2 - l.level
elseif l.level < -1 then
l.delta = -l.delta
l.level = -2 - l.level
end
end
-- ------------------------------------------------------------------------------------------------ voices
local function calcPitch(v: Voice, shift: number, rate: number)
local r = v.region
local note = v.key + r.transpose + r.tune / 100
local adjusted = r.keycenter + (note - r.keycenter) * (r.keytrack / 100) + shift
v.pitchIn = adjusted * 100
v.pitchOut = r.sampleRate / (tc2s(r.keycenter * 100) * rate)
end
local function setPan(v: Voice, pan: number)
if pan <= -0.5 then
v.panL, v.panR = 1, 0
elseif pan >= 0.5 then
v.panL, v.panR = 0, 1
else
v.panL, v.panR = sqrt(0.5 - pan), sqrt(0.5 + pan)
end
end
local function channelShift(c: Channel): number
return if c.pitchWheel == 8192 then c.tuning else (c.pitchWheel / 16383 * c.pitchRange * 2) - c.pitchRange + c.tuning
end
local function voiceEnd(s: State, v: Voice)
nextSegment(v.amp, SUSTAIN, s.rate)
nextSegment(v.mod, SUSTAIN, s.rate)
if v.region.loopMode == LOOP_SUSTAIN then
v.loopEnd = v.loopStart -- keep playing, stop looping
end
end
local function voiceEndQuick(s: State, v: Voice)
v.amp.release = 0
nextSegment(v.amp, SUSTAIN, s.rate)
v.mod.release = 0
nextSegment(v.mod, SUSTAIN, s.rate)
end
local function newVoice(): Voice
return {
preset = -1, key = 0, channel = 0, held = false, region = {}, pitchIn = 0, pitchOut = 0, pos = 0, gainDB = 0,
panL = 0, panR = 0, playIndex = 0, loopStart = 0, loopEnd = 0, amp = newEnv(), mod = newEnv(),
lpActive = false, qinv = 0, a0 = 0, a1 = 0, b1 = 0, b2 = 0, z1 = 0, z2 = 0,
modlfo = { untilStart = 0, level = 0, delta = 0 }, viblfo = { untilStart = 0, level = 0, delta = 0 },
}
end
local function newChannel(): Channel
return {
preset = 1, bank = 0, pitchWheel = 8192, midiPan = 8192, midiVolume = 16383, midiExpression = 16383,
midiRPN = 0xFFFF, midiData = 0, sustain = false, panOffset = 0, gainDB = 0, pitchRange = 2, tuning = 0,
}
end
-- new(sf, sampleRate, opts) -> State. sf: { presets, samples } (Parse.parse or Fallback.build).
-- opts.gain: output gain (linear, default 0.5); opts.maxVoices (default 256)
function Synth.new(sf: any, rate: number, gain: number?, maxVoices: number?): State
local lookup: { [number]: number } = {}
for i, p in sf.presets do
local k = p.bank * 128 + p.preset
if lookup[k] == nil then
lookup[k] = i
end
end
local s: State = {
presets = sf.presets,
lookup = lookup,
samples = sf.samples,
rate = rate,
gainDB = gain2db(gain or 0.5),
voices = {},
maxVoices = maxVoices or 256,
playIndex = 0,
channels = {},
}
for ch = 1, 16 do
s.channels[ch] = newChannel()
end
for ch = 0, 15 do
Synth.program(s, ch, 0)
end
return s
end
local function presetIndex(s: State, bank: number, preset: number): number
return s.lookup[bank * 128 + preset] or -1
end
-- noteOn(s, channel, key, velocity 0..127)
function Synth.noteOn(s: State, ch: number, key: number, velocity: number)
local c = s.channels[ch + 1]
if not c then
return
end
if velocity <= 0 then
Synth.noteOff(s, ch, key)
return
end
local pi = c.preset
local preset = s.presets[pi]
if not preset then
return
end
local vel = math.min(velocity, 127) / 127
local midiVel = floor(vel * 127)
local rate = s.rate
local voices = s.voices
local playIndex = s.playIndex
s.playIndex += 1
for _, region in preset.regions do
if key < region.lokey or key > region.hikey or midiVel < region.lovel or midiVel > region.hivel then
continue
end
local voice: Voice? = nil
if region.group ~= 0 then
for _, v in voices do
if v.preset == pi and v.region.group == region.group then
voiceEndQuick(s, v)
elseif v.preset == -1 and not voice then
voice = v
end
end
else
for _, v in voices do
if v.preset == -1 then
voice = v
break
end
end
end
if not voice then
if #voices < s.maxVoices then
local v = newVoice()
table.insert(voices, v)
voice = v
else
local best = -1e18
for _, v in voices do
if v.amp.segment == RELEASE then
local done = releaseSamples(v.amp, rate) - v.amp.untilNext
if done > best then
best, voice = done, v
end
end
end
if not voice then
continue
end
end
end
local v = voice :: Voice
v.region = region
v.preset = pi
v.key = key
v.channel = ch
v.playIndex = playIndex
v.held = false
v.gainDB = s.gainDB - region.attenuation - gain2db(1 / vel) + c.gainDB
calcPitch(v, channelShift(c), rate)
setPan(v, region.pan + c.panOffset)
v.pos = region.offset
local doLoop = region.loopMode ~= LOOP_NONE and region.loopStart < region.loopEnd
v.loopStart = if doLoop then region.loopStart else 0
v.loopEnd = if doLoop then region.loopEnd else 0
envSetup(v.amp, region, "a", key, midiVel, true, rate)
envSetup(v.mod, region, "m", key, midiVel, false, rate)
local fc = if region.filterFc <= 13500 then cents2Hz(region.filterFc) / rate else 1
v.qinv = 1 / 10 ^ ((region.filterQ / 10) / 20)
v.z1, v.z2 = 0, 0
v.lpActive = fc < 0.499
if v.lpActive then
lowpassSetup(v, fc)
end
lfoSetup(v.modlfo, region.delayModLFO, region.freqModLFO, rate)
lfoSetup(v.viblfo, region.delayVibLFO, region.freqVibLFO, rate)
end
end
-- noteOff(s, channel, key): ends the oldest matching note (all its regions); held while sustain is down
function Synth.noteOff(s: State, ch: number, key: number)
local c = s.channels[ch + 1]
if not c then
return
end
local first = -1
for _, v in s.voices do
if v.preset ~= -1 and v.channel == ch and v.key == key and v.amp.segment < RELEASE and not v.held then
if first == -1 or v.playIndex < first then
first = v.playIndex
end
end
end
if first == -1 then
return
end
for _, v in s.voices do
if v.preset ~= -1 and v.channel == ch and v.key == key and v.amp.segment < RELEASE and not v.held and v.playIndex == first then
if c.sustain then
v.held = true
else
voiceEnd(s, v)
end
end
end
end
local function applyPitch(s: State, ch: number, c: Channel)
local shift = channelShift(c)
for _, v in s.voices do
if v.preset ~= -1 and v.channel == ch then
calcPitch(v, shift, s.rate)
end
end
end
local function setVolume(s: State, ch: number, c: Channel, volume: number)
local db = gain2db(volume)
if db == c.gainDB then
return
end
local change = db - c.gainDB
for _, v in s.voices do
if v.preset ~= -1 and v.channel == ch then
v.gainDB += change
end
end
c.gainDB = db
end
local function setChannelPan(s: State, ch: number, c: Channel, pan: number)
for _, v in s.voices do
if v.preset ~= -1 and v.channel == ch then
setPan(v, v.region.pan + pan - 0.5)
end
end
c.panOffset = pan - 0.5
end
local function setTuning(s: State, ch: number, c: Channel, tuning: number)
if c.tuning ~= tuning then
c.tuning = tuning
applyPitch(s, ch, c)
end
end
local function setPitchRange(s: State, ch: number, c: Channel, range: number)
if c.pitchRange ~= range then
c.pitchRange = range
if c.pitchWheel ~= 8192 then
applyPitch(s, ch, c)
end
end
end
local function setSustain(s: State, ch: number, c: Channel, on: boolean)
if c.sustain == on then
return
end
c.sustain = on
if on then
return
end
for _, v in s.voices do
if v.preset ~= -1 and v.channel == ch and v.amp.segment < RELEASE and v.held then
voiceEnd(s, v)
end
end
end
-- program(s, channel, program): bank select + program change (channel 9: drums, bank 128)
function Synth.program(s: State, ch: number, program: number)
local c = s.channels[ch + 1]
if not c then
return
end
local bank = c.bank % 32768
local idx
if ch == 9 then
idx = presetIndex(s, 128 + bank, program)
if idx == -1 then
idx = presetIndex(s, 128, program)
end
if idx == -1 then
idx = presetIndex(s, 128, 0)
end
if idx == -1 then
idx = presetIndex(s, bank, program)
end
else
idx = presetIndex(s, bank, program)
end
if idx == -1 then
idx = presetIndex(s, 0, program)
end
if idx ~= -1 then
c.preset = idx
end
end
-- pitchBend(s, channel, 0..16383)
function Synth.pitchBend(s: State, ch: number, value: number)
local c = s.channels[ch + 1]
if not c or c.pitchWheel == value then
return
end
c.pitchWheel = value
applyPitch(s, ch, c)
end
-- control(s, channel, controller, value 0..127)
function Synth.control(s: State, ch: number, cc: number, value: number)
local c = s.channels[ch + 1]
if not c then
return
end
local volume, pan, data = false, false, false
if cc == 7 then
c.midiVolume = c.midiVolume % 128 + value * 128
volume = true
elseif cc == 39 then
c.midiVolume = c.midiVolume - c.midiVolume % 128 + value
volume = true
elseif cc == 11 then
c.midiExpression = c.midiExpression % 128 + value * 128
volume = true
elseif cc == 43 then
c.midiExpression = c.midiExpression - c.midiExpression % 128 + value
volume = true
elseif cc == 10 then
c.midiPan = c.midiPan % 128 + value * 128
pan = true
elseif cc == 42 then
c.midiPan = c.midiPan - c.midiPan % 128 + value
pan = true
elseif cc == 6 then
c.midiData = c.midiData % 128 + value * 128
data = true
elseif cc == 38 then
c.midiData = c.midiData - c.midiData % 128 + value
data = true
elseif cc == 0 then
c.bank = 0x8000 + value -- bank select MSB alone acts like LSB (as tsf.h)
elseif cc == 32 then
c.bank = (if c.bank >= 0x8000 then (c.bank % 128) * 128 else 0) + value
elseif cc == 101 then
local rpn = if c.midiRPN == 0xFFFF then 0 else c.midiRPN
c.midiRPN = rpn % 128 + value * 128
elseif cc == 100 then
local rpn = if c.midiRPN == 0xFFFF then 0 else c.midiRPN
c.midiRPN = rpn - rpn % 128 + value
elseif cc == 98 or cc == 99 then
c.midiRPN = 0xFFFF
elseif cc == 64 then
setSustain(s, ch, c, value >= 64)
elseif cc == 120 then
for _, v in s.voices do
if v.preset ~= -1 and v.channel == ch and (v.amp.segment < RELEASE or v.amp.release ~= 0) then
voiceEndQuick(s, v)
end
end
elseif cc == 123 then
for _, v in s.voices do
if v.preset ~= -1 and v.channel == ch and v.amp.segment < RELEASE then
voiceEnd(s, v)
end
end
elseif cc == 121 then
c.midiVolume, c.midiExpression, c.midiPan, c.bank, c.midiRPN, c.midiData = 16383, 16383, 8192, 0, 0xFFFF, 0
setVolume(s, ch, c, 1)
setChannelPan(s, ch, c, 0.5)
setPitchRange(s, ch, c, 2)
setTuning(s, ch, c, 0)
end
if volume then
-- the cube gives a decent MIDI volume curve (tsf.h)
setVolume(s, ch, c, ((c.midiVolume / 16383) * (c.midiExpression / 16383)) ^ 3)
elseif pan then
setChannelPan(s, ch, c, c.midiPan / 16383)
elseif data then
if c.midiRPN == 0 then
setPitchRange(s, ch, c, c.midiData // 128 + 0.01 * (c.midiData % 128))
elseif c.midiRPN == 1 then
local t = c.tuning
setTuning(s, ch, c, (if t < 0 then math.ceil(t) else floor(t)) + (c.midiData - 8192) / 8192)
elseif c.midiRPN == 2 and cc == 6 then
local t = c.tuning
setTuning(s, ch, c, (value - 64) + (t - (if t < 0 then math.ceil(t) else floor(t))))
end
end
end
-- midi(s, status, d1, d2): one channel message
function Synth.midi(s: State, status: number, d1: number, d2: number)
local kind, ch = status // 16, status % 16
if kind == 9 then
Synth.noteOn(s, ch, d1, d2)
elseif kind == 8 then
Synth.noteOff(s, ch, d1)
elseif kind == 11 then
Synth.control(s, ch, d1, d2)
elseif kind == 12 then
Synth.program(s, ch, d1)
elseif kind == 14 then
Synth.pitchBend(s, ch, d1 + d2 * 128)
end
end
-- reset(s): all voices off, channels back to their defaults
function Synth.reset(s: State)
for _, v in s.voices do
v.preset = -1
end
for ch = 1, 16 do
s.channels[ch] = newChannel()
end
for ch = 0, 15 do
Synth.program(s, ch, 0)
end
end
-- active(s) -> the number of sounding voices
function Synth.active(s: State): number
local n = 0
for _, v in s.voices do
if v.preset ~= -1 then
n += 1
end
end
return n
end
-- ------------------------------------------------------------------------------------------------ render
local function voiceRender(s: State, v: Voice, out: buffer, frame: number, numSamples: number)
local region = v.region
local input = s.samples
local rate = s.rate
local modEnvToPitch, modEnvToFilterFc = region.modEnvToPitch, region.modEnvToFilterFc
local modLfoToPitch, modLfoToFilterFc, modLfoToVolume = region.modLfoToPitch, region.modLfoToFilterFc, region.modLfoToVolume
local vibLfoToPitch = region.vibLfoToPitch
local updateModEnv = modEnvToPitch ~= 0 or modEnvToFilterFc ~= 0
local updateModLfo = v.modlfo.delta ~= 0 and (modLfoToPitch ~= 0 or modLfoToFilterFc ~= 0 or modLfoToVolume ~= 0)
local updateVibLfo = v.viblfo.delta ~= 0 and vibLfoToPitch ~= 0
local loopStart, loopEnd = v.loopStart, v.loopEnd
local isLooping = loopStart < loopEnd
local endD = region.stop
local loopEndD = loopEnd + 1
local loopLen = loopEnd - loopStart + 1
local pos = v.pos
local lpActive, a0, a1, b1, b2, z1, z2 = v.lpActive, v.a0, v.a1, v.b1, v.b2, v.z1, v.z2
local dynamicLowpass = modLfoToFilterFc ~= 0 or modEnvToFilterFc ~= 0
local dynamicPitch = modLfoToPitch ~= 0 or modEnvToPitch ~= 0 or vibLfoToPitch ~= 0
local dynamicGain = modLfoToVolume ~= 0
local filterFc = region.filterFc
local pitchRatio = if dynamicPitch then 0 else tc2s(v.pitchIn) * v.pitchOut
local noteGain = if dynamicGain then 0 else db2gain(v.gainDB)
local o = frame * 8
while numSamples > 0 do
local block = if numSamples > BLOCK then BLOCK else numSamples
numSamples -= block
if dynamicLowpass then
local fres = filterFc + v.modlfo.level * modLfoToFilterFc + v.mod.level * modEnvToFilterFc
local fc = if fres <= 13500 then cents2Hz(fres) / rate else 1
lpActive = fc < 0.499
if lpActive then
lowpassSetup(v, fc)
a0, a1, b1, b2 = v.a0, v.a1, v.b1, v.b2
end
end
if dynamicPitch then
pitchRatio = tc2s(v.pitchIn + (v.modlfo.level * modLfoToPitch + v.viblfo.level * vibLfoToPitch + v.mod.level * modEnvToPitch)) * v.pitchOut
end
if dynamicGain then
noteGain = db2gain(v.gainDB + v.modlfo.level * modLfoToVolume * 0.1)
end
local gainMono = noteGain * v.amp.level
envProcess(v.amp, block, rate)
if updateModEnv then
envProcess(v.mod, block, rate)
end
if updateModLfo then
lfoProcess(v.modlfo, block)
end
if updateVibLfo then
lfoProcess(v.viblfo, block)
end
-- ramp the gain across the block to the envelope's next level (tsf.h steps it per block: zipper noise)
local gainNext = noteGain * v.amp.level
local step = (gainNext - gainMono) / block
local panL, panR = v.panL, v.panR
local g = gainMono
local k = block
while k > 0 and pos < endD do
k -= 1
local ip = floor(pos)
local np = if ip >= loopEnd and isLooping then loopStart else ip + 1
local s0 = readf32(input, ip * 4)
local val = s0 + (readf32(input, np * 4) - s0) * (pos - ip)
if lpActive then
local y = val * a0 + z1
z1 = val * a1 + z2 - b1 * y
z2 = val * a0 - b2 * y
val = y
end
val *= g
g += step
writef32(out, o, readf32(out, o) + val * panL)
writef32(out, o + 4, readf32(out, o + 4) + val * panR)
o += 8
pos += pitchRatio
if pos >= loopEndD and isLooping then
pos -= loopLen
end
end
o += k * 8
if not (pos < endD) or v.amp.segment == DONE then
v.preset = -1
return
end
end
v.pos = pos
v.lpActive, v.z1, v.z2 = lpActive, z1, z2
end
-- render(s, out, frame, n): mixes n stereo frames into out (interleaved f32) starting at frame; out-of-range
-- requests are clipped to the buffer
function Synth.render(s: State, out: buffer, frame: number, n: number)
local room = blen(out) // 8 - frame
if frame < 0 or room <= 0 then
return
end
if n > room then
n = room
end
if n <= 0 then
return
end
-- the sample buffer must hold every region's range + the pad sample (Parse / Fallback guarantee it; checked here
-- once so a hand-made SoundFont cannot index outside it)
local count = blen(s.samples) // 4 - 1
for _, v in s.voices do
if v.preset ~= -1 then
local r = v.region
if r.stop > count or r.loopEnd > count or r.offset < 0 or r.loopStart < 0 or v.pos < 0 then
v.preset = -1
else
voiceRender(s, v, out, frame, n)
end
end
end
end
return Synth
+69
View File
@@ -0,0 +1,69 @@
--!strict
-- codecs/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by
-- music/sf2 (the file format) and music/midi (rendering). The synth is a port of TinySoundFont (tsf.h v0.9, MIT,
-- (c) 2017-2025 Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt); see Parse / Synth for what is covered.
-- Without a bank, fallback() is a generated General MIDI set of simple waveforms (sine / triangle / square / saw /
-- noise) with a drum kit.
--
-- local SoundFont = require("@formats/codecs/SoundFont")
-- local sf, err = SoundFont.parse(buf) -- buffer | string | core/Bytes Reader -> SoundFont | nil, Err
-- local sf = SoundFont.fallback() -- the built-in waveform set
-- local s = SoundFont.synth(sf, 44100, { gain = 0.5 }) -- a synth State; SoundFont.Synth.midi(s, 0x90, 60, 100)
-- SoundFont.Synth.render(s, out, frame, n) -- mix n stereo f32 frames into out at frame
--
-- Never throws: bad data returns nil, Err.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Parse = require("@formats/codecs/SoundFont/Parse")
local Synth = require("@formats/codecs/SoundFont/Synth")
local Fallback = require("@formats/codecs/SoundFont/Fallback")
local SoundFont = {}
export type SoundFont = Parse.SoundFont
export type State = Synth.State
SoundFont.Synth = Synth
SoundFont.defaultRegion = Parse.defaultRegion
-- sniff(r) -> true when r starts with RIFF....sfbk
function SoundFont.sniff(r: Bytes.Reader): boolean
return r:peek(4) == "RIFF" and r:peek(4, 8) == "sfbk"
end
-- parse(src, opts?) -> SoundFont | nil, Err. src: buffer | string | Reader. opts.maxRegions (default 10^6),
-- opts.maxSamples (default 2^28)
function SoundFont.parse(src: any, opts: Parse.Options?): (SoundFont?, Err.Err?)
local r: Bytes.Reader
if type(src) == "string" then
r = Bytes.reader(buffer.fromstring(src))
elseif type(src) == "buffer" then
r = Bytes.reader(src)
elseif type(src) == "table" and type(src.buf) == "buffer" then
r = Bytes.reader(src.buf, src.pos, src.limit - src.pos)
else
return nil, Err.new(Err.ARG, "soundfont: expected a buffer, string or Reader")
end
local ok, sf, err = pcall(Parse.parse, r, opts)
if not ok then
return nil, Err.new(Err.CORRUPT, "soundfont parser failed: " .. tostring(sf))
end
return sf, err
end
-- fallback() -> the built-in General MIDI waveform set
function SoundFont.fallback(): SoundFont
return Fallback.build()
end
-- isSoundFont(v) -> true for a parsed / fallback SoundFont value
function SoundFont.isSoundFont(v: any): boolean
return type(v) == "table" and v.kind == "soundfont" and type(v.samples) == "buffer" and type(v.presets) == "table"
end
-- synth(sf?, sampleRate?, opts?) -> State. opts.gain (linear, default 0.5), opts.maxVoices (default 256)
function SoundFont.synth(sf: SoundFont?, sampleRate: number?, opts: { gain: number?, maxVoices: number? }?): State
return Synth.new(sf or Fallback.build(), sampleRate or 44100, opts and opts.gain, opts and opts.maxVoices)
end
return SoundFont
+173
View File
@@ -0,0 +1,173 @@
--!strict
--!native
-- codecs/Tracker/Mixer: mixes the player's active voices into an interleaved stereo f32 buffer. Per voice: sample
-- loops (forward, ping-pong, IT sustain loops while the key is held), linear or no interpolation, the IT two-pole
-- resonant filter, and a short gain ramp per tick against clicks. Written for this library (no third-party code).
--
-- Never throws: sample indexes are clamped to the sample, every loop is bounded, and the caller (codecs/Tracker)
-- validates the sample buffers' sizes.
local floor, ceil, min = math.floor, math.ceil, math.min
local readf32, writef32 = buffer.readf32, buffer.writef32
local Mixer = {}
-- mixVoice(v, out?, off, n, linear, ramp): n frames of voice v added at frame off of out (nil: only advance)
local function mixVoice(v: any, out: buffer?, off: number, n: number, linear: boolean, ramp: number)
local data: buffer = v.data
local nch = v.nch
local inc = v.inc
if not (inc > 0 and inc < 1e6) then
return
end
local len = v.len
local hi = len - 1
local i = 0
local guard = 0
while i < n do
guard += 1
if guard > n + 64 then
return
end
local s, e, t
if v.keyOn and v.susT > 0 then
s, e, t = v.susS, v.susE, v.susT
elseif v.loopT > 0 then
s, e, t = v.loopS, v.loopE, v.loopT
else
s, e, t = 0, len, 0
end
local p = v.p
local dir = v.dir
local count
if dir > 0 then
local lim = if t == 2 then e - 1 else e
if p >= lim then
if t == 0 then
v.active = false
return
elseif t == 1 then
p = s + (p - e) % (e - s)
else
p = 2 * (e - 1) - p
if p < s then
p = s
end
v.dir = -1
end
v.p = p
continue
end
count = ceil((lim - p) / inc)
else
if p < s then
p = 2 * s - p
if p > e - 1 then
p = e - 1
end
v.p = p
v.dir = 1
continue
end
count = floor((p - s) / inc) + 1
end
if count < 1 then
count = 1
end
local m = min(n - i, count)
local step = inc * dir
if out == nil then
v.p = p + step * m
i += m
continue
end
local wrapJ = if t == 1 then s else e - 1
local gl, gr = v.gl, v.gr
local rl = v.rampN
local dl, dr = 0, 0
local tl, tr = v.tl, v.tr
if rl > 0 then
dl, dr = (tl - gl) / rl, (tr - gr) / rl
end
local fOn = v.fOn
local fa, fb0, fb1 = v.fa, v.fb0, v.fb1
local y1l, y2l, y1r, y2r = v.y1l, v.y2l, v.y1r, v.y2r
local o = (off + i) * 8
for _ = 1, m do
local idx = floor(p)
if idx > hi then
idx = hi
elseif idx < 0 then
idx = 0
end
local j = idx + 1
if j >= e then
j = wrapJ
end
if j > hi then
j = hi
end
local xl, xr
if nch == 1 then
local a = readf32(data, idx * 4)
if linear then
local b = readf32(data, j * 4)
xl = a + (b - a) * (p - idx)
else
xl = a
end
if fOn then
local y = xl * fa + y1l * fb0 + y2l * fb1
y2l, y1l = y1l, y
xl = y
end
xr = xl
else
local al = readf32(data, idx * 8)
local ar = readf32(data, idx * 8 + 4)
if linear then
local f = p - idx
xl = al + (readf32(data, j * 8) - al) * f
xr = ar + (readf32(data, j * 8 + 4) - ar) * f
else
xl, xr = al, ar
end
if fOn then
local y = xl * fa + y1l * fb0 + y2l * fb1
y2l, y1l = y1l, y
xl = y
y = xr * fa + y1r * fb0 + y2r * fb1
y2r, y1r = y1r, y
xr = y
end
end
if rl > 0 then
gl += dl
gr += dr
rl -= 1
if rl == 0 then
gl, gr = tl, tr
end
end
writef32(out, o, readf32(out, o) + xl * gl)
writef32(out, o + 4, readf32(out, o + 4) + xr * gr)
o += 8
p += step
end
v.p = p
v.gl, v.gr, v.rampN = gl, gr, rl
v.y1l, v.y2l, v.y1r, v.y2r = y1l, y2l, y1r, y2r
i += m
end
local _ = ramp
end
-- mix(st, out?, off, n, linear): every active voice of player st; out nil only advances the sample positions
function Mixer.mix(st: any, out: buffer?, off: number, n: number, linear: boolean)
for _, v in st.voices do
if v.active and v.data then
mixVoice(v, out, off, n, linear, 0)
end
end
end
return Mixer
+132
View File
@@ -0,0 +1,132 @@
--!strict
--!native
-- codecs/Tracker/Pcm: sample data conversions shared by the tracker formats. Raw 8 / 16-bit PCM (signed or unsigned,
-- plain or delta coded as in XM / IT 2.15, interleaved or planar stereo) to the engine's f32 samples, and back.
--
-- Never throws: reads past the source are refused up front (decode returns nil).
local readu8, readi8, readu16, readi16 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16
local writef32, readf32, writeu8, writei16 = buffer.writef32, buffer.readf32, buffer.writeu8, buffer.writei16
local floor = math.floor
local Pcm = {}
export type Spec = {
bits: number, -- 8 | 16
signed: boolean,
delta: boolean?, -- each value is the difference to the previous one (XM, IT 2.15 "delta" flag)
channels: number?, -- 1 (default) | 2
planar: boolean?, -- stereo stored as all left then all right (XM, IT); default interleaved
bigEndian: boolean?,
}
-- bytes(frames, spec) -> the size of the raw data
function Pcm.bytes(frames: number, spec: Spec): number
return frames * (spec.channels or 1) * (spec.bits // 8)
end
-- decode(buf, off, frames, spec) -> f32 buffer (frames * channels, interleaved) | nil when the source is too short
function Pcm.decode(buf: buffer, off: number, frames: number, spec: Spec): buffer?
local nch = spec.channels or 1
local bps = spec.bits // 8
local total = frames * nch
if frames < 0 or off < 0 or off + total * bps > buffer.len(buf) then
return nil
end
local out = buffer.create(total * 4)
local planar = spec.planar and nch == 2
for c = 0, nch - 1 do
local acc = 0
for i = 0, frames - 1 do
local k = if planar then c * frames + i else i * nch + c
local v
if bps == 1 then
if spec.signed then
v = readi8(buf, off + k)
else
v = readu8(buf, off + k) - 128
end
if spec.delta then
acc = (acc + v + 128) % 256 - 128
v = acc
end
writef32(out, (i * nch + c) * 4, v / 128)
else
local p = off + k * 2
if spec.bigEndian then
v = readu8(buf, p) * 256 + readu8(buf, p + 1)
if spec.signed and v >= 32768 then
v -= 65536
end
elseif spec.signed then
v = readi16(buf, p)
else
v = readu16(buf, p)
end
if not spec.signed then
v -= 32768
end
if spec.delta then
acc = (acc + v + 32768) % 65536 - 32768
v = acc
end
writef32(out, (i * nch + c) * 4, v / 32768)
end
end
end
return out
end
-- encode(samples, frames, spec) -> raw PCM (signed or unsigned, optional delta, interleaved or planar)
function Pcm.encode(samples: buffer, frames: number, spec: Spec): buffer
local nch = spec.channels or 1
local bps = spec.bits // 8
local out = buffer.create(frames * nch * bps)
local planar = spec.planar and nch == 2
local avail = buffer.len(samples) // 4
for c = 0, nch - 1 do
local prev = 0
for i = 0, frames - 1 do
local si = i * nch + c
local x = if si < avail then readf32(samples, si * 4) else 0
local k = if planar then c * frames + i else i * nch + c
if bps == 1 then
local v = math.clamp(floor(x * 128 + 0.5), -128, 127)
local w = v
if spec.delta then
w = (v - prev) % 256
prev = v
else
w = if spec.signed then v % 256 else v + 128
end
writeu8(out, k, w)
else
local v = math.clamp(floor(x * 32768 + 0.5), -32768, 32767)
local w = v
if spec.delta then
w = (v - prev + 32768) % 65536 - 32768
prev = v
elseif not spec.signed then
w = v + 32768
if w >= 32768 then
w -= 65536
end
end
writei16(out, k * 2, w)
end
end
end
return out
end
-- bits(samples) -> 8 when every value is exactly representable in 8 bits (data loaded from 8-bit), else 16
function Pcm.bitsNeeded(samples: buffer): number
for i = 0, buffer.len(samples) // 4 - 1 do
local x = readf32(samples, i * 4) * 128
if x ~= floor(x) then
return 16
end
end
return 8
end
return Pcm
File diff suppressed because it is too large. Load diff
+113
View File
@@ -0,0 +1,113 @@
--!strict
--!native
-- codecs/Tracker/Tables: lookup tables of the tracker engine. Waveforms for vibrato / tremolo / panbrello and the
-- auto-vibrato, the ProTracker period table (finetune 0, used to map MOD periods to notes and back) and the IT / S3M
-- volume-column tone-portamento and retrigger tables. All values are from the public format documents (ProTracker
-- 2.3 effect docs, FT2 / XM spec, ST3 TECH.DOC, ITTECH.TXT).
local Tables = {}
-- the ProTracker half-sine (32 steps, 0..255)
local SINE32 = { 0, 24, 49, 74, 97, 120, 141, 161, 180, 197, 212, 224, 235, 244, 250, 253, 255, 253, 250, 244, 235, 224, 212, 197, 180, 161, 141, 120, 97, 74, 49, 24 }
-- wave64(type, pos) -> -255..255 for pos 0..63: 0 sine, 1 ramp down, 2 square, 3 random (deterministic)
local RANDOM: { number } = {}
do
local s = 12345
for i = 1, 64 do
s = (s * 1103515245 + 12345) % 2147483648
RANDOM[i] = (s // 65536) % 511 - 255
end
end
function Tables.wave64(kind: number, pos: number): number
local p = pos % 64
if kind == 1 then
return 255 - p * 8
elseif kind == 2 then
return if p < 32 then 255 else -255
elseif kind == 3 then
return RANDOM[p + 1]
end
local v = SINE32[(p % 32) + 1]
return if p >= 32 then -v else v
end
-- autoWave(type, pos, it) -> -64..64 for pos 0..255. XM: 0 sine, 1 square, 2 ramp down, 3 ramp up.
-- IT: 0 sine, 1 ramp down, 2 square, 3 random.
local SINE256: { number } = {}
for i = 0, 255 do
SINE256[i + 1] = math.floor(math.sin(i * math.pi / 128) * 64 + 0.5)
end
function Tables.autoWave(kind: number, pos: number, it: boolean): number
local p = pos % 256
if it then
if kind == 1 then
return 64 - (p + 1) // 2
elseif kind == 2 then
return if p < 128 then 64 else -64
elseif kind == 3 then
return RANDOM[(p % 64) + 1] // 4
end
return SINE256[p + 1]
end
if kind == 1 then
return if p < 128 then 64 else -64
elseif kind == 2 then
return 64 - (p + 1) // 2
elseif kind == 3 then
return (p + 1) // 2 - 64
end
return SINE256[p + 1]
end
-- ProTracker periods, finetune 0, C-0 .. B-4 (60 notes; ProTracker itself uses C-1 .. B-3). Our note numbers:
-- 1 = C-0 (FT2 numbering), so ProTracker C-1 (856) = note 37 and C-2 (428) = note 49, the note that plays a sample at
-- its base rate (8363 Hz).
local PERIODS = {
3424, 3232, 3048, 2880, 2712, 2560, 2416, 2280, 2152, 2032, 1920, 1812,
1712, 1616, 1524, 1440, 1356, 1280, 1208, 1140, 1076, 1016, 960, 906,
856, 808, 762, 720, 678, 640, 604, 570, 538, 508, 480, 453,
428, 404, 381, 360, 339, 320, 302, 285, 269, 254, 240, 226,
214, 202, 190, 180, 170, 160, 151, 143, 135, 127, 120, 113,
107, 101, 95, 90, 85, 80, 75, 71, 67, 63, 60, 56,
}
Tables.PERIODS = PERIODS
Tables.PERIOD_FIRST_NOTE = 13 -- PERIODS[1] is note 13 (C-1 in FT2 numbering = ProTracker octave -1)
-- periodToNote(period) -> note (1..120), 0 for period 0
function Tables.periodToNote(period: number): number
if period <= 0 then
return 0
end
-- exact match first, then the nearest note on a log scale
for i = 1, #PERIODS do
if PERIODS[i] == period then
return i + Tables.PERIOD_FIRST_NOTE - 1
end
end
local n = 49 + math.floor(12 * math.log(428 / period) / math.log(2) + 0.5)
return math.clamp(n, 1, 120)
end
-- noteToPeriod(note) -> ProTracker period (finetune 0) for a note, computed past the table's ends
function Tables.noteToPeriod(note: number): number
local i = note - Tables.PERIOD_FIRST_NOTE + 1
if i >= 1 and i <= #PERIODS then
return PERIODS[i]
end
return math.max(1, math.floor(428 * 2 ^ ((49 - note) / 12) + 0.5))
end
-- IT volume column "g" (tone portamento) speeds
Tables.IT_VOLPORTA = { 0, 1, 4, 8, 16, 32, 64, 96, 128, 255 }
-- XM Rxy / S3M-IT Qxy volume changes: kind 0 add, 1 multiply; value
Tables.RETRIG_ADD = { 0, -1, -2, -4, -8, -16, 0, 0, 0, 1, 2, 4, 8, 16, 0, 0 }
Tables.RETRIG_MUL = { 1, 1, 1, 1, 1, 1, 2 / 3, 0.5, 1, 1, 1, 1, 1, 1, 1.5, 2 }
-- the Amiga clock constant: frequency = AMIGA / period, with period 1712 playing an 8363 Hz sample at its base rate
-- (FT2 / ST3 period units, 4x ProTracker's)
Tables.AMIGA = 8363 * 1712
-- MOD: the PAL Amiga clock (7093789.2 Hz / 2 per ProTracker period unit; period 428 plays at 8287 Hz)
Tables.AMIGA_PAL = 7093789.2 / 2 * 4
return Tables
+516
View File
@@ -0,0 +1,516 @@
--!strict
-- codecs/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read
-- their files into one Module structure (below); render(module, opts) plays any of them through the standard audio
-- Decoder (Types.Decoder: stereo f32). Written for this library from the format documents (ProTracker 2.3, the XM
-- spec + FT2 behaviour, ST3 TECH.DOC, ITTECH.TXT); libxmp / OpenMPT were used only as reference players for tests.
--
-- local Tracker = require("@formats/codecs/Tracker")
-- local dec, err = Tracker.render(module, { sampleRate = 44100 }) -- a Types.Decoder
-- local seconds = Tracker.duration(module) -- one pass, song loops detected
--
-- Module (Types.Module plus the engine fields; pattern / instrument / sample numbers are as in the file):
-- format "mod" | "s3m" | "xm" | "it": selects the effect family and the format quirks
-- title, channels, speed (ticks per row), tempo (BPM: a tick lasts 2.5 / tempo s)
-- globalVolume 0..128 (S3M / XM 0..64 are stored doubled), mixVolume 0..128 (IT mix volume, S3M master volume)
-- order { pattern number (0-based) | 254 skip ("+++") | 255 end ("---") }, restart (0-based order index)
-- linear linear frequency slides (XM / IT flag) or Amiga periods
-- instrumentMode XM, IT with instruments: notes go through Instrument keymaps; otherwise the instrument column
-- is a sample number (MOD, S3M, IT sample mode)
-- flags { oldEffects, compatGxx (IT), fastSlides (ST3.00 volume slides), amigaLimits (MOD) }
-- channelPan { 0..256 per channel (128 centre; 512 = surround); MOD: 64 / 192 (Amiga L R R L at half width,
-- as OpenMPT plays it; set 0 / 256 or render with stereoSeparation = 200 for hard panning) }, channelVolume { 0..64 }, channelMute { bool }
-- patterns { Pattern } (pattern n at patterns[n + 1]); Pattern = { rows, data }: data holds rows * channels
-- cells of 5 bytes: note, instrument, volume column, effect, parameter. Notes: 0 none, 1..120 (1 =
-- C-0; C-4 = 49 plays an XM / MOD sample at its base rate, C-5 = 61 an S3M / IT sample at its C5
-- speed), 253 note fade, 254 note cut, 255 key off. The volume column and effects are kept in the
-- file's own coding: MOD / XM effects 0..35 (XM letters G.. = 16..), XM volume byte as stored;
-- S3M / IT effects 1..26 (A = 1), S3M volume 0 = none else volume + 1, IT volume byte + 1
-- (0 = none). Tracker.cell / Tracker.setCell read and write cells.
-- samples { Sample }: { name, data (f32, interleaved when stereo), length (frames), channels, bits (8 | 16,
-- for writers), loopStart, loopEnd (frames, end exclusive), loopType (0 none, 1 forward, 2 ping-pong),
-- susStart, susEnd, susType (IT sustain loop), volume 0..64, globalVolume 0..64, pan (0..256 or nil),
-- c5speed (S3M / IT), relativeNote, finetune -128..127 (MOD / XM), vibType / vibSweep / vibDepth /
-- vibRate (IT auto-vibrato) }
-- instruments { Instrument }: { name, sampleMap = { [note] = sample number }, noteMap = { [note] = note },
-- volEnv / panEnv / pitchEnv (Envelope?), fadeout (as stored: XM 0..4095, IT 0..1024), nna (0 cut,
-- 1 continue, 2 note off, 3 fade), dct (0 off, 1 note, 2 sample, 3 instrument), dca (0 cut, 1 off,
-- 2 fade), globalVolume 0..128, pan (0..256 or nil), pps, ppc (pitch-pan separation / centre),
-- cutoff, resonance (0..127 or nil), vibType / vibSweep / vibDepth / vibRate (XM auto-vibrato) }
-- Envelope { enabled, ticks = { tick }, values = { volume 0..64 | pan / pitch -32..32 }, loop, loopStart,
-- loopEnd, sustain, susStart, susEnd (1-based point indexes), filter (IT pitch envelope as filter) }
--
-- Pitch: two period spaces. Linear: P = (ref - note) * 64 - transpose (64 per semitone), frequency = base * 2^(-P/768).
-- Amiga: P = 1712 * 8363 / base * 2^(Plinear / 768), frequency = 8363 * 1712 / P (FT2 / ST3 period units; slides add
-- 4 per effect unit in both). MOD / XM: base 8363, ref 49, transpose = relativeNote * 64 + finetune / 2; S3M / IT:
-- base = c5speed, ref 61.
--
-- Not supported: MIDI macros other than IT's default filter macros (Z00..Z8F), glissando, ST3 / IT finetune effects
-- (S2x), random volume / pan variation, OPL (AdLib) instruments, MOD Amiga low-pass filter emulation.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Player = require("@formats/codecs/Tracker/Player")
local Mixer = require("@formats/codecs/Tracker/Mixer")
local Pcm = require("@formats/codecs/Tracker/Pcm")
local Tables = require("@formats/codecs/Tracker/Tables")
local Tracker = {}
Tracker.Pcm = Pcm
Tracker.Tables = Tables
export type Envelope = {
enabled: boolean,
ticks: { number },
values: { number },
loop: boolean,
loopStart: number,
loopEnd: number,
sustain: boolean,
susStart: number,
susEnd: number,
carry: boolean?,
filter: boolean?,
raw: any?, -- format-specific fields kept for a faithful re-save (XM)
}
export type Pattern = { rows: number, data: buffer }
export type RenderOptions = {
sampleRate: number?, -- default 44100
interpolation: ("linear" | "none")?, -- default "linear"
stereoSeparation: number?, -- 0..200 % (default 100: the panning as stored; 200 doubles every distance from centre)
loop: boolean?, -- keep playing past the song's end (frames / duration still give one pass); default false
maxDuration: number?, -- seconds; the render stops there (default 3600)
}
local CELL = 5
-- ------------------------------------------------------------------------------------------------ constructors
-- newModule(format, channels) -> an empty Module (no patterns / samples) with the format's defaults
function Tracker.newModule(format: string, channels: number): any
local m = {
kind = "music",
format = format,
title = "",
channels = channels,
speed = 6,
tempo = 125,
globalVolume = 128,
mixVolume = 48,
order = {},
restart = 0,
linear = format == "xm" or format == "it",
instrumentMode = format == "xm" or format == "it",
flags = {},
channelPan = {},
channelVolume = {},
channelMute = {},
patterns = {},
instruments = {},
samples = {},
meta = {},
render = Tracker.renderMethod,
}
for i = 1, channels do
m.channelVolume[i] = 64
if format == "mod" then
local k = (i - 1) % 4
m.channelPan[i] = if k == 0 or k == 3 then 64 else 192 -- the Amiga's L R R L, at OpenMPT's default width
else
m.channelPan[i] = 128
end
end
return m
end
-- newPattern(rows, channels) -> an empty Pattern
function Tracker.newPattern(rows: number, channels: number): Pattern
return { rows = rows, data = buffer.create(rows * channels * CELL) }
end
-- newSample() -> an empty Sample
function Tracker.newSample(name: string?): any
return {
name = name or "",
data = buffer.create(0),
length = 0,
channels = 1,
bits = 8,
loopStart = 0,
loopEnd = 0,
loopType = 0,
susStart = 0,
susEnd = 0,
susType = 0,
volume = 64,
globalVolume = 64,
pan = nil :: number?,
c5speed = 8363,
relativeNote = 0,
finetune = 0,
vibType = 0,
vibSweep = 0,
vibDepth = 0,
vibRate = 0,
}
end
function Tracker.newEnvelope(): Envelope
return { enabled = false, ticks = {}, values = {}, loop = false, loopStart = 1, loopEnd = 1, sustain = false, susStart = 1, susEnd = 1 }
end
-- newInstrument() -> an Instrument mapping every note to sample 0 (none)
function Tracker.newInstrument(name: string?): any
local sm, nm = table.create(120, 0), table.create(120, 0)
for i = 1, 120 do
nm[i] = i
end
return {
name = name or "",
sampleMap = sm,
noteMap = nm,
volEnv = nil :: Envelope?,
panEnv = nil :: Envelope?,
pitchEnv = nil :: Envelope?,
fadeout = 0,
nna = 0,
dct = 0,
dca = 0,
globalVolume = 128,
pan = nil :: number?,
pps = 0,
ppc = 60,
cutoff = nil :: number?,
resonance = nil :: number?,
vibType = 0,
vibSweep = 0,
vibDepth = 0,
vibRate = 0,
}
end
-- cell(module, pattern, row, channel) -> note, instrument, volume, effect, parameter (pattern 0-based, row 0-based,
-- channel 1-based); nil when out of range
function Tracker.cell(m: any, pattern: number, row: number, channel: number): (number?, number, number, number, number)
local p = m.patterns[pattern + 1]
if not p or row < 0 or row >= p.rows or channel < 1 or channel > m.channels then
return nil, 0, 0, 0, 0
end
local o = (row * m.channels + channel - 1) * CELL
local d = p.data
return buffer.readu8(d, o), buffer.readu8(d, o + 1), buffer.readu8(d, o + 2), buffer.readu8(d, o + 3), buffer.readu8(d, o + 4)
end
-- setCell(module, pattern, row, channel, note, instrument, volume, effect, parameter) -> true | false (out of range)
function Tracker.setCell(m: any, pattern: number, row: number, channel: number, note: number, ins: number, vol: number, fx: number, param: number): boolean
local p = m.patterns[pattern + 1]
if not p or row < 0 or row >= p.rows or channel < 1 or channel > m.channels then
return false
end
local o = (row * m.channels + channel - 1) * CELL
local d = p.data
buffer.writeu8(d, o, note % 256)
buffer.writeu8(d, o + 1, ins % 256)
buffer.writeu8(d, o + 2, vol % 256)
buffer.writeu8(d, o + 3, fx % 256)
buffer.writeu8(d, o + 4, param % 256)
return true
end
-- ------------------------------------------------------------------------------------------------ validation
local function num(v: any, lo: number, hi: number): boolean
return type(v) == "number" and v == v and v >= lo and v <= hi
end
local function fixEnvelope(e: any): (any, string?)
if e == nil then
return nil
end
if type(e) ~= "table" or type(e.ticks) ~= "table" or type(e.values) ~= "table" then
return nil, "bad envelope"
end
local n = math.min(#e.ticks, #e.values)
local last = -1
for i = 1, n do
local t, v = e.ticks[i], e.values[i]
if not num(t, 0, 1e6) or not num(v, -64, 64) or t <= last then
-- points must go forward: keep the valid prefix
n = i - 1
break
end
last = t
end
for i = #e.ticks, n + 1, -1 do
e.ticks[i] = nil
end
for i = #e.values, n + 1, -1 do
e.values[i] = nil
end
if n == 0 then
e.enabled = false
end
local function idx(v: any): number
return if num(v, 1, math.max(1, n)) then math.floor(v) else 1
end
e.loopStart, e.loopEnd = idx(e.loopStart), idx(e.loopEnd)
e.susStart, e.susEnd = idx(e.susStart), idx(e.susEnd)
if e.loopEnd < e.loopStart then
e.loop = false
end
if e.susEnd < e.susStart then
e.sustain = false
end
return e
end
local function fixLoop(s0: any, e0: any, t0: any, len: number): (number, number, number)
if not num(t0, 0, 2) or t0 == 0 or not num(s0, -2 ^ 52, 2 ^ 52) or not num(e0, -2 ^ 52, 2 ^ 52) then
return 0, 0, 0
end
local s: number = math.floor(math.clamp(s0, 0, len))
local e: number = math.floor(math.clamp(e0, 0, len))
local t: number = math.floor(t0)
if e - s < 1 or t == 0 then
return 0, 0, 0
end
if t == 2 and e - s < 2 then
t = 1
end
return s, e, t
end
-- validate(module) -> true | nil, Err: checks the structure the engine relies on, clamps loops, envelopes and
-- numbers into range (in place)
function Tracker.validate(m: any): (boolean?, Err.Err?)
if type(m) ~= "table" then
return nil, Err.new(Err.ARG, "not a module")
end
if m.format ~= "mod" and m.format ~= "s3m" and m.format ~= "xm" and m.format ~= "it" then
return nil, Err.new(Err.ARG, "unknown tracker format " .. tostring(m.format))
end
if not num(m.channels, 1, 128) or m.channels % 1 ~= 0 then
return nil, Err.new(Err.ARG, "bad channel count")
end
if type(m.order) ~= "table" or type(m.patterns) ~= "table" or type(m.samples) ~= "table" then
return nil, Err.new(Err.ARG, "module without order / patterns / samples")
end
m.instruments = if type(m.instruments) == "table" then m.instruments else {}
m.flags = if type(m.flags) == "table" then m.flags else {}
m.channelPan = if type(m.channelPan) == "table" then m.channelPan else {}
m.channelVolume = if type(m.channelVolume) == "table" then m.channelVolume else {}
m.channelMute = if type(m.channelMute) == "table" then m.channelMute else {}
for i = 1, m.channels do
local p = m.channelPan[i]
if p ~= 512 and not num(p, 0, 256) then
m.channelPan[i] = 128
end
if not num(m.channelVolume[i], 0, 64) then
m.channelVolume[i] = 64
end
end
m.speed = if num(m.speed, 1, 255) then math.floor(m.speed) else 6
m.tempo = if num(m.tempo, 1, 1000) then m.tempo else 125
m.globalVolume = if num(m.globalVolume, 0, 128) then m.globalVolume else 128
m.mixVolume = if num(m.mixVolume, 0, 256) then m.mixVolume else 48
m.restart = if num(m.restart, 0, 1e6) then math.floor(m.restart) else 0
for i, o in m.order do
if not num(o, 0, 255) then
return nil, Err.new(Err.ARG, "bad order entry " .. i)
end
end
for i, p in m.patterns do
if type(p) ~= "table" or not num(p.rows, 1, 1024) or type(p.data) ~= "buffer" or buffer.len(p.data) < p.rows * m.channels * CELL then
return nil, Err.new(Err.ARG, "bad pattern " .. (i - 1))
end
end
for i, s in m.samples do
if type(s) ~= "table" then
return nil, Err.new(Err.ARG, "bad sample " .. i)
end
local nch = if s.channels == 2 then 2 else 1
s.channels = nch
if not num(s.length, 0, 2 ^ 31) or type(s.data) ~= "buffer" or buffer.len(s.data) < math.floor(s.length) * nch * 4 then
return nil, Err.new(Err.ARG, "sample " .. i .. ": data shorter than its length")
end
s.length = math.floor(s.length)
s.loopStart, s.loopEnd, s.loopType = fixLoop(s.loopStart or 0, s.loopEnd or 0, s.loopType or 0, s.length)
s.susStart, s.susEnd, s.susType = fixLoop(s.susStart or 0, s.susEnd or 0, s.susType or 0, s.length)
s.volume = if num(s.volume, 0, 64) then s.volume else 64
s.globalVolume = if num(s.globalVolume, 0, 64) then s.globalVolume else 64
if s.pan ~= nil and not num(s.pan, 0, 256) then
s.pan = nil
end
s.c5speed = if num(s.c5speed, 1, 1e7) then s.c5speed else 8363
s.relativeNote = if num(s.relativeNote, -128, 127) then s.relativeNote else 0
s.finetune = if num(s.finetune, -128, 127) then s.finetune else 0
end
for i, ins in m.instruments do
if type(ins) ~= "table" or type(ins.sampleMap) ~= "table" or type(ins.noteMap) ~= "table" then
return nil, Err.new(Err.ARG, "bad instrument " .. i)
end
for n = 1, 120 do
if not num(ins.sampleMap[n], 0, 1e6) then
ins.sampleMap[n] = 0
end
if not num(ins.noteMap[n], 1, 120) then
ins.noteMap[n] = n
end
end
local err
ins.volEnv, err = fixEnvelope(ins.volEnv)
if err then
return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err)
end
ins.panEnv, err = fixEnvelope(ins.panEnv)
if err then
return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err)
end
ins.pitchEnv, err = fixEnvelope(ins.pitchEnv)
if err then
return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err)
end
ins.fadeout = if num(ins.fadeout, 0, 65535) then ins.fadeout else 0
ins.globalVolume = if num(ins.globalVolume, 0, 128) then ins.globalVolume else 128
if ins.pan ~= nil and not num(ins.pan, 0, 256) then
ins.pan = nil
end
if ins.cutoff ~= nil and not num(ins.cutoff, 0, 127) then
ins.cutoff = nil
end
if ins.resonance ~= nil and not num(ins.resonance, 0, 127) then
ins.resonance = nil
end
end
return true, nil
end
-- ------------------------------------------------------------------------------------------------ rendering
local Decoder = {}
Decoder.__index = Decoder
-- duration(module, opts?) -> seconds of one pass (song loops and the end of the order list detected), or nil, Err
function Tracker.duration(m: any, opts: RenderOptions?): (number?, Err.Err?)
local ok, err = Tracker.validate(m)
if not ok then
return nil, err
end
local sr = opts and opts.sampleRate or 44100
local maxFrames = (opts and opts.maxDuration or 3600) * sr
local st = Player.new(m, sr, { stereoSeparation = 100 })
local frames = 0
while frames < maxFrames do
local f = Player.tick(st)
if f == 0 and st.ended then
break
end
frames += f
end
return math.min(frames, maxFrames) / sr, nil
end
local function newPlayer(self: any)
self.st = Player.new(self.module, self.sampleRate, self.opts)
self.st.ramp = math.max(1, math.floor(self.sampleRate * 0.0015))
self.left = 0
self.pos = 0
end
-- render(module, opts?) -> Types.Decoder (stereo f32) | nil, Err
function Tracker.render(m: any, opts: RenderOptions?): (Types.Decoder?, Err.Err?)
local o: RenderOptions = opts or {}
local sr = o.sampleRate or 44100
if type(sr) ~= "number" or sr < 1000 or sr > 384000 then
return nil, Err.new(Err.ARG, "sampleRate must be 1000..384000")
end
local seconds, err = Tracker.duration(m, o)
if not seconds then
return nil, err
end
local frames = math.floor(seconds * sr + 0.5)
local self = setmetatable({
sampleRate = sr,
channels = 2,
frames = frames,
duration = frames / sr,
bitrate = 0,
tags = { title = m.title or "" },
module = m,
opts = o,
linear = o.interpolation ~= "none",
maxFrames = (o.maxDuration or 3600) * sr,
st = nil :: any,
left = 0,
pos = 0,
}, Decoder)
newPlayer(self)
return self :: any, nil
end
-- the Module method: module:render(opts)
function Tracker.renderMethod(self: any, opts: RenderOptions?): Types.Decoder
local dec = Tracker.render(self, opts)
return dec :: any
end
-- run(self, out?, n) -> frames produced (out nil: advance without mixing)
local function run(self: any, out: buffer?, n: number): number
local st = self.st
local done = 0
while done < n do
if self.left <= 0 then
if self.pos + done >= self.maxFrames then
break
end
local f = Player.tick(st)
if f == 0 and st.ended then
break
end
self.left = f
if f == 0 then
continue
end
end
local k = math.min(self.left, n - done)
Mixer.mix(st, out, done, k, self.linear)
self.left -= k
done += k
end
self.pos += done
return done
end
-- read(n, out?) -> interleaved stereo f32 buffer, frames read (0 at the end)
function Decoder.read(self: any, n: number, out: buffer?): (buffer, number)
n = math.max(0, math.floor(tonumber(n) or 0))
local o = out
if o == nil or buffer.len(o) < n * 8 then
o = buffer.create(n * 8)
else
buffer.fill(o, 0, 0, n * 8)
end
local got = run(self, o, n)
return o :: buffer, got
end
-- seek(seconds): replays the song silently up to the position (sample positions included)
function Decoder.seek(self: any, seconds: number)
local target = math.max(0, math.floor((tonumber(seconds) or 0) * self.sampleRate))
newPlayer(self)
local chunk = 65536
while self.pos < target do
local got = run(self, nil, math.min(chunk, target - self.pos))
if got == 0 then
break
end
end
-- the gains ramp in from silence after a seek
for _, v in self.st.voices do
v.gl, v.gr = 0, 0
end
end
function Decoder.position(self: any): number
return self.pos / self.sampleRate
end
return Tracker
+193
View File
@@ -0,0 +1,193 @@
--!strict
-- containers/IsoBmff/Box: the box tree of an ISO BMFF / QuickTime file (ISO/IEC 14496-12 4.2): 32-bit, 64-bit
-- (size 1) and to-the-end (size 0) sizes, uuid boxes, full-box version / flags, and the recursion into the container
-- boxes (moov / trak / mdia / minf / stbl / udta / meta / ilst items / moof / traf / iprp / ipco / iref / dinf / ...).
-- Sample descriptions (stsd) are left to the demuxer, which knows the sample entry layouts. Never throws.
local Err = require("@formats/core/Err")
local readu8, readu32, readstring = buffer.readu8, buffer.readu32, buffer.readstring
local byteswap = bit32.byteswap
local Box = {}
export type Box = {
type: string, -- four characters ("moov", "\169nam", ...); "uuid" boxes also have `uuid`
start: number, -- absolute offset of the box in the buffer
size: number, -- the whole box, header included
data: number, -- absolute offset of the payload (after size / type / largesize / uuid)
stop: number, -- absolute offset just past the box (start + size, clamped to the parent)
uuid: string?,
children: { Box }?, -- container boxes
truncated: boolean?, -- the box claims more bytes than its parent has (clamped)
}
-- plain container boxes: their payload is a list of boxes
local CONTAINERS = {
moov = true, trak = true, mdia = true, minf = true, stbl = true, dinf = true, edts = true, udta = true,
mvex = true, moof = true, traf = true, mfra = true, tref = true, iprp = true, ipco = true, sinf = true,
schi = true, wave = true, gmhd = true, tapt = true, ilst = true, clip = true, matt = true, rinf = true,
strk = true, strd = true, grpl = true, meco = true, mere = true,
}
-- full boxes (version + flags) whose payload is then a list of boxes, after `skip` more bytes
local FULL_CONTAINERS: { [string]: number } = { meta = 0, iref = 0, dref = 4 }
Box.CONTAINERS = CONTAINERS
local function be32(b: buffer, o: number): number
return byteswap(readu32(b, o))
end
Box.be32 = be32
-- the ilst item boxes ("\169nam", "trkn", "----", ...) contain data / mean / name boxes
local function isIlstItem(parentType: string?): boolean
return parentType == "ilst"
end
-- header(buf, p, limit) -> Box (without children) | nil, Err
function Box.header(b: buffer, p: number, limit: number): (Box?, Err.Err?)
if p + 8 > limit then
return nil, Err.new(Err.TRUNCATED, "box header runs past the end", p)
end
local size = be32(b, p)
local typ = readstring(b, p + 4, 4)
local data = p + 8
if size == 1 then
if p + 16 > limit then
return nil, Err.new(Err.TRUNCATED, "64-bit box size runs past the end", p)
end
size = be32(b, p + 8) * 4294967296 + be32(b, p + 12)
data = p + 16
elseif size == 0 then
size = limit - p
end
local uuid: string? = nil
if typ == "uuid" then
if data + 16 > limit then
return nil, Err.new(Err.TRUNCATED, "uuid runs past the end", p)
end
uuid = readstring(b, data, 16)
data += 16
end
if size < data - p then
return nil, Err.new(Err.CORRUPT, string.format("box '%s' size %d is smaller than its header", typ, size), p)
end
local stop = p + size
local truncated: boolean? = nil
if stop > limit then
stop = limit
truncated = true
end
return { type = typ, start = p, size = size, data = data, stop = stop, uuid = uuid, children = nil, truncated = truncated }, nil
end
-- list(buf, p, limit, parentType?, depth?) -> { Box } (a run of sibling boxes, containers parsed recursively). A
-- broken box ends the list (its siblings so far are kept); the second value is the first error met, if any.
function Box.list(b: buffer, p: number, limit: number, parentType: string?, depth: number?): ({ Box }, Err.Err?)
local d = depth or 0
local out: { Box } = {}
local firstErr: Err.Err? = nil
if d > 32 then
return out, Err.new(Err.CORRUPT, "boxes nested too deep", p)
end
while p + 8 <= limit do
local box, err = Box.header(b, p, limit)
if not box then
firstErr = firstErr or err
break
end
if box.truncated then
firstErr = firstErr or Err.new(Err.TRUNCATED, "box '" .. box.type .. "' runs past the end", p)
end
local t = box.type
local kids: { Box }? = nil
local kerr: Err.Err? = nil
if CONTAINERS[t] or isIlstItem(parentType) then
kids, kerr = Box.list(b, box.data, box.stop, t, d + 1)
elseif FULL_CONTAINERS[t] then
local q = box.data + 4 + FULL_CONTAINERS[t]
-- QuickTime writes udta/meta as a plain container: its first child box follows directly
if t == "meta" and box.data + 8 <= box.stop and readstring(b, box.data + 4, 4) == "hdlr" then
q = box.data
end
if q <= box.stop then
kids, kerr = Box.list(b, q, box.stop, t, d + 1)
end
elseif t == "iinf" then
if box.data + 4 <= box.stop then
local v = readu8(b, box.data)
local q = box.data + 4 + (if v == 0 then 2 else 4)
if q <= box.stop then
kids, kerr = Box.list(b, q, box.stop, t, d + 1)
end
end
end
box.children = kids
if kerr then
firstErr = firstErr or kerr
end
table.insert(out, box)
if box.stop <= p then
break
end
p = box.stop
end
return out, firstErr
end
-- child(box, type) -> the first child of that type
function Box.child(box: Box?, typ: string): Box?
if not box or not box.children then
return nil
end
for _, c in box.children :: { Box } do
if c.type == typ then
return c
end
end
return nil
end
-- children(box, type) -> every child of that type
function Box.childrenOf(box: Box?, typ: string): { Box }
local out = {}
if box and box.children then
for _, c in box.children :: { Box } do
if c.type == typ then
table.insert(out, c)
end
end
end
return out
end
-- path(boxes or box, "moov/trak/mdia") -> the first box along the path
function Box.path(root: any, path: string): Box?
local cur: any = root
for part in string.gmatch(path, "[^/]+") do
if cur == nil then
return nil
end
local list = if cur.children ~= nil or cur.type ~= nil then cur.children else cur
local found = nil
if list then
for _, c in list do
if c.type == part then
found = c
break
end
end
end
cur = found
end
return cur
end
-- version / flags of a full box
function Box.fullHeader(b: buffer, box: Box): (number, number)
if box.data + 4 > box.stop then
return -1, 0
end
local v = be32(b, box.data)
return bit32.rshift(v, 24), bit32.band(v, 0xFFFFFF)
end
return Box
+848
View File
@@ -0,0 +1,848 @@
--!strict
-- containers/IsoBmff/Demux: tracks and sample tables of an ISO BMFF / QuickTime file (ISO/IEC 14496-12 8.3 - 8.8):
-- tkhd / mdhd / hdlr, sample descriptions (audio v0 / QuickTime v1 / v2, video, other) with the codec configuration
-- (esds DecoderSpecificInfo, alac, dOps, dfLa, avcC, hvcC, av1C, vpcC, dac3, ...), stts / ctts / stsc / stsz / stz2 /
-- stco / co64 / stss, edit lists (elst), and fragmented files (mvex / trex, moof / traf / tfhd / tfdt / trun).
-- The per-sample tables are columnar arrays (offsets / sizes / dts / durations / cts / sync), offsets absolute in the
-- reader's buffer. Never throws.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Box = require("@formats/containers/IsoBmff/Box")
local readstring = buffer.readstring
local Demux = {}
export type Edit = { duration: number, mediaTime: number, rate: number } -- duration in movie ticks, mediaTime in media ticks (-1 = empty)
-- a track: Types.Track (id, kind, codec, timescale, duration, width, height, sampleRate, channels, config) plus the
-- sample tables and the ISO facts
export type Track = {
id: number,
kind: "video" | "audio" | "subtitle" | "data",
codec: string, -- "aac", "alac", "mp3", "opus", "flac", "pcm", "h264", "hevc", "av1", "vp8", "vp9", "mpeg4", "mjpeg", "ac3", "eac3", "tx3g", ... or the entry fourcc
entry: string, -- the sample entry fourcc ("mp4a", "alac", "avc1", ...)
handler: string, -- hdlr type ("soun", "vide", "subt", "text", "pict", ...)
timescale: number,
duration: number, -- seconds (media duration; the edit list may shorten it)
mediaDuration: number, -- ticks
language: string?, -- ISO 639-2 ("und", "eng", ...)
width: number?,
height: number?,
sampleRate: number?,
channels: number?,
bitsPerSample: number?,
config: buffer?, -- codec configuration (AudioSpecificConfig, ALAC cookie, dOps, avcC, ...)
objectType: number?, -- esds objectTypeIndication
pcm: { bits: number, float: boolean, little: boolean }?,
entryBoxes: { Box.Box }, -- the sample entry's child boxes (esds, btrt, colr, pasp, ...)
edits: { Edit }?,
skip: number, -- media ticks to drop at the start (the first edit's media time: AAC priming)
delay: number, -- movie ticks of an initial empty edit
playDuration: number?, -- media ticks the edit list plays (nil: all)
-- samples
sampleCount: number,
offsets: { number }, -- absolute offsets in the buffer
sizes: { number },
dts: { number }, -- decode times in ticks
durations: { number },
cts: { number }?, -- composition offsets (pts = dts + cts) when the track has ctts / trun offsets
sync: { [number]: boolean }?, -- sync samples (nil: every sample is a sync sample)
sampleDescription: { number }?, -- stsd index per sample when there are several entries
[string]: any,
}
export type Options = { maxSamples: number? }
local HANDLER_KIND: { [string]: "video" | "audio" | "subtitle" | "data" } = {
soun = "audio", vide = "video", pict = "video", auxv = "video", subt = "subtitle", text = "subtitle",
sbtl = "subtitle", clcp = "subtitle",
}
local CODEC: { [string]: string } = {
mp4a = "aac", alac = "alac", Opus = "opus", fLaC = "flac", [".mp3"] = "mp3", ["ac-3"] = "ac3", ["ec-3"] = "eac3",
lpcm = "pcm", sowt = "pcm", twos = "pcm", ["raw "] = "pcm", in24 = "pcm", in32 = "pcm", fl32 = "pcm", fl64 = "pcm",
ipcm = "pcm", fpcm = "pcm", ulaw = "ulaw", alaw = "alaw", samr = "amr", sawb = "amrwb",
avc1 = "h264", avc3 = "h264", hvc1 = "hevc", hev1 = "hevc", av01 = "av1", vp08 = "vp8", vp09 = "vp9",
mp4v = "mpeg4", jpeg = "mjpeg", mjpa = "mjpeg", mjpb = "mjpeg", png = "png", ["s263"] = "h263", ["mp1v"] = "mpeg1",
["mp2v"] = "mpeg2", tx3g = "tx3g", wvtt = "webvtt", stpp = "ttml", c608 = "cea608", text = "text",
}
-- esds objectTypeIndication -> codec
local OTI: { [number]: string } = {
[0x40] = "aac", [0x66] = "aac", [0x67] = "aac", [0x68] = "aac", [0x69] = "mp3", [0x6B] = "mp3", [0x6A] = "mpeg1",
[0x60] = "mpeg2", [0x61] = "mpeg2", [0x20] = "mpeg4", [0x21] = "h264", [0x6C] = "mjpeg", [0xA5] = "ac3",
[0xA6] = "eac3", [0xAD] = "opus", [0xDD] = "vorbis",
}
-- the box holding each video / audio codec's configuration
local CONFIG_BOX = { "avcC", "hvcC", "av1C", "vpcC", "dOps", "dfLa", "dac3", "dec3", "d263", "glbl" }
local FULL_CONFIG: { [string]: boolean } = { vpcC = true, dfLa = true, alac = true }
local function payload(b: buffer, box: Box.Box, skip: number?): buffer
local o = box.data + (skip or 0)
local n = math.max(0, box.stop - o)
local out = buffer.create(n)
if n > 0 then
buffer.copy(out, 0, b, o, n)
end
return out
end
local function reader(b: buffer, box: Box.Box): Bytes.Reader
return Bytes.reader(b, box.data, box.stop - box.data)
end
-- expandable descriptor length (ISO 14496-1 8.3.3)
local function descLen(r: Bytes.Reader): number
local n = 0
for _ = 1, 4 do
local c = r:u8()
n = n * 128 + bit32.band(c, 127)
if c < 128 then
break
end
end
return n
end
-- esds -> objectTypeIndication, DecoderSpecificInfo, avg bitrate
function Demux.esds(b: buffer, box: Box.Box): (number?, buffer?, number?)
local r = reader(b, box)
r:skip(4) -- version / flags
if r:u8() ~= 3 then
return nil, nil, nil
end
descLen(r)
r:skip(2) -- ES_ID
local flags = r:u8()
if bit32.band(flags, 0x80) ~= 0 then
r:skip(2)
end
if bit32.band(flags, 0x40) ~= 0 then
r:skip(r:u8())
end
if bit32.band(flags, 0x20) ~= 0 then
r:skip(2)
end
if r:u8() ~= 4 then
return nil, nil, nil
end
local dlen = descLen(r)
local dstart = r.pos
local oti = r:u8()
r:skip(1 + 3 + 4) -- streamType, bufferSize, maxBitrate
local avg = r:u32be()
local dsi: buffer? = nil
if r.pos < dstart + dlen and r:u8() == 5 then
local n = descLen(r)
if n > 0 and r:need(n) then
dsi = r:bytes(n)
end
end
if r.err then
return oti, nil, nil
end
return oti, dsi, avg
end
-- the sample entry `e` of a track with handler `handler`: fills the codec facts into t
local function sampleEntry(b: buffer, e: Box.Box, handler: string, t: Track)
local r = reader(b, e)
r:skip(6)
r:skip(2) -- data reference index
local typ = e.type
t.entry = typ
t.codec = CODEC[typ] or typ
local kind = t.kind
local childStart
if kind == "audio" then
local version = r:u16be()
r:skip(2 + 4) -- revision, vendor
local channels = r:u16be()
local bits = r:u16be()
r:skip(4) -- compression id, packet size
local rate = r:u32be() / 65536
if version == 1 then
r:skip(16)
elseif version == 2 then
r:skip(4)
rate = r:f64be()
channels = r:u32be()
r:skip(4)
bits = r:u32be()
local lpcmFlags = r:u32be()
r:skip(8)
if typ == "lpcm" then
t.pcm = {
bits = bits,
float = bit32.band(lpcmFlags, 1) ~= 0,
little = bit32.band(lpcmFlags, 2) == 0,
}
end
end
t.channels, t.sampleRate, t.bitsPerSample = channels, rate, bits
if not t.pcm and t.codec == "pcm" then
local B: { [string]: number } = { sowt = 16, twos = 16, ["raw "] = 8, in24 = 24, in32 = 32, fl32 = 32, fl64 = 64 }
t.pcm = {
bits = B[typ] or bits,
float = typ == "fl32" or typ == "fl64",
little = typ == "sowt",
}
end
childStart = r.pos
elseif kind == "video" then
r:skip(16)
t.width = r:u16be()
t.height = r:u16be()
r:skip(4 + 4 + 4 + 2 + 32 + 2 + 2)
childStart = r.pos
else
childStart = r.pos
end
if r.err then
t.entryBoxes = {}
return
end
local kids = Box.list(b, childStart, e.stop, typ)
t.entryBoxes = kids
-- QuickTime puts the codec boxes inside 'wave'
local all = table.clone(kids)
local wave = Box.child({ type = "", start = 0, size = 0, data = 0, stop = 0, children = kids } :: any, "wave")
if wave and wave.children then
for _, c in wave.children :: { Box.Box } do
table.insert(all, c)
end
end
local holder = { type = "", start = 0, size = 0, data = 0, stop = 0, children = all } :: any
local esds = Box.child(holder, "esds")
if esds then
local oti, dsi, avg = Demux.esds(b, esds)
t.objectType = oti
if oti and OTI[oti] then
t.codec = OTI[oti]
end
t.config = dsi
if avg and avg > 0 then
t.bitrate = avg
end
end
if typ == "alac" then
local a = Box.child(holder, "alac")
if a then
t.config = payload(b, a, 4)
end
end
for _, name in CONFIG_BOX do
local c = Box.child(holder, name)
if c then
t.config = payload(b, c, if FULL_CONFIG[name] then 4 else 0)
break
end
end
end
-- media handler / header / sample tables of one trak -> Track | nil, Err
local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [number]: any }, o: Options): (Track?, Err.Err?)
local tkhd = Box.child(trak, "tkhd")
local mdia = Box.child(trak, "mdia")
if not tkhd or not mdia then
return nil, Err.new(Err.CORRUPT, "trak without tkhd / mdia", trak.start)
end
local t: Track = {
id = 0, kind = "data", codec = "", entry = "", handler = "", timescale = 1, duration = 0, mediaDuration = 0,
entryBoxes = {}, skip = 0, delay = 0, sampleCount = 0, offsets = {}, sizes = {}, dts = {}, durations = {},
}
do
local r = reader(b, tkhd)
local v = r:u8()
r:skip(3)
if v == 1 then
r:skip(16)
t.id = r:u32be()
r:skip(4 + 8)
else
r:skip(8)
t.id = r:u32be()
r:skip(4 + 4)
end
r:skip(8 + 2 + 2 + 2 + 2 + 36)
local w, h = r:u32be() / 65536, r:u32be() / 65536
if r.err then
return nil, r.err
end
if w > 0 and h > 0 then
t.width, t.height = math.floor(w), math.floor(h)
end
end
local mdhd = Box.child(mdia, "mdhd")
if mdhd then
local r = reader(b, mdhd)
local v = r:u8()
r:skip(3)
if v == 1 then
r:skip(16)
t.timescale = r:u32be()
t.mediaDuration = r:u64be()
else
r:skip(8)
t.timescale = r:u32be()
t.mediaDuration = r:u32be()
end
local lang = r:u16be()
if not r.err and lang ~= 0 and lang ~= 0x7FFF then
t.language = string.char(
96 + bit32.band(bit32.rshift(lang, 10), 31),
96 + bit32.band(bit32.rshift(lang, 5), 31),
96 + bit32.band(lang, 31)
)
end
if t.timescale == 0 then
t.timescale = 1
end
end
local hdlr = Box.child(mdia, "hdlr")
if hdlr and hdlr.data + 12 <= hdlr.stop then
t.handler = readstring(b, hdlr.data + 8, 4)
end
t.kind = HANDLER_KIND[t.handler] or "data"
local stbl = Box.path(mdia, "minf/stbl")
if not stbl then
return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " has no sample table", mdia.start)
end
-- sample descriptions
local stsd = Box.child(stbl, "stsd")
if stsd and stsd.data + 8 <= stsd.stop then
local entries = Box.list(b, stsd.data + 8, stsd.stop, "stsd")
if entries[1] then
sampleEntry(b, entries[1], t.handler, t)
end
t.sampleEntries = entries
end
-- edit list
local elst = Box.path(trak, "edts/elst")
if elst then
local r = reader(b, elst)
local v = r:u8()
r:skip(3)
local n = r:u32be()
if n <= (elst.stop - elst.data) // 12 then
local edits = {}
for _ = 1, n do
local dur, mt
if v == 1 then
dur, mt = r:u64be(), r:i64be()
else
dur, mt = r:u32be(), r:i32be()
end
local rate = r:i32be() / 65536
if r.err then
break
end
table.insert(edits, { duration = dur, mediaTime = mt, rate = rate })
end
t.edits = edits
local play = 0
local started = false
for _, ed in edits do
if ed.mediaTime == -1 then
if not started then
t.delay += ed.duration
end
else
if not started then
t.skip = ed.mediaTime
started = true
end
play += ed.duration * t.timescale / math.max(1, movieTimescale)
end
end
if started and play > 0 then
t.playDuration = math.floor(play + 0.5)
end
end
end
-- sample sizes
local maxSamples = o.maxSamples or 2 ^ 25
local sizes = t.sizes
local count = 0
local stsz = Box.child(stbl, "stsz")
local stz2 = Box.child(stbl, "stz2")
if stsz then
local r = reader(b, stsz)
r:skip(4)
local fixed = r:u32be()
count = r:u32be()
if r.err then
return nil, r.err
end
if count > maxSamples then
return nil, Err.new(Err.LIMIT, string.format("track %d has %d samples (limit %d)", t.id, count, maxSamples), stsz.start)
end
if fixed ~= 0 then
for i = 1, count do
sizes[i] = fixed
end
else
if count * 4 > r:remaining() then
return nil, Err.new(Err.TRUNCATED, "stsz table runs past its box", stsz.start)
end
for i = 1, count do
sizes[i] = r:u32be()
end
end
elseif stz2 then
local r = reader(b, stz2)
r:skip(4 + 3)
local fieldSize = r:u8()
count = r:u32be()
if r.err then
return nil, r.err
end
if fieldSize ~= 4 and fieldSize ~= 8 and fieldSize ~= 16 then
return nil, Err.new(Err.CORRUPT, "bad stz2 field size " .. fieldSize, stz2.start)
end
if count * fieldSize / 8 > r:remaining() + 1 then
return nil, Err.new(Err.TRUNCATED, "stz2 table runs past its box", stz2.start)
end
for i = 1, count do
if fieldSize == 16 then
sizes[i] = r:u16be()
elseif fieldSize == 8 then
sizes[i] = r:u8()
else
local byte = r:peekU8()
if i % 2 == 1 then
sizes[i] = bit32.rshift(math.max(byte, 0), 4)
else
sizes[i] = bit32.band(math.max(byte, 0), 15)
r:skip(1)
end
end
end
end
-- decode times
local dts, durs = t.dts, t.durations
local stts = Box.child(stbl, "stts")
if stts and count > 0 then
local r = reader(b, stts)
r:skip(4)
local n = r:u32be()
if n * 8 > r:remaining() then
return nil, Err.new(Err.TRUNCATED, "stts table runs past its box", stts.start)
end
local i, time = 1, 0
for _ = 1, n do
local c, d = r:u32be(), r:u32be()
for _ = 1, c do
if i > count then
break
end
dts[i], durs[i] = time, d
time += d
i += 1
end
end
-- fewer stts entries than samples: repeat the last duration
local last = if i > 1 then durs[i - 1] else 0
while i <= count do
dts[i], durs[i] = time, last
time += last
i += 1
end
else
for i = 1, count do
dts[i], durs[i] = 0, 0
end
end
-- composition offsets
local ctts = Box.child(stbl, "ctts")
if ctts and count > 0 then
local r = reader(b, ctts)
local v = r:u8()
r:skip(3)
local n = r:u32be()
if n * 8 <= r:remaining() then
local cts = table.create(count, 0)
local i = 1
for _ = 1, n do
local c = r:u32be()
local off = if v == 1 then r:i32be() else r:u32be()
if v == 0 and off >= 2147483648 then
off -= 4294967296 -- writers put negative offsets in version 0 too
end
for _ = 1, c do
if i > count then
break
end
cts[i] = off
i += 1
end
end
t.cts = cts
end
end
-- sync samples
local stss = Box.child(stbl, "stss")
if stss then
local r = reader(b, stss)
r:skip(4)
local n = r:u32be()
if n * 4 <= r:remaining() then
local sync = {}
for _ = 1, n do
sync[r:u32be()] = true
end
t.sync = sync
end
end
-- chunk offsets + sample-to-chunk -> sample offsets
local stco = Box.child(stbl, "stco")
local co64 = Box.child(stbl, "co64")
local chunks: { number } = {}
if stco or co64 then
local box = (stco or co64) :: Box.Box
local r = reader(b, box)
r:skip(4)
local n = r:u32be()
local w = if co64 then 8 else 4
if n * w > r:remaining() then
return nil, Err.new(Err.TRUNCATED, "chunk offset table runs past its box", box.start)
end
for i = 1, n do
chunks[i] = if co64 then r:u64be() else r:u32be()
end
end
local stsc = Box.child(stbl, "stsc")
local offsets = t.offsets
if count > 0 then
if not stsc or #chunks == 0 then
return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " has samples but no stsc / stco", stbl.start)
end
local r = reader(b, stsc)
r:skip(4)
local n = r:u32be()
if n * 12 > r:remaining() then
return nil, Err.new(Err.TRUNCATED, "stsc table runs past its box", stsc.start)
end
local first, per, desc = {}, {}, {}
for k = 1, n do
first[k], per[k], desc[k] = r:u32be(), r:u32be(), r:u32be()
end
local sdi: { number }? = nil
if n > 0 then
for k = 1, n do
if desc[k] ~= desc[1] then
sdi = table.create(count, 1)
end
end
end
local i = 1
local base = 0 -- added by the caller (the file's offset in the buffer)
for k = 1, n do
local c0 = first[k]
local c1 = if k < n then first[k + 1] - 1 else #chunks
if c0 < 1 then
return nil, Err.new(Err.CORRUPT, "stsc first chunk 0", stsc.start)
end
for c = c0, math.min(c1, #chunks) do
local off = chunks[c] + base
for _ = 1, per[k] do
if i > count then
break
end
offsets[i] = off
if sdi then
sdi[i] = desc[k]
end
off += sizes[i]
i += 1
end
if i > count then
break
end
end
if i > count then
break
end
end
if i <= count then
return nil, Err.new(Err.CORRUPT, string.format("track %d: the chunks hold %d of %d samples", t.id, i - 1, count), stsc.start)
end
t.sampleDescription = sdi
end
t.sampleCount = count
-- QuickTime PCM: one "sample" per sample frame (constant size, duration 1). Regroup into packets of up to 1024
-- frames within each chunk (as ffmpeg does), so a packet is a useful amount of audio.
if t.kind == "audio" and count > 1 and not t.cts and not t.sync then
local fixed = sizes[1]
local uniform = fixed > 0
for i = 1, count do
if sizes[i] ~= fixed or durs[i] ~= 1 then
uniform = false
break
end
end
if uniform then
local no, ns, nd, nu = {}, {}, {}, {}
local i = 1
while i <= count do
local k = 1
while k < 1024 and i + k <= count and offsets[i + k] == offsets[i] + k * fixed do
k += 1
end
table.insert(no, offsets[i])
table.insert(ns, k * fixed)
table.insert(nd, dts[i])
table.insert(nu, k)
i += k
end
t.offsets, t.sizes, t.dts, t.durations = no, ns, nd, nu
t.sampleCount = #no
t.frameSize = fixed
t.sampleDescription = nil
end
end
-- fragment defaults
t.trex = trex[t.id]
return t, nil
end
-- the movie fragments (moof) after the moov: appends their samples to the tracks
local function fragments(b: buffer, fileBase: number, top: { Box.Box }, byId: { [number]: Track }, o: Options): Err.Err?
local maxSamples = o.maxSamples or 2 ^ 25
for _, moof in top do
if moof.type ~= "moof" then
continue
end
local moofStart = moof.start - fileBase -- file offsets (r.base is added at the end)
local prevEnd = moofStart
for _, traf in Box.childrenOf(moof, "traf") do
local tfhd = Box.child(traf, "tfhd")
if not tfhd then
continue
end
local r = reader(b, tfhd)
r:skip(1)
local flags = r:u24be()
local id = r:u32be()
local t = byId[id]
if r.err or not t then
continue
end
local trex = t.trex or {}
local base
if bit32.band(flags, 0x1) ~= 0 then
base = r:u64be()
elseif bit32.band(flags, 0x20000) ~= 0 then
base = moofStart
else
base = prevEnd
end
if bit32.band(flags, 0x2) ~= 0 then
r:skip(4)
end
local defDur = if bit32.band(flags, 0x8) ~= 0 then r:u32be() else (trex.duration or 0)
local defSize = if bit32.band(flags, 0x10) ~= 0 then r:u32be() else (trex.size or 0)
local defFlags = if bit32.band(flags, 0x20) ~= 0 then r:u32be() else (trex.flags or 0)
if r.err then
return r.err
end
local n0 = t.sampleCount
local time = if n0 > 0 then t.dts[n0] + t.durations[n0] else 0
local tfdt = Box.child(traf, "tfdt")
if tfdt then
local q = reader(b, tfdt)
local v = q:u8()
q:skip(3)
local bt = if v == 1 then q:u64be() else q:u32be()
if not q.err then
time = bt
end
end
local dataPos = base
for _, trun in Box.childrenOf(traf, "trun") do
local q = reader(b, trun)
local v = q:u8()
local tf = q:u24be()
local n = q:u32be()
if q.err then
return q.err
end
if t.sampleCount + n > maxSamples then
return Err.new(Err.LIMIT, "too many fragment samples", trun.start)
end
if bit32.band(tf, 0x1) ~= 0 then
dataPos = base + q:i32be()
end
local firstFlags = if bit32.band(tf, 0x4) ~= 0 then q:u32be() else nil
local per = 0
for _, bit in { 0x100, 0x200, 0x400, 0x800 } do
if bit32.band(tf, bit) ~= 0 then
per += 4
end
end
if n * per > q:remaining() then
return Err.new(Err.TRUNCATED, "trun table runs past its box", trun.start)
end
for k = 1, n do
local dur = if bit32.band(tf, 0x100) ~= 0 then q:u32be() else defDur
local size = if bit32.band(tf, 0x200) ~= 0 then q:u32be() else defSize
local sf = if bit32.band(tf, 0x400) ~= 0 then q:u32be() else (if k == 1 and firstFlags then firstFlags else defFlags)
local cto = 0
if bit32.band(tf, 0x800) ~= 0 then
cto = if v == 1 then q:i32be() else q:u32be()
end
local i = t.sampleCount + 1
t.sampleCount = i
t.offsets[i] = dataPos
t.sizes[i] = size
t.dts[i] = time
t.durations[i] = dur
if cto ~= 0 or t.cts then
if not t.cts then
t.cts = table.create(i - 1, 0)
end
(t.cts :: { number })[i] = cto
end
-- sample_is_non_sync_sample (bit 16)
local nonSync = bit32.band(sf, 0x10000) ~= 0
if nonSync then
if not t.sync then
local s = {}
for j = 1, i - 1 do
s[j] = true
end
t.sync = s
end
elseif t.sync then
(t.sync :: any)[i] = true
end
time += dur
dataPos += size
end
prevEnd = dataPos
end
end
end
return nil
end
export type Movie = {
brand: string?,
minor: number?,
compatible: { string },
timescale: number,
duration: number, -- seconds
tracks: { Track },
boxes: { Box.Box },
moov: Box.Box?,
fragmented: boolean,
}
-- parse(r, opts) -> Movie | nil, Err: the box tree, ftyp, mvhd and every track (fragments included)
function Demux.parse(r: Bytes.Reader, opts: Options?): (Movie?, Err.Err?)
local o = opts or {}
local b = r.buf
local top, terr = Box.list(b, r.base, r.limit)
if #top == 0 then
return nil, terr or Err.new(Err.CORRUPT, "no boxes", r.base)
end
local m: Movie = { compatible = {}, timescale = 1000, duration = 0, tracks = {}, boxes = top, fragmented = false }
local ftyp = Box.child({ children = top } :: any, "ftyp")
if ftyp and ftyp.data + 8 <= ftyp.stop then
m.brand = readstring(b, ftyp.data, 4)
m.minor = Box.be32(b, ftyp.data + 4)
local p = ftyp.data + 8
while p + 4 <= ftyp.stop do
table.insert(m.compatible, readstring(b, p, 4))
p += 4
end
end
local moov = Box.child({ children = top } :: any, "moov")
m.moov = moov
if not moov then
return m, nil -- an image file (HEIF / AVIF) or a fragment: no tracks
end
local mvhd = Box.child(moov, "mvhd")
local movieDuration = 0
if mvhd then
local q = reader(b, mvhd)
local v = q:u8()
q:skip(3)
if v == 1 then
q:skip(16)
m.timescale = q:u32be()
movieDuration = q:u64be()
else
q:skip(8)
m.timescale = q:u32be()
movieDuration = q:u32be()
end
if q.err or m.timescale == 0 then
m.timescale = 1000
end
end
local trex = {}
local mvex = Box.child(moov, "mvex")
if mvex then
m.fragmented = true
for _, x in Box.childrenOf(mvex, "trex") do
local q = reader(b, x)
q:skip(4)
local id = q:u32be()
q:skip(4)
local d = { duration = q:u32be(), size = q:u32be(), flags = q:u32be() }
if not q.err then
trex[id] = d
end
end
end
local byId = {}
for _, trak in Box.childrenOf(moov, "trak") do
local t, err = track(b, trak, m.timescale, trex, o)
if not t then
return nil, err
end
table.insert(m.tracks, t)
byId[t.id] = t
end
if m.fragmented then
local ferr = fragments(b, r.base, top, byId, o)
if ferr then
return nil, ferr
end
end
-- durations; drop samples outside the buffer (a truncated file) but keep what is there
for _, t in m.tracks do
local n = t.sampleCount
local ticks = t.mediaDuration
if n > 0 then
ticks = math.max(ticks, t.dts[n] + t.durations[n])
end
t.mediaDuration = ticks
t.duration = ticks / t.timescale
for i = 1, n do
local off = t.offsets[i]
if off < 0 or off + t.sizes[i] > r.limit - r.base then
t.sampleCount = i - 1
t.truncated = true
break
end
end
-- the tables hold file offsets; make them buffer offsets
local base = r.base
if base ~= 0 then
local offs = t.offsets
for i = 1, t.sampleCount do
offs[i] += base
end
end
end
m.duration = movieDuration / m.timescale
if m.duration == 0 then
for _, t in m.tracks do
m.duration = math.max(m.duration, t.duration)
end
end
return m, nil
end
return Demux
+526
View File
@@ -0,0 +1,526 @@
--!strict
-- containers/IsoBmff/Meta: the metadata boxes. HEIF / AVIF items (ISO/IEC 23008-12: pitm, iinf / infe, iloc
-- versions 0 - 2, iref, iprp / ipco / ipma, idat; the common properties ispe / pixi / colr / irot / imir / clap / auxC
-- decoded, codec configurations av1C / hvcC / avcC kept raw) and the iTunes tags (udta / meta / ilst: text, trkn /
-- disk, tmpo / cpil, gnre, covr pictures, '----' freeform), plus the ilst writer used by the muxer.
-- Never throws.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Box = require("@formats/containers/IsoBmff/Box")
local readstring = buffer.readstring
local Meta = {}
local function reader(b: buffer, box: Box.Box): Bytes.Reader
return Bytes.reader(b, box.data, box.stop - box.data)
end
local function uint(r: Bytes.Reader, size: number): number
if size == 0 then
return 0
elseif size == 4 then
return r:u32be()
elseif size == 8 then
return r:u64be()
elseif size == 2 then
return r:u16be()
elseif size == 1 then
return r:u8()
end
r:fail(Err.CORRUPT, "bad iloc field size " .. size)
return 0
end
-- ------------------------------------------------------------------------------------------------ HEIF items
export type Property = { type: string, box: Box.Box, [string]: any }
export type Item = {
id: number,
type: string, -- "av01", "hvc1", "grid", "Exif", "mime", ...
name: string,
contentType: string?,
hidden: boolean,
construction: number, -- iloc construction method (0 file offset, 1 idat, 2 item)
baseOffset: number,
extents: { { offset: number, length: number } },
properties: { Property }, -- in ipma order
essential: { [number]: boolean }, -- by index into properties
refs: { [string]: { number } }, -- iref type -> item ids (dimg, thmb, auxl, cdsc, ...)
}
export type Items = {
primary: number?,
items: { [number]: Item },
order: { number }, -- item ids in iinf order
idat: Box.Box?,
properties: { Property }, -- ipco, in order
}
local function property(b: buffer, box: Box.Box): Property
local p: Property = { type = box.type, box = box }
local r = reader(b, box)
local t = box.type
if t == "ispe" then
r:skip(4)
p.width, p.height = r:u32be(), r:u32be()
elseif t == "pixi" then
r:skip(4)
local n = r:u8()
local bits = {}
for i = 1, math.min(n, 16) do
bits[i] = r:u8()
end
p.bits = bits
elseif t == "colr" then
local ct = r:string(4)
p.colourType = ct
if ct == "nclx" then
p.primaries, p.transfer, p.matrix = r:u16be(), r:u16be(), r:u16be()
p.fullRange = bit32.band(r:u8(), 0x80) ~= 0
elseif ct == "rICC" or ct == "prof" then
p.icc = r:bytes(r:remaining())
end
elseif t == "irot" then
p.angle = bit32.band(r:u8(), 3) * 90
elseif t == "imir" then
p.axis = bit32.band(r:u8(), 1)
elseif t == "clap" then
local function frac(): number
local n, d = r:i32be(), r:u32be()
return if d == 0 then 0 else n / d
end
p.width, p.height, p.horizOff, p.vertOff = frac(), frac(), frac(), frac()
elseif t == "auxC" then
r:skip(4)
p.auxType = r:cstring()
else
local n = box.stop - box.data
local cfg = buffer.create(math.max(0, n))
if n > 0 then
buffer.copy(cfg, 0, b, box.data, n)
end
p.config = cfg
end
return p
end
-- items(buf, meta) -> Items | nil, Err (meta: a top-level 'meta' box)
function Meta.items(b: buffer, meta: Box.Box): (Items?, Err.Err?)
local out: Items = { items = {}, order = {}, properties = {} }
local pitm = Box.child(meta, "pitm")
if pitm then
local r = reader(b, pitm)
local v = r:u8()
r:skip(3)
out.primary = if v == 0 then r:u16be() else r:u32be()
end
local iinf = Box.child(meta, "iinf")
if iinf then
for _, infe in Box.childrenOf(iinf, "infe") do
local r = reader(b, infe)
local v = r:u8()
local flags = r:u24be()
local it: Item = {
id = 0, type = "", name = "", hidden = bit32.band(flags, 1) ~= 0, construction = 0, baseOffset = 0,
extents = {}, properties = {}, essential = {}, refs = {},
}
if v >= 2 then
it.id = if v == 2 then r:u16be() else r:u32be()
r:skip(2)
it.type = r:string(4)
it.name = r:cstring()
if it.type == "mime" and r:remaining() > 0 then
it.contentType = r:cstring()
end
else
it.id = r:u16be()
r:skip(2)
it.name = r:cstring()
it.contentType = r:cstring()
it.type = "mime"
end
if r.err and it.id == 0 then
return nil, r.err
end
out.items[it.id] = it
table.insert(out.order, it.id)
end
end
local iloc = Box.child(meta, "iloc")
if iloc then
local r = reader(b, iloc)
local v = r:u8()
r:skip(3)
local a, c = r:u8(), r:u8()
local offSize, lenSize, baseSize = bit32.rshift(a, 4), bit32.band(a, 15), bit32.rshift(c, 4)
local idxSize = if v >= 1 then bit32.band(c, 15) else 0
local n = if v < 2 then r:u16be() else r:u32be()
if r.err then
return nil, r.err
end
for _ = 1, n do
local id = if v < 2 then r:u16be() else r:u32be()
local method = 0
if v >= 1 then
method = bit32.band(r:u16be(), 15)
end
r:skip(2) -- data reference index
local base = uint(r, baseSize)
local ne = r:u16be()
if r.err then
return nil, r.err
end
if ne * (offSize + lenSize + idxSize) > r:remaining() then
return nil, Err.new(Err.TRUNCATED, "iloc extents run past the box", iloc.start)
end
local extents = {}
for k = 1, ne do
if idxSize > 0 then
uint(r, idxSize)
end
extents[k] = { offset = base + uint(r, offSize), length = uint(r, lenSize) }
end
if r.err then
return nil, r.err
end
local it = out.items[id]
if not it then
it = {
id = id, type = "", name = "", hidden = false, construction = 0, baseOffset = 0, extents = {},
properties = {}, essential = {}, refs = {},
}
out.items[id] = it
table.insert(out.order, id)
end
it.construction, it.baseOffset, it.extents = method, base, extents
end
end
local iref = Box.child(meta, "iref")
if iref then
local v = Box.fullHeader(b, iref)
for _, ref in (iref.children or {}) :: { Box.Box } do
local r = reader(b, ref)
local from = if v == 0 then r:u16be() else r:u32be()
local n = r:u16be()
local to = {}
for k = 1, n do
to[k] = if v == 0 then r:u16be() else r:u32be()
end
local it = out.items[from]
if it and not r.err then
it.refs[ref.type] = to
end
end
end
local ipco = Box.path(meta, "iprp/ipco")
if ipco and ipco.children then
for i, pb in ipco.children :: { Box.Box } do
out.properties[i] = property(b, pb)
end
end
local ipma = Box.path(meta, "iprp/ipma")
if ipma then
local r = reader(b, ipma)
local v = r:u8()
local flags = r:u24be()
local n = r:u32be()
for _ = 1, n do
if r.err then
break
end
local id = if v < 1 then r:u16be() else r:u32be()
local na = r:u8()
local it = out.items[id]
for _ = 1, na do
local idx, ess
if bit32.band(flags, 1) ~= 0 then
local x = r:u16be()
idx, ess = bit32.band(x, 0x7FFF), x >= 0x8000
else
local x = r:u8()
idx, ess = bit32.band(x, 0x7F), x >= 0x80
end
local p = out.properties[idx]
if it and p and not r.err then
table.insert(it.properties, p)
if ess then
it.essential[#it.properties] = true
end
end
end
end
end
out.idat = Box.child(meta, "idat")
return out, nil
end
-- itemData(buf, base, limit, items, id) -> buffer | nil, Err: the item's bytes (extents concatenated); base / limit
-- bound the file in the buffer
function Meta.itemData(b: buffer, base: number, limit: number, items: Items, id: number): (buffer?, Err.Err?)
local it = items.items[id]
if not it then
return nil, Err.new(Err.CORRUPT, "no item " .. id)
end
local origin, stop
if it.construction == 0 then
origin, stop = base, limit
elseif it.construction == 1 then
local idat = items.idat
if not idat then
return nil, Err.new(Err.CORRUPT, "item " .. id .. " is in a missing idat")
end
origin, stop = idat.data, idat.stop
else
return nil, Err.new(Err.UNSUPPORTED, "item construction method " .. it.construction)
end
local total = 0
for _, e in it.extents do
local len = e.length
if len == 0 then -- the whole rest of the file
len = stop - origin - e.offset
end
if e.offset < 0 or len < 0 or origin + e.offset + len > stop then
return nil, Err.new(Err.TRUNCATED, "item " .. id .. " runs past the end")
end
total += len
end
if total > 2 ^ 30 then
return nil, Err.new(Err.LIMIT, "item " .. id .. " is too big")
end
local out = buffer.create(total)
local p = 0
for _, e in it.extents do
local len = if e.length == 0 then stop - origin - e.offset else e.length
buffer.copy(out, p, b, origin + e.offset, len)
p += len
end
return out, nil
end
-- ------------------------------------------------------------------------------------------------ iTunes tags
-- ilst item -> standard tag name
local TAG: { [string]: string } = {
["\169nam"] = "title", ["\169ART"] = "artist", aART = "albumartist", ["\169alb"] = "album", ["\169day"] = "date",
["\169gen"] = "genre", ["\169cmt"] = "comment", ["\169wrt"] = "composer", ["\169too"] = "encoder",
["\169lyr"] = "lyrics", ["\169grp"] = "grouping", cprt = "copyright", desc = "description", ldes = "longdescription",
sonm = "titlesort", soar = "artistsort", soal = "albumsort", soaa = "albumartistsort", soco = "composersort",
tvsh = "show", ["\169st3"] = "subtitle", ["\169wrk"] = "work", ["\169mvn"] = "movement", purd = "purchasedate",
["\169pub"] = "publisher", ["\169xyz"] = "location",
}
local TAG_ATOM: { [string]: string } = {}
for atom, name in TAG do
TAG_ATOM[name] = atom
end
Meta.TAG = TAG
Meta.TAG_ATOM = TAG_ATOM
-- the ID3v1 genres gnre indexes (1-based in gnre)
local GENRES = {
"Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", "Grunge", "Hip-Hop", "Jazz", "Metal", "New Age",
"Oldies", "Other", "Pop", "R&B", "Rap", "Reggae", "Rock", "Techno", "Industrial", "Alternative", "Ska",
"Death Metal", "Pranks", "Soundtrack", "Euro-Techno", "Ambient", "Trip-Hop", "Vocal", "Jazz+Funk", "Fusion",
"Trance", "Classical", "Instrumental", "Acid", "House", "Game", "Sound Clip", "Gospel", "Noise", "AlternRock",
"Bass", "Soul", "Punk", "Space", "Meditative", "Instrumental Pop", "Instrumental Rock", "Ethnic", "Gothic",
"Darkwave", "Techno-Industrial", "Electronic", "Pop-Folk", "Eurodance", "Dream", "Southern Rock", "Comedy", "Cult",
"Gangsta", "Top 40", "Christian Rap", "Pop/Funk", "Jungle", "Native American", "Cabaret", "New Wave",
"Psychadelic", "Rave", "Showtunes", "Trailer", "Lo-Fi", "Tribal", "Acid Punk", "Acid Jazz", "Polka", "Retro",
"Musical", "Rock & Roll", "Hard Rock",
}
export type Picture = { mime: string, data: buffer }
-- tags(buf, ilst) -> Tags, { Picture }
function Meta.tags(b: buffer, ilst: Box.Box?): ({ [string]: string }, { Picture })
local tags: { [string]: string } = {}
local pics: { Picture } = {}
if not ilst or not ilst.children then
return tags, pics
end
for _, item in ilst.children :: { Box.Box } do
local typ = item.type
local freeName: string? = nil
if typ == "----" then
local nm = Box.child(item, "name")
if nm and nm.data + 4 <= nm.stop then
freeName = readstring(b, nm.data + 4, nm.stop - nm.data - 4)
end
end
for _, d in Box.childrenOf(item, "data") do
if d.data + 8 > d.stop then
continue
end
local kind = bit32.band(Box.be32(b, d.data), 0xFFFFFF)
local p, n = d.data + 8, d.stop - d.data - 8
if typ == "trkn" or typ == "disk" then
if n >= 6 then
local num = Box.be32(b, p) % 65536
local total = Box.be32(b, p + 2) % 65536
local key = if typ == "trkn" then "track" else "disc"
if num > 0 then
tags[key] = tostring(num)
end
if total > 0 then
tags[key .. "total"] = tostring(total)
end
end
elseif typ == "gnre" then
if n >= 2 then
local g = GENRES[Box.be32(b, p - 2) % 65536]
if g and not tags.genre then
tags.genre = g
end
end
elseif typ == "tmpo" then
if n >= 2 then
tags.bpm = tostring(Box.be32(b, p - 2) % 65536)
end
elseif typ == "cpil" or typ == "pgap" then
if n >= 1 then
tags[if typ == "cpil" then "compilation" else "gapless"] = tostring(buffer.readu8(b, p))
end
elseif typ == "covr" then
local mime = if kind == 14 then "image/png" elseif kind == 27 then "image/bmp" else "image/jpeg"
local data = buffer.create(n)
buffer.copy(data, 0, b, p, n)
table.insert(pics, { mime = mime, data = data })
elseif kind == 1 or kind == 0 then
local s = readstring(b, p, n)
local key = freeName or TAG[typ] or typ
if typ == "\169gen" or not tags[key] then
tags[key] = s
end
end
end
end
return tags, pics
end
-- ------------------------------------------------------------------------------------------------ ilst writer
local function box(w: Bytes.Writer, typ: string, body: (Bytes.Writer) -> ())
local start = w:tell()
w:u32be(0)
w:string(typ)
body(w)
w:setU32be(start, w:tell() - start)
end
Meta.box = box
local function dataBox(w: Bytes.Writer, kind: number, value: string | buffer)
box(w, "data", function()
w:u32be(kind)
w:u32be(0)
if type(value) == "string" then
w:string(value)
else
w:bytes(value)
end
end)
end
local function num(s: string?): number
local v = tonumber(s or "")
if not v then
return 0
end
return math.clamp(math.floor(v), 0, 65535)
end
-- writeIlst(w, tags, pictures?): an ilst box with the tags (standard names -> iTunes atoms; unknown names -> '----'
-- freeform com.apple.iTunes items) and cover pictures
function Meta.writeIlst(w: Bytes.Writer, tags: { [string]: string }, pictures: { Picture }?)
box(w, "ilst", function()
local keys = {}
for k in tags do
table.insert(keys, k)
end
table.sort(keys)
local done: { [string]: boolean } = {}
for _, k in keys do
local v = tags[k]
if type(v) ~= "string" or done[k] then
continue
end
if k == "track" or k == "tracktotal" or k == "disc" or k == "disctotal" then
local base = if k == "track" or k == "tracktotal" then "track" else "disc"
if done[base] then
continue
end
done[base] = true
local atom = if base == "track" then "trkn" else "disk"
local n, total = num(tags[base]), num(tags[base .. "total"])
box(w, atom, function()
box(w, "data", function()
w:u32be(0)
w:u32be(0)
w:u16be(0)
w:u16be(n)
w:u16be(total)
if atom == "trkn" then
w:u16be(0)
end
end)
end)
elseif k == "bpm" then
box(w, "tmpo", function()
box(w, "data", function()
w:u32be(21)
w:u32be(0)
w:u16be(num(v))
end)
end)
elseif k == "compilation" or k == "gapless" then
box(w, if k == "compilation" then "cpil" else "pgap", function()
box(w, "data", function()
w:u32be(21)
w:u32be(0)
w:u8(if num(v) ~= 0 then 1 else 0)
end)
end)
elseif TAG_ATOM[k] then
box(w, TAG_ATOM[k], function()
dataBox(w, 1, v)
end)
else
box(w, "----", function()
box(w, "mean", function()
w:u32be(0)
w:string("com.apple.iTunes")
end)
box(w, "name", function()
w:u32be(0)
w:string(k)
end)
dataBox(w, 1, v)
end)
end
done[k] = true
end
if pictures and #pictures > 0 then
box(w, "covr", function()
for _, p in pictures do
dataBox(w, if p.mime == "image/png" then 14 elseif p.mime == "image/bmp" then 27 else 13, p.data)
end
end)
end
end)
end
-- writeUdta(w, tags, pictures?): udta / meta (hdlr mdir) / ilst
function Meta.writeUdta(w: Bytes.Writer, tags: { [string]: string }, pictures: { Picture }?)
box(w, "udta", function()
box(w, "meta", function()
w:u32be(0)
box(w, "hdlr", function()
w:u32be(0)
w:u32be(0)
w:string("mdir")
w:string("appl")
w:u32be(0)
w:u32be(0)
w:u8(0)
end)
Meta.writeIlst(w, tags, pictures)
end)
end)
end
return Meta
+519
View File
@@ -0,0 +1,519 @@
--!strict
-- containers/IsoBmff/Mux: writes a progressive (non-fragmented) ISO BMFF / MP4 / M4A file: ftyp, moov (mvhd, one trak
-- per track with tkhd / edts / mdia / mdhd / hdlr / minf / [sv]mhd / dinf / stbl), the samples interleaved in chunks
-- in one mdat, and udta / meta / ilst tags. moov goes first ("fast start"); co64 replaces stco past 4 GB. Sample
-- entries: audio (mp4a + esds, alac, Opus + dOps, fLaC + dfLa, ...) and video (avc1 / hvc1 / av01 / vp09 / ... +
-- their configuration box), plus any raw child boxes. Never throws: bad specs return nil, Err.ARG.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Meta = require("@formats/containers/IsoBmff/Meta")
local Mux = {}
export type MuxTrack = {
kind: "audio" | "video" | "subtitle" | "data",
entry: string, -- sample entry fourcc: "alac", "mp4a", "Opus", "fLaC", "avc1", "hvc1", "av01", "vp09", ...
timescale: number, -- ticks per second (audio: the sample rate)
samples: { buffer }?, -- one buffer per sample, or
data: buffer?, -- the samples back to back, with
sizes: { number }?, -- their sizes
durations: { number } | number, -- ticks per sample (or one constant)
cts: { number }?, -- composition offsets (video with B-frames)
sync: { [number]: boolean }?, -- sync samples (nil: all)
sampleRate: number?,
channels: number?,
bitsPerSample: number?, -- default 16
width: number?,
height: number?,
config: buffer?, -- the codec configuration, written as the entry's configuration box
configBox: string?, -- its box type (default by entry: esds, alac, dOps, dfLa, avcC, hvcC, av1C, vpcC)
objectType: number?, -- esds objectTypeIndication (default 0x40, AAC)
bitrate: number?, -- esds average bitrate
boxes: { { type: string, data: buffer } }?, -- extra sample entry child boxes (raw payloads)
language: string?, -- ISO 639-2, default "und"
name: string?, -- hdlr name
skip: number?, -- media ticks to skip at the start (edit list media time: AAC priming)
playDuration: number?, -- media ticks to play (edit list)
}
export type MuxSpec = {
brand: string?, -- default "isom"
minor: number?,
compatible: { string }?,
timescale: number?, -- movie timescale, default 1000
tracks: { MuxTrack },
tags: { [string]: string }?,
pictures: { Meta.Picture }?,
chunkDuration: number?, -- seconds of samples per chunk, default 1
}
local DEFAULT_CONFIG_BOX: { [string]: string } = {
mp4a = "esds", mp4v = "esds", alac = "alac", Opus = "dOps", fLaC = "dfLa", avc1 = "avcC", avc3 = "avcC",
hvc1 = "hvcC", hev1 = "hvcC", av01 = "av1C", vp08 = "vpcC", vp09 = "vpcC", ["ac-3"] = "dac3", ["ec-3"] = "dec3",
}
local FULL_BOX: { [string]: boolean } = { alac = true, dfLa = true, vpcC = true }
local HANDLER = { audio = "soun", video = "vide", subtitle = "sbtl", data = "meta" }
local box = Meta.box
local function lang(s: string?): number
local l = s or "und"
if #l ~= 3 then
l = "und"
end
local v = 0
for i = 1, 3 do
v = v * 32 + bit32.band(string.byte(l, i) - 96, 31)
end
return v
end
local function descriptor(w: Bytes.Writer, tag: number, body: (Bytes.Writer) -> ())
local inner = Bytes.writer(64)
body(inner)
local n = inner:tell()
w:u8(tag)
-- 4-byte expandable length (the common iTunes / ffmpeg form)
w:u8(0x80 + bit32.band(bit32.rshift(n, 21), 127))
w:u8(0x80 + bit32.band(bit32.rshift(n, 14), 127))
w:u8(0x80 + bit32.band(bit32.rshift(n, 7), 127))
w:u8(bit32.band(n, 127))
w:bytes(inner.buf, 0, n)
end
local function esds(w: Bytes.Writer, t: MuxTrack)
box(w, "esds", function()
w:u32be(0)
descriptor(w, 3, function(d)
d:u16be(0) -- ES_ID
d:u8(0)
descriptor(d, 4, function(c)
c:u8(t.objectType or 0x40)
c:u8(if t.kind == "video" then 0x11 else 0x15) -- streamType << 2 | upStream 0 | reserved 1
c:u24be(0)
c:u32be(t.bitrate or 0)
c:u32be(t.bitrate or 0)
if t.config then
descriptor(c, 5, function(s)
s:bytes(t.config :: buffer)
end)
end
end)
descriptor(d, 6, function(s)
s:u8(2)
end)
end)
end)
end
local function sampleEntry(w: Bytes.Writer, t: MuxTrack)
box(w, t.entry, function()
w:fill(0, 6)
w:u16be(1) -- data reference index
if t.kind == "audio" then
w:u16be(0) -- version
w:u16be(0)
w:u32be(0)
w:u16be(t.channels or 2)
w:u16be(t.bitsPerSample or 16)
w:u16be(0)
w:u16be(0)
local sr = t.sampleRate or t.timescale
w:u32be(if sr < 65536 then sr * 65536 else 0)
elseif t.kind == "video" then
w:fill(0, 16)
w:u16be(t.width or 0)
w:u16be(t.height or 0)
w:u32be(0x00480000)
w:u32be(0x00480000)
w:u32be(0)
w:u16be(1) -- frame count
w:fill(0, 32) -- compressor name
w:u16be(0x18)
w:i16be(-1)
end
local cb = t.configBox or DEFAULT_CONFIG_BOX[t.entry]
if t.config and cb then
if cb == "esds" then
esds(w, t)
else
box(w, cb, function()
if FULL_BOX[cb] then
w:u32be(0)
end
w:bytes(t.config :: buffer)
end)
end
end
for _, x in t.boxes or {} do
box(w, x.type, function()
w:bytes(x.data)
end)
end
end)
end
type Chunk = { track: number, first: number, count: number, time: number, offset: number }
-- runs of equal values: { { count, value } }
local function runs(n: number, value: (number) -> number): { { number } }
local out = {}
for i = 1, n do
local v = value(i)
local last = out[#out]
if last and last[2] == v then
last[1] += 1
else
table.insert(out, { 1, v })
end
end
return out
end
type Prepared = {
t: MuxTrack,
n: number,
sizes: { number },
dur: (number) -> number,
total: number, -- media ticks
chunks: { Chunk },
sample: (number) -> (buffer, number), -- buffer, offset
}
local function moov(w: Bytes.Writer, spec: MuxSpec, prep: { Prepared }, co64: boolean)
local mts = spec.timescale or 1000
local function toMovie(p: Prepared, ticks: number): number
return math.floor(ticks * mts / p.t.timescale + 0.5)
end
local movieDur = 0
for _, p in prep do
local play = p.t.playDuration or (p.total - (p.t.skip or 0))
movieDur = math.max(movieDur, toMovie(p, play))
end
box(w, "moov", function()
box(w, "mvhd", function()
w:u32be(0)
w:u32be(0)
w:u32be(0)
w:u32be(mts)
w:u32be(movieDur)
w:u32be(0x00010000)
w:u16be(0x0100)
w:fill(0, 10)
for _, v in { 0x00010000, 0, 0, 0, 0x00010000, 0, 0, 0, 0x40000000 } do
w:u32be(v)
end
w:fill(0, 24)
w:u32be(#prep + 1)
end)
for id, p in prep do
local t = p.t
local play = t.playDuration or (p.total - (t.skip or 0))
box(w, "trak", function()
box(w, "tkhd", function()
w:u32be(3) -- enabled, in movie
w:u32be(0)
w:u32be(0)
w:u32be(id)
w:u32be(0)
w:u32be(toMovie(p, play))
w:fill(0, 8)
w:u16be(0)
w:u16be(0)
w:u16be(if t.kind == "audio" then 0x0100 else 0)
w:u16be(0)
for _, v in { 0x00010000, 0, 0, 0, 0x00010000, 0, 0, 0, 0x40000000 } do
w:u32be(v)
end
w:u32be((t.width or 0) * 65536)
w:u32be((t.height or 0) * 65536)
end)
if t.skip or t.playDuration then
box(w, "edts", function()
box(w, "elst", function()
w:u32be(0)
w:u32be(1)
w:u32be(toMovie(p, play))
w:u32be(t.skip or 0)
w:u32be(0x00010000)
end)
end)
end
box(w, "mdia", function()
box(w, "mdhd", function()
w:u32be(0)
w:u32be(0)
w:u32be(0)
w:u32be(t.timescale)
w:u32be(p.total)
w:u16be(lang(t.language))
w:u16be(0)
end)
box(w, "hdlr", function()
w:u32be(0)
w:u32be(0)
w:string(HANDLER[t.kind] or "meta")
w:fill(0, 12)
w:cstring(t.name or (if t.kind == "audio" then "SoundHandler" elseif t.kind == "video" then "VideoHandler" else "DataHandler"))
end)
box(w, "minf", function()
if t.kind == "audio" then
box(w, "smhd", function()
w:u32be(0)
w:u32be(0)
end)
elseif t.kind == "video" then
box(w, "vmhd", function()
w:u32be(1)
w:fill(0, 8)
end)
else
box(w, "nmhd", function()
w:u32be(0)
end)
end
box(w, "dinf", function()
box(w, "dref", function()
w:u32be(0)
w:u32be(1)
box(w, "url ", function()
w:u32be(1) -- self-contained
end)
end)
end)
box(w, "stbl", function()
box(w, "stsd", function()
w:u32be(0)
w:u32be(1)
sampleEntry(w, t)
end)
local stts = runs(p.n, p.dur)
box(w, "stts", function()
w:u32be(0)
w:u32be(#stts)
for _, r in stts do
w:u32be(r[1])
w:u32be(r[2])
end
end)
local cts = t.cts
if cts then
local cr = runs(p.n, function(i)
return cts[i] or 0
end)
box(w, "ctts", function()
w:u32be(0x01000000) -- version 1: signed offsets
w:u32be(#cr)
for _, r in cr do
w:u32be(r[1])
w:i32be(r[2])
end
end)
end
local sync = t.sync
if sync then
local list = {}
for i = 1, p.n do
if sync[i] then
table.insert(list, i)
end
end
box(w, "stss", function()
w:u32be(0)
w:u32be(#list)
for _, i in list do
w:u32be(i)
end
end)
end
local stsc = runs(#p.chunks, function(i)
return p.chunks[i].count
end)
box(w, "stsc", function()
w:u32be(0)
w:u32be(#stsc)
local c = 1
for _, r in stsc do
w:u32be(c)
w:u32be(r[2])
w:u32be(1)
c += r[1]
end
end)
box(w, "stsz", function()
w:u32be(0)
local fixed = p.sizes[1] or 0
for i = 2, p.n do
if p.sizes[i] ~= fixed then
fixed = -1
break
end
end
if fixed >= 0 and p.n > 0 then
w:u32be(fixed)
w:u32be(p.n)
else
w:u32be(0)
w:u32be(p.n)
for i = 1, p.n do
w:u32be(p.sizes[i])
end
end
end)
box(w, if co64 then "co64" else "stco", function()
w:u32be(0)
w:u32be(#p.chunks)
for _, c in p.chunks do
if co64 then
w:u64be(c.offset)
else
w:u32be(c.offset)
end
end
end)
end)
end)
end)
end)
end
if spec.tags and next(spec.tags) or spec.pictures and #spec.pictures > 0 then
Meta.writeUdta(w, spec.tags or {}, spec.pictures)
end
end)
end
-- mux(spec) -> buffer | nil, Err
function Mux.mux(spec: MuxSpec): (buffer?, Err.Err?)
if type(spec) ~= "table" or type(spec.tracks) ~= "table" or #spec.tracks == 0 then
return nil, Err.new(Err.ARG, "mux: expected { tracks = { ... } }")
end
local prep: { Prepared } = {}
local all: { Chunk } = {}
for k, t in spec.tracks do
if type(t) ~= "table" or type(t.entry) ~= "string" or #t.entry ~= 4 or type(t.timescale) ~= "number" or t.timescale <= 0 then
return nil, Err.new(Err.ARG, "mux: track " .. k .. " needs a 4-character entry and a timescale")
end
if not HANDLER[t.kind] then
return nil, Err.new(Err.ARG, "mux: track " .. k .. ": bad kind " .. tostring(t.kind))
end
local n, sizes, sample
if t.samples then
local list = t.samples
n = #list
sizes = table.create(n, 0)
for i = 1, n do
if type(list[i]) ~= "buffer" then
return nil, Err.new(Err.ARG, "mux: track " .. k .. ": sample " .. i .. " is not a buffer")
end
sizes[i] = buffer.len(list[i])
end
sample = function(i: number): (buffer, number)
return list[i], 0
end
elseif t.data and t.sizes then
n = #t.sizes
sizes = t.sizes
local starts = table.create(n, 0)
local o = 0
for i = 1, n do
starts[i] = o
o += sizes[i]
end
if o > buffer.len(t.data) then
return nil, Err.new(Err.ARG, "mux: track " .. k .. ": sizes exceed the data")
end
local data = t.data
sample = function(i: number): (buffer, number)
return data, starts[i]
end
else
return nil, Err.new(Err.ARG, "mux: track " .. k .. " needs samples or data + sizes")
end
local durs = t.durations
local dur
if type(durs) == "number" then
dur = function(_: number): number
return durs
end
elseif type(durs) == "table" then
dur = function(i: number): number
return durs[i] or 0
end
else
return nil, Err.new(Err.ARG, "mux: track " .. k .. " needs durations")
end
local total = 0
local chunks: { Chunk } = {}
local per = (spec.chunkDuration or 1) * t.timescale
local cur: Chunk? = nil
for i = 1, n do
if not cur or total - cur.time >= per then
cur = { track = k, first = i, count = 0, time = total, offset = 0 }
table.insert(chunks, cur :: Chunk)
table.insert(all, cur :: Chunk)
end
(cur :: Chunk).count += 1
total += dur(i)
end
prep[k] = { t = t, n = n, sizes = sizes, dur = dur, total = total, chunks = chunks, sample = sample }
end
-- interleave the chunks by time
table.sort(all, function(a: Chunk, b: Chunk): boolean
local ta = a.time / prep[a.track].t.timescale
local tb = b.time / prep[b.track].t.timescale
if ta ~= tb then
return ta < tb
end
if a.track ~= b.track then
return a.track < b.track
end
return a.first < b.first
end)
local mdatSize = 0
for _, c in all do
local p = prep[c.track]
for i = c.first, c.first + c.count - 1 do
mdatSize += p.sizes[i]
end
end
local co64 = mdatSize > 4294967295 - 2 ^ 24
-- ftyp
local w = Bytes.writer(mdatSize + 4096)
box(w, "ftyp", function()
w:string(spec.brand or "isom")
w:u32be(spec.minor or 0x200)
for _, c in spec.compatible or { spec.brand or "isom", "iso2", "mp41" } do
w:string(string.sub(c .. " ", 1, 4))
end
end)
-- moov twice: the first pass measures it, the second has the real chunk offsets
local probe = Bytes.writer(4096)
moov(probe, spec, prep, co64)
local mdatHeader = if mdatSize + 8 > 4294967295 then 16 else 8
local o = w:tell() + probe:tell() + mdatHeader
for _, c in all do
c.offset = o
local p = prep[c.track]
for i = c.first, c.first + c.count - 1 do
o += p.sizes[i]
end
end
moov(w, spec, prep, co64)
if mdatHeader == 16 then
w:u32be(1)
w:string("mdat")
w:u64be(mdatSize + 16)
else
w:u32be(mdatSize + 8)
w:string("mdat")
end
for _, c in all do
local p = prep[c.track]
for i = c.first, c.first + c.count - 1 do
local b, off = p.sample(i)
w:bytes(b, off, p.sizes[i])
end
end
return w:finish(), nil
end
return Mux
+188
View File
@@ -0,0 +1,188 @@
--!strict
-- containers/IsoBmff: ISO base media file format (ISO/IEC 14496-12) and its relatives: MP4 / M4A / M4V / MOV (QuickTime)
-- / 3GP, fragmented MP4 (moof), HEIF / AVIF items (ISO/IEC 23008-12), iTunes tags. A container (layer 2): m4a, mp4,
-- mov, heif, avif build on it. Written from the specifications; no third-party code.
--
-- local IsoBmff = require("@formats/containers/IsoBmff")
-- local movie, err = IsoBmff.parse(r) -- ftyp brand, tracks (Demux.Track: codec, config, sample tables)
-- local dmx = IsoBmff.demux(r) -- Types.Demuxer: tracks, duration, packets(trackId?), seek(s)
-- local tags, pictures = IsoBmff.tags(r, movie) -- moov/udta/meta/ilst (or a top-level meta)
-- local items = IsoBmff.items(r, movie) -- HEIF / AVIF: primary item, items, properties, refs
-- local data = IsoBmff.itemData(r, items, id) -- an item's bytes
-- local file = IsoBmff.mux({ brand = "M4A ", tracks = { { kind = "audio", entry = "alac", ... } }, tags = ... })
--
-- Sample offsets in tracks are absolute offsets into r.buf (r may cover part of a bigger buffer). Supports: 32 / 64-bit
-- boxes, stsz / stz2, stco / co64, ctts v0 / v1, stss, elst v0 / v1, QuickTime sound descriptions v1 / v2 and 'wave',
-- fragments with trex defaults / tfdt / data offsets. Not supported: external data references (dref urls),
-- encrypted tracks (sinf / senc are left to the caller), fragmented writing. Never throws.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Box = require("@formats/containers/IsoBmff/Box")
local Demux = require("@formats/containers/IsoBmff/Demux")
local Meta = require("@formats/containers/IsoBmff/Meta")
local Mux = require("@formats/containers/IsoBmff/Mux")
local IsoBmff = {}
IsoBmff.Box = Box
IsoBmff.Demux = Demux
IsoBmff.Meta = Meta
export type Track = Demux.Track
export type Movie = Demux.Movie
export type Items = Meta.Items
export type Item = Meta.Item
export type MuxSpec = Mux.MuxSpec
export type MuxTrack = Mux.MuxTrack
export type Picture = Meta.Picture
local TOP: { [string]: boolean } = {
ftyp = true, moov = true, mdat = true, free = true, skip = true, wide = true, pnot = true, moof = true,
styp = true, sidx = true, meta = true, uuid = true, PICT = true,
}
-- sniff(r) -> brand ("M4A ", "isom", "qt ", "avif", "heic", ...) or "" when the file starts with another top-level box,
-- nil when it is not an ISO BMFF file
function IsoBmff.sniff(r: Bytes.Reader): string?
local head = r:peek(12)
if #head < 8 then
return nil
end
local typ = string.sub(head, 5, 8)
if typ == "ftyp" then
return if #head >= 12 then string.sub(head, 9, 12) else ""
end
if TOP[typ] then
local size = string.byte(head, 1) * 16777216 + string.byte(head, 2) * 65536 + string.byte(head, 3) * 256 + string.byte(head, 4)
if size == 1 or size == 0 or size >= 8 then
return ""
end
end
return nil
end
-- parse(r, opts?) -> Movie | nil, Err
function IsoBmff.parse(r: Bytes.Reader, opts: Demux.Options?): (Movie?, Err.Err?)
return Demux.parse(r, opts)
end
-- tags(r, movie) -> Tags, { Picture }: iTunes tags from moov/udta/meta/ilst (or moov/meta/ilst, or a top-level meta)
function IsoBmff.tags(r: Bytes.Reader, movie: Movie): ({ [string]: string }, { Picture })
local ilst = Box.path(movie.boxes, "moov/udta/meta/ilst") or Box.path(movie.boxes, "moov/meta/ilst") or Box.path(movie.boxes, "meta/ilst")
return Meta.tags(r.buf, ilst)
end
-- items(r, movie) -> Items | nil, Err (the top-level meta box of a HEIF / AVIF file)
function IsoBmff.items(r: Bytes.Reader, movie: Movie): (Items?, Err.Err?)
local meta = Box.path(movie.boxes, "meta")
if not meta then
return nil, Err.new(Err.CORRUPT, "no top-level meta box")
end
return Meta.items(r.buf, meta)
end
-- itemData(r, items, id) -> buffer | nil, Err
function IsoBmff.itemData(r: Bytes.Reader, items: Items, id: number): (buffer?, Err.Err?)
return Meta.itemData(r.buf, r.base, r.limit, items, id)
end
-- sample(r, track, i) -> a copy of sample i (1-based)
function IsoBmff.sample(r: Bytes.Reader, t: Track, i: number): buffer?
if i < 1 or i > t.sampleCount then
return nil
end
local n = t.sizes[i]
local out = buffer.create(n)
buffer.copy(out, 0, r.buf, t.offsets[i], n)
return out
end
-- demux(r, opts?) -> Types.Demuxer (tracks, duration, packets(trackId?), seek(seconds)) | nil, Err. Packets carry pts /
-- dts / duration in their track's timescale ticks and a copy of the sample bytes.
function IsoBmff.demux(r: Bytes.Reader, opts: Demux.Options?): (any, Err.Err?)
local movie, err = Demux.parse(r, opts)
if not movie then
return nil, err
end
local cursor: { [number]: number } = {}
local byId: { [number]: Track } = {}
for _, t in movie.tracks do
cursor[t.id] = 1
byId[t.id] = t
end
local dmx = { tracks = movie.tracks, duration = movie.duration, movie = movie }
local function packet(t: Track, i: number): any
local dts = t.dts[i]
local cts = t.cts
return {
track = t.id,
dts = dts,
pts = dts + (if cts then cts[i] or 0 else 0),
duration = t.durations[i],
keyframe = t.sync == nil or (t.sync :: any)[i] == true,
data = IsoBmff.sample(r, t, i),
index = i,
}
end
function dmx.packets(_self: any, trackId: number?): () -> any
return function(): any
if trackId then
local t = byId[trackId]
if not t then
return nil
end
local i = cursor[trackId]
if i > t.sampleCount then
return nil
end
cursor[trackId] = i + 1
return packet(t, i)
end
-- all tracks in file order
local best: Track? = nil
local bestOff = math.huge
for _, t in movie.tracks do
local i = cursor[t.id]
if i <= t.sampleCount and t.offsets[i] < bestOff then
best, bestOff = t, t.offsets[i]
end
end
if not best then
return nil
end
local i = cursor[best.id]
cursor[best.id] = i + 1
return packet(best, i)
end
end
-- seek(seconds): every track to its last sync sample at or before the time
function dmx.seek(_self: any, seconds: number)
for _, t in movie.tracks do
local target = seconds * t.timescale
local lo, hi = 1, t.sampleCount
local found = 1
while lo <= hi do
local mid = (lo + hi) // 2
if t.dts[mid] <= target then
found = mid
lo = mid + 1
else
hi = mid - 1
end
end
if t.sync then
while found > 1 and not (t.sync :: any)[found] do
found -= 1
end
end
cursor[t.id] = found
end
end
return dmx, nil
end
-- mux(spec) -> buffer | nil, Err (see containers/IsoBmff/Mux)
function IsoBmff.mux(spec: MuxSpec): (buffer?, Err.Err?)
return Mux.mux(spec)
end
return IsoBmff
+164
View File
@@ -0,0 +1,164 @@
--!strict
--!native
--!optimize 2
-- core/Md5: MD5 (RFC 1321), incremental. Written from the RFC. Used by the FLAC encoder (STREAMINFO's MD5 of the PCM);
-- not for security.
--
-- local h = Md5.new()
-- h:update(buf, offset?, length?) -- any number of times
-- local digest = h:digest() -- 16-byte string (the state is finished; make a new one to hash again)
-- Md5.hex(digest) / Md5.of(buf) -> hex string
-- Never throws (ranges are clamped to the buffer).
local Md5 = {}
local band, bor, bxor, bnot, lrotate = bit32.band, bit32.bor, bit32.bxor, bit32.bnot, bit32.lrotate
local readu32, writeu32, writeu8 = buffer.readu32, buffer.writeu32, buffer.writeu8
local K = table.create(64, 0)
for i = 0, 63 do
K[i + 1] = math.floor(math.abs(math.sin(i + 1)) * 4294967296) % 4294967296
end
local S = {
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
}
local G = table.create(64, 0)
for i = 0, 63 do
if i < 16 then
G[i + 1] = i
elseif i < 32 then
G[i + 1] = (5 * i + 1) % 16
elseif i < 48 then
G[i + 1] = (3 * i + 5) % 16
else
G[i + 1] = (7 * i) % 16
end
end
export type State = {
a: number,
b: number,
c: number,
d: number,
block: buffer, -- 64-byte pending block
fill: number,
total: number, -- bytes hashed
update: (self: State, buf: buffer, offset: number?, length: number?) -> (),
digest: (self: State) -> string,
}
local M = table.create(16, 0)
local function compress(st: State, blk: buffer, o: number)
for i = 0, 15 do
M[i + 1] = readu32(blk, o + i * 4)
end
local a, b, c, d = st.a, st.b, st.c, st.d
for i = 0, 63 do
local f
if i < 16 then
f = bor(band(b, c), band(bnot(b), d))
elseif i < 32 then
f = bor(band(d, b), band(bnot(d), c))
elseif i < 48 then
f = bxor(b, c, d)
else
f = bxor(c, bor(b, bnot(d)))
end
local tmp = d
d = c
c = b
b = (b + lrotate((a + f + K[i + 1] + M[G[i + 1] + 1]) % 4294967296, S[i + 1])) % 4294967296
a = tmp
end
st.a = (st.a + a) % 4294967296
st.b = (st.b + b) % 4294967296
st.c = (st.c + c) % 4294967296
st.d = (st.d + d) % 4294967296
end
local function update(self: State, buf: buffer, offset: number?, length: number?)
local n = buffer.len(buf)
local o = math.clamp(offset or 0, 0, n)
local len = math.clamp(length or (n - o), 0, n - o)
self.total += len
local blk = self.block
if self.fill > 0 then
local take = math.min(64 - self.fill, len)
buffer.copy(blk, self.fill, buf, o, take)
self.fill += take
o += take
len -= take
if self.fill == 64 then
compress(self, blk, 0)
self.fill = 0
end
end
while len >= 64 do
compress(self, buf, o)
o += 64
len -= 64
end
if len > 0 then
buffer.copy(blk, 0, buf, o, len)
self.fill = len
end
end
local function digest(self: State): string
local bits = self.total * 8
local blk = self.block
local f = self.fill
writeu8(blk, f, 0x80)
f += 1
if f > 56 then
buffer.fill(blk, f, 0, 64 - f)
compress(self, blk, 0)
f = 0
end
buffer.fill(blk, f, 0, 56 - f)
writeu32(blk, 56, bits % 4294967296)
writeu32(blk, 60, math.floor(bits / 4294967296) % 4294967296)
compress(self, blk, 0)
self.fill = 0
local out = buffer.create(16)
writeu32(out, 0, self.a)
writeu32(out, 4, self.b)
writeu32(out, 8, self.c)
writeu32(out, 12, self.d)
return buffer.tostring(out)
end
function Md5.new(): State
return {
a = 0x67452301,
b = 0xEFCDAB89,
c = 0x98BADCFE,
d = 0x10325476,
block = buffer.create(64),
fill = 0,
total = 0,
update = update,
digest = digest,
}
end
-- hex(digest) -> 32 lower-case hex digits
function Md5.hex(d: string): string
local out = table.create(#d)
for i = 1, #d do
out[i] = string.format("%02x", string.byte(d, i))
end
return table.concat(out)
end
-- of(buf, offset?, length?) -> hex digest
function Md5.of(buf: buffer, offset: number?, length: number?): string
local h = Md5.new()
h:update(buf, offset, length)
return Md5.hex(h:digest())
end
return Md5
+120
View File
@@ -0,0 +1,120 @@
--!strict
--!native
-- music/it/Itsex: Impulse Tracker sample decompression (IT 2.14 and the IT 2.15 double-delta variant, 8 and 16-bit).
-- Written from the algorithm description in ITTECH.TXT / the public notes on the format: blocks of 0x8000 bytes of
-- output, each a u16 length then an LSB-first bit stream of deltas with three width-change methods.
--
-- Never throws: every read is bounds-checked; corrupt streams return nil, message.
local readu8, readu16, writef32 = buffer.readu8, buffer.readu16, buffer.writef32
local Itsex = {}
-- decompress(buf, off, limit, frames, bits, it215) -> f32 buffer (frames), bytes consumed | nil, message
function Itsex.decompress(buf: buffer, off: number, limit: number, frames: number, bits: number, it215: boolean): (buffer?, number | string)
local out = buffer.create(frames * 4)
local blockLen = if bits == 16 then 0x4000 else 0x8000
local topWidth = if bits == 16 then 17 else 9
local fetchA = if bits == 16 then 4 else 3
local lowerB = if bits == 16 then -8 else -4
local upperB = if bits == 16 then 7 else 3
local scale = if bits == 16 then 1 / 32768 else 1 / 128
local wrap = if bits == 16 then 65536 else 256
local half = wrap // 2
local p = off
local done = 0
while done < frames do
if p + 2 > limit then
return nil, "compressed sample truncated"
end
local clen = readu16(buf, p)
p += 2
local bstart = p
local bend = p + clen
if bend > limit then
return nil, "compressed block runs past the end"
end
p = bend
-- bit reader over [bstart, bend)
local bytePos = bstart
local bitBuf = 0
local bitCount = 0
local function readBits(n: number): number
while bitCount < n do
if bytePos >= bend then
return -1
end
bitBuf += readu8(buf, bytePos) * 2 ^ bitCount
bytePos += 1
bitCount += 8
end
local v = bitBuf % 2 ^ n
bitBuf = (bitBuf - v) / 2 ^ n
bitCount -= n
return v
end
local count = math.min(blockLen, frames - done)
local width = topWidth
local d1, d2 = 0, 0
local i = 0
while i < count do
if width < 1 or width > topWidth then
return nil, "bad bit width"
end
local v = readBits(width)
if v < 0 then
return nil, "compressed block ends early"
end
if width < 7 then
-- method A: a marker value, then the new width in fetchA bits
if v == 2 ^ (width - 1) then
local nw = readBits(fetchA)
if nw < 0 then
return nil, "compressed block ends early"
end
nw += 1
width = if nw < width then nw else nw + 1
continue
end
elseif width < topWidth then
-- method B: values just below the top of the range encode the new width
local border = bit32.rshift(if bits == 16 then 0xFFFF else 0xFF, topWidth - width) + lowerB
if v > border and v <= border + (upperB - lowerB + 1) then
local nw = v - border
width = if nw < width then nw else nw + 1
continue
end
else
-- method C: the top bit flags a width change
if v >= wrap then
width = (v + 1) % 256
continue
end
end
-- a delta, sign-extended from its width
local x = v
if width < topWidth then
local shift = 2 ^ width
if x >= shift / 2 then
x -= shift
end
else
x = v % wrap
if x >= half then
x -= wrap
end
end
d1 = (d1 + x + half) % wrap - half
local s = d1
if it215 then
d2 = (d2 + d1 + half) % wrap - half
s = d2
end
writef32(out, (done + i) * 4, s * scale)
i += 1
end
done += count
end
return out, p - off
end
return Itsex
+427
View File
@@ -0,0 +1,427 @@
--!strict
-- music/it: Impulse Tracker modules (IMPM, ITTECH.TXT; also files from OpenMPT / Schism Tracker). Reads into the
-- codecs/Tracker Module and plays through its engine (Module:render() / open() -> an audio Decoder). Supports: up to
-- 64 channels, instrument and sample mode, new and old (pre-2.0) instrument headers, volume / panning / pitch (or
-- filter) envelopes with loops and sustain loops, new note actions and duplicate checks, pitch-pan separation,
-- resonant filters (instrument cutoff / resonance, default Zxx macros), 8 / 16-bit signed or unsigned mono / stereo
-- samples, IT 2.14 / 2.15 compressed samples, sustain loops, auto-vibrato, the song message.
-- Not supported: embedded MIDI macro configurations (the default filter macros are used), MIDI output, OpenMPT's
-- extension chunks (plugins, extended instrument properties), writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Tracker = require("@formats/codecs/Tracker")
local Itsex = require("@formats/music/it/Itsex")
-- ------------------------------------------------------------------------------------------------ contract
local It = {
name = "it",
category = "music",
extensions = { "it" },
mime = { "audio/it", "audio/x-it" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" },
caps = { decode = true, encode = false, render = true, channels = { 1, 64 }, compressedSamples = true },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28)
}
-- ------------------------------------------------------------------------------------------------ sniff
function It.sniff(r: Bytes.Reader): number
return if r:peek(4) == "IMPM" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- the 82-byte envelope of a new-format instrument
local function readEnvelope(r: Bytes.Reader, kind: string): any
local flags, n = r:u8(), r:u8()
local lb, le, sb, se = r:u8(), r:u8(), r:u8(), r:u8()
local e = Tracker.newEnvelope()
n = math.min(n, 25)
for i = 1, 25 do
local y, x = r:i8(), r:u16le()
if i <= n then
e.ticks[i] = x
e.values[i] = if kind == "vol" then math.clamp(y, 0, 64) else math.clamp(y, -32, 32)
end
end
r:skip(1)
e.enabled = bit32.band(flags, 1) ~= 0 and n > 0
e.loop = bit32.band(flags, 2) ~= 0
e.sustain = bit32.band(flags, 4) ~= 0
e.carry = bit32.band(flags, 8) ~= 0
e.filter = kind == "pitch" and bit32.band(flags, 128) ~= 0
e.loopStart, e.loopEnd = lb + 1, le + 1
e.susStart, e.susEnd = sb + 1, se + 1
return e
end
local function readInstrument(r: Bytes.Reader, old: boolean): (any?, string?)
if r:string(4) ~= "IMPI" then
return nil, "bad instrument signature"
end
local ins = Tracker.newInstrument()
r:skip(13)
if old then
-- the pre-2.0 layout: volume envelope only (flags, loop and sustain points), fadeout 0..64 of 512
local flg, vls, vle, sls, sle = r:u8(), r:u8(), r:u8(), r:u8(), r:u8()
r:skip(2)
ins.fadeout = r:u16le() * 2
ins.nna = r:u8()
ins.dct = if r:u8() ~= 0 then 1 else 0
r:skip(4)
ins.name = r:fixed(26)
r:skip(6)
for n = 1, 120 do
local note, smp = r:u8(), r:u8()
ins.noteMap[n] = math.clamp(note + 1, 1, 120)
ins.sampleMap[n] = smp
end
r:skip(200)
local e = Tracker.newEnvelope()
for i = 1, 25 do
local t, v = r:u8(), r:u8()
if t == 0xFF or (i > 1 and t <= (e.ticks[#e.ticks] or -1)) then
r:skip((25 - i) * 2)
break
end
table.insert(e.ticks, t)
table.insert(e.values, math.min(v, 64))
end
e.enabled = bit32.band(flg, 1) ~= 0 and #e.ticks > 0
e.loop = bit32.band(flg, 2) ~= 0
e.sustain = bit32.band(flg, 4) ~= 0
e.loopStart, e.loopEnd, e.susStart, e.susEnd = vls + 1, vle + 1, sls + 1, sle + 1
ins.volEnv = e
return ins
end
ins.nna, ins.dct, ins.dca = r:u8() % 4, r:u8() % 4, r:u8() % 3
ins.fadeout = math.min(r:u16le(), 1024)
ins.pps, ins.ppc = r:i8(), r:u8()
ins.globalVolume = math.min(r:u8(), 128)
local dfp = r:u8()
if dfp < 128 then
ins.pan = math.min(dfp, 64) * 4
end
r:skip(2 + 2 + 1 + 1)
ins.name = r:fixed(26)
local ifc, ifr = r:u8(), r:u8()
if ifc >= 128 then
ins.cutoff = ifc - 128
end
if ifr >= 128 then
ins.resonance = ifr - 128
end
r:skip(4)
for n = 1, 120 do
local note, smp = r:u8(), r:u8()
ins.noteMap[n] = math.clamp(note + 1, 1, 120)
ins.sampleMap[n] = smp
end
ins.volEnv = readEnvelope(r, "vol")
ins.panEnv = readEnvelope(r, "pan")
ins.pitchEnv = readEnvelope(r, "pitch")
if r.err then
return nil, "instrument truncated"
end
return ins
end
function It.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local maxBytes = opts and opts.maxBytes or 2 ^ 28
if r:peek(4) ~= "IMPM" then
return nil, Err.new(Err.CORRUPT, "no IMPM signature")
end
r:skip(4)
local title = r:fixed(26)
r:skip(2)
local ordnum, insnum, smpnum, patnum = r:u16le(), r:u16le(), r:u16le(), r:u16le()
local cwt, cmwt, flags, special = r:u16le(), r:u16le(), r:u16le(), r:u16le()
local gv, mv, speed, tempo, _sep, _pwd = r:u8(), r:u8(), r:u8(), r:u8(), r:u8(), r:u8()
local msgLen, msgOff = r:u16le(), r:u32le()
r:skip(4)
local chnPan, chnVol = {}, {}
for i = 1, 64 do
chnPan[i] = r:u8()
end
for i = 1, 64 do
chnVol[i] = r:u8()
end
if r.err then
return nil, r.err
end
if ordnum > 256 or insnum > 255 or smpnum > 255 or patnum > 255 then
return nil, Err.new(Err.CORRUPT, "bad header counts")
end
local orders = {}
for i = 1, ordnum do
orders[i] = r:u8()
end
local insOff, smpOff, patOff = {}, {}, {}
for i = 1, insnum do
insOff[i] = r:u32le()
end
for i = 1, smpnum do
smpOff[i] = r:u32le()
end
for i = 1, patnum do
patOff[i] = r:u32le()
end
if r.err then
return nil, r.err
end
-- channels: the highest one any pattern uses
local nch = 1
local packed: { Bytes.Reader? } = {}
local rowsOf: { number } = {}
for p = 1, patnum do
if patOff[p] > 0 then
local pr = r:sub(patOff[p])
local len, rows = pr:u16le(), pr:u16le()
pr:skip(4)
if pr.err or rows < 1 or rows > 1024 then
return nil, Err.new(Err.CORRUPT, "bad pattern " .. (p - 1), r.base + patOff[p])
end
local data = pr:slice(len)
packed[p], rowsOf[p] = data, rows
-- scan for the channel count
local scan = data:sub(0)
local seen: { [number]: number } = {}
while not scan:eof() do
local cv = scan:u8()
if cv == 0 then
continue
end
local ch = (cv - 1) % 64
nch = math.max(nch, ch + 1)
local mask = 0
if cv >= 128 then
mask = scan:u8()
seen[ch] = mask
else
mask = seen[ch] or 0
end
if bit32.band(mask, 1) ~= 0 then
scan:skip(1)
end
if bit32.band(mask, 2) ~= 0 then
scan:skip(1)
end
if bit32.band(mask, 4) ~= 0 then
scan:skip(1)
end
if bit32.band(mask, 8) ~= 0 then
scan:skip(2)
end
end
else
rowsOf[p] = 64
end
end
local m = Tracker.newModule("it", nch)
m.title = title
m.speed = if speed > 0 then speed else 6
m.tempo = if tempo >= 31 then tempo else 125
m.globalVolume = math.min(gv, 128)
m.mixVolume = math.min(mv, 128)
m.linear = bit32.band(flags, 8) ~= 0
m.instrumentMode = bit32.band(flags, 4) ~= 0
m.flags.oldEffects = bit32.band(flags, 16) ~= 0
m.flags.compatGxx = bit32.band(flags, 32) ~= 0
local stereo = bit32.band(flags, 1) ~= 0
for i = 1, nch do
local p = chnPan[i]
if p >= 128 then
m.channelMute[i] = true
p -= 128
end
if not stereo then
m.channelPan[i] = 128
elseif p == 100 then
m.channelPan[i] = 512
else
m.channelPan[i] = math.min(p, 64) * 4
end
m.channelVolume[i] = math.min(chnVol[i], 64)
end
for i = 1, ordnum do
if orders[i] == 255 then
break
end
table.insert(m.order, orders[i])
end
m.meta.source = { format = "it", tracker = cwt, compatible = cmwt }
if bit32.band(special, 1) ~= 0 and msgLen > 0 then
local mr = r:sub(msgOff, msgLen)
m.meta.message = string.gsub(mr:fixed(msgLen), "\r", "\n")
end
-- instruments
for i = 1, insnum do
local ins, ierr = readInstrument(r:sub(insOff[i]), cmwt < 0x200)
if not ins then
return nil, Err.new(Err.CORRUPT, "instrument " .. i .. ": " .. tostring(ierr), r.base + insOff[i])
end
m.instruments[i] = ins
end
-- samples
local total = 0
for i = 1, smpnum do
local h = r:sub(smpOff[i], 80)
if h:string(4) ~= "IMPS" then
return nil, Err.new(Err.CORRUPT, "sample " .. i .. ": bad signature", r.base + smpOff[i])
end
h:skip(13)
local s = Tracker.newSample()
m.samples[i] = s
local gvl, flg, vol = h:u8(), h:u8(), h:u8()
s.name = h:fixed(26)
local cvt, dfp = h:u8(), h:u8()
local len, lb, le, c5, slb, sle, ptr = h:u32le(), h:u32le(), h:u32le(), h:u32le(), h:u32le(), h:u32le(), h:u32le()
local vis, vid, vir, vit = h:u8(), h:u8(), h:u8(), h:u8()
if h.err then
return nil, Err.new(Err.TRUNCATED, "sample header " .. i)
end
s.globalVolume = math.min(gvl, 64)
s.volume = math.min(vol, 64)
if dfp >= 128 then
s.pan = math.min(dfp - 128, 64) * 4
end
s.c5speed = if c5 > 0 then c5 else 8363
s.vibRate, s.vibDepth, s.vibSweep, s.vibType = vis, vid, vir, vit % 4
local bits = if bit32.band(flg, 2) ~= 0 then 16 else 8
local nchs = if bit32.band(flg, 4) ~= 0 then 2 else 1
s.bits = bits
if bit32.band(flg, 1) ~= 0 and len > 0 then
len = math.min(len, 2 ^ 26)
total += len * nchs * 4
if total > maxBytes then
return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit")
end
local data: buffer? = nil
if bit32.band(flg, 8) ~= 0 then
-- compressed: each channel separately
local it215 = bit32.band(cvt, 4) ~= 0
local p = r.base + ptr
local parts = {}
for c = 1, nchs do
local d, used = Itsex.decompress(r.buf, p, r.limit, len, bits, it215)
if not d then
return nil, Err.new(Err.CORRUPT, "sample " .. i .. ": " .. tostring(used))
end
parts[c] = d
p += used :: number
end
if nchs == 1 then
data = parts[1]
else
local inter = buffer.create(len * 8)
for f = 0, len - 1 do
buffer.writef32(inter, f * 8, buffer.readf32(parts[1], f * 4))
buffer.writef32(inter, f * 8 + 4, buffer.readf32(parts[2], f * 4))
end
data = inter
end
else
local bps = bits // 8
local avail = math.max(0, r:size() - ptr) // (bps * nchs)
len = math.min(len, avail)
data = Tracker.Pcm.decode(r.buf, r.base + ptr, len, {
bits = bits,
signed = bit32.band(cvt, 1) ~= 0,
bigEndian = bit32.band(cvt, 2) ~= 0,
delta = bit32.band(cvt, 4) ~= 0,
channels = nchs,
planar = true,
})
end
if data then
s.data, s.length, s.channels = data, len, nchs
if bit32.band(flg, 16) ~= 0 then
s.loopStart, s.loopEnd, s.loopType = lb, math.min(le, len), if bit32.band(flg, 64) ~= 0 then 2 else 1
end
if bit32.band(flg, 32) ~= 0 then
s.susStart, s.susEnd, s.susType = slb, math.min(sle, len), if bit32.band(flg, 128) ~= 0 then 2 else 1
end
end
end
end
-- patterns
for p = 1, patnum do
local pat = Tracker.newPattern(rowsOf[p], nch)
m.patterns[p] = pat
local pr = packed[p]
if pr then
local d = pat.data
local lastMask, lastNote, lastIns, lastVol, lastFx, lastParam = {}, {}, {}, {}, {}, {}
local row = 0
while row < pat.rows and not pr:eof() do
local cv = pr:u8()
if cv == 0 then
row += 1
continue
end
local ch = (cv - 1) % 64
local mask = if cv >= 128 then pr:u8() else (lastMask[ch] or 0)
lastMask[ch] = mask
local note, ins, vol, fx, param = 0, 0, 0, 0, 0
if bit32.band(mask, 1) ~= 0 then
local n = pr:u8()
-- 255 note off, 254 note cut, 246 note fade (as IT and OpenMPT store "~~~"); other values: nothing
note = if n < 120 then n + 1 elseif n == 255 then 255 elseif n == 254 then 254 elseif n == 246 then 253 else 0
lastNote[ch] = note
elseif bit32.band(mask, 16) ~= 0 then
note = lastNote[ch] or 0
end
if bit32.band(mask, 2) ~= 0 then
ins = pr:u8()
lastIns[ch] = ins
elseif bit32.band(mask, 32) ~= 0 then
ins = lastIns[ch] or 0
end
if bit32.band(mask, 4) ~= 0 then
vol = math.min(pr:u8(), 212) + 1
lastVol[ch] = vol
elseif bit32.band(mask, 64) ~= 0 then
vol = lastVol[ch] or 0
end
if bit32.band(mask, 8) ~= 0 then
fx, param = pr:u8(), pr:u8()
if fx > 26 then
fx, param = 0, 0
end
lastFx[ch], lastParam[ch] = fx, param
elseif bit32.band(mask, 128) ~= 0 then
fx, param = lastFx[ch] or 0, lastParam[ch] or 0
end
if ch < nch then
local o = (row * nch + ch) * 5
buffer.writeu8(d, o, note)
buffer.writeu8(d, o + 1, ins)
buffer.writeu8(d, o + 2, vol)
buffer.writeu8(d, o + 3, fx)
buffer.writeu8(d, o + 4, param)
end
end
end
end
local ok, verr = Tracker.validate(m)
if not ok then
return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module")
end
return m, nil
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions)
function It.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
local m, err = It.decode(r, opts)
if not m then
return nil, err
end
return Tracker.render(m, opts)
end
return It
+261
View File
@@ -0,0 +1,261 @@
--!strict
-- music/midi/Render: the tempo map (ticks -> seconds, as python mido computes lengths), the time-ordered event list,
-- and the audio Decoder that plays a Midi through codecs/SoundFont's synth (a SoundFont bank, or the built-in
-- waveform set). Format 0 / 1: one tempo map from every track's tempo events, tracks merged (ties keep track order).
-- Format 2: each track is its own song with its own tempo map, played one after another.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local SoundFont = require("@formats/codecs/SoundFont")
local Synth = SoundFont.Synth
local Render = {}
export type TempoMap = { ticks: { number }, secs: { number }, us: { number }, division: number }
local STATUS = { noteOff = 0x80, noteOn = 0x90, aftertouch = 0xA0, controller = 0xB0, program = 0xC0, channelPressure = 0xD0, pitchBend = 0xE0 }
local function tempoOf(ev: any): number?
if ev.type == "meta" and ev.meta == 0x51 and type(ev.data) == "table" and #ev.data >= 3 then
return ev.data[1] * 65536 + ev.data[2] * 256 + ev.data[3]
end
return nil
end
-- tempoMap(midi, track?) -> TempoMap: from every track (format 0 / 1) or from one track (format 2)
function Render.tempoMap(midi: Types.Midi, track: number?): TempoMap
local changes: { { number } } = {}
for ti, t in midi.tracks do
if track == nil or track == ti then
for i, ev in t.events do
local us = tempoOf(ev)
if us then
table.insert(changes, { ev.tick, ti, i, us })
end
end
end
end
table.sort(changes, function(a: { number }, b: { number }): boolean
if a[1] ~= b[1] then
return a[1] < b[1]
end
if a[2] ~= b[2] then
return a[2] < b[2]
end
return a[3] < b[3]
end)
local map: TempoMap = { ticks = { 0 }, secs = { 0 }, us = { 500000 }, division = midi.division }
local div = midi.division
for _, c in changes do
local n = #map.ticks
local tick = c[1]
local sec = map.secs[n] + (tick - map.ticks[n]) * map.us[n] * 1e-6 / div
if tick == map.ticks[n] then
map.us[n] = c[4]
else
table.insert(map.ticks, tick)
table.insert(map.secs, sec)
table.insert(map.us, c[4])
end
end
return map
end
-- seconds(map, tick) -> seconds (PPQ through the tempo map; SMPTE divisions are fixed time)
function Render.seconds(map: TempoMap, tick: number): number
local div = map.division
if div < 0 then
local fps = -(div // 256)
local tpf = div % 256
if tpf == 0 then
return 0
end
return tick / ((if fps == 29 then 29.97 else fps) * tpf)
end
local ticks = map.ticks
-- binary search for the last change at or before tick
local lo, hi = 1, #ticks
while lo < hi do
local mid = (lo + hi + 1) // 2
if ticks[mid] <= tick then
lo = mid
else
hi = mid - 1
end
end
return map.secs[lo] + (tick - ticks[lo]) * map.us[lo] * 1e-6 / div
end
-- length(midi) -> seconds to the last event (format 2: the tracks one after another)
function Render.length(midi: Types.Midi): number
if #midi.tracks == 0 then
return 0
end
if midi.format == 2 then
local total = 0
for ti, t in midi.tracks do
local map = Render.tempoMap(midi, ti)
local last = 0
for _, ev in t.events do
last = math.max(last, ev.tick)
end
total += Render.seconds(map, last)
end
return total
end
local map = Render.tempoMap(midi)
local last = 0
for _, t in midi.tracks do
for _, ev in t.events do
last = math.max(last, ev.tick)
end
end
return Render.seconds(map, last)
end
export type Timeline = { time: { number }, status: { number }, d1: { number }, d2: { number }, length: number }
-- timeline(midi) -> the channel messages in play order with their times in seconds
function Render.timeline(midi: Types.Midi): Timeline
local items: { { any } } = {}
local offset = 0
local function add(map: TempoMap, ti: number, t: any, base: number)
for i, ev in t.events do
local st = STATUS[ev.type]
if st and type(ev.data) == "table" then
local ch = ev.channel or 0
table.insert(items, { base + Render.seconds(map, ev.tick), ti, i, st + ch % 16, ev.data[1] or 0, ev.data[2] or 0 })
end
end
end
if midi.format == 2 then
for ti, t in midi.tracks do
local map = Render.tempoMap(midi, ti)
add(map, ti, t, offset)
local last = 0
for _, ev in t.events do
last = math.max(last, ev.tick)
end
offset += Render.seconds(map, last)
end
else
local map = Render.tempoMap(midi)
for ti, t in midi.tracks do
add(map, ti, t, 0)
end
end
table.sort(items, function(a: { any }, b: { any }): boolean
if a[1] ~= b[1] then
return a[1] < b[1]
end
if a[2] ~= b[2] then
return a[2] < b[2]
end
return a[3] < b[3]
end)
local tl: Timeline = { time = table.create(#items), status = table.create(#items), d1 = table.create(#items), d2 = table.create(#items), length = Render.length(midi) }
for i, it in items do
tl.time[i], tl.status[i], tl.d1[i], tl.d2[i] = it[1], it[4], it[5] % 128, it[6] % 128
end
return tl
end
export type RenderOptions = {
sampleRate: number?, -- default 44100
soundfont: any?, -- a SoundFont (music/sf2 decode, codecs/SoundFont.parse) or SF2 bytes (buffer / string); default the built-in waveforms
gain: number?, -- linear output gain, default 0.5
tail: number?, -- seconds rendered after the last event (release tails), default 1
maxVoices: number?, -- default 256
}
-- decoder(midi, opts?) -> Types.Decoder | nil, Err
function Render.decoder(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder?, Err.Err?)
if type(midi) ~= "table" or type(midi.tracks) ~= "table" or type(midi.division) ~= "number" or midi.division == 0 then
return nil, Err.new(Err.ARG, "render: needs a Midi value")
end
local o: RenderOptions = opts or {}
local rate = o.sampleRate or 44100
if type(rate) ~= "number" or rate < 1000 or rate > 384000 then
return nil, Err.new(Err.ARG, "render: sampleRate must be 1000..384000")
end
local sf = o.soundfont
if sf == nil then
sf = SoundFont.fallback()
elseif not SoundFont.isSoundFont(sf) then
local parsed, err = SoundFont.parse(sf)
if not parsed then
return nil, err
end
sf = parsed
end
local tl = Render.timeline(midi)
local tail = o.tail or 1
local frames = math.max(0, math.ceil((tl.length + tail) * rate))
local nev = #tl.time
local evFrame = table.create(nev)
for i = 1, nev do
evFrame[i] = math.floor(tl.time[i] * rate + 0.5)
end
local gain, maxVoices = o.gain, o.maxVoices
local state = Synth.new(sf, rate, gain, maxVoices)
local pos, nextEv = 0, 1
local dec = {
sampleRate = rate,
channels = 2,
frames = frames,
duration = frames / rate,
bitrate = 0,
tags = {} :: Types.Tags,
}
for _, t in midi.tracks do
if t.name and not dec.tags.title then
dec.tags.title = t.name
end
end
local function read(_self: any, n: number, out: buffer?): (buffer, number)
n = math.max(0, math.min(math.floor(n), frames - pos))
local buf = out
if not buf or buffer.len(buf) < n * 8 then
buf = buffer.create(math.max(n, 1) * 8)
end
local b = buf :: buffer
buffer.fill(b, 0, 0, n * 8)
local i = 0
while i < n do
while nextEv <= nev and evFrame[nextEv] <= pos + i do
Synth.midi(state, tl.status[nextEv], tl.d1[nextEv], tl.d2[nextEv])
nextEv += 1
end
local stop = n
if nextEv <= nev then
stop = math.min(n, evFrame[nextEv] - pos)
end
if stop > i then
Synth.render(state, b, i, stop - i)
i = stop
end
end
pos += n
return b, n
end
dec.read = read :: any
local scratch = buffer.create(4096 * 8)
dec.seek = function(_self: any, seconds: number)
local target = math.clamp(math.floor((tonumber(seconds) or 0) * rate), 0, frames)
if target < pos then
Synth.reset(state)
pos, nextEv = 0, 1
end
while pos < target do
read(nil, math.min(4096, target - pos), scratch)
end
end :: any
dec.position = function(_self: any): number
return pos / rate
end :: any
return (dec :: any) :: Types.Decoder, nil
end
return Render
+402
View File
@@ -0,0 +1,402 @@
--!strict
-- music/midi/Smf: Standard MIDI File chunks <-> Types.Midi. Reads MThd / MTrk (formats 0, 1, 2; PPQ and SMPTE
-- divisions; running status, also across meta / sysex events as most players accept), skips unknown chunks, unwraps
-- RIFF RMID. Writes MThd + MTrk with optional running status; with running status on (the default) the bytes are
-- those python mido writes for the same events (running status reset after meta / sysex, one end-of-track at the
-- end, mid-track end-of-track events dropped). Written from the SMF 1.0 specification (no third-party code).
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Smf = {}
local readu8 = buffer.readu8
local CHANNEL_TYPES = { [8] = "noteOff", [9] = "noteOn", [10] = "aftertouch", [11] = "controller", [12] = "program", [13] = "channelPressure", [14] = "pitchBend" }
local TYPE_STATUS = { noteOff = 0x80, noteOn = 0x90, aftertouch = 0xA0, controller = 0xB0, program = 0xC0, channelPressure = 0xD0, pitchBend = 0xE0 }
Smf.TYPE_STATUS = TYPE_STATUS
export type ReadOptions = {
strict: boolean?, -- a truncated track / file is an error (default false: keep the events read so far, meta.truncated)
maxEvents: number?, -- default 2^24
}
export type WriteOptions = {
runningStatus: boolean?, -- default true
}
local function bytesOf(b: buffer, p: number, n: number): { number }
local t: { number } = table.create(n)
for i = 0, n - 1 do
t[i + 1] = readu8(b, p + i)
end
return t
end
local function text(data: { number }): string
local parts = table.create(#data)
for i, c in data do
parts[i] = string.char(c)
end
return table.concat(parts)
end
Smf.text = text
-- ------------------------------------------------------------------------------------------------ read
-- one MTrk body [p, e): events | nil, message, truncated
local function readTrack(b: buffer, p: number, e: number, budget: { number }): ({ Types.MidiEvent }?, string?, boolean)
local events: { Types.MidiEvent } = {}
local tick = 0
local running = 0
while p < e do
-- delta time
local delta, n = 0, 0
repeat
if p >= e then
return events, nil, true
end
local c = readu8(b, p)
p += 1
n += 1
delta = delta * 128 + c % 128
if n > 4 then
return nil, "delta time longer than 4 bytes", false
end
until c < 128
tick += delta
if p >= e then
return events, nil, true
end
local status = readu8(b, p)
if status < 0x80 then
if running == 0 then
return nil, "running status without a previous status byte", false
end
status = running
else
p += 1
if status < 0xF0 then
running = status
end
end
budget[1] -= 1
if budget[1] < 0 then
return nil, "LIMIT", false
end
if status == 0xFF or status == 0xF0 or status == 0xF7 then
local mtype = 0
if status == 0xFF then
if p >= e then
return events, nil, true
end
mtype = readu8(b, p)
p += 1
end
local len, m = 0, 0
repeat
if p >= e then
return events, nil, true
end
local c = readu8(b, p)
p += 1
m += 1
len = len * 128 + c % 128
if m > 4 then
return nil, "length longer than 4 bytes", false
end
until c < 128
if p + len > e then
return events, nil, true
end
local data = bytesOf(b, p, len)
p += len
if status == 0xFF then
table.insert(events, { tick = tick, type = "meta", meta = mtype, data = data })
else
table.insert(events, { tick = tick, type = if status == 0xF0 then "sysex" else "escape", data = data })
end
elseif status >= 0xF0 then
return nil, string.format("unexpected status byte 0x%02x in a track", status), false
else
local kind = status // 16
local count = if kind == 12 or kind == 13 then 1 else 2
if p + count > e then
return events, nil, true
end
local d1 = readu8(b, p)
local d2 = if count == 2 then readu8(b, p + 1) else 0
if d1 >= 128 or d2 >= 128 then
return nil, "data byte over 127", false
end
p += count
table.insert(events, {
tick = tick,
type = CHANNEL_TYPES[kind],
channel = status % 16,
data = if count == 2 then { d1, d2 } else { d1 },
})
end
end
return events, nil, false
end
-- read(r, opts?) -> Midi | nil, Err
function Smf.read(r: Bytes.Reader, opts: ReadOptions?): (Types.Midi?, Err.Err?)
local strict = opts and opts.strict or false
local budget = { opts and opts.maxEvents or 2 ^ 24 }
local b = r.buf
local base, limit = r.base, r.limit
local rmid = false
-- RIFF RMID: the SMF is the "data" chunk
if r:peek(4) == "RIFF" and r:peek(4, 8) == "RMID" then
local q = base + 12
local found = false
while q + 8 <= limit do
local id = buffer.readstring(b, q, 4)
local size = buffer.readu32(b, q + 4)
if id == "data" then
base = q + 8
limit = math.min(limit, base + size)
found = true
break
end
q += 8 + size + size % 2
end
if not found then
return nil, Err.new(Err.CORRUPT, "RMID without a data chunk", r.base)
end
rmid = true
end
local h = Bytes.reader(b, base, limit - base)
if h:string(4) ~= "MThd" then
return nil, Err.new(Err.CORRUPT, "no MThd header", base)
end
local hlen = h:u32be()
local format, ntrks, division = h:u16be(), h:u16be(), h:i16be()
if h.err then
return nil, h.err
end
if hlen < 6 then
return nil, Err.new(Err.CORRUPT, "MThd shorter than 6 bytes", base + 4)
end
if format > 2 then
return nil, Err.new(Err.UNSUPPORTED, "SMF format " .. format, base + 8)
end
if division == 0 then
return nil, Err.new(Err.CORRUPT, "zero ticks per quarter note", base + 12)
end
local midi = Types.Midi.new(division)
midi.format = format
local truncated = false
local p = base + 8 + hlen
while #midi.tracks < ntrks and p + 8 <= limit do
local id = buffer.readstring(b, p, 4)
local size = bit32.byteswap(buffer.readu32(b, p + 4))
local s = p + 8
local e = s + size
if e > limit then
e = limit
truncated = true
end
if id == "MTrk" then
local events, msg, short = readTrack(b, s, e, budget)
if not events then
if msg == "LIMIT" then
return nil, Err.new(Err.LIMIT, "over the event limit")
end
return nil, Err.new(Err.CORRUPT, msg or "bad track", s)
end
truncated = truncated or short
local track: { events: { Types.MidiEvent }, name: string? } = { events = events, name = nil }
for _, ev in events do
if ev.type == "meta" and ev.meta == 3 then
track.name = text(ev.data :: { number })
break
end
end
table.insert(midi.tracks, track)
end
p = s + size
end
if #midi.tracks < ntrks and p < limit then
truncated = true
elseif #midi.tracks < ntrks then
truncated = true
end
if truncated and strict then
return nil, Err.new(Err.TRUNCATED, "the file ends inside a track (or before all tracks)")
end
midi.meta.declaredTracks = ntrks
midi.meta.truncated = truncated
midi.meta.rmid = rmid
if division < 0 then
local fps = -(division // 256)
midi.meta.smpte = { fps = if fps == 29 then 29.97 else fps, ticksPerFrame = division % 256 }
end
return midi, nil
end
-- ------------------------------------------------------------------------------------------------ write
local function vlq(w: Bytes.Writer, v: number)
if v < 128 then
w:u8(v)
return
end
local bytes = {}
while v > 0 do
table.insert(bytes, 1, v % 128)
v = v // 128
end
for i, c in bytes do
w:u8(if i < #bytes then c + 128 else c)
end
end
local function byteList(d: any, want: number?): { number }?
if type(d) ~= "table" then
return if want == 0 then {} else nil
end
for i, v in d do
if type(i) ~= "number" or type(v) ~= "number" or v < 0 or v > 255 or v % 1 ~= 0 then
return nil
end
end
if want and #d < want then
return nil
end
return d
end
-- write(midi, opts?) -> buffer | nil, Err
function Smf.write(midi: Types.Midi, opts: WriteOptions?): (buffer?, Err.Err?)
if type(midi) ~= "table" or type(midi.tracks) ~= "table" then
return nil, Err.new(Err.ARG, "midi encode: needs a Midi value with tracks")
end
local running = not (opts and opts.runningStatus == false)
local format = midi.format or 1
local division = midi.division or 480
if type(format) ~= "number" or format < 0 or format > 2 or format % 1 ~= 0 then
return nil, Err.new(Err.ARG, "midi encode: format must be 0, 1 or 2")
end
if type(division) ~= "number" or division == 0 or division < -32768 or division > 32767 or division % 1 ~= 0 then
return nil, Err.new(Err.ARG, "midi encode: division must be a non-zero 16-bit integer")
end
if format == 0 and #midi.tracks ~= 1 then
return nil, Err.new(Err.ARG, "midi encode: format 0 needs exactly one track")
end
if #midi.tracks > 65535 then
return nil, Err.new(Err.ARG, "midi encode: too many tracks")
end
local w = Bytes.writer(1024)
w:string("MThd")
w:u32be(6)
w:u16be(format)
w:u16be(#midi.tracks)
w:u16be(if division < 0 then division + 65536 else division)
for ti, track in midi.tracks do
local events = if type(track) == "table" then track.events else nil
if type(events) ~= "table" then
return nil, Err.new(Err.ARG, "midi encode: track " .. ti .. " has no events list")
end
-- stable order by tick
local sorted = true
local last = 0
for i, ev in events do
if type(ev) ~= "table" or type(ev.tick) ~= "number" or ev.tick < 0 or ev.tick % 1 ~= 0 then
return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d needs a whole non-negative tick", ti, i))
end
if ev.tick < last then
sorted = false
end
last = ev.tick
end
local list = events
if not sorted then
list = table.clone(events)
local order: { [any]: number } = {}
for i, ev in list do
order[ev] = i
end
table.sort(list, function(a: any, c: any): boolean
if a.tick ~= c.tick then
return a.tick < c.tick
end
return order[a] < order[c]
end)
end
w:string("MTrk")
local lenAt = w:tell()
w:u32be(0)
local start = w:tell()
local prev = 0
local status = 0
local endTick = 0
for i, ev in list do
local t = ev.type
endTick = ev.tick
if t == "meta" and ev.meta == 0x2F then
continue -- written once at the end
end
local delta = ev.tick - prev
if delta > 0x0FFFFFFF then
return nil, Err.new(Err.ARG, "midi encode: a delta time over 0x0FFFFFFF ticks")
end
local base = TYPE_STATUS[t]
if base then
local ch = ev.channel or 0
if type(ch) ~= "number" or ch < 0 or ch > 15 or ch % 1 ~= 0 then
return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: channel must be 0..15", ti, i))
end
local n = if base == 0xC0 or base == 0xD0 then 1 else 2
local d = byteList(ev.data, n)
if not d or d[1] > 127 or (n == 2 and d[2] > 127) then
return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: %s needs %d data bytes 0..127", ti, i, t, n))
end
vlq(w, delta)
local st = base + ch
if not (running and st == status) then
w:u8(st)
end
status = st
w:u8(d[1])
if n == 2 then
w:u8(d[2])
end
elseif t == "meta" or t == "sysex" or t == "escape" then
local d = byteList(ev.data, 0)
if not d then
return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: data must be bytes", ti, i))
end
vlq(w, delta)
if t == "meta" then
local m = ev.meta
if type(m) ~= "number" or m < 0 or m > 127 or m % 1 ~= 0 then
return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: meta type must be 0..127", ti, i))
end
w:u8(0xFF)
w:u8(m)
else
w:u8(if t == "sysex" then 0xF0 else 0xF7)
end
if #d > 0x0FFFFFFF then
return nil, Err.new(Err.ARG, "midi encode: event data too long")
end
vlq(w, #d)
for _, c in d do
w:u8(c)
end
status = 0
else
return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: unknown type %s", ti, i, tostring(t)))
end
prev = ev.tick
end
vlq(w, math.max(0, endTick - prev))
w:u8(0xFF)
w:u8(0x2F)
w:u8(0)
w:setU32be(lenAt, w:tell() - start)
end
return w:finish(), nil
end
return Smf
+136
View File
@@ -0,0 +1,136 @@
--!strict
-- music/midi: Standard MIDI Files (SMF 1.0: formats 0, 1 and 2; PPQ and SMPTE time; RIFF RMID read). Written from the
-- specification (no third-party code); rendering goes through codecs/SoundFont (a TinySoundFont port).
-- Supports: decode to a Types.Midi (absolute ticks; channel events noteOff / noteOn / aftertouch / controller /
-- program / channelPressure / pitchBend with their raw data bytes, sysex / escape with the bytes after the length,
-- meta events with meta = the meta type; meta.tempos / timeSignatures / keySignatures, track names), encode (running
-- status optional, byte-identical to python mido's writer by default), the tempo map (tickToSeconds, length), and
-- render / open: an audio Decoder (stereo f32) through an SF2 SoundFont (opts.soundfont) or the built-in waveform set.
-- Not supported: RMID write, XMF / RMI DLS banks, system common / realtime bytes inside tracks (CORRUPT).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Smf = require("@formats/music/midi/Smf")
local Render = require("@formats/music/midi/Render")
-- ------------------------------------------------------------------------------------------------ contract
local Midi = {
name = "midi",
category = "music",
extensions = { "mid", "midi", "smf", "kar", "rmi" },
mime = { "audio/midi", "audio/x-midi" },
deps = { "core/Err", "core/Bytes", "codecs/SoundFont", "Types" },
caps = { decode = true, encode = true, formats = { 0, 1, 2 }, render = true, streaming = true, rmid = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = Smf.ReadOptions -- strict (default false), maxEvents (default 2^24)
export type EncodeOptions = Smf.WriteOptions -- runningStatus (default true)
export type RenderOptions = Render.RenderOptions -- sampleRate, soundfont, gain, tail, maxVoices
-- ------------------------------------------------------------------------------------------------ sniff
function Midi.sniff(r: Bytes.Reader): number
if r:peek(4) == "MThd" then
return 1
end
if r:peek(4) == "RIFF" and r:peek(4, 8) == "RMID" then
return 1
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function render(self: Types.Midi, opts: RenderOptions?): Types.Decoder
local dec, err = Render.decoder(self, opts)
if not dec then
-- the Types contract returns a Decoder; a failed render is an empty one (Midi.render returns the Err)
local empty: any = {
sampleRate = 44100, channels = 2, frames = 0, duration = 0, bitrate = 0, tags = {}, err = err,
read = function(_self: any, _n: number, out: buffer?): (buffer, number)
return out or buffer.create(0), 0
end,
seek = function() end,
position = function(): number
return 0
end,
}
return empty
end
return dec
end
local function summarize(midi: Types.Midi)
local tempos, sigs, keys = {}, {}, {}
local map = Render.tempoMap(midi)
for ti, t in midi.tracks do
for _, ev in t.events do
if ev.type == "meta" then
local d = ev.data :: { number }
if ev.meta == 0x51 and #d >= 3 then
table.insert(tempos, { tick = ev.tick, track = ti, usPerQuarter = d[1] * 65536 + d[2] * 256 + d[3], bpm = 60000000 / math.max(1, d[1] * 65536 + d[2] * 256 + d[3]), seconds = Render.seconds(map, ev.tick) })
elseif ev.meta == 0x58 and #d >= 4 then
table.insert(sigs, { tick = ev.tick, track = ti, numerator = d[1], denominator = 2 ^ math.min(d[2], 31), clocksPerClick = d[3], notated32ndsPerBeat = d[4] })
elseif ev.meta == 0x59 and #d >= 2 then
table.insert(keys, { tick = ev.tick, track = ti, sharps = if d[1] >= 128 then d[1] - 256 else d[1], minor = d[2] == 1 })
end
end
end
end
midi.meta.tempos = tempos
midi.meta.timeSignatures = sigs
midi.meta.keySignatures = keys
midi.meta.length = Render.length(midi)
end
function Midi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Err?)
local midi, err = Smf.read(r, opts)
if not midi then
return nil, err
end
summarize(midi)
midi.meta.source = { format = "midi", smf = midi.format }
midi.render = render
return midi, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Midi.encode(midi: Types.Midi, opts: EncodeOptions?): (buffer?, Err.Err?)
return Smf.write(midi, opts)
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + RenderOptions)
function Midi.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
local midi, err = Midi.decode(r, opts)
if not midi then
return nil, err
end
return Render.decoder(midi, opts)
end
-- ------------------------------------------------------------------------------------------------ extras
-- render(midi, opts?) -> Decoder | nil, Err (also works on a Midi built by hand with Types.Midi.new)
function Midi.render(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder?, Err.Err?)
return Render.decoder(midi, opts)
end
-- tickToSeconds(midi, tick, track?) -> seconds (track: format 2's per-track tempo map)
function Midi.tickToSeconds(midi: Types.Midi, tick: number, track: number?): number
return Render.seconds(Render.tempoMap(midi, track), tick)
end
-- tempoMap(midi, track?) -> { ticks, secs, us, division } (change points)
Midi.tempoMap = Render.tempoMap
Midi.seconds = Render.seconds
-- length(midi) -> seconds to the last event (what python mido's MidiFile.length reports for formats 0 / 1)
function Midi.length(midi: Types.Midi): number
return Render.length(midi)
end
-- text(data) -> the bytes of a text meta event as a string
Midi.text = Smf.text
return Midi
+361
View File
@@ -0,0 +1,361 @@
--!strict
-- music/mod: ProTracker / NoiseTracker / StarTrekker MOD modules (the 31-sample "M.K." family: M.K., M!K!, FLT4,
-- 4CHN .. 9CHN, 10CH .. 32CH, xxCN, CD81, OKTA / OCTA, TDZx; 15-sample Soundtracker files when asked for by name or
-- extension). Written from the ProTracker 2.3 documentation. Reads into the codecs/Tracker Module and plays through
-- its engine (Module:render() / open() -> an audio Decoder). Writes 31-sample MODs (M.K. / xCHN / xxCH) from "mod"
-- modules, and from XM modules that fit (one sample per instrument, effects 0..F, 64-row patterns).
-- Not supported: FLT8's split 4 + 4 channel patterns (read as 8 plain channels), the Amiga hardware low-pass filter
-- (E0x), PowerPacker-packed files.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Tracker = require("@formats/codecs/Tracker")
-- ------------------------------------------------------------------------------------------------ contract
local Mod = {
name = "mod",
category = "music",
extensions = { "mod", "m15", "stk", "nst" },
mime = { "audio/x-mod", "audio/mod" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" },
caps = { decode = true, encode = true, render = true, channels = { 1, 32 } },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse bigger sample data in total (default 64 MB of f32 samples)
}
export type EncodeOptions = {}
-- ------------------------------------------------------------------------------------------------ constants
local Pcm = Tracker.Pcm
local Tables = Tracker.Tables
local FIXED: { [string]: number } = {
["M.K."] = 4,
["M!K!"] = 4,
["M&K!"] = 4,
["N.T."] = 4,
["FLT4"] = 4,
["FLT8"] = 8,
["CD81"] = 8,
["OKTA"] = 8,
["OCTA"] = 8,
["EXO4"] = 4,
["EXO8"] = 8,
}
-- channels from the 4-byte signature at 1080, or nil
local function signatureChannels(sig: string): number?
local fixed = FIXED[sig]
if fixed then
return fixed
end
local d = string.match(sig, "^(%d)CHN$")
if d then
local n = tonumber(d) :: number
return if n >= 1 then n else nil
end
local dd = string.match(sig, "^(%d%d)C[HN]$")
if dd then
local n = tonumber(dd) :: number
return if n >= 1 and n <= 32 then n else nil
end
local t = string.match(sig, "^TDZ(%d)$")
if t then
local n = tonumber(t) :: number
return if n >= 1 then n else nil
end
return nil
end
-- ------------------------------------------------------------------------------------------------ sniff
function Mod.sniff(r: Bytes.Reader): number
if r:size() < 1084 then
return 0
end
local sig = r:peek(4, 1080)
if signatureChannels(sig) then
return 0.8
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Mod.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local maxBytes = opts and opts.maxBytes or 2 ^ 26
local size = r:size()
local sig = if size >= 1084 then r:peek(4, 1080) else ""
local channels = signatureChannels(sig)
local nsamples = 31
if not channels then
-- a 15-sample Soundtracker module (no signature): only when the header is plausible
nsamples, channels = 15, 4
end
local nch = channels :: number
local m = Tracker.newModule("mod", nch)
m.title = r:fixed(20)
local lengths: { number } = {}
for i = 1, nsamples do
local s = Tracker.newSample(r:fixed(22))
local len = r:u16be() * 2
local ft = r:u8() % 16
local vol = r:u8()
local ls = r:u16be() * 2
local ll = r:u16be() * 2
if r.err then
return nil, r.err
end
if nsamples == 15 and (vol > 64 or ft ~= 0) then
return nil, Err.new(Err.CORRUPT, "not a MOD (bad sample header)")
end
s.finetune = (if ft >= 8 then ft - 16 else ft) * 16
s.volume = math.min(vol, 64)
s.bits = 8
if ll > 2 then
s.loopStart, s.loopEnd, s.loopType = ls, ls + ll, 1
end
lengths[i] = len
m.samples[i] = s
end
local songLength = r:u8()
local restart = r:u8()
local order: { number } = {}
local maxPat = 0
for i = 1, 128 do
local p = r:u8()
order[i] = p
maxPat = math.max(maxPat, p)
end
if r.err then
return nil, r.err
end
if songLength == 0 or songLength > 128 or maxPat >= 128 then
return nil, Err.new(Err.CORRUPT, "not a MOD (bad order list)")
end
if nsamples == 31 then
r:skip(4)
end
for i = 1, songLength do
m.order[i] = order[i]
end
m.restart = if restart < songLength then restart else 0
m.meta.signature = if nsamples == 31 then sig else nil
m.flags.amigaLimits = nch == 4
-- patterns
local npat = maxPat + 1
local patBytes = 64 * nch * 4
if not r:need(npat * patBytes) then
return nil, r.err
end
local buf = r.buf
for p = 0, npat - 1 do
local pat = Tracker.newPattern(64, nch)
local base = r.pos + p * patBytes
local d = pat.data
for i = 0, 64 * nch - 1 do
local o = base + i * 4
local b0, b1, b2, b3 = buffer.readu8(buf, o), buffer.readu8(buf, o + 1), buffer.readu8(buf, o + 2), buffer.readu8(buf, o + 3)
local period = (b0 % 16) * 256 + b1
local ins = (b0 // 16) * 16 + b2 // 16
local q = i * 5
buffer.writeu8(d, q, Tables.periodToNote(period))
buffer.writeu8(d, q + 1, ins)
buffer.writeu8(d, q + 3, b2 % 16)
buffer.writeu8(d, q + 4, b3)
end
m.patterns[p + 1] = pat
end
r:skip(npat * patBytes)
-- sample data (8-bit signed; the last samples of a truncated file are cut short)
local total = 0
for i = 1, nsamples do
local s = m.samples[i]
local len = math.min(lengths[i], r:remaining())
total += len * 4
if total > maxBytes then
return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit")
end
local data = Pcm.decode(buf, r.pos, len, { bits = 8, signed = true })
if not data then
return nil, Err.new(Err.TRUNCATED, "sample data", r.pos)
end
r:skip(len)
s.data, s.length = data, len
if s.loopEnd > len then
s.loopEnd = len
if s.loopEnd - s.loopStart < 2 then
s.loopType, s.loopStart, s.loopEnd = 0, 0, 0
end
end
end
m.meta.source = { format = "mod", samples = nsamples }
m.render = Tracker.renderMethod
local ok, verr = Tracker.validate(m)
if not ok then
return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module")
end
return m, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function writeName(w: Bytes.Writer, s: string, n: number)
local t = string.sub(s or "", 1, n)
w:string(t)
w:fill(0, n - #t)
end
-- encode(module) -> MOD bytes. The module must be "mod", or an "xm" module whose instruments each map every note to
-- one sample; patterns must have 64 rows, at most 31 samples, effects 0..F.
function Mod.encode(m: any, _opts: EncodeOptions?): (buffer?, Err.Err?)
local ok, verr = Tracker.validate(m)
if not ok then
return nil, verr
end
if m.format ~= "mod" and m.format ~= "xm" then
return nil, Err.new(Err.UNSUPPORTED, "only mod and xm modules can be written as MOD (got " .. tostring(m.format) .. "); xm is the closest writable format")
end
local nch = m.channels
if nch > 32 then
return nil, Err.new(Err.ARG, "MOD holds at most 32 channels")
end
-- the sample for each instrument number
local smpOf: { any } = {}
if m.format == "xm" then
for i, ins in m.instruments do
local first = 0
for n = 1, 120 do
local s = ins.sampleMap[n]
if s ~= 0 then
if first ~= 0 and s ~= first then
return nil, Err.new(Err.ARG, "instrument " .. i .. " uses several samples")
end
first = s
end
end
smpOf[i] = m.samples[first] or Tracker.newSample(ins.name)
end
else
for i, s in m.samples do
smpOf[i] = s
end
end
if #smpOf > 31 then
return nil, Err.new(Err.ARG, "MOD holds at most 31 samples")
end
local order: { number } = {}
for _, o in m.order do
if o == 255 then
break
elseif o ~= 254 then
table.insert(order, o)
end
end
if #order == 0 or #order > 128 then
return nil, Err.new(Err.ARG, "MOD needs 1..128 order entries")
end
local npat = #m.patterns
if npat > 100 then
return nil, Err.new(Err.ARG, "too many patterns for MOD")
end
for p, pat in m.patterns do
if pat.rows ~= 64 then
return nil, Err.new(Err.ARG, "pattern " .. (p - 1) .. " has " .. pat.rows .. " rows (MOD patterns have 64)")
end
end
local w = Bytes.writer(1084 + npat * 64 * nch * 4 + 65536)
writeName(w, m.title or "", 20)
local datas: { buffer } = {}
for i = 1, 31 do
local s = smpOf[i]
if s then
local len = math.min(s.length, 131070)
local pcm = Pcm.encode(s.data, len, { bits = 8, signed = true, channels = 1 })
if s.channels == 2 then
-- mix stereo samples down
local mono = buffer.create(len * 4)
for k = 0, len - 1 do
buffer.writef32(mono, k * 4, (buffer.readf32(s.data, k * 8) + buffer.readf32(s.data, k * 8 + 4)) / 2)
end
pcm = Pcm.encode(mono, len, { bits = 8, signed = true })
end
local even = len + len % 2
local padded = buffer.create(even)
buffer.copy(padded, 0, pcm, 0, len)
datas[i] = padded
writeName(w, s.name or "", 22)
w:u16be(even // 2)
local ft = math.clamp(math.floor((s.finetune or 0) / 16 + 0.5), -8, 7)
w:u8(ft % 16)
w:u8(math.clamp(math.floor(s.volume), 0, 64))
if s.loopType > 0 and s.loopEnd <= even then
w:u16be(s.loopStart // 2)
w:u16be(math.max(1, (s.loopEnd - s.loopStart) // 2))
else
w:u16be(0)
w:u16be(1)
end
else
w:fill(0, 22)
w:u16be(0)
w:u8(0)
w:u8(0)
w:u16be(0)
w:u16be(1)
end
end
w:u8(#order)
w:u8(if m.restart < #order and m.restart > 0 then m.restart else 127)
for i = 1, 128 do
w:u8(order[i] or 0)
end
local sig
if nch == 4 then
sig = if npat > 64 then "M!K!" else "M.K."
elseif nch < 10 then
sig = nch .. "CHN"
else
sig = nch .. "CH"
end
w:string(sig)
for p = 1, npat do
local d = m.patterns[p].data
for i = 0, 64 * nch - 1 do
local q = i * 5
local note, ins, fx, param = buffer.readu8(d, q), buffer.readu8(d, q + 1), buffer.readu8(d, q + 3), buffer.readu8(d, q + 4)
local period = if note >= 1 and note <= 120 then Tables.noteToPeriod(note) else 0
if period > 4095 then
period = 0
end
if fx > 15 then
fx, param = 0, 0
end
if ins > 31 then
ins = 0
end
w:u8((ins // 16) * 16 + period // 256)
w:u8(period % 256)
w:u8((ins % 16) * 16 + fx)
w:u8(param)
end
end
for i = 1, 31 do
if datas[i] then
w:bytes(datas[i])
end
end
return w:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions)
function Mod.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
local m, err = Mod.decode(r, opts)
if not m then
return nil, err
end
return Tracker.render(m, opts)
end
return Mod
+241
View File
@@ -0,0 +1,241 @@
--!strict
-- music/s3m: Scream Tracker 3 modules (SCRM, ST3 TECH.DOC; also files from Impulse Tracker / OpenMPT / Schism
-- Tracker). Reads into the codecs/Tracker Module and plays through its engine (Module:render() / open() -> an audio
-- Decoder). Supports: up to 32 PCM channels, 8 / 16-bit signed or unsigned, mono or stereo samples, loops, the panning
-- table, ST3.00 fast volume slides, every ST3 effect. Notes are stored one octave up (S3M C-4 = note 61 = the C5
-- speed reference, as IT shows S3M files).
-- Not supported: AdLib (OPL) instruments and channels (read as silent), writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Tracker = require("@formats/codecs/Tracker")
-- ------------------------------------------------------------------------------------------------ contract
local S3m = {
name = "s3m",
category = "music",
extensions = { "s3m" },
mime = { "audio/s3m", "audio/x-s3m" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" },
caps = { decode = true, encode = false, render = true, channels = { 1, 32 } },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28)
}
-- ------------------------------------------------------------------------------------------------ sniff
function S3m.sniff(r: Bytes.Reader): number
if r:size() >= 48 and r:peek(4, 44) == "SCRM" then
return 1
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function S3m.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local maxBytes = opts and opts.maxBytes or 2 ^ 28
if r:size() < 96 then
return nil, Err.new(Err.TRUNCATED, "header")
end
if r:peek(4, 44) ~= "SCRM" then
return nil, Err.new(Err.CORRUPT, "no SCRM signature")
end
local title = r:fixed(28)
r:seek(32)
local ordnum, insnum, patnum = r:u16le(), r:u16le(), r:u16le()
local flags, cwt, ffi = r:u16le(), r:u16le(), r:u16le()
r:seek(48)
local gv, speed, tempo, mv, _uc, dp = r:u8(), r:u8(), r:u8(), r:u8(), r:u8(), r:u8()
r:seek(64)
local chnset: { number } = {}
for i = 1, 32 do
chnset[i] = r:u8()
end
if r.err then
return nil, r.err
end
if ordnum > 256 or insnum > 256 or patnum > 256 then
return nil, Err.new(Err.CORRUPT, "bad header counts")
end
-- channels: enabled PCM channels (0..15); the count is the last used one
local nch = 0
for i = 1, 32 do
local c = chnset[i]
if c < 16 then
nch = i
end
end
if nch == 0 then
return nil, Err.new(Err.UNSUPPORTED, "no PCM channels (AdLib only)")
end
local m = Tracker.newModule("s3m", nch)
m.title = title
m.speed = if speed > 0 and speed < 255 then speed else 6
m.tempo = if tempo >= 33 then tempo else 125
m.globalVolume = math.min(gv, 64) * 2
m.mixVolume = math.max(mv % 128, 16)
if mv < 128 then
-- mono files play at 8 / 11 of the master volume (ST3's stereo boost is missing; OpenMPT does the same)
m.mixVolume = math.floor(m.mixVolume * 8 / 11 + 0.5)
end
m.linear = false
m.instrumentMode = false
m.flags.fastSlides = cwt == 0x1300 or bit32.band(flags, 64) ~= 0
m.flags.amigaLimits = bit32.band(flags, 16) ~= 0
m.meta.source = { format = "s3m", tracker = cwt, stereo = mv >= 128 }
-- orders, parapointers, panning
r:seek(96)
for i = 1, ordnum do
local o = r:u8()
table.insert(m.order, o)
end
local insPtr, patPtr = {}, {}
for i = 1, insnum do
insPtr[i] = r:u16le() * 16
end
for i = 1, patnum do
patPtr[i] = r:u16le() * 16
end
local pans: { number } = {}
if dp == 252 then
for i = 1, 32 do
pans[i] = r:u8()
end
end
if r.err then
return nil, r.err
end
-- drop trailing end markers; keep inner "+++" / "---"
while #m.order > 0 and m.order[#m.order] == 255 do
table.remove(m.order)
end
local stereo = mv >= 128
for i = 1, nch do
local c = chnset[i]
local pan = 128
if stereo then
pan = if c % 16 >= 8 then 0xCC else 0x33
local p = pans[i]
if p and bit32.band(p, 0x20) ~= 0 then
pan = (p % 16) * 0x11
end
end
m.channelPan[i] = pan
m.channelMute[i] = c >= 16
end
-- samples
local total = 0
local unsigned = ffi ~= 1
for i = 1, insnum do
local s = Tracker.newSample()
m.samples[i] = s
local h = r:sub(insPtr[i], 80)
if h:size() < 80 then
return nil, Err.new(Err.TRUNCATED, "sample header " .. i, insPtr[i])
end
local typ = h:u8()
h:skip(12)
local hi = h:u8()
local lo = h:u16le()
local len, ls, le = h:u32le(), h:u32le(), h:u32le()
local vol = h:u8()
h:skip(1)
local pack, sflags = h:u8(), h:u8()
local c2spd = h:u32le()
h:seek(48)
s.name = h:fixed(28)
s.volume = math.min(vol, 64)
s.c5speed = if c2spd > 0 then c2spd else 8363
if typ == 1 and len > 0 and pack == 0 then
local bits = if bit32.band(sflags, 4) ~= 0 then 16 else 8
local nchs = if bit32.band(sflags, 2) ~= 0 then 2 else 1
local off = (hi * 65536 + lo) * 16
len = math.min(len, 2 ^ 26)
-- a short file: keep what is there
local avail = math.max(0, r:size() - off) // (nchs * bits // 8)
len = math.min(len, avail)
total += len * nchs * 4
if total > maxBytes then
return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit")
end
local data = Tracker.Pcm.decode(r.buf, r.base + off, len, { bits = bits, signed = not unsigned, channels = nchs, planar = true })
if data then
s.data, s.length, s.bits, s.channels = data, len, bits, nchs
if bit32.band(sflags, 1) ~= 0 and le > ls then
s.loopStart, s.loopEnd, s.loopType = ls, math.min(le, len), 1
end
end
end
end
-- patterns
for p = 1, patnum do
local pat = Tracker.newPattern(64, nch)
m.patterns[p] = pat
local ptr = patPtr[p]
if ptr > 0 then
local pr = r:sub(ptr)
local plen = pr:u16le()
pr = pr:sub(2, math.max(0, plen - 2))
local d = pat.data
local row = 0
while row < 64 and not pr:eof() do
local what = pr:u8()
if what == 0 then
row += 1
else
local ch = what % 32
local note, ins, vol, cmd, info = 0, 0, 0, 0, 0
if bit32.band(what, 0x20) ~= 0 then
local nb = pr:u8()
ins = pr:u8()
if nb == 254 then
note = 254
elseif nb < 254 and nb % 16 < 12 then
note = (nb // 16) * 12 + nb % 16 + 13
if note > 120 then
note = 0
end
end
end
if bit32.band(what, 0x40) ~= 0 then
vol = math.min(pr:u8(), 64) + 1
end
if bit32.band(what, 0x80) ~= 0 then
cmd, info = pr:u8(), pr:u8()
if cmd > 26 then
cmd, info = 0, 0
end
end
if ch < nch then
local o = (row * nch + ch) * 5
buffer.writeu8(d, o, note)
buffer.writeu8(d, o + 1, ins)
buffer.writeu8(d, o + 2, vol)
buffer.writeu8(d, o + 3, cmd)
buffer.writeu8(d, o + 4, info)
end
end
end
end
end
local ok, verr = Tracker.validate(m)
if not ok then
return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module")
end
return m, nil
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions)
function S3m.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
local m, err = S3m.decode(r, opts)
if not m then
return nil, err
end
return Tracker.render(m, opts)
end
return S3m
+44
View File
@@ -0,0 +1,44 @@
--!strict
-- music/sf2: SoundFont 2 banks (SoundFont 2.04 specification), read-only. A thin wrapper over codecs/SoundFont (the
-- parser and the TinySoundFont-port synth music/midi renders with). Supports: INFO, 16-bit samples (+ sm24 24-bit),
-- presets / instruments / sample headers with global zones, generator merging into playable regions.
-- Not supported: writing, SF3 (Ogg Vorbis samples), modulators (read past, not applied).
-- decode returns the SoundFont value (kind "soundfont"): pass it to music/midi render as opts.soundfont.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local SoundFont = require("@formats/codecs/SoundFont")
-- ------------------------------------------------------------------------------------------------ contract
local Sf2 = {
name = "sf2",
category = "music",
extensions = { "sf2" },
mime = { "audio/x-soundfont" },
deps = { "core/Err", "core/Bytes", "codecs/SoundFont" },
caps = { decode = true, encode = false, sm24 = true, sf3 = false },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxRegions: number?, -- default 10^6
maxSamples: number?, -- default 2^28
}
-- ------------------------------------------------------------------------------------------------ sniff
function Sf2.sniff(r: Bytes.Reader): number
return if SoundFont.sniff(r) then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Sf2.decode(r: Bytes.Reader, opts: DecodeOptions?): (SoundFont.SoundFont?, Err.Err?)
return SoundFont.parse(r, opts)
end
-- ------------------------------------------------------------------------------------------------ extras
-- synth(sf?, sampleRate?, opts?) -> a synth State (codecs/SoundFont.Synth drives it)
Sf2.synth = SoundFont.synth
Sf2.fallback = SoundFont.fallback
return Sf2
+560
View File
@@ -0,0 +1,560 @@
--!strict
-- music/xm: FastTracker 2 Extended Modules (XM 1.04, the "Extended Module: " format; also OpenMPT / MilkyTracker /
-- Skale files). Written from the XM specification and FT2 behaviour notes. Reads into the codecs/Tracker Module and
-- plays through its engine (Module:render() / open() -> an audio Decoder): up to 32 channels (more are read), 8 / 16-bit
-- delta samples, multi-sample instruments with volume / panning envelopes, fadeout and auto-vibrato, linear and Amiga
-- frequency tables, every FT2 effect and volume-column command. Writes XM from "xm" modules (byte-identical for files
-- in FT2's layout) and from "mod" modules (one instrument per sample, Amiga frequencies).
-- Not supported: ModPlug ADPCM samples (read as silence), OpenMPT's stereo-sample / extra-effect extensions on write.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Tracker = require("@formats/codecs/Tracker")
-- ------------------------------------------------------------------------------------------------ contract
local Xm = {
name = "xm",
category = "music",
extensions = { "xm" },
mime = { "audio/xm", "audio/x-xm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" },
caps = { decode = true, encode = true, render = true, channels = { 1, 64 } },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28)
}
export type EncodeOptions = {
tracker: string?, -- the tracker name field (default: the source file's, else "formats-luau")
}
-- ------------------------------------------------------------------------------------------------ constants
local MAGIC = "Extended Module: "
local Pcm = Tracker.Pcm
-- ------------------------------------------------------------------------------------------------ sniff
function Xm.sniff(r: Bytes.Reader): number
return if r:peek(17) == MAGIC then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function readEnvelope(r: Bytes.Reader): ({ number }, { number })
local xs, ys = {}, {}
for i = 1, 12 do
xs[i] = r:u16le()
ys[i] = r:u16le()
end
return xs, ys
end
local function makeEnvelope(xs: { number }, ys: { number }, n: number, typ: number, sus: number, ls: number, le: number, pan: boolean): any
local e = Tracker.newEnvelope()
n = math.min(n, 12)
for i = 1, n do
e.ticks[i] = xs[i]
e.values[i] = if pan then math.clamp(ys[i], 0, 64) - 32 else math.clamp(ys[i], 0, 64)
end
e.enabled = bit32.band(typ, 1) ~= 0 and n > 0
e.sustain = bit32.band(typ, 2) ~= 0
e.loop = bit32.band(typ, 4) ~= 0
e.susStart, e.susEnd = sus + 1, sus + 1
e.loopStart, e.loopEnd = ls + 1, le + 1
-- the raw fields, for a faithful re-save
e.raw = { type = typ, sustain = sus, loopStart = ls, loopEnd = le, count = n }
return e
end
function Xm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local maxBytes = opts and opts.maxBytes or 2 ^ 28
if r:peek(17) ~= MAGIC then
return nil, Err.new(Err.CORRUPT, "no XM signature")
end
r:skip(17)
local title = r:fixed(20)
r:skip(1)
local tracker = r:fixed(20)
local version = r:u16le()
local hdrStart = r:tell()
local hdrSize = r:u32le()
local songLen, restart, nch, npat, nins = r:u16le(), r:u16le(), r:u16le(), r:u16le(), r:u16le()
local flags, speed, bpm = r:u16le(), r:u16le(), r:u16le()
local orders = {}
for i = 1, 256 do
orders[i] = r:u8()
end
if r.err then
return nil, r.err
end
if nch < 1 or nch > 128 or npat > 256 or nins > 256 or songLen > 256 then
return nil, Err.new(Err.CORRUPT, "bad header counts")
end
if version < 0x0104 then
return nil, Err.new(Err.UNSUPPORTED, string.format("XM version %x (only 1.04 is supported)", version))
end
local m = Tracker.newModule("xm", nch)
m.title = title
m.speed = if speed > 0 and speed < 256 then speed else 6
m.tempo = if bpm >= 32 and bpm <= 999 then bpm else 125
m.linear = bit32.band(flags, 1) ~= 0
m.restart = restart
for i = 1, songLen do
m.order[i] = orders[i]
end
m.meta.tracker = tracker
m.meta.source = { format = "xm", tracker = tracker, version = version }
-- patterns
if not r:seek(hdrStart + hdrSize) then
return nil, r.err
end
for p = 1, npat do
local start = r:tell()
local plen = r:u32le()
r:u8()
local rows = r:u16le()
local psize = r:u16le()
if r.err then
return nil, r.err
end
if rows < 1 or rows > 256 then
return nil, Err.new(Err.CORRUPT, "pattern " .. (p - 1) .. " has " .. rows .. " rows", r.pos)
end
r:seek(start + plen)
local pat = Tracker.newPattern(rows, nch)
m.patterns[p] = pat
local pr = r:slice(psize)
if r.err then
return nil, r.err
end
local d = pat.data
if psize > 0 then
for i = 0, rows * nch - 1 do
local b = pr:u8()
local note, ins, vol, fx, param = 0, 0, 0, 0, 0
if b >= 128 then
if bit32.band(b, 1) ~= 0 then
note = pr:u8()
end
if bit32.band(b, 2) ~= 0 then
ins = pr:u8()
end
if bit32.band(b, 4) ~= 0 then
vol = pr:u8()
end
if bit32.band(b, 8) ~= 0 then
fx = pr:u8()
end
if bit32.band(b, 16) ~= 0 then
param = pr:u8()
end
else
note, ins, vol, fx, param = b, pr:u8(), pr:u8(), pr:u8(), pr:u8()
end
if pr.err then
break -- a short pattern: the rest stays empty
end
if note == 97 then
note = 255
elseif note > 96 then
note = 0
end
if fx > 35 then
fx, param = 0, 0
end
local o = i * 5
buffer.writeu8(d, o, note)
buffer.writeu8(d, o + 1, ins)
buffer.writeu8(d, o + 2, vol)
buffer.writeu8(d, o + 3, fx)
buffer.writeu8(d, o + 4, param)
end
end
end
-- instruments and their samples
local total = 0
for i = 1, nins do
local start = r:tell()
local isize = r:u32le()
local ins = Tracker.newInstrument(r:fixed(22))
r:u8()
local ns = r:u16le()
if r.err then
-- a file cut inside the instruments: keep what was read
r.err = nil
break
end
m.instruments[i] = ins
ins.samples = {}
if ns == 0 then
r:seek(start + math.max(isize, 29))
continue
end
if ns > 256 then
return nil, Err.new(Err.CORRUPT, "instrument " .. i .. " has " .. ns .. " samples")
end
local shSize = r:u32le()
local keymap = {}
for n = 1, 96 do
keymap[n] = r:u8()
end
local vx, vy = readEnvelope(r)
local px, py = readEnvelope(r)
local nv, np = r:u8(), r:u8()
local vs, vls, vle, ps, pls, ple = r:u8(), r:u8(), r:u8(), r:u8(), r:u8(), r:u8()
local vt, pt = r:u8(), r:u8()
ins.vibType, ins.vibSweep, ins.vibDepth, ins.vibRate = r:u8(), r:u8(), r:u8(), r:u8()
ins.fadeout = r:u16le()
if r.err then
return nil, r.err
end
ins.volEnv = makeEnvelope(vx, vy, nv, vt, vs, vls, vle, false)
ins.panEnv = makeEnvelope(px, py, np, pt, ps, pls, ple, true)
ins.headerSize = isize
r:seek(start + isize)
local base = #m.samples
local heads = {}
for k = 1, ns do
local hs = r:tell()
local len, ls, ll = r:u32le(), r:u32le(), r:u32le()
local vol, ft, typ, pan, rel, res = r:u8(), r:i8(), r:u8(), r:u8(), r:i8(), r:u8()
local nm = r:fixed(22)
r:seek(hs + math.max(shSize, 40))
heads[k] = { len = len, ls = ls, ll = ll, vol = vol, ft = ft, typ = typ, pan = pan, rel = rel, res = res, name = nm }
end
if r.err then
return nil, r.err
end
for k = 1, ns do
local h = heads[k]
local s = Tracker.newSample(h.name)
local bits = if bit32.band(h.typ, 16) ~= 0 then 16 else 8
local bps = bits // 8
s.bits = bits
s.volume = math.min(h.vol, 64)
s.finetune = h.ft
s.relativeNote = h.rel
s.pan = h.pan
local frames = h.len // bps
if h.res == 0xAD then
-- ModPlug ADPCM: 16-byte table + 4 bits per sample (not decoded: silence of the right length)
local bytes = 16 + (h.len + 1) // 2
r:skip(math.min(bytes, r:remaining()))
frames = h.len
s.data = buffer.create(frames * 4)
else
local avail = r:remaining() // bps
local got = math.min(frames, avail)
total += got * 4
if total > maxBytes then
return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit")
end
local data = Pcm.decode(r.buf, r.pos, got, { bits = bits, signed = true, delta = true })
r:skip(got * bps)
s.data = data or buffer.create(0)
frames = if data then got else 0
end
s.length = frames
local lt = h.typ % 4
if lt == 3 then
lt = 2
end
if lt > 0 and h.ll > 0 then
s.loopStart = h.ls // bps
s.loopEnd = (h.ls + h.ll) // bps
s.loopType = lt
end
m.samples[base + k] = s
table.insert(ins.samples, base + k)
end
for n = 1, 120 do
local k = keymap[math.min(n, 96)]
ins.sampleMap[n] = if n <= 96 and k < ns then base + k + 1 else 0
end
ins.keymap = keymap
end
local ok, verr = Tracker.validate(m)
if not ok then
return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module")
end
return m, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function writeName(w: Bytes.Writer, s: string?, n: number)
local t = string.sub(s or "", 1, n)
w:string(t)
w:fill(0, n - #t)
end
-- the instruments to write: { name, samples = { sample table }, keymap = { 96 local indexes }, ins? }
local function instrumentsOf(m: any): ({ any }?, string?)
local out = {}
if m.format == "mod" then
for i, s in m.samples do
local km = table.create(96, 0)
out[i] = { name = s.name, samples = if s.length > 0 then { s } else {}, keymap = km, ins = nil }
end
return out
end
for i, ins in m.instruments do
local list: { number } = {}
if type(ins.samples) == "table" then
for _, g in ins.samples do
table.insert(list, g)
end
end
local index: { [number]: number } = {}
for k, g in list do
index[g] = k - 1
end
local km = table.create(96, 0)
for n = 1, 96 do
local g = ins.sampleMap[n] or 0
if g > 0 and m.samples[g] then
if index[g] == nil then
table.insert(list, g)
index[g] = #list - 1
end
km[n] = index[g]
end
end
if #list > 255 then
return nil, "instrument " .. i .. " uses more than 255 samples"
end
local smps = {}
for k, g in list do
smps[k] = m.samples[g] or Tracker.newSample()
end
out[i] = { name = ins.name, samples = smps, keymap = km, ins = ins }
end
return out
end
local function writeEnvelope(w: Bytes.Writer, e: any, pan: boolean)
local n = if e then math.min(#e.ticks, 12) else 0
for i = 1, 12 do
if i <= n then
w:u16le(math.clamp(math.floor(e.ticks[i]), 0, 65535))
w:u16le(math.clamp(math.floor(e.values[i] + (if pan then 32 else 0) + 0.5), 0, 64))
else
w:u32le(0)
end
end
end
-- envelope count, type, sustain, loop start, loop end
local function envelopeFields(e: any): (number, number, number, number, number)
if not e then
return 0, 0, 0, 0, 0
end
local n = math.min(#e.ticks, 12)
local typ = (if e.enabled then 1 else 0) + (if e.sustain then 2 else 0) + (if e.loop then 4 else 0)
local raw = e.raw
if raw and raw.type % 8 == typ then
typ = raw.type -- keep unknown bits
end
local function idx(v: number): number
return math.clamp(math.floor(v) - 1, 0, math.max(0, n - 1))
end
local sus = idx(e.susStart)
local ls, le = idx(e.loopStart), idx(e.loopEnd)
if raw and n == 0 then
sus, ls, le = raw.sustain, raw.loopStart, raw.loopEnd
end
return n, typ, sus, ls, le
end
-- encode(module, opts) -> XM bytes ("xm" or "mod" modules)
function Xm.encode(m: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local ok, verr = Tracker.validate(m)
if not ok then
return nil, verr
end
if m.format ~= "xm" and m.format ~= "mod" then
return nil, Err.new(Err.UNSUPPORTED, "only xm and mod modules can be written as XM (got " .. tostring(m.format) .. ")")
end
local nch = m.channels
if nch > 64 then
return nil, Err.new(Err.ARG, "XM holds at most 64 channels")
end
local insts, ierr = instrumentsOf(m)
if not insts then
return nil, Err.new(Err.ARG, ierr or "bad instruments")
end
if #insts > 128 then
return nil, Err.new(Err.ARG, "XM holds at most 128 instruments")
end
if #m.patterns > 256 then
return nil, Err.new(Err.ARG, "XM holds at most 256 patterns")
end
local order: { number } = {}
for _, o in m.order do
if o == 255 then
break
elseif o ~= 254 then
table.insert(order, o)
end
end
if #order > 256 then
return nil, Err.new(Err.ARG, "XM holds at most 256 order entries")
end
local w = Bytes.writer(65536)
w:string(MAGIC)
writeName(w, m.title, 20)
w:u8(0x1A)
writeName(w, opts and opts.tracker or (m.meta and m.meta.tracker) or "formats-luau", 20)
w:u16le(0x0104)
w:u32le(276)
w:u16le(#order)
w:u16le(if m.restart < #order then m.restart else 0)
w:u16le(nch)
w:u16le(#m.patterns)
w:u16le(#insts)
w:u16le(if m.linear then 1 else 0)
w:u16le(m.speed)
w:u16le(math.clamp(math.floor(m.tempo), 32, 999))
for i = 1, 256 do
w:u8(order[i] or 0)
end
-- patterns (every cell packed, as FT2-compatible writers may)
for _, pat in m.patterns do
local pk = Bytes.writer(pat.rows * nch * 2)
local d = pat.data
for i = 0, pat.rows * nch - 1 do
local o = i * 5
local note, ins, vol, fx, param = buffer.readu8(d, o), buffer.readu8(d, o + 1), buffer.readu8(d, o + 2), buffer.readu8(d, o + 3), buffer.readu8(d, o + 4)
if note == 255 then
note = 97
elseif note > 96 then
note = 0
end
if m.format == "mod" then
vol = 0
if fx > 15 then
fx, param = 0, 0
end
end
if ins > 128 then
ins = 0
end
local flags = 0x80 + (if note > 0 then 1 else 0) + (if ins > 0 then 2 else 0) + (if vol > 0 then 4 else 0) + (if fx > 0 then 8 else 0) + (if param > 0 then 16 else 0)
pk:u8(flags)
if note > 0 then
pk:u8(note)
end
if ins > 0 then
pk:u8(ins)
end
if vol > 0 then
pk:u8(vol)
end
if fx > 0 then
pk:u8(fx)
end
if param > 0 then
pk:u8(param)
end
end
local data = pk:finish()
if buffer.len(data) > 65535 then
return nil, Err.new(Err.ARG, "a pattern packs to more than 64 KB")
end
w:u32le(9)
w:u8(0)
w:u16le(pat.rows)
w:u16le(buffer.len(data))
w:bytes(data)
end
-- instruments
for _, it in insts do
local ins = it.ins
local smps = it.samples
if #smps == 0 then
w:u32le(29)
writeName(w, it.name, 22)
w:u8(0)
w:u16le(0)
continue
end
w:u32le(263)
writeName(w, it.name, 22)
w:u8(0)
w:u16le(#smps)
w:u32le(40)
for n = 1, 96 do
w:u8(it.keymap[n])
end
local ve, pe = ins and ins.volEnv, ins and ins.panEnv
writeEnvelope(w, ve, false)
writeEnvelope(w, pe, true)
local vn, vt, vs, vls, vle = envelopeFields(ve)
local pn, pt, ps, pls, ple = envelopeFields(pe)
w:u8(vn)
w:u8(pn)
w:u8(vs)
w:u8(vls)
w:u8(vle)
w:u8(ps)
w:u8(pls)
w:u8(ple)
w:u8(vt)
w:u8(pt)
w:u8(ins and ins.vibType or 0)
w:u8(ins and ins.vibSweep or 0)
w:u8(ins and ins.vibDepth or 0)
w:u8(ins and ins.vibRate or 0)
w:u16le(ins and math.clamp(ins.fadeout, 0, 0xFFF) or 0)
w:fill(0, 22)
local datas = {}
for k, s in smps do
local mono = s.data
if s.channels == 2 then
mono = buffer.create(s.length * 4)
for f = 0, s.length - 1 do
buffer.writef32(mono, f * 4, (buffer.readf32(s.data, f * 8) + buffer.readf32(s.data, f * 8 + 4)) / 2)
end
end
local bits = if s.bits == 16 then 16 else 8
local bps = bits // 8
datas[k] = Pcm.encode(mono, s.length, { bits = bits, signed = true, delta = true })
local typ = (if bits == 16 then 16 else 0)
local ls, ll = 0, 0
if s.loopType > 0 then
typ += s.loopType
ls, ll = s.loopStart * bps, (s.loopEnd - s.loopStart) * bps
end
local ft = s.finetune
local rel = s.relativeNote
if m.format == "mod" then
rel = 0
end
w:u32le(s.length * bps)
w:u32le(ls)
w:u32le(ll)
w:u8(math.clamp(math.floor(s.volume), 0, 64))
w:u8(math.clamp(math.floor(ft), -128, 127) % 256)
w:u8(typ)
w:u8(math.clamp(math.floor(s.pan or 128), 0, 255))
w:u8(math.clamp(math.floor(rel), -128, 127) % 256)
w:u8(0)
writeName(w, s.name, 22)
end
for _, dd in datas do
w:bytes(dd)
end
end
return w:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions)
function Xm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
local m, err = Xm.decode(r, opts)
if not m then
return nil, err
end
return Tracker.render(m, opts)
end
return Xm