Files
Dragon-s-Lair-X68k/tools/encoder/encode.py
T
prosolis 497f88b945 Rate control: rebuilt per-frame, wired in, and gated at zero drift
FINDINGS 26 stopped the session-5 rate controller before it shipped: it built a
lam-ladder of independent whole-sequence encodes and picked frames off it, so
SKIP blocks referenced reconstructions the decoder never saw -- 111 of 120
frames drifted. The fix is the structural one 26.1 said it had to be.

vq_hybrid is now frame-drivable -- frame_ctx / decide / paint -- and encode() is
a thin loop over it. Rate control drives the same three calls, bisects lam per
frame under the leaky bucket, and feeds back the frame it actually emitted. The
desync has no way to occur, and 09_ratectl_drift.py goes 111/120 -> 0/120. That
test is now part of check.sh, which is ~2 min rather than ~40 s.

Both overshoots on the worst sustained window are closed for under 1 dB, totals
including audio: sasi 137.4 -> 109.5 KB/s (-0.60 dB), scsi 381.6 -> 280.0 KB/s
(-0.91 dB). Zero frames hit the lam=800 cliff, so nothing was destroyed to get
there. Rate control also makes the display path cheaper -- scsi's median drops
53.6% -> 47.1% -- because raising lam moves blocks to SKIP and V1.

Two knobs measured rather than guessed. --rc-floor is worth 0.00 dB on that
window and defaults to the profile lam, so rate control cannot regress content
that already fits. --prefill defaults to 0 and is documented as a trap: it buys
a permission to overshoot of exactly bucket/nframes, and on a 14-frame clip it
disables the controller outright.

FINDINGS 26.5 was wrong in both halves and 27.6 records it. _paint was not the
bottleneck (14% of a frame, though vectorising it was still right at 17.1x) and
the ladder was never "minutes" -- those were k-means in build(). What makes
per-frame rate control affordable is that VQ.assign depends on neither lam nor
prev, so it is cached one frame deep: a 12-step search over 120 frames costs
0.31 s against 49.1 s.

Also caught: fixed-lam sasi was already 5% over target on 00020, the clip
everyone called easy. Nothing noticed because the profile table quotes PSNR and
not bitrate.

check.sh: ALL GREEN.

Claude-Session: https://claude.ai/code/session_01194oWYW8DQXK1SZ2DnChW6
2026-08-23 14:36:45 -07:00

220 lines
9.8 KiB
Python

