mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 08:58:36 +00:00
Invalidate previous music cue regions before a bank re-export (#6867)
Squash-merged after diff review of PR #6867 - Invalidate previous music cue regions before a bank re-export
This commit is contained in:
@ -403,3 +403,14 @@ the audio itself is not. See the ground rules in [design.md](design.md#ground-ru
|
||||
|
||||
The tools export the streams and channels as stored. They do not reconstruct runtime mixing, looping, ducking or
|
||||
music-segment selection; that belongs to the game's audio system.
|
||||
|
||||
## Streamed-music cue sheets
|
||||
|
||||
Run `python -I tools/awc_opus.py <bank-or-directory> <output> --cue-sheet` to write
|
||||
`cue_regions.json` next to the Ogg files for each bank with verified regions. Each row names
|
||||
a sibling audio file and the hexadecimal cue-name hash. The integer interval
|
||||
`[start_sample, end_sample)` counts 48 kHz frames per channel from the start of playback.
|
||||
Overlapping regions keep their original endpoints. The exporter pairs consecutive same-name
|
||||
start/end records within one ordered marker tag. It requires a unique stream entry and
|
||||
descriptor channel with the same ID, exported packets, and endpoints within the declared
|
||||
and exported audio. A rerun with the option refreshes an existing sheet even if it becomes empty.
|
||||
|
||||
@ -158,8 +158,8 @@ The name word is 0 on 96 records (78 tags start with one); what a nameless recor
|
||||
`0xE5C74063` (418,838 records, 402,357 of them on speech streams with a `0x5c` clip) and `0xdbedd43c` (330,756,
|
||||
all on such streams and all with `extra = 0`) are not known.
|
||||
- **`value`** is a whole number stored as `f32` on every record of those six names. On five of the other names it
|
||||
is `joaat("start")` or `joaat("end")` in equal or near-equal numbers (196/197, 101/101, 54/54, 49/49, 20/19),
|
||||
which reads as region start/end pairs (hypothesis: the split was counted, not matched record by record).
|
||||
is `joaat("start")` (`0x84dc271f`) or `joaat("end")` (`0xb0c485d7`). Matched record by record, 418 of the 420
|
||||
`start` records are followed by their `end`; see [Region cues](#region-cues-start-and-end-records).
|
||||
- The same reference states that an AWC tag id is the low byte of the joaat of the chunk name. That holds for
|
||||
`markers` (`0xbd`), `data` (`0x55`), `peak` (`0x36`), `seektable` (`0xa3`) and `streamformat` (`0x48`), which
|
||||
`tests/test_rsc8_audio.py` checks, and by the same rule `0x5a` and `0xd9` are `granulargrains` and
|
||||
@ -167,6 +167,60 @@ The name word is 0 on 96 records (78 tags start with one); what a nameless recor
|
||||
`stream_format`, and with the underscore the rule fails (`0xb8` and `0xf9`). It does not hold for `0x5c`,
|
||||
`0x76` and `0xb2` under the names `animation`, `format` and `metadata` either, so those three names stay open.
|
||||
|
||||
#### Region cues: `start` and `end` records
|
||||
|
||||
The five names whose `value` is the hash of `start` or `end` have 841 records in 22 tags of `audio.rpf`: 420
|
||||
`start`, 420 `end` and one with a third value. An earlier version of this page read the near-equal counts per name
|
||||
(196/197, 101/101, 54/54, 49/49, 20/19) as region pairs without matching them. `tools/rsc8_audio.py` now matches
|
||||
them (`pair_marker_regions`, the `marker_regions` block of every scan summary): inside one tag it takes the
|
||||
records of one name in stored order, and a pair is a `start` whose next record of the same name is an `end` at the
|
||||
same or a later offset. Every other record of such a name is counted as an exception.
|
||||
|
||||
| Name | Tags | `start` | `end` | Pairs | Not paired | Pair length in samples (min / median / max) |
|
||||
|---|---:|---:|---:|---:|---|---:|
|
||||
| `0xda559149` | 22 | 196 | 197 | 196 | 1 `end` | 172,602 / 857,823 / 3,899,077 |
|
||||
| `0x1df219ec` | 1 | 101 | 101 | 101 | none | 25,289 / 95,237 / 497,606 |
|
||||
| `0x77edd3a2` | 1 | 54 | 54 | 53 | 1 `start`, 1 `end`, the record with the third value | 44,984 / 90,546 / 209,958 |
|
||||
| `0x994ee645` | 1 | 49 | 49 | 49 | none | 22,233 / 93,644 / 212,156 |
|
||||
| `0xccb465d1` | 1 | 20 | 19 | 19 | 1 `start` | 36,146 / 92,928 / 186,375 |
|
||||
| **Total** | **22** | **420** | **420** | **418** | **5 records** | |
|
||||
|
||||
So the reading holds for 418 pairs, and equal counts did not prove it: the 54/54 name has two unpaired records.
|
||||
20 of the 22 tags pair completely (a tag holds 1 to 181 pairs, median 3). The five exceptions sit in two tags:
|
||||
|
||||
- `0xda559149` has a second `end` 16,717 samples after the `end` that closes the region before it (record 744 of
|
||||
its tag's 1,435). Nothing opens it.
|
||||
- A `0x77edd3a2` `start` (record 40 of 834) is followed, 118,171 samples later, by a record of the same name whose
|
||||
value is `0xdaa2d5ec`, the only value on these names that is neither word. Hypothesis: that record closes the
|
||||
region under another word; the distance is inside the name's pair lengths.
|
||||
- A `0xccb465d1` `start` (record 773 of the same tag, the last record of its name) is directly followed by a
|
||||
`0x77edd3a2` `end` that no `start` opens (record 774), 114,697 samples later. Hypothesis: one region whose two
|
||||
records carry different names; the distance is inside the pair lengths of both.
|
||||
|
||||
If both hypotheses hold, every one of the 420 `start` records has a closing record and only the second `end`
|
||||
is left over. None of the five is a region left open at an edge of its tag: none is the tag's first or last
|
||||
record, the nearest to an edge is 40 records in, and the unclosed `0xccb465d1` `start` is 18,219,408 samples
|
||||
before its tag's last offset.
|
||||
|
||||
Also measured on the 418 pairs:
|
||||
|
||||
- No pair has a zero length, and `extra` is the same on a pair's two records (418 / 418).
|
||||
- Regions of one name cannot overlap under this matching; an overlap would show as an unpaired `start` followed
|
||||
by a `start`, and there is none. Regions of different names do overlap: 54 pairs of regions share samples, 43
|
||||
with one region inside the other and 11 crossing (each starts or ends inside the other). All 54 are between
|
||||
`0xda559149` and one of the other four names (`0x1df219ec` 13 inside / 7 crossing, `0x77edd3a2` 19 / 4,
|
||||
`0x994ee645` 2 / 0, `0xccb465d1` 9 / 0); the other four never overlap each other. So a sample can lie in
|
||||
regions of two names at once.
|
||||
- None of the 22 streams has a `0x76` tag (`tags_with_sample_count` is 0), so this parser has no sample count to
|
||||
compare a region's end with.
|
||||
|
||||
The other three archives with `ADAT` banks have `0xbd` tags as well (226,788 in `story000.rpf`, 1,959 in
|
||||
`shared_minigame000.rpf`, 22 in `story000_restofworld.rpf`) and not one record with either value.
|
||||
|
||||
Not known: the words behind the five names and behind `0xdaa2d5ec`, what a region does in the game, and whether
|
||||
the two hypotheses above are right. The lengths are in the unit of `offset`; they were not converted to seconds,
|
||||
because the rate of these 22 streams is not read here.
|
||||
|
||||
## Binary format of `RSC8` (version `8001`)
|
||||
|
||||
All integers and IEEE-754 floats are little-endian. Every `RSC8` tag payload is 16-byte aligned.
|
||||
@ -368,6 +422,10 @@ python -I tools/rsc8_audio.py <package>\pack\shared_minigame000\shared_minigame0
|
||||
python -I tools/rsc8_audio.py <package>\pack\story000\story000.rpf --summary-only
|
||||
python -I tools/rsc8_audio.py <package>\audio.rpf --summary-only
|
||||
|
||||
# Every summary also has the cue counts (marker_* keys) and the region pairing (marker_regions): pairs and
|
||||
# exceptions per name hash, pair lengths, overlaps between names and where each exception sits in its tag.
|
||||
# The numbers of "Region cues" above are the audio.rpf summary's (57 to 87 s over three runs of the 28.5 GB archive).
|
||||
|
||||
# Also decode every clip's keyframes and count the outcome (slower: about 40 clips per second per process;
|
||||
# split a large archive with --start/--limit and add the summaries)
|
||||
python -I tools/rsc8_audio.py <package>\pack\shared_minigame000\shared_minigame000.rpf --summary-only --curves
|
||||
|
||||
@ -6,6 +6,7 @@ import contextlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
@ -68,6 +69,67 @@ def speech_bank(sid, samples, marker_chunk, payload=b"\0" * 64):
|
||||
return build_bank([(sid, [(0x55, payload), (0x76, bytes(fmt)), (0xBD, marker_chunk)])])
|
||||
|
||||
|
||||
class MusicCueSheetTest(unittest.TestCase):
|
||||
def test_failed_cli_rerun_clears_previous_regions(self):
|
||||
from rsc8_audio import MARKER_VALUE_START, MARKER_VALUE_END
|
||||
|
||||
cues = event(1, MARKER_VALUE_START, 10) + event(1, MARKER_VALUE_END, 30)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
src = Path(tmp) / "music.awc"
|
||||
out = Path(tmp) / "out"
|
||||
sheet = out / "music" / "cue_regions.json"
|
||||
args = [sys.executable, "-I", Path(TOOL).with_name("awc_opus.py"), src, out, "--cue-sheet", "--jobs", "1"]
|
||||
for failure in ("parse", "write"):
|
||||
with self.subTest(failure=failure):
|
||||
src.write_bytes(music_bank(7, 200, 0xFC, cues))
|
||||
subprocess.run(args, check=True, capture_output=True)
|
||||
self.assertEqual(json.loads(sheet.read_bytes())["regions"][0]["file"], "00000007.ogg")
|
||||
if failure == "parse":
|
||||
src.write_bytes(b"invalid bank")
|
||||
else:
|
||||
src.write_bytes(music_bank(8, 200, 0xFC, cues))
|
||||
(sheet.parent / "00000008.ogg").mkdir()
|
||||
result = subprocess.run(args, capture_output=True)
|
||||
self.assertEqual(result.returncode, 0 if failure == "parse" else 1)
|
||||
self.assertEqual(json.loads(sheet.read_bytes()), {"sample_rate": 48000, "regions": []})
|
||||
|
||||
def test_exported_frame_coordinates_and_ambiguous_inputs(self):
|
||||
import awc_opus
|
||||
from rsc8_audio import MARKER_VALUE_START as start, MARKER_VALUE_END as end, parse_adat_header_bytes
|
||||
|
||||
cues = (event(1, start, 10) + event(2, start, 20) + event(1, end, 30)
|
||||
+ event(2, end, 40) + event(3, start, 60) + event(3, end, 500))
|
||||
bank = music_bank(7, 200, 0xFC, cues) # 100 frames of stereo
|
||||
header = parse_adat_header_bytes(bank, 0, len(bank))
|
||||
entries = [(sid, [(kind, bank[off:off + size]) for kind, off, size in tags])
|
||||
for sid, tags in header["entries"]]
|
||||
desc, data = [blob for _, blob in entries[0][1]]
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
src = os.path.join(tmp, "music.awc")
|
||||
out = os.path.join(tmp, "out")
|
||||
sheet = os.path.join(out, "music", "cue_regions.json")
|
||||
|
||||
def export(payload, flag=True):
|
||||
with open(src, "wb") as f:
|
||||
f.write(payload)
|
||||
args = [src, out, "--jobs", "1"] + (["--cue-sheet"] if flag else [])
|
||||
self.assertEqual(awc_opus.main(args), 0)
|
||||
if flag:
|
||||
with open(sheet, encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
|
||||
export(bank, False)
|
||||
self.assertFalse(os.path.exists(sheet))
|
||||
self.assertEqual(export(bank), {"sample_rate": 48000, "regions": [
|
||||
{"file": "00000007.ogg", "name_hash": "00000001", "start_sample": 10, "end_sample": 30},
|
||||
{"file": "00000007.ogg", "name_hash": "00000002", "start_sample": 20, "end_sample": 40}]})
|
||||
self.assertTrue(os.path.isfile(os.path.join(out, "music", "00000007.ogg")))
|
||||
for ambiguous in (entries + [entries[0]], entries + [entries[1]],
|
||||
[(0, [(0x48, desc), (0x55, bytes(len(data)))]), entries[1]],
|
||||
[entries[0], (9, entries[1][1])]):
|
||||
self.assertEqual(export(build_bank(ambiguous))["regions"], [])
|
||||
|
||||
|
||||
class EventLayoutTest(unittest.TestCase):
|
||||
def test_sixteen_byte_events_and_a_dropped_tail(self):
|
||||
chunk = event(TRACK, 1234.0, 0) + event(TICK, 8.0, 48000, 5) + b"\x01\x02\x03"
|
||||
|
||||
@ -1382,5 +1382,273 @@ class MarkerRecordsTest(unittest.TestCase):
|
||||
self.assertTrue(comp["markers"]["offsets_within_samples"])
|
||||
|
||||
|
||||
def build_synthetic_region_markers(records):
|
||||
"""16-byte cue records with the value as a u32 word, as a region cue stores it: name, value, offset, extra."""
|
||||
return b"".join(struct.pack("<IIII", *record) for record in records)
|
||||
|
||||
|
||||
class MarkerRegionsTest(unittest.TestCase):
|
||||
"""Region cues matched into start/end pairs record by record (ASSET-320). The names are made up."""
|
||||
S, E = _joaat("start"), _joaat("end")
|
||||
VERSE, FILL, BEAT = 0x11111111, 0x22222222, _joaat("beat")
|
||||
FMT = struct.pack("<I", 96000) + bytes(4) + struct.pack("<H", 48000) + bytes(18) + b"\x0B\x01"
|
||||
|
||||
def pair(self, records):
|
||||
return rsc8_audio.pair_marker_regions(rsc8_audio.marker_records(build_synthetic_region_markers(records)))
|
||||
|
||||
def kinds(self, paired):
|
||||
return [(e["kind"], e["index"], e["before"], e["after"]) for e in paired["exceptions"]]
|
||||
|
||||
def check_sums(self, paired):
|
||||
for counts in paired["names"].values():
|
||||
self.assertEqual(counts["starts"],
|
||||
counts["pairs"] + counts["start_without_end"] + counts["end_before_start"])
|
||||
self.assertEqual(counts["ends"], counts["pairs"] + counts["end_without_start"] + counts["end_before_start"])
|
||||
|
||||
def test_value_words_are_the_hashes_of_start_and_end(self):
|
||||
self.assertEqual(rsc8_audio.MARKER_VALUE_START, self.S)
|
||||
self.assertEqual(rsc8_audio.MARKER_VALUE_END, self.E)
|
||||
|
||||
def test_marker_records_are_the_whole_records(self):
|
||||
blob = build_synthetic_region_markers([(self.VERSE, self.S, 100, 0), (self.VERSE, self.E, 200, 1)])
|
||||
self.assertEqual(rsc8_audio.marker_records(blob), [(self.VERSE, self.S, 100, 0), (self.VERSE, self.E, 200, 1)])
|
||||
self.assertEqual(len(rsc8_audio.marker_records(blob[:-1])), 1)
|
||||
self.assertEqual(rsc8_audio.marker_records(b""), [])
|
||||
|
||||
def test_well_formed_pairs(self):
|
||||
p = self.pair([
|
||||
(self.BEAT, struct.unpack("<I", struct.pack("<f", 4.0))[0], 0, 0), # not a region cue: ignored
|
||||
(self.VERSE, self.S, 100, 0),
|
||||
(self.VERSE, self.E, 200, 0),
|
||||
(self.VERSE, self.S, 200, 0), # starts where the last one ended
|
||||
(self.BEAT, struct.unpack("<I", struct.pack("<f", 8.0))[0], 200, 0),
|
||||
(self.VERSE, self.E, 200, 0), # a zero-length region is still a pair
|
||||
(self.VERSE, self.S, 300, 2),
|
||||
(self.VERSE, self.E, 900, 3),
|
||||
])
|
||||
self.assertEqual(p["exceptions"], [])
|
||||
self.assertEqual(list(p["names"]), [self.VERSE])
|
||||
self.assertEqual(p["names"][self.VERSE], {
|
||||
"starts": 3, "ends": 3, "other_value": 0, "pairs": 3,
|
||||
"start_without_end": 0, "end_without_start": 0, "end_before_start": 0,
|
||||
})
|
||||
self.assertEqual([(r["start"], r["end"], r["start_index"], r["end_index"]) for r in p["regions"]],
|
||||
[(100, 200, 1, 2), (200, 200, 3, 5), (300, 900, 6, 7)])
|
||||
self.assertEqual([r["extra_differs"] for r in p["regions"]], [False, False, True])
|
||||
self.check_sums(p)
|
||||
# A tag without a start/end value has no region name at all.
|
||||
self.assertEqual(self.pair([(self.BEAT, 0, 0, 0), (self.VERSE, 0x33333333, 5, 0)]),
|
||||
{"regions": [], "exceptions": [], "names": {}})
|
||||
|
||||
def test_unmatched_start(self):
|
||||
p = self.pair([(self.VERSE, self.S, 100, 0), (self.VERSE, self.E, 200, 0), (self.VERSE, self.S, 300, 0)])
|
||||
self.assertEqual(len(p["regions"]), 1)
|
||||
self.assertEqual(self.kinds(p), [("start_without_end", 2, "end", None)]) # open at the end of the tag
|
||||
self.assertEqual(p["exceptions"][0], {
|
||||
"kind": "start_without_end", "name": self.VERSE, "value": self.S, "index": 2, "offset": 300,
|
||||
"before": "end", "before_offset": 200, "after": None, "after_offset": None,
|
||||
})
|
||||
self.check_sums(p)
|
||||
|
||||
def test_unmatched_end(self):
|
||||
p = self.pair([(self.VERSE, self.E, 50, 0), (self.VERSE, self.S, 100, 0), (self.VERSE, self.E, 200, 0),
|
||||
(self.VERSE, self.E, 250, 0)])
|
||||
self.assertEqual([(r["start"], r["end"]) for r in p["regions"]], [(100, 200)])
|
||||
self.assertEqual(self.kinds(p), [("end_without_start", 0, None, "start"), # open at the start of the tag
|
||||
("end_without_start", 3, "end", None)]) # a second end
|
||||
self.check_sums(p)
|
||||
|
||||
def test_end_before_its_start(self):
|
||||
# In record order: the end comes first, so neither record has a partner.
|
||||
p = self.pair([(self.VERSE, self.E, 100, 0), (self.VERSE, self.S, 200, 0)])
|
||||
self.assertEqual(p["regions"], [])
|
||||
self.assertEqual(self.kinds(p), [("end_without_start", 0, None, "start"),
|
||||
("start_without_end", 1, "end", None)])
|
||||
self.check_sums(p)
|
||||
# In offsets: the end follows its start but lies before it. The pair is refused, once.
|
||||
p = self.pair([(self.VERSE, self.S, 500, 0), (self.VERSE, self.E, 400, 0), (self.VERSE, self.S, 600, 0),
|
||||
(self.VERSE, self.E, 600, 0)])
|
||||
self.assertEqual([(r["start"], r["end"]) for r in p["regions"]], [(600, 600)])
|
||||
self.assertEqual(self.kinds(p), [("end_before_start", 1, "start", "start")])
|
||||
self.assertEqual(p["names"][self.VERSE]["end_before_start"], 1)
|
||||
self.assertEqual(p["names"][self.VERSE]["start_without_end"], 0)
|
||||
self.check_sums(p)
|
||||
|
||||
def test_nesting_in_one_name_is_not_paired_inside_out(self):
|
||||
p = self.pair([(self.VERSE, self.S, 100, 0), (self.VERSE, self.S, 200, 0), (self.VERSE, self.E, 300, 0),
|
||||
(self.VERSE, self.E, 400, 0)])
|
||||
self.assertEqual([(r["start"], r["end"]) for r in p["regions"]], [(200, 300)])
|
||||
self.assertEqual(self.kinds(p), [("start_without_end", 0, None, "start"),
|
||||
("end_without_start", 3, "end", None)])
|
||||
self.check_sums(p)
|
||||
|
||||
def test_two_names_interleaved(self):
|
||||
p = self.pair([
|
||||
(self.VERSE, self.S, 100, 0),
|
||||
(self.FILL, self.S, 150, 0),
|
||||
(self.VERSE, self.E, 200, 0), # VERSE 100..200 and FILL 150..250 cross
|
||||
(self.FILL, self.E, 250, 0),
|
||||
(self.VERSE, self.S, 300, 0),
|
||||
(self.FILL, self.S, 300, 0),
|
||||
(self.FILL, self.E, 350, 0), # FILL 300..350 inside VERSE 300..400, same start
|
||||
(self.VERSE, self.E, 400, 0),
|
||||
(self.FILL, self.S, 400, 0), # FILL 400..450 only touches VERSE 300..400
|
||||
(self.FILL, self.E, 450, 0),
|
||||
(self.VERSE, self.S, 500, 0),
|
||||
(self.FILL, self.S, 520, 0),
|
||||
(self.FILL, self.E, 520, 0), # a zero-length region shares no sample
|
||||
(self.FILL, self.S, 530, 0),
|
||||
(self.FILL, self.E, 600, 0), # FILL 530..600 inside VERSE 500..600, same end
|
||||
(self.VERSE, self.E, 600, 0),
|
||||
])
|
||||
self.assertEqual(p["exceptions"], [])
|
||||
self.assertEqual(p["names"][self.VERSE]["pairs"], 3)
|
||||
self.assertEqual(p["names"][self.FILL]["pairs"], 5)
|
||||
self.assertEqual([r["start_index"] for r in p["regions"]], [0, 1, 4, 5, 8, 10, 11, 13])
|
||||
# {(smaller hash, larger hash): [nested, crossing]}
|
||||
self.assertEqual(rsc8_audio.marker_region_overlaps(p["regions"]), {(self.VERSE, self.FILL): [2, 1]})
|
||||
# Each name's regions alone overlap nothing.
|
||||
for name in (self.VERSE, self.FILL):
|
||||
own = [r for r in p["regions"] if r["name"] == name]
|
||||
self.assertEqual(rsc8_audio.marker_region_overlaps(own), {})
|
||||
self.check_sums(p)
|
||||
|
||||
def test_a_third_value_opens_and_closes_nothing(self):
|
||||
other = 0x44444444
|
||||
p = self.pair([(self.VERSE, self.S, 100, 0), (self.VERSE, other, 150, 0), (self.VERSE, self.E, 200, 0),
|
||||
(self.VERSE, self.S, 300, 0), (self.VERSE, self.E, 400, 0)])
|
||||
self.assertEqual([(r["start"], r["end"]) for r in p["regions"]], [(300, 400)])
|
||||
self.assertEqual(self.kinds(p), [("start_without_end", 0, None, "other"),
|
||||
("other_value", 1, "start", "end"),
|
||||
("end_without_start", 2, "other", "start")])
|
||||
self.assertEqual(p["exceptions"][1]["value"], other)
|
||||
self.assertEqual(p["names"][self.VERSE]["other_value"], 1)
|
||||
self.check_sums(p)
|
||||
|
||||
def region_bank(self, sid, records, fmt=True):
|
||||
tags = {0x55: b"\xF8\x00" + bytes(62), 0xBD: build_synthetic_region_markers(records)}
|
||||
if fmt:
|
||||
tags[0x76] = self.FMT
|
||||
return build_minimal_tag_bank(sid, tags)
|
||||
|
||||
def test_bank_tally_and_scan_summary(self):
|
||||
clean = self.region_bank(0x00112233, [
|
||||
(self.VERSE, self.S, 100, 0), (self.FILL, self.S, 150, 0), (self.VERSE, self.E, 200, 0),
|
||||
(self.FILL, self.E, 450, 0), (self.VERSE, self.S, 1000, 0), (self.VERSE, self.E, 1700, 1),
|
||||
])
|
||||
ragged = self.region_bank(0x00445566, [
|
||||
(self.BEAT, 0, 0, 0), (self.FILL, self.E, 10, 0), (self.FILL, self.S, 20, 0), (self.FILL, self.E, 60, 0),
|
||||
(self.FILL, self.S, 90, 0),
|
||||
], fmt=False)
|
||||
plain = self.region_bank(0x00778899, [(self.BEAT, 0, 0, 0), (self.BEAT, 0, 100, 0)])
|
||||
# Offsets that decrease make the tag invalid; its records are not paired.
|
||||
broken = self.region_bank(0x00AABBCC, [(self.VERSE, self.S, 500, 0), (self.VERSE, self.E, 400, 0)])
|
||||
|
||||
res = rsc8_audio.decode_awc_bank(clean)
|
||||
rep = rsc8_audio.marker_region_report(res["marker_regions"])
|
||||
self.assertEqual((rep["tags"], rep["tags_all_paired"], rep["tags_with_sample_count"]), (1, 1, 1))
|
||||
self.assertEqual((rep["starts"], rep["ends"], rep["pairs"]), (3, 3, 3))
|
||||
self.assertEqual(rep["pairs_per_tag"], {"min": 3, "median": 3, "max": 3})
|
||||
self.assertEqual(rep["pairs_extra_differs"], 1)
|
||||
both = f"0x{self.VERSE:08x}+0x{self.FILL:08x}"
|
||||
self.assertEqual(rep["overlaps_between_names"], {
|
||||
"nested": 0, "crossing": 1, "by_names": {both: {"nested": 0, "crossing": 1}},
|
||||
})
|
||||
self.assertEqual(list(rep["names"]), [f"0x{self.VERSE:08x}", f"0x{self.FILL:08x}"]) # most records first
|
||||
self.assertEqual(rep["names"][f"0x{self.VERSE:08x}"], {
|
||||
"tags": 1, "starts": 2, "ends": 2, "other_value": 0, "pairs": 2,
|
||||
"start_without_end": 0, "end_without_start": 0, "end_before_start": 0,
|
||||
"length_samples": {"min": 100, "median": 400, "max": 700},
|
||||
})
|
||||
self.assertEqual((rep["exceptions_total"], rep["exceptions"]), (0, []))
|
||||
self.assertEqual(rsc8_audio.decode_awc_bank(plain)["marker_regions"]["tags"], 0)
|
||||
res_broken = rsc8_audio.decode_awc_bank(broken)
|
||||
self.assertEqual((res_broken["marker_invalid"], res_broken["marker_regions"]["tags"]), (1, 0))
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
rpf = os.path.join(tmp, "synth.rpf")
|
||||
offsets = []
|
||||
with open(rpf, "wb") as f:
|
||||
f.write(b"9FPR" + struct.pack("<III", 0x100, 0, 0) + bytes(0xF0))
|
||||
for bank in (clean, ragged, plain, broken, clean):
|
||||
offsets.append(f.tell())
|
||||
f.write(bank)
|
||||
f.write(bytes(0x40))
|
||||
_records, summary = rsc8_audio.scan_rpf(rpf)
|
||||
self.assertEqual((summary["marker_streams"], summary["marker_invalid"]), (5, 1))
|
||||
rep = summary["marker_regions"]
|
||||
self.assertEqual((rep["tags"], rep["tags_all_paired"], rep["tags_with_sample_count"]), (3, 2, 2))
|
||||
self.assertEqual((rep["starts"], rep["ends"], rep["pairs"]), (8, 8, 7))
|
||||
self.assertEqual(rep["pairs_per_tag"], {"min": 1, "median": 3, "max": 3})
|
||||
self.assertEqual(rep["overlaps_between_names"], {
|
||||
"nested": 0, "crossing": 2, "by_names": {both: {"nested": 0, "crossing": 2}},
|
||||
})
|
||||
self.assertEqual(rep["names"][f"0x{self.FILL:08x}"], {
|
||||
"tags": 3, "starts": 4, "ends": 4, "other_value": 0, "pairs": 3,
|
||||
"start_without_end": 1, "end_without_start": 1, "end_before_start": 0,
|
||||
"length_samples": {"min": 40, "median": 300, "max": 300},
|
||||
})
|
||||
self.assertEqual(rep["exceptions_total"], 2)
|
||||
self.assertEqual(rep["exceptions"], [
|
||||
{"kind": "end_without_start", "name": f"0x{self.FILL:08x}", "value": f"0x{self.E:08x}",
|
||||
"before": None, "before_offset": None, "after": "start", "after_offset": 20,
|
||||
"record": 1, "tag_records": 5, "offset": 10,
|
||||
"tag_last_offset": 90, "stream_samples": None, "bank_offset": offsets[1],
|
||||
"stream_id": "0x00445566"},
|
||||
{"kind": "start_without_end", "name": f"0x{self.FILL:08x}", "value": f"0x{self.S:08x}",
|
||||
"before": "end", "before_offset": 60, "after": None, "after_offset": None,
|
||||
"record": 4, "tag_records": 5, "offset": 90,
|
||||
"tag_last_offset": 90, "stream_samples": None, "bank_offset": offsets[1],
|
||||
"stream_id": "0x00445566"},
|
||||
])
|
||||
|
||||
# The list of exceptions is capped; the counts are not.
|
||||
old_cap = rsc8_audio.MAX_REGION_EXCEPTIONS_LISTED
|
||||
try:
|
||||
rsc8_audio.MAX_REGION_EXCEPTIONS_LISTED = 1
|
||||
_records, capped = rsc8_audio.scan_rpf(rpf)
|
||||
finally:
|
||||
rsc8_audio.MAX_REGION_EXCEPTIONS_LISTED = old_cap
|
||||
self.assertEqual(capped["marker_regions"]["exceptions_total"], 2)
|
||||
self.assertEqual(capped["marker_regions"]["exceptions"], rep["exceptions"][:1])
|
||||
|
||||
# Directory and single-bank scans report the same block; the CLI writes it as JSON.
|
||||
os.remove(rpf)
|
||||
for i, bank in enumerate((clean, ragged, plain, broken, clean)):
|
||||
with open(os.path.join(tmp, f"bank{i}.awc"), "wb") as f:
|
||||
f.write(bank)
|
||||
out_json = os.path.join(tmp, "report.json")
|
||||
cp = subprocess.run(
|
||||
[sys.executable, "-I", TOOL, tmp, out_json, "--summary-only", "--quiet"],
|
||||
capture_output=True, text=True,
|
||||
)
|
||||
self.assertEqual(cp.returncode, 0, cp.stderr)
|
||||
with open(out_json, encoding="utf-8") as f:
|
||||
from_dir = json.load(f)["summary"]["marker_regions"]
|
||||
self.assertEqual(json.loads(cp.stdout)["marker_regions"], from_dir)
|
||||
for entry in from_dir["exceptions"]:
|
||||
self.assertEqual(entry.pop("bank_offset"), 0)
|
||||
for entry in rep["exceptions"]:
|
||||
entry.pop("bank_offset")
|
||||
self.assertEqual(from_dir, rep)
|
||||
_records, single = rsc8_audio.scan_single_file(os.path.join(tmp, "bank1.awc"))
|
||||
self.assertEqual((single["marker_regions"]["pairs"], single["marker_regions"]["exceptions_total"]), (1, 2))
|
||||
self.assertEqual(single["marker_regions"]["names"][f"0x{self.FILL:08x}"]["length_samples"],
|
||||
{"min": 40, "median": 40, "max": 40})
|
||||
|
||||
def test_a_scan_without_region_cues_reports_an_empty_block(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
rsc_path = os.path.join(tmp, "only.rsc8")
|
||||
with open(rsc_path, "wb") as f:
|
||||
f.write(build_synthetic_rsc8(stream_hash=0x11112222, frames=45))
|
||||
_records, summary = rsc8_audio.scan_single_file(rsc_path)
|
||||
self.assertEqual(summary["marker_regions"], {
|
||||
"tags": 0, "tags_all_paired": 0, "tags_with_sample_count": 0, "starts": 0, "ends": 0, "pairs": 0,
|
||||
"pairs_per_tag": None, "pairs_extra_differs": 0,
|
||||
"overlaps_between_names": {"nested": 0, "crossing": 0, "by_names": {}},
|
||||
"names": {}, "exceptions_total": 0, "exceptions": [],
|
||||
})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@ -30,6 +30,8 @@ Usage: `python -I tools/awc_opus.py --help` lists the options.
|
||||
"""
|
||||
import argparse
|
||||
import functools
|
||||
import json
|
||||
from collections import Counter
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
@ -39,6 +41,7 @@ from concurrent.futures import ProcessPoolExecutor, as_completed
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from file_mode import new_file_mode, published_mode # noqa: E402
|
||||
from pool_workers import process_workers # noqa: E402
|
||||
from rsc8_audio import decode_marker_records, marker_records, pair_marker_regions, parse_adat_header_bytes
|
||||
from report_paths import path_key # noqa: E402
|
||||
|
||||
# ---- Ogg ----
|
||||
@ -344,19 +347,61 @@ def bank_output_dir(path, out_dir):
|
||||
return os.path.join(out_dir, name)
|
||||
|
||||
|
||||
def export_bank(path: str, out_dir: str, pre_skip: int = OPUS_PRE_SKIP):
|
||||
def music_cue_regions(data, frame_limits):
|
||||
"""Join a unique marker stream-table entry to a unique exported music channel in this bank."""
|
||||
if not frame_limits:
|
||||
return []
|
||||
bank = parse_adat_header_bytes(data, 0, len(data))
|
||||
if bank is None:
|
||||
return []
|
||||
entries = bank["entries"]
|
||||
occurrences = Counter(sid for sid, _ in entries)
|
||||
rows = []
|
||||
for sid, tags in entries:
|
||||
if sid not in frame_limits or occurrences[sid] != 1:
|
||||
continue
|
||||
for kind, offset, size in tags:
|
||||
if kind != 0xBD:
|
||||
continue
|
||||
blob = data[offset:offset + size]
|
||||
if not decode_marker_records(blob)["offsets_ascending"]:
|
||||
continue
|
||||
for region in pair_marker_regions(marker_records(blob))["regions"]:
|
||||
if region["end"] <= frame_limits[sid]:
|
||||
rows.append({"file": f"{sid:08X}.ogg", "name_hash": f"{region['name']:08X}",
|
||||
"start_sample": region["start"], "end_sample": region["end"]})
|
||||
return rows
|
||||
|
||||
|
||||
def write_cue_sheet(sheet, rows):
|
||||
payload = {"sample_rate": 48000, "regions": rows}
|
||||
write_file(sheet, (json.dumps(payload, indent=2) + "\n").encode("utf-8"))
|
||||
|
||||
|
||||
def export_bank(path: str, out_dir: str, pre_skip: int = OPUS_PRE_SKIP, cue_sheet: bool = False):
|
||||
od = bank_output_dir(path, out_dir)
|
||||
if cue_sheet:
|
||||
sheet = os.path.join(od, "cue_regions.json")
|
||||
if os.path.exists(sheet):
|
||||
# A skipped bank or interrupted channel write must not leave last run's regions current.
|
||||
write_cue_sheet(sheet, [])
|
||||
with open(path, "rb") as f:
|
||||
d = f.read()
|
||||
streams, music = parse_awc(d)
|
||||
od = bank_output_dir(path, out_dir)
|
||||
os.makedirs(od, exist_ok=True)
|
||||
counts = {"opus": 0, "pcm": 0, "other": 0, "music": 0}
|
||||
channel_counts = Counter()
|
||||
frame_limits = {}
|
||||
for mus, data in music:
|
||||
for cid, samples, rate, codec, pk, packet_channels in music_channels(d, mus, data):
|
||||
if cue_sheet:
|
||||
channel_counts[cid] += 1
|
||||
if pk:
|
||||
n48 = samples * 48000 // rate if rate else 0
|
||||
write_ogg_opus(os.path.join(od, f"{cid:08X}.ogg"), pk, packet_channels, cid, n48,
|
||||
pre_skip=pre_skip)
|
||||
granule = write_ogg_opus(os.path.join(od, f"{cid:08X}.ogg"), pk, packet_channels, cid, n48,
|
||||
pre_skip=pre_skip)
|
||||
if cue_sheet and rate == 48000 and samples > 0:
|
||||
frame_limits[cid] = min(samples, max(0, granule - pre_skip))
|
||||
counts["music"] += 1
|
||||
for s, stem in zip(streams, export_stems([s["id"] for s in streams])):
|
||||
at, size = s["data"]
|
||||
@ -384,6 +429,13 @@ def export_bank(path: str, out_dir: str, pre_skip: int = OPUS_PRE_SKIP):
|
||||
counts["pcm"] += 1
|
||||
continue
|
||||
counts["other"] += 1
|
||||
if cue_sheet:
|
||||
for stream in streams:
|
||||
frame_limits.pop(stream["id"], None)
|
||||
verified = {cid: limit for cid, limit in frame_limits.items() if channel_counts[cid] == 1}
|
||||
rows = music_cue_regions(d, verified)
|
||||
if rows:
|
||||
write_cue_sheet(sheet, rows)
|
||||
return counts
|
||||
|
||||
|
||||
@ -391,6 +443,7 @@ def main(argv=None) -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("src")
|
||||
ap.add_argument("out")
|
||||
ap.add_argument("--cue-sheet", action="store_true", help="write paired music cues beside their Ogg files")
|
||||
ap.add_argument("--limit", type=int, help="maximum number of banks to export (default: all)")
|
||||
ap.add_argument("--jobs", type=int, default=max(1, (os.cpu_count() or 2) // 2),
|
||||
help="banks to export at once (default: half the CPU count)")
|
||||
@ -454,7 +507,7 @@ def main(argv=None) -> int:
|
||||
if jobs == 1:
|
||||
for i, (b, output_parent) in enumerate(banks):
|
||||
try:
|
||||
add(export_bank(b, output_parent, a.pre_skip))
|
||||
add(export_bank(b, output_parent, a.pre_skip, a.cue_sheet))
|
||||
except (ValueError, struct.error, IndexError, OSError) as e:
|
||||
skipped(b, e)
|
||||
continue
|
||||
@ -462,7 +515,7 @@ def main(argv=None) -> int:
|
||||
print(f" {i + 1}/{len(banks)} banks: {tot}", flush=True)
|
||||
else:
|
||||
with ProcessPoolExecutor(max_workers=process_workers(jobs)) as ex:
|
||||
futures = {ex.submit(export_bank, b, output_parent, a.pre_skip): b for b, output_parent in banks}
|
||||
futures = {ex.submit(export_bank, b, output_parent, a.pre_skip, a.cue_sheet): b for b, output_parent in banks}
|
||||
for i, fut in enumerate(as_completed(futures), 1):
|
||||
b = futures[fut]
|
||||
try:
|
||||
|
||||
@ -25,12 +25,17 @@ Usage:
|
||||
|
||||
`--curves` also decodes every clip's keyframes (the blocks are the sequence layout of
|
||||
tools/anim_clips.py) and counts the outcome; it reports counts only, never a value.
|
||||
|
||||
Every scan also reads the `0xbd` cue records of each stream; the summary's `marker_regions` block
|
||||
matches the records whose value is joaat("start") or joaat("end") into region pairs, name by name
|
||||
(pair_marker_regions(), docs/rsc8_audio.md).
|
||||
"""
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import statistics
|
||||
import struct
|
||||
import sys
|
||||
import tempfile
|
||||
@ -68,6 +73,11 @@ MARKER_NAME_COMMON = 0xE5C74063
|
||||
MARKER_MAGIC = MARKER_NAME_COMMON
|
||||
MARKER_RECORD_BYTES = 16
|
||||
MAX_MARKER_BYTES = 16 * 1024 * 1024
|
||||
# A region cue stores a second name hash in its `value` word (pair_marker_regions()).
|
||||
MARKER_VALUE_START = 0x84DC271F # joaat("start")
|
||||
MARKER_VALUE_END = 0xB0C485D7 # joaat("end")
|
||||
_REGION_VALUES = {MARKER_VALUE_START: "start", MARKER_VALUE_END: "end"}
|
||||
MAX_REGION_EXCEPTIONS_LISTED = 64
|
||||
|
||||
ATTR_FLOAT = 0xFFFF0001
|
||||
ATTR_INT = 0xFFFF0002
|
||||
@ -1035,6 +1045,251 @@ def decode_marker_records(blob, sample_count=None):
|
||||
return out
|
||||
|
||||
|
||||
def marker_records(blob):
|
||||
"""The ``(name, value, offset, extra)`` u32 words of every whole 16-byte record of a ``0xbd`` tag."""
|
||||
raw = bytes(blob)
|
||||
return list(struct.iter_unpack("<IIII", raw[: len(raw) - len(raw) % MARKER_RECORD_BYTES]))
|
||||
|
||||
|
||||
def pair_marker_regions(records):
|
||||
"""Match the region cues of one ``0xbd`` tag into start/end pairs, record by record (ASSET-320).
|
||||
|
||||
`records` is `marker_records()` output. A region record is one whose ``value`` word is
|
||||
`MARKER_VALUE_START` or `MARKER_VALUE_END`, and a name with at least one of them is a region name of
|
||||
this tag. Each region name's records are walked in stored order, and a pair is a ``start`` whose
|
||||
next record of the same name is an ``end`` at the same or a later offset. Every other record of a
|
||||
region name is one exception:
|
||||
|
||||
- ``start_without_end``: the next record of the name is not an ``end``, or there is none;
|
||||
- ``end_without_start``: the record of the name before it is not a ``start``, or there is none;
|
||||
- ``end_before_start``: an ``end`` right after a ``start`` but at a smaller offset (the pair is refused
|
||||
and the ``start`` is counted here, not as ``start_without_end``);
|
||||
- ``other_value``: the name also has a record whose value is neither word; it opens and closes nothing.
|
||||
|
||||
So per name ``starts == pairs + start_without_end + end_before_start`` and
|
||||
``ends == pairs + end_without_start + end_before_start``. Two regions of one name therefore never
|
||||
nest or overlap by construction; what would be a nested region shows up as a ``start_without_end``
|
||||
followed by a ``start`` and an ``end_without_start`` preceded by an ``end``.
|
||||
|
||||
Returns ``{"regions": [...], "exceptions": [...], "names": {name: counts}}`` with a region as
|
||||
``{"name", "start", "end", "start_index", "end_index", "extra_differs"}`` (offsets in samples,
|
||||
indices into `records`) and an exception as ``{"kind", "name", "value", "index", "offset",
|
||||
"before", "before_offset", "after", "after_offset"}``, where ``before`` and ``after`` say what the
|
||||
neighbouring records of the same name are (``"start"``, ``"end"``, ``"other"``, or ``None`` when
|
||||
the record is the name's first or last of the tag) and the two offsets are theirs.
|
||||
"""
|
||||
out = {"regions": [], "exceptions": [], "names": {}}
|
||||
if not any(value in _REGION_VALUES for _name, value, _offset, _extra in records):
|
||||
return out
|
||||
by_name = {}
|
||||
for index, (name, value, offset, extra) in enumerate(records):
|
||||
by_name.setdefault(name, []).append((index, value, offset, extra))
|
||||
for name, rows in by_name.items():
|
||||
kinds = [_REGION_VALUES.get(value, "other") for _index, value, _offset, _extra in rows]
|
||||
if "start" not in kinds and "end" not in kinds:
|
||||
continue
|
||||
counts = {"starts": 0, "ends": 0, "other_value": 0, "pairs": 0,
|
||||
"start_without_end": 0, "end_without_start": 0, "end_before_start": 0}
|
||||
|
||||
def refuse(kind, k):
|
||||
index, value, offset, _extra = rows[k]
|
||||
counts[kind] += 1
|
||||
out["exceptions"].append({
|
||||
"kind": kind, "name": name, "value": value, "index": index, "offset": offset,
|
||||
"before": kinds[k - 1] if k else None,
|
||||
"before_offset": rows[k - 1][2] if k else None,
|
||||
"after": kinds[k + 1] if k + 1 < len(kinds) else None,
|
||||
"after_offset": rows[k + 1][2] if k + 1 < len(kinds) else None,
|
||||
})
|
||||
|
||||
opened = None # position in `rows` of a start that no record has followed yet
|
||||
for k, (index, _value, offset, extra) in enumerate(rows):
|
||||
kind = kinds[k]
|
||||
if kind != "end" and opened is not None:
|
||||
refuse("start_without_end", opened)
|
||||
opened = None
|
||||
if kind == "start":
|
||||
counts["starts"] += 1
|
||||
opened = k
|
||||
elif kind == "end":
|
||||
counts["ends"] += 1
|
||||
if opened is None:
|
||||
refuse("end_without_start", k)
|
||||
elif offset < rows[opened][2]:
|
||||
refuse("end_before_start", k)
|
||||
else:
|
||||
start_index, _v, start, start_extra = rows[opened]
|
||||
counts["pairs"] += 1
|
||||
out["regions"].append({
|
||||
"name": name, "start": start, "end": offset, "start_index": start_index,
|
||||
"end_index": index, "extra_differs": extra != start_extra,
|
||||
})
|
||||
opened = None
|
||||
else:
|
||||
refuse("other_value", k)
|
||||
if opened is not None:
|
||||
refuse("start_without_end", opened)
|
||||
out["names"][name] = counts
|
||||
out["regions"].sort(key=lambda r: r["start_index"])
|
||||
out["exceptions"].sort(key=lambda e: e["index"])
|
||||
return out
|
||||
|
||||
|
||||
def marker_region_overlaps(regions):
|
||||
"""How the paired regions of different names in one tag lie against each other.
|
||||
|
||||
Returns ``{(name, other name): [nested, crossing]}`` with the smaller hash first, counting pairs of
|
||||
regions that share at least one sample (``[start, end)``, so a zero-length region and two regions
|
||||
that only touch share none). ``nested`` is one region inside the other (equal bounds included),
|
||||
``crossing`` is each one starting or ending inside the other. `regions` come from one
|
||||
`pair_marker_regions()` call on a tag whose offsets never decrease, where regions of one name
|
||||
cannot overlap, so at most one region per name is open at a time.
|
||||
"""
|
||||
out = {}
|
||||
active = []
|
||||
for region in sorted(regions, key=lambda r: (r["start"], r["start_index"])):
|
||||
if region["end"] <= region["start"]:
|
||||
continue
|
||||
active = [a for a in active if a["end"] > region["start"]]
|
||||
for a in active:
|
||||
if a["name"] == region["name"]:
|
||||
continue
|
||||
counts = out.setdefault((min(a["name"], region["name"]), max(a["name"], region["name"])), [0, 0])
|
||||
nested = region["end"] <= a["end"] or region["start"] == a["start"]
|
||||
counts[0 if nested else 1] += 1
|
||||
active.append(region)
|
||||
return out
|
||||
|
||||
|
||||
def _new_region_tally():
|
||||
"""Running totals of pair_marker_regions() over the tags of a scan; marker_region_report() finishes them."""
|
||||
return {
|
||||
"tags": 0, # tags with at least one start/end record
|
||||
"tags_all_paired": 0, # ... and no exception
|
||||
"tags_with_sample_count": 0, # ... on a stream that has a 0x76 sample count
|
||||
"pairs_per_tag": [],
|
||||
"pairs_extra_differs": 0,
|
||||
"overlaps": {}, # marker_region_overlaps(), added up
|
||||
"names": {}, # name -> the counts of pair_marker_regions(), "tags" and the "lengths" of its pairs
|
||||
"exceptions_total": 0,
|
||||
"exceptions": [], # the first MAX_REGION_EXCEPTIONS_LISTED in scan order
|
||||
}
|
||||
|
||||
|
||||
def _tally_marker_regions(tally, records, *, bank_offset=0, stream_id=None, sample_count=None):
|
||||
"""Add one valid ``0xbd`` tag's region pairing to a `_new_region_tally()`."""
|
||||
paired = pair_marker_regions(records)
|
||||
if not paired["names"]:
|
||||
return
|
||||
tally["tags"] += 1
|
||||
tally["tags_all_paired"] += not paired["exceptions"]
|
||||
tally["tags_with_sample_count"] += sample_count is not None
|
||||
tally["pairs_per_tag"].append(len(paired["regions"]))
|
||||
for name, counts in paired["names"].items():
|
||||
into = tally["names"].setdefault(name, {"tags": 0, "lengths": []})
|
||||
into["tags"] += 1
|
||||
for key, count in counts.items():
|
||||
into[key] = into.get(key, 0) + count
|
||||
for region in paired["regions"]:
|
||||
tally["names"][region["name"]]["lengths"].append(region["end"] - region["start"])
|
||||
tally["pairs_extra_differs"] += region["extra_differs"]
|
||||
_add_region_overlaps(tally["overlaps"], marker_region_overlaps(paired["regions"]))
|
||||
tally["exceptions_total"] += len(paired["exceptions"])
|
||||
for exc in paired["exceptions"]:
|
||||
if len(tally["exceptions"]) >= MAX_REGION_EXCEPTIONS_LISTED:
|
||||
break
|
||||
tally["exceptions"].append({
|
||||
"kind": exc["kind"],
|
||||
"name": f"0x{exc['name']:08x}",
|
||||
"value": f"0x{exc['value']:08x}",
|
||||
"before": exc["before"],
|
||||
"before_offset": exc["before_offset"],
|
||||
"after": exc["after"],
|
||||
"after_offset": exc["after_offset"],
|
||||
"record": exc["index"],
|
||||
"tag_records": len(records),
|
||||
"offset": exc["offset"],
|
||||
"tag_last_offset": records[-1][2],
|
||||
"stream_samples": sample_count,
|
||||
"bank_offset": bank_offset,
|
||||
"stream_id": None if stream_id is None else f"0x{stream_id:08x}",
|
||||
})
|
||||
|
||||
|
||||
def _add_region_overlaps(dst, src):
|
||||
for names, (nested, crossing) in src.items():
|
||||
into = dst.setdefault(names, [0, 0])
|
||||
into[0] += nested
|
||||
into[1] += crossing
|
||||
|
||||
|
||||
def _merge_region_tally(dst, src):
|
||||
for key, value in src.items():
|
||||
if key == "overlaps":
|
||||
_add_region_overlaps(dst[key], value)
|
||||
elif key == "names":
|
||||
for name, counts in value.items():
|
||||
into = dst["names"].setdefault(name, {"tags": 0, "lengths": []})
|
||||
for field, count in counts.items():
|
||||
if field == "lengths":
|
||||
into["lengths"].extend(count)
|
||||
else:
|
||||
into[field] = into.get(field, 0) + count
|
||||
elif key == "exceptions":
|
||||
dst[key].extend(value[: MAX_REGION_EXCEPTIONS_LISTED - len(dst[key])])
|
||||
elif isinstance(value, list):
|
||||
dst[key].extend(value)
|
||||
else:
|
||||
dst[key] += value
|
||||
|
||||
|
||||
def _min_median_max(values):
|
||||
if not values:
|
||||
return None
|
||||
return {"min": min(values), "median": statistics.median(values), "max": max(values)}
|
||||
|
||||
|
||||
def marker_region_report(tally):
|
||||
"""The `marker_regions` block of a scan summary, from a `_new_region_tally()`: counts, sample
|
||||
offsets and 32-bit hashes only.
|
||||
|
||||
``names`` maps each region name (hex) to its ``starts``, ``ends``, ``pairs``, the four exception
|
||||
counts of pair_marker_regions() and the ``length_samples`` (min/median/max) of its pairs.
|
||||
``overlaps_between_names`` counts pairs of paired regions of different names in one tag that share a
|
||||
sample (marker_region_overlaps()), in all and per pair of names. ``exceptions`` lists the first
|
||||
`MAX_REGION_EXCEPTIONS_LISTED` in scan order with where each one sits: its record index among the
|
||||
tag's ``tag_records``, its offset, the tag's last offset, the stream's ``0x76`` sample count when it
|
||||
has one, and what and where the neighbouring records of the same name are (``None``: it is the
|
||||
name's first or last record of the tag). ``exceptions_total`` counts them all.
|
||||
"""
|
||||
names = {}
|
||||
for name, counts in sorted(tally["names"].items(), key=lambda kv: (-kv[1]["starts"] - kv[1]["ends"], kv[0])):
|
||||
row = {key: value for key, value in counts.items() if key != "lengths"}
|
||||
row["length_samples"] = _min_median_max(counts["lengths"])
|
||||
names[f"0x{name:08x}"] = row
|
||||
return {
|
||||
"tags": tally["tags"],
|
||||
"tags_all_paired": tally["tags_all_paired"],
|
||||
"tags_with_sample_count": tally["tags_with_sample_count"],
|
||||
"starts": sum(c["starts"] for c in tally["names"].values()),
|
||||
"ends": sum(c["ends"] for c in tally["names"].values()),
|
||||
"pairs": sum(c["pairs"] for c in tally["names"].values()),
|
||||
"pairs_per_tag": _min_median_max(tally["pairs_per_tag"]),
|
||||
"pairs_extra_differs": tally["pairs_extra_differs"],
|
||||
"overlaps_between_names": {
|
||||
"nested": sum(n for n, _c in tally["overlaps"].values()),
|
||||
"crossing": sum(c for _n, c in tally["overlaps"].values()),
|
||||
"by_names": {
|
||||
f"0x{a:08x}+0x{b:08x}": {"nested": n, "crossing": c}
|
||||
for (a, b), (n, c) in sorted(tally["overlaps"].items())
|
||||
},
|
||||
},
|
||||
"names": names,
|
||||
"exceptions_total": tally["exceptions_total"],
|
||||
"exceptions": list(tally["exceptions"]),
|
||||
}
|
||||
|
||||
|
||||
def _decode_companion_tags(read_slice, bank_offset, tag_map):
|
||||
"""Decode companion speech tags (`0x76`, `0x55`, `0x36`, `0x5a`, `0xa3`, `0xb2`, `0xbd`, `0xd9`) on a stream."""
|
||||
comp = {
|
||||
@ -1135,24 +1390,31 @@ def _new_grid_tally():
|
||||
"marker_records": 0,
|
||||
"marker_invalid": 0,
|
||||
"marker_first_names": {},
|
||||
# Region cues matched into start/end pairs (ASSET-320). A running `_new_region_tally()` while banks are
|
||||
# read and in decode_awc_bank()'s result; a scan's summary carries marker_region_report() of it.
|
||||
"marker_regions": _new_region_tally(),
|
||||
}
|
||||
|
||||
|
||||
def _merge_grid_tally(dst, src):
|
||||
"""Add one bank's companion-table tally to a running summary (counts add, per-name maps merge)."""
|
||||
for key, start in _new_grid_tally().items():
|
||||
if isinstance(start, dict):
|
||||
if key == "marker_regions":
|
||||
_merge_region_tally(dst[key], src[key])
|
||||
elif isinstance(start, dict):
|
||||
for name, count in src[key].items():
|
||||
dst[key][name] = dst[key].get(name, 0) + count
|
||||
else:
|
||||
dst[key] += src[key]
|
||||
|
||||
|
||||
def _tally_undocumented_tables(read_slice, bank_base, tmap, tally):
|
||||
def _tally_undocumented_tables(read_slice, bank_base, tmap, tally, stream_id=None):
|
||||
"""Decode the ``0x5a``/``0xd9`` tables and the ``0xbd`` cue list on one stream into a running tally.
|
||||
|
||||
A stream counts as invalid when one of the layout invariants measured over the whole ``audio.rpf``
|
||||
population fails, so the tally doubles as a package-wide validator.
|
||||
population fails, so the tally doubles as a package-wide validator. The region cues of a valid
|
||||
``0xbd`` tag are matched into start/end pairs (`marker_regions`); `stream_id` only labels the
|
||||
exceptions listed there.
|
||||
"""
|
||||
grid = None
|
||||
if TAG_GRID20 in tmap:
|
||||
@ -1197,9 +1459,10 @@ def _tally_undocumented_tables(read_slice, bank_base, tmap, tally):
|
||||
tally["indexrun_index_overruns"] += 1
|
||||
if TAG_MARKER in tmap:
|
||||
mo, ms = tmap[TAG_MARKER][0]
|
||||
marks = None
|
||||
marks = blob = None
|
||||
if 0 < ms <= MAX_MARKER_BYTES:
|
||||
marks = decode_marker_records(read_slice(bank_base + mo, ms))
|
||||
blob = read_slice(bank_base + mo, ms)
|
||||
marks = decode_marker_records(blob)
|
||||
tally["marker_streams"] += 1
|
||||
if marks is None or not (marks["size_ok"] and marks["offsets_ascending"]):
|
||||
tally["marker_invalid"] += 1
|
||||
@ -1208,6 +1471,15 @@ def _tally_undocumented_tables(read_slice, bank_base, tmap, tally):
|
||||
key = f"0x{marks['first_name']:08x}"
|
||||
firsts = tally["marker_first_names"]
|
||||
firsts[key] = firsts.get(key, 0) + 1
|
||||
records = marker_records(blob)
|
||||
if any(value in _REGION_VALUES for _name, value, _offset, _extra in records):
|
||||
samples = None
|
||||
if TAG_FORMAT in tmap:
|
||||
fo, fs = tmap[TAG_FORMAT][0]
|
||||
fb = read_slice(bank_base + fo, 4) if fs >= 4 else b""
|
||||
samples = _u32(fb, 0) if len(fb) == 4 else None
|
||||
_tally_marker_regions(tally["marker_regions"], records, bank_offset=bank_base,
|
||||
stream_id=stream_id, sample_count=samples)
|
||||
|
||||
|
||||
def decode_awc_bank(data, bank_offset=0, *, deep=True, curves=False):
|
||||
@ -1229,7 +1501,7 @@ def decode_awc_bank(data, bank_offset=0, *, deep=True, curves=False):
|
||||
key = f"0x{tt:02x}"
|
||||
tag_counts[key] = tag_counts.get(key, 0) + 1
|
||||
tmap.setdefault(tt, []).append((toff, tsz))
|
||||
_tally_undocumented_tables(read_slice, 0, tmap, tally)
|
||||
_tally_undocumented_tables(read_slice, 0, tmap, tally, sid)
|
||||
for tt, toff, tsz in tags:
|
||||
if tt == TAG_RSC8_CLIP:
|
||||
if tsz < 4 or tsz > MAX_RSC8_BYTES:
|
||||
@ -1306,6 +1578,12 @@ def _new_summary(mode, source):
|
||||
}
|
||||
|
||||
|
||||
def _finish_summary(summary, t0):
|
||||
"""Close a scan's summary: the running region tally becomes its report, and the clock stops."""
|
||||
summary["marker_regions"] = marker_region_report(summary["marker_regions"])
|
||||
summary["elapsed_seconds"] = round(time.time() - t0, 3)
|
||||
|
||||
|
||||
def _accumulate_record(summary, rec, *, in_adat=True, has_audio=None):
|
||||
summary["rsc8_decoded"] += 1
|
||||
if in_adat:
|
||||
@ -1498,7 +1776,7 @@ def scan_rpf(path, *, start=0, limit=None, max_banks=None, deep=True, collect_re
|
||||
tk = f"0x{tt:02x}"
|
||||
summary["adat_tag_counts"][tk] = summary["adat_tag_counts"].get(tk, 0) + 1
|
||||
tmap.setdefault(tt, []).append((toff, tsz))
|
||||
_tally_undocumented_tables(bank_read_slice, aoff, tmap, summary)
|
||||
_tally_undocumented_tables(bank_read_slice, aoff, tmap, summary, sid)
|
||||
if not has_5c:
|
||||
continue
|
||||
for tt, toff, tsz in tags:
|
||||
@ -1557,7 +1835,7 @@ def scan_rpf(path, *, start=0, limit=None, max_banks=None, deep=True, collect_re
|
||||
progress(pos, scan_end, summary)
|
||||
next_prog += 2 * 1024 * 1024 * 1024
|
||||
|
||||
summary["elapsed_seconds"] = round(time.time() - t0, 3)
|
||||
_finish_summary(summary, t0)
|
||||
return records, summary
|
||||
|
||||
|
||||
@ -1617,7 +1895,7 @@ def scan_dir(path, *, max_banks=None, deep=True, collect_records=True, curves=Fa
|
||||
summary["invalid_files"] += 1
|
||||
print(f"{fp}: {e}", file=sys.stderr)
|
||||
|
||||
summary["elapsed_seconds"] = round(time.time() - t0, 3)
|
||||
_finish_summary(summary, t0)
|
||||
return records, summary
|
||||
|
||||
|
||||
@ -1637,7 +1915,7 @@ def scan_single_file(path, *, start=0, limit=None, max_banks=None, deep=True, co
|
||||
rec = _make_record(0, 0, None, dec, None)
|
||||
summary = _new_summary("rsc8", path)
|
||||
_accumulate_record(summary, rec, in_adat=False, has_audio=None)
|
||||
summary["elapsed_seconds"] = round(time.time() - t0, 3)
|
||||
_finish_summary(summary, t0)
|
||||
return ([rec] if collect_records else []), summary
|
||||
if head == ADAT_MAGIC and start == 0 and limit is None and fsize <= MAX_AWC_FILE_BYTES:
|
||||
t0 = time.time()
|
||||
@ -1653,7 +1931,7 @@ def scan_single_file(path, *, start=0, limit=None, max_banks=None, deep=True, co
|
||||
summary["rsc8_non_rsc8_0x5c"] = bank_res["non_rsc8_0x5c"]
|
||||
for rec in bank_res["records"]:
|
||||
_accumulate_record(summary, rec, in_adat=True, has_audio=rec.get("has_audio_data"))
|
||||
summary["elapsed_seconds"] = round(time.time() - t0, 3)
|
||||
_finish_summary(summary, t0)
|
||||
return (bank_res["records"] if collect_records else []), summary
|
||||
return scan_rpf(
|
||||
path,
|
||||
|
||||
Reference in New Issue
Block a user