Merge pull request #1300 from kaoru-maki/psin-native-speaker

Export native speaker hashes from PSIN dialogue turns
This commit is contained in:
MoonEyes
2026-11-29 01:46:10 +01:00
committed by GitHub
4 changed files with 234 additions and 1 deletions

View File

@ -203,12 +203,28 @@ keys and their text sit in different archives.
| `--dialogue` | `wave`, `key`, `label`, `speaker`, `text_<lang>` per language |
| `--tables` | `source`, `offset`, `lang`, `guess` (the per-table guess), `archive` (nested archive offset), `group`, `strings`, `resolved` |
| `--strings` | `source`, `offset`, `lang`, `hash`, `label`, `text` |
| `--native-speakers` | `source`, `offset`, `conversation_offset`, `turn_offset`, `line_offset`, `speaker_slot`, `character_hash`, `cue`, `label`, `subtitle_hash` |
Standard library only. The four archives above take about 2 minutes on one core from a carve.
`tools/opus_tags.py` writes the `--dialogue` rows into the exported Ogg Opus files as `LABEL`, `SPEAKER` and
`SUBTITLE` comments (see [audio.md](audio.md#tags-names-and-subtitles)).
## Native PSIN speaker report
Add `--native-speakers <temp>/speakers.csv` to read conversation occurrences from complete PSIN resources.
`offset` is the resource location in the input, and the conversation, turn and line offsets are relative to the
resource. The report keeps repeated cue/label pairs as distinct occurrences. `subtitle_hash` is the lowercase
JOAAT of the line label and can be joined to the localized tables. `cue` is the native cue and carries no inferred
wave number or AWC address.
The `0xEDAF33B4` conversation has participant (`0x1638FDAA`) and turn (`0x06A04D25`) arrays at `+0x10` and `+0x20`.
The turn's source slot at `+0x18` selects the participant whose slot is at `+0x04`. That participant's `+0x00`
value supplies `character_hash`. The turn's line array references `0x7622C7F9` records with cue and subtitle label
strings at `+0x00` and `+0x08`. The reader checks the LSCH layout and bounds each array within its typed block.
An absent or duplicate slot, or a zero participant hash, leaves `character_hash` empty. The legacy `speaker`
suffix is still available in `--dialogue`. Keep these CSV exports on the machine that reads the game data.
## Open questions
- **Language per table.** The nested archive now groups the tables of `data.rpf`, `story000.rpf` and

View File

@ -0,0 +1,91 @@
"""Synthetic conversation records for the native speaker report."""
import csv
import pathlib
import struct
import subprocess
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).parent))
from test_psin_data import make_container, ptr # noqa: E402
from test_psin_index import joaat # noqa: E402
from psin_dialogue import speaker_rows # noqa: E402
ROOT = pathlib.Path(__file__).resolve().parents[1]
# Schema identifiers and offsets describe the disk format. Payloads and names below are invented.
SCHEMA = [
(0xEDAF33B4, 1, 88, 3, [(0x827F53FD, 16, 0x52, 0, 0, 0), (0xCDE324D0, 32, 0x52, 0, 0, 0)]),
(0x1638FDAA, 2, 20, 2, [(0xB2A5A79B, 0, 0x4A, 0, 0, 0), (0xBD6915B4, 4, 0x14, 0, 0, 0)]),
(0x06A04D25, 3, 64, 3, [(0x53C6B42D, 0, 0x52, 0, 0, 0), (0x59519816, 24, 0x15, 0, 0, 0)]),
(0x7622C7F9, 4, 40, 3, [(0x9624A3B6, 0, 0x42, 0, 0, 0), (0x66FB3A21, 8, 0x42, 0, 0, 0)]),
]
SPEAKERS = (joaat("InventedFirst"), joaat("InventedSecond"))
def sample(*, second_slot=7, array_capacity=1, invalid_string=False, wrong_schema=False, duplicate_slot=False):
# The same cue, label and slot are used in two conversations with different participants.
groups = bytearray(176)
participants = bytearray(40)
turns = bytearray(128)
lines = bytearray(80)
cue = b"FISHING_CUE\0"
strings = cue + b"FICTIONAL_AB_1\0"
for i, character in enumerate(SPEAKERS):
struct.pack_into("<QHHI", groups, i * 88 + 16, ptr(2, i * 20), 1, 1, 0)
struct.pack_into("<QHHI", groups, i * 88 + 32, ptr(3, i * 64), 1, 1, 0)
struct.pack_into("<II", participants, i * 20, character, second_slot if i else 7)
struct.pack_into("<QHHI", turns, i * 64, ptr(4, i * 40), 1, array_capacity if i else 1, 0)
struct.pack_into("<I", turns, i * 64 + 24, 7)
label_at = len(strings) - 1 if i and invalid_string else len(cue)
struct.pack_into("<QQ", lines, i * 40, ptr(5), ptr(5, label_at))
if duplicate_slot:
struct.pack_into("<QHHI", groups, 16, ptr(2), 2, 2, 0)
schema = SCHEMA if not wrong_schema else SCHEMA[:-1] + [(0x7622C7F9, 4, 40, 3, [])]
return make_container([(0xEDAF33B4, groups), (0x1638FDAA, participants), (0x06A04D25, turns),
(0x7622C7F9, lines), (0x10, strings)], schema)
class TestDialogue(unittest.TestCase):
def test_slot_is_local_to_the_conversation(self):
rows = list(speaker_rows(sample()))
self.assertEqual(len(rows), 2)
self.assertEqual([r[4] for r in rows], list(SPEAKERS))
self.assertEqual([r[3] for r in rows], [7, 7])
self.assertEqual([r[5:] for r in rows], [("FISHING_CUE", "FICTIONAL_AB_1")] * 2)
self.assertEqual([b - a for a, b in zip(rows[0][:3], rows[1][:3])], [88, 64, 40])
def test_unresolved_slot_stays_empty(self):
self.assertEqual([r[4] for r in speaker_rows(sample(second_slot=8))], [SPEAKERS[0], 0])
def test_duplicate_slot_stays_empty_in_its_conversation(self):
self.assertEqual([r[4] for r in speaker_rows(sample(duplicate_slot=True))], [0, SPEAKERS[1]])
def test_bad_records_stay_in_bounds(self):
for blob in (sample(array_capacity=2), sample(invalid_string=True)):
with self.subTest(size=len(blob)):
self.assertEqual([r[4] for r in speaker_rows(blob)], [SPEAKERS[0]])
self.assertEqual(list(speaker_rows(sample(wrong_schema=True))), [])
self.assertEqual(list(speaker_rows(sample()[:-3])), [])
def test_cli_writes_a_separate_report(self):
with tempfile.TemporaryDirectory() as tmp:
folder = pathlib.Path(tmp)
resource, legacy, native = (folder / n for n in ("sample.bin", "dialogue.csv", "native.csv"))
resource.write_bytes(sample())
subprocess.run([sys.executable, "-I", str(ROOT / "tools/text_tables.py"), str(resource),
"--dialogue", str(legacy), "--native-speakers", str(native)],
check=True, capture_output=True, text=True)
self.assertEqual(legacy.read_text(), "wave,key,label,speaker\n")
with native.open(encoding="utf-8", newline="") as handle:
rows = list(csv.DictReader(handle))
self.assertEqual([row["character_hash"] for row in rows], [f"{n:08x}" for n in SPEAKERS])
self.assertEqual({row["subtitle_hash"] for row in rows}, {f"{joaat('fictional_ab_1'):08x}"})
self.assertEqual({row["offset"] for row in rows}, {"0x0"})
self.assertEqual({row["source"] for row in rows}, {str(resource)})
if __name__ == "__main__":
unittest.main()

