diff --git a/docs/FORMATS.md b/docs/FORMATS.md index bd4f9e8..35547d4 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -73,6 +73,8 @@ 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 | 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` | @@ -89,6 +91,7 @@ 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: diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index d61e1b4..c0c9de3 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -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"). diff --git a/licenses/hivelytracker-LICENSE.txt b/licenses/hivelytracker-LICENSE.txt new file mode 100644 index 0000000..2100428 --- /dev/null +++ b/licenses/hivelytracker-LICENSE.txt @@ -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. diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index ee48276..65a6e9b 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -830,6 +830,30 @@ 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 = "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", diff --git a/src/Formats/codecs/audio/Hively/Load.luau b/src/Formats/codecs/audio/Hively/Load.luau new file mode 100644 index 0000000..0becae4 --- /dev/null +++ b/src/Formats/codecs/audio/Hively/Load.luau @@ -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" + 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) + 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 diff --git a/src/Formats/codecs/audio/Hively/Player.luau b/src/Formats/codecs/audio/Hively/Player.luau new file mode 100644 index 0000000..b639be6 --- /dev/null +++ b/src/Formats/codecs/audio/Hively/Player.luau @@ -0,0 +1,972 @@ +--!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 + v.squareWait = if v.instrument then v.instrument.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 + if v.newWaveform and v.audioSrc then + if v.waveform == 3 then + fillCycles(v.voiceBuf, v.audioSrc, v.audioOff, 0x280) + else + fillCycles(v.voiceBuf, v.audioSrc, v.audioOff, 4 * 2 ^ v.waveLength) + end + 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 diff --git a/src/Formats/codecs/audio/Hively/Tables.luau b/src/Formats/codecs/audio/Hively/Tables.luau new file mode 100644 index 0000000..8d76e0e --- /dev/null +++ b/src/Formats/codecs/audio/Hively/Tables.luau @@ -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 diff --git a/src/Formats/codecs/audio/Hively/init.luau b/src/Formats/codecs/audio/Hively/init.luau new file mode 100644 index 0000000..1585985 --- /dev/null +++ b/src/Formats/codecs/audio/Hively/init.luau @@ -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 diff --git a/src/Formats/music/ahx/init.luau b/src/Formats/music/ahx/init.luau new file mode 100644 index 0000000..28aa9bc --- /dev/null +++ b/src/Formats/music/ahx/init.luau @@ -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 diff --git a/src/Formats/music/hvl/init.luau b/src/Formats/music/hvl/init.luau new file mode 100644 index 0000000..c731c6c --- /dev/null +++ b/src/Formats/music/hvl/init.luau @@ -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 diff --git a/tests/music/_hively.luau b/tests/music/_hively.luau new file mode 100644 index 0000000..4081503 --- /dev/null +++ b/tests/music/_hively.luau @@ -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 diff --git a/tests/music/ahx.luau b/tests/music/ahx.luau new file mode 100644 index 0000000..edf2e12 --- /dev/null +++ b/tests/music/ahx.luau @@ -0,0 +1,68 @@ +-- 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") + +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() diff --git a/tests/music/hvl.luau b/tests/music/hvl.luau new file mode 100644 index 0000000..cf4fbdb --- /dev/null +++ b/tests/music/hvl.luau @@ -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() diff --git a/tools/fixtures/_hively.py b/tools/fixtures/_hively.py new file mode 100644 index 0000000..739ad94 --- /dev/null +++ b/tools/fixtures/_hively.py @@ -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) diff --git a/tools/fixtures/ahx.py b/tools/fixtures/ahx.py new file mode 100644 index 0000000..bd70a3b --- /dev/null +++ b/tools/fixtures/ahx.py @@ -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) diff --git a/tools/fixtures/hvl.py b/tools/fixtures/hvl.py new file mode 100644 index 0000000..92d6d6c --- /dev/null +++ b/tools/fixtures/hvl.py @@ -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)