"""Regression tests for tools/awc_opus.py, built entirely from synthetic AWC data (no game files). python -I tests/test_awc_opus.py """ import contextlib import importlib.util import io import os import struct import subprocess import sys import tempfile import tracemalloc import unittest import wave from pathlib import Path from unittest import mock ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def load_awc_opus(): path = os.path.join(ROOT, "tools", "awc_opus.py") spec = importlib.util.spec_from_file_location("awc_opus_under_test", path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module awc = load_awc_opus() def read_wav(path): """Read the RIFF chunks so the audio can follow either PCM or float metadata.""" with open(path, "rb") as f: data = f.read() if data[:4] != b"RIFF" or data[8:12] != b"WAVE": raise AssertionError("not a RIFF/WAVE file") riff_size, = struct.unpack_from(" len(data): raise AssertionError(f"truncated WAV chunk {name!r}") chunks[name] = data[offset:offset + size] offset += size + (size & 1) fmt, channels, rate, byte_rate, block_align, bits = struct.unpack_from(" 2048: raise AssertionError("synthetic packets do not fit their subblock") bank[start:start + 2048] = payload.ljust(2048, b"\x00") return bytes(bank) def build_music_pcm_bank(blocks=1, count=1, pcm=None): """One streamed-music descriptor (one mono Opus group) plus one PCM16 stream. The music data tag holds exactly one real chunk: a 2048-byte header subblock and one 2048-byte data subblock with a single CELT 20 ms mono packet. The PCM payload follows the music data directly. `blocks` and `count` are what the descriptor and the chunk record declare, so a test can declare more than the data tag holds. """ chunk = 4096 desc = bytearray(12 + 16) struct.pack_into(" WAV"): w = read_wav(os.path.join(od, "00000001.wav")) self.assertEqual(w["format"], 1) self.assertEqual(w["bits"], 16) self.assertEqual(w["rate"], 22050) self.assertEqual(w["channels"], 2) self.assertEqual(w["data_size"], 100 * 2 * 2) # declared samples * channels * 2 bytes self.assertEqual(w["pcm"], pcm16) with self.subTest("float32 stream -> float WAV"): w = read_wav(os.path.join(od, "00000002.wav")) self.assertEqual(struct.unpack(" Ogg Opus"): with open(os.path.join(od, "00000003.ogg"), "rb") as f: data = f.read() pages = parse_ogg_pages(data) self.assertGreaterEqual(len(pages), 3) head = pages[0] self.assertEqual(head["seq"], 0) self.assertEqual(head["flags"] & 0x02, 0x02) # beginning of stream self.assertEqual(head["body"][:8], b"OpusHead") version, channels, preskip, in_rate, gain, mapping = struct.unpack_from(" net_skip=0, keep all packets). x, y, z, w = b"\xfcx", b"\xfcy", b"\xfcz", b"\xfcw" bank = bytearray(build_repeating_music_bank([ [(0, [x, y])], [(1920, [z, w])], ], group_samples=[2 * 3840])) _, music = awc.parse_awc(bank) _, (data_offset, _) = music[0] chunk_size = 2048 * 2 struct.pack_into(" data_offset + 2048): raise AssertionError("metadata scan sliced packet payload bytes") return super().__getitem__(key) data = NoPacketSlices(bank) tracemalloc.start() try: channels = awc.music_channels(data, *music[0], collect_packets=False) _, peak = tracemalloc.get_traced_memory() finally: tracemalloc.stop() self.assertEqual(len(channels), 1) self.assertEqual(channels[0][4:], ([], 2)) self.assertLess(peak, len(packet) * block_count, f"peak {peak:,} retained packet payloads") def test_two_mono_groups_export_two_mono_oggs(self): counts, od = self.export([[0x78, 0x78], [0x78, 0x78]], 960) self.assertEqual(counts, {"opus": 0, "pcm": 0, "other": 0, "music": 2}) for sid in ("00000100", "00000101"): with self.subTest(sid=sid): with open(os.path.join(od, sid + ".ogg"), "rb") as f: pages = parse_ogg_pages(f.read()) channels = pages[0]["body"][9] self.assertEqual(channels, 1) self.assertEqual(pages[-1]["granule"], 312 + 960) def test_two_stereo_groups_export_two_stereo_oggs(self): counts, od = self.export([[0xFC, 0xFC], [0xFC, 0xFC]], 1920) self.assertEqual(counts, {"opus": 0, "pcm": 0, "other": 0, "music": 2}) for sid in ("00000100", "00000101"): with self.subTest(sid=sid): with open(os.path.join(od, sid + ".ogg"), "rb") as f: pages = parse_ogg_pages(f.read()) self.assertEqual(pages[0]["body"][9], 2) self.assertEqual(pages[-1]["granule"], 312 + 960) def test_channel_count_includes_later_blocks(self): for tocs in ((0xF8, 0xFC), (0xFC, 0xF8)): with self.subTest(tocs=tocs): blocks = [[toc] for toc in tocs] declared_frames = 1600 _, od = self.export(blocks, 2 * declared_frames) with open(os.path.join(od, "00000100.ogg"), "rb") as f: pages = parse_ogg_pages(f.read()) self.assertEqual(pages[0]["body"][9], 2) self.assertEqual(pages[-1]["granule"], 312 + declared_frames) self.assertEqual(pages[-1]["body"], bytes(tocs)) bank = build_music_bank(blocks, 2 * declared_frames) _, music = awc.parse_awc(bank) group, = awc.music_channels(bank, *music[0], collect_packets=False) self.assertEqual((group[1], group[4], group[5]), (declared_frames, [], 2)) def test_music_channels_halves_interleaved_samples(self): path = os.path.join(self.tmp.name, "streamed.awc") with open(path, "wb") as f: f.write(build_music_bank([[0xFC]], 1920)) with open(path, "rb") as f: d = f.read() _, music = awc.parse_awc(d) info = awc.music_channels(d, music[0][0], music[0][1]) self.assertEqual((info[0][1], info[0][5]), (960, 2)) def test_music_channels_metadata_only_still_reports_packet_channels(self): path = os.path.join(self.tmp.name, "streamed.awc") with open(path, "wb") as f: f.write(build_music_bank([[0xFC]], 1920)) with open(path, "rb") as f: d = f.read() _, music = awc.parse_awc(d) info = awc.music_channels(d, music[0][0], music[0][1], collect_packets=False) self.assertEqual((info[0][1], info[0][4], info[0][5]), (960, [], 2)) class MalformedMusicGeometryTest(unittest.TestCase): """A music descriptor that declares more blocks or subblocks than its data tag holds is rejected, instead of reading past the tag into a sibling stream or past the end of the bank.""" def setUp(self): self.tmp = tempfile.TemporaryDirectory() self.addCleanup(self.tmp.cleanup) self.out = os.path.join(self.tmp.name, "out") def write_bank(self, **kw): path = os.path.join(self.tmp.name, "streamed.awc") with open(path, "wb") as f: f.write(build_music_pcm_bank(**kw)) return path def test_blocks_beyond_data_tag_keep_sibling_streams(self): # Before the fix: struct.error out of music_channels, so main() skipped the whole # bank and the valid PCM16 stream was never exported. path = self.write_bank(blocks=3) with open(path, "rb") as f: d = f.read() _, music = awc.parse_awc(d) self.assertEqual(awc.music_channels(d, *music[0]), []) self.assertEqual(awc.music_channels(d, *music[0], collect_packets=False), []) counts = awc.export_bank(path, self.out) self.assertEqual(counts, {"opus": 0, "pcm": 1, "other": 0, "music": 0}) od = os.path.join(self.out, "streamed") self.assertTrue(os.path.isfile(os.path.join(od, "00000021.wav"))) self.assertFalse(os.path.exists(os.path.join(od, "00000100.ogg"))) def test_short_descriptor_at_bank_end_keeps_sibling_streams(self): bank = bytearray(build_music_pcm_bank()) struct.pack_into("