Merge pull request #1022 from klikso/carry/old-10040-bink-index-validate

OLD-10040: bink_index: validate frame offsets within each stored stream
This commit is contained in:
MoonEyes
2026-11-28 22:52:45 +01:00
committed by GitHub
3 changed files with 146 additions and 13 deletions

View File

@ -90,9 +90,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 <archive.rpf> --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

View File

@ -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("<I", data, table + 4 * i, (payload + 8 * i) | int(i % 2 == 0))
return data
class TestFrameIndex(unittest.TestCase):
def check(self, stream, suffix=b""):
prefix = bytes(77) # embedded at a deliberately unaligned offset
data = prefix + stream + suffix
row = bink.parse_header(data, len(prefix))
self.assertIsNotNone(row)
return bink.frame_index_error(data, row)
def test_layouts_and_keyframe_flags(self):
for rev in "adfghijkn":
for tracks in (0, 2):
for frames in (1, 3):
with self.subTest(revision=rev, tracks=tracks, frames=frames):
self.assertIsNone(self.check(indexed_stream(rev, frames, tracks)))
def test_masked_offsets_must_increase_and_stay_inside_stream(self):
# Three frames, table at 48, first payload byte at 60, stream ends at 84.
for frame, entry, reason in [(0, 59, "outside"), (1, 60, "predecessor"),
(2, 65, "predecessor"), (2, 84, "outside"),
(2, 100, "outside")]:
with self.subTest(frame=frame, entry=entry):
stream = indexed_stream()
struct.pack_into("<I", stream, 48 + frame * 4, entry)
self.assertIn(reason, self.check(stream, bytes(64)))
def test_truncated_table_cannot_read_into_following_stream(self):
stream = indexed_stream()
struct.pack_into("<I", stream, 4, 56 - 8) # third index word lies past this stream
self.assertIn("exceeds stored stream size", self.check(stream))
def test_unknown_revision_is_reported_only_by_validation(self):
self.assertIn("unsupported", self.check(indexed_stream("z")))
def test_first_frame_can_start_after_a_gap(self):
stream = indexed_stream(frames=1)
struct.pack_into("<I", stream, 48, 56)
self.assertIsNone(self.check(stream))
class TestHeader(unittest.TestCase):
def test_fields(self):
row = bink.parse_header(make_stream(), 0)
@ -320,6 +369,37 @@ class TestCommandLine(unittest.TestCase):
def tearDown(self):
self.tmp.cleanup()
def test_validated_stream_produces_same_report(self):
with open(self.path, "wb") as fh:
fh.write(indexed_stream(audio=2))
for fmt in ("json", "csv"):
outputs = []
for options in ([], ["--validate-frames"]):
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
self.assertEqual(bink.main([self.path, "--format", fmt] + options), 0)
self.assertEqual("Frame offsets validated: 3 (streams: 1)" in err.getvalue(),
bool(options))
outputs.append(out.getvalue())
self.assertEqual(outputs[0], outputs[1])
def test_invalid_index_in_directory_preserves_existing_report(self):
# The first stream is valid. The second has an all-zero index.
first = indexed_stream()
with open(self.path, "wb") as fh:
fh.write(first)
fh.write(make_stream())
report = os.path.join(self.tmp.name, "result.json")
with open(report, "wb") as fh:
fh.write(b"existing report")
err, out = io.StringIO(), io.StringIO()
with contextlib.redirect_stderr(err), contextlib.redirect_stdout(out):
self.assertEqual(bink.main([self.tmp.name, "--validate-frames", "--out", report]), 2)
self.assertIn(f"one.bk2 at {len(first)}: frame 0", err.getvalue())
self.assertEqual(out.getvalue(), "")
with open(report, "rb") as fh:
self.assertEqual(fh.read(), b"existing report")
def test_csv_on_stdout_has_one_line_end_per_row(self):
# A text stream that writes "\n" as "\r\n", as Windows' stdout does, on any platform.
raw = io.BytesIO()

View File

@ -2,13 +2,15 @@
A Bink 2 stream starts with ``KB2`` and a lowercase revision letter. The first
44 (0x2C) bytes are the fixed header; audio-track metadata and the frame index
follow it, and their size depends on the revision and the track count. This
tool reads only the fixed header plus the audio descriptors, so a malformed
stream cannot make it read past the stored size.
follow it, and their size depends on the revision and the track count. By
default the indexer reads the fixed header and audio descriptors.
Usage:
python -I bink_index.py <movies.rpf | dir> [--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("<I", data, row["offset"] + table + 4 * frame)[0]
start = entry & ~1 # the low bit marks a keyframe
if start < table_end or start >= 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
@ -424,6 +461,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")
@ -458,7 +496,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)
@ -508,6 +549,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