From cb89a384d2a5ace746dcadbacb05ce6c7a18be5f Mon Sep 17 00:00:00 2001 From: fiestorra Date: Thu, 26 Nov 2026 00:15:47 +0100 Subject: [PATCH 1/5] tools: skip Ogg Opus outputs that already exist, so a stopped audio export resumes awc_opus.py repacked every bank on every run, so a stopped assets run redid the whole Ogg Opus step: on one machine 664,446 .ogg files were already written and the restart began at bank 0. The stage marks the step done only after it finishes, so there was no per-bank resume. --skip-existing leaves an output that exists alone before packing a music channel or writing a stream's .ogg/.wav, and make_game.py passes it in the audio step. The staged writer publishes atomically, so an existing file is always complete. Measured on a 1 MB bank with 29 outputs: first export 0.8 s, second with the flag 0.23 s and 0 files rewritten, while the same export without the flag does rewrite them. tests/test_awc_opus.py covers that with the control. --- make_game.py | 4 +++- tests/test_awc_opus.py | 23 +++++++++++++++++++++++ tools/awc_opus.py | 40 ++++++++++++++++++++++++++++++++-------- 3 files changed, 58 insertions(+), 9 deletions(-) diff --git a/make_game.py b/make_game.py index 31a24a8f20..83063f0d4c 100644 --- a/make_game.py +++ b/make_game.py @@ -2780,7 +2780,9 @@ def dump(*parts: str) -> None: if need_ogg: # Lossless: the banks' Opus packets repackaged as standard Ogg Opus files (PCM streams as .wav) log("assets: audio streams -> Ogg Opus") - py("awc_opus.py", os.path.join(out, "audio", "awc"), ogg, "--jobs", str(jobs)) + # A stopped run leaves most of the Ogg files written but no marker, so a restarted stage would repack every + # bank from the beginning; --skip-existing makes that restart pick up where it stopped. + py("awc_opus.py", os.path.join(out, "audio", "awc"), ogg, "--jobs", str(jobs), "--skip-existing") mark(ogg_done, "awc_opus.py") progress.tick(force=True) if need_wav: diff --git a/tests/test_awc_opus.py b/tests/test_awc_opus.py index dd09e90608..848d92f54f 100644 --- a/tests/test_awc_opus.py +++ b/tests/test_awc_opus.py @@ -398,6 +398,29 @@ def make_bank(self): f.write(bank) return path, pcm16, floats + def test_skip_existing_leaves_written_files_alone(self): + path, _, _ = self.make_bank() + awc.export_bank(path, self.out) + written = {} + for root, _, files in os.walk(self.out): + for name in files: + full = os.path.join(root, name) + written[full] = os.stat(full).st_mtime_ns + self.assertEqual(len(written), 3, written) + # Freeze one output so a rewrite is visible, then export again with the flag. + target = sorted(written)[0] + os.utime(target, ns=(0, 0)) + counts = awc.export_bank(path, self.out, skip_existing=True) + self.assertEqual(os.stat(target).st_mtime_ns, 0, "an existing file was rewritten") + for full, mtime in written.items(): + if full != target: + self.assertEqual(os.stat(full).st_mtime_ns, mtime, full) + self.assertEqual((counts["opus"], counts["pcm"]), (1, 2), counts) + # Control: the same export without the flag does rewrite the frozen file. + awc.export_bank(path, self.out) + self.assertNotEqual(os.stat(target).st_mtime_ns, 0, + "a plain export should have rewritten the file, so the flag is what spares it") + def test_recursive_cli_preserves_bank_paths(self): src = Path(self.tmp.name) / "banks" samples = {"north/shared": 11, "south/shared": 22, "flat": 33} diff --git a/tools/awc_opus.py b/tools/awc_opus.py index be3cd9aaf2..9075d9e6af 100644 --- a/tools/awc_opus.py +++ b/tools/awc_opus.py @@ -469,10 +469,11 @@ def write_cue_sheet(sheet, rows): write_file(sheet, (json.dumps(payload, indent=2) + "\n").encode("utf-8")) -def export_bank(path: str, out_dir: str, pre_skip: int = OPUS_PRE_SKIP, cue_sheet: bool = False): +def export_bank(path: str, out_dir: str, pre_skip: int = OPUS_PRE_SKIP, cue_sheet: bool = False, + skip_existing: bool = False): od = bank_output_dir(path, out_dir) - if cue_sheet: - sheet = os.path.join(od, "cue_regions.json") + sheet = os.path.join(od, "cue_regions.json") + if cue_sheet and not skip_existing: if os.path.exists(sheet): # A skipped bank or interrupted channel write must not leave last run's regions current. write_cue_sheet(sheet, []) @@ -491,8 +492,15 @@ def export_bank(path: str, out_dir: str, pre_skip: int = OPUS_PRE_SKIP, cue_shee if cue_sheet: channel_counts[cid] += 1 if pk: + # The write below uses the de-duplicated stem, so the skip has to look at the same name: a bank + # whose streams share an id exports XXXXXXXX.ogg and XXXXXXXX~2.ogg, and only the first would have + # been seen under the raw id. + target = os.path.join(od, stem + ".ogg") + if skip_existing and os.path.exists(target): + counts["music"] += 1 + continue n48 = samples * 48000 // rate if rate else 0 - granule = write_ogg_opus(os.path.join(od, stem + ".ogg"), pk, packet_channels, cid, n48, + granule = write_ogg_opus(target, pk, packet_channels, cid, n48, pre_skip=pre_skip) if cue_sheet and rate == 48000 and samples > 0: frame_limits[cid] = min(samples, max(0, granule - pre_skip)) @@ -500,6 +508,10 @@ def export_bank(path: str, out_dir: str, pre_skip: int = OPUS_PRE_SKIP, cue_shee for s, stem in zip(streams, export_stems([s["id"] for s in streams])): at, size = s["data"] if s["codec"] == 0x0B and size % 2048 == 0 and s["channels"] in (1, 2): + ogg = os.path.join(od, stem + ".ogg") + if skip_existing and os.path.exists(ogg): + counts["opus"] += 1 + continue pk = opus_packets(d, at, size) if pk: # +0x0C is the per-channel Opus frame count: equal to the +0 count for mono and @@ -509,17 +521,25 @@ def export_bank(path: str, out_dir: str, pre_skip: int = OPUS_PRE_SKIP, cue_shee frames = s["frames"] if not frames or frames * s["channels"] != s["samples"]: frames = s["samples"] // max(1, s["channels"]) - write_ogg_opus(os.path.join(od, stem + ".ogg"), pk, s["channels"], s["id"], frames, + write_ogg_opus(ogg, pk, s["channels"], s["id"], frames, pre_skip=pre_skip) counts["opus"] += 1 continue if s["codec"] == 2 and s["channels"] in (1, 2) and size == s["samples"] * s["channels"] * 4: # codec 2: 32-bit float PCM (4 bytes per sample; values can exceed +-1, e.g. impulse responses) - write_wav(os.path.join(od, stem + ".wav"), memoryview(d)[at:at + size], s["rate"], s["channels"], True) + wav = os.path.join(od, stem + ".wav") + if skip_existing and os.path.exists(wav): + counts["pcm"] += 1 + continue + write_wav(wav, memoryview(d)[at:at + size], s["rate"], s["channels"], True) counts["pcm"] += 1 continue if s["codec"] == 0 and s["channels"] in (1, 2) and size == s["samples"] * s["channels"] * 2: - write_wav(os.path.join(od, stem + ".wav"), memoryview(d)[at:at + size], s["rate"], s["channels"]) + wav = os.path.join(od, stem + ".wav") + if skip_existing and os.path.exists(wav): + counts["pcm"] += 1 + continue + write_wav(wav, memoryview(d)[at:at + size], s["rate"], s["channels"]) counts["pcm"] += 1 continue counts["other"] += 1 @@ -538,6 +558,9 @@ def main(argv=None) -> int: 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("--skip-existing", action="store_true", + help="leave outputs that already exist alone, so a stopped export resumes instead of " + "rewriting every file") 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)") @@ -601,7 +624,7 @@ def skipped(b, e): if jobs == 1: for i, (b, output_parent) in enumerate(banks): try: - add(export_bank(b, output_parent, a.pre_skip, a.cue_sheet)) + add(export_bank(b, output_parent, a.pre_skip, a.cue_sheet, a.skip_existing)) except (ValueError, struct.error, IndexError, OSError) as e: skipped(b, e) continue @@ -634,3 +657,4 @@ def skipped(b, e): except (AttributeError, ValueError, OSError): pass sys.exit(main()) + From 90cf6be69baf51f2947532e2dcb0daed47a9b7c0 Mon Sep 17 00:00:00 2001 From: fiestorra Date: Sun, 29 Nov 2026 18:05:03 +0100 Subject: [PATCH 2/5] tests: expect --skip-existing on the ogg opus call The assets test asserted the command line without the flag this branch adds, so it failed as soon as the stage started passing it. The flag is the point of the change: a stopped export leaves most of the Ogg files written and no marker, and --skip-existing makes the restart keep the ones already done. Written with an AI assistant. --- tests/test_make_game_argparse.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/test_make_game_argparse.py b/tests/test_make_game_argparse.py index 8a96c6958a..e0d2ac24fc 100644 --- a/tests/test_make_game_argparse.py +++ b/tests/test_make_game_argparse.py @@ -568,7 +568,8 @@ def test_assets_passes_jobs_to_the_ogg_opus_step(self): with patch("make_game.rpf9dump", return_value="fake_dump"), patch("make_game.log"), \ patch("make_game.py") as mock_py: make_game.assets(game, work, wav=False, jobs=3) - mock_py.assert_any_call("awc_opus.py", os.path.join(audio, "awc"), os.path.join(audio, "ogg"), "--jobs", "3") + mock_py.assert_any_call("awc_opus.py", os.path.join(audio, "awc"), os.path.join(audio, "ogg"), "--jobs", "3", + "--skip-existing") def test_assets_without_wav_skips_audio_wav(self): with tempfile.TemporaryDirectory() as tmp: From 8b605a7b71862956cbb43f5acfc160f48084b256 Mon Sep 17 00:00:00 2001 From: fiestorra Date: Sun, 29 Nov 2026 21:54:30 +0100 Subject: [PATCH 3/5] awc_opus: a kept Ogg still contributes its cue-sheet limit merzleckeier found it: the early `continue` on an Ogg that --skip-existing keeps also skipped `frame_limits[cid]`, so a rebuilt cue sheet described only the channels this run wrote. The kept file's own EOS granule is the authority - recomputing the limit from this run's packets would describe a file that was not written - so read it back with ogg_last_granule(). The regression test fails without the change. Written with an AI assistant. --- tests/test_awc_markers.py | 19 +++++++++++++++++++ tools/awc_opus.py | 22 ++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/tests/test_awc_markers.py b/tests/test_awc_markers.py index 36fa00c643..426222741a 100644 --- a/tests/test_awc_markers.py +++ b/tests/test_awc_markers.py @@ -96,6 +96,25 @@ def test_failed_cli_rerun_clears_previous_regions(self): self.assertEqual(result.returncode, 0 if failure == "parse" else 1) self.assertEqual(json.loads(sheet.read_bytes()), {"sample_rate": 48000, "regions": []}) + def test_skip_existing_keeps_the_cue_sheet_complete(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" + src.write_bytes(music_bank(7, 200, 0xFC, cues)) + args = [sys.executable, "-I", Path(TOOL).with_name("awc_opus.py"), src, out, "--cue-sheet", "--jobs", "1"] + subprocess.run(args, check=True, capture_output=True) + written = json.loads(sheet.read_bytes()) + self.assertTrue(written["regions"], "the first run must write a region for the cue it exported") + # The Oggs are kept and only the sheet is missing, so the sheet has to be rebuilt from what is on disk. + # The early `continue` on a kept Ogg used to leave its frame limit unset, and the rebuilt sheet lost it. + sheet.unlink() + subprocess.run(args + ["--skip-existing"], check=True, capture_output=True) + self.assertEqual(json.loads(sheet.read_bytes()), written) + 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 diff --git a/tools/awc_opus.py b/tools/awc_opus.py index 9075d9e6af..2f6881b330 100644 --- a/tools/awc_opus.py +++ b/tools/awc_opus.py @@ -105,6 +105,22 @@ def opus_samples(packet: bytes | memoryview) -> int: OPUS_PRE_SKIP = 312 +def ogg_last_granule(path: str): + """The granule of the last Ogg page in `path`, or None when the file has no complete page header. + + `--skip-existing` keeps an Ogg written by an earlier run, so that file's own EOS granule is the authority for + the cue-sheet limit: recomputing the limit from this run's packets would describe a file that was not written.""" + try: + with open(path, "rb") as f: + data = f.read() + except OSError: + return None + at = data.rfind(b"OggS") + if at < 0 or at + 14 > len(data): + return None + return struct.unpack_from(" int: """length: the stream's declared per-channel sample count at 48 kHz; the EOS page's granule position is @@ -496,8 +512,14 @@ def export_bank(path: str, out_dir: str, pre_skip: int = OPUS_PRE_SKIP, cue_shee # whose streams share an id exports XXXXXXXX.ogg and XXXXXXXX~2.ogg, and only the first would have # been seen under the raw id. target = os.path.join(od, stem + ".ogg") + # Kept from an earlier run: its own EOS granule is the only authority for the cue-sheet + # limit. Recomputing it from this run's packets would describe a file that was not written. if skip_existing and os.path.exists(target): counts["music"] += 1 + if cue_sheet and rate == 48000 and samples > 0: + kept = ogg_last_granule(target) + if kept is not None: + frame_limits[cid] = min(samples, max(0, kept - pre_skip)) continue n48 = samples * 48000 // rate if rate else 0 granule = write_ogg_opus(target, pk, packet_channels, cid, n48, From 89b895f287752555507d8453995644681937e54d Mon Sep 17 00:00:00 2001 From: fiestorra Date: Mon, 30 Nov 2026 15:47:26 +0100 Subject: [PATCH 4/5] tests: end the file with one newline, not two No content change. --- tools/awc_opus.py | 1 - 1 file changed, 1 deletion(-) diff --git a/tools/awc_opus.py b/tools/awc_opus.py index 2f6881b330..812108c8ba 100644 --- a/tools/awc_opus.py +++ b/tools/awc_opus.py @@ -679,4 +679,3 @@ def skipped(b, e): except (AttributeError, ValueError, OSError): pass sys.exit(main()) - From 52ed0b51a8809f26e88783eb3fe56ba08d1ab076 Mon Sep 17 00:00:00 2001 From: fiestorra Date: Mon, 30 Nov 2026 18:58:49 +0100 Subject: [PATCH 5/5] awc_opus: pass skip_existing into the parallel workers merzleckeier measured it on CachyOS: --skip-existing --jobs 1 left 0 of 3 existing outputs alone, --skip-existing --jobs 2 rewrote 3 of 3. The submit call passed export_bank four arguments where the serial call passed five, so the flag never crossed into the pool. The unit test above it calls export_bank directly - the function, not the CLI - which is why the plumbing was not covered; the new test runs the tool as a subprocess for --jobs 1 and 2, freezes an output, and carries its own control (the same command without the flag must rewrite the frozen file). --- tests/test_awc_opus.py | 23 +++++++++++++++++++++++ tools/awc_opus.py | 2 +- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/tests/test_awc_opus.py b/tests/test_awc_opus.py index 848d92f54f..7e8f916915 100644 --- a/tests/test_awc_opus.py +++ b/tests/test_awc_opus.py @@ -421,6 +421,29 @@ def test_skip_existing_leaves_written_files_alone(self): self.assertNotEqual(os.stat(target).st_mtime_ns, 0, "a plain export should have rewritten the file, so the flag is what spares it") + def test_skip_existing_reaches_the_parallel_workers(self): + # The test above calls export_bank() directly, which is the function and not the CLI: the flag also has to + # survive main() and cross into the pool, and it did not - the submit call passed four arguments where the + # serial one passed five, so --jobs 2 rewrote every existing output. This runs the tool as a subprocess, + # like the parallel test below, because the pool cannot pickle a module imported under a test-only name. + path, _, _ = self.make_bank() + for jobs in (1, 2): + with self.subTest(jobs=jobs): + out = Path(self.out) / str(jobs) + awc.export_bank(path, str(out)) + files = sorted(str(p) for p in out.rglob("*") if p.is_file()) + self.assertEqual(len(files), 3, files) + os.utime(files[0], ns=(0, 0)) + subprocess.run([sys.executable, "-I", awc.__file__, path, str(out), "--skip-existing", + "--jobs", str(jobs)], check=True, capture_output=True) + self.assertEqual(os.stat(files[0]).st_mtime_ns, 0, + f"--skip-existing was lost with --jobs {jobs}: an existing file was rewritten") + # Control: the same command without the flag does rewrite the frozen file, so the assertion above is + # about the flag and not about the export being unable to write. + subprocess.run([sys.executable, "-I", awc.__file__, path, str(out), "--jobs", str(jobs)], + check=True, capture_output=True) + self.assertNotEqual(os.stat(files[0]).st_mtime_ns, 0, + f"--jobs {jobs}: the control did not rewrite the file") def test_recursive_cli_preserves_bank_paths(self): src = Path(self.tmp.name) / "banks" samples = {"north/shared": 11, "south/shared": 22, "flat": 33} diff --git a/tools/awc_opus.py b/tools/awc_opus.py index 812108c8ba..9907566f44 100644 --- a/tools/awc_opus.py +++ b/tools/awc_opus.py @@ -654,7 +654,7 @@ def skipped(b, e): 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, a.cue_sheet): b for b, output_parent in banks} + futures = {ex.submit(export_bank, b, output_parent, a.pre_skip, a.cue_sheet, a.skip_existing): b for b, output_parent in banks} for i, fut in enumerate(as_completed(futures), 1): b = futures[fut] try: