261 lines
9.1 KiB
Python
261 lines
9.1 KiB
Python
#!/usr/bin/env python3
|
|
"""Build SPC700 RAM images (and .spc snapshots) for TBG's music from the ROM alone.
|
|
|
|
Runs the game's own bank-$88 sound code (dispatcher 88:8000) in a small 65816 interpreter
|
|
(snd_cpu.py). The APU-port primitives are replaced by Python hooks that apply their effect to a
|
|
64 KiB SPC RAM model, so the image is exactly what the real upload produces:
|
|
88:84B9 IPL boot upload: blocks [len16][dest16][data...] until len 0, then [jump16]
|
|
88:8301 "set address" (port0 = toggle|$40, ports 2/3 = address)
|
|
88:831A "write word" (port0 = toggle, ports 2/3 = word; address += 2)
|
|
88:827A stream $68 bytes (rounded to even) from [$64] (24-bit, LoROM linear) to SPC $1C; $1C += len
|
|
88:82C3 same without bank crossing
|
|
88:8570 / 88:8561 / 88:8589 / 88:85A5 handshakes and driver commands: recorded, not executed
|
|
Every other access to $2140-$2143 is recorded as a port write (the command protocol).
|
|
|
|
usage:
|
|
snd_build_spc.py ROM --compare MESEN_SPC.ram [--song N ...] verify against a Mesen SPC RAM dump
|
|
snd_build_spc.py ROM --list list the 38 sound sets
|
|
snd_build_spc.py ROM --out DIR [--songs 0x00-0x3F] write DIR/song_XX.ram (+ .spc if --spc)
|
|
"""
|
|
import argparse
|
|
import os
|
|
import struct
|
|
import sys
|
|
|
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
from snd_cpu import CPU, Halt # noqa: E402
|
|
|
|
DISPATCH = 0x888000
|
|
|
|
|
|
def lorom_linear(rom, bank, addr, n):
|
|
"""Read n bytes starting at bank:addr, continuing into the next bank's $8000 when crossing $FFFF."""
|
|
out = bytearray()
|
|
off = ((bank & 0x7F) << 15) | (addr & 0x7FFF)
|
|
for i in range(n):
|
|
out.append(rom[(off + i) % len(rom)])
|
|
return out
|
|
|
|
|
|
class SoundSim:
|
|
def __init__(self, rom):
|
|
self.rom = rom
|
|
self.cpu = CPU(rom)
|
|
self.spc = bytearray(0x10000)
|
|
self.written = bytearray(0x10000) # 1 where the upload wrote
|
|
self.spc_addr = 0
|
|
self.ipl_jump = None
|
|
self.log = [] # (kind, ...) command/port events
|
|
self.ops = [] # ordered APU operations for a host with a real SPC (see write_ops)
|
|
self.ports_out = [0, 0, 0, 0]
|
|
c = self.cpu
|
|
h = c.hooks
|
|
h[0x888301] = self._set_addr
|
|
h[0x88831A] = self._write_word
|
|
h[0x88827A] = self._stream
|
|
h[0x8882C3] = self._stream
|
|
h[0x8884B9] = self._ipl
|
|
h[0x888570] = self._noop('enter-transfer')
|
|
h[0x888561] = self._noop('end-transfer')
|
|
h[0x888589] = self._cmd0
|
|
h[0x8885A5] = self._cmd1
|
|
h[0x888A38] = self._kick
|
|
for p in range(4):
|
|
c.io[0x2140 + p] = (self._port_read(p), self._port_write(p))
|
|
|
|
# ---- hooks
|
|
def _ret(self):
|
|
self.cpu.rts()
|
|
|
|
def _set_addr(self, c):
|
|
self.spc_addr = c.a & 0xFFFF
|
|
self.ops.append(('addr', self.spc_addr))
|
|
self._ret()
|
|
|
|
def _write_word(self, c):
|
|
v = c.a & 0xFFFF
|
|
self.spc[self.spc_addr & 0xFFFF] = v & 0xFF
|
|
self.spc[(self.spc_addr + 1) & 0xFFFF] = v >> 8
|
|
self.written[self.spc_addr & 0xFFFF] = self.written[(self.spc_addr + 1) & 0xFFFF] = 1
|
|
self.spc_addr = (self.spc_addr + 2) & 0xFFFF
|
|
self.ops.append(('word', v))
|
|
self._ret()
|
|
|
|
def _dp16(self, o):
|
|
w = self.cpu.wram
|
|
return w[o] | (w[o + 1] << 8)
|
|
|
|
def _stream(self, c):
|
|
dest = self._dp16(0x1C)
|
|
lo = self._dp16(0x64)
|
|
bank = self._dp16(0x66) & 0xFF
|
|
n = self._dp16(0x68)
|
|
n2 = (n + 1) & ~1
|
|
if bank in (0x7E, 0x7F): # tables the sound code built in WRAM (7E:2000-227F)
|
|
data = bytes(c.rd((bank << 16) | ((lo + i) & 0xFFFF)) for i in range(n2))
|
|
else:
|
|
data = lorom_linear(self.rom, bank, lo, n2)
|
|
for i, b in enumerate(data):
|
|
self.spc[(dest + i) & 0xFFFF] = b
|
|
self.written[(dest + i) & 0xFFFF] = 1
|
|
new = (dest + n2) & 0xFFFF
|
|
c.wram[0x1C] = new & 0xFF
|
|
c.wram[0x1D] = new >> 8
|
|
self.log.append(('stream', dest, (bank << 16) | lo, n))
|
|
self.ops.append(('stream', dest, bytes(data)))
|
|
self._ret()
|
|
|
|
def _ipl(self, c):
|
|
lo = self._dp16(0x50)
|
|
bank = self._dp16(0x52) & 0xFF
|
|
off = ((bank & 0x7F) << 15) | (lo & 0x7FFF)
|
|
rom = self.rom
|
|
while True:
|
|
ln = rom[off] | (rom[off + 1] << 8)
|
|
dst = rom[off + 2] | (rom[off + 3] << 8)
|
|
off += 4
|
|
if ln == 0:
|
|
self.ipl_jump = dst
|
|
self.ops.append(('iplend', dst))
|
|
break
|
|
self.ops.append(('ipl', dst, bytes(rom[off:off + ln])))
|
|
self.spc[dst:dst + ln] = rom[off:off + ln]
|
|
self.written[dst:dst + ln] = b'\x01' * ln
|
|
self.log.append(('ipl', dst, ln))
|
|
off += ln
|
|
self._ret()
|
|
|
|
def _noop(self, name):
|
|
def f(c):
|
|
self.log.append((name,))
|
|
self.ops.append((name,))
|
|
self._ret()
|
|
return f
|
|
|
|
def _kick(self, c): # 88:8A38: port0 = read(port0) ^ $80 | $01, no wait
|
|
self.ops.append(('kick',))
|
|
self._ret()
|
|
|
|
def _cmd0(self, c): # port0 = (toggle) | A&$7F, the driver command byte
|
|
self.log.append(('cmd', c.a & 0x7F, list(self.ports_out)))
|
|
self.ops.append(('cmd0', c.a & 0x7F))
|
|
self._ret()
|
|
|
|
def _cmd1(self, c):
|
|
self.log.append(('cmd1', c.a & 0x7F, list(self.ports_out)))
|
|
self.ops.append(('cmd1', c.a & 0x7F))
|
|
self._ret()
|
|
|
|
def _port_read(self, p):
|
|
def f():
|
|
raise Halt(f'unhooked read of APU port {p} at {self.cpu.pc:06X}')
|
|
return f
|
|
|
|
def _port_write(self, p):
|
|
def f(v):
|
|
self.ports_out[p] = v
|
|
self.log.append(('port', p, v))
|
|
self.ops.append(('port', p, v))
|
|
return f
|
|
|
|
# ---- the game's call sequence
|
|
def call(self, cmd, x=0, y=0):
|
|
c = self.cpu
|
|
c.p = 0x04 # native, M=X=0 like the callers (REP #$30)
|
|
c.d = 0
|
|
c.dbr = 0x80
|
|
c.call_long(DISPATCH, a=cmd, x=x, y=y)
|
|
|
|
def boot(self):
|
|
self.call(0x00)
|
|
self.call(0x01)
|
|
self.call(0x19)
|
|
|
|
|
|
def write_ops(ops, path):
|
|
"""Text op list, one per line (consumed by re/tools/snd_play.cpp):
|
|
ipl DEST HEX | iplend JUMP | enter-transfer | end-transfer | addr A | word W | stream DEST HEX |
|
|
cmd0 C | cmd1 C | kick | port P V | play FRAMES (numbers hex)"""
|
|
with open(path, 'w') as f:
|
|
for o in ops:
|
|
k = o[0]
|
|
if k in ('ipl', 'stream'):
|
|
f.write(f'{k} {o[1]:04X} {o[2].hex()}\n')
|
|
elif len(o) == 1:
|
|
f.write(k + '\n')
|
|
else:
|
|
f.write(k + ' ' + ' '.join(f'{v:X}' for v in o[1:]) + '\n')
|
|
|
|
|
|
def sound_sets(rom):
|
|
"""Table 0 of the sound container at 88:8A48: 38 size-prefixed sets of three id lists."""
|
|
base = 0x40A48
|
|
be16 = lambda o: (rom[o] << 8) | rom[o + 1]
|
|
t0 = base + ((be16(base) << 16) | be16(base + 2))
|
|
count = be16(t0)
|
|
p = t0 + 2
|
|
sets = []
|
|
for _ in range(count):
|
|
size = rom[p] | (rom[p + 1] << 8)
|
|
q = p + 2
|
|
lists = []
|
|
for _k in range(3):
|
|
n = rom[q]
|
|
lists.append(list(rom[q + 1:q + 1 + n]))
|
|
q += 1 + n
|
|
sets.append(lists)
|
|
p += 2 + size
|
|
return sets
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument('rom')
|
|
ap.add_argument('--compare')
|
|
ap.add_argument('--song', type=lambda s: int(s, 0), action='append', default=[])
|
|
ap.add_argument('--list', action='store_true')
|
|
ap.add_argument('--log', action='store_true')
|
|
ap.add_argument('--ops', help='write the APU op list here')
|
|
ap.add_argument('--sfx', type=lambda s: int(s, 0), action='append', default=[], help='cmd $14 sound effect id(s) after the songs')
|
|
ap.add_argument('--play', type=int, default=0, help='append "play N frames" after each command (for --ops)')
|
|
args = ap.parse_args()
|
|
rom = open(args.rom, 'rb').read()
|
|
if args.list:
|
|
for i, (a, b, c) in enumerate(sound_sets(rom)):
|
|
print(f'set {i:02X}: A={" ".join(f"{v:02X}" for v in a)} | B={" ".join(f"{v:02X}" for v in b)} | C={" ".join(f"{v:02X}" for v in c)}')
|
|
return
|
|
sim = SoundSim(rom)
|
|
sim.boot()
|
|
for s in args.song:
|
|
sim.call(0x13, x=0, y=s)
|
|
if args.play:
|
|
sim.ops.append(('play', args.play))
|
|
for e in args.sfx:
|
|
sim.call(0x14, x=0, y=e)
|
|
if args.play:
|
|
sim.ops.append(('play', args.play))
|
|
if args.ops:
|
|
write_ops(sim.ops, args.ops)
|
|
if args.log:
|
|
for e in sim.log:
|
|
if e[0] != 'ipl':
|
|
print(e)
|
|
if args.compare:
|
|
ref = open(args.compare, 'rb').read()
|
|
lo, hi = 0x0800, 0x10000
|
|
wr = sum(sim.written[lo:hi])
|
|
diffs = [a for a in range(lo, hi) if sim.written[a] and ref[a] != sim.spc[a]]
|
|
print(f'compare {lo:04X}-{hi - 1:04X}: {wr} bytes uploaded, {len(diffs)} differ')
|
|
runs = []
|
|
for a in diffs:
|
|
if runs and a == runs[-1][1] + 1:
|
|
runs[-1][1] = a
|
|
else:
|
|
runs.append([a, a])
|
|
for a, b in runs[:30]:
|
|
print(f' {a:04X}-{b:04X}')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|