Add the FastTracker II companion module and its build chain

The module is a native XM derived from the verified score: visualizer/score.py
reads song_data.h, synth.h and voices.h and cross-checks them against
tools/arrange_v11.py, refusing a stale score; xm_build.py turns that into the
module; test_xm.py and xm_verify.py check the result. Eleven module tests and
ten score tests pass from a clean clone.

The capture scripts are included so the FastTracker II session is reproducible,
but MS-DOS, FastTracker II, emulator ROMs, boot images and the raw capture are
proprietary or machine-local and stay out. .gitignore gains the patterns that
would otherwise have let them in - it covered *.mp4 and *.wav but not *.IMG,
*.mkv, tracker/dos/ or tracker/capture/.
This commit is contained in:
CRTkafa 2026-09-05 22:53:58 +00:00
parent 40f72974b6
commit c4f5cdc5fa
12 changed files with 1955 additions and 0 deletions

12
.gitignore vendored
View file

@ -16,3 +16,15 @@ gputest.txt
export-provenance.json
delivery.json
qa/
# ---- tracker companion: local-only inputs --------------------------------
# The XM was captured by running genuine MS-DOS 6.22 and FastTracker II 2.08
# inside 86Box. Those binaries, the boot images and the ~6 GB raw capture are
# proprietary or machine-local and must never be committed here. *.mp4 and
# *.wav above already cover the renders; these cover the rest.
tracker/dos/
tracker/capture/
*.IMG
*.img
*.mkv
86box.cfg

Binary file not shown.

204
tracker/README.md Normal file
View file

