#!/usr/bin/env python3 """Run the real DL-1425 program on MAME's low-level QSound device and trace the DSP16A. In MAME 0.285 every game driver is built with the high-level ``qsound_hle`` device; the low-level ``qsound`` device (a DSP16A running ``dl-1425.bin``) is reachable without a rebuild only through the ``vgmplay`` driver. So the stimulus is a VGM file. This script writes one from scratch (a synthetic sample ROM and a handful of register writes: no game data), plays it headless, and records - ``dsp.trace`` one line per DSP instruction for a window of the run, - ``qsound.wav`` what the device's DAC model produced (MAME's -wavwrite), - ``summary.json`` the device tags, the register symbols and counts. Everything lands in tests/mame_traces// (git-ignored). python -I scripts/mame_lle_trace.py # the built-in tone python -I scripts/mame_lle_trace.py --vgm FILE.vgm # any QSound VGM python -I scripts/mame_lle_trace.py --trace-start 1.0 --trace-frames 1 python -I scripts/mame_lle_trace.py --name busy --busy --seconds 2 python -I scripts/mame_lle_trace.py --name dasm --dasm # program.dasm only """ from __future__ import annotations import os import argparse import json import math import struct import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] #: Romset folders, ';'-separated as MAME's -rompath (the device set qsound.zip and #: the game sets): from the environment, never a machine path in the repository. ROMPATH = os.environ.get("MAME_ROMPATH", "") # One line per instruction, before it executes. Symbols as MAME 0.285 registers # them for dsp16a (dsp16.cpp device_start): PC PT PR PI I R0-R3 RB RE J K # X Y P A0 A1 C0 C1 C2 AUC PSW (and YH YL A0H A0L A1H A1L, hidden). TRACE_FORMAT = ( '"%04X: pt=%04X pr=%04X pi=%04X i=%03X r=%04X,%04X,%04X,%04X rb=%04X re=%04X j=%04X k=%04X ' 'x=%04X y=%08X p=%08X a0=%09X a1=%09X c=%02X,%02X,%02X auc=%02X psw=%04X t=%d\\n",' "pc,pt,pr,pi,i,r0,r1,r2,r3,rb,re,j,k,x,y,p,a0,a1,c0,c1,c2,auc,psw,totalcycles" ) def tone_vgm(seconds: float, busy: bool = False) -> bytes: """A VGM 1.71 file: a 4,096-byte sine in bank 0, voice 0 looping it, pan centre. With ``busy``, voice 0's volume is rewritten every 64 VGM samples (about every 35 output samples) for the rest of the run, so a trace window holds host interrupts and the command path of the main loop. """ rom = bytes(int(100 * math.sin(2 * math.pi * n / 64)) & 0xFF for n in range(4096)) body = bytearray() # data block 0x8F = QSound sample ROM: total size, start offset, bytes block = struct.pack(" None: while samples: step = min(samples, 0xFFFF) body.extend(b"\x61" + struct.pack(" None: body.extend(bytes((0xC4, value >> 8, value & 0xFF, register))) wait(22050) # let the program finish its start-up for register, value in ( (0x78, 0x8000), # bank of voice 0 (the bank register is one voice early) (0x01, 0x0000), # start address (0x02, 0x0800), # rate: half a ROM byte per sample (0x03, 0x8000), # phase (0x04, 0x1000), # loop length (0x05, 0x1000), # end address (0x06, 0x1000), # volume (0x80, 0x0120), # pan: centre, QSound table (0xBA, 0x0400), # echo send (0x93, 0x1000), # echo feedback (0xD9, 0x0600), # echo length ): write(register, value) wait(64) if busy: for count in range(int(seconds * 44100) // 64): write(0x06, 0x1000 + (count & 1) * 0x0100) wait(64) else: wait(int(seconds * 44100)) body += b"\x66" header = bytearray(0x100) header[0:4] = b"Vgm " struct.pack_into("= TRACE_START then started = true dbg.visible_cpu = manager.machine.devices[dsp_tag] dbg:command('trace dsp.trace,' .. dsp_tag .. ',noloop,{tracelog TRACE_FORMAT}') elseif started and not stopped and now >= TRACE_END then stopped = true dbg:command('trace off,' .. dsp_tag) end end) """ DASM_LUA = """ local done = false keep_frame = emu.add_machine_frame_notifier(function() if not done then done = true local dbg = manager.machine.debugger dbg:command('dasm program.dasm,0,1000,1,:qsound:dsp') manager.machine:exit() end end) """ def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--vgm", type=Path, help="a QSound VGM to play instead of the built-in tone") parser.add_argument("--name", default="tone") parser.add_argument("--busy", action="store_true", help="keep writing a register during the run") parser.add_argument("--dasm", action="store_true", help="only write MAME's disassembly of 0x0000-0x0FFF to program.dasm") parser.add_argument("--seconds", type=float, default=3.0, help="emulated seconds to run") parser.add_argument("--trace-start", type=float, default=1.0) parser.add_argument("--trace-frames", type=int, default=1, help="frames (1/60 s) to trace") args = parser.parse_args() if not ROMPATH: sys.exit("set MAME_ROMPATH (folders holding qsound.zip and the game sets, ';'-separated)") run = ROOT / "tests" / "mame_traces" / args.name run.mkdir(parents=True, exist_ok=True) vgm = run / "stimulus.vgm" vgm.write_bytes(args.vgm.read_bytes() if args.vgm else tone_vgm(args.seconds, args.busy)) lua = ( LUA.replace("TRACE_FORMAT", TRACE_FORMAT) .replace("TRACE_START", repr(args.trace_start)) .replace("TRACE_END", repr(args.trace_start + args.trace_frames / 60)) ) (run / "trace.lua").write_text(DASM_LUA if args.dasm else lua, encoding="utf-8") command = [ "nice", "-n", "19", "mame", "vgmplay", "-quik", str(vgm), "-rompath", ROMPATH, "-homepath", str(run), "-cfg_directory", str(run / "cfg"), "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", "-debug", "-debugger", "none", "-log", "-wavwrite", "qsound.wav", "-seconds_to_run", str(math.ceil(args.seconds)), "-autoboot_script", "trace.lua", ] # fmt: skip result = subprocess.run(command, cwd=run, capture_output=True, text=True, check=False) (run / "mame.stdout").write_text(result.stdout + result.stderr, encoding="utf-8") trace = run / "dsp.trace" lines = trace.read_text(encoding="utf-8", errors="replace").splitlines() if trace.exists() else [] devices = (run / "devices.txt").read_text(encoding="utf-8") if (run / "devices.txt").exists() else "" summary = { "mame_exit": result.returncode, "devices": devices.splitlines(), "trace_lines": len(lines), "first": lines[:3], "last": lines[-1:], } (run / "summary.json").write_text(json.dumps(summary, indent=1), encoding="utf-8") print(json.dumps(summary, indent=1)) if args.dasm: return 0 if (run / "program.dasm").exists() else 1 return 0 if lines else 1 if __name__ == "__main__": sys.exit(main())