tools/awc_opus: honor hdr24 block_samples budget, interleaved skip, and deficit continuation #1072

Open
github-bot wants to merge 3 commits from github-bot/gh-1072 into main AGit
Owner

@⁠Elijah-J on GitHub · 2026-11-24 17:48 UTC · original
Elijah-J:fix/awc-hdr24-chunk-budget-skip → main · +231 −31 · 3 files · 3 commits · open

Claimed in the coordination issue as: AWC-HDR24-BUDGET (posted after the draft was opened)

What and why

Streamed music (0x48) chunks carry a 24-byte per-channel header with (subblocks, skip_samples, block_samples) at +4..+16. The sampled stereo banks use interleaved counts (2× per-channel 48 kHz frames), while the exporter also accepts a per-channel skip that verifies an exact packet overlap.

Previously music_channels() only checked skip as a per-channel frame count and ignored block_samples (+12), which rejected multi-stem/multi-block streamed music banks that:

  • pad a chunk's trailing 2048-byte subblock with extra Opus packets past block_samples / packet_channels,
  • store skip_samples in interleaved stereo units (2 * frames), or
  • stop a chunk short of its block_samples budget so the deficit carries into the next chunk's skip_samples.

Changes:

  • tools/awc_opus.py: read (count, skip, block_samples) from hdr24 +4..+16; trim trailing subblock padding packets past block_samples // pch; match interleaved (skip // pch) and per-channel (skip) repeated prefixes; handle exact-boundary deficit continuation when a preceding block stopped short of its block_samples budget while continuing to fail closed on partial/corrupt skips or odd block_samples.
  • docs/audio.md: document +8 (skip_samples), +12 (block_samples), and the conditions for carry-over recovery under ### Streamed music (0x48).
  • Metadata-only reads keep block locations and only the packet buffers needed for the current overlap check. On an 8.6 MB test bank, traced temporary allocations peaked at 380 KB, down from 9.1 MB in the first draft.
  • tests/test_awc_opus.py: add synthetic unit tests covering block-budget padding trimming, interleaved stereo skip deduplication, short-block deficit continuation, and partial-boundary fail-closed rejection.

Tested

Synthetic unit tests on macOS:

  • python3 -I tests/test_awc_opus.py -v — 64/64 OK
  • python3 -I tests/test_awc_manifest.py -v — 23/23 OK
  • python3 -I tests/test_text_write_line_endings.py -v — 3/3 OK
  • python3 -m compileall -q make_game.py tools tests — exit 0

A separate read-only Xbox Series 1.0.2.1 check recovered four banks (11 stems) rejected by the previous overlap-only extractor. FFmpeg decoded every stem to its descriptor length after Ogg end trimming. Three carry-over transitions exercised a zero net skip. Positive net skip was tested synthetically.

GPUs tested: n/a

AI-assisted: yes

Checklist

  • Based on current main and merges cleanly (a conflicting pull request is labeled needs rebase).
  • One topic; follow-up work goes in a new pull request.
  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed. (n/a — audio tool/docs only)