@ -0,0 +1,204 @@
# CRTkafa @ cracktro 01 — native XM
`CRTkafa-cracktro-01.xm` is a native FastTracker II XM 1.04 arrangement, with
32 channels, 48 orders, and 48 distinct 32-row patterns. It preserves all
1,398 pitched score events and 779 drum hits, including the long solo and
the seven section boundaries. It contains 13 playable instruments and 14
individually synthesized mono samples, not a recorded full-song sample.
## Build and verify
Requirements: Python 3.10 or later, NumPy, and the existing adjacent score/source
files. FFmpeg with its `libopenmpt` demuxer is needed for decode verification.
The tools do not install dependencies, open windows, or play audio.
Run from the `cracktro` directory:
```powershell
python -B tracker/xm_build.py
python -B -m unittest discover -s tracker -p test_xm.py -v
python -B tracker/xm_verify.py --decode
```
Or, from this `tracker` directory:
```powershell
python -B xm_build.py
python -B -m unittest discover -s . -p test_xm.py -v
python -B xm_verify.py --decode
```
The builder writes only the XM and `build_report.json` under `tracker/`.
An alternate output can be selected with `--output tracker/alternate.xm` from
the parent directory; outputs outside `tracker/` are rejected. Verification
writes `verification.json` here. Its temporary seekable XM is also created here
and cleaned up after decoding. Decoded PCM goes to memory. `-B` avoids bytecode
cache writes; the source-import subprocess always disables bytecode writes too.
No existing demo, music, video, or publication file is modified.
Structural verification without FFmpeg:
```powershell
python -B tracker/xm_verify.py
```
Check the available decoder and inspect native metadata directly:
```powershell
ffmpeg -hide_banner -demuxers
ffprobe -v error -f libopenmpt -show_entries format=duration:format_tags -of json tracker/CRTkafa-cracktro-01.xm
ffmpeg -hide_banner -nostdin -f libopenmpt -sample_rate 44100 -i tracker/CRTkafa-cracktro-01.xm -f null -
```
## Native structure and naming
XM's fixed song-title field has only 20 bytes. The approved title in that field
is **CRTkafa cracktro 01** (19 ASCII characters, space-padded). Instrument 14 is
a sample-free metadata slot containing the exact full branding
**CRTkafa @ cracktro 01**. The README and build report retain that full text too.
There are no creator names, local machine paths, compressed sample extensions,
stereo-sample extensions, plugins, or appended non-XM chunks in the module.
Instruments 1–13 are lead, solo, harmony, bass, guitar, organ, pad, arp, bell,
kick, snare, hat, and crash. Instrument 14 holds the full title. Instruments
15–21 are sample-free section labels with zero-based order ranges. Bell uses
two pitch-specific samples so its two played pitches retain a four-second
sample duration; the other instruments each use one sample.
All samples are native signed 16-bit delta PCM. Sustained timbres use valid
forward loops and XM volume envelopes. Drums and bells are short synthesized
one-shots. Pitch, bass octave folding, pad inversions, organ chords, compound
drum triggers, and conditional bell/harmony attacks come from the verified
score. Guitar's root and fifth are separate notes; the sample does not add a
second power-chord fifth. The section labels also survive native playback as
instrument-name metadata.
## Mix and gain channels
The first decode was too quiet. The final native mix raises the original note
balance by approximately 7.6 dB while retaining section gains and fades. Sample
peaks use 92% of the signed PCM range. Note velocity still controls the level.
Native XM note volume stops at 64 and there is no portable module preamp field.
Lead, solo, harmony, bass, kick, snare, and crash therefore use phase-coherent
gain-partner channels. Each pair plays the same sample, pitch, panning, timing,
and key-off; the desired note level is split across two legal volume columns.
This is additive gain, not a new melody, echo, compressor, or external decoder
gain setting. Primary voices occupy channels 1–22; their gain partners use
channels 23–29. Channel 30 is spare; channels 31–32 carry global volume/tempo.
Numbers in Python's channel maps are zero-based.
The resulting file contains 3,750 native note-on cells, representing exactly
2,177 distinct instrument/pitch/time onsets: 1,398 musical notes plus 779 hits.
The additional 1,573 cells are the gain partners. Tests compare the primary
events to the score and independently verify that each partner matches its
primary, with every volume column in range.
## Timing and measured verification
The source grid is 5,000 samples per row at 44,100 Hz, or approximately
132.3 BPM with six ticks per row. Standard XM has integer BPM. Native `F84`
and `F85` commands alternate 132/133 BPM with error diffusion, rather than
letting a rounded constant BPM accumulate drift. `Gxx` controls the section
gain and fades; `8xx` sets panning; note 97 provides native key-off. No pattern
loops, jumps, delays, or format-specific playback extensions are used.
| Measurement | Result |
|---|---:|
| Source score duration | 174.149659864 s |
| XM tempo-derived duration | 174.149863295 s |
| Largest calculated row-boundary timing error | 0.421 ms |
| Full FFmpeg/libopenmpt decode, 44.1 kHz stereo | 7,680,324 frames / 174.157006803 s |
| Decoded sample peak | -2.925 dBFS |
| Decoded RMS | -19.643 dBFS |
| Decoded samples at or above full scale | 0 |
| Module size | 1,251,148 bytes |
The eleven automated tests cover native headers, order/pattern lengths, every
score note and drum hit, gain partners, key-offs, section timing, legal effects,
sample mappings, delta decoding, loop bounds/seams, pitch tuning, malformed-file
rejection, byte-identical rebuilding, and unchanged source hashes/timestamps.
Decoder tests render the entire file and an isolated concert-A tuning probe.
They enforce approximately -3 to -1 dBFS peak and -20 to -17 dBFS RMS for this
decoder configuration. The generated JSON reports contain exact values and
the module SHA-256. Decoder tests explicitly skip when libopenmpt is unavailable;
`xm_verify.py --decode` instead fails so a requested verification is not silently
omitted.
## Fidelity limits
This is an editable native-tracker reconstruction, not a bit-identical export
of the realtime DSP. Oscillator timbres, detune, filters, organ drawbars, and
drum synthesis are approximated with individual samples and native envelopes.
Transposing a sample changes its fixed spectral shape; realtime filter sweeps,
continuous oscillator phase across retriggers, FM brightness behavior, exact
sidechain pumping, delay, chorus, gated/hall reverb, risers, tape coloration,
and bus compression are not reproduced. No separate riser note is invented.
The visual score's conservative durations supply key-off positions. Decaying
instruments continue their native non-sustained envelope after key-off, while
held lead/bass/organ/pad envelopes release. Tracker tick-rate envelopes cannot
match the synth's sub-millisecond attack smoothing or exact gate curves. Note
replacement and three-note organ/pad channels can cut an outgoing release at
the next chord. Guitar double-taking and stereo effects are approximated by
panning and short sample detune, not an identical stereo signal.
The looped melodic samples' tuning quantization is about 0.303 cents flat;
the independent decoder tuning test confirms concert A within 0.5 Hz. The
row-clock bound is a mathematical tempo estimate, not a guarantee about every
player's tick rounding. Libopenmpt's reported container duration is about
174.122875 s; its actual decoded frame count above differs due to player timing
and end handling. Repeat settings can loop a module at its restart order;
the verified default decode plays one pass. Different players' interpolation,
mix gain, and ramping may change loudness or timbre. The standalone XM
reference render is decoder-based. The authentic companion
video described below uses the original DOS FastTracker II output instead.
## Authentic FastTracker II video capture
The rendered capture is published as video, not as a file in this
repository. What ships here is the module itself and the chain that builds
and checks it, so the result is reproducible rather than merely watchable.
The companion tracker video is captured from an emulated 486DX2/66 booting an
unmodified MS-DOS 6.22 system and running the original FastTracker II 2.08.
The boot disk is assembled by `prepare_dos622.py` from user-supplied DOS disk
images; Microsoft system files, 86Box, its ROM set, and FastTracker II are not
redistributed here.
`capture_native_86box.ps1` records one 86Box session as lossless window video
plus WASAPI loopback from the endpoint receiving 86Box's emulated Sound Blaster
16 output. The endpoint is muted only at the physical output while loopback is
active, then its prior mute state is restored. `render_86box_capture.ps1`
requires both files to come from that same session and refuses reference or
external soundtracks.
The renderer crops only the 640x400 emulated VGA framebuffer, makes short jump
cuts through the real BIOS/DOS/floppy boot, and ends before FastTracker returns
from order `2F` to `00`. Native pixels are enlarged 5x with nearest neighbour
and centred in a 3840x2160 4:4:4 master, so tracker text stays sharp. No DOSBox
or 86Box interface, host desktop, emulator branding, loop, generated overlay,
or re-created tracker UI appears in the result. The native SB16 capture gets
only fixed gain compensation and a short ending fade.
The verified capture uses raw interval 83.42–256.79 seconds from both streams;
the last cut frame still shows order `2F`, while the first observed restart to
`00` appears approximately at 256.84–256.85 seconds. The
result is 3840x2160 at 60 fps, 181.550 seconds long, and has SHA-256
`613CFFA42F68D2C02549110021BE92F04562501D997E9B53357F8B6B821EDD88`.
`capture_verification.json` records the machine-readable verification results.
Example:
```powershell
.\capture_native_86box.ps1
.\render_86box_capture.ps1 `
-Capture .\capture\86box-crtkafa-486\native-session-YYYYMMDD-HHMMSS\86box-window.mkv `
-TrackerAudio .\capture\86box-crtkafa-486\native-session-YYYYMMDD-HHMMSS\ft2-sb16.wav `
-Output .\CRTkafa-cracktro-01-fasttracker-authentic-4K.mp4
```
Format references: [XM 1.04 format specification](https://modland.com/pub/documents/format_documentation/FastTracker%202%20v2.04%20(.xm).html),
[OpenMPT native XM notes](https://wiki.openmpt.org/Development:_Formats/XM), and
[OpenMPT effect reference](https://wiki.openmpt.org/Manual:_Effect_Reference).

View file

@ -0,0 +1,80 @@
param(
[string]$OutputDevice = "Mi monitor",
[int]$CaptureSeconds = 340
)
$ErrorActionPreference = "Stop"
$trackerRoot = $PSScriptRoot
$vmRoot = Join-Path $trackerRoot "capture\86box-crtkafa-486"
$audioExe = Join-Path $trackerRoot "capture\audio-loopback\bin\Release\net9.0-windows\AudioLoopback.exe"
$boxExe = Join-Path $env:LOCALAPPDATA "CRTkafa\86Box-v6.0\86Box.exe"
$boxHome = Split-Path -Parent $boxExe
$boxRoms = Join-Path $boxHome "roms\roms-6.0"
$boxAssets = Join-Path $boxHome "assets"
if (@(Get-Process 86Box -ErrorAction SilentlyContinue).Count -ne 0) {
throw "Exactly one clean emulator session is required; 86Box is already running."
}
foreach ($required in @($audioExe, $boxExe, (Join-Path $vmRoot "86box.cfg"))) {
if (-not (Test-Path -LiteralPath $required -PathType Leaf)) {
throw "Required capture input is missing: $required"
}
}
if (-not (Get-Command ffmpeg.exe -ErrorAction SilentlyContinue)) {
throw "ffmpeg.exe is required."
}
$stamp = [DateTime]::UtcNow.ToString("yyyyMMdd-HHmmss")
$session = Join-Path $vmRoot ("native-session-" + $stamp)
New-Item -ItemType Directory -Path $session | Out-Null
$audioPath = Join-Path $session "ft2-sb16.wav"
$videoPath = Join-Path $session "86box-window.mkv"
$audioLog = Join-Path $session "audio.log"
$audioErr = Join-Path $session "audio.err.log"
$videoLog = Join-Path $session "video.log"
$videoErr = Join-Path $session "video.err.log"
# capture-muted preserves and restores the endpoint's prior mute state. WASAPI
# loopback still receives the samples, so the authentic guest mix is recorded
# without making the workstation audible.
$audio = Start-Process -FilePath $audioExe `
-ArgumentList @("capture-muted", ('"' + $OutputDevice + '"'), "$CaptureSeconds", ('"' + $audioPath + '"')) `
-RedirectStandardOutput $audioLog -RedirectStandardError $audioErr `
-WindowStyle Hidden -PassThru
Start-Sleep -Milliseconds 750
$box = Start-Process -FilePath $boxExe -WorkingDirectory $boxHome `
-ArgumentList @("-R", $boxRoms, "-A", $boxAssets, "-P", $vmRoot) -PassThru
$deadline = (Get-Date).AddSeconds(20)
do {
Start-Sleep -Milliseconds 200
$box.Refresh()
} while ([string]::IsNullOrWhiteSpace($box.MainWindowTitle) -and (Get-Date) -lt $deadline)
if ([string]::IsNullOrWhiteSpace($box.MainWindowTitle)) {
throw "86Box did not create a capturable window."
}
$windowTitle = $box.MainWindowTitle
$ffArgs = @(
"-hide_banner", "-nostdin", "-y",
"-f", "gdigrab", "-draw_mouse", "0", "-framerate", "60",
"-i", ('"title=' + $windowTitle + '"'), "-t", "$CaptureSeconds",
"-an", "-c:v", "ffv1", "-level", "3", "-g", "1", $videoPath
)
$video = Start-Process -FilePath "ffmpeg.exe" -ArgumentList $ffArgs `
-RedirectStandardOutput $videoLog -RedirectStandardError $videoErr `
-WindowStyle Hidden -PassThru
$manifest = [ordered]@{
session = $session
startedUtc = [DateTime]::UtcNow.ToString("o")
outputDevice = $OutputDevice
audioPid = $audio.Id
videoPid = $video.Id
vmPid = $box.Id
windowTitle = $windowTitle
audio = $audioPath
video = $videoPath
}
$manifest | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $session "session.json") -Encoding utf8
$manifest | ConvertTo-Json

View file

@ -0,0 +1,47 @@
{
"artifact": "CRTkafa-cracktro-01-fasttracker-authentic-4K.mp4",
"sha256": "613CFFA42F68D2C02549110021BE92F04562501D997E9B53357F8B6B821EDD88",
"bytes": 109497677,
"duration_seconds": 181.55,
"video": {
"codec": "h264",
"profile": "High 4:4:4 Predictive",
"width": 3840,
"height": 2160,
"pixel_format": "yuv444p",
"fps": 60
},
"audio": {
"source": "ft2-sb16.wav from the same 86Box session",
"codec": "aac",
"sample_rate": 48000,
"channels": 2,
"fixed_gain_db": 15,
"mean_dbfs": -21.3,
"peak_dbfs": -4.3,
"external_soundtrack": false
},
"timeline": {
"raw_song_start_seconds": 83.42,
"raw_song_end_seconds": 256.79,
"last_verified_pre_loop_seconds": 256.79,
"observed_loop_transition_window_seconds": [256.84, 256.85],
"last_visible_order": "2F",
"loop_visible": false
},
"verification": {
"xm_tests_passed": 11,
"full_video_audio_decode": "passed",
"sampled_frames": [
"BIOS",
"DOS branding",
"loaded song",
"mid-song",
"solo",
"final order",
"fade-out"
],
"host_or_emulator_chrome_visible": false,
"privacy_scan": "passed"
}
}

266
tracker/prepare_dos622.py Normal file
View file

@ -0,0 +1,266 @@
#!/usr/bin/env python3
"""Prepare disposable MS-DOS 6.22 boot/data floppies for the FT2 capture.
The source DOS images are never modified. A bootable copy of Disk1 is made
with a tiny AUTOEXEC.BAT, while FT2 and the native XM are placed on a separate
2.88 MB FAT12 disk so the tracker still runs entirely inside real MS-DOS.
"""
from __future__ import annotations
import argparse
import shutil
from pathlib import Path
from pyfatfs.PyFat import PyFat
from pyfatfs.PyFatFS import PyFatFS
BOOT_AUTOEXEC = (
b"@ECHO OFF\r\n"
b"PROMPT $P$G\r\n"
b"SET BLASTER=A220 I7 D1 H5 T6\r\n"
b"SET ULTRASND=240,3,3,5,5\r\n"
b"CLS\r\n"
b"ECHO CRTkafa @ cracktro 01\r\n"
b"ECHO.\r\n"
b"CHOICE /C:Y /N /T:Y,2 > NUL\r\n"
b"LH A:\\CTMOUSE.EXE\r\n"
b"B:\r\n"
b"FT2.EXE A:\\CRT01.XM\r\n"
)
SINGLE_AUTOEXEC = (
b"@ECHO OFF\r\n"
b"PROMPT $P$G\r\n"
b"SET BLASTER=A220 I7 D1 H5 T6\r\n"
b"CLS\r\n"
b"ECHO CRTkafa @ cracktro 01\r\n"
b"ECHO.\r\n"
b"CHOICE /C:Y /N /T:Y,2 > NUL\r\n"
b"LH A:\\CTMOUSE.EXE\r\n"
b"A:\r\n"
b"FT2.EXE A:\\CRT01.XM\r\n"
)
BOOT_CONFIG = (
b"DEVICE=A:\\HIMEM.SYS /TESTMEM:OFF\r\n"
b"DEVICE=A:\\EMM386.EXE RAM 4096\r\n"
b"DOS=HIGH,UMB\r\n"
b"FILES=30\r\n"
b"BUFFERS=20\r\n"
)
def write_file(fs: PyFatFS, dos_path: str, source: Path) -> None:
with source.open("rb") as src, fs.openbin(dos_path, "w") as dst:
shutil.copyfileobj(src, dst, length=1024 * 1024)
def write_ft2_config(fs: PyFatFS, source: Path) -> None:
"""Select SB16 in an original encrypted FT2.CFG without touching source."""
encrypted = bytearray(source.read_bytes())
if len(encrypted) != 1736:
raise ValueError(f"Unexpected FT2.CFG size: {len(encrypted)}")
plain = bytearray(value ^ ((index * 7) & 0xFF) for index, value in enumerate(encrypted))
if plain[:35] != b"FastTracker 2.0 configuration file\x1a":
raise ValueError("FT2.CFG signature mismatch")
# Original packed FT2 config layout: output device 2 is Sound Blaster
# (1 is the parallel-port Soundplayer). Port 0x220, low DMA 1,
# high DMA 5 and IRQ 7 match the emulated SB16.
plain[41:43] = (2).to_bytes(2, "little", signed=True) # utEnhet
plain[49] = 1 # interpolation
plain[51] = 1 # stereo
plain[56:58] = (0x220).to_bytes(2, "little", signed=True)
plain[58:60] = (1).to_bytes(2, "little", signed=True)
plain[60:62] = (5).to_bytes(2, "little", signed=True)
plain[62:64] = (7).to_bytes(2, "little", signed=True)
plain[66] = 1 # 16-bit mixing
patched = bytes(value ^ ((index * 7) & 0xFF) for index, value in enumerate(plain))
fs.writebytes("/FT2.CFG", patched)
def make_combined_boot_disk(
output: Path,
disk1: Path,
disk2: Path,
ft2: Path,
ft2_config: Path,
xm: Path,
himem: Path,
emm386: Path,
ctmouse: Path,
) -> None:
"""Build one bootable 2.88 MB MS-DOS/FT2 disk for a physical-PC VM."""
if output.exists():
output.unlink()
output.touch()
fat = PyFat()
fat.mkfs(
str(output),
fat_type=PyFat.FAT_TYPE_FAT12,
size=2_949_120,
sector_size=512,
number_of_fats=2,
label="CRTKAFATRK",
volume_id=0x43525431,
media_type=0xF0,
)
fat.close()
# Keep the generated 2.88 MB BPB, but transplant Microsoft's boot jump,
# OEM tag and bootstrap from the original MS-DOS 6.22 Disk 1 sector.
source_boot = disk1.read_bytes()[:512]
with output.open("r+b") as raw:
target_boot = bytearray(raw.read(512))
target_boot[:11] = source_boot[:11]
target_boot[0x3E:512] = source_boot[0x3E:512]
target_boot[0x18:0x1A] = (36).to_bytes(2, "little")
target_boot[0x1A:0x1C] = (2).to_bytes(2, "little")
raw.seek(0)
raw.write(target_boot)
with (
PyFatFS(str(disk1), read_only=True) as dos_fs,
PyFatFS(str(disk2), read_only=True) as tools_fs,
PyFatFS(str(output), read_only=False) as out_fs,
):
# MS-DOS expects these two files first in the root directory.
out_fs.writebytes("/IO.SYS", dos_fs.readbytes("/IO.SYS"))
out_fs.writebytes("/MSDOS.SYS", dos_fs.readbytes("/MSDOS.SYS"))
out_fs.writebytes("/COMMAND.COM", dos_fs.readbytes("/COMMAND.COM"))
out_fs.writebytes("/CHOICE.COM", tools_fs.readbytes("/CHOICE.COM"))
out_fs.writebytes("/AUTOEXEC.BAT", SINGLE_AUTOEXEC)
out_fs.writebytes("/CONFIG.SYS", BOOT_CONFIG)
write_file(out_fs, "/HIMEM.SYS", himem)
write_file(out_fs, "/EMM386.EXE", emm386)
write_file(out_fs, "/CTMOUSE.EXE", ctmouse)
write_file(out_fs, "/FT2.EXE", ft2)
write_ft2_config(out_fs, ft2_config)
write_file(out_fs, "/CRT01.XM", xm)
# DOS 6.x's floppy bootstrap does not scan an arbitrary FAT12 root: it
# expects IO.SYS and MSDOS.SYS in the first two physical directory slots.
# pyfatfs puts the volume label first, so move that entry behind the files.
with output.open("r+b") as raw:
boot = raw.read(512)
reserved = int.from_bytes(boot[0x0E:0x10], "little")
fats = boot[0x10]
sectors_per_fat = int.from_bytes(boot[0x16:0x18], "little")
root_entries = int.from_bytes(boot[0x11:0x13], "little")
root_offset = (reserved + fats * sectors_per_fat) * 512
raw.seek(root_offset)
root = bytearray(raw.read(root_entries * 32))
used = 0
while used < root_entries and root[used * 32] not in (0x00, 0xE5):
used += 1
label = bytes(root[:32])
root[: used * 32] = root[32 : (used + 1) * 32]
root[(used - 1) * 32 : used * 32] = label
root[11] = 0x21 # IO.SYS: read-only + archive, as on Disk 1
root[32 + 11] = 0x21 # MSDOS.SYS
raw.seek(root_offset)
raw.write(root)
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--dos-root", type=Path, required=True)
parser.add_argument("--ft2", type=Path, required=True)
parser.add_argument("--ft2-config", type=Path)
parser.add_argument("--xm", type=Path, required=True)
parser.add_argument("--himem", type=Path, required=True)
parser.add_argument("--emm386", type=Path, required=True)
parser.add_argument("--ctmouse", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
disk1 = args.dos_root / "Disk1.img"
disk2 = args.dos_root / "Disk2.img"
ft2_config = args.ft2_config or (args.ft2.parent / "FT2.CFG")
for path in (disk1, disk2, args.ft2, ft2_config, args.xm, args.himem, args.emm386, args.ctmouse):
if not path.is_file():
raise FileNotFoundError(path)
args.output.mkdir(parents=True, exist_ok=True)
boot_img = args.output / "BOOT622.IMG"
data_img = args.output / "FT2DATA.IMG"
combined_img = args.output / "CRTK486.IMG"
shutil.copyfile(disk1, boot_img)
with PyFatFS(str(boot_img), read_only=False) as boot_fs:
keep = {
"IO.SYS", "MSDOS.SYS", "COMMAND.COM",
"AUTOEXEC.BAT", "CONFIG.SYS",
}
for name in boot_fs.listdir("/"):
if name.upper() not in keep:
boot_fs.remove("/" + name)
boot_fs.writebytes("/AUTOEXEC.BAT", BOOT_AUTOEXEC)
boot_fs.writebytes("/CONFIG.SYS", BOOT_CONFIG)
write_file(boot_fs, "/HIMEM.SYS", args.himem)
write_file(boot_fs, "/EMM386.EXE", args.emm386)
write_file(boot_fs, "/CTMOUSE.EXE", args.ctmouse)
with PyFatFS(str(disk2), read_only=True) as disk2_fs:
boot_fs.writebytes("/CHOICE.COM", disk2_fs.readbytes("/CHOICE.COM"))
if data_img.exists():
data_img.unlink()
data_img.touch()
fat = PyFat()
fat.mkfs(
str(data_img),
fat_type=PyFat.FAT_TYPE_FAT12,
size=2_949_120,
sector_size=512,
number_of_fats=2,
label="CRTKAFATRK",
volume_id=0x43525431,
media_type=0xF0,
)
fat.close()
# pyfatfs 1.1 leaves the FAT12 BPB geometry fields at zero. MS-DOS can
# still enumerate the disk, but period software (including FT2) divides by
# sectors-per-track while calculating free space. A 2.88 MB ED floppy is
# 80 cylinders, 2 heads, 36 sectors per track.
with data_img.open("r+b") as raw:
raw.seek(0x18)
raw.write((36).to_bytes(2, "little"))
raw.write((2).to_bytes(2, "little"))
with PyFatFS(str(data_img), read_only=False) as data_fs:
write_file(data_fs, "/FT2.EXE", args.ft2)
write_ft2_config(data_fs, ft2_config)
write_file(data_fs, "/CRT01.XM", args.xm)
make_combined_boot_disk(
combined_img, disk1, disk2, args.ft2, ft2_config, args.xm,
args.himem, args.emm386, args.ctmouse,
)
with PyFatFS(str(boot_img), read_only=True) as boot_fs:
assert boot_fs.readbytes("/AUTOEXEC.BAT") == BOOT_AUTOEXEC
assert boot_fs.readbytes("/CONFIG.SYS") == BOOT_CONFIG
assert boot_fs.getsize("/HIMEM.SYS") == args.himem.stat().st_size
assert boot_fs.getsize("/EMM386.EXE") == args.emm386.stat().st_size
assert boot_fs.getsize("/CTMOUSE.EXE") == args.ctmouse.stat().st_size
with PyFatFS(str(data_img), read_only=True) as data_fs:
assert data_fs.getsize("/FT2.EXE") == args.ft2.stat().st_size
assert data_fs.getsize("/FT2.CFG") == 1736
assert data_fs.getsize("/CRT01.XM") == args.xm.stat().st_size
with PyFatFS(str(combined_img), read_only=True) as combined_fs:
assert combined_fs.readbytes("/AUTOEXEC.BAT") == SINGLE_AUTOEXEC
assert combined_fs.getsize("/FT2.EXE") == args.ft2.stat().st_size
assert combined_fs.getsize("/CRT01.XM") == args.xm.stat().st_size
print(boot_img)
print(data_img)
print(combined_img)
return 0
if __name__ == "__main__":
raise SystemExit(main())

View file

@ -0,0 +1,83 @@
param(
[Parameter(Mandatory = $true)]
[string]$Capture,
[Parameter(Mandatory = $true)]
[string]$TrackerAudio,
[double]$SongStart = 83.42,
[double]$SongEnd = 256.79,
[string]$Output = ".\CRTkafa-cracktro-01-fasttracker-authentic-4K.mp4"
)
$ErrorActionPreference = "Stop"
foreach ($inputPath in @($Capture, $TrackerAudio)) {
if (-not (Test-Path -LiteralPath $inputPath -PathType Leaf)) {
throw "Capture input not found: $inputPath"
}
}
if (-not (Get-Command ffmpeg.exe -ErrorAction SilentlyContinue)) {
throw "ffmpeg.exe is required."
}
if ($SongStart -lt 0 -or $SongEnd -le $SongStart) {
throw "Invalid song boundaries."
}
$capturePath = (Resolve-Path -LiteralPath $Capture).Path
$audioPath = (Resolve-Path -LiteralPath $TrackerAudio).Path
$captureDir = Split-Path -Parent $capturePath
$audioDir = Split-Path -Parent $audioPath
if ($captureDir -ne $audioDir) {
throw "Video and audio must come from the same native 86Box capture session."
}
if ([System.IO.Path]::GetFileName($audioPath) -ne "ft2-sb16.wav") {
throw "Expected the native session file ft2-sb16.wav; external/reference audio is forbidden."
}
$outputPath = [System.IO.Path]::GetFullPath($Output)
# Five fast authentic cuts establish the physical-PC context without forcing
# viewers through the complete floppy boot. The final segment is the exact
# interval measured in both the scrolling FT2 rows and its captured SB16 audio.
$bootDuration = 8.2
$songDuration = $SongEnd - $SongStart
$fadeOutAt = $songDuration - 0.8
$finalFadeAt = $bootDuration + $songDuration - 0.6
$filter = @"
[0:v]crop=640:400:0:60,split=6[b0][b1][b2][b3][b4][song];
[b0]trim=start=2.1:end=4.2,setpts=PTS-STARTPTS[s0];
[b1]trim=start=4.9:end=6.0,setpts=PTS-STARTPTS[s1];
[b2]trim=start=7.7:end=9.0,setpts=PTS-STARTPTS[s2];
[b3]trim=start=16.0:end=17.4,setpts=PTS-STARTPTS[s3];
[b4]trim=start=80.0:end=82.3,setpts=PTS-STARTPTS[s4];
[song]trim=start=${SongStart}:end=${SongEnd},setpts=PTS-STARTPTS[s5];
[s0][s1][s2][s3][s4][s5]concat=n=6:v=1:a=0,
fps=60,scale=3200:2000:flags=neighbor,
pad=3840:2160:320:80:black,
fade=t=in:st=0:d=0.15,
fade=t=out:st=${finalFadeAt}:d=0.60,
format=yuv444p[v];
[1:a]atrim=start=${SongStart}:end=${SongEnd},asetpts=PTS-STARTPTS,
volume=15dB,
afade=t=in:st=0:d=0.03,afade=t=out:st=${fadeOutAt}:d=0.80[songa];
anullsrc=channel_layout=stereo:sample_rate=48000:d=$bootDuration[silence];
[silence][songa]concat=n=2:v=0:a=1,apad=pad_dur=0.05[a]
"@ -replace "`r?`n", ""
& ffmpeg.exe -hide_banner -nostdin -y `
-i $capturePath -i $audioPath `
-filter_complex $filter `
-map "[v]" -map "[a]" `
-c:v libx264 -preset slow -crf 10 -profile:v high444 `
-color_primaries bt709 -color_trc bt709 -colorspace bt709 `
-c:a aac -b:a 320k -ar 48000 `
-metadata title="CRTkafa @ cracktro 01 - FastTracker II" `
-metadata comment="Native FastTracker II 2.08 / Sound Blaster 16 capture" `
-movflags +faststart -shortest $outputPath
if ($LASTEXITCODE -ne 0) {
throw "ffmpeg failed with exit code $LASTEXITCODE"
}
Get-Item -LiteralPath $outputPath

