diff --git a/docs/audio.md b/docs/audio.md index 5d46966e3..d7cbc6311 100644 --- a/docs/audio.md +++ b/docs/audio.md @@ -403,3 +403,14 @@ the audio itself is not. See the ground rules in [design.md](design.md#ground-ru The tools export the streams and channels as stored. They do not reconstruct runtime mixing, looping, ducking or music-segment selection; that belongs to the game's audio system. + +## Streamed-music cue sheets + +Run `python -I tools/awc_opus.py --cue-sheet` to write +`cue_regions.json` next to the Ogg files for each bank with verified regions. Each row names +a sibling audio file and the hexadecimal cue-name hash. The integer interval +`[start_sample, end_sample)` counts 48 kHz frames per channel from the start of playback. +Overlapping regions keep their original endpoints. The exporter pairs consecutive same-name +start/end records within one ordered marker tag. It requires a unique stream entry and +descriptor channel with the same ID, exported packets, and endpoints within the declared +and exported audio. A rerun with the option refreshes an existing sheet even if it becomes empty. diff --git a/docs/rsc8_audio.md b/docs/rsc8_audio.md index 68a1b70d1..2a5766207 100644 --- a/docs/rsc8_audio.md +++ b/docs/rsc8_audio.md @@ -158,8 +158,8 @@ The name word is 0 on 96 records (78 tags start with one); what a nameless recor `0xE5C74063` (418,838 records, 402,357 of them on speech streams with a `0x5c` clip) and `0xdbedd43c` (330,756, all on such streams and all with `extra = 0`) are not known. - **`value`** is a whole number stored as `f32` on every record of those six names. On five of the other names it - is `joaat("start")` or `joaat("end")` in equal or near-equal numbers (196/197, 101/101, 54/54, 49/49, 20/19), - which reads as region start/end pairs (hypothesis: the split was counted, not matched record by record). + is `joaat("start")` (`0x84dc271f`) or `joaat("end")` (`0xb0c485d7`). Matched record by record, 418 of the 420 + `start` records are followed by their `end`; see [Region cues](#region-cues-start-and-end-records). - The same reference states that an AWC tag id is the low byte of the joaat of the chunk name. That holds for `markers` (`0xbd`), `data` (`0x55`), `peak` (`0x36`), `seektable` (`0xa3`) and `streamformat` (`0x48`), which `tests/test_rsc8_audio.py` checks, and by the same rule `0x5a` and `0xd9` are `granulargrains` and @@ -167,6 +167,60 @@ The name word is 0 on 96 records (78 tags start with one); what a nameless recor `stream_format`, and with the underscore the rule fails (`0xb8` and `0xf9`). It does not hold for `0x5c`, `0x76` and `0xb2` under the names `animation`, `format` and `metadata` either, so those three names stay open. +#### Region cues: `start` and `end` records + +The five names whose `value` is the hash of `start` or `end` have 841 records in 22 tags of `audio.rpf`: 420 +`start`, 420 `end` and one with a third value. An earlier version of this page read the near-equal counts per name +(196/197, 101/101, 54/54, 49/49, 20/19) as region pairs without matching them. `tools/rsc8_audio.py` now matches +them (`pair_marker_regions`, the `marker_regions` block of every scan summary): inside one tag it takes the +records of one name in stored order, and a pair is a `start` whose next record of the same name is an `end` at the +same or a later offset. Every other record of such a name is counted as an exception. + +| Name | Tags | `start` | `end` | Pairs | Not paired | Pair length in samples (min / median / max) | +|---|---:|---:|---:|---:|---|---:| +| `0xda559149` | 22 | 196 | 197 | 196 | 1 `end` | 172,602 / 857,823 / 3,899,077 | +| `0x1df219ec` | 1 | 101 | 101 | 101 | none | 25,289 / 95,237 / 497,606 | +| `0x77edd3a2` | 1 | 54 | 54 | 53 | 1 `start`, 1 `end`, the record with the third value | 44,984 / 90,546 / 209,958 | +| `0x994ee645` | 1 | 49 | 49 | 49 | none | 22,233 / 93,644 / 212,156 | +| `0xccb465d1` | 1 | 20 | 19 | 19 | 1 `start` | 36,146 / 92,928 / 186,375 | +| **Total** | **22** | **420** | **420** | **418** | **5 records** | | + +So the reading holds for 418 pairs, and equal counts did not prove it: the 54/54 name has two unpaired records. +20 of the 22 tags pair completely (a tag holds 1 to 181 pairs, median 3). The five exceptions sit in two tags: + +- `0xda559149` has a second `end` 16,717 samples after the `end` that closes the region before it (record 744 of + its tag's 1,435). Nothing opens it. +- A `0x77edd3a2` `start` (record 40 of 834) is followed, 118,171 samples later, by a record of the same name whose + value is `0xdaa2d5ec`, the only value on these names that is neither word. Hypothesis: that record closes the + region under another word; the distance is inside the name's pair lengths. +- A `0xccb465d1` `start` (record 773 of the same tag, the last record of its name) is directly followed by a + `0x77edd3a2` `end` that no `start` opens (record 774), 114,697 samples later. Hypothesis: one region whose two + records carry different names; the distance is inside the pair lengths of both. + +If both hypotheses hold, every one of the 420 `start` records has a closing record and only the second `end` +is left over. None of the five is a region left open at an edge of its tag: none is the tag's first or last +record, the nearest to an edge is 40 records in, and the unclosed `0xccb465d1` `start` is 18,219,408 samples +before its tag's last offset. + +Also measured on the 418 pairs: + +- No pair has a zero length, and `extra` is the same on a pair's two records (418 / 418). +- Regions of one name cannot overlap under this matching; an overlap would show as an unpaired `start` followed + by a `start`, and there is none. Regions of different names do overlap: 54 pairs of regions share samples, 43 + with one region inside the other and 11 crossing (each starts or ends inside the other). All 54 are between + `0xda559149` and one of the other four names (`0x1df219ec` 13 inside / 7 crossing, `0x77edd3a2` 19 / 4, + `0x994ee645` 2 / 0, `0xccb465d1` 9 / 0); the other four never overlap each other. So a sample can lie in + regions of two names at once. +- None of the 22 streams has a `0x76` tag (`tags_with_sample_count` is 0), so this parser has no sample count to + compare a region's end with. + +The other three archives with `ADAT` banks have `0xbd` tags as well (226,788 in `story000.rpf`, 1,959 in +`shared_minigame000.rpf`, 22 in `story000_restofworld.rpf`) and not one record with either value. + +Not known: the words behind the five names and behind `0xdaa2d5ec`, what a region does in the game, and whether +the two hypotheses above are right. The lengths are in the unit of `offset`; they were not converted to seconds, +because the rate of these 22 streams is not read here. + ## Binary format of `RSC8` (version `8001`) All integers and IEEE-754 floats are little-endian. Every `RSC8` tag payload is 16-byte aligned. @@ -368,6 +422,10 @@ python -I tools/rsc8_audio.py \pack\shared_minigame000\shared_minigame0 python -I tools/rsc8_audio.py \pack\story000\story000.rpf --summary-only python -I tools/rsc8_audio.py \audio.rpf --summary-only +# Every summary also has the cue counts (marker_* keys) and the region pairing (marker_regions): pairs and +# exceptions per name hash, pair lengths, overlaps between names and where each exception sits in its tag. +# The numbers of "Region cues" above are the audio.rpf summary's (57 to 87 s over three runs of the 28.5 GB archive). + # Also decode every clip's keyframes and count the outcome (slower: about 40 clips per second per process; # split a large archive with --start/--limit and add the summaries) python -I tools/rsc8_audio.py \pack\shared_minigame000\shared_minigame000.rpf --summary-only --curves diff --git a/tests/test_awc_markers.py b/tests/test_awc_markers.py index 618edf95a..18b289c2b 100644 --- a/tests/test_awc_markers.py +++ b/tests/test_awc_markers.py @@ -6,6 +6,7 @@ import contextlib import io import json import os +from pathlib import Path import struct import subprocess import sys @@ -68,6 +69,67 @@ def speech_bank(sid, samples, marker_chunk, payload=b"\0" * 64): return build_bank([(sid, [(0x55, payload), (0x76, bytes(fmt)), (0xBD, marker_chunk)])]) +class MusicCueSheetTest(unittest.TestCase): + def test_failed_cli_rerun_clears_previous_regions(self): + from rsc8_audio import MARKER_VALUE_START, MARKER_VALUE_END + + cues = event(1, MARKER_VALUE_START, 10) + event(1, MARKER_VALUE_END, 30) + with tempfile.TemporaryDirectory() as tmp: + src = Path(tmp) / "music.awc" + out = Path(tmp) / "out" + sheet = out / "music" / "cue_regions.json" + args = [sys.executable, "-I", Path(TOOL).with_name("awc_opus.py"), src, out, "--cue-sheet", "--jobs", "1"] + for failure in ("parse", "write"): + with self.subTest(failure=failure): + src.write_bytes(music_bank(7, 200, 0xFC, cues)) + subprocess.run(args, check=True, capture_output=True) + self.assertEqual(json.loads(sheet.read_bytes())["regions"][0]["file"], "00000007.ogg") + if failure == "parse": + src.write_bytes(b"invalid bank") + else: + src.write_bytes(music_bank(8, 200, 0xFC, cues)) + (sheet.parent / "00000008.ogg").mkdir() + result = subprocess.run(args, capture_output=True) + self.assertEqual(result.returncode, 0 if failure == "parse" else 1) + self.assertEqual(json.loads(sheet.read_bytes()), {"sample_rate": 48000, "regions": []}) + + def test_exported_frame_coordinates_and_ambiguous_inputs(self): + import awc_opus + from rsc8_audio import MARKER_VALUE_START as start, MARKER_VALUE_END as end, parse_adat_header_bytes + + cues = (event(1, start, 10) + event(2, start, 20) + event(1, end, 30) + + event(2, end, 40) + event(3, start, 60) + event(3, end, 500)) + bank = music_bank(7, 200, 0xFC, cues) # 100 frames of stereo + header = parse_adat_header_bytes(bank, 0, len(bank)) + entries = [(sid, [(kind, bank[off:off + size]) for kind, off, size in tags]) + for sid, tags in header["entries"]] + desc, data = [blob for _, blob in entries[0][1]] + with tempfile.TemporaryDirectory() as tmp: + src = os.path.join(tmp, "music.awc") + out = os.path.join(tmp, "out") + sheet = os.path.join(out, "music", "cue_regions.json") + + def export(payload, flag=True): + with open(src, "wb") as f: + f.write(payload) + args = [src, out, "--jobs", "1"] + (["--cue-sheet"] if flag else []) + self.assertEqual(awc_opus.main(args), 0) + if flag: + with open(sheet, encoding="utf-8") as f: + return json.load(f) + + export(bank, False) + self.assertFalse(os.path.exists(sheet)) + self.assertEqual(export(bank), {"sample_rate": 48000, "regions": [ + {"file": "00000007.ogg", "name_hash": "00000001", "start_sample": 10, "end_sample": 30}, + {"file": "00000007.ogg", "name_hash": "00000002", "start_sample": 20, "end_sample": 40}]}) + self.assertTrue(os.path.isfile(os.path.join(out, "music", "00000007.ogg"))) + for ambiguous in (entries + [entries[0]], entries + [entries[1]], + [(0, [(0x48, desc), (0x55, bytes(len(data)))]), entries[1]], + [entries[0], (9, entries[1][1])]): + self.assertEqual(export(build_bank(ambiguous))["regions"], []) + + class EventLayoutTest(unittest.TestCase): def test_sixteen_byte_events_and_a_dropped_tail(self): chunk = event(TRACK, 1234.0, 0) + event(TICK, 8.0, 48000, 5) + b"\x01\x02\x03" diff --git a/tests/test_rsc8_audio.py b/tests/test_rsc8_audio.py index c3ed5501f..8fcc9e4d3 100644 --- a/tests/test_rsc8_audio.py +++ b/tests/test_rsc8_audio.py @@ -1382,5 +1382,273 @@ class MarkerRecordsTest(unittest.TestCase): self.assertTrue(comp["markers"]["offsets_within_samples"]) +def build_synthetic_region_markers(records): + """16-byte cue records with the value as a u32 word, as a region cue stores it: name, value, offset, extra.""" + return b"".join(struct.pack(" 0: + frame_limits[cid] = min(samples, max(0, granule - pre_skip)) counts["music"] += 1 for s, stem in zip(streams, export_stems([s["id"] for s in streams])): at, size = s["data"] @@ -384,6 +429,13 @@ def export_bank(path: str, out_dir: str, pre_skip: int = OPUS_PRE_SKIP): counts["pcm"] += 1 continue counts["other"] += 1 + if cue_sheet: + for stream in streams: + frame_limits.pop(stream["id"], None) + verified = {cid: limit for cid, limit in frame_limits.items() if channel_counts[cid] == 1} + rows = music_cue_regions(d, verified) + if rows: + write_cue_sheet(sheet, rows) return counts @@ -391,6 +443,7 @@ def main(argv=None) -> int: ap = argparse.ArgumentParser() ap.add_argument("src") ap.add_argument("out") + ap.add_argument("--cue-sheet", action="store_true", help="write paired music cues beside their Ogg files") ap.add_argument("--limit", type=int, help="maximum number of banks to export (default: all)") ap.add_argument("--jobs", type=int, default=max(1, (os.cpu_count() or 2) // 2), help="banks to export at once (default: half the CPU count)") @@ -454,7 +507,7 @@ def main(argv=None) -> int: if jobs == 1: for i, (b, output_parent) in enumerate(banks): try: - add(export_bank(b, output_parent, a.pre_skip)) + add(export_bank(b, output_parent, a.pre_skip, a.cue_sheet)) except (ValueError, struct.error, IndexError, OSError) as e: skipped(b, e) continue @@ -462,7 +515,7 @@ def main(argv=None) -> int: print(f" {i + 1}/{len(banks)} banks: {tot}", flush=True) else: with ProcessPoolExecutor(max_workers=process_workers(jobs)) as ex: - futures = {ex.submit(export_bank, b, output_parent, a.pre_skip): b for b, output_parent in banks} + futures = {ex.submit(export_bank, b, output_parent, a.pre_skip, a.cue_sheet): b for b, output_parent in banks} for i, fut in enumerate(as_completed(futures), 1): b = futures[fut] try: diff --git a/tools/rsc8_audio.py b/tools/rsc8_audio.py index 2a9270171..0e3ba9214 100644 --- a/tools/rsc8_audio.py +++ b/tools/rsc8_audio.py @@ -25,12 +25,17 @@ Usage: `--curves` also decodes every clip's keyframes (the blocks are the sequence layout of tools/anim_clips.py) and counts the outcome; it reports counts only, never a value. + +Every scan also reads the `0xbd` cue records of each stream; the summary's `marker_regions` block +matches the records whose value is joaat("start") or joaat("end") into region pairs, name by name +(pair_marker_regions(), docs/rsc8_audio.md). """ import argparse import csv import json import math import os +import statistics import struct import sys import tempfile @@ -68,6 +73,11 @@ MARKER_NAME_COMMON = 0xE5C74063 MARKER_MAGIC = MARKER_NAME_COMMON MARKER_RECORD_BYTES = 16 MAX_MARKER_BYTES = 16 * 1024 * 1024 +# A region cue stores a second name hash in its `value` word (pair_marker_regions()). +MARKER_VALUE_START = 0x84DC271F # joaat("start") +MARKER_VALUE_END = 0xB0C485D7 # joaat("end") +_REGION_VALUES = {MARKER_VALUE_START: "start", MARKER_VALUE_END: "end"} +MAX_REGION_EXCEPTIONS_LISTED = 64 ATTR_FLOAT = 0xFFFF0001 ATTR_INT = 0xFFFF0002 @@ -1035,6 +1045,251 @@ def decode_marker_records(blob, sample_count=None): return out +def marker_records(blob): + """The ``(name, value, offset, extra)`` u32 words of every whole 16-byte record of a ``0xbd`` tag.""" + raw = bytes(blob) + return list(struct.iter_unpack(" region["start"]] + for a in active: + if a["name"] == region["name"]: + continue + counts = out.setdefault((min(a["name"], region["name"]), max(a["name"], region["name"])), [0, 0]) + nested = region["end"] <= a["end"] or region["start"] == a["start"] + counts[0 if nested else 1] += 1 + active.append(region) + return out + + +def _new_region_tally(): + """Running totals of pair_marker_regions() over the tags of a scan; marker_region_report() finishes them.""" + return { + "tags": 0, # tags with at least one start/end record + "tags_all_paired": 0, # ... and no exception + "tags_with_sample_count": 0, # ... on a stream that has a 0x76 sample count + "pairs_per_tag": [], + "pairs_extra_differs": 0, + "overlaps": {}, # marker_region_overlaps(), added up + "names": {}, # name -> the counts of pair_marker_regions(), "tags" and the "lengths" of its pairs + "exceptions_total": 0, + "exceptions": [], # the first MAX_REGION_EXCEPTIONS_LISTED in scan order + } + + +def _tally_marker_regions(tally, records, *, bank_offset=0, stream_id=None, sample_count=None): + """Add one valid ``0xbd`` tag's region pairing to a `_new_region_tally()`.""" + paired = pair_marker_regions(records) + if not paired["names"]: + return + tally["tags"] += 1 + tally["tags_all_paired"] += not paired["exceptions"] + tally["tags_with_sample_count"] += sample_count is not None + tally["pairs_per_tag"].append(len(paired["regions"])) + for name, counts in paired["names"].items(): + into = tally["names"].setdefault(name, {"tags": 0, "lengths": []}) + into["tags"] += 1 + for key, count in counts.items(): + into[key] = into.get(key, 0) + count + for region in paired["regions"]: + tally["names"][region["name"]]["lengths"].append(region["end"] - region["start"]) + tally["pairs_extra_differs"] += region["extra_differs"] + _add_region_overlaps(tally["overlaps"], marker_region_overlaps(paired["regions"])) + tally["exceptions_total"] += len(paired["exceptions"]) + for exc in paired["exceptions"]: + if len(tally["exceptions"]) >= MAX_REGION_EXCEPTIONS_LISTED: + break + tally["exceptions"].append({ + "kind": exc["kind"], + "name": f"0x{exc['name']:08x}", + "value": f"0x{exc['value']:08x}", + "before": exc["before"], + "before_offset": exc["before_offset"], + "after": exc["after"], + "after_offset": exc["after_offset"], + "record": exc["index"], + "tag_records": len(records), + "offset": exc["offset"], + "tag_last_offset": records[-1][2], + "stream_samples": sample_count, + "bank_offset": bank_offset, + "stream_id": None if stream_id is None else f"0x{stream_id:08x}", + }) + + +def _add_region_overlaps(dst, src): + for names, (nested, crossing) in src.items(): + into = dst.setdefault(names, [0, 0]) + into[0] += nested + into[1] += crossing + + +def _merge_region_tally(dst, src): + for key, value in src.items(): + if key == "overlaps": + _add_region_overlaps(dst[key], value) + elif key == "names": + for name, counts in value.items(): + into = dst["names"].setdefault(name, {"tags": 0, "lengths": []}) + for field, count in counts.items(): + if field == "lengths": + into["lengths"].extend(count) + else: + into[field] = into.get(field, 0) + count + elif key == "exceptions": + dst[key].extend(value[: MAX_REGION_EXCEPTIONS_LISTED - len(dst[key])]) + elif isinstance(value, list): + dst[key].extend(value) + else: + dst[key] += value + + +def _min_median_max(values): + if not values: + return None + return {"min": min(values), "median": statistics.median(values), "max": max(values)} + + +def marker_region_report(tally): + """The `marker_regions` block of a scan summary, from a `_new_region_tally()`: counts, sample + offsets and 32-bit hashes only. + + ``names`` maps each region name (hex) to its ``starts``, ``ends``, ``pairs``, the four exception + counts of pair_marker_regions() and the ``length_samples`` (min/median/max) of its pairs. + ``overlaps_between_names`` counts pairs of paired regions of different names in one tag that share a + sample (marker_region_overlaps()), in all and per pair of names. ``exceptions`` lists the first + `MAX_REGION_EXCEPTIONS_LISTED` in scan order with where each one sits: its record index among the + tag's ``tag_records``, its offset, the tag's last offset, the stream's ``0x76`` sample count when it + has one, and what and where the neighbouring records of the same name are (``None``: it is the + name's first or last record of the tag). ``exceptions_total`` counts them all. + """ + names = {} + for name, counts in sorted(tally["names"].items(), key=lambda kv: (-kv[1]["starts"] - kv[1]["ends"], kv[0])): + row = {key: value for key, value in counts.items() if key != "lengths"} + row["length_samples"] = _min_median_max(counts["lengths"]) + names[f"0x{name:08x}"] = row + return { + "tags": tally["tags"], + "tags_all_paired": tally["tags_all_paired"], + "tags_with_sample_count": tally["tags_with_sample_count"], + "starts": sum(c["starts"] for c in tally["names"].values()), + "ends": sum(c["ends"] for c in tally["names"].values()), + "pairs": sum(c["pairs"] for c in tally["names"].values()), + "pairs_per_tag": _min_median_max(tally["pairs_per_tag"]), + "pairs_extra_differs": tally["pairs_extra_differs"], + "overlaps_between_names": { + "nested": sum(n for n, _c in tally["overlaps"].values()), + "crossing": sum(c for _n, c in tally["overlaps"].values()), + "by_names": { + f"0x{a:08x}+0x{b:08x}": {"nested": n, "crossing": c} + for (a, b), (n, c) in sorted(tally["overlaps"].items()) + }, + }, + "names": names, + "exceptions_total": tally["exceptions_total"], + "exceptions": list(tally["exceptions"]), + } + + def _decode_companion_tags(read_slice, bank_offset, tag_map): """Decode companion speech tags (`0x76`, `0x55`, `0x36`, `0x5a`, `0xa3`, `0xb2`, `0xbd`, `0xd9`) on a stream.""" comp = { @@ -1135,24 +1390,31 @@ def _new_grid_tally(): "marker_records": 0, "marker_invalid": 0, "marker_first_names": {}, + # Region cues matched into start/end pairs (ASSET-320). A running `_new_region_tally()` while banks are + # read and in decode_awc_bank()'s result; a scan's summary carries marker_region_report() of it. + "marker_regions": _new_region_tally(), } def _merge_grid_tally(dst, src): """Add one bank's companion-table tally to a running summary (counts add, per-name maps merge).""" for key, start in _new_grid_tally().items(): - if isinstance(start, dict): + if key == "marker_regions": + _merge_region_tally(dst[key], src[key]) + elif isinstance(start, dict): for name, count in src[key].items(): dst[key][name] = dst[key].get(name, 0) + count else: dst[key] += src[key] -def _tally_undocumented_tables(read_slice, bank_base, tmap, tally): +def _tally_undocumented_tables(read_slice, bank_base, tmap, tally, stream_id=None): """Decode the ``0x5a``/``0xd9`` tables and the ``0xbd`` cue list on one stream into a running tally. A stream counts as invalid when one of the layout invariants measured over the whole ``audio.rpf`` - population fails, so the tally doubles as a package-wide validator. + population fails, so the tally doubles as a package-wide validator. The region cues of a valid + ``0xbd`` tag are matched into start/end pairs (`marker_regions`); `stream_id` only labels the + exceptions listed there. """ grid = None if TAG_GRID20 in tmap: @@ -1197,9 +1459,10 @@ def _tally_undocumented_tables(read_slice, bank_base, tmap, tally): tally["indexrun_index_overruns"] += 1 if TAG_MARKER in tmap: mo, ms = tmap[TAG_MARKER][0] - marks = None + marks = blob = None if 0 < ms <= MAX_MARKER_BYTES: - marks = decode_marker_records(read_slice(bank_base + mo, ms)) + blob = read_slice(bank_base + mo, ms) + marks = decode_marker_records(blob) tally["marker_streams"] += 1 if marks is None or not (marks["size_ok"] and marks["offsets_ascending"]): tally["marker_invalid"] += 1 @@ -1208,6 +1471,15 @@ def _tally_undocumented_tables(read_slice, bank_base, tmap, tally): key = f"0x{marks['first_name']:08x}" firsts = tally["marker_first_names"] firsts[key] = firsts.get(key, 0) + 1 + records = marker_records(blob) + if any(value in _REGION_VALUES for _name, value, _offset, _extra in records): + samples = None + if TAG_FORMAT in tmap: + fo, fs = tmap[TAG_FORMAT][0] + fb = read_slice(bank_base + fo, 4) if fs >= 4 else b"" + samples = _u32(fb, 0) if len(fb) == 4 else None + _tally_marker_regions(tally["marker_regions"], records, bank_offset=bank_base, + stream_id=stream_id, sample_count=samples) def decode_awc_bank(data, bank_offset=0, *, deep=True, curves=False): @@ -1229,7 +1501,7 @@ def decode_awc_bank(data, bank_offset=0, *, deep=True, curves=False): key = f"0x{tt:02x}" tag_counts[key] = tag_counts.get(key, 0) + 1 tmap.setdefault(tt, []).append((toff, tsz)) - _tally_undocumented_tables(read_slice, 0, tmap, tally) + _tally_undocumented_tables(read_slice, 0, tmap, tally, sid) for tt, toff, tsz in tags: if tt == TAG_RSC8_CLIP: if tsz < 4 or tsz > MAX_RSC8_BYTES: @@ -1306,6 +1578,12 @@ def _new_summary(mode, source): } +def _finish_summary(summary, t0): + """Close a scan's summary: the running region tally becomes its report, and the clock stops.""" + summary["marker_regions"] = marker_region_report(summary["marker_regions"]) + summary["elapsed_seconds"] = round(time.time() - t0, 3) + + def _accumulate_record(summary, rec, *, in_adat=True, has_audio=None): summary["rsc8_decoded"] += 1 if in_adat: @@ -1498,7 +1776,7 @@ def scan_rpf(path, *, start=0, limit=None, max_banks=None, deep=True, collect_re tk = f"0x{tt:02x}" summary["adat_tag_counts"][tk] = summary["adat_tag_counts"].get(tk, 0) + 1 tmap.setdefault(tt, []).append((toff, tsz)) - _tally_undocumented_tables(bank_read_slice, aoff, tmap, summary) + _tally_undocumented_tables(bank_read_slice, aoff, tmap, summary, sid) if not has_5c: continue for tt, toff, tsz in tags: @@ -1557,7 +1835,7 @@ def scan_rpf(path, *, start=0, limit=None, max_banks=None, deep=True, collect_re progress(pos, scan_end, summary) next_prog += 2 * 1024 * 1024 * 1024 - summary["elapsed_seconds"] = round(time.time() - t0, 3) + _finish_summary(summary, t0) return records, summary @@ -1617,7 +1895,7 @@ def scan_dir(path, *, max_banks=None, deep=True, collect_records=True, curves=Fa summary["invalid_files"] += 1 print(f"{fp}: {e}", file=sys.stderr) - summary["elapsed_seconds"] = round(time.time() - t0, 3) + _finish_summary(summary, t0) return records, summary @@ -1637,7 +1915,7 @@ def scan_single_file(path, *, start=0, limit=None, max_banks=None, deep=True, co rec = _make_record(0, 0, None, dec, None) summary = _new_summary("rsc8", path) _accumulate_record(summary, rec, in_adat=False, has_audio=None) - summary["elapsed_seconds"] = round(time.time() - t0, 3) + _finish_summary(summary, t0) return ([rec] if collect_records else []), summary if head == ADAT_MAGIC and start == 0 and limit is None and fsize <= MAX_AWC_FILE_BYTES: t0 = time.time() @@ -1653,7 +1931,7 @@ def scan_single_file(path, *, start=0, limit=None, max_banks=None, deep=True, co summary["rsc8_non_rsc8_0x5c"] = bank_res["non_rsc8_0x5c"] for rec in bank_res["records"]: _accumulate_record(summary, rec, in_adat=True, has_audio=rec.get("has_audio_data")) - summary["elapsed_seconds"] = round(time.time() - t0, 3) + _finish_summary(summary, t0) return (bank_res["records"] if collect_records else []), summary return scan_rpf( path,