diff options
| author | Solthodox <100046219+Solthodox@users.noreply.github.com> | 2026-11-23 16:45:58 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-11-23 09:45:58 -0600 |
| commit | 8a8c9e9cfdd00a13c1ee67976e7db76c08ef9327 (patch) | |
| tree | 4749cee0d7319aa9460f42bdfeef83d42ba4aec2 | |
| parent | e6190e7b5fed75ee38caedd8b494aa3a4405b3fb (diff) | |
audio_wav: bound the queue of pending WAV conversions (#6882)
Squash-merged after diff review of PR #6882 - audio_wav: bound the queue of pending WAV conversions
| -rw-r--r-- | tests/test_audio_wav.py | 36 | ||||
| -rw-r--r-- | tools/audio_wav.py | 52 |
2 files changed, 74 insertions, 14 deletions
diff --git a/tests/test_audio_wav.py b/tests/test_audio_wav.py index 6535ac998..81b38208a 100644 --- a/tests/test_audio_wav.py +++ b/tests/test_audio_wav.py | |||
| @@ -29,6 +29,42 @@ import awc_opus # noqa: E402 | |||
| 29 | import winbatch # noqa: E402 | 29 | import winbatch # noqa: E402 |
| 30 | 30 | ||
| 31 | 31 | ||
| 32 | class DecodeQueueTest(unittest.TestCase): | ||
| 33 | def test_failure_summary_counts_all_but_prints_only_ten_first_lines(self): | ||
| 34 | items = [(str(i), str(i)) for i in range(13)] | ||
| 35 | with tempfile.TemporaryDirectory() as root, \ | ||
| 36 | mock.patch.object(audio_wav, "collect", return_value=(items, 0)), \ | ||
| 37 | mock.patch.object(audio_wav, "plan_outputs", return_value=(items, 0, 0)), \ | ||
| 38 | mock.patch.object(audio_wav, "find_ffmpeg", return_value="unused"), \ | ||
| 39 | mock.patch.object(audio_wav, "decode", return_value=(False, "\n first line\nextra detail")), \ | ||
| 40 | contextlib.redirect_stdout(io.StringIO()) as out: | ||
| 41 | status = audio_wav.main([root, "--jobs", "2"]) | ||
| 42 | self.assertEqual(status, 1) | ||
| 43 | self.assertIn("13 failed", out.getvalue()) | ||
| 44 | self.assertEqual(out.getvalue().count(": first line"), 10) | ||
| 45 | self.assertNotIn("extra detail", out.getvalue()) | ||
| 46 | self.assertIn("and 3 more failures", out.getvalue()) | ||
| 47 | |||
| 48 | def test_submission_stays_within_worker_window(self): | ||
| 49 | workers, consumed = 2, 0 | ||
| 50 | expected = {str(i) for i in range(1000)} | ||
| 51 | received = set() | ||
| 52 | |||
| 53 | def jobs(): | ||
| 54 | for submitted, name in enumerate(sorted(expected), 1): | ||
| 55 | self.assertLessEqual(submitted - consumed, workers) | ||
| 56 | yield name, name, name + ".wav" | ||
| 57 | |||
| 58 | with audio_wav.concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool, \ | ||
| 59 | mock.patch.object(audio_wav, "decode", new=lambda _, src, dst: (src, dst)): | ||
| 60 | for rel, future in audio_wav._decode_jobs(pool, "unused", jobs(), workers): | ||
| 61 | self.assertEqual(future.result(), (rel, rel + ".wav")) | ||
| 62 | consumed += 1 | ||
| 63 | received.add(rel) | ||
| 64 | self.assertEqual(received, expected) | ||
| 65 | self.assertEqual(consumed, len(expected)) | ||
| 66 | |||
| 67 | |||
| 32 | @unittest.skipUnless(FFMPEG, "ffmpeg is not on PATH") | 68 | @unittest.skipUnless(FFMPEG, "ffmpeg is not on PATH") |
| 33 | class AudioWavTest(unittest.TestCase): | 69 | class AudioWavTest(unittest.TestCase): |
| 34 | def setUp(self): | 70 | def setUp(self): |
diff --git a/tools/audio_wav.py b/tools/audio_wav.py index 2ea604914..345add377 100644 --- a/tools/audio_wav.py +++ b/tools/audio_wav.py | |||
| @@ -14,6 +14,7 @@ The output is pcm_s16le at the stream's own sample rate and channel count (Opus | |||
| 14 | stream is trimmed to its Ogg Opus end granule minus pre-skip, because ffmpeg can keep samples beyond its declared | 14 | stream is trimmed to its Ogg Opus end granule minus pre-skip, because ffmpeg can keep samples beyond its declared |
| 15 | end. For chained streams, ffmpeg handles each link's timing. ffmpeg must be on PATH or given with | 15 | end. For chained streams, ffmpeg handles each link's timing. ffmpeg must be on PATH or given with |
| 16 | --ffmpeg; without it the tool exits with an explanation instead of a traceback. | 16 | --ffmpeg; without it the tool exits with an explanation instead of a traceback. |
| 17 | The decode queue holds at most one outstanding job per worker, even for a large input tree. | ||
| 17 | 18 | ||
| 18 | For PCM copies of the AWC banks' Opus streams, first repackage the banks with awc_opus.py, then run this tool on | 19 | For PCM copies of the AWC banks' Opus streams, first repackage the banks with awc_opus.py, then run this tool on |
| 19 | its output (make_game.py does both, the second only with --wav). | 20 | its output (make_game.py does both, the second only with --wav). |
| @@ -434,6 +435,24 @@ def decode(ffmpeg: str, src: str, dst: str): | |||
| 434 | return False, str(e) | 435 | return False, str(e) |
| 435 | 436 | ||
| 436 | 437 | ||
| 438 | def _decode_jobs(pool, ffmpeg, todo, workers): | ||
| 439 | """Yield (relative name, completed future) without retaining a future for every input.""" | ||
| 440 | jobs = iter(todo) | ||
| 441 | pending = {} | ||
| 442 | while True: | ||
| 443 | while len(pending) < workers: | ||
| 444 | job = next(jobs, None) | ||
| 445 | if job is None: | ||
| 446 | break | ||
| 447 | path, rel, dst = job | ||
| 448 | pending[pool.submit(decode, ffmpeg, path, dst)] = rel | ||
| 449 | if not pending: | ||
| 450 | return | ||
| 451 | ready, _ = concurrent.futures.wait(pending, return_when=concurrent.futures.FIRST_COMPLETED) | ||
| 452 | for future in ready: | ||
| 453 | yield pending.pop(future), future | ||
| 454 | |||
| 455 | |||
| 437 | def main(argv=None) -> int: | 456 | def main(argv=None) -> int: |
| 438 | ap = argparse.ArgumentParser(description="Decode Ogg Opus audio to 16-bit PCM WAV with ffmpeg.") | 457 | ap = argparse.ArgumentParser(description="Decode Ogg Opus audio to 16-bit PCM WAV with ffmpeg.") |
| 439 | ap.add_argument("src", help="a directory to search recursively, or one .ogg/.opus file") | 458 | ap.add_argument("src", help="a directory to search recursively, or one .ogg/.opus file") |
| @@ -495,13 +514,22 @@ def main(argv=None) -> int: | |||
| 495 | t0 = time.time() | 514 | t0 = time.time() |
| 496 | written = skipped = 0 | 515 | written = skipped = 0 |
| 497 | todo = [] | 516 | todo = [] |
| 498 | failures: list[tuple[str, str]] = [] | 517 | failed = 0 |
| 518 | failure_samples: list[tuple[str, str]] = [] | ||
| 519 | |||
| 520 | def record_failure(rel: str, message: str) -> None: | ||
| 521 | nonlocal failed | ||
| 522 | failed += 1 | ||
| 523 | if len(failure_samples) < 10: | ||
| 524 | first = next((line.strip() for line in message.splitlines() if line.strip()), "unknown error") | ||
| 525 | failure_samples.append((rel, first)) | ||
| 526 | |||
| 499 | for path, rel in items: | 527 | for path, rel in items: |
| 500 | dst = os.path.join(out, rel + ".wav") | 528 | dst = os.path.join(out, rel + ".wav") |
| 501 | if os.path.isfile(dst): | 529 | if os.path.isfile(dst): |
| 502 | skipped += 1 | 530 | skipped += 1 |
| 503 | elif os.path.exists(dst): | 531 | elif os.path.exists(dst): |
| 504 | failures.append((rel, f"output path is not a file: {dst}")) | 532 | record_failure(rel, f"output path is not a file: {dst}") |
| 505 | else: | 533 | else: |
| 506 | todo.append((path, rel, dst)) | 534 | todo.append((path, rel, dst)) |
| 507 | 535 | ||
| @@ -510,10 +538,7 @@ def main(argv=None) -> int: | |||
| 510 | if todo: | 538 | if todo: |
| 511 | print(f"Decoding {len(todo)} file(s) with {workers} job(s)...") | 539 | print(f"Decoding {len(todo)} file(s) with {workers} job(s)...") |
| 512 | with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool: | 540 | with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool: |
| 513 | futures = {pool.submit(decode, ffmpeg, path, dst): (path, rel) | 541 | for rel, future in _decode_jobs(pool, ffmpeg, todo, workers): |
| 514 | for path, rel, dst in todo} | ||
| 515 | for future in concurrent.futures.as_completed(futures): | ||
| 516 | path, rel = futures[future] | ||
| 517 | try: | 542 | try: |
| 518 | ok, message = future.result() | 543 | ok, message = future.result() |
| 519 | except Exception as e: # never lose the summary to an unexpected worker error | 544 | except Exception as e: # never lose the summary to an unexpected worker error |
| @@ -522,23 +547,22 @@ def main(argv=None) -> int: | |||
| 522 | if ok: | 547 | if ok: |
| 523 | written += 1 | 548 | written += 1 |
| 524 | else: | 549 | else: |
| 525 | failures.append((rel, message)) | 550 | record_failure(rel, message) |
| 526 | if done % 200 == 0: | 551 | if done % 200 == 0: |
| 527 | print(f" {done}/{len(todo)} decoded", flush=True) | 552 | print(f" {done}/{len(todo)} decoded", flush=True) |
| 528 | 553 | ||
| 529 | seconds = time.time() - t0 | 554 | seconds = time.time() - t0 |
| 530 | summary = f"{len(items)} Ogg Opus file(s): {written} WAV written, {skipped} already present" | 555 | summary = f"{len(items)} Ogg Opus file(s): {written} WAV written, {skipped} already present" |
| 531 | if failures: | 556 | if failed: |
| 532 | summary += f", {len(failures)} failed" | 557 | summary += f", {failed} failed" |
| 533 | print(summary + f" ({seconds:.1f}s)") | 558 | print(summary + f" ({seconds:.1f}s)") |
| 534 | if not_opus: | 559 | if not_opus: |
| 535 | print(f" {not_opus} .ogg/.opus file(s) skipped: not Ogg Opus") | 560 | print(f" {not_opus} .ogg/.opus file(s) skipped: not Ogg Opus") |
| 536 | for rel, message in failures[:10]: | 561 | for rel, first in failure_samples: |
| 537 | first = next((line.strip() for line in message.splitlines() if line.strip()), "unknown error") | ||
| 538 | print(f" FAILED {rel}: {first}") | 562 | print(f" FAILED {rel}: {first}") |
| 539 | if len(failures) > 10: | 563 | if failed > len(failure_samples): |
| 540 | print(f" ... and {len(failures) - 10} more failures") | 564 | print(f" ... and {failed - len(failure_samples)} more failures") |
| 541 | return 1 if failures else 0 | 565 | return 1 if failed else 0 |
| 542 | 566 | ||
| 543 | 567 | ||
| 544 | if __name__ == "__main__": | 568 | if __name__ == "__main__": |