216
tracker/test_xm.py Normal file
View file

@ -0,0 +1,216 @@
"""Structural, score-equivalence, synthesis and independent-decoder checks.
python -B -m unittest discover -s tracker -p test_xm.py -v
"""
from collections import Counter
import hashlib
import math
from pathlib import Path
import shutil
import struct
import subprocess
import unittest
import numpy as np
if __package__:
from . import xm_build as B, xm_verify as V
else:
import xm_build as B
import xm_verify as V
class XmTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.data = B.OUTPUT.read_bytes()
cls.parsed = V.parse_xm(cls.data)
cls.score,cls.gains = B.load_source()
def test_native_header_title_and_metadata_limit(self):
p = self.parsed
self.assertEqual(p["title"],"CRTkafa cracktro 01")
self.assertEqual(len(B.FULL_TITLE.encode("ascii")),21)
with self.assertRaisesRegex(ValueError,"exceeds 20"):
B.field(B.FULL_TITLE,20)
self.assertEqual(p["instruments"][13]["name"],"CRTkafa @ cracktro 01")
self.assertEqual(p["tracker"],"CRTkafa XM Export")
self.assertEqual(p["channels"],32)
self.assertEqual(p["orders"],list(range(48)))
self.assertEqual([len(pattern) for pattern in p["patterns"]],[32]*48)
self.assertEqual(p["speed"],6)
self.assertEqual(p["bpm"],132)
self.assertEqual([i["name"] for i in p["instruments"][:13]],list(B.TRACKS))
self.assertTrue(all(not i["samples"] for i in p["instruments"][13:]))
def test_all_score_notes_and_hits_survive_without_new_attacks(self):
actual = Counter()
for order in self.parsed["orders"]:
for row,cells in enumerate(self.parsed["patterns"][order]):
for channel,(note,ins,vol,effect,param) in enumerate(cells):
if channel in B.GAIN_PARTNERS.values():
continue
if 1 <= note <= 96:
track = self.parsed["instruments"][int(ins)-1]["name"]
actual[(order*32+row,track,int(note)+11)] += 1
expected = Counter((round(n["start"]/self.score["row_seconds"]),n["track"],n["pitch"])
for n in self.score["notes"])
expected.update((round(n["start"]/self.score["row_seconds"]),n["track"],60)
for n in self.score["drums"])
self.assertEqual(actual,expected)
self.assertEqual(sum(actual.values()),1398+779)
self.assertEqual(self.parsed["note_count"],3750)
self.assertEqual(self.parsed["distinct_instrument_note_onsets"],2177)
def test_gain_partners_preserve_notes_pan_envelopes_and_valid_volume(self):
cells = np.concatenate(self.parsed["patterns"])
for track,partner in B.GAIN_PARTNERS.items():
primary = B.POOLS[track][0]
np.testing.assert_array_equal(cells[:,primary,[0,1,3,4]],cells[:,partner,[0,1,3,4]])
for row in range(1536):
if cells[row,primary,0] in range(1,97):
a,b = map(int,(cells[row,primary,2],cells[row,partner,2]))
self.assertTrue(0x10 <= a <= 0x50 and 0x10 <= b <= 0x50)
self.assertLessEqual(abs(a-b),1)
def test_no_keyoff_overwrites_restrike_and_gates_have_channels(self):
_,assigned,_ = B.make_patterns(self.score,self.gains)
cells = np.concatenate(self.parsed["patterns"])
notes = {(n["row"],n["channel"]) for n in assigned}
for event in assigned:
row,end,channel = event["row"],event["end"],event["channel"]
self.assertIn(channel,B.POOLS[event["track"]])
self.assertEqual(int(cells[row,channel,0]),event["pitch"]-11)
if event["track"] not in ("kick","snare","hat","crash") and end < 1536:
if (end,channel) not in notes:
self.assertEqual(int(cells[end,channel,0]),97)
self.assertEqual(len(notes),2177)
def test_timing_section_positions_and_effects(self):
p = self.parsed
errors = [abs(t-i*self.score["row_seconds"]) for i,t in enumerate(p["row_times"])]
self.assertLess(max(errors),.00043)
self.assertLess(abs(p["duration_seconds"]-self.score["duration"]),.0003)
self.assertEqual(len(p["row_times"]),1537)
cells = np.concatenate(p["patterns"])
self.assertEqual(set(map(int,cells[:,31,4])),{132,133})
self.assertTrue(np.all(cells[:,31,3] == 0x0F))
self.assertTrue(np.all(cells[:,30,3] == 0x10))
self.assertEqual(cells[-1,30,4],0)
for index,section in enumerate(self.score["sections"]):
first = round(section["start"]/(32*self.score["row_seconds"]))
last = round(section["end"]/(32*self.score["row_seconds"]))-1
self.assertEqual(p["instruments"][14+index]["name"],f"{section['name']} {first:02}-{last:02}")
self.assertLess(abs(p["row_times"][first*32]-section["start"]),.00043)
def test_sample_delta_decode_loops_and_synthesis_are_real(self):
samples = [s for i in self.parsed["instruments"] for s in i["samples"]]
self.assertEqual(len(samples),14)
hashes = set()
for sample in samples:
data = sample["pcm"]
self.assertEqual(len(data)*2,sample["bytes"])
self.assertLessEqual(len(data),B.SAMPLE_RATE*4)
self.assertGreater(np.std(data.astype(float)),10)
self.assertLess(np.max(np.abs(data.astype(np.int32))),30500)
self.assertLess(abs(np.mean(data)),20)
hashes.add(hashlib.sha256(data.tobytes()).hexdigest())
if sample["loop_length"]:
a = sample["loop_start"]
end = a+sample["loop_length"]
self.assertLessEqual(end,len(data))
# A loop seam must be no worse than an ordinary sample step.
self.assertLessEqual(abs(int(data[a])-int(data[end-1])),
int(np.max(np.abs(np.diff(data.astype(np.int32)))))+2)
else:
self.assertEqual(int(data[0]),0)
self.assertEqual(int(data[-1]),0)
self.assertEqual(len(hashes),14)
original = np.array([0,32767,-32768,-1,15000,-20000,0],dtype=np.int16)
encoded = np.frombuffer(B.delta_encode(original),dtype="<i2")
decoded = ((np.cumsum(encoded,dtype=np.int64)+32768)%65536-32768).astype(np.int16)
np.testing.assert_array_equal(decoded,original)
def test_pitch_tuning_and_bell_multisample_duration(self):
for index in range(8):
sample = self.parsed["instruments"][index]["samples"][0]
readerate = 8363*2**((sample["relative"]+sample["finetune"]/128)/12)
pitch = readerate/128
error_cents = 1200*math.log2(pitch/(440*2**(-9/12)))
self.assertLess(abs(error_cents),.304)
bell = self.parsed["instruments"][8]
for midi in (79,81):
sample = bell["samples"][bell["mapping"][midi-12]]
readerate = 8363*2**((midi-12+sample["relative"]-48)/12)
self.assertEqual(readerate,33452)
self.assertAlmostEqual(len(sample["pcm"])/readerate,4.0)
def test_parser_rejects_truncation_bad_orders_and_stereo_extensions(self):
for data in (self.data[:80],self.data[:-1]):
with self.assertRaises(ValueError):
V.parse_xm(data)
bad = bytearray(self.data)
bad[80] = 250
with self.assertRaisesRegex(ValueError,"order reference"):
V.parse_xm(bad)
first_instrument = 336
for _ in range(48):
header,_,_,size = struct.unpack_from("<IBHH",self.data,first_instrument)
first_instrument += header+size
bad = bytearray(self.data)
bad[first_instrument+263+14] |= 0x20
with self.assertRaisesRegex(ValueError,"native mono"):
V.parse_xm(bad)
bad = bytearray(self.data)
struct.pack_into("<I",bad,first_instrument+263+8,0xFFFFFFFE)
with self.assertRaisesRegex(ValueError,"loop extent"):
V.parse_xm(bad)
def test_rebuild_is_identical_and_sources_remain_unchanged(self):
paths = [B.ROOT/name for name in ("song_data.h","synth.h","voices.h",
"visualizer/score.py","tools/arrange_v11.py")]
before = {p:(p.stat().st_mtime_ns,hashlib.sha256(p.read_bytes()).hexdigest()) for p in paths}
regenerated,_ = B.make_module(*B.load_source())
self.assertEqual(regenerated,self.data)
after = {p:(p.stat().st_mtime_ns,hashlib.sha256(p.read_bytes()).hexdigest()) for p in paths}
self.assertEqual(before,after)
@unittest.skipUnless(shutil.which("ffmpeg"),"FFmpeg unavailable; structural checks still run")
class DecoderTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
demuxers = subprocess.run(["ffmpeg","-hide_banner","-demuxers"],
capture_output=True,text=True,check=True)
if "libopenmpt" not in demuxers.stdout:
raise unittest.SkipTest("FFmpeg was built without libopenmpt")
cls.data = B.OUTPUT.read_bytes()
def test_full_decode_is_non_silent_finite_unclipped_and_correct_length(self):
report = V.summary(self.data,decoded=True)
decode = report["decode"]
self.assertEqual(decode["full_scale_samples"],0)
self.assertLess(abs(decode["seconds"]-report["duration_seconds"]),.15)
self.assertTrue(-20 <= decode["rms_dbfs"] <= -17)
self.assertTrue(-3 <= decode["peak_dbfs"] <= -1)
self.assertTrue(all(value > -60 for value in decode["order_rms_dbfs"]))
def test_decoder_concert_pitch_440hz_not_an_octave_off(self):
# Replace only pattern 0 in memory with a sustained A4 lead, unity
# global volume, and 132 BPM. The sample itself is the delivered one.
cells = np.zeros((32,32,5),dtype=np.uint8)
cells[0,0] = (69-11,1,0x50,8,128)
cells[0,30,3:] = (0x10,64)
cells[0,31,3:] = (0x0F,132)
pattern = struct.pack("<IBHH",9,0,32,cells.size)+cells.tobytes()
_,_,_,old_size = struct.unpack_from("<IBHH",self.data,336)
data = self.data[:336]+pattern+self.data[336+9+old_size:]
pcm = V.decode_pcm(data,1.0)
signal = pcm[11025:41895].mean(axis=1)
fft = np.abs(np.fft.rfft(signal*np.hanning(len(signal)),n=262144))
frequency = np.fft.rfftfreq(262144,1/44100)[np.argmax(fft)]
self.assertLess(abs(frequency-440),.5)
if __name__ == "__main__":
unittest.main()

