Handle AWC hdr24 block_samples/skip overlap and add GAME.DAT/SOUNDS.DAT metadata parser #1

Closed
github-bot wants to merge 5 commits from gh-pr/1/head into gh-pr/1/base
Owner

@⁠Elijah-J on GitHub · 2026-11-24 17:48 UTC · original
Elijah-J:feat/awc-block-skip-and-audmetadata → main · +1010 −63 · 4 files · 5 commits · closed without merging

Summary

  1. Streamed AWC (0x48 / 0x55) block budget & skip handling (awc_core.py, docs/FORMAT.md):

    • Reads (ents, skip_samples, block_samples) from each channel's 24-byte block header (+0x04..+0x10).
    • Keeps the packet that reaches or crosses block_samples / opus_channels and discards later packets in the block. The existing Ogg writer can retain final-frame padding.
    • Checks for an exact leading packet overlap or a whole-packet carry-over skip when the previous block fell short. The scanner and reader also locate tags after the optional header tables, including 2-byte-aligned tag tables. Invalid skips leave existing exports intact.
  2. Deterministic GAME.DAT / SOUNDS.DAT (audMetadataFile 0x045A88EA) parser (awc_metadata.py, docs/FORMAT.md):

    • Pure stdlib module with zero hardcoded archive offsets and zero game data/names.
    • Reads complete audMetadataFile blobs, including stored chunks a zlib-only carve can miss, locates GAME.DAT via joaat("RADIO_STATIONS_01"), enumerates RADIO_STATIONS_01..16 (0x0E) -> RadioStationSettings (0x10, including static world-emitter (flags & 0x30) == 0x10 and hidden wheel (flags & 0x0C) == 0x04 bits) -> RadioStationTrackList (0x11, external ObjectList 0x02 or inline refs) -> RadioTrackSettings (0x0F), and resolves SOUNDS.DAT StreamingSound (0x08) -> SimpleSound (0x0C) (bank_hash, wave_hash & 0x1FFFFFFF) for complete adjacent child groups, including checked multi-stem club/venue mixes. Also enumerates unattached tracklists.
  3. Synthetic tests (tests/test_awc_metadata_and_blocks.py):

    • PYTHONPATH=. python3 -W error -m unittest discover -s tests -v — 10/10 OK (zero warnings, synthetic fixtures only, no game files).
    • python3 -m compileall -q awc_core.py awc_metadata.py tests/test_awc_metadata_and_blocks.py — exit 0.

Opened as a Draft PR for review before marking ready.

