OpenTPW

TGQ movies: decoding evidence and playback#

October 9, 2026; video decoding updated October 16, 2026. Status: CPU container/audio/video decoding for the nine local Data/Movies/*.tgq files, plus streaming playback (--play-movie <name>) with audio, A/V sync and GPU presentation, and the start-up movie sequence (bf, then a trailer by day of the month) before the front end. Audio PCM matches an external FFmpeg 8.0.1 oracle bit-exactly (over the samples FFmpeg emits). Video is now tp.exe's own decoder: the dequantisation matrix, the transposed scan, the two transform passes and the colour tables of the PC movie player are reproduced, and the samples match the original routines run in the x86 oracle (see "The live PC decoder"). No in-game The triggers are proven on the PC executable tp.exe (see "Where the original plays movies", "The PC build"): two start-up movies, nothing else. How the PC player ends a movie, paces it and puts it on the screen is read there too; what it does with the 12.9 s of plan.tgq audio after the last frame is not. No dependency or movie data is added.

Code: source/OpenTPW.Files/Formats/Video/TgqMovieFile.cs, source/OpenTPW.Files/Formats/Video/TqiDecoder.cs, source/OpenTPW.Files/Formats/Video/TgqAudioReader.cs, source/OpenTPW.Files/Formats/Sound/EaXaAdpcmDecoder.cs, playback in source/OpenTPW/Client/Movie/; tests: source/OpenTPW.Tests/TgqMovieFileTests.cs, source/OpenTPW.Tests/MoviePlaybackTests.cs.

Container#

Little-endian EA chunks: ASCII FourCC, u32 size including the 8-byte preamble. All nine files parse exactly to EOF. Observed and enforced order: SCHl first (once), then interleaved pIQT video and SCDl audio, one 4-byte SCCl (audio block count, before the first SCDl, must equal the SCDl count), empty SCEl last with nothing after it. Any other FourCC (including the documented but unobserved SCLl) is rejected as unsupported.

FileBytespIQTSCDl (=SCCl)Audio samples/channelAudio sVideo s @30
bf.tgq2,462,896255265194,8158.838.50
bub.tgq20,099,2761,1741,174862,99939.1439.13
buc.tgq19,926,4201,1411,142839,44338.0738.03
grav.tgq20,301,8041,2121,213891,70140.4440.40
jug.tgq25,925,2961,1501,151846,09438.3738.33
mir.tgq15,862,5121,3601,3611,000,59145.3845.33
plan.tgq14,828,7441,1381,5251,120,54250.8237.93
roc.tgq14,301,112990991728,34733.0333.00
roll.tgq17,553,568992993729,81733.1033.07

Totals: 9,412 video frames, 9,815 audio blocks. Every file has exactly one SCHl, SCCl and SCEl. plan.tgq audio continues ~12.9 s past its last video frame; playback behaviour after the last frame is unknown.

SCHl audio header#

Identical in all files except the sample count: PT, platform u16 0 (PC), then the patch substream (tag, length byte, big-endian value; 0xFC–0xFE carry no data, 0xFF ends; 0xFF length means a 4-byte BE length follows):

00:02 06:65 1B:1E FD 85:<samples> 82:02 83:07 8A:00000000 FF

Audio: EA-XA ADPCM, stereo#

Each SCDl payload: u32 sample frames, then per channel int16 current and int16 previous predictor state (left then right), then 30-byte frames: byte 0 = predictor indexes (left high nibble, right low), byte 1 = shifts (nibble + 8), 28 bytes each holding one left (high) and one right (low) 4-bit sample. sample = ((nibble << 28) >> shift + cur*c1 + prev*c2 + 0x80) >> 8, clamped, with (c1, c2) = (0,0) (240,0) (460,-208) (392,-220). The predictor state is reset by every block header. The final frame of the final block is partial (e.g. bf.tgq 775 = 27×28 + 19); after the encoded frames, 0 or 2 zero alignment bytes are observed. Stricter than observed, the decoder rejects predictor indexes > 3, nonzero padding or ≥ 4 slack bytes.

Verification: per file, the sum of block sample counts equals the header 0x85 value, and decoded PCM equals FFmpeg's adpcm_ea output on every sample FFmpeg emits. FFmpeg drops the partial last frame (3–25 samples per file and logs "invalid number of samples in packet"); OpenTPW keeps the header count.

Video: TQI#

pIQT payload: u16 width, u16 height, u8 quantizer, 3 unknown bytes. All 9,412 frames: 320×352, quantizer 99, unknown bytes 14 16 03 (the wiki says "always zero"; meaning unknown, retained as UnknownBytes). Every frame is intra-coded.

Bitstream (verified against the corpus and the oracle): MSB-first bits read from little-endian 32-bit words. Macroblocks in raster order, each Y0 Y1 Y2 Y3 Cb Cr with no macroblock header. Each block is an MPEG-1 intra block: dct_dc_size_luminance/chrominance VLC (ISO/IEC 11172-2 B.12/B.13, sizes 0–8), DC differential with per-component predictors starting at 0, then Table B.14 run/level codes + sign, MPEG-1 escape (6-bit run, 8-bit level, 0x00/0x80 extension), end-of-block 10, standard zigzag. The wiki claims a different run/level table; the standard MPEG-1 values are what match the oracle (PSNR ~55 dB versus ~21–40 dB for wrong scan variants during investigation).

Dequantisation (the reading before tp.exe's decoder was found; superseded by "The live PC decoder"): F[0] = dc × 8, F[i] = level × W[i] × (107.5 − q) × 0.625 / 8 with W the MPEG-1 default intra matrix (wiki "base_table2"); in integer form qscale = (215 − 2q) × 5 and F[i] = level × W[i] × qscale / 128. DC is in pixel units (no +128 offset). Every frame ends within its final 32-bit word with zero padding bits; the decoder requires that.

IDCT: integer variants measured against the oracle (history)#

This section records the search before tp.exe's live decoder was read; the decoder no longer uses any of these variants. FFmpeg approximates the transform with its own integer constants, so it was a closeness measure only.

Oracle: FFmpeg 8.0.1 tqi, -pix_fmt yuv420p, run locally only; no FFmpeg or other third-party decoder source was consulted or copied. Each candidate was implemented from the published algorithms and compared sample-by-sample (scratch harness outside the repository):

Candidatebf identical / PSNRplan identical / PSNR
Orthonormal float IDCT, round half up (previous decoder)84.9 % / 56.16 dB82.3 % / 55.48 dB
IJG-style AAN IDCT (float, prescaled)≈ float—
MPEG reference Chen–Wang 11-bit IDCT (4 dequant roundings)80.4–82.2 % / ≤55.6 dB (2 frames)—
IJG-style integer AAN, best of ~4,000 precision/order/rounding variants94.6 % / 60.8 dB (1 frame)—
Transposed AAN (adjoint of the AAN forward DCT), integer, selected94.6 % / 60.70 dB90.4 % / 58.22 dB

Selected arithmetic (TqiDecoder.InverseTransform): AAN prescale folded into the dequantisation table, floor(round(2^17·s(u)·s(v)) × W × qscale / 2^18) (6 fraction bits; s(0) = 1/(2√2), s(k) = 1/(4 cos(kπ/16))); the transposed AAN flowgraph with 12-bit rotation constants (2896, 2217, 5352,

  1. and floor products; columns first with a 1-bit floor shift, then rows; output (x + 8) >> 5, clipped. Precision (6–9 bits tested), pass order, the mid shift and the quarter-LSB bias were chosen by search; constant precision (9–12 bits) barely matters. The quarter-LSB bias is unexplained: the oracle rounds slightly downward relative to round-half-up in every variant tried.

All 9,412 frames (this decoder vs the oracle), re-measured on the merged main for this revision. Identical samples count Y, Cb and Cr together. Per-frame PSNR uses all three planes with peak 255; the mean and worst are taken over the frames that differ (516 frames match exactly and are excluded from the PSNR columns). Max abs diff is over all samples:

FileIdentical samplesMean PSNRWorst frameMax abs diff
bf94.6 %60.93 dB57.98 dB4
bub88.2 %57.30 dB55.69 dB4
buc87.0 %56.92 dB54.53 dB4
grav87.2 %56.98 dB55.02 dB4
jug83.9 %56.06 dB54.53 dB4
mir90.9 %58.53 dB56.04 dB4
plan90.4 %58.17 dB56.49 dB4
roc90.0 %58.02 dB56.13 dB4
roll87.7 %57.17 dB54.70 dB4

The mean PSNR differs from the earlier table by up to 0.1 dB; the decoder is unchanged. (Previous float decoder over bf, bub, mir, plan, roll: 79–85 % identical, 54.6–56.2 dB, max difference 5.) Still not bit-exact. Evidence of the remaining gap: for blocks with one AC coefficient the oracle output is a deterministic function of the level, so the residual is IDCT rounding, not bitstream or dequantisation. Of the plan blocks holding one horizontal or vertical frequency-1 coefficient, 93,921 of 95,345 (20 of 29 distinct levels) reproduce exactly, and 6,332 of 6,334 frequency-2 blocks; the misses are ±1 in one or two columns. Frequency-1 patterns over all levels fit neither IJG-AAN nor transposed-AAN arithmetic with any tested precision, product rounding (floor, ceil, nearest, toward zero) or bias, so the original uses a different factorisation or rounding order. The synthetic test pins two of those oracle patterns.

Colour (history): before the original's tables were read, TqiFrame.ToRgb24() and the GPU path used full-range BT.601 with nearest-neighbour chroma; "The live PC decoder" below describes the conversion now used.

Original TQI decoder: static analysis of the PC executable#

(History: the cseg routines this section describes turned out to be unreachable; the movies use the .text decoder of "The live PC decoder" below.)

Static reads only (llvm-objdump, byte reads, no execution) of the decrypted Sim Theme Park World v2.0 no-CD tp.exe that COMPLETION-PLAN.md allows for analysis (3,734,528 bytes, SHA-256 5472f97b5eb28f58…, image base 0x400000). Its code and its initialised data are present. (An earlier review in this document read a damaged extraction, SHA-256 85eef533…, whose data sections were empty; its conclusions that the constants are zero or encrypted, and that 0x67832e is the movie IDCT, are withdrawn.)

The executable links EA's movie library: the chunk dispatcher at 0x66e5f0 handles MADe, TGVf, TGVk, TGQp, pIQT, UV2f and more (pIQT is frame type 4). Two separate 8×8 transforms exist:

Verified TQI arithmetic:

StepAddressWhat it does
Block decode0x6f61e8VLC run/level decode (tables in tqia_dat, zigzag at 0xfbf0e4); every coefficient, the DC included (after prediction), is level × M[pos] with a plain 32-bit imul; M is 64 dwords at 0xfac690
Pass 1 (rows)0x6f6510AAN butterfly, see below; if all seven AC inputs are zero, the DC is copied unchanged to all eight outputs; writes a 9-dword-stride temporary
Pass 2 (columns)0x6f6670the same butterfly without the zero shortcut; no shift between the passes
Driver0x6f6770per macroblock: decode, eight row passes, eight column passes into an integer macroblock buffer (0xfacab0, 256-byte rows)
Output0x6f6db4each sample is (v + 0x8000) >> 16 (round half up), used as an index into colour tables (0xfae930, 0xfaf930, 0xfb0930) that produce 16-bit RGB directly; the player never stores 8-bit YUV

The butterfly (inputs x0…x7, all 32-bit integers):

Constants (tqia_dat, identical in idct_dat): 0xfbf038 = 0x5A82799A, 0xfbf03c = 0.5411961, 0xfbf040 = 1.3065630, 0xfbf044 = 0.3826834.

Still open, so the decoder is not changed yet:

Measured against FFmpeg: FFmpeg's TQI path approximates this transform with integer constants, so a faithful port is expected to differ slightly from it; the FFmpeg table above is a closeness measure, not the bit-exactness gate.

Mac route: no TQI decoder in the Mac build (verified, negative)#

The Mac build was checked as the candidate source of the original TQI arithmetic, because its code is readable. It is not one. Static reads only: the player is 0x1009B1DC (552 bytes; its callers 0x101C0DF0 and 0x101C0F40 are confirmed by call references).

The volume was read with a scratch HFS catalogue walker outside the repository (the image does not mount with hdiutil). Nothing from it is committed.

Pinned hashes (SHA-256)#

Files:

FileSHA-256
bf.tgq174723130d5f3f03da58c26f6b162b886267f9ba694792df6bc534847704a32d
bub.tgq338764e9d40e3e9b49cf8356ea62c4bea6e6701a79d74fcedd8fbb6f9683e5e1
buc.tgq50f751e8195dbe6784037a29776b46480b75ccae542bf1ee77373dd3bbff6a44
grav.tgqfe6531e19fa0a9aea2c9ea88428898e11fba91034515818076e036061e85ebfd
jug.tgqacbde3241eb1268f525c4e50af2fcefbfef057cb0583e8831c2d63bafa2d4e69
mir.tgqffbceb6864ddda516922aceaf4ed2c55e463e663d49230ea03a2e14e4bea55a7
plan.tgq9ac41b21b05527b76be611bcb6951d05f461092a20906fa732701e864abd0ff1
roc.tgq0906c4862f9fb594b60b9c11afd7f657fc97de82d60ef3cc4d7cd210d404e72d
roll.tgq2bb0194447ae9dce24d6e15c7d9c53177fff1356e85bb6d8902dc68a69cb3fe0

Decoded PCM (interleaved s16le) — bf 9f7b0e0d…647c8, bub bd5cf5a5…3255f, plan 91839600…fadcf; all nine are pinned in full in the tests.

Decoded planes (Y‖Cb‖Cr, the original decoder's 7-bit samples; not FFmpeg's bytes):

FrameSHA-256
bf.tgq #0ad49f57f0436b8e67345865bba896140cebbfd7494a31c93e3396b7a63600d8f
bf.tgq #12781fd09cd01a2d442c68dbf4367abceb9ee7c49550ff6720c57565cf988d72904
bub.tgq #0 (identical first frame in the other 7 non-bf files)2dafcbc172a0d393b69d27ab1016be34a775ae8171bc0b475342250662bd9223
bub.tgq #5870b57596136931bd07ef0c5841cf5e510773fc33cf5411292eec715756775abc2
plan.tgq #56958ca5c38fd4cca74a124eb0c51a0ac6b26189898e5bf3d2871439fc45b4b4836

Limits and strictness#

Input ≤ 64 MiB, chunk ≤ 1 MiB, ≤ 65,536 chunks, ≤ 16 Mi samples/channel, frame dimensions multiples of 16 up to 1024, quantizer ≤ 107. Bitstream words must be whole; invalid VLCs, DC sizes > 8, more than 63 AC positions, forbidden escape levels, truncated bitstreams, whole unused trailing words and nonzero padding bits are rejected. Only PC/stereo/EA-XA (no revision tag or revision 1) audio decodes; other variants throw NotSupportedException. Caller streams stay open; nonseekable short reads are supported. Asset tests are inconclusive (not passing) without OPENTPW_GAME_PATH; the all-frames test takes ~1 min in Debug.

Container robustness audit (2026-10-13)#

PT numeric tags exposed as signed int metadata reject values greater than int.MaxValue instead of wrapping negative (frame rate, compression/revision, channels and sample rate). This is OpenTPW's typed representation policy, not a new inferred codec limit; representable unknown metadata remains available to callers, whose supported-variant checks still apply. The sample count stays a long with its existing supported bound. No transform or quantizer math changed.

TgqAudioReader advances its block ordinal only after a successful decode. A malformed block with a valid encoded length therefore remains the failing block on retry rather than being silently skipped. Reads that throw restore the complete entry cursor (block ordinal, cached frame count, cached position and buffer), so Position still names the samples returned by earlier successful reads. A caller buffer may already contain a copied prefix and must be discarded; retrying copies that same prefix again before reaching the malformed block. If a failed decode overwrote the cached PCM, the reader reconstructs its already validated block from the immutable movie data. EA-XA current/previous predictor arrays are local to each block decode and seeded from that block's header; no filter state persists between calls and no codec transform changes are required.

Synthetic regressions failed on the unsigned-tag wraparound and failed-decode retry paths before the fixes. Tests preserve the largest representable metadata, reject every truncated prefix of a valid miniature container, and decode its valid patch/audio/bitstream padding. The audit also checked that chunk sizes and file offsets are bounded before slicing, PT extended lengths are bounded before copying, audio sums use long, and frame dimensions bound plane allocation. Existing file/chunk/count/dimension limits remain unchanged.

Independent review target 9e56fba340a54896a26caad70f6dcab0c7d09956 against 72a1febf: ACCEPT after retry rollback correction. A new red regression showed that the original block-index fix alone lost the valid prefix of a failed read while leaving public Position unchanged. Added cases exercise retry from both an empty cache and a partially consumed cache, including a later-frame predictor failure that overwrites the reused PCM buffer before throwing. Independent parser checks cover 1–4-byte big-endian numeric values, big-endian extended lengths, little-endian platform values, opaque unknown tags (including embedded terminator bytes), no-data tags, duplicates, malformed lengths, and nonzero post-terminator padding. Typed representability checks preserve int.MaxValue and refuse unsigned values from 0x80000000; no new arbitrary format cap is imposed.

Fresh independent verification: 71 synthetic container/decoder/playback/intro cases pass, including fourteen container robustness cases; nineteen original-data rows skip with the corpus environment unset. Build/typecheck, changed-file style and whitespace checks, CRLF-aware diff check, fidelity register check and its eleven Python tests pass. No original asset reads were attempted. Original corpus compatibility and original-player malformed-input behavior were not requalified because USBSSD reads are blocked. Existing codec-fidelity gates above remain open.

Playback#

bash scripts/run.sh --game-path <install> --play-movie bf plays Data/Movies/bf.tgq (name or name.tgq, case-insensitive, no paths) in the game window and exits when it ends; any new key press or mouse click skips. --mute plays without audio; --headless runs the decode-and-clock simulation with a simulated real-time audio device at 60 updates/s and prints statistics and a hash of the presented planes (no window, GPU or audio device); --smoke-test is the native GPU check below.

Measured: headless bf and plan at 60 Hz with audio decode every frame (255, 1,138) with no drops and end within one update after the audio; at 12 Hz bf drops > 100 frames but keeps audio time. A real run of bf with SDL audio (macOS, Metal) showed all 255 frames with 0 drops and ended at 8.84 s (audio 8.83 s); before smoothing the stepped audio position it dropped 71.

Native check: --play-movie bf --smoke-test (audio off for determinism) plays to frame 60, reads the resolved framebuffer back at frames ≥ 15 and ≥ 60 and requires the mean RGB inside the movie rectangle to match the CPU-converted frame within 6/255 per channel, black bars outside it and a changed picture between the two reads; it saves artifacts/native-movie-bf-*.png.

Where the original plays movies#

Source: static analysis of the Mac PowerPC build (SimThemePark, QuickTime .mov files; Ghidra, never executed) for the first part, and of the PC executable tp.exe for "The PC build" below, which confirms every trigger on the .tgq side. Addresses are function entry points of the main code fragment; nothing here is decompiled text.

Mechanism (proven)#

Start-up sequence (proven)#

Main state machine (0x101C1208, 16-entry jump table): start-up routine 0x101C0B28 sets state 4 when the start-up flag (bit 0x200 of the global flag word) is set, else state 9. State 4 continues to 5, which is the logo.

StateDoes
5if a skip input is down: go to 7; else play Data:Movies:bf.mov and go to 6
6pump the movie; when done or a skip input is down: stop it, go to 7
7if a skip input is down: go to 1 (front-end loading); else play the day trailer, go to 8
8pump; when done or skip: stop it, go to 1
1splash plus normal loading (game data, lobby), then on to the lobby
9the same loading without movies (flag clear), ending in the running state
day % 801234567
moviebubbucgravjugmirplanrocroll

The choice is deterministic by date (days 8, 16, 24 play bub; days 7, 15, 23, 31 roll), not random. All nine names are the Data:Movies:<name>.mov strings; bf sits at pool offset +0x44.

The PC build (tp.exe, October 17, 2026)#

Static reads of the decrypted tp.exe (REA and byte reads, nothing executed); every address below is a tp.exe address.

Not in the data directory#

No data file names a trigger (the 18,734 files, WAD and SDT archives, and all English .str tables were searched), which is why the executable was needed.

Wired in OpenTPW#

The PC build has these two triggers and no others (above), so everything the original starts a movie for is wired. IntroPlaylist / IntroSequence: every normal start plays bf, then the day trailer, then opens the front end. Esc, Space or a mouse button (left, right or middle) skips. Before each movie the PC waits until all of those are released (0x54e360 states 5-8), so input held at launch or after skipping the logo delays the next movie rather than skipping it, and an input held during a movie stops it. The order and the trailer table were confirmed in the Windows tp.exe (UI-035 is retired). A missing or unreadable movie is skipped. --no-intro or OPENTPW_NO_INTRO=1 goes straight to the front end; smoke tests never play it; --mute silences it.

Selected CPU frame export#

--export-tgq-png <local.tgq> <0-based video-frame index> <new.png> exports one video frame through TgqMovieFile.DecodeVideoFrame, TqiFrame.WriteRgba32 and the existing PNG encoder. It runs before game/profile/window initialization and requires no installed game. All container and frame-header checks remain; only the selected video payload is decoded, and audio is not decoded. A malformed unselected video body can therefore remain unexamined when its header is valid.

The PNG has the encoded width and height, with opaque alpha and the current colour conversion. It does not reproduce movie display stretching or establish native IDCT/colour parity. Decode and PNG encoding finish before output creation; a privately owned CreateNew temporary file is flushed, moved without overwrite, and cleaned on failure. Existing output and foreign temporary files are preserved.

Independent CPU controls additionally distinguish video ordinals from three interleaved undecodable audio chunks, reject every truncated container prefix and invalid unselected chunk sizes/trailing bytes, and verify actual early CLI export preserves renderer/asset identity without profile creation. A Darwin-only CLI FIFO handshake also creates a foreign destination after the initial precheck and before valid input is delivered: the non-overwriting move refuses, foreign bytes remain unchanged and the owned temporary is removed. This qualifies that controlled host race, not cross-platform crash durability or original movie behavior.

TgqPngExportTests checks first/last and distinct frames, square/non-square raster readback against current codec pixels, invalid indices and selected payloads, strict unselected-header refusal, undecoded audio/unselected bodies, source-byte identity, output refusal/late-move cleanup and the real early Game.Run route. These are synthetic CPU tests; original movies and GPU/native-player parity were not exercised for this export slice.

The live PC decoder (tp.exe, October 16, 2026)#

A new static pass over the decrypted tp.exe found that the cseg routines described above (0x6F61E8…0x6F6770, matrix at 0xFAC690) are never called: no call, jump or pointer reaches them. The movies go through .text: dispatcher 0x66E5F0 (pIQT and UV2f are frame type 4), header 0x670900 (quantiser = header byte 4; byte 7 bits 0 and 1 are flags, the second choosing the pixel writer), frame decode 0x670C20, matrix builder 0x6710C0, block decoder 0x6747D0, transform passes 0x67673C/0x676965, colour tables 0x670350. TqiDecoder and TqiColour now reproduce them:

Verification. The x86 oracle (docs/reverse/ORACLE.md, X26) runs the matrix builder for every quantiser and the first transform pass on 500 coefficient rows, both against Python readings of the C# rules: the matrix agrees for every quantiser and the pass on every row; rows whose odd-part products end within 0.1 of a half are left out, because the emulator's x87 does not round those as hardware does, so the half-way rounding itself rests on the IEEE semantics of the fadd/fstp pair, not on the oracle. Whole frames were compared too, outside the test suite: the original block decoder and writer (0x67519D with 0x6747D0) run per macroblock in the oracle's sandbox over 51 frames sampled from all nine movies (every 97th frame) matched TqiDecoder in every one of 8.6 million samples but one. That one is a half-way odd-part rounding: Unicorn's x87 rounds values whose fraction lies between about 0.45 and 0.5 away from zero in about one case of twenty, which no IEEE precision does; real hardware at 53-bit or 64-bit precision gives the C# value there. The decoder follows 53-bit precision (the MSVC default); at 64-bit precision a double rounding of a + 1.5 · 2^52 would differ in rare ties (30 of the odd-part roundings in six sampled roll frames), so the FPU precision the game runs movies at stays an assumption.

Remaining gates#

The x87 precision control the game runs movies with (53-bit assumed, see above), the display's channel layout for the original packing (read; 5-6-5 is assumed, the masks come from the DirectDraw surface; OpenTPW presents full colour either way), the 0x100000 open flag that would replace the default brightness, what the original does with the audio of plan.tgq after its last frame (see "End of a movie"), the layout of dialog.tcf and what it can switch, and the window-mode origin correction of the picture box (a window is not an original mode). None of these are verified.

Sources#

Source: docs/TGQ-MOVIES.md in the project repository.