406
tracker/xm_build.py Normal file
View file

@ -0,0 +1,406 @@
"""Native XM 1.04 export; all output is confined to this tracker directory.
No media is read and no song-length sample is created. The score is obtained
read-only from visualizer/score.py, which verifies the bake against the arranger.
Run with -B to suppress Python bytecode writes outside this directory.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import math
from pathlib import Path
import re
import struct
import subprocess
import sys
import numpy as np
HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
FULL_TITLE = "CRTkafa @ cracktro 01" # 21 bytes: cannot fit a native XM title.
TITLE = "CRTkafa cracktro 01" # Native header; full text in instrument 14.
TRACKER = "CRTkafa XM Export"
OUTPUT = HERE / "CRTkafa-cracktro-01.xm"
CHANNELS, ROWS, ORDERS, SPEED = 32, 32, 48, 6
SAMPLE_RATE = 33452 # XM C-4 rate 8363 * 4 (relative note +24)
PERIOD = 128
# +2/128 semitones brings 33452/128 within 0.304 cents of concert C4.
TUNE = 2
TRACKS = ("lead", "solo", "harmony", "bass", "guitar", "organ", "pad", "arp",
"bell", "kick", "snare", "hat", "crash")
INSTRUMENT = {track: i+1 for i, track in enumerate(TRACKS)}
POOLS = {"lead": [0], "solo": [1], "harmony": [2], "bass": [3],
"guitar": [4,5,6,7], "organ": [8,9,10],
"pad": [11,12,13], "arp": [14,15,16], "bell": [17],
"kick": [18], "snare": [19], "hat": [20], "crash": [21]}
# Native XM has no per-module preamp and note volume cannot exceed 64.
# Phase-coherent gain partners extend seven loud voices to 128 without adding
# new pitches, sample content, delays, plugins, or nonstandard format fields.
GAIN_PARTNERS = {"lead":22,"solo":23,"harmony":24,"bass":25,
"kick":26,"snare":27,"crash":28}
BASE_LEVELS = dict(zip(TRACKS, (30,42,28,38,24,16,15,24,24,56,44,24,32)))
LEVELS = {track: level*2.3 for track,level in BASE_LEVELS.items()}
PAN = {"lead": [100], "solo": [128], "harmony": [160], "bass": [128],
"guitar": [36,220,36,220], "organ": [100,128,156],
"pad": [36,128,220], "arp": [76,104,76], "bell": [76],
"kick": [128], "snare": [124], "hat": [152], "crash": [164]}
# Native XM envelopes: (tick, volume), sustain-point index or None, fadeout.
# Non-sustained decay voices continue their envelope after score key-off.
ENVELOPES = {
"lead": ([(0,64),(6,50),(12,35),(16,0)], 2, 0),
"solo": ([(0,64),(1,56),(3,44),(6,30),(12,14),(18,7),(24,3),(36,0)], None, 0),
"harmony": ([(0,64),(1,56),(3,44),(6,30),(12,14),(18,7),(24,3),(36,0)], None, 0),
"bass": ([(0,32),(1,64),(8,45),(24,29),(30,0)], 3, 0),
"guitar": ([(0,64),(6,29),(12,13),(18,6),(24,3),(36,0)], None, 0),
"organ": ([(0,0),(1,64),(2,64),(7,0)], 2, 0),
"pad": ([(0,0),(6,18),(14,36),(28,56),(44,64),(65,0)], 4, 0),
"arp": ([(0,64),(3,42),(6,26),(12,11),(18,4),(28,0)], None, 0),
"bell": ([(0,64),(255,64),(256,0)], None, 0),
"kick": ([(0,64),(60,64),(61,0)], None, 0),
"snare": ([(0,64),(60,64),(61,0)], None, 0),
"hat": ([(0,64),(30,64),(31,0)], None, 0),
"crash": ([(0,64),(120,64),(121,0)], None, 0),
}
def field(text, length):
data = text.encode("ascii")
if len(data) > length:
raise ValueError(f"XM text exceeds {length} bytes: {text!r}")
return data.ljust(length, b" ")
def load_source():
# Child process isolates imports and disables all source-tree pyc writes.
code = ("import sys,json;sys.path.insert(0,sys.argv[1]);"
"from visualizer.score import build_score;print(json.dumps(build_score()))")
proc = subprocess.run([sys.executable,"-I","-B","-c",code,str(ROOT)],
check=True, capture_output=True, text=True)
score = json.loads(proc.stdout)
source = (ROOT / "song_data.h").read_text(encoding="utf-8")
match = re.search(r"g_sqGain\[\]\s*=\s*\{(.*?)\};", source, re.S)
if not match:
raise ValueError("Missing baked gain lane")
gains = list(map(int,re.findall(r"-?\d+",match[1])))
if len(gains) != ORDERS or score["bars"] != 96:
raise ValueError("This export expects the current 48-order score")
return score, gains
def timing(row_seconds, count=ROWS*ORDERS):
"""Error-diffuse adjacent integer BPMs; bound cumulative row-clock error."""
bpm = SPEED * 2.5 / row_seconds
low, high = math.floor(bpm), math.ceil(bpm)
if low < 32 or high > 255:
raise ValueError("Tempo is outside native Fxx BPM range")
elapsed, bpms, starts = 0.0, [], [0.0]
for row in range(count):
chosen = min((low,high), key=lambda b: abs(elapsed+SPEED*2.5/b-(row+1)*row_seconds))
elapsed += SPEED*2.5/chosen
bpms.append(chosen)
starts.append(elapsed)
return bpms, starts
def row_index(seconds, row_seconds):
value = seconds / row_seconds
row = round(value)
if abs(value-row) > 1e-7:
raise ValueError("Off-row note requires explicit tick-effect support")
return row
def make_patterns(score, gains):
count = ROWS*ORDERS
cells = np.zeros((count,CHANNELS,5), dtype=np.uint8)
used_until = {channel: -1 for pool in POOLS.values() for channel in pool}
cursor = {track: 0 for track in TRACKS}
scheduled_offs = {}
assigned = []
events = [dict(n) for n in score["notes"]]
# Percussion one-shots own a channel until the next strike; no fake notes
# for a gated snare tail, ducking, or delay repetitions.
events += [dict(n,pitch=60,end=None) for n in score["drums"]]
events.sort(key=lambda n:(n["start"],n["track"],n["pitch"]))
for note in events:
track = note["track"]
row = row_index(note["start"], score["row_seconds"])
end = row_index(note["end"],score["row_seconds"]) if note["end"] is not None else row+1
if not 0 <= row < end <= count:
raise ValueError(f"Invalid note interval: {track}, {row}, {end}")
pool = POOLS[track]
choices = pool[cursor[track]:] + pool[:cursor[track]]
free = [ch for ch in choices if used_until[ch] <= row]
if not free:
raise ValueError(f"Channel allocation would drop a {track} note at row {row}")
channel = free[0]
cursor[track] = (pool.index(channel)+1) % len(pool)
# XM C-0 is note 1 and MIDI 12, so MIDI pitch -11 is the file note.
pitch = note["pitch"] - 11
if not 1 <= pitch <= 96:
raise ValueError(f"Pitch outside XM's C-0..B-7: {note['pitch']}")
total_volume = max(1,min(128 if track in GAIN_PARTNERS else 64,
round(LEVELS[track]*note["velocity"])))
volume = (total_volume+1)//2 if track in GAIN_PARTNERS else total_volume
cells[row,channel] = (pitch,INSTRUMENT[track],0x10+volume,8,PAN[track][pool.index(channel)])
if track in GAIN_PARTNERS:
partner = GAIN_PARTNERS[track]
cells[row,partner] = cells[row,channel]
cells[row,partner,2] = 0x10+total_volume//2
used_until[channel] = end
if note["end"] is not None and end < count:
scheduled_offs[(end,channel)] = True
if track in GAIN_PARTNERS:
scheduled_offs[(end,GAIN_PARTNERS[track])] = True
assigned.append(dict(track=track,pitch=note["pitch"],row=row,end=end,channel=channel))
for (row,channel) in scheduled_offs:
# A new strike on this very row supersedes key-off, as it does in the
# source synth. Never allow an old note-off to overwrite a new note.
if cells[row,channel,0] == 0:
cells[row,channel,0] = 97
bpms, starts = timing(score["row_seconds"])
smoothed = 1.0
for row in range(count):
cells[row,31,3:] = (0x0F,bpms[row])
want = gains[row//ROWS]/1024.0
# Sample-domain section glide, represented at row centers as native
# Gxx volume. No compressor/tape/reverb emulation is claimed.
half = want + (smoothed-want)*(1-0.00006)**2500
smoothed = want + (smoothed-want)*(1-0.00006)**5000
t = (row+0.5)*score["row_seconds"]
fade = min(1.0,t/3.0)**2
if t > score["duration"]-1.8:
f = max(0.0,(score["duration"]-t)/1.8)
fade *= f*f*(3-2*f)
global_volume = max(0,min(64,round(64*half/max(gains)*1024*fade)))
cells[row,30,3:] = (0x10,global_volume)
patterns = []
for order in range(ORDERS):
packed = bytearray()
for cell in cells[order*ROWS:(order+1)*ROWS].reshape(-1,5):
mask, values = 0x80, bytearray()
for bit,value in enumerate(cell):
if value:
mask |= 1 << bit
values.append(int(value))
packed.append(mask)
packed.extend(values)
patterns.append(struct.pack("<IBHH",9,0,ROWS,len(packed))+packed)
return patterns, assigned, starts
def saw(phase, harmonics=24):
"""Finite harmonic series: bounded-bandwidth saw at the sample base pitch."""
out = np.zeros_like(phase)
for harmonic in range(1,harmonics+1):
out -= np.sin(2*np.pi*harmonic*phase)/harmonic
return out * (2/np.pi)
def lowpass(values, coefficient):
out = np.empty(len(values),dtype=np.float64)
state = 0.0
for i,value in enumerate(values):
state += (value-state)*coefficient
out[i] = state
return out
def periodic_lowpass(values, coefficient, passes=12):
"""One-pole filter in periodic steady state, suitable for an XM loop."""
values = np.asarray(values,dtype=np.float64)
state = 0.0
out = np.empty_like(values)
for _ in range(passes):
for i,value in enumerate(values):
state += (value-state)*coefficient
out[i] = state
return out
def soft_clip(values):
"""The same no-CRT rational saturator used by the realtime C synth."""
x = np.clip(np.asarray(values,dtype=np.float64),-3.0,3.0)
return x*(27.0+x*x)/(27.0+9.0*x*x)
def pcm(values, loop=False):
values = np.asarray(values,dtype=np.float64)
values -= np.mean(values)
peak = float(np.max(np.abs(values)))
if not peak or not np.all(np.isfinite(values)):
raise ValueError("Invalid synthesized sample")
values *= 0.926/peak
if not loop:
# Tiny onset ramp, then a true zero endpoint for one-shots.
attack = min(24,len(values)//8)
release = min(int(SAMPLE_RATE*.02),len(values)//8)
values[:attack] *= np.linspace(0,1,attack)
values[-release:] *= np.linspace(1,0,release)
return np.rint(values*32767).astype("<i2")
def melodic_sample(track):
length = PERIOD if track in ("lead","bass") else PERIOD*256
if track == "organ":
length *= 2
index = np.arange(length,dtype=np.float64)
phase = index/PERIOD
if track == "lead":
# pulseWave() in synth.h is intentionally a raw 50% pulse. Retaining
# its hard edge (rather than replacing it with an ideal Fourier square)
# is part of the audible chip lead.
values = np.where((phase % 1.0) < .5,1.0,-1.0)
elif track in ("solo","harmony","guitar"):
# Raw detuned saws -> fixed drive -> cabinet filter, in the same order
# as the C path. One extra cycle closes the detuned loop exactly.
a = (phase % 1.0)*2.0-1.0
b = ((phase+index/length) % 1.0)*2.0-1.0
raw = (a+b)*.5
drive = {"solo":9.0,"harmony":8.0,"guitar":7.5}[track]
values = periodic_lowpass(soft_clip(raw*drive),
.66 if track=="solo" else (.60 if track=="harmony" else .52))
if track == "guitar":
body = periodic_lowpass(values,.019)
values = values-body
elif track == "bass":
p = phase % 1.0
raw = (p*2.0-1.0)*.65 + np.where(p < .5,.35,-.35)
values = periodic_lowpass(raw,.22)
elif track == "organ":
values = np.zeros(length)
for multiple,amp in zip((.5,1,1.5,2,3,4),(.62,1,.40,.58,.24,.30)):
values += amp*.5*(np.sin(2*np.pi*phase*multiple)+
np.sin(2*np.pi*(phase*multiple+index/length)))
elif track == "pad":
det = (-3,-2,-1,0,1,2,3)
bank = []
for voice in det:
p = (phase+voice*index/length) % 1.0
duty = .5 + .18*math.sin(voice*.9)
bank.append(.62*(p*2.0-1.0)+.38*np.where(p<duty,1.0,-1.0))
values = sum(bank)/len(bank)
# Keep the bed below the lead, as the resonant SVF does in voices.h.
values = periodic_lowpass(periodic_lowpass(values,.18),.18)
low = periodic_lowpass(values,.02)
values -= low
elif track == "arp":
raw = sum((((phase+d*index/length+offset)%1.0)*2.0-1.0)
for d,offset in zip((-1,0,1),(0.0,1/3,2/3)))/3
values = periodic_lowpass(raw,.34)
else:
raise ValueError(track)
data = pcm(values,loop=True)
return dict(name=track+" synth",pcm=data,loop_start=0,loop_length=len(data),
relative=24,finetune=TUNE)
def one_shot(track, midi=60):
rng = np.random.default_rng(0x435254+TRACKS.index(track))
seconds = {"bell":4.0,"kick":.85,"snare":.65,"hat":.15,"crash":1.0}[track]
length = round(seconds*SAMPLE_RATE)
t = np.arange(length)/SAMPLE_RATE
if track == "bell":
hz = 440*2**((midi-69)/12)
index = .35+(6.5*(.4+.6*.55)-.35)*np.exp(-t/.2)
values = np.sin(2*np.pi*hz*t+index*np.sin(2*np.pi*hz*1.4*t))*np.exp(-t/1.6)
elif track == "kick":
tau = -1/(44100*math.log(.99955))
phase = 46*t+(165-46)*tau*(1-np.exp(-t/tau))
values = .55*np.sin(2*np.pi*phase)*np.exp(t*44100*math.log(.99988))
values += rng.uniform(-1,1,length)*.22*np.exp(t*44100*math.log(.9955))
elif track == "snare":
noise = rng.uniform(-1,1,length)
hp = noise-.6*lowpass(noise,.45)
values = (.75*hp+.35*np.sin(2*np.pi*187*t))*np.exp(t*44100*math.log(.99977))
else:
noise = rng.uniform(-1,1,length)
values = (noise-lowpass(noise,.70))*np.exp(t*44100*math.log(.9988 if track=="hat" else .99975))
return dict(name=f"{track} {midi}" if track=="bell" else track+" synth",
pcm=pcm(values),loop_start=0,loop_length=0,
relative=24+60-midi,finetune=0)
def delta_encode(data):
values = data.astype(np.int32)
delta = np.diff(values,prepend=0)
return ((delta+32768)%65536-32768).astype("<i2").tobytes()
def instrument_blob(track, samples, mapping=None):
header = bytearray(263)
struct.pack_into("<I22sBH",header,0,263,field(track,22),0,len(samples))
struct.pack_into("<I",header,29,40)
header[33:129] = bytes(mapping if mapping is not None else [0]*96)
points,sustain,fadeout = ENVELOPES[track]
for i,(tick,volume) in enumerate(points):
struct.pack_into("<HH",header,129+i*4,tick,volume)
header[225] = len(points)
header[227] = sustain if sustain is not None else 0
header[233] = 1 | (2 if sustain is not None else 0)
struct.pack_into("<H",header,239,fadeout)
sample_headers, sample_data = bytearray(), bytearray()
for sample in samples:
name = sample["name"]
sample_headers.extend(struct.pack("<IIIBbBBbB22s",len(sample["pcm"])*2,
sample["loop_start"]*2,sample["loop_length"]*2,64,sample["finetune"],
0x10 | bool(sample["loop_length"]),128,sample["relative"],len(name),field(name,22)))
sample_data.extend(delta_encode(sample["pcm"]))
return bytes(header+sample_headers+sample_data)
def metadata_instrument(name):
return struct.pack("<I22sBH",29,field(name,22),0,0)
def make_module(score, gains):
patterns, assigned, starts = make_patterns(score,gains)
instruments = []
for track in TRACKS:
if track == "bell":
pitches = sorted({n["pitch"] for n in score["notes"] if n["track"]=="bell"})
samples = [one_shot(track,pitch) for pitch in pitches]
mapping = [min(range(len(pitches)),key=lambda i:abs(pitches[i]-(n+12))) for n in range(96)]
else:
samples = [one_shot(track) if track in ("kick","snare","hat","crash") else melodic_sample(track)]
mapping = None
instruments.append(instrument_blob(track,samples,mapping))
instruments.append(metadata_instrument(FULL_TITLE))
for section in score["sections"]:
first = round(section["start"]/(ROWS*score["row_seconds"]))
last = round(section["end"]/(ROWS*score["row_seconds"]))-1
instruments.append(metadata_instrument(f"{section['name']} {first:02}-{last:02}"))
header = bytearray(b"Extended Module: "+field(TITLE,20)+b"\x1a"+field(TRACKER,20))
header.extend(struct.pack("<HI8H",0x0104,276,ORDERS,0,CHANNELS,ORDERS,len(instruments),1,SPEED,132))
header.extend(bytes(range(ORDERS))+bytes(256-ORDERS))
data = bytes(header)+b"".join(patterns)+b"".join(instruments)
report = dict(title=TITLE,full_title=FULL_TITLE,channels=CHANNELS,orders=ORDERS,
rows_per_pattern=ROWS,instruments=len(instruments),
score_notes=len(score["notes"]),score_drums=len(score["drums"]),
native_note_on_events=len(assigned)+sum(n["track"] in GAIN_PARTNERS for n in assigned),
gain_partner_channels=GAIN_PARTNERS,
source_duration_seconds=score["duration"],xm_tempo_duration_seconds=starts[-1],
max_row_clock_error_ms=max(abs(s-i*score["row_seconds"]) for i,s in enumerate(starts))*1000,
sections=score["sections"],bytes=len(data),sha256=hashlib.sha256(data).hexdigest())
return data, report
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output",type=Path,default=OUTPUT)
args = parser.parse_args()
output = args.output.resolve()
if not output.is_relative_to(HERE) or output.suffix.lower() != ".xm":
parser.error("Output must be an .xm file inside tracker/")
data,report = make_module(*load_source())
output.parent.mkdir(parents=True,exist_ok=True)
output.write_bytes(data)
(HERE/"build_report.json").write_text(json.dumps(report,indent=2)+"\n",encoding="utf-8")
print(json.dumps(report,indent=2))
if __name__ == "__main__":
main()

237
tracker/xm_verify.py Normal file
View file

@ -0,0 +1,237 @@
"""Independent strict parser for this native XM subset, plus silent decoding.
python -B tracker/xm_verify.py --decode
No GUI or playback. FFmpeg renders to a memory pipe, not to demo/publication files.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import math
from pathlib import Path
import shutil
import struct
import subprocess
import tempfile
import numpy as np
HERE = Path(__file__).resolve().parent
def require(condition, message):
if not condition:
raise ValueError(message)
def text(data):
require(all(byte == 0 or 32 <= byte < 127 for byte in data),"Non-ASCII metadata")
value = data.decode("ascii").rstrip(" \x00")
require(":" not in value and "\\" not in value and "/" not in value,"Path-like metadata")
return value
def parse_xm(data):
require(len(data) >= 336,"Truncated XM header")
require(data[:17] == b"Extended Module: " and data[37] == 0x1A,"Invalid XM signature")
title, tracker = text(data[17:37]), text(data[38:58])
version,header_size,length,restart,channels,npatterns,ninstruments,flags,speed,bpm = struct.unpack_from("<HI8H",data,58)
require(version == 0x104 and header_size == 276,"Expected native XM 1.04 full header")
require(1 <= length <= 256 and 0 <= restart < length,"Invalid song length/restart")
require(2 <= channels <= 32 and channels % 2 == 0,"Invalid native XM channel count")
require(1 <= npatterns <= 256 and 1 <= ninstruments <= 128,"Invalid pattern/instrument count")
require(flags in (0,1) and 1 <= speed <= 31 and 32 <= bpm <= 255,"Invalid flags/tempo")
orders = list(data[80:80+length])
require(all(order < npatterns for order in orders),"Invalid order reference")
position = 60+header_size
patterns = []
for pattern in range(npatterns):
require(position+9 <= len(data),"Truncated pattern header")
hsize,packing,rows,size = struct.unpack_from("<IBHH",data,position)
require(hsize == 9 and packing == 0 and 1 <= rows <= 256,"Invalid pattern header")
position += hsize
end = position+size
require(end <= len(data),"Truncated pattern body")
cells = []
if size == 0:
cells = [[0]*5 for _ in range(rows*channels)]
else:
for _ in range(rows*channels):
require(position < end,"Too few pattern cells")
first = data[position]
position += 1
cell = [0]*5
if first & 0x80:
require(first & 0x60 == 0,"Invalid packed-cell mask")
for bit in range(5):
if first & (1<<bit):
require(position < end,"Truncated packed cell")
cell[bit] = data[position]
position += 1
else:
require(position+4 <= end,"Truncated unpacked cell")
cell = [first]+list(data[position:position+4])
position += 4
note,instrument,volume,effect,param = cell
require(0 <= note <= 97 and instrument <= ninstruments,"Invalid note/instrument")
require(volume == 0 or 0x10 <= volume <= 0x50,"Invalid volume in export subset")
require(effect in (0,8,0xF,0x10),"Unexpected/non-native export effect")
require(effect != 0 or param == 0,"Unexpected arpeggio effect")
if effect == 0xF:
require(param != 0,"Ambiguous F00 is not allowed")
if effect == 0x10:
require(param <= 64,"Gxx exceeds native global-volume range")
cells.append(cell)
require(position == end,"Pattern size does not match cell count")
patterns.append(np.array(cells,dtype=np.uint8).reshape(rows,channels,5))
instruments = []
for index in range(ninstruments):
require(position+29 <= len(data),"Truncated instrument header")
hsize,name,kind,nsamples = struct.unpack_from("<I22sBH",data,position)
require(hsize >= 29 and position+hsize <= len(data),"Invalid instrument-header extent")
require(kind == 0 and nsamples <= 16,"Invalid native instrument/sample count")
instrument = dict(name=text(name),samples=[],mapping=[],envelope=[],envelope_type=0)
if nsamples:
require(hsize == 263,"Expected full FT2 instrument header")
sample_hsize = struct.unpack_from("<I",data,position+29)[0]
require(sample_hsize == 40,"Invalid sample-header size")
mapping = list(data[position+33:position+129])
require(all(i < nsamples for i in mapping),"Invalid key-to-sample mapping")
points = data[position+225]
sustain = data[position+227]
env_type = data[position+233]
require(2 <= points <= 12 and env_type in (1,3),"Invalid volume envelope")
envelope = [struct.unpack_from("<HH",data,position+129+i*4) for i in range(points)]
require(all(v <= 64 for _,v in envelope),"Envelope volume out of range")
require(all(a[0] < b[0] for a,b in zip(envelope,envelope[1:])),"Unordered envelope points")
require(not env_type & 2 or sustain < points,"Invalid envelope sustain index")
require(data[position+234] == 0,"Unexpected pan envelope")
instrument.update(mapping=mapping,envelope=envelope,envelope_type=env_type,sustain=sustain)
position += hsize
headers = []
for _ in range(nsamples):
require(position+40 <= len(data),"Truncated sample header")
size,loop_start,loop_length,volume,fine,kind,pan,relative,reserved,name = struct.unpack_from("<IIIBbBBbB22s",data,position)
position += 40
require(size > 0 and size % 2 == 0,"Invalid 16-bit sample length")
require(kind in (0x10,0x11),"Only native mono 16-bit/forward-loop samples expected")
require(0 <= volume <= 64 and -96 <= relative <= 95,"Sample volume/pitch out of range")
require(loop_start % 2 == 0 and loop_length % 2 == 0,"Loop offsets are bytes, must align")
if kind & 3:
require(loop_length >= 4 and loop_start+loop_length <= size,"Invalid loop extent")
else:
require(loop_start == loop_length == 0,"Unlooped sample has loop data")
sample_name = text(name)
require(reserved == len(sample_name) <= 22,"Invalid native sample-name length")
headers.append(dict(name=sample_name,bytes=size,loop_start=loop_start//2,
loop_length=loop_length//2,volume=volume,finetune=fine,
relative=relative,pan=pan))
for sample in headers:
end = position+sample["bytes"]
require(end <= len(data),"Truncated delta sample data")
delta = np.frombuffer(data[position:end],dtype="<i2")
decoded = ((np.cumsum(delta,dtype=np.int64)+32768)%65536-32768).astype(np.int16)
require(np.max(np.abs(decoded.astype(np.int32))) <= 30500,"Generated sample exceeds headroom limit")
require(np.any(decoded),"Silent instrument sample")
sample["pcm"] = decoded
instrument["samples"].append(sample)
position = end
instruments.append(instrument)
require(position == len(data),"Trailing non-native data or incorrect sample sizes")
# Independently resolve every note's instrument and mapped sample.
remembered = [0]*channels
note_count = 0
musical_onsets = set()
elapsed, row_times = 0.0, [0.0]
current_speed, current_bpm = speed,bpm
for order_index,order in enumerate(orders):
for row_index,row in enumerate(patterns[order]):
for channel,cell in enumerate(row):
note,ins,volume,effect,param = map(int,cell)
if ins:
remembered[channel] = ins
if 1 <= note <= 96:
require(remembered[channel] > 0,"Note without instrument")
inst = instruments[remembered[channel]-1]
require(bool(inst["samples"]),"Note references metadata-only instrument")
sample = inst["samples"][inst["mapping"][note-1]]
require(0 <= note-1+sample["relative"] <= 118,"Transposed note beyond native range")
note_count += 1
musical_onsets.add((order_index,row_index,remembered[channel],note))
if effect == 0xF:
if param < 32:
current_speed = param
else:
current_bpm = param
elapsed += current_speed*2.5/current_bpm
row_times.append(elapsed)
return dict(title=title,tracker=tracker,orders=orders,channels=channels,patterns=patterns,
instruments=instruments,note_count=note_count,speed=speed,bpm=bpm,
duration_seconds=elapsed,row_times=row_times,
distinct_instrument_note_onsets=len(musical_onsets))
def decode_pcm(data, seconds=None):
require(shutil.which("ffmpeg") is not None,"FFmpeg is not available")
# This FFmpeg demuxer requires seekable input. Keep its scratch module
# inside tracker/; decoded PCM still goes only to memory.
with tempfile.TemporaryDirectory(prefix=".xm-verify-",dir=HERE) as scratch:
module = Path(scratch)/"input.xm"
module.write_bytes(data)
command = ["ffmpeg","-hide_banner","-loglevel","error","-nostdin",
"-f","libopenmpt","-sample_rate","44100","-i",str(module)]
if seconds is not None:
command += ["-t",str(seconds)]
command += ["-f","f32le","-acodec","pcm_f32le","-ac","2","pipe:1"]
result = subprocess.run(command,capture_output=True,timeout=120)
require(result.returncode == 0,"FFmpeg decode failed: "+result.stderr.decode(errors="replace"))
require(len(result.stdout)%8 == 0,"Invalid decoded float-frame size")
samples = np.frombuffer(result.stdout,dtype="<f4").reshape(-1,2)
require(len(samples)>0 and np.all(np.isfinite(samples)),"Empty/nonfinite module decode")
return samples
def summary(data, decoded=False):
parsed = parse_xm(data)
result = dict(title=parsed["title"],tracker=parsed["tracker"],channels=parsed["channels"],
patterns=len(parsed["patterns"]),orders=len(parsed["orders"]),
rows=[len(p) for p in parsed["patterns"]],
instruments=len(parsed["instruments"]),
instrument_names=[i["name"] for i in parsed["instruments"]],
samples=sum(len(i["samples"]) for i in parsed["instruments"]),
note_on_events=parsed["note_count"],duration_seconds=parsed["duration_seconds"],
distinct_instrument_note_onsets=parsed["distinct_instrument_note_onsets"],
bytes=len(data),sha256=hashlib.sha256(data).hexdigest())
if decoded:
pcm = decode_pcm(data)
peak = float(np.max(np.abs(pcm)))
rms = float(np.sqrt(np.mean(pcm.astype(np.float64)**2)))
result["decode"] = dict(decoder="FFmpeg libopenmpt",rate=44100,frames=len(pcm),
seconds=len(pcm)/44100,peak_dbfs=20*math.log10(max(peak,1e-12)),
rms_dbfs=20*math.log10(max(rms,1e-12)),
full_scale_samples=int(np.count_nonzero(np.abs(pcm)>=1.0)))
require(peak > .001 and rms > .0001,"Unexpected silent/near-silent decode")
require(peak < 1.0,"Decode exceeds full scale")
require(parsed["duration_seconds"]-.25 <= len(pcm)/44100 <= parsed["duration_seconds"]+10,
"Decoded duration outside song plus player-tail allowance")
result["decode"]["order_rms_dbfs"] = []
for first in range(0,48*32,32):
a,b = (round(parsed["row_times"][i]*44100) for i in (first,first+32))
rms = float(np.sqrt(np.mean(pcm[a:b].astype(np.float64)**2)))
result["decode"]["order_rms_dbfs"].append(20*math.log10(max(rms,1e-12)))
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("module",nargs="?",type=Path,default=HERE/"CRTkafa-cracktro-01.xm")
parser.add_argument("--decode",action="store_true")
args = parser.parse_args()
result = summary(args.module.read_bytes(),args.decode)
(HERE/"verification.json").write_text(json.dumps(result,indent=2)+"\n",encoding="utf-8")
print(json.dumps(result,indent=2))
if __name__ == "__main__":
main()

