# Hand-off brief: building the core For the session that writes the code. Written 2026-11-12 at the end of Phase 0. ## Read first, in this order 1. [restart.md](restart.md): the rules. They bind you as they bound Phase 0. 2. [api.md](api.md): what the board calls today. 3. [phase0.md](phase0.md): the sources, what was read and how, what was not. 4. [spec.md](spec.md): the behaviour, statement by statement, with C and U numbers. 5. [validation.md](validation.md): the ladder. Then run `python scripts/fetch_references.py --local`. It fetches the pinned references into the git-ignored `reference/`, checks the files cited in place from megadrive-python, and extracts the pinned members of its `FMDocs.7z`. Before writing a rule from a forum post, open the post: Phase 0 read thread 386 by a notes pass (phase0.md, "How to read the tables"), and the post number is always given. Before relying on S1, view its pages 5 to 8, 11, 12, 17 to 33: Phase 0 viewed ten of its pages, not all. ## What is not to be opened Unchanged from Phase 0: `/data/backup/nuked-derived/`; any Nuked source or YM2608-LLE wherever a copy sits; MAME's `fm.cpp` and `fm2612.cpp`; Genesis Plus GX, BlastEm, Gens, PicoDrive, jt12, clownmdemu, jgenesis; megadrive-python's `src/` and its documents' accounts of the FM chip's internals; anything by the author the owner excludes. Until the owner rules: Exodus `YM2612.cpp` (P3), IKAOPN's schematics and Sauraen's VHDL (P5). Code blocks in forum posts that quote an emulator are skipped. When a comparison against a model fails, the model's source stays closed (rule 8). ## Scope A pure-Python model of the OPN2's FM section, stepping once per sample (144 master clocks), in two variants: the discrete YM2612 and the YM3438 (which also stands for the ASIC's FM block until something shows they differ, U20). It produces the six channels' 9-bit values and a stereo output through a variant-specific output stage. In scope: everything in spec.md sections 2 to 16, and $2C bit 3. Not in scope: clock-level behaviour inside a sample (the 24-clock schedule, where a write lands, lost writes); the test registers beyond $2C bit 3 (decision T8); the /IRQ pin as a signal (a property is enough); the console's filter, amplifier and mix with the PSG, which are the board's; the YM2608, YM2203, YM2610 and YMF276. The variant record should not make the last hard to add, and nothing more. ## Package shape - Repository `ym2612-python`, package `ym2612_python`, under `src/`. - Modules: `chip.py` (the chip, registers, timers, status), `operator.py` (phase, envelope, output of one operator), `tables.py` (the log-sine and exponent tables built from formulas at import; detune; envelope step patterns; vibrato), and `variant.py` (the frozen `FMVariant` record and the two values). Tests under `tests/`, one file per rung. `validation/` holds the harnesses and analysis scripts of rungs 3, 5 and 6; `validation/streams/` and `reference/` stay out of git. - State as plain attributes (integers, lists); megadrive-python's save states walk them. Per-operator state lives in a small class with `__slots__` or in parallel lists; whichever is chosen, no instance reaches 80 attributes (PyPy). - Python floor 3.11, the newest PyPy supports. CI, if any, PyPy only, on `main` and pull requests. - MIT. The README says which documents each behaviour comes from, which models were run, and that their code was not read. If any line of ymfm or ares is ported, its notice comes with it; Phase 0 ported nothing and this brief recommends porting nothing. - Every rule in the code names its spec section, or says CHOICE or PROVISIONAL. ## Proposed API Starting from api.md. The board keeps its shape; the entries tied to the old model go. ```python from ym2612_python import ( YM2612, FMVariant, YM2612_DISCRETE, YM3438_ASIC, CLOCKS_PER_SAMPLE, # 144 master clocks: spec 4.2 WAIT_AFTER_ADDRESS, # 17 master clocks: spec 2.7 (Yamaha's figure) WAIT_AFTER_OPERATOR_DATA, # 83 WAIT_AFTER_CHANNEL_DATA, # 47 BUSY_CLOCKS, # 192: spec 12.2 ) fm = YM2612(variant) # YM2612_DISCRETE or YM3438_ASIC fm.write(port, value) # port 0..3: address and data for each part status = fm.read(port) # status byte, or None where the variant leaves the bus undriven fm.run(clocks) # advance by master clocks (the chip's pin, not the crystal) samples = fm.take_samples() # list of (left, right) since the last call, one per 144 clocks fm.reset_line(level) # the /IC pin fm.enabled # the board can switch the chip off fm.irq # True while either timer flag is set (not wired in the console) fm.channel_values() # the six signed 9-bit values of the last sample, for validation ``` - **Units of `take_samples()`**: integers, the sum over the six slots of the DAC's signed step values after the variant's output stage, so about ±1,536 at most. The board scales and filters. Integers keep save states and comparisons exact; if the board prefers floats in −1.0 to 1.0 it divides once. - **`read()` returning `None`**: where the variant does not drive the bus (C4), the board supplies its own open-bus value. This replaces `busy_on_all_ports`. - **`FMVariant` fields** (each docstring names its source and standing): `name`; `ladder` (the discrete output stage on or off); `ladder_positive`, `ladder_negative`, `ladder_idle` (provisional constants, U12); `status_ports` (which of the four addresses return status, C4); `accumulator_max` (255 or 256, C8). Unsettled behaviours that are not known to differ by chip (C9, C11, C12, C14, C16) are module-level constants marked PROVISIONAL, not variant fields, so that they are not mistaken for chip differences. **Dropped from the old surface**, and what megadrive-python changes: | Old entry | Fate | Board change | |---|---|---| | `IC_SLOT_LAG`, `IC_WRITE_SLOT_LAG` | gone: there are no slots in a sample-level model | delete the uses; reset takes effect at the next sample | | `TIMER_CONTROL_DELAY_CYCLES`, `fm.control_delay` | gone: no source gives a delay for $27 | delete; timers act at the sample boundary | | `fm.mclk` | gone as a public counter; `run()` takes master clocks and keeps the remainder itself | the board keeps its own clock | | `fm.busy_on_all_ports` | replaced by `FMVariant.status_ports` and `read()` returning `None` | supply open bus for `None` | | sample-for-sample agreement with two die models, wherever the board's documents claim it | not re-earned | rewrite those passages to what validation.md's rungs measured; any lockstep test of the board against a die model becomes a detector with a tolerance, or goes | The board must also stop assuming one output value per internal clock, if it does: the core gives one frame per 144 master clocks. If megadrive-python's audio path wants the six slots (to model the multiplexed output above the audio band), ask for it through `channel_values()`; do not add a clock-level mode to the core. ## The ladder | Rung | Judge | State today | |---|---|---| | 0 | The API contract | to write | | 1 | Digital values published from real chips (Nemesis, GManiac, Sauraen, Eke) | values in hand, in spec.md and validation.md | | 2 | Yamaha's manuals (S1, S2, S4) | documents in hand | | 3 | Recordings: Nemesis's SSG-EG and CSM, Aly James's ladder, MDFourier | in hand; the 180 MB one not yet unpacked; none analysed | | 4 | Community statements checked on hardware | in hand | | 5 | ymfm and ares, run and read | fetched and pinned; no harness yet | | 6 | Nuked-OPN2 as a closed box | nothing fetched: P4, P6 | | 7 | The owner's Genesis | **waiting on a repair**: P7 | | 8 | Emulators at board level | the board's job | Rungs 0 to 4 can be built and passed with what is in hand. ## Unknowns and contradictions In full in spec.md sections 19 and 20. The ones a player hears: - **U12**: the ladder effect's size. Every quiet passage on a model 1. - **C14, C16, U16, U17**: LFO divider, vibrato precision. - **C11**: the delayed modulation paths. Timbre of algorithms 0 to 3 and 5 at high modulation, slightly. - **U1**: writes landing mid-sample. Only programs that break Yamaha's waits. - **C4**: status addresses. A driver that polls the wrong address runs at a different tempo; one game is reported. - **U13**: the ASIC's level against the discrete chip. The ones a test sees and a player does not: C8, C9, C12, C13, U2 to U11, U14, U15. Build every unsettled behaviour as a variant field or a named constant, so that a measurement later changes a value and not the structure. ## Recommended approach Three ways to build it were weighed. **A. Write from the spec** (manuals and published measurements). *For*: it is what restart.md asks; every rule can name a document or a post; the structure is ours and can be the most readable of the three, because the chip at sample level is small (a phase adder, two tables, an envelope counter); Nemesis's account is nearly complete for the note path and is tier 1. *Against*: the LFO and the output stage are thinly sourced, so some constants will be provisional; it takes longer than porting; mistakes are ours to find. **B. Port ymfm with its notice** (BSD-3-Clause). *For*: fastest; a known-good sound; the licence is clean. *Against*: it is a templated engine for a dozen chips, and a faithful port would carry that shape, which is the opposite of readable; a statement-by-statement port is what restart.md rule 3 calls copying, permitted only because the licence is permissive, and it would make this repository a translation for the second time; five of its OPN2 behaviours are, by its own comments, checked against or written to match Nuked-OPN2, and its ROM tables are "extracted from the die" without credit, so a port inherits numbers whose source cannot be named beyond "ymfm says so" (rule 5 would be met in letter only); its ladder constants have no source at all; it leaves out the delayed modulation paths that the die reading describes. **C. A mix**: write from the spec, and use ymfm and ares as rung-5 comparators and as the tie-breaker of last resort for an unsettled constant, marked PROVISIONAL with tier 5. **Recommendation: C, leaning hard on A.** Port nothing. Build the tables from S9's formulas, the phase generator from spec 5, the envelope from spec 7, in our own structure, and let rung 5 show where two independent sample-level models disagree with ours. Take a number from ymfm or ares only where spec.md says "unsettled" and no document or measurement offers one (the LFO divider, the ladder constants), name it as theirs in the code, and keep it as data. The envelope step patterns deserve a sentence, because the owner may read P2 differently: the build session takes them from spec 7.3.3, which states them as a rule in prose (a regular four-pattern cycle scaled by powers of two, with three irregular low rates), sourced to Nemesis's hardware-checked post. It does not copy MAME's table, which was never opened, nor ymfm's. ## Size and difficulty - Core: about 700 to 900 lines of Python, of which tables and their generators about 120. Tests for rungs 0 to 4: about 1,500 lines. Harnesses and analysis for rungs 3, 5 and 6: about 600 lines of Python and 150 of C or C++. - Difficulty: moderate, with three hard places. SSG-EG (spec 7.6) is a page of interacting conditions and is where the recordings will bite. The envelope's corner cases (7.4.4 to 7.4.6) are easy to get subtly wrong. The discrete output stage is under-determined and will need a fit and honest wording. - Speed: 24 operators per sample at 53 kHz is about 1.3 million operator steps a second. On PyPy that should land within a small factor of real time; on CPython, well under. A reference core being slower than real time is expected. - Order of work: tables and rung 1's table comparison; phase generator; operator and algorithms; envelope without SSG-EG; timers, CSM, status; accumulator and the YM3438 output; SSG-EG; LFO; the discrete output stage last. Rungs 1 and 2 grow with each step. ## Open decisions for Aubrey ### Policy **P1. Yamaha's YM2612 application manual (S1) is leaked internal material.** It reached the public in 2024 from a Sega of Japan developer's binder, through Hidden Palace and Sega Retro. It is the only manufacturer document written for this exact chip and says things no other does (a muted channel "may be faintly audible"). Sega's Software Manual pages are likewise stamped confidential, as the Game Gear manual was for the PSG. *Recommendation*: as decided for the PSG: cite it and quote a sentence at a time; copy no tables or pages into the repository. Nearly everything it says is also in S2, the YM3438 manual, which was sold to anyone. **P2. Numbers whose history passes through a GPL emulator or a die model.** Two cases. (a) The envelope step patterns: Nemesis says his tables began as MAME's and that he then tested "most of these values" on the chip and corrected eight; ymfm and ares carry the same patterns. (b) ymfm's detune table, phase logic, vibrato and LFO divider are, by its comments, verified against or matched to Nuked-OPN2. In both cases what would enter this core is a fact about the chip, stated in a forum post or a BSD file that Phase 0 was allowed to read, not code from MAME or Nuked, which were never opened. *Recommendation*: treat a measured or documented *fact* as usable whoever first found it, and name its road honestly in the spec and README ("Nemesis, hardware-checked; began from MAME's table"). (a) is then usable now. For (b), prefer the manual and Nemesis where they speak (detune: the manual's own table, checked in Phase 0), and use ymfm's Nuked-matched numbers only as provisional tie-breakers. If you rule the other way, the envelope table waits for rung 7, where the chip itself can dictate it. **P3. Exodus's `YM2612.cpp`** (MIT, 4,061 lines, by the researcher himself, with comments marking what "has been backed up by hardware tests"). It was closed at line 12 because its header says its envelope tables are "primarily based on" the MAME core. *Recommendation*: allow reading it as documentation of his hardware tests, skipping the two tables at its head, and port nothing from it. It is the best single source left unread, and its author's posts already give most of it in prose. This follows from P2: if facts with that history are usable, so is the file. **P4. Forum prose by the Nuked models' author and by jt12's author; emulator constants relayed in prose; constants fitted to a closed box.** Phase 0 kept all three out of the spec's rules. They would matter most for the ladder effect, where a post relays the Nuked model's rule and rung 6 could fit ours to its output. *Recommendation*: do not write rules from relayed descriptions of the excluded models' code. Do allow a constant fitted to a closed box's *output* under rule 8, marked "provisional, closed-box observation", for the ladder only and only until rung 7 measures it. Say if that is a step too far. **P5. Die-traced material under permissive or unknown terms**: IKAOPN's YM3438 schematics (BSD-2-Clause, said to be independent of any existing core, traced from siliconpr0n's photographs, whose author was not established); Sauraen's VHDL of the operator unit (licence unknown); HardWareMan's die photograph ("Feel free to use it as you wish"). *Recommendation*: as for the PSG's netlist: leave them unread for the first build. A schematic of this chip is a blueprint, and the core should stay written from prose. If rung 7 never happens, revisit IKAOPN first, after checking whose photographs it used. **P6. Which models are run in rungs 5 and 6.** *Recommendation*: ymfm (BSD, run and read); Nuked-OPN2 (LGPL, run only, under rule 8). Not Genesis Plus GX (non-commercial), as decided for the PSG. MAME's own device is ymfm, so it adds nothing. **P7. Probes on the early Genesis when its controller port is repaired.** Rung 7 lists them. The digital ones need no audio equipment and would lift the envelope table, the LFO, the vibrato, the delayed paths, the F-number latch, the status addresses and BUSY to tier 1 on a discrete YM2612; the analogue one would give the ladder effect as numbers for the first time anywhere in public. Another session owns the probe cartridge. *Recommendation*: yes, and ask that session for a YM2612 read-out probe; the analysis script belongs here. Until then the README says rung 7 is empty. **P8. The MegaDrive Wiki is CC BY-NC-SA; Aly James's snippet asks for credit.** *Recommendation*: cite the wiki, copy nothing; do not use the snippet (its prose is enough and is credited in phase0.md). **P9. Telling anyone.** Two findings might interest their authors: megadrive-python's doubt about the CSM recording is settled by Nemesis's own post, and S1 and S2 disagree on timers and channel 3's mode. *Recommendation*: nothing is posted. Neither is news to the people concerned. ### Technical The owner does not rule on chip-level questions. Each has a default the builder takes and marks PROVISIONAL. **T1. Vibrato precision (C16).** *Default*: Nemesis's table and method (spec 8.6): amounts from all set F-number bits by shifting, summed, added to the 11-bit F-number, 11 bits kept. It is the measured account; rung 2 checks its depths against the manual's cents, rung 5 shows where ymfm's 12-bit form differs. **T2. LFO divider (C14).** *Default*: the manual's, 109, 78, 72, 68, 63, 45, 9, 6 samples per step. The shorter set is emulator-tier and unattributed. One constant tuple; rung 7 settles it. **T3. Status addresses (C4).** *Default*: `YM2612_DISCRETE` returns status at address 0 only and leaves the bus undriven at the others (S1, S6, and Eke's measurement); `YM3438_ASIC` returns status at all four (Eke's measurement, and the game that plays slow on those consoles). Stef's opposite report is recorded. A variant field. **T4. Delayed modulation paths (C11).** *Default*: the die reading: operator 3 takes operators 1 and 2 from the previous sample, operator 4 takes operator 2 from the previous sample, everything else from the current one. **T5. Accumulator limit (C8).** *Default*: −256 to +255, a 9-bit signed value, on both variants. GManiac's +256 is from memory. A variant field. **T6. Sustain level 15 (C9).** *Default*: $3E0, the manual's 93 dB. A named constant. **T7. F-number latch (C12).** *Default*: one holding latch per part for $A4 to $A6 and one for $AC to $AE in part I, taken by the next low-byte write to that group whatever its channel. This is the cheaper circuit and what ymfm does. Nemesis's test (a high byte for channel 2 stays pending until channel 2's low byte is written) comes out the same under both readings unless the other channel's block is examined, which his post does not say he did. Mark it PROVISIONAL and keep the per-channel form one constant away. **T8. Test registers.** *Default*: implement $2C bit 3 (the DAC's ninth bit) only. Store $21 and the rest of $2C and ignore them. No known program needs more, and megadrive-python can ask later. **T9. When writes land (U1).** *Default*: at the next sample boundary, for every register; BUSY from the write's own clock for 192 master clocks. Export Yamaha's wait figures as constants for a board that wants to warn about fast writers. **T10. The discrete output stage (U12).** *Default*: a sign-dependent offset in DAC steps for each of the six slots, including a slot whose channel is panned off, with ymfm's +4 and −3 as the first values, marked tier 5 and fitted afterwards against Aly James's recording (rung 3). `YM3438_ASIC` has no offset. Three variant fields. The README says the discrete output is a fit. **T11. Output form.** *Default*: the sum of the six slots as an integer per side per sample; the board divides. `channel_values()` gives the slots. **T12. LFO while disabled (C15) and tremolo shifts (U16).** *Default*: counter held at 0, so tremolo rests at its maximum; shifts 8, 3, 1, 0. **T13. Envelope counter (U3) and envelope sample (U4).** *Default*: a 12-bit counter that counts 1 to 4,095 and skips 0; all operators update on the same sample of three. **T14. Reset (U14).** *Default*: /IC low clears every register, sets all panning bits, puts every operator in release at $3FF with keys off, clears timers, flags, the LFO and the envelope counter. Power-on is the same. **T15. Key-on channel values 3 and 7 (U2).** *Default*: ignored. **T16. Timer B's prescaler (U9).** *Default*: free-running, not restarted by the load bit: the only two statements there are (tier 5) agree. **T17. Does `YM3438_ASIC` differ digitally from a discrete YM3438 (U20)?** *Default*: no. One variant serves both until a source shows a difference. **T18. The name of the second variant.** `YM3438_ASIC` is api.md's and the board's. *Default*: keep it; its docstring says it is the YM3438 behaviour as measured mostly on the model 2's ASIC. ## Decisions taken (2026-11-13) The owner chose the middle rule for second-hand facts and asked that every fact carry its provenance (restart.md rules 9 to 11). The policy questions above, as they now stand; technical questions T1 to T18 are taken at their defaults, provisional. | | Decision | | --- | --- | | P1 | The YM2612 manual from the Sega binder is cited and quoted a sentence at a time; nothing is copied. The owner has been told it is a leaked document and may rule otherwise. | | P2 | The middle rule: a fact a researcher established on real hardware and states in prose is usable whatever first suggested it; cite the researcher and note the history. Code fragments in posts stay closed. A value whose only support is an emulator is a provisional default from a permissive emulator, named. | | P3 | Exodus's source stays unread: its header says its envelope tables are based on MAME. | | P4 | **Not allowed for now**: constants are not fitted to a closed box's output. The ladder effect is provisional, from the recordings and what a permissive emulator documents. | | P5 | Die-traced schematics and HDL of unknown licence stay unread. | | P6 | ymfm (and ares) are run as comparators; Nuked-OPN2 is run as a closed-box detector; Genesis Plus GX is not run. | | P7 | Deferred until the owner's Genesis is repaired; the probes are listed in validation.md. | | P8, P9 | The non-commercial wiki is cited, not copied; nothing is posted. |