**@⁠Elijah-J** on GitHub · 2026-11-24 17:48 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1072) `Elijah-J:fix/awc-hdr24-chunk-budget-skip` → `main` · +231 −31 · 3 files · 3 commits · open Claimed in the coordination issue as: [AWC-HDR24-BUDGET](https://git.gtahub.st/github/ubiquitarianism--leonida/issues/14) (posted after the draft was opened) ### What and why Streamed music (`0x48`) chunks carry a 24-byte per-channel header with `(subblocks, skip_samples, block_samples)` at `+4..+16`. The sampled stereo banks use interleaved counts (2× per-channel 48 kHz frames), while the exporter also accepts a per-channel skip that verifies an exact packet overlap. Previously `music_channels()` only checked `skip` as a per-channel frame count and ignored `block_samples` (`+12`), which rejected multi-stem/multi-block streamed music banks that: - pad a chunk's trailing 2048-byte subblock with extra Opus packets past `block_samples / packet_channels`, - store `skip_samples` in interleaved stereo units (`2 * frames`), or - stop a chunk short of its `block_samples` budget so the deficit carries into the next chunk's `skip_samples`. Changes: - `tools/awc_opus.py`: read `(count, skip, block_samples)` from `hdr24` `+4..+16`; trim trailing subblock padding packets past `block_samples // pch`; match interleaved (`skip // pch`) and per-channel (`skip`) repeated prefixes; handle exact-boundary deficit continuation when a preceding block stopped short of its `block_samples` budget while continuing to fail closed on partial/corrupt skips or odd `block_samples`. - `docs/audio.md`: document `+8` (`skip_samples`), `+12` (`block_samples`), and the conditions for carry-over recovery under `### Streamed music (0x48)`. - Metadata-only reads keep block locations and only the packet buffers needed for the current overlap check. On an 8.6 MB test bank, traced temporary allocations peaked at 380 KB, down from 9.1 MB in the first draft. - `tests/test_awc_opus.py`: add synthetic unit tests covering block-budget padding trimming, interleaved stereo skip deduplication, short-block deficit continuation, and partial-boundary fail-closed rejection. ### Tested Synthetic unit tests on macOS: - `python3 -I tests/test_awc_opus.py -v` — 64/64 OK - `python3 -I tests/test_awc_manifest.py -v` — 23/23 OK - `python3 -I tests/test_text_write_line_endings.py -v` — 3/3 OK - `python3 -m compileall -q make_game.py tools tests` — exit 0 A separate read-only Xbox Series 1.0.2.1 check recovered four banks (11 stems) rejected by the previous overlap-only extractor. FFmpeg decoded every stem to its descriptor length after Ogg end trimming. Three carry-over transitions exercised a zero net skip. Positive net skip was tested synthetically. GPUs tested: n/a AI-assisted: yes ### Checklist - [x] Based on current `main` and merges cleanly (a conflicting pull request is labeled `needs rebase`). - [x] One topic; follow-up work goes in a new pull request. - [x] No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here. - [ ] A new translator rule is in the contract table of `docs/design.md`, with how it was confirmed. *(n/a — audio tool/docs only)*
Keep block locations instead of copies of all Opus packets during discovery. Check the allocation regression and record the exact sample-count evidence for the skip and budget handling.

Co-authored-by: OpenAI Codex <[email protected]>
Carry the full deficit across an empty budgeted block and preserve overlap state across empty blocks without a budget. Read packet payloads through views for metadata-only scans, and stop measuring packet durations at the declared budget.

Cover both empty-block cases and the packet-copy and duration-scan regressions.

Co-authored-by: OpenAI Codex <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:36:37 +00:00
Author
Owner

@⁠Copilot on GitHub · 2026-11-24 18:43 UTC · original
On tools/awc_opus.py line 396 (outdated):

@@ -295,50 +332,90 @@ def music_channels(d: bytes, mus, data, collect_packets: bool = True):
         if not (1000 <= rate <= 192000) or codec != 0x0B:
             return []
         info.append([cid, samples, rate, codec, [], 0])
-    previous = [[] for _ in range(channels)]
+    block_data = [[] for _ in range(channels)]
     for b in range(blocks):
         offset = b * chunk
         at = d_at + offset
         block_size = min(chunk, d_size - offset)
         if channels * 24 > block_size:
             return []
-        recs = [struct.unpack_from("<II", d, at + 24 * c + 4) for c in range(channels)]   # (count, skip)
+        recs = [struct.unpack_from("<III", d, at + 24 * c + 4) for c in range(channels)]   # (count, skip, block_samples)
         total = sum(r[0] for r in recs)
         header = (channels * 24 + total * 4 + 2047) & ~2047
         if header + total * 2048 > block_size:
             return []
         before = 0
-        for c, (count, skip) in enumerate(recs):
+        for c, (count, skip, block_samples) in enumerate(recs):
             start = at + header + before * 2048
             before += count
-            packets = opus_packets(d, start, count * 2048)
-            repeated = repeated_prefix_packets(packets, previous[c], skip) if skip else 0
-            if repeated is None:
-                return []
-            if packets:
-                previous[c] = packets
-            if packets and info[c][5] < 2:
-                info[c][5] = 2 if any(p[0] & 0x04 for p in packets) else 1
-            if collect_packets:
-                info[c][4].extend(packets[repeated:] if repeated else packets)
+            size = count * 2048
+            if info[c][5] < 2:
+                for packet_start, _ in opus_packet_ranges(d, start, size):
+                    info[c][5] = 2 if d[packet_start] & 0x04 else 1
+                    if info[c][5] == 2:
+                        break
+            block_data[c].append((skip, block_samples, start, size))
+    for c in range(channels):
+        pch = max(1, info[c][5])
+        previous = []
+        prev_deficit = 0
+        for skip, block_samples, start, size in block_data[c]:
+            packets = opus_packets(d, start, size)
+            kept = packets
+            deficit = 0
+            if packets and block_samples > 0:
+                if block_samples % pch != 0:
+                    return []
+                kept, deficit = _trim_packets_to_budget(packets, block_samples // pch)
+            repeated = 0
+            if skip > 0:
+                if not kept:
+                    return []
+                candidates = ((skip // pch, skip) if pch > 1 and skip % pch == 0 else (skip,))
+                matched = None
+                for cand in candidates:
+                    if cand > 0:
+                        rep = repeated_prefix_packets(kept, previous, cand)
+                        if rep is not None:
+                            matched = rep
+                            break
+                if matched is not None:
+                    repeated = matched
+                elif prev_deficit > 0 and skip % pch == 0:
+                    skip_frames = skip // pch
+                    if skip_frames < prev_deficit:
+                        return []
+                    drop = _drop_exact_prefix_packets(kept, skip_frames - prev_deficit)
+                    if drop is None:
+                        return []
+                    repeated = drop
+                else:
+                    return []
+            if kept:
+                previous = kept
+                prev_deficit = deficit

prev_deficit is only updated when kept is non-empty. If a chunk has a positive block_samples budget but yields zero packets (or all packets are trimmed away), deficit can be > 0 but won’t carry forward, breaking the stated “deficit continuation” behavior for the next chunk. Consider updating prev_deficit whenever a positive budget is present (and parsing succeeded), while only updating previous when kept actually has packets.

**@⁠Copilot** on GitHub · 2026-11-24 18:43 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1072#discussion_r4684844022) On `tools/awc_opus.py` line 396 (outdated): ```diff @@ -295,50 +332,90 @@ def music_channels(d: bytes, mus, data, collect_packets: bool = True): if not (1000 <= rate <= 192000) or codec != 0x0B: return [] info.append([cid, samples, rate, codec, [], 0]) - previous = [[] for _ in range(channels)] + block_data = [[] for _ in range(channels)] for b in range(blocks): offset = b * chunk at = d_at + offset block_size = min(chunk, d_size - offset) if channels * 24 > block_size: return [] - recs = [struct.unpack_from("<II", d, at + 24 * c + 4) for c in range(channels)] # (count, skip) + recs = [struct.unpack_from("<III", d, at + 24 * c + 4) for c in range(channels)] # (count, skip, block_samples) total = sum(r[0] for r in recs) header = (channels * 24 + total * 4 + 2047) & ~2047 if header + total * 2048 > block_size: return [] before = 0 - for c, (count, skip) in enumerate(recs): + for c, (count, skip, block_samples) in enumerate(recs): start = at + header + before * 2048 before += count - packets = opus_packets(d, start, count * 2048) - repeated = repeated_prefix_packets(packets, previous[c], skip) if skip else 0 - if repeated is None: - return [] - if packets: - previous[c] = packets - if packets and info[c][5] < 2: - info[c][5] = 2 if any(p[0] & 0x04 for p in packets) else 1 - if collect_packets: - info[c][4].extend(packets[repeated:] if repeated else packets) + size = count * 2048 + if info[c][5] < 2: + for packet_start, _ in opus_packet_ranges(d, start, size): + info[c][5] = 2 if d[packet_start] & 0x04 else 1 + if info[c][5] == 2: + break + block_data[c].append((skip, block_samples, start, size)) + for c in range(channels): + pch = max(1, info[c][5]) + previous = [] + prev_deficit = 0 + for skip, block_samples, start, size in block_data[c]: + packets = opus_packets(d, start, size) + kept = packets + deficit = 0 + if packets and block_samples > 0: + if block_samples % pch != 0: + return [] + kept, deficit = _trim_packets_to_budget(packets, block_samples // pch) + repeated = 0 + if skip > 0: + if not kept: + return [] + candidates = ((skip // pch, skip) if pch > 1 and skip % pch == 0 else (skip,)) + matched = None + for cand in candidates: + if cand > 0: + rep = repeated_prefix_packets(kept, previous, cand) + if rep is not None: + matched = rep + break + if matched is not None: + repeated = matched + elif prev_deficit > 0 and skip % pch == 0: + skip_frames = skip // pch + if skip_frames < prev_deficit: + return [] + drop = _drop_exact_prefix_packets(kept, skip_frames - prev_deficit) + if drop is None: + return [] + repeated = drop + else: + return [] + if kept: + previous = kept + prev_deficit = deficit ``` `prev_deficit` is only updated when `kept` is non-empty. If a chunk has a positive `block_samples` budget but yields zero packets (or all packets are trimmed away), `deficit` can be > 0 but won’t carry forward, breaking the stated “deficit continuation” behavior for the next chunk. Consider updating `prev_deficit` whenever a positive budget is present (and parsing succeeded), while only updating `previous` when `kept` actually has packets.
Author
Owner

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

Warning

Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.

Copilot review overview

3 open issues
What changed in this PR

Updates streamed-music (0x48) parsing to correctly interpret HDR24 per-channel headers, honoring block_samples budgets and stereo-interleaved skip_samples, including deficit carry-over between chunks.

Changes:

  • Parse (subblocks, skip_samples, block_samples) from the per-channel 24-byte headers and trim packets beyond block_samples.
  • Accept both interleaved (skip // pch) and per-channel skip when verifying repeated-prefix overlaps, plus deficit continuation when a prior chunk undershot its budget.
  • Add unit tests for padding-trim, stereo interleaved skip, deficit continuation, and metadata-mode memory behavior; update audio format documentation.
File Description
tools/​awc_opus.py Implements budget trimming, interleaved/per-channel skip matching, deficit continuation, and packet-range iteration.
tests/​test_awc_opus.py Adds synthetic tests for the new trimming/skip/deficit behaviors plus a metadata allocation check.
docs/​audio.md Documents HDR24 skip_samples / block_samples semantics and deficit carry-over recovery rules.

Review effort: Lite

**@⁠copilot-pull-request-reviewer[bot]** on GitHub · 2026-11-24 18:43 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1072#pullrequestreview-6045250043) · **reviewed** > [!WARNING] > Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a `copilot-code-review.yml` file specifying one with the `runs-on` attribute. See the [docs](https://gh.io/AA11tgch) for more details. <!-- ccr-overview-v2 --> ## Copilot review overview <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> [`prev_deficit` is only updated when `kept` is non-empty. If a chunk has a positive `block_samples`…](https://git.gtahub.st/github/ubiquitarianism--leonida/pulls/1072) · 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> [`opus_packets()` always copies packet payloads into new `bytes`. In `collect_packets=False` mode,…](https://git.gtahub.st/github/ubiquitarianism--leonida/pulls/1072) · New - <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.png" alt="Low severity" width="62" height="18" align="texttop"></picture> [`_trim_packets_to_budget` computes `opus_samples()` for every packet twice (once in `sum(...)`,…](https://git.gtahub.st/github/ubiquitarianism--leonida/pulls/1072) · New </details> <details> <summary><strong>What changed in this PR</strong></summary> Updates streamed-music (`0x48`) parsing to correctly interpret HDR24 per-channel headers, honoring `block_samples` budgets and stereo-interleaved `skip_samples`, including deficit carry-over between chunks. **Changes:** - Parse `(subblocks, skip_samples, block_samples)` from the per-channel 24-byte headers and trim packets beyond `block_samples`. - Accept both interleaved (`skip // pch`) and per-channel skip when verifying repeated-prefix overlaps, plus deficit continuation when a prior chunk undershot its budget. - Add unit tests for padding-trim, stereo interleaved skip, deficit continuation, and metadata-mode memory behavior; update audio format documentation. | File | Description | | ---- | ----------- | | tools/​awc_opus.py | Implements budget trimming, interleaved/per-channel skip matching, deficit continuation, and packet-range iteration. | | tests/​test_awc_opus.py | Adds synthetic tests for the new trimming/skip/deficit behaviors plus a metadata allocation check. | | docs/​audio.md | Documents HDR24 `skip_samples` / `block_samples` semantics and deficit carry-over recovery rules. | </details> <sub>Review effort: Lite</sub>
@ -329,3 +405,3 @@
def opus_packets(d: bytes, at: int, size: int):
out = []
return [bytes(d[start:end]) for start, end in opus_packet_ranges(d, at, size)]
Author
Owner

@⁠Copilot on GitHub · 2026-11-24 18:43 UTC · original

opus_packets() always copies packet payloads into new bytes. In collect_packets=False mode, this still allocates per-packet bytes even though callers ultimately discard buffers after overlap validation. If allocation pressure matters (as noted in the PR description), consider having the overlap-check logic work on (start, end) ranges (or memoryview slices) and only materialize bytes when collect_packets=True (or when needed to persist output).

**@⁠Copilot** on GitHub · 2026-11-24 18:43 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1072#discussion_r4684844106) `opus_packets()` always copies packet payloads into new `bytes`. In `collect_packets=False` mode, this still allocates per-packet bytes even though callers ultimately discard buffers after overlap validation. If allocation pressure matters (as noted in the PR description), consider having the overlap-check logic work on `(start, end)` ranges (or `memoryview` slices) and only materialize `bytes` when `collect_packets=True` (or when needed to persist output).
Author
Owner

@⁠Copilot on GitHub · 2026-11-24 18:43 UTC · original
On tools/awc_opus.py line 282 (outdated):

@@ -263,6 +265,38 @@ def repeated_prefix_packets(packets: list[bytes], previous: list[bytes], samples
     return None
 
 
+def _trim_packets_to_budget(packets: list[bytes], target_frames: int) -> tuple[list[bytes], int]:
+    """Trim trailing subblock padding packets past a chunk's declared per-channel frame budget.
+
+    Returns (kept_packets, deficit_frames) where deficit_frames > 0 if the chunk's packets
+    stopped short of target_frames.
+    """
+    total = sum(opus_samples(p) for p in packets)
+    if total > target_frames:
+        acc = 0
+        for idx, packet in enumerate(packets):
+            acc += opus_samples(packet)
+            if acc >= target_frames:
+                return packets[:idx + 1], 0
+        return packets, 0
+    return packets, target_frames - total

_trim_packets_to_budget computes opus_samples() for every packet twice (once in sum(...), again in the trimming loop). This is avoidable by doing a single pass that accumulates durations until reaching/exceeding target_frames (and separately computing deficit when you never reach the target). This is likely small per chunk, but it’s in a hot loop over all packets/blocks.

**@⁠Copilot** on GitHub · 2026-11-24 18:43 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1072#discussion_r4684844181) On `tools/awc_opus.py` line 282 (outdated): ```diff @@ -263,6 +265,38 @@ def repeated_prefix_packets(packets: list[bytes], previous: list[bytes], samples return None +def _trim_packets_to_budget(packets: list[bytes], target_frames: int) -> tuple[list[bytes], int]: + """Trim trailing subblock padding packets past a chunk's declared per-channel frame budget. + + Returns (kept_packets, deficit_frames) where deficit_frames > 0 if the chunk's packets + stopped short of target_frames. + """ + total = sum(opus_samples(p) for p in packets) + if total > target_frames: + acc = 0 + for idx, packet in enumerate(packets): + acc += opus_samples(packet) + if acc >= target_frames: + return packets[:idx + 1], 0 + return packets, 0 + return packets, target_frames - total ``` `_trim_packets_to_budget` computes `opus_samples()` for every packet twice (once in `sum(...)`, again in the trimming loop). This is avoidable by doing a single pass that accumulates durations until reaching/exceeding `target_frames` (and separately computing deficit when you never reach the target). This is likely small per chunk, but it’s in a hot loop over all packets/blocks.
Author
Owner

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

I addressed the three review notes in c640232: empty budgeted chunks now update skip state, metadata-only scans avoid copying packet payloads, and budget trimming stops once the target is reached. All 93 focused tests passed, and FFmpeg again matched the declared lengths of all 11 sampled stems. The current CI and No Game Data runs are waiting for maintainer approval. CI · No Game Data

**@⁠Elijah-J** on GitHub · 2026-11-24 18:54 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1072#issuecomment-7141308168) I addressed the three review notes in `c640232`: empty budgeted chunks now update skip state, metadata-only scans avoid copying packet payloads, and budget trimming stops once the target is reached. All 93 focused tests passed, and FFmpeg again matched the declared lengths of all 11 sampled stems. The current CI and No Game Data runs are waiting for maintainer approval. [CI](https://github.com/ubiquitarianism/leonida/actions/runs/45464288114) · [No Game Data](https://github.com/ubiquitarianism/leonida/actions/runs/45464288155)
This pull request can be merged automatically.
This branch is out-of-date with the base branch
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/1072/head:github-bot/gh-1072'
git switch 'github-bot/gh-1072'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-1072'
git switch 'github-bot/gh-1072'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-1072'
git switch 'github-bot/gh-1072'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-1072'
git switch 'main'
git merge --squash 'github-bot/gh-1072'
git switch 'main'
git merge --ff-only 'github-bot/gh-1072'
git switch 'main'
git merge 'github-bot/gh-1072'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.