**@⁠Elijah-J** on GitHub · 2026-11-24 17:48 UTC · [original](https://github.com/Albotterin/AWC_from_RPF9_Extractor/pull/1) `Elijah-J:feat/awc-block-skip-and-audmetadata` → `main` · +1010 −63 · 4 files · 5 commits · closed without merging ### Summary 1. **Streamed AWC (`0x48` / `0x55`) block budget & skip handling (`awc_core.py`, `docs/FORMAT.md`):** - Reads `(ents, skip_samples, block_samples)` from each channel's 24-byte block header (`+0x04..+0x10`). - Keeps the packet that reaches or crosses `block_samples / opus_channels` and discards later packets in the block. The existing Ogg writer can retain final-frame padding. - Checks for an exact leading packet overlap or a whole-packet carry-over skip when the previous block fell short. The scanner and reader also locate tags after the optional header tables, including 2-byte-aligned tag tables. Invalid skips leave existing exports intact. 2. **Deterministic `GAME.DAT` / `SOUNDS.DAT` (`audMetadataFile` `0x045A88EA`) parser (`awc_metadata.py`, `docs/FORMAT.md`):** - Pure stdlib module with zero hardcoded archive offsets and zero game data/names. - Reads complete `audMetadataFile` blobs, including stored chunks a zlib-only carve can miss, locates `GAME.DAT` via `joaat("RADIO_STATIONS_01")`, enumerates `RADIO_STATIONS_01..16` (`0x0E`) -> `RadioStationSettings` (`0x10`, including static world-emitter `(flags & 0x30) == 0x10` and hidden wheel `(flags & 0x0C) == 0x04` bits) -> `RadioStationTrackList` (`0x11`, external `ObjectList` `0x02` or inline refs) -> `RadioTrackSettings` (`0x0F`), and resolves `SOUNDS.DAT` `StreamingSound` (`0x08`) -> `SimpleSound` (`0x0C`) `(bank_hash, wave_hash & 0x1FFFFFFF)` for complete adjacent child groups, including checked multi-stem club/venue mixes. Also enumerates unattached tracklists. 3. **Synthetic tests (`tests/test_awc_metadata_and_blocks.py`):** - `PYTHONPATH=. python3 -W error -m unittest discover -s tests -v` — 10/10 OK (zero warnings, synthetic fixtures only, no game files). - `python3 -m compileall -q awc_core.py awc_metadata.py tests/test_awc_metadata_and_blocks.py` — exit 0. Opened as a Draft PR for review before marking ready.
Read tags after the optional tables and refresh stale scan caches. Require exact skip boundaries, preserve existing exports on rejection, and omit incomplete metadata links.

Co-authored-by: OpenAI Codex <[email protected]>
Infer each stream's Opus channel count from its first available packet
and rebuild stale scan caches. Use the immediately preceding block for
overlap and deficit calculations, including when it contains no packets.

Keep GAME.DAT reference arrays inside their objects while preserving
external tracklists. Cover the regressions with synthetic fixtures.

Co-Authored-By: OpenAI Codex <[email protected]>
Use one packet feed for standalone exports and joined talk-show parts.
Keep skip and shortfall history local to each AWC and stage joined output
before replacing the destination. Retain both metadata readers and their
format notes.

Co-Authored-By: OpenAI Codex <[email protected]>
Move the standalone metadata reader and tests alongside the shared
extractor code. Keep upstream's station notes and their cross-links
with the standalone parser format notes in the extractor directory.

Co-Authored-By: OpenAI Codex <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 19:02:18 +00:00
github-bot closed this pull request 2026-11-26 19:02:18 +00:00
Author
Owner

@⁠Copilot on GitHub · 2026-11-24 18:30 UTC · original
On awc_core.py line 337 (outdated):

@@ -285,36 +312,94 @@ def extract(self, jobs, progress=None, cancel=None, tags=None):
                     blk = f.read(min(self.block_size, self.data_off + self.data_size - off))
                     if len(blk) < 0x18 * nch:
                         break
-                    ents = [struct.unpack_from("<i", blk, 0x18 * c + 4)[0] for c in range(nch)]
+                    recs = [struct.unpack_from("<iII", blk, 0x18 * c + 4) for c in range(nch)]
+                    ents = [r[0] for r in recs]
                     if any(e < 0 or e > 4096 for e in ents):
                         break  # corrupt block (e.g. truncated file)
                     pos = ((0x18 * nch + 4 * sum(ents)) + 0x7FF) & ~0x7FF
                     for c in range(nch):
                         if c in writers:
                             w = writers[c]
+                            _, skip_samples, block_samples = recs[c]
+                            pkts = []
                             for e in range(ents[c]):
                                 ent = blk[pos + e * 0x800: pos + (e + 1) * 0x800]
                                 p = 0
                                 while p + 2 <= len(ent):
                                     n = struct.unpack_from("<H", ent, p)[0]
                                     if n == 0 or p + 2 + n > len(ent):
                                         break
-                                    w.add(ent[p + 2:p + 2 + n])
+                                    pkts.append(ent[p + 2:p + 2 + n])
                                     p += 2 + n
+                            if skip_samples and not pkts:
+                                raise AwcError(f"Channel {c}: skip without packets")
+                            if pkts:
+                                pch = max(1, self.streams[c].opus_channels)

_estimate() only probes the first block, so a mono stream with an empty initial block retains the default channel count of 2 here. A later block with two 960-frame mono packets and a 1920-sample budget then loses its second packet. Infer the channel count from the first available packet before converting budgets and skips, as the Ogg writer does.

**@⁠Copilot** on GitHub · 2026-11-24 18:30 UTC · [original](https://github.com/Albotterin/AWC_from_RPF9_Extractor/pull/1#discussion_r4684694845) On `awc_core.py` line 337 (outdated): ```diff @@ -285,36 +312,94 @@ def extract(self, jobs, progress=None, cancel=None, tags=None): blk = f.read(min(self.block_size, self.data_off + self.data_size - off)) if len(blk) < 0x18 * nch: break - ents = [struct.unpack_from("<i", blk, 0x18 * c + 4)[0] for c in range(nch)] + recs = [struct.unpack_from("<iII", blk, 0x18 * c + 4) for c in range(nch)] + ents = [r[0] for r in recs] if any(e < 0 or e > 4096 for e in ents): break # corrupt block (e.g. truncated file) pos = ((0x18 * nch + 4 * sum(ents)) + 0x7FF) & ~0x7FF for c in range(nch): if c in writers: w = writers[c] + _, skip_samples, block_samples = recs[c] + pkts = [] for e in range(ents[c]): ent = blk[pos + e * 0x800: pos + (e + 1) * 0x800] p = 0 while p + 2 <= len(ent): n = struct.unpack_from("<H", ent, p)[0] if n == 0 or p + 2 + n > len(ent): break - w.add(ent[p + 2:p + 2 + n]) + pkts.append(ent[p + 2:p + 2 + n]) p += 2 + n + if skip_samples and not pkts: + raise AwcError(f"Channel {c}: skip without packets") + if pkts: + pch = max(1, self.streams[c].opus_channels) ``` `_estimate()` only probes the first block, so a mono stream with an empty initial block retains the default channel count of 2 here. A later block with two 960-frame mono packets and a 1920-sample budget then loses its second packet. Infer the channel count from the first available packet before converting budgets and skips, as the Ogg writer does.
Author
Owner

@⁠copilot-pull-request-reviewer[bot] on GitHub · 2026-11-24 18:30 UTC · original · reviewed

Unresolved issues allow stale state to affect skip reconciliation, incorrect channel inference to drop mono packets, and metadata arrays to consume adjacent objects’ bytes.

3 open issues
What changed in this PR

This PR improves streamed AWC extraction and adds a standalone parser for radio metadata in GAME.DAT and SOUNDS.DAT.

Changes:

  • Adds block-budget trimming, skip reconciliation, staged exports, and optional-header-table parsing; bumps the scan cache version.
  • Resolves metadata into stations, static emitters, unattached tracklists, and audio stream links.
  • Documents the supported layouts and adds synthetic regression tests.
File Description
tests/​test_awc_metadata_and_blocks.py Adds synthetic coverage for block handling, indexed headers, caching, and metadata parsing.
docs/​FORMAT.md Documents header tables, block budgets and skips, and audio metadata layouts.
awc_metadata.py Adds metadata parsing and station-to-stream resolution.
awc_core.py Updates header parsing, packet assembly, export staging, and cache invalidation.

Review effort: Balanced

**@⁠copilot-pull-request-reviewer[bot]** on GitHub · 2026-11-24 18:30 UTC · [original](https://github.com/Albotterin/AWC_from_RPF9_Extractor/pull/1#pullrequestreview-6045074564) · **reviewed** <!-- ccr-overview-v2 --> ### 🟡 Changes recommended Unresolved issues allow stale state to affect skip reconciliation, incorrect channel inference to drop mono packets, and metadata arrays to consume adjacent objects’ bytes. <details open> <summary><strong>3 open issues</strong></summary> - <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [Infer channel count from the first available packet](https://git.gtahub.st/github/Albotterin--AWC_from_RPF9_Extractor/pulls/1) · New - <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [Update skip reconciliation state for empty blocks](https://git.gtahub.st/github/Albotterin--AWC_from_RPF9_Extractor/pulls/1) · New - <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [Bound reference arrays to their containing object](https://git.gtahub.st/github/Albotterin--AWC_from_RPF9_Extractor/pulls/1) · New </details> <details> <summary><strong>What changed in this PR</strong></summary> This PR improves streamed AWC extraction and adds a standalone parser for radio metadata in `GAME.DAT` and `SOUNDS.DAT`. **Changes:** - Adds block-budget trimming, skip reconciliation, staged exports, and optional-header-table parsing; bumps the scan cache version. - Resolves metadata into stations, static emitters, unattached tracklists, and audio stream links. - Documents the supported layouts and adds synthetic regression tests. | File | Description | | ---- | ----------- | | `tests/​test_awc_metadata_and_blocks.py` | Adds synthetic coverage for block handling, indexed headers, caching, and metadata parsing. | | `docs/​FORMAT.md` | Documents header tables, block budgets and skips, and audio metadata layouts. | | `awc_metadata.py` | Adds metadata parsing and station-to-stream resolution. | | `awc_core.py` | Updates header parsing, packet assembly, export staging, and cache invalidation. | </details> <sub>Review effort: Balanced</sub>
Author
Owner

@⁠Copilot on GitHub · 2026-11-24 18:30 UTC · original
On awc_core.py line 394 (outdated):

@@ -285,36 +312,94 @@ def extract(self, jobs, progress=None, cancel=None, tags=None):
                     blk = f.read(min(self.block_size, self.data_off + self.data_size - off))
                     if len(blk) < 0x18 * nch:
                         break
-                    ents = [struct.unpack_from("<i", blk, 0x18 * c + 4)[0] for c in range(nch)]
+                    recs = [struct.unpack_from("<iII", blk, 0x18 * c + 4) for c in range(nch)]
+                    ents = [r[0] for r in recs]
                     if any(e < 0 or e > 4096 for e in ents):
                         break  # corrupt block (e.g. truncated file)
                     pos = ((0x18 * nch + 4 * sum(ents)) + 0x7FF) & ~0x7FF
                     for c in range(nch):
                         if c in writers:
                             w = writers[c]
+                            _, skip_samples, block_samples = recs[c]
+                            pkts = []
                             for e in range(ents[c]):
                                 ent = blk[pos + e * 0x800: pos + (e + 1) * 0x800]
                                 p = 0
                                 while p + 2 <= len(ent):
                                     n = struct.unpack_from("<H", ent, p)[0]
                                     if n == 0 or p + 2 + n > len(ent):
                                         break
-                                    w.add(ent[p + 2:p + 2 + n])
+                                    pkts.append(ent[p + 2:p + 2 + n])
                                     p += 2 + n
+                            if skip_samples and not pkts:
+                                raise AwcError(f"Channel {c}: skip without packets")
+                            if pkts:
+                                pch = max(1, self.streams[c].opus_channels)
+                                kept = pkts
+                                deficit = 0
+                                if block_samples > 0:
+                                    if block_samples % pch:
+                                        raise AwcError(f"Channel {c}: invalid interleaved block sample count")
+                                    target_f = block_samples // pch
+                                    tot_f = sum(opus_packet_samples(pkt) for pkt in pkts)
+                                    if tot_f > target_f:
+                                        acc = 0
+                                        trim = len(pkts)
+                                        for idx, pkt in enumerate(pkts):
+                                            acc += opus_packet_samples(pkt)
+                                            if acc >= target_f:
+                                                trim = idx + 1
+                                                break
+                                        kept = pkts[:trim]
+                                    else:
+                                        deficit = target_f - tot_f
+                                drop = 0
+                                if skip_samples > 0:
+                                    skip_f = skip_samples // pch
+                                    matched = False
+                                    candidates = ((skip_f, skip_samples)
+                                                  if pch > 1 and skip_samples % pch == 0 else (skip_samples,))
+                                    for cand in candidates:
+                                        if cand <= 0:
+                                            continue
+                                        acc = 0
+                                        for idx, pkt in enumerate(kept, 1):
+                                            acc += opus_packet_samples(pkt)
+                                            if acc == cand and kept[:idx] == prev_kept[c][-idx:]:
+                                                drop = idx
+                                                matched = True
+                                                break
+                                            if acc >= cand:
+                                                break
+                                        if matched:
+                                            break
+                                    if not matched:
+                                        if not prev_deficit[c] or skip_samples % pch or skip_f < prev_deficit[c]:
+                                            raise AwcError(f"Channel {c}: unverified skip of {skip_samples} samples")
+                                        net_skip = skip_f - prev_deficit[c]
+                                        if net_skip > 0:
+                                            acc = 0
+                                            for idx, pkt in enumerate(kept, 1):
+                                                acc += opus_packet_samples(pkt)
+                                                if acc == net_skip:
+                                                    drop = idx
+                                                    break
+                                                if acc > net_skip:
+                                                    break
+                                            if not drop:
+                                                raise AwcError(f"Channel {c}: skip cuts through or exceeds the block")
+                                for pkt in (kept[drop:] if drop else kept):
+                                    w.add(pkt)
+                                prev_kept[c] = kept
+                                prev_deficit[c] = deficit

An empty block leaves both previous-block state values unchanged, so a later skip can be accepted using an older block's deficit or overlap history. An empty block with a positive budget also fails to record its own shortfall. Update overlap history and deficit for every block, including empty ones, so skip reconciliation uses the immediately preceding block.

**@⁠Copilot** on GitHub · 2026-11-24 18:30 UTC · [original](https://github.com/Albotterin/AWC_from_RPF9_Extractor/pull/1#discussion_r4684694923) On `awc_core.py` line 394 (outdated): ```diff @@ -285,36 +312,94 @@ def extract(self, jobs, progress=None, cancel=None, tags=None): blk = f.read(min(self.block_size, self.data_off + self.data_size - off)) if len(blk) < 0x18 * nch: break - ents = [struct.unpack_from("<i", blk, 0x18 * c + 4)[0] for c in range(nch)] + recs = [struct.unpack_from("<iII", blk, 0x18 * c + 4) for c in range(nch)] + ents = [r[0] for r in recs] if any(e < 0 or e > 4096 for e in ents): break # corrupt block (e.g. truncated file) pos = ((0x18 * nch + 4 * sum(ents)) + 0x7FF) & ~0x7FF for c in range(nch): if c in writers: w = writers[c] + _, skip_samples, block_samples = recs[c] + pkts = [] for e in range(ents[c]): ent = blk[pos + e * 0x800: pos + (e + 1) * 0x800] p = 0 while p + 2 <= len(ent): n = struct.unpack_from("<H", ent, p)[0] if n == 0 or p + 2 + n > len(ent): break - w.add(ent[p + 2:p + 2 + n]) + pkts.append(ent[p + 2:p + 2 + n]) p += 2 + n + if skip_samples and not pkts: + raise AwcError(f"Channel {c}: skip without packets") + if pkts: + pch = max(1, self.streams[c].opus_channels) + kept = pkts + deficit = 0 + if block_samples > 0: + if block_samples % pch: + raise AwcError(f"Channel {c}: invalid interleaved block sample count") + target_f = block_samples // pch + tot_f = sum(opus_packet_samples(pkt) for pkt in pkts) + if tot_f > target_f: + acc = 0 + trim = len(pkts) + for idx, pkt in enumerate(pkts): + acc += opus_packet_samples(pkt) + if acc >= target_f: + trim = idx + 1 + break + kept = pkts[:trim] + else: + deficit = target_f - tot_f + drop = 0 + if skip_samples > 0: + skip_f = skip_samples // pch + matched = False + candidates = ((skip_f, skip_samples) + if pch > 1 and skip_samples % pch == 0 else (skip_samples,)) + for cand in candidates: + if cand <= 0: + continue + acc = 0 + for idx, pkt in enumerate(kept, 1): + acc += opus_packet_samples(pkt) + if acc == cand and kept[:idx] == prev_kept[c][-idx:]: + drop = idx + matched = True + break + if acc >= cand: + break + if matched: + break + if not matched: + if not prev_deficit[c] or skip_samples % pch or skip_f < prev_deficit[c]: + raise AwcError(f"Channel {c}: unverified skip of {skip_samples} samples") + net_skip = skip_f - prev_deficit[c] + if net_skip > 0: + acc = 0 + for idx, pkt in enumerate(kept, 1): + acc += opus_packet_samples(pkt) + if acc == net_skip: + drop = idx + break + if acc > net_skip: + break + if not drop: + raise AwcError(f"Channel {c}: skip cuts through or exceeds the block") + for pkt in (kept[drop:] if drop else kept): + w.add(pkt) + prev_kept[c] = kept + prev_deficit[c] = deficit ``` An empty block leaves both previous-block state values unchanged, so a later skip can be accepted using an older block's deficit or overlap history. An empty block with a positive budget also fails to record its own shortfall. Update overlap history and deficit for every block, including empty ones, so skip reconciliation uses the immediately preceding block.
Author
Owner

@⁠Copilot on GitHub · 2026-11-24 18:30 UTC · original
On awc_metadata.py line 182 (outdated):

@@ -0,0 +1,322 @@
+"""Deterministic parser for RAGE 9 GAME.DAT and SOUNDS.DAT audMetadataFile (0x045A88EA) containers.
+
+The file groups at the start of audio.rpf (before the first ADAT bank) hold
+self-describing audMetadataFile tables. Pass complete containers, including any
+uncompressed chunks left out by a zlib-only carve:
+  - GAME.DAT (identified by RADIO_STATIONS_01, type 0x0E): wheel radio stations, static world
+    emitters ((flags & 0x30) == 0x10), hidden wheel stations ((flags & 0x0C) == 0x04),
+    RadioStationTrackList (0x11) with external ObjectList (0x02) or inline refs, and
+    RadioTrackSettings (0x0F) pointing to SOUNDS.DAT sound hashes.
+  - SOUNDS.DAT: StreamingSound (0x08) duration and adjacent SimpleSound (0x0C) channel groups
+    holding (bank_hash, wave_hash) -> 29-bit AWC stream IDs.
+
+Pure Python standard library; ships no game data, keys, or station/song lists.
+"""
+from collections import defaultdict
+import struct
+
+from awc_names import STREAM_ID_MASK, joaat
+
+AUD_METADATA_MAGIC = 0x045A88EA
+AUD_METADATA_CHUNK_SIZE = 65536
+OBJECT_REF_NONE = 0xFFFFFFFF
+
+TYPE_OBJECT_LIST = 0x02
+TYPE_STREAMING_SOUND = 0x08
+TYPE_SIMPLE_SOUND = 0x0C
+TYPE_RADIO_STATION_LIST = 0x0E
+TYPE_RADIO_TRACK = 0x0F
+TYPE_RADIO_STATION = 0x10
+TYPE_RADIO_TRACKLIST = 0x11
+
+RADIO_STATIONS_LIST_PREFIX = "RADIO_STATIONS_"
+RADIO_STATIONS_MAX_LISTS = 16
+WHEEL_STATION_STATIC_MASK = 0x30
+WHEEL_STATION_STATIC_VALUE = 0x10
+WHEEL_STATION_HIDDEN_MASK = 0x0C
+WHEEL_STATION_HIDDEN_VALUE = 0x04
+
+
+def group_inflated_streams(streams, chunk_size=AUD_METADATA_CHUNK_SIZE):
+    """Group consecutive chunks, ending on any chunk whose size != chunk_size.
+
+    Callers must supply both inflated and stored chunks in archive order.
+    """
+    groups = []
+    current = []
+    for blob in streams:
+        current.append(blob)
+        if len(blob) != chunk_size:
+            groups.append(b"".join(current))
+            current = []
+    if current:
+        groups.append(b"".join(current))
+    return groups
+
+
+def parse_aud_metadata(blob):
+    """Parse one contiguous audMetadataFile (0x045A88EA) payload, or return None if magic differs."""
+    if len(blob) < 16:
+        return None
+    _version, meta_size, magic = struct.unpack_from("<III", blob, 0)
+    if magic != AUD_METADATA_MAGIC:
+        return None
+
+    s1_pos = 8 + meta_size
+    if s1_pos + 4 > len(blob):
+        raise ValueError(f"audMetadataFile metadata size 0x{meta_size:x} exceeds payload length 0x{len(blob):x}")
+    s1_size, = struct.unpack_from("<I", blob, s1_pos)
+    s2_pos = s1_pos + 4 + s1_size
+    if s2_pos + 4 > len(blob):
+        raise ValueError(f"audMetadataFile section 1 size 0x{s1_size:x} exceeds payload")
+    s2_size, = struct.unpack_from("<I", blob, s2_pos)
+    obj_pos = s2_pos + 4 + s2_size
+    if obj_pos + 4 > len(blob):
+        raise ValueError(f"audMetadataFile object table offset 0x{obj_pos:x} out of range")
+
+    obj_count, = struct.unpack_from("<I", blob, obj_pos)
+    obj_end = obj_pos + 4 + obj_count * 8
+    if obj_end > len(blob):
+        raise ValueError(f"audMetadataFile object table ({obj_count} entries) truncated")
+
+    by_hash = {}
+    by_offset = {}
+    prev_bucket = -1
+    for index in range(obj_count):
+        obj_hash, obj_offset = struct.unpack_from("<II", blob, obj_pos + 4 + index * 8)
+        bucket = obj_hash & 0xFF
+        if bucket < prev_bucket or obj_offset >= meta_size:
+            raise ValueError(f"corrupt object table entry {index}: hash=0x{obj_hash:x} off=0x{obj_offset:x}")
+        prev_bucket = bucket
+        by_hash[obj_hash] = obj_offset
+        by_offset[obj_offset] = obj_hash
+
+    return {
+        "blob": blob,
+        "meta_size": meta_size,
+        "by_hash": by_hash,
+        "by_offset": by_offset,
+        "obj_end": obj_end,
+    }
+
+
+def parse_aud_refs(meta):
+    """Parse the cross-object reference hash table that follows the object table."""
+    blob = meta["blob"]
+    p3 = meta["obj_end"]
+    if p3 + 4 > len(blob):
+        raise ValueError("truncated audMetadataFile pre-reference table")
+    n_pre, = struct.unpack_from("<I", blob, p3)
+    p4 = p3 + 4 + n_pre * 4
+    if p4 + 12 > len(blob):
+        raise ValueError("truncated audMetadataFile reference header")
+    _, _, n_refs = struct.unpack_from("<III", blob, p4)
+    refs_end = p4 + 12 + n_refs * 8
+    if refs_end > len(blob):
+        raise ValueError(f"audMetadataFile reference table ({n_refs} entries) truncated")
+    return [struct.unpack_from("<I", blob, p4 + 12 + i * 8)[0] for i in range(n_refs)]
+
+
+def parse_sounds_streaming_index(sounds_meta):
+    """Index StreamingSound (0x08) objects with a complete adjacent SimpleSound (0x0C) group."""
+    blob = sounds_meta["blob"]
+    meta_size = sounds_meta["meta_size"]
+    sorted_offsets = sorted(sounds_meta["by_offset"])
+    spans = []
+    for i, off in enumerate(sorted_offsets):
+        nxt = sorted_offsets[i + 1] if i + 1 < len(sorted_offsets) else meta_size
+        spans.append((off, nxt, sounds_meta["by_offset"][off], blob[8 + off]))
+
+    parsed = {}
+    for i, (off, nxt, sound_hash, obj_type) in enumerate(spans):
+        if obj_type != TYPE_STREAMING_SOUND:
+            continue
+        seg = blob[8 + off:8 + nxt]
+        for cnt in range(1, 17):
+            p = len(seg) - 2 - cnt * 4
+            if p >= 4 and seg[p] == TYPE_SIMPLE_SOUND and seg[p + 1] == cnt:
+                duration_ms, = struct.unpack_from("<I", seg, p - 4)
+                channels = []
+                for k in range(1, cnt + 1):
+                    if i + k < len(spans) and spans[i + k][3] == TYPE_SIMPLE_SOUND:
+                        co, cn, _, _ = spans[i + k]
+                        cseg = blob[8 + co:8 + cn]
+                        if len(cseg) >= 10 and cseg[1] == 0x00:
+                            bank_hash, wave_hash = struct.unpack_from("<II", cseg, 2)
+                            channels.append({
+                                "bank_hash": bank_hash,
+                                "wave_hash": wave_hash,
+                                "stream_id": wave_hash & STREAM_ID_MASK,
+                            })
+                if len(channels) == cnt:
+                    parsed[sound_hash] = {
+                        "sound_hash": sound_hash,
+                        "duration_ms": duration_ms,
+                        "channel_count": cnt,
+                        "channels": channels,
+                    }
+                break
+    return parsed
+
+
+def walk_tracklist_tracks(tl_hash, game_meta, game_refs):
+    """Return [(track_settings_hash, sound_hash)] for one RadioStationTrackList (0x11)."""
+    blob = game_meta["blob"]
+    meta_size = game_meta["meta_size"]
+    by_hash = game_meta["by_hash"]
+
+    tl_off = by_hash.get(tl_hash)
+    if tl_off is None or tl_off + 0x4C > meta_size or blob[8 + tl_off] != TYPE_RADIO_TRACKLIST:
+        return []
+    tl_pos = 8 + tl_off
+    obj_list_ref, = struct.unpack_from("<I", blob, tl_pos + 0x44)
+    inline_count, = struct.unpack_from("<H", blob, tl_pos + 0x48)
+    track_refs = []
+    if obj_list_ref != OBJECT_REF_NONE:
+        if obj_list_ref >= len(game_refs):
+            return []
+        ol_hash = game_refs[obj_list_ref]
+        ol_off = by_hash.get(ol_hash)
+        if ol_off is not None and ol_off + 12 <= meta_size and blob[8 + ol_off] == TYPE_OBJECT_LIST:
+            ol_count, = struct.unpack_from("<I", blob, 8 + ol_off + 8)
+            if ol_off + 12 + ol_count * 4 > meta_size:

These array bounds use the end of the metadata section rather than the containing object's span, so a truncated array can consume the next object's bytes as references and attach unrelated tracks or stations. Bound each array by the next object offset (or meta_size for the final object) and reject counts that exceed that span. The same issue affects inline track references at line 186, station references at line 235, and station tracklist entries at line 252 in this file.

**@⁠Copilot** on GitHub · 2026-11-24 18:30 UTC · [original](https://github.com/Albotterin/AWC_from_RPF9_Extractor/pull/1#discussion_r4684694988) On `awc_metadata.py` line 182 (outdated): ```diff @@ -0,0 +1,322 @@ +"""Deterministic parser for RAGE 9 GAME.DAT and SOUNDS.DAT audMetadataFile (0x045A88EA) containers. + +The file groups at the start of audio.rpf (before the first ADAT bank) hold +self-describing audMetadataFile tables. Pass complete containers, including any +uncompressed chunks left out by a zlib-only carve: + - GAME.DAT (identified by RADIO_STATIONS_01, type 0x0E): wheel radio stations, static world + emitters ((flags & 0x30) == 0x10), hidden wheel stations ((flags & 0x0C) == 0x04), + RadioStationTrackList (0x11) with external ObjectList (0x02) or inline refs, and + RadioTrackSettings (0x0F) pointing to SOUNDS.DAT sound hashes. + - SOUNDS.DAT: StreamingSound (0x08) duration and adjacent SimpleSound (0x0C) channel groups + holding (bank_hash, wave_hash) -> 29-bit AWC stream IDs. + +Pure Python standard library; ships no game data, keys, or station/song lists. +""" +from collections import defaultdict +import struct + +from awc_names import STREAM_ID_MASK, joaat + +AUD_METADATA_MAGIC = 0x045A88EA +AUD_METADATA_CHUNK_SIZE = 65536 +OBJECT_REF_NONE = 0xFFFFFFFF + +TYPE_OBJECT_LIST = 0x02 +TYPE_STREAMING_SOUND = 0x08 +TYPE_SIMPLE_SOUND = 0x0C +TYPE_RADIO_STATION_LIST = 0x0E +TYPE_RADIO_TRACK = 0x0F +TYPE_RADIO_STATION = 0x10 +TYPE_RADIO_TRACKLIST = 0x11 + +RADIO_STATIONS_LIST_PREFIX = "RADIO_STATIONS_" +RADIO_STATIONS_MAX_LISTS = 16 +WHEEL_STATION_STATIC_MASK = 0x30 +WHEEL_STATION_STATIC_VALUE = 0x10 +WHEEL_STATION_HIDDEN_MASK = 0x0C +WHEEL_STATION_HIDDEN_VALUE = 0x04 + + +def group_inflated_streams(streams, chunk_size=AUD_METADATA_CHUNK_SIZE): + """Group consecutive chunks, ending on any chunk whose size != chunk_size. + + Callers must supply both inflated and stored chunks in archive order. + """ + groups = [] + current = [] + for blob in streams: + current.append(blob) + if len(blob) != chunk_size: + groups.append(b"".join(current)) + current = [] + if current: + groups.append(b"".join(current)) + return groups + + +def parse_aud_metadata(blob): + """Parse one contiguous audMetadataFile (0x045A88EA) payload, or return None if magic differs.""" + if len(blob) < 16: + return None + _version, meta_size, magic = struct.unpack_from("<III", blob, 0) + if magic != AUD_METADATA_MAGIC: + return None + + s1_pos = 8 + meta_size + if s1_pos + 4 > len(blob): + raise ValueError(f"audMetadataFile metadata size 0x{meta_size:x} exceeds payload length 0x{len(blob):x}") + s1_size, = struct.unpack_from("<I", blob, s1_pos) + s2_pos = s1_pos + 4 + s1_size + if s2_pos + 4 > len(blob): + raise ValueError(f"audMetadataFile section 1 size 0x{s1_size:x} exceeds payload") + s2_size, = struct.unpack_from("<I", blob, s2_pos) + obj_pos = s2_pos + 4 + s2_size + if obj_pos + 4 > len(blob): + raise ValueError(f"audMetadataFile object table offset 0x{obj_pos:x} out of range") + + obj_count, = struct.unpack_from("<I", blob, obj_pos) + obj_end = obj_pos + 4 + obj_count * 8 + if obj_end > len(blob): + raise ValueError(f"audMetadataFile object table ({obj_count} entries) truncated") + + by_hash = {} + by_offset = {} + prev_bucket = -1 + for index in range(obj_count): + obj_hash, obj_offset = struct.unpack_from("<II", blob, obj_pos + 4 + index * 8) + bucket = obj_hash & 0xFF + if bucket < prev_bucket or obj_offset >= meta_size: + raise ValueError(f"corrupt object table entry {index}: hash=0x{obj_hash:x} off=0x{obj_offset:x}") + prev_bucket = bucket + by_hash[obj_hash] = obj_offset + by_offset[obj_offset] = obj_hash + + return { + "blob": blob, + "meta_size": meta_size, + "by_hash": by_hash, + "by_offset": by_offset, + "obj_end": obj_end, + } + + +def parse_aud_refs(meta): + """Parse the cross-object reference hash table that follows the object table.""" + blob = meta["blob"] + p3 = meta["obj_end"] + if p3 + 4 > len(blob): + raise ValueError("truncated audMetadataFile pre-reference table") + n_pre, = struct.unpack_from("<I", blob, p3) + p4 = p3 + 4 + n_pre * 4 + if p4 + 12 > len(blob): + raise ValueError("truncated audMetadataFile reference header") + _, _, n_refs = struct.unpack_from("<III", blob, p4) + refs_end = p4 + 12 + n_refs * 8 + if refs_end > len(blob): + raise ValueError(f"audMetadataFile reference table ({n_refs} entries) truncated") + return [struct.unpack_from("<I", blob, p4 + 12 + i * 8)[0] for i in range(n_refs)] + + +def parse_sounds_streaming_index(sounds_meta): + """Index StreamingSound (0x08) objects with a complete adjacent SimpleSound (0x0C) group.""" + blob = sounds_meta["blob"] + meta_size = sounds_meta["meta_size"] + sorted_offsets = sorted(sounds_meta["by_offset"]) + spans = [] + for i, off in enumerate(sorted_offsets): + nxt = sorted_offsets[i + 1] if i + 1 < len(sorted_offsets) else meta_size + spans.append((off, nxt, sounds_meta["by_offset"][off], blob[8 + off])) + + parsed = {} + for i, (off, nxt, sound_hash, obj_type) in enumerate(spans): + if obj_type != TYPE_STREAMING_SOUND: + continue + seg = blob[8 + off:8 + nxt] + for cnt in range(1, 17): + p = len(seg) - 2 - cnt * 4 + if p >= 4 and seg[p] == TYPE_SIMPLE_SOUND and seg[p + 1] == cnt: + duration_ms, = struct.unpack_from("<I", seg, p - 4) + channels = [] + for k in range(1, cnt + 1): + if i + k < len(spans) and spans[i + k][3] == TYPE_SIMPLE_SOUND: + co, cn, _, _ = spans[i + k] + cseg = blob[8 + co:8 + cn] + if len(cseg) >= 10 and cseg[1] == 0x00: + bank_hash, wave_hash = struct.unpack_from("<II", cseg, 2) + channels.append({ + "bank_hash": bank_hash, + "wave_hash": wave_hash, + "stream_id": wave_hash & STREAM_ID_MASK, + }) + if len(channels) == cnt: + parsed[sound_hash] = { + "sound_hash": sound_hash, + "duration_ms": duration_ms, + "channel_count": cnt, + "channels": channels, + } + break + return parsed + + +def walk_tracklist_tracks(tl_hash, game_meta, game_refs): + """Return [(track_settings_hash, sound_hash)] for one RadioStationTrackList (0x11).""" + blob = game_meta["blob"] + meta_size = game_meta["meta_size"] + by_hash = game_meta["by_hash"] + + tl_off = by_hash.get(tl_hash) + if tl_off is None or tl_off + 0x4C > meta_size or blob[8 + tl_off] != TYPE_RADIO_TRACKLIST: + return [] + tl_pos = 8 + tl_off + obj_list_ref, = struct.unpack_from("<I", blob, tl_pos + 0x44) + inline_count, = struct.unpack_from("<H", blob, tl_pos + 0x48) + track_refs = [] + if obj_list_ref != OBJECT_REF_NONE: + if obj_list_ref >= len(game_refs): + return [] + ol_hash = game_refs[obj_list_ref] + ol_off = by_hash.get(ol_hash) + if ol_off is not None and ol_off + 12 <= meta_size and blob[8 + ol_off] == TYPE_OBJECT_LIST: + ol_count, = struct.unpack_from("<I", blob, 8 + ol_off + 8) + if ol_off + 12 + ol_count * 4 > meta_size: ``` These array bounds use the end of the metadata section rather than the containing object's span, so a truncated array can consume the next object's bytes as references and attach unrelated tracks or stations. Bound each array by the next object offset (or `meta_size` for the final object) and reject counts that exceed that span. The same issue affects inline track references at line 186, station references at line 235, and station tracklist entries at line 252 in this file.
Author
Owner

@⁠Elijah-J on GitHub · 2026-11-24 22:24 UTC · original

The three review findings are addressed in dfcd185. The extractor reads each stream’s first available Opus packet to determine its channel count, uses the immediately preceding block for skip recovery, and bounds metadata reference arrays to their containing objects.

All 17 tests passed. The parsed metadata matched the previous results. All 11 sampled Ogg Opus exports matched the previous exports byte for byte, and FFmpeg decoded each one successfully.

**@⁠Elijah-J** on GitHub · 2026-11-24 22:24 UTC · [original](https://github.com/Albotterin/AWC_from_RPF9_Extractor/pull/1#issuecomment-7146198555) The three review findings are addressed in `dfcd185`. The extractor reads each stream’s first available Opus packet to determine its channel count, uses the immediately preceding block for skip recovery, and bounds metadata reference arrays to their containing objects. All 17 tests passed. The parsed metadata matched the previous results. All 11 sampled Ogg Opus exports matched the previous exports byte for byte, and FFmpeg decoded each one successfully.

Pull request closed

This discussion has been locked. Commenting is limited to contributors.
No description provided.