Files
Dragon-s-Lair-X68k/tools/encoder/spans.py
T
prosolis b49bbdc939 Build v7 into the player, and find the cost model 18% wrong on the block it made commonest
src/player/decode.s now paints v7 literal spans, pixel-exact under MAME and
px68k's C68K core over a container where every frame carries 128-216 spans
covering up to 38% of the picture. The span pass is blit.s v7 verbatim: the
66.0/9.143/9.978 fit was measured on that instruction sequence.

The container is DLX3 -- a span section between the mode header and the block
payload, since that is the only place the 68000 can reach without first parsing
something of variable length. 16_span_roundtrip.py gates it in check.sh, and
asserts it emitted enough spans to have tested anything.

Two synthetic all-SPAN anchors price v7 inside decode.s at 151.2 and 225.6
clocks per 4x4 block, against FINDINGS 40's table of 151 and 226 -- 0.2% on
both emulators. The measured mode costs what it was said to cost.

Two things that were not on the list:

TWO BYTE BUDGETS. FINDINGS 40's 18/120 was scored against the 488 KB/s PIPE,
not the 280 KB/s profile, and at the profile rate the lam search has already
spent the allowance -- spans fired on 5 frames of 120 and looked like a
regression. The profile is a chosen quality rate point; the pipe is hardware.
--kbps and --span-kbps are now separate and spans run before mu, because a span
pays in bytes and mu pays in picture. Delivered: 86/120 over budget without
spans, 77/120 at the profile budget, 34/120 on the pipe for +0.36 dB.

C_SKIP_MIXED WAS NEVER MEASURED, and it was 18% low -- 45.0, now 55.0. It is
the one constant in the table that came from a derivation, because the
synthetic frame that would measure it cannot exist: a byte needs a coded block
for its SKIP to be mixed. Four bracketing anchors measure it on both emulators
with the header byte rotated through all four positions, and the partner mode
solves back to its own anchored value to 0.2%. With it corrected the model
predicts a real spanned decode to -0.06% mean / 0.09% worst, against -2.99% /
4.30%. It matters because a span marks its run SKIP, so mixed SKIPs dominate
exactly the frames spans are judged on.

Also: the rig had been writing its synthetic timing frames 26 KB past the top
of a 2 MB machine, and got away with it because the modes it overran are
data-independent. A span's jump displacements come out of the stream, so it is
not. And frames-over-budget is no longer a safe headline -- the controller aims
at the deadline, so 55 of 120 frames sit within 5% of it and a 1% cost shift
moves 22 frames.

FINDINGS 41. check.sh ALL GREEN, now gating on a span-heavy DLX3 container.

Claude-Session: https://claude.ai/code/session_01194oWYW8DQXK1SZ2DnChW6
2026-08-23 20:02:03 -07:00

217 lines
8.7 KiB
Python

