From 77df8717a78f1595c77ba0ae273f14a8b2151322 Mon Sep 17 00:00:00 2001 From: Tiller431 <22901311+Tiller431@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:30:51 -0600 Subject: [PATCH] bink_index: validate frame offsets within each stored stream AI-assisted (Codex). --- docs/movies.md | 14 +++++-- tests/test_bink_index.py | 80 ++++++++++++++++++++++++++++++++++++++++ tools/bink_index.py | 65 +++++++++++++++++++++++++++----- 3 files changed, 146 insertions(+), 13 deletions(-) diff --git a/docs/movies.md b/docs/movies.md index a338069bd..da4d1417a 100644 --- a/docs/movies.md +++ b/docs/movies.md @@ -95,9 +95,17 @@ The audio flag bits verified against FFmpeg's demuxer are `0x4000` (prefer 16-bi All 229 are therefore Bink Audio DCT, stereo, 48 kHz by the header's own description. That does not prove the decoder output format or that every track is used by the game. -The frame index is not read by `bink_index.py`: its length depends on the frame count, and the index is not needed -to inventory the stream. `rpf9_carve.py` advances by the stored size instead, which is why it can carve without -parsing the index. +To check the frame index, run `python -I tools/bink_index.py --validate-frames`. The indexer skips +the revision-specific header and the 12 descriptor bytes per audio track, then reads one offset per frame. After +masking the keyframe bit, each offset must follow the complete table, fall inside the stored stream and increase +strictly from the preceding offset. The first frame can start immediately after the table. Validation stops at the +first bad table or unsupported revision and exits with status 2 before writing a report. A successful run reports +the number of frame offsets checked. This checks frame boundaries without decoding video or audio. The default +inventory and `rpf9_carve.py` can still advance by stored stream size alone. + +On 2026-11-23, all 22 RPF archives matched the 1.0.2.1 manifest by size and SHA-256. Four contained indexed +Bink 2 streams. The validator checked **683,552 frame offsets across all 797 streams** (787 revision `n`, 10 +revision `j`), with no table failures. This count covers streams the indexer found directly in the archives. ## 3. How the streams are found diff --git a/tests/test_bink_index.py b/tests/test_bink_index.py index db816e397..a85f780b8 100644 --- a/tests/test_bink_index.py +++ b/tests/test_bink_index.py @@ -47,6 +47,55 @@ def make_stream(revision="n", frames=4, width=320, height=240, audio=0, body=256 return bytes(header) + extra + audio_blob + bytes(4 * frames) + bytes(body) +def indexed_stream(revision="n", frames=3, audio=0): + """A synthetic stream with eight bytes per frame and alternating keyframe flags.""" + data = bytearray(make_stream(revision, frames=frames, audio=audio, body=8 * frames)) + payload = len(data) - 8 * frames + table = payload - 4 * frames + for i in range(frames): + struct.pack_into(" [--out index.csv|.json] - [--format csv|json] [--probe] + [--format csv|json] [--probe] [--validate-frames] + +With --validate-frames, check the frame offset table of each indexed stream +before producing the report. Invalid tables and unsupported revisions exit 2. With ``--probe`` each stream is written to a temporary file and passed to ``ffprobe``; the extra columns say only whether that ffprobe build can decode @@ -46,6 +48,7 @@ from replace_retry import replace as replace_retry # noqa: E402 SIG = re.compile(rb"KB2[a-z]") HDR = 0x2C +EXTRA_WORD_REVISIONS = "ijkn" MAX_FRAMES = 1_000_000 MAX_WIDTH = 7680 MAX_HEIGHT = 4800 @@ -109,7 +112,7 @@ def parse_header(data, offset): # Revisions i/j/k/n have one opaque word at 0x2C before the audio # descriptors; older revisions start them at 0x2C. Try the expected # layout first, then the other, and accept only plausible descriptors. - bases = [offset + 0x30, offset + 0x2C] if revision in "ijkn" else [offset + 0x2C] + bases = [offset + 0x30, offset + 0x2C] if revision in EXTRA_WORD_REVISIONS else [offset + 0x2C] for base in bases: got = _audio_layout(data, base, audio, offset + stored) if got: @@ -149,7 +152,37 @@ def _gap(data, start, end): return end - start, 0 -def scan_file(path, source): +def frame_index_error(data, row): + """Check stored frame starts, relative to this stream even inside an archive.""" + revision = row["revision"] + if revision in EXTRA_WORD_REVISIONS: + header = HDR + 4 + elif revision in "adfgh": + header = HDR + else: + return f"unsupported Bink 2 revision {revision}" + + table = header + 12 * row["audio_tracks"] + table_end = table + 4 * row["frames"] + if table_end > row["size"]: + return "frame index exceeds stored stream size" + previous = None + for frame in range(row["frames"]): + entry = struct.unpack_from("= row["size"]: + return f"frame {frame} starts outside the payload" + if previous is not None and start <= previous: + return f"frame {frame} does not start after its predecessor" + previous = start + return None + + +class FrameIndexError(ValueError): + """An indexed stream failed the requested frame-table check.""" + + +def scan_file(path, source, *, validate_frames=False): """Index every Bink 2 stream in one file. Returns (rows, stats).""" rows = [] size = os.path.getsize(path) @@ -178,6 +211,10 @@ def scan_file(path, source): if row is None: pos = match.start() + 1 continue + if validate_frames: + error = frame_index_error(data, row) + if error: + raise FrameIndexError(f"{source} at {match.start()}: {error}") z, u = _gap(data, last, match.start()) zero += z unread += u @@ -197,7 +234,7 @@ def scan_file(path, source): return rows, stats -def scan_target(target, skip_report=None): +def scan_target(target, skip_report=None, *, validate_frames=False): """Index a single container or every file below a directory. ``skip_report``, when given, is one existing file path (the report the @@ -221,12 +258,12 @@ def scan_target(target, skip_report=None): # "/" in the source and the sort key, so the report is the same on every platform paths.append((os.path.relpath(path, base).replace(os.sep, "/"), path)) for source, path in sorted(paths): - got, stats = scan_file(path, source) + got, stats = scan_file(path, source, validate_frames=validate_frames) rows.extend(got) for key in total: total[key] += stats[key] else: - rows, total = scan_file(target, os.path.basename(target)) + rows, total = scan_file(target, os.path.basename(target), validate_frames=validate_frames) return rows, total @@ -398,6 +435,7 @@ def main(argv=None): ap.add_argument("--out", help="index.csv or index.json; default is stdout") ap.add_argument("--format", choices=["csv", "json"], help="inferred from --out if omitted") ap.add_argument("--probe", action="store_true", help="run ffprobe on each stream") + ap.add_argument("--validate-frames", action="store_true", help="check each indexed stream's frame offsets") a = ap.parse_args(argv) if a.out and same_output_path(a.target, a.out): ap.error("--out must not overwrite the source") @@ -432,7 +470,10 @@ def main(argv=None): if a.out and os.path.isfile(a.out): skip_report = a.out try: - rows, summary = scan_target(a.target, skip_report) + rows, summary = scan_target(a.target, skip_report, validate_frames=a.validate_frames) + except FrameIndexError as error: + print(f"bink_index: error: {error}", file=sys.stderr) + return 2 except OSError as error: path = error.filename or a.target print(f"bink_index: error: cannot read {path}: {error.strerror or error}", file=sys.stderr) @@ -482,6 +523,10 @@ def main(argv=None): f"{summary['unread_bytes']} unread, {summary['zero_padding']} zero padding, " f"{summary['rpf_trailer']} RPF trailer", file=sys.stderr) + if a.validate_frames: + frames = sum(row["frames"] for row in rows) + print(f"Frame offsets validated: {frames} (streams: {len(rows)})", + file=sys.stdout if a.out else sys.stderr) return 0