ws-audio2: merge ws/audio2-chip (AHX/HVL, MUS, XMI, HMP/HMI, kar lyrics)

This commit is contained in:
4DBug committed 2026-10-31 14:42:39 -05:00
commit e779ce6e29
35 files changed
+4017 -45

No files matched your search

+7
View File
@@ -73,12 +73,17 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| subtitle | ass | .ass .ssa | yes | yes | styles: true | `tests/subtitle/ass.luau` |
| subtitle | srt | .srt | yes | yes | styles: false | `tests/subtitle/srt.luau` |
| subtitle | vtt | .vtt .webvtt | yes | yes | styles: true | `tests/subtitle/vtt.luau` |
| music | ahx | .ahx .thx | yes | - | render: true, channels: 4, 4, subsongs: true | `tests/music/ahx.luau` |
| music | hmp | .hmp .hmi | yes | - | render: true, hmi: true | `tests/music/hmp.luau` |
| music | hvl | .hvl | yes | - | render: true, channels: 4, 16, subsongs: true | `tests/music/hvl.luau` |
| music | it | .it | yes | - | render: true, channels: 1, 64, compressedSamples: true | `tests/music/it.luau` |
| music | midi | .mid .midi .smf .kar .rmi | yes | yes | formats: 0, 1, 2, render: true, streaming: true, rmid: true | `tests/music/midi.luau` |
| music | mod | .mod .m15 .stk .nst | yes | yes | render: true, channels: 1, 32 | `tests/music/mod.luau` |
| music | mus | .mus | yes | - | render: true | `tests/music/mus.luau` |
| music | s3m | .s3m | yes | - | render: true, channels: 1, 32 | `tests/music/s3m.luau` |
| music | sf2 | .sf2 | yes | - | sm24: true, sf3: false | `tests/music/sf2.luau` |
| music | xm | .xm | yes | yes | render: true, channels: 1, 64 | `tests/music/xm.luau` |
| music | xmi | .xmi .xmidi | yes | - | render: true, songs: true | `tests/music/xmi.luau` |
| playlist | m3u | .m3u .m3u8 | yes | yes | hls: true | `tests/playlist/m3u.luau` |
| playlist | pls | .pls | yes | yes | | `tests/playlist/pls.luau` |
| playlist | xspf | .xspf | yes | yes | | `tests/playlist/xspf.luau` |
@@ -89,7 +94,9 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain:
- codecs/audio/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program
- codecs/audio/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1).
- codecs/audio/Flac: FLAC frames without the container: frame header parsing, subframe decoding (constant, verbatim,
- codecs/audio/Hively: the AHX / HivelyTracker engine behind music/ahx and music/hvl: the loader for both file formats
- codecs/audio/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point
- codecs/audio/MidiRender: the tempo map (ticks -> seconds, as python mido computes lengths), the time-ordered event list,
- codecs/audio/Mpa: MPEG audio layers I / II / III (ISO/IEC 11172-3, 13818-3, MPEG-2.5) without the file around it:
- codecs/audio/Opus: the Opus codec (RFC 6716) without its container: TOC / packet framing (Packet), the SILK and CELT
- codecs/audio/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources.
+56
View File
@@ -312,9 +312,65 @@ assert(F.music.load(assert(F.save(xm))).instruments[1].name == "lead")
| s3m, it | yes | - | Module |
| midi (.mid, .kar, RMID) | yes | yes (SMF) | Midi |
| sf2 | yes | - | SoundFont |
| ahx (AHX / THX), hvl (HivelyTracker) | yes | - | Module (own synth engine) |
| mus (Doom), xmi (Miles XMIDI), hmp (HMP, HMI) | yes | - (save as midi) | Midi |
See [FORMATS.md](../FORMATS.md) for each format's capabilities.
### AHX / HVL and MIDI variants
AHX and HivelyTracker modules carry no samples: their instruments are small synth programs (waveforms, filter and
pulse-width sweeps, a performance list). They load as a Module-shaped value (`format` `"ahx"` / `"hvl"`; `patterns` are
the tracks, 6 bytes per row: note, instrument, effect, parameter, second effect, parameter; `positions` hold each
channel's track and transpose; `subsongs`) and render through their own replayer, a port of HivelyTracker's, which gives
hvl2wav's samples exactly. Render options: `sampleRate`, `subsong` (0 = the main song), `loop`, `maxDuration` (default
600 s) and, for AHX, `stereo` 0..4 (0 mono as hvl2wav renders by default, 4 the Amiga's hard L R R L panning); HVL files
store their own panning and gain.
```luau
local song = assert(F.music.load(ahxBytes))
assert(song.format == "ahx" and song.channels == 4 and song.title == "demo")
local dec = song:render({ stereo = 4 }) -- a Decoder, stereo f32 at 44100 Hz
assert(dec.channels == 2 and dec.duration > 1)
local hvl = assert(F.music.load(hvlBytes))
assert(hvl.format == "hvl" and hvl.channels == 6 and #hvl.subsongs == 1)
local intro = hvl:render({ subsong = 1, sampleRate = 22050 })
local wav = assert(F.save(intro, nil, { format = "wav" }))
assert(F.detect(wav) == "wav" and F.detect(hvlBytes) == "hvl")
```
Doom MUS, Miles XMIDI and HMI's HMP / HMI files load as a **Midi**, so they play through the SoundFont synth and save
as a Standard MIDI File. MUS runs at 140 ticks per second (`rate` option), XMIDI at a fixed 120 (note durations become
note-offs; `track` picks the song of a multi-song file, `meta.source.songs` counts them), HMP / HMI at the rate in
their header.
```luau
local doom = assert(F.music.load(musBytes))
assert(doom.kind == "midi" and doom.meta.source.format == "mus")
local audio = assert(F.ops.audio.toAudio(doom:render({ soundfont = sf2Bytes, tail = 0.2 })))
assert(audio.channels == 2)
local xmi = assert(F.music.load(xmiBytes, { track = 2 })) -- the second song
assert(xmi.meta.source.songs == 2 and xmi.meta.source.song == 2)
local smf = assert(F.save(xmi, nil, { format = "midi" })) -- as a .mid
assert(F.detect(smf) == "midi")
local hmp = assert(F.music.load(hmpBytes))
assert(hmp.meta.source.format == "hmp" and #hmp.tracks == 3)
```
Karaoke `.kar` files are MIDI files with the lyrics in text events: `meta.lyrics` lists them with their time
(`{ time, tick, text }`; a leading `\` starts a new paragraph, `/` a new line), the `@` headers land in
`meta.karaoke` (`T` = title lines, `L` language, `I` info, ...) and `meta.tags`.
```luau
local kar = assert(F.music.load(karBytes))
assert(kar.meta.tags.title == "Little Song" and kar.meta.tags.artist == "The Docs")
local line = {}
for _, l in kar.meta.lyrics do
table.insert(line, l.text)
end
assert(table.concat(line) == "\\Hello /karaoke" and kar.meta.lyrics[2].time == 0.5)
```
## Gotchas
- Saving music to an audio format renders it with the options in `opts`: `F.save(song, nil, { format = "wav",
+1
View File
@@ -38,6 +38,7 @@
| `tests/fixtures/vp8video/vp80-*.ivf` | the VP8 test vectors of the libvpx test data (vp80-00-comprehensive-001..018 and others) | WebM Project, BSD-3-Clause + patent grant: [libvpx-LICENSE.txt](libvpx-LICENSE.txt) |
| `src/Formats/codecs/H264/` (Tables: CAVLC / CABAC / deblocking / scaling constant tables of ITU-T H.264, extracted from openh264 sources; the decoder itself is written from the spec) | openh264 2.x (Cisco) | BSD-2-Clause: [openh264-LICENSE.txt](openh264-LICENSE.txt) |
| `tests/gen/h264_jvt` (downloaded at fixture time, not committed) | ITU-T H.264.1 / JVT conformance bitstreams (itu.int) | ITU-T test data |
| `src/Formats/codecs/audio/Hively/` (Tables, Load, Player: the AHX / HVL loaders, waveform generator and replayer) | port of HivelyTracker hvl2wav replay.c 1.9 by Pete Gordon (Xeron/IRIS); `tests/gen/ahx_cases` / `hvl_cases` also embed songs from its Songs/ directory (fixture time, not committed) | BSD-3-Clause: [hivelytracker-LICENSE.txt](hivelytracker-LICENSE.txt) |
Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this
folder (see docs/STYLE.md, "Absorbing an existing repo").
+29
View File
@@ -0,0 +1,29 @@
BSD 3-Clause License
Copyright (c) 2006-2018, Pete Gordon
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+61 -1
View File
@@ -830,6 +830,42 @@ local list: { Entry } = {
return require("@formats/subtitle/vtt")
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 = "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",
@@ -848,7 +884,7 @@ local list: { Entry } = {
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")
@@ -866,6 +902,18 @@ local list: { Entry } = {
return require("@formats/music/mod")
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 = "s3m",
category = "music",
@@ -902,6 +950,18 @@ local list: { Entry } = {
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",
+1 -1
View File
@@ -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 },
+249
View File
@@ -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
+970
View File
@@ -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
+221
View File
@@ -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
+209
View File
@@ -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
+10 -1
View File
@@ -479,8 +479,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
@@ -489,6 +491,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.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)
+53
View File
@@ -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
+273
View File
@@ -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
+53
View File
@@ -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
+58 -40
View File
@@ -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
+163
View File
@@ -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
+215
View File
@@ -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
+45
View File
@@ -0,0 +1,45 @@
-- tests/music/_hively: shared helper of the AHX / HVL tests (not a test itself): renders a fixture case through the
-- format and compares it with hvl2wav's output exactly (16-bit samples: CRC-32 of the whole stream, the first
-- differing frame located inside the raw head kept by tools/fixtures/ahx.py / hvl.py).
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local H = {}
-- check(t, Format, c): decode + render + exact comparison; returns the song
function H.check(t: any, Format: any, c: any): any
local song, err = Format.decode(Bytes.reader(buffer.fromstring(c.data)))
t:check(song, c.name .. ": " .. tostring(err))
if not song then
return nil
end
t:check(Format.sniff(Bytes.reader(buffer.fromstring(c.data))) == 1, c.name .. ": sniff")
local dec = song:render({ sampleRate = c.sampleRate, stereo = c.stereo, subsong = c.subsong, maxDuration = c.maxDuration })
t:check(dec.err == nil, c.name .. ": render " .. tostring(dec.err))
local frames = if c.prefix then math.min(dec.frames, c.frames) else dec.frames
if not c.prefix then
t:eq(dec.frames, c.frames, c.name .. ": frames (song end as hvl2wav finds it)")
end
local f32 = dec:read(frames)
local s16 = buffer.create(frames * 4)
for i = 0, frames * 2 - 1 do
buffer.writei16(s16, i * 2, math.floor(buffer.readf32(f32, i * 4) * 32768 + 0.5))
end
-- (a time-limited reference whose song ends earlier than the limit: only the head can be compared)
local exact = (frames == c.frames and Crc32.of(s16) == c.crc) or (c.prefix and frames < c.frames)
local head = buffer.fromstring(c.head)
local firstDiff = -1
for i = 0, math.min(frames, buffer.len(head) // 4) * 2 - 1 do
if buffer.readi16(s16, i * 2) ~= buffer.readi16(head, i * 2) then
firstDiff = i // 2
break
end
end
t:check(firstDiff < 0, string.format("%s: first differing frame %d (ours %d, hvl2wav %d)", c.name, firstDiff,
if firstDiff >= 0 then buffer.readi16(s16, firstDiff * 4) else 0, if firstDiff >= 0 then buffer.readi16(head, firstDiff * 4) else 0))
t:check(exact, c.name .. ": samples equal hvl2wav's (CRC-32 of " .. frames .. " frames)")
t:note("%-22s %6d frames %s", c.name, frames, if exact and firstDiff < 0 then "bit-exact vs hvl2wav" else "DIFFERS")
return song
end
return H
+92
View File
@@ -0,0 +1,92 @@
-- tests/music/_midivar: shared helper of the MUS / XMI / HMP tests (not a test itself): compares a decoded Midi's
-- channel events (codecs/audio/MidiRender.timeline: play order, seconds) with wildmidi -x's conversion
-- (tools/fixtures/_midivar.py): notes on / off, program changes, pitch bends (MSB) and controllers, matched per
-- (kind, channel, data) in time order, times within 0.1 ms + 1e-5 relative.
local Render = require("@formats/codecs/audio/MidiRender")
local M = {}
local function kindOf(status: number, d1: number, d2: number): string?
local hi = status // 16
if hi == 9 and d2 > 0 then
return "on"
elseif hi == 8 or hi == 9 then
return "off"
elseif hi == 12 then
return "program"
elseif hi == 14 then
return "bend"
elseif hi == 11 then
return "cc"
end
return nil
end
-- the comparable events of a list of { seconds, status, d1, d2 }: key -> { seconds }
local function index(list: { { number } }, opts: any): ({ [string]: { number } }, { [string]: number })
local by: { [string]: { number } }, counts: { [string]: number } = {}, {}
for _, e in list do
local k = kindOf(e[2], e[3], e[4])
if k and not (opts.skip and opts.skip[k]) then
local d = if k == "bend" then e[4] elseif k == "cc" then e[3] * 256 + e[4] else e[3]
local key = string.format("%s %d %d", k, e[2] % 16, d)
by[key] = by[key] or {}
table.insert(by[key], e[1])
counts[k] = (counts[k] or 0) + 1
end
end
return by, counts
end
-- compare(t, midi, ref, label, opts?) -> worst time difference (s). opts.skip = { cc = true, ... }
function M.compare(t: any, midi: any, ref: any, label: string, opts: any?): number
local o = opts or {}
local tl = Render.timeline(midi)
local ours = {}
local refEnd = 0
for _, e in ref.events do
refEnd = math.max(refEnd, e[1])
end
for i = 1, #tl.time do
-- o.hangingOffs: wildmidi drops the note-offs past the end of the song (we end those notes at the end)
local hanging = o.hangingOffs and kindOf(tl.status[i], tl.d1[i], tl.d2[i]) == "off" and tl.time[i] > refEnd + 1e-6
if not hanging then
table.insert(ours, { tl.time[i], tl.status[i], tl.d1[i], tl.d2[i] })
end
end
local a, ca = index(ours, o)
local b, cb = index(ref.events, o)
for _, k in { "on", "off", "program", "bend", "cc" } do
if not (o.skip and o.skip[k]) then
t:eq(ca[k] or 0, cb[k] or 0, label .. ": " .. k .. " events")
end
end
local worst, bad = 0, 0
for key, times in b do
local mine = a[key] or {}
table.sort(times)
table.sort(mine)
if #mine ~= #times then
bad += 1
if bad <= 3 then
t:check(false, string.format("%s: %s: %d events, wildmidi %d", label, key, #mine, #times))
end
else
for i, tm in times do
local d = math.abs(mine[i] - tm)
worst = math.max(worst, d)
if d > 1e-4 + 1e-5 * tm then
bad += 1
if bad <= 3 then
t:check(false, string.format("%s: %s at %.4f s, wildmidi %.4f s", label, key, mine[i], tm))
end
end
end
end
end
t:check(bad == 0, label .. ": event times match wildmidi's")
t:note("%-12s %4d notes, worst time difference %.2g s", label, ca.on or 0, worst)
return worst
end
return M
+79
View File
@@ -0,0 +1,79 @@
-- music/ahx tests: AHX songs written by tools/fixtures/_hively.py (every waveform, filter and square sweeps, PList
-- commands, effects, subsongs, AHX versions 0..2) and karma.ahx from the HivelyTracker source, rendered through
-- codecs/audio/Hively and compared sample for sample with hvl2wav at several stereo separations and rates; the Module
-- shape, bad input, and the fuzz no-throw pass. Fixtures: tools/fixtures/ahx.py.
local T = require("@tests/T")
local H = require("@tests/music/_hively")
local Ahx = require("@formats/music/ahx")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Cases = require("@tests/gen/ahx_cases")
local t = T.suite("ahx")
t:eq(Ahx.name, "ahx", "name")
t:eq(Ahx.category, "music", "category")
t:check(Ahx.caps.decode and not Ahx.caps.encode, "caps")
t:eq(Ahx.sniff(Bytes.reader(buffer.fromstring("HVL\1"))), 0, "sniff HVL")
local samples = {}
for _, c in Cases do
local song = H.check(t, Ahx, c)
if song and c.name == "demo" then
t:eq(song.kind, "music", "kind")
t:eq(song.format, "ahx", "format")
t:eq(song.title, "demo", "title")
t:eq(song.channels, 4, "channels")
t:eq(#song.order, 2, "positions")
t:eq(song.instruments[1].name, "tri", "instrument name")
t:eq(#song.instruments[3].plist.entries, 4, "play list")
t:eq(song.patterns[2].rows, 16, "track rows")
t:eq(buffer.readu8(song.patterns[2].data, 0), 25, "track 1 row 0 note")
t:eq(#song.subsongs, 1, "subsongs")
-- seek back and read again: the same samples
local dec = song:render()
local a = dec:read(4410)
dec:seek(0.5)
dec:seek(0)
local b = dec:read(4410)
t:check(buffer.tostring(a) == buffer.tostring(b), "seek restarts exactly")
end
if #samples < 4 then
table.insert(samples, buffer.fromstring(c.data))
end
end
-- bad input
local function code(s: string): string?
local _, e = Ahx.decode(Bytes.reader(buffer.fromstring(s)))
return e and e.code
end
t:eq(code("THX"), Err.TRUNCATED, "short header")
t:eq(code("THX\1\0\14\0\0\0\0\16\0\0\0"), Err.CORRUPT, "no positions")
t:eq(code(string.sub(Cases[1].data, 1, 60)), Err.TRUNCATED, "truncated")
local song = assert(Ahx.decode(Bytes.reader(buffer.fromstring(Cases[1].data))))
t:check(song:render({ subsong = 9 }).err ~= nil, "subsong out of range")
-- through the api: a Module saved as audio renders through its own engine
do
local F = require("@formats")
local wav, err = F.save(song, nil, { format = "wav", sampleRate = 22050 })
t:check(wav, "F.save as wav: " .. tostring(err))
t:eq(F.detect(wav :: buffer), "wav", "F.save as wav")
t:eq(F.detect(buffer.fromstring(Cases[1].data)), "ahx", "F.detect")
local _, e2 = F.save(song, nil, { format = "wav", subsong = 7 })
t:check(e2 ~= nil, "F.save: a failed render is an error")
end
t:fuzz("decode", function(b: buffer)
return Ahx.decode(Bytes.reader(b))
end, samples)
t:fuzz("decode + render", function(b: buffer)
local s = Ahx.decode(Bytes.reader(b))
if s then
local d = s:render({ sampleRate = 8000, maxDuration = 0.5 })
d:read(4000)
end
return s
end, samples, { mutations = 150, garbage = 20 })
t:done()
+57
View File
@@ -0,0 +1,57 @@
-- music/hmp tests: HMP (old and "013195" headers, several tick rates) and HMI files (tools/fixtures/hmp.py) decoded and
-- compared with wildmidi -x's conversion (notes, HMI note durations, programs, bends, controllers), the FE / loop
-- events skipped, a render, bad input, and the fuzz no-throw pass.
local T = require("@tests/T")
local V = require("@tests/music/_midivar")
local Hmp = require("@formats/music/hmp")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Cases = require("@tests/gen/hmp_cases")
local t = T.suite("hmp")
local function decode(s: string, opts: any?): (any, any)
return Hmp.decode(Bytes.reader(buffer.fromstring(s)), opts)
end
t:eq(Hmp.name, "hmp", "name")
t:check(Hmp.caps.decode and not Hmp.caps.encode, "caps")
t:eq(Hmp.sniff(Bytes.reader(buffer.fromstring("HMIMIDIP013195"))), 1, "sniff HMP")
t:eq(Hmp.sniff(Bytes.reader(buffer.fromstring("HMI-MIDISONG061595"))), 1, "sniff HMI")
t:eq(Hmp.sniff(Bytes.reader(buffer.fromstring("HMI-MIDITRACK"))), 0, "sniff other")
local samples = {}
for _, c in Cases do
local m, err = decode(c.data)
t:check(m, c.name .. ": " .. tostring(err))
if m then
t:eq(m.meta.source.format, c.kind, c.name .. ": kind")
t:eq(m.meta.source.rate, c.rate, c.name .. ": tick rate")
V.compare(t, m, c.ref, c.name)
end
table.insert(samples, buffer.fromstring(c.data))
end
do
local m = assert(decode(Cases[1].data))
local dec = m:render({ sampleRate = 22050, tail = 0.2 })
t:check(math.abs(dec.duration - (m.meta.length + 0.2)) < 0.01, "render duration")
end
local _, e1 = decode("HMIMIDIP")
t:eq(e1 and e1.code, Err.TRUNCATED, "short header")
local bad = string.sub(Cases[1].data, 1, 0x308 + 20)
local _, e2 = decode(bad)
t:eq(e2 and e2.code, Err.TRUNCATED, "truncated chunk")
t:fuzz("decode", function(b: buffer)
return Hmp.decode(Bytes.reader(b))
end, samples)
t:fuzz("decode + render", function(b: buffer)
local m = Hmp.decode(Bytes.reader(b))
if m and m.meta.length < 30 then
m:render({ sampleRate = 8000 }):read(2000)
end
return m
end, samples, { mutations = 60, garbage = 10 })
t:done()
+71
View File
@@ -0,0 +1,71 @@
-- music/hvl tests: HVL songs written by tools/fixtures/_hively.py (4..8 channels, two effect columns, ring modulation,
-- panning, mix gain / stereo from the file, subsongs) and songs from the HivelyTracker source, rendered through
-- codecs/audio/Hively and compared sample for sample with hvl2wav (44.1 and 48 kHz); the Module shape, bad input, and
-- the fuzz no-throw pass. Fixtures: tools/fixtures/hvl.py.
local T = require("@tests/T")
local H = require("@tests/music/_hively")
local Hvl = require("@formats/music/hvl")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Cases = require("@tests/gen/hvl_cases")
local t = T.suite("hvl")
t:eq(Hvl.name, "hvl", "name")
t:eq(Hvl.category, "music", "category")
t:check(Hvl.caps.decode and not Hvl.caps.encode, "caps")
t:eq(Hvl.sniff(Bytes.reader(buffer.fromstring("THX\1"))), 0, "sniff AHX")
local samples = {}
for _, c in Cases do
local song = H.check(t, Hvl, c)
if song and c.name == "demo" then
t:eq(song.kind, "music", "kind")
t:eq(song.format, "hvl", "format")
t:eq(song.title, "demo", "title")
t:eq(song.channels, 6, "channels")
t:eq(song.meta.source.stereo, 3, "stereo")
t:eq(#song.instruments, 6, "instruments")
t:eq(#song.order, 2, "positions")
t:eq(song.instruments[1].name, "tri", "instrument name")
t:eq(#song.instruments[3].plist.entries, 4, "play list")
t:eq(song.patterns[2].rows, 16, "track rows")
t:eq(buffer.readu8(song.patterns[2].data, 0), 25, "track 1 row 0 note")
t:eq(#song.subsongs, 1, "subsongs")
-- seek back and read again: the same samples
local dec = song:render()
local a = dec:read(4410)
dec:seek(0.5)
dec:seek(0)
local b = dec:read(4410)
t:check(buffer.tostring(a) == buffer.tostring(b), "seek restarts exactly")
end
if #samples < 4 then
table.insert(samples, buffer.fromstring(c.data))
end
end
-- bad input
local function code(s: string): string?
local _, e = Hvl.decode(Bytes.reader(buffer.fromstring(s)))
return e and e.code
end
t:eq(code("HVL\1\0\16\0\1\0"), Err.TRUNCATED, "short header")
t:eq(code("HVL\1\0\16\0\0\0\0\16\0\0\0\100\2"), Err.CORRUPT, "no positions")
t:eq(code("HVL\1\0\16\0\1\255\0\16\0\0\0\100\2"), Err.UNSUPPORTED, "67 channels")
t:eq(code(string.sub(Cases[1].data, 1, 60)), Err.TRUNCATED, "truncated")
local song = assert(Hvl.decode(Bytes.reader(buffer.fromstring(Cases[1].data))))
t:check(song:render({ subsong = 9 }).err ~= nil, "subsong out of range")
t:fuzz("decode", function(b: buffer)
return Hvl.decode(Bytes.reader(b))
end, samples)
t:fuzz("decode + render", function(b: buffer)
local s = Hvl.decode(Bytes.reader(b))
if s then
local d = s:render({ sampleRate = 8000, maxDuration = 0.5 })
d:read(4000)
end
return s
end, samples, { mutations = 150, garbage = 20 })
t:done()
+34
View File
@@ -271,6 +271,40 @@ for _, c in Cases do
table.insert(samples, c.data)
end
end
-- .kar karaoke: the "Words" track's text events (FF 01) with @ headers, plus FF 05 lyrics, timed through the tempo map
do
local function txt(tick: number, meta: number, s: string): any
return { tick = tick, type = "meta", meta = meta, data = { string.byte(s, 1, -1) } }
end
local k = Types.Midi.new(96)
table.insert(k.tracks, { events = {
{ tick = 0, type = "meta", meta = 0x51, data = { 0x0F, 0x42, 0x40 } }, -- 1 s per quarter
txt(0, 1, "Copyright notice, not a lyric"),
{ tick = 192, type = "noteOn", channel = 0, data = { 60, 100 } },
{ tick = 288, type = "noteOff", channel = 0, data = { 60, 0 } },
} })
table.insert(k.tracks, { events = {
txt(0, 3, "Words"), txt(0, 1, "@KMIDI KARAOKE FILE"), txt(0, 1, "@LENG"), txt(0, 1, "@TSong title"),
txt(0, 1, "@TThe artist"), txt(0, 1, "@Isome info"), txt(96, 1, "\\Hel"), txt(144, 1, "lo"),
txt(192, 1, "/world"), txt(240, 5, "!"),
} })
local m = assert(decode(Midi.encode(k)))
local ly = m.meta.lyrics
t:eq(#ly, 4, "kar: lyric count")
t:eq(ly[1].text, "\\Hel", "kar: first lyric (paragraph marker kept)")
t:eq(ly[1].tick, 96, "kar: tick")
t:check(math.abs(ly[1].time - 1) < 1e-9 and math.abs(ly[3].time - 2) < 1e-9, "kar: times through the tempo map")
t:eq(ly[4].text, "!", "kar: FF 05 lyric")
t:eq(m.meta.karaoke.T[2], "The artist", "kar: @T lines")
t:eq(m.meta.karaoke.K[1], "MIDI KARAOKE FILE", "kar: @K")
t:eq(m.meta.tags.title, "Song title", "kar: tags.title")
t:eq(m.meta.tags.artist, "The artist", "kar: tags.artist")
t:eq(m.meta.tags.language, "ENG", "kar: tags.language")
t:eq(m:render().tags.title, "Song title", "kar: decoder title")
local plain = assert(decode(Midi.encode(Types.Midi.new(96))))
t:eq(plain.meta.lyrics, nil, "no lyrics without text events")
end
t:fuzz("decode", function(b: buffer)
return decode(b)
end, samples, { mutations = 40 })
+93
View File
@@ -0,0 +1,93 @@
-- music/mus tests: Doom MUS files (tools/fixtures/mus.py) decoded and compared with wildmidi -x's conversion (notes,
-- programs, pitch bend MSB, controllers; times at wildmidi's tick rate), system events / measure ends, the tick rate
-- option, a render, bad input, and the fuzz no-throw pass.
local T = require("@tests/T")
local V = require("@tests/music/_midivar")
local Mus = require("@formats/music/mus")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Render = require("@formats/codecs/audio/MidiRender")
local Cases = require("@tests/gen/mus_cases")
local Measures = require("@tests/gen/mus_measures")
local t = T.suite("mus")
local function decode(s: string, opts: any?): (any, any)
return Mus.decode(Bytes.reader(buffer.fromstring(s)), opts)
end
t:eq(Mus.name, "mus", "name")
t:check(Mus.caps.decode and not Mus.caps.encode, "caps")
t:eq(Mus.sniff(Bytes.reader(buffer.fromstring("MUS\x1a"))), 1, "sniff")
t:eq(Mus.sniff(Bytes.reader(buffer.fromstring("MThd"))), 0, "sniff MThd")
local samples = {}
for _, c in Cases do
local m, err = decode(c.data, { rate = c.rate })
t:check(m, c.name .. ": " .. tostring(err))
if m then
t:eq(m.kind, "midi", c.name .. ": kind")
t:eq(m.meta.source.format, "mus", c.name .. ": source")
t:eq(#m.meta.source.instruments, 3, c.name .. ": instrument list")
V.compare(t, m, c.ref, c.name)
-- Doom's 140 Hz: the same events, times scaled by rate / 140
local d = assert(decode(c.data))
t:check(math.abs(d.meta.length * 140 - m.meta.length * c.rate) < 1e-5 * d.meta.length * 140 + 1e-6, c.name .. ": 140 Hz default")
end
table.insert(samples, buffer.fromstring(c.data))
end
-- system events and measure ends inserted with no delay: the same notes at the same times, more controllers
do
local p, q = assert(decode(Measures.plain)), assert(decode(Measures.marked))
local a, b = Render.timeline(p), Render.timeline(q)
local function notes(tl: any): { string }
local out = {}
for i = 1, #tl.time do
if tl.status[i] // 16 == 8 or tl.status[i] // 16 == 9 then
table.insert(out, string.format("%.6f %d %d %d", tl.time[i], tl.status[i], tl.d1[i], tl.d2[i]))
end
end
return out
end
local na, nb = notes(a), notes(b)
t:eq(#nb, #na, "measures: note count")
t:eq(table.concat(nb, ","), table.concat(na, ","), "measures: same notes")
t:check(#b.time > #a.time, "measures: system events become controllers")
t:eq(q.meta.length, p.meta.length, "measures: same length")
end
-- a render through the built-in waveforms
do
local m = assert(decode(Cases[1].data))
local dec = m:render({ sampleRate = 22050, tail = 0.2 })
t:check(dec.frames > 0 and math.abs(dec.duration - (m.meta.length + 0.2)) < 0.01, "render duration")
local buf, n = dec:read(dec.frames)
local peak = 0
for i = 0, n * 2 - 1 do
peak = math.max(peak, math.abs(buffer.readf32(buf, i * 4)))
end
t:check(peak > 0.01, "render makes sound")
end
-- bad input
local _, e1 = decode("MUS\x1a\1\0")
t:eq(e1 and e1.code, Err.TRUNCATED, "short header")
local _, e2 = decode("MUS\x1a\2\0\200\0\1\0\0\0\0\0\0\0")
t:eq(e2 and e2.code, Err.TRUNCATED, "score past the end")
local _, e3 = decode("MUS\x1a\2\0\16\0\1\0\0\0\0\0\0\0\112\0")
t:eq(e3 and e3.code, Err.CORRUPT, "event type 7")
local _, e4 = decode(Cases[1].data, { rate = 0 })
t:eq(e4 and e4.code, Err.ARG, "bad rate")
t:fuzz("decode", function(b: buffer)
return Mus.decode(Bytes.reader(b))
end, samples)
t:fuzz("decode + render", function(b: buffer)
local m = Mus.decode(Bytes.reader(b))
if m and m.meta.length < 30 then
m:render({ sampleRate = 8000 }):read(2000)
end
return m
end, samples, { mutations = 60, garbage = 10 })
t:done()
+73
View File
@@ -0,0 +1,73 @@
-- music/xmi tests: XMIDI files (tools/fixtures/xmi.py: XDIR + CAT XMID with one or two songs, a bare FORM XMID, with
-- and without TIMB) decoded and compared with wildmidi -x's conversion of song 1 (notes from durations, programs,
-- bends, controllers; 120 Hz), song selection, export to SMF, a render, bad input, and the fuzz no-throw pass.
local T = require("@tests/T")
local V = require("@tests/music/_midivar")
local Xmi = require("@formats/music/xmi")
local Midi = require("@formats/music/midi")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Cases = require("@tests/gen/xmi_cases")
local t = T.suite("xmi")
local function decode(s: string, opts: any?): (any, any)
return Xmi.decode(Bytes.reader(buffer.fromstring(s)), opts)
end
t:eq(Xmi.name, "xmi", "name")
t:check(Xmi.caps.decode and not Xmi.caps.encode, "caps")
t:eq(Xmi.sniff(Bytes.reader(buffer.fromstring("FORM\0\0\0\0XDIR"))), 1, "sniff XDIR")
t:eq(Xmi.sniff(Bytes.reader(buffer.fromstring("FORM\0\0\0\0AIFF"))), 0, "sniff AIFF")
local samples = {}
for _, c in Cases do
local m, err = decode(c.data)
t:check(m, c.name .. ": " .. tostring(err))
if m then
t:eq(m.meta.source.songs, c.songs, c.name .. ": songs")
t:eq(m.division, 60, c.name .. ": division")
V.compare(t, m, c.ref, c.name, { hangingOffs = true })
if c.songs > 1 then
local s2 = assert(decode(c.data, { track = 2 }))
t:eq(s2.meta.source.song, 2, c.name .. ": song 2")
t:check(#s2.tracks[1].events ~= #m.tracks[1].events, c.name .. ": song 2 differs")
local _, e = decode(c.data, { track = 3 })
t:eq(e and e.code, Err.ARG, c.name .. ": no song 3")
end
-- export to a Standard MIDI File and back: the same timeline
local smf = assert(Midi.encode(m))
local back = assert(Midi.decode(Bytes.reader(smf)))
t:check(math.abs(back.meta.length - m.meta.length) < 1e-9, c.name .. ": SMF export keeps the timing")
end
table.insert(samples, buffer.fromstring(c.data))
end
do
local m = assert(decode(Cases[1].data))
local dec = m:render({ sampleRate = 22050, tail = 0.2 })
t:check(math.abs(dec.duration - (m.meta.length + 0.2)) < 0.01, "render duration")
local buf, n = dec:read(dec.frames)
local peak = 0
for i = 0, n * 2 - 1 do
peak = math.max(peak, math.abs(buffer.readf32(buf, i * 4)))
end
t:check(peak > 0.01, "render makes sound")
end
local _, e1 = decode("FORM\0\0\0\4XDIR")
t:eq(e1 and e1.code, Err.CORRUPT, "no songs")
local _, e2 = decode("FORM\0\0\0\14XMIDEVNT\0\0\0\2\144\60")
t:eq(e2 and e2.code, Err.TRUNCATED, "truncated note")
t:fuzz("decode", function(b: buffer)
return Xmi.decode(Bytes.reader(b))
end, samples)
t:fuzz("decode + render", function(b: buffer)
local m = Xmi.decode(Bytes.reader(b))
if m and m.meta.length < 30 then
m:render({ sampleRate = 8000 }):read(2000)
end
return m
end, samples, { mutations = 60, garbage = 10 })
t:done()
+21
View File
@@ -1078,3 +1078,24 @@ do
jitTune(false)
end
end
-- ws-audio2: chip/midi
do
-- AHX / HVL (codecs/audio/Hively): a whole song rendered at 44.1 kHz (tools/fixtures/ahx.py karma.ahx, 3 s; hvl.py
-- the 6-channel demo with ring modulation); MB/s of stereo f32 output, and how many times faster than real time
local Ahx, Hvl = require("@formats/music/ahx"), require("@formats/music/hvl")
local AC, HC = require("@tests/gen/ahx_cases"), require("@tests/gen/hvl_cases")
for _, spec in { { Ahx, AC, "karma.ahx", "ahx render karma (4 ch)" }, { Hvl, HC, "demo", "hvl render demo (6 ch)" } } do
for _, c in spec[2] do
if c.name == spec[3] then
local song = assert(spec[1].decode(Bytes.reader(buffer.fromstring(c.data))))
local frames = 0
local dt = bench(spec[4], 3, c.frames * 8, function()
local dec = song:render({ maxDuration = c.maxDuration })
frames = dec.frames
dec:read(frames)
end)
print(string.format("%-8s %-30s %8.1f x real time", runtime, "", frames / 44100 / dt))
end
end
end
end
+205
View File
@@ -0,0 +1,205 @@
# AHX / HVL fixture helpers (not a generator; tools/fixtures/ahx.py and hvl.py load it): small writers for both module
# formats (the layouts hvl2wav's replay.c reads), hand-made and random songs exercising the waveforms, filters, square
# modulation, PList commands, effects, ring modulation and panning, and the reference render through hvl2wav
# (nixpkgs#hivelytracker). hvl2wav on Linux is built with -D_BIG_ENDIAN_ and so byte-swaps every 16-bit sample it
# writes: the swap is undone here. Songs from the HivelyTracker source tree (Songs/, BSD-3) add real-world cases.
import os, struct, subprocess, tempfile
AHX_FX = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 12: 6, 15: 7}
def ins_header(ins):
a = ins.get("env", (1, 64, 10, 48, 10, 10, 0))
fs = ins.get("filter_speed", 0)
vib = ins.get("vib", (0, 0, 0))
hc = ins.get("hardcut", (0, 0))
sq = ins.get("square", (0x20, 0x3f, 1))
return bytes([
ins.get("volume", 64), ((fs & 0x1f) << 3) | ins.get("wavelen", 3),
a[0], a[1], a[2], a[3], a[4], a[5], a[6], 0, 0, 0,
((fs & 0x20) << 2) | ins.get("filter_lower", 1), vib[0], (0x80 if hc[0] else 0) | ((hc[1] & 7) << 4) | (vib[2] & 15), vib[1],
sq[0], sq[1], sq[2], ins.get("filter_upper", 0x3f), ins.get("plist_speed", 1), len(ins.get("plist", [])),
])
def names(song):
return b"".join(s.encode("latin-1") + b"\0" for s in [song.get("title", "")] + [i.get("name", "") for i in song["instruments"]])
def header_common(song):
posn = len(song["positions"])
flag6 = (0x80 if song.get("empty_track0") else 0) | ((song.get("speedmult", 1) - 1) << 5) | (posn >> 8)
return flag6, posn
def write_ahx(song):
trkl = song["trkl"]
tracks = song["tracks"]
flag6, posn = header_common(song)
body = b"".join(struct.pack(">H", s) for s in song.get("subsongs", []))
for pos in song["positions"]:
for tr, tp in pos:
body += bytes([tr, tp & 0xff])
for i, t in enumerate(tracks):
if i == 0 and song.get("empty_track0"):
continue
for j in range(trkl):
note, ins, fx, par = (t[j] + (0, 0, 0, 0))[:4] if j < len(t) else (0, 0, 0, 0)
body += bytes([(note << 2) | (ins >> 4), ((ins & 15) << 4) | fx, par])
for ins in song["instruments"]:
body += ins_header(ins)
for (note, fixed, wave, fx0, p0, fx1, p1) in ins.get("plist", []):
body += bytes([(AHX_FX[fx1] << 5) | (AHX_FX[fx0] << 2) | (wave >> 1), ((wave & 1) << 7) | (fixed << 6) | note, p0, p1])
nameat = 14 + len(body)
hdr = b"THX" + bytes([song.get("version", 1)]) + struct.pack(">HBBHBBBB", nameat, flag6, posn & 0xff,
song.get("restart", 0), trkl, len(tracks) - 1,
len(song["instruments"]), len(song.get("subsongs", [])))
return hdr + body + names(song)
def write_hvl(song):
trkl = song["trkl"]
tracks = song["tracks"]
ch = song["channels"]
flag6, posn = header_common(song)
restart = song.get("restart", 0)
body = b"".join(struct.pack(">H", s) for s in song.get("subsongs", []))
for pos in song["positions"]:
for tr, tp in pos:
body += bytes([tr, tp & 0xff])
for i, t in enumerate(tracks):
if i == 0 and song.get("empty_track0"):
continue
for j in range(trkl):
row = (tuple(t[j]) + (0,) * 6)[:6] if j < len(t) else (0,) * 6
if row == (0,) * 6 and j % 3 == 0:
body += b"\x3f" # the one-byte empty step (sometimes: both encodings are valid)
else:
note, ins, fx, par, fxb, parb = row
body += bytes([note, ins, (fx << 4) | fxb, par, parb])
for ins in song["instruments"]:
body += ins_header(ins)
for (note, fixed, wave, fx0, p0, fx1, p1) in ins.get("plist", []):
body += bytes([fx0, (fx1 << 3) | wave, (fixed << 6) | note, p0, p1])
nameat = 16 + len(body)
hdr = b"HVL" + bytes([song.get("version", 1)]) + struct.pack(">HBBBBBBBBBB", nameat, flag6, posn & 0xff,
((ch - 4) << 2) | (restart >> 8), restart & 0xff, trkl,
len(tracks) - 1, len(song["instruments"]),
len(song.get("subsongs", [])), song.get("mixgain", 100),
song.get("stereo", 2))
return hdr + body + names(song)
def hvl2wav(ctx, data, ext, args=()):
"""the reference render: (s16le interleaved stereo bytes, frames)"""
with tempfile.TemporaryDirectory() as d:
src = os.path.join(d, "song." + ext)
out = os.path.join(d, "out.wav")
with open(src, "wb") as f:
f.write(data)
ctx.nix("hivelytracker", ["hvl2wav", "-o" + out] + list(args) + [src])
raw = open(out, "rb").read()
assert raw[:4] == b"RIFF" and raw[36:40] == b"data", "hvl2wav: unexpected wav"
pcm = bytearray(raw[44:])
pcm[0::2], pcm[1::2] = pcm[1::2], pcm[0::2] # undo the -D_BIG_ENDIAN_ byte swap
return bytes(pcm), len(pcm) // 4
def source_songs(ctx):
"""{name: bytes} from the HivelyTracker source's Songs/ directory"""
path = subprocess.run(["nix", "build", "nixpkgs#hivelytracker.src", "--no-link", "--print-out-paths"],
capture_output=True, check=True).stdout.decode().strip()
songs = {}
for f in sorted(os.listdir(os.path.join(path, "Songs"))):
with open(os.path.join(path, "Songs", f), "rb") as fh:
songs[f] = fh.read()
return songs
# ---------------------------------------------------------------------------------------------------- songs
def instruments(hvl):
"""a set exercising every waveform, the filter and square sweeps and the PList commands"""
ins = [
# 1: triangle lead with vibrato and a filter set (cmd 0) + perf slide up (cmd 1)
dict(name="tri", wavelen=4, env=(2, 64, 8, 40, 20, 12, 0), vib=(6, 3, 4), plist_speed=2,
plist=[(0, 0, 1, 0, 0x18, 1, 2), (0, 0, 0, 2, 3, 0, 0), (0, 0, 0, 12, 0x30, 0, 0)]),
# 2: sawtooth with the filter sweep (cmd 4 high nibble) and fixed notes
dict(name="saw", wavelen=5, filter_speed=3, filter_lower=8, filter_upper=50, env=(1, 64, 20, 30, 10, 20, 0),
plist_speed=3, plist=[(1, 0, 2, 4, 0x10, 0, 0), (25, 1, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0, 0)]),
# 3: square with modulation (cmd 4 low nibble, cmd 3 offset), hard cut release
dict(name="square", wavelen=3, square=(0x08, 0x38, 2), hardcut=(1, 3), env=(3, 50, 6, 40, 30, 8, 10),
plist_speed=1, plist=[(0, 0, 3, 3, 0x20, 4, 0x01), (0, 0, 0, 0, 0, 0, 0), (0, 0, 0, 15, 4, 0, 0),
(0, 0, 0, 5, 1, 0, 0)]),
# 4: noise drum: fixed note, falling filter, volume steps (cmd C)
dict(name="noise", wavelen=2, env=(1, 64, 4, 20, 2, 6, 0), filter_speed=1, filter_lower=1, filter_upper=40,
plist_speed=1, plist=[(40, 1, 4, 12, 0x40, 4, 0xf0), (30, 1, 0, 12, 0x20, 0, 0), (20, 1, 1, 0, 0, 0, 0)]),
# 5: square + filter toggles together (cmd 4 0xff: negative directions), perf slide down
dict(name="pwm", wavelen=5, square=(0x3f, 0x10, 1), filter_speed=5, filter_lower=20, filter_upper=60,
env=(4, 60, 10, 50, 40, 10, 0), plist_speed=2,
plist=[(0, 0, 3, 4, 0xff, 2, 4), (0, 0, 0, 0, 0, 1, 1), (12, 0, 2, 3, 0x10, 0, 0)]),
]
if hvl:
# 6: ring modulation (cmd 7 triangle relative / cmd 8 saw fixed) and PList panning (cmd 9)
ins.append(dict(name="ring", wavelen=4, env=(1, 64, 10, 48, 20, 10, 0), plist_speed=2,
plist=[(0, 0, 2, 7, 0x8c, 9, 0x40), (0, 0, 0, 8, 0x20, 0, 0), (0, 0, 3, 7, 0x85, 9, 0xc0),
(0, 0, 0, 7, 0, 0, 0)]))
return ins
def demo_song(hvl):
"""hand-written: notes on every instrument and the main effects"""
E = []
t1 = [(25, 1), (), (27, 0, 0xA, 0x02), (), (29, 2, 0x1, 0x04), (), (0, 0, 0x2, 0x04), (), (30, 3), (), (0, 0, 0xE, 0x13),
(32, 4), (25, 5, 0xC, 0x30), (), (37, 1, 0x3, 0x08), (0, 0, 0x4, 0x50)]
t2 = [(13, 4), (), (13, 4, 0xE, 0xD2), (), (20, 3, 0x9, 0x10), (), (13, 4, 0xE, 0xC2), (), (13, 2, 0xE, 0xA4), (),
(15, 2, 0xE, 0x24), (), (13, 4, 0xC, 0x60), (), (17, 5, 0x5, 0x31), ()]
t3 = [(37, 2), (), (), (), (39, 1, 0xE, 0x44), (), (), (), (41, 5), (), (), (), (36, 3, 0xF, 0x04), (), (), (0, 0, 0xD, 0x00)]
if hvl:
t2 = [r + ((0x7, 0x30) if len(r) == 4 else ()) if r else r for r in t2]
t1[0] = (25, 6, 0x7, 0xd0, 0x1, 0x01)
t3[4] = (39, 6, 0xE, 0x44, 0xC, 0x20)
tracks = [E, t1, t2, t3]
ch = 6 if hvl else 4
pos = []
for k in range(2):
row = [(1, 0), (2, 0), (3, k * 2), (0, 0)]
if hvl:
row += [(3, -12), (1, 5)]
pos.append(row)
return dict(title="demo", trkl=16, tracks=tracks, positions=pos, channels=ch, instruments=instruments(hvl),
empty_track0=True, mixgain=110, stereo=3, subsongs=[1])
def random_song(rng, hvl, n_tracks=6, trkl=16, n_pos=3):
ins = instruments(hvl)
ch = rng.choice([4, 5, 8]) if hvl else 4
fxs = [0x1, 0x2, 0x3, 0x4, 0x5, 0x9, 0xA, 0xC, 0xE] + ([0x7] if hvl else [])
tracks = [[]]
for _ in range(n_tracks):
t = []
for _ in range(trkl):
r = rng.random()
if r < 0.45:
t.append(())
continue
note = rng.randint(1, 60) if rng.random() < 0.8 else 0
inst = rng.randint(1, len(ins)) if rng.random() < 0.7 else 0
fx, par = 0, 0
if rng.random() < 0.5:
fx = rng.choice(fxs)
par = rng.randint(0, 255)
if fx == 0xE:
par = rng.choice([0x1, 0x2, 0x4, 0xA, 0xB, 0xC, 0xD]) << 4 | rng.randint(0, 5)
if fx == 0xC:
par = rng.choice([rng.randint(0, 0x40), 0x50 + rng.randint(0, 0x40), 0xa0 + rng.randint(0, 0x40)])
if fx == 0x4:
par = rng.randint(0x41, 0x7f) if rng.random() < 0.6 else rng.randint(1, 0x3f)
row = (note, inst, fx, par)
if hvl and rng.random() < 0.3:
row += (rng.choice([0x1, 0x2, 0xA, 0xC, 0x7]), rng.randint(0, 0x40))
t.append(row)
tracks.append(t)
pos = [[(rng.randint(0, n_tracks), rng.randint(-5, 5)) for _ in range(ch)] for _ in range(n_pos)]
return dict(title="random", trkl=trkl, tracks=tracks, positions=pos, channels=ch, instruments=ins,
speedmult=rng.choice([1, 1, 2, 3]), mixgain=rng.choice([80, 100, 140]), stereo=rng.randint(0, 4),
version=rng.choice([0, 1, 2]) if not hvl else 1)
+320
View File
@@ -0,0 +1,320 @@
# MIDI-variant fixture helpers (not a generator; tools/fixtures/mus.py, xmi.py and hmp.py load it): small writers for
# Doom MUS, Miles XMIDI and HMI HMP, random event streams, and the reference conversion through wildmidi -x
# (nixpkgs#wildmidi: it writes a Standard MIDI File; only its event stream is used, read back by the small SMF reader
# below into channel events with times in seconds).
import os, random, struct, subprocess, tempfile
def vlq(v):
out = [v & 127]
v >>= 7
while v:
out.insert(0, (v & 127) | 128)
v >>= 7
return bytes(out)
def vlq_hmp(v):
"""HMP deltas: 7-bit groups least significant first, the last byte has bit 7 set"""
out = []
while True:
b = v & 127
v >>= 7
if v == 0:
out.append(b | 128)
return bytes(out)
out.append(b)
# ---------------------------------------------------------------------------------------------------- MUS
def write_mus(events, instruments=(), primary=4, secondary=0):
"""events: [(delay_after, type, channel, data bytes)]; the last flag is set when delay_after > 0"""
score = b""
for delay, typ, ch, data in events:
score += bytes([(0x80 if delay else 0) | (typ << 4) | ch]) + bytes(data)
if delay:
score += vlq(delay)
hdr_len = 16 + 2 * len(instruments)
hdr = b"MUS\x1a" + struct.pack("<HHHHHH", len(score), hdr_len, primary, secondary, len(instruments), 0)
hdr += b"".join(struct.pack("<H", i) for i in instruments)
return hdr + score
def random_mus(rng, n=120, extras=0):
"""a random score; extras > 0 inserts that many system events (type 3, which wildmidi misreads: it takes two data
bytes) and measure ends (type 5, which wildmidi refuses), each with no delay, without changing anything else"""
ev = []
held = {}
for ch in [0, 1, 2, 15]:
ev.append((0, 4, ch, [0, rng.randint(0, 127) if ch != 15 else 0])) # program change
for _ in range(n):
ch = rng.choice([0, 1, 2, 3, 15, 9])
r = rng.random()
delay = rng.choice([0, 0, 1, 5, 17, 140, 200])
if r < 0.45:
note = rng.randint(30, 90)
if rng.random() < 0.6:
ev.append((delay, 1, ch, [note | 0x80, rng.randint(1, 127)]))
else:
ev.append((delay, 1, ch, [note]))
held.setdefault(ch, []).append(note)
elif r < 0.75 and held.get(ch):
ev.append((delay, 0, ch, [held[ch].pop(0)]))
elif r < 0.85:
ev.append((delay, 2, ch, [rng.randint(0, 255)]))
else:
ev.append((delay, 4, ch, [rng.randint(0, 9), rng.randint(0, 127)]))
for ch, notes in held.items():
for nt in notes:
ev.append((3, 0, ch, [nt]))
xr = random.Random(extras)
for _ in range(extras):
at = xr.randint(1, len(ev) - 1)
ch = ev[at][2]
ev.insert(at, (0, 5, ch, []) if xr.random() < 0.5 else (0, 3, ch, [xr.choice([10, 11, 12, 13, 14])]))
ev.append((0, 6, 0, []))
return write_mus(ev, instruments=[1, 30, 128 + 7])
# ---------------------------------------------------------------------------------------------------- XMI
def iff(cid, body):
return cid + struct.pack(">I", len(body)) + body + (b"\0" if len(body) % 2 else b"")
def xmi_events(events):
"""events: [(delay, bytes)]: a delay is written as interval bytes (each <= 0x7F) before the event"""
out = b""
for delay, ev in events:
while delay > 0x7f:
out += b"\x7f"
delay -= 0x7f
if delay:
out += bytes([delay])
out += ev
return out
def write_xmi(songs, with_xdir=True, timb=True):
forms = []
for evs in songs:
body = b"XMID"
if timb:
body += iff(b"TIMB", struct.pack("<H", 2) + bytes([0, 0, 30, 0]))
body += iff(b"EVNT", xmi_events(evs))
forms.append(iff(b"FORM", body))
if not with_xdir:
return forms[0]
xdir = iff(b"FORM", b"XDIR" + iff(b"INFO", struct.pack("<H", len(songs))))
return xdir + iff(b"CAT ", b"XMID" + b"".join(forms))
def random_xmi_song(rng, n=100, tempo=None):
ev = [(0, bytes([0xC0 | c, rng.randint(0, 127)])) for c in (0, 1, 2)]
if tempo:
ev.append((0, b"\xff\x51\x03" + tempo.to_bytes(3, "big")))
ev.append((0, b"\xff\x01\x05hello"))
for _ in range(n):
delay = rng.choice([0, 0, 3, 12, 30, 60, 200])
ch = rng.choice([0, 1, 2, 9])
r = rng.random()
if r < 0.6:
ev.append((delay, bytes([0x90 | ch, rng.randint(30, 90), rng.randint(1, 127)]) + vlq(rng.choice([1, 10, 30, 60, 150, 300]))))
elif r < 0.75:
ev.append((delay, bytes([0xB0 | ch, rng.choice([1, 7, 10, 11, 64]), rng.randint(0, 127)])))
elif r < 0.85:
ev.append((delay, bytes([0xE0 | ch, rng.randint(0, 127), rng.randint(0, 127)])))
elif r < 0.9:
ev.append((delay, bytes([0xC0 | ch, rng.randint(0, 127)])))
elif r < 0.95:
ev.append((delay, bytes([0xD0 | ch, rng.randint(0, 127)])))
else:
ev.append((delay, b"\xf0" + vlq(3) + b"\x7e\x7f\xf7"))
ev.append((rng.randint(0, 50), b"\xff\x2f\x00"))
return ev
# ---------------------------------------------------------------------------------------------------- HMP
def write_hmp(tracks, bpm=120, new=False):
"""tracks: [bytes of event data (deltas already in HMP form)]"""
head = (b"HMIMIDIP013195" if new else b"HMIMIDIP").ljust(32, b"\0")
start = 0x388 if new else 0x308
chunks = b""
for i, data in enumerate(tracks):
chunks += struct.pack("<III", i, len(data) + 12, i) + data
body = struct.pack("<I", start + len(chunks)) + b"\0" * 12 + struct.pack("<IIII", len(tracks), 0, bpm, 0)
out = head + body
return out + b"\0" * (start - len(out)) + chunks
def hmp_track(events):
"""events: [(delta, bytes)] -> HMP track data (ends with an end-of-track meta)"""
return b"".join(vlq_hmp(d) + e for d, e in events)
def random_hmp_tracks(rng, ntracks=3, n=60, running=True):
tracks = [hmp_track([(0, b"\xff\x2f\x00")])] # track 0: tempo / meta only, as in game files
for t in range(1, ntracks):
ch = t - 1 if t < 4 else 9
ev = [(0, bytes([0xC0 | ch, rng.randint(0, 127)]))]
on = []
running_ok, running = running, False
for _ in range(n):
d = rng.choice([0, 0, 5, 30, 60, 120, 400])
r = rng.random()
if r < 0.5:
note = rng.randint(30, 90)
on.append(note)
# running status (status byte left out) now and then
ev.append((d, (b"" if running else bytes([0x90 | ch])) + bytes([note, rng.randint(1, 127)])))
running = running_ok and rng.random() < 0.5
elif r < 0.8 and on:
ev.append((d, bytes([0x80 | ch, on.pop(0), 64])))
running = False
elif r < 0.9:
ev.append((d, bytes([0xB0 | ch, rng.choice([7, 10, 64]), rng.randint(0, 127)])))
running = False
else:
ev.append((d, bytes([0xE0 | ch, rng.randint(0, 127), rng.randint(0, 127)])))
running = False
for note in on:
ev.append((10, bytes([0x80 | ch, note, 0])))
ev.append((0, b"\xff\x2f\x00"))
tracks.append(hmp_track(ev))
return tracks
# ---------------------------------------------------------------------------------------------------- wildmidi
def read_smf(data):
"""-> (division, [(tick, track, status, d1, d2)] channel events, [(tick, us)] tempos); format 2: track 1 only (its
first song: wildmidi writes every XMIDI song as a track of a format 2 file)"""
assert data[:4] == b"MThd"
fmt, ntrk, div = struct.unpack(">HHH", data[8:14])
if fmt == 2:
ntrk = 1
p = 8 + struct.unpack(">I", data[4:8])[0]
events, tempos = [], []
for ti in range(ntrk):
assert data[p:p + 4] == b"MTrk"
n = struct.unpack(">I", data[p + 4:p + 8])[0]
q, e = p + 8, p + 8 + n
tick, run = 0, 0
while q < e:
d = 0
while True:
c = data[q]
q += 1
d = d * 128 + (c & 127)
if c < 128:
break
tick += d
st = data[q]
if st < 0x80:
st = run
else:
q += 1
if st == 0xFF:
typ = data[q]
q += 1
ln = 0
while True:
c = data[q]
q += 1
ln = ln * 128 + (c & 127)
if c < 128:
break
if typ == 0x51:
tempos.append((tick, int.from_bytes(data[q:q + 3], "big")))
q += ln
elif st in (0xF0, 0xF7):
ln = 0
while True:
c = data[q]
q += 1
ln = ln * 128 + (c & 127)
if c < 128:
break
q += ln
else:
run = st
k = 1 if st >> 4 in (0xC, 0xD) else 2
d1 = data[q]
d2 = data[q + 1] if k == 2 else 0
q += k
events.append((tick, ti, st, d1, d2))
p = e
return div, events, tempos
def seconds(div, tempos, tick):
tempos = sorted(tempos)
t, last, us = 0.0, 0, 500000
for tk, u in tempos:
if tk >= tick:
break
t += (tk - last) * us / 1e6 / div
last, us = tk, u
return t + (tick - last) * us / 1e6 / div
def wildmidi(ctx, data, ext, args=()):
"""the reference: wildmidi -x's SMF as { division, tempo (first), events = { {time, status, d1, d2} } }"""
with tempfile.TemporaryDirectory() as d:
src = os.path.join(d, "in." + ext)
out = os.path.join(d, "out.mid")
with open(src, "wb") as f:
f.write(data)
r = subprocess.run(["nix", "shell", "nixpkgs#wildmidi", "-c", "wildmidi"] + list(args) + ["-x", out, src],
capture_output=True)
if not os.path.exists(out):
raise RuntimeError("wildmidi failed: " + r.stdout.decode(errors="replace")[-400:] + r.stderr.decode(errors="replace")[-400:])
smf = open(out, "rb").read()
div, events, tempos = read_smf(smf)
events.sort(key=lambda e: (e[0], e[1]))
return {"division": div, "tempo": tempos[0][1] if tempos else 500000,
"events": [[seconds(div, tempos, tk), st, d1, d2] for tk, _, st, d1, d2 in events]}
# ---------------------------------------------------------------------------------------------------- HMI
def write_hmi(tracks, bpm=120):
"""tracks: [bytes of event data (MIDI deltas; note-ons followed by a duration)]"""
hdr_len = 0x5B
head = bytearray(b"HMI-MIDISONG061595".ljust(370, b"\0"))
head[212] = bpm
head[228] = len(tracks)
table = b""
body = b""
at = 370 + 4 * len(tracks)
for data in tracks:
table += struct.pack("<I", at + len(body))
th = bytearray(b"HMI-MIDITRACK".ljust(hdr_len, b"\0"))
th[0x57:0x5B] = struct.pack("<I", hdr_len)
body += bytes(th) + data
return bytes(head) + table + body
def random_hmi_tracks(rng, ntracks=3, n=50):
tracks = []
for t in range(ntracks):
ch = t if t < 3 else 9
ev = vlq(0) + bytes([0xC0 | ch, rng.randint(0, 127)])
ev += vlq(0) + b"\xfe\x15\x00\x00\x00\x00\x00\x00" # an HMI-only event (8 bytes)
ev += vlq(0) + b"\xfe\x10\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00" # FE 10 with a 3-byte payload: 12 bytes
running = False
for _ in range(n):
d = rng.choice([0, 0, 5, 30, 60, 120])
r = rng.random()
if r < 0.6:
ev += vlq(d) + (b"" if running else bytes([0x90 | ch])) + bytes([rng.randint(30, 90), rng.randint(1, 127)])
ev += vlq(rng.choice([1, 10, 40, 100, 300]))
running = rng.random() < 0.5
elif r < 0.8:
ev += vlq(d) + bytes([0xB0 | ch, rng.choice([7, 10, 64]), rng.randint(0, 127)])
running = False
elif r < 0.9:
ev += vlq(d) + b"\xfe\x01\x00\x00" # a plain 4-byte FE event
else:
ev += vlq(d) + bytes([0xE0 | ch, rng.randint(0, 127), rng.randint(0, 127)])
running = False
ev += vlq(rng.randint(0, 40)) + b"\xff\x2f\x00"
tracks.append(ev)
return tracks
+36
View File
@@ -0,0 +1,36 @@
# AHX fixtures (tools/fixtures.py): songs written by tools/fixtures/_hively.py (a hand-made demo over every waveform,
# filter / square sweeps, PList commands and effects; random songs) plus karma.ahx from the HivelyTracker source, each
# rendered by hvl2wav (nixpkgs#hivelytracker) as the reference.
# tests/gen/ahx_cases.luau { { name, data, crc (CRC-32 of hvl2wav's s16le stereo output), head (its first HEAD frames), frames, sampleRate, stereo, subsong, maxDuration?,
# prefix (true: hvl2wav ran with a time limit, compare the first frames only) } }
import importlib.util, os, zlib
INPUTS = ["tools/fixtures/_hively.py"]
_spec = importlib.util.spec_from_file_location("_hively", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_hively.py"))
H = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(H)
HEAD = 11025 # frames of hvl2wav output kept as raw samples (to locate a mismatch); the rest is checked by CRC
def case(ctx, name, data, rate=44100, stereo=0, subsong=0, limit=None):
args = ["-f%d" % rate, "-x%d" % stereo, "-s%d" % subsong] + (["-t0:%02d" % limit] if limit else [])
pcm, frames = H.hvl2wav(ctx, data, "ahx", args)
c = {"name": name, "data": data, "crc": zlib.crc32(pcm), "head": pcm[:HEAD * 4], "frames": frames, "sampleRate": rate, "stereo": stereo,
"subsong": subsong, "prefix": limit is not None}
if limit:
c["maxDuration"] = limit
return c
def generate(ctx):
rng = ctx.rng(0xA4)
demo = H.write_ahx(H.demo_song(False))
cases = [case(ctx, "demo", demo), case(ctx, "demo stereo 4", demo, stereo=4),
case(ctx, "demo 22050 Hz stereo 2", demo, rate=22050, stereo=2), case(ctx, "demo subsong 1", demo, subsong=1)]
for i in range(4):
cases.append(case(ctx, "random %d" % i, H.write_ahx(H.random_song(rng, False)), stereo=i))
songs = H.source_songs(ctx)
cases.append(case(ctx, "karma.ahx", songs["karma.ahx"], stereo=4, limit=3))
ctx.emit("ahx_cases", cases)
+49
View File
@@ -0,0 +1,49 @@
# Docs inputs for the AHX / HVL / MIDI-variant section of docs/guide/music.md (tools/fixtures.py; tools/docs_check.py
# reads them): the demo songs of tools/fixtures/_hively.py, small MUS / XMI / HMP files from tools/fixtures/_midivar.py
# and a .kar karaoke file written here.
# tests/gen/docs_chip.luau { files = { [name] = bytes }, vars = { ahxBytes = "demo.ahx", ... } }
import importlib.util, os, random, struct
INPUTS = ["tools/docs_check.py", "tools/fixtures/_hively.py", "tools/fixtures/_midivar.py"]
def load(ctx, name):
spec = importlib.util.spec_from_file_location("docs_chip_" + name.replace("/", "_"), os.path.join(ctx.root, "tools", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def kar(V):
"""SMF 1 with a melody track and a "Words" track: @ headers, then syllables with \\ / line markers"""
def trk(events):
body = b"".join(V.vlq(dt) + data for dt, data in events) + b"\x00\xff\x2f\x00"
return b"MTrk" + struct.pack(">I", len(body)) + body
def text(s, kind=1):
s = s.encode()
return bytes([0xFF, kind]) + V.vlq(len(s)) + s
melody = [(0, b"\xff\x51\x03\x07\xa1\x20"), (0, b"\xc0\x00")]
for n in (60, 62, 64, 65):
melody += [(0, bytes([0x90, n, 100])), (480, bytes([0x80, n, 0]))]
words = [(0, text("Words", 3)), (0, text("@KMIDI KARAOKE FILE")), (0, text("@TLittle Song")), (0, text("@TThe Docs")),
(0, text("\\Hel")), (480, text("lo ")), (480, text("/kar")), (480, text("aoke"))]
return b"MThd" + struct.pack(">IHHh", 6, 1, 2, 480) + trk(melody) + trk(words)
def generate(ctx):
dc = load(ctx, "docs_check")
H = load(ctx, "fixtures/_hively")
V = load(ctx, "fixtures/_midivar")
rng = random.Random(5)
files = {
"demo.ahx": H.write_ahx(H.demo_song(False)),
"demo.hvl": H.write_hvl(H.demo_song(True)),
"e1m1.mus": V.random_mus(rng, n=40),
"song.xmi": V.write_xmi([V.random_xmi_song(rng, n=30, tempo=500000), V.random_xmi_song(rng, n=10, tempo=500000)]),
"song.hmp": V.write_hmp(V.random_hmp_tracks(rng, ntracks=3, n=20, running=False)),
"song.kar": kar(V),
}
dc.emit_inputs(ctx, files, {"ahxBytes": "demo.ahx", "hvlBytes": "demo.hvl", "musBytes": "e1m1.mus",
"xmiBytes": "song.xmi", "hmpBytes": "song.hmp", "karBytes": "song.kar"})
+24
View File
@@ -0,0 +1,24 @@
# HMP / HMI fixtures (tools/fixtures.py): HMP (old and "013195" headers) and HMI files written by
# tools/fixtures/_midivar.py (several tracks, running status in HMI, HMI note durations and FE events, tick rates) and
# wildmidi -x's conversion of each as the reference event stream (wildmidi reads HMP without running status, so the
# HMP files use none).
# tests/gen/hmp_cases.luau { { name, data, kind, rate, ref = { division, tempo, events = { {seconds, status, d1, d2} } } } }
import importlib.util, os
INPUTS = ["tools/fixtures/_midivar.py"]
_spec = importlib.util.spec_from_file_location("_midivar", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_midivar.py"))
M = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(M)
def generate(ctx):
rng = ctx.rng(0x484D50)
cases = []
for i, (new, rate) in enumerate([(False, 120), (True, 120), (False, 60), (True, 140)]):
data = M.write_hmp(M.random_hmp_tracks(rng, ntracks=2 + i, n=40, running=False), bpm=rate, new=new)
cases.append({"name": "hmp %d%s" % (i, " 013195" if new else ""), "data": data, "kind": "hmp", "rate": rate,
"ref": M.wildmidi(ctx, data, "hmp")})
for i, rate in enumerate([120, 100]):
data = M.write_hmi(M.random_hmi_tracks(rng, ntracks=2 + i), bpm=rate)
cases.append({"name": "hmi %d" % i, "data": data, "kind": "hmi", "rate": rate, "ref": M.wildmidi(ctx, data, "hmi")})
ctx.emit("hmp_cases", cases)
+35
View File
@@ -0,0 +1,35 @@
# HVL fixtures (tools/fixtures.py): songs written by tools/fixtures/_hively.py (a hand-made 6-channel demo with ring
# modulation, panning and two effect columns; random 4..8 channel songs) plus songs from the HivelyTracker source, each
# rendered by hvl2wav (nixpkgs#hivelytracker) as the reference.
# tests/gen/hvl_cases.luau { { name, data, crc (CRC-32 of hvl2wav's s16le stereo output), head (its first HEAD frames), frames, sampleRate, subsong, maxDuration?, prefix } }
import importlib.util, os, zlib
INPUTS = ["tools/fixtures/_hively.py"]
_spec = importlib.util.spec_from_file_location("_hively", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_hively.py"))
H = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(H)
HEAD = 11025 # frames of hvl2wav output kept as raw samples (to locate a mismatch); the rest is checked by CRC
def case(ctx, name, data, rate=44100, subsong=0, limit=None):
args = ["-f%d" % rate, "-s%d" % subsong] + (["-t0:%02d" % limit] if limit else [])
pcm, frames = H.hvl2wav(ctx, data, "hvl", args)
c = {"name": name, "data": data, "crc": zlib.crc32(pcm), "head": pcm[:HEAD * 4], "frames": frames, "sampleRate": rate, "subsong": subsong,
"prefix": limit is not None}
if limit:
c["maxDuration"] = limit
return c
def generate(ctx):
rng = ctx.rng(0x4E1)
demo = H.write_hvl(H.demo_song(True))
cases = [case(ctx, "demo", demo), case(ctx, "demo 48000 Hz", demo, rate=48000), case(ctx, "demo subsong 1", demo, subsong=1)]
for i in range(4):
cases.append(case(ctx, "random %d" % i, H.write_hvl(H.random_song(rng, True))))
songs = H.source_songs(ctx)
for name in ["chiprolled.hvl", "sunspots.hvl", "syphus-Afterstorm.hvl"]:
cases.append(case(ctx, name, songs[name], limit=3))
ctx.emit("hvl_cases", cases)
+28
View File
@@ -0,0 +1,28 @@
# MUS fixtures (tools/fixtures.py): Doom MUS files written by tools/fixtures/_midivar.py (notes with and without volume,
# releases, pitch wheel, controllers, program changes; system events and measure ends only in mus_measures, as wildmidi
# misreads the first and refuses the second) and wildmidi -x's conversion of each as the reference event stream.
# tests/gen/mus_cases.luau { { name, data, rate (wildmidi's effective tick rate), ref = { division, tempo,
# events = { {seconds, status, d1, d2} } } } }
import importlib.util, os
INPUTS = ["tools/fixtures/_midivar.py"]
_spec = importlib.util.spec_from_file_location("_midivar", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_midivar.py"))
M = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(M)
def generate(ctx):
rng = ctx.rng(0x4D55)
cases = []
for i in range(4):
data = M.random_mus(rng, n=60 + 60 * i)
ref = M.wildmidi(ctx, data, "mus")
# wildmidi writes its tempo bytes in the wrong order (0x1B8A06 for 0x068A1B) at division 257: its MUS tick
# rate is 257 / 1.804806 s, not Doom's 140 Hz
rate = ref["division"] * 1e6 / ref["tempo"]
cases.append({"name": "random %d" % i, "data": data, "rate": rate, "ref": ref})
# system events and measure ends inserted with no delay: the same notes at the same times, more controllers
plain = M.random_mus(ctx.rng(7), n=80)
marked = M.random_mus(ctx.rng(7), n=80, extras=12)
ctx.emit("mus_cases", cases)
ctx.emit("mus_measures", {"plain": plain, "marked": marked})
+26
View File
@@ -0,0 +1,26 @@
# XMIDI fixtures (tools/fixtures.py): XMI files written by tools/fixtures/_midivar.py (FORM XDIR + CAT XMID with one or
# two songs, a bare FORM XMID (its reference converted from the same song with XDIR); every channel event, note durations, sysex, meta) and wildmidi -x's conversion of song 1
# as the reference event stream. Each song starts with a tempo event, as real files do (wildmidi derives its 120 Hz
# conversion from the first tempo event).
# tests/gen/xmi_cases.luau { { name, data, songs, ref = { division, tempo, events = { {seconds, status, d1, d2} } } } }
import importlib.util, os
INPUTS = ["tools/fixtures/_midivar.py"]
_spec = importlib.util.spec_from_file_location("_midivar", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_midivar.py"))
M = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(M)
def generate(ctx):
rng = ctx.rng(0x584D49)
cases = []
for i in range(4):
songs = [M.random_xmi_song(rng, n=60 + 40 * i, tempo=rng.choice([500000, 1000000, 400000]))]
if i == 1:
songs.append(M.random_xmi_song(rng, n=20, tempo=500000))
data = M.write_xmi(songs, timb=(i != 3))
ref = M.wildmidi(ctx, data, "xmi")
if i == 2:
data = M.write_xmi(songs, with_xdir=False) # a bare FORM XMID (wildmidi wants XDIR: the reference comes from the full file)
cases.append({"name": "random %d" % i, "data": data, "songs": len(songs), "ref": ref})
ctx.emit("xmi_cases", cases)