#!/usr/bin/env python3
"""Encode one scene to the DLX bitstream, at a chosen quality profile.
python3 tools/encoder/encode.py <frames_dir> <out.dlx> [--profile sasi|scsi]
[--lam N] [--fps 12] [--preview out.png]
[--fixed-lam] [--rc-floor profile|open]
Rate control is ON by default: lam is bisected per frame under a leaky bucket
so the profile's bitrate is a ceiling rather than an average hope. `--fixed-lam`
restores session 5's behaviour, which overshoots by 18-34% on sustained action
(FINDINGS 25.3). `--rc-floor` picks the quality floor: `profile` (default) never
spends more than the fixed-lam profile would, so it can only ever help; `open`
lets quiet frames spend the whole allowance and lands the mean ON target.
Container (little-endian is WRONG here -- the 68000 is big-endian, so every
multi-byte field is big-endian and the decoder can read it with a plain move.w):
header, 32 bytes
0 'DLX1' magic
4 u16 width, u16 height
8 u16 fps, u16 nframes
12 u16 k1, u16 k4 codebook sizes
16 u32 palette offset (256 * 3 bytes, RGB888 -- the player converts
to the X68000's GRB555 at load time)
20 u32 cb1 offset (k1 * 16 bytes of palette indices)
24 u32 cb4 offset (k4 * 4 bytes)
28 u32 frames offset
then, per frame:
u32 payload length, then
ceil(nblocks*2/8) bytes of 2-bit mode headers, MSB-first, block raster order
then payloads in block order: V1 -> 1 byte, V4 -> 4 bytes, RAW -> 16 bytes
Codebooks are emitted as palette INDICES, not pixels. The player expands them
once at load time into word-per-pixel form so the blitter can movem them
straight into GVRAM -- k1=1024 costs 1024*16*2 = 32 KB of the 2 MB.
"""
import argparse, struct, sys, os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import numpy as np
import vq as VQ, vq_hybrid as H, ratectl as RC
# Measured on the emulated 68000, FINDINGS 24. Instruction cycles against
# zero-wait-state memory, so these are floors, not hardware predictions.
BLIT_PCT = 53.6 # V1: compose in RAM, then a row-linear movem.l blit
DIRECT_PCT = 76.6 # V4: write every block straight into GVRAM
CROSSOVER_PCT = 100 * BLIT_PCT / DIRECT_PCT
def pack_modes(mode):
"""2 bits per block, MSB-first -- cheap for the 68000 to shift out."""
n = len(mode)
out = bytearray((n * 2 + 7) // 8)
for i, m in enumerate(mode):
out[i // 4] |= (int(m) & 3) << (6 - 2 * (i % 4))
return bytes(out)
def frame_payload(mode, l1, l4g, src_idx, nbx):
body = bytearray()
for b, mo in enumerate(mode):
if mo == 1:
body += _idx(l1[b])
elif mo == 2:
for j in range(4):
body += _idx(l4g[b][j])
elif mo == 3:
by, bx = divmod(b, nbx)
body += src_idx[by*4:by*4+4, bx*4:bx*4+4].tobytes()
return bytes(body)
def _idx(v):
"""codebook index: 1 byte if it fits, else big-endian u16.
k>256 means 2-byte indices -- decided once by the header, not per block."""
v = int(v)
return bytes([v]) if _IDX_BYTES == 1 else struct.pack(">H", v)
_IDX_BYTES = 1
def main():
global _IDX_BYTES
ap = argparse.ArgumentParser()
ap.add_argument("frames_dir"); ap.add_argument("out")
ap.add_argument("--profile", choices=list(RC.PROFILES), default="sasi")
ap.add_argument("--lam", type=float, default=None)
ap.add_argument("--fps", type=int, default=12)
ap.add_argument("--iters", type=int, default=16)
ap.add_argument("--fixed-lam", action="store_true",
help="disable rate control (session 5 behaviour)")
ap.add_argument("--rc-floor", choices=("profile", "open"), default="profile",
help="quality floor for rate control")
ap.add_argument("--bucket-frames", type=int, default=8,
help="leaky-bucket depth, in frame budgets")
ap.add_argument("--prefill", type=float, default=0.0,
help="how full the player's buffer is assumed to be at "
"scene start, as a fraction of the bucket (0 = cold "
"buffer after a seek, the conservative assumption)")
ap.add_argument("--preview")
a = ap.parse_args()
prof = RC.PROFILES[a.profile]
lam = a.lam if a.lam is not None else prof["lam"]
k1, k4 = prof["k1"], prof["k4"]
_IDX_BYTES = 1 if max(k1, k4) <= 256 else 2
# An explicit --lam is a request for that lam, so it implies --fixed-lam.
rc = not (a.fixed_lam or a.lam is not None)
lam_lo = lam if a.rc_floor == "profile" else 1.0
print(f"profile {a.profile}: {prof['desc']}")
if rc:
print(f" target {prof['kbps']} KB/s CEILING, rate-controlled: "
f"lam bisected per frame in [{lam_lo:g}, {RC.LAM_CLIFF:g}], "
f"{a.bucket_frames}-frame bucket")
else:
print(f" target {prof['kbps']} KB/s, FIXED lam={lam} (no rate control)")
print(f" k1={k1} k4={k4}, {_IDX_BYTES}-byte indices")
m = H.build(a.frames_dir, k1=k1, k4=k4, iters=a.iters)
if rc:
enc = RC.encode_rate_controlled(m, prof["kbps"], fps=a.fps,
bucket_frames=a.bucket_frames,
lam_lo=lam_lo, prefill=a.prefill)
else:
enc = H.encode(m, lam=lam)
r = H.evaluate(m, enc, fps=a.fps)
H_, W_ = m["H"], m["W"]; nbx = W_ // 4
pal, idx = m["pal"], m["idx"]
# The encoder hands back the symbols it actually chose. Re-deriving them
# here (as session 5 did) is a second chance to disagree with the encoder,
# and with per-frame rate control the mode map is no longer reproducible
# from a single lam anyway.
frames = []
for f, im in enumerate(idx):
mode = enc["modes"][f]
frames.append(pack_modes(mode)
+ frame_payload(mode, enc["l1"][f], enc["l4g"][f], im, nbx))
# the rate controller budgets exactly these bytes -- if that ever drifts
# from the container, every bitrate figure below is fiction
assert len(frames[-1]) == enc["sizes"][f], (f, len(frames[-1]), enc["sizes"][f])
palette = m["pal"][:256]
if len(palette) < 256:
palette = np.vstack([palette, np.zeros((256 - len(palette), 3), np.uint8)])
pal_b = palette.astype(np.uint8).tobytes()
cb1_b = m["cb1"].astype(np.uint8).tobytes()
cb4_b = m["cb4"].astype(np.uint8).tobytes()
off_pal = 32
off_cb1 = off_pal + len(pal_b)
off_cb4 = off_cb1 + len(cb1_b)
off_frm = off_cb4 + len(cb4_b)
hdr = (b"DLX1" + struct.pack(">HHHHHH", W_, H_, a.fps, len(idx), k1, k4)
+ struct.pack(">IIII", off_pal, off_cb1, off_cb4, off_frm))
assert len(hdr) == 32, len(hdr)
with open(a.out, "wb") as fh:
fh.write(hdr); fh.write(pal_b); fh.write(cb1_b); fh.write(cb4_b)
for p in frames:
fh.write(struct.pack(">I", len(p))); fh.write(p)
total = os.path.getsize(a.out)
vid = sum(len(p) + 4 for p in frames)
print(f" wrote {a.out}: {total} B "
f"(header+tables {total-vid} B, video {vid} B)")
print(f" {vid/len(idx):.0f} B/frame -> {vid/len(idx)*a.fps/1024:.1f} KB/s video"
f" + {RC.AUDIO_KBPS} KB/s audio = {vid/len(idx)*a.fps/1024+RC.AUDIO_KBPS:.1f} KB/s")
print(f" PSNR {r['psnr']:.2f} dB palette ceiling {r['pal']:.2f} dB "
f"loss {r['loss']:.2f} dB")
print(f" modes: SKIP {r['skip']:.1f}% V1 {r['v1']:.1f}% "
f"V4 {r['v4']:.1f}% RAW {r['raw']:.1f}%")
if rc:
rr = RC.summarise(m, enc, prof["kbps"], fps=a.fps)
lm = enc["lam"]
print(f" rate control: per-frame budget {enc['budget']:.0f} B, "
f"bucket {enc['cap']:.0f} B ({a.bucket_frames} frames), "
f"prefill {100*a.prefill:.0f}%")
print(f" lam: min {lm.min():.1f} median {rr['lam_med']:.1f} "
f"p90 {rr['lam_p90']:.1f} max {rr['lam_max']:.1f}")
print(f" frames over the per-frame budget (banked by the bucket): "
f"{rr['over']:.0f}%")
print(f" frames that could not fit even at the lam={RC.LAM_CLIFF:g} "
f"cliff: {rr['overrun']}/{len(lm)}")
# PER-FRAME non-SKIP distribution. The mean above cannot answer the
# decoder-architecture question (FINDINGS 24.5): decode-direct-to-GVRAM
# costs 76.6% of a 12fps frame budget x (non-SKIP fraction), while
# compose-in-RAM-then-blit is a flat 53.6% regardless. They cross at 70%,
# and that is a decision taken FRAME BY FRAME -- a scene cut is ~100%
# non-SKIP and a held frame near 0%, so their mean describes no real frame.
ns = np.array([100 * (mm != 0).mean() for mm in enc["modes"]])
over = int((ns > CROSSOVER_PCT).sum())
print(f" non-SKIP blocks/frame: median {np.median(ns):.1f}% "
f"p90 {np.percentile(ns, 90):.1f}% max {ns.max():.1f}%")
print(f" frames above the {CROSSOVER_PCT:.0f}% blit crossover: "
f"{over}/{len(ns)} ({100*over/len(ns):.1f}%) -> "
f"{'compose+blit wins on those' if over else 'direct-to-GVRAM wins throughout'}")
cost = np.minimum(BLIT_PCT, DIRECT_PCT * ns / 100)
print(f" display cost if the player picks the cheaper path per frame: "
f"median {np.median(cost):.1f}% p90 {np.percentile(cost, 90):.1f}% "
f"max {cost.max():.1f}% of a 12fps frame")
if a.preview:
from PIL import Image
f = len(idx) // 2
gap = np.full((H_ * 3, 4, 3), 40, np.uint8)
st = np.concatenate([VQ.zoom(m["rgb"][f], 3), gap,
VQ.zoom(pal[idx[f]], 3), gap,
VQ.zoom(pal[enc["recon"][f]], 3)], axis=1)
Image.fromarray(st).save(a.preview)
print(f" preview -> {a.preview} (source | palette ceiling | decoded)")
if __name__ == "__main__":
main()