# Worklog Newest first. One entry per working session; the measured result, not the intent. The Mega Drive project's log is in `docs/md-WORKLOG.md`. ## 2026-11-04 (night) — phase 3: the C1 format, decoder and player Audio pushed off by the user; video first. **Display decision (D3): direct colour, 320×192 stored, the line table repeats rows to 224** (display line i → row i·192/224). Measured at 675 B/f (MD metric): | | frames 0–374 | 2500–2874 | |---|---|---| | per-scene 256-colour palettes (decoder would rebuild a 32 KB LUT per cut: ~1 s of both SH-2s) | 117.6 | 159.3 | | one palette per clip, its 32 KB LUT in ROM | 210.2 | 256.9 | | **direct colour 320×192** | **107.6** | **154.0** | No palette bytes, no LUT, full RGB555: better and simpler. 192 × 640 B + 512 B line table = 123,392 B in one 128 KB buffer. **Format C1V2** (`r32x/c1.py` is the spec and the reference decoder): 16×16 MBs, SKIP-run / INTER / INTER0 / INTRA, full-pel MVs predicted along the MB row, 8×8 integer two-pass IDCT (K = rint(DCT·4096), exact in int32), YCbCr → RGB555 with 16.16 chroma terms and one 768-byte clip table. Each half (MB rows 0–5, 6–11) is its own bit run behind a u16 q and a u16 offset, so the two SH-2s decode one each (+~3 B/frame). Encoder `r32x/encode_c1.py` (decisions from the study, exact integer recon, `--check` decodes every payload). 15 s clips at 675 B/f: error **107.9 / 153.1**; reference decoder identical on every frame. **C decoder** `player32x/c1/c1dec.c` (portable; tables generated by `r32x/gen_tables.py`): host build (`out32/bin/c1host`, `r32x/check_host.py`) identical to the expected pictures on all 750 frames, with the player's two-buffer dirty-MB conversion modelled. **SH-2 player** `player32x/c1/` + `build_c1.sh`. Traps found on the way: - Code put in `.data` for SDRAM gets its alignment padding as zero bytes, which the SH-2 executes (BlastEm: "Unimplemented instruction: 0"). Hot code now goes in `.sdram_text` (executable: NOP padding), appended **after** `.data` in `mars.ld`; placing it before moved the skeleton's VBR/entry points off 0x06000000/0x06000240. - Kernel benchmark (`C1_BENCH=1`, sega32x-python, per 240-MB frame, first decoder): skip copy 315k cycles; MC fetch+store through int32 staging **1.89M** (7.9k/MB); full IDCT 5.6k/block; conversion **2.03M** (33 cycles/pixel: three pre-shifted 1.5 KB tables thrash the 4 KB cache). Fixed: MC copies bytes straight into the new frame and adds residuals in place; chroma by multiply, one 768 B table. - Polling COMM registers back to back: replaced with a cache-resident count-down between polls (made no measurable difference on the board, kept as hygiene). - Format v2 halves: master decodes + converts MB rows 0–5, slave rows 6–11; each purges its cache per frame (the other wrote half the reference). - gcc turns a signed `>> 12` into a call to libgcc `___ashiftrt_r4_12` (12 SHARs, in ROM): replaced by `((uint32)x ^ 0x80000000) >> 12) - 0x80000`, exact. - LTO inlined the HOT functions into `m_main`/`s_main` (ROM): now `noinline`. - Two-way cache mode (2 KB on-chip RAM at 0xC0000000 for scratch + tables): slightly *slower* (decode 3.03 vs 2.77 fields, convert 2.30 vs 2.02); reverted, scratch passed per CPU (`c1_fast_t`). **Where it stands** (sega32x-python is the judge; BlastEm a detector): - **Correct**: every picture the board shows is an expected frame, in order, 0 unknown (112 frames checked on one run, 48 on later builds). BlastEm shows partially rewritten frames (one row of the shown buffer changed): it reports FS as swapped before the VBlank that swaps it; the Manual says reads lag, and the board agrees. Not ours. - **Too slow**: ~7 fields per video frame on the board (need 2). Per CPU per frame: decode its half ~2.8 fields, convert ~2.0. Kernel costs measured (FRT, 128-cycle ticks, loops kept under the 16-bit wrap): skip copy 1.3k/MB, MC copy 2.4k/MB, IDCT 17k (full), 4.4k (2×2), 2.9k (DC only) per block; conversion 10.9k/MB = 43 cycles/pixel. The IDCT's `mul.l`/`sts macl`/`add` chains and the conversion's register pressure (the SH-2's indexed loads use only R0) are the cost: C won't get there. - **Next**: SH-2 assembly for the IDCT (MAC.W with transposed K and T, exact in the 64-bit MAC; DC-only blocks as a fill) and for the conversion (per-2×2 table pointers, Y in R0); then re-profile against 912k cycles per CPU per frame. **Assembly and bus work** (`player32x/c1/c1asm.s`; sega32x-python, master half): - `c1_idct_mac` / `c1_idct_add`: MAC.W @Rm+,@Rn+ runs entered by BRAF (n = non-zero rows or columns), basis and pass-1 output transposed so both operands are contiguous; `c1_idct_add` adds into the plane with a branch clamp, intra's +128 folded into the rounding (128 << 12). DC-only blocks: a C fill. Full IDCT 17k → 5.7k cycles, 2×2 4.4k → 2.4k, DC 2.9k → 0.44k. - `c1_conv_mb`: chroma from two packed int32 tables (1 KB each, no multiplies), three table pointers per 2×2, Y as R0, pixel pairs stored as longs: 10.9k → 7.3k per MB. - Decode breakdown (`C1_PROF=1`): skip copies 0.47, MC 0.50, IDCT+add 0.73 fields: copies cost 3× the benchmark because both CPUs share SDRAM. **Lazy skip copies** (a skipped MB is copied only if it changed in the previous frame; the target buffer holds frame N-2) and **funnel-shifted long copies** for unaligned MC: decode 1.80 → 1.57. - **Format C1V3**: a u8 split MB index per frame, chosen by the encoder to equalise the two SH-2s' estimated work (measured per-MB costs); halves are MB ranges, the MV predictor resets at each half's start. Splits seen: 77–186 (mean ~127). Errors 107.9 / 152.9 (unchanged). `changed`/`prev` are now shared arrays indexed by MB. - Profile progression (fields per video frame, sega32x-python): C 7 → asm 5 → lazy copies 4.6; BlastEm 3.7 → 3.0 with the balanced split. - Balanced split on the board: 144 frames, in order, 0 unknown; slave wait 0.66 → 0.10. Per CPU per frame: decode 1.72 (skip copies 0.19, MC 0.46, IDCT+add 0.77, parse and overhead ~0.3) + conversion 1.23 ≈ 2.95 fields, against 2.0. Typical frames 4 fields. - Cycle model per MB (encode_c1.py `mb_cycles`) against measured master-half time: measured/model 1.09, r = 0.95. **Decoder-time term in the mode decision** (cost = D + λR + μ·cycles, μ per frame to a per-half budget): frames 0–374 error 107.9 → 716 (750k model cycles), 616 (900k), 504 (1.0M), 384 (1.1M). Skipping is the only cheap mode and stale MBs compound; off by default (`--cycle-budget`). - **Bus items** (user's option 1), each verified in order with 0 unknown on the board: packed longword stores in `c1_idct_add` and the DC fill (4× fewer bus writes): decode 1.72 → 1.78 (noise). Targeted coherency (purge only the band of rows the other CPU wrote, within MV reach; `c1_prev`/job read cache-through; full purge on frame 0 only): decode 1.79, convert 1.25 (no change). In sega32x-python's model the player is bound by instruction execution, not the bus; the write buffer absorbs single stores. Both kept (they can only help on hardware); CMD-interrupt handshake and DMA not pursued yet. - **Independent review (Fable subagent)** of the asm kernels. Notes: the checked-in sega32x-python models no SDRAM burst / FB FIFO timing (`machine.py` `sh2_waits`), so miss costs in these profiles are the model's, not the Manual's. Its exact even/odd butterfly IDCT (22 multiplies per 8 outputs, constants x16 so the shift is the top halfword) checked here: identical to `idct_int` on 20,000 random blocks, max |16S| 3.7e8; the encoder now asserts |coef| < 2400. - Applied: conversion kernel with Y read as words and R/G/B paired before shifting (convert 1.25 → 1.11 fields; review estimated -30 %); no per-MB divide in the conversion loop; coefficient clear limited to the rows×cols footprint; the butterfly as C (`idct_bfly_add`, now the default; MAC.W kernel behind `-DC1_IDCT_MAC`): IDCT+add 0.78 fields vs 0.77, i.e. gcc's butterfly equals the hand MAC.W loop. All verified in order with 0 unknown on the board (143–146 frames per run), host-exact on 750. - Per CPU now: skip 0.26 + MC 0.49 + IDCT 0.78 + parse ~0.25 + convert 1.11 ≈ 2.9 fields (budget 2.0). Remaining candidates: the butterfly in hand asm (review: ~2× on IDCT), MC copies, a table-driven `getue`. Even all of them land near ~2.3 by these figures. - Committed on branch `c1-player` (3e6ed30). - **Options 2 and 3 encoded** (`encode_c1.py --step`, `--width`; previews `out32/preview_opt{2,3}_{0,2500}/`). Error per shown frame: | | 0–374 | 2500–2874 | model cycles, busier half | |---|---|---|---| | baseline 320, 25 fps, 675 B/f | 107.9 (113.4 on the middle 288 columns) | 152.9 (155.6) | ~1.15M | | option 2: 12.5 fps, 1,350 B/f | 91.8 | 106.5 | 1.82M / 1.95M (4-field budget ~1.67M model) | | option 3: 288 wide (middle columns), 675 B/f | 98.3 | 138.8 | 1.23M / 1.33M | Decoder cost follows the coded data, not the area: option 3 puts the same bytes on fewer pixels and costs *more*; option 2 nearly fits its doubled budget. Both buy per-frame quality, not speed. - The C butterfly retyped to int16 operands so gcc emits MULS.W (45 now, was 4): exact on the host (750 frames); board decode 1.79 → 1.75 fields. **Now the default.** - The butterfly in hand SH-2 assembly (`c1bfly.s`: row and column kernels, MULS.W, per-function literal pools since PC-relative loads reach only 510 bytes forward, constants generated into `c1_k16.inc`): exact (BlastEm 290 frames, board 141 frames in order, 0 unknown) but decode 1.83 fields. Opt-in with `-DC1_IDCT_BFLY_ASM`. - **Four IDCTs measure the same** (MAC.W asm, C butterfly, C MULS.W, asm butterfly: IDCT+add ~0.75–0.8 fields per CPU). In this model the arithmetic is not the cost; the per-block work they share is. The review's caveat applies: sega32x-python prices memory approximately, so the next speed measurements that matter are on hardware. - **No 32X hardware** (user: flash cart, but no 32X, and none expected). Emulators are the judges: sega32x-python for exactness; "full speed" will mean in both it and BlastEm (BlastEm ~3 fields/frame, sega32x-python ~4 today). - **Option 3 chosen by the user: 288 wide, black borders.** The player's stored width is a build setting (`C1_WIDTH=288 bash player32x/build_c1.sh DIR`): planes 288 wide, frame-buffer rows stay 320 (C1_FBW) with 16-pixel borders never written; the conversion kernel's strides come from a generated `c1_geom.inc`. Host exact at 288 and 320 (borders checked black); BlastEm 298 frames in order; sega32x-python 150 frames in order, 0 unknown; decode 1.71 + convert 1.04 fields per CPU (320: 1.75 + 1.11). - **Full song at 288 wide** (`encode_c1.py` now loads frames as it codes them: the stream is byte-identical to the all-in-memory encoder's on frames 0–374): 5,274 frames, every payload decoded and checked, 3,559,732 B (3.39 MiB, 675 B/f), mean error 130.1 over the picture area, 22 min. ROM `out32/song288/player.32x` 3.44 MiB. - **Two decode changes measured slower and reverted** (sega32x-python, 288): - Merged prediction + residual (residuals first, each 8×8 written once from the reference, no read-back): decode 1.71 → 1.91. The per-pixel C loop that replaced the longword copy + IDCT add costs more than the read-back misses it removed. Trap found on the way: an `int16` array inside `c1_fast_t` at offset 4026 filled with longword stores. The SH-2 faults on unaligned longword access; BlastEm quietly wrote garbage, and the x86 host didn't care. - Table-driven `ue()` (256 entries, codes up to 7 bits): decode 1.71 → 1.79. The SH-2 has no variable-count shift (SHAD/SHLD arrived with the SH-3), so `buf <<= len` is a loop or a libgcc call; the existing `getu` pays it too. - **libgcc variable shifts removed from the decoder**: 26 `___ashlsi3` + 14 `___lshrsi3` call sites (in the cartridge, 0x02001abc) came from the bit reader's refill (`byte << (24 - n)`), `getu`, `(1 << z)` and `cbp & (32 >> k)`. Now multiplies by a 2^k table in SDRAM (`DMULU.L` gives `buf << k` low and `buf >> (32-k)` high) and a running mask. 0 calls left. Decode 1.71 → 1.63 fields at 288 (sega32x-python, 154 frames in order, 0 unknown); host exact on four clips. - **Full song in BlastEm** (288 build before the shift change): 5,101 of 5,274 frames within 17,000 hardware frames (window ended), all in order; ~3.3 fields per frame; 661 unknown, BlastEm's early-FS rows as on the clips. - Per CPU now (288, sega32x-python): decode 1.63 + convert 1.03 = 2.66 fields. ## 2026-11-04 (evening) — phase 1 PASS in sega32x-python Built with marsdev (user approved running it here): `wsl -e bash player32x/build_hello.sh` → `out32/hello/hello.32x`, 81,920 B (frame 100 of the song, 255 colours). Boot ROMs from the share (`\\10.10.10.10\emu\source\myrient.erista.me\files\No-Intro\Sega - 32X\`), copied to `D:\dev\tools\bios32x`; all three SHA-1s match `bootrom.py`. - **sega32x-python** (PyPy venv `.venv-pypy` in its repo, cores at its pins): the 32X-only picture and the composite are **pixel-identical to `expected.png` from frame 120** (checked at 120, 130 and every 10 to 150); comm4 reads `"OK"` (20299). 150 frames in 54 s (~2.8 frames/s, far faster than its worklog's 0.4 on the other machine). - **BlastEm** libretro core (megadrive-python's build, detector): the picture from frame 100; every pixel is its palette entry exactly, at BlastEm's levels `v << 3` (no low-bit fill) where sega32x-python assumes `v << 3 | v >> 2`: a level convention, max difference 5. - The two differ in when the picture appears (BlastEm ~frame 100, the board 120): boot and SH-2 speed, consistent with the emulator's notes on SH-2 speed against detectors. The ROM header still carries the skeleton's names ("SKYCHASE", "SAMPLE PROGRAM"). ## 2026-11-04 (later) — phase 2 first codec (C1) measured; phase 1 sources written **Codec C1 "MPEG-lite"** (`study/codec_study.py`): 16x16 MBs, full-pel MC (±16) from the previous decoded frame, 8x8 DCT residuals, 4:2:0 YCbCr reference planes in SDRAM, shown as 8bpp through per-scene 256-colour palettes (cuts + every 50 frames, 512 B each, charged) or as direct colour. Rates exact from Exp-Golomb/run-level codes except the per-MB mode symbol (adaptive entropy). Inputs: the MD project's 5,274 fields through `rrmd.encode.load_picture`; error is the MD metric, and the MD build is the current best ROM's own expected frames (`rick-roll-md/out/full-lloyd`, 2,340 B/f). λ = 0.25 q² (swept 0.1/0.25/0.5/1.0 on frames 0–374 at 675 B/f: 120.2/117.9/121.4/127.7). | window | 32X 675 B/f (4 MB) | 1,500 B/f | 3,000 B/f (mapper) | MD build 2,340 B/f | |---|---|---|---|---| | frames 0–374, 8bpp | 117.6 | 58.0 | 39.0 | 205.2 | | frames 2500–2874, 8bpp | 159.3 | 73.1 | 44.6 | 220.1 | | (direct colour, same decodes) | 117.9 / 158.9 | 56.9 / 71.0 | 37.6 / 41.9 | | The metric is squared error, which favours a smooth DCT picture over the MD build's dithered tiles; the side-by-sides (`out32/preview_*/preview.webp`) are the judgement the metric can't make. Palette fitter fixed on the way: seeding from repeated pixels left 158 of 256 entries duplicated; seeding from distinct RGB555 colours fixed it (study numbers moved by <1 %). **SH-2 decode cost** (`study/sh2_cost.py`: an assumption model, not a measurement. IDCT 1,000 cyc/block, 64 cyc/byte, MC 1,200 cyc/MB, colour conversion 15 cyc/pixel over MBs changed in the last two frames; budget = two SH-2s at PAL 25 fps = 1.82 M cyc): 675 B/f median 82 %, 14/375 frames over (cuts); 3,000 B/f median 128 %, 354/375 over. The per-pixel YCbCr → palette conversion is the largest term, so it's the lever for higher budgets. **Phase 1 sources**: `study/hello_frame.py` (one frame as palette + indices + exact expected render), `player32x/hello/` (master SH-2 shows it in both buffers, word writes), `player32x/build_hello.sh` (copies marsdev's 32x-skeleton from the pinned source at build time, so Sega's security bytes stay out of the repo). **Not built**: running the downloaded marsdev binaries needs the user's permission. Toolchain: `D:\dev\tools\marsdev\mars` (v1.0.0-rc1, SHA-256 matches sega32x-python's pin); sources `D:\dev\tools\_dl\marsdev-src` @ 3318d3f, `D:\dev\tools\_dl\32XDK` @ 7e92989. **Verification also needs**: sh2-python and megadrive-python at sega32x-python's pins, and the user's three 32X boot ROMs (none on this machine). ## 2026-11-04 — phase 0: facts checked against sega32x-python Cloned the 32X emulator to `D:\dev\sega32x-python` (private GitHub repo, master `5f2067c`: milestones 0–4 plus early PWM commits). PLAN.md section 2 rewritten from its `start-here.md`, `undocumented-behavior.md` and `claims.md`: every fact confirmed except the SH-2 cache size (sh2-python's). New for the plan: PAL allows 320×240; frame-buffer `$00` byte writes are dropped; cartridge writes need RV = 1, which stalls the SH-2s (it shapes the D1 mapper); PWM FIFO is 3 deep and its period (`cycle` or `cycle − 1`) is contested. Oracle limits: composite and colours are detectors only, PWM not finished, ~0.4 frames/s. No code changed; no encode yet. ## 2026-10-24 — forked from rick-roll-md Cloned `D:\dev\rick-roll-md` at `83650e1` (remote `md-upstream`); new `PLAN.md` for a 4 MB 32X cartridge; the MD plan and worklog moved to `docs/`. The source `.m2v` was copied (gitignored); `fields/`, `out/`, `encoder-prototype/` and `audio.u8` were not: the 32X build will choose its own resolution and audio rate, so they get re-extracted. No code changed yet: `rrmd/` and `player/` are still the MD build, kept as the baseline and as the source of the ingest/audio/verification code to reuse. Toolchain: WSL has `m68k-linux-gnu-as` and `z80asm`; **no SH toolchain yet**. The 32X emulator does not exist on disk yet (being built in another session).