105
tools/psin_dialogue.py Normal file
View File

@ -0,0 +1,105 @@
"""Read speaker slots and subtitle labels from typed PSIN conversation records."""
import collections
import re
import struct
from psin_data import Container
CONVERSATION = 0xEDAF33B4
PARTICIPANT = 0x1638FDAA
TURN = 0x06A04D25
LINE = 0x7622C7F9
# LSCH structure sizes and the (name hash, byte offset, member type) of each field read here.
_LAYOUT = {
CONVERSATION: (88, {(0x827F53FD, 16, 0x52), (0xCDE324D0, 32, 0x52)}),
PARTICIPANT: (20, {(0xB2A5A79B, 0, 0x4A), (0xBD6915B4, 4, 0x14)}),
TURN: (64, {(0x53C6B42D, 0, 0x52), (0x59519816, 24, 0x15)}),
LINE: (40, {(0x9624A3B6, 0, 0x42), (0x66FB3A21, 8, 0x42)}),
}
_NAME = re.compile(rb"[A-Za-z0-9_]{1,104}")
_CONVERSATION_HASH = struct.pack("<I", CONVERSATION)
def _matches_layout(container):
for kind, (size, fields) in _LAYOUT.items():
entry = container.structs.get(kind)
if entry is None or entry["size"] != size:
return False
if not fields <= {(m["hash"], m["offset"], m["type"]) for m in entry["members"]}:
return False
return True
def _array(container, at, kind):
"""Offsets of the type-0x52 array's records in the pointed-to block."""
count, capacity, reserved = struct.unpack_from("<HHI", container.blob, at + 8)
if not count:
return ()
number, offset = container.pointer(at)
stride, _ = _LAYOUT[kind]
if count > capacity or reserved or not 1 <= number <= len(container.blocks):
raise ValueError("invalid conversation array header")
block_type, base, size = container.blocks[number - 1]
if block_type != kind or offset % stride or offset + capacity * stride > size:
raise ValueError("invalid conversation array target")
return range(base + offset, base + offset + count * stride, stride)
def _name(container, at):
number, offset = container.pointer(at)
if not 1 <= number <= len(container.blocks):
return None
block_type, base, size = container.blocks[number - 1]
if block_type != 0x10 or offset >= size:
return None
start = base + offset
end = container.blob.find(b"\0", start, min(base + size, start + 105))
if end == -1 or not _NAME.fullmatch(container.blob[start:end]):
return None
return container.blob[start:end].decode("ascii")
def speaker_rows(blob):
"""Yield native line locations, slots, hashes and labels from a supported container.
Offsets are relative to the PSIN blob. A missing, repeated or zero-hash participant slot has no known speaker.
Malformed arrays never borrow a record from an adjacent block or another conversation.
"""
if blob[:4] != b"PSIN" or _CONVERSATION_HASH not in blob:
return
try:
container = Container(blob)
except (ValueError, struct.error):
return
if not container.fills or not _matches_layout(container):
return
for kind, base, size in container.blocks:
stride, _ = _LAYOUT[CONVERSATION]
if kind != CONVERSATION or size % stride:
continue
for conversation in range(base, base + size, stride):
try:
participants = _array(container, conversation + 16, PARTICIPANT)
turns = _array(container, conversation + 32, TURN)
except ValueError:
continue
by_slot = collections.defaultdict(list)
for participant in participants:
character_hash, slot = struct.unpack_from("<II", blob, participant)
by_slot[slot].append(character_hash)
for turn in turns:
slot = struct.unpack_from("<I", blob, turn + 24)[0]
characters = by_slot.get(slot, ())
character_hash = characters[0] if len(characters) == 1 else 0
try:
lines = _array(container, turn, LINE)
except ValueError:
continue
for line in lines:
cue = _name(container, line)
label = _name(container, line + 8)
if cue and label:
yield conversation, turn, line, slot, character_hash, cue, label

