pysoundmonitor 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,38 @@
1
+ """Pure-Python reader and detector for Soundmonitor (64'er / Hulsbeck) SID tunes.
2
+
3
+ Soundmonitor is HVSC tracker #6. Its player is relocatable and the SID-header
4
+ addresses are not a reliable locator, so this package finds the engine by a
5
+ small hardware-register fingerprint and decodes the documented section->stream
6
+ song-data structures into a :class:`Song` model. Scope is the container/detection
7
+ plus a song-data reader -- not a byte-exact playback engine.
8
+ """
9
+
10
+ from .errors import SidParseError, SoundMonitorError
11
+ from .model import (
12
+ FilterTail,
13
+ Instrument,
14
+ NoteFreqTable,
15
+ Row,
16
+ Section,
17
+ Song,
18
+ )
19
+ from .reader import find_fingerprint, parse, read
20
+ from .sidparser import SoundMonitorSidParser
21
+
22
+ __version__ = "0.1.0"
23
+
24
+ __all__ = [
25
+ "FilterTail",
26
+ "Instrument",
27
+ "NoteFreqTable",
28
+ "Row",
29
+ "Section",
30
+ "SidParseError",
31
+ "Song",
32
+ "SoundMonitorError",
33
+ "SoundMonitorSidParser",
34
+ "__version__",
35
+ "find_fingerprint",
36
+ "parse",
37
+ "read",
38
+ ]
@@ -0,0 +1,144 @@
1
+ """Documented Soundmonitor (64'er / Hulsbeck) song-data layout constants.
2
+
3
+ Every value here is a *structural fact* transcribed from the reverse-engineering
4
+ architecture reference (``re-trackers/Soundmonitor/soundmonitor-architecture.md``)
5
+ - table geometry, the 16-byte instrument-record field map, section-header and row
6
+ layouts, and a tiny relocation-invariant engine fingerprint. No player code is
7
+ reproduced: the fingerprint is expressed purely as writes to fixed C64 hardware
8
+ registers plus an immediate guard constant, which are functional facts, not
9
+ copyrightable expression.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ # --- Recognizer fingerprint (relocation-invariant) --------------------------
15
+ # Soundmonitor is CIA-timed and programs its OWN play period: the section loader
16
+ # reads the CIA-1 Timer-A latch from the per-section header and writes it to the
17
+ # fixed hardware registers $DC04/$DC05, guarding the hi byte with ``CMP #$06``.
18
+ # These target absolute hardware addresses that never relocate, so the sequence
19
+ # is a load-address-independent signature of the engine.
20
+ STA_DC04 = bytes((0x8D, 0x04, 0xDC)) # STA $DC04 (Timer-A latch lo)
21
+ STA_DC05 = bytes((0x8D, 0x05, 0xDC)) # STA $DC05 (Timer-A latch hi)
22
+ CMP_06 = bytes((0xC9, 0x06)) # CMP #$06 (hi-latch guard)
23
+ # Max byte gap between the two CIA stores for the fingerprint to match.
24
+ FINGERPRINT_WINDOW = 0x10
25
+
26
+ # ``LDA abs,X`` opcode: the section loader indexes the page-aligned split
27
+ # pointer tables (and the note-freq tables) with it, so its operands recover the
28
+ # data-region base page and the note-freq table addresses relocation-tolerantly.
29
+ LDA_ABSX = 0xBD
30
+ # ``CPX abs`` / ``LDX abs`` opcodes: the section-advance code compares the live
31
+ # section index against ``sec_last`` (``CPX``) and reloads ``sec_start``
32
+ # (``LDX``) from two adjacent player globals, so their operands recover the song
33
+ # section bounds relocation-tolerantly (see ``_recover_section_bounds``).
34
+ CPX_ABS = 0xEC
35
+ LDX_ABS = 0xAE
36
+
37
+ # --- Data-region table geometry (byte offsets from the data base) -----------
38
+ # The per-tune data region is a run of page-aligned split (lo/hi) pointer and
39
+ # transpose tables indexed by the section number, followed by the instrument
40
+ # records. Layout mirrors the Only_3 map ($A000 base) from the architecture doc.
41
+ PAGE = 0x100
42
+ V0_PTR_LO = 0x000
43
+ V0_PTR_HI = 0x100
44
+ V0_XPOSE = 0x200
45
+ V0_XPOSE2 = 0x300
46
+ V1_PTR_LO = 0x400
47
+ V1_PTR_HI = 0x500
48
+ V1_XPOSE = 0x600
49
+ V1_XPOSE2 = 0x700
50
+ V2_PTR_LO = 0x800
51
+ V2_PTR_HI = 0x900
52
+ V2_XPOSE = 0xA00
53
+ V2_XPOSE2 = 0xB00
54
+ SECTION_HEADER_PTR_LO = 0xC00
55
+ SECTION_HEADER_PTR_HI = 0xD00
56
+ INSTRUMENTS = 0xE00
57
+
58
+ # Per-voice (stream-ptr-lo, stream-ptr-hi, transpose) page offsets, voice order.
59
+ VOICE_PTR_LO = (V0_PTR_LO, V1_PTR_LO, V2_PTR_LO)
60
+ VOICE_PTR_HI = (V0_PTR_HI, V1_PTR_HI, V2_PTR_HI)
61
+ VOICE_XPOSE = (V0_XPOSE, V1_XPOSE, V2_XPOSE)
62
+
63
+ # Pages that must all be present for a run of pages to be the data region.
64
+ BASE_PROBE_OFFSETS = (V0_PTR_LO, V1_PTR_LO, V2_PTR_LO, SECTION_HEADER_PTR_LO)
65
+
66
+ # --- Instrument records -----------------------------------------------------
67
+ INSTRUMENT_STRIDE = 24 # record spacing: 16 record bytes + 8-byte filter tail
68
+ INSTRUMENT_RECORD_LEN = 16
69
+ FILTER_TAIL_LEN = 8
70
+ # record[16] doubles as the filter-tail vol/mode byte and the "no tail" marker.
71
+ FILTER_MARKER = 16
72
+ NO_FILTER_TAIL = 0xFF
73
+ MAX_INSTRUMENTS = INSTRUMENT_STRIDE # ctrl low-nibble + base can reach this many
74
+
75
+ # 16-byte instrument record field offsets (architecture doc record map).
76
+ INST_CTRL_GATE = 0 # key-on CTRL (waveform + gate)
77
+ INST_AD = 1
78
+ INST_SR = 2
79
+ INST_GLIDE_RATE_LO = 3
80
+ INST_PW = 4 # lo-nibble<<4 -> PW lo, hi-nibble -> PW hi
81
+ INST_PW_UP_DWELL = 5
82
+ INST_PW_DOWN_DWELL = 6
83
+ INST_PW_STEP = 7
84
+ INST_SUSTAIN_CTRL = 8 # re-emitted on a rest (gate off)
85
+ INST_MODE = 9 # bit5 abs/PW-up-suppress, bit4 PW-sweep enable, bits0/1 glide mode
86
+ INST_GLIDE_ENABLE = 10
87
+ INST_GLIDE_RATE_HI = 11
88
+ INST_VIB_DEPTH = 12
89
+ INST_VIB_PERIOD = 13 # &$7F half-period, bit7 direction
90
+ INST_VIB_DELAY = 14
91
+ INST_DETUNE = 15
92
+
93
+ # 8-byte filter tail field offsets (relative to the tail start = record[16]).
94
+ FT_VOL_MODE = 0
95
+ FT_RES_FILT = 1 # -> $D417
96
+ FT_CUTOFF_HI = 2 # cutoff-hi seed
97
+ FT_UP_DWELL = 3
98
+ FT_DOWN_DWELL = 4
99
+ FT_STEP = 5
100
+ FT_BOUND = 6
101
+ FT_FLAGS = 7 # per-voice init/reload/reinit/ping-pong bits
102
+
103
+ # --- Section header ---------------------------------------------------------
104
+ SH_LATCH_LO = 0 # CIA Timer-A latch lo (play-cadence source)
105
+ SH_LATCH_HI = 1
106
+ SH_TEMPO = 2 # tempo divider reload
107
+ SH_PATLEN = 3 # pattern length / row loop
108
+ SH_VOL_RAMP = 4 # volume-ramp config ($FF = none)
109
+ SH_BASE_VOL = 5 # steady base-volume nibble
110
+ SH_ARP_TABLE = 6 # start of the 8-entry arp-note table
111
+ ARP_TABLE_LEN = 8
112
+ SECTION_HEADER_LEN = SH_ARP_TABLE + ARP_TABLE_LEN
113
+
114
+ # --- Pattern rows (per voice, per section: flat 2-byte [note][ctrl] rows) ----
115
+ ROW_LEN = 2
116
+ NOTE_REST = 0x00 # re-emit the saved sustain ctrl
117
+ NOTE_TIE = 0x80 # leave the voice untouched (legato hold)
118
+ NOTE_TRIGGER = 0x80 # note bit7: new-note key-on trigger
119
+ NOTE_INDEX_MASK = 0x7F # note bits0-6: freq-table index
120
+ CTRL_INSTR_MASK = 0x0F # ctrl bits0-3: instrument index
121
+ CTRL_PORTAMENTO = 0x10 # ctrl bit4: keep old freq (slide)
122
+ CTRL_ABSOLUTE = 0x20 # ctrl bit5: skip the section transpose
123
+ CTRL_ARP_ENABLE = 0x40 # ctrl bit6: enable the arp/glide-target chain
124
+ CTRL_INSTR_BASE = 0x80 # ctrl bit7 clear: add the per-section instrument base
125
+
126
+ # Cap on rows/sections walked, so a malformed image cannot loop unboundedly.
127
+ MAX_SECTIONS = 256
128
+ MAX_PATTERN_LEN = 256
129
+
130
+ # --- Note-frequency tables --------------------------------------------------
131
+ # Two parallel u8 tables (freq hi, then freq lo) of one entry per semitone; the
132
+ # hi table is an octave ramp (non-decreasing, doubling per octave). The lo table
133
+ # starts exactly ``NOTE_FREQ_LEN`` bytes after the hi table (the two tables abut,
134
+ # and the player reads ``LDA NoteFreqHi,X`` / ``LDA NoteFreqLo,X`` -- adjacent
135
+ # absolute-indexed operands whose difference IS the table length). On real HVSC
136
+ # tunes the tables are 95 entries (the hi ramp climbs 01..f8 over indices 0..94).
137
+ NOTE_FREQ_LEN = 95
138
+ # Candidate table lengths tried (largest valid wins) when the pair is located
139
+ # from the player's paired ``LDA`` operands.
140
+ NOTE_FREQ_LENGTHS = (96, 95)
141
+ # Content signature used to validate a candidate hi table.
142
+ NOTE_FREQ_HI_START_MAX = 0x04 # first hi byte is small (low octave)
143
+ NOTE_FREQ_HI_END_MIN = 0x20 # last hi byte has climbed into the high octaves
144
+ NOTE_FREQ_MIN_STEPS = 6 # at least this many upward steps across the ramp
@@ -0,0 +1,11 @@
1
+ """Exceptions for pysoundmonitor."""
2
+
3
+ from pysidtracker import SidError
4
+
5
+
6
+ class SoundMonitorError(SidError):
7
+ """Base error for all pysoundmonitor failures."""
8
+
9
+
10
+ class SidParseError(SoundMonitorError):
11
+ """A SID/PRG image could not be parsed as a Soundmonitor tune."""
@@ -0,0 +1,206 @@
1
+ """Dataclass model of a decoded Soundmonitor song.
2
+
3
+ The song is a *section sequence*; each section carries a CIA play cadence, a
4
+ tempo, an arp table, and three per-voice ``[note][ctrl]`` pattern streams. New-
5
+ note rows reference a 16-byte instrument record (optionally trailed by an 8-byte
6
+ global-filter tail). See ``docs/format.md`` for the layout narrative.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass, field
12
+ from typing import List, Optional, Tuple
13
+
14
+ from . import constants as c
15
+
16
+
17
+ @dataclass
18
+ class Row:
19
+ """One decoded pattern row (``note`` byte + ``ctrl`` byte)."""
20
+
21
+ note: int
22
+ ctrl: int
23
+ is_rest: bool
24
+ is_tie: bool
25
+ trigger: bool
26
+ freq_index: int
27
+ instrument: int
28
+ portamento: bool
29
+ absolute: bool
30
+ arp_enable: bool
31
+ instrument_base: bool
32
+
33
+ @classmethod
34
+ def decode(cls, note: int, ctrl: int) -> "Row":
35
+ """Decode a raw ``(note, ctrl)`` pair per the documented row encoding."""
36
+ is_rest = note == c.NOTE_REST
37
+ is_tie = note == c.NOTE_TIE
38
+ # A tie is note==$80: bit7 set with a zero index; it is a hold, not a
39
+ # key-on. A rest is note==$00. Any other value is a real note.
40
+ trigger = bool(note & c.NOTE_TRIGGER) and not is_tie
41
+ return cls(
42
+ note=note,
43
+ ctrl=ctrl,
44
+ is_rest=is_rest,
45
+ is_tie=is_tie,
46
+ trigger=trigger,
47
+ freq_index=note & c.NOTE_INDEX_MASK,
48
+ instrument=ctrl & c.CTRL_INSTR_MASK,
49
+ portamento=bool(ctrl & c.CTRL_PORTAMENTO),
50
+ absolute=bool(ctrl & c.CTRL_ABSOLUTE),
51
+ arp_enable=bool(ctrl & c.CTRL_ARP_ENABLE),
52
+ instrument_base=not ctrl & c.CTRL_INSTR_BASE,
53
+ )
54
+
55
+
56
+ @dataclass
57
+ class FilterTail:
58
+ """The optional 8-byte global-filter tail of an instrument record."""
59
+
60
+ vol_mode: int
61
+ res_filt: int
62
+ cutoff_hi: int
63
+ up_dwell: int
64
+ down_dwell: int
65
+ step: int
66
+ bound: int
67
+ flags: int
68
+ raw: bytes
69
+
70
+ @classmethod
71
+ def from_bytes(cls, tail: bytes) -> "FilterTail":
72
+ """Decode an 8-byte filter tail."""
73
+ return cls(
74
+ vol_mode=tail[c.FT_VOL_MODE],
75
+ res_filt=tail[c.FT_RES_FILT],
76
+ cutoff_hi=tail[c.FT_CUTOFF_HI],
77
+ up_dwell=tail[c.FT_UP_DWELL],
78
+ down_dwell=tail[c.FT_DOWN_DWELL],
79
+ step=tail[c.FT_STEP],
80
+ bound=tail[c.FT_BOUND],
81
+ flags=tail[c.FT_FLAGS],
82
+ raw=bytes(tail),
83
+ )
84
+
85
+
86
+ @dataclass
87
+ class Instrument:
88
+ """A decoded 16-byte instrument record (+ optional filter tail)."""
89
+
90
+ index: int
91
+ ctrl_gate: int
92
+ ad: int
93
+ sr: int
94
+ glide_rate_lo: int
95
+ pw: int
96
+ pw_up_dwell: int
97
+ pw_down_dwell: int
98
+ pw_step: int
99
+ sustain_ctrl: int
100
+ mode: int
101
+ glide_enable: int
102
+ glide_rate_hi: int
103
+ vib_depth: int
104
+ vib_period: int
105
+ vib_delay: int
106
+ detune: int
107
+ raw: bytes
108
+ filter: Optional[FilterTail] = None
109
+
110
+ @property
111
+ def pw_lo(self) -> int:
112
+ """Seeded pulse-width low byte (``(pw & $0F) << 4``)."""
113
+ return (self.pw & 0x0F) << 4
114
+
115
+ @property
116
+ def pw_hi(self) -> int:
117
+ """Seeded pulse-width high nibble (``pw >> 4``)."""
118
+ return self.pw >> 4
119
+
120
+ @classmethod
121
+ def from_record(cls, index: int, record: bytes) -> "Instrument":
122
+ """Decode a record of at least 16 bytes (24 with a filter tail).
123
+
124
+ The tail is present when the marker byte ``record[16]`` is not ``$FF``
125
+ and the buffer carries the 8 trailing bytes.
126
+ """
127
+ tail = None
128
+ if (
129
+ len(record) >= c.FILTER_MARKER + c.FILTER_TAIL_LEN
130
+ and record[c.FILTER_MARKER] != c.NO_FILTER_TAIL
131
+ ):
132
+ tail = FilterTail.from_bytes(
133
+ record[c.FILTER_MARKER : c.FILTER_MARKER + c.FILTER_TAIL_LEN]
134
+ )
135
+ return cls(
136
+ index=index,
137
+ ctrl_gate=record[c.INST_CTRL_GATE],
138
+ ad=record[c.INST_AD],
139
+ sr=record[c.INST_SR],
140
+ glide_rate_lo=record[c.INST_GLIDE_RATE_LO],
141
+ pw=record[c.INST_PW],
142
+ pw_up_dwell=record[c.INST_PW_UP_DWELL],
143
+ pw_down_dwell=record[c.INST_PW_DOWN_DWELL],
144
+ pw_step=record[c.INST_PW_STEP],
145
+ sustain_ctrl=record[c.INST_SUSTAIN_CTRL],
146
+ mode=record[c.INST_MODE],
147
+ glide_enable=record[c.INST_GLIDE_ENABLE],
148
+ glide_rate_hi=record[c.INST_GLIDE_RATE_HI],
149
+ vib_depth=record[c.INST_VIB_DEPTH],
150
+ vib_period=record[c.INST_VIB_PERIOD],
151
+ vib_delay=record[c.INST_VIB_DELAY],
152
+ detune=record[c.INST_DETUNE],
153
+ raw=bytes(record[: c.INSTRUMENT_RECORD_LEN]),
154
+ filter=tail,
155
+ )
156
+
157
+
158
+ @dataclass
159
+ class Section:
160
+ """One song-step: cadence + tempo + arp table + three voice streams."""
161
+
162
+ index: int
163
+ header_addr: int
164
+ cia_latch: int
165
+ tempo: int
166
+ pattern_length: int
167
+ vol_ramp: int
168
+ base_volume: int
169
+ arp_table: Tuple[int, ...]
170
+ transpose: Tuple[int, int, int]
171
+ voices: List[List[Row]]
172
+
173
+ @property
174
+ def cadence(self) -> int:
175
+ """Play period in CPU cycles per call (``CIA latch + 1``)."""
176
+ return self.cia_latch + 1
177
+
178
+
179
+ @dataclass
180
+ class NoteFreqTable:
181
+ """The parallel note-frequency hi/lo tables (one entry per semitone)."""
182
+
183
+ hi: List[int]
184
+ lo: List[int]
185
+ addr: Optional[int] = None
186
+
187
+ def freq(self, index: int) -> int:
188
+ """16-bit SID frequency for semitone ``index``."""
189
+ return (self.hi[index] << 8) | self.lo[index]
190
+
191
+
192
+ @dataclass
193
+ class Song:
194
+ """A decoded Soundmonitor tune."""
195
+
196
+ base: int
197
+ player_anchor: int
198
+ header: object = None
199
+ sections: List[Section] = field(default_factory=list)
200
+ instruments: List[Instrument] = field(default_factory=list)
201
+ note_freq: Optional[NoteFreqTable] = None
202
+
203
+ @property
204
+ def cia_latch(self) -> Optional[int]:
205
+ """CIA latch of the first section (the initial play cadence)."""
206
+ return self.sections[0].cia_latch if self.sections else None
@@ -0,0 +1,384 @@
1
+ """Decode a Soundmonitor ``.sid``/``.prg`` image into a :class:`Song`.
2
+
3
+ The player is relocatable and the SID-header addresses are not a reliable
4
+ locator, so the song data is found *relocation- and build-tolerantly* from the
5
+ player's own code operands: the engine is recognised by its CIA section-loader
6
+ fingerprint or its note-frequency tables, the data-region base page comes from
7
+ the loader's table-indexing operands, the section bounds from the section-advance
8
+ ``CPX``/``LDX`` operands, and the note-freq tables from the paired ``LDA`` reads.
9
+ A packed/relocating tune is unpacked by emulating its init first. The documented
10
+ structures are then decoded into the model; this is a song-data reader, not a
11
+ playback engine.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from typing import Dict, List, Optional, Set
17
+
18
+ import numpy as np
19
+
20
+ from pysidtracker import SidImage, read_bytes
21
+
22
+ from . import constants as c
23
+ from .errors import SidParseError
24
+ from .model import Instrument, NoteFreqTable, Row, Section, Song
25
+
26
+
27
+ def _operand_targets(image: SidImage, opcode: int) -> Dict[int, int]:
28
+ """Map every absolute operand of ``opcode`` in the image to its first site.
29
+
30
+ An absolute-addressed 6502 instruction is ``opcode lo hi``; this returns
31
+ ``{lo | hi<<8: site_address}`` for every occurrence, letting a relocatable
32
+ player's own table/global addresses be recovered from its code operands.
33
+ """
34
+ mem = np.frombuffer(bytes(image.mem), dtype=np.uint8)
35
+ sites = np.nonzero(mem[:-2] == opcode)[0]
36
+ targets: Dict[int, int] = {}
37
+ for site in sites.tolist():
38
+ target = int(mem[site + 1]) | (int(mem[site + 2]) << 8)
39
+ targets.setdefault(target, site)
40
+ return targets
41
+
42
+
43
+ def find_cia_fingerprint(image: SidImage) -> Optional[int]:
44
+ """Address of the CIA-timer section-loader fingerprint, or ``None``.
45
+
46
+ Matches the relocation-invariant ``STA $DC04 ... CMP #$06 ... STA $DC05``
47
+ sequence (writes to fixed hardware registers). Present in the CIA-timed
48
+ builds ($C000 Hulsbeck / $1000); absent in the fixed-cadence builds, which
49
+ are recognised by their note-freq tables instead.
50
+ """
51
+ span = len(c.STA_DC04) + c.FINGERPRINT_WINDOW
52
+ for pos in image.find_all(c.STA_DC04):
53
+ window = image.slice(pos, min(span, len(image.mem) - pos))
54
+ hi = window.find(c.STA_DC05, len(c.STA_DC04))
55
+ if hi < 0:
56
+ continue
57
+ guard = window.find(c.CMP_06, len(c.STA_DC04))
58
+ if 0 <= guard < hi:
59
+ return pos
60
+ return None
61
+
62
+
63
+ def find_fingerprint(image: SidImage) -> Optional[int]:
64
+ """Address of the Soundmonitor engine, or ``None`` -- build-tolerant.
65
+
66
+ Returns the CIA section-loader fingerprint when present (the CIA-timed
67
+ builds), else the note-frequency hi-table address (the fixed-cadence
68
+ builds carry the same octave-ramp tables, read via paired ``LDA`` operands).
69
+ Either is a truthy relocation-tolerant anchor for :meth:`detect`.
70
+ """
71
+ cia = find_cia_fingerprint(image)
72
+ if cia is not None:
73
+ return cia
74
+ freq = _find_note_freq_addr(image)
75
+ if freq is not None:
76
+ return freq
77
+ return None
78
+
79
+
80
+ def _base_candidates(image: SidImage) -> List[int]:
81
+ """Candidate data-region base addresses from the loader's table operands.
82
+
83
+ The section loader reads the split pointer tables with ``LDA $pp00,X``; a
84
+ base page is any ``$pp00`` operand whose voice/section-header lo tables are
85
+ all present. A relocated image can present a run of consecutive candidate
86
+ pages; the caller disambiguates by which one actually decodes sections.
87
+ """
88
+ pages: Set[int] = set()
89
+ for target in _operand_targets(image, c.LDA_ABSX):
90
+ if target & 0xFF == 0x00:
91
+ pages.add(target >> 8)
92
+ probe_pages = {off >> 8 for off in c.BASE_PROBE_OFFSETS}
93
+ return [
94
+ page << 8
95
+ for page in sorted(pages)
96
+ if all((page + rel) in pages for rel in probe_pages)
97
+ ]
98
+
99
+
100
+ def _bounds_candidates(image: SidImage) -> List[tuple]:
101
+ """Candidate ``(sec_start, sec_last)`` pairs from the section-advance code.
102
+
103
+ ``SUB_c940`` does ``CPX sec_last`` then, on wrap, ``LDX sec_start``; the two
104
+ globals are adjacent (``sec_last`` at ``A``, ``sec_start`` at ``A+1``), so a
105
+ ``CPX $A`` whose neighbour ``$A+1`` is an ``LDX`` operand pins the bounds.
106
+ ``sec_start`` may exceed ``sec_last`` (the section counter wraps mod 256).
107
+ """
108
+ cpx = _operand_targets(image, c.CPX_ABS)
109
+ ldx = _operand_targets(image, c.LDX_ABS)
110
+ out: List[tuple] = []
111
+ for last_addr in sorted(cpx):
112
+ if last_addr + 1 in ldx:
113
+ out.append((image.peek(last_addr + 1), image.peek(last_addr)))
114
+ return out
115
+
116
+
117
+ def _section_span(start: int, last: int) -> List[int]:
118
+ """Section indices from ``start`` up to ``last`` inclusive, wrapping mod 256."""
119
+ count = ((last - start) & 0xFF) + 1
120
+ return [(start + k) & 0xFF for k in range(count)]
121
+
122
+
123
+ def _section_ok(image: SidImage, base: int, index: int) -> bool:
124
+ """Cheap validity probe: header + all voice stream pointers land in-image."""
125
+ header = image.ptr(
126
+ base + c.SECTION_HEADER_PTR_LO, base + c.SECTION_HEADER_PTR_HI, index
127
+ )
128
+ if not _in_image(image, header):
129
+ return False
130
+ patlen = image.peek(header + c.SH_PATLEN)
131
+ if patlen == 0 or patlen > c.MAX_PATTERN_LEN:
132
+ return False
133
+ for voice in range(3):
134
+ stream = image.ptr(
135
+ base + c.VOICE_PTR_LO[voice], base + c.VOICE_PTR_HI[voice], index
136
+ )
137
+ if not _in_image(image, stream):
138
+ return False
139
+ return True
140
+
141
+
142
+ def _count_sections(image: SidImage, base: int, start: int, last: int) -> int:
143
+ """Valid sections decodable from ``start`` to ``last`` (stops at first bad)."""
144
+ count = 0
145
+ for index in _section_span(start, last):
146
+ if not _section_ok(image, base, index):
147
+ break
148
+ count += 1
149
+ return count
150
+
151
+
152
+ def _plan(image: SidImage) -> tuple:
153
+ """Choose ``(base, start, last, count)`` that decodes the most valid sections.
154
+
155
+ Enumerates the operand-recovered base and section-bound candidates (falling
156
+ back to the load page and a full walk) and picks the combination yielding the
157
+ largest bounded run of valid sections -- robust to base ambiguity and to the
158
+ relocation-dependent player globals that a blind walk would run into garbage.
159
+ """
160
+ bases = _base_candidates(image) or [image.load & 0xFF00]
161
+ bounds = _bounds_candidates(image) or [(0, c.MAX_SECTIONS - 1)]
162
+ best = (bases[0], bounds[0][0], bounds[0][1], -1)
163
+ for base in bases:
164
+ for start, last in bounds:
165
+ count = _count_sections(image, base, start, last)
166
+ if count > best[3]:
167
+ best = (base, start, last, count)
168
+ return best
169
+
170
+
171
+ def _recover_base(image: SidImage) -> int:
172
+ """The chosen data-region base address (see :func:`_plan`)."""
173
+ return _plan(image)[0]
174
+
175
+
176
+ def _in_image(image: SidImage, addr: int) -> bool:
177
+ return image.load <= addr < image.end
178
+
179
+
180
+ def _decode_stream(image: SidImage, addr: int, rows: int) -> List[Row]:
181
+ out: List[Row] = []
182
+ rows = min(rows, c.MAX_PATTERN_LEN)
183
+ for row in range(rows):
184
+ base = addr + row * c.ROW_LEN
185
+ out.append(Row.decode(image.peek(base), image.peek(base + 1)))
186
+ return out
187
+
188
+
189
+ def _decode_section(image: SidImage, base: int, index: int) -> Optional[Section]:
190
+ header = image.ptr(
191
+ base + c.SECTION_HEADER_PTR_LO, base + c.SECTION_HEADER_PTR_HI, index
192
+ )
193
+ if not _in_image(image, header):
194
+ return None
195
+ patlen = image.peek(header + c.SH_PATLEN)
196
+ if patlen == 0 or patlen > c.MAX_PATTERN_LEN:
197
+ return None
198
+ latch = image.peek(header + c.SH_LATCH_LO) | (
199
+ image.peek(header + c.SH_LATCH_HI) << 8
200
+ )
201
+ arp = tuple(image.peek(header + c.SH_ARP_TABLE + i) for i in range(c.ARP_TABLE_LEN))
202
+ voices: List[List[Row]] = []
203
+ transpose = []
204
+ for voice in range(3):
205
+ stream = image.ptr(
206
+ base + c.VOICE_PTR_LO[voice], base + c.VOICE_PTR_HI[voice], index
207
+ )
208
+ if not _in_image(image, stream):
209
+ return None
210
+ voices.append(_decode_stream(image, stream, patlen))
211
+ transpose.append(image.peek(base + c.VOICE_XPOSE[voice] + index))
212
+ return Section(
213
+ index=index,
214
+ header_addr=header,
215
+ cia_latch=latch,
216
+ tempo=image.peek(header + c.SH_TEMPO),
217
+ pattern_length=patlen,
218
+ vol_ramp=image.peek(header + c.SH_VOL_RAMP),
219
+ base_volume=image.peek(header + c.SH_BASE_VOL),
220
+ arp_table=arp,
221
+ transpose=(transpose[0], transpose[1], transpose[2]),
222
+ voices=voices,
223
+ )
224
+
225
+
226
+ def _decode_sections(
227
+ image: SidImage, base: int, start: int, last: int
228
+ ) -> List[Section]:
229
+ """Decode the song's sections over ``start..last`` (inclusive, wrapping).
230
+
231
+ Stops at the first invalid section. ``base`` and the ``(start, last)`` bounds
232
+ come from :func:`_plan`, which recovers them from the player's own operands
233
+ (so a bounded, correct set is decoded rather than walking a relocation-
234
+ dependent table into garbage and hitting the 256 cap).
235
+ """
236
+ sections: List[Section] = []
237
+ for index in _section_span(start, last):
238
+ section = _decode_section(image, base, index)
239
+ if section is None:
240
+ break
241
+ sections.append(section)
242
+ return sections
243
+
244
+
245
+ def _instrument_indices(sections: List[Section]) -> List[int]:
246
+ used: Set[int] = set()
247
+ for section in sections:
248
+ for voice in section.voices:
249
+ for row in voice:
250
+ if row.trigger:
251
+ used.add(row.instrument)
252
+ return sorted(used)
253
+
254
+
255
+ def _decode_instruments(
256
+ image: SidImage, base: int, indices: List[int]
257
+ ) -> List[Instrument]:
258
+ out: List[Instrument] = []
259
+ table = base + c.INSTRUMENTS
260
+ for index in indices:
261
+ addr = table + index * c.INSTRUMENT_STRIDE
262
+ if not _in_image(image, addr):
263
+ continue
264
+ record = image.slice(addr, c.INSTRUMENT_STRIDE)
265
+ out.append(Instrument.from_record(index, record))
266
+ return out
267
+
268
+
269
+ def decode_note_freq(
270
+ image: SidImage, addr: int, length: int = c.NOTE_FREQ_LEN
271
+ ) -> NoteFreqTable:
272
+ """Decode the parallel hi/lo note-frequency tables at ``addr``."""
273
+ hi = list(image.slice(addr, length))
274
+ lo = list(image.slice(addr + length, length))
275
+ return NoteFreqTable(hi=hi, lo=lo, addr=addr)
276
+
277
+
278
+ def _valid_freq_hi(image: SidImage, addr: int, length: int) -> bool:
279
+ """Is ``[addr, addr+length)`` a valid note-freq hi octave ramp?"""
280
+ if addr < 0 or addr + length > len(image.mem):
281
+ return False
282
+ hi = np.frombuffer(image.slice(addr, length), dtype=np.uint8).astype(np.int16)
283
+ if hi[0] == 0 or hi[0] > c.NOTE_FREQ_HI_START_MAX:
284
+ return False
285
+ if hi[-1] < c.NOTE_FREQ_HI_END_MIN:
286
+ return False
287
+ diffs = np.diff(hi)
288
+ if not bool((diffs >= 0).all()):
289
+ return False
290
+ return int((diffs > 0).sum()) >= c.NOTE_FREQ_MIN_STEPS
291
+
292
+
293
+ def _find_note_freq(image: SidImage) -> Optional[tuple]:
294
+ """Locate the note-freq tables from the player's paired ``LDA`` operands.
295
+
296
+ The player reads ``LDA NoteFreqHi,X`` and ``LDA NoteFreqLo,X``; the two
297
+ absolute-indexed operands abut (``lo = hi + length``), so a pair of
298
+ ``LDA abs,X`` targets that differ by a candidate table length and whose hi
299
+ table is a valid octave ramp pins the tables regardless of relocation.
300
+ Returns ``(hi_addr, length)`` or ``None``.
301
+ """
302
+ targets = set(_operand_targets(image, c.LDA_ABSX))
303
+ for hi_addr in sorted(targets):
304
+ for length in c.NOTE_FREQ_LENGTHS:
305
+ if hi_addr + length not in targets:
306
+ continue
307
+ if _valid_freq_hi(image, hi_addr, length):
308
+ return (hi_addr, length)
309
+ return None
310
+
311
+
312
+ def _find_note_freq_addr(image: SidImage) -> Optional[int]:
313
+ found = _find_note_freq(image)
314
+ return found[0] if found is not None else None
315
+
316
+
317
+ def locate_note_freq(image: SidImage) -> Optional[NoteFreqTable]:
318
+ """Locate and decode the note-frequency tables, or ``None``.
319
+
320
+ Uses the relocation-tolerant paired-operand locator (:func:`_find_note_freq`);
321
+ returns ``None`` only when the player carries no such table pair.
322
+ """
323
+ found = _find_note_freq(image)
324
+ if found is None:
325
+ return None
326
+ hi_addr, length = found
327
+ return decode_note_freq(image, hi_addr, length)
328
+
329
+
330
+ def _run_init(image: SidImage) -> bool:
331
+ """Emulate the tune's init so a packed/relocating player lands in memory.
332
+
333
+ Returns ``True`` if init ran. A no-op (returns ``False``) for a bare ``.prg``
334
+ with no header, or when the optional emulator dependency is unavailable.
335
+ """
336
+ if image.header is None:
337
+ return False
338
+ try:
339
+ from pysidtracker import run_init
340
+ from pysidtracker.image import MEM_SIZE
341
+
342
+ run_init(image)
343
+ image.end = MEM_SIZE
344
+ return True
345
+ except SidParseError:
346
+ return False
347
+
348
+
349
+ def parse(data: bytes) -> Song:
350
+ """Decode raw ``.sid``/``.prg`` ``data`` into a :class:`Song`.
351
+
352
+ Recognises the engine build-tolerantly (CIA-timed or fixed-cadence). A
353
+ packed/relocating tune only exposes its player and song tables after its init
354
+ routine has moved/decompressed them, so init is emulated and decoding retried
355
+ whenever the engine is absent or no section decodes in the directly loaded
356
+ image. Raises :class:`SidParseError` if the engine is not found either way.
357
+ """
358
+ image = SidImage.from_bytes(data)
359
+ anchor = find_fingerprint(image)
360
+ plan = _plan(image) if anchor is not None else None
361
+ if (anchor is None or plan[3] <= 0) and _run_init(image):
362
+ retry = find_fingerprint(image)
363
+ if retry is not None:
364
+ anchor = retry
365
+ plan = _plan(image)
366
+ if anchor is None:
367
+ raise SidParseError("Soundmonitor engine fingerprint not found in image")
368
+ base, start, last, _count = plan
369
+ sections = _decode_sections(image, base, start, last)
370
+ instruments = _decode_instruments(image, base, _instrument_indices(sections))
371
+ note_freq = locate_note_freq(image)
372
+ return Song(
373
+ base=base,
374
+ player_anchor=anchor,
375
+ header=image.header,
376
+ sections=sections,
377
+ instruments=instruments,
378
+ note_freq=note_freq,
379
+ )
380
+
381
+
382
+ def read(src) -> Song:
383
+ """Read ``src`` (path, ``bytes``, or file-like) and :func:`parse` it."""
384
+ return parse(read_bytes(src))
@@ -0,0 +1,32 @@
1
+ """The :class:`~pysidtracker.BaseSidParser` implementation for Soundmonitor."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from pysidtracker import BaseSidParser, SidImage
8
+
9
+ from .errors import SidParseError
10
+ from .model import Song
11
+ from .reader import find_fingerprint, parse
12
+
13
+
14
+ class SoundMonitorSidParser(BaseSidParser):
15
+ """Parse Soundmonitor tunes and recognise the engine for ``detect()``.
16
+
17
+ ``recognize`` returns the address of a tiny relocation-invariant fingerprint
18
+ (the CIA Timer-A latch programming in the section loader), so a directly
19
+ loaded tune classifies as :attr:`PlayroutineKind.DIRECT` and a
20
+ packed/relocated one as :attr:`PlayroutineKind.RELOCATED`/``PACKED`` after
21
+ the base library emulates its init.
22
+ """
23
+
24
+ error_class: type = SidParseError
25
+
26
+ def parse(self, data: bytes, **kwargs: Any) -> Song:
27
+ """Decode ``data`` into a :class:`~pysoundmonitor.model.Song`."""
28
+ return parse(data)
29
+
30
+ def recognize(self, image: SidImage) -> object:
31
+ """Return the fingerprint address if the engine is present, else ``None``."""
32
+ return find_fingerprint(image)
@@ -0,0 +1,285 @@
1
+ Metadata-Version: 2.4
2
+ Name: pysoundmonitor
3
+ Version: 0.1.0
4
+ Summary: Pure-Python reader and detector for Soundmonitor (64'er / Hulsbeck) SID tunes
5
+ Author: Josh Bailey
6
+ License: Apache License
7
+ Version 2.0, January 2004
8
+ http://www.apache.org/licenses/
9
+
10
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
11
+
12
+ 1. Definitions.
13
+
14
+ "License" shall mean the terms and conditions for use, reproduction,
15
+ and distribution as defined by Sections 1 through 9 of this document.
16
+
17
+ "Licensor" shall mean the copyright owner or entity authorized by
18
+ the copyright owner that is granting the License.
19
+
20
+ "Legal Entity" shall mean the union of the acting entity and all
21
+ other entities that control, are controlled by, or are under common
22
+ control with that entity. For the purposes of this definition,
23
+ "control" means (i) the power, direct or indirect, to cause the
24
+ direction or management of such entity, whether by contract or
25
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
26
+ outstanding shares, or (iii) beneficial ownership of such entity.
27
+
28
+ "You" (or "Your") shall mean an individual or Legal Entity
29
+ exercising permissions granted by this License.
30
+
31
+ "Source" form shall mean the preferred form for making modifications,
32
+ including but not limited to software source code, documentation
33
+ source, and configuration files.
34
+
35
+ "Object" form shall mean any form resulting from mechanical
36
+ transformation or translation of a Source form, including but
37
+ not limited to compiled object code, generated documentation,
38
+ and conversions to other media types.
39
+
40
+ "Work" shall mean the work of authorship, whether in Source or
41
+ Object form, made available under the License, as indicated by a
42
+ copyright notice that is included in or attached to the work
43
+ (an example is provided in the Appendix below).
44
+
45
+ "Derivative Works" shall mean any work, whether in Source or Object
46
+ form, that is based on (or derived from) the Work and for which the
47
+ editorial revisions, annotations, elaborations, or other modifications
48
+ represent, as a whole, an original work of authorship. For the purposes
49
+ of this License, Derivative Works shall not include works that remain
50
+ separable from, or merely link (or bind by name) to the interfaces of,
51
+ the Work and Derivative Works thereof.
52
+
53
+ "Contribution" shall mean any work of authorship, including
54
+ the original version of the Work and any modifications or additions
55
+ to that Work or Derivative Works thereof, that is intentionally
56
+ submitted to Licensor for inclusion in the Work by the copyright owner
57
+ or by an individual or Legal Entity authorized to submit on behalf of
58
+ the copyright owner. For the purposes of this definition, "submitted"
59
+ means any form of electronic, verbal, or written communication sent
60
+ to the Licensor or its representatives, including but not limited to
61
+ communication on electronic mailing lists, source code control systems,
62
+ and issue tracking systems that are managed by, or on behalf of, the
63
+ Licensor for the purpose of discussing and improving the Work, but
64
+ excluding communication that is conspicuously marked or otherwise
65
+ designated in writing by the copyright owner as "Not a Contribution."
66
+
67
+ "Contributor" shall mean Licensor and any individual or Legal Entity
68
+ on behalf of whom a Contribution has been received by Licensor and
69
+ subsequently incorporated within the Work.
70
+
71
+ 2. Grant of Copyright License. Subject to the terms and conditions of
72
+ this License, each Contributor hereby grants to You a perpetual,
73
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
74
+ copyright license to reproduce, prepare Derivative Works of,
75
+ publicly display, publicly perform, sublicense, and distribute the
76
+ Work and such Derivative Works in Source or Object form.
77
+
78
+ 3. Grant of Patent License. Subject to the terms and conditions of
79
+ this License, each Contributor hereby grants to You a perpetual,
80
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
81
+ (except as stated in this section) patent license to make, have made,
82
+ use, offer to sell, sell, import, and otherwise transfer the Work,
83
+ where such license applies only to those patent claims licensable
84
+ by such Contributor that are necessarily infringed by their
85
+ Contribution(s) alone or by combination of their Contribution(s)
86
+ with the Work to which such Contribution(s) was submitted. If You
87
+ institute patent litigation against any entity (including a
88
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
89
+ or a Contribution incorporated within the Work constitutes direct
90
+ or contributory patent infringement, then any patent licenses
91
+ granted to You under this License for that Work shall terminate
92
+ as of the date such litigation is filed.
93
+
94
+ 4. Redistribution. You may reproduce and distribute copies of the
95
+ Work or Derivative Works thereof in any medium, with or without
96
+ modifications, and in Source or Object form, provided that You
97
+ meet the following conditions:
98
+
99
+ (a) You must give any other recipients of the Work or
100
+ Derivative Works a copy of this License; and
101
+
102
+ (b) You must cause any modified files to carry prominent notices
103
+ stating that You changed the files; and
104
+
105
+ (c) You must retain, in the Source form of any Derivative Works
106
+ that You distribute, all copyright, patent, trademark, and
107
+ attribution notices from the Source form of the Work,
108
+ excluding those notices that do not pertain to any part of
109
+ the Derivative Works; and
110
+
111
+ (d) If the Work includes a "NOTICE" text file as part of its
112
+ distribution, then any Derivative Works that You distribute must
113
+ include a readable copy of the attribution notices contained
114
+ within such NOTICE file, excluding those notices that do not
115
+ pertain to any part of the Derivative Works, in at least one
116
+ of the following places: within a NOTICE text file distributed
117
+ as part of the Derivative Works; within the Source form or
118
+ documentation, if provided along with the Derivative Works; or,
119
+ within a display generated by the Derivative Works, if and
120
+ wherever such third-party notices normally appear. The contents
121
+ of the NOTICE file are for informational purposes only and
122
+ do not modify the License. You may add Your own attribution
123
+ notices within Derivative Works that You distribute, alongside
124
+ or as an addendum to the NOTICE text from the Work, provided
125
+ that such additional attribution notices cannot be construed
126
+ as modifying the License.
127
+
128
+ You may add Your own copyright statement to Your modifications and
129
+ may provide additional or different license terms and conditions
130
+ for use, reproduction, or distribution of Your modifications, or
131
+ for any such Derivative Works as a whole, provided Your use,
132
+ reproduction, and distribution of the Work otherwise complies with
133
+ the conditions stated in this License.
134
+
135
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
136
+ any Contribution intentionally submitted for inclusion in the Work
137
+ by You to the Licensor shall be under the terms and conditions of
138
+ this License, without any additional terms or conditions.
139
+ Notwithstanding the above, nothing herein shall supersede or modify
140
+ the terms of any separate license agreement you may have executed
141
+ with Licensor regarding such Contributions.
142
+
143
+ 6. Trademarks. This License does not grant permission to use the trade
144
+ names, trademarks, service marks, or product names of the Licensor,
145
+ except as required for reasonable and customary use in describing the
146
+ origin of the Work and reproducing the content of the NOTICE file.
147
+
148
+ 7. Disclaimer of Warranty. Unless required by applicable law or
149
+ agreed to in writing, Licensor provides the Work (and each
150
+ Contributor provides its Contributions) on an "AS IS" BASIS,
151
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
152
+ implied, including, without limitation, any warranties or conditions
153
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
154
+ PARTICULAR PURPOSE. You are solely responsible for determining the
155
+ appropriateness of using or redistributing the Work and assume any
156
+ risks associated with Your exercise of permissions under this License.
157
+
158
+ 8. Limitation of Liability. In no event and under no legal theory,
159
+ whether in tort (including negligence), contract, or otherwise,
160
+ unless required by applicable law (such as deliberate and grossly
161
+ negligent acts) or agreed to in writing, shall any Contributor be
162
+ liable to You for damages, including any direct, indirect, special,
163
+ incidental, or consequential damages of any character arising as a
164
+ result of this License or out of the use or inability to use the
165
+ Work (including but not limited to damages for loss of goodwill,
166
+ work stoppage, computer failure or malfunction, or any and all
167
+ other commercial damages or losses), even if such Contributor
168
+ has been advised of the possibility of such damages.
169
+
170
+ 9. Accepting Warranty or Additional Liability. While redistributing
171
+ the Work or Derivative Works thereof, You may choose to offer,
172
+ and charge a fee for, acceptance of support, warranty, indemnity,
173
+ or other liability obligations and/or rights consistent with this
174
+ License. However, in accepting such obligations, You may act only
175
+ on Your own behalf and on Your sole responsibility, not on behalf
176
+ of any other Contributor, and only if You agree to indemnify,
177
+ defend, and hold each Contributor harmless for any liability
178
+ incurred by, or claims asserted against, such Contributor by reason
179
+ of your accepting any such warranty or additional liability.
180
+
181
+ END OF TERMS AND CONDITIONS
182
+
183
+ APPENDIX: How to apply the Apache License to your work.
184
+
185
+ To apply the Apache License to your work, attach the following
186
+ boilerplate notice, with the fields enclosed by brackets "[]"
187
+ replaced with your own identifying information. (Don't include
188
+ the brackets!) The text should be enclosed in the appropriate
189
+ comment syntax for the file format. We also recommend that a
190
+ file or class name and description of purpose be included on the
191
+ same "printed page" as the copyright notice for easier
192
+ identification within third-party archives.
193
+
194
+ Copyright [yyyy] [name of copyright owner]
195
+
196
+ Licensed under the Apache License, Version 2.0 (the "License");
197
+ you may not use this file except in compliance with the License.
198
+ You may obtain a copy of the License at
199
+
200
+ http://www.apache.org/licenses/LICENSE-2.0
201
+
202
+ Unless required by applicable law or agreed to in writing, software
203
+ distributed under the License is distributed on an "AS IS" BASIS,
204
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
205
+ See the License for the specific language governing permissions and
206
+ limitations under the License.
207
+
208
+ Project-URL: Homepage, https://github.com/anarkiwi/pysoundmonitor
209
+ Project-URL: Source, https://github.com/anarkiwi/pysoundmonitor
210
+ Project-URL: Issues, https://github.com/anarkiwi/pysoundmonitor/issues
211
+ Keywords: sid,c64,soundmonitor,hulsbeck,tracker,chiptune
212
+ Classifier: License :: OSI Approved :: Apache Software License
213
+ Classifier: Programming Language :: Python :: 3
214
+ Classifier: Programming Language :: Python :: 3.10
215
+ Classifier: Programming Language :: Python :: 3.11
216
+ Classifier: Programming Language :: Python :: 3.12
217
+ Classifier: Programming Language :: Python :: 3.13
218
+ Classifier: Topic :: Multimedia :: Sound/Audio
219
+ Requires-Python: >=3.10
220
+ Description-Content-Type: text/markdown
221
+ License-File: LICENSE
222
+ Requires-Dist: pysidtracker>=0.1
223
+ Requires-Dist: numpy>=1.23
224
+ Provides-Extra: emu
225
+ Requires-Dist: pysidtracker[emu]; extra == "emu"
226
+ Provides-Extra: dev
227
+ Requires-Dist: black>=24; extra == "dev"
228
+ Requires-Dist: py65>=1.1; extra == "dev"
229
+ Requires-Dist: pylint>=3; extra == "dev"
230
+ Requires-Dist: pytest>=7; extra == "dev"
231
+ Requires-Dist: pytest-cov>=4; extra == "dev"
232
+ Requires-Dist: pytest-xdist>=3; extra == "dev"
233
+ Dynamic: license-file
234
+
235
+ # pysoundmonitor
236
+
237
+ Pure-Python reader and detector for **Soundmonitor** (64'er / Chris Hulsbeck)
238
+ SID tunes — HVSC tracker #6. Built on [`pysidtracker`](https://github.com/anarkiwi/pysidtracker).
239
+
240
+ The Soundmonitor player is relocatable and the SID-header addresses are not a
241
+ reliable locator, so the engine is found by a small relocation-invariant
242
+ hardware-register fingerprint and the documented section→stream song data is
243
+ decoded into a model. Scope is container/detection + a song-data reader, not a
244
+ byte-exact playback engine.
245
+
246
+ ## Install
247
+
248
+ ```sh
249
+ pip install pysoundmonitor
250
+ ```
251
+
252
+ ## Usage
253
+
254
+ ```python
255
+ import pysoundmonitor as psm
256
+
257
+ song = psm.read("tune.sid") # or psm.parse(raw_bytes)
258
+ print(song.cia_latch, len(song.sections), len(song.instruments))
259
+ for section in song.sections:
260
+ print(section.cadence, section.tempo, section.pattern_length)
261
+
262
+ # Relocation-tolerant detection (untrustworthy header):
263
+ det = psm.SoundMonitorSidParser().detect("tune.sid")
264
+ print(det.kind) # DIRECT / RELOCATED / PACKED / UNKNOWN
265
+ ```
266
+
267
+ ## Development
268
+
269
+ ```sh
270
+ pip install -e ".[dev]"
271
+ pytest # offline synthetic fixtures
272
+ python scripts/fetch_tunes.py # cache the HVSC reference tune (never committed)
273
+ ```
274
+
275
+ Test tunes are HVSC copyright works: fetched + cached on demand (gitignored),
276
+ never committed.
277
+
278
+ ## Docs
279
+
280
+ - [`docs/format.md`](docs/format.md) — Soundmonitor container, detection, and
281
+ song-data model.
282
+
283
+ ## License
284
+
285
+ Apache-2.0.
@@ -0,0 +1,11 @@
1
+ pysoundmonitor/__init__.py,sha256=7rOwvmX9pIww9YXanaYAbN_fy0BLSN5p1LJDye5xEZs,994
2
+ pysoundmonitor/constants.py,sha256=kXsspoW0ERIiCqvqEfk5FuO3f3KUiiYmHJJw7GWdjTQ,6488
3
+ pysoundmonitor/errors.py,sha256=4rRSBZgRXAVmNkCXrX0bt5j92YKyx_XfqHKFLn72N88,275
4
+ pysoundmonitor/model.py,sha256=PetCsvipqSzKQZNaikn1t64rnCTdp_KwVCyBsrJfcdk,6027
5
+ pysoundmonitor/reader.py,sha256=6RTcQshu-gzcGgkghv-ugyir0DJ8mGca2E8XF9ZNuNE,14379
6
+ pysoundmonitor/sidparser.py,sha256=AosS1OGoe7nLSp_55Dt_J9Dc__X8to-Z-BhVW_nKajY,1143
7
+ pysoundmonitor-0.1.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
8
+ pysoundmonitor-0.1.0.dist-info/METADATA,sha256=V3PfdHROJcF6NZl_LJXUowBEpFcD3cPWFQFzfOQVXpU,15732
9
+ pysoundmonitor-0.1.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
10
+ pysoundmonitor-0.1.0.dist-info/top_level.txt,sha256=q6FIHsUsEn7MI8HICcNZHDL_NZ3NjCZXdELgicqBCKo,15
11
+ pysoundmonitor-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ pysoundmonitor