Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion make_game.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
19 changes: 19 additions & 0 deletions tests/test_awc_markers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
46 changes: 46 additions & 0 deletions tests/test_awc_opus.py
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,52 @@ 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_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}
Expand Down
3 changes: 2 additions & 1 deletion tests/test_make_game_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
63 changes: 54 additions & 9 deletions tools/awc_opus.py
Original file line number Diff line number Diff line change
Expand Up @@ -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("<q", data, at + 6)[0]


def write_ogg_opus(path: str, packets: list, channels: int, serial: int, length: int = 0,
pre_skip: int = OPUS_PRE_SKIP) -> int:
"""length: the stream's declared per-channel sample count at 48 kHz; the EOS page's granule position is
Expand Down Expand Up @@ -469,10 +485,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, [])
Expand All @@ -491,15 +508,32 @@ 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")
# 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(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))
counts["music"] += 1
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
Expand All @@ -509,17 +543,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
Expand All @@ -538,6 +580,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)")
Expand Down Expand Up @@ -601,15 +646,15 @@ 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
if (i + 1) % 200 == 0:
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:
Expand Down