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

Merged
Elijah-J merged 3 commits from upstream-pr/1072 into main 2026-11-28 13:09:29 +00:00
Elijah-J commented 2026-11-24 17:48:45 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by Elijah-J on 2026-11-24T17:48:45Z.


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)
<!-- greyfinch-sync:ubiquitarianism/leonida:issue:5477407436 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/1072). Originally posted by [Elijah-J](https://github.com/Elijah-J) on 2026-11-24T17:48:45Z. --- Claimed in the coordination issue as: [AWC-HDR24-BUDGET](https://github.com/ubiquitarianism/leonida/issues/14#issuecomment-7140624662) (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)*
Copilot commented 2026-11-24 18:43:22 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by Copilot on 2026-11-24T18:43:22Z.

Code review location: tools/awc_opus.py; line 396

@@ -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.

<!-- greyfinch-sync:ubiquitarianism/leonida:review-comment:4684844022 --> Imported from [ubiquitarianism/leonida](https://github.com/ubiquitarianism/leonida/pull/1072#discussion_r4684844022). Originally posted by [Copilot](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-24T18:43:22Z. **Code review location:** `tools/awc_opus.py`; line 396 ~~~~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.
copilot-pull-request-reviewer[bot] commented 2026-11-24 18:43:23 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by copilot-pull-request-reviewer[bot] on 2026-11-24T18:43:23Z.

Review: COMMENTED


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

<!-- greyfinch-sync:ubiquitarianism/leonida:review:6045250043 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/1072#pullrequestreview-6045250043). Originally posted by [copilot-pull-request-reviewer[bot]](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-24T18:43:23Z. **Review:** COMMENTED --- > [!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://github.com/ubiquitarianism/leonida/pull/1072#discussion_r4684844022) · 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://github.com/ubiquitarianism/leonida/pull/1072#discussion_r4684844106) · 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://github.com/ubiquitarianism/leonida/pull/1072#discussion_r4684844181) · 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>
Copilot commented 2026-11-24 18:43:23 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by Copilot on 2026-11-24T18:43:23Z.

Code review location: tools/awc_opus.py; line 406

@@ -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
+            if collect_packets and kept:
+                info[c][4].extend(kept[repeated:] if repeated else kept)
     for x in info:
         if x[3] == 0x0B and x[5] > 1:
             x[1] //= x[5]
     return [tuple(x) for x in info]
 
 
 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)]

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).

<!-- greyfinch-sync:ubiquitarianism/leonida:review-comment:4684844106 --> Imported from [ubiquitarianism/leonida](https://github.com/ubiquitarianism/leonida/pull/1072#discussion_r4684844106). Originally posted by [Copilot](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-24T18:43:23Z. **Code review location:** `tools/awc_opus.py`; line 406 ~~~~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 + if collect_packets and kept: + info[c][4].extend(kept[repeated:] if repeated else kept) for x in info: if x[3] == 0x0B and x[5] > 1: x[1] //= x[5] return [tuple(x) for x in info] 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)] ~~~~ --- `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 commented 2026-11-24 18:43:23 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by Copilot on 2026-11-24T18:43:23Z.

Code review location: tools/awc_opus.py; line 282

@@ -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.

<!-- greyfinch-sync:ubiquitarianism/leonida:review-comment:4684844181 --> Imported from [ubiquitarianism/leonida](https://github.com/ubiquitarianism/leonida/pull/1072#discussion_r4684844181). Originally posted by [Copilot](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-24T18:43:23Z. **Code review location:** `tools/awc_opus.py`; line 282 ~~~~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.
Elijah-J commented 2026-11-24 18:54:00 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by Elijah-J on 2026-11-24T18:54:00Z.


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

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7141308168 --> Imported from [ubiquitarianism/leonida](https://github.com/ubiquitarianism/leonida/pull/1072#issuecomment-7141308168). Originally posted by [Elijah-J](https://github.com/Elijah-J) on 2026-11-24T18:54:00Z. --- 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)
MoonEyes commented 2026-11-28 13:09:23 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-11-28T13:09:23Z.


Red/green: tests/test_awc_opus.py 6 failed on main, 67 passed with the PR.
Targeted batch of 30 PRs (their tests, the tests importing the changed modules, the docs tests, the translator suite) on main a997a3c: no new failure, Windows 11 / Python.
AI-assisted (Claude Code, Claude Opus 5.5)

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7239733605 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/1072#issuecomment-7239733605). Originally posted by [MoonEyes](https://github.com/MoonEyes) on 2026-11-28T13:09:23Z. --- Red/green: tests/test_awc_opus.py 6 failed on main, 67 passed with the PR. Targeted batch of 30 PRs (their tests, the tests importing the changed modules, the docs tests, the translator suite) on main a997a3c: no new failure, Windows 11 / Python. AI-assisted (Claude Code, Claude Opus 5.5)
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
ProjectLeonida/mandy!1072
No description provided.