merge ws/audio
This commit is contained in:
commit
fa98dd77c2
43 files changed
+8963
-19
No files matched your search
@@ -158,6 +158,30 @@ local list: { Entry } = {
|
||||
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",
|
||||
@@ -176,8 +200,8 @@ local list: { Entry } = {
|
||||
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,
|
||||
@@ -200,8 +224,8 @@ local list: { Entry } = {
|
||||
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,
|
||||
@@ -218,6 +242,30 @@ local list: { Entry } = {
|
||||
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",
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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?)
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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 }
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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,
|
||||
})
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
Reference in new issue
Block a user