diff --git a/docs/text.md b/docs/text.md index 946d07c90..d37a3485a 100644 --- a/docs/text.md +++ b/docs/text.md @@ -203,12 +203,28 @@ keys and their text sit in different archives. | `--dialogue` | `wave`, `key`, `label`, `speaker`, `text_` 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 /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 diff --git a/tests/test_psin_dialogue.py b/tests/test_psin_dialogue.py new file mode 100644 index 000000000..c3ee7336b --- /dev/null +++ b/tests/test_psin_dialogue.py @@ -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(" 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(" [ ...] [--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 = []