#!/usr/bin/python3 -I # SPDX-FileCopyrightText: 2026 Tomasz Kramkowski # SPDX-License-Identifier: CC0-1.0 """A minimally intrusive Frame SteamOS patcher""" import argparse import hashlib import json import os import subprocess import sys from dataclasses import dataclass from pathlib import Path MARKER = "x-valve-please-fix" RUNTIME = Path(os.environ.get("RUNTIME_DIRECTORY", "/run/patcher")) @dataclass(frozen=True) class Edit: offset: int replacement: bytes @dataclass(frozen=True) class Patch: original_hash: bytes edits: tuple[Edit, ...] def apply_to(self, data: bytes) -> bytearray: result = bytearray(data) for edit in self.edits: end = edit.offset + len(edit.replacement) if edit.offset < 0 or end > len(result): raise ValueError(f"Patch outside file at {edit.offset:#x}") result[edit.offset : end] = edit.replacement return result def patch(original_hash: str, edits: tuple[tuple[int, str], ...]) -> Patch: return Patch( bytes.fromhex(original_hash), tuple( Edit(offset, bytes.fromhex(replacement)) for offset, replacement in edits ), ) PATCHES = { "/opt/steamvr/tools/vrlink/bin/linuxarm64/vrlink": patch( original_hash="9590d9ab3e9e77d109d9aad734d587e55c601bfb574730311c0f21fb25e68121", edits=( # Clear the lists of ready and submitted frame IDs after a reset. # If not done, this can cause empty frames to be submitted to the # decoder, or skip submitting a received frame that hasn't been # submitted since the reset. (0x56814, "add70214"), ( 0x10C6C8, "6072049161720c9102008092020881a81f0001ebc1ffff54616202916082249103048052020881a863040071c1ffff544828fd17", ), # Let the decoder worker continue running when either DQBUF returns # EAGAIN. This can happen after a reset, and will trigger more # resets, and can only recover after the decoder stalls for at # least an absurd 0.8s. (0x348A0, "975f0314"), (0x10C6FC, "090040b93f2d007160ef9354130040b966a0fc17"), (0x348E0, "8c5f0314"), (0x10C710, "090040b93f2d0071c0f49354130040b971a0fc17"), # Fix a possible bug where a missing frame wouldn't trigger a # request when a newer frame arrived and the gap straddled the 16 # bit wrapping boundary. (0x56954, "a102024b213c00133f080071ab0100547316931a06000014"), (0x56980, "613e0053"), # Ignore packets which are for an older frame when re-assembling. # There are 16 slots and this could otherwise cause an old packet # to override a newer one. (0x56898, "a3d70214"), (0x10C724, "c00a40b96000f837a002004b60007837c03240395928fd179628fd17"), # Avoid two corner cases: # - After reset, wait for a complete recovery frame instead of # simply waiting for _a_ frame to avoid trying to start decoding # from a frame which depends on prior ones. # - Ignore frames which complete reassembly but which are older # than the last submitted frame. (0x56BD8, "dad60214"), ( 0x10C740, "092061f92a1941b9ca00f8370b0840b96b010a4b0b017837fd7bbea92029fd170a3040398a0000340a1040914a754d394aff0f37c0035fd6", ), # To compensate for the first of the above two fixes, any frames # which completed out of order before a recovery frame must be # revisited after that frame. (0x563F0, "411c5b54"), ( 0x10C778, "800e4092000f008b004c40f9010840b93f00146be1e9a4541229fd974d27fd17", ), # If decoder submission fails, request reset without advancing the # last-submitted frame number as though submission succeeded. (0x56468, "ccd80214"), (0x10C798, "40e9a434001b46f93327fd17"), # With FEC, audio gets sent as two blocks (A, B) followed by their # parity (A^B) block. If the next block arrives (C) while the # headset has received B but not A and is still waiting for A^B # then B gets discarded without playing it. This loses two blocks # worth of audio (10.67ms) rather than just skipping one missed # block (5.33ms) and flushing the second one (B). This fixes that # issue by just flushing B in that case. (0x3C990, "853f0314"), ( 0x10C7A4, "2000004b6000f836e2ff9f520000020b1f0800712c0f98540b129854620080522308c21a6384021b830e98348bc0fc17", ), # Patch incorrect sequence gap calculation when sequence numbers # wrap modulo 65535 (recurring theme...) (0x3CB98, "0f3f0314"), (0x10C7D4, "6000f836e1ff9f520000010b77c0fc17"), # Don't request retransmission of frames that the headset has # already moved ahead of (i.e. the last-submitted frame or older). # Assume that a frame with a size of 4 MiB with missing metadata is # not actually 4 MiB to avoid requesting way too many potentially # missing fragments automatically. This can cause too many requests # which triggers an unnecessary stream reset. Requests for the # frame's metadata fragment continue which will contain and # populate the size field allowing the retransmit request code to # work normally from that point. (0x55558, "a3dc0214"), ( 0x10C7E4, "832261f9641841b99f04003180000054e400044bc47ca434e400783780324039607ba435951240b9bf025071f503951a5523fd17de23fd17", ), # Don't trigger a reset if more than 512 missing fragments need to # be requested as a result of a time based repair. Instead stop # early once 20 entries are accumulated, reserving an extra 21st # entry so that a request for a fresh metadata fragment can always # be sent. This avoids an unnecessary reset and can speed up # recovery. (0x557EC, "0cdc0214"), ( 0x10C81C, "130080523f040031617ea45484364079a0fe0f11007c0a539f00006bc27da45402008012e2c3007933008052ea23fd17", ), (0x55828, "09dc0214"), (0x10C84C, "8a3240394a01130a4a4d0011852640b9f423fd17"), (0x55898, "7f020a6b6c040054"), (0x558F8, "7f020a6b6c010054"), (0x55920, "7f020a6bedeaff5453050011647a1f53"), ), ), } def start(): for name, patch in PATCHES.items(): target = Path(name).resolve(strict=True) data = target.read_bytes() checksum = hashlib.sha256(data).digest() if checksum != patch.original_hash: print( f"Skipping {target}: unrecognised checksum {checksum.hex()}", file=sys.stderr, ) continue patched = patch.apply_to(data) source = RUNTIME / hashlib.sha256(os.fsencode(target)).hexdigest() source.parent.mkdir(parents=True, exist_ok=True) source.write_bytes(patched) attributes = target.stat() os.chown(source, attributes.st_uid, attributes.st_gid) source.chmod(attributes.st_mode) subprocess.run( ["mount", "-o", f"bind,ro,{MARKER}", str(source), str(target)], check=True, ) print(f"Patched {target}", file=sys.stderr) def stop(): result = subprocess.run( [ "findmnt", "--mtab", "--options", MARKER, "--json", "--output", "TARGET", ], check=True, capture_output=True, text=True, ) for target in reversed( [ Path(row["target"]) for row in json.loads(result.stdout).get("filesystems", []) ] ): subprocess.run(["umount", str(target)], check=True) print(f"Unmounted {target}", file=sys.stderr) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("action", choices=("start", "stop")) args = parser.parse_args() if args.action == "start": start() else: stop() if __name__ == "__main__": main()