merge ws/audio2
This commit is contained in:
commit
f0a23eb676
149 files changed
+23004
-312
No files matched your search
+293
-5
@@ -290,18 +290,66 @@ local list: { Entry } = {
|
||||
return require("@formats/audio/aac")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "ac3",
|
||||
category = "audio",
|
||||
path = "audio/ac3",
|
||||
extensions = { "ac3", "a52" },
|
||||
mime = { "audio/ac3", "audio/x-ac3" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Ac3" },
|
||||
caps = { decode = true, encode = false, codecs = { "ac3" }, channels = 6, streaming = true, lossy = true },
|
||||
load = function()
|
||||
return require("@formats/audio/ac3")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "adpcm",
|
||||
category = "audio",
|
||||
path = "audio/adpcm",
|
||||
extensions = { "adpcm", "ima" },
|
||||
mime = { "audio/x-adpcm" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" },
|
||||
caps = { decode = true, encode = true, streaming = true, lossy = true, headerless = true, codecs = { "ima", "ima_wav", "ms", "ima_qt", "psx" } },
|
||||
load = function()
|
||||
return require("@formats/audio/adpcm")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "adx",
|
||||
category = "audio",
|
||||
path = "audio/adx",
|
||||
extensions = { "adx" },
|
||||
mime = { "audio/x-adx" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" },
|
||||
caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 8 },
|
||||
load = function()
|
||||
return require("@formats/audio/adx")
|
||||
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/audio/Pcm", "containers/Chunks" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder", "containers/Chunks" },
|
||||
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false },
|
||||
load = function()
|
||||
return require("@formats/audio/aiff")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "ape",
|
||||
category = "audio",
|
||||
path = "audio/ape",
|
||||
extensions = { "ape" },
|
||||
mime = { "audio/ape", "audio/x-ape", "audio/x-monkeys-audio" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Ape" },
|
||||
caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, float = true, depths = { 8, 16, 24, 32 } },
|
||||
load = function()
|
||||
return require("@formats/audio/ape")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "au",
|
||||
category = "audio",
|
||||
@@ -314,13 +362,25 @@ local list: { Entry } = {
|
||||
return require("@formats/audio/au")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "brstm",
|
||||
category = "audio",
|
||||
path = "audio/brstm",
|
||||
extensions = { "brstm", "bcstm", "bfstm" },
|
||||
mime = { "audio/x-brstm" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder" },
|
||||
caps = { decode = true, encode = false, streaming = true, lossy = true, loops = true, containers = { "RSTM", "CSTM", "FSTM" } },
|
||||
load = function()
|
||||
return require("@formats/audio/brstm")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "caf",
|
||||
category = "audio",
|
||||
path = "audio/caf",
|
||||
extensions = { "caf", "caff" },
|
||||
mime = { "audio/x-caf" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream", "containers/Chunks" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Adpcm/Decoder", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream", "containers/Chunks" },
|
||||
caps = { decode = true, encode = true, codecs = { "pcm", "alac", "aac", "ulaw", "alaw" }, encodeCodecs = { "pcm", "alac" }, tags = true, streaming = true },
|
||||
load = function()
|
||||
return require("@formats/audio/caf")
|
||||
@@ -362,6 +422,18 @@ local list: { Entry } = {
|
||||
return require("@formats/audio/mp3")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "mpc",
|
||||
category = "audio",
|
||||
path = "audio/mpc",
|
||||
extensions = { "mpc", "mp+", "mpp" },
|
||||
mime = { "audio/x-musepack", "audio/musepack" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Musepack" },
|
||||
caps = { decode = true, encode = false, codecs = { "musepack" }, versions = { 7, 8 }, streaming = true, lossy = true },
|
||||
load = function()
|
||||
return require("@formats/audio/mpc")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "opus",
|
||||
category = "audio",
|
||||
@@ -374,6 +446,42 @@ local list: { Entry } = {
|
||||
return require("@formats/audio/opus")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "qoa",
|
||||
category = "audio",
|
||||
path = "audio/qoa",
|
||||
extensions = { "qoa" },
|
||||
mime = { "audio/qoa" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Qoa" },
|
||||
caps = { decode = true, encode = true, streaming = true, lossy = true, seek = true, channels = 8 },
|
||||
load = function()
|
||||
return require("@formats/audio/qoa")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "tta",
|
||||
category = "audio",
|
||||
path = "audio/tta",
|
||||
extensions = { "tta" },
|
||||
mime = { "audio/x-tta", "audio/tta" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Tta" },
|
||||
caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, depths = { 8, 16, 24 } },
|
||||
load = function()
|
||||
return require("@formats/audio/tta")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "vag",
|
||||
category = "audio",
|
||||
path = "audio/vag",
|
||||
extensions = { "vag" },
|
||||
mime = { "audio/x-vag" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" },
|
||||
caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 2 },
|
||||
load = function()
|
||||
return require("@formats/audio/vag")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "voc",
|
||||
category = "audio",
|
||||
@@ -404,12 +512,24 @@ local list: { Entry } = {
|
||||
path = "audio/wav",
|
||||
extensions = { "wav", "wave", "rf64", "bw64" },
|
||||
mime = { "audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/audio/Pcm" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/audio/Pcm", "codecs/audio/Adpcm" },
|
||||
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true },
|
||||
load = function()
|
||||
return require("@formats/audio/wav")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "wavpack",
|
||||
category = "audio",
|
||||
path = "audio/wavpack",
|
||||
extensions = { "wv" },
|
||||
mime = { "audio/x-wavpack", "audio/wavpack" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/WavPack" },
|
||||
caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, hybrid = true, float = true, depths = { 8, 12, 16, 20, 24, 32 } },
|
||||
load = function()
|
||||
return require("@formats/audio/wavpack")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "avi",
|
||||
category = "video",
|
||||
@@ -1238,6 +1358,66 @@ local list: { Entry } = {
|
||||
return require("@formats/subtitle/vtt")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "669",
|
||||
category = "music",
|
||||
path = "music/669",
|
||||
extensions = { "669" },
|
||||
mime = { "audio/x-669" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
|
||||
caps = { decode = true, encode = false, render = true, channels = { 8, 8 } },
|
||||
load = function()
|
||||
return require("@formats/music/669")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "ahx",
|
||||
category = "music",
|
||||
path = "music/ahx",
|
||||
extensions = { "ahx", "thx" },
|
||||
mime = { "audio/x-ahx" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Hively" },
|
||||
caps = { decode = true, encode = false, render = true, channels = { 4, 4 }, subsongs = true },
|
||||
load = function()
|
||||
return require("@formats/music/ahx")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "far",
|
||||
category = "music",
|
||||
path = "music/far",
|
||||
extensions = { "far" },
|
||||
mime = { "audio/x-far" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
|
||||
caps = { decode = true, encode = false, render = true, channels = { 16, 16 } },
|
||||
load = function()
|
||||
return require("@formats/music/far")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "hmp",
|
||||
category = "music",
|
||||
path = "music/hmp",
|
||||
extensions = { "hmp", "hmi" },
|
||||
mime = { "audio/x-hmp" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/MidiRender" },
|
||||
caps = { decode = true, encode = false, render = true, hmi = true },
|
||||
load = function()
|
||||
return require("@formats/music/hmp")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "hvl",
|
||||
category = "music",
|
||||
path = "music/hvl",
|
||||
extensions = { "hvl" },
|
||||
mime = { "audio/x-hvl" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Hively" },
|
||||
caps = { decode = true, encode = false, render = true, channels = { 4, 16 }, subsongs = true },
|
||||
load = function()
|
||||
return require("@formats/music/hvl")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "it",
|
||||
category = "music",
|
||||
@@ -1250,13 +1430,25 @@ local list: { Entry } = {
|
||||
return require("@formats/music/it")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "med",
|
||||
category = "music",
|
||||
path = "music/med",
|
||||
extensions = { "med", "mmd0", "mmd1", "mmd2", "mmd3", "omed" },
|
||||
mime = { "audio/x-med" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
|
||||
caps = { decode = true, encode = false, render = true, channels = { 1, 64 } },
|
||||
load = function()
|
||||
return require("@formats/music/med")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "midi",
|
||||
category = "music",
|
||||
path = "music/midi",
|
||||
extensions = { "mid", "midi", "smf", "kar", "rmi" },
|
||||
mime = { "audio/midi", "audio/x-midi" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/audio/SoundFont", "Types" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/audio/MidiRender", "Types" },
|
||||
caps = { decode = true, encode = true, formats = { 0, 1, 2 }, render = true, streaming = true, rmid = true },
|
||||
load = function()
|
||||
return require("@formats/music/midi")
|
||||
@@ -1274,6 +1466,54 @@ local list: { Entry } = {
|
||||
return require("@formats/music/mod")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "mtm",
|
||||
category = "music",
|
||||
path = "music/mtm",
|
||||
extensions = { "mtm" },
|
||||
mime = { "audio/x-mtm" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
|
||||
caps = { decode = true, encode = false, render = true, channels = { 1, 32 } },
|
||||
load = function()
|
||||
return require("@formats/music/mtm")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "mus",
|
||||
category = "music",
|
||||
path = "music/mus",
|
||||
extensions = { "mus" },
|
||||
mime = { "audio/x-mus" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/MidiRender" },
|
||||
caps = { decode = true, encode = false, render = true },
|
||||
load = function()
|
||||
return require("@formats/music/mus")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "okt",
|
||||
category = "music",
|
||||
path = "music/okt",
|
||||
extensions = { "okt", "okta" },
|
||||
mime = { "audio/x-okt" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
|
||||
caps = { decode = true, encode = false, render = true, channels = { 4, 8 } },
|
||||
load = function()
|
||||
return require("@formats/music/okt")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "ptm",
|
||||
category = "music",
|
||||
path = "music/ptm",
|
||||
extensions = { "ptm" },
|
||||
mime = { "audio/x-ptm" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
|
||||
caps = { decode = true, encode = false, render = true, channels = { 1, 32 } },
|
||||
load = function()
|
||||
return require("@formats/music/ptm")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "s3m",
|
||||
category = "music",
|
||||
@@ -1298,18 +1538,66 @@ local list: { Entry } = {
|
||||
return require("@formats/music/sf2")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "stm",
|
||||
category = "music",
|
||||
path = "music/stm",
|
||||
extensions = { "stm" },
|
||||
mime = { "audio/x-stm" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
|
||||
caps = { decode = true, encode = false, render = true, channels = { 4, 4 } },
|
||||
load = function()
|
||||
return require("@formats/music/stm")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "ult",
|
||||
category = "music",
|
||||
path = "music/ult",
|
||||
extensions = { "ult" },
|
||||
mime = { "audio/x-ult" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
|
||||
caps = { decode = true, encode = false, render = true, channels = { 1, 32 } },
|
||||
load = function()
|
||||
return require("@formats/music/ult")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "umx",
|
||||
category = "music",
|
||||
path = "music/umx",
|
||||
extensions = { "umx" },
|
||||
mime = { "audio/x-umx" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" },
|
||||
caps = { decode = true, encode = false, render = true, container = true },
|
||||
load = function()
|
||||
return require("@formats/music/umx")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "xm",
|
||||
category = "music",
|
||||
path = "music/xm",
|
||||
extensions = { "xm" },
|
||||
mime = { "audio/xm", "audio/x-xm" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Adpcm" },
|
||||
caps = { decode = true, encode = true, render = true, channels = { 1, 64 } },
|
||||
load = function()
|
||||
return require("@formats/music/xm")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "xmi",
|
||||
category = "music",
|
||||
path = "music/xmi",
|
||||
extensions = { "xmi", "xmidi" },
|
||||
mime = { "audio/x-xmidi" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/audio/MidiRender" },
|
||||
caps = { decode = true, encode = false, render = true, songs = true },
|
||||
load = function()
|
||||
return require("@formats/music/xmi")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "m3u",
|
||||
category = "playlist",
|
||||
|
||||
@@ -138,7 +138,7 @@ Types.Audio = Audio
|
||||
export type Module = {
|
||||
kind: "music",
|
||||
title: string,
|
||||
format: string, -- "mod", "s3m", "xm", "it", "mid"
|
||||
format: string, -- "mod", "s3m", "xm", "it" (codecs/audio/Tracker); "ahx", "hvl" (codecs/audio/Hively, own render)
|
||||
channels: number,
|
||||
patterns: { any },
|
||||
order: { number },
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
--!strict
|
||||
-- audio/ac3: raw AC-3 (Dolby Digital, ATSC A/52) elementary streams, the .ac3 files of DVD / broadcast rips, through
|
||||
-- codecs/audio/Ac3 (written from the A/52 specification). Supports: every channel layout (1+1, 1/0 .. 3/2, LFE)
|
||||
-- output in WAVE order without downmixing, 32 / 44.1 / 48 kHz, every bit rate, coupling, rematrixing, block
|
||||
-- switching, delta bit allocation, the CRC check, resync over garbage, a truncated last frame (dropped), streaming and
|
||||
-- exact seeking (one frame of pre-roll for the overlap). Dynamic range control is off by default (`drc` = 0 .. 1).
|
||||
-- Not supported: writing, E-AC-3 / Dolby Digital Plus (UNSUPPORTED), bsid 9 / 10 reduced-rate streams.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Pcm = require("@formats/codecs/audio/Pcm")
|
||||
local Stream = require("@formats/codecs/audio/Stream")
|
||||
local Ac3 = require("@formats/codecs/audio/Ac3")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Ac3Format = {
|
||||
name = "ac3",
|
||||
category = "audio",
|
||||
extensions = { "ac3", "a52" },
|
||||
mime = { "audio/ac3", "audio/x-ac3" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Ac3" },
|
||||
caps = { decode = true, encode = false, codecs = { "ac3" }, channels = 6, streaming = true, lossy = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxFrames: number?, -- refuse streams with more syncframes (default 2^22)
|
||||
drc: number?, -- dynamic range control scale: 0 = off (default), 1 = full
|
||||
crc: boolean?, -- check every syncframe's CRC (default true; a bad frame ends the stream with Err.CHECKSUM)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
-- (E-AC-3 streams sniff too, so loading one says UNSUPPORTED instead of an unknown format)
|
||||
function Ac3Format.sniff(r: Bytes.Reader): number
|
||||
local b, p, limit = r.buf, r.pos, r.limit
|
||||
local h = Ac3.header(b, p, limit)
|
||||
if not h then
|
||||
return 0
|
||||
end
|
||||
local h2 = Ac3.header(b, p + h.frameSize, limit)
|
||||
if h2 and h2.sampleRate == h.sampleRate then
|
||||
return 0.9
|
||||
end
|
||||
return if p + h.frameSize >= limit then 0.6 else 0.3
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- the syncframe index (resyncing over garbage: a header counts when the next one follows it, or the data ends)
|
||||
local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number }, Ac3.Header?, Err.Err?)
|
||||
local b, limit = r.buf, r.limit
|
||||
local p = r.base
|
||||
local offs, sizes = {}, {}
|
||||
local first: Ac3.Header? = nil
|
||||
while p + 8 <= limit do
|
||||
local h = Ac3.header(b, p, limit)
|
||||
if h and first and (h.sampleRate ~= first.sampleRate or h.bsid > 10) then
|
||||
h = nil
|
||||
end
|
||||
if h and not first and p + h.frameSize + 8 <= limit then
|
||||
local h2 = Ac3.header(b, p + h.frameSize, limit)
|
||||
if not h2 then
|
||||
h = nil -- a false sync word
|
||||
end
|
||||
end
|
||||
if not h then
|
||||
p += 1
|
||||
continue
|
||||
end
|
||||
if not first then
|
||||
first = h
|
||||
if h.bsid > 10 then
|
||||
return offs, sizes, first, Err.new(Err.UNSUPPORTED, "E-AC-3 (Dolby Digital Plus)", p)
|
||||
elseif h.bsid > 8 then
|
||||
return offs, sizes, first, Err.new(Err.UNSUPPORTED, "reduced sample rate AC-3 (bsid " .. h.bsid .. ")", p)
|
||||
end
|
||||
end
|
||||
if p + h.frameSize > limit then
|
||||
break -- a truncated last frame
|
||||
end
|
||||
table.insert(offs, p)
|
||||
table.insert(sizes, h.frameSize)
|
||||
if #offs > maxFrames then
|
||||
return offs, sizes, first, Err.new(Err.LIMIT, "more than " .. maxFrames .. " frames")
|
||||
end
|
||||
p += h.frameSize
|
||||
end
|
||||
return offs, sizes, first, nil
|
||||
end
|
||||
|
||||
function Ac3Format.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local offs, sizes, first, ierr = index(r, o.maxFrames or 2 ^ 22)
|
||||
if ierr then
|
||||
return nil, ierr
|
||||
end
|
||||
if not first or #offs == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "no AC-3 syncframe", r.base)
|
||||
end
|
||||
local h = first :: Ac3.Header
|
||||
local d = Ac3.decoder({ drc = o.drc, crc = o.crc })
|
||||
local buf = r.buf
|
||||
local n = #offs
|
||||
local out = {
|
||||
sampleRate = h.sampleRate,
|
||||
channels = h.channels,
|
||||
frames = n * 1536,
|
||||
duration = n * 1536 / h.sampleRate,
|
||||
bitrate = h.bitrate,
|
||||
tags = {},
|
||||
codec = "ac3",
|
||||
acmod = h.acmod,
|
||||
lfe = h.lfeon,
|
||||
}
|
||||
return Stream.packets(out, {
|
||||
count = n,
|
||||
start = function(i: number): number
|
||||
return (i - 1) * 1536
|
||||
end,
|
||||
decode = function(i: number): (number?, Err.Err?)
|
||||
local frames, err = d:decode(buf, offs[i], sizes[i])
|
||||
if frames and d.channels ~= h.channels then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "channel layout change inside the stream", offs[i])
|
||||
end
|
||||
return frames, err
|
||||
end,
|
||||
pcm = function(): { number }
|
||||
return d.pcm
|
||||
end,
|
||||
reset = function()
|
||||
d:reset()
|
||||
end,
|
||||
preroll = 1,
|
||||
})
|
||||
end
|
||||
|
||||
function Ac3Format.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
|
||||
local dec, err = Ac3Format.open(r, opts)
|
||||
if not dec then
|
||||
return nil, err
|
||||
end
|
||||
local d: any = dec
|
||||
return Pcm.drain(d, { format = "ac3", codec = "ac3", acmod = d.acmod, lfe = d.lfe, bitrate = d.bitrate })
|
||||
end
|
||||
|
||||
return Ac3Format
|
||||
@@ -0,0 +1,155 @@
|
||||
--!strict
|
||||
-- audio/adpcm: headerless ADPCM streams (.adpcm / .ima / .vox-style dumps), over codecs/audio/Adpcm. New in
|
||||
-- formats-luau. A raw stream has no header, so nothing identifies it: sniff is always 0, F.detect only finds it by
|
||||
-- extension, and the layout comes from the options (codec, sampleRate, channels, blockAlign). vgmstream plays such
|
||||
-- files only through a .txth description and ffmpeg not at all (its adpcm_* codecs need a container), so the codecs
|
||||
-- here are the layouts those containers use:
|
||||
-- "ima" IMA nibbles from predictor 0 / step index 0, channels interleaved by nibble, the high nibble first
|
||||
-- (DVI order, as KVAG / adpcm_ima_ssi); lowFirst = true for the other order
|
||||
-- "ima_wav" Microsoft IMA blocks (the WAV / AVI data chunk), blockAlign bytes each (default 1024)
|
||||
-- "ms" Microsoft ADPCM blocks with the 7 standard coefficient pairs (default blockAlign 1024)
|
||||
-- "ima_qt" Apple ima4 packets (34 bytes per channel, 64 frames), as in AIFF-C / CAF / QuickTime
|
||||
-- "psx" Sony PS-ADPCM frames (16 bytes, 28 samples), channels interleaved every `interleave` bytes (default 16)
|
||||
-- Encode: "ima", "ima_wav" and "ms" (from an Audio or a Decoder). Not supported: raw DSP / ADX (their coefficients
|
||||
-- live in a header: see audio/brstm and audio/adx).
|
||||
--
|
||||
-- local a = Adpcm.decode(Bytes.reader(buf), { codec = "ms", sampleRate = 22050, channels = 2, blockAlign = 512 })
|
||||
-- local raw = Adpcm.encode(a, { codec = "ima" })
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Pcm = require("@formats/codecs/audio/Pcm")
|
||||
local Adpcm = require("@formats/codecs/audio/Adpcm")
|
||||
local Decoder = require("@formats/codecs/audio/Adpcm/Decoder")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Raw = {
|
||||
name = "adpcm",
|
||||
category = "audio",
|
||||
extensions = { "adpcm", "ima" },
|
||||
mime = { "audio/x-adpcm" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" },
|
||||
caps = { decode = true, encode = true, streaming = true, lossy = true, headerless = true, codecs = { "ima", "ima_wav", "ms", "ima_qt", "psx" } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type Codec = "ima" | "ima_wav" | "ms" | "ima_qt" | "psx"
|
||||
export type Options = {
|
||||
codec: Codec?, -- default "ima"
|
||||
sampleRate: number?, -- default 22050 (decode)
|
||||
channels: number?, -- default 1 (decode)
|
||||
blockAlign: number?, -- ima_wav / ms: bytes per block (default 1024 when decoding; 256 * channels when encoding)
|
||||
lowFirst: boolean?, -- ima: the low nibble first
|
||||
interleave: number?, -- psx: bytes per channel before the next channel (default 16)
|
||||
maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local CODECS = { ima = true, ima_wav = true, ms = true, ima_qt = true, psx = true }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Raw.sniff(_r: Bytes.Reader): number
|
||||
return 0 -- no header: found by extension or opts.format only
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Raw.decode(r: Bytes.Reader, opts: Options?): (Types.Audio?, Err.Err?)
|
||||
local dec, err = Raw.open(r, opts)
|
||||
if not dec then
|
||||
return nil, err
|
||||
end
|
||||
local limit = opts and opts.maxFrames or 2 ^ 28
|
||||
if dec.frames > limit or dec.frames * dec.channels > 2 ^ 28 then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", dec.frames))
|
||||
end
|
||||
return Pcm.drain(dec, { format = "adpcm", codec = (dec :: any).codec }, limit)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Raw.encode(value: any, opts: Options?): (buffer?, Err.Err?)
|
||||
local o: Options = opts or {}
|
||||
local codec = o.codec or "ima"
|
||||
if codec ~= "ima" and codec ~= "ima_wav" and codec ~= "ms" then
|
||||
return nil, Err.new(Err.ARG, "encode: codec must be ima, ima_wav or ms")
|
||||
end
|
||||
local src, serr = Pcm.source(value)
|
||||
if not src then
|
||||
return nil, serr
|
||||
end
|
||||
local a, cerr = Pcm.collect(src)
|
||||
if not a then
|
||||
return nil, cerr
|
||||
end
|
||||
local ch, n, x = a.channels, a.frames, a.samples
|
||||
if codec == "ima" then
|
||||
local out = buffer.create((n * ch + 1) // 2)
|
||||
local st = buffer.create(8 * ch)
|
||||
for c = 0, ch - 1 do
|
||||
Adpcm.imaEncode(x, c, ch, n, st, c * 8, out, 0, c, ch, not o.lowFirst)
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
local ba = o.blockAlign or 256 * ch
|
||||
local spb = Decoder.blockFrames(codec, ba, ch)
|
||||
if type(ba) ~= "number" or ba ~= math.floor(ba) or ba > 65535 or not spb or spb < 2 then
|
||||
return nil, Err.new(Err.ARG, "bad blockAlign " .. tostring(ba))
|
||||
end
|
||||
if codec == "ima_wav" and (ba % (4 * ch) ~= 0) then
|
||||
return nil, Err.new(Err.ARG, "ima_wav: blockAlign must be a multiple of 4 * channels")
|
||||
end
|
||||
local blocks = (n + spb - 1) // spb
|
||||
local out = buffer.create(blocks * ba)
|
||||
local st = buffer.create(8 * ch)
|
||||
for b = 0, blocks - 1 do
|
||||
local f0 = b * spb
|
||||
if codec == "ms" then
|
||||
Adpcm.msEncode(x, f0, n - f0, ch, spb, out, b * ba)
|
||||
else
|
||||
Adpcm.imaWavEncode(x, f0, n - f0, ch, spb, st, out, b * ba)
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
function Raw.open(r: Bytes.Reader, opts: Options?): (Types.Decoder?, Err.Err?)
|
||||
if type(r) ~= "table" or type(r.buf) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "open: expected a Reader")
|
||||
end
|
||||
local o: Options = opts or {}
|
||||
local codec = o.codec or "ima"
|
||||
local rate, ch = o.sampleRate or 22050, o.channels or 1
|
||||
if not CODECS[codec] then
|
||||
return nil, Err.new(Err.ARG, "unknown codec " .. tostring(codec))
|
||||
end
|
||||
if type(rate) ~= "number" or rate <= 0 or rate ~= rate or type(ch) ~= "number" or ch < 1 or ch > 255 or ch ~= math.floor(ch) then
|
||||
return nil, Err.new(Err.ARG, "bad sampleRate or channels")
|
||||
end
|
||||
local size = r.limit - r.base
|
||||
local dec: any = { sampleRate = rate, channels = ch, tags = {}, codec = codec, frames = 0, duration = 0 }
|
||||
local d, err
|
||||
if codec == "ima" then
|
||||
d, err = Decoder.nibbles(dec, { buf = r.buf, offset = r.base, size = size, hi = not o.lowFirst })
|
||||
elseif codec == "psx" then
|
||||
local il = o.interleave or 16
|
||||
if type(il) ~= "number" or il < 16 or il % 16 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "interleave must be a multiple of 16")
|
||||
end
|
||||
d, err = Decoder.interleaved(dec, { kind = "psx", buf = r.buf, offset = r.base, size = size, interleave = if ch == 1 then 16 else il })
|
||||
else
|
||||
local ba = o.blockAlign or 1024
|
||||
if type(ba) ~= "number" or ba < 1 or ba ~= math.floor(ba) then
|
||||
return nil, Err.new(Err.ARG, "bad blockAlign")
|
||||
end
|
||||
d, err = Decoder.blocks(dec, { kind = codec :: any, buf = r.buf, offset = r.base, size = size, blockAlign = ba })
|
||||
end
|
||||
if not d then
|
||||
return nil, err
|
||||
end
|
||||
d.bitrate = if d.duration > 0 then math.floor(size * 8 / d.duration) else 0
|
||||
return d, nil
|
||||
end
|
||||
|
||||
return Raw
|
||||
@@ -0,0 +1,237 @@
|
||||
--!strict
|
||||
-- audio/adx: CRI ADX (.adx), the game-audio ADPCM of Sega / CRI Middleware, over codecs/audio/Adpcm. New in
|
||||
-- formats-luau; the header layout and the decoder details follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt),
|
||||
-- whose output it matches bit for bit (the scale + 1 of CRI's decoders, the version 3 rounding; ffmpeg's ADX decoder
|
||||
-- differs slightly on both). Supports: encoding type 3 (the standard predictor from the header's high-pass cutoff),
|
||||
-- versions 3, 4 and 5, 1-8 channels, the initial history of version 4, loop points (dec.loop and
|
||||
-- meta.source.loop = { start, stop } in frames, stop exclusive). Encode (Audio or Decoder): version 4, 1-8 channels,
|
||||
-- loop points from opts.loop. Not supported: encrypted ADX (versions 0x0408 / 0x0409, keys needed), the fixed (2) and
|
||||
-- exponential (4) encoding types, AHX.
|
||||
--
|
||||
-- local dec = Adx.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, version, cutoff)
|
||||
-- local file = Adx.encode(audio, { loop = { start = 44100, stop = 441000 } })
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Pcm = require("@formats/codecs/audio/Pcm")
|
||||
local Adpcm = require("@formats/codecs/audio/Adpcm")
|
||||
local Decoder = require("@formats/codecs/audio/Adpcm/Decoder")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Adx = {
|
||||
name = "adx",
|
||||
category = "audio",
|
||||
extensions = { "adx" },
|
||||
mime = { "audio/x-adx" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" },
|
||||
caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 8 },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type Loop = { start: number, stop: number }
|
||||
export type DecodeOptions = {
|
||||
maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
loop: Loop?, -- loop points in frames (stop exclusive); default: the source's meta.source.loop / loop, else none
|
||||
cutoff: number?, -- the predictor's high-pass cutoff in Hz (default 500, as CRI's encoders)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local FRAME = 18
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Adx.sniff(r: Bytes.Reader): number
|
||||
if r:peekU8(0) ~= 0x80 or r:peekU8(1) ~= 0 then
|
||||
return 0
|
||||
end
|
||||
local off = r:peekU8(2) * 256 + r:peekU8(3)
|
||||
return if r:peek(6, off - 2) == "(c)CRI" then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Adx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
|
||||
local dec, err = Adx.open(r)
|
||||
if not dec then
|
||||
return nil, err
|
||||
end
|
||||
local d = dec :: any
|
||||
local limit = opts and opts.maxFrames or 2 ^ 28
|
||||
if d.frames > limit or d.frames * d.channels > 2 ^ 28 then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames))
|
||||
end
|
||||
return Pcm.drain(d, { format = "adx", version = d.version, cutoff = d.cutoff, loop = d.loop }, limit)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Adx.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local o: EncodeOptions = opts or {}
|
||||
local src, serr = Pcm.source(value)
|
||||
if not src then
|
||||
return nil, serr
|
||||
end
|
||||
local ch, rate = src.channels, src.sampleRate
|
||||
if ch > 8 then
|
||||
return nil, Err.new(Err.ARG, "ADX holds at most 8 channels")
|
||||
end
|
||||
if rate ~= math.floor(rate) or rate < 1 or rate >= 2 ^ 31 then
|
||||
return nil, Err.new(Err.ARG, "the sample rate must be a positive integer")
|
||||
end
|
||||
local loop = o.loop
|
||||
if loop == nil then
|
||||
local v = value :: any
|
||||
local m = type(v.meta) == "table" and type(v.meta.source) == "table" and v.meta.source.loop
|
||||
loop = if type(m) == "table" then m else (if type(v.loop) == "table" then v.loop else nil)
|
||||
end
|
||||
local a, cerr = Pcm.collect(src)
|
||||
if not a then
|
||||
return nil, cerr
|
||||
end
|
||||
local n = a.frames
|
||||
if loop and (type(loop.start) ~= "number" or type(loop.stop) ~= "number" or loop.start < 0 or loop.stop <= loop.start or loop.stop > n) then
|
||||
return nil, Err.new(Err.ARG, "loop must be { start, stop } inside the audio")
|
||||
end
|
||||
local cutoff = o.cutoff or 500
|
||||
if type(cutoff) ~= "number" or cutoff < 1 or cutoff >= rate / 2 or cutoff > 65535 then
|
||||
return nil, Err.new(Err.ARG, "bad cutoff")
|
||||
end
|
||||
cutoff = math.floor(cutoff)
|
||||
local c1, c2 = Adpcm.adxCoefs(cutoff, rate)
|
||||
local hist = if ch > 1 then 4 * ch else 8
|
||||
local start = 0x18 + hist + (if loop then 0x18 else 0) + 6
|
||||
start = (start + 3) // 4 * 4
|
||||
local nframes = (n + 31) // 32
|
||||
local w = Bytes.writer(start + (nframes + 1) * FRAME * ch)
|
||||
w:u16be(0x8000)
|
||||
w:u16be(start - 4)
|
||||
w:u8(3)
|
||||
w:u8(FRAME)
|
||||
w:u8(4)
|
||||
w:u8(ch)
|
||||
w:u32be(rate)
|
||||
w:u32be(n)
|
||||
w:u16be(cutoff)
|
||||
w:u16be(0x0400)
|
||||
w:u32be(0)
|
||||
w:fill(0, hist)
|
||||
if loop then
|
||||
local bytesAt = function(f: number): number
|
||||
return start + (f // 32) * FRAME * ch
|
||||
end
|
||||
w:u16be(0)
|
||||
w:u16be(1)
|
||||
w:u32be(1)
|
||||
w:u32be(loop.start)
|
||||
w:u32be(bytesAt(loop.start))
|
||||
w:u32be(loop.stop)
|
||||
w:u32be(bytesAt(loop.stop + 31))
|
||||
end
|
||||
w:fill(0, start - 6 - w.pos)
|
||||
w:string("(c)CRI")
|
||||
local at = w:reserve(nframes * FRAME * ch)
|
||||
local st = buffer.create(8 * ch)
|
||||
for c = 0, ch - 1 do
|
||||
Adpcm.adxEncode(a.samples, c, ch, n, c1, c2, st, c * 8, w.buf, at + c * FRAME, FRAME * ch)
|
||||
end
|
||||
w.pos = at + nframes * FRAME * ch
|
||||
-- the end marker: scale 0x8001, then the padding size
|
||||
w:u16be(0x8001)
|
||||
w:u16be(FRAME - 4)
|
||||
w:fill(0, FRAME - 4)
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
function Adx.open(r: Bytes.Reader, _opts: any?): (Types.Decoder?, Err.Err?)
|
||||
if type(r) ~= "table" or type(r.buf) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "open: expected a Reader")
|
||||
end
|
||||
if Adx.sniff(r) == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "not an ADX file")
|
||||
end
|
||||
local h = r:sub(0)
|
||||
local copyright = (h:seek(2) and h:u16be()) or 0
|
||||
local start = copyright + 4
|
||||
local enc, fsize, bits, ch = h:u8(), h:u8(), h:u8(), h:u8()
|
||||
local rate, frames, cutoff, version = h:u32be(), h:u32be(), h:u16be(), h:u16be()
|
||||
if h.err then
|
||||
return nil, h.err
|
||||
end
|
||||
if version == 0x0408 or version == 0x0409 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "encrypted ADX (keys needed)")
|
||||
end
|
||||
if enc ~= 3 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "encoding type " .. enc .. (if enc == 0x10 or enc == 0x11 then " (AHX)" else ""))
|
||||
end
|
||||
if fsize ~= FRAME or bits ~= 4 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, string.format("frame size %d, %d bits", fsize, bits))
|
||||
end
|
||||
if ch < 1 or ch > 8 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad channel count " .. ch)
|
||||
end
|
||||
if rate < 1 or rate >= 2 ^ 31 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad sample rate " .. rate)
|
||||
end
|
||||
if version ~= 0x0300 and version ~= 0x0400 and version ~= 0x0500 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, string.format("version 0x%04X", version))
|
||||
end
|
||||
local size = r.limit - r.base - start
|
||||
if size < 0 then
|
||||
return nil, Err.new(Err.TRUNCATED, "the header runs past the end")
|
||||
end
|
||||
-- loop points and the initial history (vgmstream's reading of the extra header fields)
|
||||
local hist: { number }? = nil
|
||||
local loopsAt: number? = nil
|
||||
if version == 0x0300 then
|
||||
if start - 6 >= 0x14 + 0x18 then
|
||||
loopsAt = 0x14
|
||||
end
|
||||
elseif version == 0x0400 then
|
||||
local hsize = if ch > 1 then 4 * ch else 8
|
||||
hist = {}
|
||||
for c = 0, ch - 1 do
|
||||
local hh = r:sub(0x18 + c * 4, 4)
|
||||
local h1, h2 = hh:i16be(), hh:i16be()
|
||||
hist[c * 2 + 1], hist[c * 2 + 2] = if hh.err then 0 else h1, if hh.err then 0 else h2
|
||||
end
|
||||
local ainf = 0
|
||||
local ai = r:sub(0x18 + hsize + 4, 8)
|
||||
if ai:string(4) == "AINF" then
|
||||
ainf = ai:u32be()
|
||||
end
|
||||
if start - ainf - 6 >= 0x18 + hsize + 0x18 then
|
||||
loopsAt = 0x18 + hsize
|
||||
end
|
||||
end
|
||||
local loopTable: { start: number, stop: number }? = nil
|
||||
if loopsAt then
|
||||
local l = r:sub(loopsAt + 4, 0x14)
|
||||
local flag, ls, _, le = l:u32be(), l:u32be(), l:u32be(), l:u32be()
|
||||
if not l.err and flag ~= 0 and le > ls then
|
||||
loopTable = { start = ls, stop = le }
|
||||
end
|
||||
end
|
||||
local c1, c2 = Adpcm.adxCoefs(cutoff, rate)
|
||||
local dec: any = { sampleRate = rate, channels = ch, tags = {}, version = version, cutoff = cutoff, loop = loopTable }
|
||||
local d, err = Decoder.interleaved(dec, {
|
||||
kind = "adx",
|
||||
buf = r.buf,
|
||||
offset = r.base + start,
|
||||
size = size,
|
||||
interleave = FRAME,
|
||||
frames = frames,
|
||||
c1 = c1,
|
||||
c2 = c2,
|
||||
v3 = version == 0x0300,
|
||||
hist = hist,
|
||||
})
|
||||
if not d then
|
||||
return nil, err
|
||||
end
|
||||
d.bitrate = rate * FRAME * ch * 8 // 32
|
||||
return d, nil
|
||||
end
|
||||
|
||||
return Adx
|
||||
@@ -3,8 +3,9 @@
|
||||
-- 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.
|
||||
-- 16 / 24 / 32-bit, or AIFF-C sowt / fl32 / fl64 / ulaw / alaw. AIFF-C ima4 (Apple IMA ADPCM, codecs/audio/Adpcm;
|
||||
-- COMM counts packets of 64 frames) decodes too. Not supported: the other compressed AIFF-C codecs (MAC3 / MAC6,
|
||||
-- Qclp, ...: Err.UNSUPPORTED), MARK / INST loops (ignored), the ID3 chunk.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
@@ -12,6 +13,7 @@ local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Chunks = require("@formats/containers/Chunks")
|
||||
local Pcm = require("@formats/codecs/audio/Pcm")
|
||||
local Adpcm = require("@formats/codecs/audio/Adpcm/Decoder")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Aiff = {
|
||||
@@ -19,7 +21,7 @@ local Aiff = {
|
||||
category = "audio",
|
||||
extensions = { "aiff", "aif", "aifc", "afc" },
|
||||
mime = { "audio/aiff", "audio/x-aiff" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "containers/Chunks" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder", "containers/Chunks" },
|
||||
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false },
|
||||
}
|
||||
|
||||
@@ -115,6 +117,8 @@ local function sampleFormat(comp: string, bits: number): (string?, string?)
|
||||
return "ulaw", nil
|
||||
elseif comp == "alaw" or comp == "ALAW" then
|
||||
return "alaw", nil
|
||||
elseif comp == "ima4" then
|
||||
return "ima4", nil -- not a Pcm format: Adpcm/Decoder.blocks
|
||||
end
|
||||
return nil, "compression " .. string.format("%q", comp)
|
||||
end
|
||||
@@ -138,6 +142,7 @@ type Info = {
|
||||
compression: string,
|
||||
aifc: boolean,
|
||||
dataOffset: number, -- absolute in r.buf
|
||||
dataSize: number, -- bytes of sample data present
|
||||
truncated: boolean,
|
||||
tags: Types.Tags,
|
||||
}
|
||||
@@ -194,6 +199,7 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?)
|
||||
compression = comp,
|
||||
aifc = aifc,
|
||||
dataOffset = 0,
|
||||
dataSize = 0,
|
||||
truncated = false,
|
||||
tags = tags,
|
||||
}
|
||||
@@ -228,13 +234,19 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?)
|
||||
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
|
||||
local present
|
||||
if fi.format == "ima4" then
|
||||
fi.frames *= 64 -- COMM counts packets
|
||||
present = if ssnd then ssndLen // (34 * fi.channels) * 64 else 0
|
||||
else
|
||||
present = if ssnd then ssndLen // (fi.channels * Pcm.Convert.SIZE[fi.format]) else 0
|
||||
end
|
||||
if present < fi.frames then
|
||||
fi.frames = present
|
||||
fi.truncated = true
|
||||
end
|
||||
fi.dataOffset = ssnd or base
|
||||
fi.dataSize = ssndLen
|
||||
return fi, nil
|
||||
end
|
||||
|
||||
@@ -360,7 +372,16 @@ function Aiff.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.
|
||||
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)
|
||||
local dec, derr
|
||||
if info.format == "ima4" then
|
||||
local base = { sampleRate = info.sampleRate, channels = info.channels, tags = info.tags }
|
||||
dec, derr = Adpcm.blocks(base, { kind = "ima_qt", buf = r.buf, offset = info.dataOffset, size = info.dataSize, frames = info.frames })
|
||||
if dec then
|
||||
(dec :: any).bitrate = math.floor(info.sampleRate * 34 * 8 * info.channels / 64)
|
||||
end
|
||||
else
|
||||
dec, derr = Pcm.rawDecoder(r.buf, info.dataOffset, info.frames, info.channels, info.sampleRate, info.format, info.tags)
|
||||
end
|
||||
if not dec then
|
||||
return nil, derr
|
||||
end
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
--!strict
|
||||
-- audio/ape: Monkey's Audio (.ape) files around codecs/audio/Ape: the header in front (after an optional ID3v2 tag),
|
||||
-- the frames (each independent: sample-accurate seeking through the seek table), APEv2 tags at the end
|
||||
-- (codecs/audio/ApeTag). Written from the Monkey's Audio SDK 13.28 (BSD 3-clause, licenses/monkeys-audio-LICENSE.txt).
|
||||
-- Supports file versions 3.95 and later, every compression level, 8 - 32-bit integer and 32-bit float, 1 - 32
|
||||
-- channels (as the source WAV ordered them). Not supported: files before 3.95, encoding.
|
||||
--
|
||||
-- local dec = Ape.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, level, version, float, md5
|
||||
-- local i32, n = dec:readInt(4096) -- integer files: the samples as `mac -d` writes them
|
||||
-- local audio = Ape.decode(Bytes.reader(buf)) -- Types.Audio
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Pcm = require("@formats/codecs/audio/Pcm")
|
||||
local Stream = require("@formats/codecs/audio/Stream")
|
||||
local ApeTag = require("@formats/codecs/audio/ApeTag")
|
||||
local ApeCodec = require("@formats/codecs/audio/Ape")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Ape = {
|
||||
name = "ape",
|
||||
category = "audio",
|
||||
extensions = { "ape" },
|
||||
mime = { "audio/ape", "audio/x-ape", "audio/x-monkeys-audio" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Ape" },
|
||||
caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, float = true, depths = { 8, 16, 24, 32 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type OpenOptions = {
|
||||
maxFrames: number?, -- decode(): refuse longer streams (default 2^28)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local LEVELS = { [1000] = "fast", [2000] = "normal", [3000] = "high", [4000] = "extra high", [5000] = "insane" }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Ape.sniff(r: Bytes.Reader): number
|
||||
local head = r:peek(4)
|
||||
if head == "MAC " or head == "MACF" then -- MACF: float samples
|
||||
return 1
|
||||
end
|
||||
if string.sub(head, 1, 3) == "ID3" then
|
||||
local sz = 0
|
||||
for i = 6, 9 do
|
||||
local v = r:peekU8(i)
|
||||
if v < 0 then
|
||||
return 0
|
||||
end
|
||||
sz = sz * 128 + bit32.band(v, 127)
|
||||
end
|
||||
local footer = bit32.band(math.max(r:peekU8(5), 0), 0x10) ~= 0
|
||||
local id = r:peek(4, 10 + sz + (if footer then 10 else 0))
|
||||
return if id == "MAC " or id == "MACF" then 1 else 0
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream
|
||||
function Ape.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?)
|
||||
local dec, err = Ape.open(r, opts)
|
||||
if not dec then
|
||||
return nil, err
|
||||
end
|
||||
local d = dec :: any
|
||||
local limit = opts and opts.maxFrames or 2 ^ 28
|
||||
if d.frames > limit or d.frames * d.channels > 2 ^ 28 then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames))
|
||||
end
|
||||
return Pcm.drain(d, d.source, limit)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> Decoder | nil, Err
|
||||
function Ape.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?)
|
||||
if type(r) == "buffer" then
|
||||
r = Bytes.reader(r :: any)
|
||||
end
|
||||
if type(r) ~= "table" or type(r.buf) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "open: expected a Reader")
|
||||
end
|
||||
local buf, base, limit = r.buf, r.base, r.limit
|
||||
local tags, tagInfo = ApeTag.find(buf, base, limit)
|
||||
local stop = if tagInfo then tagInfo.start else limit
|
||||
local info, err = ApeCodec.info(buf, base, stop)
|
||||
if not info then
|
||||
return nil, err
|
||||
end
|
||||
if info.channels * info.blocksPerFrame > 2 ^ 24 then
|
||||
return nil, Err.new(Err.LIMIT, "frames of " .. info.blocksPerFrame .. " blocks")
|
||||
end
|
||||
local codec, cerr = ApeCodec.decoder(info)
|
||||
if not codec then
|
||||
return nil, cerr
|
||||
end
|
||||
local frames = info.totalBlocks
|
||||
local bpf = info.blocksPerFrame
|
||||
local dec: any = {
|
||||
sampleRate = info.sampleRate,
|
||||
channels = info.channels,
|
||||
frames = frames,
|
||||
duration = frames / info.sampleRate,
|
||||
bitrate = if frames > 0 then math.floor((stop - base) * 8 * info.sampleRate / frames) else 0,
|
||||
tags = tags or {},
|
||||
bitsPerSample = info.bitsPerSample,
|
||||
float = info.float,
|
||||
level = LEVELS[info.level] or tostring(info.level),
|
||||
version = info.version,
|
||||
md5 = info.md5,
|
||||
source = { format = "ape", bitDepth = info.bitsPerSample, float = info.float, level = info.level, version = info.version, programVersion = info.programVersion, tags = tagInfo and tagInfo.items },
|
||||
}
|
||||
local count = info.totalFrames
|
||||
return Stream.packets(dec, {
|
||||
count = count,
|
||||
start = function(i: number): number
|
||||
return if i > count then frames else (i - 1) * bpf
|
||||
end,
|
||||
decode = function(i: number): (number?, Err.Err?)
|
||||
return codec:frame(buf, i)
|
||||
end,
|
||||
pcm = function(): { number }
|
||||
return codec.pcm
|
||||
end,
|
||||
reset = function() end,
|
||||
stop = frames,
|
||||
scale = if info.float then 1 else 1 / 2 ^ (info.bitsPerSample - 1),
|
||||
ints = not info.float,
|
||||
})
|
||||
end
|
||||
|
||||
return Ape
|
||||
@@ -0,0 +1,298 @@
|
||||
--!strict
|
||||
-- audio/brstm: Nintendo's streamed audio: BRSTM (Wii, "RSTM", big-endian), BCSTM (3DS, "CSTM", little-endian) and
|
||||
-- BFSTM (Wii U big-endian / Switch little-endian, "FSTM"), over codecs/audio/Adpcm. New in formats-luau; the layouts
|
||||
-- follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), whose output it matches bit for bit. Supports: DSP
|
||||
-- ADPCM (with the header's initial history; seeks into blocks not yet played use the ADPC / SEEK history table), PCM16
|
||||
-- and PCM8, 1-255 channels in block-interleaved layout, the loop start (dec.loop and meta.source.loop = { start, stop }
|
||||
-- in frames, stop exclusive). Read only. Not supported: BCSTM IMA ADPCM, BRSTM version 0.1 (beta), BFSTM regions
|
||||
-- (the whole stream plays), the track table (channels are not grouped).
|
||||
--
|
||||
-- local dec = Brstm.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, container, codec)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Pcm = require("@formats/codecs/audio/Pcm")
|
||||
local Decoder = require("@formats/codecs/audio/Adpcm/Decoder")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Brstm = {
|
||||
name = "brstm",
|
||||
category = "audio",
|
||||
extensions = { "brstm", "bcstm", "bfstm" },
|
||||
mime = { "audio/x-brstm" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder" },
|
||||
caps = { decode = true, encode = false, streaming = true, lossy = true, loops = true, containers = { "RSTM", "CSTM", "FSTM" } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local CODECS = { [0] = "pcm8", [1] = "pcm16", [2] = "dsp", [3] = "ima" }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Brstm.sniff(r: Bytes.Reader): number
|
||||
local m = r:peek(4)
|
||||
if m ~= "RSTM" and m ~= "CSTM" and m ~= "FSTM" then
|
||||
return 0
|
||||
end
|
||||
local bom = r:peek(2, 4)
|
||||
return if bom == "\254\255" or bom == "\255\254" then 1 else 0
|
||||
end
|
||||
|
||||
-- variant(r) -> "brstm" / "bcstm" / "bfstm": the flavour, for F.detect
|
||||
function Brstm.variant(r: Bytes.Reader): string?
|
||||
local m = r:peek(4)
|
||||
return if m == "RSTM" then "brstm" elseif m == "CSTM" then "bcstm" elseif m == "FSTM" then "bfstm" else nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Brstm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
|
||||
local dec, err = Brstm.open(r)
|
||||
if not dec then
|
||||
return nil, err
|
||||
end
|
||||
local d = dec :: any
|
||||
local limit = opts and opts.maxFrames or 2 ^ 28
|
||||
if d.frames > limit or d.frames * d.channels > 2 ^ 28 then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames))
|
||||
end
|
||||
return Pcm.drain(d, { format = "brstm", container = d.container, codec = d.codec, loop = d.loop }, limit)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- a reader of the whole file in its byte order: u8 / u16 / u32 / i16 / i32 at absolute offsets (relative to the file
|
||||
-- start); a read out of range records the error in .err and returns 0
|
||||
local function view(r: Bytes.Reader, be: boolean)
|
||||
local v = { err = nil :: string? }
|
||||
local size = r.limit - r.base
|
||||
local function at(o: number, n: number): Bytes.Reader?
|
||||
if o < 0 or o + n > size then
|
||||
v.err = "an offset points past the end"
|
||||
return nil
|
||||
end
|
||||
return r:sub(o, n)
|
||||
end
|
||||
function v.u8(o: number): number
|
||||
local s = at(o, 1)
|
||||
return if s then s:u8() else 0
|
||||
end
|
||||
function v.u16(o: number): number
|
||||
local s = at(o, 2)
|
||||
return if s then (if be then s:u16be() else s:u16le()) else 0
|
||||
end
|
||||
function v.i16(o: number): number
|
||||
local s = at(o, 2)
|
||||
return if s then (if be then s:i16be() else s:i16le()) else 0
|
||||
end
|
||||
function v.u32(o: number): number
|
||||
local s = at(o, 4)
|
||||
return if s then (if be then s:u32be() else s:u32le()) else 0
|
||||
end
|
||||
function v.i32(o: number): number
|
||||
local s = at(o, 4)
|
||||
return if s then (if be then s:i32be() else s:i32le()) else 0
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
type Layout = {
|
||||
codec: number,
|
||||
loop: boolean,
|
||||
ch: number,
|
||||
rate: number,
|
||||
loopStart: number,
|
||||
frames: number,
|
||||
blockSize: number,
|
||||
lastPadded: number,
|
||||
data: number, -- the first block (absolute in the file)
|
||||
adp: { number }, -- each channel's DSP info offset (coefficients, then gain, ps, yn1, yn2)
|
||||
hist: number?, -- the per-block history table: (yn1, yn2) per channel per block
|
||||
histEntries: number,
|
||||
}
|
||||
|
||||
local function parseRstm(v: any): (Layout?, string?)
|
||||
if v.u16(0x06) ~= 0x0100 then
|
||||
return nil, string.format("unsupported: BRSTM version %d.%d", v.u8(0x06), v.u8(0x07))
|
||||
end
|
||||
local head = v.u32(0x10)
|
||||
local adpc = v.u32(0x18)
|
||||
if v.u32(head) ~= 0x48454144 then -- "HEAD", read big-endian
|
||||
return nil, "no HEAD chunk"
|
||||
end
|
||||
local base = head + 8
|
||||
local info = base + v.u32(base + 4)
|
||||
local chans = base + v.u32(base + 20)
|
||||
local ch = v.u8(info + 2)
|
||||
local L: Layout = {
|
||||
codec = v.u8(info),
|
||||
loop = v.u8(info + 1) ~= 0,
|
||||
ch = ch,
|
||||
rate = v.u16(info + 4),
|
||||
loopStart = v.u32(info + 8),
|
||||
frames = v.u32(info + 12),
|
||||
data = v.u32(info + 16),
|
||||
blockSize = v.u32(info + 24),
|
||||
lastPadded = v.u32(info + 40),
|
||||
adp = {},
|
||||
hist = nil,
|
||||
histEntries = 0,
|
||||
}
|
||||
for c = 0, ch - 1 do
|
||||
local ci = base + v.u32(chans + 4 + c * 8 + 4)
|
||||
L.adp[c + 1] = base + v.u32(ci + 4)
|
||||
end
|
||||
if adpc > 0 and v.u32(adpc) == 0x41445043 then -- "ADPC"
|
||||
L.hist = adpc + 8
|
||||
L.histEntries = (v.u32(adpc + 4) - 8) // math.max(1, 4 * ch)
|
||||
end
|
||||
return L, nil
|
||||
end
|
||||
|
||||
local function parseFstm(v: any): (Layout?, string?)
|
||||
local info: number, seek: number, data: number = 0, 0, 0
|
||||
local seekSize: number = 0
|
||||
for i = 0, math.min(v.u16(0x10), 16) - 1 do
|
||||
local id, off = v.u16(0x14 + i * 12), v.u32(0x14 + i * 12 + 4)
|
||||
if id == 0x4000 then
|
||||
info = off
|
||||
elseif id == 0x4001 then
|
||||
seek = off
|
||||
seekSize = v.u32(0x14 + i * 12 + 8) :: number
|
||||
elseif id == 0x4002 then
|
||||
data = off
|
||||
end
|
||||
end
|
||||
if info == 0 or data == 0 then
|
||||
return nil, "no INFO or DATA block"
|
||||
end
|
||||
local stream = info + 8 + v.i32(info + 0x0C)
|
||||
local chans = info + 8 + v.i32(info + 0x1C)
|
||||
local ch = v.u8(stream + 2)
|
||||
local dataRef = stream + 0x30
|
||||
local L: Layout = {
|
||||
codec = v.u8(stream),
|
||||
loop = v.u8(stream + 1) ~= 0,
|
||||
ch = ch,
|
||||
rate = v.u32(stream + 4),
|
||||
loopStart = v.u32(stream + 8),
|
||||
frames = v.u32(stream + 12),
|
||||
blockSize = v.u32(stream + 20),
|
||||
lastPadded = v.u32(stream + 36),
|
||||
data = if v.u16(dataRef) == 0x1F00 then data + 8 + v.i32(dataRef + 4) else data + 0x20,
|
||||
adp = {},
|
||||
hist = nil,
|
||||
histEntries = 0,
|
||||
}
|
||||
for c = 0, ch - 1 do
|
||||
local ci = chans + v.i32(chans + 4 + c * 8 + 4)
|
||||
L.adp[c + 1] = ci + v.i32(ci + 4)
|
||||
end
|
||||
if seek > 0 and seekSize > 8 then
|
||||
L.hist = seek + 8
|
||||
L.histEntries = (seekSize - 8) // math.max(1, 4 * ch)
|
||||
end
|
||||
return L, nil
|
||||
end
|
||||
|
||||
function Brstm.open(r: Bytes.Reader, _opts: any?): (Types.Decoder?, Err.Err?)
|
||||
if type(r) ~= "table" or type(r.buf) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "open: expected a Reader")
|
||||
end
|
||||
if r.limit - r.base < 0x40 then
|
||||
return nil, Err.new(Err.TRUNCATED, "the header runs past the end")
|
||||
end
|
||||
if Brstm.sniff(r) == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "not a BRSTM / BCSTM / BFSTM file")
|
||||
end
|
||||
local magic = r:peek(4)
|
||||
local be = r:peek(2, 4) == "\254\255"
|
||||
local v = view(r, be)
|
||||
local parsed: Layout?, msg: string?
|
||||
if magic == "RSTM" then
|
||||
if not be then
|
||||
return nil, Err.new(Err.CORRUPT, "a little-endian BRSTM")
|
||||
end
|
||||
parsed, msg = parseRstm(v)
|
||||
else
|
||||
parsed, msg = parseFstm(v)
|
||||
end
|
||||
if v.err then
|
||||
return nil, Err.new(Err.TRUNCATED, v.err)
|
||||
elseif not parsed then
|
||||
return nil, Err.from(msg)
|
||||
end
|
||||
local L = parsed :: Layout
|
||||
local codec = CODECS[L.codec]
|
||||
if not codec then
|
||||
return nil, Err.new(Err.CORRUPT, "codec " .. L.codec)
|
||||
elseif codec == "ima" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "IMA ADPCM streams")
|
||||
end
|
||||
local ch = L.ch
|
||||
if ch < 1 or L.rate < 1 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad channel count or sample rate")
|
||||
end
|
||||
local size = r.limit - r.base - L.data
|
||||
if L.data < 0 or size < 0 then
|
||||
return nil, Err.new(Err.TRUNCATED, "the data starts past the end")
|
||||
end
|
||||
local kind = if codec == "dsp" then "dsp" elseif codec == "pcm8" then "s8" elseif be then "s16be" else "s16le"
|
||||
local coefs: buffer? = nil
|
||||
local hist: { number }? = nil
|
||||
if codec == "dsp" then
|
||||
coefs = buffer.create(64 * ch)
|
||||
hist = {}
|
||||
for c = 0, ch - 1 do
|
||||
local adp = L.adp[c + 1]
|
||||
for k = 0, 15 do
|
||||
buffer.writei32(coefs :: buffer, c * 64 + k * 4, v.i16(adp + k * 2))
|
||||
end
|
||||
hist[c * 2 + 1], hist[c * 2 + 2] = v.i16(adp + 36), v.i16(adp + 38)
|
||||
end
|
||||
if v.err then
|
||||
return nil, Err.new(Err.TRUNCATED, v.err)
|
||||
end
|
||||
end
|
||||
local histAt, entries = L.hist, L.histEntries
|
||||
local loop = if L.loop and L.loopStart < L.frames then { start = L.loopStart, stop = L.frames } else nil
|
||||
local dec: any = { sampleRate = L.rate, channels = ch, tags = {}, container = magic, codec = codec, loop = loop }
|
||||
local block = L.blockSize
|
||||
if block < 1 or (kind == "dsp" and block % 8 ~= 0) or (kind ~= "s8" and block % 2 ~= 0) then
|
||||
return nil, Err.new(Err.CORRUPT, "bad block size " .. block)
|
||||
end
|
||||
local d, err = Decoder.interleaved(dec, {
|
||||
kind = kind :: any,
|
||||
buf = r.buf,
|
||||
offset = r.base + L.data,
|
||||
size = size,
|
||||
interleave = block,
|
||||
lastInterleave = if L.lastPadded > 0 and L.lastPadded <= block then L.lastPadded else block,
|
||||
frames = L.frames,
|
||||
coefs = coefs,
|
||||
hist = hist,
|
||||
restore = if codec == "dsp" and histAt
|
||||
then function(row: number, st: buffer): boolean
|
||||
if row >= entries then
|
||||
return false
|
||||
end
|
||||
for c = 0, ch - 1 do
|
||||
local p = (histAt :: number) + (row * ch + c) * 4
|
||||
buffer.writei32(st, c * 8, v.i16(p))
|
||||
buffer.writei32(st, c * 8 + 4, v.i16(p + 2))
|
||||
end
|
||||
return v.err == nil
|
||||
end
|
||||
else nil,
|
||||
})
|
||||
if d then
|
||||
d.bitrate = if d.duration > 0 then math.floor(size * 8 / d.duration) else 0
|
||||
end
|
||||
return d, err
|
||||
end
|
||||
|
||||
return Brstm
|
||||
@@ -3,7 +3,8 @@
|
||||
-- PCM (8 / 16 / 24 / 32-bit integer, 32 / 64-bit float, big / little endian), ALAC (codecs/audio/Alac), AAC-LC (codecs/audio/Aac,
|
||||
-- kuki esds), mu-law and A-law; the packet table (pakt) with priming / remainder trimming, a data chunk of unknown
|
||||
-- size (-1), info chunk tags; seeking. Writing linear PCM (16 / 24-bit big endian, 32-bit float) and ALAC (16 / 20 /
|
||||
-- 24-bit) with info tags. Not supported: IMA4, other compressed formats (UNSUPPORTED).
|
||||
-- 24-bit) with info tags. IMA4 (Apple IMA ADPCM, codecs/audio/Adpcm) decodes too, with exact seeking. Not supported:
|
||||
-- other compressed formats (UNSUPPORTED).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
@@ -14,6 +15,7 @@ local Pcm = require("@formats/codecs/audio/Pcm")
|
||||
local Stream = require("@formats/codecs/audio/Stream")
|
||||
local Aac = require("@formats/codecs/audio/Aac")
|
||||
local Alac = require("@formats/codecs/audio/Alac")
|
||||
local Adpcm = require("@formats/codecs/audio/Adpcm/Decoder")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Caf = {
|
||||
@@ -21,7 +23,7 @@ local Caf = {
|
||||
category = "audio",
|
||||
extensions = { "caf", "caff" },
|
||||
mime = { "audio/x-caf" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream", "containers/Chunks" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Adpcm/Decoder", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream", "containers/Chunks" },
|
||||
caps = { decode = true, encode = true, codecs = { "pcm", "alac", "aac", "ulaw", "alaw" }, encodeCodecs = { "pcm", "alac" }, tags = true, streaming = true },
|
||||
}
|
||||
|
||||
@@ -333,7 +335,7 @@ local function source(r: Bytes.Reader, p: Parsed): (Source?, Err.Err?)
|
||||
end
|
||||
-- packetised codecs
|
||||
local sizes = p.packets
|
||||
if not sizes then
|
||||
if not sizes or (#sizes == 0 and d.bytesPerPacket > 0) then -- constant packets: pakt may list none
|
||||
if d.bytesPerPacket > 0 then
|
||||
local n = (p.dataEnd - p.dataStart) // d.bytesPerPacket
|
||||
sizes = table.create(n, d.bytesPerPacket)
|
||||
@@ -425,7 +427,23 @@ function Caf.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E
|
||||
if not p then
|
||||
return nil, err
|
||||
end
|
||||
local s, serr = source(r, p :: Parsed)
|
||||
local pp = p :: Parsed
|
||||
if pp.desc.format == "ima4" then
|
||||
-- Apple IMA ADPCM: 34-byte packets per channel, 64 frames; the predictor carries across packets
|
||||
local ch = pp.desc.channels
|
||||
local packets = (pp.dataEnd - pp.dataStart) // (34 * ch)
|
||||
local frames = packets * 64
|
||||
if pp.validFrames and pp.validFrames >= 0 then
|
||||
frames = math.min(frames, pp.validFrames)
|
||||
end
|
||||
local dec: any = { sampleRate = pp.desc.rate, channels = ch, tags = pp.tags, codec = "ima4", bitsPerSample = 16 }
|
||||
local d, derr = Adpcm.blocks(dec, { kind = "ima_qt", buf = r.buf, offset = pp.dataStart, size = pp.dataEnd - pp.dataStart, frames = frames })
|
||||
if d then
|
||||
d.bitrate = math.floor(pp.desc.rate * 34 * 8 * ch / 64)
|
||||
end
|
||||
return d, derr
|
||||
end
|
||||
local s, serr = source(r, pp)
|
||||
if not s then
|
||||
return nil, serr
|
||||
end
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
--!strict
|
||||
-- audio/mpc: Musepack (.mpc / .mp+ / .mpp), stream versions 7 and 8, through codecs/audio/Musepack (a libmpcdec
|
||||
-- port). Supports: SV7 (mppenc 1.x) and SV8 (mpcenc 1.30) streams, mono / stereo, every rate (32 / 37.8 / 44.1 /
|
||||
-- 48 kHz), gapless length (the synthesis delay, SV8 leading silence and the last frame's length are honoured), seeking
|
||||
-- (SV8: by audio packet, exact; SV7: by frame with 32 frames of pre-roll, as libmpcdec), APEv2 tags
|
||||
-- (codecs/audio/ApeTag), a leading ID3v2 tag (skipped), ReplayGain values in meta (not applied). Not supported:
|
||||
-- writing, SV4 - SV6 (UNSUPPORTED), chapters.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Pcm = require("@formats/codecs/audio/Pcm")
|
||||
local Stream = require("@formats/codecs/audio/Stream")
|
||||
local ApeTag = require("@formats/codecs/audio/ApeTag")
|
||||
local Musepack = require("@formats/codecs/audio/Musepack")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Mpc = {
|
||||
name = "mpc",
|
||||
category = "audio",
|
||||
extensions = { "mpc", "mp+", "mpp" },
|
||||
mime = { "audio/x-musepack", "audio/musepack" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Musepack" },
|
||||
caps = { decode = true, encode = false, codecs = { "musepack" }, versions = { 7, 8 }, streaming = true, lossy = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxFrames: number?, -- Err.LIMIT past this many output sample frames (default 2^31)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
-- the size of an ID3v2 tag at p (0 if none)
|
||||
local function id3v2(b: buffer, p: number, limit: number): number
|
||||
if p + 10 > limit or buffer.readstring(b, p, 3) ~= "ID3" then
|
||||
return 0
|
||||
end
|
||||
local n = 10
|
||||
for i = 6, 9 do
|
||||
n += bit32.band(buffer.readu8(b, p + i), 127) * 128 ^ (9 - i)
|
||||
end
|
||||
return n + (if bit32.band(buffer.readu8(b, p + 5), 0x10) ~= 0 then 10 else 0)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Mpc.sniff(r: Bytes.Reader): number
|
||||
local b, p, limit = r.buf, r.pos, r.limit
|
||||
p += id3v2(b, p, limit)
|
||||
local v = Musepack.magic(b, p, limit)
|
||||
if v == 8 then
|
||||
return 1
|
||||
end
|
||||
return if v == 7 then 0.9 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Mpc.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local b, base, limit = r.buf, r.base, r.limit
|
||||
local start = base + id3v2(b, base, limit)
|
||||
local tags, info = ApeTag.find(b, start, limit)
|
||||
local stop = if info and info.start > start then info.start else limit
|
||||
local s, err = Musepack.open(b, start, stop)
|
||||
if not s then
|
||||
return nil, err
|
||||
end
|
||||
if s.frames > (o.maxFrames or 2 ^ 31) then
|
||||
return nil, Err.new(Err.LIMIT, "more than " .. (o.maxFrames or 2 ^ 31) .. " frames")
|
||||
end
|
||||
local duration = s.frames / s.sampleRate
|
||||
local dec = {
|
||||
sampleRate = s.sampleRate,
|
||||
channels = s.channels,
|
||||
frames = s.frames,
|
||||
duration = duration,
|
||||
bitrate = if duration > 0 then math.floor(s.bytes * 8 / duration + 0.5) else 0,
|
||||
tags = tags or {},
|
||||
codec = "musepack",
|
||||
version = s.version,
|
||||
profile = s.profile,
|
||||
gain = s.gain,
|
||||
}
|
||||
return Stream.packets(dec, s :: any)
|
||||
end
|
||||
|
||||
function Mpc.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
|
||||
local dec, err = Mpc.open(r, opts)
|
||||
if not dec then
|
||||
return nil, err
|
||||
end
|
||||
local d: any = dec
|
||||
return Pcm.drain(d, { format = "mpc", codec = "musepack", version = d.version, profile = d.profile, gain = d.gain, bitrate = d.bitrate })
|
||||
end
|
||||
|
||||
return Mpc
|
||||
@@ -0,0 +1,185 @@
|
||||
--!strict
|
||||
-- audio/qoa: QOA, "Quite OK Audio" (.qoa), over codecs/audio/Qoa (a port of qoa.h, phoboslab, MIT). New in
|
||||
-- formats-luau. Decode / open: static files and streaming files (total 0 in the header), 1-255 channels (WAVE order
|
||||
-- for 1-8, as the spec lays them out), any rate up to 16777215 Hz, frame-accurate seeking (every frame carries its
|
||||
-- own predictor state), a truncated file decodes its whole frames. Encode (Audio or Decoder, streamed frame by frame):
|
||||
-- byte-for-byte what qoa.h's qoa_encode writes, 1-8 channels (qoa.h's limit). Not supported: frames whose channel
|
||||
-- count or rate change mid-stream (Err.UNSUPPORTED).
|
||||
--
|
||||
-- local dec = Qoa.open(Bytes.reader(buf)) -- Types.Decoder
|
||||
-- local file = Qoa.encode(audio)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Pcm = require("@formats/codecs/audio/Pcm")
|
||||
local Stream = require("@formats/codecs/audio/Stream")
|
||||
local Codec = require("@formats/codecs/audio/Qoa")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Qoa = {
|
||||
name = "qoa",
|
||||
category = "audio",
|
||||
extensions = { "qoa" },
|
||||
mime = { "audio/qoa" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Qoa" },
|
||||
caps = { decode = true, encode = true, streaming = true, lossy = true, seek = true, channels = 8 },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxFrames: number?, -- decode(): Err.LIMIT past this many sample frames (default 2^28)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Qoa.sniff(r: Bytes.Reader): number
|
||||
return if r:peek(4) == "qoaf" then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Qoa.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
|
||||
local dec, err = Qoa.open(r)
|
||||
if not dec then
|
||||
return nil, err
|
||||
end
|
||||
local d = dec :: any
|
||||
local limit = opts and opts.maxFrames or 2 ^ 28
|
||||
if d.frames > limit or d.frames * d.channels > 2 ^ 28 then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames))
|
||||
end
|
||||
return Pcm.drain(d, { format = "qoa", streaming = d.streaming }, limit)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Qoa.encode(value: any, _opts: any?): (buffer?, Err.Err?)
|
||||
local src, serr = Pcm.source(value)
|
||||
if not src then
|
||||
return nil, serr
|
||||
end
|
||||
local ch, rate = src.channels, src.sampleRate
|
||||
if ch > 8 then
|
||||
return nil, Err.new(Err.ARG, "QOA (qoa.h) holds at most 8 channels")
|
||||
end
|
||||
if rate ~= math.floor(rate) or rate < 1 or rate > 0xFFFFFF then
|
||||
return nil, Err.new(Err.ARG, "the sample rate must be an integer in 1 .. 16777215")
|
||||
end
|
||||
local FL = Codec.FRAME_LEN
|
||||
local w = Bytes.writer(8 + (if src.frames > 0 then Codec.frameSize(ch, (src.frames + 19) // 20) + 24 * ch * (src.frames // FL + 1) else 65536))
|
||||
w:string("qoaf")
|
||||
w:u32be(0)
|
||||
local lms = Codec.newLms(ch)
|
||||
local fb = buffer.create(FL * ch * 4)
|
||||
local tmp: buffer? = nil
|
||||
local total = 0
|
||||
while true do
|
||||
-- one frame: 5120 sample frames (the last may be shorter), as qoa.h cuts them
|
||||
local have = 0
|
||||
while have < FL do
|
||||
local b, n = src:read(FL - have, tmp)
|
||||
if n <= 0 then
|
||||
break
|
||||
end
|
||||
tmp = b
|
||||
buffer.copy(fb, have * ch * 4, b, 0, n * ch * 4)
|
||||
have += n
|
||||
end
|
||||
if have == 0 then
|
||||
break
|
||||
end
|
||||
local at = w:reserve(Codec.frameSize(ch, (have + 19) // 20))
|
||||
w.pos = at + Codec.encodeFrame(fb, 0, have, ch, rate, lms, w.buf, at)
|
||||
total += have
|
||||
if have < FL then
|
||||
break
|
||||
end
|
||||
end
|
||||
if src.err then
|
||||
return nil, src.err
|
||||
end
|
||||
if total == 0 then
|
||||
return nil, Err.new(Err.ARG, "QOA needs at least one sample")
|
||||
end
|
||||
if total >= 2 ^ 32 then
|
||||
return nil, Err.new(Err.ARG, "too many samples for QOA")
|
||||
end
|
||||
local out = w:finish()
|
||||
buffer.writeu32(out, 4, bit32.byteswap(total))
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
function Qoa.open(r: Bytes.Reader, _opts: any?): (Types.Decoder?, Err.Err?)
|
||||
if type(r) ~= "table" or type(r.buf) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "open: expected a Reader")
|
||||
end
|
||||
local h = r:sub(0)
|
||||
if h:string(4) ~= "qoaf" then
|
||||
return nil, Err.new(Err.CORRUPT, "not a QOA file")
|
||||
end
|
||||
local declared = h:u32be()
|
||||
if h.err then
|
||||
return nil, h.err
|
||||
end
|
||||
local buf = r.buf
|
||||
-- the frame index: offsets, first frames
|
||||
local offs, starts = {}, {}
|
||||
local p, total = r.base + 8, 0
|
||||
local ch, rate = 0, 0
|
||||
while p < r.limit do
|
||||
local info, msg = Codec.frameInfo(buf, p, r.limit - p)
|
||||
if not info then
|
||||
if #offs == 0 then
|
||||
return nil, Err.from(msg, p - r.base)
|
||||
end
|
||||
break -- a cut or damaged tail: keep the whole frames
|
||||
end
|
||||
if #offs == 0 then
|
||||
ch, rate = info.channels, info.rate
|
||||
elseif info.channels ~= ch or info.rate ~= rate then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "the channel count or rate changes mid-stream", p - r.base)
|
||||
end
|
||||
table.insert(offs, p)
|
||||
table.insert(starts, total)
|
||||
total += info.samples
|
||||
p += info.size
|
||||
if declared > 0 and total >= declared then
|
||||
break
|
||||
end
|
||||
end
|
||||
if #offs == 0 then
|
||||
return nil, Err.new(Err.TRUNCATED, "no frames")
|
||||
end
|
||||
local frames = if declared > 0 then math.min(declared, total) else total
|
||||
local pcm = buffer.create(Codec.FRAME_LEN * ch * 4)
|
||||
local dec: any = {
|
||||
sampleRate = rate,
|
||||
channels = ch,
|
||||
frames = frames,
|
||||
duration = frames / rate,
|
||||
bitrate = math.floor((p - r.base) * 8 / math.max(frames / rate, 1e-9)),
|
||||
tags = {},
|
||||
streaming = declared == 0,
|
||||
}
|
||||
local limit = r.limit
|
||||
return Stream.packets(dec, {
|
||||
count = #offs,
|
||||
start = function(i: number): number
|
||||
return if i > #offs then total else starts[i]
|
||||
end,
|
||||
decode = function(i: number): (number?, Err.Err?)
|
||||
local n, msg = Codec.decodeFrame(buf, offs[i], limit - offs[i], pcm, 0)
|
||||
if not n then
|
||||
return nil, Err.from(msg, offs[i] - r.base)
|
||||
end
|
||||
return n, nil
|
||||
end,
|
||||
pcm = function(): buffer
|
||||
return pcm
|
||||
end,
|
||||
reset = function() end,
|
||||
stop = frames,
|
||||
})
|
||||
end
|
||||
|
||||
return Qoa
|
||||
@@ -0,0 +1,123 @@
|
||||
--!strict
|
||||
-- audio/tta: True Audio (.tta, TTA1) files around codecs/audio/Tta: an optional ID3v2 tag in front (skipped), the
|
||||
-- header and seek table, independent frames (sample-accurate seeking), APEv2 tags at the end (codecs/audio/ApeTag).
|
||||
-- Written from the TTA1 format description; no libtta / ffmpeg code. Supports 8 / 16 / 24 bits, any channel count.
|
||||
-- Not supported: password-protected files (Err.UNSUPPORTED), TTA2, ID3v2 tag contents, encoding.
|
||||
--
|
||||
-- local dec = Tta.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, readInt
|
||||
-- local audio = Tta.decode(Bytes.reader(buf)) -- Types.Audio
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Pcm = require("@formats/codecs/audio/Pcm")
|
||||
local Stream = require("@formats/codecs/audio/Stream")
|
||||
local ApeTag = require("@formats/codecs/audio/ApeTag")
|
||||
local TtaCodec = require("@formats/codecs/audio/Tta")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Tta = {
|
||||
name = "tta",
|
||||
category = "audio",
|
||||
extensions = { "tta" },
|
||||
mime = { "audio/x-tta", "audio/tta" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Tta" },
|
||||
caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, depths = { 8, 16, 24 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type OpenOptions = {
|
||||
maxFrames: number?, -- decode(): refuse longer streams (default 2^28)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
-- the size of an ID3v2 tag at the reader's start (0 when none)
|
||||
local function id3Size(r: Bytes.Reader): number
|
||||
if r:peek(3) ~= "ID3" then
|
||||
return 0
|
||||
end
|
||||
local sz = 0
|
||||
for i = 6, 9 do
|
||||
local v = r:peekU8(i)
|
||||
if v < 0 then
|
||||
return 0
|
||||
end
|
||||
sz = sz * 128 + bit32.band(v, 127)
|
||||
end
|
||||
local footer = bit32.band(math.max(r:peekU8(5), 0), 0x10) ~= 0
|
||||
return 10 + sz + (if footer then 10 else 0)
|
||||
end
|
||||
|
||||
function Tta.sniff(r: Bytes.Reader): number
|
||||
return if r:peek(4, id3Size(r)) == "TTA1" then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream
|
||||
function Tta.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?)
|
||||
local dec, err = Tta.open(r, opts)
|
||||
if not dec then
|
||||
return nil, err
|
||||
end
|
||||
local d = dec :: any
|
||||
local limit = opts and opts.maxFrames or 2 ^ 28
|
||||
if d.frames > limit or d.frames * d.channels > 2 ^ 28 then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames))
|
||||
end
|
||||
return Pcm.drain(d, d.source, limit)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> Decoder | nil, Err
|
||||
function Tta.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?)
|
||||
if type(r) == "buffer" then
|
||||
r = Bytes.reader(r :: any)
|
||||
end
|
||||
if type(r) ~= "table" or type(r.buf) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "open: expected a Reader")
|
||||
end
|
||||
local buf, base, limit = r.buf, r.base, r.limit
|
||||
local at = base + id3Size(r)
|
||||
local tags, tagInfo = ApeTag.find(buf, at, limit)
|
||||
local stop = if tagInfo then tagInfo.start else limit
|
||||
local info, err = TtaCodec.info(buf, at, stop)
|
||||
if not info then
|
||||
return nil, err
|
||||
end
|
||||
if info.channels * info.frameLength > 2 ^ 24 then
|
||||
return nil, Err.new(Err.LIMIT, info.channels .. " channels of " .. info.frameLength .. "-sample frames")
|
||||
end
|
||||
local codec = TtaCodec.decoder(info, stop)
|
||||
local frames = info.samples
|
||||
local dec: any = {
|
||||
sampleRate = info.sampleRate,
|
||||
channels = info.channels,
|
||||
frames = frames,
|
||||
duration = frames / info.sampleRate,
|
||||
bitrate = if frames > 0 then math.floor((stop - base) * 8 * info.sampleRate / frames) else 0,
|
||||
tags = tags or {},
|
||||
bitsPerSample = info.bitsPerSample,
|
||||
float = false,
|
||||
source = { format = "tta", bitDepth = info.bitsPerSample, tags = tagInfo and tagInfo.items },
|
||||
}
|
||||
local fl, count = info.frameLength, info.frames
|
||||
return Stream.packets(dec, {
|
||||
count = count,
|
||||
start = function(i: number): number
|
||||
return if i > count then frames else (i - 1) * fl
|
||||
end,
|
||||
decode = function(i: number): (number?, Err.Err?)
|
||||
return codec:frame(buf, i)
|
||||
end,
|
||||
pcm = function(): { number }
|
||||
return codec.pcm
|
||||
end,
|
||||
reset = function() end,
|
||||
stop = frames,
|
||||
scale = 1 / 2 ^ (info.bitsPerSample - 1),
|
||||
ints = true,
|
||||
})
|
||||
end
|
||||
|
||||
return Tta
|
||||
@@ -0,0 +1,231 @@
|
||||
--!strict
|
||||
-- audio/vag: Sony VAG (PlayStation SPU PS-ADPCM, .vag), and Simon & Schuster / Hyperscan KVAG (IMA ADPCM, the same
|
||||
-- extension), over codecs/audio/Adpcm. New in formats-luau; the header variants and the PS-ADPCM decoding follow
|
||||
-- vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), whose output it matches bit for bit. Supports: "VAGp" mono
|
||||
-- (versions 0, 2, 3, 4, 6, 0x20; the name field as tags.title; loop points from the frame flags, as dec.loop and
|
||||
-- meta.source.loop = { start, stop } in frames, stop exclusive), "VAGi" stereo (interleaved blocks), "KVAG" mono /
|
||||
-- stereo IMA. The output starts with the blank frame Sony's tools put first (28 silent samples), as vgmstream plays it.
|
||||
-- Encode (Audio or Decoder): mono to VAGp, stereo to VAGi (2048-byte interleave), loop points from opts.loop (frame
|
||||
-- aligned: 28 samples). Not supported: HEVAG (VAGp versions 0x00020001 / 0x00030000, Vita / PS4), the many game
|
||||
-- specific variants vgmstream knows (pGAV, VAG1 / VAG2, Jak, ...).
|
||||
--
|
||||
-- local dec = Vag.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, variant)
|
||||
-- local file = Vag.encode(audio, { loop = { start = 0, stop = audio.frames } })
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Pcm = require("@formats/codecs/audio/Pcm")
|
||||
local Adpcm = require("@formats/codecs/audio/Adpcm")
|
||||
local Decoder = require("@formats/codecs/audio/Adpcm/Decoder")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Vag = {
|
||||
name = "vag",
|
||||
category = "audio",
|
||||
extensions = { "vag" },
|
||||
mime = { "audio/x-vag" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" },
|
||||
caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 2 },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type Loop = { start: number, stop: number }
|
||||
export type DecodeOptions = {
|
||||
maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
loop: Loop?, -- loop points in frames of the input (stop exclusive), rounded out to 28-sample frames; default: the
|
||||
-- source's meta.source.loop, else none
|
||||
name: string?, -- the 16-byte name field (default: tags.title)
|
||||
interleave: number?, -- stereo: bytes per channel block (default 2048, a multiple of 16)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local HEVAG = { [0x00020001] = true, [0x00030000] = true }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Vag.sniff(r: Bytes.Reader): number
|
||||
local m = r:peek(4)
|
||||
return if m == "VAGp" or m == "VAGi" or m == "KVAG" then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Vag.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
|
||||
local dec, err = Vag.open(r)
|
||||
if not dec then
|
||||
return nil, err
|
||||
end
|
||||
local d = dec :: any
|
||||
local limit = opts and opts.maxFrames or 2 ^ 28
|
||||
if d.frames > limit or d.frames * d.channels > 2 ^ 28 then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames))
|
||||
end
|
||||
return Pcm.drain(d, { format = "vag", variant = d.variant, codec = d.codec, loop = d.loop }, limit)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Vag.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local o: EncodeOptions = opts or {}
|
||||
local src, serr = Pcm.source(value)
|
||||
if not src then
|
||||
return nil, serr
|
||||
end
|
||||
local ch, rate = src.channels, src.sampleRate
|
||||
if ch > 2 then
|
||||
return nil, Err.new(Err.ARG, "VAG holds mono or stereo")
|
||||
end
|
||||
if rate ~= math.floor(rate) or rate < 1 or rate >= 2 ^ 32 then
|
||||
return nil, Err.new(Err.ARG, "the sample rate must be a positive integer")
|
||||
end
|
||||
local il = o.interleave or 2048
|
||||
if type(il) ~= "number" or il < 16 or il % 16 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "interleave must be a multiple of 16")
|
||||
end
|
||||
local loop = o.loop
|
||||
local v = value :: any
|
||||
if loop == nil and type(v.meta) == "table" and type(v.meta.source) == "table" and type(v.meta.source.loop) == "table" then
|
||||
loop = v.meta.source.loop
|
||||
end
|
||||
local a, cerr = Pcm.collect(src)
|
||||
if not a then
|
||||
return nil, cerr
|
||||
end
|
||||
local n = a.frames
|
||||
local nf = (n + 27) // 28 -- data frames (after the blank one)
|
||||
local ls, le = -1, -1
|
||||
if loop then
|
||||
if type(loop.start) ~= "number" or type(loop.stop) ~= "number" or loop.start < 0 or loop.stop > n then
|
||||
return nil, Err.new(Err.ARG, "loop must be { start, stop } inside the audio")
|
||||
end
|
||||
ls, le = loop.start // 28, (loop.stop + 27) // 28 - 1
|
||||
if le <= ls then
|
||||
return nil, Err.new(Err.ARG, "the loop must span two 28-sample frames")
|
||||
end
|
||||
end
|
||||
local chBytes = (nf + 1) * 16
|
||||
local stride = if ch == 1 then chBytes else (chBytes + il - 1) // il * il
|
||||
local start = if ch == 1 then 0x30 else 0x800
|
||||
local out = buffer.create(start + stride * ch)
|
||||
local title = o.name or (a.tags and a.tags.title) or ""
|
||||
buffer.writestring(out, 0, if ch == 1 then "VAGp" else "VAGi")
|
||||
buffer.writeu32(out, 4, bit32.byteswap(0x20))
|
||||
if ch == 2 then
|
||||
buffer.writeu32(out, 8, il)
|
||||
end
|
||||
buffer.writeu32(out, 0x0C, bit32.byteswap(if ch == 1 then chBytes else stride))
|
||||
buffer.writeu32(out, 0x10, bit32.byteswap(rate))
|
||||
buffer.writestring(out, 0x20, string.sub(title, 1, 16))
|
||||
local st = buffer.create(8 * ch)
|
||||
local plane = buffer.create(chBytes)
|
||||
for c = 0, ch - 1 do
|
||||
buffer.fill(plane, 0, 0)
|
||||
Adpcm.psxEncode(a.samples, c, ch, n, st, c * 8, plane, 16, 16)
|
||||
for k = 0, nf - 1 do
|
||||
local flag = if k == ls then 6 elseif k == le then 3 elseif k > ls and k < le then 2 else 0
|
||||
if not loop and k == nf - 1 then
|
||||
flag = 1
|
||||
end
|
||||
buffer.writeu8(plane, 16 + k * 16 + 1, flag)
|
||||
end
|
||||
if ch == 1 then
|
||||
buffer.copy(out, start, plane, 0, chBytes)
|
||||
else
|
||||
for b = 0, stride // il - 1 do
|
||||
local take = math.clamp(chBytes - b * il, 0, il)
|
||||
if take > 0 then
|
||||
buffer.copy(out, start + (b * ch + c) * il, plane, b * il, take)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- the loop from the PS-ADPCM frame flags of channel 0 (vgmstream's reading: the first start flag 6, the first end
|
||||
-- flag 3), or nil
|
||||
local function findLoop(buf: buffer, p: number, frames: number, il: number, ch: number): Loop?
|
||||
local ls, le = -1, -1
|
||||
for k = 0, frames - 1 do
|
||||
local off = p + (k * 16) // il * il * ch + (k * 16) % il
|
||||
local flag = bit32.band(buffer.readu8(buf, off + 1), 15)
|
||||
if flag == 6 and ls < 0 then
|
||||
ls = k * 28
|
||||
elseif flag == 3 and le < 0 then
|
||||
le = k * 28 + 28
|
||||
if ls >= 0 then
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
return if ls >= 0 and le > ls then { start = ls, stop = le } else nil
|
||||
end
|
||||
|
||||
function Vag.open(r: Bytes.Reader, _opts: any?): (Types.Decoder?, Err.Err?)
|
||||
if type(r) ~= "table" or type(r.buf) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "open: expected a Reader")
|
||||
end
|
||||
local h = r:sub(0)
|
||||
local magic = h:string(4)
|
||||
local total = r.limit - r.base
|
||||
if magic == "KVAG" then
|
||||
local size, rate, stereo = h:u32le(), h:u32le(), h:u16le()
|
||||
if h.err then
|
||||
return nil, h.err
|
||||
end
|
||||
if rate < 1 or stereo > 1 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad KVAG header")
|
||||
end
|
||||
local dec: any = { sampleRate = rate, channels = stereo + 1, tags = {}, variant = "KVAG", codec = "ima" }
|
||||
local d, err = Decoder.nibbles(dec, { buf = r.buf, offset = r.base + 14, size = math.min(size, total - 14), hi = true })
|
||||
if d then
|
||||
d.bitrate = rate * 4 * (stereo + 1)
|
||||
end
|
||||
return d, err
|
||||
end
|
||||
if magic ~= "VAGp" and magic ~= "VAGi" then
|
||||
return nil, Err.new(Err.CORRUPT, "not a VAG file")
|
||||
end
|
||||
local version, il = h:u32be(), h:u32le()
|
||||
local chSize, rate = h:u32be(), h:u32be()
|
||||
local name = r:sub(0x20, 16):cstring(16)
|
||||
if h.err then
|
||||
return nil, h.err
|
||||
end
|
||||
if HEVAG[version] then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "HEVAG (Vita / PS4 VAG)")
|
||||
end
|
||||
if rate < 1 or rate >= 2 ^ 31 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad sample rate " .. rate)
|
||||
end
|
||||
local ch, start = 1, 0x30
|
||||
if magic == "VAGi" then
|
||||
ch, start = 2, 0x800
|
||||
if il < 16 or il % 16 ~= 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad interleave " .. il)
|
||||
end
|
||||
else
|
||||
il = 16
|
||||
end
|
||||
if total < start then
|
||||
return nil, Err.new(Err.TRUNCATED, "the header runs past the end")
|
||||
end
|
||||
local size = math.min(chSize * ch, total - start)
|
||||
local p = r.base + start
|
||||
local frames = math.min(chSize // 16, (size // (il * ch)) * (il // 16) + math.clamp(size % (il * ch) - (ch - 1) * il, 0, il) // 16)
|
||||
local loop = if magic == "VAGp" then findLoop(r.buf, p, frames, il, ch) else nil -- vgmstream: VAGi never loops
|
||||
local tags = {}
|
||||
if name ~= "" then
|
||||
tags.title = name
|
||||
end
|
||||
local dec: any = { sampleRate = rate, channels = ch, tags = tags, variant = magic, codec = "psx", loop = loop }
|
||||
local d, err = Decoder.interleaved(dec, { kind = "psx", buf = r.buf, offset = p, size = size, interleave = il, frames = frames * 28 })
|
||||
if d then
|
||||
d.bitrate = rate * 16 * 8 * ch // 28
|
||||
end
|
||||
return d, err
|
||||
end
|
||||
|
||||
return Vag
|
||||
@@ -1,7 +1,8 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- audio/wav/Codecs: sample conversion loops (native) into interleaved f32, and back (the encoder's quantizers).
|
||||
-- audio/wav/Codecs: sample conversion loops (native) into interleaved f32, and back (the encoder's quantizers). The
|
||||
-- ADPCM block decoders moved to codecs/audio/Adpcm.
|
||||
-- Absorbed from wav-luau fd9a909 (same author); the encoder loops are new. They never throw: audio/wav (init.luau)
|
||||
-- only calls them with ranges it has checked against the source length and the output size.
|
||||
local readu8, readi8, readu16, readi16, readu32, readi32 =
|
||||
@@ -102,160 +103,6 @@ function Codecs.law(src: buffer, off: number, dst: buffer, d: number, count: num
|
||||
end
|
||||
end
|
||||
|
||||
local IMA_STEP = buffer.create(89 * 4)
|
||||
do
|
||||
local steps = {
|
||||
7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97,
|
||||
107, 118, 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724,
|
||||
796, 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026,
|
||||
4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500,
|
||||
20350, 22385, 24623, 27086, 29794, 32767,
|
||||
}
|
||||
for i, s in steps do
|
||||
buffer.writei32(IMA_STEP, (i - 1) * 4, s)
|
||||
end
|
||||
end
|
||||
local IMA_INDEX = buffer.create(16 * 4)
|
||||
do
|
||||
local t = { -1, -1, -1, -1, 2, 4, 6, 8, -1, -1, -1, -1, 2, 4, 6, 8 }
|
||||
for i, v in t do
|
||||
buffer.writei32(IMA_INDEX, (i - 1) * 4, v)
|
||||
end
|
||||
end
|
||||
|
||||
-- IMA ADPCM (Microsoft / WAV layout), one block at src[off] of blockAlign bytes with `avail` bytes present (a
|
||||
-- truncated last block decodes the whole 8-sample groups it has). Writes interleaved f32 to dst from frame 0 and
|
||||
-- returns the frame count.
|
||||
function Codecs.imaBlock(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer): number
|
||||
if avail < 4 * ch then
|
||||
return 0
|
||||
end
|
||||
-- groups of 8 samples per channel (4 bytes each) after the per-channel headers
|
||||
local groups = (avail - 4 * ch) // (4 * ch)
|
||||
local frames = math.min(spb, 1 + groups * 8)
|
||||
for c = 0, ch - 1 do
|
||||
local pred = readi16(src, off + c * 4)
|
||||
local index = readu8(src, off + c * 4 + 2)
|
||||
if index > 88 then
|
||||
index = 88
|
||||
end
|
||||
writef32(dst, c * 4, pred / 32768)
|
||||
local f = 1
|
||||
local g = 0
|
||||
while f < frames do
|
||||
local p = off + 4 * ch + (g * ch + c) * 4
|
||||
for k = 0, 7 do
|
||||
if f >= frames then
|
||||
break
|
||||
end
|
||||
local b = readu8(src, p + rshift(k, 1))
|
||||
local nib = if band(k, 1) == 0 then band(b, 15) else rshift(b, 4)
|
||||
local step = buffer.readi32(IMA_STEP, index * 4)
|
||||
local diff = rshift(step, 3)
|
||||
if band(nib, 1) ~= 0 then
|
||||
diff += rshift(step, 2)
|
||||
end
|
||||
if band(nib, 2) ~= 0 then
|
||||
diff += rshift(step, 1)
|
||||
end
|
||||
if band(nib, 4) ~= 0 then
|
||||
diff += step
|
||||
end
|
||||
if band(nib, 8) ~= 0 then
|
||||
pred -= diff
|
||||
else
|
||||
pred += diff
|
||||
end
|
||||
if pred > 32767 then
|
||||
pred = 32767
|
||||
elseif pred < -32768 then
|
||||
pred = -32768
|
||||
end
|
||||
index += buffer.readi32(IMA_INDEX, nib * 4)
|
||||
if index < 0 then
|
||||
index = 0
|
||||
elseif index > 88 then
|
||||
index = 88
|
||||
end
|
||||
writef32(dst, (f * ch + c) * 4, pred / 32768)
|
||||
f += 1
|
||||
end
|
||||
g += 1
|
||||
end
|
||||
end
|
||||
return frames
|
||||
end
|
||||
|
||||
local MS_ADAPT = buffer.create(16 * 4)
|
||||
do
|
||||
local t = { 230, 230, 230, 230, 307, 409, 512, 614, 768, 614, 512, 409, 307, 230, 230, 230 }
|
||||
for i, v in t do
|
||||
buffer.writei32(MS_ADAPT, (i - 1) * 4, v)
|
||||
end
|
||||
end
|
||||
|
||||
-- MS ADPCM, one block. coefs: i32 pairs (coef1, coef2) x ncoef (256 = 1.0). state: 5 * ch i32 scratch.
|
||||
-- Returns the frame count (a truncated last block decodes the whole bytes it has).
|
||||
function Codecs.msBlock(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer,
|
||||
coefs: buffer, ncoef: number, state: buffer): number
|
||||
local hdr = 7 * ch
|
||||
if avail < hdr or ncoef < 1 then
|
||||
return 0
|
||||
end
|
||||
local frames = math.min(spb, 2 + ((avail - hdr) * 2) // ch)
|
||||
-- state per channel: c1, c2, idelta, s1, s2 (5 i32)
|
||||
for c = 0, ch - 1 do
|
||||
local pi = readu8(src, off + c)
|
||||
if pi >= ncoef then
|
||||
pi = ncoef - 1
|
||||
end
|
||||
local idelta = readi16(src, off + ch + c * 2)
|
||||
local s1 = readi16(src, off + 3 * ch + c * 2)
|
||||
local s2 = readi16(src, off + 5 * ch + c * 2)
|
||||
local so = c * 20
|
||||
buffer.writei32(state, so, buffer.readi32(coefs, pi * 8))
|
||||
buffer.writei32(state, so + 4, buffer.readi32(coefs, pi * 8 + 4))
|
||||
buffer.writei32(state, so + 8, idelta)
|
||||
buffer.writei32(state, so + 12, s1)
|
||||
buffer.writei32(state, so + 16, s2)
|
||||
writef32(dst, c * 4, s2 / 32768)
|
||||
if frames > 1 then
|
||||
writef32(dst, (ch + c) * 4, s1 / 32768)
|
||||
end
|
||||
end
|
||||
-- nibbles, high first, channels interleaved per nibble
|
||||
local total = (frames - 2) * ch
|
||||
for k = 0, total - 1 do
|
||||
local b = readu8(src, off + hdr + rshift(k, 1))
|
||||
local nib = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15)
|
||||
local c = k % ch
|
||||
local so = c * 20
|
||||
local c1, c2 = buffer.readi32(state, so), buffer.readi32(state, so + 4)
|
||||
local idelta = buffer.readi32(state, so + 8)
|
||||
local s1, s2 = buffer.readi32(state, so + 12), buffer.readi32(state, so + 16)
|
||||
local p = s1 * c1 + s2 * c2
|
||||
p = if p >= 0 then p // 256 else -((-p) // 256)
|
||||
local sn = if nib >= 8 then nib - 16 else nib
|
||||
p += sn * idelta
|
||||
if p > 32767 then
|
||||
p = 32767
|
||||
elseif p < -32768 then
|
||||
p = -32768
|
||||
end
|
||||
idelta = (buffer.readi32(MS_ADAPT, nib * 4) * idelta) // 256
|
||||
if idelta < 16 then
|
||||
idelta = 16
|
||||
elseif idelta > 2796202 then -- INT_MAX / 768, as ffmpeg
|
||||
idelta = 2796202
|
||||
end
|
||||
buffer.writei32(state, so + 8, idelta)
|
||||
buffer.writei32(state, so + 12, p)
|
||||
buffer.writei32(state, so + 16, s1)
|
||||
writef32(dst, (2 * ch + k) * 4, p / 32768)
|
||||
end
|
||||
return frames
|
||||
end
|
||||
|
||||
-- copy frames from a block cache into the output: count f32 values
|
||||
function Codecs.copy(src: buffer, sOff: number, dst: buffer, dOff: number, count: number)
|
||||
buffer.copy(dst, dOff * 4, src, sOff * 4, count * 4)
|
||||
|
||||
@@ -21,6 +21,7 @@ local Types = require("@formats/Types")
|
||||
local Pcm = require("@formats/codecs/audio/Pcm")
|
||||
local Riff = require("@formats/containers/Riff")
|
||||
local Codecs = require("@formats/audio/wav/Codecs")
|
||||
local Adpcm = require("@formats/codecs/audio/Adpcm")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Wav = {
|
||||
@@ -28,7 +29,7 @@ local Wav = {
|
||||
category = "audio",
|
||||
extensions = { "wav", "wave", "rf64", "bw64" },
|
||||
mime = { "audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/audio/Pcm" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/audio/Pcm", "codecs/audio/Adpcm" },
|
||||
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true },
|
||||
}
|
||||
|
||||
@@ -488,8 +489,7 @@ function Wav.open(r: Bytes.Reader, _opts: OpenOptions?): (Decoder?, Err.Err?)
|
||||
spb = computed
|
||||
end
|
||||
-- coefficients from the fmt extension, else the 7 standard pairs
|
||||
local c1 = { 256, 512, 0, 192, 240, 460, 392 }
|
||||
local c2 = { 0, -256, 0, 64, 0, -208, -232 }
|
||||
local c1, c2 = Adpcm.MS_COEF1, Adpcm.MS_COEF2
|
||||
local ncoef = 7
|
||||
if fmt.avail >= 22 then
|
||||
local k = u16(fmt.body + 20)
|
||||
@@ -592,9 +592,9 @@ function Decoder.read(self: Decoder, maxFrames: number, out: buffer?): (buffer,
|
||||
local avail = math.min(ba, self.dataOffset + self.dataSize - off)
|
||||
local got
|
||||
if kind == "ima_adpcm" then
|
||||
got = Codecs.imaBlock(self._buf, off, avail, ch, spb, cache)
|
||||
got = Adpcm.imaWav(self._buf, off, avail, ch, spb, cache, 0)
|
||||
else
|
||||
got = Codecs.msBlock(self._buf, off, avail, ch, spb, cache, self._coefs :: buffer, self._ncoef,
|
||||
got = Adpcm.msBlock(self._buf, off, avail, ch, spb, cache, 0, self._coefs :: buffer, self._ncoef,
|
||||
self._state :: buffer)
|
||||
end
|
||||
self._cacheBlock = block
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
--!strict
|
||||
-- audio/wavpack: WavPack (.wv) files: the block sequence around codecs/audio/WavPack, APEv2 tags, the .wvc correction
|
||||
-- file of hybrid lossless files. Written from the WavPack 5 file format document (David Bryant) and the WavPack 5.9.0
|
||||
-- library's file handling (open_utils.c; BSD 3-clause, licenses/wavpack-LICENSE.txt).
|
||||
-- Supports: lossless and hybrid streams, integer 8 - 32 bit and 32-bit float, 1 - 4096 channels (WAV order, as the
|
||||
-- encoder stores them), non-standard sample rates, the correction file (opts.correction, else opts.resolve("<name>c")
|
||||
-- on hosts with files) which makes a hybrid file lossless, garbage between blocks (resync), sample-accurate seeking
|
||||
-- (every block is independent), APEv2 tags at the end (codecs/audio/ApeTag). Without a correction file a hybrid file
|
||||
-- decodes lossy (as wvunpack does). Not supported: DSD (Err.UNSUPPORTED), WavPack 1 - 3 files, encoding.
|
||||
--
|
||||
-- local dec = WavPack.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, float, hybrid, lossless, ...
|
||||
-- local f32, n = dec:read(4096)
|
||||
-- local i32, n = dec:readInt(4096) -- integer streams: the samples as wvunpack writes them
|
||||
-- local audio = WavPack.decode(Bytes.reader(buf)) -- Types.Audio
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Pcm = require("@formats/codecs/audio/Pcm")
|
||||
local Stream = require("@formats/codecs/audio/Stream")
|
||||
local ApeTag = require("@formats/codecs/audio/ApeTag")
|
||||
local WavPackCodec = require("@formats/codecs/audio/WavPack")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local WavPack = {
|
||||
name = "wavpack",
|
||||
category = "audio",
|
||||
extensions = { "wv" },
|
||||
mime = { "audio/x-wavpack", "audio/wavpack" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/WavPack" },
|
||||
caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, hybrid = true, float = true, depths = { 8, 12, 16, 20, 24, 32 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type OpenOptions = {
|
||||
correction: (buffer | string)?, -- the .wvc file of a hybrid file (default: opts.resolve(name .. "c") when given)
|
||||
resolve: ((uri: string) -> buffer?)?, -- sibling files (the api passes it for paths)
|
||||
name: string?, -- the file name (the api passes it)
|
||||
maxFrames: number?, -- decode(): refuse longer streams (default 2^28)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function WavPack.sniff(r: Bytes.Reader): number
|
||||
if r:peek(4) ~= "wvpk" then
|
||||
return 0
|
||||
end
|
||||
local v = r:peekU8(9)
|
||||
return if v == 4 then 1 else 0.5
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream
|
||||
function WavPack.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?)
|
||||
local dec, err = WavPack.open(r, opts)
|
||||
if not dec then
|
||||
return nil, err
|
||||
end
|
||||
local d = dec :: any
|
||||
local limit = opts and opts.maxFrames or 2 ^ 28
|
||||
if d.frames > limit or d.frames * d.channels > 2 ^ 28 then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames))
|
||||
end
|
||||
return Pcm.drain(d, d.source, limit)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
type Index = { offsets: { { number } }, starts: { number }, samples: { number }, total: number, first: number, md5: string? }
|
||||
|
||||
-- index(buf, base, limit) -> the frames (block offsets per frame) of a .wv / .wvc block sequence
|
||||
local function index(buf: buffer, base: number, limit: number): (Index?, string?)
|
||||
local at = base
|
||||
local idx: Index = { offsets = {}, starts = {}, samples = {}, total = -1, first = -1 }
|
||||
local cur: { number }? = nil
|
||||
local initial = -1
|
||||
local resyncs = 0
|
||||
while at + 32 <= limit do
|
||||
local h = WavPackCodec.header(buf, at, limit)
|
||||
if not h then
|
||||
-- garbage (or a tag) between blocks: search the next header
|
||||
if resyncs > 64 then
|
||||
break
|
||||
end
|
||||
local s = buffer.readstring(buf, at + 1, math.min(limit - at - 1, 1048576))
|
||||
local k = string.find(s, "wvpk", 1, true)
|
||||
if not k then
|
||||
break
|
||||
end
|
||||
at = at + k
|
||||
resyncs += 1
|
||||
continue
|
||||
end
|
||||
if initial < 0 then
|
||||
initial = h.index
|
||||
idx.total = h.total
|
||||
end
|
||||
if h.samples > 0 then
|
||||
if bit32.band(h.flags, WavPackCodec.INITIAL) ~= 0 or not cur then
|
||||
cur = { at }
|
||||
table.insert(idx.offsets, cur)
|
||||
table.insert(idx.starts, h.index - initial)
|
||||
table.insert(idx.samples, h.samples)
|
||||
if idx.first < 0 then
|
||||
idx.first = at
|
||||
end
|
||||
else
|
||||
table.insert(cur, at)
|
||||
end
|
||||
if bit32.band(h.flags, WavPackCodec.FINAL) ~= 0 then
|
||||
cur = nil
|
||||
end
|
||||
else
|
||||
idx.md5 = idx.md5 or WavPackCodec.md5(buf, at, limit)
|
||||
end
|
||||
at += h.size
|
||||
end
|
||||
if idx.first < 0 then
|
||||
return nil, "no audio blocks"
|
||||
end
|
||||
return idx, nil
|
||||
end
|
||||
|
||||
local function correctionFile(opts: OpenOptions?): buffer?
|
||||
if not opts then
|
||||
return nil
|
||||
end
|
||||
local c = opts.correction
|
||||
if type(c) == "string" then
|
||||
return buffer.fromstring(c)
|
||||
elseif type(c) == "buffer" then
|
||||
return c
|
||||
end
|
||||
if type(opts.resolve) == "function" and type(opts.name) == "string" then
|
||||
local base = string.match(opts.name, "([^/\\]+)$")
|
||||
if base then
|
||||
local ok, b = pcall(opts.resolve, base .. "c")
|
||||
if ok and type(b) == "buffer" then
|
||||
return b
|
||||
end
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- open(r, opts?) -> Decoder | nil, Err
|
||||
function WavPack.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?)
|
||||
if type(r) == "buffer" then
|
||||
r = Bytes.reader(r :: any)
|
||||
end
|
||||
if type(r) ~= "table" or type(r.buf) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "open: expected a Reader")
|
||||
end
|
||||
local buf, base, limit = r.buf, r.base, r.limit
|
||||
local tags, tagInfo = ApeTag.find(buf, base, limit)
|
||||
local stop = if tagInfo then tagInfo.start else limit
|
||||
local idx, ierr = index(buf, base, stop)
|
||||
if not idx then
|
||||
return nil, Err.from(ierr, base)
|
||||
end
|
||||
local info, err = WavPackCodec.info(buf, idx.first, stop)
|
||||
if not info then
|
||||
return nil, err
|
||||
end
|
||||
if info.channels > 256 then
|
||||
return nil, Err.new(Err.LIMIT, info.channels .. " channels")
|
||||
end
|
||||
local count = #idx.offsets
|
||||
local last = idx.starts[count] + idx.samples[count]
|
||||
local frames = if idx.total >= 0 then math.min(idx.total, last) else last
|
||||
-- the correction file: its frames by start sample
|
||||
local cbuf = if info.hybrid then correctionFile(opts) else nil
|
||||
local cfor: { [number]: { number } } = {}
|
||||
if cbuf then
|
||||
local cidx = index(cbuf, 0, buffer.len(cbuf))
|
||||
if cidx then
|
||||
for i, offs in cidx.offsets do
|
||||
cfor[cidx.starts[i]] = offs
|
||||
end
|
||||
else
|
||||
cbuf = nil
|
||||
end
|
||||
end
|
||||
local codec = WavPackCodec.decoder(info.channels)
|
||||
local dec: any = {
|
||||
sampleRate = info.sampleRate,
|
||||
channels = info.channels,
|
||||
frames = frames,
|
||||
duration = frames / info.sampleRate,
|
||||
bitrate = if frames > 0 then math.floor((stop - base) * 8 * info.sampleRate / frames) else 0,
|
||||
tags = tags or {},
|
||||
bitsPerSample = info.bitsPerSample,
|
||||
float = info.float,
|
||||
hybrid = info.hybrid,
|
||||
lossless = not info.hybrid or cbuf ~= nil,
|
||||
channelMask = info.channelMask,
|
||||
md5 = idx.md5,
|
||||
source = { format = "wavpack", bitDepth = info.bitsPerSample, float = info.float, hybrid = info.hybrid, correction = cbuf ~= nil, version = info.version, tags = tagInfo and tagInfo.items },
|
||||
}
|
||||
local starts, offsets = idx.starts, idx.offsets
|
||||
return Stream.packets(dec, {
|
||||
count = count,
|
||||
start = function(i: number): number
|
||||
return if i > count then last else starts[i]
|
||||
end,
|
||||
decode = function(i: number): (number?, Err.Err?)
|
||||
local co = if cbuf then cfor[starts[i]] else nil
|
||||
return codec:frame(buf, offsets[i], if co then cbuf else nil, co)
|
||||
end,
|
||||
pcm = function(): { number }
|
||||
return codec.pcm
|
||||
end,
|
||||
reset = function() end,
|
||||
stop = frames,
|
||||
scale = if info.float then 1 else 1 / 2 ^ (info.bytesPerSample * 8 - 1),
|
||||
ints = not info.float,
|
||||
})
|
||||
end
|
||||
|
||||
return WavPack
|
||||
@@ -0,0 +1,916 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/audio/Ac3/Decode: one AC-3 syncframe (6 audio blocks of 256 samples) -> PCM. Written from ATSC A/52:2018
|
||||
-- (section 5.3 syntax, 7.1 exponents, 7.2 parametric bit allocation with delta bit allocation, 7.3 mantissas with
|
||||
-- grouping and dither, 7.4 coupling with phase flags, 7.5 rematrixing, 7.7.1 dynamic range, 7.9 the 512 / 2 x 256
|
||||
-- inverse transforms with block switching) on codecs/audio/Mdct; no third-party code. The bit reader is module state
|
||||
-- over a frame the caller pads by PAD bytes; every section stops when the position passes the frame. No error /
|
||||
-- assert: failures return nil, "message".
|
||||
local T = require("@formats/codecs/audio/Ac3/Tables")
|
||||
local Mdct = require("@formats/codecs/audio/Mdct")
|
||||
|
||||
local readu32, bswap, extract, band, rshift = buffer.readu32, bit32.byteswap, bit32.extract, bit32.band, bit32.rshift
|
||||
local max, min = math.max, math.min
|
||||
|
||||
local Decode = {}
|
||||
Decode.PAD = 2048
|
||||
|
||||
local CPL, LFE = 7, 6 -- channel slots: 1 .. 5 full bandwidth, 6 LFE, 7 the coupling channel
|
||||
local NFCHANS = { [0] = 2, 1, 2, 3, 3, 4, 4, 5 }
|
||||
|
||||
local SLOWDEC, FASTDEC, SLOWGAIN, DBPBTAB, FLOORTAB, FASTGAIN = T.SLOWDEC, T.FASTDEC, T.SLOWGAIN, T.DBPBTAB, T.FLOORTAB, T.FASTGAIN
|
||||
local BNDTAB, BNDSZ, MASKTAB, LATAB, HTH, BAPTAB = T.BNDTAB, T.BNDSZ, T.MASKTAB, T.LATAB, T.HTH, T.BAPTAB
|
||||
|
||||
-- 2^-e for the exponents 0 .. 24
|
||||
local POW2 = table.create(32, 0)
|
||||
for e = 0, 31 do
|
||||
POW2[e + 1] = 2 ^ -e
|
||||
end
|
||||
-- symmetric quantiser values (Tables 7.19 - 7.23): Q1[code + 1] etc.
|
||||
local function levels(n: number): { number }
|
||||
local t = {}
|
||||
for c = 0, n - 1 do
|
||||
t[c + 1] = (2 * c - (n - 1)) / n
|
||||
end
|
||||
return t
|
||||
end
|
||||
local Q1, Q2, Q3, Q4, Q5 = levels(3), levels(5), levels(7), levels(11), levels(15)
|
||||
-- bits of the asymmetric quantisers (bap 6 .. 15)
|
||||
local QBITS = { [6] = 5, [7] = 6, [8] = 7, [9] = 8, [10] = 9, [11] = 10, [12] = 11, [13] = 12, [14] = 14, [15] = 16 }
|
||||
|
||||
local WINDOW = Mdct.window("kbd", 512, 5) :: { number }
|
||||
local PLAN512 = Mdct.new(512) :: Mdct.Plan
|
||||
local PLAN256 = Mdct.new(256) :: Mdct.Plan
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ bit reader
|
||||
local B: buffer = buffer.create(0)
|
||||
local P = 0
|
||||
|
||||
local function bits(n: number): number
|
||||
if n <= 0 then
|
||||
return 0
|
||||
end
|
||||
if n > 24 then
|
||||
local hi = bits(n - 16)
|
||||
return hi * 65536 + bits(16)
|
||||
end
|
||||
local w = bswap(readu32(B, rshift(P, 3)))
|
||||
local v = extract(w, 32 - band(P, 7) - n, n)
|
||||
P += n
|
||||
return v
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ state
|
||||
export type State = {
|
||||
-- the frame header
|
||||
fscod: number,
|
||||
acmod: number,
|
||||
lfeon: boolean,
|
||||
nfchans: number,
|
||||
channels: number, -- output channels
|
||||
map: { number }, -- output index of slots 1 .. 6
|
||||
drc: number, -- the dynamic range scale (0 = off)
|
||||
-- per channel slot (1 .. 7)
|
||||
exp: { { number } },
|
||||
bap: { { number } },
|
||||
coef: { { number } },
|
||||
delay: { { number } },
|
||||
endmant: { number },
|
||||
chexpstr: { number },
|
||||
blksw: { boolean },
|
||||
dithflag: { boolean },
|
||||
fsnroffst: { number },
|
||||
fgaincod: { number },
|
||||
dbaOn: { boolean },
|
||||
dbaOffst: { { number } },
|
||||
dbaLen: { { number } },
|
||||
dbaBa: { { number } },
|
||||
-- coupling
|
||||
cplinu: boolean,
|
||||
chincpl: { boolean },
|
||||
phsflginu: boolean,
|
||||
cplbegf: number,
|
||||
cplendf: number,
|
||||
cplbndstrc: { boolean }, -- [sbnd + 1], sbnd = 0 .. 17 (absolute sub-band)
|
||||
cplco: { { number } }, -- [ch][sbnd + 1]
|
||||
phsflg: { boolean }, -- [sbnd + 1]
|
||||
cplfleak: number,
|
||||
cplsleak: number,
|
||||
rematflg: { boolean },
|
||||
-- bit allocation parameters
|
||||
sdcycod: number,
|
||||
fdcycod: number,
|
||||
sgaincod: number,
|
||||
dbpbcod: number,
|
||||
floorcod: number,
|
||||
csnroffst: number,
|
||||
dynrng: { number }, -- gain for Ch1 / Ch2
|
||||
seed: number, -- dither generator
|
||||
-- scratch
|
||||
psd: { number },
|
||||
bndpsd: { number },
|
||||
excite: { number },
|
||||
mask: { number },
|
||||
y: { number },
|
||||
pcm: { number },
|
||||
blocks: { number }, -- the bit offset of each audio block in the last frame (for tools)
|
||||
}
|
||||
|
||||
local function arrays(n: number, size: number, v: any): { any }
|
||||
local t = {}
|
||||
for i = 1, n do
|
||||
t[i] = table.create(size, v)
|
||||
end
|
||||
return t
|
||||
end
|
||||
|
||||
function Decode.state(): State
|
||||
return {
|
||||
fscod = 0,
|
||||
acmod = 2,
|
||||
lfeon = false,
|
||||
nfchans = 2,
|
||||
channels = 2,
|
||||
map = { 1, 2, 3, 4, 5, 6 },
|
||||
drc = 0,
|
||||
exp = arrays(7, 264, 0),
|
||||
bap = arrays(7, 264, 0),
|
||||
coef = arrays(7, 256, 0),
|
||||
delay = arrays(6, 256, 0),
|
||||
endmant = table.create(7, 0),
|
||||
chexpstr = table.create(7, 0),
|
||||
blksw = table.create(7, false),
|
||||
dithflag = table.create(7, false),
|
||||
fsnroffst = table.create(7, 0),
|
||||
fgaincod = table.create(7, 0),
|
||||
dbaOn = table.create(7, false),
|
||||
dbaOffst = arrays(7, 8, 0),
|
||||
dbaLen = arrays(7, 8, 0),
|
||||
dbaBa = arrays(7, 8, 0),
|
||||
cplinu = false,
|
||||
chincpl = table.create(7, false),
|
||||
phsflginu = false,
|
||||
cplbegf = 0,
|
||||
cplendf = 0,
|
||||
cplbndstrc = table.create(18, false),
|
||||
cplco = arrays(5, 18, 0),
|
||||
phsflg = table.create(18, false),
|
||||
cplfleak = 0,
|
||||
cplsleak = 0,
|
||||
rematflg = table.create(4, false),
|
||||
sdcycod = 0,
|
||||
fdcycod = 0,
|
||||
sgaincod = 0,
|
||||
dbpbcod = 0,
|
||||
floorcod = 0,
|
||||
csnroffst = 0,
|
||||
dynrng = { 1, 1 },
|
||||
seed = 1,
|
||||
psd = table.create(256, 0),
|
||||
bndpsd = table.create(50, 0),
|
||||
excite = table.create(50, 0),
|
||||
mask = table.create(50, 0),
|
||||
y = table.create(512, 0),
|
||||
pcm = table.create(1536 * 2, 0),
|
||||
blocks = table.create(6, 0),
|
||||
}
|
||||
end
|
||||
|
||||
-- reset(st): forget the overlap (before a seek)
|
||||
function Decode.reset(st: State)
|
||||
for _, d in st.delay do
|
||||
for i = 1, 256 do
|
||||
d[i] = 0
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ exponents
|
||||
-- read ngrps grouped exponents (7 bits = 3 deltas each) after absexp into e[first + 1 ..] (bins first ..), grpsize
|
||||
-- bins per delta; false when an exponent leaves 0 .. 24
|
||||
local function exponents(e: { number }, absexp: number, ngrps: number, grpsize: number, first: number): boolean
|
||||
local prev = absexp
|
||||
local k = first + 1
|
||||
for _ = 1, ngrps do
|
||||
local g = bits(7)
|
||||
if g >= 125 then
|
||||
return false
|
||||
end
|
||||
local d1 = g // 25
|
||||
local d2 = (g % 25) // 5
|
||||
local d3 = g % 5
|
||||
for m = 1, 3 do
|
||||
local d = if m == 1 then d1 elseif m == 2 then d2 else d3
|
||||
prev += d - 2
|
||||
if prev < 0 or prev > 24 then
|
||||
return false
|
||||
end
|
||||
for _ = 1, grpsize do
|
||||
e[k] = prev
|
||||
k += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ bit allocation
|
||||
local function logadd(a: number, b: number): number
|
||||
local c = a - b
|
||||
local adr = min(rshift(if c >= 0 then c else -c, 1), 255)
|
||||
return if c >= 0 then a + LATAB[adr + 1] else b + LATAB[adr + 1]
|
||||
end
|
||||
|
||||
local function lowcomp(a: number, b0: number, b1: number, bin: number): number
|
||||
if bin < 7 then
|
||||
if b0 + 256 == b1 then
|
||||
a = 384
|
||||
elseif b0 > b1 then
|
||||
a = max(0, a - 64)
|
||||
end
|
||||
elseif bin < 20 then
|
||||
if b0 + 256 == b1 then
|
||||
a = 320
|
||||
elseif b0 > b1 then
|
||||
a = max(0, a - 64)
|
||||
end
|
||||
else
|
||||
a = max(0, a - 128)
|
||||
end
|
||||
return a
|
||||
end
|
||||
|
||||
-- section 7.2.2: the bap of bins [start, stop) of channel slot ch
|
||||
local function allocate(st: State, ch: number, start: number, stop: number, fgain: number, snroffset: number, isLfe: boolean)
|
||||
local e, bap = st.exp[ch], st.bap[ch]
|
||||
local psd, bndpsd, excite, mask = st.psd, st.bndpsd, st.excite, st.mask
|
||||
local sdecay, fdecay = SLOWDEC[st.sdcycod + 1], FASTDEC[st.fdcycod + 1]
|
||||
local sgain, dbknee, floor = SLOWGAIN[st.sgaincod + 1], DBPBTAB[st.dbpbcod + 1], FLOORTAB[st.floorcod + 1]
|
||||
if floor >= 0x8000 then
|
||||
floor -= 0x10000 -- 0xf800: a negative 16-bit value
|
||||
end
|
||||
for bin = start, stop - 1 do
|
||||
psd[bin + 1] = 3072 - e[bin + 1] * 128
|
||||
end
|
||||
-- PSD integration
|
||||
local j = start
|
||||
local k = MASKTAB[start + 1]
|
||||
local lastbin
|
||||
repeat
|
||||
lastbin = min(BNDTAB[k + 1] + BNDSZ[k + 1], stop)
|
||||
local v = psd[j + 1]
|
||||
j += 1
|
||||
while j < lastbin do
|
||||
v = logadd(v, psd[j + 1])
|
||||
j += 1
|
||||
end
|
||||
bndpsd[k + 1] = v
|
||||
k += 1
|
||||
until stop <= lastbin
|
||||
-- excitation
|
||||
local bndstrt = MASKTAB[start + 1]
|
||||
local bndend = MASKTAB[stop] + 1
|
||||
local fastleak, slowleak = 0, 0
|
||||
local begin
|
||||
if bndstrt == 0 then
|
||||
local lc = 0
|
||||
lc = lowcomp(lc, bndpsd[1], bndpsd[2], 0)
|
||||
excite[1] = bndpsd[1] - fgain - lc
|
||||
lc = lowcomp(lc, bndpsd[2], bndpsd[3], 1)
|
||||
excite[2] = bndpsd[2] - fgain - lc
|
||||
begin = 7
|
||||
for bin = 2, 6 do
|
||||
local last = isLfe and bin == 6
|
||||
if not last then
|
||||
lc = lowcomp(lc, bndpsd[bin + 1], bndpsd[bin + 2], bin)
|
||||
end
|
||||
fastleak = bndpsd[bin + 1] - fgain
|
||||
slowleak = bndpsd[bin + 1] - sgain
|
||||
excite[bin + 1] = fastleak - lc
|
||||
if not last and bndpsd[bin + 1] <= bndpsd[bin + 2] then
|
||||
begin = bin + 1
|
||||
break
|
||||
end
|
||||
end
|
||||
for bin = begin, min(bndend, 22) - 1 do
|
||||
if not (isLfe and bin == 6) then
|
||||
lc = lowcomp(lc, bndpsd[bin + 1], bndpsd[bin + 2], bin)
|
||||
end
|
||||
fastleak = max(fastleak - fdecay, bndpsd[bin + 1] - fgain)
|
||||
slowleak = max(slowleak - sdecay, bndpsd[bin + 1] - sgain)
|
||||
excite[bin + 1] = max(fastleak - lc, slowleak)
|
||||
end
|
||||
begin = 22
|
||||
else
|
||||
begin = bndstrt
|
||||
fastleak = st.cplfleak * 256 + 768
|
||||
slowleak = st.cplsleak * 256 + 768
|
||||
end
|
||||
for bin = begin, bndend - 1 do
|
||||
fastleak = max(fastleak - fdecay, bndpsd[bin + 1] - fgain)
|
||||
slowleak = max(slowleak - sdecay, bndpsd[bin + 1] - sgain)
|
||||
excite[bin + 1] = max(fastleak, slowleak)
|
||||
end
|
||||
-- masking curve
|
||||
local hth = HTH[st.fscod + 1]
|
||||
for bin = bndstrt, bndend - 1 do
|
||||
local x = excite[bin + 1]
|
||||
local p = bndpsd[bin + 1]
|
||||
if p < dbknee then
|
||||
x += (dbknee - p) // 4
|
||||
end
|
||||
mask[bin + 1] = max(x, hth[bin + 1])
|
||||
end
|
||||
-- delta bit allocation
|
||||
if st.dbaOn[ch] then
|
||||
local offs, lens, bas = st.dbaOffst[ch], st.dbaLen[ch], st.dbaBa[ch]
|
||||
local b = 0
|
||||
for seg = 1, #offs do
|
||||
b += offs[seg]
|
||||
local ba = bas[seg]
|
||||
local delta = if ba >= 4 then (ba - 3) * 128 else (ba - 4) * 128
|
||||
for _ = 1, lens[seg] do
|
||||
if b < 50 then
|
||||
mask[b + 1] += delta
|
||||
end
|
||||
b += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
-- bit allocation pointers
|
||||
local i = start
|
||||
j = MASKTAB[start + 1]
|
||||
repeat
|
||||
lastbin = min(BNDTAB[j + 1] + BNDSZ[j + 1], stop)
|
||||
local m = mask[j + 1] - snroffset - floor
|
||||
if m < 0 then
|
||||
m = 0
|
||||
end
|
||||
m = band(m, 0x1fe0) + floor
|
||||
while i < lastbin do
|
||||
local adr = (psd[i + 1] - m) // 32
|
||||
bap[i + 1] = BAPTAB[min(63, max(0, adr)) + 1]
|
||||
i += 1
|
||||
end
|
||||
j += 1
|
||||
until stop <= lastbin
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ mantissas
|
||||
-- grouped mantissa state (bap 1, 2, 4 share groups across channels within a block)
|
||||
local G1, G2, G4 = table.create(3, 0), table.create(3, 0), table.create(2, 0)
|
||||
local n1, n2, n4 = 0, 0, 0
|
||||
|
||||
local function dither(st: State): number
|
||||
local s = (st.seed * 1664525 + 1013904223) % 4294967296
|
||||
st.seed = s
|
||||
return (s / 2147483648 - 1) * 0.707
|
||||
end
|
||||
|
||||
-- the mantissas of bins [start, stop) of slot ch into out[], scaled by their exponents (bap 0: dither when asked)
|
||||
local function mantissas(st: State, ch: number, start: number, stop: number, out: { number }, dith: boolean)
|
||||
local e, bap = st.exp[ch], st.bap[ch]
|
||||
for bin = start, stop - 1 do
|
||||
local b = bap[bin + 1]
|
||||
local v
|
||||
if b == 0 then
|
||||
v = if dith then dither(st) else 0
|
||||
elseif b == 1 then
|
||||
if n1 == 0 then
|
||||
local g = bits(5)
|
||||
if g > 26 then
|
||||
g = 26
|
||||
end
|
||||
G1[1], G1[2], G1[3] = Q1[g // 9 + 1], Q1[(g % 9) // 3 + 1], Q1[g % 3 + 1]
|
||||
n1 = 3
|
||||
end
|
||||
v = G1[4 - n1]
|
||||
n1 -= 1
|
||||
elseif b == 2 then
|
||||
if n2 == 0 then
|
||||
local g = bits(7)
|
||||
if g > 124 then
|
||||
g = 124
|
||||
end
|
||||
G2[1], G2[2], G2[3] = Q2[g // 25 + 1], Q2[(g % 25) // 5 + 1], Q2[g % 5 + 1]
|
||||
n2 = 3
|
||||
end
|
||||
v = G2[4 - n2]
|
||||
n2 -= 1
|
||||
elseif b == 3 then
|
||||
v = Q3[min(bits(3), 6) + 1]
|
||||
elseif b == 4 then
|
||||
if n4 == 0 then
|
||||
local g = bits(7)
|
||||
if g > 120 then
|
||||
g = 120
|
||||
end
|
||||
G4[1], G4[2] = Q4[g // 11 + 1], Q4[g % 11 + 1]
|
||||
n4 = 2
|
||||
end
|
||||
v = G4[3 - n4]
|
||||
n4 -= 1
|
||||
elseif b == 5 then
|
||||
v = Q5[min(bits(4), 14) + 1]
|
||||
else
|
||||
local nb = QBITS[b]
|
||||
local m = bits(nb)
|
||||
local half = 2 ^ (nb - 1)
|
||||
if m >= half then
|
||||
m -= 2 * half
|
||||
end
|
||||
v = m / half
|
||||
end
|
||||
out[bin + 1] = v * POW2[e[bin + 1] + 1]
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ audio block
|
||||
local function readDba(st: State, ch: number)
|
||||
local nseg = bits(3) + 1
|
||||
local offs, lens, bas = st.dbaOffst[ch], st.dbaLen[ch], st.dbaBa[ch]
|
||||
table.clear(offs)
|
||||
table.clear(lens)
|
||||
table.clear(bas)
|
||||
for seg = 1, nseg do
|
||||
offs[seg] = bits(5)
|
||||
lens[seg] = bits(4)
|
||||
bas[seg] = bits(3)
|
||||
end
|
||||
end
|
||||
|
||||
local EXPGRP = { 3, 6, 12 } -- bins per group of 3 deltas, by strategy (D15 / D25 / D45)
|
||||
|
||||
local function audblk(st: State, blk: number, limit: number): (boolean?, string?)
|
||||
local nf, acmod = st.nfchans, st.acmod
|
||||
for ch = 1, nf do
|
||||
st.blksw[ch] = bits(1) == 1
|
||||
end
|
||||
for ch = 1, nf do
|
||||
st.dithflag[ch] = bits(1) == 1
|
||||
end
|
||||
for i = 1, if acmod == 0 then 2 else 1 do
|
||||
if bits(1) == 1 then
|
||||
local v = bits(8)
|
||||
local x = rshift(v, 5)
|
||||
if x >= 4 then
|
||||
x -= 8
|
||||
end
|
||||
local g = 2 ^ (x + 1) * (32 + band(v, 31)) / 64
|
||||
st.dynrng[i] = if st.drc == 1 then g else g ^ st.drc
|
||||
elseif blk == 0 then
|
||||
st.dynrng[i] = 1
|
||||
end
|
||||
end
|
||||
-- coupling strategy
|
||||
if bits(1) == 1 then
|
||||
st.cplinu = bits(1) == 1
|
||||
if st.cplinu then
|
||||
if acmod < 2 then
|
||||
return nil, "coupling in a mono / dual mono stream"
|
||||
end
|
||||
for ch = 1, nf do
|
||||
st.chincpl[ch] = bits(1) == 1
|
||||
end
|
||||
st.phsflginu = if acmod == 2 then bits(1) == 1 else false
|
||||
st.cplbegf = bits(4)
|
||||
st.cplendf = bits(4)
|
||||
if st.cplendf + 3 <= st.cplbegf then
|
||||
return nil, "bad coupling range"
|
||||
end
|
||||
st.cplbndstrc[st.cplbegf + 1] = false
|
||||
for sbnd = st.cplbegf + 1, st.cplendf + 2 do
|
||||
st.cplbndstrc[sbnd + 1] = bits(1) == 1
|
||||
end
|
||||
else
|
||||
for ch = 1, nf do
|
||||
st.chincpl[ch] = false
|
||||
end
|
||||
st.phsflginu = false
|
||||
end
|
||||
elseif blk == 0 then
|
||||
return nil, "no coupling strategy in block 0"
|
||||
end
|
||||
local cplinu = st.cplinu
|
||||
local cplbegf, cplendf = st.cplbegf, st.cplendf
|
||||
local cplstrt = 37 + 12 * cplbegf
|
||||
local cplend = 37 + 12 * (cplendf + 3)
|
||||
-- coupling coordinates (per sub-band, duplicated over each coupling band)
|
||||
if cplinu then
|
||||
local anyNew = false
|
||||
for ch = 1, nf do
|
||||
if st.chincpl[ch] then
|
||||
if bits(1) == 1 then
|
||||
anyNew = true
|
||||
local mstr = bits(2) * 3
|
||||
local co = st.cplco[ch]
|
||||
local v = 0
|
||||
for sbnd = cplbegf, cplendf + 2 do
|
||||
if not st.cplbndstrc[sbnd + 1] then
|
||||
local ex, mant = bits(4), bits(4)
|
||||
local m = if ex == 15 then mant / 16 else (mant + 16) / 32
|
||||
v = m * 2 ^ -(ex + mstr)
|
||||
end
|
||||
co[sbnd + 1] = v
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if acmod == 2 and st.phsflginu and anyNew then
|
||||
local f = false
|
||||
for sbnd = cplbegf, cplendf + 2 do
|
||||
if not st.cplbndstrc[sbnd + 1] then
|
||||
f = bits(1) == 1
|
||||
end
|
||||
st.phsflg[sbnd + 1] = f
|
||||
end
|
||||
end
|
||||
end
|
||||
-- rematrixing
|
||||
if acmod == 2 then
|
||||
if bits(1) == 1 then
|
||||
local n = if not cplinu or cplbegf > 2 then 4 elseif cplbegf > 0 then 3 else 2
|
||||
for r = 1, 4 do
|
||||
st.rematflg[r] = if r <= n then bits(1) == 1 else false
|
||||
end
|
||||
elseif blk == 0 then
|
||||
for r = 1, 4 do
|
||||
st.rematflg[r] = false
|
||||
end
|
||||
end
|
||||
end
|
||||
-- exponent strategies
|
||||
local chexpstr = st.chexpstr
|
||||
chexpstr[CPL] = if cplinu then bits(2) else 0
|
||||
for ch = 1, nf do
|
||||
chexpstr[ch] = bits(2)
|
||||
end
|
||||
chexpstr[LFE] = if st.lfeon then bits(1) else 0
|
||||
if blk == 0 then
|
||||
for ch = 1, nf do
|
||||
if chexpstr[ch] == 0 then
|
||||
return nil, "exponent reuse in block 0"
|
||||
end
|
||||
end
|
||||
if (cplinu and chexpstr[CPL] == 0) or (st.lfeon and chexpstr[LFE] == 0) then
|
||||
return nil, "exponent reuse in block 0"
|
||||
end
|
||||
end
|
||||
local endmant = st.endmant
|
||||
for ch = 1, nf do
|
||||
if chexpstr[ch] ~= 0 then
|
||||
if st.chincpl[ch] then
|
||||
endmant[ch] = cplstrt
|
||||
else
|
||||
local bw = bits(6)
|
||||
if bw > 60 then
|
||||
return nil, "bad channel bandwidth code"
|
||||
end
|
||||
endmant[ch] = 37 + 3 * (bw + 12)
|
||||
end
|
||||
end
|
||||
end
|
||||
endmant[LFE] = 7
|
||||
-- exponents
|
||||
if cplinu and chexpstr[CPL] ~= 0 then
|
||||
local abs = bits(4) * 2
|
||||
local grp = EXPGRP[chexpstr[CPL]]
|
||||
if not exponents(st.exp[CPL], abs, (cplend - cplstrt) // grp, grp // 3, cplstrt) then
|
||||
return nil, "bad coupling exponents"
|
||||
end
|
||||
end
|
||||
for ch = 1, nf do
|
||||
local s = chexpstr[ch]
|
||||
if s ~= 0 then
|
||||
local grp = EXPGRP[s]
|
||||
local ngrps
|
||||
if s == 1 then
|
||||
ngrps = (endmant[ch] - 1) // 3
|
||||
elseif s == 2 then
|
||||
ngrps = (endmant[ch] - 1 + 3) // 6
|
||||
else
|
||||
ngrps = (endmant[ch] - 1 + 9) // 12
|
||||
end
|
||||
local e = st.exp[ch]
|
||||
e[1] = bits(4)
|
||||
if not exponents(e, e[1], ngrps, grp // 3, 1) then
|
||||
return nil, "bad exponents"
|
||||
end
|
||||
bits(2) -- gainrng
|
||||
end
|
||||
end
|
||||
if st.lfeon and chexpstr[LFE] ~= 0 then
|
||||
local e = st.exp[LFE]
|
||||
e[1] = bits(4)
|
||||
if not exponents(e, e[1], 2, 1, 1) then
|
||||
return nil, "bad LFE exponents"
|
||||
end
|
||||
end
|
||||
if P > limit then
|
||||
return nil, "truncated block"
|
||||
end
|
||||
-- bit allocation parameters
|
||||
if bits(1) == 1 then
|
||||
st.sdcycod, st.fdcycod, st.sgaincod, st.dbpbcod, st.floorcod = bits(2), bits(2), bits(2), bits(2), bits(3)
|
||||
elseif blk == 0 then
|
||||
return nil, "no bit allocation parameters in block 0"
|
||||
end
|
||||
if bits(1) == 1 then
|
||||
st.csnroffst = bits(6)
|
||||
if cplinu then
|
||||
st.fsnroffst[CPL], st.fgaincod[CPL] = bits(4), bits(3)
|
||||
end
|
||||
for ch = 1, nf do
|
||||
st.fsnroffst[ch], st.fgaincod[ch] = bits(4), bits(3)
|
||||
end
|
||||
if st.lfeon then
|
||||
st.fsnroffst[LFE], st.fgaincod[LFE] = bits(4), bits(3)
|
||||
end
|
||||
elseif blk == 0 then
|
||||
return nil, "no SNR offsets in block 0"
|
||||
end
|
||||
if cplinu then
|
||||
if bits(1) == 1 then
|
||||
st.cplfleak, st.cplsleak = bits(3), bits(3)
|
||||
end
|
||||
end
|
||||
-- delta bit allocation
|
||||
if bits(1) == 1 then
|
||||
local modes = table.create(7, 0)
|
||||
if cplinu then
|
||||
modes[CPL] = bits(2)
|
||||
end
|
||||
for ch = 1, nf do
|
||||
modes[ch] = bits(2)
|
||||
end
|
||||
if cplinu and modes[CPL] == 1 then
|
||||
readDba(st, CPL)
|
||||
end
|
||||
for ch = 1, nf do
|
||||
if modes[ch] == 1 then
|
||||
readDba(st, ch)
|
||||
end
|
||||
end
|
||||
for _, ch in { 1, 2, 3, 4, 5, CPL } do
|
||||
if modes[ch] == 1 then
|
||||
st.dbaOn[ch] = true
|
||||
elseif modes[ch] == 2 or modes[ch] == 3 then
|
||||
st.dbaOn[ch] = false
|
||||
end
|
||||
end
|
||||
elseif blk == 0 then
|
||||
for ch = 1, 7 do
|
||||
st.dbaOn[ch] = false
|
||||
end
|
||||
end
|
||||
-- skip field
|
||||
if bits(1) == 1 then
|
||||
P += bits(9) * 8
|
||||
end
|
||||
if P > limit then
|
||||
return nil, "truncated block"
|
||||
end
|
||||
-- bit allocation
|
||||
local zero = st.csnroffst == 0
|
||||
if zero then
|
||||
for ch = 1, nf do
|
||||
if st.fsnroffst[ch] ~= 0 then
|
||||
zero = false
|
||||
end
|
||||
end
|
||||
if (cplinu and st.fsnroffst[CPL] ~= 0) or (st.lfeon and st.fsnroffst[LFE] ~= 0) then
|
||||
zero = false
|
||||
end
|
||||
end
|
||||
local function alloc(ch: number, start: number, stop: number, isLfe: boolean)
|
||||
if zero then
|
||||
for i = start + 1, stop do
|
||||
st.bap[ch][i] = 0
|
||||
end
|
||||
else
|
||||
local snr = ((st.csnroffst - 15) * 16 + st.fsnroffst[ch]) * 4
|
||||
allocate(st, ch, start, stop, FASTGAIN[st.fgaincod[ch] + 1], snr, isLfe)
|
||||
end
|
||||
end
|
||||
if cplinu then
|
||||
alloc(CPL, cplstrt, cplend, false)
|
||||
end
|
||||
for ch = 1, nf do
|
||||
alloc(ch, 0, endmant[ch], false)
|
||||
end
|
||||
if st.lfeon then
|
||||
alloc(LFE, 0, 7, true)
|
||||
end
|
||||
-- mantissas
|
||||
n1, n2, n4 = 0, 0, 0
|
||||
local gotCpl = false
|
||||
local coef = st.coef
|
||||
for ch = 1, nf do
|
||||
local c = coef[ch]
|
||||
mantissas(st, ch, 0, endmant[ch], c, st.dithflag[ch])
|
||||
for i = endmant[ch] + 1, 256 do
|
||||
c[i] = 0
|
||||
end
|
||||
if cplinu and st.chincpl[ch] and not gotCpl then
|
||||
mantissas(st, CPL, cplstrt, cplend, coef[CPL], false)
|
||||
gotCpl = true
|
||||
end
|
||||
if P > limit then
|
||||
return nil, "truncated block"
|
||||
end
|
||||
end
|
||||
if st.lfeon then
|
||||
local c = coef[LFE]
|
||||
mantissas(st, LFE, 0, 7, c, false)
|
||||
for i = 8, 256 do
|
||||
c[i] = 0
|
||||
end
|
||||
end
|
||||
if P > limit then
|
||||
return nil, "truncated block"
|
||||
end
|
||||
-- decoupling (section 7.4): dither the coupling channel's zero-bit mantissas per channel
|
||||
if cplinu then
|
||||
local cc, cbap, cexp = coef[CPL], st.bap[CPL], st.exp[CPL]
|
||||
for ch = 1, nf do
|
||||
if st.chincpl[ch] then
|
||||
local c, co = coef[ch], st.cplco[ch]
|
||||
local dith = st.dithflag[ch]
|
||||
local flip = acmod == 2 and ch == 2 and st.phsflginu
|
||||
for sbnd = cplbegf, cplendf + 2 do
|
||||
local f = co[sbnd + 1] * 8
|
||||
if flip and st.phsflg[sbnd + 1] then
|
||||
f = -f
|
||||
end
|
||||
for k = 37 + 12 * sbnd + 1, 37 + 12 * sbnd + 12 do
|
||||
local v = cc[k]
|
||||
if cbap[k] == 0 then
|
||||
v = if dith then dither(st) * POW2[cexp[k] + 1] else 0
|
||||
end
|
||||
c[k] = v * f
|
||||
end
|
||||
end
|
||||
for k = cplend + 1, 256 do
|
||||
c[k] = 0
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
-- rematrixing (section 7.5)
|
||||
if acmod == 2 then
|
||||
local stop = if cplinu then cplstrt else min(endmant[1], endmant[2])
|
||||
local l, r = coef[1], coef[2]
|
||||
local edges = { 13, 25, 37, 61, 253 }
|
||||
for rb = 1, 4 do
|
||||
if st.rematflg[rb] then
|
||||
for k = edges[rb] + 1, min(edges[rb + 1], stop) do
|
||||
local a, b = l[k], r[k]
|
||||
l[k], r[k] = a + b, a - b
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ transform
|
||||
-- the inverse transform of slot ch (long or two short), windowed, overlap-added into out[base + i * step]
|
||||
local function synth(st: State, ch: number, short: boolean, gain: number, out: { number }, base: number, step: number)
|
||||
local x, y, d, w = st.coef[ch], st.y, st.delay[ch], WINDOW
|
||||
if short then
|
||||
-- two 256-point transforms of the interleaved coefficients, phases alpha = -1 (n0 = 0) and +1 (n0 = N / 2)
|
||||
local z = st.psd -- 256 scratch
|
||||
Mdct.inverse(PLAN256, x, 1, 2, z, 1, -2 * gain)
|
||||
for n = 0, 63 do
|
||||
y[n + 1] = -z[n + 193]
|
||||
end
|
||||
for n = 64, 255 do
|
||||
y[n + 1] = z[n - 63]
|
||||
end
|
||||
Mdct.inverse(PLAN256, x, 2, 2, z, 1, -2 * gain)
|
||||
for n = 0, 191 do
|
||||
y[257 + n] = z[n + 65]
|
||||
end
|
||||
for n = 192, 255 do
|
||||
y[257 + n] = -z[n - 191]
|
||||
end
|
||||
else
|
||||
Mdct.inverse(PLAN512, x, 1, 1, y, 1, -2 * gain)
|
||||
end
|
||||
local p = base
|
||||
for n = 1, 256 do
|
||||
out[p] = y[n] * w[n] + d[n]
|
||||
d[n] = y[n + 256] * w[n + 256]
|
||||
p += step
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ frame
|
||||
-- the output index of each slot (1 .. 5 full bandwidth, 6 LFE) in WAVE order: L R C LFE surrounds
|
||||
local ORDER: { [number]: { number } } = {
|
||||
[0] = { 1, 2 },
|
||||
{ 1 },
|
||||
{ 1, 2 },
|
||||
{ 1, 3, 2 },
|
||||
{ 1, 2, 3 },
|
||||
{ 1, 3, 2, 4 },
|
||||
{ 1, 2, 3, 4 },
|
||||
{ 1, 3, 2, 4, 5 },
|
||||
}
|
||||
local HAS_C = { [0] = false, true, false, true, false, true, false, true }
|
||||
|
||||
-- frame(st, buf, len, drc) -> 1536 | nil, message: decodes the syncframe at buf[0 .. len) (padded by PAD bytes)
|
||||
-- into st.pcm (1536 * st.channels interleaved floats, WAVE order). drc: the dynamic range scale (0 = off, 1 = full).
|
||||
function Decode.frame(st: State, buf: buffer, len: number, drc: number): (number?, string?)
|
||||
if len < 8 or buffer.len(buf) < len + Decode.PAD then
|
||||
return nil, "truncated frame"
|
||||
end
|
||||
B, P = buf, 32
|
||||
local fscod = bits(2)
|
||||
bits(6)
|
||||
local bsid = bits(5)
|
||||
if bsid > 8 then
|
||||
B = buffer.create(0)
|
||||
return nil, "unsupported: bsid " .. bsid .. (if bsid > 10 then " (E-AC-3)" else " (reduced sample rate)")
|
||||
end
|
||||
if fscod == 3 then
|
||||
B = buffer.create(0)
|
||||
return nil, "bad sample rate code"
|
||||
end
|
||||
bits(3) -- bsmod
|
||||
local acmod = bits(3)
|
||||
if band(acmod, 1) == 1 and acmod ~= 1 then
|
||||
bits(2)
|
||||
end
|
||||
if band(acmod, 4) ~= 0 then
|
||||
bits(2)
|
||||
end
|
||||
if acmod == 2 then
|
||||
bits(2)
|
||||
end
|
||||
local lfeon = bits(1) == 1
|
||||
for _ = 1, if acmod == 0 then 2 else 1 do
|
||||
bits(5)
|
||||
if bits(1) == 1 then
|
||||
bits(8)
|
||||
end
|
||||
if bits(1) == 1 then
|
||||
bits(8)
|
||||
end
|
||||
if bits(1) == 1 then
|
||||
bits(7)
|
||||
end
|
||||
end
|
||||
bits(2)
|
||||
if bits(1) == 1 then
|
||||
bits(14)
|
||||
end
|
||||
if bits(1) == 1 then
|
||||
bits(14)
|
||||
end
|
||||
if bits(1) == 1 then
|
||||
P += (bits(6) + 1) * 8
|
||||
end
|
||||
local nf = NFCHANS[acmod]
|
||||
local channels = nf + (if lfeon then 1 else 0)
|
||||
if st.acmod ~= acmod or st.lfeon ~= lfeon then
|
||||
-- a new channel layout: build the output map and forget the overlap
|
||||
local order = ORDER[acmod]
|
||||
local map = table.create(6, 0)
|
||||
local nfront = if HAS_C[acmod] then 3 elseif acmod == 1 then 1 else 2
|
||||
for ch = 1, nf do
|
||||
local o = order[ch]
|
||||
map[ch] = if lfeon and o > nfront then o + 1 else o
|
||||
end
|
||||
if lfeon then
|
||||
map[LFE] = nfront + 1
|
||||
end
|
||||
st.map = map
|
||||
st.pcm = table.create(1536 * channels, 0)
|
||||
Decode.reset(st)
|
||||
end
|
||||
st.fscod, st.acmod, st.lfeon, st.nfchans, st.channels, st.drc = fscod, acmod, lfeon, nf, channels, drc
|
||||
local pcm = st.pcm
|
||||
local limit = len * 8 - 16 -- crc2
|
||||
for blk = 0, 5 do
|
||||
st.blocks[blk + 1] = P
|
||||
local ok, err = audblk(st, blk, limit)
|
||||
if not ok then
|
||||
B = buffer.create(0)
|
||||
return nil, err
|
||||
end
|
||||
local base = blk * 256 * channels
|
||||
for ch = 1, nf do
|
||||
local g = st.dynrng[if acmod == 0 and ch == 2 then 2 else 1]
|
||||
synth(st, ch, st.blksw[ch], g, pcm, base + st.map[ch], channels)
|
||||
end
|
||||
if lfeon then
|
||||
synth(st, LFE, false, st.dynrng[1], pcm, base + st.map[LFE], channels)
|
||||
end
|
||||
end
|
||||
B = buffer.create(0)
|
||||
return 1536, nil
|
||||
end
|
||||
|
||||
return Decode
|
||||
@@ -0,0 +1,102 @@
|
||||
--!strict
|
||||
-- codecs/audio/Ac3/Tables: the AC-3 constant tables, transcribed from ATSC A/52:2018 (Digital Audio Compression
|
||||
-- Standard) section 7.2.3 (bit allocation: slowdec, fastdec, slowgain, dbpbtab, floortab, fastgain, bndtab / bndsz,
|
||||
-- latab, hth, baptab) and section 5.4 (frame sizes). masktab is derived from bndtab / bndsz, the transform window
|
||||
-- (Table 7.33) is the Kaiser-Bessel-derived window with alpha 5 (codecs/audio/Mdct), which Table 7.33 rounds to five
|
||||
-- decimals. No third-party code.
|
||||
local T = {}
|
||||
|
||||
T.SLOWDEC = { 0x0f, 0x11, 0x13, 0x15 }
|
||||
T.FASTDEC = { 0x3f, 0x53, 0x67, 0x7b }
|
||||
T.SLOWGAIN = { 0x540, 0x4d8, 0x478, 0x410 }
|
||||
T.DBPBTAB = { 0x000, 0x700, 0x900, 0xb00 }
|
||||
T.FLOORTAB = { 0x2f0, 0x2b0, 0x270, 0x230, 0x1f0, 0x170, 0x0f0, 0xf800 }
|
||||
T.FASTGAIN = { 0x080, 0x100, 0x180, 0x200, 0x280, 0x300, 0x380, 0x400 }
|
||||
|
||||
-- the 50 bit allocation bands: first bin and width (Table 7.12)
|
||||
T.BNDTAB = {
|
||||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
|
||||
25, 26, 27, 28, 31, 34, 37, 40, 43, 46, 49, 55, 61, 67, 73, 79, 85, 97, 109, 121, 133, 157, 181, 205, 229,
|
||||
}
|
||||
T.BNDSZ = {
|
||||
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
|
||||
1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 6, 6, 6, 6, 6, 6, 12, 12, 12, 12, 24, 24, 24, 24, 24,
|
||||
}
|
||||
-- masktab[bin + 1]: the band of each bin (Table 7.13; bins 253 .. 255 map to 0)
|
||||
T.MASKTAB = table.create(256, 0)
|
||||
for b = 1, 50 do
|
||||
for k = T.BNDTAB[b], T.BNDTAB[b] + T.BNDSZ[b] - 1 do
|
||||
T.MASKTAB[k + 1] = b - 1
|
||||
end
|
||||
end
|
||||
|
||||
-- log-addition table (Table 7.14)
|
||||
T.LATAB = {
|
||||
0x0040, 0x003f, 0x003e, 0x003d, 0x003c, 0x003b, 0x003a, 0x0039, 0x0038, 0x0037, 0x0036, 0x0035, 0x0034, 0x0034, 0x0033, 0x0032,
|
||||
0x0031, 0x0030, 0x002f, 0x002f, 0x002e, 0x002d, 0x002c, 0x002c, 0x002b, 0x002a, 0x0029, 0x0029, 0x0028, 0x0027, 0x0026, 0x0026,
|
||||
0x0025, 0x0024, 0x0024, 0x0023, 0x0023, 0x0022, 0x0021, 0x0021, 0x0020, 0x0020, 0x001f, 0x001e, 0x001e, 0x001d, 0x001d, 0x001c,
|
||||
0x001c, 0x001b, 0x001b, 0x001a, 0x001a, 0x0019, 0x0019, 0x0018, 0x0018, 0x0017, 0x0017, 0x0016, 0x0016, 0x0015, 0x0015, 0x0015,
|
||||
0x0014, 0x0014, 0x0013, 0x0013, 0x0013, 0x0012, 0x0012, 0x0012, 0x0011, 0x0011, 0x0011, 0x0010, 0x0010, 0x0010, 0x000f, 0x000f,
|
||||
0x000f, 0x000e, 0x000e, 0x000e, 0x000d, 0x000d, 0x000d, 0x000d, 0x000c, 0x000c, 0x000c, 0x000c, 0x000b, 0x000b, 0x000b, 0x000b,
|
||||
0x000a, 0x000a, 0x000a, 0x000a, 0x000a, 0x0009, 0x0009, 0x0009, 0x0009, 0x0009, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008,
|
||||
0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0005, 0x0005,
|
||||
0x0005, 0x0005, 0x0005, 0x0005, 0x0005, 0x0005, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004,
|
||||
0x0004, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0002,
|
||||
0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002,
|
||||
0x0002, 0x0002, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001,
|
||||
0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001,
|
||||
0x0001, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
|
||||
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
|
||||
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
|
||||
}
|
||||
|
||||
-- hearing threshold per band (Table 7.15): HTH[fscod + 1][band + 1]
|
||||
T.HTH = {
|
||||
{
|
||||
0x04d0, 0x04d0, 0x0440, 0x0400, 0x03e0, 0x03c0, 0x03b0, 0x03b0, 0x03a0, 0x03a0,
|
||||
0x03a0, 0x03a0, 0x03a0, 0x0390, 0x0390, 0x0390, 0x0380, 0x0380, 0x0370, 0x0370,
|
||||
0x0360, 0x0360, 0x0350, 0x0350, 0x0340, 0x0340, 0x0330, 0x0320, 0x0310, 0x0300,
|
||||
0x02f0, 0x02f0, 0x02f0, 0x02f0, 0x0300, 0x0310, 0x0340, 0x0390, 0x03e0, 0x0420,
|
||||
0x0460, 0x0490, 0x04a0, 0x0460, 0x0440, 0x0440, 0x0520, 0x0800, 0x0840, 0x0840,
|
||||
},
|
||||
{
|
||||
0x04f0, 0x04f0, 0x0460, 0x0410, 0x03e0, 0x03d0, 0x03c0, 0x03b0, 0x03b0, 0x03a0,
|
||||
0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x0390, 0x0390, 0x0390, 0x0380, 0x0380, 0x0380,
|
||||
0x0370, 0x0370, 0x0360, 0x0360, 0x0350, 0x0350, 0x0340, 0x0340, 0x0320, 0x0310,
|
||||
0x0300, 0x02f0, 0x02f0, 0x02f0, 0x02f0, 0x0300, 0x0320, 0x0350, 0x0390, 0x03e0,
|
||||
0x0420, 0x0450, 0x04a0, 0x0490, 0x0460, 0x0440, 0x0480, 0x0630, 0x0840, 0x0840,
|
||||
},
|
||||
{
|
||||
0x0580, 0x0580, 0x04b0, 0x0450, 0x0420, 0x03f0, 0x03e0, 0x03d0, 0x03c0, 0x03b0,
|
||||
0x03b0, 0x03b0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0,
|
||||
0x0390, 0x0390, 0x0390, 0x0390, 0x0380, 0x0380, 0x0380, 0x0370, 0x0360, 0x0350,
|
||||
0x0340, 0x0330, 0x0320, 0x0310, 0x0300, 0x02f0, 0x02f0, 0x02f0, 0x0300, 0x0310,
|
||||
0x0330, 0x0350, 0x03c0, 0x0410, 0x0470, 0x04a0, 0x0460, 0x0440, 0x0450, 0x04e0,
|
||||
},
|
||||
}
|
||||
|
||||
-- bit allocation pointers (Table 7.16)
|
||||
T.BAPTAB = {
|
||||
0, 1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10,
|
||||
10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15,
|
||||
}
|
||||
|
||||
-- words per syncframe (Table 5.18) for frmsizecod // 2 (the nominal bit rate in kbps) and fscod: 48 kHz = 2 x rate,
|
||||
-- 32 kHz = 3 x rate, 44.1 kHz = floor(rate x 1536000 / 705600) + (frmsizecod & 1)
|
||||
T.BITRATES = { 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 448, 512, 576, 640 }
|
||||
T.RATES = { 48000, 44100, 32000 }
|
||||
|
||||
function T.frameWords(fscod: number, frmsizecod: number): number
|
||||
local kbps = T.BITRATES[frmsizecod // 2 + 1]
|
||||
if not kbps or fscod > 2 then
|
||||
return 0
|
||||
end
|
||||
if fscod == 0 then
|
||||
return 2 * kbps
|
||||
elseif fscod == 2 then
|
||||
return 3 * kbps
|
||||
end
|
||||
return kbps * 1536000 // 705600 + frmsizecod % 2
|
||||
end
|
||||
|
||||
return T
|
||||
@@ -0,0 +1,172 @@
|
||||
--!strict
|
||||
-- codecs/audio/Ac3: AC-3 (Dolby Digital, ATSC A/52) syncframes: the syncinfo / BSI header, the CRC check, and the
|
||||
-- decoder (codecs/audio/Ac3/Decode). Written from ATSC A/52:2018; no third-party code. A codec (layer 3): audio/ac3
|
||||
-- (raw .ac3 files) builds on it, and the AC-3 tracks of MKV / MP4 / MPEG-TS / AVI reach it through
|
||||
-- containers/AudioWrap.
|
||||
-- Supports: every acmod (1+1, 1/0 .. 3/2) with or without LFE, 32 / 44.1 / 48 kHz, all bit rates, coupling with phase
|
||||
-- flags, rematrixing, block switching, delta bit allocation, dither, dynamic range control (off by default,
|
||||
-- `drc` = 0 .. 1 scales it). Output: every channel in WAVE order (L R C LFE surrounds), no downmix. Not supported:
|
||||
-- E-AC-3 (bsid 11 .. 16) and the reduced-rate bsid 9 / 10 streams (UNSUPPORTED).
|
||||
--
|
||||
-- local h = Ac3.header(buf, offset, limit) -- { sampleRate, frameSize, channels, acmod, lfeon, bsid, bitrate }
|
||||
-- local dec = Ac3.decoder({ drc = 0 }) -- dec:decode(buf, offset, length) -> 1536, dec.pcm (interleaved)
|
||||
--
|
||||
-- Never throws: bad data returns nil, Err.
|
||||
local Err = require("@formats/core/Err")
|
||||
local T = require("@formats/codecs/audio/Ac3/Tables")
|
||||
local Decode = require("@formats/codecs/audio/Ac3/Decode")
|
||||
|
||||
local Ac3 = {}
|
||||
|
||||
local readu8 = buffer.readu8
|
||||
local NFCHANS = { [0] = 2, 1, 2, 3, 3, 4, 4, 5 }
|
||||
|
||||
export type Header = {
|
||||
sampleRate: number,
|
||||
frameSize: number, -- bytes
|
||||
bitrate: number, -- bits per second
|
||||
channels: number,
|
||||
acmod: number,
|
||||
lfeon: boolean,
|
||||
bsid: number,
|
||||
}
|
||||
|
||||
-- header(buf, o, limit) -> Header | nil (not an AC-3 / E-AC-3 syncframe header at o). E-AC-3 headers (bsid > 10)
|
||||
-- come back with frameSize from their own frmsiz field so a scanner can step over them.
|
||||
function Ac3.header(b: buffer, o: number, limit: number): Header?
|
||||
if o < 0 or o + 8 > limit or o + 8 > buffer.len(b) then
|
||||
return nil
|
||||
end
|
||||
if readu8(b, o) ~= 0x0B or readu8(b, o + 1) ~= 0x77 then
|
||||
return nil
|
||||
end
|
||||
local bsid = bit32.rshift(readu8(b, o + 5), 3)
|
||||
if bsid > 10 then
|
||||
if bsid > 16 then
|
||||
return nil
|
||||
end
|
||||
-- E-AC-3: strmtyp(2) substreamid(3) frmsiz(11) fscod(2) ...
|
||||
local words = bit32.band(readu8(b, o + 2), 7) * 256 + readu8(b, o + 3) + 1
|
||||
local fs = bit32.rshift(readu8(b, o + 4), 6)
|
||||
return {
|
||||
sampleRate = if fs < 3 then T.RATES[fs + 1] else 0,
|
||||
frameSize = words * 2,
|
||||
bitrate = 0,
|
||||
channels = 0,
|
||||
acmod = bit32.band(bit32.rshift(readu8(b, o + 4), 1), 7),
|
||||
lfeon = false,
|
||||
bsid = bsid,
|
||||
}
|
||||
end
|
||||
local b4 = readu8(b, o + 4)
|
||||
local fscod, frmsizecod = bit32.rshift(b4, 6), bit32.band(b4, 63)
|
||||
local words = T.frameWords(fscod, frmsizecod)
|
||||
if words == 0 then
|
||||
return nil
|
||||
end
|
||||
local acmod = bit32.rshift(readu8(b, o + 6), 5)
|
||||
-- lfeon: after acmod and the optional cmixlev / surmixlev / dsurmod fields
|
||||
local skip = 0
|
||||
if bit32.band(acmod, 1) == 1 and acmod ~= 1 then
|
||||
skip += 2
|
||||
end
|
||||
if bit32.band(acmod, 4) ~= 0 then
|
||||
skip += 2
|
||||
end
|
||||
if acmod == 2 then
|
||||
skip += 2
|
||||
end
|
||||
local w = readu8(b, o + 6) * 256 + readu8(b, o + 7)
|
||||
local lfeon = bit32.extract(w, 12 - skip, 1) == 1
|
||||
local shift = if bsid > 8 then bsid - 8 else 0
|
||||
return {
|
||||
sampleRate = T.RATES[fscod + 1] // 2 ^ shift,
|
||||
frameSize = words * 2,
|
||||
bitrate = T.BITRATES[frmsizecod // 2 + 1] * 1000 // 2 ^ shift,
|
||||
channels = NFCHANS[acmod] + (if lfeon then 1 else 0),
|
||||
acmod = acmod,
|
||||
lfeon = lfeon,
|
||||
bsid = bsid,
|
||||
}
|
||||
end
|
||||
|
||||
-- the CRC-16 of A/52 section 7.10.1 (x^16 + x^15 + x^2 + 1, MSB first, zero start): a syncframe checks when the CRC of
|
||||
-- everything after the sync word is 0
|
||||
local CRC = table.create(256, 0)
|
||||
for i = 0, 255 do
|
||||
local c = i * 256
|
||||
for _ = 1, 8 do
|
||||
c = if c >= 0x8000 then bit32.bxor(bit32.band(c * 2, 0xFFFF), 0x8005) else c * 2
|
||||
end
|
||||
CRC[i + 1] = c
|
||||
end
|
||||
|
||||
function Ac3.crc(b: buffer, o: number, n: number): number
|
||||
local c = 0
|
||||
for i = o, o + n - 1 do
|
||||
c = bit32.bxor(bit32.band(c * 256, 0xFFFF), CRC[bit32.bxor(bit32.rshift(c, 8), readu8(b, i)) + 1])
|
||||
end
|
||||
return c
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decoder
|
||||
export type Options = {
|
||||
drc: number?, -- dynamic range control: 0 = off (default, like ffmpeg -drc_scale 0), 1 = as the stream says
|
||||
crc: boolean?, -- check crc2 (default true): a mismatch is Err.CHECKSUM
|
||||
}
|
||||
|
||||
export type Decoder = {
|
||||
pcm: { number }, -- the last frame: 1536 * channels interleaved floats, WAVE order
|
||||
channels: number,
|
||||
sampleRate: number,
|
||||
blocks: { number }, -- the bit offset of each audio block in the last frame (tools: stream editing, analysis)
|
||||
decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?),
|
||||
reset: (self: Decoder) -> (),
|
||||
}
|
||||
|
||||
function Ac3.decoder(opts: Options?): Decoder
|
||||
local o: Options = opts or {}
|
||||
local drc = math.max(0, o.drc or 0)
|
||||
local checkCrc = o.crc ~= false
|
||||
local st = Decode.state()
|
||||
local scratch = buffer.create(3840 + Decode.PAD)
|
||||
local dec: Decoder
|
||||
dec = {
|
||||
pcm = st.pcm,
|
||||
channels = 0,
|
||||
sampleRate = 0,
|
||||
blocks = st.blocks,
|
||||
decode = function(self: Decoder, buf: buffer, offset: number?, length: number?): (number?, Err.Err?)
|
||||
local off = offset or 0
|
||||
if type(buf) ~= "buffer" or off < 0 or off >= buffer.len(buf) then
|
||||
return nil, Err.new(Err.ARG, "frame range out of the buffer")
|
||||
end
|
||||
local h = Ac3.header(buf, off, buffer.len(buf))
|
||||
if not h then
|
||||
return nil, Err.new(Err.CORRUPT, "no AC-3 syncframe", off)
|
||||
end
|
||||
local n = h.frameSize
|
||||
if length and length < n or off + n > buffer.len(buf) then
|
||||
return nil, Err.new(Err.TRUNCATED, "truncated syncframe", off)
|
||||
end
|
||||
if checkCrc and Ac3.crc(buf, off + 2, n - 2) ~= 0 then
|
||||
return nil, Err.new(Err.CHECKSUM, "syncframe CRC", off)
|
||||
end
|
||||
buffer.copy(scratch, 0, buf, off, n)
|
||||
local frames, msg = Decode.frame(st, scratch, n, drc)
|
||||
if not frames then
|
||||
return nil, Err.from(msg, off)
|
||||
end
|
||||
self.pcm = st.pcm
|
||||
self.channels = st.channels
|
||||
self.sampleRate = h.sampleRate
|
||||
return frames, nil
|
||||
end,
|
||||
reset = function(_self: Decoder)
|
||||
Decode.reset(st)
|
||||
end,
|
||||
}
|
||||
return dec
|
||||
end
|
||||
|
||||
return Ac3
|
||||
@@ -0,0 +1,328 @@
|
||||
--!strict
|
||||
-- codecs/audio/Adpcm/Decoder: the streaming Decoder (Types.Decoder) over an ADPCM stream cut into packets, for the
|
||||
-- formats whose state carries from packet to packet (ADX, VAG, BRSTM, raw IMA): codecs/audio/Stream.packets plus
|
||||
-- exact seeking. The codec state (one buffer the packet decoder advances) is snapshotted at every packet start it
|
||||
-- passes; a seek restores the snapshot, else the format's own state for that packet (BRSTM's ADPC history), else
|
||||
-- decodes forward from the nearest earlier snapshot. New in formats-luau.
|
||||
--
|
||||
-- local dec, err = Decoder.packets(dec, { -- dec: the Decoder table (sampleRate, channels, frames, ...)
|
||||
-- count = n, packetFrames = 4096, -- packets of packetFrames frames (the last may be shorter)
|
||||
-- frames = total, -- output frames
|
||||
-- state = st, -- the codec state buffer decode advances
|
||||
-- decode = function(i, out) return frames end, -- packet i (1-based) as interleaved f32 into out from 0
|
||||
-- restore = function(i) return false end, -- optional: set st for packet i, true if it could
|
||||
-- })
|
||||
--
|
||||
-- The layouts the formats share, each returning the Decoder (dec gets read / seek / position) | nil, Err:
|
||||
-- Decoder.interleaved(dec, spec) psx / adx / dsp frames (or s16 / s8 PCM), channels interleaved every
|
||||
-- spec.interleave bytes (VAG, ADX, BRSTM / BCSTM / BFSTM, raw PS-ADPCM)
|
||||
-- Decoder.nibbles(dec, spec) an IMA nibble stream, channels interleaved by nibble (raw IMA, KVAG)
|
||||
-- Decoder.blocks(dec, spec) self-contained blocks: "ms" / "ima_wav" (blockAlign bytes), "ima_qt" (34 bytes
|
||||
-- per channel), raw or inside AIFF-C / CAF
|
||||
--
|
||||
-- Never throws (decode failures end the stream and land in dec.error, see codecs/audio/Stream).
|
||||
local Err = require("@formats/core/Err")
|
||||
local Stream = require("@formats/codecs/audio/Stream")
|
||||
local Adpcm = require("@formats/codecs/audio/Adpcm")
|
||||
|
||||
local Decoder = {}
|
||||
|
||||
export type Spec = {
|
||||
count: number,
|
||||
packetFrames: number,
|
||||
frames: number,
|
||||
state: buffer,
|
||||
decode: (i: number, out: buffer) -> (number?, Err.Err?),
|
||||
restore: ((i: number) -> boolean)?,
|
||||
}
|
||||
|
||||
function Decoder.packets(dec: any, spec: Spec): (any, Err.Err?)
|
||||
local ch = dec.channels
|
||||
local pf = spec.packetFrames
|
||||
local st = spec.state
|
||||
local out = buffer.create(pf * ch * 4)
|
||||
local decodeP = spec.decode
|
||||
local restore = spec.restore
|
||||
local snaps: { [number]: buffer } = {}
|
||||
local nextPacket = 1
|
||||
local function snap(i: number)
|
||||
if not snaps[i] then
|
||||
local b = buffer.create(buffer.len(st))
|
||||
buffer.copy(b, 0, st)
|
||||
snaps[i] = b
|
||||
end
|
||||
end
|
||||
snap(1)
|
||||
local function decode(i: number): (number?, Err.Err?)
|
||||
if i ~= nextPacket then
|
||||
if snaps[i] then
|
||||
buffer.copy(st, 0, snaps[i])
|
||||
elseif restore and restore(i) then
|
||||
-- the format set the state (BRSTM's seek table)
|
||||
else
|
||||
local j = i - 1
|
||||
while j > 1 and not snaps[j] do
|
||||
j -= 1
|
||||
end
|
||||
buffer.copy(st, 0, snaps[j])
|
||||
for k = j, i - 1 do
|
||||
local n, e = decodeP(k, out)
|
||||
if not n then
|
||||
return nil, e
|
||||
end
|
||||
snap(k + 1)
|
||||
end
|
||||
end
|
||||
end
|
||||
local n, e = decodeP(i, out)
|
||||
if n then
|
||||
nextPacket = i + 1
|
||||
snap(i + 1)
|
||||
end
|
||||
return n, e
|
||||
end
|
||||
return Stream.packets(dec, {
|
||||
count = spec.count,
|
||||
start = function(i: number): number
|
||||
return (i - 1) * pf
|
||||
end,
|
||||
decode = decode,
|
||||
pcm = function(): buffer
|
||||
return out
|
||||
end,
|
||||
reset = function() end,
|
||||
stop = spec.frames,
|
||||
})
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ layouts
|
||||
local FRAME: { [string]: number } = { psx = 16, adx = 18, dsp = 8, s16be = 2, s16le = 2, s8 = 1 } -- bytes per frame
|
||||
local SPF: { [string]: number } = { psx = 28, adx = 32, dsp = 14, s16be = 1, s16le = 1, s8 = 1 } -- samples per frame
|
||||
|
||||
-- PCM samples of one channel into every ds-th float of dst from float d
|
||||
local function pcm(kind: string, src: buffer, p: number, n: number, dst: buffer, d: number, ds: number)
|
||||
if kind == "s8" then
|
||||
for k = 0, n - 1 do
|
||||
buffer.writef32(dst, (d + k * ds) * 4, buffer.readi8(src, p + k) / 128)
|
||||
end
|
||||
elseif kind == "s16le" then
|
||||
for k = 0, n - 1 do
|
||||
buffer.writef32(dst, (d + k * ds) * 4, buffer.readi16(src, p + k * 2) / 32768)
|
||||
end
|
||||
else
|
||||
for k = 0, n - 1 do
|
||||
local v = buffer.readu8(src, p + k * 2) * 256 + buffer.readu8(src, p + k * 2 + 1)
|
||||
buffer.writef32(dst, (d + k * ds) * 4, (if v >= 32768 then v - 65536 else v) / 32768)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
export type InterleavedSpec = {
|
||||
kind: "psx" | "adx" | "dsp" | "s16be" | "s16le" | "s8", -- ADPCM frames, or PCM samples laid out the same way
|
||||
buf: buffer,
|
||||
offset: number, -- the first row
|
||||
size: number, -- data bytes (rows past it are cut; a truncated file decodes its whole frames)
|
||||
interleave: number, -- bytes per channel per row (a multiple of the frame size; mono: any multiple)
|
||||
lastInterleave: number?, -- bytes per channel in the last row (BRSTM's padded last block), default interleave
|
||||
frames: number?, -- frames to output (default: what the data holds)
|
||||
c1: number?, -- adx: the predictor (Adpcm.adxCoefs)
|
||||
c2: number?,
|
||||
v3: boolean?, -- adx: version 3 rounding
|
||||
coefs: buffer?, -- dsp: 16 i32 per channel
|
||||
hist: { number }?, -- initial history, h1 / h2 per channel (default 0)
|
||||
restore: ((row: number, st: buffer) -> boolean)?, -- the exact history at the start of a row (BRSTM ADPC)
|
||||
}
|
||||
|
||||
-- interleaved(dec, spec) -> Decoder | nil, Err
|
||||
function Decoder.interleaved(dec: any, spec: InterleavedSpec): (any, Err.Err?)
|
||||
local ch = dec.channels
|
||||
local kind = spec.kind
|
||||
local fsize, spf = FRAME[kind], SPF[kind]
|
||||
local il = spec.interleave
|
||||
local last = spec.lastInterleave or il
|
||||
if not fsize or ch < 1 or il < fsize or il % fsize ~= 0 or last < 0 or last > il then
|
||||
return nil, Err.new(Err.CORRUPT, "bad interleave " .. tostring(il))
|
||||
end
|
||||
local buf, base, size = spec.buf, spec.offset, spec.size
|
||||
local rowBytes = il * ch
|
||||
-- rows: the full ones, then the last (which may be shorter, and may be cut by a truncated file)
|
||||
local rows = math.max(1, math.ceil(size / rowBytes))
|
||||
local function rowFrames(r: number): number -- the frames row r (0-based) holds whole in every channel
|
||||
local width = if r == rows - 1 then last else il
|
||||
-- channel c sits at c * width in the row: the last channel is the one a cut file shortens
|
||||
local per = math.clamp(size - r * rowBytes - (ch - 1) * width, 0, width)
|
||||
return (per // fsize) * spf
|
||||
end
|
||||
local fullFrames = (il // fsize) * spf
|
||||
local total = (rows - 1) * fullFrames + rowFrames(rows - 1)
|
||||
local frames = math.min(spec.frames or total, total)
|
||||
local st = buffer.create(8 * ch)
|
||||
if spec.hist then
|
||||
for c = 0, ch - 1 do
|
||||
buffer.writei32(st, c * 8, spec.hist[c * 2 + 1] or 0)
|
||||
buffer.writei32(st, c * 8 + 4, spec.hist[c * 2 + 2] or 0)
|
||||
end
|
||||
end
|
||||
local rowsPer = if spec.restore then 1 else math.max(1, 4096 // fullFrames)
|
||||
local pf = rowsPer * fullFrames
|
||||
local c1, c2, v3, coefs = spec.c1 or 0, spec.c2 or 0, spec.v3 == true, spec.coefs
|
||||
local restore = spec.restore
|
||||
dec.frames = frames
|
||||
dec.duration = frames / dec.sampleRate
|
||||
return Decoder.packets(dec, {
|
||||
count = math.max(1, math.ceil(frames / pf)),
|
||||
packetFrames = pf,
|
||||
frames = frames,
|
||||
state = st,
|
||||
restore = if restore
|
||||
then function(i: number): boolean
|
||||
return restore(i - 1, st)
|
||||
end
|
||||
else nil,
|
||||
decode = function(i: number, out: buffer): (number?, Err.Err?)
|
||||
local got = 0
|
||||
for r = (i - 1) * rowsPer, math.min(i * rowsPer, rows) - 1 do
|
||||
local n = math.min(rowFrames(r), frames - r * fullFrames)
|
||||
if n <= 0 then
|
||||
break
|
||||
end
|
||||
local nf = math.ceil(n / spf)
|
||||
local width = if r == rows - 1 then last else il
|
||||
for c = 0, ch - 1 do
|
||||
local p = base + r * rowBytes + c * width
|
||||
local d = got * ch + c
|
||||
if kind == "psx" then
|
||||
Adpcm.psx(buf, p, fsize, nf, st, c * 8, out, d, ch)
|
||||
elseif kind == "adx" then
|
||||
Adpcm.adx(buf, p, fsize, nf, c1, c2, v3, st, c * 8, out, d, ch)
|
||||
elseif kind == "dsp" then
|
||||
Adpcm.dsp(buf, p, n, coefs :: buffer, c * 64, st, c * 8, out, d, ch)
|
||||
else
|
||||
pcm(kind, buf, p, n, out, d, ch)
|
||||
end
|
||||
end
|
||||
got += n
|
||||
end
|
||||
return got, nil
|
||||
end,
|
||||
})
|
||||
end
|
||||
|
||||
export type NibbleSpec = {
|
||||
buf: buffer,
|
||||
offset: number,
|
||||
size: number, -- bytes
|
||||
hi: boolean?, -- the high nibble first (DVI / KVAG); default low first
|
||||
frames: number?, -- default: every whole frame of nibbles
|
||||
}
|
||||
|
||||
-- nibbles(dec, spec): an IMA stream starting from predictor 0, step index 0, channel c in nibbles c, c + ch, ...
|
||||
function Decoder.nibbles(dec: any, spec: NibbleSpec): (any, Err.Err?)
|
||||
local ch = dec.channels
|
||||
local buf, base = spec.buf, spec.offset
|
||||
local frames = math.min(spec.frames or math.huge, (spec.size * 2) // ch)
|
||||
local st = buffer.create(8 * ch)
|
||||
local hi = spec.hi == true
|
||||
dec.frames = frames
|
||||
dec.duration = frames / dec.sampleRate
|
||||
return Decoder.packets(dec, {
|
||||
count = math.max(1, math.ceil(frames / 4096)),
|
||||
packetFrames = 4096,
|
||||
frames = frames,
|
||||
state = st,
|
||||
decode = function(i: number, out: buffer): (number?, Err.Err?)
|
||||
local f0 = (i - 1) * 4096
|
||||
local n = math.min(4096, frames - f0)
|
||||
for c = 0, ch - 1 do
|
||||
Adpcm.ima(buf, base, f0 * ch + c, ch, n, hi, st, c * 8, out, c, ch)
|
||||
end
|
||||
return n, nil
|
||||
end,
|
||||
})
|
||||
end
|
||||
|
||||
export type BlockSpec = {
|
||||
kind: "ms" | "ima_wav" | "ima_qt",
|
||||
buf: buffer,
|
||||
offset: number,
|
||||
size: number,
|
||||
blockAlign: number?, -- ms / ima_wav: bytes per block
|
||||
frames: number?, -- default: what the blocks hold
|
||||
coefs: { number }?, -- ms: coefficient pairs, flat (default the 7 standard pairs)
|
||||
}
|
||||
|
||||
-- blockFrames(kind, blockAlign, ch) -> frames per block, or nil when the block cannot hold the headers
|
||||
function Decoder.blockFrames(kind: string, ba: number, ch: number): number?
|
||||
if kind == "ima_qt" then
|
||||
return 64
|
||||
elseif kind == "ms" then
|
||||
return if ba >= 7 * ch then (ba - 7 * ch) * 2 // ch + 2 else nil
|
||||
end
|
||||
return if ba >= 4 * ch then (ba - 4 * ch) * 2 // ch + 1 else nil
|
||||
end
|
||||
|
||||
-- blocks(dec, spec): self-contained ADPCM blocks (no state across blocks); a truncated last block decodes what it has
|
||||
function Decoder.blocks(dec: any, spec: BlockSpec): (any, Err.Err?)
|
||||
local ch = dec.channels
|
||||
local kind = spec.kind
|
||||
local ba = if kind == "ima_qt" then 34 * ch else spec.blockAlign or 0
|
||||
local spb = Decoder.blockFrames(kind, ba, ch)
|
||||
if not spb then
|
||||
return nil, Err.new(Err.CORRUPT, "block of " .. ba .. " bytes is too small")
|
||||
end
|
||||
if spb * ch > 2 ^ 20 then
|
||||
return nil, Err.new(Err.LIMIT, "ADPCM block too large")
|
||||
end
|
||||
local buf, base, size = spec.buf, spec.offset, spec.size
|
||||
local full = size // ba
|
||||
local rest = size - full * ba
|
||||
local total = full * spb
|
||||
if kind ~= "ima_qt" and rest > 0 then
|
||||
-- a partial last block: the frames it holds whole
|
||||
if kind == "ms" then
|
||||
total += if rest >= 7 * ch then math.min(spb, 2 + ((rest - 7 * ch) * 2) // ch) else 0
|
||||
elseif rest >= 4 * ch then
|
||||
total += math.min(spb, 1 + ((rest - 4 * ch) // (4 * ch)) * 8)
|
||||
end
|
||||
end
|
||||
local frames = math.min(spec.frames or total, total)
|
||||
local ncoef = 7
|
||||
local cf = spec.coefs
|
||||
if cf and #cf >= 2 then
|
||||
ncoef = math.min(256, #cf // 2)
|
||||
end
|
||||
local coefs = buffer.create(ncoef * 8)
|
||||
for k = 0, ncoef - 1 do
|
||||
buffer.writei32(coefs, k * 8, if cf and #cf >= 2 then cf[k * 2 + 1] else Adpcm.MS_COEF1[k + 1])
|
||||
buffer.writei32(coefs, k * 8 + 4, if cf and #cf >= 2 then cf[k * 2 + 2] else Adpcm.MS_COEF2[k + 1])
|
||||
end
|
||||
local scratch = buffer.create(20 * ch)
|
||||
dec.frames = frames
|
||||
dec.duration = frames / dec.sampleRate
|
||||
dec.blockAlign = ba
|
||||
dec.samplesPerBlock = spb
|
||||
return Decoder.packets(dec, {
|
||||
count = math.max(1, math.ceil(frames / spb)),
|
||||
packetFrames = spb,
|
||||
frames = frames,
|
||||
state = scratch,
|
||||
decode = function(i: number, out: buffer): (number?, Err.Err?)
|
||||
local off = base + (i - 1) * ba
|
||||
local avail = math.min(ba, base + size - off)
|
||||
if kind == "ms" then
|
||||
return Adpcm.msBlock(buf, off, avail, ch, spb, out, 0, coefs, ncoef, scratch), nil
|
||||
elseif kind == "ima_wav" then
|
||||
return Adpcm.imaWav(buf, off, avail, ch, spb, out, 0), nil
|
||||
end
|
||||
if avail < ba then
|
||||
return 0, nil
|
||||
end
|
||||
for c = 0, ch - 1 do
|
||||
Adpcm.imaQt(buf, off + c * 34, scratch, c * 8, out, c, ch)
|
||||
end
|
||||
return 64, nil
|
||||
end,
|
||||
})
|
||||
end
|
||||
|
||||
return Decoder
|
||||
@@ -0,0 +1,707 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/audio/Adpcm: the 4-bit ADPCM family, decode (and encode where it is cheap). New in formats-luau; the IMA and
|
||||
-- MS block decoders moved here from audio/wav/Codecs (wav-luau, same author). ADX coefficients, PS-ADPCM and Nintendo
|
||||
-- DSP decoding follow vgmstream r2117 (ISC licence, licenses/vgmstream-LICENSE.txt) so the output is bit-exact with it:
|
||||
-- the ADX scale + 1 and the version 3 rounding, PS-ADPCM's float filter (exact in integers below 2^17), DSP's 1024
|
||||
-- rounding. Codec kernels only: the formats (wav, aiff, caf, adx, vag, brstm, adpcm, ...) walk the layouts.
|
||||
--
|
||||
-- Decoders write f32 (sample / 32768) to dst at float index d, every ds floats (interleaving), and keep their running
|
||||
-- state in a caller-owned buffer `st` at byte offset `so` (i32 pairs: IMA pred / step index, the others hist1 / hist2),
|
||||
-- so a decoder can stop between calls and snapshot the state for seeking (codecs/audio/Adpcm/Decoder).
|
||||
--
|
||||
-- Adpcm.ima(src, p, q0, qs, count, hi, st, so, dst, d, ds) -- IMA nibbles: count samples, nibble q0, q0+qs, ...
|
||||
-- Adpcm.imaQt(src, p, st, so, dst, d, ds) -- Apple ima4: one 34-byte packet -> 64 samples
|
||||
-- Adpcm.imaWav(src, off, avail, ch, spb, dst, d) -> frames -- Microsoft IMA block (WAV / AVI)
|
||||
-- Adpcm.msBlock(src, off, avail, ch, spb, dst, d, coefs, ncoef, st) -> frames -- MS ADPCM block
|
||||
-- Adpcm.adx(src, p, pstride, nframes, c1, c2, v3, st, so, dst, d, ds) -- CRI ADX: 18-byte frames, 32 samples
|
||||
-- Adpcm.adxCoefs(cutoff, rate) -> c1, c2
|
||||
-- Adpcm.psx(src, p, pstride, nframes, st, so, dst, d, ds) -- Sony PS-ADPCM (VAG): 16-byte frames, 28 samples
|
||||
-- Adpcm.dsp(src, p, count, coefs, co, st, so, dst, d, ds) -- Nintendo DSP: 8-byte frames, 14 samples
|
||||
-- Adpcm.modplug(src, p, count, dst, d) -- ModPlug ADPCM (XM / MOD samples)
|
||||
-- encoders: imaEncode, imaWavEncode, msEncode, adxEncode, psxEncode, dspEncode (see each)
|
||||
--
|
||||
-- Every function reads only the bytes its arguments describe: the caller checks the ranges (byte counts per call are
|
||||
-- documented on each). Never throws.
|
||||
local readu8, readi16, readu16, readi32 = buffer.readu8, buffer.readi16, buffer.readu16, buffer.readi32
|
||||
local writef32, readf32, writei32, writeu8, writeu16 = buffer.writef32, buffer.readf32, buffer.writei32, buffer.writeu8, buffer.writeu16
|
||||
local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lshift
|
||||
local floor = math.floor
|
||||
|
||||
local Adpcm = {}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ IMA
|
||||
local IMA_STEP = {
|
||||
7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
|
||||
130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060,
|
||||
1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484,
|
||||
7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767,
|
||||
}
|
||||
local IMA_ADJ = { -1, -1, -1, -1, 2, 4, 6, 8, -1, -1, -1, -1, 2, 4, 6, 8 }
|
||||
-- IMA_DIFF[index * 8 + (nibble & 7) + 1]: the shift-and-add difference (step/8 + bits of step/4, step/2, step), as
|
||||
-- the IMA reference computes it (not (2n + 1) * step / 8, which rounds differently)
|
||||
local IMA_DIFF = table.create(89 * 8, 0)
|
||||
-- IMA_NEXT[index * 16 + nibble + 1]: the next step index
|
||||
local IMA_NEXT = table.create(89 * 16, 0)
|
||||
for i = 0, 88 do
|
||||
local step = IMA_STEP[i + 1]
|
||||
for n = 0, 7 do
|
||||
local d = rshift(step, 3)
|
||||
if band(n, 1) ~= 0 then
|
||||
d += rshift(step, 2)
|
||||
end
|
||||
if band(n, 2) ~= 0 then
|
||||
d += rshift(step, 1)
|
||||
end
|
||||
if band(n, 4) ~= 0 then
|
||||
d += step
|
||||
end
|
||||
IMA_DIFF[i * 8 + n + 1] = d
|
||||
end
|
||||
for n = 0, 15 do
|
||||
IMA_NEXT[i * 16 + n + 1] = math.clamp(i + IMA_ADJ[n + 1], 0, 88)
|
||||
end
|
||||
end
|
||||
Adpcm.IMA_STEP = IMA_STEP
|
||||
|
||||
-- ima: `count` samples of one channel from a nibble stream at byte p: nibble q0, q0 + qs, q0 + 2 qs, ... (nibble q is
|
||||
-- in byte p + q // 2, the low half first unless hi). State: st[so] predictor, st[so + 4] step index. Reads bytes
|
||||
-- p .. p + (q0 + (count - 1) * qs) // 2.
|
||||
function Adpcm.ima(src: buffer, p: number, q0: number, qs: number, count: number, hi: boolean, st: buffer, so: number,
|
||||
dst: buffer, d: number, ds: number)
|
||||
local pred = readi32(st, so)
|
||||
local index = math.clamp(readi32(st, so + 4), 0, 88)
|
||||
local q = q0
|
||||
local o = d * 4
|
||||
local os = ds * 4
|
||||
for _ = 1, count do
|
||||
local b = readu8(src, p + rshift(q, 1))
|
||||
local nib
|
||||
if (band(q, 1) == 0) == hi then
|
||||
nib = rshift(b, 4)
|
||||
else
|
||||
nib = band(b, 15)
|
||||
end
|
||||
local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1]
|
||||
if nib >= 8 then
|
||||
pred -= diff
|
||||
if pred < -32768 then
|
||||
pred = -32768
|
||||
end
|
||||
else
|
||||
pred += diff
|
||||
if pred > 32767 then
|
||||
pred = 32767
|
||||
end
|
||||
end
|
||||
index = IMA_NEXT[index * 16 + nib + 1]
|
||||
writef32(dst, o, pred / 32768)
|
||||
o += os
|
||||
q += qs
|
||||
end
|
||||
writei32(st, so, pred)
|
||||
writei32(st, so + 4, index)
|
||||
end
|
||||
|
||||
-- imaQt: one Apple ima4 packet (34 bytes at p: a big-endian header, the predictor's top 9 bits and the 7-bit step
|
||||
-- index, then 64 nibbles low first) -> 64 samples. Apple's decoders keep the running full-precision predictor while
|
||||
-- the header agrees with it (the same step index, the predictor within 127): st carries it from packet to packet
|
||||
-- (zeros before the first).
|
||||
function Adpcm.imaQt(src: buffer, p: number, st: buffer, so: number, dst: buffer, d: number, ds: number)
|
||||
local h = readu8(src, p) * 256 + readu8(src, p + 1)
|
||||
local pred = band(h, 0xFF80)
|
||||
if pred >= 32768 then
|
||||
pred -= 65536
|
||||
end
|
||||
local index = band(h, 0x7F)
|
||||
if index ~= readi32(st, so + 4) or math.abs(pred - readi32(st, so)) > 0x7F then
|
||||
writei32(st, so, pred)
|
||||
writei32(st, so + 4, index)
|
||||
end
|
||||
Adpcm.ima(src, p + 2, 0, 1, 64, false, st, so, dst, d, ds)
|
||||
end
|
||||
|
||||
-- imaWav: one Microsoft IMA ADPCM block (WAV / AVI) at src[off]: per channel a 4-byte header (s16 predictor = the
|
||||
-- first sample, u8 step index, pad), then groups of 4 bytes (8 nibbles, low first) per channel in turn. avail: the
|
||||
-- bytes present (a truncated last block decodes the whole groups it has). Writes interleaved frames to dst from float
|
||||
-- index d; returns the frame count (<= spb).
|
||||
function Adpcm.imaWav(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer, d: number): number
|
||||
if avail < 4 * ch then
|
||||
return 0
|
||||
end
|
||||
local groups = (avail - 4 * ch) // (4 * ch)
|
||||
local frames = math.min(spb, 1 + groups * 8)
|
||||
local o = d * 4
|
||||
for c = 0, ch - 1 do
|
||||
local pred = readi16(src, off + c * 4)
|
||||
local index = math.min(readu8(src, off + c * 4 + 2), 88)
|
||||
writef32(dst, o + c * 4, pred / 32768)
|
||||
local f = 1
|
||||
local g = 0
|
||||
while f < frames do
|
||||
local p = off + 4 * ch + (g * ch + c) * 4
|
||||
local k = 0
|
||||
while k < 8 and f < frames do
|
||||
local b = readu8(src, p + rshift(k, 1))
|
||||
local nib = if band(k, 1) == 0 then band(b, 15) else rshift(b, 4)
|
||||
local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1]
|
||||
if nib >= 8 then
|
||||
pred -= diff
|
||||
if pred < -32768 then
|
||||
pred = -32768
|
||||
end
|
||||
else
|
||||
pred += diff
|
||||
if pred > 32767 then
|
||||
pred = 32767
|
||||
end
|
||||
end
|
||||
index = IMA_NEXT[index * 16 + nib + 1]
|
||||
writef32(dst, o + (f * ch + c) * 4, pred / 32768)
|
||||
f += 1
|
||||
k += 1
|
||||
end
|
||||
g += 1
|
||||
end
|
||||
end
|
||||
return frames
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ MS ADPCM
|
||||
local MS_ADAPT = { 230, 230, 230, 230, 307, 409, 512, 614, 768, 614, 512, 409, 307, 230, 230, 230 }
|
||||
Adpcm.MS_COEF1 = { 256, 512, 0, 192, 240, 460, 392 }
|
||||
Adpcm.MS_COEF2 = { 0, -256, 0, 64, 0, -208, -232 }
|
||||
|
||||
-- msBlock: one MS ADPCM block: per channel u8 predictor index, s16 delta, s16 sample 1, s16 sample 2 (each field for
|
||||
-- every channel in turn), then nibbles high first, channels interleaved per nibble. coefs: i32 pairs (coef1, coef2) x
|
||||
-- ncoef (256 = 1.0). state: 20 * ch bytes of scratch. avail: the bytes present. Writes interleaved frames to dst from
|
||||
-- float index d; returns the frame count (<= spb).
|
||||
function Adpcm.msBlock(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer, d: number,
|
||||
coefs: buffer, ncoef: number, state: buffer): number
|
||||
local hdr = 7 * ch
|
||||
if avail < hdr or ncoef < 1 then
|
||||
return 0
|
||||
end
|
||||
local frames = math.min(spb, 2 + ((avail - hdr) * 2) // ch)
|
||||
local o = d * 4
|
||||
for c = 0, ch - 1 do
|
||||
local pi = math.min(readu8(src, off + c), ncoef - 1)
|
||||
local idelta = readi16(src, off + ch + c * 2)
|
||||
local s1 = readi16(src, off + 3 * ch + c * 2)
|
||||
local s2 = readi16(src, off + 5 * ch + c * 2)
|
||||
local so = c * 20
|
||||
writei32(state, so, readi32(coefs, pi * 8))
|
||||
writei32(state, so + 4, readi32(coefs, pi * 8 + 4))
|
||||
writei32(state, so + 8, idelta)
|
||||
writei32(state, so + 12, s1)
|
||||
writei32(state, so + 16, s2)
|
||||
writef32(dst, o + c * 4, s2 / 32768)
|
||||
if frames > 1 then
|
||||
writef32(dst, o + (ch + c) * 4, s1 / 32768)
|
||||
end
|
||||
end
|
||||
local total = (frames - 2) * ch
|
||||
for k = 0, total - 1 do
|
||||
local b = readu8(src, off + hdr + rshift(k, 1))
|
||||
local nib = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15)
|
||||
local so = (k % ch) * 20
|
||||
local c1, c2 = readi32(state, so), readi32(state, so + 4)
|
||||
local idelta = readi32(state, so + 8)
|
||||
local s1, s2 = readi32(state, so + 12), readi32(state, so + 16)
|
||||
local p = s1 * c1 + s2 * c2
|
||||
p = if p >= 0 then p // 256 else -((-p) // 256)
|
||||
p += (if nib >= 8 then nib - 16 else nib) * idelta
|
||||
if p > 32767 then
|
||||
p = 32767
|
||||
elseif p < -32768 then
|
||||
p = -32768
|
||||
end
|
||||
idelta = (MS_ADAPT[nib + 1] * idelta) // 256
|
||||
if idelta < 16 then
|
||||
idelta = 16
|
||||
elseif idelta > 2796202 then -- INT_MAX / 768
|
||||
idelta = 2796202
|
||||
end
|
||||
writei32(state, so + 8, idelta)
|
||||
writei32(state, so + 12, p)
|
||||
writei32(state, so + 16, s1)
|
||||
writef32(dst, o + (2 * ch + k) * 4, p / 32768)
|
||||
end
|
||||
return frames
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ CRI ADX
|
||||
local F32 = buffer.create(4)
|
||||
local function f32(x: number): number
|
||||
writef32(F32, 0, x)
|
||||
return readf32(F32, 0)
|
||||
end
|
||||
|
||||
-- adxCoefs(cutoff, rate) -> coef1, coef2 (fixed point, 12 fractional bits): the 2-pole high-pass predictor from the
|
||||
-- header's cutoff frequency, in single precision as CRI's decoders (and vgmstream) compute it
|
||||
function Adpcm.adxCoefs(cutoff: number, rate: number): (number, number)
|
||||
if rate <= 0 then
|
||||
return 0, 0
|
||||
end
|
||||
local z = f32(math.cos(f32(2 * math.pi * cutoff / rate)))
|
||||
local a = f32(math.sqrt(2) - z)
|
||||
local b = f32(math.sqrt(2) - 1)
|
||||
local c = f32(f32(a - f32(math.sqrt(f32(f32(a + b) * f32(a - b))))) / b)
|
||||
local c1 = c * 8192
|
||||
local c2 = f32(c * c) * -4096
|
||||
c1 = if c1 >= 0 then floor(c1) else -floor(-c1)
|
||||
c2 = if c2 >= 0 then floor(c2) else -floor(-c2)
|
||||
return c1, c2
|
||||
end
|
||||
|
||||
-- adx: nframes 18-byte frames of one channel (s16 big-endian scale, 32 nibbles high first), pstride bytes apart from
|
||||
-- p. v3: the version 3 rounding (each product shifted on its own). A scale of 0x8001 (CRI's end marker) decodes as
|
||||
-- silence. Reads p .. p + (nframes - 1) * pstride + 17; writes 32 * nframes samples.
|
||||
function Adpcm.adx(src: buffer, p: number, pstride: number, nframes: number, c1: number, c2: number, v3: boolean,
|
||||
st: buffer, so: number, dst: buffer, d: number, ds: number)
|
||||
local h1, h2 = readi32(st, so), readi32(st, so + 4)
|
||||
local o = d * 4
|
||||
local os = ds * 4
|
||||
for f = 0, nframes - 1 do
|
||||
local fp = p + f * pstride
|
||||
local scale = readu8(src, fp) * 256 + readu8(src, fp + 1)
|
||||
if scale == 0x8001 then
|
||||
scale = 0
|
||||
elseif scale >= 32768 then
|
||||
scale -= 65535 -- the signed value + 1
|
||||
else
|
||||
scale += 1
|
||||
end
|
||||
for k = 0, 31 do
|
||||
local b = readu8(src, fp + 2 + rshift(k, 1))
|
||||
local n = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15)
|
||||
if n >= 8 then
|
||||
n -= 16
|
||||
end
|
||||
local s
|
||||
if v3 then
|
||||
s = n * scale + (c1 * h1) // 4096 + (c2 * h2) // 4096
|
||||
else
|
||||
s = n * scale + (c1 * h1 + c2 * h2) // 4096
|
||||
end
|
||||
if s > 32767 then
|
||||
s = 32767
|
||||
elseif s < -32768 then
|
||||
s = -32768
|
||||
end
|
||||
h2 = h1
|
||||
h1 = s
|
||||
writef32(dst, o, s / 32768)
|
||||
o += os
|
||||
end
|
||||
end
|
||||
writei32(st, so, h1)
|
||||
writei32(st, so + 4, h2)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ PS-ADPCM
|
||||
local PSX1 = { 0, 60, 115, 98, 122 }
|
||||
local PSX2 = { 0, 0, -52, -55, -60 }
|
||||
|
||||
-- the filter term (c1 * h1 + c2 * h2) / 64 * 256 truncated, as vgmstream's single-precision float code computes it:
|
||||
-- exact in integers while the products fit a float's 24 bits
|
||||
local function psxPred(f: number, h1: number, h2: number): number
|
||||
local x = PSX1[f] * h1 + PSX2[f] * h2
|
||||
if h1 > -65536 and h1 < 65536 and h2 > -65536 and h2 < 65536 then
|
||||
return 4 * x
|
||||
end
|
||||
local v = f32(f32(f32(PSX1[f] / 64) * h1) + f32(f32(PSX2[f] / 64) * h2)) * 256
|
||||
return if v >= 0 then floor(v) else -floor(-v)
|
||||
end
|
||||
|
||||
-- psx: nframes 16-byte frames of one channel (filter << 4 | shift, flags, 28 nibbles low first), pstride bytes apart
|
||||
-- from p. Filters past 4 decode as 0 and shifts past 12 as 9 (as vgmstream); a frame with flags 7 is silence. The
|
||||
-- history keeps the unclipped value. Reads p .. p + (nframes - 1) * pstride + 15; writes 28 * nframes samples.
|
||||
function Adpcm.psx(src: buffer, p: number, pstride: number, nframes: number, st: buffer, so: number, dst: buffer,
|
||||
d: number, ds: number)
|
||||
local h1, h2 = readi32(st, so), readi32(st, so + 4)
|
||||
local o = d * 4
|
||||
local os = ds * 4
|
||||
for f = 0, nframes - 1 do
|
||||
local fp = p + f * pstride
|
||||
local head = readu8(src, fp)
|
||||
local filter = rshift(head, 4)
|
||||
local shift = band(head, 15)
|
||||
if filter > 4 then
|
||||
filter = 0
|
||||
end
|
||||
if shift > 12 then
|
||||
shift = 9
|
||||
end
|
||||
local mul = 2 ^ (20 - shift)
|
||||
local fi = filter + 1
|
||||
local silent = band(readu8(src, fp + 1), 15) == 7
|
||||
for k = 0, 27 do
|
||||
local s = 0
|
||||
if not silent then
|
||||
local b = readu8(src, fp + 2 + rshift(k, 1))
|
||||
local n = if band(k, 1) == 0 then band(b, 15) else rshift(b, 4)
|
||||
if n >= 8 then
|
||||
n -= 16
|
||||
end
|
||||
s = (n * mul + psxPred(fi, h1, h2)) // 256
|
||||
end
|
||||
h2 = h1
|
||||
h1 = s
|
||||
if s > 32767 then
|
||||
s = 32767
|
||||
elseif s < -32768 then
|
||||
s = -32768
|
||||
end
|
||||
writef32(dst, o, s / 32768)
|
||||
o += os
|
||||
end
|
||||
end
|
||||
writei32(st, so, h1)
|
||||
writei32(st, so + 4, h2)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ Nintendo DSP
|
||||
-- dsp: count samples of one channel from 8-byte frames at p (predictor << 4 | scale shift, 14 nibbles high first).
|
||||
-- coefs: 16 i32 at byte co (8 pairs, 11 fractional bits); a predictor index past 7 uses pair 7. Reads p ..
|
||||
-- p + ceil(count / 14) * 8 - 1.
|
||||
function Adpcm.dsp(src: buffer, p: number, count: number, coefs: buffer, co: number, st: buffer, so: number,
|
||||
dst: buffer, d: number, ds: number)
|
||||
local h1, h2 = readi32(st, so), readi32(st, so + 4)
|
||||
local o = d * 4
|
||||
local os = ds * 4
|
||||
local done = 0
|
||||
local fp = p
|
||||
while done < count do
|
||||
local head = readu8(src, fp)
|
||||
local pi = math.min(rshift(head, 4), 7)
|
||||
local scale = 2 ^ band(head, 15) * 2048
|
||||
local c1, c2 = readi32(coefs, co + pi * 8), readi32(coefs, co + pi * 8 + 4)
|
||||
local n14 = math.min(14, count - done)
|
||||
for k = 0, n14 - 1 do
|
||||
local b = readu8(src, fp + 1 + rshift(k, 1))
|
||||
local n = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15)
|
||||
if n >= 8 then
|
||||
n -= 16
|
||||
end
|
||||
local s = (n * scale + 1024 + c1 * h1 + c2 * h2) // 2048
|
||||
if s > 32767 then
|
||||
s = 32767
|
||||
elseif s < -32768 then
|
||||
s = -32768
|
||||
end
|
||||
h2 = h1
|
||||
h1 = s
|
||||
writef32(dst, o, s / 32768)
|
||||
o += os
|
||||
end
|
||||
done += n14
|
||||
fp += 8
|
||||
end
|
||||
writei32(st, so, h1)
|
||||
writei32(st, so + 4, h2)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encoders
|
||||
-- the nearest s16 to x * 32768 (NaN -> 0)
|
||||
local function toS16(x: number): number
|
||||
local v = floor(x * 32768 + 0.5)
|
||||
if v ~= v then
|
||||
return 0
|
||||
elseif v > 32767 then
|
||||
return 32767
|
||||
elseif v < -32768 then
|
||||
return -32768
|
||||
end
|
||||
return v
|
||||
end
|
||||
Adpcm.toS16 = toS16
|
||||
|
||||
-- the IMA nibble for x from (pred, index): the one whose decoded value lands nearest (greedy, all 16 tried)
|
||||
local function imaNibble(x: number, pred: number, index: number): number
|
||||
local base = index * 8 + 1
|
||||
local best, bestErr = 0, math.huge
|
||||
for m = 0, 7 do
|
||||
local diff = IMA_DIFF[base + m]
|
||||
local up = math.min(pred + diff, 32767)
|
||||
local e = math.abs(x - up)
|
||||
if e < bestErr then
|
||||
best, bestErr = m, e
|
||||
end
|
||||
local down = math.max(pred - diff, -32768)
|
||||
e = math.abs(x - down)
|
||||
if e < bestErr then
|
||||
best, bestErr = m + 8, e
|
||||
end
|
||||
end
|
||||
return best
|
||||
end
|
||||
|
||||
-- imaEncode: count samples of one channel, f32 at float index xi every xs floats of x, into nibbles q0, q0 + qs, ...
|
||||
-- of out at byte p (the other half of each byte is kept). State as Adpcm.ima. Writes bytes p ..
|
||||
-- p + (q0 + (count - 1) * qs) // 2.
|
||||
function Adpcm.imaEncode(x: buffer, xi: number, xs: number, count: number, st: buffer, so: number, out: buffer,
|
||||
p: number, q0: number, qs: number, hi: boolean)
|
||||
local pred = readi32(st, so)
|
||||
local index = math.clamp(readi32(st, so + 4), 0, 88)
|
||||
local q = q0
|
||||
for i = 0, count - 1 do
|
||||
local v = toS16(readf32(x, (xi + i * xs) * 4))
|
||||
local nib = imaNibble(v, pred, index)
|
||||
local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1]
|
||||
pred = if nib >= 8 then math.max(pred - diff, -32768) else math.min(pred + diff, 32767)
|
||||
index = IMA_NEXT[index * 16 + nib + 1]
|
||||
local bp = p + rshift(q, 1)
|
||||
local b = readu8(out, bp)
|
||||
if (band(q, 1) == 0) == hi then
|
||||
b = bor(band(b, 0x0F), lshift(nib, 4))
|
||||
else
|
||||
b = bor(band(b, 0xF0), nib)
|
||||
end
|
||||
writeu8(out, bp, b)
|
||||
q += qs
|
||||
end
|
||||
writei32(st, so, pred)
|
||||
writei32(st, so + 4, index)
|
||||
end
|
||||
|
||||
-- imaWavEncode: one Microsoft IMA block of spb frames (spb = 1 + 8k) from interleaved f32 x at frame xf (frames
|
||||
-- available: n; the rest is padded with the last sample) to out[off] (4 * ch + (spb - 1) / 2 * ch bytes). st: 8 * ch
|
||||
-- bytes carrying the step index from block to block.
|
||||
function Adpcm.imaWavEncode(x: buffer, xf: number, n: number, ch: number, spb: number, st: buffer, out: buffer, off: number)
|
||||
local groups = (spb - 1) // 8
|
||||
for c = 0, ch - 1 do
|
||||
local so = c * 8
|
||||
local first = if n > 0 then toS16(readf32(x, (xf * ch + c) * 4)) else 0
|
||||
writei32(st, so, first)
|
||||
local index = math.clamp(readi32(st, so + 4), 0, 88)
|
||||
writei32(st, so + 4, index)
|
||||
buffer.writei16(out, off + c * 4, first)
|
||||
writeu8(out, off + c * 4 + 2, index)
|
||||
writeu8(out, off + c * 4 + 3, 0)
|
||||
local pred = first
|
||||
for g = 0, groups - 1 do
|
||||
local gp = off + 4 * ch + (g * ch + c) * 4
|
||||
for k = 0, 7 do
|
||||
local f = 1 + g * 8 + k
|
||||
local v = if f < n then toS16(readf32(x, ((xf + f) * ch + c) * 4)) else pred
|
||||
local nib = imaNibble(v, pred, index)
|
||||
local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1]
|
||||
pred = if nib >= 8 then math.max(pred - diff, -32768) else math.min(pred + diff, 32767)
|
||||
index = IMA_NEXT[index * 16 + nib + 1]
|
||||
local bp = gp + rshift(k, 1)
|
||||
if band(k, 1) == 0 then
|
||||
writeu8(out, bp, nib)
|
||||
else
|
||||
writeu8(out, bp, bor(readu8(out, bp), lshift(nib, 4)))
|
||||
end
|
||||
end
|
||||
end
|
||||
writei32(st, so + 4, index)
|
||||
end
|
||||
end
|
||||
|
||||
-- one MS ADPCM channel run for the encoder: the nibbles for samples 2 .. n - 1 with predictor (c1, c2) and the first
|
||||
-- delta; returns the squared error and the nibbles in nibs (when given)
|
||||
local function msTrial(xs: { number }, n: number, c1: number, c2: number, delta0: number, nibs: { number }?): number
|
||||
local s1, s2 = xs[2], xs[1]
|
||||
local idelta = delta0
|
||||
local err = 0
|
||||
for i = 3, n do
|
||||
local p = s1 * c1 + s2 * c2
|
||||
p = if p >= 0 then p // 256 else -((-p) // 256)
|
||||
local e = xs[i] - p
|
||||
local nib = if e >= 0 then (e + idelta // 2) // idelta else -((-e + idelta // 2) // idelta)
|
||||
nib = math.clamp(nib, -8, 7)
|
||||
local v = math.clamp(p + nib * idelta, -32768, 32767)
|
||||
err += (xs[i] - v) * (xs[i] - v)
|
||||
if nibs then
|
||||
nibs[i] = band(nib, 15)
|
||||
end
|
||||
idelta = math.clamp((MS_ADAPT[band(nib, 15) + 1] * idelta) // 256, 16, 2796202)
|
||||
s2 = s1
|
||||
s1 = v
|
||||
end
|
||||
return err
|
||||
end
|
||||
|
||||
-- msEncode: one MS ADPCM block of spb frames (standard 7 coefficient pairs) from interleaved f32 x at frame xf
|
||||
-- (frames available: n; the rest is padded with silence) to out[off] (7 * ch + (spb - 2) * ch / 2 bytes). Each channel
|
||||
-- takes the predictor with the least error.
|
||||
function Adpcm.msEncode(x: buffer, xf: number, n: number, ch: number, spb: number, out: buffer, off: number)
|
||||
local C1, C2 = Adpcm.MS_COEF1, Adpcm.MS_COEF2
|
||||
local xs = table.create(spb, 0)
|
||||
local nibs = table.create(spb, 0)
|
||||
local all = table.create(spb * ch, 0)
|
||||
for c = 0, ch - 1 do
|
||||
for i = 1, spb do
|
||||
xs[i] = if i <= n then toS16(readf32(x, ((xf + i - 1) * ch + c) * 4)) else 0
|
||||
end
|
||||
-- the first delta from the first steps
|
||||
local sum = 0
|
||||
for i = 3, math.min(spb, 10) do
|
||||
sum += math.abs(xs[i] - xs[i - 1])
|
||||
end
|
||||
local delta0 = math.clamp(sum // 16, 16, 32767)
|
||||
local best, bestErr = 1, math.huge
|
||||
for k = 1, 7 do
|
||||
local e = msTrial(xs, spb, C1[k], C2[k], delta0, nil)
|
||||
if e < bestErr then
|
||||
best, bestErr = k, e
|
||||
end
|
||||
end
|
||||
msTrial(xs, spb, C1[best], C2[best], delta0, nibs)
|
||||
writeu8(out, off + c, best - 1)
|
||||
writeu16(out, off + ch + c * 2, delta0)
|
||||
buffer.writei16(out, off + 3 * ch + c * 2, xs[2] or 0)
|
||||
buffer.writei16(out, off + 5 * ch + c * 2, xs[1])
|
||||
for i = 3, spb do
|
||||
all[(i - 3) * ch + c + 1] = nibs[i]
|
||||
end
|
||||
end
|
||||
local total = (spb - 2) * ch
|
||||
for k = 0, total - 1, 2 do
|
||||
writeu8(out, off + 7 * ch + k // 2, all[k + 1] * 16 + (all[k + 2] or 0))
|
||||
end
|
||||
end
|
||||
|
||||
-- one ADX frame for the encoder: the squared error of encoding xs[1..32] with scale from (h1, h2) (v4 rounding), and
|
||||
-- the nibbles in nibs when given; returns the error and the new history
|
||||
local function adxTrial(xs: { number }, scale: number, c1: number, c2: number, h1: number, h2: number, nibs: { number }?): (number, number, number)
|
||||
local err = 0
|
||||
for k = 1, 32 do
|
||||
local pred = (c1 * h1 + c2 * h2) // 4096
|
||||
local e = xs[k] - pred
|
||||
local n = if e >= 0 then (e + scale // 2) // scale else -((-e + scale // 2) // scale)
|
||||
n = math.clamp(n, -8, 7)
|
||||
local s = math.clamp(n * scale + pred, -32768, 32767)
|
||||
err += (xs[k] - s) * (xs[k] - s)
|
||||
if nibs then
|
||||
nibs[k] = band(n, 15)
|
||||
end
|
||||
h2 = h1
|
||||
h1 = s
|
||||
end
|
||||
return err, h1, h2
|
||||
end
|
||||
|
||||
-- adxEncode: count samples of one channel (f32 at float index xi every xs floats of x) as ceil(count / 32) ADX frames
|
||||
-- (v4 rounding, the scale stored minus one as CRI's decoders add it back) at out[p], pstride bytes apart; the frame
|
||||
-- past count is padded with silence. State as Adpcm.adx.
|
||||
function Adpcm.adxEncode(x: buffer, xi: number, xs: number, count: number, c1: number, c2: number, st: buffer, so: number,
|
||||
out: buffer, p: number, pstride: number)
|
||||
local h1, h2 = readi32(st, so), readi32(st, so + 4)
|
||||
local v = table.create(32, 0)
|
||||
local nibs = table.create(32, 0)
|
||||
for f = 0, (count + 31) // 32 - 1 do
|
||||
local peak = 0
|
||||
local a, b = h1, h2
|
||||
for k = 1, 32 do
|
||||
local i = f * 32 + k - 1
|
||||
local s = if i < count then toS16(readf32(x, (xi + i * xs) * 4)) else 0
|
||||
v[k] = s
|
||||
peak = math.max(peak, math.abs(s - (c1 * a + c2 * b) // 4096))
|
||||
b = a
|
||||
a = s
|
||||
end
|
||||
-- the scale that covers the open-loop residual peak, and a few around it, closed loop
|
||||
local base = math.max(1, (peak + 6) // 7)
|
||||
local best, bestErr = base, math.huge
|
||||
for _, m in { 1, 0.75, 1.25, 0.5, 1.6 } do
|
||||
local sc = math.clamp(floor(base * m + 0.5), 1, 0x7FFF)
|
||||
local e = adxTrial(v, sc, c1, c2, h1, h2, nil)
|
||||
if e < bestErr then
|
||||
best, bestErr = sc, e
|
||||
end
|
||||
end
|
||||
local _, n1, n2 = adxTrial(v, best, c1, c2, h1, h2, nibs)
|
||||
h1, h2 = n1, n2
|
||||
local fp = p + f * pstride
|
||||
writeu8(out, fp, rshift(best - 1, 8))
|
||||
writeu8(out, fp + 1, band(best - 1, 255))
|
||||
for k = 0, 15 do
|
||||
writeu8(out, fp + 2 + k, nibs[k * 2 + 1] * 16 + nibs[k * 2 + 2])
|
||||
end
|
||||
end
|
||||
writei32(st, so, h1)
|
||||
writei32(st, so + 4, h2)
|
||||
end
|
||||
|
||||
-- psxEncode: count samples of one channel (f32 at float index xi every xs floats of x) as ceil(count / 28) PS-ADPCM
|
||||
-- frames at out[p], pstride bytes apart, flags byte 0 (the caller sets loop / end flags); every filter and shift is
|
||||
-- tried per frame against Adpcm.psx's decoding, the least squared error wins. State as Adpcm.psx.
|
||||
function Adpcm.psxEncode(x: buffer, xi: number, xs: number, count: number, st: buffer, so: number, out: buffer,
|
||||
p: number, pstride: number)
|
||||
local h1, h2 = readi32(st, so), readi32(st, so + 4)
|
||||
local v = table.create(28, 0)
|
||||
local nibs = table.create(28, 0)
|
||||
for f = 0, (count + 27) // 28 - 1 do
|
||||
for k = 1, 28 do
|
||||
local i = f * 28 + k - 1
|
||||
v[k] = if i < count then toS16(readf32(x, (xi + i * xs) * 4)) else 0
|
||||
end
|
||||
local bestErr, bestHead = math.huge, 0
|
||||
for fi = 1, 5 do
|
||||
for shift = 0, 12 do
|
||||
local mul = 2 ^ (20 - shift)
|
||||
local a, b = h1, h2
|
||||
local err = 0
|
||||
for k = 1, 28 do
|
||||
local pred = psxPred(fi, a, b)
|
||||
local n = floor((v[k] * 256 - pred) / mul + 0.5)
|
||||
n = if n > 7 then 7 elseif n < -8 then -8 else n
|
||||
local s = (n * mul + pred) // 256
|
||||
local c = if s > 32767 then 32767 elseif s < -32768 then -32768 else s
|
||||
err += (v[k] - c) * (v[k] - c)
|
||||
if err >= bestErr then
|
||||
break
|
||||
end
|
||||
b = a
|
||||
a = s
|
||||
end
|
||||
if err < bestErr then
|
||||
bestErr, bestHead = err, (fi - 1) * 16 + shift
|
||||
end
|
||||
end
|
||||
end
|
||||
-- the winner again, for its nibbles and history
|
||||
local fi, shift = rshift(bestHead, 4) + 1, band(bestHead, 15)
|
||||
local mul = 2 ^ (20 - shift)
|
||||
for k = 1, 28 do
|
||||
local pred = psxPred(fi, h1, h2)
|
||||
local n = math.clamp(floor((v[k] * 256 - pred) / mul + 0.5), -8, 7)
|
||||
nibs[k] = band(n, 15)
|
||||
h2 = h1
|
||||
h1 = (n * mul + pred) // 256
|
||||
end
|
||||
local fp = p + f * pstride
|
||||
writeu8(out, fp, bestHead)
|
||||
writeu8(out, fp + 1, 0)
|
||||
for k = 0, 13 do
|
||||
writeu8(out, fp + 2 + k, nibs[k * 2 + 1] + nibs[k * 2 + 2] * 16)
|
||||
end
|
||||
end
|
||||
writei32(st, so, h1)
|
||||
writei32(st, so + 4, h2)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ ModPlug
|
||||
-- modplug: ModPlug / OpenMPT ADPCM samples (XM / MOD sample data marked 0xAD): a table of 16 signed byte deltas at
|
||||
-- p, then count nibbles (low first) at p + 16, each adding its table delta to a running signed byte (wrapping).
|
||||
-- Writes count f32 (value / 128) to dst from float index d. Reads p .. p + 16 + ceil(count / 2) - 1.
|
||||
function Adpcm.modplug(src: buffer, p: number, count: number, dst: buffer, d: number)
|
||||
local tab = table.create(16, 0)
|
||||
for k = 0, 15 do
|
||||
tab[k + 1] = buffer.readi8(src, p + k)
|
||||
end
|
||||
local v = 0
|
||||
for i = 0, count - 1 do
|
||||
local b = readu8(src, p + 16 + rshift(i, 1))
|
||||
local nib = if band(i, 1) == 0 then band(b, 15) else rshift(b, 4)
|
||||
v = (v + tab[nib + 1] + 128) % 256 - 128
|
||||
writef32(dst, (d + i) * 4, v / 128)
|
||||
end
|
||||
end
|
||||
|
||||
return Adpcm
|
||||
@@ -0,0 +1,778 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/audio/Ape/Decode: one Monkey's Audio frame -> samples. Ported from the Monkey's Audio SDK 13.28 (Matthew T.
|
||||
-- Ashland, BSD 3-clause, licenses/monkeys-audio-LICENSE.txt): UnBitArray.cpp (the range coder and its value model,
|
||||
-- 3.99+) and Old/UnBitArrayOld.cpp (CUnBitArray3891To3989, the 3.95 - 3.98 model), NNFilter / NNFilterCommon.h (the
|
||||
-- neural-net filters of the normal .. insane levels), NewPredictor.cpp (CPredictorDecompress3950toCurrent, its int32
|
||||
-- and int64 flavours), ScaledFirstOrderFilter.h, Prepare.cpp (Unprepare: X / Y -> channels), APEDecompressCore.cpp
|
||||
-- (special frames, the frame CRC) and FloatTransform.cpp. Never throws: returns nil, message.
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
|
||||
local readu8, readu32, writeu32, byteswap = buffer.readu8, buffer.readu32, buffer.writeu32, bit32.byteswap
|
||||
local writeu8, writei16, writeu16, writei32, readf32 = buffer.writeu8, buffer.writei16, buffer.writeu16, buffer.writei32, buffer.readf32
|
||||
local readi16, readi32 = buffer.readi16, buffer.readi32
|
||||
local band, bor, bnot, rshift, lshift, bxor = bit32.band, bit32.bor, bit32.bnot, bit32.rshift, bit32.lshift, bit32.bxor
|
||||
local sign = math.sign
|
||||
|
||||
local Decode = {}
|
||||
|
||||
local TWO31, TWO32 = 2147483648, 4294967296
|
||||
local PAD = 64
|
||||
|
||||
-- the range coder's symbol models (UnBitArrayBase.h)
|
||||
local RT1 = { 0, 14824, 28224, 39348, 47855, 53994, 58171, 60926, 62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419, 65450, 65469, 65480, 65487, 65491, 65493, 65494, 65495, 65496, 65497, 65498, 65499, 65500, 65501, 65502, 65503, 65504, 65505, 65506, 65507, 65508, 65509, 65510, 65511, 65512, 65513, 65514, 65515, 65516, 65517, 65518, 65519, 65520, 65521, 65522, 65523, 65524, 65525, 65526, 65527, 65528, 65529, 65530, 65531, 65532, 65533, 65534, 65535, 65536 }
|
||||
local RT2 = { 0, 19578, 36160, 48417, 56323, 60899, 63265, 64435, 64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482, 65485, 65488, 65490, 65491, 65492, 65493, 65494, 65495, 65496, 65497, 65498, 65499, 65500, 65501, 65502, 65503, 65504, 65505, 65506, 65507, 65508, 65509, 65510, 65511, 65512, 65513, 65514, 65515, 65516, 65517, 65518, 65519, 65520, 65521, 65522, 65523, 65524, 65525, 65526, 65527, 65528, 65529, 65530, 65531, 65532, 65533, 65534, 65535, 65536 }
|
||||
local KMIN = { 0, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824, 2147483648, 0, 0, 0, 0, 0 }
|
||||
|
||||
-- symbol(total) lookup buffers (RangeOverflowTable), built on first use
|
||||
local OVT: { [number]: buffer } = {}
|
||||
local function overflowTable(rt: { number }): buffer
|
||||
local t = OVT[rt[2]]
|
||||
if t then
|
||||
return t
|
||||
end
|
||||
t = buffer.create(65536)
|
||||
local o = 0
|
||||
for z = 0, 65535 do
|
||||
if z >= rt[o + 2] then
|
||||
o += 1
|
||||
end
|
||||
writeu8(t, z, o)
|
||||
end
|
||||
OVT[rt[2]] = t
|
||||
return t
|
||||
end
|
||||
|
||||
local function wrap32(v: number): number
|
||||
if v >= TWO31 or v < -TWO31 then
|
||||
return (v + TWO31) % TWO32 - TWO31
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
-- C integer division by 2 (toward zero)
|
||||
local function half(v: number): number
|
||||
return if v >= 0 then v // 2 else -((-v) // 2)
|
||||
end
|
||||
|
||||
export type Filter = { order: number, shift: number, M: buffer, I: buffer, D: buffer }
|
||||
export type State = {
|
||||
version: number,
|
||||
bits: number,
|
||||
channels: number,
|
||||
filters: { Filter }, -- per level, applied last to first on decode (as m_spNNFilter2, 1, 0)
|
||||
V: { { number } }, -- per channel: the frame's values through the stages
|
||||
S: buffer, -- the frame bytes, word-swapped (+ PAD zeros)
|
||||
crcbuf: buffer,
|
||||
scratch: buffer,
|
||||
lastX: number,
|
||||
rc: Rc,
|
||||
}
|
||||
|
||||
local FILTERS: { [number]: { number } } = { -- level -> { order, shift, ... } in m_spNNFilter, 1, 2 order
|
||||
[1000] = {},
|
||||
[2000] = { 16, 11 },
|
||||
[3000] = { 64, 11 },
|
||||
[4000] = { 256, 13, 32, 10 },
|
||||
[5000] = { 1280, 15, 256, 13, 16, 11 },
|
||||
}
|
||||
|
||||
-- state(version, level, bits, channels) -> State | nil, message
|
||||
function Decode.state(version: number, level: number, bits: number, channels: number): (State?, string?)
|
||||
local spec = FILTERS[level]
|
||||
if not spec then
|
||||
return nil, "unsupported: compression level " .. level
|
||||
end
|
||||
local filters: { Filter } = {}
|
||||
for k = 1, #spec, 2 do
|
||||
local order = spec[k]
|
||||
local es = if bits >= 32 then 4 else 2
|
||||
table.insert(filters, {
|
||||
order = order,
|
||||
shift = spec[k + 1],
|
||||
M = buffer.create(order * es),
|
||||
I = buffer.create((512 + order + 1) * es),
|
||||
D = buffer.create((512 + order + 1) * es),
|
||||
})
|
||||
end
|
||||
local V = {}
|
||||
for c = 1, channels do
|
||||
V[c] = {}
|
||||
end
|
||||
return {
|
||||
version = version,
|
||||
bits = bits,
|
||||
channels = channels,
|
||||
filters = filters,
|
||||
V = V,
|
||||
S = buffer.create(1024),
|
||||
crcbuf = buffer.create(1024),
|
||||
scratch = buffer.create(4),
|
||||
lastX = 0,
|
||||
rc = { q = 0, low = 0, range = 0, prev = 0 },
|
||||
}, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ entropy
|
||||
-- the range coder as a record (the 3.95 - 3.98 model's RangeDecodeFastWithUpdate)
|
||||
type Rc = { q: number, low: number, range: number, prev: number }
|
||||
local function rcBits(rc: Rc, S: buffer, nb: number): number
|
||||
local q, low, range, prev = rc.q, rc.low, rc.range, rc.prev
|
||||
while range <= 8388608 do
|
||||
local byte = readu8(S, q)
|
||||
q += 1
|
||||
low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1))
|
||||
prev = byte
|
||||
range *= 256
|
||||
end
|
||||
range = range // 2 ^ nb
|
||||
local r = 0
|
||||
if range > 0 then
|
||||
r = low // range
|
||||
low %= range
|
||||
end
|
||||
rc.q, rc.low, rc.range, rc.prev = q, low, range, prev
|
||||
return r
|
||||
end
|
||||
|
||||
-- values(st, q, n, order, old) -> q | nil, message: n blocks of range-coded values into st.V[c] for the channels of
|
||||
-- `order` (decode order), from byte q of st.S (the range coder starts there)
|
||||
local function values(st: State, q: number, lim: number, n: number, order: { number }, old: boolean): (number?, string?)
|
||||
local S = st.S
|
||||
local V = st.V
|
||||
local version = st.version
|
||||
-- FlushBitArray: a dummy byte, then the first byte
|
||||
local prev = readu8(S, q + 1)
|
||||
q += 2
|
||||
local low = rshift(prev, 1)
|
||||
local range = 128
|
||||
local nch = #order
|
||||
local ksum = table.create(nch, 16384)
|
||||
local kk = table.create(nch, 10)
|
||||
local ovt = overflowTable(if old then RT1 else RT2)
|
||||
local RT = if old then RT1 else RT2
|
||||
for b = 1, n do
|
||||
for ci = 1, nch do
|
||||
if q > lim then
|
||||
return nil, "overrun"
|
||||
end
|
||||
local ks = ksum[ci]
|
||||
local value
|
||||
-- the overflow symbol (RangeDecodeFast(16) + the model)
|
||||
while range <= 8388608 do
|
||||
local byte = readu8(S, q)
|
||||
q += 1
|
||||
low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1))
|
||||
prev = byte
|
||||
range *= 256
|
||||
end
|
||||
range = range // 65536
|
||||
local total = low // range
|
||||
if total >= 65536 then
|
||||
return nil, "bad range code"
|
||||
end
|
||||
local ov = readu8(ovt, total)
|
||||
low -= range * RT[ov + 1]
|
||||
range *= RT[ov + 2] - RT[ov + 1]
|
||||
if not old then
|
||||
local pivot = math.max(ks // 32, 1)
|
||||
while ov == 63 do
|
||||
-- escape: 32 bits of overflow (two 16-bit range decodes); 1 = the overflow signal
|
||||
local r = 0
|
||||
for _ = 1, 2 do
|
||||
while range <= 8388608 do
|
||||
local byte = readu8(S, q)
|
||||
q += 1
|
||||
low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1))
|
||||
prev = byte
|
||||
range *= 256
|
||||
end
|
||||
range = range // 65536
|
||||
if range == 0 then
|
||||
return nil, "bad range code"
|
||||
end
|
||||
r = r * 65536 + low // range
|
||||
low %= range
|
||||
end
|
||||
ov = r
|
||||
if ov == 1 then
|
||||
pivot = 32768
|
||||
while range <= 8388608 do
|
||||
local byte = readu8(S, q)
|
||||
q += 1
|
||||
low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1))
|
||||
prev = byte
|
||||
range *= 256
|
||||
end
|
||||
range = range // 65536
|
||||
total = low // range
|
||||
if total >= 65536 then
|
||||
return nil, "bad range code"
|
||||
end
|
||||
ov = readu8(ovt, total)
|
||||
low -= range * RT[ov + 1]
|
||||
range *= RT[ov + 2] - RT[ov + 1]
|
||||
else
|
||||
break
|
||||
end
|
||||
end
|
||||
local base
|
||||
if pivot >= 65536 then
|
||||
local pbits = 0
|
||||
while pivot // 2 ^ pbits > 0 do
|
||||
pbits += 1
|
||||
end
|
||||
local split = 2 ^ (if pbits >= 16 then pbits - 16 else 0)
|
||||
local pa = pivot // split + 1
|
||||
while range <= 8388608 do
|
||||
local byte = readu8(S, q)
|
||||
q += 1
|
||||
low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1))
|
||||
prev = byte
|
||||
range *= 256
|
||||
end
|
||||
range = range // pa
|
||||
local ba = low // range
|
||||
low %= range
|
||||
while range <= 8388608 do
|
||||
local byte = readu8(S, q)
|
||||
q += 1
|
||||
low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1))
|
||||
prev = byte
|
||||
range *= 256
|
||||
end
|
||||
range = range // split
|
||||
local bb = low // range
|
||||
low %= range
|
||||
base = ba * split + bb
|
||||
else
|
||||
while range <= 8388608 do
|
||||
local byte = readu8(S, q)
|
||||
q += 1
|
||||
low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1))
|
||||
prev = byte
|
||||
range *= 256
|
||||
end
|
||||
range = range // pivot
|
||||
base = low // range
|
||||
low %= range
|
||||
end
|
||||
value = base + ov * pivot
|
||||
else
|
||||
-- 3.95 - 3.98: k bits (escape: k in 5 bits)
|
||||
local rc = st.rc
|
||||
rc.q, rc.low, rc.range, rc.prev = q, low, range, prev
|
||||
local k
|
||||
if ov == 63 then
|
||||
k = rcBits(rc, S, 5)
|
||||
ov = 0
|
||||
else
|
||||
k = math.max(kk[ci] - 1, 0)
|
||||
end
|
||||
if k <= 16 or version < 3910 then
|
||||
value = rcBits(rc, S, k)
|
||||
else
|
||||
local x1 = rcBits(rc, S, 16)
|
||||
value = x1 + rcBits(rc, S, k - 16) * 65536
|
||||
end
|
||||
value += ov * 2 ^ k
|
||||
q = rc.q
|
||||
low = rc.low
|
||||
range = rc.range
|
||||
prev = rc.prev
|
||||
end
|
||||
ks = (ks + (value + 1) // 2 - (ks + 16) // 32) % TWO32
|
||||
ksum[ci] = ks
|
||||
if old then
|
||||
local k = kk[ci]
|
||||
if ks < KMIN[k + 1] then
|
||||
kk[ci] = k - 1
|
||||
elseif KMIN[k + 2] ~= 0 and ks >= KMIN[k + 2] then
|
||||
kk[ci] = k + 1
|
||||
end
|
||||
end
|
||||
V[order[ci]][b] = if value % 2 == 1 then (value - 1) // 2 + 1 else -(value // 2)
|
||||
end
|
||||
end
|
||||
return q, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ NN filters
|
||||
-- ((v >> s) & m) ~= 0 for an int64 v (s given as 2^s)
|
||||
local function negBit(v: number, p2: number, m: number): boolean
|
||||
return band((v // p2) % TWO32, m) ~= 0
|
||||
end
|
||||
|
||||
-- the int16 dot product of the weights and the inputs from byte b (span bytes)
|
||||
local function dot16(M: buffer, I: buffer, b: number, span: number): number
|
||||
local dot = 0
|
||||
for k = 0, span - 16, 16 do
|
||||
local bb = b + k
|
||||
dot += readi16(I, bb) * readi16(M, k) + readi16(I, bb + 2) * readi16(M, k + 2)
|
||||
+ readi16(I, bb + 4) * readi16(M, k + 4) + readi16(I, bb + 6) * readi16(M, k + 6)
|
||||
+ readi16(I, bb + 8) * readi16(M, k + 8) + readi16(I, bb + 10) * readi16(M, k + 10)
|
||||
+ readi16(I, bb + 12) * readi16(M, k + 12) + readi16(I, bb + 14) * readi16(M, k + 14)
|
||||
end
|
||||
return dot
|
||||
end
|
||||
|
||||
-- the same, adapting each weight after its use: M += D * dm (int16, wrapping)
|
||||
local function dotAdapt16(M: buffer, I: buffer, D: buffer, b: number, span: number, dm: number): number
|
||||
local dot = 0
|
||||
for k = 0, span - 8, 8 do
|
||||
local bb = b + k
|
||||
local m0, m1, m2, m3 = readi16(M, k), readi16(M, k + 2), readi16(M, k + 4), readi16(M, k + 6)
|
||||
dot += readi16(I, bb) * m0 + readi16(I, bb + 2) * m1 + readi16(I, bb + 4) * m2 + readi16(I, bb + 6) * m3
|
||||
writei16(M, k, m0 + readi16(D, bb) * dm)
|
||||
writei16(M, k + 2, m1 + readi16(D, bb + 2) * dm)
|
||||
writei16(M, k + 4, m2 + readi16(D, bb + 4) * dm)
|
||||
writei16(M, k + 6, m3 + readi16(D, bb + 6) * dm)
|
||||
end
|
||||
return dot
|
||||
end
|
||||
|
||||
-- one CNNFilter over n values of v, in place (DecompressGeneric). The weights, inputs and deltas live in buffers of
|
||||
-- the C types (int16 for 8 - 24-bit files, int32 for 32-bit ones: `wide`), so the weights wrap as the C shorts do
|
||||
local function nnFilter(f: Filter, v: { number }, n: number, newDelta: boolean, wide: boolean)
|
||||
local order, M, I, D = f.order, f.M, f.I, f.D
|
||||
local es = if wide then 4 else 2
|
||||
local shift = 2 ^ f.shift
|
||||
local round = shift // 2
|
||||
buffer.fill(M, 0, 0, order * es)
|
||||
buffer.fill(I, 0, 0, (order + 1) * es)
|
||||
buffer.fill(D, 0, 0, (order + 1) * es)
|
||||
local p = order -- the current element (0-based); its history is p - order .. p - 1
|
||||
local total = 512 + order
|
||||
local avg = 0
|
||||
local span = order * 2
|
||||
for t = 1, n do
|
||||
local x = v[t]
|
||||
local dm = -sign(x) -- the weights move by +delta when x < 0, -delta when x > 0
|
||||
local dot = 0
|
||||
if wide then
|
||||
local b = (p - order) * 4
|
||||
for k = 0, order * 4 - 4, 4 do
|
||||
local m = readi32(M, k)
|
||||
local pr = readi32(I, b + k) * m
|
||||
if pr >= TWO31 or pr < -TWO31 then
|
||||
pr = (pr + TWO31) % TWO32 - TWO31
|
||||
end
|
||||
dot += pr
|
||||
if dm ~= 0 then
|
||||
writei32(M, k, m + readi32(D, b + k) * dm)
|
||||
end
|
||||
end
|
||||
else
|
||||
local b = (p - order) * 2
|
||||
dot = if dm == 0 then dot16(M, I, b, span) else dotAdapt16(M, I, D, b, span, dm)
|
||||
dot = wrap32(dot)
|
||||
end
|
||||
local o = x + (dot + round) // shift
|
||||
if not wide then
|
||||
o = wrap32(o)
|
||||
end
|
||||
local d = 0
|
||||
local a = if o < 0 then -o else o
|
||||
if newDelta then
|
||||
if a > avg * 3 then
|
||||
d = if (if wide then negBit(o, 33554432, 64) else o < 0) then 32 else -32
|
||||
elseif a > (avg * 4) // 3 then
|
||||
d = if (if wide then negBit(o, 67108864, 32) else o < 0) then 16 else -16
|
||||
elseif a > 0 then
|
||||
d = if (if wide then negBit(o, 134217728, 16) else o < 0) then 8 else -8
|
||||
end
|
||||
local dd = a - avg
|
||||
avg += if dd >= 0 then dd // 16 else -((-dd) // 16)
|
||||
else
|
||||
d = if o == 0 then 0 elseif o < 0 then 4 else -4
|
||||
end
|
||||
local sat = if o > 32767 then 32767 elseif o < -32768 then -32768 else o
|
||||
if wide then
|
||||
local q = p * 4
|
||||
writei32(D, q, d)
|
||||
if newDelta then
|
||||
writei32(D, q - 4, readi32(D, q - 4) // 2)
|
||||
writei32(D, q - 8, readi32(D, q - 8) // 2)
|
||||
else
|
||||
writei32(D, q - 16, readi32(D, q - 16) // 2)
|
||||
end
|
||||
writei32(D, q - 32, readi32(D, q - 32) // 2)
|
||||
writei32(I, q, sat)
|
||||
else
|
||||
local q = p * 2
|
||||
writei16(D, q, d)
|
||||
if newDelta then
|
||||
writei16(D, q - 2, readi16(D, q - 2) // 2)
|
||||
writei16(D, q - 4, readi16(D, q - 4) // 2)
|
||||
else
|
||||
writei16(D, q - 8, readi16(D, q - 8) // 2)
|
||||
end
|
||||
writei16(D, q - 16, readi16(D, q - 16) // 2)
|
||||
writei16(I, q, sat)
|
||||
end
|
||||
v[t] = o
|
||||
p += 1
|
||||
if p == total then
|
||||
buffer.copy(I, 0, I, (p - order) * es, order * es)
|
||||
buffer.copy(D, 0, D, (p - order) * es, order * es)
|
||||
p = order
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ predictor
|
||||
-- the adapt sign of a 32-bit file's int64 prediction value: ((v >> 30) & 2) - 1, or 0
|
||||
local function adaptWide(v: number): number
|
||||
if v == 0 then
|
||||
return 0
|
||||
end
|
||||
return if (v // 1073741824) % 4 >= 2 then 1 else -1
|
||||
end
|
||||
|
||||
-- predict(st, a, b?, n) : CPredictorDecompress3950toCurrent over channel a's values (nB = channel b's outputs of the
|
||||
-- block, or 0), single-channel form; stereo uses predictStereo
|
||||
local function predictOne(st: State, v: { number }, n: number)
|
||||
local wide = st.bits >= 32
|
||||
local lastA, prevA0, A1, A2, A3 = 0, 0, 0, 0, 0
|
||||
local MA0, MA1, MA2, MA3 = 360, 317, -109, 98
|
||||
local stage = 0
|
||||
for t = 1, n do
|
||||
local nA = v[t]
|
||||
local A0 = lastA
|
||||
A3 = A2
|
||||
A2 = A1
|
||||
A1 = A0 - prevA0
|
||||
prevA0 = A0
|
||||
local predA = A0 * MA0 + A1 * MA1 + A2 * MA2 + A3 * MA3
|
||||
local cur
|
||||
if wide then
|
||||
cur = nA + predA // 1024
|
||||
else
|
||||
cur = wrap32(nA + wrap32(predA) // 1024)
|
||||
end
|
||||
local s = sign(nA)
|
||||
if s ~= 0 then
|
||||
if wide then
|
||||
s = -s
|
||||
MA0 += adaptWide(A0) * s
|
||||
MA1 += adaptWide(A1) * s
|
||||
MA2 += adaptWide(A2) * s
|
||||
MA3 += adaptWide(A3) * s
|
||||
else
|
||||
MA0 += sign(A0) * s
|
||||
MA1 += sign(A1) * s
|
||||
MA2 += sign(A2) * s
|
||||
MA3 += sign(A3) * s
|
||||
end
|
||||
end
|
||||
stage = wrap32(cur + (stage * 31) // 32)
|
||||
lastA = cur
|
||||
v[t] = stage
|
||||
end
|
||||
end
|
||||
|
||||
-- the stereo predictors: Y = P1(nY, last X), X = P0(nX, Y); X into V[1], Y into V[2]
|
||||
local function predictStereo(st: State, X: { number }, Y: { number }, n: number)
|
||||
local wide = st.bits >= 32
|
||||
-- predictor 1 (Y)
|
||||
local yLast, yPrev, yA1, yA2, yA3 = 0, 0, 0, 0, 0
|
||||
local yBin, yBprev, yB1, yB2, yB3, yB4 = 0, 0, 0, 0, 0, 0
|
||||
local yMA0, yMA1, yMA2, yMA3 = 360, 317, -109, 98
|
||||
local yMB0, yMB1, yMB2, yMB3, yMB4 = 0, 0, 0, 0, 0
|
||||
local yStage = 0
|
||||
-- predictor 0 (X)
|
||||
local xLast, xPrev, xA1, xA2, xA3 = 0, 0, 0, 0, 0
|
||||
local xBin, xBprev, xB1, xB2, xB3, xB4 = 0, 0, 0, 0, 0, 0
|
||||
local xMA0, xMA1, xMA2, xMA3 = 360, 317, -109, 98
|
||||
local xMB0, xMB1, xMB2, xMB3, xMB4 = 0, 0, 0, 0, 0
|
||||
local xStage = 0
|
||||
local lastX = 0
|
||||
for t = 1, n do
|
||||
-- Y
|
||||
local nA = Y[t]
|
||||
local A0 = yLast
|
||||
yA3 = yA2
|
||||
yA2 = yA1
|
||||
yA1 = A0 - yPrev
|
||||
yPrev = A0
|
||||
local B0 = lastX - (yBin * 31) // 32
|
||||
yBin = lastX
|
||||
yB4 = yB3
|
||||
yB3 = yB2
|
||||
yB2 = yB1
|
||||
yB1 = B0 - yBprev
|
||||
yBprev = B0
|
||||
local predA = A0 * yMA0 + yA1 * yMA1 + yA2 * yMA2 + yA3 * yMA3
|
||||
local predB = B0 * yMB0 + yB1 * yMB1 + yB2 * yMB2 + yB3 * yMB3 + yB4 * yMB4
|
||||
local cur
|
||||
if wide then
|
||||
cur = nA + (predA + predB // 2) // 1024
|
||||
else
|
||||
cur = wrap32(nA + wrap32(wrap32(predA) + wrap32(predB) // 2) // 1024)
|
||||
end
|
||||
local s = sign(nA)
|
||||
if s ~= 0 then
|
||||
if wide then
|
||||
s = -s
|
||||
yMA0 += adaptWide(A0) * s
|
||||
yMA1 += adaptWide(yA1) * s
|
||||
yMA2 += adaptWide(yA2) * s
|
||||
yMA3 += adaptWide(yA3) * s
|
||||
yMB0 += adaptWide(B0) * s
|
||||
yMB1 += adaptWide(yB1) * s
|
||||
yMB2 += adaptWide(yB2) * s
|
||||
yMB3 += adaptWide(yB3) * s
|
||||
yMB4 += adaptWide(yB4) * s
|
||||
else
|
||||
yMA0 += sign(A0) * s
|
||||
yMA1 += sign(yA1) * s
|
||||
yMA2 += sign(yA2) * s
|
||||
yMA3 += sign(yA3) * s
|
||||
yMB0 += sign(B0) * s
|
||||
yMB1 += sign(yB1) * s
|
||||
yMB2 += sign(yB2) * s
|
||||
yMB3 += sign(yB3) * s
|
||||
yMB4 += sign(yB4) * s
|
||||
end
|
||||
end
|
||||
yStage = wrap32(cur + (yStage * 31) // 32)
|
||||
yLast = cur
|
||||
local yv = yStage
|
||||
-- X
|
||||
nA = X[t]
|
||||
A0 = xLast
|
||||
xA3 = xA2
|
||||
xA2 = xA1
|
||||
xA1 = A0 - xPrev
|
||||
xPrev = A0
|
||||
B0 = yv - (xBin * 31) // 32
|
||||
xBin = yv
|
||||
xB4 = xB3
|
||||
xB3 = xB2
|
||||
xB2 = xB1
|
||||
xB1 = B0 - xBprev
|
||||
xBprev = B0
|
||||
predA = A0 * xMA0 + xA1 * xMA1 + xA2 * xMA2 + xA3 * xMA3
|
||||
predB = B0 * xMB0 + xB1 * xMB1 + xB2 * xMB2 + xB3 * xMB3 + xB4 * xMB4
|
||||
if wide then
|
||||
cur = nA + (predA + predB // 2) // 1024
|
||||
else
|
||||
cur = wrap32(nA + wrap32(wrap32(predA) + wrap32(predB) // 2) // 1024)
|
||||
end
|
||||
s = sign(nA)
|
||||
if s ~= 0 then
|
||||
if wide then
|
||||
s = -s
|
||||
xMA0 += adaptWide(A0) * s
|
||||
xMA1 += adaptWide(xA1) * s
|
||||
xMA2 += adaptWide(xA2) * s
|
||||
xMA3 += adaptWide(xA3) * s
|
||||
xMB0 += adaptWide(B0) * s
|
||||
xMB1 += adaptWide(xB1) * s
|
||||
xMB2 += adaptWide(xB2) * s
|
||||
xMB3 += adaptWide(xB3) * s
|
||||
xMB4 += adaptWide(xB4) * s
|
||||
else
|
||||
xMA0 += sign(A0) * s
|
||||
xMA1 += sign(xA1) * s
|
||||
xMA2 += sign(xA2) * s
|
||||
xMA3 += sign(xA3) * s
|
||||
xMB0 += sign(B0) * s
|
||||
xMB1 += sign(xB1) * s
|
||||
xMB2 += sign(xB2) * s
|
||||
xMB3 += sign(xB3) * s
|
||||
xMB4 += sign(xB4) * s
|
||||
end
|
||||
end
|
||||
xStage = wrap32(cur + (xStage * 31) // 32)
|
||||
xLast = cur
|
||||
lastX = xStage
|
||||
X[t], Y[t] = xStage, yv
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ frame
|
||||
-- frame(st, buf, at, rem, stop, n, P, float) -> n | nil, message: the frame whose words start at byte `at` (its first
|
||||
-- byte at at + rem), reading at most up to `stop`; n blocks into P (interleaved integers, or floats when float); cut:
|
||||
-- the data ends at `stop` before the frame does (a running-over decode is then "truncated", else corrupt)
|
||||
function Decode.frame(st: State, buf: buffer, at: number, rem: number, stop: number, n: number, P: { number }, float: boolean, cut: boolean): (number?, string?)
|
||||
local C, bits = st.channels, st.bits
|
||||
local len = math.max(0, stop - at)
|
||||
local words = (len + 3) // 4
|
||||
local S = st.S
|
||||
if buffer.len(S) < words * 4 + PAD then
|
||||
S = buffer.create(words * 4 + PAD + 4096)
|
||||
st.S = S
|
||||
end
|
||||
buffer.fill(S, 0, 0, words * 4 + PAD)
|
||||
-- the bit array: 32-bit little-endian words read MSB first
|
||||
for w = 0, words - 1 do
|
||||
local o = at + w * 4
|
||||
if o + 4 <= stop then
|
||||
writeu32(S, w * 4, byteswap(readu32(buf, o)))
|
||||
else
|
||||
for k = 0, 3 do
|
||||
if o + k < stop then
|
||||
writeu8(S, w * 4 + 3 - k, readu8(buf, o + k))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local function u32be(q: number): number
|
||||
return readu8(S, q) * 16777216 + readu8(S, q + 1) * 65536 + readu8(S, q + 2) * 256 + readu8(S, q + 3)
|
||||
end
|
||||
local q = rem
|
||||
if q + 16 > words * 4 + PAD then
|
||||
return nil, "truncated frame"
|
||||
end
|
||||
local stored = u32be(q)
|
||||
q += 4
|
||||
local special = 0
|
||||
if st.version > 3820 then
|
||||
if stored >= TWO31 then
|
||||
special = u32be(q)
|
||||
q += 4
|
||||
end
|
||||
stored %= TWO31
|
||||
end
|
||||
-- the values
|
||||
local V = st.V
|
||||
local order: { number }
|
||||
local mode -- "silence", "pseudo", "stereo", "mono", "multi"
|
||||
if C == 1 then
|
||||
if band(special, 1) ~= 0 then
|
||||
mode = "silence"
|
||||
order = {}
|
||||
else
|
||||
mode = "mono"
|
||||
order = { 1 }
|
||||
end
|
||||
elseif C == 2 then
|
||||
if band(special, 3) == 3 then
|
||||
mode = "silence"
|
||||
order = {}
|
||||
elseif band(special, 4) ~= 0 then
|
||||
mode = "pseudo"
|
||||
order = { 1 }
|
||||
else
|
||||
mode, order = "stereo", { 2, 1 }
|
||||
end
|
||||
else
|
||||
mode = "multi"
|
||||
order = {}
|
||||
for c = 1, C do
|
||||
order[c] = c
|
||||
end
|
||||
end
|
||||
local lim = words * 4 + PAD - 40
|
||||
if #order > 0 then
|
||||
local qe = values(st, q, lim, n, order, st.version < 3990)
|
||||
if not qe or qe > words * 4 + 8 then
|
||||
return nil, if cut then "truncated frame" else "bad frame: the values run over its data"
|
||||
end
|
||||
-- the NN filters (last level first), then the predictors
|
||||
local newDelta = st.version >= 3980
|
||||
local filters = st.filters
|
||||
for _, c in order do
|
||||
for f = #filters, 1, -1 do
|
||||
nnFilter(filters[f], V[c], n, newDelta, bits >= 32)
|
||||
end
|
||||
end
|
||||
if mode == "stereo" then
|
||||
predictStereo(st, V[1], V[2], n)
|
||||
else
|
||||
for _, c in order do
|
||||
predictOne(st, V[c], n)
|
||||
end
|
||||
end
|
||||
end
|
||||
-- Unprepare: values -> channels, the CRC over the output bytes as the WAV holds them
|
||||
local bps = bits // 8
|
||||
local cb = st.crcbuf
|
||||
if buffer.len(cb) < n * C * bps then
|
||||
cb = buffer.create(n * C * bps + 1024)
|
||||
st.crcbuf = cb
|
||||
end
|
||||
local paired: { [number]: boolean } = {} -- first channel (0-based) of an X / Y pair
|
||||
if C == 2 and mode == "stereo" then
|
||||
paired[0] = true
|
||||
elseif C == 4 and (bits == 16 or bits == 24) then
|
||||
paired[0], paired[2] = true, true
|
||||
elseif C >= 6 and (bits == 16 or bits == 24) then
|
||||
paired[0], paired[4] = true, true
|
||||
if C >= 8 then
|
||||
paired[6] = true
|
||||
end
|
||||
end
|
||||
local o = 0
|
||||
local mono = mode == "mono" or mode == "pseudo"
|
||||
local X = V[1]
|
||||
for t = 1, n do
|
||||
local base = (t - 1) * C
|
||||
local c = 0
|
||||
while c < C do
|
||||
local a: number, b2: number = 0, 0
|
||||
local pair = paired[c]
|
||||
if mode == "silence" then
|
||||
a = 0
|
||||
b2 = 0
|
||||
elseif mono then
|
||||
a = X[t]
|
||||
b2 = a
|
||||
elseif pair then
|
||||
local x, y = V[c + 1][t], V[c + 2][t]
|
||||
a = x - half(y)
|
||||
b2 = a + y
|
||||
else
|
||||
a = V[c + 1][t]
|
||||
end
|
||||
local width = if pair or (C == 2) then 2 else 1
|
||||
for k = 0, width - 1 do
|
||||
local s: number = if k == 0 then a else b2
|
||||
if bits == 16 then
|
||||
if s < -32768 or s > 32767 then
|
||||
return nil, "sample out of range"
|
||||
end
|
||||
writei16(cb, o, s)
|
||||
o += 2
|
||||
elseif bits == 8 then
|
||||
s = (s + 128) % 256 - 128
|
||||
writeu8(cb, o, s + 128)
|
||||
o += 1
|
||||
elseif bits == 24 then
|
||||
s = (s + 8388608) % 16777216 - 8388608
|
||||
local u = s % 16777216
|
||||
writeu16(cb, o, u % 65536)
|
||||
writeu8(cb, o + 2, u // 65536)
|
||||
o += 3
|
||||
else
|
||||
s = wrap32(s)
|
||||
writei32(cb, o, s)
|
||||
o += 4
|
||||
end
|
||||
P[base + c + k + 1] = s
|
||||
end
|
||||
c += width
|
||||
end
|
||||
end
|
||||
local crc = Crc32.of(cb, 0, o)
|
||||
if crc // 2 ~= stored then
|
||||
return nil, "checksum: frame CRC mismatch"
|
||||
end
|
||||
if float then
|
||||
local sc = st.scratch
|
||||
for k = 1, n * C do
|
||||
local u = P[k] % TWO32
|
||||
local out = bor(band(u, 0xC3FFFFFF), bxor(bnot(band(u, 0x3C000000)), 0xC3FFFFFF))
|
||||
if out >= TWO31 then
|
||||
out = bor(bnot(out), 0x80000000)
|
||||
end
|
||||
writeu32(sc, 0, out)
|
||||
P[k] = readf32(sc, 0)
|
||||
end
|
||||
end
|
||||
return n, nil
|
||||
end
|
||||
|
||||
return Decode
|
||||
@@ -0,0 +1,229 @@
|
||||
--!strict
|
||||
-- codecs/audio/Ape: the Monkey's Audio codec (.ape). A codec (layer 3). Ported from the Monkey's Audio SDK 13.28
|
||||
-- (Matthew T. Ashland, BSD 3-clause since v10, licenses/monkeys-audio-LICENSE.txt): APEHeader.cpp (the descriptor /
|
||||
-- header / seek table, and the pre-3.98 header), APEInfo / APEDecompress.cpp (frame bytes and alignment); the frame
|
||||
-- decoder is codecs/audio/Ape/Decode. Supports file versions 3.95 and later (3.99+ as the current encoder writes; the
|
||||
-- 3.95 - 3.98 range coder model is ported but has no reference fixture), every compression level (fast, normal, high,
|
||||
-- extra high, insane), 8 / 16 / 24 / 32-bit integer and 32-bit float, 1 - 32 channels, special frames (silence,
|
||||
-- pseudo stereo) and the frame CRC. Not supported: versions before 3.95 (UNSUPPORTED), the "interim" 24-bit
|
||||
-- re-decode for files of the 32-bit era before 8.50, big-endian / signed 8-bit source flags (the samples are returned
|
||||
-- as numbers either way).
|
||||
--
|
||||
-- local info, err = Ape.info(buf, base, limit) -- header facts + the frame table
|
||||
-- local dec = Ape.decoder(info)
|
||||
-- local n, err = dec:frame(buf, i) -- frame i (1-based) -> dec.pcm (interleaved; integers, or floats)
|
||||
--
|
||||
-- Never throws: bad data returns nil, Err.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Decode = require("@formats/codecs/audio/Ape/Decode")
|
||||
|
||||
local Ape = {}
|
||||
|
||||
export type Info = {
|
||||
version: number, -- file version * 1000 (3990)
|
||||
programVersion: number, -- 13280 (0 when not stored)
|
||||
level: number, -- 1000 (fast) .. 5000 (insane)
|
||||
flags: number,
|
||||
channels: number,
|
||||
sampleRate: number,
|
||||
bitsPerSample: number,
|
||||
float: boolean,
|
||||
blocksPerFrame: number,
|
||||
finalFrameBlocks: number,
|
||||
totalFrames: number,
|
||||
totalBlocks: number,
|
||||
frameStart: { number }, -- byte offset of each frame
|
||||
firstFrame: number, -- byte offset of frame 1 (the word alignment origin)
|
||||
dataEnd: number, -- the end of the frame data
|
||||
limit: number, -- the end of the file data (frames past it are truncated)
|
||||
md5: string?,
|
||||
}
|
||||
|
||||
local FLAG_8, FLAG_24, FLAG_PEAK, FLAG_SEEKN, FLAG_WAVHDR, FLAG_FLOAT = 1, 8, 4, 16, 32, 4096
|
||||
|
||||
-- find(buf, base, limit) -> the offset of "MAC " / "MACF" (after an ID3v2 tag) | nil
|
||||
function Ape.find(buf: buffer, base: number, limit: number): number?
|
||||
local at = base
|
||||
if limit - at >= 10 and buffer.readstring(buf, at, 3) == "ID3" then
|
||||
local size = 0
|
||||
for i = 6, 9 do
|
||||
size = size * 128 + bit32.band(buffer.readu8(buf, at + i), 127)
|
||||
end
|
||||
local footer = bit32.band(buffer.readu8(buf, at + 5), 16) ~= 0
|
||||
at += size + (if footer then 20 else 10)
|
||||
if not footer then
|
||||
while at < limit and buffer.readu8(buf, at) == 0 do
|
||||
at += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
if at + 4 > limit then
|
||||
return nil
|
||||
end
|
||||
local id = buffer.readstring(buf, at, 4)
|
||||
if id == "MAC " or id == "MACF" then
|
||||
return at
|
||||
end
|
||||
local s = buffer.readstring(buf, at, math.min(limit - at, 1048576))
|
||||
local k = string.find(s, "MAC ", 1, true)
|
||||
return if k then at + k - 1 else nil
|
||||
end
|
||||
|
||||
-- info(buf, base, limit) -> Info | nil, Err
|
||||
function Ape.info(buf: buffer, base: number, limit: number): (Info?, Err.Err?)
|
||||
local at = Ape.find(buf, base, limit)
|
||||
if not at then
|
||||
return nil, Err.new(Err.CORRUPT, "no Monkey's Audio header")
|
||||
end
|
||||
local junk = at - base -- seek offsets count from the start of the APE data (after any junk / ID3v2)
|
||||
local r = Bytes.reader(buf, at, limit - at)
|
||||
r:skip(4)
|
||||
local version = r:u16le()
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
if version < 3950 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "Monkey's Audio file version " .. version .. " (3950 and later are supported)")
|
||||
end
|
||||
local info: any = { version = version, programVersion = 0 }
|
||||
local seekCount, seekAt
|
||||
if version >= 3980 then
|
||||
info.programVersion = r:u16le()
|
||||
local descBytes, headBytes, seekBytes, hdrDataBytes = r:u32le(), r:u32le(), r:u32le(), r:u32le()
|
||||
local dataLo, dataHi, termBytes = r:u32le(), r:u32le(), r:u32le()
|
||||
local md5 = r:string(16)
|
||||
r:seek(descBytes)
|
||||
info.level = r:u16le()
|
||||
info.flags = r:u16le()
|
||||
info.blocksPerFrame = r:u32le()
|
||||
info.finalFrameBlocks = r:u32le()
|
||||
info.totalFrames = r:u32le()
|
||||
info.bitsPerSample = r:u16le()
|
||||
info.channels = r:u16le()
|
||||
info.sampleRate = r:u32le()
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
seekAt = at + descBytes + headBytes
|
||||
seekCount = seekBytes // 4
|
||||
info.dataEnd = seekAt + seekBytes + hdrDataBytes + dataLo + dataHi * 4294967296
|
||||
local _ = termBytes
|
||||
local hex = table.create(16, "")
|
||||
local any = false
|
||||
for k = 1, 16 do
|
||||
local b = string.byte(md5, k)
|
||||
any = any or b ~= 0
|
||||
hex[k] = string.format("%02x", b)
|
||||
end
|
||||
info.md5 = if any then table.concat(hex) else nil
|
||||
else
|
||||
info.level = r:u16le()
|
||||
info.flags = r:u16le()
|
||||
info.channels = r:u16le()
|
||||
info.sampleRate = r:u32le()
|
||||
local headerBytes = r:u32le()
|
||||
r:u32le() -- terminating bytes
|
||||
info.totalFrames = r:u32le()
|
||||
info.finalFrameBlocks = r:u32le()
|
||||
if bit32.band(info.flags, FLAG_PEAK) ~= 0 then
|
||||
r:skip(4)
|
||||
end
|
||||
seekCount = info.totalFrames
|
||||
if bit32.band(info.flags, FLAG_SEEKN) ~= 0 then
|
||||
seekCount = r:u32le()
|
||||
end
|
||||
if bit32.band(info.flags, FLAG_WAVHDR) == 0 then
|
||||
r:skip(headerBytes)
|
||||
end
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
info.blocksPerFrame = 73728 * 4
|
||||
info.bitsPerSample = if bit32.band(info.flags, FLAG_8) ~= 0 then 8 elseif bit32.band(info.flags, FLAG_24) ~= 0 then 24 else 16
|
||||
seekAt = r:tell()
|
||||
info.dataEnd = limit
|
||||
end
|
||||
local C, bits = info.channels, info.bitsPerSample
|
||||
if C < 1 or C > 32 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad channel count " .. C)
|
||||
end
|
||||
if bits ~= 8 and bits ~= 16 and bits ~= 24 and bits ~= 32 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, bits .. "-bit samples")
|
||||
end
|
||||
if info.sampleRate < 1 or info.blocksPerFrame < 1 or info.blocksPerFrame > 10000000 or info.finalFrameBlocks > info.blocksPerFrame then
|
||||
return nil, Err.new(Err.CORRUPT, "bad header")
|
||||
end
|
||||
if info.totalFrames < 1 then
|
||||
return nil, Err.new(Err.CORRUPT, "no frames")
|
||||
end
|
||||
info.float = bit32.band(info.flags, FLAG_FLOAT) ~= 0 and bits == 32
|
||||
info.totalBlocks = (info.totalFrames - 1) * info.blocksPerFrame + info.finalFrameBlocks
|
||||
if seekCount < info.totalFrames or seekAt + seekCount * 4 > limit then
|
||||
return nil, Err.new(Err.TRUNCATED, "the seek table is incomplete")
|
||||
end
|
||||
local starts = table.create(info.totalFrames, 0)
|
||||
local add, prev = 0, 0
|
||||
for i = 1, info.totalFrames do
|
||||
local v = buffer.readu32(buf, seekAt + (i - 1) * 4)
|
||||
if v < prev then
|
||||
add += 4294967296
|
||||
end
|
||||
prev = v
|
||||
starts[i] = base + junk + add + v
|
||||
end
|
||||
for i = 1, info.totalFrames do
|
||||
if starts[i] < base or (i > 1 and starts[i] < starts[i - 1]) then
|
||||
return nil, Err.new(Err.CORRUPT, "bad seek table entry " .. i)
|
||||
end
|
||||
end
|
||||
info.frameStart = starts
|
||||
info.firstFrame = starts[1]
|
||||
info.dataEnd = math.min(math.max(info.dataEnd, starts[info.totalFrames]), limit)
|
||||
info.limit = limit
|
||||
return info :: Info, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decoder
|
||||
export type Decoder = {
|
||||
info: Info,
|
||||
pcm: { number },
|
||||
frame: (self: Decoder, buf: buffer, i: number) -> (number?, Err.Err?),
|
||||
state: Decode.State,
|
||||
}
|
||||
|
||||
local function frame(self: Decoder, buf: buffer, i: number): (number?, Err.Err?)
|
||||
local info = self.info
|
||||
if i < 1 or i > info.totalFrames then
|
||||
return nil, Err.new(Err.ARG, "no frame " .. i)
|
||||
end
|
||||
local start = info.frameStart[i]
|
||||
local rem = (start - info.firstFrame) % 4
|
||||
local want = (if i < info.totalFrames then info.frameStart[i + 1] else info.dataEnd) + 4
|
||||
local stop = math.min(want, info.limit, buffer.len(buf))
|
||||
if start + 8 > stop then
|
||||
return nil, Err.new(Err.TRUNCATED, "frame " .. i .. " is past the end of the data", start)
|
||||
end
|
||||
local n = if i < info.totalFrames then info.blocksPerFrame else info.finalFrameBlocks
|
||||
local n2, msg = Decode.frame(self.state, buf, start - rem, rem, stop, n, self.pcm, info.float, stop < want - 4)
|
||||
if not n2 then
|
||||
return nil, Err.from(msg, start)
|
||||
end
|
||||
return n2, nil
|
||||
end
|
||||
|
||||
-- decoder(info) -> Decoder | nil, Err
|
||||
function Ape.decoder(info: Info): (Decoder?, Err.Err?)
|
||||
local st, msg = Decode.state(info.version, info.level, info.bitsPerSample, info.channels)
|
||||
if not st then
|
||||
return nil, Err.from(msg)
|
||||
end
|
||||
return {
|
||||
info = info,
|
||||
pcm = table.create(math.min(info.blocksPerFrame, 1048576) * info.channels, 0),
|
||||
frame = frame,
|
||||
state = st,
|
||||
}, nil
|
||||
end
|
||||
|
||||
return Ape
|
||||
@@ -0,0 +1,110 @@
|
||||
--!strict
|
||||
-- codecs/audio/ApeTag: APEv1 / APEv2 tags (the tag block of Monkey's Audio, WavPack, Musepack, TTA, OptimFROG and
|
||||
-- some MP3s) -> Types.Tags. Written from the APEv2 specification (wiki.hydrogenaud.io "APEv2 specification"); no
|
||||
-- third-party code. A tag sits at the end of the file (before an optional ID3v1 tag) as items + a 32-byte footer
|
||||
-- "APETAGEX", with an optional 32-byte header in front (APEv2). Item keys become lower case tag keys (Year -> date,
|
||||
-- Track -> track, Album Artist -> albumartist, Disc -> disc, Comment -> comment); text values holding several
|
||||
-- values (NUL separated) are joined with "; "; binary items (cover art) and external links stay in info.items.
|
||||
-- Never throws.
|
||||
--
|
||||
-- local tags, info = ApeTag.find(buf, start, limit) -- the tag ending at limit (or before an ID3v1 tag there)
|
||||
-- -- tags: { title = ..., artist = ... } | nil (no tag / malformed)
|
||||
-- -- info: { start = first byte (the header when present), stop = past the footer, version = 1000 | 2000,
|
||||
-- -- items = { { key = "Title", value = "...", kind = "text" | "binary" | "link" } } }
|
||||
-- local tags, info = ApeTag.parse(buf, footer, start) -- the tag whose footer is at byte `footer` (>= start)
|
||||
local ApeTag = {}
|
||||
|
||||
export type Item = { key: string, value: string, kind: string }
|
||||
export type Info = { start: number, stop: number, version: number, items: { Item } }
|
||||
|
||||
local TO_TAG: { [string]: string } = {
|
||||
year = "date",
|
||||
["album artist"] = "albumartist",
|
||||
albumartist = "albumartist",
|
||||
tracknumber = "track",
|
||||
discnumber = "disc",
|
||||
description = "comment",
|
||||
}
|
||||
local KINDS = { [0] = "text", "binary", "link", "text" }
|
||||
|
||||
-- tagKey(itemKey) -> the Types.Tags key
|
||||
function ApeTag.tagKey(key: string): string
|
||||
local k = string.lower(key)
|
||||
return TO_TAG[k] or k
|
||||
end
|
||||
|
||||
-- parse(buf, footer, start?) -> tags, info | nil: the tag whose 32-byte footer starts at byte `footer`; the items
|
||||
-- must lie at or after `start` (default 0)
|
||||
function ApeTag.parse(buf: buffer, footer: number, start: number?): ({ [string]: string }?, Info?)
|
||||
local lo = start or 0
|
||||
local n = buffer.len(buf)
|
||||
if footer < lo or footer + 32 > n or buffer.readstring(buf, footer, 8) ~= "APETAGEX" then
|
||||
return nil, nil
|
||||
end
|
||||
local version = buffer.readu32(buf, footer + 8)
|
||||
local size = buffer.readu32(buf, footer + 12) -- items + footer
|
||||
local count = buffer.readu32(buf, footer + 16)
|
||||
local flags = buffer.readu32(buf, footer + 20)
|
||||
if size < 32 or footer + 32 - size < lo then
|
||||
return nil, nil
|
||||
end
|
||||
local p = footer + 32 - size
|
||||
local first = p
|
||||
if version >= 2000 and bit32.band(flags, 0x80000000) ~= 0 and p - 32 >= lo and buffer.readstring(buf, p - 32, 8) == "APETAGEX" then
|
||||
first = p - 32
|
||||
end
|
||||
local stop = footer
|
||||
local tags: { [string]: string } = {}
|
||||
local items: { Item } = {}
|
||||
for _ = 1, math.min(count, 65536) do
|
||||
if p + 9 > stop then
|
||||
break
|
||||
end
|
||||
local len = buffer.readu32(buf, p)
|
||||
local iflags = buffer.readu32(buf, p + 4)
|
||||
local k = p + 8
|
||||
while k < stop and buffer.readu8(buf, k) ~= 0 do
|
||||
k += 1
|
||||
end
|
||||
if k >= stop then
|
||||
break
|
||||
end
|
||||
local key = buffer.readstring(buf, p + 8, k - p - 8)
|
||||
local v0 = k + 1
|
||||
if len > stop - v0 then
|
||||
break
|
||||
end
|
||||
local value = buffer.readstring(buf, v0, len)
|
||||
local kind = if version >= 2000 then KINDS[bit32.band(bit32.rshift(iflags, 1), 3)] else "text"
|
||||
table.insert(items, { key = key, value = value, kind = kind })
|
||||
if kind == "text" and key ~= "" then
|
||||
local tk = ApeTag.tagKey(key)
|
||||
local s = (string.gsub(value, "%z+$", ""))
|
||||
s = (string.gsub(s, "%z", "; "))
|
||||
local old = tags[tk]
|
||||
tags[tk] = if old then old .. "; " .. s else s
|
||||
end
|
||||
p = v0 + len
|
||||
end
|
||||
return tags, { start = first, stop = footer + 32, version = version, items = items }
|
||||
end
|
||||
|
||||
-- find(buf, start, limit) -> tags, info | nil: the tag at the end of [start, limit), or just before a 128-byte
|
||||
-- ID3v1 tag ("TAG") there
|
||||
function ApeTag.find(buf: buffer, start: number, limit: number): ({ [string]: string }?, Info?)
|
||||
if limit > buffer.len(buf) then
|
||||
limit = buffer.len(buf)
|
||||
end
|
||||
if limit - start >= 32 then
|
||||
local tags, info = ApeTag.parse(buf, limit - 32, start)
|
||||
if tags then
|
||||
return tags, info
|
||||
end
|
||||
end
|
||||
if limit - start >= 160 and buffer.readstring(buf, limit - 128, 3) == "TAG" then
|
||||
return ApeTag.parse(buf, limit - 160, start)
|
||||
end
|
||||
return nil, nil
|
||||
end
|
||||
|
||||
return ApeTag
|
||||
@@ -0,0 +1,249 @@
|
||||
--!strict
|
||||
-- codecs/audio/Hively/Load: AHX ("THX\0".."THX\2") and HivelyTracker ("HVL\0", "HVL\1") module files -> the replayer's
|
||||
-- Tune. Ported from hvl2wav's replay.c 1.9 loaders (hvl_load_ahx / hvl_reset; BSD-3-Clause, (c) 2006-2018 Pete Gordon;
|
||||
-- licenses/hivelytracker-LICENSE.txt), with bounds checks the C code does not have. Errors are returned as
|
||||
-- (nil, message, kind) for core/Err.from.
|
||||
local Load = {}
|
||||
|
||||
local readu8, readi8 = buffer.readu8, buffer.readi8
|
||||
|
||||
export type PlistEntry = { note: number, waveform: number, fixed: number, fx: { number }, param: { number } }
|
||||
export type Instrument = {
|
||||
name: string,
|
||||
volume: number,
|
||||
waveLength: number,
|
||||
filterLower: number,
|
||||
filterUpper: number,
|
||||
filterSpeed: number,
|
||||
squareLower: number,
|
||||
squareUpper: number,
|
||||
squareSpeed: number,
|
||||
vibratoDelay: number,
|
||||
vibratoSpeed: number,
|
||||
vibratoDepth: number,
|
||||
hardCutRelease: number,
|
||||
hardCutReleaseFrames: number,
|
||||
envelope: { aFrames: number, aVolume: number, dFrames: number, dVolume: number, sFrames: number, rFrames: number, rVolume: number },
|
||||
plist: { speed: number, length: number, entries: { PlistEntry } },
|
||||
}
|
||||
export type Tune = {
|
||||
format: string, -- "ahx" | "hvl"
|
||||
version: number, -- the 4th byte: AHX 0..2, HVL 0..1
|
||||
title: string,
|
||||
channels: number, -- 4 (AHX), 4..16 (HVL)
|
||||
positionNr: number,
|
||||
restart: number,
|
||||
speedMultiplier: number, -- 1..4 player calls per 50 Hz frame
|
||||
trackLength: number, -- rows per track, 1..64
|
||||
trackNr: number, -- the highest track number stored
|
||||
instrumentNr: number,
|
||||
subsongs: { number }, -- first positions of subsongs 1..n
|
||||
positions: buffer, -- positionNr * 16 * 2 bytes: per channel track (u8), transpose (i8)
|
||||
tracks: buffer, -- 257 * 64 * 6 bytes: per track row note, instrument, fx, param, fxb, paramb
|
||||
instruments: { Instrument }, -- 1-based, as numbered in the file
|
||||
mixgain: number, -- (percent * 256) / 100, HVL only (AHX: set by the stereo separation at render time)
|
||||
stereo: number, -- HVL: the default stereo separation 0..4
|
||||
emptyTrack0: boolean, -- track 0 is not stored (always empty)
|
||||
}
|
||||
|
||||
local function cstring(b: buffer, p: number, limit: number, max: number): (string, number)
|
||||
local e = p
|
||||
while e < limit and e - p < max and readu8(b, e) ~= 0 do
|
||||
e += 1
|
||||
end
|
||||
return buffer.readstring(b, p, e - p), e
|
||||
end
|
||||
|
||||
-- parse(b, base, limit) -> Tune | nil, message, kind
|
||||
function Load.parse(b: buffer, base: number, limit: number): (Tune?, string?, string?)
|
||||
local size = limit - base
|
||||
if size < 14 then
|
||||
return nil, "truncated header", "truncated"
|
||||
end
|
||||
local function u8(o: number): number
|
||||
return readu8(b, base + o)
|
||||
end
|
||||
local magic = buffer.readstring(b, base, 3)
|
||||
local ahx = magic == "THX" and u8(3) < 3
|
||||
if not ahx and not (magic == "HVL" and u8(3) <= 1) then
|
||||
return nil, "not an AHX / HVL module", nil
|
||||
end
|
||||
if not ahx and size < 16 then
|
||||
return nil, "truncated header", "truncated"
|
||||
end
|
||||
local posn = bit32.band(u8(6), 0x0f) * 256 + u8(7)
|
||||
local insn, ssn, trkl, trkn = u8(12), u8(13), u8(10), u8(11)
|
||||
local chnn = if ahx then 4 else bit32.rshift(u8(8), 2) + 4
|
||||
local tune: Tune = {
|
||||
format = if ahx then "ahx" else "hvl",
|
||||
version = u8(3),
|
||||
title = "",
|
||||
channels = chnn,
|
||||
positionNr = posn,
|
||||
restart = if ahx then u8(8) * 256 + u8(9) else bit32.band(u8(8), 3) * 256 + u8(9),
|
||||
speedMultiplier = bit32.band(bit32.rshift(u8(6), 5), 3) + 1,
|
||||
trackLength = trkl,
|
||||
trackNr = trkn,
|
||||
instrumentNr = insn,
|
||||
subsongs = {},
|
||||
positions = buffer.create(math.max(posn, 1) * 32),
|
||||
tracks = buffer.create(257 * 64 * 6),
|
||||
instruments = {},
|
||||
mixgain = if ahx then 256 else (u8(14) * 256) // 100,
|
||||
stereo = if ahx then 0 else math.min(u8(15), 4),
|
||||
emptyTrack0 = bit32.band(u8(6), 0x80) ~= 0,
|
||||
}
|
||||
if posn == 0 or posn > 1000 or trkl > 64 or trkl == 0 or insn > 64 then
|
||||
return nil, string.format("bad header (positions %d, track length %d, instruments %d)", posn, trkl, insn), nil
|
||||
end
|
||||
if chnn > 16 then
|
||||
return nil, "unsupported: more than 16 channels", "unsupported"
|
||||
end
|
||||
if tune.restart >= posn then
|
||||
tune.restart = posn - 1
|
||||
end
|
||||
local nameAt = u8(4) * 256 + u8(5)
|
||||
local nptr = limit
|
||||
if nameAt < size then
|
||||
local title, e = cstring(b, base + nameAt, limit, 128)
|
||||
tune.title = title
|
||||
nptr = e + 1
|
||||
end
|
||||
|
||||
local p = base + (if ahx then 14 else 16)
|
||||
local function need(n: number): boolean
|
||||
return p + n <= limit
|
||||
end
|
||||
if not need(ssn * 2 + posn * chnn * 2) then
|
||||
return nil, "truncated position list", "truncated"
|
||||
end
|
||||
for i = 1, ssn do
|
||||
local s = readu8(b, p) * 256 + readu8(b, p + 1)
|
||||
if s >= posn then
|
||||
s = 0
|
||||
end
|
||||
tune.subsongs[i] = s
|
||||
p += 2
|
||||
end
|
||||
for i = 0, posn - 1 do
|
||||
for j = 0, chnn - 1 do
|
||||
buffer.writeu8(tune.positions, (i * 16 + j) * 2, readu8(b, p))
|
||||
buffer.writei8(tune.positions, (i * 16 + j) * 2 + 1, readi8(b, p + 1))
|
||||
p += 2
|
||||
end
|
||||
end
|
||||
local tracks = tune.tracks
|
||||
for i = 0, trkn do
|
||||
if not (tune.emptyTrack0 and i == 0) then
|
||||
for j = 0, trkl - 1 do
|
||||
local o = (i * 64 + j) * 6
|
||||
if ahx then
|
||||
if not need(3) then
|
||||
return nil, "truncated track data", "truncated"
|
||||
end
|
||||
local b0, b1 = readu8(b, p), readu8(b, p + 1)
|
||||
buffer.writeu8(tracks, o, bit32.band(bit32.rshift(b0, 2), 0x3f))
|
||||
buffer.writeu8(tracks, o + 1, bit32.band(b0, 3) * 16 + bit32.rshift(b1, 4))
|
||||
buffer.writeu8(tracks, o + 2, bit32.band(b1, 0xf))
|
||||
buffer.writeu8(tracks, o + 3, readu8(b, p + 2))
|
||||
p += 3
|
||||
else
|
||||
if not need(1) then
|
||||
return nil, "truncated track data", "truncated"
|
||||
end
|
||||
if readu8(b, p) == 0x3f then
|
||||
p += 1
|
||||
else
|
||||
if not need(5) then
|
||||
return nil, "truncated track data", "truncated"
|
||||
end
|
||||
local fx = readu8(b, p + 2)
|
||||
buffer.writeu8(tracks, o, readu8(b, p))
|
||||
buffer.writeu8(tracks, o + 1, readu8(b, p + 1))
|
||||
buffer.writeu8(tracks, o + 2, bit32.rshift(fx, 4))
|
||||
buffer.writeu8(tracks, o + 3, readu8(b, p + 3))
|
||||
buffer.writeu8(tracks, o + 4, bit32.band(fx, 0xf))
|
||||
buffer.writeu8(tracks, o + 5, readu8(b, p + 4))
|
||||
p += 5
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local plSize = if ahx then 4 else 5
|
||||
for i = 1, insn do
|
||||
if not need(22) then
|
||||
return nil, "truncated instrument", "truncated"
|
||||
end
|
||||
local function at(k: number): number
|
||||
return readu8(b, p + k)
|
||||
end
|
||||
local name = ""
|
||||
if nptr < limit then
|
||||
local e
|
||||
name, e = cstring(b, nptr, limit, 128)
|
||||
nptr = e + 1
|
||||
end
|
||||
local plen = at(21)
|
||||
local ins: Instrument = {
|
||||
name = name,
|
||||
volume = at(0),
|
||||
filterSpeed = bit32.bor(bit32.band(bit32.rshift(at(1), 3), 0x1f), bit32.band(bit32.rshift(at(12), 2), 0x20)),
|
||||
waveLength = bit32.band(at(1), 7),
|
||||
envelope = { aFrames = at(2), aVolume = at(3), dFrames = at(4), dVolume = at(5), sFrames = at(6), rFrames = at(7), rVolume = at(8) },
|
||||
filterLower = bit32.band(at(12), 0x7f),
|
||||
vibratoDelay = at(13),
|
||||
hardCutReleaseFrames = bit32.band(bit32.rshift(at(14), 4), 7),
|
||||
hardCutRelease = if bit32.band(at(14), 0x80) ~= 0 then 1 else 0,
|
||||
vibratoDepth = bit32.band(at(14), 0x0f),
|
||||
vibratoSpeed = at(15),
|
||||
squareLower = at(16),
|
||||
squareUpper = at(17),
|
||||
squareSpeed = at(18),
|
||||
filterUpper = bit32.band(at(19), 0x3f),
|
||||
plist = { speed = at(20), length = plen, entries = {} },
|
||||
}
|
||||
p += 22
|
||||
if not need(plen * plSize) then
|
||||
return nil, "truncated instrument play list", "truncated"
|
||||
end
|
||||
for j = 1, plen do
|
||||
local e: PlistEntry
|
||||
local b0, b1, b2, b3 = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2), readu8(b, p + 3)
|
||||
if ahx then
|
||||
local k = bit32.band(bit32.rshift(b0, 5), 7)
|
||||
k = if k == 6 then 12 elseif k == 7 then 15 else k
|
||||
local l = bit32.band(bit32.rshift(b0, 2), 7)
|
||||
l = if l == 6 then 12 elseif l == 7 then 15 else l
|
||||
e = {
|
||||
fx = { l, k },
|
||||
waveform = bit32.band(b0 * 2, 6) + bit32.rshift(b1, 7),
|
||||
fixed = bit32.band(bit32.rshift(b1, 6), 1),
|
||||
note = bit32.band(b1, 0x3f),
|
||||
param = { b2, b3 },
|
||||
}
|
||||
-- 1.6: version 0 modules (before filters) drop the "toggle filter" half of command 4
|
||||
if tune.version == 0 and l == 4 and bit32.band(b2, 0xf0) ~= 0 then
|
||||
e.param[1] = bit32.band(b2, 0x0f)
|
||||
end
|
||||
if tune.version == 0 and k == 4 and bit32.band(b3, 0xf0) ~= 0 then
|
||||
e.param[2] = bit32.band(b3, 0x0f)
|
||||
end
|
||||
else
|
||||
e = {
|
||||
fx = { bit32.band(b0, 0xf), bit32.band(bit32.rshift(b1, 3), 0xf) },
|
||||
waveform = bit32.band(b1, 7),
|
||||
fixed = bit32.band(bit32.rshift(b2, 6), 1),
|
||||
note = bit32.band(b2, 0x3f),
|
||||
param = { b3, readu8(b, p + 4) },
|
||||
}
|
||||
end
|
||||
ins.plist.entries[j] = e
|
||||
p += plSize
|
||||
end
|
||||
tune.instruments[i] = ins
|
||||
end
|
||||
return tune, nil, nil
|
||||
end
|
||||
|
||||
return Load
|
||||
@@ -0,0 +1,970 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- codecs/audio/Hively/Player: the AHX / HivelyTracker replayer: positions and tracks (two effect columns in HVL), the
|
||||
-- instrument engine (ADSR, vibrato, the PList performance list, square modulation, the resonant filter sweep, hard cut,
|
||||
-- ring modulation and panning for HVL) and the integer mixer, all as hvl2wav's replay.c 1.9 computes them so the output
|
||||
-- matches hvl2wav sample for sample. Ported from HivelyTracker (BSD-3-Clause, (c) 2006-2018 Pete Gordon;
|
||||
-- licenses/hivelytracker-LICENSE.txt). Where the C code reads outside its arrays on bad data this port clamps instead.
|
||||
local Tables = require("@formats/codecs/audio/Hively/Tables")
|
||||
local Load = require("@formats/codecs/audio/Hively/Load")
|
||||
|
||||
local Player = {}
|
||||
|
||||
local readu8, readi8, writei8, writef32 = buffer.readu8, buffer.readi8, buffer.writei8, buffer.writef32
|
||||
local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift
|
||||
|
||||
local FILTER_SET = Tables.FILTER_SET
|
||||
local WO_TRIANGLE_04, WO_SAWTOOTH_04 = Tables.WO_TRIANGLE_04, Tables.WO_SAWTOOTH_04
|
||||
local WO_SQUARES, WO_WHITENOISE = Tables.WO_SQUARES, Tables.WO_WHITENOISE
|
||||
local OFFSETS, VIB, PERIOD = Tables.OFFSETS, Tables.VIB, Tables.PERIOD
|
||||
local WAVEFORM_AT = { [0] = WO_TRIANGLE_04, WO_SAWTOOTH_04, 0, WO_WHITENOISE }
|
||||
local WRAP = 0x280 * 65536
|
||||
local TWO32 = 4294967296
|
||||
|
||||
local f32scratch = buffer.create(4)
|
||||
|
||||
local function s16(v: number): number
|
||||
return (v + 32768) % 65536 - 32768
|
||||
end
|
||||
|
||||
local function tdiv(a: number, b: number): number -- C integer division (truncates)
|
||||
local q = a / b
|
||||
return if q >= 0 then math.floor(q) else -math.floor(-q)
|
||||
end
|
||||
|
||||
local function period(i: number): number
|
||||
return PERIOD[i] or 0
|
||||
end
|
||||
|
||||
-- (3546897.f * 65536.f) / period as a float, then / mix rate as a double, truncated
|
||||
local function deltaOf(p: number, freq: number): number
|
||||
if p == 0 then
|
||||
return 1
|
||||
end
|
||||
writef32(f32scratch, 0, 232449441792 / p) -- 3546897 * 65536 = 232449441792 (exact in a float)
|
||||
local d = math.floor(buffer.readf32(f32scratch, 0) / freq)
|
||||
if d < 0 then
|
||||
d = 0
|
||||
end
|
||||
if d > WRAP then
|
||||
d -= WRAP
|
||||
end
|
||||
if d == 0 then
|
||||
d = 1
|
||||
end
|
||||
return d
|
||||
end
|
||||
|
||||
export type Voice = { [string]: any }
|
||||
export type State = {
|
||||
tune: Load.Tune,
|
||||
freq: number,
|
||||
version: number,
|
||||
channels: number,
|
||||
voices: { Voice },
|
||||
tempo: number,
|
||||
posNr: number,
|
||||
posJump: number,
|
||||
posJumpNote: number,
|
||||
noteNr: number,
|
||||
stepWaitFrames: number,
|
||||
getNewPosition: boolean,
|
||||
patternBreak: boolean,
|
||||
songEndReached: boolean,
|
||||
playingTime: number,
|
||||
mixgain: number,
|
||||
waves: buffer,
|
||||
panL: { number },
|
||||
panR: { number },
|
||||
}
|
||||
|
||||
local function newVoice(i: number): Voice
|
||||
return {
|
||||
track = 0, nextTrack = 0, transpose = 0, nextTranspose = 0, overrideTranspose = 1000,
|
||||
adsrVolume = 0, aFrames = 0, aVolume = 0, dFrames = 0, dVolume = 0, sFrames = 0, rFrames = 0, rVolume = 0,
|
||||
instrument = false :: any, samplePos = 0, delta = 1, instrPeriod = 0, trackPeriod = 0, vibratoPeriod = 0,
|
||||
waveLength = 0, noteMaxVolume = 0, perfSubVolume = 0, newWaveform = false, waveform = 0, plantPeriod = false,
|
||||
voiceVolume = 0, plantSquare = false, ignoreSquare = 0, fixedNote = 0, volumeSlideUp = 0, volumeSlideDown = 0,
|
||||
hardCut = 0, hardCutRelease = 0, hardCutReleaseF = 0, periodSlideOn = false, periodSlideSpeed = 0,
|
||||
periodSlidePeriod = 0, periodSlideLimit = 0, periodSlideWithLimit = false, periodPerfSlideSpeed = 0,
|
||||
periodPerfSlidePeriod = 0, periodPerfSlideOn = false, vibratoDelay = 0, vibratoSpeed = 0, vibratoCurrent = 0,
|
||||
vibratoDepth = 0, squareOn = 0, squareInit = 0, squareWait = 0, squareLowerLimit = 0, squareUpperLimit = 0,
|
||||
squarePos = 0, squareSign = 0, squareSlidingIn = false, squareReverse = false, filterOn = 0, filterInit = 0,
|
||||
filterWait = 0, filterSpeed = 0, filterUpperLimit = 0, filterLowerLimit = 0, filterPos = 0, filterSign = 0,
|
||||
filterSlidingIn = false, ignoreFilter = 0, perfCurrent = 0, perfSpeed = 0, perfWait = 0, perfList = false :: any,
|
||||
audioSrc = false :: any, audioOff = 0, noteDelayOn = false, noteCutOn = false, noteDelayWait = 0, noteCutWait = 0,
|
||||
audioPeriod = 0, audioVolume = 0, wnHi = 0, wnLo = 0x280,
|
||||
squareBuf = buffer.create(0x80), voiceBuf = buffer.create(0x284), voiceNum = i, trackMasterVolume = 0x40,
|
||||
pan = 0, setPan = 0, panMultLeft = 0, panMultRight = 0,
|
||||
ringSamplePos = 0, ringDelta = 0, ringMix = false, ringPlantPeriod = false, ringBasePeriod = 0,
|
||||
ringAudioPeriod = 0, ringAudioOff = -1, ringNewWaveform = false, ringWaveform = 0, ringFixedPeriod = 0,
|
||||
ringBuf = buffer.create(0x284),
|
||||
}
|
||||
end
|
||||
|
||||
-- new(tune, freq, stereo, subsong) -> State | nil (subsong out of range). stereo: AHX separation 0..4 (HVL: the file's)
|
||||
function Player.new(tune: Load.Tune, freq: number, stereo: number, subsong: number): State?
|
||||
if subsong < 0 or subsong > #tune.subsongs then
|
||||
return nil
|
||||
end
|
||||
local t = Tables.get()
|
||||
local defstereo = if tune.format == "ahx" then math.clamp(math.floor(stereo), 0, 4) else tune.stereo
|
||||
local mixgain = tune.mixgain
|
||||
if tune.format == "ahx" then
|
||||
local defgain = { [0] = 71, 72, 76, 85, 100 }
|
||||
mixgain = (defgain[defstereo] * 256) // 100
|
||||
end
|
||||
local st: State = {
|
||||
tune = tune, freq = freq, version = if tune.format == "hvl" then tune.version else 0,
|
||||
channels = tune.channels, voices = {}, tempo = 6, posNr = if subsong > 0 then tune.subsongs[subsong] else 0,
|
||||
posJump = 0, posJumpNote = 0, noteNr = 0, stepWaitFrames = 0, getNewPosition = true, patternBreak = false,
|
||||
songEndReached = false, playingTime = 0, mixgain = mixgain, waves = t.waves, panL = t.panL, panR = t.panR,
|
||||
}
|
||||
local left, right = Tables.STEREO_LEFT[defstereo], Tables.STEREO_RIGHT[defstereo]
|
||||
for i = 0, 15 do
|
||||
local v = newVoice(i)
|
||||
local p = if i % 4 == 0 or i % 4 == 3 then left else right
|
||||
v.pan, v.setPan, v.panMultLeft, v.panMultRight = p, p, t.panL[p], t.panR[p]
|
||||
st.voices[i + 1] = v
|
||||
end
|
||||
return st
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ steps
|
||||
local function setPan(st: State, v: Voice, p: number)
|
||||
v.pan = p
|
||||
v.panMultLeft, v.panMultRight = st.panL[p], st.panR[p]
|
||||
end
|
||||
|
||||
local function stepfx1(st: State, v: Voice, fx: number, param: number)
|
||||
if fx == 0x0 then
|
||||
local lo = band(param, 0x0f)
|
||||
if lo > 0 and lo <= 9 then
|
||||
st.posJump = lo
|
||||
end
|
||||
elseif fx == 0x5 or fx == 0xa then
|
||||
v.volumeSlideDown = band(param, 0x0f)
|
||||
v.volumeSlideUp = rshift(param, 4)
|
||||
elseif fx == 0x7 then
|
||||
if param > 127 then
|
||||
param -= 256
|
||||
end
|
||||
setPan(st, v, param + 128)
|
||||
v.setPan = param + 128
|
||||
elseif fx == 0xb then
|
||||
st.posJump = (st.posJump * 100 + band(param, 0x0f) + rshift(param, 4) * 10) % 65536
|
||||
st.patternBreak = true
|
||||
if st.posJump <= st.posNr then
|
||||
st.songEndReached = true
|
||||
end
|
||||
elseif fx == 0xd then
|
||||
st.posJump = st.posNr + 1
|
||||
st.posJumpNote = band(param, 0x0f) + rshift(param, 4) * 10
|
||||
st.patternBreak = true
|
||||
if st.posJumpNote > st.tune.trackLength then
|
||||
st.posJumpNote = 0
|
||||
end
|
||||
elseif fx == 0xe then
|
||||
if rshift(param, 4) == 0xc and band(param, 0x0f) < st.tempo then
|
||||
v.noteCutWait = band(param, 0x0f)
|
||||
if v.noteCutWait ~= 0 then
|
||||
v.noteCutOn = true
|
||||
v.hardCutRelease = 0
|
||||
end
|
||||
end
|
||||
elseif fx == 0xf then
|
||||
st.tempo = param
|
||||
if param == 0 then
|
||||
st.songEndReached = true
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function stepfx2(v: Voice, fx: number, param: number, note: number): number
|
||||
if fx == 0x9 then
|
||||
v.squarePos = rshift(param, 5 - v.waveLength)
|
||||
v.ignoreSquare = 1
|
||||
elseif fx == 0x3 or fx == 0x5 then
|
||||
if fx == 0x3 and param ~= 0 then
|
||||
v.periodSlideSpeed = param
|
||||
end
|
||||
if note ~= 0 then
|
||||
local new = period(note)
|
||||
local diff = period(v.trackPeriod) - new
|
||||
new = diff + v.periodSlidePeriod
|
||||
if new ~= 0 then
|
||||
v.periodSlideLimit = s16(-diff)
|
||||
end
|
||||
end
|
||||
v.periodSlideOn = true
|
||||
v.periodSlideWithLimit = true
|
||||
note = 0
|
||||
end
|
||||
return note
|
||||
end
|
||||
|
||||
local function stepfx3(st: State, v: Voice, fx: number, param: number)
|
||||
if fx == 0x01 then
|
||||
v.periodSlideSpeed = -param
|
||||
v.periodSlideOn = true
|
||||
v.periodSlideWithLimit = false
|
||||
elseif fx == 0x02 then
|
||||
v.periodSlideSpeed = param
|
||||
v.periodSlideOn = true
|
||||
v.periodSlideWithLimit = false
|
||||
elseif fx == 0x04 then
|
||||
if param == 0 or param == 0x40 then
|
||||
return
|
||||
end
|
||||
if param < 0x40 then
|
||||
v.ignoreFilter = param
|
||||
return
|
||||
end
|
||||
if param > 0x7f then
|
||||
return
|
||||
end
|
||||
v.filterPos = param - 0x40
|
||||
elseif fx == 0x0c then
|
||||
if param <= 0x40 then
|
||||
v.noteMaxVolume = param
|
||||
return
|
||||
end
|
||||
param -= 0x50
|
||||
if param < 0 then
|
||||
return
|
||||
end
|
||||
if param <= 0x40 then
|
||||
for i = 1, st.channels do
|
||||
st.voices[i].trackMasterVolume = param
|
||||
end
|
||||
return
|
||||
end
|
||||
param -= 0xa0 - 0x50
|
||||
if param < 0 then
|
||||
return
|
||||
end
|
||||
if param <= 0x40 then
|
||||
v.trackMasterVolume = param
|
||||
end
|
||||
elseif fx == 0xe then
|
||||
local sub, lo = rshift(param, 4), band(param, 0x0f)
|
||||
if sub == 0x1 then
|
||||
v.periodSlidePeriod = s16(v.periodSlidePeriod - lo)
|
||||
v.plantPeriod = true
|
||||
elseif sub == 0x2 then
|
||||
v.periodSlidePeriod = s16(v.periodSlidePeriod + lo)
|
||||
v.plantPeriod = true
|
||||
elseif sub == 0x4 then
|
||||
v.vibratoDepth = lo
|
||||
elseif sub == 0xa then
|
||||
v.noteMaxVolume = math.min(v.noteMaxVolume + lo, 0x40)
|
||||
elseif sub == 0xb then
|
||||
v.noteMaxVolume = math.max(v.noteMaxVolume - lo, 0)
|
||||
elseif sub == 0xf then
|
||||
if st.version >= 1 and lo == 1 then
|
||||
v.overrideTranspose = v.transpose
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function processStep(st: State, v: Voice)
|
||||
v.volumeSlideUp, v.volumeSlideDown = 0, 0
|
||||
local tune = st.tune
|
||||
local track = readu8(tune.positions, (st.posNr * 16 + v.voiceNum) * 2)
|
||||
local so = (track * 64 + st.noteNr) * 6
|
||||
local tracks = tune.tracks
|
||||
local note, instr = readu8(tracks, so), readu8(tracks, so + 1)
|
||||
local fx, fxp, fxb, fxbp = band(readu8(tracks, so + 2), 0xf), readu8(tracks, so + 3), band(readu8(tracks, so + 4), 0xf), readu8(tracks, so + 5)
|
||||
|
||||
local doneNoteDel = false
|
||||
if fx == 0xe and band(fxp, 0xf0) == 0xd0 then
|
||||
if v.noteDelayOn then
|
||||
v.noteDelayOn = false
|
||||
doneNoteDel = true
|
||||
elseif band(fxp, 0x0f) < st.tempo then
|
||||
v.noteDelayWait = band(fxp, 0x0f)
|
||||
if v.noteDelayWait ~= 0 then
|
||||
v.noteDelayOn = true
|
||||
return
|
||||
end
|
||||
end
|
||||
end
|
||||
if not doneNoteDel and fxb == 0xe and band(fxbp, 0xf0) == 0xd0 then
|
||||
if v.noteDelayOn then
|
||||
v.noteDelayOn = false
|
||||
elseif band(fxbp, 0x0f) < st.tempo then
|
||||
v.noteDelayWait = band(fxbp, 0x0f)
|
||||
if v.noteDelayWait ~= 0 then
|
||||
v.noteDelayOn = true
|
||||
return
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
if note ~= 0 then
|
||||
v.overrideTranspose = 1000
|
||||
end
|
||||
stepfx1(st, v, fx, fxp)
|
||||
stepfx1(st, v, fxb, fxbp)
|
||||
|
||||
if instr ~= 0 and instr <= tune.instrumentNr then
|
||||
local ins = tune.instruments[instr]
|
||||
setPan(st, v, v.setPan)
|
||||
v.periodSlideSpeed, v.periodSlidePeriod, v.periodSlideLimit = 0, 0, 0
|
||||
v.perfSubVolume = 0x40
|
||||
v.adsrVolume = 0
|
||||
v.instrument = ins
|
||||
v.samplePos = 0
|
||||
local env = ins.envelope
|
||||
v.aFrames = env.aFrames
|
||||
v.aVolume = s16(if v.aFrames ~= 0 then tdiv(env.aVolume * 256, v.aFrames) else env.aVolume * 256)
|
||||
v.dFrames = env.dFrames
|
||||
v.dVolume = s16(if v.dFrames ~= 0 then tdiv((env.dVolume - env.aVolume) * 256, v.dFrames) else env.dVolume * 256)
|
||||
v.sFrames = env.sFrames
|
||||
v.rFrames = env.rFrames
|
||||
v.rVolume = s16(if v.rFrames ~= 0 then tdiv((env.rVolume - env.dVolume) * 256, v.rFrames) else env.rVolume * 256)
|
||||
v.waveLength = math.min(ins.waveLength, 5)
|
||||
v.noteMaxVolume = ins.volume
|
||||
v.vibratoCurrent = 0
|
||||
v.vibratoDelay = ins.vibratoDelay
|
||||
v.vibratoDepth = ins.vibratoDepth
|
||||
v.vibratoSpeed = ins.vibratoSpeed
|
||||
v.vibratoPeriod = 0
|
||||
v.hardCutRelease = ins.hardCutRelease
|
||||
v.hardCut = ins.hardCutReleaseFrames
|
||||
v.ignoreSquare, v.squareSlidingIn = 0, false
|
||||
v.squareWait, v.squareOn = 0, 0
|
||||
local lower = rshift(ins.squareLower, 5 - v.waveLength)
|
||||
local upper = rshift(ins.squareUpper, 5 - v.waveLength)
|
||||
if upper < lower then
|
||||
lower, upper = upper, lower
|
||||
end
|
||||
v.squareUpperLimit, v.squareLowerLimit = upper, lower
|
||||
v.ignoreFilter, v.filterWait, v.filterOn = 0, 0, 0
|
||||
v.filterSlidingIn = false
|
||||
local d6, d3, d4 = ins.filterSpeed, ins.filterLower, ins.filterUpper
|
||||
v.filterSpeed = d6
|
||||
if d3 > d4 then
|
||||
d3, d4 = d4, d3
|
||||
end
|
||||
v.filterUpperLimit, v.filterLowerLimit = d4, d3
|
||||
v.filterPos = 32
|
||||
v.perfWait, v.perfCurrent = 0, 0
|
||||
v.perfSpeed = ins.plist.speed
|
||||
v.perfList = ins.plist
|
||||
v.ringMix = false
|
||||
v.ringSamplePos = 0
|
||||
v.ringPlantPeriod = false
|
||||
v.ringNewWaveform = false
|
||||
end
|
||||
|
||||
v.periodSlideOn = false
|
||||
note = stepfx2(v, fx, fxp, note)
|
||||
note = stepfx2(v, fxb, fxbp, note)
|
||||
if note ~= 0 then
|
||||
v.trackPeriod = note
|
||||
v.plantPeriod = true
|
||||
end
|
||||
stepfx3(st, v, fx, fxp)
|
||||
stepfx3(st, v, fxb, fxbp)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ frames
|
||||
local function plistCommand(st: State, v: Voice, fx: number, param: number)
|
||||
if fx == 0 then
|
||||
if param > 0 and param < 0x40 then
|
||||
if v.ignoreFilter ~= 0 then
|
||||
v.filterPos = v.ignoreFilter
|
||||
v.ignoreFilter = 0
|
||||
else
|
||||
v.filterPos = param
|
||||
end
|
||||
v.newWaveform = true
|
||||
end
|
||||
elseif fx == 1 then
|
||||
v.periodPerfSlideSpeed = param
|
||||
v.periodPerfSlideOn = true
|
||||
elseif fx == 2 then
|
||||
v.periodPerfSlideSpeed = -param
|
||||
v.periodPerfSlideOn = true
|
||||
elseif fx == 3 then
|
||||
if v.ignoreSquare == 0 then
|
||||
v.squarePos = rshift(param, 5 - v.waveLength)
|
||||
else
|
||||
v.ignoreSquare = 0
|
||||
end
|
||||
elseif fx == 4 then
|
||||
if param == 0 then
|
||||
v.squareOn = 1 - v.squareOn
|
||||
v.squareInit = v.squareOn
|
||||
v.squareSign = 1
|
||||
else
|
||||
if band(param, 0x0f) ~= 0 then
|
||||
v.squareOn = 1 - v.squareOn
|
||||
v.squareInit = v.squareOn
|
||||
v.squareSign = if band(param, 0x0f) == 0x0f then -1 else 1
|
||||
end
|
||||
if band(param, 0xf0) ~= 0 then
|
||||
v.filterOn = 1 - v.filterOn
|
||||
v.filterInit = v.filterOn
|
||||
v.filterSign = if band(param, 0xf0) == 0xf0 then -1 else 1
|
||||
end
|
||||
end
|
||||
elseif fx == 5 then
|
||||
v.perfCurrent = param
|
||||
elseif fx == 7 or fx == 8 then
|
||||
if param >= 1 and param <= 0x3c then
|
||||
v.ringBasePeriod = param
|
||||
v.ringFixedPeriod = 1
|
||||
elseif param >= 0x81 and param <= 0xbc then
|
||||
v.ringBasePeriod = param - 0x80
|
||||
v.ringFixedPeriod = 0
|
||||
else
|
||||
v.ringBasePeriod = 0
|
||||
v.ringFixedPeriod = 0
|
||||
v.ringNewWaveform = false
|
||||
v.ringAudioOff = -1
|
||||
v.ringMix = false
|
||||
return
|
||||
end
|
||||
v.ringWaveform = fx - 7
|
||||
v.ringNewWaveform = true
|
||||
v.ringPlantPeriod = true
|
||||
elseif fx == 9 then
|
||||
if param > 127 then
|
||||
param -= 256
|
||||
end
|
||||
setPan(st, v, param + 128)
|
||||
elseif fx == 12 then
|
||||
if param <= 0x40 then
|
||||
v.noteMaxVolume = param
|
||||
return
|
||||
end
|
||||
param -= 0x50
|
||||
if param < 0 then
|
||||
return
|
||||
end
|
||||
if param <= 0x40 then
|
||||
v.perfSubVolume = param
|
||||
return
|
||||
end
|
||||
param -= 0xa0 - 0x50
|
||||
if param < 0 then
|
||||
return
|
||||
end
|
||||
if param <= 0x40 then
|
||||
v.trackMasterVolume = param
|
||||
end
|
||||
elseif fx == 15 then
|
||||
v.perfSpeed = param
|
||||
v.perfWait = param
|
||||
end
|
||||
end
|
||||
|
||||
-- the noise offset generator (vc_WNRandom, a 64-bit `long` in hvl2wav): W += 2239384;
|
||||
-- W = ((((W >> 8) | (W << 24)) + 782323) ^ 75) - 6735
|
||||
local function wnStep(v: Voice)
|
||||
local hi, lo = v.wnHi, v.wnLo + 2239384
|
||||
if lo >= TWO32 then
|
||||
lo -= TWO32
|
||||
hi = (hi + 1) % TWO32
|
||||
end
|
||||
local shi = rshift(hi, 8)
|
||||
if hi >= 0x80000000 then
|
||||
shi = bor(shi, 0xff000000)
|
||||
end
|
||||
local nlo = bor(rshift(lo, 8), lshift(band(hi, 0xff), 24), lshift(lo, 24))
|
||||
local nhi = bor(shi, lshift(hi, 24), rshift(lo, 8))
|
||||
nlo += 782323
|
||||
if nlo >= TWO32 then
|
||||
nlo -= TWO32
|
||||
nhi = (nhi + 1) % TWO32
|
||||
end
|
||||
nlo = bit32.bxor(nlo, 75)
|
||||
nlo -= 6735
|
||||
if nlo < 0 then
|
||||
nlo += TWO32
|
||||
nhi = (nhi + TWO32 - 1) % TWO32
|
||||
end
|
||||
v.wnHi, v.wnLo = nhi, nlo
|
||||
end
|
||||
|
||||
local function processFrame(st: State, v: Voice)
|
||||
local tune = st.tune
|
||||
if v.noteDelayOn then
|
||||
if v.noteDelayWait <= 0 then
|
||||
processStep(st, v)
|
||||
else
|
||||
v.noteDelayWait -= 1
|
||||
end
|
||||
end
|
||||
|
||||
if v.hardCut ~= 0 then
|
||||
local row = st.noteNr + 1
|
||||
local nextinst
|
||||
if row < tune.trackLength then
|
||||
nextinst = readu8(tune.tracks, ((v.track * 64) + row) * 6 + 1)
|
||||
else
|
||||
nextinst = readu8(tune.tracks, (v.nextTrack * 64) * 6 + 1)
|
||||
end
|
||||
if nextinst ~= 0 then
|
||||
local d1 = math.max(st.tempo - v.hardCut, 0)
|
||||
if not v.noteCutOn then
|
||||
v.noteCutOn = true
|
||||
v.noteCutWait = d1
|
||||
v.hardCutReleaseF = -(d1 - st.tempo)
|
||||
else
|
||||
v.hardCut = 0
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
if v.noteCutOn then
|
||||
if v.noteCutWait <= 0 then
|
||||
v.noteCutOn = false
|
||||
if v.hardCutRelease ~= 0 then
|
||||
local ins = v.instrument
|
||||
local f = v.hardCutReleaseF
|
||||
v.rVolume = if f ~= 0 then s16(tdiv(-(v.adsrVolume - ins.envelope.rVolume * 256), f)) else 0
|
||||
v.rFrames = f
|
||||
v.aFrames, v.dFrames, v.sFrames = 0, 0, 0
|
||||
else
|
||||
v.noteMaxVolume = 0
|
||||
end
|
||||
else
|
||||
v.noteCutWait -= 1
|
||||
end
|
||||
end
|
||||
|
||||
-- ADSR envelope
|
||||
if v.aFrames ~= 0 then
|
||||
v.adsrVolume += v.aVolume
|
||||
v.aFrames -= 1
|
||||
if v.aFrames <= 0 then
|
||||
v.adsrVolume = v.instrument.envelope.aVolume * 256
|
||||
end
|
||||
elseif v.dFrames ~= 0 then
|
||||
v.adsrVolume += v.dVolume
|
||||
v.dFrames -= 1
|
||||
if v.dFrames <= 0 then
|
||||
v.adsrVolume = v.instrument.envelope.dVolume * 256
|
||||
end
|
||||
elseif v.sFrames ~= 0 then
|
||||
v.sFrames -= 1
|
||||
elseif v.rFrames ~= 0 then
|
||||
v.adsrVolume += v.rVolume
|
||||
v.rFrames -= 1
|
||||
if v.rFrames <= 0 then
|
||||
v.adsrVolume = v.instrument.envelope.rVolume * 256
|
||||
end
|
||||
end
|
||||
|
||||
-- volume slide
|
||||
v.noteMaxVolume = math.clamp(v.noteMaxVolume + v.volumeSlideUp - v.volumeSlideDown, 0, 0x40)
|
||||
|
||||
-- portamento
|
||||
if v.periodSlideOn then
|
||||
if v.periodSlideWithLimit then
|
||||
local d0 = v.periodSlidePeriod - v.periodSlideLimit
|
||||
local d2 = v.periodSlideSpeed
|
||||
if d0 > 0 then
|
||||
d2 = -d2
|
||||
end
|
||||
if d0 ~= 0 then
|
||||
local sum = d0 + d2
|
||||
-- (d0 + d2) ^ d0 >= 0: the same sign (or zero)
|
||||
if (sum >= 0) == (d0 >= 0) then
|
||||
d0 = v.periodSlidePeriod + d2
|
||||
else
|
||||
d0 = v.periodSlideLimit
|
||||
end
|
||||
v.periodSlidePeriod = s16(d0)
|
||||
v.plantPeriod = true
|
||||
end
|
||||
else
|
||||
v.periodSlidePeriod = s16(v.periodSlidePeriod + v.periodSlideSpeed)
|
||||
v.plantPeriod = true
|
||||
end
|
||||
end
|
||||
|
||||
-- vibrato
|
||||
if v.vibratoDepth ~= 0 then
|
||||
if v.vibratoDelay <= 0 then
|
||||
v.vibratoPeriod = (VIB[v.vibratoCurrent] * v.vibratoDepth) // 128
|
||||
v.plantPeriod = true
|
||||
v.vibratoCurrent = band(v.vibratoCurrent + v.vibratoSpeed, 0x3f)
|
||||
else
|
||||
v.vibratoDelay -= 1
|
||||
end
|
||||
end
|
||||
|
||||
-- PList
|
||||
local pl = v.perfList
|
||||
if pl then
|
||||
if v.instrument and v.perfCurrent < v.instrument.plist.length then
|
||||
local overflow = v.perfWait == 128
|
||||
v.perfWait = s16(v.perfWait - 1)
|
||||
local w8 = (v.perfWait + 128) % 256 - 128
|
||||
if overflow or w8 <= 0 then
|
||||
local cur = v.perfCurrent
|
||||
v.perfCurrent += 1
|
||||
v.perfWait = v.perfSpeed
|
||||
local e = pl.entries[cur + 1]
|
||||
if e then
|
||||
if e.waveform ~= 0 then
|
||||
v.waveform = e.waveform - 1
|
||||
v.newWaveform = true
|
||||
v.periodPerfSlideSpeed, v.periodPerfSlidePeriod = 0, 0
|
||||
end
|
||||
v.periodPerfSlideOn = false
|
||||
plistCommand(st, v, e.fx[1], e.param[1])
|
||||
plistCommand(st, v, e.fx[2], e.param[2])
|
||||
if e.note ~= 0 then
|
||||
v.instrPeriod = e.note
|
||||
v.plantPeriod = true
|
||||
v.fixedNote = e.fixed
|
||||
end
|
||||
end
|
||||
end
|
||||
else
|
||||
if v.perfWait ~= 0 then
|
||||
v.perfWait -= 1
|
||||
else
|
||||
v.periodPerfSlideSpeed = 0
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- perf portamento
|
||||
if v.periodPerfSlideOn then
|
||||
v.periodPerfSlidePeriod = s16(v.periodPerfSlidePeriod - v.periodPerfSlideSpeed)
|
||||
if v.periodPerfSlidePeriod ~= 0 then
|
||||
v.plantPeriod = true
|
||||
end
|
||||
end
|
||||
|
||||
if v.waveform == 2 and v.squareOn ~= 0 then
|
||||
v.squareWait -= 1
|
||||
if v.squareWait <= 0 then
|
||||
local d1, d2, d3 = v.squareLowerLimit, v.squareUpperLimit, v.squarePos
|
||||
if v.squareInit ~= 0 then
|
||||
v.squareInit = 0
|
||||
if d3 <= d1 then
|
||||
v.squareSlidingIn = true
|
||||
v.squareSign = 1
|
||||
elseif d3 >= d2 then
|
||||
v.squareSlidingIn = true
|
||||
v.squareSign = -1
|
||||
end
|
||||
end
|
||||
if d1 == d3 or d2 == d3 then
|
||||
if v.squareSlidingIn then
|
||||
v.squareSlidingIn = false
|
||||
else
|
||||
v.squareSign = -v.squareSign
|
||||
end
|
||||
end
|
||||
d3 += v.squareSign
|
||||
v.squarePos = s16(d3)
|
||||
v.plantSquare = true
|
||||
local ins: any = v.instrument
|
||||
v.squareWait = if ins then ins.squareSpeed else 0
|
||||
end
|
||||
end
|
||||
|
||||
if v.filterOn ~= 0 then
|
||||
v.filterWait -= 1
|
||||
if v.filterWait <= 0 then
|
||||
local d1, d2, d3 = v.filterLowerLimit, v.filterUpperLimit, v.filterPos
|
||||
if v.filterInit ~= 0 then
|
||||
v.filterInit = 0
|
||||
if d3 <= d1 then
|
||||
v.filterSlidingIn = true
|
||||
v.filterSign = 1
|
||||
elseif d3 >= d2 then
|
||||
v.filterSlidingIn = true
|
||||
v.filterSign = -1
|
||||
end
|
||||
end
|
||||
local fmax = if v.filterSpeed < 4 then 5 - v.filterSpeed else 1
|
||||
for _ = 1, fmax do
|
||||
if d1 == d3 or d2 == d3 then
|
||||
if v.filterSlidingIn then
|
||||
v.filterSlidingIn = false
|
||||
else
|
||||
v.filterSign = -v.filterSign
|
||||
end
|
||||
end
|
||||
d3 += v.filterSign
|
||||
end
|
||||
v.filterPos = math.clamp(d3, 1, 63)
|
||||
v.newWaveform = true
|
||||
v.filterWait = math.max(v.filterSpeed - 3, 1)
|
||||
end
|
||||
end
|
||||
|
||||
local waves = st.waves
|
||||
local fpos = math.clamp(v.filterPos, 1, 63)
|
||||
if v.waveform == 2 or v.plantSquare then
|
||||
-- CalcSquare
|
||||
local sp = WO_SQUARES + (fpos - 0x20) * FILTER_SET
|
||||
local x = v.squarePos * 2 ^ (5 - v.waveLength)
|
||||
if x > 0x20 then
|
||||
x = 0x40 - x
|
||||
v.squareReverse = true
|
||||
end
|
||||
if x > 0 then
|
||||
sp += (x - 1) * 128
|
||||
end
|
||||
local delta = 32 // 2 ^ v.waveLength
|
||||
local sb = v.squareBuf
|
||||
for i = 0, 4 * 2 ^ v.waveLength - 1 do
|
||||
writei8(sb, i, readi8(waves, sp))
|
||||
sp += delta
|
||||
end
|
||||
v.newWaveform = true
|
||||
v.waveform = 2
|
||||
v.plantSquare = false
|
||||
end
|
||||
|
||||
if v.waveform == 3 then
|
||||
v.newWaveform = true
|
||||
end
|
||||
|
||||
if v.ringNewWaveform then
|
||||
if v.ringWaveform > 1 then
|
||||
v.ringWaveform = 1
|
||||
end
|
||||
v.ringAudioOff = WAVEFORM_AT[v.ringWaveform] + OFFSETS[v.waveLength]
|
||||
end
|
||||
|
||||
if v.newWaveform and v.waveform <= 3 then
|
||||
if v.waveform == 2 then
|
||||
v.audioSrc, v.audioOff = v.squareBuf, 0
|
||||
else
|
||||
local off = WAVEFORM_AT[v.waveform] + (fpos - 0x20) * FILTER_SET
|
||||
if v.waveform < 2 then
|
||||
off += OFFSETS[v.waveLength]
|
||||
else
|
||||
off += band(band(v.wnLo, 2 * 0x280 - 1), 0xfffffffe)
|
||||
wnStep(v)
|
||||
end
|
||||
v.audioSrc, v.audioOff = waves, off
|
||||
end
|
||||
end
|
||||
|
||||
-- ring modulation period
|
||||
if v.ringAudioOff >= 0 then
|
||||
local rp = v.ringBasePeriod
|
||||
if v.ringFixedPeriod == 0 then
|
||||
if v.overrideTranspose ~= 1000 then
|
||||
rp += v.overrideTranspose + v.trackPeriod - 1
|
||||
else
|
||||
rp += v.transpose + v.trackPeriod - 1
|
||||
end
|
||||
end
|
||||
rp = period(math.clamp(s16(rp), 0, 60))
|
||||
if v.ringFixedPeriod == 0 then
|
||||
rp += v.periodSlidePeriod
|
||||
end
|
||||
rp = s16(rp + v.periodPerfSlidePeriod + v.vibratoPeriod)
|
||||
v.ringAudioPeriod = math.clamp(rp, 0x71, 0xd60)
|
||||
end
|
||||
|
||||
-- the period
|
||||
local ap = v.instrPeriod
|
||||
if v.fixedNote == 0 then
|
||||
if v.overrideTranspose ~= 1000 then
|
||||
ap += v.overrideTranspose + v.trackPeriod - 1
|
||||
else
|
||||
ap += v.transpose + v.trackPeriod - 1
|
||||
end
|
||||
end
|
||||
ap = period(math.clamp(s16(ap), 0, 60))
|
||||
if v.fixedNote == 0 then
|
||||
ap += v.periodSlidePeriod
|
||||
end
|
||||
ap = s16(ap + v.periodPerfSlidePeriod + v.vibratoPeriod)
|
||||
v.audioPeriod = math.clamp(ap, 0x71, 0xd60)
|
||||
|
||||
local vol = (v.adsrVolume // 256 * v.noteMaxVolume) // 64
|
||||
vol = (vol * v.perfSubVolume) // 64
|
||||
vol = (vol * v.trackMasterVolume) // 64
|
||||
v.audioVolume = s16(vol)
|
||||
end
|
||||
|
||||
-- fill the 0x280-byte voice buffer with repeats of the 4 << waveLength cycle at (src, off)
|
||||
local function fillCycles(dst: buffer, src: buffer, off: number, len: number)
|
||||
if off < 0 or off + len > buffer.len(src) then
|
||||
buffer.fill(dst, 0, 0, 0x281)
|
||||
return
|
||||
end
|
||||
buffer.copy(dst, 0, src, off, len)
|
||||
local filled = len
|
||||
while filled < 0x280 do
|
||||
local k = math.min(filled, 0x280 - filled)
|
||||
buffer.copy(dst, filled, dst, 0, k)
|
||||
filled += k
|
||||
end
|
||||
writei8(dst, 0x280, readi8(dst, 0))
|
||||
end
|
||||
|
||||
local function setAudio(st: State, v: Voice)
|
||||
v.voiceVolume = v.audioVolume % 256
|
||||
if v.plantPeriod then
|
||||
v.plantPeriod = false
|
||||
v.delta = deltaOf(v.audioPeriod, st.freq)
|
||||
end
|
||||
local src: buffer? = v.audioSrc or nil
|
||||
if v.newWaveform and src then
|
||||
fillCycles(v.voiceBuf, src, v.audioOff, if v.waveform == 3 then 0x280 else 4 * 2 ^ v.waveLength)
|
||||
end
|
||||
if v.ringPlantPeriod then
|
||||
v.ringPlantPeriod = false
|
||||
v.ringDelta = deltaOf(v.ringAudioPeriod, st.freq)
|
||||
end
|
||||
if v.ringNewWaveform and v.ringAudioOff >= 0 then
|
||||
fillCycles(v.ringBuf, st.waves, v.ringAudioOff, 4 * 2 ^ v.waveLength)
|
||||
v.ringMix = true
|
||||
end
|
||||
end
|
||||
|
||||
-- irq(st, audio): one player call (hvl_play_irq); audio = false skips the audio side (duration scans)
|
||||
function Player.irq(st: State, audio: boolean)
|
||||
local tune = st.tune
|
||||
local nch = st.channels
|
||||
local voices = st.voices
|
||||
if st.stepWaitFrames == 0 then
|
||||
if st.getNewPosition then
|
||||
local nextpos = if st.posNr + 1 == tune.positionNr then 0 else st.posNr + 1
|
||||
local P = tune.positions
|
||||
for i = 0, nch - 1 do
|
||||
local v = voices[i + 1]
|
||||
v.track = readu8(P, (st.posNr * 16 + i) * 2)
|
||||
v.transpose = readi8(P, (st.posNr * 16 + i) * 2 + 1)
|
||||
v.nextTrack = readu8(P, (nextpos * 16 + i) * 2)
|
||||
v.nextTranspose = readi8(P, (nextpos * 16 + i) * 2 + 1)
|
||||
end
|
||||
st.getNewPosition = false
|
||||
end
|
||||
for i = 1, nch do
|
||||
processStep(st, voices[i])
|
||||
end
|
||||
st.stepWaitFrames = st.tempo
|
||||
end
|
||||
for i = 1, nch do
|
||||
processFrame(st, voices[i])
|
||||
end
|
||||
st.playingTime += 1
|
||||
st.stepWaitFrames = s16(st.stepWaitFrames - 1)
|
||||
if st.stepWaitFrames == 0 then
|
||||
if not st.patternBreak then
|
||||
st.noteNr += 1
|
||||
if st.noteNr >= tune.trackLength then
|
||||
st.posJump = st.posNr + 1
|
||||
st.posJumpNote = 0
|
||||
st.patternBreak = true
|
||||
end
|
||||
end
|
||||
if st.patternBreak then
|
||||
st.patternBreak = false
|
||||
st.posNr = st.posJump
|
||||
st.noteNr = st.posJumpNote
|
||||
if st.posNr >= tune.positionNr then
|
||||
-- (past the end is bad data: the C code reads outside its position list)
|
||||
st.songEndReached = true
|
||||
st.posNr = tune.restart
|
||||
end
|
||||
st.posJumpNote = 0
|
||||
st.posJump = 0
|
||||
st.getNewPosition = true
|
||||
end
|
||||
end
|
||||
if audio then
|
||||
for i = 1, nch do
|
||||
setAudio(st, voices[i])
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- mix(st, out, at, n): n stereo frames of f32 into out at frame `at` (hvl_mixchunk: integer mixing, s16 clipping, / 32768)
|
||||
function Player.mix(st: State, out: buffer, at: number, n: number)
|
||||
local nch = st.channels
|
||||
local voices = st.voices
|
||||
local src, rsrc, delta, rdelta, vol, pos, rpos, panl, panr = {}, {}, {}, {}, {}, {}, {}, {}, {}
|
||||
for i = 1, nch do
|
||||
local v = voices[i]
|
||||
delta[i] = math.max(v.delta, 1)
|
||||
vol[i] = v.voiceVolume
|
||||
pos[i] = v.samplePos
|
||||
src[i] = v.voiceBuf
|
||||
panl[i] = v.panMultLeft
|
||||
panr[i] = v.panMultRight
|
||||
rdelta[i] = math.max(v.ringDelta, 1)
|
||||
rpos[i] = v.ringSamplePos
|
||||
rsrc[i] = if v.ringMix then v.ringBuf else false
|
||||
end
|
||||
local gain = st.mixgain
|
||||
local o = at * 8
|
||||
local samples = n
|
||||
while samples > 0 do
|
||||
local loops = samples
|
||||
for i = 1, nch do
|
||||
if pos[i] >= WRAP then
|
||||
pos[i] -= WRAP
|
||||
end
|
||||
local cnt = (WRAP - pos[i] - 1) // delta[i] + 1
|
||||
if cnt < loops then
|
||||
loops = cnt
|
||||
end
|
||||
if rsrc[i] then
|
||||
if rpos[i] >= WRAP then
|
||||
rpos[i] -= WRAP
|
||||
end
|
||||
cnt = (WRAP - rpos[i] - 1) // rdelta[i] + 1
|
||||
if cnt < loops then
|
||||
loops = cnt
|
||||
end
|
||||
end
|
||||
end
|
||||
samples -= loops
|
||||
for _ = 1, loops do
|
||||
local a, b = 0, 0
|
||||
for i = 1, nch do
|
||||
local j
|
||||
local r = rsrc[i]
|
||||
if r then
|
||||
j = ((readi8(src[i], pos[i] // 65536) * readi8(r, rpos[i] // 65536)) // 128) * vol[i]
|
||||
rpos[i] += rdelta[i]
|
||||
else
|
||||
j = readi8(src[i], pos[i] // 65536) * vol[i]
|
||||
end
|
||||
a += (j * panl[i]) // 128
|
||||
b += (j * panr[i]) // 128
|
||||
pos[i] += delta[i]
|
||||
end
|
||||
a = (a * gain) // 256
|
||||
b = (b * gain) // 256
|
||||
if a < -32768 then
|
||||
a = -32768
|
||||
elseif a > 32767 then
|
||||
a = 32767
|
||||
end
|
||||
if b < -32768 then
|
||||
b = -32768
|
||||
elseif b > 32767 then
|
||||
b = 32767
|
||||
end
|
||||
writef32(out, o, a / 32768)
|
||||
writef32(out, o + 4, b / 32768)
|
||||
o += 8
|
||||
end
|
||||
end
|
||||
for i = 1, nch do
|
||||
voices[i].samplePos = pos[i]
|
||||
voices[i].ringSamplePos = rpos[i]
|
||||
end
|
||||
end
|
||||
|
||||
return Player
|
||||
@@ -0,0 +1,221 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- codecs/audio/Hively/Tables: the AHX / HivelyTracker replayer's tables: the waveform block (triangle and sawtooth at
|
||||
-- six lengths, 32 square pulse widths, white noise, and the 31 low-pass and 31 high-pass filtered copies of all of
|
||||
-- them, generated as hvl_replay.c does), the sine panning tables, the vibrato sine and the Amiga period table. Ported
|
||||
-- from HivelyTracker's hvl2wav replay.c 1.9 (BSD-3-Clause, (c) 2006-2018 Pete Gordon; licenses/hivelytracker-LICENSE.txt)
|
||||
-- as hvl2wav builds on 64-bit Linux (`long` is 64-bit there: the noise generator's shifts do not wrap at 32 bits).
|
||||
local Tables = {}
|
||||
|
||||
local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift
|
||||
|
||||
-- the offsets inside `waves` (bytes)
|
||||
local FILTER_SET = 0xfc + 0xfc + 0x80 * 0x1f + 0x80 + 3 * 0x280 -- 6520: one filtered copy of every waveform
|
||||
local WHITENOISELEN = 0x280 * 3
|
||||
local WO_LOWPASSES = 0
|
||||
local WO_TRIANGLE_04 = WO_LOWPASSES + FILTER_SET * 31
|
||||
local WO_SAWTOOTH_04 = WO_TRIANGLE_04 + 0xfc
|
||||
local WO_SQUARES = WO_SAWTOOTH_04 + 0xfc
|
||||
local WO_WHITENOISE = WO_SQUARES + 0x80 * 0x20
|
||||
local WO_HIGHPASSES = WO_WHITENOISE + WHITENOISELEN
|
||||
local WAVES_SIZE = WO_HIGHPASSES + FILTER_SET * 31
|
||||
|
||||
Tables.FILTER_SET = FILTER_SET
|
||||
Tables.WO_TRIANGLE_04 = WO_TRIANGLE_04
|
||||
Tables.WO_SAWTOOTH_04 = WO_SAWTOOTH_04
|
||||
Tables.WO_SQUARES = WO_SQUARES
|
||||
Tables.WO_WHITENOISE = WO_WHITENOISE
|
||||
Tables.WAVES_SIZE = WAVES_SIZE
|
||||
-- offset of the waveform of length 4 << n inside the triangle / sawtooth runs
|
||||
Tables.OFFSETS = { [0] = 0x00, 0x04, 0x04 + 0x08, 0x04 + 0x08 + 0x10, 0x04 + 0x08 + 0x10 + 0x20, 0x04 + 0x08 + 0x10 + 0x20 + 0x40 }
|
||||
|
||||
Tables.VIB = {
|
||||
[0] = 0, 24, 49, 74, 97, 120, 141, 161, 180, 197, 212, 224, 235, 244, 250, 253, 255,
|
||||
253, 250, 244, 235, 224, 212, 197, 180, 161, 141, 120, 97, 74, 49, 24,
|
||||
0, -24, -49, -74, -97, -120, -141, -161, -180, -197, -212, -224, -235, -244, -250, -253, -255,
|
||||
-253, -250, -244, -235, -224, -212, -197, -180, -161, -141, -120, -97, -74, -49, -24,
|
||||
}
|
||||
|
||||
Tables.PERIOD = {
|
||||
[0] = 0x0000, 0x0D60, 0x0CA0, 0x0BE8, 0x0B40, 0x0A98, 0x0A00, 0x0970,
|
||||
0x08E8, 0x0868, 0x07F0, 0x0780, 0x0714, 0x06B0, 0x0650, 0x05F4,
|
||||
0x05A0, 0x054C, 0x0500, 0x04B8, 0x0474, 0x0434, 0x03F8, 0x03C0,
|
||||
0x038A, 0x0358, 0x0328, 0x02FA, 0x02D0, 0x02A6, 0x0280, 0x025C,
|
||||
0x023A, 0x021A, 0x01FC, 0x01E0, 0x01C5, 0x01AC, 0x0194, 0x017D,
|
||||
0x0168, 0x0153, 0x0140, 0x012E, 0x011D, 0x010D, 0x00FE, 0x00F0,
|
||||
0x00E2, 0x00D6, 0x00CA, 0x00BE, 0x00B4, 0x00AA, 0x00A0, 0x0097,
|
||||
0x008F, 0x0087, 0x007F, 0x0078, 0x0071,
|
||||
}
|
||||
|
||||
Tables.STEREO_LEFT = { [0] = 128, 96, 64, 32, 0 }
|
||||
Tables.STEREO_RIGHT = { [0] = 128, 160, 193, 225, 255 }
|
||||
|
||||
local function i8(v: number): number
|
||||
v = v % 256
|
||||
return if v >= 128 then v - 256 else v
|
||||
end
|
||||
|
||||
local function genSawtooth(w: buffer, at: number, len: number)
|
||||
local add = 256 // (len - 1)
|
||||
local val = -128
|
||||
for i = 0, len - 1 do
|
||||
buffer.writei8(w, at + i, i8(val))
|
||||
val += add
|
||||
end
|
||||
end
|
||||
|
||||
local function genTriangle(w: buffer, at: number, len: number)
|
||||
local d5 = len // 4
|
||||
local d1 = 128 // d5
|
||||
local d4 = -(len // 2)
|
||||
local p = at
|
||||
local val = 0
|
||||
for _ = 1, d5 do
|
||||
buffer.writei8(w, p, i8(val))
|
||||
p += 1
|
||||
val += d1
|
||||
end
|
||||
buffer.writei8(w, p, 0x7f)
|
||||
p += 1
|
||||
if d5 ~= 1 then
|
||||
val = 128
|
||||
for _ = 1, d5 - 1 do
|
||||
val -= d1
|
||||
buffer.writei8(w, p, i8(val))
|
||||
p += 1
|
||||
end
|
||||
end
|
||||
local q = p + d4
|
||||
for _ = 1, d5 * 2 do
|
||||
local c = buffer.readi8(w, q)
|
||||
q += 1
|
||||
buffer.writei8(w, p, if c == 0x7f then -128 else i8(-c))
|
||||
p += 1
|
||||
end
|
||||
end
|
||||
|
||||
local function genSquare(w: buffer, at: number)
|
||||
local p = at
|
||||
for i = 1, 0x20 do
|
||||
for _ = 1, (0x40 - i) * 2 do
|
||||
buffer.writei8(w, p, -128)
|
||||
p += 1
|
||||
end
|
||||
for _ = 1, i * 2 do
|
||||
buffer.writei8(w, p, 0x7f)
|
||||
p += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- hvl_GenWhiteNoise with `unsigned long` = 64 bits: (hi, lo) halves
|
||||
local function genWhiteNoise(w: buffer, at: number, len: number)
|
||||
local hi, lo = 0, 0x41595321
|
||||
for i = 0, len - 1 do
|
||||
local s = i8(band(lo, 0xff))
|
||||
if band(lo, 0x100) ~= 0 then
|
||||
s = 0x7f -- (int32)(ays & 0xffff) >= 0 always holds
|
||||
end
|
||||
buffer.writei8(w, at + i, s)
|
||||
-- ays = (ays >> 5) | (ays << 27)
|
||||
local nlo = bor(rshift(lo, 5), lshift(band(hi, 31), 27), lshift(lo, 27))
|
||||
-- (the high half is masked off next: ays & 0xffffff00 zero-extends)
|
||||
lo = bor(band(nlo, 0xffffff00), bxor(band(nlo, 0xff), 0x9a))
|
||||
local bx = band(lo, 0xffff)
|
||||
-- ays = (ays << 2) | (ays >> 30)
|
||||
lo = bor(lshift(lo, 2), rshift(lo, 30))
|
||||
local ax = band(lo, 0xffff)
|
||||
bx = band(bx + ax, 0xffff)
|
||||
ax = bxor(ax, bx)
|
||||
lo = bor(band(lo, 0xffff0000), ax)
|
||||
-- ays = (ays >> 3) | (ays << 29)
|
||||
hi = rshift(lo, 3)
|
||||
lo = bor(rshift(lo, 3), lshift(lo, 29))
|
||||
end
|
||||
end
|
||||
|
||||
local LENTAB = { 3, 7, 0xf, 0x1f, 0x3f, 0x7f, 3, 7, 0xf, 0x1f, 0x3f, 0x7f }
|
||||
for _ = 1, 32 do
|
||||
table.insert(LENTAB, 0x7f)
|
||||
end
|
||||
table.insert(LENTAB, 0x280 * 3 - 1)
|
||||
|
||||
local function clip(x: number): number
|
||||
if x > 127 then
|
||||
return 127
|
||||
elseif x < -128 then
|
||||
return -128
|
||||
end
|
||||
return x
|
||||
end
|
||||
|
||||
local function trunc8(x: number): number
|
||||
return if x >= 0 then math.floor(x) else -math.floor(-x)
|
||||
end
|
||||
|
||||
local function genFilterWaves(w: buffer)
|
||||
local low, high = WO_LOWPASSES, WO_HIGHPASSES
|
||||
local freq = 8
|
||||
for _ = 0, 30 do
|
||||
local a0 = WO_TRIANGLE_04
|
||||
local fre = freq * 1.25 / 100.0
|
||||
for wv = 1, 45 do
|
||||
local n = LENTAB[wv]
|
||||
local mid, lo = 0, 0
|
||||
for i = 0, n do
|
||||
local h = clip(buffer.readi8(w, a0 + i) - mid - lo)
|
||||
mid = clip(mid + h * fre)
|
||||
lo = clip(lo + mid * fre)
|
||||
end
|
||||
for i = 0, n do
|
||||
local h = clip(buffer.readi8(w, a0 + i) - mid - lo)
|
||||
mid = clip(mid + h * fre)
|
||||
lo = clip(lo + mid * fre)
|
||||
buffer.writei8(w, low, trunc8(lo))
|
||||
buffer.writei8(w, high, trunc8(h))
|
||||
low += 1
|
||||
high += 1
|
||||
end
|
||||
a0 += n + 1
|
||||
end
|
||||
freq += 3
|
||||
end
|
||||
end
|
||||
|
||||
local cache: { waves: buffer, panL: { number }, panR: { number } }? = nil
|
||||
|
||||
-- get() -> { waves (int8 buffer), panL, panR (0-based, 256 entries) }: built once, shared read only
|
||||
function Tables.get(): { waves: buffer, panL: { number }, panR: { number } }
|
||||
if cache then
|
||||
return cache
|
||||
end
|
||||
local w = buffer.create(WAVES_SIZE)
|
||||
local n = 4
|
||||
for k = 0, 5 do
|
||||
genSawtooth(w, WO_SAWTOOTH_04 + Tables.OFFSETS[k], n)
|
||||
genTriangle(w, WO_TRIANGLE_04 + Tables.OFFSETS[k], n)
|
||||
n *= 2
|
||||
end
|
||||
genSquare(w, WO_SQUARES)
|
||||
genWhiteNoise(w, WO_WHITENOISE, WHITENOISELEN)
|
||||
genFilterWaves(w)
|
||||
-- sine panning: the start angle is a float expression in the C source ((3.14159265f * 2.0f) / 4.0f)
|
||||
local f = buffer.create(4)
|
||||
buffer.writef32(f, 0, 3.14159265)
|
||||
local aa = buffer.readf32(f, 0) * 2 / 4
|
||||
local ab = 0.0
|
||||
local step = (3.14159265 * 2.0 / 4.0) / 256.0
|
||||
local pl: { number }, pr: { number } = {}, {}
|
||||
for i = 0, 255 do
|
||||
pl[i] = math.floor(math.sin(aa) * 255.0)
|
||||
pr[i] = math.floor(math.sin(ab) * 255.0)
|
||||
aa += step
|
||||
ab += step
|
||||
end
|
||||
pl[255] = 0
|
||||
pr[0] = 0
|
||||
cache = { waves = w, panL = pl, panR = pr }
|
||||
return cache :: any
|
||||
end
|
||||
|
||||
return Tables
|
||||
@@ -0,0 +1,209 @@
|
||||
--!strict
|
||||
-- codecs/audio/Hively: the AHX / HivelyTracker engine behind music/ahx and music/hvl: the loader for both file formats
|
||||
-- (Load), the replayer with its waveform generator (Tables: triangle / sawtooth / square / noise and the 31 + 31
|
||||
-- filtered copies) and integer mixer (Player), and the render glue to a Types.Decoder (stereo f32). A port of
|
||||
-- HivelyTracker's hvl2wav replay.c 1.9 (BSD-3-Clause, (c) 2006-2018 Pete Gordon; licenses/hivelytracker-LICENSE.txt):
|
||||
-- at hvl2wav's settings the output equals hvl2wav's 16-bit samples / 32768, sample for sample.
|
||||
--
|
||||
-- local Hively = require("@formats/codecs/audio/Hively")
|
||||
-- local tune, err = Hively.parse(buf, 0, buffer.len(buf)) -- the replayer's Tune
|
||||
-- local song = Hively.module(tune) -- a Types.Module-shaped value with render()
|
||||
-- local dec = Hively.decoder(tune, { sampleRate = 44100 }) -- a Types.Decoder
|
||||
--
|
||||
-- Not supported: hvl2wav's -a auto gain; a speed multiplier of 4 at 44.1 kHz renders 880 samples per 50 Hz frame
|
||||
-- (hvl2wav pads each frame to 882 with stale samples).
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Load = require("@formats/codecs/audio/Hively/Load")
|
||||
local Player = require("@formats/codecs/audio/Hively/Player")
|
||||
local Pcm = require("@formats/codecs/audio/Pcm")
|
||||
|
||||
local Hively = {}
|
||||
|
||||
export type Tune = Load.Tune
|
||||
export type RenderOptions = {
|
||||
sampleRate: number?, -- default 44100 (the replayer runs at any rate: 8000..192000)
|
||||
subsong: number?, -- 0 = the main song (default), 1..n the subsongs
|
||||
stereo: number?, -- AHX stereo separation 0..4 (0 mono, 4 = 100 % Amiga L R R L); default 0 as hvl2wav. HVL: the file's
|
||||
loop: boolean?, -- keep playing past the song end (frames / duration still give one pass)
|
||||
maxDuration: number?, -- seconds, default 600 (hvl2wav's 10 minute limit)
|
||||
}
|
||||
|
||||
-- parse(b, base?, limit?) -> Tune | nil, Err
|
||||
function Hively.parse(b: buffer, base: number?, limit: number?): (Tune?, Err.Err?)
|
||||
local tune, msg, kind = Load.parse(b, base or 0, limit or buffer.len(b))
|
||||
if not tune then
|
||||
return nil, Err.from(msg or "corrupt", nil, kind)
|
||||
end
|
||||
return tune, nil
|
||||
end
|
||||
|
||||
local function settings(tune: Tune, opts: RenderOptions?): (number?, number, number, Err.Err?)
|
||||
local o: RenderOptions = opts or {}
|
||||
local rate = o.sampleRate or 44100
|
||||
if type(rate) ~= "number" or rate < 8000 or rate > 192000 or rate % 1 ~= 0 then
|
||||
return nil, 0, 0, Err.new(Err.ARG, "render: sampleRate must be an integer 8000..192000")
|
||||
end
|
||||
local sub = o.subsong or 0
|
||||
if type(sub) ~= "number" or sub < 0 or sub > #tune.subsongs or sub % 1 ~= 0 then
|
||||
return nil, 0, 0, Err.new(Err.ARG, string.format("render: subsong must be 0..%d", #tune.subsongs))
|
||||
end
|
||||
return rate, sub, tonumber(o.stereo) or 0, nil
|
||||
end
|
||||
|
||||
-- frameCount(tune, opts?) -> 50 Hz frames until the song end (as hvl2wav stops), capped by maxDuration
|
||||
function Hively.frameCount(tune: Tune, opts: RenderOptions?): number
|
||||
local rate, sub, stereo = settings(tune, opts)
|
||||
local st = rate and Player.new(tune, rate :: number, stereo, sub)
|
||||
if not st then
|
||||
return 0
|
||||
end
|
||||
local maxFrames = math.floor(((opts and opts.maxDuration) or 600) * 50)
|
||||
local n = 0
|
||||
while n < maxFrames and not st.songEndReached do
|
||||
for _ = 1, tune.speedMultiplier do
|
||||
Player.irq(st, false)
|
||||
end
|
||||
n += 1
|
||||
end
|
||||
return n
|
||||
end
|
||||
|
||||
-- decoder(tune, opts?) -> Types.Decoder | nil, Err
|
||||
function Hively.decoder(tune: Tune, opts: RenderOptions?): (Types.Decoder?, Err.Err?)
|
||||
local rate, sub, stereo, err = settings(tune, opts)
|
||||
if not rate then
|
||||
return nil, err
|
||||
end
|
||||
local sr = rate :: number
|
||||
local mult = tune.speedMultiplier
|
||||
local perIrq = sr // 50 // mult
|
||||
local perFrame = perIrq * mult
|
||||
local nframes = Hively.frameCount(tune, opts)
|
||||
local frames = nframes * perFrame
|
||||
local loop = opts ~= nil and opts.loop == true
|
||||
local st = Player.new(tune, sr, stereo, sub) :: Player.State
|
||||
local fbuf = buffer.create(perFrame * 8)
|
||||
local fpos, ffill = 0, 0 -- read position / filled frames inside fbuf
|
||||
local pos = 0
|
||||
|
||||
local function nextFrame()
|
||||
for k = 0, mult - 1 do
|
||||
Player.irq(st, true)
|
||||
Player.mix(st, fbuf, k * perIrq, perIrq)
|
||||
end
|
||||
fpos, ffill = 0, perFrame
|
||||
end
|
||||
|
||||
local dec = {
|
||||
sampleRate = sr,
|
||||
channels = 2,
|
||||
frames = frames,
|
||||
duration = frames / sr,
|
||||
bitrate = 0,
|
||||
tags = { title = if tune.title ~= "" then tune.title else nil } :: Types.Tags,
|
||||
}
|
||||
local function read(_self: any, n: number, out: buffer?): (buffer, number)
|
||||
n = math.max(0, math.floor(n))
|
||||
if not loop then
|
||||
n = math.min(n, frames - pos)
|
||||
end
|
||||
local b = out
|
||||
if not b or buffer.len(b) < n * 8 then
|
||||
b = buffer.create(math.max(n, 1) * 8)
|
||||
end
|
||||
local ob = b :: buffer
|
||||
local done = 0
|
||||
while done < n do
|
||||
if fpos >= ffill then
|
||||
nextFrame()
|
||||
end
|
||||
local k = math.min(n - done, ffill - fpos)
|
||||
buffer.copy(ob, done * 8, fbuf, fpos * 8, k * 8)
|
||||
fpos += k
|
||||
done += k
|
||||
end
|
||||
pos += n
|
||||
return ob, n
|
||||
end
|
||||
dec.read = read :: any
|
||||
local scratch = buffer.create(4096 * 8)
|
||||
dec.seek = function(_self: any, seconds: number)
|
||||
local target = math.max(0, math.floor((tonumber(seconds) or 0) * sr))
|
||||
if not loop then
|
||||
target = math.min(target, frames)
|
||||
end
|
||||
if target < pos then
|
||||
st = Player.new(tune, sr, stereo, sub) :: Player.State
|
||||
pos, fpos, ffill = 0, 0, 0
|
||||
end
|
||||
while pos < target do
|
||||
read(nil, math.min(4096, target - pos), scratch)
|
||||
end
|
||||
end :: any
|
||||
dec.position = function(_self: any): number
|
||||
return pos / sr
|
||||
end :: any
|
||||
return (dec :: any) :: Types.Decoder, nil
|
||||
end
|
||||
|
||||
-- module(tune) -> a Types.Module-shaped value (kind "music"): tracks as patterns (rows * 6 bytes: note, instrument,
|
||||
-- fx, param, fxb, paramb), positions, instruments with their play lists, and render(opts) -> Decoder
|
||||
function Hively.module(tune: Tune): Types.Module
|
||||
local patterns = {}
|
||||
for t = 0, tune.trackNr do
|
||||
local data = buffer.create(tune.trackLength * 6)
|
||||
buffer.copy(data, 0, tune.tracks, t * 64 * 6, tune.trackLength * 6)
|
||||
patterns[t + 1] = { rows = tune.trackLength, data = data }
|
||||
end
|
||||
local order, positions = {}, {}
|
||||
for i = 0, tune.positionNr - 1 do
|
||||
order[i + 1] = i
|
||||
local tr, tp = {}, {}
|
||||
for c = 0, tune.channels - 1 do
|
||||
tr[c + 1] = buffer.readu8(tune.positions, (i * 16 + c) * 2)
|
||||
tp[c + 1] = buffer.readi8(tune.positions, (i * 16 + c) * 2 + 1)
|
||||
end
|
||||
positions[i + 1] = { tracks = tr, transpose = tp }
|
||||
end
|
||||
local m: any = {
|
||||
kind = "music",
|
||||
format = tune.format,
|
||||
title = tune.title,
|
||||
channels = tune.channels,
|
||||
speed = 6,
|
||||
tempo = 125 * tune.speedMultiplier, -- 50 Hz player calls per speed multiplier (a tick lasts 2.5 / tempo s)
|
||||
patterns = patterns,
|
||||
order = order,
|
||||
positions = positions,
|
||||
restart = tune.restart,
|
||||
subsongs = table.clone(tune.subsongs),
|
||||
instruments = tune.instruments,
|
||||
samples = {},
|
||||
meta = {
|
||||
source = {
|
||||
format = tune.format,
|
||||
version = tune.version,
|
||||
speedMultiplier = tune.speedMultiplier,
|
||||
trackLength = tune.trackLength,
|
||||
tracks = tune.trackNr + 1,
|
||||
mixgain = if tune.format == "hvl" then tune.mixgain else nil,
|
||||
stereo = if tune.format == "hvl" then tune.stereo else nil,
|
||||
},
|
||||
},
|
||||
tune = tune,
|
||||
}
|
||||
m.render = function(self: any, opts: RenderOptions?): Types.Decoder
|
||||
local dec, derr = Hively.decoder(self.tune, opts)
|
||||
if dec then
|
||||
return dec
|
||||
end
|
||||
-- the Types contract returns a Decoder: a failed render is an empty one carrying the Err
|
||||
local empty: any = Pcm.audioDecoder(Types.Audio.new(44100, 2, 0))
|
||||
empty.err = derr
|
||||
return empty
|
||||
end
|
||||
return m :: Types.Module
|
||||
end
|
||||
|
||||
return Hively
|
||||
@@ -1,8 +1,9 @@
|
||||
--!strict
|
||||
-- music/midi/Render: the tempo map (ticks -> seconds, as python mido computes lengths), the time-ordered event list,
|
||||
-- codecs/audio/MidiRender: the tempo map (ticks -> seconds, as python mido computes lengths), the time-ordered event list,
|
||||
-- and the audio Decoder that plays a Midi through codecs/audio/SoundFont's synth (a SoundFont bank, or the built-in
|
||||
-- waveform set). Format 0 / 1: one tempo map from every track's tempo events, tracks merged (ties keep track order).
|
||||
-- Format 2: each track is its own song with its own tempo map, played one after another.
|
||||
-- Format 2: each track is its own song with its own tempo map, played one after another. Shared by every format that
|
||||
-- decodes to a Types.Midi (music/midi, mus, xmi, hmp): attach() adds the meta summary and the render method.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local SoundFont = require("@formats/codecs/audio/SoundFont")
|
||||
@@ -208,6 +209,14 @@ function Render.decoder(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder?
|
||||
bitrate = 0,
|
||||
tags = {} :: Types.Tags,
|
||||
}
|
||||
local mtags = type(midi.meta) == "table" and midi.meta.tags
|
||||
if type(mtags) == "table" then
|
||||
for k, v in mtags do
|
||||
if type(k) == "string" and type(v) == "string" then
|
||||
dec.tags[k] = v
|
||||
end
|
||||
end
|
||||
end
|
||||
for _, t in midi.tracks do
|
||||
if t.name and not dec.tags.title then
|
||||
dec.tags.title = t.name
|
||||
@@ -258,4 +267,93 @@ function Render.decoder(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder?
|
||||
return (dec :: any) :: Types.Decoder, nil
|
||||
end
|
||||
|
||||
-- tempoBytes(division, ticksPerSecond) -> the 3 data bytes of a tempo meta event making each tick last
|
||||
-- 1 / ticksPerSecond seconds at that division (for formats with a fixed tick rate: MUS, XMIDI, HMP / HMI)
|
||||
function Render.tempoBytes(division: number, ticksPerSecond: number): { number }
|
||||
local us = math.clamp(math.floor(division * 1e6 / ticksPerSecond + 0.5), 1, 0xFFFFFF)
|
||||
return { us // 65536, (us // 256) % 256, us % 256 }
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ durations
|
||||
export type PendingOff = { tick: number, onTick: number, ev: Types.MidiEvent }
|
||||
|
||||
-- merge(events, offs) -> one tick-ordered event list: for formats that store a duration with each note (XMIDI, HMI).
|
||||
-- events are in file order (ticks never decrease); offs are the generated note-offs. At equal ticks an off whose note
|
||||
-- started earlier goes before the file's events, an off of a zero-length note after them.
|
||||
function Render.merge(events: { Types.MidiEvent }, offs: { PendingOff }): { Types.MidiEvent }
|
||||
for i, o in offs do
|
||||
(o :: any).seq = i
|
||||
end
|
||||
table.sort(offs, function(a: any, b: any): boolean
|
||||
if a.tick ~= b.tick then
|
||||
return a.tick < b.tick
|
||||
end
|
||||
return a.seq < b.seq
|
||||
end)
|
||||
local out: { Types.MidiEvent } = table.create(#events + #offs) :: { Types.MidiEvent }
|
||||
local k = 1
|
||||
for _, ev in events do
|
||||
while k <= #offs and (offs[k].tick < ev.tick or (offs[k].tick == ev.tick and offs[k].onTick < ev.tick)) do
|
||||
table.insert(out, offs[k].ev)
|
||||
k += 1
|
||||
end
|
||||
table.insert(out, ev)
|
||||
end
|
||||
for j = k, #offs do
|
||||
table.insert(out, offs[j].ev)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ attach
|
||||
local function render(self: Types.Midi, opts: RenderOptions?): Types.Decoder
|
||||
local dec, err = Render.decoder(self, opts)
|
||||
if not dec then
|
||||
-- the Types contract returns a Decoder; a failed render is an empty one (Midi.render returns the Err)
|
||||
local empty: any = {
|
||||
sampleRate = 44100, channels = 2, frames = 0, duration = 0, bitrate = 0, tags = {}, err = err,
|
||||
read = function(_self: any, _n: number, out: buffer?): (buffer, number)
|
||||
return out or buffer.create(0), 0
|
||||
end,
|
||||
seek = function() end,
|
||||
position = function(): number
|
||||
return 0
|
||||
end,
|
||||
}
|
||||
return empty
|
||||
end
|
||||
return dec
|
||||
end
|
||||
|
||||
-- summarize(midi): meta.tempos / timeSignatures / keySignatures / length from the events
|
||||
function Render.summarize(midi: Types.Midi)
|
||||
local tempos, sigs, keys = {}, {}, {}
|
||||
local map = Render.tempoMap(midi)
|
||||
for ti, t in midi.tracks do
|
||||
for _, ev in t.events do
|
||||
if ev.type == "meta" then
|
||||
local d = ev.data :: { number }
|
||||
if ev.meta == 0x51 and #d >= 3 then
|
||||
table.insert(tempos, { tick = ev.tick, track = ti, usPerQuarter = d[1] * 65536 + d[2] * 256 + d[3], bpm = 60000000 / math.max(1, d[1] * 65536 + d[2] * 256 + d[3]), seconds = Render.seconds(map, ev.tick) })
|
||||
elseif ev.meta == 0x58 and #d >= 4 then
|
||||
table.insert(sigs, { tick = ev.tick, track = ti, numerator = d[1], denominator = 2 ^ math.min(d[2], 31), clocksPerClick = d[3], notated32ndsPerBeat = d[4] })
|
||||
elseif ev.meta == 0x59 and #d >= 2 then
|
||||
table.insert(keys, { tick = ev.tick, track = ti, sharps = if d[1] >= 128 then d[1] - 256 else d[1], minor = d[2] == 1 })
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
midi.meta.tempos = tempos
|
||||
midi.meta.timeSignatures = sigs
|
||||
midi.meta.keySignatures = keys
|
||||
midi.meta.length = Render.length(midi)
|
||||
end
|
||||
|
||||
-- attach(midi, source): what every MIDI-like decoder does last: the meta summary, meta.source and the render method
|
||||
function Render.attach(midi: Types.Midi, source: { [string]: any })
|
||||
Render.summarize(midi)
|
||||
midi.meta.source = source
|
||||
midi.render = render
|
||||
end
|
||||
|
||||
return Render
|
||||
@@ -0,0 +1,899 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/audio/Musepack/Decode: one Musepack SV7 / SV8 frame (1152 samples per channel): the bitstream (band
|
||||
-- resolutions, scalefactor indices, quantised subband samples, with SV8's canonical Huffman / enumerative codes),
|
||||
-- requantisation (M/S or L/R) and the 32-band polyphase synthesis. A line-by-line port of libmpcdec's mpc_decoder.c,
|
||||
-- requant.c and synth_filter.c (musepack_src_r475, BSD-3-Clause, (c) The Musepack Development Team,
|
||||
-- licenses/libmpcdec-BSD.txt) in double precision float. The bit reader is module state (decoding is synchronous) over
|
||||
-- a buffer the caller pads by at least PAD bytes past `limit`: the band loops stop as soon as the position passes the
|
||||
-- limit, so every read stays inside the buffer. No error / assert: failures return nil, "message".
|
||||
local T = require("@formats/codecs/audio/Musepack/Tables")
|
||||
|
||||
local readu32, bswap, extract, band, bor, rshift, lshift, bnot, bxor =
|
||||
buffer.readu32, bit32.byteswap, bit32.extract, bit32.band, bit32.bor, bit32.rshift, bit32.lshift, bit32.bnot, bit32.bxor
|
||||
local abs = math.abs
|
||||
|
||||
local Decode = {}
|
||||
Decode.PAD = 8192
|
||||
Decode.DELAY = 481 -- MPC_DECODER_SYNTH_DELAY
|
||||
Decode.FRAME = 1152
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ tables
|
||||
local L = T.lut
|
||||
local HDR, SCFI7, DSCF7 = L(T.HuffHdr), L(T.HuffSCFI), L(T.HuffDSCF)
|
||||
local Q7: { { T.Lut } } = {
|
||||
{ L(T.HuffQ1_0), L(T.HuffQ1_1) },
|
||||
{ L(T.HuffQ2_0), L(T.HuffQ2_1) },
|
||||
{ L(T.HuffQ3_0), L(T.HuffQ3_1) },
|
||||
{ L(T.HuffQ4_0), L(T.HuffQ4_1) },
|
||||
{ L(T.HuffQ5_0), L(T.HuffQ5_1) },
|
||||
{ L(T.HuffQ6_0), L(T.HuffQ6_1) },
|
||||
{ L(T.HuffQ7_0), L(T.HuffQ7_1) },
|
||||
}
|
||||
local BANDS8 = L(T.H_Bands, T.S_Bands)
|
||||
local SCFI8 = { L(T.H_SCFI_1, T.S_SCFI_1), L(T.H_SCFI_2, T.S_SCFI_2) }
|
||||
local DSCF8 = { L(T.H_DSCF_1, T.S_DSCF_1), L(T.H_DSCF_2, T.S_DSCF_2) }
|
||||
local RES8 = { L(T.H_Res_1, T.S_Res_1), L(T.H_Res_2, T.S_Res_2) }
|
||||
local Q1_8 = L(T.H_Q1, T.S_Q1)
|
||||
local Q9UP = L(T.H_Q9up, T.S_Q9up)
|
||||
-- mpc_can_Q[res - 2][0 / 1] for res 2 and 5 .. 8; res 3 / 4 use Q34[res - 2]
|
||||
local Q8: { [number]: { T.Lut } } = {
|
||||
[2] = { L(T.H_Q2_1, T.S_Q2_1), L(T.H_Q2_2, T.S_Q2_2) },
|
||||
[5] = { L(T.H_Q5_1, T.S_Q5_1), L(T.H_Q5_2, T.S_Q5_2) },
|
||||
[6] = { L(T.H_Q6_1, T.S_Q6_1), L(T.H_Q6_2, T.S_Q6_2) },
|
||||
[7] = { L(T.H_Q7_1, T.S_Q7_1), L(T.H_Q7_2, T.S_Q7_2) },
|
||||
[8] = { L(T.H_Q8_1, T.S_Q8_1), L(T.H_Q8_2, T.S_Q8_2) },
|
||||
}
|
||||
local Q34 = { L(T.H_Q3, T.S_Q3), L(T.H_Q4, T.S_Q4) }
|
||||
local THRES = { [2] = 3, [5] = 1, [6] = 3, [7] = 4, [8] = 8 }
|
||||
local CC, DC, RES_BIT = T.CC, T.DC, T.RES_BIT
|
||||
local CNK, CNK_LEN, CNK_LOST, LOG2, LOG2_LOST = T.CNK, T.CNK_LEN, T.CNK_LOST, T.LOG2, T.LOG2_LOST
|
||||
|
||||
-- the f32 rounding of the C tables (libmpcdec decodes in single precision)
|
||||
local F32 = buffer.create(4)
|
||||
local function f32(x: number): number
|
||||
buffer.writef32(F32, 0, x)
|
||||
return buffer.readf32(F32, 0)
|
||||
end
|
||||
for i, v in CC do
|
||||
CC[i] = f32(v)
|
||||
end
|
||||
|
||||
-- SCF[i]: the scalefactor of index i (0 .. 255, the index's low byte): 2^-15 * 0.83298...^(s - 1), s = i as int8
|
||||
-- (libmpcdec's mpc_decoder_scale_output in float mode: 1 dB steps, the table filled outwards from index 1)
|
||||
local SCF = table.create(256, 0)
|
||||
do
|
||||
local f1 = 1 / 32768
|
||||
local f2 = f1
|
||||
SCF[2] = f32(f1)
|
||||
f1 *= 0.83298066476582673961
|
||||
f2 *= 1 / 0.83298066476582673961
|
||||
for n = 1, 128 do
|
||||
SCF[band(1 + n, 255) + 1] = f32(f1)
|
||||
SCF[band(1 - n, 255) + 1] = f32(f2)
|
||||
f1 *= 0.83298066476582673961
|
||||
f2 *= 1 / 0.83298066476582673961
|
||||
end
|
||||
end
|
||||
|
||||
-- the synthesis window D (Di_opt / 65536), 32 x 16, row-major
|
||||
local DW = table.create(512, 0)
|
||||
for i, v in T.DI do
|
||||
DW[i] = f32(v / 65536)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ bit reader
|
||||
local B: buffer = buffer.create(0)
|
||||
local P = 0 -- bit position
|
||||
|
||||
local function bits(n: number): number
|
||||
if n <= 0 then
|
||||
return 0
|
||||
end
|
||||
if n > 24 then
|
||||
local hi = bits(n - 16)
|
||||
return hi * 65536 + bits(16)
|
||||
end
|
||||
local w = bswap(readu32(B, rshift(P, 3)))
|
||||
local v = extract(w, 32 - band(P, 7) - n, n)
|
||||
P += n
|
||||
return v
|
||||
end
|
||||
|
||||
local function peek16(): number
|
||||
local w = bswap(readu32(B, rshift(P, 3)))
|
||||
return extract(w, 16 - band(P, 7), 16)
|
||||
end
|
||||
|
||||
-- a table-driven Huffman symbol (plain or canonical)
|
||||
local function huff(t: T.Lut): number
|
||||
local code = peek16()
|
||||
local k = rshift(code, 8) + 1
|
||||
local n = t.len[k]
|
||||
if n > 0 then
|
||||
P += n
|
||||
return t.val[k]
|
||||
end
|
||||
local j = t.val[k]
|
||||
local codes = t.codes
|
||||
while code < codes[j] do
|
||||
j += 1
|
||||
end
|
||||
n = t.lens[j]
|
||||
P += n
|
||||
local sym = t.sym
|
||||
if sym then
|
||||
return sym[band(t.vals[j] - rshift(code, 16 - n), 255) + 1] or 0
|
||||
end
|
||||
return t.vals[j]
|
||||
end
|
||||
|
||||
-- mpc_bits_log_dec: 0 .. max
|
||||
local function logDec(max: number): number
|
||||
if max <= 0 then
|
||||
return 0
|
||||
end
|
||||
local v = 0
|
||||
local len, lost = LOG2[max], LOG2_LOST[max]
|
||||
if len > 1 then
|
||||
v = bits(len - 1)
|
||||
end
|
||||
if v >= lost then
|
||||
v = v * 2 + bits(1) - lost
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
-- mpc_bits_enum_dec: an n-bit word with k bits set
|
||||
local function enumDec(k: number, n: number): number
|
||||
local out = 0
|
||||
local code = bits(CNK_LEN[k][n] - 1)
|
||||
local lost = CNK_LOST[k][n]
|
||||
if code >= lost then
|
||||
code = code * 2 + bits(1) - lost
|
||||
end
|
||||
repeat
|
||||
n -= 1
|
||||
local c = CNK[k][n + 1]
|
||||
if code >= c then
|
||||
out = bor(out, lshift(1, n))
|
||||
code -= c
|
||||
k -= 1
|
||||
end
|
||||
until k <= 0 or n <= 0
|
||||
return out
|
||||
end
|
||||
|
||||
-- mpc_random_int: two polynomial counters, XORed
|
||||
local PARITY = table.create(256, 0)
|
||||
for i = 0, 255 do
|
||||
local p, v = 0, i
|
||||
while v > 0 do
|
||||
p = bxor(p, band(v, 1))
|
||||
v = rshift(v, 1)
|
||||
end
|
||||
PARITY[i + 1] = p
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ synthesis
|
||||
-- mpc_compute_new_V: 32 subband samples Y[y .. y + 31] -> 64 V values at V[o .. o + 63] (the ISO 11172-3 matrixing
|
||||
-- through Byeong Gi Lee's fast DCT)
|
||||
local function newV(Y: { number }, y: number, V: { number }, o: number)
|
||||
local A00 = Y[y] + Y[y + 31]
|
||||
local A01 = Y[y + 1] + Y[y + 30]
|
||||
local A02 = Y[y + 2] + Y[y + 29]
|
||||
local A03 = Y[y + 3] + Y[y + 28]
|
||||
local A04 = Y[y + 4] + Y[y + 27]
|
||||
local A05 = Y[y + 5] + Y[y + 26]
|
||||
local A06 = Y[y + 6] + Y[y + 25]
|
||||
local A07 = Y[y + 7] + Y[y + 24]
|
||||
local A08 = Y[y + 8] + Y[y + 23]
|
||||
local A09 = Y[y + 9] + Y[y + 22]
|
||||
local A10 = Y[y + 10] + Y[y + 21]
|
||||
local A11 = Y[y + 11] + Y[y + 20]
|
||||
local A12 = Y[y + 12] + Y[y + 19]
|
||||
local A13 = Y[y + 13] + Y[y + 18]
|
||||
local A14 = Y[y + 14] + Y[y + 17]
|
||||
local A15 = Y[y + 15] + Y[y + 16]
|
||||
local B00 = A00 + A15
|
||||
local B01 = A01 + A14
|
||||
local B02 = A02 + A13
|
||||
local B03 = A03 + A12
|
||||
local B04 = A04 + A11
|
||||
local B05 = A05 + A10
|
||||
local B06 = A06 + A09
|
||||
local B07 = A07 + A08
|
||||
local B08 = (A00 - A15) * 0.5024192929
|
||||
local B09 = (A01 - A14) * 0.5224986076
|
||||
local B10 = (A02 - A13) * 0.5669440627
|
||||
local B11 = (A03 - A12) * 0.6468217969
|
||||
local B12 = (A04 - A11) * 0.7881546021
|
||||
local B13 = (A05 - A10) * 1.0606776476
|
||||
local B14 = (A06 - A09) * 1.7224471569
|
||||
local B15 = (A07 - A08) * 5.1011486053
|
||||
A00 = B00 + B07
|
||||
A01 = B01 + B06
|
||||
A02 = B02 + B05
|
||||
A03 = B03 + B04
|
||||
A04 = (B00 - B07) * 0.5097956061
|
||||
A05 = (B01 - B06) * 0.6013448834
|
||||
A06 = (B02 - B05) * 0.8999761939
|
||||
A07 = (B03 - B04) * 2.5629155636
|
||||
A08 = B08 + B15
|
||||
A09 = B09 + B14
|
||||
A10 = B10 + B13
|
||||
A11 = B11 + B12
|
||||
A12 = (B08 - B15) * 0.5097956061
|
||||
A13 = (B09 - B14) * 0.6013448834
|
||||
A14 = (B10 - B13) * 0.8999761939
|
||||
A15 = (B11 - B12) * 2.5629155636
|
||||
B00 = A00 + A03
|
||||
B01 = A01 + A02
|
||||
B02 = (A00 - A03) * 0.5411961079
|
||||
B03 = (A01 - A02) * 1.3065630198
|
||||
B04 = A04 + A07
|
||||
B05 = A05 + A06
|
||||
B06 = (A04 - A07) * 0.5411961079
|
||||
B07 = (A05 - A06) * 1.3065630198
|
||||
B08 = A08 + A11
|
||||
B09 = A09 + A10
|
||||
B10 = (A08 - A11) * 0.5411961079
|
||||
B11 = (A09 - A10) * 1.3065630198
|
||||
B12 = A12 + A15
|
||||
B13 = A13 + A14
|
||||
B14 = (A12 - A15) * 0.5411961079
|
||||
B15 = (A13 - A14) * 1.3065630198
|
||||
A00 = B00 + B01
|
||||
A01 = (B00 - B01) * 0.7071067691
|
||||
A02 = B02 + B03
|
||||
A03 = (B02 - B03) * 0.7071067691
|
||||
A04 = B04 + B05
|
||||
A05 = (B04 - B05) * 0.7071067691
|
||||
A06 = B06 + B07
|
||||
A07 = (B06 - B07) * 0.7071067691
|
||||
A08 = B08 + B09
|
||||
A09 = (B08 - B09) * 0.7071067691
|
||||
A10 = B10 + B11
|
||||
A11 = (B10 - B11) * 0.7071067691
|
||||
A12 = B12 + B13
|
||||
A13 = (B12 - B13) * 0.7071067691
|
||||
A14 = B14 + B15
|
||||
A15 = (B14 - B15) * 0.7071067691
|
||||
V[o + 48] = -A00
|
||||
V[o] = A01
|
||||
V[o + 8] = A03
|
||||
V[o + 40] = -A02 - A03
|
||||
V[o + 12] = A07
|
||||
local t = A05 + A07
|
||||
V[o + 4] = t
|
||||
V[o + 36] = -(t + A06)
|
||||
V[o + 44] = -A04 - A06 - A07
|
||||
V[o + 14] = A15
|
||||
t = A11 + A15
|
||||
V[o + 10] = t
|
||||
V[o + 6] = t + A13
|
||||
t = A09 + A13 + A15
|
||||
V[o + 2] = t
|
||||
t = -t - A14
|
||||
V[o + 34] = t
|
||||
V[o + 38] = t + A09 - A10 - A11
|
||||
t = -(A12 + A14 + A15)
|
||||
V[o + 46] = t - A08
|
||||
V[o + 42] = t - A10 - A11
|
||||
A00 = (Y[y] - Y[y + 31]) * 0.5006030202
|
||||
A01 = (Y[y + 1] - Y[y + 30]) * 0.5054709315
|
||||
A02 = (Y[y + 2] - Y[y + 29]) * 0.5154473186
|
||||
A03 = (Y[y + 3] - Y[y + 28]) * 0.5310425758
|
||||
A04 = (Y[y + 4] - Y[y + 27]) * 0.5531039238
|
||||
A05 = (Y[y + 5] - Y[y + 26]) * 0.5829349756
|
||||
A06 = (Y[y + 6] - Y[y + 25]) * 0.6225041151
|
||||
A07 = (Y[y + 7] - Y[y + 24]) * 0.6748083234
|
||||
A08 = (Y[y + 8] - Y[y + 23]) * 0.7445362806
|
||||
A09 = (Y[y + 9] - Y[y + 22]) * 0.8393496275
|
||||
A10 = (Y[y + 10] - Y[y + 21]) * 0.9725682139
|
||||
A11 = (Y[y + 11] - Y[y + 20]) * 1.1694399118
|
||||
A12 = (Y[y + 12] - Y[y + 19]) * 1.4841645956
|
||||
A13 = (Y[y + 13] - Y[y + 18]) * 2.0577809811
|
||||
A14 = (Y[y + 14] - Y[y + 17]) * 3.4076085091
|
||||
A15 = (Y[y + 15] - Y[y + 16]) * 10.1900081635
|
||||
B00 = A00 + A15
|
||||
B01 = A01 + A14
|
||||
B02 = A02 + A13
|
||||
B03 = A03 + A12
|
||||
B04 = A04 + A11
|
||||
B05 = A05 + A10
|
||||
B06 = A06 + A09
|
||||
B07 = A07 + A08
|
||||
B08 = (A00 - A15) * 0.5024192929
|
||||
B09 = (A01 - A14) * 0.5224986076
|
||||
B10 = (A02 - A13) * 0.5669440627
|
||||
B11 = (A03 - A12) * 0.6468217969
|
||||
B12 = (A04 - A11) * 0.7881546021
|
||||
B13 = (A05 - A10) * 1.0606776476
|
||||
B14 = (A06 - A09) * 1.7224471569
|
||||
B15 = (A07 - A08) * 5.1011486053
|
||||
A00 = B00 + B07
|
||||
A01 = B01 + B06
|
||||
A02 = B02 + B05
|
||||
A03 = B03 + B04
|
||||
A04 = (B00 - B07) * 0.5097956061
|
||||
A05 = (B01 - B06) * 0.6013448834
|
||||
A06 = (B02 - B05) * 0.8999761939
|
||||
A07 = (B03 - B04) * 2.5629155636
|
||||
A08 = B08 + B15
|
||||
A09 = B09 + B14
|
||||
A10 = B10 + B13
|
||||
A11 = B11 + B12
|
||||
A12 = (B08 - B15) * 0.5097956061
|
||||
A13 = (B09 - B14) * 0.6013448834
|
||||
A14 = (B10 - B13) * 0.8999761939
|
||||
A15 = (B11 - B12) * 2.5629155636
|
||||
B00 = A00 + A03
|
||||
B01 = A01 + A02
|
||||
B02 = (A00 - A03) * 0.5411961079
|
||||
B03 = (A01 - A02) * 1.3065630198
|
||||
B04 = A04 + A07
|
||||
B05 = A05 + A06
|
||||
B06 = (A04 - A07) * 0.5411961079
|
||||
B07 = (A05 - A06) * 1.3065630198
|
||||
B08 = A08 + A11
|
||||
B09 = A09 + A10
|
||||
B10 = (A08 - A11) * 0.5411961079
|
||||
B11 = (A09 - A10) * 1.3065630198
|
||||
B12 = A12 + A15
|
||||
B13 = A13 + A14
|
||||
B14 = (A12 - A15) * 0.5411961079
|
||||
B15 = (A13 - A14) * 1.3065630198
|
||||
A00 = (B00 + B01)
|
||||
A01 = (B00 - B01) * 0.7071067691
|
||||
A02 = (B02 + B03)
|
||||
A03 = (B02 - B03) * 0.7071067691
|
||||
A04 = (B04 + B05)
|
||||
A05 = (B04 - B05) * 0.7071067691
|
||||
A06 = (B06 + B07)
|
||||
A07 = (B06 - B07) * 0.7071067691
|
||||
A08 = (B08 + B09)
|
||||
A09 = (B08 - B09) * 0.7071067691
|
||||
A10 = (B10 + B11)
|
||||
A11 = (B10 - B11) * 0.7071067691
|
||||
A12 = (B12 + B13)
|
||||
A13 = (B12 - B13) * 0.7071067691
|
||||
A14 = (B14 + B15)
|
||||
A15 = (B14 - B15) * 0.7071067691
|
||||
V[o + 15] = A15
|
||||
t = A07 + A15
|
||||
V[o + 13] = t
|
||||
t += A11
|
||||
V[o + 11] = t
|
||||
V[o + 5] = t + A05 + A13
|
||||
t = A03 + A11 + A15
|
||||
V[o + 9] = t
|
||||
V[o + 7] = t + A13
|
||||
t = A01 + A09 + A13 + A15
|
||||
V[o + 1] = t
|
||||
V[o + 33] = -t - A14
|
||||
t = A05 + A07 + A09 + A13 + A15
|
||||
V[o + 3] = t
|
||||
V[o + 35] = -t - A06 - A14
|
||||
t = -(A10 + A11 + A13 + A14 + A15)
|
||||
V[o + 37] = t - A05 - A06 - A07
|
||||
V[o + 39] = t - A02 - A03
|
||||
t += A13 - A12
|
||||
V[o + 41] = t - A02 - A03
|
||||
V[o + 43] = t - A04 - A06 - A07
|
||||
t = -(A08 + A12 + A14 + A15)
|
||||
V[o + 47] = t - A00
|
||||
V[o + 45] = t - A04 - A06 - A07
|
||||
for i = 0, 15 do
|
||||
V[o + 32 - i] = -V[o + i]
|
||||
end
|
||||
for i = 33, 47 do
|
||||
V[o + 96 - i] = V[o + i]
|
||||
end
|
||||
end
|
||||
-- ------------------------------------------------------------------------------------------------ state
|
||||
export type State = {
|
||||
version: number, -- 7 | 8
|
||||
maxBand: number, -- the highest band index (0 .. 31)
|
||||
ms: boolean,
|
||||
channels: number,
|
||||
resL: { number }, -- [band + 1]
|
||||
resR: { number },
|
||||
scfL: { number }, -- [band * 3 + m + 1]
|
||||
scfR: { number },
|
||||
scfiL: { number },
|
||||
scfiR: { number },
|
||||
dscfL: { boolean },
|
||||
dscfR: { boolean },
|
||||
msf: { boolean },
|
||||
qL: { number }, -- [band * 36 + k + 1]
|
||||
qR: { number },
|
||||
yL: { number }, -- [n * 32 + band + 1], n = 0 .. 35
|
||||
yR: { number },
|
||||
vL: { number }, -- synthesis history, 2304 + 960
|
||||
vR: { number },
|
||||
r1: number,
|
||||
r2: number,
|
||||
lastMaxBand: number,
|
||||
}
|
||||
|
||||
function Decode.state(version: number, maxBand: number, ms: boolean, channels: number): State
|
||||
local st: State = {
|
||||
version = version,
|
||||
maxBand = maxBand,
|
||||
ms = ms,
|
||||
channels = channels,
|
||||
resL = table.create(33, 0),
|
||||
resR = table.create(33, 0),
|
||||
scfL = table.create(99, 0),
|
||||
scfR = table.create(99, 0),
|
||||
scfiL = table.create(33, 0),
|
||||
scfiR = table.create(33, 0),
|
||||
dscfL = table.create(33, false),
|
||||
dscfR = table.create(33, false),
|
||||
msf = table.create(33, false),
|
||||
qL = table.create(32 * 36, 0),
|
||||
qR = table.create(32 * 36, 0),
|
||||
yL = table.create(36 * 32, 0),
|
||||
yR = table.create(36 * 32, 0),
|
||||
vL = table.create(2304 + 960, 0),
|
||||
vR = table.create(2304 + 960, 0),
|
||||
r1 = 1,
|
||||
r2 = 1,
|
||||
lastMaxBand = 0,
|
||||
}
|
||||
return st
|
||||
end
|
||||
|
||||
-- reset(st, scf): forget the history (before a seek); scf = the scalefactor indices to assume (libmpcdec: 0 at the
|
||||
-- start of the stream, 0x01010101 in the middle of an SV7 stream). The noise generator restarts too, so a seek
|
||||
-- decodes like libmpcdec seeking in a freshly opened stream.
|
||||
function Decode.reset(st: State, scf: number)
|
||||
for i = 1, 99 do
|
||||
st.scfL[i] = scf
|
||||
st.scfR[i] = scf
|
||||
end
|
||||
for i = 1, 33 do
|
||||
st.resL[i], st.resR[i] = 0, 0
|
||||
st.dscfL[i], st.dscfR[i] = false, false
|
||||
st.msf[i] = false
|
||||
end
|
||||
for i = 1, 2304 + 960 do
|
||||
st.vL[i], st.vR[i] = 0, 0
|
||||
end
|
||||
st.lastMaxBand = 0
|
||||
st.r1, st.r2 = 1, 1
|
||||
end
|
||||
|
||||
local function noise(st: State, q: { number }, o: number)
|
||||
local r1, r2 = st.r1, st.r2
|
||||
for k = 0, 35 do
|
||||
local t1 = PARITY[band(r1, 0xF5) + 1]
|
||||
local t2 = PARITY[band(rshift(r2, 25), 0x63) + 1]
|
||||
r1 = bor(rshift(r1, 1), lshift(t1, 31))
|
||||
r2 = bor(band(lshift(r2, 1), 0xFFFFFFFF), t2)
|
||||
local t = bxor(r1, r2)
|
||||
q[o + k] = band(rshift(t, 24), 255) + band(rshift(t, 16), 255) + band(rshift(t, 8), 255) + band(t, 255) - 510
|
||||
end
|
||||
st.r1, st.r2 = r1, r2
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ SV7
|
||||
-- mpc_decoder_read_bitstream_sv7 -> true | nil, message
|
||||
local function readSv7(st: State, limit: number): (boolean?, string?)
|
||||
local resL, resR, msf = st.resL, st.resR, st.msf
|
||||
local maxUsed = 0
|
||||
local ms = st.ms
|
||||
resL[1] = bits(4)
|
||||
resR[1] = bits(4)
|
||||
if resL[1] ~= 0 or resR[1] ~= 0 then
|
||||
if ms then
|
||||
msf[1] = bits(1) == 1
|
||||
end
|
||||
maxUsed = 1
|
||||
end
|
||||
for n = 1, st.maxBand do
|
||||
local idx = huff(HDR)
|
||||
resL[n + 1] = if idx ~= 4 then resL[n] + idx else bits(4)
|
||||
idx = huff(HDR)
|
||||
resR[n + 1] = if idx ~= 4 then resR[n] + idx else bits(4)
|
||||
local l, r = resL[n + 1], resR[n + 1]
|
||||
if l < -1 or l > 17 or r < -1 or r > 17 then
|
||||
return nil, "bad band resolution"
|
||||
end
|
||||
if l ~= 0 or r ~= 0 then
|
||||
if ms then
|
||||
msf[n + 1] = bits(1) == 1
|
||||
end
|
||||
maxUsed = n + 1
|
||||
end
|
||||
end
|
||||
if resL[1] > 17 or resR[1] > 17 then
|
||||
return nil, "bad band resolution"
|
||||
end
|
||||
-- SCFI
|
||||
local scfiL, scfiR = st.scfiL, st.scfiR
|
||||
for n = 1, maxUsed do
|
||||
if resL[n] ~= 0 then
|
||||
scfiL[n] = huff(SCFI7)
|
||||
end
|
||||
if resR[n] ~= 0 then
|
||||
scfiR[n] = huff(SCFI7)
|
||||
end
|
||||
end
|
||||
if P > limit then
|
||||
return nil, "truncated frame"
|
||||
end
|
||||
-- SCF / DSCF
|
||||
for n = 1, maxUsed do
|
||||
for c = 1, 2 do
|
||||
local res = if c == 1 then resL[n] else resR[n]
|
||||
if res ~= 0 then
|
||||
local scf = if c == 1 then st.scfL else st.scfR
|
||||
local scfi = if c == 1 then scfiL[n] else scfiR[n]
|
||||
local o = (n - 1) * 3
|
||||
local idx = huff(DSCF7)
|
||||
local s0 = if idx ~= 8 then scf[o + 3] + idx else bits(6)
|
||||
local s1, s2
|
||||
if scfi == 1 then
|
||||
idx = huff(DSCF7)
|
||||
s1 = if idx ~= 8 then s0 + idx else bits(6)
|
||||
s2 = s1
|
||||
elseif scfi == 3 then
|
||||
s1, s2 = s0, s0
|
||||
elseif scfi == 2 then
|
||||
s1 = s0
|
||||
idx = huff(DSCF7)
|
||||
s2 = if idx ~= 8 then s1 + idx else bits(6)
|
||||
else
|
||||
idx = huff(DSCF7)
|
||||
s1 = if idx ~= 8 then s0 + idx else bits(6)
|
||||
idx = huff(DSCF7)
|
||||
s2 = if idx ~= 8 then s1 + idx else bits(6)
|
||||
end
|
||||
scf[o + 1] = if s0 > 1024 then 0x8080 else s0
|
||||
scf[o + 2] = if s1 > 1024 then 0x8080 else s1
|
||||
scf[o + 3] = if s2 > 1024 then 0x8080 else s2
|
||||
end
|
||||
end
|
||||
end
|
||||
if P > limit then
|
||||
return nil, "truncated frame"
|
||||
end
|
||||
-- samples
|
||||
for n = 1, maxUsed do
|
||||
for c = 1, 2 do
|
||||
local res = if c == 1 then resL[n] else resR[n]
|
||||
local q = if c == 1 then st.qL else st.qR
|
||||
local o = (n - 1) * 36 + 1
|
||||
if res == -1 then
|
||||
noise(st, q, o)
|
||||
elseif res == 1 then
|
||||
local tab = Q7[1][bits(1) + 1]
|
||||
for k = 0, 35, 3 do
|
||||
local idx = huff(tab)
|
||||
q[o + k] = idx % 3 - 1
|
||||
q[o + k + 1] = (idx // 3) % 3 - 1
|
||||
q[o + k + 2] = idx // 9 - 1
|
||||
end
|
||||
elseif res == 2 then
|
||||
local tab = Q7[2][bits(1) + 1]
|
||||
for k = 0, 35, 2 do
|
||||
local idx = huff(tab)
|
||||
q[o + k] = idx % 5 - 2
|
||||
q[o + k + 1] = idx // 5 - 2
|
||||
end
|
||||
elseif res >= 3 and res <= 7 then
|
||||
local tab = Q7[res][bits(1) + 1]
|
||||
for k = 0, 35 do
|
||||
q[o + k] = huff(tab)
|
||||
end
|
||||
elseif res >= 8 then
|
||||
local nb, dc = RES_BIT[res], DC[res + 2]
|
||||
for k = 0, 35 do
|
||||
q[o + k] = bits(nb) - dc
|
||||
end
|
||||
end
|
||||
if P > limit then
|
||||
return nil, "truncated frame"
|
||||
end
|
||||
end
|
||||
end
|
||||
-- bands above maxUsed: silent
|
||||
for n = maxUsed + 1, st.maxBand + 1 do
|
||||
resL[n], resR[n] = 0, 0
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ SV8
|
||||
local function readSv8(st: State, key: boolean, limit: number): (boolean?, string?)
|
||||
local resL, resR, msf = st.resL, st.resR, st.msf
|
||||
local maxBand = st.maxBand
|
||||
local maxUsed
|
||||
if key then
|
||||
maxUsed = logDec(maxBand + 1)
|
||||
else
|
||||
maxUsed = st.lastMaxBand + huff(BANDS8)
|
||||
if maxUsed > 32 then
|
||||
maxUsed -= 33
|
||||
end
|
||||
end
|
||||
if maxUsed > maxBand + 1 then
|
||||
return nil, "bad band count"
|
||||
end
|
||||
st.lastMaxBand = maxUsed
|
||||
if maxUsed > 0 then
|
||||
local l, r = huff(RES8[1]), huff(RES8[1])
|
||||
resL[maxUsed] = if l > 15 then l - 17 else l
|
||||
resR[maxUsed] = if r > 15 then r - 17 else r
|
||||
for n = maxUsed - 1, 1, -1 do
|
||||
l = huff(RES8[if resL[n + 1] > 2 then 2 else 1]) + resL[n + 1]
|
||||
resL[n] = if l > 15 then l - 17 else l
|
||||
r = huff(RES8[if resR[n + 1] > 2 then 2 else 1]) + resR[n + 1]
|
||||
resR[n] = if r > 15 then r - 17 else r
|
||||
end
|
||||
if st.ms then
|
||||
local tot = 0
|
||||
for n = 1, maxUsed do
|
||||
if resL[n] ~= 0 or resR[n] ~= 0 then
|
||||
tot += 1
|
||||
end
|
||||
end
|
||||
local cnt = logDec(tot)
|
||||
local tmp = 0
|
||||
if cnt ~= 0 and cnt ~= tot then
|
||||
tmp = enumDec(math.min(cnt, tot - cnt), tot)
|
||||
end
|
||||
if cnt * 2 > tot then
|
||||
tmp = bnot(tmp)
|
||||
end
|
||||
for n = maxUsed, 1, -1 do
|
||||
if resL[n] ~= 0 or resR[n] ~= 0 then
|
||||
msf[n] = band(tmp, 1) == 1
|
||||
tmp = rshift(tmp, 1)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
for n = maxUsed + 1, maxBand + 1 do
|
||||
resL[n], resR[n] = 0, 0
|
||||
end
|
||||
-- SCFI
|
||||
local dscfL, dscfR = st.dscfL, st.dscfR
|
||||
if key then
|
||||
for n = 1, 32 do
|
||||
dscfL[n], dscfR[n] = true, true
|
||||
end
|
||||
end
|
||||
local scfiL, scfiR = st.scfiL, st.scfiR
|
||||
for n = 1, maxUsed do
|
||||
local cnt = -1
|
||||
if resL[n] ~= 0 then
|
||||
cnt += 1
|
||||
end
|
||||
if resR[n] ~= 0 then
|
||||
cnt += 1
|
||||
end
|
||||
if cnt >= 0 then
|
||||
local tmp = huff(SCFI8[cnt + 1])
|
||||
if resL[n] ~= 0 then
|
||||
scfiL[n] = rshift(tmp, 2 * cnt)
|
||||
end
|
||||
if resR[n] ~= 0 then
|
||||
scfiR[n] = band(tmp, 3)
|
||||
end
|
||||
end
|
||||
end
|
||||
if P > limit then
|
||||
return nil, "truncated frame"
|
||||
end
|
||||
-- SCF / DSCF
|
||||
for n = 1, maxUsed do
|
||||
for c = 1, 2 do
|
||||
local res = if c == 1 then resL[n] else resR[n]
|
||||
if res ~= 0 then
|
||||
local scf = if c == 1 then st.scfL else st.scfR
|
||||
local scfi = if c == 1 then scfiL[n] else scfiR[n]
|
||||
local dscf = if c == 1 then dscfL else dscfR
|
||||
local o = (n - 1) * 3
|
||||
if dscf[n] then
|
||||
scf[o + 1] = bits(7) - 6
|
||||
dscf[n] = false
|
||||
else
|
||||
local tmp = huff(DSCF8[2])
|
||||
if tmp == 64 then
|
||||
tmp += bits(6)
|
||||
end
|
||||
scf[o + 1] = band(scf[o + 3] - 25 + tmp, 127) - 6
|
||||
end
|
||||
for m = 0, 1 do
|
||||
if band(lshift(scfi, m), 2) == 0 then
|
||||
local tmp = huff(DSCF8[1])
|
||||
if tmp == 31 then
|
||||
tmp = 64 + bits(6)
|
||||
end
|
||||
scf[o + m + 2] = band(scf[o + m + 1] - 25 + tmp, 127) - 6
|
||||
else
|
||||
scf[o + m + 2] = scf[o + m + 1]
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if P > limit then
|
||||
return nil, "truncated frame"
|
||||
end
|
||||
-- samples
|
||||
for n = 1, maxUsed do
|
||||
for c = 1, 2 do
|
||||
local res = if c == 1 then resL[n] else resR[n]
|
||||
local q = if c == 1 then st.qL else st.qR
|
||||
local o = (n - 1) * 36 + 1
|
||||
if res == 2 then
|
||||
local tabs = Q8[2]
|
||||
local thres = 3
|
||||
local idx = 6
|
||||
for k = 0, 35, 3 do
|
||||
local tmp = huff(tabs[if idx > thres then 2 else 1])
|
||||
local a, b, cc = tmp % 5 - 2, (tmp // 5) % 5 - 2, tmp // 25 - 2
|
||||
q[o + k], q[o + k + 1], q[o + k + 2] = a, b, cc
|
||||
idx = rshift(idx, 1) + abs(a) + abs(b) + abs(cc)
|
||||
end
|
||||
elseif res == 1 then
|
||||
local k = 0
|
||||
while k < 36 do
|
||||
local kmax = k + 18
|
||||
local cnt = huff(Q1_8)
|
||||
local idx = 0
|
||||
if cnt > 0 and cnt < 18 then
|
||||
idx = enumDec(if cnt <= 9 then cnt else 18 - cnt, 18)
|
||||
end
|
||||
if cnt > 9 then
|
||||
idx = bnot(idx)
|
||||
end
|
||||
while k < kmax do
|
||||
q[o + k] = 0
|
||||
if band(idx, 0x20000) ~= 0 then
|
||||
q[o + k] = bits(1) * 2 - 1
|
||||
end
|
||||
idx = lshift(idx, 1)
|
||||
k += 1
|
||||
end
|
||||
end
|
||||
elseif res == -1 then
|
||||
noise(st, q, o)
|
||||
elseif res == 3 or res == 4 then
|
||||
local tab = Q34[res - 2]
|
||||
for k = 0, 35, 2 do
|
||||
local s = band(huff(tab), 255)
|
||||
local s1, s2 = band(s, 15), rshift(s, 4)
|
||||
q[o + k] = if s1 >= 8 then s1 - 16 else s1
|
||||
q[o + k + 1] = if s2 >= 8 then s2 - 16 else s2
|
||||
end
|
||||
elseif res >= 5 and res <= 8 then
|
||||
local tabs = Q8[res]
|
||||
local thres = THRES[res]
|
||||
local idx = 2 * thres
|
||||
for k = 0, 35 do
|
||||
local v = huff(tabs[if idx > thres then 2 else 1])
|
||||
q[o + k] = v
|
||||
idx = rshift(idx, 1) + abs(v)
|
||||
end
|
||||
elseif res >= 9 then
|
||||
local sh = res - 9
|
||||
local dc = DC[res + 2]
|
||||
for k = 0, 35 do
|
||||
local v = band(huff(Q9UP), 255)
|
||||
if sh > 0 then
|
||||
v = v * 2 ^ sh + bits(sh)
|
||||
end
|
||||
q[o + k] = v - dc
|
||||
end
|
||||
elseif res < -1 then
|
||||
return nil, "bad band resolution"
|
||||
end
|
||||
if P > limit then
|
||||
return nil, "truncated frame"
|
||||
end
|
||||
end
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requantisation
|
||||
local function requant(st: State)
|
||||
local resL, resR, msf = st.resL, st.resR, st.msf
|
||||
local scfL, scfR, qL, qR, yL, yR = st.scfL, st.scfR, st.qL, st.qR, st.yL, st.yR
|
||||
for b = 1, st.maxBand + 1 do
|
||||
local rl, rr = resL[b], resR[b]
|
||||
local ccl, ccr = CC[rl + 2] or 0, CC[rr + 2] or 0
|
||||
local ms = msf[b]
|
||||
local o = (b - 1) * 36 + 1
|
||||
for part = 0, 2 do
|
||||
local fl = if rl ~= 0 then f32(ccl * SCF[band(scfL[(b - 1) * 3 + part + 1], 255) + 1]) else 0
|
||||
local fr = if rr ~= 0 then f32(ccr * SCF[band(scfR[(b - 1) * 3 + part + 1], 255) + 1]) else 0
|
||||
local y = part * 12 * 32 + b
|
||||
local qo = o + part * 12
|
||||
if ms then
|
||||
for k = 0, 11 do
|
||||
local l, r = fl * qL[qo + k], fr * qR[qo + k]
|
||||
yL[y], yR[y] = l + r, l - r
|
||||
y += 32
|
||||
end
|
||||
else
|
||||
for k = 0, 11 do
|
||||
yL[y], yR[y] = fl * qL[qo + k], fr * qR[qo + k]
|
||||
y += 32
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
-- mpc_synthese_filter_float for one channel: 36 x 32 subband samples -> 1152 samples at out[base + i * step]
|
||||
local function synth(V: { number }, Y: { number }, out: { number }, base: number, step: number)
|
||||
table.move(V, 1, 960, 2305)
|
||||
local o = 2304 + 1
|
||||
local dw = DW
|
||||
local p = base
|
||||
for n = 0, 35 do
|
||||
o -= 64
|
||||
newV(Y, n * 32 + 1, V, o)
|
||||
for k = 0, 31 do
|
||||
local v = o + k
|
||||
local d = k * 16 + 1
|
||||
out[p] = V[v] * dw[d] + V[v + 96] * dw[d + 1] + V[v + 128] * dw[d + 2] + V[v + 224] * dw[d + 3]
|
||||
+ V[v + 256] * dw[d + 4] + V[v + 352] * dw[d + 5] + V[v + 384] * dw[d + 6] + V[v + 480] * dw[d + 7]
|
||||
+ V[v + 512] * dw[d + 8] + V[v + 608] * dw[d + 9] + V[v + 640] * dw[d + 10] + V[v + 736] * dw[d + 11]
|
||||
+ V[v + 768] * dw[d + 12] + V[v + 864] * dw[d + 13] + V[v + 896] * dw[d + 14] + V[v + 992] * dw[d + 15]
|
||||
p += step
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ frames
|
||||
-- frame(st, buf, bitPos, limitBits, key, out, base) -> the bit position after the frame | nil, message: decodes one
|
||||
-- frame from buf (padded by PAD bytes past limitBits / 8) into out[base ..] (1152 * channels interleaved floats).
|
||||
-- key: an SV8 key frame (the first of a block). bitPos < 0 decodes a silent frame (the synthesis tail).
|
||||
function Decode.frame(st: State, buf: buffer, bitPos: number, limitBits: number, key: boolean, out: { number }, base: number): (number?, string?)
|
||||
if bitPos >= 0 then
|
||||
if rshift(limitBits, 3) + Decode.PAD > buffer.len(buf) or bitPos > limitBits then
|
||||
return nil, "truncated frame"
|
||||
end
|
||||
B, P = buf, bitPos
|
||||
local ok, err
|
||||
if st.version == 8 then
|
||||
ok, err = readSv8(st, key, limitBits)
|
||||
else
|
||||
ok, err = readSv7(st, limitBits)
|
||||
end
|
||||
B = buffer.create(0)
|
||||
if not ok then
|
||||
return nil, err
|
||||
end
|
||||
else
|
||||
for b = 1, st.maxBand + 1 do
|
||||
st.resL[b], st.resR[b] = 0, 0
|
||||
end
|
||||
end
|
||||
local pos = P
|
||||
requant(st)
|
||||
local ch = st.channels
|
||||
synth(st.vL, st.yL, out, base, ch)
|
||||
if ch > 1 then
|
||||
synth(st.vR, st.yR, out, base + 1, ch)
|
||||
end
|
||||
return if bitPos >= 0 then pos else bitPos, nil
|
||||
end
|
||||
|
||||
-- bitsAt(buf, bitPos, n) -> n (1 .. 24) bits at bitPos (frame headers: the SV7 frame size); the caller keeps
|
||||
-- bitPos / 8 + 4 inside buf
|
||||
function Decode.bitsAt(buf: buffer, bitPos: number, n: number): number
|
||||
local w = bswap(readu32(buf, rshift(bitPos, 3)))
|
||||
return extract(w, 32 - band(bitPos, 7) - n, n)
|
||||
end
|
||||
|
||||
return Decode
|
||||
@@ -0,0 +1,379 @@
|
||||
--!strict
|
||||
-- codecs/audio/Musepack/Tables: the Musepack SV7 / SV8 Huffman tables, the synthesis window and the requantisation
|
||||
-- constants. Ported from libmpcdec (musepack_src_r475: huffman.c, synth_filter.c, requant.c, mpc_bits_reader.c;
|
||||
-- BSD-3-Clause, (c) The Musepack Development Team, licenses/libmpcdec-BSD.txt); the tables are transcribed by script.
|
||||
-- Each Huffman table is a flat { code, length, value, ... } list sorted by descending left-aligned 16-bit code;
|
||||
-- canonical (SV8) tables map value - (code >> (16 - length)) through their symbol list. lut(table, sym?) builds the
|
||||
-- 8-bit first-level lookup the decoder uses.
|
||||
local T = {}
|
||||
|
||||
T.HuffHdr = {
|
||||
32768, 1, 0, 24576, 3, 1, 24064, 7, -4, 23936, 9, 3, 23808, 9, 4, 23552, 8, -5, 22528, 6, 2, 20480, 5, -3, 16384, 4, -2, 0, 2, -1,
|
||||
}
|
||||
T.HuffSCFI = {
|
||||
32768, 1, 1, 24576, 3, 2, 16384, 3, 0, 0, 2, 3,
|
||||
}
|
||||
T.HuffDSCF = {
|
||||
63488, 5, 5, 61440, 5, -4, 57344, 4, 3, 53248, 4, -3, 49152, 4, 8, 40960, 3, 1, 36864, 4, 0, 34816, 5, -5, 33792, 6, 7, 32768, 6, -7,
|
||||
24576, 3, -1, 16384, 3, 2, 12288, 4, 4, 10240, 5, 6, 8192, 5, -6, 0, 3, -2,
|
||||
}
|
||||
T.HuffQ1_0 = {
|
||||
57344, 3, 13, 56320, 6, 26, 55296, 6, 0, 54272, 6, 20, 53248, 6, 6, 49152, 4, 14, 45056, 4, 12, 40960, 4, 4, 36864, 4, 22, 35840, 6, 8,
|
||||
34816, 6, 18, 33792, 6, 24, 32768, 6, 2, 28672, 4, 16, 24576, 4, 10, 22528, 5, 17, 20480, 5, 9, 18432, 5, 1, 16384, 5, 25, 14336, 5, 5,
|
||||
12288, 5, 21, 10240, 5, 3, 8192, 5, 11, 6144, 5, 15, 4096, 5, 23, 2048, 5, 19, 0, 5, 7,
|
||||
}
|
||||
T.HuffQ1_1 = {
|
||||
32768, 1, 13, 32256, 7, 15, 31744, 7, 1, 31232, 7, 11, 30720, 7, 7, 30208, 7, 17, 29696, 7, 25, 29184, 7, 19, 29056, 9, 8, 28928, 9, 18,
|
||||
28800, 9, 2, 28672, 9, 24, 28160, 7, 3, 27648, 7, 23, 27136, 7, 21, 26624, 7, 5, 26368, 8, 0, 26112, 8, 26, 25856, 8, 6, 25600, 8, 20,
|
||||
24576, 6, 9, 20480, 4, 14, 16384, 4, 12, 12288, 4, 4, 8192, 4, 22, 4096, 4, 16, 0, 4, 10,
|
||||
}
|
||||
T.HuffQ2_0 = {
|
||||
61440, 4, 13, 57344, 4, 17, 53248, 4, 7, 49152, 4, 11, 48128, 6, 1, 47104, 6, 23, 46592, 7, 4, 46080, 7, 20, 45568, 7, 0, 45056, 7, 24,
|
||||
43008, 5, 22, 40960, 5, 10, 32768, 3, 12, 30720, 5, 2, 28672, 5, 14, 24576, 4, 6, 20480, 4, 18, 16384, 4, 8, 12288, 4, 16, 10240, 5, 9,
|
||||
8192, 5, 5, 6144, 5, 15, 4096, 5, 21, 2048, 5, 19, 0, 5, 3,
|
||||
}
|
||||
T.HuffQ2_1 = {
|
||||
63488, 5, 18, 61440, 5, 6, 59392, 5, 8, 59136, 8, 3, 59072, 10, 24, 59008, 10, 4, 58944, 10, 0, 58880, 10, 20, 58368, 7, 23, 57856, 7, 1,
|
||||
57344, 7, 19, 55296, 5, 16, 54784, 7, 15, 54272, 7, 21, 53760, 7, 9, 53248, 7, 5, 52224, 6, 2, 51200, 6, 10, 50176, 6, 14, 49152, 6, 22,
|
||||
32768, 2, 12, 24576, 3, 13, 16384, 3, 17, 8192, 3, 11, 0, 3, 7,
|
||||
}
|
||||
T.HuffQ3_0 = {
|
||||
57344, 3, 1, 53248, 4, 3, 49152, 4, -3, 40960, 3, 2, 32768, 3, -2, 16384, 2, 0, 0, 2, -1,
|
||||
}
|
||||
T.HuffQ3_1 = {
|
||||
49152, 2, 0, 32768, 2, -1, 16384, 2, 1, 12288, 4, -2, 10240, 5, 3, 8192, 5, -3, 0, 3, 2,
|
||||
}
|
||||
T.HuffQ4_0 = {
|
||||
57344, 3, 0, 49152, 3, -1, 40960, 3, 1, 32768, 3, -2, 24576, 3, 2, 20480, 4, -4, 16384, 4, 4, 8192, 3, 3, 0, 3, -3,
|
||||
}
|
||||
T.HuffQ4_1 = {
|
||||
57344, 3, 1, 53248, 4, 2, 49152, 4, -3, 32768, 2, 0, 24576, 3, -2, 20480, 4, 3, 18432, 5, -4, 16384, 5, 4, 0, 2, -1,
|
||||
}
|
||||
T.HuffQ5_0 = {
|
||||
61440, 4, 2, 59392, 5, 5, 58368, 6, -7, 57344, 6, 7, 53248, 4, -3, 49152, 4, 3, 47104, 5, -6, 45056, 5, 6, 40960, 4, -4, 36864, 4, 4,
|
||||
32768, 4, -5, 24576, 3, 0, 16384, 3, -1, 8192, 3, 1, 0, 3, -2,
|
||||
}
|
||||
T.HuffQ5_1 = {
|
||||
61440, 4, 3, 59392, 5, 4, 58880, 7, 6, 58624, 8, -7, 58368, 8, 7, 57344, 6, -6, 49152, 3, 0, 40960, 3, -1, 32768, 3, 1, 24576, 3, -2,
|
||||
16384, 3, 2, 14336, 5, -5, 12288, 5, 5, 8192, 4, -4, 0, 3, -3,
|
||||
}
|
||||
T.HuffQ6_0 = {
|
||||
63488, 5, 3, 61440, 5, -4, 60416, 6, -11, 59392, 6, 12, 57344, 5, 4, 55296, 5, 6, 53248, 5, -5, 51200, 5, 5, 49152, 5, 7, 47104, 5, -7,
|
||||
46080, 6, -12, 45056, 6, -13, 43008, 5, -6, 40960, 5, 8, 38912, 5, -8, 36864, 5, 9, 34816, 5, -9, 33792, 6, 13, 33280, 7, -15, 32768, 7, 15,
|
||||
28672, 4, 0, 26624, 5, -10, 24576, 5, 10, 20480, 4, -1, 16384, 4, 2, 12288, 4, 1, 8192, 4, -2, 7168, 6, 14, 6144, 6, -14, 4096, 5, 11,
|
||||
0, 4, -3,
|
||||
}
|
||||
T.HuffQ6_1 = {
|
||||
63488, 5, -6, 61440, 5, 6, 57344, 4, 1, 53248, 4, -1, 52736, 7, 10, 52224, 7, -10, 51968, 8, -11, 51840, 9, -12, 51808, 11, 13, 51800, 13, 15,
|
||||
51792, 13, -14, 51784, 13, 14, 51776, 13, -15, 51712, 10, -13, 51456, 8, 11, 51200, 8, 12, 50176, 6, -9, 49152, 6, 9, 45056, 4, -2, 40960, 4, 2,
|
||||
36864, 4, 3, 32768, 4, -3, 30720, 5, -7, 28672, 5, 7, 24576, 4, -4, 20480, 4, 4, 18432, 5, -8, 16384, 5, 8, 12288, 4, 5, 8192, 4, -5,
|
||||
0, 3, 0,
|
||||
}
|
||||
T.HuffQ7_0 = {
|
||||
64512, 6, 7, 63488, 6, 8, 62464, 6, 9, 61440, 6, -8, 60416, 6, 11, 59904, 7, 21, 59648, 8, -28, 59392, 8, 28, 58368, 6, -9, 57856, 7, -22,
|
||||
57344, 7, -21, 56320, 6, -10, 55296, 6, -11, 54272, 6, 10, 53248, 6, 12, 52224, 6, -13, 51712, 7, 22, 51200, 7, 23, 50176, 6, -12, 49152, 6, 13,
|
||||
48128, 6, 14, 47104, 6, -14, 46592, 7, -23, 46336, 8, -29, 46080, 8, 29, 45056, 6, -15, 44032, 6, 15, 43008, 6, 16, 41984, 6, -16, 41472, 7, -24,
|
||||
40960, 7, 24, 39936, 6, 17, 39424, 7, -25, 39168, 8, -30, 38912, 8, 30, 37888, 6, -17, 36864, 6, 18, 35840, 6, -18, 35328, 7, 25, 34816, 7, 26,
|
||||
33792, 6, 19, 33280, 7, -26, 32768, 7, -27, 30720, 5, 2, 29696, 6, -19, 28672, 6, 20, 26624, 5, -1, 26368, 8, -31, 26112, 8, 31, 25600, 7, 27,
|
||||
24576, 6, -20, 22528, 5, 1, 20480, 5, -5, 18432, 5, -3, 16384, 5, 3, 14336, 5, 0, 12288, 5, -2, 10240, 5, -4, 8192, 5, 4, 6144, 5, 5,
|
||||
4096, 5, -6, 2048, 5, 6, 0, 5, -7,
|
||||
}
|
||||
T.HuffQ7_1 = {
|
||||
63488, 5, -1, 61440, 5, 2, 59392, 5, -2, 57344, 5, 3, 57088, 8, -20, 57024, 10, 24, 57020, 14, 28, 57016, 14, -28, 57012, 14, -30, 57008, 14, 30,
|
||||
56992, 12, -27, 56988, 14, 29, 56984, 14, -29, 56980, 14, 31, 56976, 14, -31, 56960, 12, 27, 56832, 9, -22, 56320, 7, -17, 55296, 6, -11, 53248, 5, -3,
|
||||
51200, 5, 4, 49152, 5, -4, 48640, 7, 17, 48384, 8, 20, 48256, 9, 22, 48192, 10, -25, 48128, 10, -26, 47104, 6, 12, 45056, 5, 5, 43008, 5, -5,
|
||||
40960, 5, 6, 38912, 5, -6, 37888, 6, -12, 37376, 7, -18, 36864, 7, 18, 35840, 6, 13, 34816, 6, -13, 32768, 5, -7, 31744, 6, 14, 31488, 8, 21,
|
||||
31232, 8, -21, 30720, 7, -19, 28672, 5, 7, 26624, 5, 8, 25600, 6, -14, 24576, 6, -15, 22528, 5, -8, 21504, 6, 15, 20992, 7, 19, 20928, 10, 25,
|
||||
20864, 10, 26, 20736, 9, -23, 20608, 9, 23, 20480, 9, -24, 18432, 5, -9, 16384, 5, 9, 15360, 6, 16, 14336, 6, -16, 12288, 5, 10, 8192, 4, 0,
|
||||
6144, 5, -10, 4096, 5, 11, 0, 4, 1,
|
||||
}
|
||||
T.H_SCFI_1 = {
|
||||
32768, 1, 1, 16384, 2, 2, 0, 3, 3,
|
||||
}
|
||||
T.H_SCFI_2 = {
|
||||
32768, 2, 3, 16384, 3, 5, 6144, 5, 11, 1024, 6, 14, 0, 7, 15,
|
||||
}
|
||||
T.H_DSCF_1 = {
|
||||
40960, 3, 7, 16384, 4, 12, 10240, 5, 16, 6144, 6, 21, 3584, 7, 27, 1792, 8, 34, 896, 9, 41, 320, 10, 48, 128, 11, 53, 48, 12, 57,
|
||||
24, 13, 60, 0, 14, 63,
|
||||
}
|
||||
T.H_DSCF_2 = {
|
||||
24576, 3, 7, 12288, 4, 10, 6144, 5, 13, 4096, 6, 16, 2560, 7, 20, 1536, 8, 25, 896, 9, 31, 448, 10, 38, 224, 11, 45, 80, 12, 52,
|
||||
32, 13, 57, 12, 14, 61, 0, 15, 64,
|
||||
}
|
||||
T.H_Bands = {
|
||||
32768, 1, 1, 16384, 2, 2, 8192, 3, 3, 4096, 5, 6, 2048, 6, 8, 1536, 7, 10, 768, 8, 13, 512, 9, 16, 320, 10, 20, 192, 11, 25,
|
||||
16, 12, 31, 0, 13, 32,
|
||||
}
|
||||
T.H_Res_1 = {
|
||||
32768, 1, 1, 16384, 2, 2, 8192, 3, 3, 4096, 4, 4, 2048, 5, 5, 1024, 6, 6, 512, 7, 7, 256, 8, 8, 128, 9, 9, 64, 10, 10,
|
||||
32, 11, 11, 16, 12, 12, 8, 13, 13, 4, 14, 14, 2, 15, 15, 0, 16, 16,
|
||||
}
|
||||
T.H_Res_2 = {
|
||||
16384, 2, 3, 8192, 3, 4, 4096, 4, 5, 2048, 5, 6, 1024, 6, 7, 512, 7, 8, 256, 8, 9, 128, 9, 10, 64, 10, 11, 32, 11, 12,
|
||||
16, 12, 13, 0, 14, 16,
|
||||
}
|
||||
T.H_Q1 = {
|
||||
24576, 3, 7, 4096, 4, 10, 2048, 5, 11, 1024, 6, 12, 512, 7, 13, 256, 8, 14, 128, 9, 15, 64, 10, 16, 32, 11, 17, 0, 12, 18,
|
||||
}
|
||||
T.H_Q2_1 = {
|
||||
57344, 3, 7, 32768, 4, 14, 15360, 6, 38, 10752, 7, 53, 4608, 8, 74, 1536, 9, 92, 960, 10, 104, 96, 11, 119, 32, 12, 122, 0, 13, 124,
|
||||
}
|
||||
T.H_Q2_2 = {
|
||||
61440, 4, 15, 28672, 5, 30, 18432, 6, 44, 15360, 7, 62, 3072, 8, 92, 1920, 9, 104, 192, 10, 119, 64, 11, 122, 0, 12, 124,
|
||||
}
|
||||
T.H_Q3 = {
|
||||
57344, 3, 7, 32768, 4, 14, 20480, 5, 22, 9216, 6, 32, 2560, 7, 41, 512, 8, 46, 0, 9, 48,
|
||||
}
|
||||
T.H_Q4 = {
|
||||
61440, 4, 15, 36864, 5, 30, 13312, 6, 48, 6144, 7, 61, 1280, 8, 73, 256, 9, 78, 0, 10, 80, 0, 0, 90,
|
||||
}
|
||||
T.H_Q5_1 = {
|
||||
49152, 2, 3, 16384, 3, 6, 8192, 4, 8, 4096, 5, 10, 2048, 6, 12, 0, 7, 14,
|
||||
}
|
||||
T.H_Q5_2 = {
|
||||
24576, 3, 7, 8192, 4, 10, 4096, 5, 12, 0, 6, 14,
|
||||
}
|
||||
T.H_Q6_1 = {
|
||||
49152, 2, 3, 32768, 3, 6, 16384, 4, 10, 10240, 5, 14, 3072, 6, 19, 2048, 7, 22, 1024, 8, 26, 0, 9, 30,
|
||||
}
|
||||
T.H_Q6_2 = {
|
||||
20480, 4, 15, 8192, 5, 20, 4096, 6, 24, 1024, 7, 28, 0, 8, 30,
|
||||
}
|
||||
T.H_Q7_1 = {
|
||||
49152, 2, 3, 32768, 3, 6, 24576, 4, 10, 16384, 5, 16, 10240, 6, 24, 5120, 7, 34, 2560, 8, 44, 1024, 9, 54, 0, 10, 62,
|
||||
}
|
||||
T.H_Q7_2 = {
|
||||
24576, 5, 31, 9216, 6, 43, 4096, 7, 52, 512, 8, 60, 0, 9, 62,
|
||||
}
|
||||
T.H_Q8_1 = {
|
||||
49152, 2, 3, 32768, 3, 6, 28672, 4, 10, 22528, 5, 17, 14336, 6, 28, 10240, 7, 42, 6400, 8, 62, 3328, 9, 87, 640, 10, 113, 96, 11, 123,
|
||||
0, 12, 126,
|
||||
}
|
||||
T.H_Q8_2 = {
|
||||
38912, 6, 63, 10752, 7, 101, 1024, 8, 122, 0, 9, 126,
|
||||
}
|
||||
T.H_Q9up = {
|
||||
63488, 6, 63, 44032, 7, 125, 9728, 8, -45, 640, 9, -7, 64, 10, -2, 0, 11, -1,
|
||||
}
|
||||
T.S_SCFI_1 = {
|
||||
2, 3, 1, 0,
|
||||
}
|
||||
T.S_SCFI_2 = {
|
||||
15, 10, 14, 11, 13, 9, 7, 6, 5, 12, 8, 3, 2, 0, 4, 1,
|
||||
}
|
||||
T.S_DSCF_1 = {
|
||||
35, 34, 33, 36, 32, 30, 29, 27, 26, 37, 28, 25, 39, 38, 24, 23, 40, 22, 21, 20, 19, 43, 42, 41, 18, 17, 16, 15, 46, 45, 44, 14,
|
||||
13, 12, 11, 49, 48, 47, 31, 10, 9, 8, 7, 6, 52, 51, 50, 5, 4, 3, 54, 53, 2, 1, 0, 57, 56, 55, 63, 62, 61, 60, 59, 58,
|
||||
}
|
||||
T.S_DSCF_2 = {
|
||||
33, 32, 31, 30, 29, 34, 28, 27, 36, 35, 26, 37, 25, 38, 24, 23, 40, 39, 22, 21, 42, 41, 20, 19, 18, 45, 44, 43, 17, 16, 15, 14,
|
||||
48, 47, 46, 13, 12, 11, 10, 64, 52, 51, 50, 49, 9, 8, 7, 6, 55, 54, 53, 5, 4, 3, 58, 57, 56, 2, 1, 63, 62, 61, 60, 59,
|
||||
0,
|
||||
}
|
||||
T.S_Bands = {
|
||||
0, 32, 1, 31, 2, 30, 3, 4, 29, 6, 5, 28, 7, 27, 26, 8, 25, 24, 23, 9, 22, 21, 20, 18, 17, 16, 15, 14, 12, 11, 10, 19,
|
||||
13,
|
||||
}
|
||||
T.S_Res_1 = {
|
||||
0, 1, 16, 2, 3, 4, 5, 15, 6, 7, 8, 9, 10, 11, 12, 14, 13,
|
||||
}
|
||||
T.S_Res_2 = {
|
||||
16, 1, 0, 2, 15, 3, 14, 4, 5, 13, 6, 12, 7, 11, 10, 9, 8,
|
||||
}
|
||||
T.S_Q1 = {
|
||||
7, 6, 5, 4, 3, 10, 9, 8, 2, 1, 11, 0, 12, 13, 14, 15, 16, 18, 17,
|
||||
}
|
||||
T.S_Q2_1 = {
|
||||
62, 87, 67, 63, 61, 57, 37, 93, 92, 88, 86, 83, 82, 81, 68, 66, 58, 56, 42, 41, 38, 36, 32, 31, 112, 91, 72, 64, 60, 52, 43, 33,
|
||||
12, 117, 113, 111, 107, 97, 89, 85, 77, 73, 71, 69, 65, 59, 55, 53, 51, 47, 39, 35, 27, 17, 13, 11, 7, 118, 116, 108, 106, 98, 96, 94,
|
||||
90, 84, 80, 78, 76, 48, 46, 44, 40, 34, 30, 28, 26, 18, 16, 8, 6, 122, 110, 102, 74, 70, 54, 50, 22, 2, 123, 121, 119, 115, 114, 109,
|
||||
105, 103, 101, 99, 95, 79, 75, 49, 45, 29, 25, 23, 21, 19, 15, 14, 10, 9, 5, 3, 1, 124, 104, 20, 0, 120, 100, 24, 4,
|
||||
}
|
||||
T.S_Q2_2 = {
|
||||
62, 92, 87, 86, 82, 68, 67, 66, 63, 61, 58, 57, 56, 42, 38, 37, 32, 93, 91, 88, 83, 81, 43, 41, 36, 33, 31, 112, 72, 64, 60, 52,
|
||||
12, 118, 117, 116, 113, 111, 108, 107, 106, 98, 97, 96, 94, 90, 89, 85, 84, 80, 78, 77, 76, 73, 71, 69, 65, 59, 55, 53, 51, 48, 47, 46,
|
||||
44, 40, 39, 35, 34, 30, 28, 27, 26, 18, 17, 16, 13, 11, 8, 7, 6, 122, 110, 74, 70, 54, 50, 22, 14, 2, 123, 121, 119, 115, 114, 109,
|
||||
105, 103, 102, 101, 99, 95, 79, 75, 49, 45, 29, 25, 23, 21, 19, 15, 10, 9, 5, 3, 1, 124, 104, 20, 0, 120, 100, 24, 4,
|
||||
}
|
||||
T.S_Q3 = {
|
||||
0, 17, 16, 1, 15, -16, -1, 32, 31, 2, 14, -15, -32, 34, 33, 47, 46, 18, 30, -14, -2, -31, -17, -18, 49, 48, 63, 19, 29, 3, 13, -13,
|
||||
-3, -30, -47, -48, -33, 50, 62, 35, 45, -29, -19, -46, -34, 51, 61, -45, -35,
|
||||
}
|
||||
T.S_Q4 = {
|
||||
0, 32, 17, 16, 31, 2, 1, 15, 14, -15, -16, -1, -32, 49, 48, 34, 33, 47, 46, 19, 18, 30, 29, 3, 13, -13, -14, -2, -3, -30, -31, -17,
|
||||
-18, -47, -48, -33, 64, 50, 63, 62, 35, 45, 4, 12, -29, -19, -46, -34, -64, -49, 66, 65, 79, 78, 51, 61, 36, 44, 20, 28, -12, -4, -28, -20,
|
||||
-45, -35, -62, -63, -50, 67, 77, 52, 60, -44, -36, -61, -51, 68, 76, -60, -52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
}
|
||||
T.S_Q5_1 = {
|
||||
0, 2, 1, -1, -2, 3, -3, 4, -4, 5, -5, 7, 6, -6, -7,
|
||||
}
|
||||
T.S_Q5_2 = {
|
||||
2, 1, 0, -1, -2, 4, 3, -3, -4, 5, -5, 7, 6, -6, -7,
|
||||
}
|
||||
T.S_Q6_1 = {
|
||||
0, 1, -1, 3, 2, -2, -3, 4, -4, -5, 8, 7, 6, 5, -6, -7, -8, 9, -9, 11, 10, -10, -11, 15, 14, 13, 12, -12, -13, -14, -15,
|
||||
}
|
||||
T.S_Q6_2 = {
|
||||
5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, 8, 7, 6, -6, -7, -8, 10, 9, -9, -10, 13, 12, 11, -11, -12, -13, 15, 14, -14, -15,
|
||||
}
|
||||
T.S_Q7_1 = {
|
||||
0, 1, -1, 2, -2, 4, 3, -3, -4, 7, 6, 5, -5, -6, -7, 13, 11, 10, 9, 8, -8, -9, -10, -11, -12, 17, 16, 15, 14, 12, -13, -14,
|
||||
-15, -16, -17, 28, 27, 21, 20, 19, 18, -18, -19, -20, -21, -27, -28, 31, 30, 29, 26, 25, 24, 23, 22, -22, -23, -24, -25, -26, -29, -30, -31,
|
||||
}
|
||||
T.S_Q7_2 = {
|
||||
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, 17, 16, 15, 14, 13, 12, 11, -10, -11, -12, -13, -14,
|
||||
-15, -16, -17, 22, 21, 20, 19, 18, -18, -19, -20, -21, -22, 29, 28, 27, 26, 25, 24, 23, -23, -24, -25, -26, -27, -28, -29, 31, 30, -30, -31,
|
||||
}
|
||||
T.S_Q8_1 = {
|
||||
0, 1, -1, -2, 3, 2, -3, 7, 6, 5, 4, -4, -5, -6, -7, 11, 10, 9, 8, -8, -9, -10, -11, 19, 18, 17, 16, 15, 14, 13, 12, -12,
|
||||
-13, -14, -15, -16, -17, -19, 56, 55, 31, 28, 27, 26, 25, 24, 23, 22, 21, 20, -18, -20, -21, -22, -23, -24, -25, -26, -27, -33, -54, -56, 63, 62,
|
||||
61, 60, 59, 58, 57, 54, 53, 43, 40, 39, 38, 37, 36, 35, 34, 33, 32, 30, 29, -28, -29, -30, -31, -32, -34, -35, -36, -37, -38, -39, -40, -41,
|
||||
-43, -53, -55, -57, -58, -59, -60, -61, 49, 47, 46, 45, 44, 42, 41, -42, -44, -45, -46, -47, -48, -49, -50, -62, -63, 52, 51, 50, 48, -51, -52,
|
||||
}
|
||||
T.S_Q8_2 = {
|
||||
13, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, 39, 38, 37, 36, 35, 34,
|
||||
33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 12, -14, -15, -16, -17, -18, -19, -20, -21, -22, -23, -24,
|
||||
-25, -26, -27, -28, -29, -30, -31, -32, -33, -34, -35, -36, -37, -38, -39, -40, -41, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45,
|
||||
44, 43, 42, 41, 40, -42, -43, -44, -45, -46, -47, -48, -49, -50, -51, -52, -53, -54, -55, -56, -57, -58, -59, 63, 62, 61, 60, -60, -61, -62, -63,
|
||||
}
|
||||
T.S_Q9up = {
|
||||
-128, 127, -108, -110, -111, -112, -113, -114, -115, -116, -117, -118, -119, -120, -121, -122, -123, -124, -125, -126, -127, 126, 125, 124, 123, 122, 121, 120, 119, 118, 117, 116,
|
||||
115, 114, 113, 112, 111, 110, 109, 108, -44, -45, -46, -47, -48, -49, -50, -51, -52, -53, -54, -55, -56, -57, -58, -59, -60, -61, -62, -63, -64, -65, -66, -67,
|
||||
-68, -69, -70, -71, -72, -73, -74, -75, -76, -77, -78, -79, -80, -81, -82, -83, -84, -85, -86, -87, -88, -89, -90, -91, -92, -93, -94, -95, -96, -97, -98, -99,
|
||||
-100, -101, -102, -103, -104, -105, -106, -107, -109, 107, 106, 105, 104, 103, 102, 101, 100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85,
|
||||
84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53,
|
||||
52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 40, 20, 19, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -20, -21, -22, -23, -24,
|
||||
-25, -26, -27, -28, -29, -30, -31, -32, -33, -34, -35, -36, -37, -38, -39, -40, -41, -42, -43, 41, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28,
|
||||
27, 26, 25, 24, 23, 22, 21, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, -3, -4, -5, -6, 4, 3, 2, 1, 0, -1, -2,
|
||||
}
|
||||
|
||||
-- Di_opt[32][16] (times 65536)
|
||||
T.DI = {
|
||||
0, -29, 213, -459, 2037, -5153, 6574, -37489, 75038, 37489, 6574, 5153, 2037, 459, 213, 29,
|
||||
-1, -31, 218, -519, 2000, -5517, 5959, -39336, 74992, 35640, 7134, 4788, 2063, 401, 208, 26,
|
||||
-1, -35, 222, -581, 1952, -5879, 5288, -41176, 74856, 33791, 7640, 4425, 2080, 347, 202, 24,
|
||||
-1, -38, 225, -645, 1893, -6237, 4561, -43006, 74630, 31947, 8092, 4063, 2087, 294, 196, 21,
|
||||
-1, -41, 227, -711, 1822, -6589, 3776, -44821, 74313, 30112, 8492, 3705, 2085, 244, 190, 19,
|
||||
-1, -45, 228, -779, 1739, -6935, 2935, -46617, 73908, 28289, 8840, 3351, 2075, 197, 183, 17,
|
||||
-1, -49, 228, -848, 1644, -7271, 2037, -48390, 73415, 26482, 9139, 3004, 2057, 153, 176, 16,
|
||||
-2, -53, 227, -919, 1535, -7597, 1082, -50137, 72835, 24694, 9389, 2663, 2032, 111, 169, 14,
|
||||
-2, -58, 224, -991, 1414, -7910, 70, -51853, 72169, 22929, 9592, 2330, 2001, 72, 161, 13,
|
||||
-2, -63, 221, -1064, 1280, -8209, -998, -53534, 71420, 21189, 9750, 2006, 1962, 36, 154, 11,
|
||||
-2, -68, 215, -1137, 1131, -8491, -2122, -55178, 70590, 19478, 9863, 1692, 1919, 2, 147, 10,
|
||||
-3, -73, 208, -1210, 970, -8755, -3300, -56778, 69679, 17799, 9935, 1388, 1870, -29, 139, 9,
|
||||
-3, -79, 200, -1283, 794, -8998, -4533, -58333, 68692, 16155, 9966, 1095, 1817, -57, 132, 8,
|
||||
-4, -85, 189, -1356, 605, -9219, -5818, -59838, 67629, 14548, 9959, 814, 1759, -83, 125, 7,
|
||||
-4, -91, 177, -1428, 402, -9416, -7154, -61289, 66494, 12980, 9916, 545, 1698, -106, 117, 7,
|
||||
-5, -97, 163, -1498, 185, -9585, -8540, -62684, 65290, 11455, 9838, 288, 1634, -127, 111, 6,
|
||||
-5, -104, 146, -1567, -45, -9727, -9975, -64019, 64019, 9975, 9727, 45, 1567, -146, 104, 5,
|
||||
-6, -111, 127, -1634, -288, -9838, -11455, -65290, 62684, 8540, 9585, -185, 1498, -163, 97, 5,
|
||||
-7, -117, 106, -1698, -545, -9916, -12980, -66494, 61289, 7154, 9416, -402, 1428, -177, 91, 4,
|
||||
-7, -125, 83, -1759, -814, -9959, -14548, -67629, 59838, 5818, 9219, -605, 1356, -189, 85, 4,
|
||||
-8, -132, 57, -1817, -1095, -9966, -16155, -68692, 58333, 4533, 8998, -794, 1283, -200, 79, 3,
|
||||
-9, -139, 29, -1870, -1388, -9935, -17799, -69679, 56778, 3300, 8755, -970, 1210, -208, 73, 3,
|
||||
-10, -147, -2, -1919, -1692, -9863, -19478, -70590, 55178, 2122, 8491, -1131, 1137, -215, 68, 2,
|
||||
-11, -154, -36, -1962, -2006, -9750, -21189, -71420, 53534, 998, 8209, -1280, 1064, -221, 63, 2,
|
||||
-13, -161, -72, -2001, -2330, -9592, -22929, -72169, 51853, -70, 7910, -1414, 991, -224, 58, 2,
|
||||
-14, -169, -111, -2032, -2663, -9389, -24694, -72835, 50137, -1082, 7597, -1535, 919, -227, 53, 2,
|
||||
-16, -176, -153, -2057, -3004, -9139, -26482, -73415, 48390, -2037, 7271, -1644, 848, -228, 49, 1,
|
||||
-17, -183, -197, -2075, -3351, -8840, -28289, -73908, 46617, -2935, 6935, -1739, 779, -228, 45, 1,
|
||||
-19, -190, -244, -2085, -3705, -8492, -30112, -74313, 44821, -3776, 6589, -1822, 711, -227, 41, 1,
|
||||
-21, -196, -294, -2087, -4063, -8092, -31947, -74630, 43006, -4561, 6237, -1893, 645, -225, 38, 1,
|
||||
-24, -202, -347, -2080, -4425, -7640, -33791, -74856, 41176, -5288, 5879, -1952, 581, -222, 35, 1,
|
||||
-26, -208, -401, -2063, -4788, -7134, -35640, -74992, 39336, -5959, 5517, -2000, 519, -218, 31, 1,
|
||||
}
|
||||
|
||||
-- requantisation: Cc[res] = 65536 / steps (res -1 .. 17, stored at res + 2), Dc[res] = (steps - 1) / 2, bits per
|
||||
-- sample of the plain quantisers (res 8 .. 17)
|
||||
T.CC = {
|
||||
111.285962475327, 65536.000000000000, 21845.333333333332, 13107.200000000001, 9362.285714285713,
|
||||
7281.777777777777, 4369.066666666666, 2114.064516129032, 1040.253968253968, 516.031496062992, 257.003921568627,
|
||||
128.250489236790, 64.062561094819, 32.015632633121, 16.003907203907, 8.000976681723, 4.000244155527,
|
||||
2.000061037018, 1.000015259021,
|
||||
}
|
||||
T.DC = { 2, 0, 1, 2, 3, 4, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767 }
|
||||
T.RES_BIT = { [8] = 7, [9] = 8, [10] = 9, [11] = 10, [12] = 11, [13] = 12, [14] = 13, [15] = 14, [16] = 15, [17] = 16 }
|
||||
|
||||
-- log_dec(max): ceil(log2(max + 2)) bits and the unused codes (index max + 1, max = 0 .. 31)
|
||||
T.LOG2 = { 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6 }
|
||||
T.LOG2_LOST = { 0, 1, 0, 3, 2, 1, 0, 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 31 }
|
||||
|
||||
-- enum_dec: CNK[k][n + 1] = C(n, k) (k = 1 .. 16, n = 0 .. 31), the code length ceil(log2 C(n, k)) and the unused
|
||||
-- codes 2^len - C(n, k) (computed: libmpcdec's tables, whose last entry is 0)
|
||||
T.CNK, T.CNK_LEN, T.CNK_LOST = {}, {}, {}
|
||||
do
|
||||
for k = 1, 16 do
|
||||
local c, l, lost = table.create(32, 0), table.create(32, 0), table.create(32, 0)
|
||||
for n = 0, 32 do
|
||||
local v = 0
|
||||
if n >= k then
|
||||
v = 1
|
||||
for i = 1, k do
|
||||
v = v * (n - k + i) / i
|
||||
end
|
||||
v = math.floor(v + 0.5)
|
||||
end
|
||||
if n <= 31 then
|
||||
c[n + 1] = v
|
||||
end
|
||||
if n >= 1 then
|
||||
local bits = 0
|
||||
while 2 ^ bits < v do
|
||||
bits += 1
|
||||
end
|
||||
l[n] = bits
|
||||
lost[n] = if v > 0 then 2 ^ bits - v else 0
|
||||
end
|
||||
end
|
||||
T.CNK[k], T.CNK_LEN[k], T.CNK_LOST[k] = c, l, lost
|
||||
end
|
||||
T.CNK_LOST[16][32] = 0
|
||||
end
|
||||
|
||||
export type Lut = {
|
||||
len: { number }, -- 256 entries: code length when the 8-bit prefix decides the symbol, else 0
|
||||
val: { number }, -- the symbol, or the 1-based table entry to scan from
|
||||
codes: { number },
|
||||
lens: { number },
|
||||
vals: { number },
|
||||
sym: { number }?,
|
||||
}
|
||||
|
||||
-- lut(table, sym?) -> Lut
|
||||
function T.lut(tab: { number }, sym: { number }?): Lut
|
||||
local codes, lens, vals = {}, {}, {}
|
||||
for i = 1, #tab, 3 do
|
||||
table.insert(codes, tab[i])
|
||||
table.insert(lens, tab[i + 1])
|
||||
table.insert(vals, tab[i + 2])
|
||||
end
|
||||
local function find(code: number): number
|
||||
local j = 1
|
||||
while code < codes[j] do
|
||||
j += 1
|
||||
end
|
||||
return j
|
||||
end
|
||||
local function symbol(j: number, code: number): number
|
||||
if sym then
|
||||
local idx = bit32.band(vals[j] - bit32.rshift(code, 16 - lens[j]), 255)
|
||||
return sym[idx + 1] or 0
|
||||
end
|
||||
return vals[j]
|
||||
end
|
||||
local len, val = table.create(256, 0), table.create(256, 0)
|
||||
for p = 0, 255 do
|
||||
local lo, hi = find(p * 256), find(p * 256 + 255)
|
||||
if lo == hi and lens[lo] <= 8 then
|
||||
len[p + 1] = lens[lo]
|
||||
val[p + 1] = symbol(lo, p * 256)
|
||||
else
|
||||
len[p + 1] = 0
|
||||
val[p + 1] = hi
|
||||
end
|
||||
end
|
||||
return { len = len, val = val, codes = codes, lens = lens, vals = vals, sym = sym }
|
||||
end
|
||||
|
||||
return T
|
||||
@@ -0,0 +1,359 @@
|
||||
--!strict
|
||||
-- codecs/audio/Musepack: Musepack (MPC) stream versions 7 and 8: the stream headers (SV7's 32-bit word-swapped
|
||||
-- header, SV8's key / size packets: SH with its CRC, RG, EI, AP, SE), the frame / audio packet index, and the
|
||||
-- decoder (codecs/audio/Musepack/Decode: subband bitstream, requantisation, polyphase synthesis). A port of libmpcdec
|
||||
-- (musepack_src_r475: mpc_demux.c, streaminfo.c, mpc_decoder.c; BSD-3-Clause, (c) The Musepack Development Team,
|
||||
-- licenses/libmpcdec-BSD.txt), gapless like libmpcdec (the 481-sample synthesis delay and SV8's leading silence are
|
||||
-- dropped, the length is exact). Not supported: SV4 - SV6 (UNSUPPORTED), the SV8 seek table (the packets are indexed
|
||||
-- instead), chapters.
|
||||
--
|
||||
-- local s, err = Musepack.open(buf, start, limit) -- start: the "MP+" / "MPCK" magic (after an ID3v2 tag)
|
||||
-- -- s: { version, sampleRate, channels, frames, maxBand, ms, profile, encoder, gapless, gain, ... } plus the
|
||||
-- -- codecs/audio/Stream spec: count, start(i), decode(i), pcm(), reset(), skip, stop, preroll
|
||||
--
|
||||
-- Never throws: bad data returns nil, Err.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Decode = require("@formats/codecs/audio/Musepack/Decode")
|
||||
|
||||
local Musepack = {}
|
||||
|
||||
local RATES = { 44100, 48000, 37800, 32000 }
|
||||
local FRAME, DELAY, PAD = Decode.FRAME, Decode.DELAY, Decode.PAD
|
||||
local readu8 = buffer.readu8
|
||||
|
||||
export type Stream = {
|
||||
version: number,
|
||||
sampleRate: number,
|
||||
channels: number,
|
||||
frames: number, -- output sample frames (gapless)
|
||||
maxBand: number,
|
||||
ms: boolean,
|
||||
profile: number, -- SV7: the profile index (7 telephone .. 13 braindead); SV8: the quality (0 .. 15.875)
|
||||
encoder: number, -- encoder version (SV7: one byte; SV8: major * 2^24 + minor * 2^16 + build * 2^8)
|
||||
gapless: boolean,
|
||||
pns: boolean?,
|
||||
gain: { titleGain: number, titlePeak: number, albumGain: number, albumPeak: number }?,
|
||||
blockFrames: number, -- frames per packet (SV7: 1; SV8: 2^block_pwr)
|
||||
bytes: number, -- the stream's size in bytes (for the bitrate)
|
||||
-- the codecs/audio/Stream spec
|
||||
count: number,
|
||||
start: (i: number) -> number,
|
||||
decode: (i: number) -> (number?, Err.Err?),
|
||||
pcm: () -> { number },
|
||||
reset: () -> (),
|
||||
skip: number,
|
||||
stop: number,
|
||||
preroll: number,
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ SV7
|
||||
-- SV7 reads the stream as little-endian 32-bit words, most significant bit first: swap them into a padded copy
|
||||
local function swapped(buf: buffer, p: number, limit: number): buffer
|
||||
local n = limit - p
|
||||
local words = (n + 3) // 4
|
||||
local out = buffer.create(words * 4 + PAD)
|
||||
buffer.copy(out, 0, buf, p, n)
|
||||
for i = 0, words - 1 do
|
||||
buffer.writeu32(out, i * 4, bit32.byteswap(buffer.readu32(out, i * 4)))
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function sv7(buf: buffer, start: number, limit: number): (Stream?, Err.Err?)
|
||||
if limit - start < 32 then
|
||||
return nil, Err.new(Err.TRUNCATED, "SV7 header", start)
|
||||
end
|
||||
local ver = bit32.band(readu8(buf, start + 3), 15)
|
||||
if ver ~= 7 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "Musepack stream version " .. ver .. " (SV7 and SV8 only)", start)
|
||||
end
|
||||
local s = swapped(buf, start + 4, limit)
|
||||
local totalBits = (limit - start - 4) * 8
|
||||
local at = Decode.bitsAt
|
||||
local frames = at(s, 0, 16) * 65536 + at(s, 16, 16)
|
||||
local ms = at(s, 33, 1) == 1
|
||||
local maxBand = at(s, 34, 6)
|
||||
local profile = at(s, 40, 4)
|
||||
local rate = RATES[at(s, 46, 2) + 1]
|
||||
local gainTitle, peakTitle = at(s, 64, 16), at(s, 80, 16)
|
||||
local gainAlbum, peakAlbum = at(s, 96, 16), at(s, 112, 16)
|
||||
local gapless = at(s, 128, 1) == 1
|
||||
local last = at(s, 129, 11)
|
||||
local encoder = at(s, 160, 8)
|
||||
if maxBand == 0 or maxBand >= 32 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad band count " .. maxBand, start)
|
||||
end
|
||||
if last == 0 then
|
||||
last = FRAME
|
||||
elseif last > FRAME then
|
||||
return nil, Err.new(Err.CORRUPT, "bad last frame length", start)
|
||||
end
|
||||
if frames == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "no frames", start)
|
||||
end
|
||||
if frames > 2 ^ 24 then
|
||||
return nil, Err.new(Err.LIMIT, "more than 2^24 frames", start)
|
||||
end
|
||||
local samples = frames * FRAME - (if gapless then FRAME - last else DELAY)
|
||||
-- the frame index: a 20-bit size in front of each frame (the last one has 11 more bits: its length)
|
||||
local offs: { number }, sizes: { number } = {}, {}
|
||||
local pos = 168
|
||||
for i = 1, frames do
|
||||
if pos + 20 > totalBits then
|
||||
break
|
||||
end
|
||||
local size = at(s, pos, 20)
|
||||
local stop = pos + 20 + size + (if i == frames then 11 else 0)
|
||||
if stop > totalBits then
|
||||
break -- a truncated last frame
|
||||
end
|
||||
offs[i], sizes[i] = pos + 20, size
|
||||
pos = stop
|
||||
end
|
||||
local have = #offs
|
||||
if have == 0 then
|
||||
return nil, Err.new(Err.TRUNCATED, "no complete frame", start)
|
||||
end
|
||||
-- frames past the stream (a truncated file, or the synthesis tail of a gapless stream) decode as silence
|
||||
local need = math.min((samples + DELAY + FRAME - 1) // FRAME, have + 1)
|
||||
local stopAt = math.min(samples + DELAY, have * FRAME + (if have < frames then 0 else FRAME))
|
||||
local st = Decode.state(7, maxBand, ms, 2)
|
||||
local pcm = table.create(FRAME * 2, 0)
|
||||
local prev = 0
|
||||
local out: Stream = {
|
||||
version = 7,
|
||||
sampleRate = rate,
|
||||
channels = 2,
|
||||
frames = math.max(0, stopAt - DELAY),
|
||||
maxBand = maxBand,
|
||||
ms = ms,
|
||||
profile = profile,
|
||||
encoder = encoder,
|
||||
gapless = gapless,
|
||||
gain = { titleGain = gainTitle, titlePeak = peakTitle, albumGain = gainAlbum, albumPeak = peakAlbum },
|
||||
blockFrames = 1,
|
||||
bytes = limit - start,
|
||||
count = need,
|
||||
start = function(i: number): number
|
||||
return (i - 1) * FRAME
|
||||
end,
|
||||
decode = function(i: number): (number?, Err.Err?)
|
||||
if i ~= prev + 1 then
|
||||
Decode.reset(st, if i == 1 then 0 else 0x01010101)
|
||||
end
|
||||
prev = i
|
||||
local o: number? = offs[i]
|
||||
if o == nil then
|
||||
Decode.frame(st, s, -1, 0, false, pcm, 1)
|
||||
return FRAME, nil
|
||||
end
|
||||
local e, msg = Decode.frame(st, s, o, o + sizes[i], false, pcm, 1)
|
||||
if not e then
|
||||
return nil, Err.from(msg, start + 4 + o // 8)
|
||||
end
|
||||
if e ~= o + sizes[i] then
|
||||
return nil, Err.new(Err.CORRUPT, "frame " .. i .. " has the wrong size", start + 4 + o // 8)
|
||||
end
|
||||
return FRAME, nil
|
||||
end,
|
||||
pcm = function(): { number }
|
||||
return pcm
|
||||
end,
|
||||
reset = function()
|
||||
prev = -1
|
||||
end,
|
||||
skip = DELAY,
|
||||
stop = stopAt,
|
||||
preroll = 32,
|
||||
}
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ SV8
|
||||
-- a packet size: 7 bits per byte, most significant first, bit 7 = more
|
||||
local function varint(buf: buffer, p: number, limit: number): (number, number)
|
||||
local v = 0
|
||||
for k = 0, 7 do
|
||||
if p + k >= limit then
|
||||
return -1, p
|
||||
end
|
||||
local b = readu8(buf, p + k)
|
||||
v = v * 128 + bit32.band(b, 127)
|
||||
if b < 128 then
|
||||
return v, p + k + 1
|
||||
end
|
||||
end
|
||||
return -1, p
|
||||
end
|
||||
|
||||
local function sv8(buf: buffer, start: number, limit: number): (Stream?, Err.Err?)
|
||||
local p = start + 4
|
||||
local sh: { [string]: any }? = nil
|
||||
local gain, pns, profile, encoder = nil, nil, 0, 0
|
||||
local apOff: { number }, apSize: { number } = {}, {}
|
||||
while p + 2 < limit do
|
||||
local k1, k2 = readu8(buf, p), readu8(buf, p + 1)
|
||||
if k1 < 65 or k1 > 90 or k2 < 65 or k2 > 90 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad packet key", p)
|
||||
end
|
||||
local key = buffer.readstring(buf, p, 2)
|
||||
local size, body = varint(buf, p + 2, limit)
|
||||
if size < 0 or size < body - p then
|
||||
return nil, Err.new(Err.CORRUPT, "bad packet size", p)
|
||||
end
|
||||
local stop = p + size
|
||||
if stop > limit then
|
||||
if key == "AP" then
|
||||
break -- a truncated last packet
|
||||
end
|
||||
return nil, Err.new(Err.TRUNCATED, key .. " packet", p)
|
||||
end
|
||||
if key == "SH" then
|
||||
if stop - body < 6 then
|
||||
return nil, Err.new(Err.CORRUPT, "short stream header", p)
|
||||
end
|
||||
local crc = buffer.readu32(buf, body)
|
||||
crc = bit32.byteswap(crc)
|
||||
if Crc32.of(buf, body + 4, stop - body - 4) ~= crc then
|
||||
return nil, Err.new(Err.CHECKSUM, "stream header CRC", p)
|
||||
end
|
||||
if readu8(buf, body + 4) ~= 8 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "Musepack stream version " .. readu8(buf, body + 4), p)
|
||||
end
|
||||
local samples, q = varint(buf, body + 5, stop)
|
||||
local silence, q2 = varint(buf, q, stop)
|
||||
if samples < 0 or silence < 0 or q2 + 2 > stop then
|
||||
return nil, Err.new(Err.CORRUPT, "bad stream header", p)
|
||||
end
|
||||
local b0, b1 = readu8(buf, q2), readu8(buf, q2 + 1)
|
||||
sh = {
|
||||
samples = samples,
|
||||
silence = silence,
|
||||
rate = RATES[bit32.rshift(b0, 5) + 1],
|
||||
maxBand = bit32.band(b0, 31) + 1,
|
||||
channels = bit32.rshift(b1, 4) + 1,
|
||||
ms = bit32.band(b1, 8) ~= 0,
|
||||
blockPwr = bit32.band(b1, 7) * 2,
|
||||
}
|
||||
elseif key == "RG" and stop - body >= 9 and readu8(buf, body) == 1 then
|
||||
local function u16(o: number): number
|
||||
return readu8(buf, body + o) * 256 + readu8(buf, body + o + 1)
|
||||
end
|
||||
gain = { titleGain = u16(1), titlePeak = u16(3), albumGain = u16(5), albumPeak = u16(7) }
|
||||
elseif key == "EI" and stop - body >= 4 then
|
||||
local b = readu8(buf, body)
|
||||
profile = bit32.rshift(b, 1) / 8
|
||||
pns = bit32.band(b, 1) == 1
|
||||
encoder = readu8(buf, body + 1) * 2 ^ 24 + readu8(buf, body + 2) * 2 ^ 16 + readu8(buf, body + 3) * 2 ^ 8
|
||||
elseif key == "AP" then
|
||||
table.insert(apOff, body)
|
||||
table.insert(apSize, stop - body)
|
||||
elseif key == "SE" then
|
||||
break
|
||||
end
|
||||
p = stop
|
||||
end
|
||||
if not sh then
|
||||
return nil, Err.new(Err.CORRUPT, "no stream header", start)
|
||||
end
|
||||
local h = sh :: { [string]: any }
|
||||
local samples, silence, maxBand, channels = h.samples, h.silence, h.maxBand, h.channels
|
||||
if maxBand >= 32 or channels > 2 or silence > samples then
|
||||
return nil, Err.new(Err.UNSUPPORTED, string.format("%d bands, %d channels", maxBand, channels), start)
|
||||
end
|
||||
if samples > 2 ^ 34 then
|
||||
return nil, Err.new(Err.LIMIT, "too many samples", start)
|
||||
end
|
||||
if #apOff == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "no audio packet", start)
|
||||
end
|
||||
local per = 2 ^ h.blockPwr
|
||||
if per * FRAME * channels > 2 ^ 22 then
|
||||
return nil, Err.new(Err.LIMIT, per .. " frames per audio packet", start)
|
||||
end
|
||||
local needFrames = (samples + DELAY + FRAME - 1) // FRAME
|
||||
local count = math.min(#apOff, (needFrames + per - 1) // per)
|
||||
local stopAt = math.min(samples + DELAY, count * per * FRAME)
|
||||
local st = Decode.state(8, maxBand, h.ms, channels)
|
||||
local pcm = table.create(per * FRAME * channels, 0)
|
||||
local scratch = buffer.create(0)
|
||||
local out: Stream = {
|
||||
version = 8,
|
||||
sampleRate = h.rate,
|
||||
channels = channels,
|
||||
frames = math.max(0, stopAt - DELAY - silence),
|
||||
maxBand = maxBand,
|
||||
ms = h.ms,
|
||||
profile = profile,
|
||||
encoder = encoder,
|
||||
gapless = true,
|
||||
pns = pns,
|
||||
gain = gain,
|
||||
blockFrames = per,
|
||||
bytes = limit - start,
|
||||
count = count,
|
||||
start = function(i: number): number
|
||||
return (i - 1) * per * FRAME
|
||||
end,
|
||||
decode = function(i: number): (number?, Err.Err?)
|
||||
local o: number, size: number = apOff[i], apSize[i]
|
||||
if buffer.len(scratch) < size + PAD then
|
||||
scratch = buffer.create(size + PAD)
|
||||
end
|
||||
buffer.copy(scratch, 0, buf, o, size)
|
||||
local nf = math.min(per, needFrames - (i - 1) * per)
|
||||
local pos = 0
|
||||
for f = 1, nf do
|
||||
local e, msg = Decode.frame(st, scratch, pos, size * 8, f == 1, pcm, (f - 1) * FRAME * channels + 1)
|
||||
if not e then
|
||||
return nil, Err.from(msg, o)
|
||||
end
|
||||
pos = e
|
||||
end
|
||||
if nf == per and size * 8 - pos > 7 then
|
||||
return nil, Err.new(Err.CORRUPT, "audio packet " .. i .. " has unused data", o)
|
||||
end
|
||||
return nf * FRAME, nil
|
||||
end,
|
||||
pcm = function(): { number }
|
||||
return pcm
|
||||
end,
|
||||
reset = function()
|
||||
Decode.reset(st, 0)
|
||||
end,
|
||||
skip = DELAY + silence,
|
||||
stop = stopAt,
|
||||
preroll = 1,
|
||||
}
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- magic(buf, p, limit) -> 7 | 8 | 0 (other: "MP+" with another version is 7's family, reported by open)
|
||||
function Musepack.magic(buf: buffer, p: number, limit: number): number
|
||||
if p + 4 > limit then
|
||||
return 0
|
||||
end
|
||||
local m = buffer.readstring(buf, p, 4)
|
||||
if m == "MPCK" then
|
||||
return 8
|
||||
end
|
||||
if string.sub(m, 1, 3) == "MP+" then
|
||||
return 7
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- open(buf, start, limit) -> Stream | nil, Err
|
||||
function Musepack.open(buf: buffer, start: number, limit: number): (Stream?, Err.Err?)
|
||||
local v = Musepack.magic(buf, start, limit)
|
||||
if v == 8 then
|
||||
return sv8(buf, start, limit)
|
||||
elseif v == 7 then
|
||||
return sv7(buf, start, limit)
|
||||
end
|
||||
return nil, Err.new(Err.CORRUPT, "not a Musepack stream", start)
|
||||
end
|
||||
|
||||
return Musepack
|
||||
@@ -0,0 +1,297 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/audio/Qoa: the "Quite OK Audio" codec (QOA): frames of up to 256 slices per channel, each slice a 4-bit scale
|
||||
-- factor and 20 3-bit residuals over a 4-tap sign-sign LMS predictor. Ported from qoa.h (phoboslab/qoa, Dominic
|
||||
-- Szablewski, MIT: licenses/qoa-LICENSE.txt): the tables, the predictor, the decoder and the encoder's brute-force
|
||||
-- scale factor search, so encoding is byte-for-byte qoa.h's (including its 32-bit wrap in the reciprocal division).
|
||||
-- The 64-bit slices are handled as two 32-bit halves.
|
||||
--
|
||||
-- local info = Qoa.frameInfo(buf, p, avail) -- { channels, rate, samples, size } | nil, message
|
||||
-- local n, msg = Qoa.decodeFrame(buf, p, avail, dst, d) -- one frame -> interleaved f32 at float index d
|
||||
-- local size = Qoa.encodeFrame(x, xf, n, ch, rate, lms, out, p) -- n frames of f32 at frame xf -> bytes at out[p]
|
||||
-- local lms = Qoa.newLms(ch) -- the encoder state (history 0, weights 0, 0, -1, 2)
|
||||
--
|
||||
-- Never throws: decodeFrame checks the frame against avail before reading; encodeFrame needs Qoa.frameSize bytes.
|
||||
local readu8, readu32, readf32, writef32, writeu32 = buffer.readu8, buffer.readu32, buffer.readf32, buffer.writef32, buffer.writeu32
|
||||
local readi32, writei32 = buffer.readi32, buffer.writei32
|
||||
local band, rshift, bor, lshift, byteswap = bit32.band, bit32.rshift, bit32.bor, bit32.lshift, bit32.byteswap
|
||||
local floor = math.floor
|
||||
|
||||
local Qoa = {}
|
||||
|
||||
Qoa.SLICE_LEN = 20
|
||||
Qoa.SLICES_PER_FRAME = 256
|
||||
Qoa.FRAME_LEN = 256 * 20
|
||||
Qoa.MAX_CHANNELS = 255
|
||||
|
||||
local QUANT = { 7, 7, 7, 5, 5, 3, 3, 1, 0, 0, 2, 2, 4, 4, 6, 6, 6 } -- residual -8 .. 8 -> code
|
||||
local RECIP = { 65536, 9363, 3121, 1457, 781, 475, 311, 216, 156, 117, 90, 71, 57, 47, 39, 32 }
|
||||
-- DEQ[sf * 8 + q + 1]
|
||||
local DEQ = {
|
||||
1, -1, 3, -3, 5, -5, 7, -7,
|
||||
5, -5, 18, -18, 32, -32, 49, -49,
|
||||
16, -16, 53, -53, 95, -95, 147, -147,
|
||||
34, -34, 113, -113, 203, -203, 315, -315,
|
||||
63, -63, 210, -210, 378, -378, 588, -588,
|
||||
104, -104, 345, -345, 621, -621, 966, -966,
|
||||
158, -158, 528, -528, 950, -950, 1477, -1477,
|
||||
228, -228, 760, -760, 1368, -1368, 2128, -2128,
|
||||
316, -316, 1053, -1053, 1895, -1895, 2947, -2947,
|
||||
422, -422, 1405, -1405, 2529, -2529, 3934, -3934,
|
||||
548, -548, 1828, -1828, 3290, -3290, 5117, -5117,
|
||||
696, -696, 2320, -2320, 4176, -4176, 6496, -6496,
|
||||
868, -868, 2893, -2893, 5207, -5207, 8099, -8099,
|
||||
1064, -1064, 3548, -3548, 6386, -6386, 9933, -9933,
|
||||
1286, -1286, 4288, -4288, 7718, -7718, 12005, -12005,
|
||||
1536, -1536, 5120, -5120, 9216, -9216, 14336, -14336,
|
||||
}
|
||||
|
||||
local function be32(b: buffer, p: number): number
|
||||
return byteswap(readu32(b, p))
|
||||
end
|
||||
|
||||
local function s16(v: number): number
|
||||
return if v >= 32768 then v - 65536 else v
|
||||
end
|
||||
|
||||
-- frameSize(channels, slices) -> bytes
|
||||
function Qoa.frameSize(ch: number, slices: number): number
|
||||
return 8 + 16 * ch + 8 * slices * ch
|
||||
end
|
||||
|
||||
export type FrameInfo = { channels: number, rate: number, samples: number, size: number }
|
||||
|
||||
-- frameInfo(buf, p, avail) -> the frame header's facts, checked against avail and the slice count | nil, message
|
||||
function Qoa.frameInfo(b: buffer, p: number, avail: number): (FrameInfo?, string?)
|
||||
if avail < 8 then
|
||||
return nil, "truncated frame header"
|
||||
end
|
||||
local hi, lo = be32(b, p), be32(b, p + 4)
|
||||
local ch = rshift(hi, 24)
|
||||
local rate = band(hi, 0xFFFFFF)
|
||||
local samples = rshift(lo, 16)
|
||||
local size = band(lo, 0xFFFF)
|
||||
if ch == 0 or rate == 0 or samples == 0 then
|
||||
return nil, "bad frame header"
|
||||
end
|
||||
local slices = (samples + 19) // 20
|
||||
local head = 8 + 16 * ch
|
||||
if slices > 256 or size < head or slices * ch > (size - head) // 8 then
|
||||
return nil, "bad frame size"
|
||||
end
|
||||
if size > avail then
|
||||
return nil, "truncated frame"
|
||||
end
|
||||
return { channels = ch, rate = rate, samples = samples, size = size }, nil
|
||||
end
|
||||
|
||||
-- decodeFrame(buf, p, avail, dst, d) -> samples per channel, frame bytes | nil, message: one frame (its own LMS state
|
||||
-- in the header) as interleaved f32 into dst from float index d (dst holds samples * channels floats there)
|
||||
function Qoa.decodeFrame(b: buffer, p: number, avail: number, dst: buffer, d: number): (number?, number | string)
|
||||
local info, msg = Qoa.frameInfo(b, p, avail)
|
||||
if not info then
|
||||
return nil, msg :: string
|
||||
end
|
||||
local ch, samples = info.channels, info.samples
|
||||
for c = 0, ch - 1 do
|
||||
local lp = p + 8 + c * 16
|
||||
local hA, hB, hC, hD = be32(b, lp), be32(b, lp + 4), be32(b, lp + 8), be32(b, lp + 12)
|
||||
local h0, h1, h2, h3 = s16(rshift(hA, 16)), s16(band(hA, 0xFFFF)), s16(rshift(hB, 16)), s16(band(hB, 0xFFFF))
|
||||
local w0, w1, w2, w3 = s16(rshift(hC, 16)), s16(band(hC, 0xFFFF)), s16(rshift(hD, 16)), s16(band(hD, 0xFFFF))
|
||||
local sp = p + 8 + 16 * ch + c * 8
|
||||
local o = (d + c) * 4
|
||||
local os = ch * 4
|
||||
local s0 = 0
|
||||
while s0 < samples do
|
||||
local hi, lo = be32(b, sp), be32(b, sp + 4)
|
||||
local base = rshift(hi, 28) * 8 + 1
|
||||
local n = math.min(20, samples - s0)
|
||||
for k = 0, n - 1 do
|
||||
local q
|
||||
if k < 9 then
|
||||
q = band(rshift(hi, 25 - 3 * k), 7)
|
||||
elseif k == 9 then
|
||||
q = band(hi, 1) * 4 + rshift(lo, 30)
|
||||
else
|
||||
q = band(rshift(lo, 57 - 3 * k), 7)
|
||||
end
|
||||
local pred = (w0 * h0 + w1 * h1 + w2 * h2 + w3 * h3) // 8192
|
||||
local dq = DEQ[base + q]
|
||||
local r = pred + dq
|
||||
if r > 32767 then
|
||||
r = 32767
|
||||
elseif r < -32768 then
|
||||
r = -32768
|
||||
end
|
||||
writef32(dst, o, r / 32768)
|
||||
o += os
|
||||
local delta = dq // 16
|
||||
w0 += if h0 < 0 then -delta else delta
|
||||
w1 += if h1 < 0 then -delta else delta
|
||||
w2 += if h2 < 0 then -delta else delta
|
||||
w3 += if h3 < 0 then -delta else delta
|
||||
h0, h1, h2, h3 = h1, h2, h3, r
|
||||
end
|
||||
s0 += 20
|
||||
sp += 8 * ch
|
||||
end
|
||||
end
|
||||
return samples, info.size
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encoder
|
||||
-- newLms(ch) -> the encoder's LMS state: 8 i32 per channel (history 0..3, weights 0..3), weights 0, 0, -1, 2 (<< 13)
|
||||
function Qoa.newLms(ch: number): buffer
|
||||
local st = buffer.create(32 * ch)
|
||||
for c = 0, ch - 1 do
|
||||
writei32(st, c * 32 + 24, -8192)
|
||||
writei32(st, c * 32 + 28, 16384)
|
||||
end
|
||||
return st
|
||||
end
|
||||
|
||||
-- the nearest s16 to x * 32768 (NaN -> 0)
|
||||
local function toS16(x: number): number
|
||||
local v = floor(x * 32768 + 0.5)
|
||||
if v ~= v then
|
||||
return 0
|
||||
elseif v > 32767 then
|
||||
return 32767
|
||||
elseif v < -32768 then
|
||||
return -32768
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
-- qoa.h's qoa_div: a rounding division by the scale factor through its .16 reciprocal (in 32-bit int arithmetic, which
|
||||
-- wraps for big residuals at scale factor 0), rounding away from zero
|
||||
local function qdiv(v: number, sf: number): number
|
||||
local x = v * RECIP[sf + 1] + 32768
|
||||
if x >= 2147483648 or x < -2147483648 then
|
||||
x = (x + 2147483648) % 4294967296 - 2147483648
|
||||
end
|
||||
local n = x // 65536
|
||||
local sv = if v > 0 then 1 elseif v < 0 then -1 else 0
|
||||
local sn = if n > 0 then 1 elseif n < 0 then -1 else 0
|
||||
return n + sv - sn
|
||||
end
|
||||
|
||||
-- encodeFrame(x, xf, n, ch, rate, lms, out, p) -> bytes written: frames xf .. xf + n - 1 (n <= 5120) of interleaved f32 x
|
||||
-- as one QOA frame at out[p] (Qoa.frameSize(ch, ceil(n / 20)) bytes); lms carries the encoder state between frames
|
||||
function Qoa.encodeFrame(x: buffer, xf: number, n: number, ch: number, rate: number, lms: buffer, out: buffer, p: number): number
|
||||
local slices = (n + 19) // 20
|
||||
local size = Qoa.frameSize(ch, slices)
|
||||
writeu32(out, p, byteswap(bor(lshift(ch, 24), rate)))
|
||||
writeu32(out, p + 4, byteswap(bor(lshift(n, 16), size)))
|
||||
for c = 0, ch - 1 do
|
||||
local so = c * 32
|
||||
-- the history and weights as big-endian i16 x 4
|
||||
for i = 0, 3 do
|
||||
local hv = band(readi32(lms, so + i * 4), 0xFFFF)
|
||||
local wv = band(readi32(lms, so + 16 + i * 4), 0xFFFF)
|
||||
buffer.writeu8(out, p + 8 + c * 16 + i * 2, rshift(hv, 8))
|
||||
buffer.writeu8(out, p + 8 + c * 16 + i * 2 + 1, band(hv, 255))
|
||||
buffer.writeu8(out, p + 8 + c * 16 + 8 + i * 2, rshift(wv, 8))
|
||||
buffer.writeu8(out, p + 8 + c * 16 + 8 + i * 2 + 1, band(wv, 255))
|
||||
end
|
||||
end
|
||||
local xs = table.create(20, 0)
|
||||
local codes = table.create(20, 0)
|
||||
local best = table.create(20, 0)
|
||||
local prevSf = table.create(ch, 0)
|
||||
local sp = p + 8 + 16 * ch
|
||||
for s = 0, slices - 1 do
|
||||
local len = math.min(20, n - s * 20)
|
||||
for c = 0, ch - 1 do
|
||||
for k = 1, len do
|
||||
xs[k] = toS16(readf32(x, ((xf + s * 20 + k - 1) * ch + c) * 4))
|
||||
end
|
||||
local so = c * 32
|
||||
local H0, H1, H2, H3 = readi32(lms, so), readi32(lms, so + 4), readi32(lms, so + 8), readi32(lms, so + 12)
|
||||
local W0, W1, W2, W3 = readi32(lms, so + 16), readi32(lms, so + 20), readi32(lms, so + 24), readi32(lms, so + 28)
|
||||
local bestRank, bestSf = math.huge, 0
|
||||
local b0, b1, b2, b3, bw0, bw1, bw2, bw3 = H0, H1, H2, H3, W0, W1, W2, W3
|
||||
for sfi = 0, 15 do
|
||||
local sf = (sfi + prevSf[c + 1]) % 16
|
||||
local h0, h1, h2, h3, w0, w1, w2, w3 = H0, H1, H2, H3, W0, W1, W2, W3
|
||||
local rank = 0
|
||||
local base = sf * 8 + 1
|
||||
for k = 1, len do
|
||||
local v = xs[k]
|
||||
local pred = (w0 * h0 + w1 * h1 + w2 * h2 + w3 * h3) // 8192
|
||||
local res = v - pred
|
||||
local sc = qdiv(res, sf)
|
||||
if sc > 8 then
|
||||
sc = 8
|
||||
elseif sc < -8 then
|
||||
sc = -8
|
||||
end
|
||||
local q = QUANT[sc + 9]
|
||||
local dq = DEQ[base + q]
|
||||
local r = pred + dq
|
||||
if r > 32767 then
|
||||
r = 32767
|
||||
elseif r < -32768 then
|
||||
r = -32768
|
||||
end
|
||||
local sq = w0 * w0 + w1 * w1 + w2 * w2 + w3 * w3
|
||||
if sq >= 2147483648 then -- C int arithmetic
|
||||
sq = (sq + 2147483648) % 4294967296 - 2147483648
|
||||
end
|
||||
local pen = sq // 262144 - 0x8ff
|
||||
if pen < 0 then
|
||||
pen = 0
|
||||
end
|
||||
local e = v - r
|
||||
rank += e * e + pen * pen
|
||||
if rank > bestRank then
|
||||
break
|
||||
end
|
||||
local delta = dq // 16
|
||||
w0 += if h0 < 0 then -delta else delta
|
||||
w1 += if h1 < 0 then -delta else delta
|
||||
w2 += if h2 < 0 then -delta else delta
|
||||
w3 += if h3 < 0 then -delta else delta
|
||||
h0, h1, h2, h3 = h1, h2, h3, r
|
||||
codes[k] = q
|
||||
end
|
||||
if rank < bestRank then
|
||||
bestRank, bestSf = rank, sf
|
||||
b0, b1, b2, b3, bw0, bw1, bw2, bw3 = h0, h1, h2, h3, w0, w1, w2, w3
|
||||
for k = 1, len do
|
||||
best[k] = codes[k]
|
||||
end
|
||||
end
|
||||
end
|
||||
prevSf[c + 1] = bestSf
|
||||
writei32(lms, so, b0)
|
||||
writei32(lms, so + 4, b1)
|
||||
writei32(lms, so + 8, b2)
|
||||
writei32(lms, so + 12, b3)
|
||||
writei32(lms, so + 16, bw0)
|
||||
writei32(lms, so + 20, bw1)
|
||||
writei32(lms, so + 24, bw2)
|
||||
writei32(lms, so + 28, bw3)
|
||||
-- the slice: sf in the top 4 bits, then the codes, unused codes 0
|
||||
local hi, lo = bestSf * 268435456, 0
|
||||
for k = 0, 19 do
|
||||
local q = if k < len then best[k + 1] else 0
|
||||
if k < 9 then
|
||||
hi += q * 2 ^ (25 - 3 * k)
|
||||
elseif k == 9 then
|
||||
hi += rshift(q, 2)
|
||||
lo += band(q, 3) * 1073741824
|
||||
else
|
||||
lo += q * 2 ^ (57 - 3 * k)
|
||||
end
|
||||
end
|
||||
writeu32(out, sp, byteswap(hi))
|
||||
writeu32(out, sp + 4, byteswap(lo))
|
||||
sp += 8
|
||||
end
|
||||
end
|
||||
return size
|
||||
end
|
||||
|
||||
return Qoa
|
||||
@@ -10,11 +10,13 @@
|
||||
-- count = n, -- frames, duration, bitrate, tags, ...); read / seek / position
|
||||
-- start = function(i) return ... end, -- are added. start(i): packet i's first frame (absolute, before
|
||||
-- decode = function(i) return n, err end,-- trimming); decode(i) -> frames | nil, Err, the samples in pcm()
|
||||
-- pcm = function() return floats end, -- (interleaved, 1-based) until the next decode
|
||||
-- pcm = function() return floats end, -- (interleaved, 1-based; or a buffer of f32) until the next decode
|
||||
-- reset = function() end, -- forget codec state (before a seek)
|
||||
-- skip = priming, stop = lastFrame, -- output = absolute frames [skip, stop)
|
||||
-- preroll = 1, -- packets decoded before the one holding a seek target (AAC: 1)
|
||||
-- })
|
||||
-- scale = 1 / 32768, -- optional: read() writes pcm() values * scale (default 1)
|
||||
-- ints = true, -- optional: pcm() holds integers; adds dec:readInt(n, out?), the
|
||||
-- }) -- same frames as read() as i32 (bit-exact checks)
|
||||
--
|
||||
-- A decode failure ends the stream and is kept in dec.error (Pcm.drain reports it); a failing first packet is
|
||||
-- returned by packets() as the open error. Never throws.
|
||||
@@ -26,12 +28,14 @@ export type Spec = {
|
||||
count: number,
|
||||
start: (i: number) -> number,
|
||||
decode: (i: number) -> (number?, Err.Err?),
|
||||
pcm: () -> { number },
|
||||
pcm: () -> { number } | buffer, -- a buffer: interleaved f32 from byte 0
|
||||
reset: () -> (),
|
||||
skip: number?, -- default 0
|
||||
stop: number?, -- default start(count + 1)
|
||||
preroll: number?, -- default 0
|
||||
cumulative: boolean?, -- frames after a packet = frames before + its output (default: start(i) + its output)
|
||||
scale: number?, -- read() writes pcm() values times this (default 1)
|
||||
ints: boolean?, -- pcm() values are integers: dec:readInt(n, out?) returns them as i32
|
||||
}
|
||||
|
||||
-- packets(dec, spec) -> dec (with read / seek / position) | nil, Err (the first packet failed)
|
||||
@@ -75,12 +79,13 @@ function Stream.packets(dec: any, spec: Spec): (any, Err.Err?)
|
||||
end
|
||||
end
|
||||
|
||||
function dec.read(_self: any, n: number, out: buffer?): (buffer, number)
|
||||
local scale = spec.scale or 1
|
||||
local function pull(n: number, out: buffer?, asInt: boolean): (buffer, number)
|
||||
local want = math.max(0, math.floor(n))
|
||||
local need = want * ch * 4
|
||||
local ob = if out and buffer.len(out) >= need then out else buffer.create(need)
|
||||
local got = 0
|
||||
local writef32 = buffer.writef32
|
||||
local writef32, writei32 = buffer.writef32, buffer.writei32
|
||||
while got < want do
|
||||
if pendPos >= pendN then
|
||||
if failed or not fill() then
|
||||
@@ -91,9 +96,35 @@ function Stream.packets(dec: any, spec: Spec): (any, Err.Err?)
|
||||
local src = pcmOf()
|
||||
local q = got * ch * 4
|
||||
local s = pendPos * ch
|
||||
for k = 1, take * ch do
|
||||
writef32(ob, q, src[s + k])
|
||||
q += 4
|
||||
if type(src) == "buffer" then
|
||||
if scale == 1 and not asInt then
|
||||
buffer.copy(ob, q, src, s * 4, take * ch * 4)
|
||||
else
|
||||
for k = 0, take * ch - 1 do
|
||||
local v = buffer.readf32(src, (s + k) * 4)
|
||||
if asInt then
|
||||
writei32(ob, q, v)
|
||||
else
|
||||
writef32(ob, q, v * scale)
|
||||
end
|
||||
q += 4
|
||||
end
|
||||
end
|
||||
elseif asInt then
|
||||
for k = 1, take * ch do
|
||||
writei32(ob, q, src[s + k])
|
||||
q += 4
|
||||
end
|
||||
elseif scale == 1 then
|
||||
for k = 1, take * ch do
|
||||
writef32(ob, q, src[s + k])
|
||||
q += 4
|
||||
end
|
||||
else
|
||||
for k = 1, take * ch do
|
||||
writef32(ob, q, src[s + k] * scale)
|
||||
q += 4
|
||||
end
|
||||
end
|
||||
pendPos += take
|
||||
got += take
|
||||
@@ -102,6 +133,15 @@ function Stream.packets(dec: any, spec: Spec): (any, Err.Err?)
|
||||
return ob, got
|
||||
end
|
||||
|
||||
function dec.read(_self: any, n: number, out: buffer?): (buffer, number)
|
||||
return pull(n, out, false)
|
||||
end
|
||||
if spec.ints then
|
||||
function dec.readInt(_self: any, n: number, out: buffer?): (buffer, number)
|
||||
return pull(n, out, true)
|
||||
end
|
||||
end
|
||||
|
||||
function dec.seek(_self: any, seconds: number)
|
||||
local sec = if type(seconds) == "number" and seconds == seconds then seconds else 0
|
||||
local target = math.clamp(math.floor(sec * sr + 0.5), 0, frames) + skip -- absolute frame
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
--!strict
|
||||
-- codecs/audio/Tracker/Load: helpers shared by the tracker loaders that map another format's effects onto one of the
|
||||
-- engine's families (music/mtm, 669, stm, ult, okt, med, ptm, far). Effects are first named the way OpenMPT's loaders
|
||||
-- name them ("portaup", "volslide", "modex", ...), then written in the family's own cell coding: S3M / IT letter
|
||||
-- codes (A = 1) with the IT volume column, or MOD / XM numbers. Ported from OpenMPT's ModCommand helpers
|
||||
-- (ConvertModCommand, ConvertToVolCommand, FillInTwoCommands, GetEffectWeight, CPattern::WriteEffect; BSD licence,
|
||||
-- licenses/openmpt-LICENSE.txt), reduced to what the engine plays.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Player = require("@formats/codecs/audio/Tracker/Player")
|
||||
local Pcm = require("@formats/codecs/audio/Tracker/Pcm")
|
||||
local Tables = require("@formats/codecs/audio/Tracker/Tables")
|
||||
|
||||
local Load = {}
|
||||
|
||||
local EXT = Player.EXT
|
||||
|
||||
-- the S3M / IT letter code of each effect name (engine extension effects included)
|
||||
local IT: { [string]: number } = {
|
||||
speed = 1,
|
||||
jump = 2,
|
||||
["break"] = 3,
|
||||
volslide = 4,
|
||||
portadown = 5,
|
||||
portaup = 6,
|
||||
toneporta = 7,
|
||||
vibrato = 8,
|
||||
tremor = 9,
|
||||
arpeggio = 10,
|
||||
vibratovol = 11,
|
||||
toneportavol = 12,
|
||||
chanvol = 13,
|
||||
chanvolslide = 14,
|
||||
offset = 15,
|
||||
panslide = 16,
|
||||
retrig = 17,
|
||||
tremolo = 18,
|
||||
s3mex = 19,
|
||||
tempo = 20,
|
||||
finevibrato = 21,
|
||||
globalvol = 22,
|
||||
globalvolslide = 23,
|
||||
panning8 = 24,
|
||||
panbrello = 25,
|
||||
noteslideup = EXT.NOTE_SLIDE_UP,
|
||||
noteslidedown = EXT.NOTE_SLIDE_DOWN,
|
||||
noteslideupretrig = EXT.NOTE_SLIDE_UP_RETRIG,
|
||||
noteslidedownretrig = EXT.NOTE_SLIDE_DOWN_RETRIG,
|
||||
autoportaup = EXT.AUTO_PORTA_UP,
|
||||
autoportadown = EXT.AUTO_PORTA_DOWN,
|
||||
freqadjust = EXT.FREQ_ADJUST,
|
||||
}
|
||||
Load.IT = IT
|
||||
|
||||
-- OpenMPT's effect weights (low to high): which of two effects a cell keeps when only one fits
|
||||
local WEIGHT: { [string]: number } = {}
|
||||
for i, n in
|
||||
{
|
||||
"none", "keyoff", "tremolo", "finevibrato", "vibrato", "panbrello", "s3mex", "modex", "panslide", "panning8",
|
||||
"noteslideupretrig", "noteslideup", "noteslidedownretrig", "noteslidedown", "portaup", "autoportaup",
|
||||
"portadown", "autoportadown", "volslide", "vibratovol", "volume", "volume8", "offset", "tremor", "retrig",
|
||||
"arpeggio", "toneporta", "toneportavol", "chanvolslide", "chanvol", "globalvolslide", "globalvol", "tempo",
|
||||
"speed", "jump", "break",
|
||||
}
|
||||
do
|
||||
WEIGHT[n] = i
|
||||
end
|
||||
|
||||
local GLOBAL = { jump = true, ["break"] = true, speed = true, tempo = true, globalvol = true, globalvolslide = true }
|
||||
|
||||
-- isGlobal(name, param) -> the effect acts on the whole song (OpenMPT's IsGlobalCommand)
|
||||
function Load.isGlobal(name: string?, param: number): boolean
|
||||
if name == nil then
|
||||
return false
|
||||
end
|
||||
if GLOBAL[name] then
|
||||
return true
|
||||
end
|
||||
local x = param // 16
|
||||
if name == "modex" then
|
||||
return x == 0 or x == 6 or x == 0xE
|
||||
elseif name == "s3mex" then
|
||||
return x == 6 or x == 0xB or x == 0xE
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
-- modCommand(cmd, param) -> name?, param: a MOD / XM effect number (0..F, XM letters 16..) by name (ConvertModCommand)
|
||||
local MODFX: { [number]: string } = {
|
||||
[0] = "arpeggio", [1] = "portaup", [2] = "portadown", [3] = "toneporta", [4] = "vibrato", [5] = "toneportavol",
|
||||
[6] = "vibratovol", [7] = "tremolo", [8] = "panning8", [9] = "offset", [10] = "volslide", [11] = "jump",
|
||||
[12] = "volume", [13] = "break", [14] = "modex", [15] = "tempo", [16] = "globalvol", [17] = "globalvolslide",
|
||||
[20] = "keyoff", [25] = "panslide", [27] = "retrig", [29] = "tremor",
|
||||
}
|
||||
function Load.modCommand(cmd: number, param: number): (string?, number)
|
||||
if cmd == 0 and param == 0 then
|
||||
return nil, 0
|
||||
elseif cmd == 0xF and param < 0x20 then
|
||||
return "speed", param
|
||||
end
|
||||
local n = MODFX[cmd]
|
||||
if n == "break" then
|
||||
param = (param // 16) * 10 + param % 16
|
||||
end
|
||||
return n, param
|
||||
end
|
||||
|
||||
-- itVolume(name, param, force) -> the IT volume-column byte + 1 (the engine's coding) for an effect that fits there,
|
||||
-- or nil (OpenMPT's ConvertToVolCommand; force: fit it with some loss of precision)
|
||||
function Load.itVolume(name: string?, param: number, force: boolean): number?
|
||||
if name == "volume" then
|
||||
return math.min(param, 64) + 1
|
||||
elseif name == "volume8" then
|
||||
if not force and param % 4 ~= 0 then
|
||||
return nil
|
||||
end
|
||||
return (param + 3) // 4 + 1
|
||||
elseif name == "portaup" or name == "portadown" then
|
||||
if not force and (param % 4 ~= 0 or param >= 0xE0) then
|
||||
return nil
|
||||
end
|
||||
return (if name == "portaup" then 115 else 105) + math.min(param // 4, 9) + 1
|
||||
elseif name == "toneporta" then
|
||||
if param >= 0xF0 then
|
||||
return 193 + 9 + 1
|
||||
end
|
||||
for n = 0, 9 do
|
||||
local v = Tables.IT_VOLPORTA[n + 1]
|
||||
if (force and param <= v) or param == v then
|
||||
return 193 + n + 1
|
||||
end
|
||||
end
|
||||
return nil
|
||||
elseif name == "vibrato" then
|
||||
if force then
|
||||
param = math.min(param % 16, 9)
|
||||
elseif param % 16 > 9 or param >= 16 then
|
||||
return nil
|
||||
end
|
||||
return 203 + param % 16 + 1
|
||||
elseif name == "panning8" then
|
||||
return 128 + (if param == 255 then 64 else param // 4) + 1
|
||||
elseif name == "volslide" then
|
||||
local x, y = param // 16, param % 16
|
||||
if param == 0 then
|
||||
return nil
|
||||
elseif y == 0 then
|
||||
return 85 + math.min(x, 9) + 1
|
||||
elseif x == 0 then
|
||||
return 95 + math.min(y, 9) + 1
|
||||
elseif y == 0xF then
|
||||
return 65 + math.min(x, 9) + 1
|
||||
elseif x == 0xF then
|
||||
return 75 + math.min(y, 9) + 1
|
||||
end
|
||||
return nil
|
||||
elseif name == "s3mex" and param // 16 == 8 then
|
||||
return 128 + (param % 16) * 4 + 2 + 1
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- itEffect(name, param) -> effect code, param in S3M / IT coding (0, 0 for none or an effect the family lacks; MOD's
|
||||
-- extended E commands become their S3M equivalents)
|
||||
function Load.itEffect(name: string?, param: number): (number, number)
|
||||
if name == nil then
|
||||
return 0, 0
|
||||
end
|
||||
if name == "modex" then
|
||||
local x, y = param // 16, param % 16
|
||||
if x == 1 then
|
||||
return IT.portaup, 0xF0 + y
|
||||
elseif x == 2 then
|
||||
return IT.portadown, 0xF0 + y
|
||||
elseif x == 9 then
|
||||
return IT.retrig, y
|
||||
elseif x == 0xA then
|
||||
return IT.volslide, y * 16 + 0xF
|
||||
elseif x == 0xB then
|
||||
return IT.volslide, 0xF0 + y
|
||||
end
|
||||
local s = ({ [3] = 1, [4] = 3, [5] = 2, [6] = 0xB, [7] = 4, [8] = 8, [0xC] = 0xC, [0xD] = 0xD, [0xE] = 0xE })[x]
|
||||
if s then
|
||||
return IT.s3mex, s * 16 + y
|
||||
end
|
||||
return 0, 0
|
||||
end
|
||||
local code = IT[name]
|
||||
if code == nil then
|
||||
return 0, 0
|
||||
end
|
||||
return code, param
|
||||
end
|
||||
|
||||
-- fillTwo(name1, param1, name2, param2, lowResOffset?) -> volume byte (engine IT coding, 0 none), effect name, param,
|
||||
-- lost name?, lost param: two effects of one cell into the IT volume column and the effect column, keeping the
|
||||
-- heavier one when both cannot fit (OpenMPT's FillInTwoCommands)
|
||||
function Load.fillTwo(e1: string?, p1: number, e2: string?, p2: number): (number, string?, number, string?, number)
|
||||
if e1 ~= nil and e1 == e2 then
|
||||
e2 = nil -- the same effect twice: keep one (most are absolute; slides are kept once too, a simplification)
|
||||
end
|
||||
for n = 0, 3 do
|
||||
local v = Load.itVolume(e1, p1, n > 1)
|
||||
if e1 == nil or v then
|
||||
if v == nil and (e2 == "volume" or e2 == "volume8") then
|
||||
-- the engine's IT family sets volumes in the volume column only
|
||||
return Load.itVolume(e2, p2, true) or 0, nil, 0, nil, 0
|
||||
end
|
||||
return v or 0, e2, p2, nil, 0
|
||||
end
|
||||
e1, p1, e2, p2 = e2, p2, e1, p1
|
||||
end
|
||||
if (WEIGHT[e1 :: string] or 0) > (WEIGHT[e2 :: string] or 0) then
|
||||
e1, p1, e2, p2 = e2, p2, e1, p1
|
||||
end
|
||||
return 0, e2, p2, e1, p1
|
||||
end
|
||||
|
||||
-- writeEffect(m, pattern (0-based), row, fx, param, retry?, channel?, multiple?) -> true when written: puts an effect
|
||||
-- into a free effect slot of the row (any channel, or the given 1-based one); none free: the next row (retry "next") or
|
||||
-- the previous one ("prev"). The same effect already on the row counts as written unless multiple (OpenMPT's
|
||||
-- CPattern::WriteEffect).
|
||||
function Load.writeEffect(m: any, pattern: number, row: number, fx: number, param: number, retry: string?, channel: number?, multiple: boolean?): boolean
|
||||
local p = m.patterns[pattern + 1]
|
||||
if not p then
|
||||
return false
|
||||
end
|
||||
local fam = m.engine or m.format
|
||||
local modLike = fam == "mod" or fam == "xm"
|
||||
local nch = m.channels
|
||||
local d = p.data
|
||||
local guard = 0
|
||||
while row >= 0 and row < p.rows and guard < 1024 do
|
||||
guard += 1
|
||||
local c0, c1 = 1, nch
|
||||
if channel then
|
||||
c0, c1 = channel, channel
|
||||
end
|
||||
for c = c0, c1 do
|
||||
local o = (row * nch + c - 1) * 5
|
||||
if not multiple and buffer.readu8(d, o + 3) == fx and (fx ~= 0 or not modLike) then
|
||||
return true
|
||||
end
|
||||
end
|
||||
for c = c0, c1 do
|
||||
local o = (row * nch + c - 1) * 5
|
||||
local f, q = buffer.readu8(d, o + 3), buffer.readu8(d, o + 4)
|
||||
if f == 0 and (not modLike or q == 0) then
|
||||
buffer.writeu8(d, o + 3, fx)
|
||||
buffer.writeu8(d, o + 4, param)
|
||||
return true
|
||||
end
|
||||
end
|
||||
if retry == "next" then
|
||||
row += 1
|
||||
elseif retry == "prev" then
|
||||
row -= 1
|
||||
else
|
||||
return false
|
||||
end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
-- readSample(buf, offset, frames, spec, sample, budget) -> true | nil, Err: decodes raw PCM (codecs/audio/Tracker/Pcm
|
||||
-- spec) at the absolute buffer offset into the sample (data, length, bits, channels). A short file keeps the frames
|
||||
-- that are there (end = the buffer's length, or spec.limit). budget = { left = f32 bytes still allowed } (maxBytes).
|
||||
function Load.readSample(buf: buffer, offset: number, frames: number, spec: any, s: any, budget: { left: number }): (boolean?, Err.Err?)
|
||||
local nch = spec.channels or 1
|
||||
local bps = spec.bits // 8
|
||||
local limit = math.min(spec.limit or buffer.len(buf), buffer.len(buf))
|
||||
local avail = math.max(0, limit - offset) // (nch * bps)
|
||||
local n = math.max(0, math.min(math.floor(frames), avail))
|
||||
budget.left -= n * nch * 4
|
||||
if budget.left < 0 then
|
||||
return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit")
|
||||
end
|
||||
local data = Pcm.decode(buf, offset, n, spec)
|
||||
if not data then
|
||||
return nil, Err.new(Err.TRUNCATED, "sample data", offset)
|
||||
end
|
||||
s.data, s.length, s.bits, s.channels = data, n, spec.bits, nch
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- bcd(n) -> n as the two decimal digits S3M / MOD pattern breaks store (0..99)
|
||||
function Load.bcd(n: number): number
|
||||
n = math.clamp(math.floor(n), 0, 99)
|
||||
return (n // 10) * 16 + n % 10
|
||||
end
|
||||
|
||||
return Load
|
||||
@@ -23,6 +23,20 @@ local MOD, S3M, XM, IT = 1, 2, 3, 4
|
||||
Player.MOD, Player.S3M, Player.XM, Player.IT = MOD, S3M, XM, IT
|
||||
local FAMILY = { mod = MOD, s3m = S3M, xm = XM, it = IT }
|
||||
|
||||
-- engine extension effects: format-specific commands of the other tracker formats, in any family (see
|
||||
-- codecs/audio/Tracker)
|
||||
local EXT = {
|
||||
NOTE_SLIDE_UP = 0x40,
|
||||
NOTE_SLIDE_DOWN = 0x41,
|
||||
NOTE_SLIDE_UP_RETRIG = 0x42,
|
||||
NOTE_SLIDE_DOWN_RETRIG = 0x43,
|
||||
AUTO_PORTA_UP = 0x44,
|
||||
AUTO_PORTA_DOWN = 0x45,
|
||||
FREQ_ADJUST = 0x46,
|
||||
TEMPO_256 = 0x47, -- set the tempo to 256 + param (0x48: 512 + param, 0x49: 768 + param)
|
||||
}
|
||||
Player.EXT = EXT
|
||||
|
||||
local BG_VOICES = 64 -- voices beyond one per channel, for IT new note actions
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ state
|
||||
@@ -171,12 +185,20 @@ local function newChannel(i: number, pan: number, vol: number): any
|
||||
pitchEnvOn = true,
|
||||
muted = false,
|
||||
triggered = false,
|
||||
autoPorta = 0, -- auto portamento (EXT 0x44 / 0x45): period units per tick, + down
|
||||
autoTone = false, -- flags.autoTonePorta: the tone portamento keeps running
|
||||
hzAdd = 0, -- EXT 0x46: Hz added to the frequency (669)
|
||||
slideCount = 0, -- note slides: ticks to the next step
|
||||
mNoteSlide = 0,
|
||||
tonePortaRow = false,
|
||||
}
|
||||
end
|
||||
|
||||
-- new(module, opts) -> player state (module validated by the caller)
|
||||
function Player.new(m: any, sampleRate: number, opts: any): any
|
||||
local fmt = FAMILY[m.format] or MOD
|
||||
local fmt = FAMILY[m.engine or m.format] or MOD
|
||||
local flags = m.flags
|
||||
local ptPeriods = fmt == MOD or flags.periods == "amiga"
|
||||
local st: any = {
|
||||
m = m,
|
||||
fmt = fmt,
|
||||
@@ -189,8 +211,19 @@ function Player.new(m: any, sampleRate: number, opts: any): any
|
||||
insMode = m.instrumentMode and #m.instruments > 0,
|
||||
oldFx = m.flags.oldEffects or false,
|
||||
compatG = m.flags.compatGxx or false,
|
||||
fastSlides = m.flags.fastSlides or false,
|
||||
amigaLimits = m.flags.amigaLimits or false,
|
||||
fastSlides = flags.fastSlides or false,
|
||||
amigaLimits = flags.amigaLimits or false,
|
||||
ptPeriods = ptPeriods, -- ProTracker periods (integer table periods, PAL clock)
|
||||
hz = flags.periods == "hz", -- periods are frequencies in Hz
|
||||
hzScale = if type(flags.hzSlide) == "number" then flags.hzSlide else 1,
|
||||
hzTone = if type(flags.hzTonePorta) == "number" then flags.hzTonePorta else 1,
|
||||
fastPortas = flags.fastPortas or false,
|
||||
autoTonePorta = flags.autoTonePorta or false,
|
||||
autoReset = flags.autoReset or false,
|
||||
st2Tempo = flags.st2Tempo or false,
|
||||
oktSlides = flags.oktSlides or false,
|
||||
ft2Pan = flags.panLaw == "ft2",
|
||||
envHold = flags.envRowHold or false,
|
||||
ord = 0,
|
||||
row = 0,
|
||||
tick = 0,
|
||||
@@ -214,7 +247,7 @@ function Player.new(m: any, sampleRate: number, opts: any): any
|
||||
master = 1,
|
||||
rows = 0,
|
||||
ramp = 64,
|
||||
amiga = if fmt == MOD then AMIGA_PAL else AMIGA,
|
||||
amiga = if ptPeriods then AMIGA_PAL else AMIGA,
|
||||
loopAllowed = opts and opts.loop or false,
|
||||
}
|
||||
for i = 1, m.channels do
|
||||
@@ -240,6 +273,9 @@ end
|
||||
-- the output scale per format, calibrated against OpenMPT's default mix levels (tools/fixtures: a full-scale sine at
|
||||
-- volume 64 on one centred channel)
|
||||
function Player.masterGain(m: any, fmt: number): number
|
||||
if type(m.preamp) == "number" then
|
||||
return m.preamp / 128 -- OpenMPT's sample pre-amp, as set by the format's loader
|
||||
end
|
||||
if fmt == IT or fmt == S3M then
|
||||
return (m.mixVolume or 48) / 128 -- OpenMPT: linear in the mix / master volume, 64 = 0.5
|
||||
end
|
||||
@@ -335,10 +371,15 @@ local function notePeriod(st: any, note: number, smp: any, ft: number?): (number
|
||||
end
|
||||
end
|
||||
local plin = (ref - note) * 64 - tr
|
||||
if st.fmt == MOD then
|
||||
if st.hz then
|
||||
-- periods are frequencies (Hz, rounded as OpenMPT does): the sample's rate at C-5
|
||||
return floor((smp.c5speed or 8363) * 2 ^ ((note - 61) / 12)), base
|
||||
end
|
||||
if st.ptPeriods then
|
||||
-- ProTracker: integer periods from the finetune tables (finetune 0 table scaled by 2^(-ft / 96), rounded)
|
||||
local ftp = (ft or smp.finetune or 0) / 16
|
||||
return 4 * floor(Tables.noteToPeriod(note) * 2 ^ (-ftp / 12 / 8) + 0.5), base
|
||||
local n = note + (if st.fmt == MOD or st.fmt == XM then smp.relativeNote or 0 else 0)
|
||||
return 4 * floor(Tables.noteToPeriod(n) * 2 ^ (-ftp / 12 / 8) + 0.5), base
|
||||
end
|
||||
if st.linear then
|
||||
return plin, base
|
||||
@@ -350,6 +391,9 @@ local function arpPeriod(st: any, period: number, semis: number): number
|
||||
if semis == 0 then
|
||||
return period
|
||||
end
|
||||
if st.hz then
|
||||
return period * 2 ^ (semis / 12)
|
||||
end
|
||||
if st.linear then
|
||||
return period - semis * 64
|
||||
end
|
||||
@@ -357,7 +401,9 @@ local function arpPeriod(st: any, period: number, semis: number): number
|
||||
end
|
||||
|
||||
local function clampPeriod(st: any, c: any)
|
||||
if st.linear then
|
||||
if st.hz then
|
||||
c.period = clamp(c.period, 1, 1e6)
|
||||
elseif st.linear then
|
||||
c.period = clamp(c.period, -6000, 6000)
|
||||
elseif st.amigaLimits then
|
||||
c.period = clamp(c.period, 113 * 4, 856 * 4)
|
||||
@@ -366,6 +412,17 @@ local function clampPeriod(st: any, c: any)
|
||||
end
|
||||
end
|
||||
|
||||
-- slide(st, c, units): a pitch slide in period units (positive: down; 4 per effect unit); in Hz mode the frequency
|
||||
-- moves units * hzSlide Hz the other way
|
||||
local function slide(st: any, c: any, units: number)
|
||||
if st.hz then
|
||||
c.period -= units * st.hzScale
|
||||
else
|
||||
c.period += units
|
||||
end
|
||||
clampPeriod(st, c)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ voices
|
||||
local function allocVoice(st: any): any
|
||||
local best, bestScore = nil, math.huge
|
||||
@@ -674,6 +731,7 @@ local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: numb
|
||||
keep = if c.voice.ins == ins then true else "release"
|
||||
end
|
||||
c.triggered = true
|
||||
c.hzAdd = 0
|
||||
c.tremorOn = true
|
||||
c.retrigCount = 0
|
||||
v = startVoice(st, c, smp, smpIdx, ins, useIns, realNote, period, base, keep)
|
||||
@@ -758,6 +816,9 @@ local function tonePorta(st: any, c: any, speed: number)
|
||||
if c.period == c.target then
|
||||
return
|
||||
end
|
||||
if st.hz then
|
||||
speed *= st.hzScale * st.hzTone
|
||||
end
|
||||
if c.period < c.target then
|
||||
c.period = min(c.period + speed, c.target)
|
||||
else
|
||||
@@ -837,23 +898,21 @@ local function fxModXm(st: any, c: any, tick: number)
|
||||
if xm and param > 0 then
|
||||
c.mPortaUp = param
|
||||
end
|
||||
if tick > 0 then
|
||||
c.period -= (if xm then c.mPortaUp else param) * 4
|
||||
clampPeriod(st, c)
|
||||
if tick > 0 or st.fastPortas then
|
||||
slide(st, c, -(if xm then c.mPortaUp else param) * 4)
|
||||
end
|
||||
elseif fx == 2 then
|
||||
if xm and param > 0 then
|
||||
c.mPortaDn = param
|
||||
end
|
||||
if tick > 0 then
|
||||
c.period += (if xm then c.mPortaDn else param) * 4
|
||||
clampPeriod(st, c)
|
||||
if tick > 0 or st.fastPortas then
|
||||
slide(st, c, (if xm then c.mPortaDn else param) * 4)
|
||||
end
|
||||
elseif fx == 3 or fx == 5 then
|
||||
if fx == 3 and param > 0 then
|
||||
c.portaSpeed = param
|
||||
end
|
||||
if tick > 0 then
|
||||
if tick > 0 or st.fastPortas then
|
||||
tonePorta(st, c, c.portaSpeed * 4)
|
||||
end
|
||||
elseif fx == 4 or fx == 6 then
|
||||
@@ -909,16 +968,14 @@ local function fxModXm(st: any, c: any, tick: number)
|
||||
c.mFineUp = y
|
||||
end
|
||||
if tick == 0 then
|
||||
c.period -= (if xm then c.mFineUp else y) * 4
|
||||
clampPeriod(st, c)
|
||||
slide(st, c, -(if xm then c.mFineUp else y) * 4)
|
||||
end
|
||||
elseif x == 2 then
|
||||
if xm and y > 0 then
|
||||
c.mFineDn = y
|
||||
end
|
||||
if tick == 0 then
|
||||
c.period += (if xm then c.mFineDn else y) * 4
|
||||
clampPeriod(st, c)
|
||||
slide(st, c, (if xm then c.mFineDn else y) * 4)
|
||||
end
|
||||
elseif x == 4 then
|
||||
c.vibWave = y % 8
|
||||
@@ -1054,16 +1111,14 @@ local function fxModXm(st: any, c: any, tick: number)
|
||||
c.mXFineUp = y
|
||||
end
|
||||
if tick == 0 then
|
||||
c.period -= c.mXFineUp
|
||||
clampPeriod(st, c)
|
||||
slide(st, c, -c.mXFineUp)
|
||||
end
|
||||
elseif x == 2 then
|
||||
if y > 0 then
|
||||
c.mXFineDn = y
|
||||
end
|
||||
if tick == 0 then
|
||||
c.period += c.mXFineDn
|
||||
clampPeriod(st, c)
|
||||
slide(st, c, c.mXFineDn)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1073,10 +1128,10 @@ local function fxModXm(st: any, c: any, tick: number)
|
||||
if param > 0 then
|
||||
c.mVolSlide = param
|
||||
end
|
||||
if tick > 0 then
|
||||
if tick > 0 or st.fastSlides then
|
||||
volSlideMod(c, c.mVolSlide)
|
||||
end
|
||||
elseif tick > 0 then
|
||||
elseif tick > 0 or st.fastSlides then
|
||||
volSlideMod(c, param)
|
||||
end
|
||||
end
|
||||
@@ -1161,16 +1216,15 @@ end
|
||||
local function portaS3m(st: any, c: any, p: number, tick: number, sign: number)
|
||||
if p >= 0xF0 then
|
||||
if tick == 0 then
|
||||
c.period += sign * (p % 16) * 4
|
||||
slide(st, c, sign * (p % 16) * 4)
|
||||
end
|
||||
elseif p >= 0xE0 then
|
||||
if tick == 0 then
|
||||
c.period += sign * (p % 16)
|
||||
slide(st, c, sign * (p % 16))
|
||||
end
|
||||
elseif tick > 0 then
|
||||
c.period += sign * p * 4
|
||||
elseif tick > 0 or st.fastPortas then
|
||||
slide(st, c, sign * p * 4)
|
||||
end
|
||||
clampPeriod(st, c)
|
||||
end
|
||||
|
||||
local function fxS3mIt(st: any, c: any, tick: number)
|
||||
@@ -1178,7 +1232,11 @@ local function fxS3mIt(st: any, c: any, tick: number)
|
||||
local it = st.fmt == IT
|
||||
if fx == 1 then -- A speed
|
||||
if tick == 0 and param > 0 then
|
||||
st.speed = param
|
||||
if st.st2Tempo then
|
||||
st.speed, st.tempo = Tables.st2Tempo(param)
|
||||
else
|
||||
st.speed = param
|
||||
end
|
||||
end
|
||||
elseif fx == 2 then -- B jump
|
||||
if tick == 0 then
|
||||
@@ -1446,7 +1504,7 @@ local function fxS3mIt(st: any, c: any, tick: number)
|
||||
c.portaSpeed = c.mEF
|
||||
end
|
||||
end
|
||||
if tick > 0 then
|
||||
if tick > 0 or st.fastPortas then
|
||||
tonePorta(st, c, c.portaSpeed * 4)
|
||||
end
|
||||
end
|
||||
@@ -1514,8 +1572,7 @@ local function volColIt(st: any, c: any, tick: number)
|
||||
c.mEF = p
|
||||
end
|
||||
if tick > 0 then
|
||||
c.period += c.mEF * 4
|
||||
clampPeriod(st, c)
|
||||
slide(st, c, c.mEF * 4)
|
||||
end
|
||||
elseif v <= 124 then
|
||||
local p = (v - 115) * 4
|
||||
@@ -1523,8 +1580,7 @@ local function volColIt(st: any, c: any, tick: number)
|
||||
c.mEF = p
|
||||
end
|
||||
if tick > 0 then
|
||||
c.period -= c.mEF * 4
|
||||
clampPeriod(st, c)
|
||||
slide(st, c, -c.mEF * 4)
|
||||
end
|
||||
elseif v >= 193 and v <= 202 then
|
||||
local p = Tables.IT_VOLPORTA[v - 192] or 0
|
||||
@@ -1550,6 +1606,66 @@ local function volColIt(st: any, c: any, tick: number)
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extension effects
|
||||
-- the engine extension effects (EXT, codes 0x40..) and the auto slides, in any family
|
||||
local function fxExt(st: any, c: any, tick: number)
|
||||
local fx, param = c.fx, c.param
|
||||
if fx >= EXT.NOTE_SLIDE_UP and fx <= EXT.NOTE_SLIDE_DOWN_RETRIG then
|
||||
-- note slides (PTM, Oktalyzer): every (param >> 4) ticks by (param & 15) semitones; Oktalyzer (flags.oktSlides):
|
||||
-- 1x = every tick, 5x = once on the first tick
|
||||
if tick == 0 then
|
||||
if param // 16 > 0 then
|
||||
c.mNoteSlide = (param // 16) * 16 + c.mNoteSlide % 16
|
||||
end
|
||||
if param % 16 > 0 then
|
||||
c.mNoteSlide = (c.mNoteSlide // 16) * 16 + param % 16
|
||||
end
|
||||
c.slideCount = c.mNoteSlide // 16
|
||||
end
|
||||
local p = c.mNoteSlide
|
||||
local go
|
||||
if st.oktSlides then
|
||||
go = p // 16 == 1 or tick == 0
|
||||
else
|
||||
go = false
|
||||
if tick > 0 then
|
||||
c.slideCount -= 1
|
||||
go = c.slideCount == 0
|
||||
end
|
||||
end
|
||||
if go and c.smp and c.realNote > 0 then
|
||||
c.slideCount = p // 16
|
||||
local up = fx == EXT.NOTE_SLIDE_UP or fx == EXT.NOTE_SLIDE_UP_RETRIG
|
||||
c.realNote = clamp(c.realNote + (if up then p % 16 else -(p % 16)), 1, 120)
|
||||
c.period = notePeriod(st, c.realNote, c.smp, c.finetune)
|
||||
if fx >= EXT.NOTE_SLIDE_UP_RETRIG then
|
||||
retrigVoice(st, c)
|
||||
end
|
||||
end
|
||||
elseif fx == EXT.AUTO_PORTA_UP or fx == EXT.AUTO_PORTA_DOWN then
|
||||
if tick == 0 then
|
||||
c.autoPorta = (if fx == EXT.AUTO_PORTA_UP then -param else param) * 4
|
||||
end
|
||||
elseif fx == EXT.FREQ_ADJUST then
|
||||
if tick == 0 then
|
||||
c.hzAdd = param * 80
|
||||
end
|
||||
elseif fx >= EXT.TEMPO_256 and fx <= EXT.TEMPO_256 + 2 then
|
||||
if tick == 0 then
|
||||
st.tempo = (fx - EXT.TEMPO_256 + 1) * 256 + param
|
||||
end
|
||||
end
|
||||
-- auto slides: every tick (fast portamentos) or every tick but the first
|
||||
if tick > 0 or st.fastPortas then
|
||||
if c.autoPorta ~= 0 then
|
||||
slide(st, c, c.autoPorta)
|
||||
end
|
||||
if c.autoTone and not c.tonePortaRow then
|
||||
tonePorta(st, c, c.portaSpeed * 4)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ rows and ticks
|
||||
local function noteDelayOf(st: any, fx: number, param: number): number
|
||||
if (st.fmt == MOD or st.fmt == XM) and fx == 0xE and param // 16 == 0xD then
|
||||
@@ -1573,6 +1689,9 @@ end
|
||||
|
||||
local function runEffects(st: any, c: any, tick: number)
|
||||
c.vibDelta, c.arp = 0, 0
|
||||
if (c.fx >= 0x40 and c.fx < 0x50) or c.autoPorta ~= 0 or c.autoTone then
|
||||
fxExt(st, c, tick)
|
||||
end
|
||||
if st.fmt == MOD or st.fmt == XM then
|
||||
fxModXm(st, c, tick)
|
||||
if st.fmt == XM then
|
||||
@@ -1621,6 +1740,15 @@ local function processRow(st: any)
|
||||
end
|
||||
c.fx, c.param, c.vcmd = fx, param, vcmd
|
||||
c.cutTick, c.keyOffTick = -1, -1
|
||||
if st.autoReset and fx ~= 0 and fx ~= 255 then
|
||||
-- 669: any effect stops the auto slides
|
||||
c.autoPorta, c.autoTone = 0, false
|
||||
end
|
||||
local tp = isPorta(st, fx, vcmd)
|
||||
c.tonePortaRow = tp
|
||||
if tp and st.autoTonePorta then
|
||||
c.autoTone = param ~= 0 or not st.autoReset or not isPorta(st, fx, 0)
|
||||
end
|
||||
c.triggered = false
|
||||
local delay = noteDelayOf(st, fx, param)
|
||||
c.finetune = finetuneOf(st, fx, param)
|
||||
@@ -1684,10 +1812,11 @@ local function updateVoice(st: any, v: any)
|
||||
local envVol, envPan, envPitch = 64, 0, 0
|
||||
local filterEnv = nil
|
||||
if ins then
|
||||
local hold = st.envHold and st.tick == 0 -- MED: the envelopes do not move on a row's first tick
|
||||
local e = ins.volEnv
|
||||
if e and e.enabled and v.volEnvOn then
|
||||
local val, np, ended = updateEnvelope(e, v.volEnvPos, v.keyOn, it)
|
||||
envVol, v.volEnvPos = val, np
|
||||
envVol, v.volEnvPos = val, if hold then v.volEnvPos else np
|
||||
if ended and it then
|
||||
if val <= 0 then
|
||||
v.active = false
|
||||
@@ -1699,12 +1828,12 @@ local function updateVoice(st: any, v: any)
|
||||
e = ins.panEnv
|
||||
if e and e.enabled and v.panEnvOn then
|
||||
local val, np = updateEnvelope(e, v.panEnvPos, v.keyOn, it)
|
||||
envPan, v.panEnvPos = val, np
|
||||
envPan, v.panEnvPos = val, if hold then v.panEnvPos else np
|
||||
end
|
||||
e = ins.pitchEnv
|
||||
if e and e.enabled and v.pitchEnvOn then
|
||||
local val, np = updateEnvelope(e, v.pitchEnvPos, v.keyOn, it)
|
||||
v.pitchEnvPos = np
|
||||
v.pitchEnvPos = if hold then v.pitchEnvPos else np
|
||||
if e.filter then
|
||||
filterEnv = val
|
||||
else
|
||||
@@ -1750,7 +1879,9 @@ local function updateVoice(st: any, v: any)
|
||||
-- frequency
|
||||
local P = v.periodOut + avDelta
|
||||
local freq
|
||||
if st.linear then
|
||||
if st.hz then
|
||||
freq = max(0, P + (v.hzAdd or 0))
|
||||
elseif st.linear then
|
||||
freq = v.base * 2 ^ (-P / 768)
|
||||
else
|
||||
freq = if P > 0 then st.amiga / P else 0
|
||||
@@ -1762,9 +1893,9 @@ local function updateVoice(st: any, v: any)
|
||||
-- volume
|
||||
local smp = v.smp
|
||||
local vol = v.vol / 64 * envVol / 64 * v.fade / 65536 * st.gvol / 128
|
||||
if it then
|
||||
vol *= v.chanVol / 64 * (if smp then (smp.globalVolume or 64) / 64 else 1) * (if ins then (ins.globalVolume or 128) / 128 else 1)
|
||||
end
|
||||
-- channel, sample and instrument global volumes (64 / 64 / 128 unless an IT file, or another format's loader,
|
||||
-- sets them)
|
||||
vol *= v.chanVol / 64 * (if smp then (smp.globalVolume or 64) / 64 else 1) * (if ins then (ins.globalVolume or 128) / 128 else 1)
|
||||
if v.tremorMute then
|
||||
vol = 0
|
||||
end
|
||||
@@ -1782,6 +1913,10 @@ local function updateVoice(st: any, v: any)
|
||||
local g = vol * st.master
|
||||
if v.surround then
|
||||
v.tl, v.tr = g * 0.5, -g * 0.5
|
||||
elseif st.ft2Pan then
|
||||
-- FT2's square-root pan law (OpenMPT's CompatibleFT2 mix levels), pan at most 255
|
||||
local p = min(pan, 255)
|
||||
v.tl, v.tr = g * math.sqrt((256 - p) / 256), g * math.sqrt(p / 256)
|
||||
else
|
||||
v.tl, v.tr = g * (256 - pan) / 256, g * pan / 256
|
||||
end
|
||||
@@ -1853,8 +1988,9 @@ function Player.tick(st: any): number
|
||||
local c = st.chans[i]
|
||||
local v = c.voice
|
||||
if v and v.active and v.chan == i and not v.bg then
|
||||
local P = arpPeriod(st, c.period, c.arp) + c.vibDelta
|
||||
local P = arpPeriod(st, c.period, c.arp) + (if st.hz then -c.vibDelta * st.hzScale else c.vibDelta)
|
||||
v.period, v.periodOut, v.base = c.period, P, c.base
|
||||
v.hzAdd = c.hzAdd
|
||||
v.vol = clamp(c.vol + c.tremDelta, 0, 64)
|
||||
if c.muted then
|
||||
v.vol = 0
|
||||
|
||||
@@ -110,4 +110,17 @@ Tables.AMIGA = 8363 * 1712
|
||||
-- MOD: the PAL Amiga clock (7093789.2 Hz / 2 per ProTracker period unit; period 428 plays at 8287 Hz)
|
||||
Tables.AMIGA_PAL = 7093789.2 / 2 * 4
|
||||
|
||||
-- st2Tempo(byte) -> speed, tempo: a Scream Tracker 2 tempo byte (high nibble ticks per row, low nibble a fine factor)
|
||||
-- as OpenMPT plays it (ConvertST2Tempo: ST2's tick length at its 23863 Hz mixing rate, as a fractional BPM)
|
||||
local ST2_FACTOR = { 140, 50, 25, 15, 10, 7, 6, 4, 3, 3, 2, 2, 2, 2, 1, 1 }
|
||||
function Tables.st2Tempo(byte: number): (number, number)
|
||||
local hi, lo = byte // 16, byte % 16
|
||||
local d = 50 - (ST2_FACTOR[hi + 1] * lo) // 16 -- never 0; negative at tempo 06..0F (C integer division truncates)
|
||||
local spt = if d > 0 then 23863 // d else -(23863 // -d)
|
||||
if spt <= 0 then
|
||||
spt += 65536
|
||||
end
|
||||
return math.max(hi, 1), math.floor((23863 * 50000 + spt) / (spt * 2)) / 10000
|
||||
end
|
||||
|
||||
return Tables
|
||||
@@ -1,6 +1,7 @@
|
||||
--!strict
|
||||
-- codecs/audio/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read
|
||||
-- their files into one Module structure (below); render(module, opts) plays any of them through the standard audio
|
||||
-- codecs/audio/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it, and the loaders
|
||||
-- that map other trackers onto those four effect families (music/mtm, 669, stm, ult, okt, med, ptm, far; helpers in
|
||||
-- codecs/audio/Tracker/Load). The loaders read their files into one Module structure (below); render(module, opts) plays any of them through the standard audio
|
||||
-- Decoder (Types.Decoder: stereo f32). Written for this library from the format documents (ProTracker 2.3, the XM
|
||||
-- spec + FT2 behaviour, ST3 TECH.DOC, ITTECH.TXT); libxmp / OpenMPT were used only as reference players for tests.
|
||||
--
|
||||
@@ -9,14 +10,25 @@
|
||||
-- local seconds = Tracker.duration(module) -- one pass, song loops detected
|
||||
--
|
||||
-- Module (Types.Module plus the engine fields; pattern / instrument / sample numbers are as in the file):
|
||||
-- format "mod" | "s3m" | "xm" | "it": selects the effect family and the format quirks
|
||||
-- format the file format ("mod", "s3m", "xm", "it", "mtm", "669", ...): what the module was read from
|
||||
-- engine "mod" | "s3m" | "xm" | "it": the effect family the engine plays (default: format, so the four
|
||||
-- families need no engine field). Other formats map their effects onto one family (music/mtm: "xm",
|
||||
-- music/669: "s3m", ...) and set the quirks they need in flags.
|
||||
-- preamp optional 0..256: the output gain as OpenMPT's sample pre-amp (gain = preamp / 128); default per family
|
||||
-- title, channels, speed (ticks per row), tempo (BPM: a tick lasts 2.5 / tempo s)
|
||||
-- globalVolume 0..128 (S3M / XM 0..64 are stored doubled), mixVolume 0..128 (IT mix volume, S3M master volume)
|
||||
-- order { pattern number (0-based) | 254 skip ("+++") | 255 end ("---") }, restart (0-based order index)
|
||||
-- linear linear frequency slides (XM / IT flag) or Amiga periods
|
||||
-- instrumentMode XM, IT with instruments: notes go through Instrument keymaps; otherwise the instrument column
|
||||
-- is a sample number (MOD, S3M, IT sample mode)
|
||||
-- flags { oldEffects, compatGxx (IT), fastSlides (ST3.00 volume slides), amigaLimits (MOD) }
|
||||
-- flags { oldEffects, compatGxx (IT), fastSlides (ST3.00 volume slides: also on tick 0; any family),
|
||||
-- amigaLimits (MOD), and the quirks of the other formats (any family):
|
||||
-- periods = "amiga" (ProTracker period table + PAL clock, as MOD) | "hz" (periods are frequencies in
|
||||
-- Hz: 669, FAR; slides move hzSlide Hz per unit, tone portamento hzSlide * hzTonePorta),
|
||||
-- fastPortas (slides on tick 0 too), autoTonePorta (a tone portamento keeps running on later rows),
|
||||
-- autoReset (669: any effect stops the auto slides), st2Tempo (S3M family A: Scream Tracker 2 tempo),
|
||||
-- oktSlides (Oktalyzer note slides), panLaw = "ft2" (square-root panning, OpenMPT's FT2 mix levels),
|
||||
-- envRowHold (MED: envelopes do not advance on a row's first tick) }
|
||||
-- channelPan { 0..256 per channel (128 centre; 512 = surround); MOD: 64 / 192 (Amiga L R R L at half width,
|
||||
-- as OpenMPT plays it; set 0 / 256 or render with stereoSeparation = 200 for hard panning) }, channelVolume { 0..64 }, channelMute { bool }
|
||||
-- patterns { Pattern } (pattern n at patterns[n + 1]); Pattern = { rows, data }: data holds rows * channels
|
||||
@@ -25,7 +37,11 @@
|
||||
-- speed), 253 note fade, 254 note cut, 255 key off. The volume column and effects are kept in the
|
||||
-- file's own coding: MOD / XM effects 0..35 (XM letters G.. = 16..), XM volume byte as stored;
|
||||
-- S3M / IT effects 1..26 (A = 1), S3M volume 0 = none else volume + 1, IT volume byte + 1
|
||||
-- (0 = none). Tracker.cell / Tracker.setCell read and write cells.
|
||||
-- (0 = none). Engine extension effects (any family, for the other formats): Tracker.EXT (0x40 note
|
||||
-- slide up, 0x41 down, 0x42 / 0x43 the same with retrigger: param = ticks per step << 4 | semitones;
|
||||
-- 0x44 / 0x45 auto portamento up / down (669: every tick until another effect), 0x46 frequency
|
||||
-- adjust (+ param * 80 Hz, 669), 0x47 / 0x48 / 0x49 tempo 256 / 512 / 768 + param (MED)).
|
||||
-- Tracker.cell / Tracker.setCell read and write cells.
|
||||
-- samples { Sample }: { name, data (f32, interleaved when stereo), length (frames), channels, bits (8 | 16,
|
||||
-- for writers), loopStart, loopEnd (frames, end exclusive), loopType (0 none, 1 forward, 2 ping-pong),
|
||||
-- susStart, susEnd, susType (IT sustain loop), volume 0..64, globalVolume 0..64, pan (0..256 or nil),
|
||||
@@ -85,12 +101,29 @@ export type RenderOptions = {
|
||||
|
||||
local CELL = 5
|
||||
|
||||
-- engine extension effects (see the Module notes above)
|
||||
Tracker.EXT = Player.EXT
|
||||
|
||||
-- st2Tempo(byte) -> speed, tempo (BPM): a Scream Tracker 2 tempo byte
|
||||
Tracker.st2Tempo = Tables.st2Tempo
|
||||
|
||||
local FAMILIES = { mod = true, s3m = true, xm = true, it = true }
|
||||
|
||||
-- family(module) -> "mod" | "s3m" | "xm" | "it" | nil: the effect family a module plays as
|
||||
function Tracker.family(m: any): string?
|
||||
local f = m.engine or m.format
|
||||
return if type(f) == "string" and FAMILIES[f] then f else nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constructors
|
||||
-- newModule(format, channels) -> an empty Module (no patterns / samples) with the format's defaults
|
||||
function Tracker.newModule(format: string, channels: number): any
|
||||
-- newModule(format, channels, engine?) -> an empty Module (no patterns / samples) with the defaults of the effect family
|
||||
-- (engine, default format)
|
||||
function Tracker.newModule(format: string, channels: number, engine: string?): any
|
||||
local fam = engine or format
|
||||
local m = {
|
||||
kind = "music",
|
||||
format = format,
|
||||
engine = engine,
|
||||
title = "",
|
||||
channels = channels,
|
||||
speed = 6,
|
||||
@@ -99,8 +132,8 @@ function Tracker.newModule(format: string, channels: number): any
|
||||
mixVolume = 48,
|
||||
order = {},
|
||||
restart = 0,
|
||||
linear = format == "xm" or format == "it",
|
||||
instrumentMode = format == "xm" or format == "it",
|
||||
linear = fam == "xm" or fam == "it",
|
||||
instrumentMode = fam == "xm" or fam == "it",
|
||||
flags = {},
|
||||
channelPan = {},
|
||||
channelVolume = {},
|
||||
@@ -113,7 +146,7 @@ function Tracker.newModule(format: string, channels: number): any
|
||||
}
|
||||
for i = 1, channels do
|
||||
m.channelVolume[i] = 64
|
||||
if format == "mod" then
|
||||
if fam == "mod" then
|
||||
local k = (i - 1) % 4
|
||||
m.channelPan[i] = if k == 0 or k == 3 then 64 else 192 -- the Amiga's L R R L, at OpenMPT's default width
|
||||
else
|
||||
@@ -285,8 +318,11 @@ function Tracker.validate(m: any): (boolean?, Err.Err?)
|
||||
if type(m) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "not a module")
|
||||
end
|
||||
if m.format ~= "mod" and m.format ~= "s3m" and m.format ~= "xm" and m.format ~= "it" then
|
||||
return nil, Err.new(Err.ARG, "unknown tracker format " .. tostring(m.format))
|
||||
if not Tracker.family(m) then
|
||||
return nil, Err.new(Err.ARG, "unknown tracker format " .. tostring(m.engine or m.format))
|
||||
end
|
||||
if m.preamp ~= nil and not num(m.preamp, 0, 256) then
|
||||
m.preamp = nil
|
||||
end
|
||||
if not num(m.channels, 1, 128) or m.channels % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "bad channel count")
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/audio/Tta/Decode: one TTA1 frame -> samples. Written from the TTA1 format description (the True Audio
|
||||
-- format notes: adaptive Rice codes with two running sums per channel, the order-8 sign-LMS "hybrid" filter, the
|
||||
-- first-order fixed predictor, inter-channel decorrelation, a CRC-32 per frame); no libtta / ffmpeg code. Checked
|
||||
-- bit-exact against the ttaenc 3.4.1 decoder (tools/fixtures/tta.py). Never throws: returns nil, message.
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
|
||||
local readu8, readu32 = buffer.readu8, buffer.readu32
|
||||
local band, rshift = bit32.band, bit32.rshift
|
||||
local min, max, floor = math.min, math.max, math.floor
|
||||
|
||||
local Decode = {}
|
||||
|
||||
local TWO31, TWO32 = 2147483648, 4294967296
|
||||
local INV31 = 1 / TWO31
|
||||
local PAD = 16
|
||||
local P2: { number } = table.create(40, 0) -- P2[k + 1] = 2^k
|
||||
for i = 0, 39 do
|
||||
P2[i + 1] = 2 ^ i
|
||||
end
|
||||
-- ONES[b + 1]: the trailing 1 bits of the byte b
|
||||
local ONES: { number } = table.create(256, 0)
|
||||
for b = 0, 255 do
|
||||
local n, v = 0, b
|
||||
while v % 2 == 1 do
|
||||
n += 1
|
||||
v //= 2
|
||||
end
|
||||
ONES[b + 1] = n
|
||||
end
|
||||
|
||||
-- longUnary(S, pos, lim) -> the count of 1 bits from pos, the position after the 0 | nil (past lim)
|
||||
local function longUnary(S: buffer, pos: number, lim: number): (number?, number)
|
||||
local unary = 0
|
||||
while pos <= lim do
|
||||
local w = rshift(readu32(S, rshift(pos, 3)), band(pos, 7))
|
||||
local ones = ONES[band(w, 255) + 1]
|
||||
if ones < 8 then
|
||||
return unary + ones, pos + ones + 1
|
||||
end
|
||||
unary += 8
|
||||
pos += 8
|
||||
end
|
||||
return nil, pos
|
||||
end
|
||||
|
||||
export type State = {
|
||||
channels: number,
|
||||
bytes: number, -- 1 .. 3
|
||||
S: buffer, -- the frame's bits (+ PAD zeros)
|
||||
-- per channel: rice k0, k1, sum0, sum1; filter error, Q (weights), X (steps), L (delay line) x 8; the last value
|
||||
R: { number },
|
||||
Q: { number },
|
||||
X: { number },
|
||||
L: { number },
|
||||
E: { number },
|
||||
last: { number },
|
||||
cur: { number },
|
||||
}
|
||||
|
||||
function Decode.state(channels: number, bytes: number): State
|
||||
return {
|
||||
channels = channels,
|
||||
bytes = bytes,
|
||||
S = buffer.create(4096),
|
||||
R = table.create(channels * 4, 0),
|
||||
Q = table.create(channels * 8, 0),
|
||||
X = table.create(channels * 8, 0),
|
||||
L = table.create(channels * 8, 0),
|
||||
E = table.create(channels, 0),
|
||||
last = table.create(channels, 0),
|
||||
cur = table.create(channels, 0),
|
||||
}
|
||||
end
|
||||
|
||||
-- frame(st, buf, o, len, n, P) -> n | nil, message: the frame of len bytes at o (its CRC-32 last) holding n samples per
|
||||
-- channel, into P (interleaved integers)
|
||||
function Decode.frame(st: State, buf: buffer, o: number, len: number, n: number, P: { number }): (number?, string?)
|
||||
if len < 4 then
|
||||
return nil, "truncated frame"
|
||||
end
|
||||
local dlen = len - 4
|
||||
if Crc32.of(buf, o, dlen) ~= readu32(buf, o + dlen) then
|
||||
return nil, "checksum: frame CRC mismatch"
|
||||
end
|
||||
local S = st.S
|
||||
if buffer.len(S) < dlen + PAD then
|
||||
S = buffer.create(dlen + PAD + 4096)
|
||||
st.S = S
|
||||
end
|
||||
buffer.copy(S, 0, buf, o, dlen)
|
||||
buffer.fill(S, dlen, 0, PAD)
|
||||
local C, bytes = st.channels, st.bytes
|
||||
local shift = if bytes == 2 then 9 else 10 -- the filter's precision per sample size
|
||||
local fdiv = 2 ^ shift
|
||||
local round = fdiv // 2
|
||||
local pk = if bytes == 1 then 16 else 32 -- the fixed predictor: last * (pk - 1) / pk
|
||||
local R, Q, X, L, E, last, cur = st.R, st.Q, st.X, st.L, st.E, st.last, st.cur
|
||||
for c = 0, C - 1 do
|
||||
R[c * 4 + 1], R[c * 4 + 2], R[c * 4 + 3], R[c * 4 + 4] = 10, 10, 16384, 16384
|
||||
E[c + 1], last[c + 1] = 0, 0
|
||||
for i = 1, 8 do
|
||||
Q[c * 8 + i], X[c * 8 + i], L[c * 8 + i] = 0, 0, 0
|
||||
end
|
||||
end
|
||||
local pos = 0 -- bit position
|
||||
local lim = dlen * 8
|
||||
local c = 0 -- the channel of the sample at idx
|
||||
for idx = 1, n * C do
|
||||
do
|
||||
if pos > lim then
|
||||
return nil, "truncated frame"
|
||||
end
|
||||
-- the unary prefix: 1 bits up to a 0 (a run past one byte goes to longUnary)
|
||||
local unary
|
||||
local w = rshift(readu32(S, rshift(pos, 3)), band(pos, 7))
|
||||
local ones = ONES[band(w, 255) + 1]
|
||||
if ones < 8 then
|
||||
unary = ones
|
||||
pos += ones + 1
|
||||
else
|
||||
local u, p2 = longUnary(S, pos, lim)
|
||||
if not u then
|
||||
return nil, "truncated frame"
|
||||
end
|
||||
unary, pos = u, p2
|
||||
end
|
||||
local rb = c * 4
|
||||
local k0, k1, s0, s1 = R[rb + 1], R[rb + 2], R[rb + 3], R[rb + 4]
|
||||
local deep = unary > 0
|
||||
local k
|
||||
if deep then
|
||||
k = k1
|
||||
unary -= 1
|
||||
else
|
||||
k = k0
|
||||
end
|
||||
local value = unary
|
||||
if k > 0 then
|
||||
local bits
|
||||
if k <= 24 then
|
||||
bits = band(rshift(readu32(S, rshift(pos, 3)), band(pos, 7)), P2[k + 1] - 1)
|
||||
else
|
||||
local lo = band(rshift(readu32(S, rshift(pos, 3)), band(pos, 7)), 0xFFFF)
|
||||
local p2 = pos + 16
|
||||
bits = lo + band(rshift(readu32(S, rshift(p2, 3)), band(p2, 7)), P2[k - 15] - 1) * 65536
|
||||
end
|
||||
pos += k
|
||||
value = unary * P2[k + 1] + bits
|
||||
end
|
||||
if deep then
|
||||
s1 += value - s1 // 16
|
||||
if k1 > 0 and s1 < P2[k1 + 5] then
|
||||
k1 -= 1
|
||||
elseif s1 > P2[k1 + 6] then
|
||||
k1 += 1
|
||||
end
|
||||
value += P2[k0 + 1]
|
||||
end
|
||||
s0 += value - s0 // 16
|
||||
if k0 > 0 and s0 < P2[k0 + 5] then
|
||||
k0 -= 1
|
||||
elseif s0 > P2[k0 + 6] then
|
||||
k0 += 1
|
||||
end
|
||||
R[rb + 1] = math.min(k0, 31)
|
||||
R[rb + 2] = math.min(k1, 31)
|
||||
R[rb + 3] = s0
|
||||
R[rb + 4] = s1
|
||||
local odd = value % 2 -- odd -> (v + 1) / 2, even -> -v / 2 (branch-free)
|
||||
value = (value + odd) // 2 * (2 * odd - 1)
|
||||
-- the adaptive filter: the weights step toward the sign of the last residual
|
||||
local fb = c * 8
|
||||
local err = E[c + 1]
|
||||
-- (one assignment per statement: LuaJIT cannot coalesce long multiple assignments)
|
||||
local dq = max(-1, min(1, err))
|
||||
local x1, x2, x3, x4 = X[fb + 1], X[fb + 2], X[fb + 3], X[fb + 4]
|
||||
local x5, x6, x7, x8 = X[fb + 5], X[fb + 6], X[fb + 7], X[fb + 8]
|
||||
local q1 = Q[fb + 1] + x1 * dq
|
||||
local q2 = Q[fb + 2] + x2 * dq
|
||||
local q3 = Q[fb + 3] + x3 * dq
|
||||
local q4 = Q[fb + 4] + x4 * dq
|
||||
local q5 = Q[fb + 5] + x5 * dq
|
||||
local q6 = Q[fb + 6] + x6 * dq
|
||||
local q7 = Q[fb + 7] + x7 * dq
|
||||
local q8 = Q[fb + 8] + x8 * dq
|
||||
Q[fb + 1] = q1
|
||||
Q[fb + 2] = q2
|
||||
Q[fb + 3] = q3
|
||||
Q[fb + 4] = q4
|
||||
Q[fb + 5] = q5
|
||||
Q[fb + 6] = q6
|
||||
Q[fb + 7] = q7
|
||||
Q[fb + 8] = q8
|
||||
local l2, l3, l4, l5 = L[fb + 2], L[fb + 3], L[fb + 4], L[fb + 5]
|
||||
local l6, l7, l8 = L[fb + 6], L[fb + 7], L[fb + 8]
|
||||
local sum = round + L[fb + 1] * q1 + l2 * q2 + l3 * q3 + l4 * q4 + l5 * q5 + l6 * q6 + l7 * q7 + l8 * q8
|
||||
if sum >= TWO31 or sum < -TWO31 then
|
||||
sum = (sum + TWO31) % TWO32 - TWO31
|
||||
end
|
||||
-- the steps follow the delay line's signs (x 1, 2, 2, 4)
|
||||
X[fb + 1] = x2
|
||||
X[fb + 2] = x3
|
||||
X[fb + 3] = x4
|
||||
X[fb + 4] = x5
|
||||
X[fb + 5] = 1 + 2 * floor(l5 * INV31) -- -1 for a negative value, else 1 (branch-free)
|
||||
X[fb + 6] = 2 + 4 * floor(l6 * INV31)
|
||||
X[fb + 7] = 2 + 4 * floor(l7 * INV31)
|
||||
X[fb + 8] = 4 + 8 * floor(l8 * INV31)
|
||||
E[c + 1] = value
|
||||
value += sum // fdiv
|
||||
-- the delay line: the last value and its first and second differences
|
||||
local n7 = value - l8
|
||||
local n6 = n7 - l7
|
||||
L[fb + 1] = l2
|
||||
L[fb + 2] = l3
|
||||
L[fb + 3] = l4
|
||||
L[fb + 4] = l5
|
||||
L[fb + 5] = n6 - l6
|
||||
L[fb + 6] = n6
|
||||
L[fb + 7] = n7
|
||||
L[fb + 8] = value
|
||||
-- the fixed predictor
|
||||
value += (last[c + 1] * (pk - 1)) // pk
|
||||
last[c + 1] = value
|
||||
cur[c + 1] = value
|
||||
end
|
||||
c += 1
|
||||
if c == C then
|
||||
-- inter-channel decorrelation: the last channel carries half the previous one, the others are differences
|
||||
c = 0
|
||||
local o = idx - C
|
||||
if C == 1 then
|
||||
P[idx] = cur[1]
|
||||
elseif C == 2 then
|
||||
local a = cur[1]
|
||||
local b = cur[2] + (if a >= 0 then a // 2 else -((-a) // 2))
|
||||
P[o + 1], P[o + 2] = b - a, b
|
||||
else
|
||||
local a = cur[C - 1]
|
||||
cur[C] += if a >= 0 then a // 2 else -((-a) // 2)
|
||||
for r = C - 1, 1, -1 do
|
||||
cur[r] = cur[r + 1] - cur[r]
|
||||
end
|
||||
for k = 1, C do
|
||||
P[o + k] = cur[k]
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if pos > lim then
|
||||
return nil, "truncated frame"
|
||||
end
|
||||
return n, nil
|
||||
end
|
||||
|
||||
return Decode
|
||||
@@ -0,0 +1,126 @@
|
||||
--!strict
|
||||
-- codecs/audio/Tta: the TTA1 (True Audio) lossless codec. A codec (layer 3). Written from the TTA1 format description
|
||||
-- (the 22-byte header with its CRC-32, the seek table of frame sizes with its CRC-32, frames of 256 / 245 seconds);
|
||||
-- no libtta / ffmpeg code (those are LGPL). The frame decoder is codecs/audio/Tta/Decode. Supports format 1 (plain
|
||||
-- PCM), 8 / 16 / 24 bits, any channel count, the header / seek table / frame CRCs. Not supported: format 2
|
||||
-- (password-protected: UNSUPPORTED), TTA2.
|
||||
--
|
||||
-- local info, err = Tta.info(buf, at, limit) -- the header at `at` (after any ID3v2 tag) + the frame table
|
||||
-- local dec = Tta.decoder(info)
|
||||
-- local n, err = dec:frame(buf, i) -- frame i (1-based) -> dec.pcm (interleaved integers)
|
||||
--
|
||||
-- Never throws: bad data returns nil, Err.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Decode = require("@formats/codecs/audio/Tta/Decode")
|
||||
|
||||
local Tta = {}
|
||||
|
||||
export type Info = {
|
||||
format: number,
|
||||
channels: number,
|
||||
bitsPerSample: number,
|
||||
sampleRate: number,
|
||||
samples: number, -- per channel
|
||||
frameLength: number, -- samples per frame (256 * rate / 245)
|
||||
frames: number,
|
||||
offsets: { number }, -- each frame's byte offset
|
||||
sizes: { number },
|
||||
}
|
||||
|
||||
-- info(buf, at, limit) -> Info | nil, Err: the TTA1 header at byte `at`
|
||||
function Tta.info(buf: buffer, at: number, limit: number): (Info?, Err.Err?)
|
||||
if at + 22 > limit then
|
||||
return nil, Err.new(Err.TRUNCATED, "truncated header")
|
||||
end
|
||||
if buffer.readstring(buf, at, 4) ~= "TTA1" then
|
||||
return nil, Err.new(Err.CORRUPT, "no TTA1 header")
|
||||
end
|
||||
if Crc32.of(buf, at, 18) ~= buffer.readu32(buf, at + 18) then
|
||||
return nil, Err.new(Err.CHECKSUM, "header CRC mismatch", at)
|
||||
end
|
||||
local format = buffer.readu16(buf, at + 4)
|
||||
local info: Info = {
|
||||
format = format,
|
||||
channels = buffer.readu16(buf, at + 6),
|
||||
bitsPerSample = buffer.readu16(buf, at + 8),
|
||||
sampleRate = buffer.readu32(buf, at + 10),
|
||||
samples = buffer.readu32(buf, at + 14),
|
||||
frameLength = 0,
|
||||
frames = 0,
|
||||
offsets = {},
|
||||
sizes = {},
|
||||
}
|
||||
if format == 2 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "password-protected TTA")
|
||||
elseif format ~= 1 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "TTA format " .. format)
|
||||
end
|
||||
local bits = info.bitsPerSample
|
||||
if bits ~= 8 and bits ~= 16 and bits ~= 24 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, bits .. "-bit TTA")
|
||||
end
|
||||
if info.channels < 1 or info.sampleRate < 1 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad header")
|
||||
end
|
||||
info.frameLength = (256 * info.sampleRate) // 245
|
||||
if info.frameLength < 1 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad sample rate")
|
||||
end
|
||||
local frames = (info.samples + info.frameLength - 1) // info.frameLength
|
||||
info.frames = frames
|
||||
local st = at + 22
|
||||
if st + frames * 4 + 4 > limit then
|
||||
return nil, Err.new(Err.TRUNCATED, "truncated seek table")
|
||||
end
|
||||
if Crc32.of(buf, st, frames * 4) ~= buffer.readu32(buf, st + frames * 4) then
|
||||
return nil, Err.new(Err.CHECKSUM, "seek table CRC mismatch", st)
|
||||
end
|
||||
local o = st + frames * 4 + 4
|
||||
for i = 1, frames do
|
||||
local size = buffer.readu32(buf, st + (i - 1) * 4)
|
||||
info.offsets[i] = o
|
||||
info.sizes[i] = size
|
||||
o += size
|
||||
end
|
||||
return info, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decoder
|
||||
export type Decoder = {
|
||||
info: Info,
|
||||
pcm: { number },
|
||||
limit: number,
|
||||
frame: (self: Decoder, buf: buffer, i: number) -> (number?, Err.Err?),
|
||||
state: Decode.State,
|
||||
}
|
||||
|
||||
local function frame(self: Decoder, buf: buffer, i: number): (number?, Err.Err?)
|
||||
local info = self.info
|
||||
if i < 1 or i > info.frames then
|
||||
return nil, Err.new(Err.ARG, "no frame " .. i)
|
||||
end
|
||||
local o, size = info.offsets[i], info.sizes[i]
|
||||
if o + size > self.limit then
|
||||
return nil, Err.new(Err.TRUNCATED, "frame " .. i .. " runs past the end", o)
|
||||
end
|
||||
local n = if i < info.frames then info.frameLength else info.samples - (info.frames - 1) * info.frameLength
|
||||
local got, msg = Decode.frame(self.state, buf, o, size, n, self.pcm)
|
||||
if not got then
|
||||
return nil, Err.from(msg, o)
|
||||
end
|
||||
return got, nil
|
||||
end
|
||||
|
||||
-- decoder(info, limit) -> Decoder (limit: the end of the file data)
|
||||
function Tta.decoder(info: Info, limit: number): Decoder
|
||||
return {
|
||||
info = info,
|
||||
pcm = table.create(info.frameLength * info.channels, 0),
|
||||
limit = limit,
|
||||
frame = frame,
|
||||
state = Decode.state(info.channels, info.bitsPerSample // 8),
|
||||
}
|
||||
end
|
||||
|
||||
return Tta
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,65 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/audio/WavPack/Tables: the WavPack log2 / exp2 tables and the conversions built on them (wp_log2, wp_exp2s,
|
||||
-- restore_weight). Ported from WavPack 5.9.0 entropy_utils.c (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt).
|
||||
local band, rshift, lshift, countlz = bit32.band, bit32.rshift, bit32.lshift, bit32.countlz
|
||||
|
||||
local Tables = {}
|
||||
|
||||
-- LOG2[x + 1], EXP2[x + 1] for x = 0 .. 255
|
||||
local LOG2: { number } = {
|
||||
0, 1, 3, 4, 6, 7, 9, 10, 11, 13, 14, 16, 17, 18, 20, 21, 22, 24, 25, 26, 28, 29, 30, 32, 33, 34, 36, 37, 38, 40, 41, 42,
|
||||
44, 45, 46, 47, 49, 50, 51, 52, 54, 55, 56, 57, 59, 60, 61, 62, 63, 65, 66, 67, 68, 69, 71, 72, 73, 74, 75, 77, 78, 79, 80, 81,
|
||||
82, 84, 85, 86, 87, 88, 89, 90, 92, 93, 94, 95, 96, 97, 98, 99, 100, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 116, 117,
|
||||
118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
|
||||
150, 151, 152, 153, 154, 155, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 178,
|
||||
179, 180, 181, 182, 183, 184, 185, 185, 186, 187, 188, 189, 190, 191, 192, 192, 193, 194, 195, 196, 197, 198, 198, 199, 200, 201, 202, 203, 203, 204, 205, 206,
|
||||
207, 208, 208, 209, 210, 211, 212, 212, 213, 214, 215, 216, 216, 217, 218, 219, 220, 220, 221, 222, 223, 224, 224, 225, 226, 227, 228, 228, 229, 230, 231, 231,
|
||||
232, 233, 234, 234, 235, 236, 237, 238, 238, 239, 240, 241, 241, 242, 243, 244, 244, 245, 246, 247, 247, 248, 249, 249, 250, 251, 252, 252, 253, 254, 255, 255,
|
||||
}
|
||||
local EXP2: { number } = {
|
||||
0, 1, 1, 2, 3, 3, 4, 5, 6, 6, 7, 8, 8, 9, 10, 11, 11, 12, 13, 14, 14, 15, 16, 16, 17, 18, 19, 19, 20, 21, 22, 22,
|
||||
23, 24, 25, 25, 26, 27, 28, 29, 29, 30, 31, 32, 32, 33, 34, 35, 36, 36, 37, 38, 39, 40, 40, 41, 42, 43, 44, 44, 45, 46, 47, 48,
|
||||
48, 49, 50, 51, 52, 53, 53, 54, 55, 56, 57, 58, 58, 59, 60, 61, 62, 63, 64, 65, 65, 66, 67, 68, 69, 70, 71, 72, 72, 73, 74, 75,
|
||||
76, 77, 78, 79, 80, 81, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105,
|
||||
106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 135, 136, 137, 138,
|
||||
139, 140, 141, 142, 143, 144, 145, 146, 147, 149, 150, 151, 152, 153, 154, 155, 156, 157, 159, 160, 161, 162, 163, 164, 165, 166, 168, 169, 170, 171, 172, 173,
|
||||
175, 176, 177, 178, 179, 180, 182, 183, 184, 185, 186, 188, 189, 190, 191, 192, 194, 195, 196, 197, 198, 200, 201, 202, 203, 205, 206, 207, 208, 210, 211, 212,
|
||||
214, 215, 216, 217, 219, 220, 221, 222, 224, 225, 226, 228, 229, 230, 232, 233, 234, 236, 237, 238, 240, 241, 242, 244, 245, 246, 248, 249, 250, 252, 253, 255,
|
||||
}
|
||||
|
||||
-- exp2s(log) -> the int32 the signed log stands for (wp_exp2s)
|
||||
function Tables.exp2s(lg: number): number
|
||||
if lg < 0 then
|
||||
local v = Tables.exp2s(-lg)
|
||||
v = -(if v >= 2147483648 then v - 4294967296 else v)
|
||||
return if v >= 2147483648 then v - 4294967296 else v
|
||||
end
|
||||
local value = bit32.bor(EXP2[band(lg, 255) + 1], 0x100)
|
||||
local k = lg // 256
|
||||
local r = if k <= 9 then rshift(value, 9 - k) else lshift(value, band(k - 9, 31))
|
||||
return if r >= 2147483648 then r - 4294967296 else r
|
||||
end
|
||||
|
||||
-- log2(v) -> wp_log2 of the uint32 v
|
||||
function Tables.log2(v: number): number
|
||||
v = (v + rshift(v, 9)) % 4294967296
|
||||
if v < 256 then
|
||||
local dbits = 32 - countlz(v)
|
||||
return dbits * 256 + LOG2[band(lshift(v, 9 - dbits), 255) + 1]
|
||||
end
|
||||
local dbits = 32 - countlz(v)
|
||||
return dbits * 256 + LOG2[band(rshift(v, dbits - 9), 255) + 1]
|
||||
end
|
||||
|
||||
-- restoreWeight(signed byte) -> the decorrelation weight (restore_weight)
|
||||
function Tables.restoreWeight(w: number): number
|
||||
local r = w * 8
|
||||
if r > 0 then
|
||||
r += (r + 64) // 128
|
||||
end
|
||||
return r
|
||||
end
|
||||
|
||||
return Tables
|
||||
@@ -0,0 +1,238 @@
|
||||
--!strict
|
||||
-- codecs/audio/WavPack: the WavPack 4 / 5 audio codec (the blocks of .wv files, and of WavPack in Matroska). A codec
|
||||
-- (layer 3). Ported from WavPack 5.9.0 (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt); the hot code is in
|
||||
-- codecs/audio/WavPack/Block. Lossless and hybrid (lossy, and lossless with the .wvc correction blocks), integer 8 - 32
|
||||
-- bit (with the extended int32 modes) and 32-bit float, mono / stereo / multichannel (one block per mono or stereo
|
||||
-- stream, INITIAL .. FINAL), every decorrelation pass (terms 1 - 8, 17, 18, -1 .. -3), joint stereo, cross
|
||||
-- decorrelation, noise shaping, block CRCs and block checksums. Not supported: DSD, pre-4.0 streams (version < 0x402).
|
||||
--
|
||||
-- local h, err = WavPack.header(buf, at, limit) -- the 32-byte block header at `at` (nil, message if none)
|
||||
-- local info, err = WavPack.info(buf, at, limit) -- stream facts from the first audio block (channels, rate, ...)
|
||||
-- local dec = WavPack.decoder(info.channels)
|
||||
-- local frames, err = dec:frame(buf, blocks, cbuf?, cblocks?) -- blocks = { offset, ... } of one frame (+ wvc)
|
||||
-- -- dec.pcm: interleaved samples (integers in the container range, or float values), WAV channel order
|
||||
--
|
||||
-- Never throws: bad data returns nil, Err.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Block = require("@formats/codecs/audio/WavPack/Block")
|
||||
|
||||
local WavPack = {}
|
||||
|
||||
export type Header = {
|
||||
size: number, -- the whole block (ckSize + 8)
|
||||
version: number,
|
||||
index: number, -- the first sample of the block (40 bits)
|
||||
total: number, -- total samples of the file (-1: unknown)
|
||||
samples: number,
|
||||
flags: number,
|
||||
crc: number,
|
||||
}
|
||||
|
||||
local RATES = { 6000, 8000, 9600, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000, 64000, 88200, 96000, 192000 }
|
||||
WavPack.MONO, WavPack.HYBRID, WavPack.FLOAT, WavPack.INITIAL, WavPack.FINAL = 4, 8, 0x80, 0x800, 0x1000
|
||||
WavPack.DSD = 0x80000000
|
||||
|
||||
-- header(buf, at, limit?) -> Header | nil, message: a valid "wvpk" block header at byte `at` whose block ends by limit
|
||||
function WavPack.header(buf: buffer, at: number, limit: number?): (Header?, string?)
|
||||
local lim = math.min(limit or buffer.len(buf), buffer.len(buf))
|
||||
if at < 0 or at + 32 > lim then
|
||||
return nil, "truncated block header"
|
||||
end
|
||||
if buffer.readstring(buf, at, 4) ~= "wvpk" then
|
||||
return nil, "no block header"
|
||||
end
|
||||
local ck = buffer.readu32(buf, at + 4)
|
||||
local version = buffer.readu16(buf, at + 8)
|
||||
if ck % 2 == 1 or ck < 24 or ck > 0x1000000 then
|
||||
return nil, "bad block size"
|
||||
end
|
||||
if version < 0x402 or version > 0x410 then
|
||||
return nil, "unsupported: stream version " .. string.format("0x%x", version)
|
||||
end
|
||||
local total = buffer.readu32(buf, at + 12)
|
||||
local tu8 = buffer.readu8(buf, at + 11)
|
||||
local h: Header = {
|
||||
size = ck + 8,
|
||||
version = version,
|
||||
index = buffer.readu32(buf, at + 16) + buffer.readu8(buf, at + 10) * 4294967296,
|
||||
total = if total == 0xFFFFFFFF then -1 else total + tu8 * 4294967296 - tu8,
|
||||
samples = buffer.readu32(buf, at + 20),
|
||||
flags = buffer.readu32(buf, at + 24),
|
||||
crc = buffer.readu32(buf, at + 28),
|
||||
}
|
||||
if at + h.size > lim then
|
||||
return nil, "truncated block"
|
||||
end
|
||||
return h, nil
|
||||
end
|
||||
|
||||
export type Info = {
|
||||
channels: number,
|
||||
channelMask: number,
|
||||
sampleRate: number,
|
||||
bitsPerSample: number, -- the source depth (container bytes * 8 - shift)
|
||||
bytesPerSample: number, -- the container: 1 .. 4
|
||||
float: boolean,
|
||||
hybrid: boolean,
|
||||
md5: string?, -- 32 hex digits when stored
|
||||
version: number,
|
||||
}
|
||||
|
||||
-- info(buf, at, limit?) -> Info | nil, Err: the facts of the stream whose first audio block is at `at`
|
||||
function WavPack.info(buf: buffer, at: number, limit: number?): (Info?, Err.Err?)
|
||||
local h, herr = WavPack.header(buf, at, limit)
|
||||
if not h then
|
||||
return nil, Err.from(herr, at)
|
||||
end
|
||||
local m, merr = Block.meta(buf, at, h.size)
|
||||
if not m then
|
||||
return nil, Err.from(merr, at)
|
||||
end
|
||||
local flags = h.flags
|
||||
if bit32.band(flags, WavPack.DSD) ~= 0 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "DSD audio")
|
||||
end
|
||||
local bytes = bit32.band(flags, 3) + 1
|
||||
local info: Info = {
|
||||
channels = if bit32.band(flags, WavPack.MONO) ~= 0 then 1 else 2,
|
||||
channelMask = 0,
|
||||
sampleRate = 44100,
|
||||
bitsPerSample = bytes * 8 - bit32.band(bit32.rshift(flags, 13), 31),
|
||||
bytesPerSample = bytes,
|
||||
float = bit32.band(flags, WavPack.FLOAT) ~= 0,
|
||||
hybrid = bit32.band(flags, WavPack.HYBRID) ~= 0,
|
||||
version = h.version,
|
||||
}
|
||||
info.channelMask = if info.channels == 1 then 4 else 3
|
||||
local sr = bit32.band(bit32.rshift(flags, 23), 15)
|
||||
if sr < 15 then
|
||||
info.sampleRate = RATES[sr + 1]
|
||||
end
|
||||
local o = m[0x27] -- ID_SAMPLE_RATE
|
||||
if o and (m[0x27 + 256] == 3 or m[0x27 + 256] == 4) then
|
||||
local rate = buffer.readu8(buf, o) + buffer.readu8(buf, o + 1) * 256 + buffer.readu8(buf, o + 2) * 65536
|
||||
if m[0x27 + 256] == 4 then
|
||||
rate += bit32.band(buffer.readu8(buf, o + 3), 0x7F) * 16777216
|
||||
end
|
||||
info.sampleRate = rate
|
||||
end
|
||||
o = m[0xD] -- ID_CHANNEL_INFO
|
||||
if o then
|
||||
local len = m[0xD + 256]
|
||||
if len == 0 or len > 7 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad channel info", o)
|
||||
end
|
||||
local mask = 0
|
||||
if len >= 6 then
|
||||
info.channels = buffer.readu8(buf, o) + bit32.band(buffer.readu8(buf, o + 2), 0xF) * 256 + 1
|
||||
mask = buffer.readu8(buf, o + 3) + buffer.readu8(buf, o + 4) * 256 + buffer.readu8(buf, o + 5) * 65536
|
||||
if len == 7 then
|
||||
mask += buffer.readu8(buf, o + 6) * 16777216
|
||||
end
|
||||
else
|
||||
info.channels = buffer.readu8(buf, o)
|
||||
for k = 1, len - 1 do
|
||||
mask += buffer.readu8(buf, o + k) * 256 ^ (k - 1)
|
||||
end
|
||||
end
|
||||
info.channelMask = mask
|
||||
end
|
||||
if info.channels < 1 then
|
||||
return nil, Err.new(Err.CORRUPT, "no channels")
|
||||
end
|
||||
if info.sampleRate < 1 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad sample rate")
|
||||
end
|
||||
return info, nil
|
||||
end
|
||||
|
||||
-- md5(buf, at, limit?) -> 32 hex digits | nil: an ID_MD5_CHECKSUM in the block at `at`
|
||||
function WavPack.md5(buf: buffer, at: number, limit: number?): string?
|
||||
local h = WavPack.header(buf, at, limit)
|
||||
if not h then
|
||||
return nil
|
||||
end
|
||||
local m = Block.meta(buf, at, h.size)
|
||||
if not m then
|
||||
return nil
|
||||
end
|
||||
local o = m[0x26]
|
||||
if not o or m[0x26 + 256] ~= 16 then
|
||||
return nil
|
||||
end
|
||||
local hex = table.create(16, "")
|
||||
for k = 0, 15 do
|
||||
hex[k + 1] = string.format("%02x", buffer.readu8(buf, o + k))
|
||||
end
|
||||
return table.concat(hex)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decoder
|
||||
export type Decoder = {
|
||||
channels: number,
|
||||
pcm: { number }, -- the last frame's samples, interleaved (integers in the container range, or floats)
|
||||
frame: (self: Decoder, buf: buffer, blocks: { number }, cbuf: buffer?, cblocks: { number }?) -> (number?, Err.Err?),
|
||||
state: Block.State,
|
||||
}
|
||||
|
||||
-- frame(buf, blocks, cbuf?, cblocks?) -> frames | nil, Err: decode one frame (the blocks of one sample range, one per
|
||||
-- mono / stereo stream, in channel order) into dec.pcm; cblocks are the matching .wvc blocks (hybrid lossless)
|
||||
local function frame(self: Decoder, buf: buffer, blocks: { number }, cbuf: buffer?, cblocks: { number }?): (number?, Err.Err?)
|
||||
local C = self.channels
|
||||
local n = -1
|
||||
local c0 = 0
|
||||
for i, at in blocks do
|
||||
if c0 >= C then
|
||||
break
|
||||
end
|
||||
local h, herr = WavPack.header(buf, at)
|
||||
if not h then
|
||||
return nil, Err.from(herr, at)
|
||||
end
|
||||
if n < 0 then
|
||||
n = h.samples
|
||||
if n * C > 16777216 then
|
||||
return nil, Err.new(Err.LIMIT, "a frame of " .. n .. " samples x " .. C .. " channels", at)
|
||||
end
|
||||
if #self.pcm < n * C then
|
||||
self.pcm = table.create(n * C, 0)
|
||||
end
|
||||
elseif h.samples ~= n then
|
||||
return nil, Err.new(Err.CORRUPT, "blocks of a frame differ in length", at)
|
||||
end
|
||||
local cb, cp, cs = nil, nil, nil
|
||||
if cbuf and cblocks and cblocks[i] then
|
||||
local ch = WavPack.header(cbuf, cblocks[i])
|
||||
if ch and ch.samples == h.samples and ch.index == h.index then
|
||||
cb, cp, cs = cbuf, cblocks[i], ch.size
|
||||
end
|
||||
end
|
||||
local got, msg = Block.decode(self.state, buf, at, h.size, self.pcm, c0, C, cb, cp, cs)
|
||||
if not got then
|
||||
return nil, Err.from(msg, at)
|
||||
end
|
||||
c0 += got
|
||||
end
|
||||
if n < 0 then
|
||||
return 0, nil
|
||||
end
|
||||
if c0 < C then
|
||||
return nil, Err.new(Err.CORRUPT, "a frame is missing channels")
|
||||
end
|
||||
return n, nil
|
||||
end
|
||||
|
||||
-- decoder(channels) -> Decoder
|
||||
function WavPack.decoder(channels: number): Decoder
|
||||
return {
|
||||
channels = channels,
|
||||
pcm = table.create(4096 * channels, 0),
|
||||
frame = frame,
|
||||
state = Block.state(),
|
||||
}
|
||||
end
|
||||
|
||||
WavPack.checksum = Block.checksum
|
||||
WavPack.meta = Block.meta
|
||||
|
||||
return WavPack
|
||||
@@ -8,7 +8,8 @@
|
||||
-- flac -> "fLaC" + the metadata blocks (CodecPrivate / dfLa) + the frames;
|
||||
-- opus -> Ogg Opus (OpusHead from the config or made up, OpusTags, packets with granules from their TOC durations);
|
||||
-- vorbis -> Ogg Vorbis (the three headers from Matroska's Xiph-laced CodecPrivate or MP4's esds-less layout);
|
||||
-- aac -> ADTS (from the AudioSpecificConfig) for audio/aac.
|
||||
-- aac -> ADTS (from the AudioSpecificConfig) for audio/aac;
|
||||
-- ac3 -> the syncframes back to back (format "ac3"; E-AC-3 tracks stay UNSUPPORTED).
|
||||
--
|
||||
-- local buf, format, err = AudioWrap.wrap(demuxer, track) -- then F.open(buf, { format = format })
|
||||
local Err = require("@formats/core/Err")
|
||||
@@ -407,6 +408,9 @@ function AudioWrap.wrap(dmx: any, track: Types.Track): (buffer?, string?, Err.Er
|
||||
if codec == "mp3" or codec == "mp2" or codec == "mp1" then
|
||||
return concat(packets), "mp3", nil
|
||||
end
|
||||
if codec == "ac3" then
|
||||
return concat(packets), "ac3", nil
|
||||
end
|
||||
if codec == "flac" then
|
||||
local c = track.config
|
||||
local prefix: buffer? = nil
|
||||
|
||||
+21
-3
@@ -279,9 +279,12 @@ end
|
||||
-- the embedded parts) when called directly.
|
||||
-- They also see the injected plug-ins as opts.plugins (F.plugins: the B-rep kernel for cad/step) unless given their own.
|
||||
--
|
||||
-- Tracker modules inside other files (music/umx): opts.decodeModule(buf, format?) -> Module | nil, Err, the bytes loaded
|
||||
-- as music (sniffed, or as the given format).
|
||||
--
|
||||
-- Audio tracks of video containers: opts.openAudio(demuxer, track) -> audio Decoder | nil, Err. The track's packets
|
||||
-- become a stream an audio format reads (containers/AudioWrap: PCM -> WAV, Opus / Vorbis -> Ogg, AAC -> ADTS, MP3 /
|
||||
-- FLAC as they are), opened through F.open with that format.
|
||||
-- FLAC / AC-3 as they are), opened through F.open with that format.
|
||||
local function openAudio(demuxer: any, track: any): (any, Err.Err?)
|
||||
local buf, fmt, err = AudioWrap.wrap(demuxer, track)
|
||||
if not buf then
|
||||
@@ -302,7 +305,7 @@ local function openAudio(demuxer: any, track: any): (any, Err.Err?)
|
||||
end
|
||||
|
||||
local function withHooks(o: Options): Options
|
||||
if o.decodeImage ~= nil and o.encodeImage ~= nil and o.plugins ~= nil and o.openAudio ~= nil then
|
||||
if o.decodeImage ~= nil and o.encodeImage ~= nil and o.plugins ~= nil and o.openAudio ~= nil and o.decodeModule ~= nil then
|
||||
return o
|
||||
end
|
||||
local c = table.clone(o)
|
||||
@@ -322,6 +325,12 @@ local function withHooks(o: Options): Options
|
||||
return F.save(img, nil, { format = format, category = "image" })
|
||||
end
|
||||
end
|
||||
if c.decodeModule == nil then
|
||||
-- tracker modules inside other files (music/umx: the module of an Unreal package), as their own format
|
||||
c.decodeModule = function(b: buffer, format: string?): (any, Err.Err?)
|
||||
return F.load(b, { category = "music", format = format })
|
||||
end
|
||||
end
|
||||
return c
|
||||
end
|
||||
|
||||
@@ -482,8 +491,10 @@ local function videoToImage(v: any, o: Options): (any, Err.Err?)
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- renderMusic(value, opts) -> the audio Decoder of a Module (codecs/audio/Tracker) or a Midi (music/midi render) |
|
||||
-- renderMusic(value, opts) -> the audio Decoder of a Module (codecs/audio/Tracker, or the Module's own render method
|
||||
-- for other engines) or a Midi (music/midi render) |
|
||||
-- nil, Err. opts are the render options: sampleRate, soundfont, gain, tail, interpolation, stereoSeparation, ...
|
||||
local TRACKER_FAMILY = { mod = true, s3m = true, xm = true, it = true }
|
||||
local function renderMusic(value: any, o: Options): (any, Err.Err?)
|
||||
local ok, dec, err
|
||||
if value.kind == "midi" then
|
||||
@@ -492,6 +503,13 @@ local function renderMusic(value: any, o: Options): (any, Err.Err?)
|
||||
return nil, merr
|
||||
end
|
||||
ok, dec, err = pcall(m.render, value, o)
|
||||
elseif TRACKER_FAMILY[value.engine or value.format] == nil and type(value.render) == "function" then
|
||||
-- a Module with its own engine (AHX / HVL: codecs/audio/Hively): its render method (a failed render is an
|
||||
-- empty Decoder carrying .err)
|
||||
ok, dec = pcall(value.render, value, o)
|
||||
if ok and type(dec) == "table" and dec.err then
|
||||
return nil, dec.err
|
||||
end
|
||||
else
|
||||
local Tracker: any = require("@formats/codecs/audio/Tracker")
|
||||
ok, dec, err = pcall(Tracker.render, value, o)
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
--!strict
|
||||
-- music/669: Composer 669 and UNIS 669 modules ("if" / "JN"; 8 channels, 64-row patterns with their own speed and
|
||||
-- break row). Ported from OpenMPT's Load_669.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the
|
||||
-- codecs/audio/Tracker Module and plays as the "s3m" effect family with 669's quirks (flags): periods in Hz (slides
|
||||
-- move the frequency 80 Hz per step, tone portamento 40 Hz), slides on every tick, auto portamentos that run until
|
||||
-- the channel's next effect, a tone portamento that keeps going, frequency adjust (D), frequency vibrato (E), speed (F),
|
||||
-- UNIS 669 balance slides (G) and slot retrigger (H). The tempo is fixed (78 BPM in tracker terms).
|
||||
-- Not supported: UNIS 669's "super fast" speed 0, writing.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Tracker = require("@formats/codecs/audio/Tracker")
|
||||
local Load = require("@formats/codecs/audio/Tracker/Load")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Six69 = {
|
||||
name = "669",
|
||||
category = "music",
|
||||
extensions = { "669" },
|
||||
mime = { "audio/x-669" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
|
||||
caps = { decode = true, encode = false, render = true, channels = { 8, 8 } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local IT = Load.IT
|
||||
-- the 669 effects (high nibble of the effect byte) by name
|
||||
local EFFECTS = { "autoportaup", "autoportadown", "toneporta", "freqadjust", "vibrato", "speed", "panslide", "retrig" }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
-- the 497-byte header is valid (669 has a two-byte magic only, so the rest is checked too)
|
||||
local function validHeader(r: Bytes.Reader): boolean
|
||||
if r:size() < 497 then
|
||||
return false
|
||||
end
|
||||
local magic = r:peek(2)
|
||||
if magic ~= "if" and magic ~= "JN" then
|
||||
return false
|
||||
end
|
||||
local nsmp, npat, restart = r:peekU8(110), r:peekU8(111), r:peekU8(112)
|
||||
if nsmp > 64 or restart >= 128 or npat > 128 then
|
||||
return false
|
||||
end
|
||||
local bad = 0
|
||||
for i = 2, 109 do
|
||||
local c = r:peekU8(i)
|
||||
if c > 0 and c <= 31 then
|
||||
bad += 1
|
||||
if bad > 40 then
|
||||
return false
|
||||
end
|
||||
end
|
||||
end
|
||||
for i = 0, 127 do
|
||||
local o, t, b = r:peekU8(113 + i), r:peekU8(241 + i), r:peekU8(369 + i)
|
||||
if (o >= 128 and o < 0xFE) or (o < 128 and t == 0) or t > 15 or b >= 64 then
|
||||
return false
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
function Six69.sniff(r: Bytes.Reader): number
|
||||
return if validHeader(r) then 0.6 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Six69.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local budget = { left = opts and opts.maxBytes or 2 ^ 28 }
|
||||
if not validHeader(r) then
|
||||
return nil, Err.new(if r:size() < 497 then Err.TRUNCATED else Err.CORRUPT, "not a 669 module")
|
||||
end
|
||||
local extended = r:peek(2) == "JN"
|
||||
r:skip(2)
|
||||
local message = r:string(108)
|
||||
local nsmp, npat, restart = r:u8(), r:u8(), r:u8()
|
||||
local orders, tempos, breaks = {}, {}, {}
|
||||
for i = 1, 128 do
|
||||
orders[i] = r:u8()
|
||||
end
|
||||
for i = 1, 128 do
|
||||
tempos[i] = r:u8()
|
||||
end
|
||||
for i = 1, 128 do
|
||||
breaks[i] = r:u8()
|
||||
end
|
||||
if not r:need(nsmp * 25 + npat * 1536) then
|
||||
return nil, r.err
|
||||
end
|
||||
local m = Tracker.newModule("669", 8, "s3m")
|
||||
m.title = (string.gsub(string.sub(message, 1, 36), "[%z ]+$", ""))
|
||||
m.meta.message = message
|
||||
m.speed, m.tempo = 4, 78
|
||||
m.linear = false
|
||||
m.instrumentMode = false
|
||||
m.flags.periods, m.flags.hzSlide, m.flags.hzTonePorta = "hz", 20, 0.5
|
||||
m.flags.fastPortas, m.flags.autoTonePorta, m.flags.autoReset = true, true, true
|
||||
for i = 1, 8 do
|
||||
m.channelPan[i] = if i % 2 == 0 then 0xD0 else 0x30
|
||||
end
|
||||
local lengths: { number } = {}
|
||||
for i = 1, nsmp do
|
||||
local s = Tracker.newSample(r:fixed(13))
|
||||
local len, ls, le = r:u32le(), r:u32le(), r:u32le()
|
||||
if len >= 0x4000000 then
|
||||
return nil, Err.new(Err.CORRUPT, "sample " .. i .. " too long")
|
||||
end
|
||||
s.c5speed = 8363
|
||||
if not (le > len and ls == 0) and le ~= 0 then
|
||||
s.loopStart, s.loopEnd, s.loopType = ls, math.min(le, len), 1
|
||||
end
|
||||
lengths[i] = len
|
||||
m.samples[i] = s
|
||||
end
|
||||
for i = 1, 128 do
|
||||
m.order[i] = orders[i]
|
||||
end
|
||||
while #m.order > 0 and m.order[#m.order] == 255 do
|
||||
table.remove(m.order)
|
||||
end
|
||||
if orders[restart + 1] < npat then
|
||||
m.restart = restart
|
||||
end
|
||||
-- patterns: 64 rows x 8 channels x 3 bytes (note / instrument, instrument / volume, effect / parameter)
|
||||
local buf = r.buf
|
||||
for p = 0, npat - 1 do
|
||||
local pat = Tracker.newPattern(64, 8)
|
||||
m.patterns[p + 1] = pat
|
||||
local d = pat.data
|
||||
local effect = table.create(8, 0xFF) -- the last effect per channel (balance slides repeat)
|
||||
for row = 0, 63 do
|
||||
for ch = 0, 7 do
|
||||
local o = r.pos + (row * 8 + ch) * 3
|
||||
local ni, iv, ep = buffer.readu8(buf, o), buffer.readu8(buf, o + 1), buffer.readu8(buf, o + 2)
|
||||
local q = (row * 8 + ch) * 5
|
||||
local hasNote = ni < 0xFE
|
||||
if hasNote then
|
||||
buffer.writeu8(d, q, ni // 4 + 37)
|
||||
buffer.writeu8(d, q + 1, (ni % 4) * 16 + iv // 16 + 1)
|
||||
effect[ch + 1] = 0xFF
|
||||
end
|
||||
if ni <= 0xFE then
|
||||
buffer.writeu8(d, q + 2, ((iv % 16) * 64 + 8) // 15 + 1)
|
||||
end
|
||||
if ep ~= 0xFF then
|
||||
effect[ch + 1] = ep
|
||||
end
|
||||
local e = effect[ch + 1]
|
||||
if e ~= 0xFF then
|
||||
local cmd, param = e // 16, e % 16
|
||||
local name = EFFECTS[cmd + 1]
|
||||
if cmd == 4 then
|
||||
param = param * 17 -- vibrato: speed = depth
|
||||
elseif cmd == 6 then
|
||||
param = if param == 0 then 0x4F elseif param == 1 then 0xF4 else -1
|
||||
elseif cmd == 7 and not (hasNote and extended) then
|
||||
name = nil
|
||||
end
|
||||
if name ~= "panslide" then
|
||||
effect[ch + 1] = 0xFF
|
||||
end
|
||||
if name and param >= 0 then
|
||||
buffer.writeu8(d, q + 3, IT[name])
|
||||
buffer.writeu8(d, q + 4, param)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
r:skip(1536)
|
||||
if breaks[p + 1] < 63 then
|
||||
Load.writeEffect(m, p, breaks[p + 1], IT["break"], 0, "next")
|
||||
end
|
||||
Load.writeEffect(m, p, 0, IT.speed, tempos[p + 1], "next")
|
||||
end
|
||||
-- sample data: unsigned 8-bit
|
||||
local pos = r.pos
|
||||
for i = 1, nsmp do
|
||||
local s = m.samples[i]
|
||||
local ok, err = Load.readSample(buf, pos, lengths[i], { bits = 8, signed = false, limit = r.limit }, s, budget)
|
||||
if not ok then
|
||||
return nil, err
|
||||
end
|
||||
pos += lengths[i]
|
||||
end
|
||||
m.meta.source = { format = "669", tracker = if extended then "UNIS 669" else "Composer 669" }
|
||||
local ok, verr = Tracker.validate(m)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module")
|
||||
end
|
||||
return m, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions)
|
||||
function Six69.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
|
||||
local m, err = Six69.decode(r, opts)
|
||||
if not m then
|
||||
return nil, err
|
||||
end
|
||||
return Tracker.render(m, opts)
|
||||
end
|
||||
|
||||
return Six69
|
||||
@@ -0,0 +1,53 @@
|
||||
--!strict
|
||||
-- music/ahx: AHX (Abyss' Highest eXperience) modules, "THX\0" .. "THX\2": 4-channel Amiga synth tunes (no samples:
|
||||
-- triangle / sawtooth / square / noise waveforms through filters, square modulation, the PList instrument programs).
|
||||
-- Loads into a Types.Module-shaped value (kind "music", format "ahx": tracks as patterns, positions with per-channel
|
||||
-- transposes, instruments with play lists, subsongs) and renders through codecs/audio/Hively, a port of HivelyTracker's
|
||||
-- hvl2wav replayer (BSD-3-Clause): at 44.1 kHz with stereo = 0 the samples equal hvl2wav's.
|
||||
-- Not supported: writing.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Hively = require("@formats/codecs/audio/Hively")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Ahx = {
|
||||
name = "ahx",
|
||||
category = "music",
|
||||
extensions = { "ahx", "thx" },
|
||||
mime = { "audio/x-ahx" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Hively" },
|
||||
caps = { decode = true, encode = false, render = true, channels = { 4, 4 }, subsongs = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type RenderOptions = Hively.RenderOptions -- sampleRate, subsong, stereo (0..4), loop, maxDuration
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Ahx.sniff(r: Bytes.Reader): number
|
||||
local m = r:peek(4)
|
||||
return if m and #m == 4 and string.sub(m, 1, 3) == "THX" and string.byte(m, 4) < 3 then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Ahx.decode(r: Bytes.Reader, _opts: any?): (Types.Module?, Err.Err?)
|
||||
local tune, err = Hively.parse(r.buf, r.base, r.limit)
|
||||
if not tune or tune.format ~= "ahx" then
|
||||
return nil, err or Err.new(Err.CORRUPT, "not an AHX module")
|
||||
end
|
||||
return Hively.module(tune), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> the rendered audio Decoder (opts: RenderOptions)
|
||||
function Ahx.open(r: Bytes.Reader, opts: RenderOptions?): (Types.Decoder?, Err.Err?)
|
||||
local song, err = Ahx.decode(r)
|
||||
if not song then
|
||||
return nil, err
|
||||
end
|
||||
return Hively.decoder((song :: any).tune, opts)
|
||||
end
|
||||
|
||||
return Ahx
|
||||
@@ -0,0 +1,232 @@
|
||||
--!strict
|
||||
-- music/far: Farandole Composer modules (FAR, Daniel Potter's DOS tracker; 16 channels, up to 256 patterns of any
|
||||
-- length with a break row, 64 samples). Ported from OpenMPT's Load_far.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads
|
||||
-- into the codecs/audio/Tracker Module and plays as the "s3m" effect family with Farandole's quirks (flags): periods
|
||||
-- in Hz (a slide step moves the frequency 36318 / 1024 Hz), a tone portamento that keeps going, fine pitch slides,
|
||||
-- retrigger, vibrato depth / speed, volume slides, volume portamento (as a set volume), panning, speed; the fixed
|
||||
-- tempo OpenMPT uses (80 BPM in tracker terms).
|
||||
-- Not supported: Farandole's own tempo model (fine tempo up / down, D / E), the note-offset effect (C), writing.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Tracker = require("@formats/codecs/audio/Tracker")
|
||||
local Load = require("@formats/codecs/audio/Tracker/Load")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Far = {
|
||||
name = "far",
|
||||
category = "music",
|
||||
extensions = { "far" },
|
||||
mime = { "audio/x-far" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
|
||||
caps = { decode = true, encode = false, render = true, channels = { 16, 16 } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local IT = Load.IT
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Far.sniff(r: Bytes.Reader): number
|
||||
if r:size() >= 98 and r:peek(4) == "FAR\xFE" and r:peek(3, 44) == "\r\n\x1A" and r:peekU8(47) + r:peekU8(48) * 256 >= 98 then
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- a pattern cell's effect byte -> effect code, parameter, volume byte (S3M coding, 0 = none) (OpenMPT's table)
|
||||
local function effect(e: number): (number, number, number)
|
||||
local cmd, p = e // 16, e % 16
|
||||
if cmd == 1 then
|
||||
return IT.portaup, 0xF0 + p, 0
|
||||
elseif cmd == 2 then
|
||||
return IT.portadown, 0xF0 + p, 0
|
||||
elseif cmd == 3 then
|
||||
return IT.toneporta, if p ~= 0 then 60 // p else 0, 0
|
||||
elseif cmd == 4 then
|
||||
return IT.retrig, 6 // (1 + p) + 1, 0
|
||||
elseif cmd == 5 or cmd == 9 then
|
||||
return IT.vibrato, p, 0
|
||||
elseif cmd == 6 then
|
||||
return IT.vibrato, p * 8, 0
|
||||
elseif cmd == 7 then
|
||||
return IT.volslide, p * 8, 0
|
||||
elseif cmd == 8 then
|
||||
return IT.volslide, p, 0
|
||||
elseif cmd == 0xA then
|
||||
return 0, 0, p * 4 + 4 + 1 -- volume portamento: a set volume
|
||||
elseif cmd == 0xB then
|
||||
return IT.s3mex, 0x80 + p, 0
|
||||
elseif cmd == 0xF then
|
||||
return IT.speed, p, 0
|
||||
end
|
||||
return 0, 0, 0
|
||||
end
|
||||
|
||||
function Far.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local budget = { left = opts and opts.maxBytes or 2 ^ 28 }
|
||||
if Far.sniff(r) == 0 then
|
||||
return nil, Err.new(if r:size() < 98 then Err.TRUNCATED else Err.CORRUPT, "not a Farandole module")
|
||||
end
|
||||
r:skip(4)
|
||||
local title = r:fixed(40)
|
||||
r:skip(3)
|
||||
local headerLength, version = r:u16le(), r:u8()
|
||||
local onOff, pans = {}, {}
|
||||
for i = 1, 16 do
|
||||
onOff[i] = r:u8()
|
||||
end
|
||||
r:skip(9)
|
||||
local speed = r:u8()
|
||||
for i = 1, 16 do
|
||||
pans[i] = r:u8()
|
||||
end
|
||||
r:skip(4)
|
||||
local msgLen = r:u16le()
|
||||
local message = r:string(msgLen)
|
||||
local orders = {}
|
||||
for i = 1, 256 do
|
||||
orders[i] = r:u8()
|
||||
end
|
||||
local _npat, nord, restart = r:u8(), r:u8(), r:u8()
|
||||
local sizes = {}
|
||||
for i = 1, 256 do
|
||||
sizes[i] = r:u16le()
|
||||
end
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
local m = Tracker.newModule("far", 16, "s3m")
|
||||
m.title = title
|
||||
m.meta.message = message
|
||||
m.speed, m.tempo = if speed > 0 then speed else 4, 80
|
||||
m.mixVolume = 32 -- OpenMPT's pre-amp for FAR
|
||||
m.linear = false
|
||||
m.instrumentMode = false
|
||||
m.flags.periods, m.flags.hzSlide = "hz", 36318 / 1024
|
||||
m.flags.autoTonePorta = true
|
||||
for i = 1, 16 do
|
||||
m.channelMute[i] = onOff[i] == 0
|
||||
m.channelPan[i] = (pans[i] % 16) * 16 + 8
|
||||
end
|
||||
for i = 1, nord do
|
||||
m.order[i] = orders[i]
|
||||
end
|
||||
while #m.order > 0 and m.order[#m.order] == 255 do
|
||||
table.remove(m.order)
|
||||
end
|
||||
m.restart = restart
|
||||
-- patterns: (size - 2) / 64 rows of 16 channels x (note, instrument, volume, effect), after a break row byte
|
||||
if not r:seek(headerLength) then
|
||||
return nil, r.err
|
||||
end
|
||||
local last = -1
|
||||
for p = 0, 255 do
|
||||
if sizes[p + 1] > 0 then
|
||||
last = p
|
||||
end
|
||||
end
|
||||
for p = 0, last do
|
||||
local size = sizes[p + 1]
|
||||
local rows = math.clamp((size - 2) // 64, 1, 1024)
|
||||
local pat = Tracker.newPattern(if size > 0 then rows else 64, 16)
|
||||
m.patterns[p + 1] = pat
|
||||
if size > 0 then
|
||||
local pr = r:slice(size)
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
local br = pr:u8()
|
||||
pr:skip(1)
|
||||
local d = pat.data
|
||||
for row = 0, rows - 1 do
|
||||
for ch = 0, 15 do
|
||||
local note, ins, vol, e = pr:u8(), pr:u8(), pr:u8(), pr:u8()
|
||||
if pr.err then
|
||||
break
|
||||
end
|
||||
local q = (row * 16 + ch) * 5
|
||||
if note > 0 and note <= 72 then
|
||||
buffer.writeu8(d, q, note + 36)
|
||||
buffer.writeu8(d, q + 1, ins + 1)
|
||||
end
|
||||
if vol > 0 and vol <= 16 then
|
||||
buffer.writeu8(d, q + 2, (vol - 1) * 64 // 15 + 1)
|
||||
end
|
||||
local fx, param, setVol = effect(e)
|
||||
if setVol > 0 then
|
||||
buffer.writeu8(d, q + 2, setVol)
|
||||
end
|
||||
buffer.writeu8(d, q + 3, fx)
|
||||
buffer.writeu8(d, q + 4, param)
|
||||
end
|
||||
end
|
||||
if br > 0 and br < rows - 2 then
|
||||
Load.writeEffect(m, p, br + 1, IT["break"], 0, "next")
|
||||
end
|
||||
end
|
||||
end
|
||||
-- samples: a 64-bit map of the stored ones, each a 48-byte header + signed 8 / 16-bit data
|
||||
local map = {}
|
||||
for i = 1, 8 do
|
||||
map[i] = r:u8()
|
||||
end
|
||||
r.err = nil
|
||||
for i = 0, 63 do
|
||||
if bit32.band(map[i // 8 + 1] or 0, bit32.lshift(1, i % 8)) ~= 0 then
|
||||
local h = r:slice(48)
|
||||
if r.err then
|
||||
break
|
||||
end
|
||||
local s = Tracker.newSample(h:fixed(32))
|
||||
local len = h:u32le()
|
||||
h:skip(1)
|
||||
local vol = h:u8()
|
||||
local ls, le = h:u32le(), h:u32le()
|
||||
local typ, loop = h:u8(), h:u8()
|
||||
local bits = if typ % 2 == 1 then 16 else 8
|
||||
local frames = if bits == 16 then len // 2 else len
|
||||
if bits == 16 then
|
||||
ls, le = ls // 2, le // 2
|
||||
end
|
||||
s.c5speed = 8363 * 2
|
||||
s.volume = math.min(vol * 4, 64)
|
||||
local ok, err = Load.readSample(r.buf, r.pos, frames, { bits = bits, signed = true, limit = r.limit }, s, budget)
|
||||
if not ok then
|
||||
return nil, err
|
||||
end
|
||||
r:skip(math.min(len, r:remaining()))
|
||||
if bit32.band(loop, 8) ~= 0 and le > ls then
|
||||
s.loopStart, s.loopEnd, s.loopType = ls, math.min(le, s.length), 1
|
||||
end
|
||||
for k = #m.samples + 1, i do
|
||||
m.samples[k] = Tracker.newSample()
|
||||
end
|
||||
m.samples[i + 1] = s
|
||||
end
|
||||
end
|
||||
m.meta.source = { format = "far", version = version }
|
||||
local ok, verr = Tracker.validate(m)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module")
|
||||
end
|
||||
return m, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions)
|
||||
function Far.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
|
||||
local m, err = Far.decode(r, opts)
|
||||
if not m then
|
||||
return nil, err
|
||||
end
|
||||
return Tracker.render(m, opts)
|
||||
end
|
||||
|
||||
return Far
|
||||
@@ -0,0 +1,273 @@
|
||||
--!strict
|
||||
-- music/hmp: Human Machine Interfaces SOS music: HMP ("HMIMIDIP", and the newer "HMIMIDIP013195" with the bigger header)
|
||||
-- and HMI ("HMI-MIDISONG061595"), as used by Descent, Duke Nukem 3D's predecessors and other DOS games. Written from the
|
||||
-- HMP / HMI layout notes (header fields, chunk tables, the reversed delta encoding of HMP, HMI's note durations and FE
|
||||
-- events); wildmidi was used only as a reference converter in tests. Decodes to a Types.Midi (format 1, one track per
|
||||
-- chunk): HMP deltas (7-bit groups least significant first, the last byte flagged) and running status; loop marker
|
||||
-- controllers 110 / 111 with a value above 127 are skipped (meta.source.loops counts them); HMI note-ons carry a
|
||||
-- duration that becomes a note-off (velocity 64), HMI-only FE events are skipped. Time: the header's tick rate (HMP
|
||||
-- at 0x38, HMI byte 212) in ticks per second, as division 60 at 60000000 / rate us per quarter; tempo events in the
|
||||
-- tracks apply on top. Renders through codecs/audio/MidiRender.
|
||||
-- Not supported: writing; HMP branch tables (skipped).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Render = require("@formats/codecs/audio/MidiRender")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Hmp = {
|
||||
name = "hmp",
|
||||
category = "music",
|
||||
extensions = { "hmp", "hmi" },
|
||||
mime = { "audio/x-hmp" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/MidiRender" },
|
||||
caps = { decode = true, encode = false, render = true, hmi = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxEvents: number?, -- default 2^24
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
local HMI_MAGIC = "HMI-MIDISONG061595"
|
||||
|
||||
function Hmp.sniff(r: Bytes.Reader): number
|
||||
return if r:peek(8) == "HMIMIDIP" or r:peek(18) == HMI_MAGIC then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local readu8, readu32 = buffer.readu8, buffer.readu32
|
||||
local DATA = { [8] = 2, [9] = 2, [10] = 2, [11] = 2, [12] = 1, [13] = 1, [14] = 2 }
|
||||
local TYPES = { [8] = "noteOff", [9] = "noteOn", [10] = "aftertouch", [11] = "controller", [12] = "program", [13] = "channelPressure", [14] = "pitchBend" }
|
||||
|
||||
-- a delta at p -> value, next p (nil past e). hmp: least significant group first, the last byte has bit 7 set;
|
||||
-- otherwise the MIDI encoding
|
||||
local function delta(b: buffer, p: number, e: number, hmp: boolean): (number?, number)
|
||||
local v, shift = 0, 1
|
||||
for _ = 1, 5 do
|
||||
if p >= e then
|
||||
return nil, p
|
||||
end
|
||||
local c = readu8(b, p)
|
||||
p += 1
|
||||
if hmp then
|
||||
v += (c % 128) * shift
|
||||
shift *= 128
|
||||
if c >= 128 then
|
||||
return v, p
|
||||
end
|
||||
else
|
||||
v = v * 128 + c % 128
|
||||
if c < 128 then
|
||||
return v, p
|
||||
end
|
||||
end
|
||||
end
|
||||
return nil, p
|
||||
end
|
||||
|
||||
local function bytes(b: buffer, p: number, n: number): { number }
|
||||
local t: { number } = table.create(n) :: { number }
|
||||
for i = 1, n do
|
||||
t[i] = readu8(b, p + i - 1)
|
||||
end
|
||||
return t
|
||||
end
|
||||
|
||||
type Ctx = { loops: number, budget: number }
|
||||
|
||||
-- one track [p, e) -> events (note-offs merged in) | nil, message
|
||||
local function track(b: buffer, p: number, e: number, hmp: boolean, ctx: Ctx): ({ Types.MidiEvent }?, string?)
|
||||
local list: { Types.MidiEvent }, offs: { Render.PendingOff } = {}, {}
|
||||
local tick, running = 0, 0
|
||||
while p < e do
|
||||
local d, q = delta(b, p, e, hmp)
|
||||
if not d then
|
||||
break -- (a track cut inside its last delta: keep what was read)
|
||||
end
|
||||
tick += d
|
||||
p = q
|
||||
if p >= e then
|
||||
return nil, "truncated event"
|
||||
end
|
||||
local st = readu8(b, p)
|
||||
if st == 0xFE and not hmp then
|
||||
-- HMI-only events: FE 10 (with a length at +4), FE 15, others 4 bytes
|
||||
local n = 4
|
||||
if p + 1 < e and readu8(b, p + 1) == 0x10 then
|
||||
n = if p + 4 < e then readu8(b, p + 4) + 9 else e - p + 1
|
||||
elseif p + 1 < e and readu8(b, p + 1) == 0x15 then
|
||||
n = 8
|
||||
end
|
||||
if p + n > e then
|
||||
return nil, "truncated FE event"
|
||||
end
|
||||
p += n
|
||||
elseif st == 0xFF then
|
||||
local kind = if p + 1 < e then readu8(b, p + 1) else -1
|
||||
local n, r = delta(b, p + 2, e, false)
|
||||
if kind < 0 or not n or r + n > e then
|
||||
return nil, "truncated meta event"
|
||||
end
|
||||
if kind == 0x2F then
|
||||
break
|
||||
end
|
||||
table.insert(list, { tick = tick, type = "meta", meta = kind, data = bytes(b, r, n) })
|
||||
p = r + n
|
||||
elseif st == 0xF0 or st == 0xF7 then
|
||||
local n, r = delta(b, p + 1, e, false)
|
||||
if not n or r + n > e then
|
||||
return nil, "truncated sysex"
|
||||
end
|
||||
table.insert(list, { tick = tick, type = if st == 0xF0 then "sysex" else "escape", data = bytes(b, r, n) })
|
||||
p = r + n
|
||||
running = 0
|
||||
else
|
||||
if st >= 0x80 then
|
||||
if st >= 0xF0 then
|
||||
return nil, string.format("unexpected status byte 0x%02X", st)
|
||||
end
|
||||
running = st
|
||||
p += 1
|
||||
elseif running == 0 then
|
||||
return nil, "running status without a status byte"
|
||||
end
|
||||
local hi, ch = running // 16, running % 16
|
||||
local n = DATA[hi]
|
||||
if p + n > e then
|
||||
return nil, "truncated event"
|
||||
end
|
||||
local data = bytes(b, p, n)
|
||||
p += n
|
||||
if hmp and hi == 11 and (data[1] == 110 or data[1] == 111) and data[2] > 127 then
|
||||
ctx.loops += 1
|
||||
else
|
||||
for i = 1, n do
|
||||
data[i] %= 128
|
||||
end
|
||||
table.insert(list, { tick = tick, type = TYPES[hi], channel = ch, data = data })
|
||||
end
|
||||
if hi == 9 and not hmp then
|
||||
local dur, r = delta(b, p, e, false)
|
||||
if not dur then
|
||||
return nil, "truncated note duration"
|
||||
end
|
||||
p = r
|
||||
table.insert(offs, { tick = tick + dur, onTick = tick, ev = { tick = tick + dur, type = "noteOff", channel = ch, data = { data[1], 64 } } })
|
||||
end
|
||||
end
|
||||
ctx.budget -= 1
|
||||
if ctx.budget < 0 then
|
||||
return nil, "limit: too many events"
|
||||
end
|
||||
end
|
||||
-- (notes still sounding at the end of an HMI track keep their full duration, as wildmidi plays them)
|
||||
local out = Render.merge(list, offs)
|
||||
table.insert(out, { tick = math.max(tick, if #out > 0 then out[#out].tick else 0), type = "meta", meta = 0x2F, data = {} })
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- the chunk table -> { { start, stop } } track ranges | nil, message, kind
|
||||
local function hmpTracks(b: buffer, base: number, limit: number): ({ { number } }?, string?, string?)
|
||||
local new = buffer.readstring(b, base + 8, 6) == "013195"
|
||||
local n = readu32(b, base + 0x30)
|
||||
local p = base + (if new then 0x388 else 0x308)
|
||||
if n == 0 or n > 256 then
|
||||
return nil, string.format("bad track count %d", n), nil
|
||||
end
|
||||
local ranges = {}
|
||||
for _ = 1, n do
|
||||
if p + 12 > limit then
|
||||
return nil, "truncated chunk header", "truncated"
|
||||
end
|
||||
local len = readu32(b, p + 4)
|
||||
if len < 12 or p + len > limit then
|
||||
return nil, "truncated chunk", "truncated"
|
||||
end
|
||||
table.insert(ranges, { p + 12, p + len })
|
||||
p += len
|
||||
end
|
||||
return ranges, nil, nil
|
||||
end
|
||||
|
||||
local function hmiTracks(b: buffer, base: number, limit: number): ({ { number } }?, string?, string?)
|
||||
local n = readu8(b, base + 228)
|
||||
if n == 0 then
|
||||
return nil, "no tracks", nil
|
||||
end
|
||||
if base + 370 + n * 4 > limit then
|
||||
return nil, "truncated track table", "truncated"
|
||||
end
|
||||
local ranges, heads = {}, {}
|
||||
for i = 0, n - 1 do
|
||||
local at = base + readu32(b, base + 370 + i * 4)
|
||||
if at < base or at + 0x5B > limit or buffer.readstring(b, at, 13) ~= "HMI-MIDITRACK" then
|
||||
return nil, string.format("bad track %d header", i), nil
|
||||
end
|
||||
local start = at + readu32(b, at + 0x57)
|
||||
if start >= limit then
|
||||
return nil, "truncated track", "truncated"
|
||||
end
|
||||
table.insert(ranges, { start, limit })
|
||||
table.insert(heads, at)
|
||||
end
|
||||
-- a track ends where the next track header starts (or at the end of the file)
|
||||
for _, rg in ranges do
|
||||
for _, h in heads do
|
||||
if h >= rg[1] and h < rg[2] then
|
||||
rg[2] = h
|
||||
end
|
||||
end
|
||||
end
|
||||
return ranges, nil, nil
|
||||
end
|
||||
|
||||
function Hmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Err?)
|
||||
local b, base, limit = r.buf, r.base, r.limit
|
||||
local hmi = r:peek(18) == HMI_MAGIC
|
||||
if not hmi and r:peek(8) ~= "HMIMIDIP" then
|
||||
return nil, Err.new(Err.CORRUPT, "not an HMP / HMI file")
|
||||
end
|
||||
if limit - base < (if hmi then 371 else 0x40) then
|
||||
return nil, Err.new(Err.TRUNCATED, "truncated header")
|
||||
end
|
||||
local rate = if hmi then readu8(b, base + 212) else readu32(b, base + 0x38)
|
||||
if rate == 0 or rate > 100000 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad tick rate " .. rate)
|
||||
end
|
||||
local ranges, msg, kind = (if hmi then hmiTracks else hmpTracks)(b, base, limit)
|
||||
if not ranges then
|
||||
return nil, Err.from(msg :: string, nil, kind)
|
||||
end
|
||||
local ctx: Ctx = { loops = 0, budget = (opts and opts.maxEvents) or 2 ^ 24 }
|
||||
local midi = Types.Midi.new(60)
|
||||
for i, rg in ranges do
|
||||
local evs, err = track(b, rg[1], rg[2], not hmi, ctx)
|
||||
if not evs then
|
||||
return nil, Err.from(err :: string, rg[1])
|
||||
end
|
||||
if i == 1 then
|
||||
local us = math.min(60000000 // rate, 0xFFFFFF)
|
||||
table.insert(evs, 1, { tick = 0, type = "meta", meta = 0x51, data = { us // 65536, (us // 256) % 256, us % 256 } })
|
||||
end
|
||||
midi.tracks[i] = { events = evs }
|
||||
end
|
||||
local version = if hmi then "hmi" elseif buffer.readstring(b, base + 8, 6) == "013195" then "013195" else "hmp"
|
||||
Render.attach(midi, { format = if hmi then "hmi" else "hmp", version = version, rate = rate, loops = ctx.loops })
|
||||
return midi, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + MidiRender.RenderOptions)
|
||||
function Hmp.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
|
||||
local midi, err = Hmp.decode(r, opts)
|
||||
if not midi then
|
||||
return nil, err
|
||||
end
|
||||
return Render.decoder(midi, opts)
|
||||
end
|
||||
|
||||
return Hmp
|
||||
@@ -0,0 +1,53 @@
|
||||
--!strict
|
||||
-- music/hvl: HivelyTracker modules, "HVL\0" / "HVL\1": AHX's synth extended to 4..16 channels, two effect columns,
|
||||
-- ring modulation, per-channel panning, mix gain and stereo separation stored in the file. Loads into a Types.Module-
|
||||
-- shaped value (kind "music", format "hvl": tracks as patterns, positions with per-channel transposes, instruments with
|
||||
-- play lists, subsongs) and renders through codecs/audio/Hively, a port of HivelyTracker's hvl2wav replayer
|
||||
-- (BSD-3-Clause): at 44.1 kHz the samples equal hvl2wav's.
|
||||
-- Not supported: writing.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Hively = require("@formats/codecs/audio/Hively")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Hvl = {
|
||||
name = "hvl",
|
||||
category = "music",
|
||||
extensions = { "hvl" },
|
||||
mime = { "audio/x-hvl" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Hively" },
|
||||
caps = { decode = true, encode = false, render = true, channels = { 4, 16 }, subsongs = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type RenderOptions = Hively.RenderOptions -- sampleRate, subsong, loop, maxDuration (stereo: the file's)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Hvl.sniff(r: Bytes.Reader): number
|
||||
local m = r:peek(4)
|
||||
return if m and #m == 4 and string.sub(m, 1, 3) == "HVL" and string.byte(m, 4) <= 1 then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Hvl.decode(r: Bytes.Reader, _opts: any?): (Types.Module?, Err.Err?)
|
||||
local tune, err = Hively.parse(r.buf, r.base, r.limit)
|
||||
if not tune or tune.format ~= "hvl" then
|
||||
return nil, err or Err.new(Err.CORRUPT, "not an HVL module")
|
||||
end
|
||||
return Hively.module(tune), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> the rendered audio Decoder (opts: RenderOptions)
|
||||
function Hvl.open(r: Bytes.Reader, opts: RenderOptions?): (Types.Decoder?, Err.Err?)
|
||||
local song, err = Hvl.decode(r)
|
||||
if not song then
|
||||
return nil, err
|
||||
end
|
||||
return Hively.decoder((song :: any).tune, opts)
|
||||
end
|
||||
|
||||
return Hvl
|
||||
@@ -0,0 +1,661 @@
|
||||
--!strict
|
||||
-- music/med: MED / OctaMED modules (MMD0, MMD1, MMD2, MMD3; Amiga MED 2+, OctaMED 4 .. Soundstudio; 1..64 tracks,
|
||||
-- blocks of any length). Ported from OpenMPT's Load_med.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads the first song
|
||||
-- into the codecs/audio/Tracker Module and plays it as the "xm" effect family with ProTracker periods and the PAL
|
||||
-- clock (flags.periods = "amiga"): MED's effects mapped as OpenMPT maps them, slides on every tick unless the song asks
|
||||
-- for ProTracker-style slides, the SPD / 8-channel / BPM tempo modes, MMD2 / MMD3 play sequences and sections (stop
|
||||
-- and jump commands), track volumes and pans, hold / decay (as a volume envelope and fadeout), IFF multi-octave
|
||||
-- samples (instruments with keymaps), 8 / 16-bit, stereo and delta samples, instrument extras (finetune, loops,
|
||||
-- default pitch, volume).
|
||||
-- Not supported: synthetic and hybrid instruments (silent), MIDI instruments and commands, extra command pages and
|
||||
-- the second command parameter, songs past the first, echo / stereo separation, packed (ADPCM) samples, writing.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Tracker = require("@formats/codecs/audio/Tracker")
|
||||
local Load = require("@formats/codecs/audio/Tracker/Load")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Med = {
|
||||
name = "med",
|
||||
category = "music",
|
||||
extensions = { "med", "mmd0", "mmd1", "mmd2", "mmd3", "omed" },
|
||||
mime = { "audio/x-med" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
|
||||
caps = { decode = true, encode = false, render = true, channels = { 1, 64 } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
-- IFF multi-octave samples: the sample (0 = the lowest octave stored first... as OpenMPT orders them) and the
|
||||
-- transpose used per octave of the keyboard, by the number of octaves stored (2..7)
|
||||
local OCT_SAMPLE = {
|
||||
{ 1, 1, 0, 0, 0, 0, 0, 0 },
|
||||
{ 2, 2, 1, 1, 0, 0, 0, 0 },
|
||||
{ 3, 3, 2, 2, 1, 0, 0, 0 },
|
||||
{ 4, 3, 2, 1, 1, 0, 0, 0 },
|
||||
{ 5, 4, 3, 2, 1, 0, 0, 0 },
|
||||
{ 6, 5, 4, 3, 2, 1, 0, 0 },
|
||||
}
|
||||
local OCT_TRANSPOSE = {
|
||||
{ 0, 0, -12, -12, -24, -36, -48, -60 },
|
||||
{ 0, 0, -12, -12, -24, -36, -48, -60 },
|
||||
{ 0, 0, -12, -12, -24, -36, -48, -60 },
|
||||
{ 12, 0, -12, -24, -24, -36, -48, -60 },
|
||||
{ 12, 0, -12, -24, -36, -48, -48, -60 },
|
||||
{ 12, 0, -12, -24, -36, -48, -60, -72 },
|
||||
}
|
||||
local SAMPLES_PER_TYPE = { [0] = 1, 5, 3, 2, 4, 6, 7 }
|
||||
local TEMPO_8CH = { 179, 164, 152, 141, 131, 123, 116, 110, 104, 99 }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
local function validHeader(r: Bytes.Reader): boolean
|
||||
if r:size() < 52 or r:peek(3) ~= "MMD" then
|
||||
return false
|
||||
end
|
||||
local v = r:peekU8(3)
|
||||
if v < 0x30 or v > 0x33 then
|
||||
return false
|
||||
end
|
||||
local h = r:sub(8, 44)
|
||||
local songOff = h:u32be()
|
||||
h:skip(4)
|
||||
local blockOff = h:u32be()
|
||||
h:skip(4)
|
||||
local smpOff = h:u32be()
|
||||
return songOff >= 52 and songOff + 63 * 8 + 284 <= r:size() and blockOff >= 52 and (smpOff == 0 or smpOff >= 52)
|
||||
end
|
||||
|
||||
function Med.sniff(r: Bytes.Reader): number
|
||||
return if validHeader(r) then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
type Ctx = { transpose: number, is8Ch: boolean, softMix: boolean, bpm: boolean, rowsPerBeat: number, volHex: boolean, vol7bit: boolean }
|
||||
|
||||
-- a MED tempo -> BPM (OpenMPT's MMDTempoToBPM: the SPD / 8-channel / BPM modes)
|
||||
local function tempoToBpm(tempo: number, ctx: Ctx): number
|
||||
if ctx.bpm and not ctx.is8Ch then
|
||||
return if tempo < 7 then 111.5 else tempo * ctx.rowsPerBeat / 4
|
||||
end
|
||||
if ctx.is8Ch and tempo > 0 then
|
||||
return TEMPO_8CH[math.min(tempo, 10)]
|
||||
elseif not ctx.softMix and tempo > 0 and tempo <= 10 then
|
||||
return 6 * 1773447 / 14500 / tempo -- SoundTracker-compatible tempo
|
||||
elseif ctx.softMix and tempo < 8 then
|
||||
return 157.86
|
||||
end
|
||||
return tempo / 0.264
|
||||
end
|
||||
|
||||
-- a MED command -> MOD / XM effect, param, and a note-cut flag (OpenMPT's ConvertMEDEffect)
|
||||
local function effect(cmd: number, p: number, ctx: Ctx): (number, number, boolean)
|
||||
local lo = math.min(p, 15)
|
||||
if cmd == 1 or cmd == 2 then
|
||||
return if p > 0 then cmd else 0, p, false
|
||||
elseif cmd == 4 then
|
||||
return 4, p - p % 16 + math.min((p % 16) * 2, 15), false -- twice as deep as ProTracker's
|
||||
elseif cmd == 5 then
|
||||
return if p > 0 then 5 else 3, p, false
|
||||
elseif cmd == 6 then
|
||||
return if p > 0 then 6 else 4, p, false
|
||||
elseif cmd == 8 or cmd == 0xE or cmd == 0x10 or cmd == 0x1C or cmd == 0x20 or cmd == 0x29 then
|
||||
return 0, 0, false -- hold / decay (instrument data), synth jump, MIDI, reverse, relative offset
|
||||
elseif cmd == 9 then
|
||||
return if p > 0 and p <= 0x20 then 0xF else 0, math.min(p, 0x1F), false
|
||||
elseif cmd == 0xC then
|
||||
if not ctx.volHex and p < 0x99 then
|
||||
return 0xC, (p // 16) * 10 + p % 16, false
|
||||
elseif ctx.volHex and not ctx.vol7bit then
|
||||
return 0xC, math.min(p % 128, 64), false
|
||||
elseif ctx.volHex then
|
||||
return 0xC, (p % 128 + 1) // 2, false
|
||||
end
|
||||
return 0, 0, false
|
||||
elseif cmd == 0xD then
|
||||
return if p > 0 then 0xA else 0, p, false
|
||||
elseif cmd == 0xF then
|
||||
if p == 0 then
|
||||
return 0xD, 0, false
|
||||
elseif p <= 0xF0 then
|
||||
local bpm = if p < 3 then 0x70 else math.floor(tempoToBpm(p, ctx) + 0.5)
|
||||
if bpm > 255 then
|
||||
local ext = Tracker.EXT.TEMPO_256 + math.min(bpm // 256, 3) - 1 -- tempos past 255 (EXT 0x47..0x49)
|
||||
return ext, math.min(bpm - (ext - Tracker.EXT.TEMPO_256 + 1) * 256, 255), false
|
||||
end
|
||||
return 0xF, math.max(bpm, 0x20), false
|
||||
elseif p == 0xF1 then
|
||||
return 0xE, 0x93, false
|
||||
elseif p == 0xF2 then
|
||||
return 0xE, 0xD3, false
|
||||
elseif p == 0xF3 then
|
||||
return 0xE, 0x92, false
|
||||
elseif p == 0xFF then
|
||||
return 0, 0, true
|
||||
end
|
||||
return 0, 0, false
|
||||
elseif cmd == 0x11 then
|
||||
return 0xE, 0x10 + lo, false
|
||||
elseif cmd == 0x12 then
|
||||
return 0xE, 0x20 + lo, false
|
||||
elseif cmd == 0x14 then
|
||||
return 4, p, false -- ProTracker depth, faster
|
||||
elseif cmd == 0x15 then
|
||||
return 0xE, 0x50 + p % 16, false
|
||||
elseif cmd == 0x16 then
|
||||
return 0xE, 0x60 + lo, false
|
||||
elseif cmd == 0x18 then
|
||||
return 0xE, 0xC0 + lo, false
|
||||
elseif cmd == 0x19 then
|
||||
return 9, p, false
|
||||
elseif cmd == 0x1A then
|
||||
return 0xE, 0xA0 + lo, false
|
||||
elseif cmd == 0x1B then
|
||||
return 0xE, 0xB0 + lo, false
|
||||
elseif cmd == 0x1D then
|
||||
return 0xD, Load.bcd(p), false -- pattern break, the row in hex
|
||||
elseif cmd == 0x1E then
|
||||
return 0xE, 0xE0 + lo, false
|
||||
elseif cmd == 0x1F then
|
||||
if p >= 16 then
|
||||
return 0xE, 0xD0 + p // 16, false
|
||||
elseif p > 0 then
|
||||
return 0xE, 0x90 + p, false
|
||||
end
|
||||
return 0, 0, false
|
||||
elseif cmd == 0x2E then
|
||||
if p <= 0x10 or p >= 0xF0 then
|
||||
return 8, math.clamp((bit32.bxor(p, 0x80) - 0x70) * 8, 0, 255), false
|
||||
end
|
||||
return 0, 0, false
|
||||
elseif cmd < 0x10 and (cmd > 0 or p > 0) then
|
||||
return cmd, p, false -- the remaining ProTracker effects as they are (0, 3, 7, 8, A, B)
|
||||
end
|
||||
return 0, 0, false
|
||||
end
|
||||
|
||||
-- a MED note (with the play transpose) -> our note, or 0 (OpenMPT's octave wrapping)
|
||||
local function wrapNote(note: number, vol7bit: boolean): number
|
||||
local n = note + 12 -- OpenMPT's numbering (ProTracker notes an octave up)
|
||||
if n > 132 and not vol7bit then
|
||||
n -= 108
|
||||
elseif n > 120 then
|
||||
n -= (n - 109) - (n - 109) % 12
|
||||
end
|
||||
return if n >= 13 then n - 12 else 0
|
||||
end
|
||||
|
||||
-- one block -> a Pattern (the main command page); returns whether a note needs the instruments' octave folding
|
||||
local function readBlock(r: Bytes.Reader, off: number, version: number, ctx: Ctx, nch: number): (any?, boolean)
|
||||
local br = r:sub(off)
|
||||
local ntracks, nrows, info
|
||||
if version < 1 then
|
||||
ntracks, nrows, info = br:u8(), br:u8() + 1, 0
|
||||
else
|
||||
ntracks, nrows, info = br:u16be(), br:u16be() + 1, br:u32be()
|
||||
end
|
||||
if br.err or nrows > 1024 then
|
||||
return nil, false
|
||||
end
|
||||
local cmdExt: Bytes.Reader? = nil
|
||||
if version >= 1 and info > 0 then
|
||||
local ir = r:sub(info, 36)
|
||||
ir:skip(16)
|
||||
local ext = ir:u32be()
|
||||
if not ir.err and ext > 0 then
|
||||
local p = r:sub(ext, 4):u32be()
|
||||
if p > 0 then
|
||||
cmdExt = r:sub(p)
|
||||
end
|
||||
end
|
||||
end
|
||||
local lctx = table.clone(ctx)
|
||||
lctx.vol7bit = cmdExt ~= nil
|
||||
local pat = Tracker.newPattern(nrows, nch)
|
||||
local d = pat.data
|
||||
local high = false
|
||||
local used = math.min(ntracks, nch)
|
||||
for row = 0, nrows - 1 do
|
||||
for ch = 0, ntracks - 1 do
|
||||
local note, ins, cmd, param, cut = 0, 0, 0, 0, false
|
||||
if version < 1 then
|
||||
local ni, ic, p = br:u8(), br:u8(), br:u8()
|
||||
if ni % 64 > 0 then
|
||||
note = ni % 64 + lctx.transpose
|
||||
end
|
||||
ins = ic // 16 + bit32.rshift(bit32.band(ni, 0x80), 3) + bit32.rshift(bit32.band(ni, 0x40), 1)
|
||||
cmd, param = ic % 16, p
|
||||
else
|
||||
local nv, iv, c, p = br:u8(), br:u8(), br:u8(), br:u8()
|
||||
if nv % 128 > 0 then
|
||||
note = nv % 128 + lctx.transpose
|
||||
elseif nv == 0x80 then
|
||||
cut = true
|
||||
end
|
||||
ins, cmd, param = iv % 64, c, p
|
||||
end
|
||||
if br.err then
|
||||
return pat, high
|
||||
end
|
||||
if ch < used then
|
||||
local q = (row * nch + ch) * 5
|
||||
if note >= 61 + 24 - 12 then
|
||||
high = true
|
||||
end
|
||||
local n = wrapNote(note, lctx.vol7bit)
|
||||
if n > 0 then
|
||||
buffer.writeu8(d, q, n)
|
||||
elseif cut then
|
||||
buffer.writeu8(d, q, 254)
|
||||
end
|
||||
buffer.writeu8(d, q + 1, ins)
|
||||
if cmd ~= 0 or param ~= 0 then
|
||||
local fx, fp, noteCut = effect(cmd, param, lctx)
|
||||
if noteCut and n == 0 then
|
||||
buffer.writeu8(d, q, 254)
|
||||
end
|
||||
buffer.writeu8(d, q + 3, fx)
|
||||
buffer.writeu8(d, q + 4, fp)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return pat, high
|
||||
end
|
||||
|
||||
function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local budget = { left = opts and opts.maxBytes or 2 ^ 28 }
|
||||
if not validHeader(r) then
|
||||
return nil, Err.new(if r:size() < 52 then Err.TRUNCATED else Err.CORRUPT, "not a MED module")
|
||||
end
|
||||
local version = r:peekU8(3) - 0x30
|
||||
local h = r:sub(8, 44)
|
||||
local songOff = h:u32be()
|
||||
h:skip(4)
|
||||
local blockOff = h:u32be()
|
||||
h:skip(4)
|
||||
local smpOff = h:u32be()
|
||||
h:skip(4)
|
||||
local expOff = h:u32be()
|
||||
-- the song: 63 sample headers, then the song header
|
||||
local sh = r:sub(songOff, 63 * 8)
|
||||
local song = r:sub(songOff + 63 * 8, 284)
|
||||
local numBlocks, songLength = song:u16be(), song:u16be()
|
||||
local seq = song:sub(4, 256)
|
||||
song:skip(256)
|
||||
local defTempo, playTranspose, flags, flags2, tempo2 = song:u16be(), song:i8(), song:u8(), song:u8(), song:u8()
|
||||
local trackVol = {}
|
||||
for i = 1, 16 do
|
||||
trackVol[i] = song:u8()
|
||||
end
|
||||
local masterVol, numSamples = song:u8(), song:u8()
|
||||
if song.err or numSamples > 63 or numBlocks > 0x7FFF then
|
||||
return nil, Err.new(Err.CORRUPT, "bad song header")
|
||||
end
|
||||
if numSamples > 0 and smpOff == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "no sample table")
|
||||
end
|
||||
-- channels: the widest block (at least 4)
|
||||
local nch = 4
|
||||
local blockPtr: { number } = {}
|
||||
for b = 0, numBlocks - 1 do
|
||||
local p = r:sub(blockOff + b * 4, 4):u32be()
|
||||
blockPtr[b + 1] = p
|
||||
if p > 0 and p < r:size() then
|
||||
local w = if version < 1 then r:peekU8(p) else r:peekU8(p) * 256 + r:peekU8(p + 1)
|
||||
nch = math.max(nch, w)
|
||||
end
|
||||
end
|
||||
if nch > 64 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, nch .. " tracks")
|
||||
end
|
||||
local m = Tracker.newModule("med", nch, "xm")
|
||||
m.linear = false
|
||||
m.instrumentMode = false
|
||||
m.flags.periods, m.flags.envRowHold = "amiga", true
|
||||
local stSlides = bit32.band(flags, 0x20) ~= 0
|
||||
m.flags.fastSlides, m.flags.fastPortas = not stSlides, not stSlides
|
||||
local hardwareMix = version < 2 or bit32.band(flags2, 0x80) == 0
|
||||
m.flags.amigaLimits = hardwareMix
|
||||
-- the expansion data: instrument extras and names, the song name
|
||||
local ext = { instrExt = 0, instrExtN = 0, instrExtSize = 0, infoOff = 0, infoN = 0, infoSize = 0, nameOff = 0, nameLen = 0, annoOff = 0, annoLen = 0 }
|
||||
if expOff > 0 then
|
||||
local e = r:sub(expOff, 80)
|
||||
e:skip(4)
|
||||
ext.instrExt, ext.instrExtN, ext.instrExtSize = e:u32be(), e:u16be(), e:u16be()
|
||||
ext.annoOff, ext.annoLen = e:u32be(), e:u32be()
|
||||
ext.infoOff, ext.infoN, ext.infoSize = e:u32be(), e:u16be(), e:u16be()
|
||||
e:skip(16)
|
||||
ext.nameOff, ext.nameLen = e:u32be(), e:u32be()
|
||||
if e.err then
|
||||
ext.instrExt, ext.infoOff, ext.nameOff, ext.annoOff = 0, 0, 0, 0
|
||||
end
|
||||
end
|
||||
if ext.nameOff > 0 and ext.nameLen > 0 then
|
||||
m.title = r:sub(ext.nameOff, math.min(ext.nameLen, 256)):fixed(math.min(ext.nameLen, 256))
|
||||
end
|
||||
-- instruments and samples
|
||||
local needInstruments = false
|
||||
local instruments, samples = {}, {}
|
||||
local unsupported = {}
|
||||
for ins = 1, numSamples do
|
||||
local smpHead = sh:sub((ins - 1) * 8, 8)
|
||||
local loopStart, loopLen = smpHead:u16be() * 2, smpHead:u16be() * 2
|
||||
local midiCh, _midiPreset, volume, transpose = smpHead:u8(), smpHead:u8(), smpHead:u8(), smpHead:i8()
|
||||
local x = { hold = 0, decay = 0, finetune = 0, pitch = 0, flags = 0, loopStart = 0, loopLen = 0, volume = 0 }
|
||||
local xsize = 0
|
||||
if ext.instrExt > 0 and ins <= ext.instrExtN then
|
||||
xsize = ext.instrExtSize
|
||||
local xr = r:sub(ext.instrExt + (ins - 1) * xsize, xsize)
|
||||
x.hold, x.decay = xr:u8(), xr:u8()
|
||||
xr:skip(1)
|
||||
x.finetune = xr:i8()
|
||||
x.pitch, x.flags = xr:u8(), xr:u8()
|
||||
xr:skip(4)
|
||||
x.loopStart, x.loopLen = xr:u32be(), xr:u32be()
|
||||
x.volume = xr:u8()
|
||||
end
|
||||
local name = ""
|
||||
if ext.infoOff > 0 and ins <= ext.infoN then
|
||||
name = r:sub(ext.infoOff + (ins - 1) * ext.infoSize, math.min(ext.infoSize, 40)):fixed(math.min(ext.infoSize, 40))
|
||||
end
|
||||
local instr = Tracker.newInstrument(name)
|
||||
instruments[ins] = instr
|
||||
local iptr = if smpOff > 0 then r:sub(smpOff + (ins - 1) * 4, 4):u32be() else 0
|
||||
local length, typ = 0, 0
|
||||
if iptr > 0 then
|
||||
local ih = r:sub(iptr, 6)
|
||||
length, typ = ih:u32be(), ih:i16be()
|
||||
if ih.err then
|
||||
length, typ = 0, 0
|
||||
end
|
||||
end
|
||||
local isSynth = typ < 0
|
||||
local masked = bit32.band(typ % 65536, 0x0F)
|
||||
local count = if not isSynth then (SAMPLES_PER_TYPE[masked] or 1) else 1
|
||||
if isSynth then
|
||||
table.insert(unsupported, "synth / hybrid instrument " .. ins)
|
||||
needInstruments = needInstruments or typ == -1 or typ == -2
|
||||
end
|
||||
if midiCh > 0 and midiCh <= 16 then
|
||||
needInstruments = true
|
||||
table.insert(unsupported, "MIDI instrument " .. ins)
|
||||
end
|
||||
local first = #samples + 1
|
||||
-- keymap: one sample per note, multi-octave samples spread over the octaves
|
||||
for n = 1, 120 do
|
||||
instr.sampleMap[n] = first
|
||||
end
|
||||
if count > 1 then
|
||||
needInstruments = true
|
||||
for n = 1, 120 do
|
||||
local note = n + 11 + transpose -- OpenMPT's keyboard index
|
||||
if note < 0 then
|
||||
note = -note % 12
|
||||
end
|
||||
local oct = math.clamp(note // 12 - 4, 0, 7)
|
||||
instr.sampleMap[n] = first + OCT_SAMPLE[count - 1][oct + 1]
|
||||
instr.noteMap[n] = math.clamp(1 + note + OCT_TRANSPOSE[count - 1][oct + 1] - 12, 1, 120)
|
||||
end
|
||||
transpose = 0
|
||||
elseif masked == 7 then
|
||||
needInstruments = true -- two extra-low octaves
|
||||
for n = 1, 120 do
|
||||
instr.noteMap[n] = math.clamp(n - 24, 1, 120)
|
||||
end
|
||||
end
|
||||
if midiCh == 0 then
|
||||
-- notes past the mixer's range fold down (by octaves)
|
||||
local top = 61 + (if hardwareMix then 24 else 36)
|
||||
for n = 1, 120 do
|
||||
local real = instr.noteMap[n] + 12 + transpose
|
||||
if real >= top then
|
||||
instr.noteMap[n] = math.max(1, instr.noteMap[n] - ((real - top + 12) - (real - top + 12) % 12))
|
||||
end
|
||||
end
|
||||
end
|
||||
-- sample data
|
||||
local list = {}
|
||||
for i = 0, count - 1 do
|
||||
local s = Tracker.newSample(name)
|
||||
s.volume = math.min(volume, 64)
|
||||
s.relativeNote = transpose
|
||||
list[i + 1] = s
|
||||
samples[first + i] = s
|
||||
end
|
||||
local hasLoop = loopLen > 2
|
||||
if not isSynth and iptr > 0 and length > 0 then
|
||||
local bits = if bit32.band(typ, 0x10) ~= 0 then 16 else 8
|
||||
local stereo = bit32.band(typ, 0x20) ~= 0
|
||||
local nchs = if stereo then 2 else 1
|
||||
local bytes = length * nchs
|
||||
local frames = length // (bits // 8)
|
||||
if count > 1 then
|
||||
frames //= (2 ^ count - 1)
|
||||
end
|
||||
local pos = r.base + iptr + 6
|
||||
local ls, le = loopStart, loopStart + loopLen
|
||||
for i = 1, count do
|
||||
local s = list[i]
|
||||
local spec = { bits = bits, signed = true, bigEndian = true, channels = nchs, planar = stereo, delta = bit32.band(typ, 0x40) ~= 0, limit = math.min(r.limit, r.base + iptr + 6 + bytes) }
|
||||
local ok, err = Load.readSample(r.buf, pos, frames, spec, s, budget)
|
||||
if not ok then
|
||||
return nil, err
|
||||
end
|
||||
pos += frames * nchs * bits // 8
|
||||
if hasLoop then
|
||||
s.loopStart, s.loopEnd, s.loopType = ls, math.min(le, s.length), 1
|
||||
end
|
||||
frames, ls, le = frames * 2, ls * 2, le * 2
|
||||
end
|
||||
end
|
||||
-- the instrument extras
|
||||
if xsize > 0 then
|
||||
if x.hold > 0 and not isSynth then
|
||||
local env = Tracker.newEnvelope()
|
||||
env.enabled = true
|
||||
local fall = x.hold + (if x.decay > 0 then 64 // x.decay else 0)
|
||||
if x.hold == 1 then
|
||||
env.ticks, env.values = { 0, fall }, { 64, 0 }
|
||||
else
|
||||
env.ticks, env.values = { 0, x.hold - 1, fall }, { 64, 64, 0 }
|
||||
end
|
||||
instr.volEnv = env
|
||||
instr.fadeout = if x.decay > 0 then math.min(x.decay * 512, 65535) else 32767
|
||||
needInstruments = true
|
||||
end
|
||||
if xsize > 4 and x.pitch ~= 0 then
|
||||
instr.noteMap[24 - 12 + 1] = math.clamp(x.pitch + 1 + 23 - 12, 1, 120)
|
||||
needInstruments = true
|
||||
end
|
||||
if xsize > 18 then
|
||||
instr.globalVolume = (x.volume + 1) // 2 * 2
|
||||
end
|
||||
local ls, le = x.loopStart, x.loopStart + x.loopLen
|
||||
for _, s in list do
|
||||
s.finetune = math.clamp(x.finetune * 16, -128, 127)
|
||||
if not isSynth and xsize > 14 then
|
||||
s.loopStart, s.loopEnd = ls, math.min(le, s.length)
|
||||
ls, le = ls * 2, le * 2
|
||||
end
|
||||
if xsize > 5 then
|
||||
if not isSynth then
|
||||
s.loopType = if bit32.band(x.flags, 1) == 0 then 0 elseif bit32.band(x.flags, 8) ~= 0 then 2 else 1
|
||||
end
|
||||
if bit32.band(x.flags, 4) ~= 0 then
|
||||
s.globalVolume = 0
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
-- the play order: MMD0 / MMD1 a sequence of blocks; MMD2 / MMD3 sections of play sequences (stop / jump commands)
|
||||
local jumps: { [number]: number } = {}
|
||||
local preamp = 32
|
||||
if version < 2 then
|
||||
if songLength > 256 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad song length")
|
||||
end
|
||||
for i = 1, songLength do
|
||||
m.order[i] = seq:u8()
|
||||
end
|
||||
for i = 1, nch do
|
||||
local k = (i - 1) % 4
|
||||
m.channelPan[i] = if k == 1 or k == 2 then 0xC0 else 0x40
|
||||
if i <= 16 then
|
||||
m.channelVolume[i] = math.min(trackVol[i], 64)
|
||||
end
|
||||
end
|
||||
else
|
||||
local s2 = song:sub(4, 256)
|
||||
local playSeqTable, sectionTable, trackVolsOff = s2:u32be(), s2:u32be(), s2:u32be()
|
||||
local numTracks, numPlaySeqs = s2:u16be(), s2:u16be()
|
||||
local trackPanOff, flags3, volAdjust = s2:u32be(), s2:u32be(), s2:u16be()
|
||||
if numTracks < 1 or numTracks > 64 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad track count")
|
||||
end
|
||||
local freePan = not hardwareMix and bit32.band(flags3, 2) ~= 0
|
||||
if volAdjust > 0 then
|
||||
preamp = (preamp * math.min(volAdjust, 800) + 50) // 100
|
||||
end
|
||||
if freePan then
|
||||
preamp //= 2
|
||||
end
|
||||
if trackVolsOff > 0 then
|
||||
for i = 1, nch do
|
||||
m.channelVolume[i] = math.min(r:sub(trackVolsOff + i - 1, 1):u8(), 64)
|
||||
end
|
||||
end
|
||||
local pans = (freePan or version > 2) and trackPanOff > 0
|
||||
for i = 1, nch do
|
||||
if pans then
|
||||
m.channelPan[i] = (math.clamp(r:sub(trackPanOff + i - 1, 1):i8(), -16, 16) + 16) * 8
|
||||
else
|
||||
local k = (i - 1) % 4
|
||||
m.channelPan[i] = if k == 1 or k == 2 then 0xC0 else 0x40
|
||||
end
|
||||
end
|
||||
local sections = r:sub(sectionTable, songLength * 2)
|
||||
for _ = 1, songLength do
|
||||
local sec = sections:u16be()
|
||||
if sections.err then
|
||||
break
|
||||
end
|
||||
if sec <= numPlaySeqs then
|
||||
local ps = r:sub(playSeqTable + sec * 4, 4):u32be()
|
||||
local pr = r:sub(ps, 42)
|
||||
pr:skip(32)
|
||||
local cmdTable = pr:u32be()
|
||||
pr:skip(4)
|
||||
local len = pr:u16be()
|
||||
if not pr.err then
|
||||
if #m.order > 0 then
|
||||
table.insert(m.order, 254)
|
||||
end
|
||||
local start = #m.order
|
||||
local er = r:sub(ps + 42, len * 2)
|
||||
for _ = 1, len do
|
||||
local b = er:u16be()
|
||||
if er.err then
|
||||
break
|
||||
end
|
||||
if b < 0x8000 then
|
||||
table.insert(m.order, math.min(b, 253))
|
||||
end
|
||||
end
|
||||
if cmdTable > 0 then
|
||||
local cr = r:sub(cmdTable)
|
||||
for _ = 1, 4096 do
|
||||
local off, c, extra = cr:u16be(), cr:u8(), cr:u8()
|
||||
local arg = if extra >= 2 then cr:sub(cr:tell(), 2):u16be() else 0
|
||||
cr:skip(extra)
|
||||
local at = start + off + 1
|
||||
if cr.err or off == 0xFFFF or at > #m.order then
|
||||
break
|
||||
end
|
||||
if c == 1 then
|
||||
m.order[at] = 255
|
||||
elseif c == 2 then
|
||||
jumps[at] = arg
|
||||
m.order[at] = 254
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
m.preamp = preamp
|
||||
-- tempo, speed, volume, the pattern context
|
||||
local ctx: Ctx = {
|
||||
transpose = 36 + playTranspose - (if version > 2 then 24 else 0),
|
||||
is8Ch = bit32.band(flags, 0x40) ~= 0,
|
||||
softMix = bit32.band(flags2, 0x80) ~= 0,
|
||||
bpm = bit32.band(flags2, 0x20) ~= 0,
|
||||
rowsPerBeat = 1 + bit32.band(flags2, 0x1F),
|
||||
volHex = bit32.band(flags, 0x10) ~= 0,
|
||||
vol7bit = false,
|
||||
}
|
||||
m.tempo = tempoToBpm(defTempo, ctx)
|
||||
m.speed = math.clamp(tempo2, 1, 32)
|
||||
if masterVol > 0 then
|
||||
m.globalVolume = math.min(masterVol, 64) * 2
|
||||
end
|
||||
-- blocks
|
||||
for b = 0, numBlocks - 1 do
|
||||
local p = blockPtr[b + 1]
|
||||
local pat, high = nil, false
|
||||
if p and p > 0 then
|
||||
pat, high = readBlock(r, p, version, ctx, nch)
|
||||
end
|
||||
m.patterns[b + 1] = pat or Tracker.newPattern(64, nch)
|
||||
needInstruments = needInstruments or high
|
||||
end
|
||||
-- play-sequence jumps: a jump effect at the end of the block before the command
|
||||
for at, to in jumps do
|
||||
local prev = m.order[at - 1]
|
||||
if prev and prev < 254 and m.patterns[prev + 1] then
|
||||
-- the block may be played elsewhere: give this order entry its own copy
|
||||
local src = m.patterns[prev + 1]
|
||||
local cp = Tracker.newPattern(src.rows, nch)
|
||||
buffer.copy(cp.data, 0, src.data)
|
||||
table.insert(m.patterns, cp)
|
||||
m.order[at - 1] = #m.patterns - 1
|
||||
Load.writeEffect(m, #m.patterns - 1, cp.rows - 1, 0xB, math.min(to, 255), "prev")
|
||||
end
|
||||
end
|
||||
m.samples = samples
|
||||
if needInstruments then
|
||||
m.instrumentMode = true
|
||||
m.instruments = instruments
|
||||
end
|
||||
if #unsupported > 0 then
|
||||
m.meta.unsupported = unsupported
|
||||
end
|
||||
if ext.annoOff > 0 and ext.annoLen > 1 then
|
||||
m.meta.message = r:sub(ext.annoOff, ext.annoLen - 1):string(math.min(ext.annoLen - 1, r:size()))
|
||||
end
|
||||
m.meta.source = { format = "med", version = "MMD" .. version, instruments = needInstruments }
|
||||
local ok, verr = Tracker.validate(m)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module")
|
||||
end
|
||||
return m, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions)
|
||||
function Med.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
|
||||
local m, err = Med.decode(r, opts)
|
||||
if not m then
|
||||
return nil, err
|
||||
end
|
||||
return Tracker.render(m, opts)
|
||||
end
|
||||
|
||||
return Med
|
||||
@@ -3,7 +3,9 @@
|
||||
-- specification (no third-party code); rendering goes through codecs/audio/SoundFont (a TinySoundFont port).
|
||||
-- Supports: decode to a Types.Midi (absolute ticks; channel events noteOff / noteOn / aftertouch / controller /
|
||||
-- program / channelPressure / pitchBend with their raw data bytes, sysex / escape with the bytes after the length,
|
||||
-- meta events with meta = the meta type; meta.tempos / timeSignatures / keySignatures, track names), encode (running
|
||||
-- meta events with meta = the meta type; meta.tempos / timeSignatures / keySignatures, track names; .kar karaoke:
|
||||
-- meta.lyrics = { { time, tick, text } } from the "Words" track's text events (FF 01; the @ headers go to
|
||||
-- meta.karaoke and meta.tags) and from lyric events (FF 05), in time order), encode (running
|
||||
-- status optional, byte-identical to python mido's writer by default), the tempo map (tickToSeconds, length), and
|
||||
-- render / open: an audio Decoder (stereo f32) through an SF2 SoundFont (opts.soundfont) or the built-in waveform set.
|
||||
-- Not supported: RMID write, XMF / RMI DLS banks, system common / realtime bytes inside tracks (CORRUPT).
|
||||
@@ -13,7 +15,7 @@ local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Smf = require("@formats/music/midi/Smf")
|
||||
local Render = require("@formats/music/midi/Render")
|
||||
local Render = require("@formats/codecs/audio/MidiRender")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Midi = {
|
||||
@@ -21,7 +23,7 @@ local Midi = {
|
||||
category = "music",
|
||||
extensions = { "mid", "midi", "smf", "kar", "rmi" },
|
||||
mime = { "audio/midi", "audio/x-midi" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/audio/SoundFont", "Types" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/audio/MidiRender", "Types" },
|
||||
caps = { decode = true, encode = true, formats = { 0, 1, 2 }, render = true, streaming = true, rmid = true },
|
||||
}
|
||||
|
||||
@@ -42,46 +44,63 @@ function Midi.sniff(r: Bytes.Reader): number
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function render(self: Types.Midi, opts: RenderOptions?): Types.Decoder
|
||||
local dec, err = Render.decoder(self, opts)
|
||||
if not dec then
|
||||
-- the Types contract returns a Decoder; a failed render is an empty one (Midi.render returns the Err)
|
||||
local empty: any = {
|
||||
sampleRate = 44100, channels = 2, frames = 0, duration = 0, bitrate = 0, tags = {}, err = err,
|
||||
read = function(_self: any, _n: number, out: buffer?): (buffer, number)
|
||||
return out or buffer.create(0), 0
|
||||
end,
|
||||
seek = function() end,
|
||||
position = function(): number
|
||||
return 0
|
||||
end,
|
||||
}
|
||||
return empty
|
||||
end
|
||||
return dec
|
||||
end
|
||||
|
||||
local function summarize(midi: Types.Midi)
|
||||
local tempos, sigs, keys = {}, {}, {}
|
||||
-- karaoke(midi): .kar text (FF 01 in a track named "Words", or in any track once an "@K" / "@T" header shows up) and
|
||||
-- FF 05 lyric events -> meta.lyrics; "@X" headers -> meta.karaoke[X] (lists of lines) and meta.tags
|
||||
local function karaoke(midi: Types.Midi)
|
||||
local lyrics: { { time: number, tick: number, text: string } } = {}
|
||||
local headers: { [string]: { string } } = {}
|
||||
local map = Render.tempoMap(midi)
|
||||
for ti, t in midi.tracks do
|
||||
local kar, hasWords = false, false
|
||||
for _, t in midi.tracks do
|
||||
if t.name == "Words" then
|
||||
kar, hasWords = true, true
|
||||
end
|
||||
for _, ev in t.events do
|
||||
if ev.type == "meta" then
|
||||
local d = ev.data :: { number }
|
||||
if ev.meta == 0x51 and #d >= 3 then
|
||||
table.insert(tempos, { tick = ev.tick, track = ti, usPerQuarter = d[1] * 65536 + d[2] * 256 + d[3], bpm = 60000000 / math.max(1, d[1] * 65536 + d[2] * 256 + d[3]), seconds = Render.seconds(map, ev.tick) })
|
||||
elseif ev.meta == 0x58 and #d >= 4 then
|
||||
table.insert(sigs, { tick = ev.tick, track = ti, numerator = d[1], denominator = 2 ^ math.min(d[2], 31), clocksPerClick = d[3], notated32ndsPerBeat = d[4] })
|
||||
elseif ev.meta == 0x59 and #d >= 2 then
|
||||
table.insert(keys, { tick = ev.tick, track = ti, sharps = if d[1] >= 128 then d[1] - 256 else d[1], minor = d[2] == 1 })
|
||||
if ev.type == "meta" and ev.meta == 1 and type(ev.data) == "table" and ev.data[1] == 64 then
|
||||
local c = ev.data[2]
|
||||
if c == 75 or c == 84 then -- @K, @T
|
||||
kar = true
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
midi.meta.tempos = tempos
|
||||
midi.meta.timeSignatures = sigs
|
||||
midi.meta.keySignatures = keys
|
||||
midi.meta.length = Render.length(midi)
|
||||
for ti, t in midi.tracks do
|
||||
local tmap = if midi.format == 2 then Render.tempoMap(midi, ti) else map
|
||||
local words = kar and (t.name == "Words" or not hasWords)
|
||||
for _, ev in t.events do
|
||||
if ev.type == "meta" and type(ev.data) == "table" and (ev.meta == 5 or (ev.meta == 1 and words)) then
|
||||
local text = Smf.text(ev.data :: { number })
|
||||
if ev.meta == 1 and string.sub(text, 1, 1) == "@" and #text >= 2 then
|
||||
local key = string.sub(text, 2, 2)
|
||||
local list = headers[key] or {}
|
||||
headers[key] = list
|
||||
table.insert(list, string.sub(text, 3))
|
||||
else
|
||||
table.insert(lyrics, { time = Render.seconds(tmap, ev.tick), tick = ev.tick, text = text })
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if #lyrics == 0 and next(headers) == nil then
|
||||
return
|
||||
end
|
||||
table.sort(lyrics, function(a: { time: number, tick: number, text: string }, b: { time: number, tick: number, text: string }): boolean
|
||||
return a.time < b.time
|
||||
end)
|
||||
midi.meta.lyrics = lyrics
|
||||
midi.meta.karaoke = headers
|
||||
local tags: { [string]: string } = {}
|
||||
if headers.T then
|
||||
tags.title = headers.T[1]
|
||||
tags.artist = headers.T[2]
|
||||
end
|
||||
if headers.L then
|
||||
tags.language = headers.L[1]
|
||||
end
|
||||
if headers.I then
|
||||
tags.comment = table.concat(headers.I, "\n")
|
||||
end
|
||||
midi.meta.tags = tags
|
||||
end
|
||||
|
||||
function Midi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Err?)
|
||||
@@ -89,9 +108,8 @@ function Midi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.E
|
||||
if not midi then
|
||||
return nil, err
|
||||
end
|
||||
summarize(midi)
|
||||
midi.meta.source = { format = "midi", smf = midi.format }
|
||||
midi.render = render
|
||||
Render.attach(midi, { format = "midi", smf = midi.format })
|
||||
karaoke(midi)
|
||||
return midi, nil
|
||||
end
|
||||
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
--!strict
|
||||
-- music/mtm: MultiTracker modules (MTM, Renaissance's DOS tracker, 1..32 channels; patterns built from shared
|
||||
-- tracks). Ported from OpenMPT's Load_mtm.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the
|
||||
-- codecs/audio/Tracker Module and plays as the "xm" effect family with Amiga periods (OpenMPT plays MTM like XM):
|
||||
-- MOD effects (no 8xx panning, E8x pans), 8 / 16-bit unsigned samples, finetune, the song speed / tempo quirk
|
||||
-- (MultiTracker resets the tempo on a speed command and the speed on a tempo command when they never share a row).
|
||||
-- Not supported: MultiTracker's E9x / EDx retrigger timing and its vibrato start phase (played as in XM), writing.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Tracker = require("@formats/codecs/audio/Tracker")
|
||||
local Load = require("@formats/codecs/audio/Tracker/Load")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Mtm = {
|
||||
name = "mtm",
|
||||
category = "music",
|
||||
extensions = { "mtm" },
|
||||
mime = { "audio/x-mtm" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
|
||||
caps = { decode = true, encode = false, render = true, channels = { 1, 32 } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Mtm.sniff(r: Bytes.Reader): number
|
||||
if r:size() >= 66 and r:peek(3) == "MTM" and r:peekU8(3) < 0x20 and r:peekU8(33) >= 1 and r:peekU8(33) <= 32 then
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- MultiTracker: a speed command resets the tempo to 125 and a tempo command the speed to 6, unless the module puts
|
||||
-- both on one row somewhere (then it was written for players that treat them as ProTracker does)
|
||||
local function speedTempoQuirk(m: any)
|
||||
local speed, tempo, together = false, false, false
|
||||
for _, p in m.patterns do
|
||||
for row = 0, p.rows - 1 do
|
||||
local s, t = false, false
|
||||
for c = 1, m.channels do
|
||||
local o = (row * m.channels + c - 1) * 5
|
||||
local fx, param = buffer.readu8(p.data, o + 3), buffer.readu8(p.data, o + 4)
|
||||
if fx == 0xF then
|
||||
if param < 0x20 then
|
||||
s = true
|
||||
else
|
||||
t = true
|
||||
end
|
||||
end
|
||||
end
|
||||
speed, tempo, together = speed or s, tempo or t, together or (s and t)
|
||||
end
|
||||
end
|
||||
if not (speed and tempo) or together then
|
||||
return
|
||||
end
|
||||
for pi, p in m.patterns do
|
||||
for row = 0, p.rows - 1 do
|
||||
for c = 1, m.channels do
|
||||
local o = (row * m.channels + c - 1) * 5
|
||||
local fx, param = buffer.readu8(p.data, o + 3), buffer.readu8(p.data, o + 4)
|
||||
if fx == 0xF then
|
||||
Load.writeEffect(m, pi - 1, row, 0xF, if param < 0x20 then 125 else 6, nil, nil, true)
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function Mtm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local budget = { left = opts and opts.maxBytes or 2 ^ 28 }
|
||||
if r:size() < 66 then
|
||||
return nil, Err.new(Err.TRUNCATED, "header")
|
||||
end
|
||||
if r:peek(3) ~= "MTM" then
|
||||
return nil, Err.new(Err.CORRUPT, "no MTM signature")
|
||||
end
|
||||
r:skip(3)
|
||||
local version = r:u8()
|
||||
local title = r:fixed(20)
|
||||
local numTracks, lastPattern, lastOrder = r:u16le(), r:u8(), r:u8()
|
||||
local commentSize, numSamples, _attr, rowsPerTrack, nch = r:u16le(), r:u8(), r:u8(), r:u8(), r:u8()
|
||||
local pans: { number } = {}
|
||||
for i = 1, 32 do
|
||||
pans[i] = r:u8()
|
||||
end
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
if version >= 0x20 or lastOrder > 127 or rowsPerTrack > 64 or nch == 0 or nch > 32 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad header")
|
||||
end
|
||||
local m = Tracker.newModule("mtm", nch, "xm")
|
||||
m.title = title
|
||||
m.linear = false
|
||||
m.instrumentMode = false
|
||||
for i = 1, nch do
|
||||
m.channelPan[i] = (pans[i] % 16) * 16 + 8
|
||||
end
|
||||
-- samples
|
||||
local sizes: { number } = {}
|
||||
for i = 1, numSamples do
|
||||
local s = Tracker.newSample(r:fixed(22))
|
||||
local len, ls, le = r:u32le(), r:u32le(), r:u32le()
|
||||
local ft, vol, attr = r:i8(), r:u8(), r:u8()
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
s.volume = math.min(vol, 64)
|
||||
s.finetune = math.clamp(ft * 16, -128, 127)
|
||||
local bits = if attr % 2 == 1 then 16 else 8
|
||||
s.bits = bits
|
||||
local frames = 0
|
||||
if len > 2 then
|
||||
frames = len
|
||||
le = math.min(math.max(le, 1) - 1, len)
|
||||
if ls + 4 >= le then
|
||||
ls, le = 0, 0
|
||||
end
|
||||
if bits == 16 then
|
||||
frames, ls, le = frames // 2, ls // 2, le // 2
|
||||
end
|
||||
if le > 2 then
|
||||
s.loopStart, s.loopEnd, s.loopType = ls, le, 1
|
||||
end
|
||||
end
|
||||
sizes[i] = if len > 2 then len else 0
|
||||
s.length = frames
|
||||
m.samples[i] = s
|
||||
end
|
||||
-- the order list
|
||||
for i = 1, 128 do
|
||||
local o = r:u8()
|
||||
if i <= lastOrder + 1 then
|
||||
m.order[i] = o
|
||||
end
|
||||
end
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
-- tracks (64 rows of 3 bytes each) and the patterns made of them
|
||||
local rows = if rowsPerTrack > 0 then rowsPerTrack else 64
|
||||
local tracks = r:tell()
|
||||
if not r:skip(192 * numTracks) then
|
||||
return nil, r.err
|
||||
end
|
||||
local buf = r.buf
|
||||
for p = 0, lastPattern do
|
||||
local pat = Tracker.newPattern(rows, nch)
|
||||
m.patterns[p + 1] = pat
|
||||
for ch = 0, 31 do
|
||||
local track = r:u16le()
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
if track > 0 and track <= numTracks and ch < nch then
|
||||
local base = r.base + tracks + 192 * (track - 1)
|
||||
for row = 0, rows - 1 do
|
||||
local o = base + row * 3
|
||||
local b0, b1, b2 = buffer.readu8(buf, o), buffer.readu8(buf, o + 1), buffer.readu8(buf, o + 2)
|
||||
local q = (row * nch + ch) * 5
|
||||
if b0 >= 4 then
|
||||
buffer.writeu8(pat.data, q, b0 // 4 + 25) -- C-4 = 49 plays the sample at 8363 Hz (OpenMPT keeps MTM / XM notes an octave up)
|
||||
end
|
||||
buffer.writeu8(pat.data, q + 1, (b0 % 4) * 16 + b1 // 16)
|
||||
local cmd, param = b1 % 16, b2
|
||||
if cmd == 0xA then
|
||||
param = if param >= 16 then param - param % 16 else param
|
||||
elseif cmd == 8 then
|
||||
cmd, param = 0, 0 -- no 8xx panning in MultiTracker
|
||||
elseif cmd == 0xE then
|
||||
local x = param // 16
|
||||
if x == 0 or x == 3 or x == 4 or x == 6 or x == 7 or x == 0xF then
|
||||
cmd, param = 0, 0 -- not in MultiTracker
|
||||
end
|
||||
end
|
||||
buffer.writeu8(pat.data, q + 3, cmd)
|
||||
buffer.writeu8(pat.data, q + 4, param)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
speedTempoQuirk(m)
|
||||
-- the song message (40-character lines), then the sample data (unsigned PCM)
|
||||
m.meta.message = r:string(commentSize)
|
||||
if r.err then
|
||||
r.err = nil
|
||||
end
|
||||
local pos = r.pos
|
||||
for i = 1, numSamples do
|
||||
local s = m.samples[i]
|
||||
if sizes[i] > 0 then
|
||||
local ok, err = Load.readSample(buf, pos, s.length, { bits = s.bits, signed = false, limit = r.limit }, s, budget)
|
||||
if not ok then
|
||||
return nil, err
|
||||
end
|
||||
pos += sizes[i]
|
||||
s.loopEnd = math.min(s.loopEnd, s.length)
|
||||
end
|
||||
end
|
||||
m.meta.source = { format = "mtm", version = version, tracks = numTracks }
|
||||
local ok, verr = Tracker.validate(m)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module")
|
||||
end
|
||||
return m, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions)
|
||||
function Mtm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
|
||||
local m, err = Mtm.decode(r, opts)
|
||||
if not m then
|
||||
return nil, err
|
||||
end
|
||||
return Tracker.render(m, opts)
|
||||
end
|
||||
|
||||
return Mtm
|
||||
@@ -0,0 +1,163 @@
|
||||
--!strict
|
||||
-- music/mus: DMX MUS, the music format of Doom, Heretic, Hexen and Strife ("MUS\x1a"). Written from the MUS format
|
||||
-- description (Vladimir Arnost's "MUS File Format", the DMX event set); wildmidi was used only as a reference converter
|
||||
-- in tests. Decodes to a Types.Midi (format 0, one track) the way the usual MUS-to-MIDI converters map it: MUS channel
|
||||
-- 15 is the percussion channel 9, the others get MIDI channels 0..8, 10..15 in order of first use (each starting at
|
||||
-- volume 127), MUS controllers / system events become MIDI controllers (controller 0 = program change), notes without
|
||||
-- a volume reuse the channel's last one (127 at first), pitch wheel 0..255 becomes a 14-bit bend. Time: 140 ticks per
|
||||
-- second (opts.rate), as division 70 at 500000 us per quarter. Renders through codecs/audio/MidiRender (SoundFont /
|
||||
-- built-in waveforms). meta.source: primaryChannels, secondaryChannels, instruments (the patch list), rate.
|
||||
-- Not supported: writing (save as .mid through the midi format's encoder).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Render = require("@formats/codecs/audio/MidiRender")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Mus = {
|
||||
name = "mus",
|
||||
category = "music",
|
||||
extensions = { "mus" },
|
||||
mime = { "audio/x-mus" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/MidiRender" },
|
||||
caps = { decode = true, encode = false, render = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
rate: number?, -- ticks per second, default 140 (Doom); some players use 70
|
||||
maxEvents: number?, -- default 2^24
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
-- MUS controller / system event number -> MIDI controller (0 is the program change)
|
||||
local CONTROLLER = { [0] = 0, 0, 0x01, 0x07, 0x0A, 0x0B, 0x5B, 0x5D, 0x40, 0x43, 0x78, 0x7B, 0x7E, 0x7F, 0x79 }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Mus.sniff(r: Bytes.Reader): number
|
||||
return if r:peek(4) == "MUS\x1a" then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local readu8 = buffer.readu8
|
||||
|
||||
-- the score [p, e) -> events | nil, message
|
||||
local function score(b: buffer, p: number, e: number, primary: number, maxEvents: number): ({ Types.MidiEvent }?, string?, boolean)
|
||||
local events: { Types.MidiEvent } = { { tick = 0, type = "controller", channel = 9, data = { 0x07, 127 } } }
|
||||
local map: { [number]: number } = { [15] = 9 }
|
||||
local volume: { [number]: number } = {}
|
||||
local nextChannel = 0
|
||||
local tick = 0
|
||||
while p < e do
|
||||
local ev = readu8(b, p)
|
||||
p += 1
|
||||
local kind, mch = bit32.band(bit32.rshift(ev, 4), 7), bit32.band(ev, 15)
|
||||
if kind == 6 then
|
||||
return events, nil, false
|
||||
end
|
||||
local ch = map[mch]
|
||||
if not ch then
|
||||
ch = nextChannel
|
||||
map[mch] = ch
|
||||
nextChannel += if nextChannel == 8 then 2 else 1
|
||||
table.insert(events, { tick = tick, type = "controller", channel = ch, data = { 0x07, 127 } })
|
||||
end
|
||||
local need = if kind == 1 then (if p < e and readu8(b, p) >= 128 then 2 else 1) elseif kind == 4 then 2 elseif kind == 5 then 0 else 1
|
||||
if kind == 7 then
|
||||
return nil, "unknown event type 7", false
|
||||
elseif p + need > e then
|
||||
return events, nil, true
|
||||
end
|
||||
local d1, d2 = if need > 0 then readu8(b, p) else 0, if need > 1 then readu8(b, p + 1) else 0
|
||||
p += need
|
||||
if kind == 0 then
|
||||
table.insert(events, { tick = tick, type = "noteOff", channel = ch, data = { d1 % 128, 64 } })
|
||||
elseif kind == 1 then
|
||||
if need == 2 then
|
||||
volume[ch] = math.min(d2, 127)
|
||||
end
|
||||
table.insert(events, { tick = tick, type = "noteOn", channel = ch, data = { d1 % 128, volume[ch] or 127 } })
|
||||
elseif kind == 2 then
|
||||
table.insert(events, { tick = tick, type = "pitchBend", channel = ch, data = { bit32.band(d1, 1) * 64, bit32.rshift(d1, 1) } })
|
||||
elseif kind == 3 or kind == 4 then
|
||||
local c, v = d1, if kind == 3 then (if d1 == 12 then math.min(primary + 1, 127) else 0) else math.min(d2, 127)
|
||||
if CONTROLLER[c] == nil then
|
||||
return nil, string.format("unknown controller %d", c), false
|
||||
end
|
||||
if kind == 4 and c == 0 then
|
||||
table.insert(events, { tick = tick, type = "program", channel = ch, data = { v } })
|
||||
else
|
||||
table.insert(events, { tick = tick, type = "controller", channel = ch, data = { CONTROLLER[c], v } })
|
||||
end
|
||||
end
|
||||
if #events > maxEvents then
|
||||
return nil, "limit: more than " .. maxEvents .. " events", false
|
||||
end
|
||||
if ev >= 128 then
|
||||
local delay = 0
|
||||
repeat
|
||||
if p >= e then
|
||||
return events, nil, true
|
||||
end
|
||||
local c = readu8(b, p)
|
||||
p += 1
|
||||
delay = delay * 128 + c % 128
|
||||
until c < 128 or delay > 2 ^ 28
|
||||
tick += delay
|
||||
end
|
||||
end
|
||||
return events, nil, true
|
||||
end
|
||||
|
||||
function Mus.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local rate = o.rate or 140
|
||||
if type(rate) ~= "number" or rate < 1 or rate > 100000 then
|
||||
return nil, Err.new(Err.ARG, "rate must be 1..100000 ticks per second")
|
||||
end
|
||||
if r:peek(4) ~= "MUS\x1a" then
|
||||
return nil, Err.new(Err.CORRUPT, "not a MUS file")
|
||||
end
|
||||
r:skip(4)
|
||||
local len, start, primary, secondary, ninst = r:u16le(), r:u16le(), r:u16le(), r:u16le(), r:u16le()
|
||||
r:skip(2)
|
||||
local instruments = {}
|
||||
for i = 1, ninst do
|
||||
instruments[i] = r:u16le()
|
||||
end
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
local size = r.limit - r.base
|
||||
if start > size then
|
||||
return nil, Err.new(Err.TRUNCATED, "score starts past the end")
|
||||
end
|
||||
local p = r.base + start
|
||||
local events, msg, truncated = score(r.buf, p, math.min(p + len, r.limit), primary, o.maxEvents or 2 ^ 24)
|
||||
if not events then
|
||||
return nil, Err.from(msg :: string, p)
|
||||
end
|
||||
local last = events[#events].tick
|
||||
table.insert(events, 1, { tick = 0, type = "meta", meta = 0x51, data = Render.tempoBytes(70, rate) })
|
||||
table.insert(events, { tick = last, type = "meta", meta = 0x2F, data = {} })
|
||||
local midi = Types.Midi.new(70)
|
||||
midi.format = 0
|
||||
midi.tracks = { { events = events } }
|
||||
Render.attach(midi, { format = "mus", primaryChannels = primary, secondaryChannels = secondary, instruments = instruments, rate = rate })
|
||||
midi.meta.truncated = truncated or p + len > r.limit
|
||||
return midi, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + MidiRender.RenderOptions)
|
||||
function Mus.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
|
||||
local midi, err = Mus.decode(r, opts)
|
||||
if not midi then
|
||||
return nil, err
|
||||
end
|
||||
return Render.decoder(midi, opts)
|
||||
end
|
||||
|
||||
return Mus
|
||||
@@ -0,0 +1,286 @@
|
||||
--!strict
|
||||
-- music/okt: Oktalyzer modules (OKTASONG, Armin Sander's Amiga tracker; 4 to 8 channels: each of the Amiga's four can
|
||||
-- be split into a mixed pair). Ported from OpenMPT's Load_okt.cpp (BSD, licenses/openmpt-LICENSE.txt). An IFF-style
|
||||
-- chunk list (containers/Chunks) read into the codecs/audio/Tracker Module, played as the "it" effect family with
|
||||
-- ProTracker periods and the PAL clock (flags.periods = "amiga"), Amiga period limits, slides on every tick, sample
|
||||
-- loops as sustain loops (released by R), Oktalyzer's three arpeggios, note slides (D / U every tick, L / H once:
|
||||
-- flags.oktSlides), and its volume command: on a mixed pair the volume is the pair's channel volume.
|
||||
-- Not supported: the Amiga LED filter (F), writing.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Chunks = require("@formats/containers/Chunks")
|
||||
local Tracker = require("@formats/codecs/audio/Tracker")
|
||||
local Load = require("@formats/codecs/audio/Tracker/Load")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Okt = {
|
||||
name = "okt",
|
||||
category = "music",
|
||||
extensions = { "okt", "okta" },
|
||||
mime = { "audio/x-okt" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
|
||||
caps = { decode = true, encode = false, render = true, channels = { 4, 8 } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local IT = Load.IT
|
||||
local LAYOUT = table.freeze({ bigEndian = true }) :: Chunks.Layout
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Okt.sniff(r: Bytes.Reader): number
|
||||
return if r:peek(8) == "OKTASONG" then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- a negative arpeggio offset as the equivalent positive one
|
||||
local function invert(p: number): number
|
||||
p %= 16
|
||||
if p == 0 then
|
||||
return 0
|
||||
end
|
||||
return if p <= 12 then 12 - p else 24 - p
|
||||
end
|
||||
|
||||
-- the Oktalyzer effect of a cell -> effect name?, param, volume (0..64, the volume column) or -1, a key off
|
||||
local function effect(e: number, p: number, paired: boolean): (string?, number, number, boolean)
|
||||
if e == 1 and p > 0 then
|
||||
return "portaup", p, -1, false -- "portamento down (period)": the period goes down
|
||||
elseif e == 2 and p > 0 then
|
||||
return "portadown", p, -1, false
|
||||
elseif e == 10 and p > 0 then
|
||||
return "arpeggio", p % 16 + invert(p // 16) * 16, -1, false -- down, original, up
|
||||
elseif e == 11 and p > 0 then
|
||||
return "arpeggio", p - p % 16 + invert(p % 16), -1, false -- original, up, original, down
|
||||
elseif e == 12 and p > 0 then
|
||||
return "arpeggio", p, -1, false -- up, up, original
|
||||
elseif e == 13 and p > 0 then
|
||||
return "noteslidedown", 0x10 + math.min(p, 15), -1, false
|
||||
elseif e == 30 and p > 0 then
|
||||
return "noteslideup", 0x10 + math.min(p, 15), -1, false
|
||||
elseif e == 21 and p > 0 then
|
||||
return "noteslidedown", 0x50 + math.min(p, 15), -1, false
|
||||
elseif e == 17 and p > 0 then
|
||||
return "noteslideup", 0x50 + math.min(p, 15), -1, false
|
||||
elseif e == 25 then
|
||||
return "jump", p, -1, false
|
||||
elseif e == 27 then
|
||||
return nil, 0, -1, true
|
||||
elseif e == 28 and p < 0x20 then
|
||||
return "speed", p, -1, false
|
||||
elseif e == 31 then
|
||||
local x, y = p // 16, p % 16
|
||||
local slide = if paired then "chanvolslide" else "volslide"
|
||||
if p <= 0x40 then
|
||||
if paired then
|
||||
return "chanvol", p, -1, false
|
||||
end
|
||||
return nil, 0, p, false
|
||||
elseif x == 4 then
|
||||
return slide, y, -1, false
|
||||
elseif x == 5 then
|
||||
return slide, y * 16, -1, false
|
||||
elseif x == 6 then
|
||||
return slide, 0xF0 + math.min(y, 0xE), -1, false
|
||||
elseif x == 7 then
|
||||
return slide, math.min(y, 0xE) * 16 + 0xF, -1, false
|
||||
end
|
||||
end
|
||||
return nil, 0, -1, false
|
||||
end
|
||||
|
||||
function Okt.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local budget = { left = opts and opts.maxBytes or 2 ^ 28 }
|
||||
if r:peek(8) ~= "OKTASONG" then
|
||||
return nil, Err.new(if r:size() < 8 then Err.TRUNCATED else Err.CORRUPT, "no OKTASONG signature")
|
||||
end
|
||||
local buf = r.buf
|
||||
local list = Chunks.walk(buf, r.base + 8, r.limit, LAYOUT)
|
||||
local cmod = Chunks.find(list, "CMOD")
|
||||
if not cmod or cmod.avail < 8 then
|
||||
return nil, Err.new(Err.CORRUPT, "no channel table (CMOD)")
|
||||
end
|
||||
-- channels: each Amiga channel is one channel, or a mixed pair
|
||||
local paired: { number } = {} -- 1: the first of a pair, -1: the second, 0: a raw Paula channel
|
||||
local pans: { number } = {}
|
||||
for ch = 0, 3 do
|
||||
local pan = if ch == 1 or ch == 2 then 0xC0 else 0x40
|
||||
if buffer.readu16(buf, cmod.offset + ch * 2) ~= 0 then
|
||||
table.insert(paired, 1)
|
||||
table.insert(pans, pan)
|
||||
table.insert(paired, -1)
|
||||
else
|
||||
table.insert(paired, 0)
|
||||
end
|
||||
table.insert(pans, pan)
|
||||
end
|
||||
local nch = #paired
|
||||
local m = Tracker.newModule("okt", nch, "it")
|
||||
m.linear = false
|
||||
m.instrumentMode = false
|
||||
m.tempo = 125
|
||||
m.flags.periods, m.flags.amigaLimits, m.flags.fastPortas, m.flags.oktSlides = "amiga", true, true, true
|
||||
for i = 1, nch do
|
||||
m.channelPan[i] = pans[i]
|
||||
end
|
||||
-- samples: 32-byte headers (name, length, loop start / length in words, volume, type 0 / 1 / 2)
|
||||
local types: { number } = {}
|
||||
local samp = Chunks.find(list, "SAMP")
|
||||
if samp then
|
||||
for i = 1, math.min(samp.avail // 32, 36) do
|
||||
local h = Bytes.reader(buf, samp.offset + (i - 1) * 32, 32)
|
||||
local s = Tracker.newSample(h:fixed(20))
|
||||
local len, ls, ll, vol, typ = h:u32be(), h:u16be() * 2, h:u16be() * 2, h:u16be(), h:u16be()
|
||||
s.c5speed = 8287
|
||||
s.volume = math.min(vol, 64)
|
||||
s.length = len - len % 2
|
||||
if ll > 2 and ls + ll <= s.length then
|
||||
s.susStart, s.susEnd, s.susType = ls, ls + ll, 1
|
||||
end
|
||||
types[i] = typ
|
||||
m.samples[i] = s
|
||||
end
|
||||
end
|
||||
local spee = Chunks.find(list, "SPEE")
|
||||
if spee and spee.avail >= 2 then
|
||||
m.speed = math.clamp(buffer.readu8(buf, spee.offset) * 256 + buffer.readu8(buf, spee.offset + 1), 1, 255)
|
||||
end
|
||||
local nord = 0
|
||||
local plen = Chunks.find(list, "PLEN")
|
||||
if plen and plen.avail >= 2 then
|
||||
nord = buffer.readu8(buf, plen.offset) * 256 + buffer.readu8(buf, plen.offset + 1)
|
||||
end
|
||||
local patt = Chunks.find(list, "PATT")
|
||||
for i = 1, math.min(nord, if patt then patt.avail else 0) do
|
||||
m.order[i] = buffer.readu8(buf, (patt :: Chunks.Chunk).offset + i - 1)
|
||||
end
|
||||
-- patterns (PBOD: rows, then 4 bytes per cell: note 1..36, sample, effect, parameter)
|
||||
local copies: { [number]: boolean } = {} -- type B samples with a loop also need an unlooped copy (paired channels)
|
||||
local npat = 0
|
||||
for _, c in list do
|
||||
if c.id == "PBOD" and npat < 256 then
|
||||
local pr = Bytes.reader(buf, c.offset, c.avail)
|
||||
local rows = if c.avail >= 2 then math.clamp(pr:u16be(), 1, 1024) else 64
|
||||
local pat = Tracker.newPattern(rows, nch)
|
||||
npat += 1
|
||||
m.patterns[npat] = pat
|
||||
local d = pat.data
|
||||
for row = 0, rows - 1 do
|
||||
for ch = 0, nch - 1 do
|
||||
local note, ins, e, p = pr:u8(), pr:u8(), pr:u8(), pr:u8()
|
||||
if pr.err then
|
||||
break
|
||||
end
|
||||
local q = (row * nch + ch) * 5
|
||||
local pair = paired[ch + 1] ~= 0
|
||||
if note > 0 and note <= 36 then
|
||||
local n = note + 36 -- note 13 = C-4 = ProTracker period 428 (OpenMPT keeps MOD notes an octave up)
|
||||
if pair and n >= 49 + 22 then
|
||||
n = 49 + 21 -- the mixer's highest note
|
||||
end
|
||||
local smp = ins + 1
|
||||
local s = m.samples[smp]
|
||||
if s then
|
||||
if pair and s.volume < 64 then
|
||||
buffer.writeu8(d, q + 2, 64 + 1) -- the default volume only works on raw Paula channels
|
||||
end
|
||||
local t = types[smp]
|
||||
if (t == 1 and pair) or (t == 0 and not pair) then
|
||||
smp += 100 -- a sample of the wrong type stops the channel
|
||||
elseif t == 2 and pair and s.susType > 0 then
|
||||
copies[smp] = true
|
||||
smp += 36
|
||||
end
|
||||
end
|
||||
buffer.writeu8(d, q, n)
|
||||
buffer.writeu8(d, q + 1, smp)
|
||||
end
|
||||
local name, param, vol, off = effect(e, p, pair)
|
||||
if off then
|
||||
buffer.writeu8(d, q, 255)
|
||||
buffer.writeu8(d, q + 1, 0)
|
||||
end
|
||||
if vol >= 0 then
|
||||
buffer.writeu8(d, q + 2, vol + 1)
|
||||
end
|
||||
local fx, fp = Load.itEffect(name, param)
|
||||
if fx ~= 0 then
|
||||
buffer.writeu8(d, q + 3, fx)
|
||||
buffer.writeu8(d, q + 4, fp)
|
||||
if name == "chanvol" or name == "chanvolslide" then
|
||||
-- a mixed pair shares its volume: the other channel gets it too (the second one wins)
|
||||
local other = ch + paired[ch + 1]
|
||||
local o2 = (row * nch + other) * 5
|
||||
local ofx = buffer.readu8(d, o2 + 3)
|
||||
if ofx == 0 or ofx == IT.chanvol or ofx == IT.chanvolslide then
|
||||
buffer.writeu8(d, o2 + 3, fx)
|
||||
buffer.writeu8(d, o2 + 4, fp)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
-- sample data: SBOD chunks in order (signed 8-bit), for the samples with a length
|
||||
local k = 0
|
||||
local bodies: { Chunks.Chunk } = {}
|
||||
for _, c in list do
|
||||
if c.id == "SBOD" and c.avail > 0 then
|
||||
table.insert(bodies, c)
|
||||
end
|
||||
end
|
||||
local nsmp = #m.samples
|
||||
for i = 1, nsmp do
|
||||
local s = m.samples[i]
|
||||
if s.length > 0 then
|
||||
k += 1
|
||||
local c = bodies[k]
|
||||
if not c then
|
||||
s.length = 0
|
||||
continue
|
||||
end
|
||||
local ok, err = Load.readSample(buf, c.offset, math.min(s.length, c.avail), { bits = 8, signed = true, limit = c.offset + c.avail }, s, budget)
|
||||
if not ok then
|
||||
return nil, err
|
||||
end
|
||||
end
|
||||
end
|
||||
for i = 1, nsmp do
|
||||
local s = m.samples[i]
|
||||
if copies[i] then
|
||||
local cp = Tracker.newSample(s.name)
|
||||
cp.c5speed, cp.volume, cp.data, cp.length = s.c5speed, s.volume, s.data, s.length
|
||||
m.samples[i + 36] = cp
|
||||
end
|
||||
end
|
||||
for i = 1, (if next(copies) then 72 else nsmp) do
|
||||
if m.samples[i] == nil then
|
||||
m.samples[i] = Tracker.newSample()
|
||||
end
|
||||
end
|
||||
m.meta.source = { format = "okt", channels = nch }
|
||||
local ok, verr = Tracker.validate(m)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module")
|
||||
end
|
||||
return m, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions)
|
||||
function Okt.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
|
||||
local m, err = Okt.decode(r, opts)
|
||||
if not m then
|
||||
return nil, err
|
||||
end
|
||||
return Tracker.render(m, opts)
|
||||
end
|
||||
|
||||
return Okt
|
||||
@@ -0,0 +1,227 @@
|
||||
--!strict
|
||||
-- music/ptm: PolyTracker modules (PTMF, Lone Ranger's DOS tracker; up to 32 channels, S3M-like packed patterns, MOD
|
||||
-- effect letters). Ported from OpenMPT's Load_ptm.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the
|
||||
-- codecs/audio/Tracker Module and plays as the "it" effect family with Amiga periods, IT old effects and linked Gxx
|
||||
-- memory (as OpenMPT converts PTM): MOD effects whose slides take S3M-style fine values, global volume, retrigger,
|
||||
-- fine vibrato and the note slides (G..J: Tracker.EXT), delta-coded 8-bit and 16-bit samples (8-bit deltas of the
|
||||
-- byte stream, as PolyTracker stores them), ping-pong loops.
|
||||
-- Not supported: reverse sample offset (K), sample offsets scaled for 16-bit samples, writing.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Tracker = require("@formats/codecs/audio/Tracker")
|
||||
local Load = require("@formats/codecs/audio/Tracker/Load")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Ptm = {
|
||||
name = "ptm",
|
||||
category = "music",
|
||||
extensions = { "ptm" },
|
||||
mime = { "audio/x-ptm" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
|
||||
caps = { decode = true, encode = false, render = true, channels = { 1, 32 } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
-- PolyTracker's effects past MOD's 0..F
|
||||
local EXTRA = { "globalvol", "retrig", "finevibrato", "noteslideup", "noteslidedown", "noteslideupretrig", "noteslidedownretrig" }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
local function validHeader(r: Bytes.Reader): boolean
|
||||
if r:size() < 608 or r:peek(4, 44) ~= "PTMF" or r:peekU8(28) ~= 26 or r:peekU8(30) > 2 then
|
||||
return false
|
||||
end
|
||||
local h = r:sub(32, 10)
|
||||
local nord, nsmp, npat, nch, flags = h:u16le(), h:u16le(), h:u16le(), h:u16le(), h:u16le()
|
||||
return flags == 0 and nch >= 1 and nch <= 32 and nord >= 1 and nord <= 256 and nsmp >= 1 and nsmp <= 255 and npat >= 1 and npat <= 128
|
||||
end
|
||||
|
||||
function Ptm.sniff(r: Bytes.Reader): number
|
||||
return if validHeader(r) then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- 16-bit samples: the byte stream is 8-bit delta coded, then read as little-endian 16-bit values
|
||||
local function delta16(buf: buffer, off: number, frames: number, limit: number): (buffer, number)
|
||||
local n = math.max(0, math.min(frames, (limit - off) // 2))
|
||||
local raw = buffer.create(n * 2)
|
||||
local acc = 0
|
||||
for i = 0, n * 2 - 1 do
|
||||
acc = (acc + buffer.readu8(buf, off + i)) % 256
|
||||
buffer.writeu8(raw, i, acc)
|
||||
end
|
||||
return raw, n
|
||||
end
|
||||
|
||||
-- a PolyTracker effect -> name?, param
|
||||
local function effect(cmd: number, param: number): (string?, number)
|
||||
if cmd == 0x10 then
|
||||
return "globalvol", math.min(param, 0x40) * 2
|
||||
elseif cmd > 0x10 then
|
||||
return EXTRA[cmd - 0x10 + 1], param
|
||||
elseif cmd == 8 then
|
||||
return "s3mex", 0x80 + (math.max(param // 8, 1) - 1) % 16 -- 8xx pans in 16 steps
|
||||
end
|
||||
return Load.modCommand(cmd, param)
|
||||
end
|
||||
|
||||
-- one pattern (S3M-style packing: 0 ends a row; channel | 0x20 note + instrument, 0x40 effect, 0x80 volume)
|
||||
local function readPattern(pr: Bytes.Reader, d: buffer, nch: number)
|
||||
local row = 0
|
||||
while row < 64 and not pr:eof() do
|
||||
local b = pr:u8()
|
||||
if b == 0 then
|
||||
row += 1
|
||||
else
|
||||
local ch = b % 32
|
||||
local q = (row * nch + ch) * 5
|
||||
local ok = ch < nch
|
||||
if bit32.band(b, 0x20) ~= 0 then
|
||||
local note, ins = pr:u8(), pr:u8()
|
||||
if note == 254 then
|
||||
note = 254
|
||||
elseif note == 0 or note > 120 then
|
||||
note = 0
|
||||
end
|
||||
if ok then
|
||||
buffer.writeu8(d, q, note)
|
||||
buffer.writeu8(d, q + 1, ins)
|
||||
end
|
||||
end
|
||||
if bit32.band(b, 0x40) ~= 0 then
|
||||
local name, param = effect(pr:u8(), pr:u8())
|
||||
if ok then
|
||||
if name == "volume" then
|
||||
if buffer.readu8(d, q + 2) == 0 then
|
||||
buffer.writeu8(d, q + 2, math.min(param, 64) + 1)
|
||||
end
|
||||
else
|
||||
local fx, fp = Load.itEffect(name, param)
|
||||
buffer.writeu8(d, q + 3, fx)
|
||||
buffer.writeu8(d, q + 4, fp)
|
||||
end
|
||||
end
|
||||
end
|
||||
if bit32.band(b, 0x80) ~= 0 then
|
||||
local v = pr:u8()
|
||||
if ok then
|
||||
buffer.writeu8(d, q + 2, math.min(v, 64) + 1)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function Ptm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local budget = { left = opts and opts.maxBytes or 2 ^ 28 }
|
||||
if not validHeader(r) then
|
||||
return nil, Err.new(if r:size() < 608 then Err.TRUNCATED else Err.CORRUPT, "not a PolyTracker module")
|
||||
end
|
||||
local title = r:fixed(28)
|
||||
r:skip(1)
|
||||
local vlo, vhi = r:u8(), r:u8()
|
||||
r:skip(1)
|
||||
local nord, nsmp, npat, nch = r:u16le(), r:u16le(), r:u16le(), r:u16le()
|
||||
r:seek(64)
|
||||
local m = Tracker.newModule("ptm", nch, "it")
|
||||
m.title = title
|
||||
m.linear = false
|
||||
m.instrumentMode = false
|
||||
m.flags.oldEffects, m.flags.compatGxx = true, true
|
||||
m.flags.panLaw = "ft2" -- OpenMPT plays PTM with its FT2 mix levels
|
||||
for i = 1, 32 do
|
||||
local p = r:u8()
|
||||
if i <= nch then
|
||||
m.channelPan[i] = (p % 16) * 16 + 4
|
||||
end
|
||||
end
|
||||
for i = 1, 256 do
|
||||
local o = r:u8()
|
||||
if i <= nord then
|
||||
m.order[i] = o
|
||||
end
|
||||
end
|
||||
local patOff: { number } = {}
|
||||
for i = 1, 128 do
|
||||
patOff[i] = r:u16le() * 16
|
||||
end
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
-- samples
|
||||
local buf = r.buf
|
||||
for i = 1, nsmp do
|
||||
local h = r:slice(80)
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
local flags = h:u8()
|
||||
h:skip(12)
|
||||
local vol, c4 = h:u8(), h:u16le()
|
||||
h:skip(2)
|
||||
local off, len, ls, le = h:u32le(), h:u32le(), h:u32le(), h:u32le()
|
||||
h:skip(14)
|
||||
local s = Tracker.newSample(h:fixed(28))
|
||||
m.samples[i] = s
|
||||
s.volume = math.min(vol, 64)
|
||||
s.c5speed = math.max(1, c4 * 2)
|
||||
if flags % 4 == 1 and len > 0 then
|
||||
local bits = if bit32.band(flags, 0x10) ~= 0 then 16 else 8
|
||||
if le > ls then
|
||||
le -= 1
|
||||
end
|
||||
local frames = len
|
||||
if bits == 16 then
|
||||
frames, ls, le = frames // 2, ls // 2, le // 2
|
||||
end
|
||||
local at = r.base + off
|
||||
if at < r.limit then
|
||||
local ok, err
|
||||
if bits == 16 then
|
||||
local raw, n = delta16(buf, at, frames, r.limit)
|
||||
ok, err = Load.readSample(raw, 0, n, { bits = 16, signed = true }, s, budget)
|
||||
else
|
||||
ok, err = Load.readSample(buf, at, frames, { bits = 8, signed = true, delta = true, limit = r.limit }, s, budget)
|
||||
end
|
||||
if not ok then
|
||||
return nil, err
|
||||
end
|
||||
end
|
||||
if bit32.band(flags, 4) ~= 0 and le > ls then
|
||||
s.loopStart, s.loopEnd = ls, math.min(le, s.length)
|
||||
s.loopType = if bit32.band(flags, 8) ~= 0 then 2 else 1
|
||||
end
|
||||
end
|
||||
end
|
||||
for p = 1, npat do
|
||||
local pat = Tracker.newPattern(64, nch)
|
||||
m.patterns[p] = pat
|
||||
if patOff[p] > 0 and patOff[p] < r:size() then
|
||||
readPattern(r:sub(patOff[p]), pat.data, nch)
|
||||
end
|
||||
end
|
||||
m.meta.source = { format = "ptm", version = string.format("%d.%02x", vhi, vlo) }
|
||||
local ok, verr = Tracker.validate(m)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module")
|
||||
end
|
||||
return m, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions)
|
||||
function Ptm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
|
||||
local m, err = Ptm.decode(r, opts)
|
||||
if not m then
|
||||
return nil, err
|
||||
end
|
||||
return Tracker.render(m, opts)
|
||||
end
|
||||
|
||||
return Ptm
|
||||
@@ -0,0 +1,233 @@
|
||||
--!strict
|
||||
-- music/stm: Scream Tracker 2 modules (STM, "!Scream!" / BMOD2STM / WUZAMOD! / SWavePro; 4 channels, 31 samples).
|
||||
-- Ported from OpenMPT's Load_stm.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the codecs/audio/Tracker Module
|
||||
-- and plays as the "s3m" effect family with Scream Tracker 2's tempo (flags.st2Tempo: the speed byte also sets the
|
||||
-- tick length), no effect memory, no fine slides (the loader drops what ST2 ignores) and its deferred Bxx (the jump
|
||||
-- happens at the end of the pattern or at the next Cxx).
|
||||
-- Not supported: STX (Scream Tracker Music Interface Kit), ST2's noise for samples at volume 0 (silent here), writing.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Tracker = require("@formats/codecs/audio/Tracker")
|
||||
local Load = require("@formats/codecs/audio/Tracker/Load")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Stm = {
|
||||
name = "stm",
|
||||
category = "music",
|
||||
extensions = { "stm" },
|
||||
mime = { "audio/x-stm" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
|
||||
caps = { decode = true, encode = false, render = true, channels = { 4, 4 } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local IT = Load.IT
|
||||
-- .ABCDEFGHIJ (K..O do nothing)
|
||||
local EFFECTS = { "speed", "jump", "break", "volslide", "portadown", "portaup", "toneporta", "vibrato", "tremor", "arpeggio" }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
local function validHeader(r: Bytes.Reader): boolean
|
||||
if r:size() < 48 then
|
||||
return false
|
||||
end
|
||||
local eof, ftype, major, minor = r:peekU8(28), r:peekU8(29), r:peekU8(30), r:peekU8(31)
|
||||
local npat, gv = r:peekU8(33), r:peekU8(34)
|
||||
if ftype ~= 2 or (eof ~= 0x1A and eof ~= 2) or major ~= 2 or (minor ~= 0 and minor ~= 10 and minor ~= 20 and minor ~= 21) then
|
||||
return false
|
||||
end
|
||||
if npat > 64 or (gv > 64 and gv ~= 0x58) then
|
||||
return false
|
||||
end
|
||||
for i = 20, 27 do
|
||||
local c = r:peekU8(i)
|
||||
if c < 0x20 or c >= 0x7F then
|
||||
return false
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
function Stm.sniff(r: Bytes.Reader): number
|
||||
return if validHeader(r) then 0.7 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- a tempo byte of files before ST 2.21 is decimal
|
||||
local function tempoByte(v: number, minor: number): number
|
||||
return if minor < 21 then (v // 10) * 16 + v % 10 else v
|
||||
end
|
||||
|
||||
function Stm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local budget = { left = opts and opts.maxBytes or 2 ^ 28 }
|
||||
if not validHeader(r) then
|
||||
return nil, Err.new(if r:size() < 48 then Err.TRUNCATED else Err.CORRUPT, "not a Scream Tracker 2 module")
|
||||
end
|
||||
local title = r:fixed(20)
|
||||
local tracker = r:fixed(8)
|
||||
r:skip(3)
|
||||
local minor, initTempo, npat, gv = r:u8(), r:u8(), r:u8(), r:u8()
|
||||
r:skip(13)
|
||||
local m = Tracker.newModule("stm", 4, "s3m")
|
||||
m.title = title
|
||||
m.linear = false
|
||||
m.instrumentMode = false
|
||||
m.flags.st2Tempo = true
|
||||
initTempo = tempoByte(initTempo, minor)
|
||||
if initTempo == 0 then
|
||||
initTempo = 0x60
|
||||
end
|
||||
m.speed, m.tempo = Tracker.st2Tempo(initTempo)
|
||||
if minor > 10 then
|
||||
m.globalVolume = math.min(gv, 64) * 2
|
||||
end
|
||||
local offsets: { number } = {}
|
||||
for i = 1, 31 do
|
||||
local s = Tracker.newSample(r:fixed(12))
|
||||
local zero = r:u8()
|
||||
r:skip(1)
|
||||
local off, len, ls, le = r:u16le(), r:u16le(), r:u16le(), r:u16le()
|
||||
local vol = r:u8()
|
||||
r:skip(1)
|
||||
local rate = r:u16le()
|
||||
r:skip(6)
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
if zero ~= 0 and zero ~= 46 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad sample header " .. i)
|
||||
end
|
||||
s.c5speed = if rate > 0 then rate else 8363
|
||||
s.volume = math.min(vol, 64)
|
||||
if len < 2 then
|
||||
len = 0
|
||||
end
|
||||
if ls < len and le > ls and le ~= 0xFFFF then
|
||||
s.loopStart, s.loopEnd, s.loopType = ls, le, 1
|
||||
len = math.max(le, len) -- ST2 lets a loop run into the next sample's data
|
||||
end
|
||||
s.length = len
|
||||
offsets[i] = off * 16
|
||||
m.samples[i] = s
|
||||
end
|
||||
for i = 1, (if minor == 0 then 64 else 128) do
|
||||
local o = r:u8()
|
||||
if o == 99 or o == 255 then
|
||||
o = 255
|
||||
elseif o > 63 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad order list")
|
||||
end
|
||||
m.order[i] = o
|
||||
end
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
while #m.order > 0 and m.order[#m.order] == 255 do
|
||||
table.remove(m.order)
|
||||
end
|
||||
-- patterns: 64 rows x 4 channels; one byte 0xFB (C-0, volume 0), 0xFC (nothing) or 0xFD (note cut), else 4 bytes
|
||||
for p = 0, npat - 1 do
|
||||
local pat = Tracker.newPattern(64, 4)
|
||||
m.patterns[p + 1] = pat
|
||||
local d = pat.data
|
||||
local breakPos, breakRow = -1, 63 -- ST2: Bxx only sets the next order, taken at the pattern's end or a Cxx
|
||||
for row = 0, 63 do
|
||||
for ch = 0, 3 do
|
||||
local q = (row * 4 + ch) * 5
|
||||
local note = r:u8()
|
||||
local insVol, volCmd, info = 0, 0, 0
|
||||
if note == 0xFB then
|
||||
note = 0 -- a C-0 at volume 0 (OpenMPT reads it so)
|
||||
elseif note == 0xFD then
|
||||
buffer.writeu8(d, q, 254)
|
||||
elseif note ~= 0xFC then
|
||||
insVol, volCmd, info = r:u8(), r:u8(), r:u8()
|
||||
end
|
||||
if note ~= 0xFC and note ~= 0xFD then
|
||||
if note == 0xFE then
|
||||
buffer.writeu8(d, q, 254)
|
||||
elseif note < 0x60 then
|
||||
buffer.writeu8(d, q, (note // 16) * 12 + note % 16 + 37)
|
||||
end
|
||||
local ins = insVol // 8
|
||||
buffer.writeu8(d, q + 1, if ins > 31 then 0 else ins)
|
||||
local vol = insVol % 8 + (volCmd // 16) * 8
|
||||
if vol <= 64 then
|
||||
buffer.writeu8(d, q + 2, vol + 1)
|
||||
end
|
||||
local name, param = EFFECTS[volCmd % 16], info
|
||||
if name == "volslide" then
|
||||
param = if param % 16 > 0 then param % 16 else param - param % 16
|
||||
elseif name == "break" then
|
||||
param = ((param - param % 16) * 10 + param % 16) % 256
|
||||
if breakPos >= 0 and param == 0 then
|
||||
name, param = "jump", breakPos -- Bxx + C00 is a plain Bxx
|
||||
breakPos = -1
|
||||
end
|
||||
breakRow = math.min(breakRow, row)
|
||||
if name == "break" then
|
||||
param = Load.bcd(param)
|
||||
end
|
||||
elseif name == "jump" then
|
||||
breakPos, breakRow = param, 63
|
||||
name = nil
|
||||
elseif name == "speed" then
|
||||
param = tempoByte(param, minor)
|
||||
if param == 0 then
|
||||
name = nil
|
||||
end
|
||||
elseif name ~= "tremor" and param == 0 then
|
||||
name = nil -- no effect memory in ST2
|
||||
end
|
||||
if name then
|
||||
buffer.writeu8(d, q + 3, IT[name])
|
||||
buffer.writeu8(d, q + 4, param)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
if breakPos >= 0 then
|
||||
Load.writeEffect(m, p, breakRow, IT.jump, breakPos, "prev")
|
||||
end
|
||||
end
|
||||
-- sample data: signed 8-bit at the paragraph offsets (samples at volume 0 are not read)
|
||||
local buf = r.buf
|
||||
for i = 1, 31 do
|
||||
local s = m.samples[i]
|
||||
local len = s.length
|
||||
s.length = 0
|
||||
if len > 0 and s.volume > 0 and offsets[i] > 48 then
|
||||
local ok, err = Load.readSample(buf, r.base + offsets[i], len, { bits = 8, signed = true, limit = r.limit }, s, budget)
|
||||
if not ok then
|
||||
return nil, err
|
||||
end
|
||||
end
|
||||
end
|
||||
m.meta.source = { format = "stm", tracker = tracker, version = "2." .. minor }
|
||||
local ok, verr = Tracker.validate(m)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module")
|
||||
end
|
||||
return m, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions)
|
||||
function Stm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
|
||||
local m, err = Stm.decode(r, opts)
|
||||
if not m then
|
||||
return nil, err
|
||||
end
|
||||
return Tracker.render(m, opts)
|
||||
end
|
||||
|
||||
return Stm
|
||||
@@ -0,0 +1,309 @@
|
||||
--!strict
|
||||
-- music/ult: UltraTracker modules (MAS_UTrack_V001 .. V004; up to 32 channels, two effects per cell, patterns stored
|
||||
-- channel by channel with run-length repeats). Ported from OpenMPT's Load_ult.cpp (BSD, licenses/openmpt-LICENSE.txt).
|
||||
-- Reads into the codecs/audio/Tracker Module and plays as the "it" effect family with Amiga periods, IT old effects
|
||||
-- and linked Gxx memory (as OpenMPT converts ULT): the two effect columns go into the IT volume column and the effect
|
||||
-- column (or the more important one is kept), sample loops are sustain loops (released by a key off), the tone
|
||||
-- portamento keeps going on later rows. 8 / 16-bit signed samples, the v1.4+ sample speed and finetune.
|
||||
-- Not supported: reverse playback (5x2), "no loop" (5x1), vibrato strength (E0x), sample offsets past 64 KiB (the
|
||||
-- high byte is dropped), the logarithmic volumes of pre-1.4 files, writing.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Tracker = require("@formats/codecs/audio/Tracker")
|
||||
local Load = require("@formats/codecs/audio/Tracker/Load")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Ult = {
|
||||
name = "ult",
|
||||
category = "music",
|
||||
extensions = { "ult" },
|
||||
mime = { "audio/x-ult" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" },
|
||||
caps = { decode = true, encode = false, render = true, channels = { 1, 32 } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local EFFECTS: { [number]: string } = {
|
||||
[0] = "arpeggio", [1] = "portaup", [2] = "portadown", [3] = "toneporta", [4] = "vibrato", [7] = "tremolo",
|
||||
[9] = "offset", [10] = "volslide", [11] = "panning8", [12] = "volume8", [13] = "break", [15] = "speed",
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Ult.sniff(r: Bytes.Reader): number
|
||||
local v = r:peekU8(14)
|
||||
if r:size() >= 48 and r:peek(14) == "MAS_UTrack_V00" and v >= 0x31 and v <= 0x34 then
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- one effect nibble + parameter -> name?, param (OpenMPT's TranslateULTCommands)
|
||||
local function translate(e: number, param: number, version: number): (string?, number)
|
||||
local name = EFFECTS[e]
|
||||
if e == 0 then
|
||||
if param == 0 or version < 3 then
|
||||
name = nil
|
||||
end
|
||||
elseif e == 5 then
|
||||
if (param % 16 == 0xC or param // 16 == 0xC) and version >= 3 then
|
||||
return "keyoff", 0
|
||||
end
|
||||
elseif e == 7 then
|
||||
if version < 4 then
|
||||
name = nil
|
||||
end
|
||||
elseif e == 0xA then
|
||||
if param >= 16 then
|
||||
param -= param % 16
|
||||
end
|
||||
elseif e == 0xB then
|
||||
param = (param % 16) * 0x11
|
||||
elseif e == 0xD then
|
||||
param = 10 * (param // 16) + param % 16
|
||||
elseif e == 0xE then
|
||||
local x, y = param // 16, param % 16
|
||||
if x == 1 then
|
||||
return "portaup", 0xF0 + y
|
||||
elseif x == 2 then
|
||||
return "portadown", 0xF0 + y
|
||||
elseif x == 8 and version >= 4 then
|
||||
return "s3mex", 0x60 + y
|
||||
elseif x == 9 then
|
||||
return "retrig", y
|
||||
elseif x == 0xA then
|
||||
return "volslide", y * 16 + 0xF
|
||||
elseif x == 0xB then
|
||||
return "volslide", 0xF0 + y
|
||||
elseif x == 0xC or x == 0xD then
|
||||
return "s3mex", param
|
||||
end
|
||||
return nil, param
|
||||
elseif e == 0xF then
|
||||
if param > 0x2F then
|
||||
name = "tempo"
|
||||
end
|
||||
end
|
||||
return name, param
|
||||
end
|
||||
|
||||
-- volume slide + vibrato / tone portamento without a parameter -> one combined effect (OpenMPT's CombineEffects)
|
||||
local function combine(a: string?, pa: number, b: string?, pb: number): (string?, number, string?, number)
|
||||
if a == "volslide" and (b == "vibrato" or b == "toneportavol") and pb == 0 then
|
||||
return if b == "vibrato" then "vibratovol" else "toneportavol", pa, nil, 0
|
||||
elseif b == "volslide" and (a == "vibrato" or a == "toneportavol") and pa == 0 then
|
||||
return if a == "vibrato" then "vibratovol" else "toneportavol", pb, nil, 0
|
||||
end
|
||||
return a, pa, b, pb
|
||||
end
|
||||
|
||||
-- an event: [0xFC repeat] note instrument effects param1 param2 -> repeat, note, instrument, volume byte, fx, param,
|
||||
-- lost global effect (name?, param)
|
||||
local function readEvent(r: Bytes.Reader, version: number): (number, number, number, number, number, number, string?, number)
|
||||
local rep = 1
|
||||
local b = r:u8()
|
||||
if b == 0xFC then
|
||||
rep = r:u8()
|
||||
b = r:u8()
|
||||
end
|
||||
local note = if b > 0 and b < 97 then b + 24 else 0
|
||||
local ins, cmd, p1, p2 = r:u8(), r:u8(), r:u8(), r:u8()
|
||||
local c1, q1 = translate(cmd % 16, p1, version)
|
||||
local c2, q2 = translate(cmd // 16, p2, version)
|
||||
if c1 == "offset" and c2 == "offset" then
|
||||
local off = (p2 * 256 + p1) // 64
|
||||
return rep, note, ins, 0, Load.IT.offset, off % 256, nil, 0
|
||||
elseif c1 == "offset" then
|
||||
q1 = math.min(p1 * 4, 255)
|
||||
elseif c2 == "offset" then
|
||||
q2 = math.min(p2 * 4, 255)
|
||||
elseif c1 ~= nil and c1 == c2 then
|
||||
c2 = nil
|
||||
end
|
||||
if c2 == nil then -- (OpenMPT also swaps for CMD_VOLUME, which ULT never produces)
|
||||
c1, q1, c2, q2 = c2, q2, c1, q1
|
||||
end
|
||||
c2, q2, c1, q1 = combine(c2, q2, c1, q1)
|
||||
if c1 == "keyoff" or c2 == "keyoff" then
|
||||
-- key off (5xC): a note-off when the cell has no note
|
||||
if note == 0 then
|
||||
note = 255
|
||||
end
|
||||
if c1 == "keyoff" then
|
||||
c1 = nil
|
||||
else
|
||||
c2 = nil
|
||||
end
|
||||
end
|
||||
local vol, name, param, lost, lostParam = Load.fillTwo(c1, q1, c2, q2)
|
||||
local fx, fp = Load.itEffect(name, param)
|
||||
return rep, note, ins, vol, fx, fp, lost, lostParam
|
||||
end
|
||||
|
||||
function Ult.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local budget = { left = opts and opts.maxBytes or 2 ^ 28 }
|
||||
if Ult.sniff(r) == 0 then
|
||||
return nil, Err.new(if r:size() < 48 then Err.TRUNCATED else Err.CORRUPT, "not an UltraTracker module")
|
||||
end
|
||||
r:skip(14)
|
||||
local version = r:u8() - 0x30
|
||||
local title = (string.gsub(r:fixed(32), " +$", ""))
|
||||
local lines = r:u8()
|
||||
local message = r:string(lines * 32)
|
||||
local nsmp = r:u8()
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
local samples, sizes = {}, {}
|
||||
for i = 1, nsmp do
|
||||
local s = Tracker.newSample((string.gsub(r:fixed(32), " +$", "")))
|
||||
r:skip(12)
|
||||
local ls, le, ss, se = r:u32le(), r:u32le(), r:u32le(), r:u32le()
|
||||
local vol, flags = r:u8(), r:u8()
|
||||
local speed, finetune = 8363, 0
|
||||
if version >= 4 then
|
||||
speed, finetune = r:u16le(), r:i16le()
|
||||
else
|
||||
finetune = r:i16le()
|
||||
end
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
local bits = if bit32.band(flags, 4) ~= 0 then 16 else 8
|
||||
s.bits = bits
|
||||
sizes[i] = 0
|
||||
if se > ss then
|
||||
s.length = se - ss
|
||||
sizes[i] = s.length * bits // 8
|
||||
s.volume = vol / 4
|
||||
s.c5speed = math.max(1, speed * 2 * 2 ^ (finetune / (12 * 32768)))
|
||||
if bit32.band(flags, 8) ~= 0 then
|
||||
if bits == 16 then
|
||||
ls, le = ls // 2, le // 2
|
||||
end
|
||||
s.susStart, s.susEnd = ls, le
|
||||
s.susType = if bit32.band(flags, 16) ~= 0 then 2 else 1
|
||||
end
|
||||
end
|
||||
samples[i] = s
|
||||
end
|
||||
local order = {}
|
||||
for i = 1, 256 do
|
||||
order[i] = r:u8()
|
||||
end
|
||||
local nch, npat = r:u8() + 1, r:u8() + 1
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
if nch > 32 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, nch .. " channels")
|
||||
end
|
||||
local m = Tracker.newModule("ult", nch, "it")
|
||||
m.title = title
|
||||
m.meta.message = message
|
||||
m.linear = false
|
||||
m.instrumentMode = false
|
||||
m.flags.oldEffects, m.flags.compatGxx, m.flags.autoTonePorta = true, true, true
|
||||
m.samples = samples
|
||||
for i = 1, 256 do
|
||||
m.order[i] = order[i]
|
||||
end
|
||||
while #m.order > 0 and m.order[#m.order] == 255 do
|
||||
table.remove(m.order)
|
||||
end
|
||||
for i = 1, nch do
|
||||
m.channelPan[i] = if version >= 3 then (r:u8() % 16) * 16 + 8 elseif i % 2 == 0 then 192 else 64
|
||||
end
|
||||
for p = 1, npat do
|
||||
m.patterns[p] = Tracker.newPattern(64, nch)
|
||||
end
|
||||
-- events, channel by channel, pattern by pattern
|
||||
local speed0 = false
|
||||
for ch = 0, nch - 1 do
|
||||
for p = 0, npat - 1 do
|
||||
if r:remaining() < 5 then
|
||||
break
|
||||
end
|
||||
local d = m.patterns[p + 1].data
|
||||
local row = 0
|
||||
while row < 64 do
|
||||
local rep, note, ins, vol, fx, param, lost, lostParam = readEvent(r, version)
|
||||
if r.err then
|
||||
break
|
||||
end
|
||||
if lost and Load.isGlobal(lost, lostParam) then
|
||||
local lf, lp = Load.itEffect(lost, lostParam)
|
||||
Load.writeEffect(m, p, row, lf, lp, "next")
|
||||
end
|
||||
rep = math.min(rep, 64 - row)
|
||||
if rep == 0 then
|
||||
break
|
||||
end
|
||||
if fx == Load.IT.speed and param == 0 then
|
||||
speed0 = true
|
||||
end
|
||||
for _ = 1, rep do
|
||||
local q = (row * nch + ch) * 5
|
||||
buffer.writeu8(d, q, note)
|
||||
buffer.writeu8(d, q + 1, ins)
|
||||
buffer.writeu8(d, q + 2, vol)
|
||||
buffer.writeu8(d, q + 3, fx)
|
||||
buffer.writeu8(d, q + 4, param)
|
||||
row += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
r.err = nil
|
||||
if speed0 then
|
||||
-- speed 0 resets the song speed and tempo (UltraTracker)
|
||||
for p, pat in m.patterns do
|
||||
for row = 0, 63 do
|
||||
for ch = 0, nch - 1 do
|
||||
local q = (row * nch + ch) * 5
|
||||
if buffer.readu8(pat.data, q + 3) == Load.IT.speed and buffer.readu8(pat.data, q + 4) == 0 then
|
||||
buffer.writeu8(pat.data, q + 4, 6)
|
||||
Load.writeEffect(m, p - 1, row, Load.IT.tempo, 125, "next")
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
-- sample data: signed 8 / 16-bit
|
||||
local pos = r.pos
|
||||
for i = 1, nsmp do
|
||||
local s = samples[i]
|
||||
if sizes[i] > 0 then
|
||||
local ok, err = Load.readSample(r.buf, pos, s.length, { bits = s.bits, signed = true, limit = r.limit }, s, budget)
|
||||
if not ok then
|
||||
return nil, err
|
||||
end
|
||||
pos += sizes[i]
|
||||
end
|
||||
end
|
||||
m.meta.source = { format = "ult", version = version }
|
||||
local ok, verr = Tracker.validate(m)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module")
|
||||
end
|
||||
return m, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions)
|
||||
function Ult.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
|
||||
local m, err = Ult.decode(r, opts)
|
||||
if not m then
|
||||
return nil, err
|
||||
end
|
||||
return Tracker.render(m, opts)
|
||||
end
|
||||
|
||||
return Ult
|
||||
@@ -0,0 +1,222 @@
|
||||
--!strict
|
||||
-- music/umx: Unreal music packages (.umx, Unreal / Unreal Tournament / Deus Ex era Unreal Engine 1 packages; package
|
||||
-- versions up to 128). Ported from OpenMPT's UMXTools.cpp / ContainerUMX.cpp (BSD, licenses/openmpt-LICENSE.txt):
|
||||
-- reads the package's name, import and export tables, finds the exports of class "music" and unwraps the module each
|
||||
-- one embeds (IT, S3M, XM or MOD, kept as it is). A format never requires another one, so decode hands the first
|
||||
-- module's bytes to opts.decodeModule (the api passes it: F.load / F.music.load sniff and load the inner module) and
|
||||
-- returns that Module with meta.container = { format = "umx", name, version }; without the hook decode is
|
||||
-- Err.UNSUPPORTED. Umx.extract(r) lists every embedded module without decoding it.
|
||||
-- Not supported: Unreal Engine 2+ packages (sounds, .uax), writing.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Tracker = require("@formats/codecs/audio/Tracker")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Umx = {
|
||||
name = "umx",
|
||||
category = "music",
|
||||
extensions = { "umx" },
|
||||
mime = { "audio/x-umx" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" },
|
||||
caps = { decode = true, encode = false, render = true, container = true },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
decodeModule: ((buf: buffer, format: string?) -> (any, Err.Err?))?, -- loads the inner module (the api passes it)
|
||||
index: number?, -- which music export to load (1-based, default 1)
|
||||
}
|
||||
|
||||
export type Entry = { name: string, data: buffer, format: string? }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local MAGIC = "\xC1\x83\x2A\x9E"
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
type Header = { version: number, nameCount: number, nameOffset: number, exportCount: number, exportOffset: number, importCount: number, importOffset: number }
|
||||
|
||||
local function header(r: Bytes.Reader): Header?
|
||||
if r:size() < 36 or r:peek(4) ~= MAGIC then
|
||||
return nil
|
||||
end
|
||||
local h = r:sub(4, 32)
|
||||
local version = h:u16le()
|
||||
h:skip(6)
|
||||
local hd: Header = {
|
||||
version = version,
|
||||
nameCount = h:u32le(),
|
||||
nameOffset = h:u32le(),
|
||||
exportCount = h:u32le(),
|
||||
exportOffset = h:u32le(),
|
||||
importCount = h:u32le(),
|
||||
importOffset = h:u32le(),
|
||||
}
|
||||
if h.err or hd.nameOffset < 36 or hd.exportOffset < 36 or hd.importOffset < 36 then
|
||||
return nil
|
||||
end
|
||||
if hd.nameCount == 0 or hd.exportCount == 0 or hd.importCount == 0 or hd.nameCount > 2 ^ 20 or hd.exportCount > 2 ^ 20 or hd.importCount > 2 ^ 20 then
|
||||
return nil
|
||||
end
|
||||
return hd
|
||||
end
|
||||
|
||||
-- a compact index: sign and 6 bits, then 7 bits per byte while the continue bits are set
|
||||
local function index(r: Bytes.Reader): number
|
||||
local b = r:u8()
|
||||
local neg = b >= 0x80
|
||||
local v = b % 64
|
||||
if bit32.band(b, 0x40) ~= 0 then
|
||||
local shift = 6
|
||||
repeat
|
||||
b = r:u8()
|
||||
v += (b % 128) * 2 ^ shift
|
||||
shift += 7
|
||||
until b < 0x80 or shift >= 32
|
||||
end
|
||||
return if neg then -v else v
|
||||
end
|
||||
|
||||
-- the name table (lower case)
|
||||
local function names(r: Bytes.Reader, h: Header): { string }
|
||||
local list = {}
|
||||
local nr = r:sub(h.nameOffset)
|
||||
for _ = 1, math.min(h.nameCount, 65536) do
|
||||
if nr:remaining() < 5 then
|
||||
break
|
||||
end
|
||||
if h.version >= 64 then
|
||||
index(nr)
|
||||
end
|
||||
table.insert(list, string.lower(nr:cstring(1024)))
|
||||
nr:skip(4)
|
||||
end
|
||||
return list
|
||||
end
|
||||
|
||||
function Umx.sniff(r: Bytes.Reader): number
|
||||
local h = header(r)
|
||||
if not h then
|
||||
return 0
|
||||
end
|
||||
return if table.find(names(r, h), "music") then 1 else 0.3
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- extract(r) -> { { name, data, format? } } | nil, Err: every module embedded in the package's music exports (format:
|
||||
-- a guess from the inner module's signature: "it", "s3m", "xm", "mod")
|
||||
function Umx.extract(r: Bytes.Reader): ({ Entry }?, Err.Err?)
|
||||
local h = header(r)
|
||||
if not h then
|
||||
return nil, Err.new(if r:size() < 36 then Err.TRUNCATED else Err.CORRUPT, "not an Unreal package")
|
||||
end
|
||||
local nm = names(r, h)
|
||||
-- imports: the class names objects refer to
|
||||
local classes = {}
|
||||
local ir = r:sub(h.importOffset)
|
||||
for _ = 1, math.min(h.importCount, 65536) do
|
||||
if ir:remaining() < 4 then
|
||||
break
|
||||
end
|
||||
index(ir)
|
||||
index(ir)
|
||||
if h.version >= 60 then
|
||||
ir:skip(4)
|
||||
else
|
||||
index(ir)
|
||||
end
|
||||
local obj = index(ir)
|
||||
if obj >= 0 and obj < #nm then
|
||||
table.insert(classes, obj)
|
||||
end
|
||||
end
|
||||
local out: { Entry } = {}
|
||||
local er = r:sub(h.exportOffset)
|
||||
for _ = 1, math.min(h.exportCount, 65536) do
|
||||
if er:remaining() < 8 then
|
||||
break
|
||||
end
|
||||
local cls = -index(er) - 1 -- ~index: the import the class is
|
||||
index(er)
|
||||
if h.version >= 60 then
|
||||
er:skip(4)
|
||||
end
|
||||
local objName = index(er)
|
||||
er:skip(4)
|
||||
local size, offset = index(er), index(er)
|
||||
if er.err then
|
||||
break
|
||||
end
|
||||
if cls >= 0 and cls < #classes and nm[classes[cls + 1] + 1] == "music" and size > 0 and offset > 36 then
|
||||
local c = r:sub(offset, size)
|
||||
if h.version < 40 then
|
||||
c:skip(8)
|
||||
end
|
||||
if h.version < 60 then
|
||||
c:skip(16)
|
||||
end
|
||||
index(c) -- the property list's "none"
|
||||
if h.version >= 120 then
|
||||
index(c)
|
||||
c:skip(8)
|
||||
elseif h.version >= 100 then
|
||||
c:skip(4)
|
||||
index(c)
|
||||
c:skip(4)
|
||||
elseif h.version >= 62 then
|
||||
index(c)
|
||||
c:skip(4)
|
||||
else
|
||||
index(c)
|
||||
end
|
||||
local len = index(c)
|
||||
if not c.err and len > 0 and len <= c:remaining() then
|
||||
local data = c:bytes(len)
|
||||
local sig = Bytes.reader(data)
|
||||
local fmt = if sig:peek(4) == "IMPM" then "it" elseif sig:peek(4, 44) == "SCRM" then "s3m" elseif sig:peek(17) == "Extended Module: " then "xm" elseif buffer.len(data) >= 1084 then "mod" else nil
|
||||
table.insert(out, { name = nm[objName + 1] or "", data = data, format = fmt })
|
||||
end
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
function Umx.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local list, err = Umx.extract(r)
|
||||
if not list then
|
||||
return nil, err
|
||||
end
|
||||
local i = opts and opts.index or 1
|
||||
local e = list[i]
|
||||
if not e then
|
||||
return nil, Err.new(Err.CORRUPT, "no music export" .. (if i > 1 then " " .. i else ""))
|
||||
end
|
||||
local hook = opts and opts.decodeModule
|
||||
if type(hook) ~= "function" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "the embedded " .. (e.format or "tracker") .. " module needs opts.decodeModule (F.load passes it; Umx.extract gives the bytes)")
|
||||
end
|
||||
local m, merr = hook(e.data, nil)
|
||||
if not m then
|
||||
return nil, merr
|
||||
end
|
||||
if type(m) ~= "table" or m.kind ~= "music" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "the embedded module is not a tracker module")
|
||||
end
|
||||
local h = header(r) :: Header
|
||||
m.meta = if type(m.meta) == "table" then m.meta else {}
|
||||
m.meta.container = { format = "umx", name = e.name, version = h.version, count = #list }
|
||||
return m, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts) -> the embedded module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions)
|
||||
function Umx.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
|
||||
local m, err = Umx.decode(r, opts)
|
||||
if not m then
|
||||
return nil, err
|
||||
end
|
||||
return Tracker.render(m, opts)
|
||||
end
|
||||
|
||||
return Umx
|
||||
@@ -5,13 +5,15 @@
|
||||
-- delta samples, multi-sample instruments with volume / panning envelopes, fadeout and auto-vibrato, linear and Amiga
|
||||
-- frequency tables, every FT2 effect and volume-column command. Writes XM from "xm" modules (byte-identical for files
|
||||
-- in FT2's layout) and from "mod" modules (one instrument per sample, Amiga frequencies).
|
||||
-- Not supported: ModPlug ADPCM samples (read as silence), OpenMPT's stereo-sample / extra-effect extensions on write.
|
||||
-- ModPlug ADPCM samples decode (codecs/audio/Adpcm; written back as plain delta PCM). Not supported: OpenMPT's
|
||||
-- stereo-sample / extra-effect extensions on write.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Tracker = require("@formats/codecs/audio/Tracker")
|
||||
local Adpcm = require("@formats/codecs/audio/Adpcm")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Xm = {
|
||||
@@ -19,7 +21,7 @@ local Xm = {
|
||||
category = "music",
|
||||
extensions = { "xm" },
|
||||
mime = { "audio/xm", "audio/x-xm" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Adpcm" },
|
||||
caps = { decode = true, encode = true, render = true, channels = { 1, 64 } },
|
||||
}
|
||||
|
||||
@@ -240,12 +242,19 @@ function Xm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
s.relativeNote = h.rel
|
||||
s.pan = h.pan
|
||||
local frames = h.len // bps
|
||||
if h.res == 0xAD then
|
||||
-- ModPlug ADPCM: 16-byte table + 4 bits per sample (not decoded: silence of the right length)
|
||||
local bytes = 16 + (h.len + 1) // 2
|
||||
r:skip(math.min(bytes, r:remaining()))
|
||||
frames = h.len
|
||||
if h.res == 0xAD and bits == 8 then
|
||||
-- ModPlug ADPCM (codecs/audio/Adpcm): a 16-byte delta table, then 4 bits per sample; a cut file keeps
|
||||
-- the samples whose nibbles are present
|
||||
frames = math.max(0, math.min(h.len, (r:remaining() - 16) * 2))
|
||||
total += frames * 4
|
||||
if total > maxBytes then
|
||||
return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit")
|
||||
end
|
||||
s.data = buffer.create(frames * 4)
|
||||
if frames > 0 then
|
||||
Adpcm.modplug(r.buf, r.pos, frames, s.data, 0)
|
||||
end
|
||||
r:skip(math.min(16 + (h.len + 1) // 2, r:remaining()))
|
||||
else
|
||||
local avail = r:remaining() // bps
|
||||
local got = math.min(frames, avail)
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
--!strict
|
||||
-- music/xmi: Miles Sound System XMIDI (IFF: an optional FORM XDIR with the song count, then CAT XMID of FORM XMID songs,
|
||||
-- or one FORM XMID; each with TIMB / RBRN chunks and the EVNT event stream). Written from the XMIDI format description
|
||||
-- (Miles AIL; Ryan Nunn's notes); wildmidi was used only as a reference converter in tests. Decodes one song (opts.track,
|
||||
-- 1-based, default 1) to a Types.Midi (format 0): interval bytes (< 0x80, summed) become absolute ticks, each note-on's
|
||||
-- duration becomes a note-off (velocity 64; notes still sounding at the end-of-track event end there), tempo events are dropped: XMIDI plays at a fixed 120 ticks per second
|
||||
-- (division 60 at 500000 us per quarter). meta.source: songs, song, timbres ({ patch, bank } from TIMB), tempo (the
|
||||
-- first tempo event's value, unused). Renders through codecs/audio/MidiRender.
|
||||
-- Not supported: writing; the RBRN branch table (kept as meta.source.branches = count); MT-32 -> GM program mapping.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Chunks = require("@formats/containers/Chunks")
|
||||
local Render = require("@formats/codecs/audio/MidiRender")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Xmi = {
|
||||
name = "xmi",
|
||||
category = "music",
|
||||
extensions = { "xmi", "xmidi" },
|
||||
mime = { "audio/x-xmidi" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/audio/MidiRender" },
|
||||
caps = { decode = true, encode = false, render = true, songs = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
track: number?, -- the song (1-based), default 1
|
||||
maxEvents: number?, -- default 2^24
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Xmi.sniff(r: Bytes.Reader): number
|
||||
local id, kind = r:peek(4), r:peek(4, 8)
|
||||
if id == "FORM" and (kind == "XDIR" or kind == "XMID") then
|
||||
return 1
|
||||
end
|
||||
return if id == "CAT " and kind == "XMID" then 0.9 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local readu8 = buffer.readu8
|
||||
local DATA = { [8] = 2, [9] = 2, [10] = 2, [11] = 2, [12] = 1, [13] = 1, [14] = 2 }
|
||||
local TYPES = { [8] = "noteOff", [9] = "noteOn", [10] = "aftertouch", [11] = "controller", [12] = "program", [13] = "channelPressure", [14] = "pitchBend" }
|
||||
|
||||
-- a MIDI variable-length number at p -> value, next p (nil past e)
|
||||
local function vlq(b: buffer, p: number, e: number): (number?, number)
|
||||
local v = 0
|
||||
for _ = 1, 4 do
|
||||
if p >= e then
|
||||
return nil, p
|
||||
end
|
||||
local c = readu8(b, p)
|
||||
p += 1
|
||||
v = v * 128 + c % 128
|
||||
if c < 128 then
|
||||
return v, p
|
||||
end
|
||||
end
|
||||
return nil, p
|
||||
end
|
||||
|
||||
local function bytes(b: buffer, p: number, n: number): { number }
|
||||
local t: { number } = table.create(n) :: { number }
|
||||
for i = 1, n do
|
||||
t[i] = readu8(b, p + i - 1)
|
||||
end
|
||||
return t
|
||||
end
|
||||
|
||||
-- the EVNT stream [p, e) -> events (note-offs merged in), end tick, first tempo | nil, message
|
||||
local function events(b: buffer, p: number, e: number, maxEvents: number): ({ Types.MidiEvent }?, any, number?)
|
||||
local list: { Types.MidiEvent }, offs: { Render.PendingOff } = {}, {}
|
||||
local tick, tempo = 0, nil
|
||||
while p < e do
|
||||
local st = readu8(b, p)
|
||||
p += 1
|
||||
if st < 0x80 then
|
||||
tick += st
|
||||
elseif st == 0xFF then
|
||||
if p >= e then
|
||||
return nil, "truncated meta event"
|
||||
end
|
||||
local kind = readu8(b, p)
|
||||
local n, q = vlq(b, p + 1, e)
|
||||
if not n or q + n > e then
|
||||
return nil, "truncated meta event"
|
||||
end
|
||||
if kind == 0x2F then
|
||||
break
|
||||
elseif kind == 0x51 and n >= 3 then
|
||||
tempo = tempo or readu8(b, q) * 65536 + readu8(b, q + 1) * 256 + readu8(b, q + 2)
|
||||
else
|
||||
table.insert(list, { tick = tick, type = "meta", meta = kind, data = bytes(b, q, n) })
|
||||
end
|
||||
p = q + n
|
||||
elseif st == 0xF0 or st == 0xF7 then
|
||||
local n, q = vlq(b, p, e)
|
||||
if not n or q + n > e then
|
||||
return nil, "truncated sysex"
|
||||
end
|
||||
table.insert(list, { tick = tick, type = if st == 0xF0 then "sysex" else "escape", data = bytes(b, q, n) })
|
||||
p = q + n
|
||||
elseif st < 0xF0 then
|
||||
local hi, ch = st // 16, st % 16
|
||||
local n = DATA[hi]
|
||||
if p + n > e then
|
||||
return nil, "truncated event"
|
||||
end
|
||||
local d = bytes(b, p, n)
|
||||
p += n
|
||||
table.insert(list, { tick = tick, type = TYPES[hi], channel = ch, data = d })
|
||||
if hi == 9 then
|
||||
local dur, q = vlq(b, p, e)
|
||||
if not dur then
|
||||
return nil, "truncated note duration"
|
||||
end
|
||||
p = q
|
||||
table.insert(offs, { tick = tick + dur, onTick = tick, ev = { tick = tick + dur, type = "noteOff", channel = ch, data = { d[1] % 128, 64 } } })
|
||||
end
|
||||
else
|
||||
return nil, string.format("unexpected status byte 0x%02X", st)
|
||||
end
|
||||
if #list + #offs > maxEvents then
|
||||
return nil, "limit: more than " .. maxEvents .. " events"
|
||||
end
|
||||
end
|
||||
-- the sequence stops at its end-of-track event: notes still sounding end there (wildmidi leaves them hanging)
|
||||
for _, o in offs do
|
||||
if o.tick > tick then
|
||||
o.tick = tick
|
||||
o.ev.tick = tick
|
||||
end
|
||||
end
|
||||
return Render.merge(list, offs), tick, tempo
|
||||
end
|
||||
|
||||
-- the songs: { { evnt = Chunk, timb = Chunk? } } from the IFF tree
|
||||
local function songs(b: buffer, base: number, limit: number): { { [string]: Chunks.Chunk } }
|
||||
local out = {}
|
||||
local function form(c: Chunks.Chunk)
|
||||
local song = {}
|
||||
for _, s in Chunks.walk(b, c.offset + 4, c.offset + c.avail, Chunks.IFF) do
|
||||
song[s.id] = song[s.id] or s
|
||||
end
|
||||
if song.EVNT then
|
||||
table.insert(out, song)
|
||||
end
|
||||
end
|
||||
for _, c in Chunks.walk(b, base, limit, Chunks.IFF) do
|
||||
local kind = if c.avail >= 4 then buffer.readstring(b, c.offset, 4) else ""
|
||||
if c.id == "FORM" and kind == "XMID" then
|
||||
form(c)
|
||||
elseif c.id == "CAT " and kind == "XMID" then
|
||||
for _, s in Chunks.walk(b, c.offset + 4, c.offset + c.avail, Chunks.IFF) do
|
||||
if s.id == "FORM" and s.avail >= 4 and buffer.readstring(b, s.offset, 4) == "XMID" then
|
||||
form(s)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
function Xmi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
if Xmi.sniff(r) == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "not an XMIDI file")
|
||||
end
|
||||
local list = songs(r.buf, r.base, r.limit)
|
||||
local index = o.track or 1
|
||||
if #list == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "no XMID song with an EVNT chunk")
|
||||
elseif type(index) ~= "number" or index < 1 or index > #list or index % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, string.format("track must be 1..%d", #list))
|
||||
end
|
||||
local song = list[index]
|
||||
local ev = song.EVNT
|
||||
local evs, endTick, tempo = events(r.buf, ev.offset, ev.offset + ev.avail, o.maxEvents or 2 ^ 24)
|
||||
if not evs then
|
||||
return nil, Err.from(endTick :: string, ev.offset)
|
||||
end
|
||||
local last = math.max(endTick :: number, if #evs > 0 then evs[#evs].tick else 0)
|
||||
table.insert(evs, 1, { tick = 0, type = "meta", meta = 0x51, data = Render.tempoBytes(60, 120) })
|
||||
table.insert(evs, { tick = last, type = "meta", meta = 0x2F, data = {} })
|
||||
local timbres = {}
|
||||
local tb = song.TIMB
|
||||
if tb and tb.avail >= 2 then
|
||||
for i = 0, math.min(buffer.readu16(r.buf, tb.offset), (tb.avail - 2) // 2) - 1 do
|
||||
table.insert(timbres, { patch = readu8(r.buf, tb.offset + 2 + i * 2), bank = readu8(r.buf, tb.offset + 3 + i * 2) })
|
||||
end
|
||||
end
|
||||
local rb = song.RBRN
|
||||
local branches = if rb and rb.avail >= 2 then buffer.readu16(r.buf, rb.offset) else 0
|
||||
local midi = Types.Midi.new(60)
|
||||
midi.format = 0
|
||||
midi.tracks = { { events = evs } }
|
||||
Render.attach(midi, { format = "xmi", songs = #list, song = index, timbres = timbres, tempo = tempo, branches = branches })
|
||||
midi.meta.truncated = ev.truncated
|
||||
return midi, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + MidiRender.RenderOptions)
|
||||
function Xmi.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
|
||||
local midi, err = Xmi.decode(r, opts)
|
||||
if not midi then
|
||||
return nil, err
|
||||
end
|
||||
return Render.decoder(midi, opts)
|
||||
end
|
||||
|
||||
return Xmi
|
||||
@@ -27,7 +27,8 @@ local function bad(what: string): (nil, Err.Err)
|
||||
end
|
||||
|
||||
local function isModule(m: any): boolean
|
||||
return type(m) == "table" and m.kind == "music" and FORMATS[m.format] == true and type(m.patterns) == "table"
|
||||
-- (the engine family: modules of the other tracker formats, music/mtm etc., play as one of the four)
|
||||
return type(m) == "table" and m.kind == "music" and FORMATS[Tracker.family(m) or ""] == true and type(m.patterns) == "table"
|
||||
end
|
||||
|
||||
local function int(v: any, lo: number, hi: number): boolean
|
||||
@@ -243,7 +244,7 @@ function MusicOps.addSample(m: any, spec: SampleSpec): (number?, Err.Err?)
|
||||
local copy = buffer.create(length * channels * 4)
|
||||
buffer.copy(copy, 0, data, 0, length * channels * 4)
|
||||
s.data, s.length, s.channels = copy, length, channels
|
||||
s.bits = spec.bits or (if m.format == "mod" then 8 else 16)
|
||||
s.bits = spec.bits or (if Tracker.family(m) == "mod" then 8 else 16)
|
||||
if s.bits ~= 8 and s.bits ~= 16 then
|
||||
return bad("addSample: bits must be 8 or 16")
|
||||
end
|
||||
@@ -298,7 +299,7 @@ function MusicOps.addInstrument(m: any, spec: InstrumentSpec): (number?, Err.Err
|
||||
if not isModule(m) then
|
||||
return bad("addInstrument: needs a tracker Module")
|
||||
end
|
||||
if m.format ~= "xm" and m.format ~= "it" then
|
||||
if Tracker.family(m) ~= "xm" and Tracker.family(m) ~= "it" then
|
||||
return bad("addInstrument: only xm and it modules have instruments (mod / s3m cells name samples)")
|
||||
end
|
||||
if type(spec) ~= "table" then
|
||||
|
||||
Reference in new issue
Block a user