View File

@ -35,6 +35,7 @@ keeps every table's own guess in ``guess`` and its nested archive's offset in ``
Usage:
python -I text_tables.py <source> [<source> ...] [--labels FILE ...]
[--dialogue dialogue.csv] [--tables tables.csv] [--strings strings.csv]
[--native-speakers speakers.csv]
A source is an ``rpf9_carve.py`` directory, an ``.rpf`` archive (read through ``gamedata_index.py``; nothing is
written), or files and directories of whole resources. ``--labels`` adds label names (word lists or a
@ -59,6 +60,7 @@ if ROOT not in sys.path:
sys.path.insert(0, ROOT)
from file_mode import published_mode # noqa: E402
from hashdict import joaat # noqa: E402
from psin_dialogue import speaker_rows # noqa: E402
RESOURCE_MAGIC = b"0DRP"
RPF9_MAGIC = b"9FPR"
@ -430,6 +432,18 @@ class Scan:
yield row
NATIVE_SPEAKER_FIELDS = ["source", "offset", "conversation_offset", "turn_offset", "line_offset",
"speaker_slot", "character_hash", "cue", "label", "subtitle_hash"]
def native_speaker_rows(source, offset, data):
for conversation, turn, line, slot, character, cue, label in speaker_rows(data):
yield {"source": source, "offset": f"{offset:#x}", "conversation_offset": f"{conversation:#x}",
"turn_offset": f"{turn:#x}", "line_offset": f"{line:#x}", "speaker_slot": slot,
"character_hash": f"{character:08x}" if character else "", "cue": cue,
"label": label, "subtitle_hash": f"{joaat(label):08x}"}
def _clean(s: str) -> str:
return s.replace("\t", " ").replace("\r", " ").replace("\n", " ")
@ -461,9 +475,11 @@ def main(argv=None) -> int:
ap.add_argument("--dialogue", help="CSV: wave, key, label, speaker, text per language")
ap.add_argument("--tables", help="CSV: one row per string table (source, offset, lang, group, counts)")
ap.add_argument("--strings", help="CSV: every string (source, offset, lang, hash, label, text)")
ap.add_argument("--native-speakers", help="CSV: native PSIN speaker hashes with source and line locations")
a = ap.parse_args(argv)
out_flags = [(flag, path) for flag, path in (("--dialogue", a.dialogue), ("--tables", a.tables),
("--strings", a.strings)) if path]
("--strings", a.strings),
("--native-speakers", a.native_speakers)) if path]
outs = [path for _, path in out_flags]
seen = []
for flag, p in out_flags:
@ -490,12 +506,15 @@ def main(argv=None) -> int:
ap.error(f"{flag} would overwrite the input {clash}")
scan = Scan()
native = []
try:
for source in a.sources:
starts = archive_starts(source)
for label, offset, data in blobs(source):
nested = archive_of(starts, offset) if starts else None
scan.add(label, offset, data, None if nested is None else (source, nested))
if a.native_speakers:
native.extend(native_speaker_rows(label, offset, data))
names = {}
for path in a.labels:
names.update(read_labels(path))
@ -524,6 +543,8 @@ def main(argv=None) -> int:
({"source": s, "offset": o, "lang": lang, "hash": f"{h:08x}", "label": names.get(h, ""),
"text": _clean(text)}
for s, o, lang, t in scan.tables for h, text in t.items())))
if a.native_speakers:
jobs.append((a.native_speakers, NATIVE_SPEAKER_FIELDS, native))
# Stage every report next to its destination, then swap them all in. A write that fails part-way must
# leave the previous reports intact instead of truncating the ones that came before it.
staged = []