238
visualizer/score.py Normal file
View file

@ -0,0 +1,238 @@
"""Read-only piano-roll score for CRTkafa @ cracktro 01.
build_score() verifies every baked table against arrange_v11 before extracting
events from song_data.h. It does not render, inspect, or modify media. The video
renderer must stream-copy CRTkafa.mp4 audio separately; this score cannot prove
that an arbitrary encoded video was produced from these source files.
Times use the engine's sample clock; pitches are conventional MIDI (engine+12).
Durations are visual notation: lead/bass stop at their 2/4-row rest gates or
next strike; solo/harmony at at most 4 rows; guitar at 3 rows (8 when held);
bell at 16 rows; polysynth arp at 2 rows. Bass also ends at a voice handoff.
Release, delay, reverb, crossfade, and FM-sideband tails are not extra notes.
Organ/pad chords merge only while the complete engine voicing stays unchanged.
Guitar shows root and the deliberately played fifth, not detuned duplicates;
organ shows its three chord tones, not drawbar partials. Velocity is trigger
strength, not measured loudness, section gain, or master fade automation.
The legacy chip arp (unused in 01) is shown as tick-length pitch segments, not
as invented note-on attacks. There is no EP trigger in songTick, so no EP notes.
No file writes occur on import or in build_score(). Only the CLI prints JSON.
"""
from __future__ import annotations
import json
import math
from pathlib import Path
import re
import subprocess
import sys
ROOT = Path(__file__).resolve().parents[1]
TRACKS = frozenset(("lead", "solo", "harmony", "bass", "guitar", "organ",
"pad", "arp", "bell"))
DRUM_TRACKS = frozenset(("kick", "snare", "hat", "crash"))
def _defines(source):
"""Simple literal/object aliases only; do not evaluate arbitrary C/Python."""
return dict(re.findall(r"^#define\s+(\w+)\s+([\w.+-]+)", source, re.M))
def _number(defines, name):
value = defines[name]
seen = {name}
while value in defines:
if value in seen:
raise ValueError(f"Cyclic macro: {name}")
seen.add(value)
value = defines[value]
return float(value.rstrip("fF"))
def _arrangement():
# Isolate the arranger's sibling import of motif without modifying sys.path
# or sys.modules in the renderer. -B prevents even bytecode-cache writes.
code = ("import sys,json; sys.path.insert(0,sys.argv[1]); import arrange_v11 as a; "
"print(json.dumps(dict(tables={k:[t,a.flatten(v)] for k,(t,v) in "
"a.TABLES.items()},sections=a.SECTIONS,section_ids=a.SECTION_IDS,"
"orders=a.ORDERS,rows=a.ROWS,spr=a.SPR,srate=a.SRATE)))")
result = subprocess.run([sys.executable, "-I", "-B", "-c", code,
str(ROOT / "tools")], check=True,
capture_output=True, text=True)
return json.loads(result.stdout)
def _inputs():
source = (ROOT / "song_data.h").read_text(encoding="utf-8")
tables = {}
for typ, name, body in re.findall(
r"static const (signed char|unsigned char|short) (g_sq\w+)\[\]"
r"\s*=\s*\{(.*?)\};", source, re.S):
if name in tables:
raise ValueError(f"Duplicate table: {name}")
tables[name] = [typ, list(map(int, re.findall(r"-?\d+", body)))]
arrangement = _arrangement()
if tables != arrangement["tables"]:
raise ValueError("song_data.h differs from arrange_v11; refusing a stale score")
synth = (ROOT / "synth.h").read_text(encoding="utf-8")
voices = (ROOT / "voices.h").read_text(encoding="utf-8")
defines = _defines(source + "\n" + synth + "\n" + voices)
for macro, key in (("SNG_ORDERS", "orders"), ("SNG_ROWS", "rows"),
("SPR", "spr"), ("SRATE", "srate")):
if _number(defines, macro) != arrangement[key]:
raise ValueError(f"Clock mismatch: {macro}")
if arrangement["rows"] != 32 or int(_number(defines, "TPR")) != 6:
raise ValueError("Extractor expects the current 32-row/six-tick engine")
return {key: value[1] for key, value in tables.items()}, arrangement, defines
def _extract(t, arrangement, defines):
rows, orders = arrangement["rows"], arrangement["orders"]
spr, rate = arrangement["spr"], arrangement["srate"]
row_seconds = spr / rate
count, duration = rows * orders, rows * orders * spr / rate
notes, drums, sections = [], [], []
def add(track, pitch, start_row, end_row, velocity=1.0):
notes.append(dict(track=track, pitch=int(pitch) + 12,
start=start_row * spr / rate,
end=min(end_row * spr / rate, duration),
velocity=float(velocity)))
def strikes(track, lane, length, pitches=lambda n, k: (n,), condition=None):
events = [(k, n) for k, n in enumerate(t[lane])
if n >= 0 and (condition is None or condition(k))]
for i, (k, n) in enumerate(events):
end = min(count, k + (length(k) if callable(length) else length))
if i + 1 < len(events):
end = min(end, events[i+1][0])
if track == "bass":
for boundary in range((k//rows + 1)*rows, end, rows):
if bool(t["g_sqSyn"][boundary//rows]) != bool(t["g_sqSyn"][k//rows]):
end = boundary
break
for pitch in pitches(n, k):
add(track, pitch, k, end)
def bass_pitch(note, k):
if t["g_sqSyn"][k//rows]:
hz = 440.0 * 2 ** ((note - 57) / 12)
while hz > _number(defines, "PB_FOLD_HI"):
hz /= 2
note -= 12
while hz < _number(defines, "PB_FOLD_LO"):
hz *= 2
note += 12
return (note,)
strikes("lead", "g_sqLead", 2)
strikes("solo", "g_sqSolo", 4)
strikes("harmony", "g_sqHarm", 4,
condition=lambda k: t["g_sqSolo"][k] >= 0)
strikes("bass", "g_sqBass", 4, pitches=bass_pitch)
strikes("guitar", "g_sqGtr", lambda k: 8 if t["g_sqHold"][k] else 3,
pitches=lambda n, k: (n, n+7))
# Stateful voices: compare the full ordered voicing, as orgSet/padSet do.
active = {track: (None, 0) for track in ("organ", "pad")}
for k in range(count + 1):
chord = {"organ": None, "pad": None}
if k < count:
o, r = divmod(k, rows)
root = t["g_sqRoot"][o*4 + r//8]
major = bool(t["g_sqType"][o*4 + r//8])
offsets = (0, 4 if major else 3, 7)
mode = t["g_sqOrgMode"][o]
if mode:
base = 24 + (12 if mode == 2 else 0) + root
chord["organ"] = (mode, tuple(base+n for n in
((0, 7, 12) if mode == 1 else offsets)))
if t["g_sqSyn"][o]:
base = int(_number(defines, "PAD_BASE"))
chord["pad"] = (1, tuple(base + (root+n) % 12 for n in offsets))
for track in active:
previous, start = active[track]
if chord[track] != previous:
if previous is not None:
for pitch in previous[1]:
add(track, pitch, start, k)
active[track] = (chord[track], k)
drum_map = {0: (), 1: (("kick", 1.0),), 2: (("snare", .85),),
3: (("hat", .30),), 4: (("hat", .55),),
5: (("crash", .95),),
6: (("kick", 1.0), ("crash", .95)),
7: (("kick", 1.0), ("snare", .85))}
ticks = int(_number(defines, "TPR"))
for k in range(count):
o, r = divmod(k, rows)
root = t["g_sqRoot"][o*4 + r//8]
major = bool(t["g_sqType"][o*4 + r//8])
for track, velocity in drum_map[t["g_sqDrum"][k]]:
drums.append(dict(track=track, start=k * spr / rate, velocity=velocity))
if r == 0 and t["g_sqSect"][o] in (0, 7, 10) and o % 2 == 0:
note = 48 + root
while note < _number(defines, "BELL_LO"):
note += 12
while note > _number(defines, "BELL_HI"):
note -= 12
add("bell", note, k, min(k+16, count), .55)
if t["g_sqSyn"][o] and r % 2 == 0:
offsets = (0, 4 if major else 3, 7, 12)
add("arp", 36 + root + offsets[(r//2) & 3], k, k+2,
1.0 if r % 8 == 0 else .62)
if t["g_sqArpOct"][o] >= 0:
offsets = (0, 4 if major else 3, 7)
for tick in range(ticks):
# Integer tick boundaries match TICKLEN; SPR/TPR truncation
# must not accumulate across rows. These are pitch segments.
begin = k*spr + tick*spr//ticks
end = k*spr + (tick+1)*spr//ticks
pitch = t["g_sqArpOct"][o] + root + offsets[(tick+r*ticks) % 3]
notes.append(dict(track="arp", pitch=pitch+12, start=begin/rate,
end=end/rate, velocity=1.0))
for (name, first, last, _), section_id in zip(arrangement["sections"],
arrangement["section_ids"]):
if t["g_sqSect"][first:last+1] != [section_id] * (last-first+1):
raise ValueError(f"Section metadata mismatch: {name}")
sections.append(dict(name=name, start=first*rows*spr/rate,
end=(last+1)*rows*spr/rate))
notes.sort(key=lambda event: (event["start"], event["track"], event["pitch"], event["end"]))
drums.sort(key=lambda event: (event["start"], event["track"]))
sections.sort(key=lambda event: event["start"])
score = dict(duration=duration, notes=notes, drums=drums, sections=sections,
row_seconds=row_seconds, bars=count//16)
_validate(score)
return score
def _validate(score):
for event in score["notes"] + score["drums"]:
if not (math.isfinite(event["start"]) and 0 <= event["start"] < score["duration"]
and math.isfinite(event["velocity"]) and 0 <= event["velocity"] <= 1):
raise ValueError(f"Invalid event: {event}")
if "pitch" in event:
if not (event["track"] in TRACKS and isinstance(event["pitch"], int)
and 0 <= event["pitch"] <= 127 and math.isfinite(event["end"])
and event["start"] < event["end"] <= score["duration"]):
raise ValueError(f"Invalid note: {event}")
elif event["track"] not in DRUM_TRACKS:
raise ValueError(f"Invalid drum: {event}")
end = 0.0
for section in score["sections"]:
if section["start"] != end or not section["start"] < section["end"]:
raise ValueError("Sections must cover the score without gaps or overlaps")
end = section["end"]
if end != score["duration"]:
raise ValueError("Sections do not cover the song duration")
def build_score() -> dict:
"""Return sorted notes/drums/sections; refuse an outdated or invalid bake."""
return _extract(*_inputs())
if __name__ == "__main__":
print(json.dumps(build_score(), separators=(",", ":"), allow_nan=False))

166
visualizer/score_test.py Normal file
View file

@ -0,0 +1,166 @@
"""Score/schema regressions. Run: python -B -m unittest discover -s visualizer -p score_test.py -v"""
import copy
from collections import Counter
import importlib.util
import json
from pathlib import Path
import unittest
from unittest.mock import patch
if __package__:
from . import score
else:
import score
class ScoreTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tables, cls.arrangement, cls.defines = score._inputs()
cls.result = score.build_score()
cls.row = cls.result["row_seconds"]
def events(self, track):
return [n for n in self.result["notes"] if n["track"] == track]
def row_of(self, event):
return round(event["start"] / self.row)
def test_schema_clock_and_sorted_events(self):
result = self.result
self.assertEqual(set(result), {"duration", "notes", "drums", "sections", "row_seconds", "bars"})
self.assertEqual(result["duration"], 7680000 / 44100)
self.assertEqual(result["row_seconds"], 5000 / 44100)
self.assertEqual(result["bars"], 96)
self.assertEqual({n["track"] for n in result["notes"]}, score.TRACKS)
for note in result["notes"]:
self.assertEqual(set(note), {"track", "pitch", "start", "end", "velocity"})
self.assertIs(type(note["pitch"]), int)
self.assertIn(note["pitch"], range(128))
self.assertTrue(0 <= note["start"] < note["end"] <= result["duration"])
for drum in result["drums"]:
self.assertEqual(set(drum), {"track", "start", "velocity"})
self.assertIn(drum["track"], score.DRUM_TRACKS)
for key in ("notes", "drums", "sections"):
self.assertEqual([e["start"] for e in result[key]],
sorted(e["start"] for e in result[key]))
json.dumps(result, allow_nan=False)
score._validate(result)
def test_bake_equivalence_is_checked_and_failure_is_explicit(self):
stale = copy.deepcopy(self.arrangement)
stale["tables"]["g_sqSolo"][1][25*32] += 1
with patch.object(score, "_arrangement", return_value=stale):
with self.assertRaisesRegex(ValueError, "differs"):
score.build_score()
wrong_clock = copy.deepcopy(self.arrangement)
wrong_clock["spr"] += 1
with patch.object(score, "_arrangement", return_value=wrong_clock):
with self.assertRaisesRegex(ValueError, "Clock mismatch"):
score.build_score()
def test_direct_note_attacks_preserve_midi_register_and_restrikes(self):
for track, table in (("lead", "g_sqLead"), ("solo", "g_sqSolo"),
("harmony", "g_sqHarm")):
expected = [(k, pitch+12) for k, pitch in enumerate(self.tables[table])
if pitch >= 0 and (track != "harmony" or self.tables["g_sqSolo"][k] >= 0)]
self.assertEqual([(self.row_of(n), n["pitch"]) for n in self.events(track)], expected)
self.assertEqual([n["pitch"] for n in self.events("solo")
if self.row_of(n) == 40*32], [95])
self.assertFalse(any(39*32+16 <= self.row_of(n) < 39*32+28 for n in self.events("solo")))
self.assertEqual(sum(n["start"] >= 16*32*self.row and n["start"] < 40*32*self.row
for n in self.events("solo")),
sum(n >= 0 for n in self.tables["g_sqSolo"][16*32:40*32]))
orphan = copy.deepcopy(self.tables)
orphan["g_sqHarm"][0] = 69
result = score._extract(orphan, self.arrangement, self.defines)
self.assertFalse(any(n["track"] == "harmony" and n["start"] == 0 for n in result["notes"]))
def test_bass_folding_and_guitar_chord_not_oscillator_duplicates(self):
bass = self.events("bass")
self.assertEqual(len(bass), sum(n >= 0 for n in self.tables["g_sqBass"]))
for note in bass:
k = self.row_of(note)
original = self.tables["g_sqBass"][k] + 12
self.assertEqual(note["pitch"] % 12, original % 12)
if self.tables["g_sqSyn"][k//32]:
hz = 440 * 2 ** ((note["pitch"]-69)/12)
self.assertTrue(58 <= hz <= 150)
else:
self.assertEqual(note["pitch"], original)
for k, pitch in enumerate(self.tables["g_sqGtr"]):
actual = [n["pitch"] for n in self.events("guitar") if self.row_of(n) == k]
self.assertEqual(actual, [] if pitch < 0 else [pitch+12, pitch+19])
def test_arp_and_bell_trigger_conditions(self):
arp = self.events("arp")
self.assertEqual(len(arp), 6*16)
self.assertEqual([self.row_of(n) for n in arp], list(range(2*32, 8*32, 2)))
self.assertEqual([n["pitch"] for n in arp[:8]], [57,60,64,69,57,60,64,69])
self.assertEqual([n["velocity"] for n in arp[:4]], [1.0,.62,.62,.62])
bells = self.events("bell")
self.assertEqual([(self.row_of(n)//32, n["pitch"], n["velocity"]) for n in bells],
[(0,81,.55), (46,79,.55)])
def test_sustained_voicings_and_unchanged_order_boundaries(self):
organ = [n for n in self.events("organ") if n["start"] == 0]
self.assertEqual([n["pitch"] for n in organ], [57,60,64])
self.assertTrue(all(n["end"] == 16*self.row for n in organ))
pad = [n for n in self.events("pad") if self.row_of(n) == 2*32]
self.assertEqual([n["pitch"] for n in pad], [60,64,69])
altered = copy.deepcopy(self.tables)
# A constant Am pad across two orders is one chord, not eight triggers.
altered["g_sqRoot"][2*4:4*4] = [9]*8
altered["g_sqType"][2*4:4*4] = [0]*8
result = score._extract(altered, self.arrangement, self.defines)
held = [n for n in result["notes"] if n["track"] == "pad" and n["start"] == 64*self.row]
self.assertEqual(len(held), 3)
self.assertTrue(all(n["end"] == 128*self.row for n in held))
self.assertFalse(any(n["track"] == "pad" and 64*self.row < n["start"] < 128*self.row
for n in result["notes"]))
def test_drum_decoding_has_no_invented_hat_or_echo_triggers(self):
expected = Counter()
for k, code in enumerate(self.tables["g_sqDrum"]):
if code in (1,6,7): expected[(k,"kick",1.0)] += 1
if code in (2,7): expected[(k,"snare",.85)] += 1
if code in (3,4): expected[(k,"hat",.30 if code == 3 else .55)] += 1
if code in (5,6): expected[(k,"crash",.95)] += 1
self.assertEqual(Counter((self.row_of(n),n["track"],n["velocity"])
for n in self.result["drums"]), expected)
def test_unused_chip_arp_uses_exact_tick_boundaries(self):
altered = copy.deepcopy(self.tables)
altered["g_sqArpOct"][0] = 36
result = score._extract(altered, self.arrangement, self.defines)
notes = [n for n in result["notes"] if n["track"] == "arp" and n["start"] < 32*self.row]
self.assertEqual(len(notes), 32*6)
self.assertEqual([n["pitch"] for n in notes[:6]], [57,60,64,57,60,64])
self.assertEqual([round((n["end"]-n["start"])*44100) for n in notes[:6]],
[833,833,834,833,833,834])
self.assertEqual(notes[-1]["end"], 160000/44100)
def test_visual_gates_and_section_coverage(self):
for track, cap in (("lead",2), ("bass",4), ("solo",4), ("harmony",4), ("bell",16)):
for note in self.events(track):
self.assertLessEqual(note["end"]-note["start"], cap*self.row+1e-12)
sections = self.result["sections"]
self.assertEqual([s["name"] for s in sections],
["INTRO","SYNTHWAVE","METAL VERSE","CHORUS","SOLO","ARRIVAL","OUTRO"])
self.assertEqual(sections[0]["start"],0)
self.assertEqual(sections[-1]["end"],self.result["duration"])
for a,b in zip(sections,sections[1:]):
self.assertEqual(a["end"],b["start"])
def test_import_has_no_export_or_subprocess_side_effect(self):
spec = importlib.util.spec_from_file_location("score_import_probe", Path(score.__file__))
module = importlib.util.module_from_spec(spec)
with patch.object(Path,"write_text",side_effect=AssertionError("import wrote text")), \
patch.object(Path,"write_bytes",side_effect=AssertionError("import wrote bytes")), \
patch.object(score.subprocess,"run",side_effect=AssertionError("import launched a process")):
spec.loader.exec_module(module)
self.assertTrue(callable(module.build_score))
if __name__ == "__main__":
unittest.main()