#!/usr/bin/env python3
"""v7 literal spans: geometry, selection, and the bytes that go in the container.
A span is a ROW-LINEAR run of word-expanded literal pixels that the 68000
copies straight from the stream buffer into GVRAM through an unrolled chain of
`movem.l` units, with no address arithmetic, no loop and no remainder logic.
It is the mode FINDINGS 29 derived, FINDINGS 30 measured as v6, and FINDINGS 40
re-measured as v7 -- v6's 24-pixel coarse chain with a 2-pixel fine chain
appended, at
66.0 clocks/span + 9.143/coarse pixel + 9.978/fine pixel (MEASURED)
The span constants live in tools/analysis/buscost.py and the per-block ones in
tools/encoder/vq_hybrid.py; both are imported rather than copied, which is what
kept session 12's correction to C_SKIP_MIXED from having to be made twice.
WHAT A SPAN COVERS. A run of L horizontally adjacent 4x4 blocks inside one
block row, coded as FOUR spans of 4L pixels -- one per picture row. The run's
blocks are marked SKIP in the mode header and the span paints them instead, so
a span costs the mode-map dispatch but not the block body. That is exactly the
accounting tools/analysis/14_dmac_chain.py scores.
WHY THE PADDING IS ZERO. v7's fine unit is one `move.l (a0)+,(a2)+` = 2
pixels, and a span is a run of 4x4 blocks, so its length is always a multiple
of 4 and splits into 24*c + 2*f with nothing left over (FINDINGS 40.3). v6's
24-pixel quantum wasted ~11 pixels a span and was 86% of the DMAC's advantage
over it.
SPANS ARE LITERAL, SO THEY ARE PIXEL-EXACT. A span carries palette indices
straight out of the palettised source, exactly as a RAW block does. Spanning a
run therefore does not just buy cycles, it removes that run's quantisation
error -- which is why the selection below can only improve PSNR, and why the
reconstruction the encoder feeds back to the next frame has to include spans
(a temporally recursive codec drifts otherwise -- FINDINGS 26.1).
"""
import os, sys
import numpy as np
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)),
"..", "analysis"))
import buscost as B
# Display geometry, and it must match tools/bench/crtc_mode.lua: 256-colour
# page, one pixel per WORD of CPU address space, 1024-byte line stride, picture
# in rows 32..223 of a 256-row page. GVRAM is at a fixed $C00000 on every
# X68000, which is what makes an absolute destination address a legitimate
# thing for an encoder to bake into a stream (FINDINGS 30.2).
GVRAM, YOFF, STRIDE = 0xC00000, 32, 1024
# The two chains, and these must match tools/bench/blit.s v7 exactly.
COARSE_PX, COARSE_CODE, COARSE_N = 24, 12, 11
FINE_PX, FINE_CODE, FINE_N = 2, 2, 11
SPAN_HDR = B.V7_SPAN_HDR # {u32 address, u16 coarse disp} + u16 fine
BYTES_PX = 2 # word-expanded, high byte discarded by gvram_w
def split(npix):
"""(coarse units, fine units) for a span of npix pixels. Exact: npix is a
multiple of 4 for any real span, and 4 is a multiple of the 2-pixel fine
quantum, so nothing is padded."""
if npix % FINE_PX:
raise ValueError(f"span of {npix} px is not a multiple of {FINE_PX}")
c, r = divmod(npix, COARSE_PX)
f = r // FINE_PX
if c > COARSE_N or f > FINE_N:
raise ValueError(f"span of {npix} px exceeds the chain "
f"({c} coarse > {COARSE_N} or {f} fine > {FINE_N})")
return c, f
def clocks(npix):
"""68000 clocks to paint one span of npix pixels (MEASURED, FINDINGS 40)."""
c, f = split(npix)
return (B.V7_SPAN_CYC + c * COARSE_PX * B.V7_CPX_CYC
+ f * FINE_PX * B.V7_FPX_CYC)
def run_clocks(L):
"""Clocks for a run of L blocks: four spans of 4L pixels."""
return 4.0 * clocks(4 * L)
def run_bytes(L):
"""Container bytes for a run of L blocks."""
return 4 * (SPAN_HDR + 4 * L * BYTES_PX)
def dest(y, x):
"""Absolute GVRAM address of picture pixel (x, y)."""
return GVRAM + (YOFF + y) * STRIDE + x * 2
def dirty_runs(mode2d, nbx):
"""Maximal runs of horizontally adjacent non-SKIP blocks, per block row."""
for by in range(mode2d.shape[0]):
d = mode2d[by] != 0
i = 0
while i < nbx:
if not d[i]:
i += 1
continue
j = i
while j < nbx and d[j]:
j += 1
yield by, i, j
i = j
# Per-block decode cost, the same measured table vq_hybrid.cycles() uses --
# imported rather than copied, because session 12 corrected one of them and a
# second copy is how a corrected constant stops being corrected everywhere.
import vq_hybrid as _H
C_SKIP_MIXED = _H.C_SKIP_MIXED # a spanned block still pays its dispatch
BLK_CLK = {1: _H.C_V1, 2: _H.C_V4, 3: _H.C_RAW}
BLK_BYT = {1: 1, 2: 4, 3: 16}
def select(mode, src_idx, nbx, nby, byte_room, need_clocks=None,
idx_bytes=1):
"""Choose which runs to paint as spans.
`mode` 1-D mode map, modified nowhere (a new one is returned)
`src_idx` (H, W) palettised source -- what the spans will carry
`byte_room` container bytes the frame may still spend
`need_clocks` stop as soon as the frame's decode cost is at or below this;
None spends every profitable byte instead (the model
tools/analysis/14_dmac_chain.py scores).
Ranked by clocks saved per byte spent, which is the same greedy 12 and 14
use. Selection is deliberately conservative in two ways and the reported
figures are exact rather than greedy: a run is only offered if the span
beats the blocks it replaces on cycles ALONE, and the saving credited here
ignores the extra all-SKIP header bytes spanning tends to create. The
caller recomputes the frame's real cost from the returned mode map.
Returns dict(mode, spanned, spans, bytes, clocks).
"""
m2 = np.asarray(mode).reshape(nby, nbx)
spanned = np.zeros((nby, nbx), bool)
cand = []
for by, i, j in dirty_runs(m2, nbx):
L = j - i
cur_c = sum(BLK_CLK[int(b)] for b in m2[by][i:j])
cur_b = sum(BLK_BYT[int(b)] * (idx_bytes if int(b) != 3 else 1)
for b in m2[by][i:j])
sc = run_clocks(L) + L * C_SKIP_MIXED # the dispatch still happens
if sc >= cur_c:
continue
db = run_bytes(L) - cur_b
cand.append(((cur_c - sc) / max(db, 1), cur_c - sc, db, by, i, j))
cand.sort(key=lambda s: -s[0])
# `need_clocks` is measured against the frame as it stands, so the loop
# tracks the real running total rather than a delta: a spanned run's blocks
# become SKIP, and four SKIPs sharing a header byte cost 53 cycles instead
# of 4x55, which the greedy's per-run delta does not see.
import vq_hybrid as H
cur = m2.copy()
total_b, total_c = 0.0, 0.0
chosen = []
for _, dc, db, by, i, j in cand:
if need_clocks is not None and H.cycles(cur) + total_c <= need_clocks:
break
if total_b + db > byte_room:
continue
total_b += db
total_c += run_clocks(j - i)
cur[by][i:j] = 0
spanned[by][i:j] = True
chosen.append((by, i, j))
spans = []
for by, i, j in sorted(chosen):
x, npix = i * 4, (j - i) * 4
for k in range(4):
y = by * 4 + k
spans.append((y, x, src_idx[y, x:x + npix].astype(np.uint8)))
spans.sort()
return dict(mode=cur.reshape(-1), spanned=spanned, spans=spans,
bytes=int(total_b), clocks=float(total_c))
def serialise(spans):
"""The span section of a frame record, exactly as blit.s v7 reads it.
u16 nspans
nspans * { u32 GVRAM address, u16 coarse disp, c*48 B pixels,
u16 fine disp, f*4 B pixels }
The fine displacement sits MID-STREAM rather than in the record because
that is what lets the decoder keep all 12 payload registers: the coarse
chain falls out into `move.w (a0)+,d0 / jmp` with d0 dead payload and a0
already pointing at it (FINDINGS 40.4).
Every field is big-endian and every span record is a multiple of 4 bytes
long (4 + 2 + 48c + 2 + 4f), so the section needs no internal padding.
"""
out = bytearray()
out += len(spans).to_bytes(2, "big")
for y, x, pix in spans:
c, f = split(len(pix))
w = np.zeros((len(pix), 2), np.uint8)
w[:, 1] = pix # high byte discarded by gvram_w
w = w.tobytes()
out += dest(y, x).to_bytes(4, "big")
out += ((COARSE_N - c) * COARSE_CODE).to_bytes(2, "big")
out += w[:c * COARSE_PX * 2]
out += ((FINE_N - f) * FINE_CODE).to_bytes(2, "big")
out += w[c * COARSE_PX * 2:]
return bytes(out)
def section_bytes(spans):
return 2 + sum(SPAN_HDR + len(p) * BYTES_PX for _, _, p in spans)