Free fork of NotProton: Windows Steam games in Mac Steam, on CodeWeavers' Wine and Apple's Game Porting Toolkit
Swift apple-silicond3dmetaldxmtdxvkgame-porting-toolkitgptkmac-gamingmacosmetalfxrosetta-2steamsteam-playwinewinecx
revert(controllers): take out the DualSense bridge, Steam rumble and game-mode host
Raystorm5df8a5f96daa
diff --git a/AGENTS.md b/AGENTS.mdindex fa90547..ecd0aeb 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -19,7 +19,6 @@ steps from it.| `*-patch/` (win32u, winemac, winebus, winecoreaudio, wined3d, ws2_32, ngx-signer) | Patches for single WineCX/WineHQ files. The rebuilt binaries are committed in `app/Sources/BridgeplayApp/Resources/` | Wine || `nvapi-shim/` | Windows `nvapi64.dll` that lets games use DLSS (answered by MetalFX) | Wine || `overlay-shim/` | HDR, Metal 4 and frame generation | Game process |-| `controllers/` | DualSense Bluetooth bridge and Steam Input rumble | Game process, plus a broker process || `native-launch/`, `native-shim/` | Launch wrapper and gamepad shim for native Mac games | Native game process || `helpers/` | Small tools the dylib and run script call (icons, app info, game host, shortcuts) | Command line || `gamefixes/` | Per-game defaults, `<appid>.conf`. Format: [docs/GAMEFIXES.md](docs/GAMEFIXES.md) | Read by the run script |@@ -28,8 +27,7 @@ steps from it.| `compat/` | Game compatibility list, generated from `compat/games.json`. Don't edit `compat/README.md` by hand | — |More docs: [docs/WINECX.md](docs/WINECX.md) (engine, patch build recipes and pins),-[docs/DXMT.md](docs/DXMT.md), [docs/dualsense-bluetooth.md](docs/dualsense-bluetooth.md),-[docs/game-mode-host.md](docs/game-mode-host.md) and [docs/RELEASING.md](docs/RELEASING.md).+[docs/DXMT.md](docs/DXMT.md) and [docs/RELEASING.md](docs/RELEASING.md).## Build and check@@ -63,7 +61,6 @@ The checks the workflows run (`make -s <target>`):`shortcutcheck`, `launch-shell`, `envcheck`, `buildcheck`, `settingscheck`, `routecheck`,`bridgecheck`, `envpasscheck`, `prefixnotecheck`, `powernotecheck`, `exitcheck`, `gamedrivecheck`, `launchercheck`, `seedcheck`, `gamefixescheck`, `versioncheck`, `cicheck`,`compat-reported-check`-- **Hardware-free device checks:** `game-host-check`, `dualsense-check`, `steam-rumble-check``make tests-list` prints the test paths. A check whose tool or input is missing prints`skipped` and exits 0: that is not a pass. Install the tool, or say the check didn't run.diff --git a/Makefile b/Makefileindex c80384b..59c4a6e 100644--- a/Makefile+++ b/Makefile@@ -589,97 +589,7 @@ $(APPINFO): helpers/appinfo.swiftswiftc -O -target $(ARCH)-apple-macos$(MIN_VER) -o $@ $<@echo "==> Built $@"-GAME_HOST := $(OUT_DIR)/game-host.dylib-GAME_METADATA := $(OUT_DIR)/prepare-game-loader--$(GAME_HOST): helpers/game-host.c- @mkdir -p $(OUT_DIR)- $(CC) -dynamiclib -arch arm64 -arch x86_64 -mmacosx-version-min=$(MIN_VER) -O2 -Wall -Wextra $< -o $@- codesign -f -s - --identifier com.notproton.game-host $@--$(GAME_METADATA): helpers/prepare-game-loader.swift- @mkdir -p $(OUT_DIR)- swiftc -O -target $(ARCH)-apple-macos$(MIN_VER) $< -o $@- codesign -f -s - --identifier com.notproton.game-metadata $@--.PHONY: game-host-check-game-host-check: $(GAME_HOST) $(GAME_METADATA)- python3 helpers/tests/game-host.py- python3 helpers/tests/game-metadata.py $(GAME_METADATA)--DUALSENSE_SRC := controllers/dualsense-DUALSENSE_OUT := $(OUT_DIR)/controllers/dualsense-DUALSENSE_RUNTIME := $(DUALSENSE_OUT)/bridge.dylib $(DUALSENSE_OUT)/broker $(DUALSENSE_OUT)/launch-DUALSENSE_HEADERS := $(wildcard $(DUALSENSE_SRC)/*.h)--$(DUALSENSE_OUT)/bridge.dylib: $(DUALSENSE_SRC)/bridge.m $(DUALSENSE_SRC)/AudioFacade.m $(DUALSENSE_HEADERS)- @mkdir -p $(DUALSENSE_OUT)- $(CC) -dynamiclib -arch arm64 -arch x86_64 -mmacosx-version-min=$(MIN_VER) -O2 -Wall $(filter %.m,$^) -framework Foundation -framework IOKit -framework CoreAudio -framework AudioUnit -lz -o $@- codesign -f -s - --identifier com.notproton.dualsense.bridge $@--$(DUALSENSE_OUT)/broker: $(DUALSENSE_SRC)/broker.m $(DUALSENSE_SRC)/PCMTransport.m $(DUALSENSE_HEADERS)- @mkdir -p $(DUALSENSE_OUT)- $(CC) -arch $(ARCH) -mmacosx-version-min=$(MIN_VER) -O2 -Wall -fobjc-arc $(filter %.m,$^) -framework AudioToolbox -framework AppKit -framework GameController -framework CoreHaptics -framework IOKit -lz -o $@- codesign -f -s - --identifier com.notproton.dualsense.broker $@--$(DUALSENSE_OUT)/launch: $(DUALSENSE_SRC)/launch.swift- @mkdir -p $(DUALSENSE_OUT)- swiftc -O -target $(ARCH)-apple-macos$(MIN_VER) $< -o $@- codesign -f -s - --identifier com.notproton.dualsense.launch $@--.PHONY: dualsense dualsense-check-dualsense: $(DUALSENSE_RUNTIME)--dualsense-check: dualsense- $(CC) -arch arm64 -arch x86_64 $(DUALSENSE_SRC)/audio-test.c -framework CoreAudio -framework AudioUnit -o $(DUALSENSE_OUT)/audio-test- $(CC) -O2 $(DUALSENSE_SRC)/test-pcm-unit.c -lz -o $(DUALSENSE_OUT)/test-pcm-unit- $(CC) -O2 $(DUALSENSE_SRC)/test-controls.c -o $(DUALSENSE_OUT)/test-controls- $(DUALSENSE_OUT)/test-pcm-unit- $(DUALSENSE_OUT)/test-controls- $(CC) -O1 $(DUALSENSE_SRC)/hid-test.m -framework Foundation -framework IOKit -o $(DUALSENSE_OUT)/hid-test- $(DUALSENSE_OUT)/hid-test- $(CC) -O1 -fobjc-arc $(DUALSENSE_SRC)/output-test.m $(DUALSENSE_SRC)/PCMTransport.m -framework AudioToolbox -framework AppKit -framework GameController -framework CoreHaptics -framework IOKit -lz -o $(DUALSENSE_OUT)/output-test- $(DUALSENSE_OUT)/output-test- DSB_TEST_BUILD=$(DUALSENSE_OUT) python3 $(DUALSENSE_SRC)/test-launch.py- DSB_TEST_BUILD=$(DUALSENSE_OUT) python3 $(DUALSENSE_SRC)/test-bridge.py- DSB_TEST_BUILD=$(DUALSENSE_OUT) python3 $(DUALSENSE_SRC)/test-pcm.py- DSB_TEST_BUILD=$(DUALSENSE_OUT) DSB_TEST_DEFER_TIMERS=1 python3 $(DUALSENSE_SRC)/test-pcm.py- DSB_TEST_BUILD=$(DUALSENSE_OUT) python3 $(DUALSENSE_SRC)/test-lifecycle.py- DSB_TEST_BUILD=$(DUALSENSE_OUT) python3 $(DUALSENSE_SRC)/test-trigger-routing.py--STEAM_RUMBLE_SRC := controllers/steam-input-STEAM_RUMBLE_OUT := $(OUT_DIR)/controllers/steam-input-STEAM_RUMBLE := $(STEAM_RUMBLE_OUT)/rumble.dylib-STEAM_SDK := build/lsteamclient/steamworks_sdk_162-STEAM_RUMBLE_FLAGS := -arch arm64 -arch x86_64 -mmacosx-version-min=$(MIN_VER) -std=c++17 -Wall -Wextra -I$(STEAM_SDK)--$(STEAM_SDK)/steam_api.h: lsteamclient/fetch.sh- sh lsteamclient/fetch.sh- @touch $@--$(STEAM_RUMBLE): $(STEAM_RUMBLE_SRC)/rumble.cpp $(STEAM_RUMBLE_SRC)/VirtualGamepad.h $(STEAM_RUMBLE_SRC)/SteamSession.h $(STEAM_SDK)/steam_api.h- @mkdir -p $(STEAM_RUMBLE_OUT)- clang++ -dynamiclib $(STEAM_RUMBLE_FLAGS) -O2 $< -framework CoreFoundation -framework IOKit -o $@- codesign -f -s - --identifier com.notproton.steam-input.rumble $@--.PHONY: steam-rumble steam-rumble-check-steam-rumble: $(STEAM_RUMBLE)--steam-rumble-check: $(STEAM_RUMBLE)- clang++ -dynamiclib $(STEAM_RUMBLE_FLAGS) -O1 -Wno-unused-parameter $(STEAM_RUMBLE_SRC)/tests/mock-steam.cpp -o $(STEAM_RUMBLE_OUT)/steamclient.dylib- clang++ $(STEAM_RUMBLE_FLAGS) -g -O1 $(STEAM_RUMBLE_SRC)/tests/routing.cpp -framework CoreFoundation -framework IOKit -o $(STEAM_RUMBLE_OUT)/test-routing- $(STEAM_RUMBLE_OUT)/test-routing "$(CURDIR)/$(STEAM_RUMBLE_OUT)"- clang++ $(STEAM_RUMBLE_FLAGS) -g -O1 $(STEAM_RUMBLE_SRC)/tests/hooks.cpp -framework CoreFoundation -framework IOKit -o $(STEAM_RUMBLE_OUT)/test-hooks- $(STEAM_RUMBLE_OUT)/test-hooks- python3 $(STEAM_RUMBLE_SRC)/tests/launcher.py--helpers-install: $(ICONMAKER) $(APPINFO) $(GAME_HOST) $(GAME_METADATA) $(DUALSENSE_RUNTIME) $(STEAM_RUMBLE)- $(call install_atomically,$(STEAM_RUMBLE),$(SUPPORT_DIR)/controllers/steam-input/rumble.dylib)- $(call install_atomically,$(DUALSENSE_OUT)/launch,$(SUPPORT_DIR)/controllers/dualsense/launch)- $(call install_atomically,$(DUALSENSE_OUT)/broker,$(SUPPORT_DIR)/controllers/dualsense/broker)- $(call install_atomically,$(DUALSENSE_OUT)/bridge.dylib,$(SUPPORT_DIR)/controllers/dualsense/bridge.dylib)- $(call install_atomically,$(GAME_HOST),$(SUPPORT_DIR)/game-host.dylib)- $(call install_atomically,$(GAME_METADATA),$(SUPPORT_DIR)/prepare-game-loader)+helpers-install: $(ICONMAKER) $(APPINFO)$(call install_atomically,$(ICONMAKER),$(SUPPORT_DIR)/iconmaker)$(call install_atomically,$(APPINFO),$(SUPPORT_DIR)/appinfo)@echo "==> Installed: $(SUPPORT_DIR)/{iconmaker,appinfo}"@@ -753,13 +663,8 @@ bridge:fonts:fonts/build.sh-app-payload: $(TARGET) $(OVERLAY_SHIM) $(ICONMAKER) $(APPINFO) $(GAME_HOST) $(GAME_METADATA) $(DUALSENSE_RUNTIME) $(STEAM_RUMBLE)+app-payload: $(TARGET) $(OVERLAY_SHIM) $(ICONMAKER) $(APPINFO)@mkdir -p "$(APP_PAYLOAD)/signatures/macos.arm64"- @mkdir -p "$(APP_PAYLOAD)/controllers/steam-input"- cp -f $(STEAM_RUMBLE) "$(APP_PAYLOAD)/controllers/steam-input/"- @mkdir -p "$(APP_PAYLOAD)/controllers/dualsense"- cp -f $(DUALSENSE_RUNTIME) "$(APP_PAYLOAD)/controllers/dualsense/"- cp -f $(GAME_HOST) $(GAME_METADATA) "$(APP_PAYLOAD)/"@mkdir -p "$(APP_PAYLOAD)/bridge"cp -f $(TARGET) "$(APP_PAYLOAD)/notproton.dylib"cp -f $(OVERLAY_SHIM) "$(APP_PAYLOAD)/overlay-shim.dylib"@@ -807,12 +712,6 @@ PAYLOAD_SIGN_IDS := \overlay-shim.dylib:com.bridgeplay.overlay-shim \iconmaker:com.bridgeplay.iconmaker \appinfo:com.bridgeplay.appinfo \- game-host.dylib:com.notproton.game-host \- prepare-game-loader:com.notproton.game-metadata \- controllers/dualsense/bridge.dylib:com.notproton.dualsense.bridge \- controllers/dualsense/broker:com.notproton.dualsense.broker \- controllers/dualsense/launch:com.notproton.dualsense.launch \- controllers/steam-input/rumble.dylib:com.notproton.steam-input.rumble \bridge/x86_64-unix-lsteamclient.so:com.bridgeplay.lsteamclient \bridge/aarch64-unix-lsteamclient.so:com.bridgeplay.lsteamclient@@ -977,7 +876,7 @@ CI_CHECKS := mincheck l10ncheck \activatecheck compatcheck compatsvc-check prefixstate-check shortcutcheck launch-shell envcheck \buildcheck settingscheck routecheck bridgecheck envpasscheck prefixnotecheck powernotecheck exitcheck gamedrivecheck launchercheck \seedcheck gamefixescheck versioncheck cicheck padcheck compat-reported-check np-native-tests native-shim-tests \- app-tests native-installercheck game-host-check dualsense-check steam-rumble-check+ app-tests native-installercheck# app.yml runs the checks that need the built app in its build job and the rest in a# parallel job; both lists together are CI_CHECKS.@@ -994,7 +893,7 @@ ci-checks-source:# once all have finished. The slowest start first.CHECK_JOBS ?= $(shell sysctl -n hw.ncpu 2>/dev/null || echo 4)CHECK_LOGS := $(OUT_DIR)/check-logs-CI_CHECKS_FIRST := app-tests dualsense-check panel-behavior launchercheck gamefixescheck+CI_CHECKS_FIRST := app-tests panel-behavior launchercheck gamefixescheckCI_CHECKS_ORDERED := $(filter $(CI_CHECKS_FIRST),$(CI_CHECKS)) $(filter-out $(CI_CHECKS_FIRST),$(CI_CHECKS))ci-checks:diff --git a/NOTICE b/NOTICEindex 1510413..9a667de 100644--- a/NOTICE+++ b/NOTICE@@ -4,7 +4,6 @@ Bridgeplay licensingBridgeplayCopyright (C) 2026 NotProtonNot and the NotProton contributorsCopyright (C) 2026 Leon Seemann (NotProton-WineHQ)-Copyright (C) 2026 sn0wst0rm (controllers/, helpers/game-host.c, helpers/prepare-game-loader.swift)Copyright (C) 2026 Raymond Chin and the Bridgeplay contributorshttps://github.com/raymondchins/Bridgeplay@@ -34,12 +33,11 @@ Sparkle 2.10.0 (https://github.com/sparkle-project/Sparkle), embedded in the appas Sparkle.framework for updates, is licensed under the MIT license togetherwith the external licenses it lists. Full text: LICENSE.sparkle.-The DualSense Bluetooth bridge (controllers/dualsense/), the Steam Input-rumble forwarding (controllers/steam-input/) and the game-mode host-(helpers/game-host.c, helpers/prepare-game-loader.swift) were written by-sn0wst0rm and ported from sn0wst0rm's NotProton fork-(https://github.com/sn0wst0rm/NotProton), GPL-3.0. The same work is proposed to-NotProton as https://github.com/NotProtonNot/NotProton/pull/90.+Bridgeplay 0.7.51 and earlier also shipped a DualSense Bluetooth bridge, Steam+Input rumble forwarding and a game-mode host, written by sn0wst0rm+(https://github.com/sn0wst0rm/NotProton, GPL-3.0). They are left out until the+same work, proposed to NotProton as+https://github.com/NotProtonNot/NotProton/pull/90, is merged there.Patched Wine (WineCX) binaries------------------------------diff --git a/README.md b/README.mdindex 49683c1..949ebe5 100644--- a/README.md+++ b/README.md@@ -138,7 +138,7 @@ Bridgeplay is a fork of [NotProton](https://github.com/NotProtonNot/NotProton) b- **Engine:** CodeWeavers' [WineCX](https://www.codeweavers.com/crossover) (LGPL-2.1-or-later), as rebased by [dappermint](https://github.com/dappermint/winecx) and packaged with [winecx-gptk](https://github.com/dappermint/winecx-gptk).- **Graphics:** Apple's [Game Porting Toolkit](https://developer.apple.com/games/game-porting-toolkit/) (Apple's license), [DXMT](https://github.com/3Shain/dxmt) by 3Shain and [DXVK-macOS](https://github.com/Gcenx/DXVK-macOS) by Gcenx.- **Steam bridge:** `lsteamclient` and `steam.exe` come from Valve's [Proton](https://github.com/ValveSoftware/Proton).-- **Controllers and Game Mode:** the DualSense Bluetooth bridge, Steam rumble forwarding and game-mode host were written by [sn0wst0rm](https://github.com/sn0wst0rm) ([sn0wst0rm/NotProton](https://github.com/sn0wst0rm/NotProton)).+- **Controllers and Game Mode:** [sn0wst0rm](https://github.com/sn0wst0rm) wrote the DualSense Bluetooth bridge, Steam rumble forwarding and game-mode host that Bridgeplay 0.7.51 and earlier shipped. They are paused until NotProton merges the same work ([NotProton#90](https://github.com/NotProtonNot/NotProton/pull/90)).- **Libraries:** [Dobby](https://github.com/jmpews/Dobby) (Apache-2.0), [Sparkle](https://sparkle-project.org) (MIT), [SDL](https://www.libsdl.org) (zlib) and [cJSON](https://github.com/DaveGamble/cJSON) (MIT).- **Bridgeplay:** [everyone who has contributed](https://github.com/raymondchins/Bridgeplay/graphs/contributors).diff --git a/app/Sources/BridgeplayApp/Model/DeploymentContent.swift b/app/Sources/BridgeplayApp/Model/DeploymentContent.swiftindex ae9aa7b..c378d3f 100644--- a/app/Sources/BridgeplayApp/Model/DeploymentContent.swift+++ b/app/Sources/BridgeplayApp/Model/DeploymentContent.swift@@ -169,10 +169,6 @@ enum DeploymentContent {File(source: payload.iconmaker, destination: iconmaker, name: "iconmaker", executable: true),File(source: payload.appinfo, destination: appinfo, name: "appinfo", executable: true),]- files += payload.runtime.sorted { $0.key < $1.key }.map { name, source in- File(source: source, destination: iconmaker.deletingLastPathComponent().appending(path: name),- name: name, executable: !name.hasSuffix(".dylib"))- }files += payload.signatures.map {File(source: $0, destination: signatures.appending(path: $0.lastPathComponent),name: "signatures/\($0.lastPathComponent)")diff --git a/app/Sources/BridgeplayApp/Model/InstallPayload.swift b/app/Sources/BridgeplayApp/Model/InstallPayload.swiftindex 2e636b2..9d0a289 100644--- a/app/Sources/BridgeplayApp/Model/InstallPayload.swift+++ b/app/Sources/BridgeplayApp/Model/InstallPayload.swift@@ -5,14 +5,7 @@ import Foundationenum InstallPayload {static let step = String(localized: "Find Bridgeplay's components")- static let runtimeFiles = [- "prepare-game-loader", "game-host.dylib",- "controllers/steam-input/rumble.dylib",- "controllers/dualsense/launch", "controllers/dualsense/broker", "controllers/dualsense/bridge.dylib",- ]-struct Located: Sendable {- var runtime: [String: URL] = [:]let dylib: URLlet overlayShim: URLlet iconmaker: URL@@ -80,9 +73,6 @@ enum InstallPayload {)) ?? []).filter { $0.pathExtension == "json" }.sorted { $0.lastPathComponent < $1.lastPathComponent }if signatures.isEmpty { missing.append("signatures/macos.arm64/*.json") }- for name in runtimeFiles where !files.fileExists(atPath: root.appending(path: name).path) {- missing.append(name)- }let fontsRoot = root.appending(path: "fonts")let fonts = (files.subpaths(atPath: fontsRoot.path(percentEncoded: false)) ?? [])@@ -99,7 +89,6 @@ enum InstallPayload {let gamefixes = try locateGamefixes(in: root)return Located(- runtime: Dictionary(uniqueKeysWithValues: runtimeFiles.map { ($0, root.appending(path: $0)) }),dylib: dylib, overlayShim: shim, iconmaker: iconmaker,appinfo: appinfo, run: run, builtAt: builtAt, signatures: signatures,fontsRoot: fontsRoot, fonts: fonts,diff --git a/app/Tests/BridgeplayAppTests/InstallPayloadTests.swift b/app/Tests/BridgeplayAppTests/InstallPayloadTests.swiftindex ddfe2f8..4e8f263 100644--- a/app/Tests/BridgeplayAppTests/InstallPayloadTests.swift+++ b/app/Tests/BridgeplayAppTests/InstallPayloadTests.swift@@ -14,11 +14,6 @@ struct InstallPayloadTests {if shim { try Data("shim".utf8).write(to: root.appending(path: "overlay-shim.dylib")) }if iconmaker { try Data("iconmaker".utf8).write(to: root.appending(path: "iconmaker")) }if appinfo { try Data("appinfo".utf8).write(to: root.appending(path: "appinfo")) }- for name in InstallPayload.runtimeFiles {- let file = root.appending(path: name)- try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)- try Data("runtime fixture".utf8).write(to: file)- }try Data("#!/bin/sh\nexit 0\n".utf8).write(to: root.appending(path: "run"))try Data("100\n".utf8).write(to: root.appending(path: "build-time"))for name in signatures {@@ -95,26 +90,6 @@ struct InstallPayloadTests {}}- @Test("Runtime helpers are required and included in the located payload")- func requiresRuntimeHelpers() throws {- let root = try scratchDirectory("runtime-payload")- defer { try? FileManager.default.removeItem(at: root) }- try stage(root)- let located = try InstallPayload.locate(root: root)- #expect(Set(located.runtime.keys) == Set(InstallPayload.runtimeFiles))- for name in InstallPayload.runtimeFiles {- let path = root.appending(path: name)- try FileManager.default.removeItem(at: path)- do {- _ = try InstallPayload.locate(root: root)- Issue.record("payload accepted without \(name)")- } catch let failure as StepFailure {- #expect(failure.detail.contains(name))- }- try Data("runtime fixture".utf8).write(to: path)- }- }-@Test("An empty payload names every missing artifact")func reportsEverythingMissing() throws {let root = try scratchDirectory("payload")diff --git a/app/Tests/BridgeplayAppTests/SteamInstallerTests.swift b/app/Tests/BridgeplayAppTests/SteamInstallerTests.swiftindex b0718aa..9cc7d79 100644--- a/app/Tests/BridgeplayAppTests/SteamInstallerTests.swift+++ b/app/Tests/BridgeplayAppTests/SteamInstallerTests.swift@@ -42,11 +42,6 @@ struct SteamInstallerTests {let appinfo = root.appending(path: "appinfo")try FileManager.default.copyItem(at: dylib, to: appinfo)- for name in InstallPayload.runtimeFiles {- let file = root.appending(path: name)- try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)- try Data("runtime fixture".utf8).write(to: file)- }try Data("#!/bin/sh\nexit 0\n".utf8).write(to: root.appending(path: "run"))try Data("100\n".utf8).write(to: root.appending(path: "build-time"))@@ -159,13 +154,6 @@ struct SteamInstallerTests {#expect(files.fileExists(atPath: fixture.overlayShim.path(percentEncoded: false)))#expect(files.fileExists(atPath: fixture.iconmaker.path(percentEncoded: false)))#expect(files.fileExists(atPath: fixture.appinfo.path(percentEncoded: false)))- for name in InstallPayload.runtimeFiles {- let installed = fixture.support.appending(path: name)- #expect(try Data(contentsOf: installed) == Data("runtime fixture".utf8))- if !name.hasSuffix(".dylib") {- #expect(files.isExecutableFile(atPath: installed.path(percentEncoded: false)))- }- }#expect(try String(contentsOf: fixture.deployedVersion, encoding: .utf8).trimmingCharacters(in: .whitespacesAndNewlines) == "9.9.9-test"diff --git a/controllers/dualsense/AudioFacade.m b/controllers/dualsense/AudioFacade.mdeleted file mode 100644index b4a34cc..0000000--- a/controllers/dualsense/AudioFacade.m+++ /dev/null@@ -1,544 +0,0 @@-// Wine-local CoreAudio/AudioUnit facade. HID translation lives in bridge.m;-// only authenticated packet transport is shared between the two components.-#import <Foundation/Foundation.h>-#import <CoreAudio/CoreAudio.h>-#import <AudioUnit/AudioUnit.h>-#include <pthread.h>-#include <stdatomic.h>-#include <unistd.h>-#include <mach/mach_time.h>-#include "Bridge.h"-#include "PCM.h"-#include "protocol.h"--// A four-channel endpoint visible only to the Wine processes which load this library.-// Speaker channels 0/1 are discarded; haptic channels 2/3 feed the selected transport.-#define VDEVICE 0x44533542u-#define VSTREAM 0x44533543u-#define VUID CFSTR("DualSenseSteamBridge-Bluetooth-Haptics-v1")-// Element zero is the master volume; elements 1..4 address individual channels.-static _Atomic(float) deviceVolume[5] = {1, 1, 1, 1, 1};-static atomic_bool deviceMuted;-static bool audioEnabled(void) {- return DSBBridgeEnabled() && DSBRawControllerEnabled();-}-static OSStatus copyResult(UInt32 *n, void *out, const void *in, UInt32 size) {- if (*n < size) {- return kAudioHardwareBadPropertySizeError;- }- memcpy(out, in, size);- *n = size;- return noErr;-}-static OSStatus virtualProperty(AudioObjectID id, const AudioObjectPropertyAddress *a, UInt32 *size,- void *data, bool sizeOnly) {- uint8_t bytes[256] = {0};- UInt32 n = 4, u = 0;- Float64 rate = 48000;- Float32 volume;- CFStringRef s = NULL;- switch (a->mSelector) {- case kAudioObjectPropertyName:- s = CFSTR("DualSense Wireless Controller (Bluetooth Bridge)");- break;- case kAudioDevicePropertyDeviceUID:- s = VUID;- break;- case kAudioObjectPropertyManufacturer:- s = CFSTR("Local DualSense Steam Bridge");- break;- case kAudioDevicePropertyModelUID:- s = CFSTR("054c:0ce6:wireless");- break;- case kAudioDevicePropertyStreamConfiguration: {- AudioBufferList list = {.mNumberBuffers =- a->mScope == kAudioDevicePropertyScopeInput ? 0 : 1,- .mBuffers = {{.mNumberChannels = 4}}};- n = sizeof(list);- memcpy(bytes, &list, n);- break;- }- case kAudioDevicePropertyPreferredChannelLayout:- return kAudioHardwareUnknownPropertyError;- case kAudioDevicePropertyNominalSampleRate:- n = 8;- memcpy(bytes, &rate, n);- break;- case kAudioDevicePropertyAvailableNominalSampleRates: {- AudioValueRange range = {48000, 48000};- n = sizeof(range);- memcpy(bytes, &range, n);- break;- }- case kAudioDevicePropertyStreams:- u = VSTREAM;- memcpy(bytes, &u, 4);- if (a->mScope == kAudioDevicePropertyScopeInput) {- n = 0;- }- break;- case kAudioObjectPropertyClass:- u = id == VSTREAM ? kAudioStreamClassID : kAudioDeviceClassID;- memcpy(bytes, &u, 4);- break;- case kAudioDevicePropertyTransportType:- u = kAudioDeviceTransportTypeUSB;- memcpy(bytes, &u, 4);- break;- case kAudioDevicePropertyDeviceIsAlive:- u = 1;- memcpy(bytes, &u, 4);- break;- case kAudioDevicePropertyBufferFrameSize:- u = 480;- memcpy(bytes, &u, 4);- break;- case kAudioDevicePropertyBufferFrameSizeRange: {- AudioValueRange range = {480, 480};- n = sizeof(range);- memcpy(bytes, &range, n);- break;- }- case kAudioDevicePropertyVolumeScalar:- if (a->mElement > 4) {- return kAudioHardwareUnknownPropertyError;- }- volume = atomic_load(&deviceVolume[a->mElement]);- memcpy(bytes, &volume, 4);- break;- case kAudioDevicePropertyMute:- u = atomic_load(&deviceMuted);- memcpy(bytes, &u, 4);- break;- case kAudioDevicePropertyLatency:- case kAudioDevicePropertySafetyOffset:- break;- default:- return kAudioHardwareUnknownPropertyError;- }- if (s) {- n = sizeof(s);- if (!sizeOnly && *size >= n) {- CFRetain(s);- }- memcpy(bytes, &s, n);- }- if (sizeOnly) {- *size = n;- return noErr;- }- return copyResult(size, data, bytes, n);-}-static OSStatus objectSize(AudioObjectID id, const AudioObjectPropertyAddress *a, UInt32 q,- const void *qual, UInt32 *n) {- if (audioEnabled() && (id == VDEVICE || id == VSTREAM)) {- return virtualProperty(id, a, n, NULL, true);- }- OSStatus r = AudioObjectGetPropertyDataSize(id, a, q, qual, n);- if (audioEnabled() && r == noErr && id == kAudioObjectSystemObject &&- a->mSelector == kAudioHardwarePropertyDevices) {- *n += 4;- }- return r;-}-DSB_INTERPOSE(objectSize, AudioObjectGetPropertyDataSize);-static OSStatus objectData(AudioObjectID id, const AudioObjectPropertyAddress *a, UInt32 q,- const void *qual, UInt32 *n, void *out) {- if (audioEnabled()) {- if (id == VDEVICE || id == VSTREAM) {- return virtualProperty(id, a, n, out, false);- }- if (id == kAudioObjectSystemObject &&- a->mSelector == kAudioHardwarePropertyTranslateUIDToDevice &&- q == sizeof(CFStringRef) && qual && CFEqual(*(CFStringRef *)qual, VUID)) {- UInt32 v = VDEVICE;- return copyResult(n, out, &v, 4);- }- if (id == kAudioObjectSystemObject && a->mSelector == kAudioHardwarePropertyDevices) {- UInt32 cap = *n;- OSStatus r = AudioObjectGetPropertyData(id, a, q, qual, n, out);- if (r == noErr && cap >= *n + 4) {- ((UInt32 *)((char *)out + *n))[0] = VDEVICE;- *n += 4;- }- return r;- }- }- return AudioObjectGetPropertyData(id, a, q, qual, n, out);-}-DSB_INTERPOSE(objectData, AudioObjectGetPropertyData);-static Boolean objectHas(AudioObjectID id, const AudioObjectPropertyAddress *a) {- if (audioEnabled() && (id == VDEVICE || id == VSTREAM)) {- UInt32 n;- return virtualProperty(id, a, &n, NULL, true) == 0;- }- return AudioObjectHasProperty(id, a);-}-DSB_INTERPOSE(objectHas, AudioObjectHasProperty);-static OSStatus objectSet(AudioObjectID id, const AudioObjectPropertyAddress *a, UInt32 q,- const void *qual, UInt32 n, const void *in) {- if (audioEnabled() && (id == VDEVICE || id == VSTREAM)) {- if (id == VDEVICE && a->mSelector == kAudioDevicePropertyVolumeScalar && a->mElement <= 4) {- if (n != sizeof(Float32) || !in) {- return kAudioHardwareBadPropertySizeError;- }- Float32 volume;- memcpy(&volume, in, sizeof(volume));- if (!isfinite(volume) || volume < 0 || volume > 1) {- return kAudioHardwareIllegalOperationError;- }- atomic_store(&deviceVolume[a->mElement], volume);- return noErr;- }- if (id == VDEVICE && a->mSelector == kAudioDevicePropertyMute) {- if (n != sizeof(UInt32) || !in) {- return kAudioHardwareBadPropertySizeError;- }- UInt32 muted;- memcpy(&muted, in, sizeof(muted));- atomic_store(&deviceMuted, muted != 0);- return noErr;- }- return kAudioHardwareUnknownPropertyError;- }- return AudioObjectSetPropertyData(id, a, q, qual, n, in);-}-DSB_INTERPOSE(objectSet, AudioObjectSetPropertyData);-static OSStatus objectListener(AudioObjectID id, const AudioObjectPropertyAddress *a,- AudioObjectPropertyListenerProc cb, void *c) {- if (audioEnabled() && (id == VDEVICE || id == VSTREAM)) {- return noErr;- }- return AudioObjectAddPropertyListener(id, a, cb, c);-}-DSB_INTERPOSE(objectListener, AudioObjectAddPropertyListener);-static OSStatus objectUnlisten(AudioObjectID id, const AudioObjectPropertyAddress *a,- AudioObjectPropertyListenerProc cb, void *c) {- if (audioEnabled() && (id == VDEVICE || id == VSTREAM)) {- return noErr;- }- return AudioObjectRemovePropertyListener(id, a, cb, c);-}-DSB_INTERPOSE(objectUnlisten, AudioObjectRemovePropertyListener);-typedef struct Unit {- AudioUnit unit;- AudioStreamBasicDescription fmt;- AURenderCallbackStruct callback;- pthread_t thread;- atomic_bool running;- bool started;- _Atomic(float) volume;- struct Unit *next;-} Unit;-// As with the underlying AudioUnit API, each client serializes a unit's lifecycle-// and property changes. The registry lock protects different clients/units;-// running and volume are the only fields changed concurrently with render().-static Unit *units;-static pthread_mutex_t unitLock = PTHREAD_MUTEX_INITIALIZER;-static Unit *getUnit(AudioUnit unit) {- pthread_mutex_lock(&unitLock);- Unit *u = units;- while (u && u->unit != unit) {- u = u->next;- }- pthread_mutex_unlock(&unitLock);- return u;-}-static AudioStreamBasicDescription defaultFormat(void) {- return (AudioStreamBasicDescription){48000,- kAudioFormatLinearPCM,- kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,- 16,- 1,- 16,- 4,- 32,- 0};-}-static OSStatus unitStop(AudioUnit unit);-static void removeUnit(Unit *unit);--static OSStatus unitSet(AudioUnit unit, AudioUnitPropertyID p, AudioUnitScope scope,- AudioUnitElement elem, const void *data, UInt32 n) {- Unit *u = getUnit(unit);- if (audioEnabled() && p == kAudioOutputUnitProperty_CurrentDevice && n == 4 &&- *(UInt32 *)data == VDEVICE) {- if (!u) {- u = calloc(1, sizeof(*u));- if (!u) {- return kAudioUnitErr_FailedInitialization;- }- u->unit = unit;- u->fmt = defaultFormat();- u->volume = 1;- pthread_mutex_lock(&unitLock);- u->next = units;- units = u;- pthread_mutex_unlock(&unitLock);- }- return noErr;- }- if (u) {- if (p == kAudioOutputUnitProperty_CurrentDevice) {- if (n != sizeof(AudioDeviceID)) {- return kAudioUnitErr_InvalidPropertyValue;- }- if (u->started) {- return kAudioUnitErr_CannotDoInCurrentContext;- }- OSStatus result = AudioUnitSetProperty(unit, p, scope, elem, data, n);- if (result == noErr) {- removeUnit(u);- }- return result;- }- if (p == kAudioUnitProperty_StreamFormat) {- if (n != sizeof(u->fmt)) {- return kAudioUnitErr_InvalidPropertyValue;- }- AudioStreamBasicDescription f = *(AudioStreamBasicDescription *)data;- if (f.mFormatID != kAudioFormatLinearPCM || f.mChannelsPerFrame != 4 ||- !isfinite(f.mSampleRate) || f.mSampleRate < 8000 || f.mSampleRate > 192000 ||- (f.mFormatFlags &- (kAudioFormatFlagIsNonInterleaved | kAudioFormatFlagIsBigEndian)) ||- f.mBytesPerFrame != 4 * (f.mBitsPerChannel / 8) || f.mFramesPerPacket != 1 ||- f.mBytesPerPacket != f.mBytesPerFrame ||- ((f.mFormatFlags & kAudioFormatFlagIsFloat) && f.mBitsPerChannel != 32) ||- !(f.mBitsPerChannel == 8 || f.mBitsPerChannel == 16 || f.mBitsPerChannel == 32)) {- return kAudioUnitErr_FormatNotSupported;- }- if (u->started) {- return kAudioUnitErr_CannotDoInCurrentContext;- }- u->fmt = f;- } else if (p == kAudioUnitProperty_SetRenderCallback) {- if (n != sizeof(u->callback)) {- return kAudioUnitErr_InvalidPropertyValue;- }- if (u->started) {- return kAudioUnitErr_CannotDoInCurrentContext;- }- u->callback = *(AURenderCallbackStruct *)data;- }- return noErr;- }- return AudioUnitSetProperty(unit, p, scope, elem, data, n);-}-DSB_INTERPOSE(unitSet, AudioUnitSetProperty);-static OSStatus unitGet(AudioUnit unit, AudioUnitPropertyID p, AudioUnitScope scope,- AudioUnitElement elem, void *data, UInt32 *n) {- Unit *u = getUnit(unit);- if (u) {- if (p == kAudioUnitProperty_StreamFormat) {- return copyResult(n, data, &u->fmt, sizeof(u->fmt));- }- UInt32 v = p == kAudioOutputUnitProperty_CurrentDevice ? VDEVICE- : p == kAudioUnitProperty_MaximumFramesPerSlice ? 4096- : 0;- return copyResult(n, data, &v, 4);- }- return AudioUnitGetProperty(unit, p, scope, elem, data, n);-}-DSB_INTERPOSE(unitGet, AudioUnitGetProperty);-static OSStatus unitInit(AudioUnit unit) {- if (getUnit(unit)) {- return 0;- }- return AudioUnitInitialize(unit);-}-DSB_INTERPOSE(unitInit, AudioUnitInitialize);-static OSStatus unitUninit(AudioUnit unit) {- if (getUnit(unit)) {- return unitStop(unit);- }- return AudioUnitUninitialize(unit);-}-DSB_INTERPOSE(unitUninit, AudioUnitUninitialize);-// Samples are interleaved little-endian PCM. Honor signedness at every width;-// Wine may choose either signed or unsigned integer PCM before opening a stream.-static float sample(const uint8_t *bytes, const AudioStreamBasicDescription *format) {- if (format->mFormatFlags & kAudioFormatFlagIsFloat) {- float value;- memcpy(&value, bytes, sizeof(value));- return isfinite(value) ? value : 0;- }- uint32_t value = 0;- memcpy(&value, bytes, format->mBitsPerChannel / 8);- double midpoint = ldexp(1.0, format->mBitsPerChannel - 1);- double normalized = value;- if (format->mFormatFlags & kAudioFormatFlagIsSignedInteger) {- if (normalized >= midpoint) {- normalized -= 2 * midpoint;- }- } else {- normalized -= midpoint;- }- return (float)(normalized / midpoint);-}-static void clearAudioBuffer(uint8_t *buffer, size_t size,- const AudioStreamBasicDescription *format) {- memset(buffer, 0, size);- if (!(format->mFormatFlags & (kAudioFormatFlagIsFloat | kAudioFormatFlagIsSignedInteger))) {- unsigned width = format->mBitsPerChannel / 8;- for (size_t i = width - 1; i < size; i += width) {- buffer[i] = 0x80;- }- }-}--static void *render(void *ctx) {- Unit *u = ctx;- unsigned frames = (unsigned)(u->fmt.mSampleRate / 100);- size_t size = frames * u->fmt.mBytesPerFrame;- uint8_t *buf = calloc(1, size);- if (!buf) {- atomic_store(&u->running, false);- return NULL;- }- double frameTime = 0;- DSBResampler resampler;- DSBResamplerInit(&resampler, u->fmt.mSampleRate);- static atomic_uint nextStream;- uint32_t stream = atomic_fetch_add(&nextStream, 1) + 1;- uint8_t pcm[64] = {0, (uint8_t)stream, (uint8_t)(stream >> 8), (uint8_t)(stream >> 16)};- unsigned count = 0;- double next = clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW) / 1e9;- pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0);- while (atomic_load(&u->running)) {- clearAudioBuffer(buf, size, &u->fmt);- AudioBufferList list = {.mNumberBuffers = 1, .mBuffers = {{4, (UInt32)size, buf}}};- AudioUnitRenderActionFlags flags = 0;- AudioTimeStamp ts = {.mSampleTime = frameTime,- .mHostTime = mach_absolute_time(),- .mFlags =- kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid};- OSStatus result =- u->callback.inputProc- ? u->callback.inputProc(u->callback.inputProcRefCon, &flags, &ts, 0, frames, &list)- : 0;- const uint8_t *samples = list.mBuffers[0].mData;- if (result || (flags & kAudioUnitRenderAction_OutputIsSilence) ||- list.mNumberBuffers != 1 || list.mBuffers[0].mNumberChannels != 4 || !samples ||- list.mBuffers[0].mDataByteSize < size) {- clearAudioBuffer(buf, size, &u->fmt);- samples = buf;- }- float l = 0, r = 0;- float master = atomic_load(&deviceMuted) ? 0 : atomic_load(&deviceVolume[0]);- float leftGain = u->volume * master * atomic_load(&deviceVolume[3]);- float rightGain = u->volume * master * atomic_load(&deviceVolume[4]);- unsigned stride = u->fmt.mBytesPerFrame, bytes = u->fmt.mBitsPerChannel / 8;- for (unsigned i = 0; i < frames; i++) {- float left = sample(samples + i * stride + bytes * 2, &u->fmt) * leftGain,- right = sample(samples + i * stride + bytes * 3, &u->fmt) * rightGain;- l = fmaxf(l, fabsf(left));- r = fmaxf(r, fabsf(right));- if (DSBDirectPCMEnabled()) {- int8_t out[2];- if (DSBResample(&resampler, left, right, out)) {- memcpy(pcm + 4 + count * 2, out, 2);- if (++count == 30) {- pcm[0] = 30;- DSBSendPacket(DSB_PCM, 0, 0, pcm, 64);- count = 0;- }- }- }- }- if (!DSBDirectPCMEnabled()) {- DSBSendPacket(DSB_LEVEL, fminf(1, l), fminf(1, r), NULL, 0);- }- frameTime += frames;- next += frames / u->fmt.mSampleRate;- double now = clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW) / 1e9;- if (now - next > .04) {- next = now;- }- while (atomic_load(&u->running) &&- (now = clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW) / 1e9) < next) {- double remain = next - now;- if (remain > .0005) {- usleep((remain - .0003) * 1e6);- }- }- }- if (DSBDirectPCMEnabled()) {- pcm[0] = 0;- memset(pcm + 4, 0, 60);- DSBSendPacket(DSB_PCM, 0, 0, pcm, 64);- } else {- DSBSendPacket(DSB_LEVEL, 0, 0, NULL, 0);- }- free(buf);- return NULL;-}-static OSStatus unitStart(AudioUnit unit) {- Unit *u = getUnit(unit);- if (!u) {- return AudioOutputUnitStart(unit);- }- if (!u->started) {- atomic_store(&u->running, true);- if (pthread_create(&u->thread, NULL, render, u)) {- atomic_store(&u->running, false);- return kAudioUnitErr_FailedInitialization;- }- u->started = true;- fprintf(stderr, "DSB: virtual haptic stream started, 4 channels %.0f Hz\n",- u->fmt.mSampleRate);- }- return 0;-}-DSB_INTERPOSE(unitStart, AudioOutputUnitStart);-static OSStatus unitStop(AudioUnit unit) {- Unit *u = getUnit(unit);- if (!u) {- return AudioOutputUnitStop(unit);- }- if (u->started) {- if (pthread_equal(pthread_self(), u->thread)) {- return kAudioUnitErr_CannotDoInCurrentContext;- }- atomic_store(&u->running, false);- pthread_join(u->thread, NULL);- u->started = false;- }- return 0;-}-DSB_INTERPOSE(unitStop, AudioOutputUnitStop);-static void removeUnit(Unit *unit) {- pthread_mutex_lock(&unitLock);- Unit **entry = &units;- while (*entry && *entry != unit) {- entry = &(*entry)->next;- }- if (*entry) {- *entry = unit->next;- }- pthread_mutex_unlock(&unitLock);- free(unit);-}-static OSStatus unitDispose(AudioComponentInstance unit) {- Unit *u = getUnit(unit);- if (u) {- OSStatus result = unitStop(unit);- if (result) {- return result;- }- removeUnit(u);- }- return AudioComponentInstanceDispose(unit);-}-DSB_INTERPOSE(unitDispose, AudioComponentInstanceDispose);-static OSStatus unitParam(AudioUnit unit, AudioUnitParameterID p, AudioUnitScope s,- AudioUnitElement e, AudioUnitParameterValue v, UInt32 o) {- Unit *u = getUnit(unit);- if (u) {- if (p == kHALOutputParam_Volume) {- u->volume = fmaxf(0, fminf(1, v));- }- return 0;- }- return AudioUnitSetParameter(unit, p, s, e, v, o);-}-DSB_INTERPOSE(unitParam, AudioUnitSetParameter);diff --git a/controllers/dualsense/Bridge.h b/controllers/dualsense/Bridge.hdeleted file mode 100644index 0cea7ab..0000000--- a/controllers/dualsense/Bridge.h+++ /dev/null@@ -1,15 +0,0 @@-#pragma once-#include <stdbool.h>-#include <stddef.h>-#include <stdint.h>--// Immutable session configuration is initialized before Wine starts using HID/audio.-bool DSBBridgeEnabled(void);-bool DSBRawControllerEnabled(void);-bool DSBDirectPCMEnabled(void);-void DSBSendPacket(uint32_t kind, float left, float right, const uint8_t *report, size_t size);--#define DSB_INTERPOSE(new, old) \- __attribute__((used)) static struct { \- const void *a, *b; \- } ip_##old __attribute__((section("__DATA,__interpose"))) = {(void *)new, (void *)old}diff --git a/controllers/dualsense/BrokerInternal.h b/controllers/dualsense/BrokerInternal.hdeleted file mode 100644index 49eada7..0000000--- a/controllers/dualsense/BrokerInternal.h+++ /dev/null@@ -1,38 +0,0 @@-#pragma once-#import <Foundation/Foundation.h>-#import <IOKit/hid/IOHIDManager.h>-#include <pthread.h>-#include <stdatomic.h>-#include "protocol.h"--// Private state shared by the session loop and its output worker.-// Session configuration (hid/dry/pcmMode) is immutable after worker creation.-// pending/lastSent/history/dirty flags are protected by outputLock.-// Counters, shutdown and legacy motor values are atomic across threads.-typedef struct {- IOHIDDeviceRef hid;- bool dry, pcmMode;- pthread_mutex_t outputLock;- uint8_t pending[47], lastSent[47];- bool outputDirty, haveLast, legacyDirty;- NSMutableArray *sentHistory;- atomic_bool quitting, workerRunning, workerExited, stalled, deviceRemoved;- atomic_uint reports, errors;- atomic_ullong writeStartedNS;- atomic_uchar legacyLeft, legacyRight;- uint8_t btSequence; // Owned only by the active output worker.-} DSBBrokerState;-extern DSBBrokerState dsb;--// The session loop monitors writes independently of the blocking IOKit call.-bool DSBWriteOutput(const uint8_t *report, unsigned size);-bool DSBOutputWriteTimedOut(void);--// Called on the main run loop before the worker starts; no output is sent.-bool DSBPCMStartInput(void);-bool DSBPCMWorkerIsReady(void);-void *DSBPCMWorker(void *unused);-void DSBPCMNotify(void);-void DSBPCMReceive(const DSBPacket *packet);-// Takes its own lock. Callers must not hold outputLock.-NSDictionary *DSBPCMSnapshot(void);diff --git a/controllers/dualsense/Calibration.h b/controllers/dualsense/Calibration.hdeleted file mode 100644index 01ea400..0000000--- a/controllers/dualsense/Calibration.h+++ /dev/null@@ -1,16 +0,0 @@-#import <Foundation/Foundation.h>-#include <math.h>-// Gain for the Core Haptics envelope conversion.-static float DSBPCMGain(NSString *path) {- NSData *d = [NSData dataWithContentsOfFile:path];- id s = d ? [NSJSONSerialization JSONObjectWithData:d options:0 error:NULL] : nil;- if (![s isKindOfClass:NSDictionary.class] || ![s[@"version"] isEqual:@1] ||- ![s[@"pcmGain"] isKindOfClass:NSNumber.class]) {- return 1;- }- double g = [s[@"pcmGain"] doubleValue];- return isfinite(g) && g >= .25 && g <= 4 ? (float)g : 1;-}-static float DSBCalibratedPCM(float sample, float gain) {- return fmaxf(0, fminf(1, sample * gain));-}diff --git a/controllers/dualsense/Controls.h b/controllers/dualsense/Controls.hdeleted file mode 100644index 4d0c9b9..0000000--- a/controllers/dualsense/Controls.h+++ /dev/null@@ -1,46 +0,0 @@-#pragma once-#include <stdint.h>-#include <stdbool.h>-#include <string.h>--// State is retained for comparison, but valid bits are transactions. Replaying-// a stale LED/player color alongside every trigger update fights Steam/macOS.-static inline bool DSBControlDelta(const uint8_t state[47], const uint8_t previous[47], bool known,- uint8_t out[47]) {- memset(out, 0, 47);- // Offsets are within the 47-byte common output payload (report ID excluded).- static const struct {- unsigned flagByte, validBit, offset, length;- } fields[] = {- {0, 4, 10, 11}, // Right adaptive trigger.- {0, 8, 21, 11}, // Left adaptive trigger.- {1, 4, 44, 3}, // RGB lightbar.- {1, 16, 43, 1}, // Player indicator.- {1, 1, 8, 1}, // Microphone indicator.- };- bool changed = false;- for (unsigned i = 0; i < sizeof(fields) / sizeof(fields[0]); i++) {- unsigned flag = fields[i].flagByte, bit = fields[i].validBit;- unsigned offset = fields[i].offset, length = fields[i].length;- if ((state[flag] & bit) && (!known || !(previous[flag] & bit) ||- memcmp(state + offset, previous + offset, length))) {- out[flag] |= bit;- memcpy(out + offset, state + offset, length);- changed = true;- }- }- return changed;-}--// Release only triggers written by this session; never reset another client's trigger.-static inline void DSBTriggerRelease(uint8_t touched, uint8_t report[64]) {- memset(report, 0, 64);- report[0] = 2;- report[1] = touched & 12;- if (touched & 4) {- report[11] = 5;- }- if (touched & 8) {- report[22] = 5;- }-}diff --git a/controllers/dualsense/PCM.h b/controllers/dualsense/PCM.hdeleted file mode 100644index bda153e..0000000--- a/controllers/dualsense/PCM.h+++ /dev/null@@ -1,88 +0,0 @@-#pragma once-#include <stdint.h>-#include <stdbool.h>-#include <string.h>-#include <math.h>-#include <zlib.h>--// Streaming 257-tap, 1.2 kHz anti-alias filter for conversion to 3 kHz PCM.-typedef struct {- float h[257], history[257][2];- unsigned pos;- double phase, rate;-} DSBResampler;-static inline void DSBResamplerInit(DSBResampler *r, double rate) {- memset(r, 0, sizeof(*r));- r->rate = rate;- double sum = 0, cut = 1200 / rate;- for (int i = 0; i < 257; i++) {- double x = i - 128;- double v = (x ? sin(2 * M_PI * cut * x) / (M_PI * x) : 2 * cut) *- (.5 - .5 * cos(2 * M_PI * i / 256));- r->h[i] = v;- sum += v;- }- for (int i = 0; i < 257; i++) {- r->h[i] /= sum;- }-}-static inline bool DSBResample(DSBResampler *r, float l, float rr, int8_t out[2]) {- r->history[r->pos][0] = isfinite(l) ? l : 0;- r->history[r->pos][1] = isfinite(rr) ? rr : 0;- r->pos = (r->pos + 1) % 257;- r->phase += 3000;- if (r->phase + 1e-6 < r->rate) {- return false;- }- r->phase -= r->rate;- double a = 0, b = 0;- unsigned at = r->pos;- for (unsigned k = 0; k < 257; k++) {- at = (at + 256) % 257;- a += r->h[k] * r->history[at][0];- b += r->h[k] * r->history[at][1];- }- out[0] = (int8_t)lrint(fmax(-128, fmin(127, a * 127)));- out[1] = (int8_t)lrint(fmax(-128, fmin(127, b * 127)));- return true;-}-static inline void DSBCRC(uint8_t *b, unsigned n) {- uint8_t seed = 0xa2;- uint32_t c = (uint32_t)crc32(0, &seed, 1);- c = (uint32_t)crc32(c, b, n - 4);- for (int i = 0; i < 4; i++) {- b[n - 4 + i] = c >> (8 * i);- }-}-// The first report initializes audio buffers. Compact continuation retains-// control bit 1 to keep normal HID input active during PCM output.-static inline unsigned DSBPCMReport(uint8_t b[206], unsigned seq, unsigned pcmIndex, bool first,- const int8_t samples[128]) {- memset(b, 0, 206);- b[0] = first ? 0x33 : 0x32;- b[1] = (seq & 15) << 4;- b[2] = 0x91;- unsigned offset, n;- if (first) {- b[3] = 7;- b[4] = 0xfe;- memset(b + 5, 48, 5);- b[10] = (uint8_t)(pcmIndex * 2);- b[11] = 0xd2;- b[12] = 64;- offset = 13;- n = 206;- } else {- b[3] = 3;- b[4] = 0x62;- b[5] = 48;- b[6] = (uint8_t)(pcmIndex * 2);- b[7] = 0xd2;- b[8] = 64;- offset = 9;- n = 142;- }- memcpy(b + offset, samples, 128);- DSBCRC(b, n);- return n;-}diff --git a/controllers/dualsense/PCMTransport.m b/controllers/dualsense/PCMTransport.mdeleted file mode 100644index a61421f..0000000--- a/controllers/dualsense/PCMTransport.m+++ /dev/null@@ -1,461 +0,0 @@-#include "BrokerInternal.h"-#include "Controls.h"-#include <unistd.h>-// The single PCM writer owns all physical output for direct PCM sessions.-// No Core Haptics engine is started in this mode.-#include "PCM.h"-#include <mach/mach.h>-#include <mach/mach_time.h>-#include <mach/thread_policy.h>-#include <mach/semaphore.h>-#include <mach/sync_policy.h>-#import <AudioToolbox/AudioWorkInterval.h>-static uint8_t inputBuffer[1024];-static atomic_ullong inputTime;-static atomic_uint inputReports, pcmReports, pcmUnderruns, pcmDiscarded, inputHz, pcmPauses,- pcmBackgroundFrames;-static atomic_bool pcmSuspended;-static int8_t fifo[256][2];-static unsigned fifoHead, fifoCount, pcmOwner, pcmStream;-static double pcmReceived, pcmNonzero;-static bool pcmEnded;-static double maximumWrite, maximumLag;-static mach_timebase_info_data_t pcmTimebase;-static atomic_int pcmRealtimeResult = -1;-static atomic_ullong pcmMaxWaitLateNS, pcmMaxLockNS, pcmMaxLoopNS;-static os_workgroup_interval_t pcmWorkgroup;-static bool pcmIntervalOpen;-static atomic_int pcmWorkgroupResult = -1;-static atomic_bool pcmWorkerReady;-static semaphore_t pcmWake = MACH_PORT_NULL;-static atomic_bool pcmWakePending;-static bool pcmDeferTestTimers;-void DSBPCMNotify(void) {- bool expected = false;- if (atomic_load(&pcmWorkerReady) &&- atomic_compare_exchange_strong(&pcmWakePending, &expected, true)) {- semaphore_signal(pcmWake);- }-}-// Relative nanosleep/usleep can be coalesced by ~100 ms while another app-// owns Game Mode. Use Mach deadlines and an audio-sized realtime budget.-// Blocking HID writes remain guarded; missed deadlines still discard audio.-static uint64_t pcmTicks(double seconds) {- return (uint64_t)(seconds * 1e9 * pcmTimebase.denom / pcmTimebase.numer);-}-static void pcmMax(atomic_ullong *value, uint64_t n) {- uint64_t old = atomic_load(value);- while (old < n && !atomic_compare_exchange_weak(value, &old, n)) {- };-}-static void pcmCycleEnd(void) {- if (pcmIntervalOpen) {- int result = os_workgroup_interval_finish(pcmWorkgroup, NULL);- if (result) {- pcmWorkgroupResult = result;- }- pcmIntervalOpen = false;- }-}-static void pcmCycleBegin(void) {- pcmCycleEnd();- if (pcmWorkgroupResult == 0) {- uint64_t now = mach_absolute_time();- pcmIntervalOpen =- os_workgroup_interval_start(pcmWorkgroup, now, now + pcmTicks(.021333333), NULL) == 0;- }-}-static void pcmWait(double seconds) {- if (seconds > 0) {- pcmCycleEnd();- uint64_t start = mach_absolute_time(), due = start + pcmTicks(seconds), now;- // Game Mode may defer timer-only wakeups even on a realtime thread. Actual- // HID/UDP arrivals signal this semaphore and let us check the same deadline.- // Signals are coalesced, so neither bursts nor old notifications build up.- while ((now = mach_absolute_time()) < due) {- uint64_t ns = (due - now) * pcmTimebase.numer / pcmTimebase.denom;- if (pcmDeferTestTimers) {- ns += 100000000; // Offline regression: emulate deferred timer wakeups.- }- mach_timespec_t timeout = {(unsigned)(ns / 1000000000), (int)(ns % 1000000000)};- if (semaphore_timedwait(pcmWake, timeout) == KERN_SUCCESS) {- atomic_store(&pcmWakePending, false);- }- }- uint64_t end = mach_absolute_time();- if (end > due) {- pcmMax(&pcmMaxWaitLateNS, (end - due) * pcmTimebase.numer / pcmTimebase.denom);- }- pcmCycleBegin();- }-}-static double monotonicNow(void) {- return clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW) / 1e9;-}-static void pcmRemoved(void *ctx, IOReturn result, void *sender) {- atomic_store(&dsb.deviceRemoved, true);- atomic_store(&dsb.stalled, true);- dsb.quitting = 1;- fprintf(stderr, "PCM device removed; waiting for a fresh Bluetooth connection\n");-}-static void pcmInput(void *ctx, IOReturn r, void *sender, IOHIDReportType type, uint32_t id,- uint8_t *b, CFIndex n) {- if (!r && n > 0) {- uint64_t now = clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW);- atomic_store(&inputTime, now);- unsigned count = atomic_fetch_add(&inputReports, 1) + 1;- static uint64_t epoch;- static unsigned previous;- if (!epoch) {- epoch = now;- previous = count;- }- if (now - epoch >= 250000000) {- atomic_store(&inputHz, (unsigned)((count - previous) * 1e9 / (now - epoch)));- epoch = now;- previous = count;- }- DSBPCMNotify();- }-}-static bool inputAlive(void) {- return dsb.dry || (atomic_load(&inputReports) >= 10 &&- monotonicNow() - atomic_load(&inputTime) / 1e9 < .2);-}-void DSBPCMReceive(const DSBPacket *p) {- unsigned stream = p->report[1] | (p->report[2] << 8) | (p->report[3] << 16), n = p->report[0];- double now = monotonicNow();- pthread_mutex_lock(&dsb.outputLock);- // Independent audio clients cannot concatenate their timelines. Keep one- // owner until stopped/stale; current facade exposes just one haptic device.- if (pcmOwner != p->pid || pcmStream != stream) {- if (pcmOwner && !pcmEnded && now - pcmReceived < .15) {- atomic_fetch_add(&pcmDiscarded, n);- pthread_mutex_unlock(&dsb.outputLock);- return;- }- pcmOwner = p->pid;- pcmStream = stream;- fifoHead = fifoCount = 0;- pcmNonzero = 0;- }- pcmReceived = now;- pcmEnded = !n;- if (n) {- // Bound queue latency to 64ms. Drop old samples after a scheduling pause,- // never catch up with a burst of Bluetooth writes.- if (atomic_load(&pcmSuspended)) {- atomic_fetch_add(&pcmBackgroundFrames, fifoCount);- fifoHead = fifoCount = 0;- }- if (fifoCount + n > 192) {- unsigned discard = fifoCount > 64 ? fifoCount - 64 : 0;- fifoHead = (fifoHead + discard) % 256;- fifoCount -= discard;- atomic_fetch_add(&pcmDiscarded, discard);- }- for (unsigned i = 0; i < n; i++) {- unsigned at = (fifoHead + fifoCount++) % 256;- memcpy(fifo[at], p->report + 4 + i * 2, 2);- if (fifo[at][0] || fifo[at][1]) {- pcmNonzero = now;- }- }- }- pthread_mutex_unlock(&dsb.outputLock);- DSBPCMNotify();-}-static bool pcmWrite(uint8_t *b, unsigned n) {- if (atomic_load(&dsb.stalled) || !inputAlive()) {- return false;- }- double start = monotonicNow();- bool success = DSBWriteOutput(b, n);- double elapsed = monotonicNow() - start;- pthread_mutex_lock(&dsb.outputLock);- maximumWrite = fmax(maximumWrite, elapsed);- pthread_mutex_unlock(&dsb.outputLock);- return success;-}-static bool pcmControl(const uint8_t payload[47], bool audio) {- uint8_t b[78] = {0x31};- b[1] = (dsb.btSequence++ & 15) << 4;- b[2] = 0x10;- if (payload) {- memcpy(b + 3, payload, 47);- }- // Mode bits belong to this writer. A game's legacy zero/rumble command- // must not switch off an ongoing audio stream.- if (audio) {- b[3] &= ~3;- b[5] = b[6] = 0;- b[41] &= ~4;- } else {- b[3] |= 3;- b[5] = dsb.legacyRight;- b[6] = dsb.legacyLeft;- b[41] &= ~4;- }- DSBCRC(b, 78);- return pcmWrite(b, 78);-}-void *DSBPCMWorker(void *unused) {- @autoreleasepool {- pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0);- mach_timebase_info(&pcmTimebase);- pcmDeferTestTimers = dsb.dry && getenv("DSB_TEST_DEFER_TIMERS") != NULL;- kern_return_t semResult = semaphore_create(mach_task_self(), &pcmWake, SYNC_POLICY_FIFO, 0);- if (semResult) {- fprintf(stderr, "PCM wake semaphore failed: %d\n", semResult);- atomic_store(&dsb.stalled, true);- atomic_store(&pcmWorkerReady, true);- atomic_store(&dsb.workerExited, true);- return NULL;- }- thread_time_constraint_policy_data_t policy = {.period = (uint32_t)pcmTicks(64. / 3000.),- .computation = (uint32_t)pcmTicks(.001),- .constraint = (uint32_t)pcmTicks(.005),- .preemptible = TRUE};- pcmRealtimeResult =- thread_policy_set(pthread_mach_thread_np(pthread_self()), THREAD_TIME_CONSTRAINT_POLICY,- (thread_policy_t)&policy, THREAD_TIME_CONSTRAINT_POLICY_COUNT);- fprintf(stderr, "PCM deadline scheduling result=%d (1 ms budget / 21.33 ms period)\n",- pcmRealtimeResult);- pcmWorkgroup =- AudioWorkIntervalCreate("DualSense Bluetooth PCM", OS_CLOCK_MACH_ABSOLUTE_TIME, NULL);- os_workgroup_join_token_s joinToken;- pcmWorkgroupResult = pcmWorkgroup ? os_workgroup_join(pcmWorkgroup, &joinToken) : -1;- bool workgroupJoined = pcmWorkgroupResult == 0;- fprintf(stderr, "PCM audio workgroup result=%d\n", pcmWorkgroupResult);- atomic_store(&pcmWorkerReady, true);- bool streaming = false;- unsigned index = 0;- double nextPCM = 0, previous = 0, nextControl = 0, resumeAfter = 0, previousLoop = 0;- while (atomic_load(&dsb.workerRunning) && !atomic_load(&dsb.stalled)) {- @autoreleasepool {- pcmCycleBegin();- double now = monotonicNow();- if (previousLoop) {- pcmMax(&pcmMaxLoopNS, (now - previousLoop) * 1e9);- }- previousLoop = now;- if (!inputAlive()) {- if (streaming) {- atomic_store(&dsb.stalled, true);- fprintf(stderr, "PCM stopped: controller input stale\n");- }- pcmWait(.002);- continue;- }- bool linkFast = dsb.dry || atomic_load(&inputHz) >= 100;- atomic_store(&pcmSuspended, !linkFast || now < resumeAfter);- if (streaming && atomic_load(&pcmSuspended)) {- int8_t zero[128] = {0};- uint8_t b[206];- unsigned n = DSBPCMReport(b, dsb.btSequence++, index, false, zero);- if (!pcmWrite(b, n)) {- break;- }- pcmWait(.030);- if (!pcmControl(NULL, false)) {- break;- }- streaming = false;- atomic_fetch_add(&pcmPauses, 1);- pthread_mutex_lock(&dsb.outputLock);- atomic_fetch_add(&pcmBackgroundFrames, fifoCount);- fifoHead = fifoCount = 0;- pthread_mutex_unlock(&dsb.outputLock);- }- uint8_t payload[47] = {0}, snapshot[47];- bool control = false, controlChange = false, hasAudio = false;- double lockStart = monotonicNow();- pthread_mutex_lock(&dsb.outputLock);- pcmMax(&pcmMaxLockNS, (monotonicNow() - lockStart) * 1e9);- // Games often keep an audio stream open with zeros in menus. Release- // audio mode after the actual waveform's tail, not only on stream close.- // Exact signed samples determine activity; no envelope conversion/gain.- hasAudio = !atomic_load(&pcmSuspended) && pcmNonzero > 0 &&- now - pcmNonzero < .15 &&- (fifoCount || (!pcmEnded && pcmOwner && now - pcmReceived < .15));- if (!hasAudio && !streaming) {- fifoHead = fifoCount = 0;- }- memcpy(snapshot, dsb.pending, 47);- if (dsb.outputDirty && now >= nextControl) {- dsb.outputDirty = false;- control = controlChange =- DSBControlDelta(snapshot, dsb.lastSent, dsb.haveLast, payload);- }- if (!hasAudio && dsb.legacyDirty) {- control = true;- dsb.legacyDirty = false;- }- pthread_mutex_unlock(&dsb.outputLock);- if (control) {- if (!pcmControl(payload, hasAudio || streaming)) {- break;- }- nextControl = monotonicNow() + .016;- pthread_mutex_lock(&dsb.outputLock);- if (controlChange) {- memcpy(dsb.lastSent, snapshot, 47);- dsb.haveLast = true;- }- NSMutableArray *r2 = [NSMutableArray array];- for (int i = 10; i < 21; i++) {- [r2 addObject:@(snapshot[i])];- }- [dsb.sentHistory addObject:@{- @"at" : @([[NSDate date] timeIntervalSince1970]),- @"r2" : r2- }];- if (dsb.sentHistory.count > 40) {- [dsb.sentHistory removeObjectAtIndex:0];- }- pthread_mutex_unlock(&dsb.outputLock);- }- if (hasAudio && !streaming) {- if (!pcmControl(NULL, true)) {- break;- }- streaming = true;- index = 0;- nextPCM = monotonicNow() + .030;- previous = nextPCM - .022;- }- if (streaming && now >= nextPCM) {- double lag = now - nextPCM;- pthread_mutex_lock(&dsb.outputLock);- maximumLag = fmax(maximumLag, lag);- pthread_mutex_unlock(&dsb.outputLock);- if (lag > .040) {- fprintf(stderr, "PCM resync: scheduler pause %.3f ms\n", lag * 1000);- resumeAfter = now + .5;- continue;- }- if (now - previous < .018) {- pcmWait(.0005);- continue;- }- int8_t samples[128] = {0};- unsigned n;- pthread_mutex_lock(&dsb.outputLock);- n = MIN(fifoCount, 64);- for (unsigned i = 0; i < n; i++) {- memcpy(samples + i * 2, fifo[fifoHead], 2);- fifoHead = (fifoHead + 1) % 256;- fifoCount--;- }- pthread_mutex_unlock(&dsb.outputLock);- if (n < 64 && hasAudio) {- atomic_fetch_add(&pcmUnderruns, 64 - n);- }- uint8_t b[206];- unsigned size = DSBPCMReport(b, dsb.btSequence++, index, index == 0, samples);- previous = monotonicNow();- if (!pcmWrite(b, size)) {- break;- }- atomic_fetch_add(&pcmReports, 1);- index++;- nextPCM += 64. / 3000.;- if (!hasAudio) {- // Allow the zero tail to reach the actuators, then restore regular- // rumble. No LED changes. All writes remain serialized in this thread.- pcmWait(.030);- if (!pcmControl(NULL, false)) {- break;- }- streaming = false;- }- }- if (streaming) {- while (atomic_load(&dsb.workerRunning)) {- double remaining = nextPCM - monotonicNow();- if (remaining <= 0) {- break;- }- pcmWait(remaining);- }- } else {- pcmWait(.002);- }- }- }- bool failed = atomic_load(&dsb.stalled);- if (inputAlive() && !atomic_load(&dsb.errors)) {- atomic_store(&dsb.stalled, false);- if (streaming) {- int8_t zero[128] = {0};- uint8_t b[206];- unsigned n = DSBPCMReport(b, dsb.btSequence++, index, false, zero);- pcmWrite(b, n);- pcmWait(.030);- }- dsb.legacyLeft = dsb.legacyRight = 0;- pcmControl(NULL, false);- if (failed) {- atomic_store(&dsb.stalled, true);- }- }- pcmCycleEnd();- if (workgroupJoined) {- os_workgroup_leave(pcmWorkgroup, &joinToken);- }- pcmWorkgroup = nil;- atomic_store(&pcmWorkerReady, false);- semaphore_destroy(mach_task_self(), pcmWake);- }- atomic_store(&dsb.workerExited, true);- return NULL;-}--NSDictionary *DSBPCMSnapshot(void) {- pthread_mutex_lock(&dsb.outputLock);- NSDictionary *snapshot = @{- @"direct" : @(dsb.pcmMode),- @"realtimeResult" : @(pcmRealtimeResult),- @"audioWorkgroupResult" : @(pcmWorkgroupResult),- @"maxWaitLateMs" : @(atomic_load(&pcmMaxWaitLateNS) / 1e6),- @"maxLockMs" : @(atomic_load(&pcmMaxLockNS) / 1e6),- @"maxLoopMs" : @(atomic_load(&pcmMaxLoopNS) / 1e6),- @"suspended" : @(atomic_load(&pcmSuspended)),- @"inputHz" : @(atomic_load(&inputHz)),- @"pauses" : @(atomic_load(&pcmPauses)),- @"backgroundFrames" : @(atomic_load(&pcmBackgroundFrames)),- @"reports" : @(atomic_load(&pcmReports)),- @"inputReports" : @(atomic_load(&inputReports)),- @"queueFrames" : @(fifoCount),- @"underrunFrames" : @(atomic_load(&pcmUnderruns)),- @"discardedFrames" : @(atomic_load(&pcmDiscarded)),- @"maxWriteMs" : @(maximumWrite * 1000),- @"maxLagMs" : @(maximumLag * 1000)- };- pthread_mutex_unlock(&dsb.outputLock);- return snapshot;-}--bool DSBPCMStartInput(void) {- IOHIDDeviceRegisterRemovalCallback(dsb.hid, pcmRemoved, NULL);- IOHIDDeviceRegisterInputReportCallback(dsb.hid, inputBuffer, sizeof(inputBuffer), pcmInput,- NULL);- IOHIDDeviceScheduleWithRunLoop(dsb.hid, CFRunLoopGetMain(), kCFRunLoopCommonModes);- uint8_t feature[41] = {5};- CFIndex n = sizeof(feature);- if (IOHIDDeviceGetReport(dsb.hid, kIOHIDReportTypeFeature, 5, feature, &n)) {- return false;- }- for (int i = 0; i < 40 && !inputAlive(); i++) {- [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:.01]];- }- if (!inputAlive()) {- fprintf(stderr, "PCM: no live HID input; no output sent\n");- return false;- }- return true;-}--bool DSBPCMWorkerIsReady(void) {- return atomic_load(&pcmWorkerReady);-}diff --git a/controllers/dualsense/audio-test.c b/controllers/dualsense/audio-test.cdeleted file mode 100644index d96e769..0000000--- a/controllers/dualsense/audio-test.c+++ /dev/null@@ -1,153 +0,0 @@-#include <CoreAudio/CoreAudio.h>-#include <AudioUnit/AudioUnit.h>-#include <assert.h>-#include <stdio.h>-#include <stdlib.h>-#include <unistd.h>-#include <stdatomic.h>-#include <math.h>-#include <string.h>-static atomic_uint calls;-static unsigned sampleBits = 32;-static bool floating = true, signedPCM = false;-static const char *mode = "normal";-static uint8_t alternateBuffer[1920 * 16];-static void storeSample(uint8_t *out, float sample) {- if (floating) {- memcpy(out, &sample, sizeof(sample));- return;- }- double midpoint = ldexp(1.0, sampleBits - 1);- int64_t value = llrint(sample * midpoint);- if (!signedPCM) {- value += (int64_t)midpoint;- }- uint32_t bits = (uint32_t)value;- memcpy(out, &bits, sampleBits / 8);-}-static OSStatus render(void *ctx, AudioUnitRenderActionFlags *f, const AudioTimeStamp *t,- UInt32 bus, UInt32 n, AudioBufferList *list) {- assert(list->mNumberBuffers == 1);- if (!strcmp(mode, "fail")) {- atomic_fetch_add(&calls, 1);- return -1;- }- if (!strcmp(mode, "external")) {- assert(list->mBuffers[0].mDataByteSize <= sizeof(alternateBuffer));- list->mBuffers[0].mData = alternateBuffer;- }- uint8_t *samples = list->mBuffers[0].mData;- unsigned width = sampleBits / 8;- for (unsigned i = 0; i < n; i++) {- storeSample(samples + (i * 4) * width, .75);- storeSample(samples + (i * 4 + 1) * width, .75);- storeSample(samples + (i * 4 + 2) * width, -.125);- storeSample(samples + (i * 4 + 3) * width, .5);- }- if (!strcmp(mode, "silence")) {- *f |= kAudioUnitRenderAction_OutputIsSilence;- } else if (!strcmp(mode, "short")) {- list->mBuffers[0].mDataByteSize = 0;- }- atomic_fetch_add(&calls, 1);- return 0;-}-int main(int argc, char **argv) {- if (argc > 1) {- floating = argv[1][0] == 'f';- signedPCM = argv[1][0] == 's';- sampleBits = (unsigned)atoi(argv[1] + 1);- }- if (argc > 2) {- mode = argv[2];- }- AudioObjectPropertyAddress a = {kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal,- kAudioObjectPropertyElementMain};- UInt32 n = 0;- assert(!AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &a, 0, NULL, &n));- AudioObjectID *ids = calloc(1, n);- assert(!AudioObjectGetPropertyData(kAudioObjectSystemObject, &a, 0, NULL, &n, ids));- bool found = false;- for (unsigned i = 0; i < n / 4; i++) {- if (ids[i] == 0x44533542) {- found = true;- }- }- free(ids);- assert(found);- if (!strcmp(mode, "volume")) {- a.mSelector = kAudioDevicePropertyVolumeScalar;- for (UInt32 element = 0; element <= 4; element++) {- a.mElement = element;- Float32 volume = element == 0 ? .5 : element == 3 ? .5 : 1;- assert(!AudioObjectSetPropertyData(0x44533542, &a, 0, NULL, sizeof(volume), &volume));- Float32 observed = -1;- n = sizeof(observed);- assert(!AudioObjectGetPropertyData(0x44533542, &a, 0, NULL, &n, &observed));- assert(observed == volume);- }- } else if (!strcmp(mode, "mute")) {- a.mSelector = kAudioDevicePropertyMute;- UInt32 muted = 1;- assert(!AudioObjectSetPropertyData(0x44533542, &a, 0, NULL, sizeof(muted), &muted));- }- AudioComponentDescription d = {kAudioUnitType_Output, kAudioUnitSubType_HALOutput,- kAudioUnitManufacturer_Apple, 0, 0};- AudioComponent comp = AudioComponentFindNext(NULL, &d);- assert(comp);- AudioComponentInstance unit;- assert(!AudioComponentInstanceNew(comp, &unit));- UInt32 dev = 0x44533542;- assert(!AudioUnitSetProperty(unit, kAudioOutputUnitProperty_CurrentDevice,- kAudioUnitScope_Global, 0, &dev, 4));- AudioStreamBasicDescription fmt = {48000,- kAudioFormatLinearPCM,- kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,- 16,- 1,- 16,- 4,- 32,- 0};- fmt.mBitsPerChannel = sampleBits;- fmt.mBytesPerFrame = fmt.mBytesPerPacket = 4 * (sampleBits / 8);- fmt.mFormatFlags = kAudioFormatFlagIsPacked | (floating ? kAudioFormatFlagIsFloat- : signedPCM ? kAudioFormatFlagIsSignedInteger- : 0);- AudioStreamBasicDescription invalid = fmt;- invalid.mSampleRate = NAN;- assert(AudioUnitSetProperty(unit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0,- &invalid, sizeof(invalid)) == kAudioUnitErr_FormatNotSupported);- invalid = fmt;- invalid.mBytesPerPacket = 0;- assert(AudioUnitSetProperty(unit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0,- &invalid, sizeof(invalid)) == kAudioUnitErr_FormatNotSupported);- UInt32 current = 0, currentSize = sizeof(current);- assert(!AudioUnitGetProperty(unit, kAudioOutputUnitProperty_CurrentDevice,- kAudioUnitScope_Global, 0, ¤t, ¤tSize));- assert(current == dev);- assert(!AudioUnitSetProperty(unit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0,- &fmt, sizeof(fmt)));- AURenderCallbackStruct cb = {render, NULL};- assert(!AudioUnitSetProperty(unit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,- 0, &cb, sizeof(cb)));- assert(!AudioUnitInitialize(unit));- assert(!AudioOutputUnitStart(unit));- usleep(150000);- // A slow host may start the renderer late; wait up to 2s more.- for (int i = 0; i < 200 && atomic_load(&calls) < 5; i++) {- usleep(10000);- }- assert(AudioUnitSetProperty(unit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,- 0, &cb, sizeof(cb)) == kAudioUnitErr_CannotDoInCurrentContext);- // Uninitialize must join the renderer even when the client omitted Stop.- assert(!AudioUnitUninitialize(unit));- unsigned stoppedAt = atomic_load(&calls);- assert(stoppedAt >= 5);- usleep(30000);- assert(atomic_load(&calls) == stoppedAt);- assert(!AudioOutputUnitStop(unit));- assert(!AudioComponentInstanceDispose(unit));- printf("PASS callbacks=%u format=%s mode=%s\n", atomic_load(&calls), argc > 1 ? argv[1] : "f32",- mode);-}diff --git a/controllers/dualsense/bridge.m b/controllers/dualsense/bridge.mdeleted file mode 100644index dae955d..0000000--- a/controllers/dualsense/bridge.m+++ /dev/null@@ -1,248 +0,0 @@-// Present the Bluetooth DualSense through Wine's USB HID interface.-#import <Foundation/Foundation.h>-#import <IOKit/hid/IOHIDManager.h>-#include <arpa/inet.h>-#include <sys/socket.h>-#include <pthread.h>-#include <stdatomic.h>-#include <unistd.h>-#include <math.h>-#include "protocol.h"-#include "descriptor.h"-#include "Bridge.h"-static bool enabled, raw, pcmMode;-static int sock = -1;-static uint8_t token[16];-static uint32_t sequence;-static pthread_mutex_t senderLock = PTHREAD_MUTEX_INITIALIZER;-static struct sockaddr_in dest;-static CFDataRef descriptor;-static CFNumberRef usbInput, usbOutput;-static bool bluetooth(IOHIDDeviceRef d) {- if (!enabled) {- return false;- }- int vid = 0, pid = 0;- CFTypeRef v = IOHIDDeviceGetProperty(d, CFSTR(kIOHIDVendorIDKey));- if (v && CFGetTypeID(v) == CFNumberGetTypeID()) {- CFNumberGetValue(v, kCFNumberIntType, &vid);- }- v = IOHIDDeviceGetProperty(d, CFSTR(kIOHIDProductIDKey));- if (v && CFGetTypeID(v) == CFNumberGetTypeID()) {- CFNumberGetValue(v, kCFNumberIntType, &pid);- }- CFStringRef tr = IOHIDDeviceGetProperty(d, CFSTR(kIOHIDTransportKey));- return vid == 0x54c && pid == 0xce6 && tr && CFGetTypeID(tr) == CFStringGetTypeID() &&- CFStringHasPrefix(tr, CFSTR("Bluetooth"));-}-void DSBSendPacket(uint32_t kind, float left, float right, const uint8_t *report, size_t size) {- if (!enabled || sock < 0) {- return;- }- DSBPacket p = {.magic = DSB_MAGIC,- .kind = kind,- .pid = getpid(),- .timestamp = CFAbsoluteTimeGetCurrent(),- .left = left,- .right = right};- memcpy(p.token, token, 16);- if (report) {- memcpy(p.report, report, MIN(size, 64));- }- // Audio and HID callbacks may run on different threads. Assign the sequence- // at the send boundary so a newer datagram cannot overtake an older control.- pthread_mutex_lock(&senderLock);- p.sequence = sequence++;- ssize_t sent = sendto(sock, &p, sizeof(p), MSG_DONTWAIT, (void *)&dest, sizeof(dest));- int sendError = sent < 0 ? errno : 0;- pthread_mutex_unlock(&senderLock);- static atomic_uint logged;- unsigned bit = 1u << kind;- if (!(atomic_fetch_or(&logged, bit) & bit)) {- fprintf(stderr, "DSB: first packet pid=%d kind=%u port=%u bytes=%ld errno=%d\n", getpid(),- kind, ntohs(dest.sin_port), (long)sent, sendError);- }-}-__attribute__((constructor)) static void initialize(void) {- const char *port = getenv("DSB_PORT"), *secret = getenv("DSB_TOKEN"), *mode = getenv("DSB_RAW");- if (!port || !secret || strlen(secret) != 32) {- return;- }- char *end = NULL;- long n = strtol(port, &end, 10);- if (end == port || *end || n < 1024 || n > 65535 || !DSBParseToken(secret, token)) {- return;- }- sock = socket(AF_INET, SOCK_DGRAM, 0);- if (sock < 0) {- return;- }- dest = (struct sockaddr_in){.sin_len = sizeof(dest),- .sin_family = AF_INET,- .sin_port = htons(n),- .sin_addr.s_addr = htonl(INADDR_LOOPBACK)};- raw = mode && atoi(mode) == 1;- const char *pcm = getenv("DSB_PCM");- pcmMode = (mode && !strcmp(mode, "1:pcm")) || (pcm && !strcmp(pcm, "1"));- descriptor = CFDataCreate(NULL, usb_descriptor, sizeof(usb_descriptor));- int a = 78, b = 48;- usbInput = CFNumberCreate(NULL, kCFNumberIntType, &a);- usbOutput = CFNumberCreate(NULL, kCFNumberIntType, &b);- enabled = true;- fprintf(stderr, "DSB: Bluetooth bridge loaded pid=%d raw=%d pcm=%d port=%u\n", getpid(), raw,- pcmMode, ntohs(dest.sin_port));-}-static CFTypeRef property(IOHIDDeviceRef d, CFStringRef key) {- if (raw && bluetooth(d)) {- if (CFEqual(key, CFSTR(kIOHIDTransportKey))) {- return CFSTR("USB");- }- if (CFEqual(key, CFSTR(kIOHIDManufacturerKey))) {- return CFSTR("Sony Interactive Entertainment");- }- if (CFEqual(key, CFSTR(kIOHIDReportDescriptorKey))) {- return descriptor;- }- if (CFEqual(key, CFSTR(kIOHIDMaxInputReportSizeKey))) {- return usbInput;- }- if (CFEqual(key, CFSTR(kIOHIDMaxOutputReportSizeKey))) {- return usbOutput;- }- }- return IOHIDDeviceGetProperty(d, key);-}-DSB_INTERPOSE(property, IOHIDDeviceGetProperty);-typedef struct Reader {- IOHIDDeviceRef d;- IOHIDReportCallback cb;- void *ctx;- uint8_t buffer[1024];- struct Reader *next;-} Reader;-// Keep callback contexts at stable addresses until process exit, including after-// unregister: IOKit may still have an in-flight callback on the device run loop.-static Reader *readers;-static pthread_mutex_t readersLock = PTHREAD_MUTEX_INITIALIZER;-static void input(void *c, IOReturn result, void *sender, IOHIDReportType type, uint32_t id,- uint8_t *bytes, CFIndex length) {- Reader *r = c;- pthread_mutex_lock(&readersLock);- IOHIDReportCallback cb = r->cb;- void *context = r->ctx;- pthread_mutex_unlock(&readersLock);- if (!cb) {- return;- }- if (result == 0 && id == 0x31 && length >= 66) {- uint8_t usb[64] = {1};- memcpy(usb + 1, bytes + 2, 63);- cb(context, result, sender, type, 1, usb, 64);- } else if (result == 0 && id == 1 && length <= 10) {- // Feature 05 enables full reports; abbreviated Bluetooth reports lack USB fields.- } else {- cb(context, result, sender, type, id, bytes, length);- }-}-static void registerInput(IOHIDDeviceRef d, uint8_t *buffer, CFIndex len, IOHIDReportCallback cb,- void *ctx) {- if (!raw || !bluetooth(d)) {- IOHIDDeviceRegisterInputReportCallback(d, buffer, len, cb, ctx);- return;- }- pthread_mutex_lock(&readersLock);- Reader *r = readers;- while (r && r->d != d) {- r = r->next;- }- if (!r) {- r = calloc(1, sizeof(*r));- if (r) {- r->d = (IOHIDDeviceRef)CFRetain(d);- r->next = readers;- readers = r;- }- }- if (r) {- r->cb = cb;- r->ctx = ctx;- }- pthread_mutex_unlock(&readersLock);- if (!r) {- fprintf(stderr, "DSB: cannot allocate Bluetooth input callback\n");- return;- }- IOHIDDeviceRegisterInputReportCallback(d, r->buffer, sizeof(r->buffer), cb ? input : NULL,- cb ? r : NULL);- if (cb) {- uint8_t f[64] = {5};- CFIndex n = 41;- IOHIDDeviceGetReport(d, kIOHIDReportTypeFeature, 5, f, &n);- }-}-DSB_INTERPOSE(registerInput, IOHIDDeviceRegisterInputReportCallback);-// USB clients (including Sony's PC library) disable the physical radio after-// enumeration via feature 08/02. The virtual USB transport uses that radio,-// so acknowledge this exact transport-management request locally. Unknown-// feature reports still pass through unchanged.-static bool virtualRadioDisable(IOHIDReportType type, CFIndex id, const uint8_t *b, CFIndex n) {- if (type != kIOHIDReportTypeFeature || id != 8 || !b || n != 48 || b[0] != 8 || b[1] != 2) {- return false;- }- for (CFIndex i = 2; i < n; i++) {- if (b[i]) {- return false;- }- }- return true;-}-static IOReturn setReport(IOHIDDeviceRef d, IOHIDReportType type, CFIndex id, const uint8_t *b,- CFIndex n) {- if (raw && bluetooth(d) && type == kIOHIDReportTypeFeature) {- static atomic_uint count;- if (atomic_fetch_add(&count, 1) < 20) {- fprintf(stderr, "DSB: feature write pid=%d id=%ld size=%ld head=", getpid(), (long)id,- (long)n);- for (CFIndex i = 0; i < MIN(n, 8); i++) {- fprintf(stderr, "%02x", b[i]);- }- fprintf(stderr, "\n");- }- }- if (raw && bluetooth(d) && virtualRadioDisable(type, id, b, n)) {- static atomic_uint handled;- if (atomic_fetch_add(&handled, 1) < 4) {- fprintf(stderr, "DSB: virtual USB radio-disable acknowledged; Bluetooth retained\n");- }- return kIOReturnSuccess;- }- if (raw && bluetooth(d) && type == kIOHIDReportTypeOutput && id == 2 && n >= 48 && b[0] == 2) {- DSBSendPacket(DSB_OUTPUT, 0, 0, b, n);- return kIOReturnSuccess;- }- return IOHIDDeviceSetReport(d, type, id, b, n);-}-DSB_INTERPOSE(setReport, IOHIDDeviceSetReport);-static IOReturn getReport(IOHIDDeviceRef d, IOHIDReportType type, CFIndex id, uint8_t *b,- CFIndex *n) {- IOReturn r = IOHIDDeviceGetReport(d, type, id, b, n);- if (raw && bluetooth(d)) {- static atomic_uint count[256];- if (id >= 0 && id < 256 && atomic_fetch_add(&count[id], 1) < 4) {- fprintf(stderr, "DSB: HID get type=%d id=%ld size=%ld result=%x\n", type, (long)id,- (long)*n, r);- }- }- return r;-}-DSB_INTERPOSE(getReport, IOHIDDeviceGetReport);--bool DSBBridgeEnabled(void) {- return enabled;-}-bool DSBRawControllerEnabled(void) {- return raw;-}-bool DSBDirectPCMEnabled(void) {- return pcmMode;-}diff --git a/controllers/dualsense/broker.m b/controllers/dualsense/broker.mdeleted file mode 100644index e080853..0000000--- a/controllers/dualsense/broker.m+++ /dev/null@@ -1,880 +0,0 @@-#import <AppKit/AppKit.h>-#import <GameController/GameController.h>-#import <CoreHaptics/CoreHaptics.h>-#import <IOKit/hid/IOHIDManager.h>-#include <arpa/inet.h>-#include <fcntl.h>-#include <signal.h>-#include <unistd.h>-#include <zlib.h>-#include <pthread.h>-#include <stdatomic.h>-#include <mach/mach.h>-#include <limits.h>-#include <time.h>-#include "BrokerInternal.h"-#include "protocol.h"-#include "Calibration.h"-#include "Controls.h"--// Local per-session service. Only receives packets bearing the launch token.-// --pcm selects the bounded direct PCM transport; default retains Core Haptics.-static CHHapticEngine *engines[2];-static atomic_bool engineRunning[2];-static id<CHHapticPatternPlayer> players[2];-static float lastLevel[2] = {-1, -1};-static CHHapticPattern *silentPattern;-static double playerStart;-static GCDualSenseGamepad *nativePad;-// Optional grace period for interleaved active-trigger and reset commands.-// Off commands are delayed only briefly after an active feedback command.-// A genuine release is applied within resetGrace; effect bytes stay unchanged.-static double resetGrace, lastActive[2], releaseAt[2];-static uint8_t releaseEffect[2][11];-static unsigned suppressedResets[2];-static uint64_t ledCommands, playerCommands;-static uint32_t ledSource;-static uint8_t ledRGB[3], playerLED;-DSBBrokerState dsb = {.outputLock = PTHREAD_MUTEX_INITIALIZER};-static uint64_t writeTimeoutNS(void) {- return dsb.pcmMode ? 80000000 : 250000000;-}--static bool markWriteTimeout(uint64_t started) {- uint64_t now = clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW);- if (!started || now - started <= writeTimeoutNS() ||- atomic_load(&dsb.writeStartedNS) != started) {- return false;- }- if (!atomic_exchange(&dsb.stalled, true)) {- atomic_fetch_add(&dsb.errors, 1);- fprintf(stderr, "HID output timed out after %.1f ms\n", (now - started) / 1e6);- }- return true;-}--bool DSBOutputWriteTimedOut(void) {- return markWriteTimeout(atomic_load(&dsb.writeStartedNS));-}--bool DSBWriteOutput(const uint8_t *report, unsigned size) {- if (atomic_load(&dsb.stalled)) {- return false;- }- uint64_t started = clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW);- atomic_store(&dsb.writeStartedNS, started);- IOReturn result =- dsb.dry ? kIOReturnSuccess- : IOHIDDeviceSetReport(dsb.hid, kIOHIDReportTypeOutput, report[0], report, size);- markWriteTimeout(started);- atomic_store(&dsb.writeStartedNS, 0);- atomic_fetch_add(&dsb.reports, 1);- if (result) {- atomic_fetch_add(&dsb.errors, 1);- atomic_store(&dsb.stalled, true);- fprintf(stderr, "HID output failed: error=0x%x report=0x%02x size=%u\n", result, report[0],- size);- }- return !atomic_load(&dsb.stalled);-}--static void stopSignal(int s) {- dsb.quitting = 1;-}-// Read readiness wakes the run loop immediately; the main loop drains and-// authenticates datagrams before rearming this source.-static void socketReady(CFFileDescriptorRef descriptor, CFOptionFlags flags, void *context) {}-static void queueOutput(const uint8_t *usb) {- const uint8_t *src = usb + 1;- pthread_mutex_lock(&dsb.outputLock);- // Merge independent valid fields, optionally defer transient trigger resets.- double now = CFAbsoluteTimeGetCurrent();- for (int side = 0; side < 2; side++) {- unsigned bit = 4u << side, offset = 10 + side * 11;- if (!(src[0] & bit)) {- continue;- }- const uint8_t *effect = src + offset;- if (effect[0] == 0x21) {- lastActive[side] = now;- releaseAt[side] = 0;- } else if (resetGrace > 0 && (effect[0] == 5 || effect[0] == 0) &&- dsb.pending[offset] == 0x21 && now - lastActive[side] < resetGrace) {- releaseAt[side] = lastActive[side] + resetGrace;- memcpy(releaseEffect[side], effect, 11);- suppressedResets[side]++;- continue;- } else {- releaseAt[side] = 0;- }- dsb.pending[0] |= bit;- memcpy(dsb.pending + offset, effect, 11);- }- if (src[1] & 4) {- dsb.pending[1] |= 4;- memcpy(dsb.pending + 44, src + 44, 3);- }- if (src[1] & 0x10) {- dsb.pending[1] |= 0x10;- dsb.pending[43] = src[43];- }- if (src[1] & 1) {- dsb.pending[1] |= 1;- dsb.pending[8] = src[8];- }- dsb.outputDirty = dsb.pending[0] || dsb.pending[1];- pthread_mutex_unlock(&dsb.outputLock);- if (dsb.pcmMode) {- DSBPCMNotify();- }-}-static void *outputWorker(void *unused) {- @autoreleasepool {- while (atomic_load(&dsb.workerRunning)) {- @autoreleasepool {- uint8_t payload[47], snapshot[47];- bool changed = false;- pthread_mutex_lock(&dsb.outputLock);- if (dsb.outputDirty) {- memcpy(snapshot, dsb.pending, 47);- dsb.outputDirty = false;- changed = DSBControlDelta(snapshot, dsb.lastSent, dsb.haveLast, payload);- }- pthread_mutex_unlock(&dsb.outputLock);- if (changed && !atomic_load(&dsb.stalled)) {- uint8_t b[78] = {0x31};- b[1] = (dsb.btSequence++ & 15) << 4;- b[2] = 0x10;- memcpy(b + 3, payload, 47);- uint8_t seed = 0xa2;- uLong crc = crc32(0, &seed, 1);- crc = crc32(crc, b, 74);- for (int i = 0; i < 4; i++) {- b[74 + i] = crc >> (8 * i);- }- if (!DSBWriteOutput(b, sizeof(b))) {- break;- }- pthread_mutex_lock(&dsb.outputLock);- memcpy(dsb.lastSent, snapshot, 47);- dsb.haveLast = true;- NSMutableArray *r2 = [NSMutableArray array];- for (int i = 10; i < 21; i++) {- [r2 addObject:@(payload[i])];- }- [dsb.sentHistory addObject:@{- @"at" : @([[NSDate date] timeIntervalSince1970]),- @"r2" : r2- }];- if (dsb.sentHistory.count > 40) {- [dsb.sentHistory removeObjectAtIndex:0];- }- pthread_mutex_unlock(&dsb.outputLock);- }- }- usleep(16000);- }- }- atomic_store(&dsb.workerExited, true);- return NULL;-}-static bool setLevel(int ch, float level) {- level = fmaxf(0, fminf(1, level));- if (fabsf(lastLevel[ch] - level) < .001) {- return true;- }- if (dsb.dry) {- lastLevel[ch] = level;- return true;- }- if (!atomic_load(&engineRunning[ch])) {- return level == 0;- }- NSError *error = nil;- CHHapticDynamicParameter *p = [[CHHapticDynamicParameter alloc]- initWithParameterID:CHHapticDynamicParameterIDHapticIntensityControl- value:level- relativeTime:0];- @try {- if (![players[ch] sendParameters:@[ p ] atTime:CHHapticTimeImmediate error:&error]) {- fprintf(stderr, "Core Haptics update failed: %s\n", error.description.UTF8String);- return false;- }- } @catch (NSException *exception) {- atomic_store(&engineRunning[ch], false);- fprintf(stderr, "Core Haptics became unavailable: %s\n", exception.reason.UTF8String);- return false;- }- lastLevel[ch] = level;- return true;-}-static bool prepare(GCController *pad) {- NSArray *localities = @[ GCHapticsLocalityLeftHandle, GCHapticsLocalityRightHandle ];- for (int i = 0; i < 2; i++) {- engines[i] = [pad.haptics createEngineWithLocality:localities[i]];- if (!engines[i]) {- fprintf(stderr, "No haptic engine locality=%s supported=%s\n",- [localities[i] UTF8String],- pad.haptics.supportedLocalities.description.UTF8String);- return false;- }- engines[i].autoShutdownEnabled = NO;- engines[i].stoppedHandler = ^(CHHapticEngineStoppedReason reason) {- atomic_store(&engineRunning[i], false);- fprintf(stderr, "Core Haptics stopped: %ld\n", (long)reason);- dsb.quitting = 1;- };- engines[i].resetHandler = ^{- atomic_store(&engineRunning[i], false);- fprintf(stderr, "Core Haptics reset; session must restart\n");- dsb.quitting = 1;- };- NSError *e = nil;- if (![engines[i] startAndReturnError:&e]) {- fprintf(stderr, "Engine start ch=%d error=%s\n", i, e.description.UTF8String);- return false;- }- atomic_store(&engineRunning[i], true);- CHHapticEventParameter *one = [[CHHapticEventParameter alloc]- initWithParameterID:CHHapticEventParameterIDHapticIntensity- value:1];- CHHapticEvent *event =- [[CHHapticEvent alloc] initWithEventType:CHHapticEventTypeHapticContinuous- parameters:@[ one ]- relativeTime:0- duration:30];- CHHapticDynamicParameter *zero = [[CHHapticDynamicParameter alloc]- initWithParameterID:CHHapticDynamicParameterIDHapticIntensityControl- value:0- relativeTime:0];- CHHapticPattern *pattern = [[CHHapticPattern alloc] initWithEvents:@[ event ]- parameters:@[ zero ]- error:&e];- silentPattern = pattern;- players[i] = [engines[i] createPlayerWithPattern:pattern error:&e];- if (!players[i]) {- fprintf(stderr, "Player create ch=%d error=%s\n", i, e.description.UTF8String);- return false;- }-- if (![players[i] startAtTime:CHHapticTimeImmediate error:&e]) {- fprintf(stderr, "Player start ch=%d error=%s\n", i, e.description.UTF8String);- return false;- }- lastLevel[i] = 0;- }- playerStart = CFAbsoluteTimeGetCurrent();- return true;-}-static bool renewPlayers(void) {- if (dsb.dry || CFAbsoluteTimeGetCurrent() - playerStart < 25) {- return true;- }- for (int i = 0; i < 2; i++) {- NSError *e = nil;- id<CHHapticPatternPlayer> next = [engines[i] createPlayerWithPattern:silentPattern- error:&e];- if (!next) {- return false;- }- [players[i] stopAtTime:CHHapticTimeImmediate error:NULL];- players[i] = next;- if (![next startAtTime:CHHapticTimeImmediate error:&e]) {- return false;- }- lastLevel[i] = -1;- }- playerStart = CFAbsoluteTimeGetCurrent();- return true;-}-typedef struct {- uint32_t pid, sequence;- double lastLevelAt, lastRumbleAt, lastPacketAt;- float levelLeft, levelRight, rumbleLeft, rumbleRight;- bool initialized;-} Source;-static Source sources[64];--// Source state and metrics are owned by the session's main run loop.-typedef struct {- uint64_t accepted, dropped, levels, outputs;- float left, right, peakLeft, peakRight;-} SessionMetrics;--static bool validPayload(const DSBPacket *packet) {- switch (packet->kind) {- case DSB_LEVEL:- return true;- case DSB_PCM:- return dsb.pcmMode && (packet->report[0] == 0 || packet->report[0] == 30);- case DSB_OUTPUT:- return packet->report[0] == 2;- default:- return false;- }-}--static void receivePackets(int fd, const uint8_t token[16], double now, SessionMetrics *metrics) {- for (int j = 0; j < 1024; j++) {- DSBPacket p;- uint8_t datagram[sizeof(p) + 1];- ssize_t n = recv(fd, datagram, sizeof(datagram), 0);- if (n < 0) {- break;- }- memcpy(&p, datagram, MIN((size_t)n, sizeof(p)));- if (n != sizeof(p) || p.magic != DSB_MAGIC || memcmp(p.token, token, 16) ||- !isfinite(p.timestamp) || fabs(now - p.timestamp) > .25 || !isfinite(p.left) ||- !isfinite(p.right) || !p.pid || !validPayload(&p)) {- metrics->dropped++;- continue;- }- Source *s = NULL;- for (int k = 0; k < 64; k++) {- if (sources[k].pid == p.pid) {- s = sources + k;- break;- }- }- if (!s) {- for (int k = 0; k < 64; k++) {- if (!sources[k].pid || now - sources[k].lastPacketAt > 2) {- s = sources + k;- memset(s, 0, sizeof(*s));- s->pid = p.pid;- break;- }- }- }- if (!s || (s->initialized && (int32_t)(p.sequence - s->sequence) <= 0)) {- metrics->dropped++;- continue;- }- s->initialized = true;- s->lastPacketAt = now;- s->sequence = p.sequence;- if (p.kind == DSB_LEVEL) {- s->lastLevelAt = now;- s->levelLeft = fmaxf(0, fminf(1, p.left));- s->levelRight = fmaxf(0, fminf(1, p.right));- metrics->levels++;- } else if (dsb.pcmMode && p.kind == DSB_PCM && (p.report[0] == 0 || p.report[0] == 30)) {- DSBPCMReceive(&p);- s->lastLevelAt = now;- metrics->levels++;- } else if (p.kind == DSB_OUTPUT && p.report[0] == 2) {- const uint8_t *b = p.report + 1;- if (b[1] & 4) {- if (!ledCommands || memcmp(ledRGB, b + 44, 3) || ledSource != p.pid) {- fprintf(stderr, "LED source=%u rgb=%u,%u,%u flags=%02x/%02x\n", p.pid, b[44],- b[45], b[46], b[0], b[1]);- }- ledCommands++;- ledSource = p.pid;- memcpy(ledRGB, b + 44, 3);- }- if (b[1] & 16) {- if (!playerCommands || playerLED != b[43]) {- fprintf(stderr, "Player LED source=%u value=%02x flags=%02x/%02x\n", p.pid,- b[43], b[0], b[1]);- }- playerCommands++;- playerLED = b[43];- }- queueOutput(p.report);- metrics->outputs++;- if ((b[0] & 3) || (b[38] & 4)) {- s->lastRumbleAt = now;- s->rumbleLeft = b[3] / 255.f;- s->rumbleRight = b[2] / 255.f;- }- // LED/trigger-only transactions leave the last rumble intact.- } else {- metrics->dropped++;- continue;- }- metrics->accepted++;- }-}--static bool updateEffects(double now, float pcmGain, SessionMetrics *metrics) {- pthread_mutex_lock(&dsb.outputLock);- for (int side = 0; side < 2; side++) {- if (releaseAt[side] && now >= releaseAt[side]) {- dsb.pending[0] |= 4u << side;- memcpy(dsb.pending + 10 + side * 11, releaseEffect[side], 11);- releaseAt[side] = 0;- dsb.outputDirty = true;- }- }- pthread_mutex_unlock(&dsb.outputLock);- float l = 0, r = 0;- for (int i = 0; i < 64; i++) {- Source *s = sources + i;- if (now - s->lastLevelAt < .15) {- l = fmaxf(l, DSBCalibratedPCM(s->levelLeft, pcmGain));- r = fmaxf(r, DSBCalibratedPCM(s->levelRight, pcmGain));- }- if (now - s->lastRumbleAt < .5) {- l = fmaxf(l, s->rumbleLeft);- r = fmaxf(r, s->rumbleRight);- }- }- if (dsb.pcmMode) {- float a = 0, b = 0;- for (int i = 0; i < 64; i++) {- if (now - sources[i].lastRumbleAt < .5) {- a = fmaxf(a, sources[i].rumbleLeft);- b = fmaxf(b, sources[i].rumbleRight);- }- }- uint8_t left = (uint8_t)lrintf(a * 255), right = (uint8_t)lrintf(b * 255);- pthread_mutex_lock(&dsb.outputLock);- if (left != dsb.legacyLeft || right != dsb.legacyRight) {- dsb.legacyLeft = left;- dsb.legacyRight = right;- dsb.legacyDirty = true;- }- pthread_mutex_unlock(&dsb.outputLock);- }- if (dsb.pcmMode) {- DSBPCMNotify();- }- metrics->peakLeft = fmaxf(metrics->peakLeft, l);- metrics->peakRight = fmaxf(metrics->peakRight, r);- if (!dsb.pcmMode) {- if (!renewPlayers()) {- return false;- }- if (!setLevel(0, l) || !setLevel(1, r)) {- return false;- }- }-- metrics->left = l;- metrics->right = r;- return true;-}--static void writeStatus(NSString *status, unsigned port, float pcmGain,- const SessionMetrics *metrics) {- NSDictionary *pcmStats = DSBPCMSnapshot();- pthread_mutex_lock(&dsb.outputLock);- NSMutableArray *r2 = [NSMutableArray array];- for (int i = 10; i < 21; i++) {- [r2 addObject:@(dsb.pending[i])];- }- NSDictionary *triggers = @{- @"resetGraceMs" : @(resetGrace * 1000),- @"suppressedR2Resets" : @(suppressedResets[0]),- @"r2" : r2,- @"sentHistory" : [dsb.sentHistory copy],- @"physicalR2Mode" : @(dsb.pcmMode ? -1 : nativePad.rightTrigger.mode),- @"physicalR2Status" : @(dsb.pcmMode ? -1 : nativePad.rightTrigger.status)- };- pthread_mutex_unlock(&dsb.outputLock);- NSDictionary *obj = @{- @"state" : @"running",- @"led" : @{- @"commands" : @(ledCommands),- @"sourcePid" : @(ledSource),- @"rgb" : @[ @(ledRGB[0]), @(ledRGB[1]), @(ledRGB[2]) ],- @"playerCommands" : @(playerCommands),- @"player" : @(playerLED)- },- @"pcm" : pcmStats,- @"triggers" : triggers,- @"pid" : @(getpid()),- @"port" : @(port),- @"accepted" : @(metrics->accepted),- @"dropped" : @(metrics->dropped),- @"pcmBlocks" : @(metrics->levels),- @"pcmGain" : @(pcmGain),- @"outputCommands" : @(metrics->outputs),- @"hidReports" : @(atomic_load(&dsb.reports)),- @"hidErrors" : @(atomic_load(&dsb.errors)),- @"hidStalled" : @(atomic_load(&dsb.stalled)),- @"left" : @(metrics->left),- @"right" : @(metrics->right),- @"peakLeft" : @(metrics->peakLeft),- @"peakRight" : @(metrics->peakRight),- @"updated" : @([[NSDate date] timeIntervalSince1970])- };- [[NSJSONSerialization dataWithJSONObject:obj options:NSJSONWritingPrettyPrinted- error:NULL] writeToFile:status atomically:YES];-}--typedef struct {- NSString *status, *secret;- pid_t parent;- double seconds;- bool probe;- unsigned requestedPort;-} BrokerOptions;--static bool parseArguments(int argc, char **argv, BrokerOptions *options) {- for (int i = 1; i < argc; i++) {- if (!strcmp(argv[i], "--probe")) {- options->probe = true;- } else if (!strcmp(argv[i], "--pcm")) {- dsb.pcmMode = true;- } else if (!strcmp(argv[i], "--trigger-reset-grace-ms") && i + 1 < argc) {- char *end = NULL;- long ms = strtol(argv[++i], &end, 10);- if (end == argv[i] || *end || ms < 0 || ms > 100) {- return false;- }- resetGrace = ms / 1000.;- } else if (!strcmp(argv[i], "--dry-run")) {- dsb.dry = true;- } else if (!strcmp(argv[i], "--token") && i + 1 < argc) {- options->secret = @(argv[++i]);- } else if (!strcmp(argv[i], "--status") && i + 1 < argc) {- options->status = @(argv[++i]);- } else if (!strcmp(argv[i], "--parent") && i + 1 < argc) {- char *end = NULL;- long parent = strtol(argv[++i], &end, 10);- if (end == argv[i] || *end || parent <= 0 || parent > INT_MAX) {- return false;- }- options->parent = (pid_t)parent;- } else if (!strcmp(argv[i], "--seconds") && i + 1 < argc) {- char *end = NULL;- options->seconds = strtod(argv[++i], &end);- if (end == argv[i] || *end || !isfinite(options->seconds) || options->seconds <= 0) {- return false;- }- } else if (!strcmp(argv[i], "--port") && i + 1 < argc) {- char *end = NULL;- long p = strtol(argv[++i], &end, 10);- if (end == argv[i] || *end || p < 1024 || p > 65535) {- return false;- }- options->requestedPort = (unsigned)p;- } else {- return false;- }- }- return true;-}--static int openController(bool probe, IOHIDManagerRef *owner) {- if (dsb.dry) {- if (probe) {- puts("{\"bluetooth\":0,\"usb\":0,\"eligible\":false}");- }- return 0;- }- IOHIDManagerRef manager = NULL;- unsigned bt = 0, usb = 0;- manager = IOHIDManagerCreate(NULL, dsb.pcmMode ? kIOHIDManagerOptionIndependentDevices : 0);- *owner = manager;- if (!manager) {- return 4;- }- IOHIDManagerSetDeviceMatching(- manager, (__bridge CFDictionaryRef)- @{@kIOHIDVendorIDKey : @0x54c,- @kIOHIDProductIDKey : @0xce6});- if (IOHIDManagerOpen(manager, 0)) {- return 4;- }- CFSetRef devices = IOHIDManagerCopyDevices(manager);- if (devices) {- for (id obj in (__bridge NSSet *)devices) {- IOHIDDeviceRef d = (__bridge IOHIDDeviceRef)obj;- NSString *transport =- (__bridge NSString *)IOHIDDeviceGetProperty(d, CFSTR(kIOHIDTransportKey));- if ([transport isEqualToString:@"USB"]) {- usb++;- } else if ([transport hasPrefix:@"Bluetooth"]) {- bt++;- dsb.hid = d;- }- }- if (dsb.hid) {- CFRetain(dsb.hid);- }- CFRelease(devices);- }- if (probe) {- printf("{\"bluetooth\":%u,\"usb\":%u,\"eligible\":%s}\n", bt, usb,- bt == 1 && !usb ? "true" : "false");- return 0;- }- if (bt != 1 || usb) {- fprintf(stderr, "Requires exactly one Bluetooth DualSense and no USB DualSense\n");- return 3;- }- if (IOHIDDeviceOpen(dsb.hid, 0)) {- return 4;- }- [NSApplication sharedApplication];- [NSApp setActivationPolicy:NSApplicationActivationPolicyProhibited];- GCController *pad = nil;- // The raw PCM transport owns HID output. Do not also create a native- // controller/haptic client: its initialization and teardown can write- // competing mode/LED commands. Core Haptics is an explicit fallback only.- if (!dsb.pcmMode) {- GCController.shouldMonitorBackgroundEvents = YES;- for (int i = 0; i < 80 && !pad; i++) {- for (GCController *c in GCController.controllers) {- if ([c.extendedGamepad isKindOfClass:GCDualSenseGamepad.class]) {- pad = c;- break;- }- }- if (!pad) {- [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:.05]];- }- }- nativePad = (GCDualSenseGamepad *)pad.extendedGamepad;- if (!pad || !prepare(pad)) {- fprintf(stderr, "DualSense Core Haptics initialization failed\n");- return 5;- }- }- if (dsb.pcmMode) {- if (!DSBPCMStartInput()) {- return 8;- }- }- if (!dsb.pcmMode) {- [[NSNotificationCenter defaultCenter]- addObserverForName:GCControllerDidDisconnectNotification- object:pad- queue:NSOperationQueue.mainQueue- usingBlock:^(NSNotification *n) {- fprintf(stderr, "Core Haptics controller disconnected\n");- dsb.quitting = 1;- }];- }-- return 0;-}--// Scope cleanup covers probe and every startup failure before the event loop.-// A stalled driver call is the exception: the process exits without touching-// that IOKit connection again, since closing it could block on the same driver.-static void releaseControllerManager(IOHIDManagerRef *manager) {- if (*manager && !atomic_load(&dsb.stalled)) {- IOHIDManagerClose(*manager, 0);- CFRelease(*manager);- }-}--int main(int argc, char **argv) {- @autoreleasepool {- id activity = [[NSProcessInfo processInfo]- beginActivityWithOptions:NSActivityUserInitiated | NSActivityLatencyCritical- reason:@"DualSense real-time haptic transport"];- setbuf(stdout, NULL);- dsb.sentHistory = [NSMutableArray array];- signal(SIGTERM, stopSignal);- signal(SIGINT, stopSignal);- BrokerOptions options = {0};- uint8_t token[16] = {0};- if (!parseArguments(argc, argv, &options) ||- (!options.probe && !DSBParseToken(options.secret.UTF8String, token))) {- return 64;- }- NSString *status = options.status;- IOHIDManagerRef manager __attribute__((cleanup(releaseControllerManager))) = NULL;- int controllerResult = openController(options.probe, &manager);- if (controllerResult || options.probe) {- if (dsb.hid) {- CFRelease(dsb.hid);- dsb.hid = NULL;- }- return controllerResult;- }- if (dsb.pcmMode) {- task_category_policy_data_t policy = {TASK_FOREGROUND_APPLICATION};- kern_return_t result =- task_policy_set(mach_task_self(), TASK_CATEGORY_POLICY, (task_policy_t)&policy,- TASK_CATEGORY_POLICY_COUNT);- fprintf(stderr, "PCM task scheduling role result=%d\n", result);- }- int fd = socket(AF_INET, SOCK_DGRAM, 0);- if (fd < 0) {- return 6;- }- struct sockaddr_in addr = {.sin_len = sizeof(addr),- .sin_family = AF_INET,- .sin_port = htons(options.requestedPort),- .sin_addr.s_addr = htonl(INADDR_LOOPBACK)};- if (bind(fd, (void *)&addr, sizeof(addr))) {- return 6;- }- socklen_t len = sizeof(addr);- if (getsockname(fd, (void *)&addr, &len) || fcntl(fd, F_SETFL, O_NONBLOCK) < 0) {- return 6;- }- unsigned port = ntohs(addr.sin_port);- CFFileDescriptorRef socketEvents = NULL;- CFRunLoopSourceRef socketSource = NULL;- if (dsb.pcmMode) {- socketEvents = CFFileDescriptorCreate(NULL, fd, false, socketReady, NULL);- if (!socketEvents) {- fprintf(stderr, "PCM socket event source unavailable\n");- return 9;- }- socketSource = CFFileDescriptorCreateRunLoopSource(NULL, socketEvents, 0);- if (!socketSource) {- fprintf(stderr, "PCM socket run loop source unavailable\n");- return 9;- }- CFRunLoopAddSource(CFRunLoopGetMain(), socketSource, kCFRunLoopDefaultMode);- }- pthread_t worker;- atomic_store(&dsb.workerRunning, true);- if (pthread_create(&worker, NULL, dsb.pcmMode ? DSBPCMWorker : outputWorker, NULL)) {- fprintf(stderr, "Controller writer thread unavailable\n");- return 9;- }- if (dsb.pcmMode) {- double deadline = CFAbsoluteTimeGetCurrent() + 5;- while (!DSBPCMWorkerIsReady() && CFAbsoluteTimeGetCurrent() < deadline) {- CFRunLoopRunInMode(kCFRunLoopDefaultMode, .002, true);- }- if (!DSBPCMWorkerIsReady() || atomic_load(&dsb.stalled)) {- fprintf(stderr, "PCM writer did not initialize\n");- atomic_store(&dsb.workerRunning, false);- atomic_store(&dsb.stalled, true);- return 9;- }- }- printf("{\"ready\":true,\"port\":%u,\"pid\":%d}\n", port, getpid());- // The notproton folder is read until the app moves it to bridgeplay.- NSString *supportPath = [NSHomeDirectory()- stringByAppendingPathComponent:@"Library/Application Support/bridgeplay"];- NSString *legacySupportPath = [NSHomeDirectory()- stringByAppendingPathComponent:@"Library/Application Support/notproton"];- BOOL isDirectory = NO;- if (![[NSFileManager defaultManager] fileExistsAtPath:supportPath isDirectory:&isDirectory]- && [[NSFileManager defaultManager] fileExistsAtPath:legacySupportPath isDirectory:&isDirectory]- && isDirectory)- supportPath = legacySupportPath;- NSString *calibrationPath = [supportPath- stringByAppendingPathComponent:@"controllers/dualsense/calibration.json"];- float pcmGain = 1;- double nextCalibration = 0;- double start = CFAbsoluteTimeGetCurrent(), nextStatus = 0;- SessionMetrics metrics = {0};- while (!dsb.quitting &&- (!options.seconds || CFAbsoluteTimeGetCurrent() - start < options.seconds)) {- @autoreleasepool {- double now = CFAbsoluteTimeGetCurrent();- if (options.parent && kill(options.parent, 0) && errno == ESRCH) {- break;- }- if (DSBOutputWriteTimedOut() || atomic_load(&dsb.stalled)) {- break;- }- if (now >= nextCalibration) {- pcmGain = DSBPCMGain(calibrationPath);- nextCalibration = now + 1;- }- receivePackets(fd, token, now, &metrics);- if (!updateEffects(now, pcmGain, &metrics)) {- break;- }- if (status && now >= nextStatus) {- writeStatus(status, port, pcmGain, &metrics);- nextStatus = now + 1;- }- if (dsb.pcmMode) {- CFFileDescriptorEnableCallBacks(socketEvents, kCFFileDescriptorReadCallBack);- CFRunLoopRunInMode(kCFRunLoopDefaultMode, .002, true);- } else {- [[NSRunLoop currentRunLoop]- runUntilDate:[NSDate dateWithTimeIntervalSinceNow:.01]];- }- }- }- if (!dsb.pcmMode) {- setLevel(0, 0);- setLevel(1, 0);- }- // Release triggers only if this session touched them. Leave unrelated Steam output alone.- resetGrace = 0; // Cleanup must never defer release.- if (!atomic_load(&dsb.stalled) && !atomic_load(&dsb.deviceRemoved) &&- (dsb.pending[0] & 12)) {- uint8_t reset[64];- DSBTriggerRelease(dsb.pending[0], reset);- queueOutput(reset);- double deadline = CFAbsoluteTimeGetCurrent() + .25;- while (!atomic_load(&dsb.stalled) && CFAbsoluteTimeGetCurrent() < deadline) {- uint8_t unsent[47];- pthread_mutex_lock(&dsb.outputLock);- bool pending = DSBControlDelta(dsb.pending, dsb.lastSent, dsb.haveLast, unsent);- pthread_mutex_unlock(&dsb.outputLock);- if (!pending || DSBOutputWriteTimedOut()) {- break;- }- CFRunLoopRunInMode(kCFRunLoopDefaultMode, .002, true);- }- }- atomic_store(&dsb.workerRunning, false);- while (!atomic_load(&dsb.workerExited) && !atomic_load(&dsb.stalled)) {- DSBOutputWriteTimedOut();- CFRunLoopRunInMode(kCFRunLoopDefaultMode, .002, true);- }- if (atomic_load(&dsb.workerExited)) {- pthread_join(worker, NULL);- }- for (int i = 0; i < 2; i++) {- // Disconnect can stop the engine before cleanup. PatternPlayer stop then- // raises an ObjC exception rather than returning NSError on macOS 27.- @try {- if (atomic_load(&engineRunning[i])) {- [players[i] stopAtTime:CHHapticTimeImmediate error:NULL];- }- [engines[i] stopWithCompletionHandler:nil];- } @catch (NSException *exception) {- fprintf(stderr, "Core Haptics already stopped during cleanup: %s\n",- exception.reason.UTF8String);- }- atomic_store(&engineRunning[i], false);- }- if (dsb.hid && !atomic_load(&dsb.stalled)) {- if (dsb.pcmMode) {- IOHIDDeviceUnscheduleFromRunLoop(dsb.hid, CFRunLoopGetMain(),- kCFRunLoopCommonModes);- }- IOHIDDeviceClose(dsb.hid, 0);- CFRelease(dsb.hid);- }- [[NSProcessInfo processInfo] endActivity:activity];- if (status) {- writeStatus(status, port, pcmGain, &metrics);- NSData *data = [NSData dataWithContentsOfFile:status];- NSMutableDictionary *final =- data ? [[NSJSONSerialization JSONObjectWithData:data- options:NSJSONReadingMutableContainers- error:NULL] mutableCopy]- : [NSMutableDictionary dictionary];- if (!final) {- final = [NSMutableDictionary dictionary];- }- final[@"state"] = atomic_load(&dsb.deviceRemoved) ? @"disconnected"- : atomic_load(&dsb.stalled) ? @"output-stopped"- : @"stopped";- final[@"updated"] = @([[NSDate date] timeIntervalSince1970]);- [[NSJSONSerialization dataWithJSONObject:final- options:NSJSONWritingPrettyPrinted- error:NULL] writeToFile:status atomically:YES];- }- if (socketEvents) {- CFFileDescriptorInvalidate(socketEvents);- CFRunLoopRemoveSource(CFRunLoopGetMain(), socketSource, kCFRunLoopDefaultMode);- CFRelease(socketSource);- CFRelease(socketEvents);- }- close(fd);- fprintf(stderr, "Stopped: packets=%llu PCM=%llu output=%llu HID=%u errors=%u\n",- metrics.accepted, metrics.levels, metrics.outputs, atomic_load(&dsb.reports),- atomic_load(&dsb.errors));- return atomic_load(&dsb.deviceRemoved) ? 10 : atomic_load(&dsb.stalled) ? 11 : 0;- }-}diff --git a/controllers/dualsense/descriptor.h b/controllers/dualsense/descriptor.hdeleted file mode 100644index 840996e..0000000--- a/controllers/dualsense/descriptor.h+++ /dev/null@@ -1,20 +0,0 @@-/* Published DualSense USB descriptor: github.com/nondebug/dualsense */-static const unsigned char usb_descriptor[] = {- 0x05, 0x01, 0x09, 0x05, 0xa1, 0x01, 0x85, 0x01, 0x09, 0x30, 0x09, 0x31, 0x09, 0x32, 0x09, 0x35,- 0x09, 0x33, 0x09, 0x34, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x06, 0x81, 0x02, 0x06,- 0x00, 0xff, 0x09, 0x20, 0x95, 0x01, 0x81, 0x02, 0x05, 0x01, 0x09, 0x39, 0x15, 0x00, 0x25, 0x07,- 0x35, 0x00, 0x46, 0x3b, 0x01, 0x65, 0x14, 0x75, 0x04, 0x95, 0x01, 0x81, 0x42, 0x65, 0x00, 0x05,- 0x09, 0x19, 0x01, 0x29, 0x0f, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x0f, 0x81, 0x02, 0x06,- 0x00, 0xff, 0x09, 0x21, 0x95, 0x0d, 0x81, 0x02, 0x06, 0x00, 0xff, 0x09, 0x22, 0x15, 0x00, 0x26,- 0xff, 0x00, 0x75, 0x08, 0x95, 0x34, 0x81, 0x02, 0x85, 0x02, 0x09, 0x23, 0x95, 0x2f, 0x91, 0x02,- 0x85, 0x05, 0x09, 0x33, 0x95, 0x28, 0xb1, 0x02, 0x85, 0x08, 0x09, 0x34, 0x95, 0x2f, 0xb1, 0x02,- 0x85, 0x09, 0x09, 0x24, 0x95, 0x13, 0xb1, 0x02, 0x85, 0x0a, 0x09, 0x25, 0x95, 0x1a, 0xb1, 0x02,- 0x85, 0x20, 0x09, 0x26, 0x95, 0x3f, 0xb1, 0x02, 0x85, 0x21, 0x09, 0x27, 0x95, 0x04, 0xb1, 0x02,- 0x85, 0x22, 0x09, 0x40, 0x95, 0x3f, 0xb1, 0x02, 0x85, 0x80, 0x09, 0x28, 0x95, 0x3f, 0xb1, 0x02,- 0x85, 0x81, 0x09, 0x29, 0x95, 0x3f, 0xb1, 0x02, 0x85, 0x82, 0x09, 0x2a, 0x95, 0x09, 0xb1, 0x02,- 0x85, 0x83, 0x09, 0x2b, 0x95, 0x3f, 0xb1, 0x02, 0x85, 0x84, 0x09, 0x2c, 0x95, 0x3f, 0xb1, 0x02,- 0x85, 0x85, 0x09, 0x2d, 0x95, 0x02, 0xb1, 0x02, 0x85, 0xa0, 0x09, 0x2e, 0x95, 0x01, 0xb1, 0x02,- 0x85, 0xe0, 0x09, 0x2f, 0x95, 0x3f, 0xb1, 0x02, 0x85, 0xf0, 0x09, 0x30, 0x95, 0x3f, 0xb1, 0x02,- 0x85, 0xf1, 0x09, 0x31, 0x95, 0x3f, 0xb1, 0x02, 0x85, 0xf2, 0x09, 0x32, 0x95, 0x0f, 0xb1, 0x02,- 0x85, 0xf4, 0x09, 0x35, 0x95, 0x3f, 0xb1, 0x02, 0x85, 0xf5, 0x09, 0x36, 0x95, 0x03, 0xb1, 0x02,- 0xc0};diff --git a/controllers/dualsense/hid-test.m b/controllers/dualsense/hid-test.mdeleted file mode 100644index cdbf3f0..0000000--- a/controllers/dualsense/hid-test.m+++ /dev/null@@ -1,108 +0,0 @@-#import <Foundation/Foundation.h>-#import <IOKit/hid/IOHIDManager.h>-#include <sys/socket.h>-#include <assert.h>-#include "protocol.h"-#include "Bridge.h"--static IOHIDReportCallback registeredCallback;-static void *registeredContext;-static unsigned physicalWrites, packets, callbacks;-static uint32_t receivedID;-static CFIndex receivedSize;-static uint8_t received[1024];-static DSBPacket sent;--static CFTypeRef mockProperty(IOHIDDeviceRef device, CFStringRef key) {- return CFDictionaryGetValue((CFDictionaryRef)device, key);-}-static void mockRegister(IOHIDDeviceRef device, uint8_t *buffer, CFIndex size,- IOHIDReportCallback callback, void *context) {- registeredCallback = callback;- registeredContext = context;-}-static IOReturn mockGetReport(IOHIDDeviceRef device, IOHIDReportType type, CFIndex reportID,- uint8_t *report, CFIndex *size) {- return kIOReturnSuccess;-}-static IOReturn mockSetReport(IOHIDDeviceRef device, IOHIDReportType type, CFIndex reportID,- const uint8_t *report, CFIndex size) {- physicalWrites++;- return kIOReturnSuccess;-}-static ssize_t mockSend(int socket, const void *bytes, size_t size, int flags,- const struct sockaddr *address, socklen_t length) {- assert(size == sizeof(sent));- memcpy(&sent, bytes, size);- packets++;- return size;-}--#undef DSB_INTERPOSE-#define DSB_INTERPOSE(replacement, original)-#define IOHIDDeviceGetProperty mockProperty-#define IOHIDDeviceRegisterInputReportCallback mockRegister-#define IOHIDDeviceGetReport mockGetReport-#define IOHIDDeviceSetReport mockSetReport-#define sendto mockSend-#include "bridge.m"--static void receiveReport(void *context, IOReturn result, void *sender, IOHIDReportType type,- uint32_t reportID, uint8_t *bytes, CFIndex size) {- assert(context == &callbacks);- assert(size <= sizeof(received));- memcpy(received, bytes, size);- receivedID = reportID;- receivedSize = size;- callbacks++;-}--int main(void) {- setenv("DSB_PORT", "19000", 1);- setenv("DSB_TOKEN", "1234567890abcdef1234567890abcdef", 1);- setenv("DSB_RAW", "1", 1);- initialize();- assert(DSBBridgeEnabled());- @autoreleasepool {- for (unsigned connection = 0; connection < 24; connection++) {- NSDictionary *info = @{- @kIOHIDVendorIDKey : @0x54c,- @kIOHIDProductIDKey : @0xce6,- @kIOHIDTransportKey : @"Bluetooth"- };- IOHIDDeviceRef device = (__bridge IOHIDDeviceRef)[info mutableCopy];- assert(CFEqual(property(device, CFSTR(kIOHIDTransportKey)), CFSTR("USB")));- uint8_t buffer[1024], report[78] = {0x31};- for (unsigned i = 1; i < sizeof(report); i++) {- report[i] = i;- }- registerInput(device, buffer, sizeof(buffer), receiveReport, &callbacks);- registeredCallback(registeredContext, 0, device, kIOHIDReportTypeInput, 0x31, report,- sizeof(report));- assert(receivedID == 1 && receivedSize == 64 && received[0] == 1);- assert(!memcmp(received + 1, report + 2, 63));- unsigned before = callbacks;- registeredCallback(registeredContext, 0, device, kIOHIDReportTypeInput, 1, report, 10);- assert(callbacks == before);- IOHIDReportCallback inflight = registeredCallback;- void *context = registeredContext;- registerInput(device, buffer, sizeof(buffer), NULL, NULL);- inflight(context, 0, device, kIOHIDReportTypeInput, 0x31, report, sizeof(report));- assert(callbacks == before);-- uint8_t feature[48] = {8, 2};- unsigned previousWrites = physicalWrites;- assert(!setReport(device, kIOHIDReportTypeFeature, 8, feature, sizeof(feature)));- assert(physicalWrites == previousWrites);- feature[2] = 1;- assert(!setReport(device, kIOHIDReportTypeFeature, 8, feature, sizeof(feature)));- assert(physicalWrites == previousWrites + 1);- uint8_t output[48] = {2, 4};- assert(!setReport(device, kIOHIDReportTypeOutput, 2, output, sizeof(output)));- assert(sent.kind == DSB_OUTPUT && !memcmp(sent.report, output, sizeof(output)));- CFRelease(device);- }- }- assert(packets == 24);- puts("PASS: HID identity, sensor/button bytes, unregister, reconnects and output routing");-}diff --git a/controllers/dualsense/launch.swift b/controllers/dualsense/launch.swiftdeleted file mode 100644index 15caa77..0000000--- a/controllers/dualsense/launch.swift+++ /dev/null@@ -1,267 +0,0 @@-// Supervise the broker and compatibility command for one direct-controller session.-import Darwin-import Foundation--struct LaunchError: Error, CustomStringConvertible {- let description: String- init(_ description: String) { self.description = description }-}--func tick(_ seconds: Double) {- RunLoop.current.run(until: Date(timeIntervalSinceNow: seconds))-}--func stop(_ process: Process?) {- guard let process, process.isRunning else { return }- process.terminate()- let deadline = Date(timeIntervalSinceNow: 3)- while process.isRunning && Date() < deadline { tick(0.02) }- if process.isRunning { kill(process.processIdentifier, SIGKILL) }- process.waitUntilExit()-}--// The broker prints one small readiness/probe object. Bound both time and size-// so a failed helper cannot hang the launcher or fill memory.-func readJSON(_ pipe: Pipe, timeout: Double) throws -> [String: Any] {- var data = Data()- let fd = pipe.fileHandleForReading.fileDescriptor- let deadline = Date(timeIntervalSinceNow: timeout)- while Date() < deadline {- var descriptor = pollfd(fd: fd, events: Int16(POLLIN), revents: 0)- let result = poll(&descriptor, 1, 50)- if result < 0 && errno != EINTR {- throw LaunchError("Cannot read controller service readiness")- }- if result > 0 {- var bytes = [UInt8](repeating: 0, count: 1024)- let n = read(fd, &bytes, bytes.count)- if n <= 0 { break }- data.append(contentsOf: bytes.prefix(n))- if data.count > 65536 { throw LaunchError("Controller service response too large") }- if let newline = data.firstIndex(of: 10) {- guard- let object = try JSONSerialization.jsonObject(with: data[..<newline])- as? [String: Any]- else {- throw LaunchError("Invalid controller service response")- }- return object- }- }- tick(0.001)- }- throw LaunchError("Controller service readiness timed out or exited")-}--func writeJSON(_ object: [String: Any], to path: URL) throws {- let bytes = try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])- let temporary = path.deletingLastPathComponent().appendingPathComponent(- ".session-\(UUID().uuidString)")- let fd = open(temporary.path, O_CREAT | O_EXCL | O_WRONLY | O_CLOEXEC | O_NOFOLLOW, 0o600)- guard fd >= 0 else { throw LaunchError("Cannot create controller session record") }- defer {- close(fd)- try? FileManager.default.removeItem(at: temporary)- }- try FileHandle(fileDescriptor: fd, closeOnDealloc: false).write(contentsOf: bytes)- guard rename(temporary.path, path.path) == 0 else {- throw LaunchError("Cannot save controller session record")- }-}--func execute(_ command: [String], environment: [String: String]) throws -> Never {- for key in ProcessInfo.processInfo.environment.keys where environment[key] == nil {- unsetenv(key)- }- for (key, value) in environment { setenv(key, value, 1) }- let arguments = command.map { strdup($0) } + [nil]- defer { arguments.forEach { free($0) } }- arguments.withUnsafeBufferPointer { _ = execvp(command[0], $0.baseAddress!) }- throw LaunchError("Cannot run compatibility tool: \(String(cString: strerror(errno)))")-}--func main() throws -> Int32 {- let command = Array(CommandLine.arguments.dropFirst())- guard !command.isEmpty else { return 64 }- let files = FileManager.default- let root = URL(fileURLWithPath: CommandLine.arguments[0]).resolvingSymlinksInPath()- .deletingLastPathComponent()- var environment = ProcessInfo.processInfo.environment- // Never inherit credentials from another session. User options are retained.- for key in ["DSB_PORT", "DSB_TOKEN", "DSB_RAW", "DSB_LIBRARY"] {- environment.removeValue(forKey: key)- }- environment["DSB_SESSION"] = "1"- let sessions = root.appendingPathComponent("sessions", isDirectory: true)- try files.createDirectory(- at: sessions, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])- let candidate = environment["STEAM_COMPAT_APP_ID"] ?? environment["SteamAppId"] ?? ""- let app =- !candidate.isEmpty && candidate.utf8.allSatisfy({ (48...57).contains($0) })- ? candidate : "unknown"- let info = sessions.appendingPathComponent(app + ".json")- let stats = sessions.appendingPathComponent(app + "-status.json")- func bypass(_ reason: String) throws -> Never {- try writeJSON(- ["state": "bypass", "route": reason, "updated": Date().timeIntervalSince1970], to: stats- )- return try execute(command, environment: environment)- }- if environment["DSB_DISABLED"] == "1" { try bypass("disabled") }- if environment["NOTPROTON_RAW_CONTROLLERS"] != "1" { try bypass("steam-input") }-- var brokerEnvironment = environment- brokerEnvironment.removeValue(forKey: "DYLD_INSERT_LIBRARIES")- func probe() throws -> (eligible: Bool, usb: Int) {- let process = Process()- let pipe = Pipe()- process.executableURL = root.appendingPathComponent("broker")- process.arguments = ["--probe"]- process.environment = brokerEnvironment- process.standardOutput = pipe- try process.run()- defer { stop(process) }- let state = try readJSON(pipe, timeout: 5)- guard let eligible = state["eligible"] as? Bool, let usb = state["usb"] as? Int,- state["bluetooth"] is Int- else { throw LaunchError("Incomplete controller probe") }- return (eligible, usb)- }- var state: (eligible: Bool, usb: Int)?- var probeError: Error?- for attempt in 0..<3 {- do {- state = try probe()- probeError = nil- } catch { probeError = error }- if let state, state.eligible || state.usb > 0 { break }- if attempt < 2 { tick(0.75) }- }- if let probeError { throw probeError }- guard let state else { throw LaunchError("Cannot verify controller transport") }- if !state.eligible {- try bypass(state.usb > 0 ? "original-usb" : "no-single-bluetooth-dualsense")- }-- let lock = open(- sessions.appendingPathComponent("controller.lock").path,- O_CREAT | O_WRONLY | O_CLOEXEC | O_NOFOLLOW, 0o600)- guard lock >= 0 else { throw LaunchError("Cannot lock controller session") }- defer { close(lock) }- guard flock(lock, LOCK_EX | LOCK_NB) == 0 else {- throw LaunchError("Another direct-controller game owns the wireless bridge")- }- let logURL = sessions.appendingPathComponent(app + ".log")- let logFD = open(logURL.path, O_CREAT | O_WRONLY | O_APPEND | O_CLOEXEC | O_NOFOLLOW, 0o600)- guard logFD >= 0 else { throw LaunchError("Cannot open controller log") }- let log = FileHandle(fileDescriptor: logFD, closeOnDealloc: true)- var random = [UInt8](repeating: 0, count: 16)- arc4random_buf(&random, random.count)- let token = random.map { String(format: "%02x", $0) }.joined()- let pcm = environment["DSB_PCM"] != "0"- environment["DSB_PCM"] = pcm ? "1" : "0"- var broker: Process?- var brokerPipe: Pipe?- var child: Process?- let signals = [SIGTERM, SIGINT, SIGHUP].map { value -> DispatchSourceSignal in- signal(value, SIG_IGN)- let source = DispatchSource.makeSignalSource(signal: value, queue: .main)- source.setEventHandler {- if let child, child.isRunning {- kill(child.processIdentifier, value)- } else {- stop(broker)- exit(128 + value)- }- }- source.resume()- return source- }- defer {- signals.forEach { $0.cancel() }- stop(broker)- try? files.removeItem(at: info)- try? log.close()- }- func startBroker(port: Int? = nil) throws -> Int {- let process = Process()- let pipe = Pipe()- process.executableURL = root.appendingPathComponent("broker")- process.arguments =- ["--token", token, "--parent", String(getpid()), "--status", stats.path]- + (pcm ? ["--pcm"] : []) + (port.map { ["--port", String($0)] } ?? [])- process.environment = brokerEnvironment- process.standardOutput = pipe- process.standardError = log- broker = process- brokerPipe = pipe- try process.run()- let ready = try readJSON(pipe, timeout: 8)- guard ready["ready"] as? Bool == true, let assigned = ready["port"] as? Int,- (1024...65535).contains(assigned), port == nil || port == assigned- else {- throw LaunchError("Controller transport did not become ready")- }- return assigned- }- let port = try startBroker()- environment["DSB_PORT"] = String(port)- environment["DSB_TOKEN"] = token- environment["DSB_RAW"] = pcm ? "1:pcm" : "1"- environment["DSB_LIBRARY"] = root.appendingPathComponent("bridge.dylib").path- func saveSession() throws {- try writeJSON(- [- "pid": getpid(), "brokerPid": broker!.processIdentifier,- "started": Date().timeIntervalSince1970,- "prefix": (environment["STEAM_COMPAT_DATA_PATH"] ?? "") + "/pfx",- "environment": environment.filter {- ["DSB_PORT", "DSB_TOKEN", "DSB_RAW", "DSB_LIBRARY", "DSB_PCM"].contains($0.key)- },- ], to: info)- }- try saveSession()- let game = Process()- // Commands supplied by compat_run.sh are absolute. /usr/bin/env also- // preserves normal PATH lookup for standalone use without shell parsing.- game.executableURL = URL(fileURLWithPath: "/usr/bin/env")- game.arguments = command- game.environment = environment- child = game- try game.run()- var reconnects = [Date]()- var disabled = false- while game.isRunning {- if !disabled, let service = broker, !service.isRunning {- reconnects.removeAll { Date().timeIntervalSince($0) >= 60 }- if service.terminationStatus == 10 && reconnects.count < 3 {- reconnects.append(Date())- let deadline = Date(timeIntervalSinceNow: 60)- while game.isRunning && Date() < deadline {- tick(0.5)- guard let reconnected = try? probe(), reconnected.eligible else { continue }- do {- _ = try startBroker(port: port)- try saveSession()- } catch {- stop(broker)- disabled = true- }- break- }- }- if broker?.isRunning != true {- disabled = true- fputs("DualSense transport stopped; reconnect and relaunch the game.\n", stderr)- }- }- tick(0.05)- }- withExtendedLifetime(brokerPipe) {}- return game.terminationReason == .exit ? game.terminationStatus : 128 + game.terminationStatus-}--do { exit(try main()) } catch {- fputs("DualSense launch: \(error)\n", stderr)- exit(70)-}diff --git a/controllers/dualsense/output-test.m b/controllers/dualsense/output-test.mdeleted file mode 100644index b482123..0000000--- a/controllers/dualsense/output-test.m+++ /dev/null@@ -1,66 +0,0 @@-#import <IOKit/hid/IOHIDManager.h>-#include <stdatomic.h>-#include <assert.h>-#include <pthread.h>-#include <unistd.h>--static atomic_bool blockWrite, writeEntered;-static atomic_uint physicalWrites;-static IOReturn writeResult;-static IOReturn mockSetReport(IOHIDDeviceRef device, IOHIDReportType type, CFIndex reportID,- const uint8_t *report, CFIndex size) {- atomic_fetch_add(&physicalWrites, 1);- atomic_store(&writeEntered, true);- while (atomic_load(&blockWrite)) {- usleep(1000);- }- return writeResult;-}--#define IOHIDDeviceSetReport mockSetReport-#define main brokerMain-#include "broker.m"-#undef main-#undef IOHIDDeviceSetReport--static bool writeSucceeded;-static void *writeOnWorker(void *unused) {- uint8_t report[78] = {0x31};- writeSucceeded = DSBWriteOutput(report, sizeof(report));- return NULL;-}--int main(void) {- uint8_t report[78] = {0x31};- assert(DSBWriteOutput(report, sizeof(report)));- assert(dsb.reports == 1 && dsb.errors == 0 && !dsb.writeStartedNS);- writeResult = kIOReturnError;- assert(!DSBWriteOutput(report, sizeof(report)));- assert(dsb.stalled && dsb.errors == 1 && !dsb.writeStartedNS);- unsigned writes = physicalWrites;- assert(!DSBWriteOutput(report, sizeof(report)) && physicalWrites == writes);-- for (unsigned pcm = 0; pcm < 2; pcm++) {- dsb.pcmMode = pcm;- dsb.stalled = false;- dsb.errors = 0;- writeResult = kIOReturnSuccess;- blockWrite = true;- writeEntered = false;- pthread_t worker;- assert(!pthread_create(&worker, NULL, writeOnWorker, NULL));- while (!atomic_load(&writeEntered)) {- usleep(1000);- }- assert(!DSBOutputWriteTimedOut());- double deadline = CFAbsoluteTimeGetCurrent() + 1;- while (!DSBOutputWriteTimedOut() && CFAbsoluteTimeGetCurrent() < deadline) {- usleep(1000);- }- assert(dsb.stalled && dsb.errors == 1 && dsb.writeStartedNS);- blockWrite = false;- pthread_join(worker, NULL);- assert(!writeSucceeded && !dsb.writeStartedNS && dsb.errors == 1);- }- puts("PASS: write errors, blocked-driver watchdog and suppression after failure");-}diff --git a/controllers/dualsense/protocol.h b/controllers/dualsense/protocol.hdeleted file mode 100644index d7b5445..0000000--- a/controllers/dualsense/protocol.h+++ /dev/null@@ -1,44 +0,0 @@-#pragma once-#include <stdint.h>-#include <stdbool.h>-#include <string.h>-#define DSB_MAGIC 0x31425344u-#define DSB_LEVEL 1-#define DSB_OUTPUT 2-#define DSB_PCM 3-// report[0]: frame count (0=end, 30=10ms), report[1..3]: stream ID,-// report[4..63]: 30 signed-8-bit stereo PCM frames at 3000 Hz.-typedef struct __attribute__((packed)) {- uint32_t magic, kind;- uint8_t token[16];- uint32_t pid, sequence;- double timestamp;- float left, right;- uint8_t report[64];-} DSBPacket;--// Session tokens are exactly 16 bytes encoded as 32 hexadecimal characters.-static inline bool DSBParseToken(const char *text, uint8_t token[16]) {- if (!text || strlen(text) != 32) {- return false;- }- for (unsigned i = 0; i < 16; ++i) {- unsigned byte = 0;- for (unsigned digit = 0; digit < 2; ++digit) {- unsigned char c = text[i * 2 + digit];- unsigned value;- if (c >= '0' && c <= '9') {- value = c - '0';- } else if (c >= 'a' && c <= 'f') {- value = c - 'a' + 10;- } else if (c >= 'A' && c <= 'F') {- value = c - 'A' + 10;- } else {- return false;- }- byte = (byte << 4) | value;- }- token[i] = byte;- }- return true;-}diff --git a/controllers/dualsense/test-bridge.py b/controllers/dualsense/test-bridge.pydeleted file mode 100644index f4a91d8..0000000--- a/controllers/dualsense/test-bridge.py+++ /dev/null@@ -1,130 +0,0 @@-import json-import os-import socket-import struct-import subprocess-import time-import tempfile-from pathlib import Path--root = Path(os.environ["DSB_TEST_BUILD"]).resolve()-packet = struct.Struct("<II16sIIdff64s")-token = bytes.fromhex("12" * 16)-s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)-s.bind(("127.0.0.1", 0))-# Read once audio-test has exited, when its packets are already on their way: the-# timeout only has to outlast loopback delivery.-s.settimeout(0.3)-env = dict(- os.environ,- DSB_PORT=str(s.getsockname()[1]),- DSB_TOKEN=token.hex(),- DSB_RAW="1",- DYLD_INSERT_LIBRARIES=str(root / "bridge.dylib"),-)-for arch in ("arm64", "x86_64"):- subprocess.run(- [- "lipo",- str(root / "audio-test"),- "-thin",- arch,- "-output",- str(root / ("audio-test-" + arch)),- ],- check=True,- )- for sample_format, mode in (- [(fmt, "normal") for fmt in ("f32", "s8", "u8", "s16", "u16", "s32", "u32")]- + [("u8", "fail"), ("u32", "fail")]- + [("f32", mode) for mode in ("volume", "mute", "silence", "short", "external")]- ):- p = subprocess.run(- [str(root / ("audio-test-" + arch)), sample_format, mode],- env=env,- capture_output=True,- text=True,- timeout=10,- )- assert p.returncode == 0, p.stderr + p.stdout- levels = []- while True:- try:- v = packet.unpack(s.recv(1024))- assert v[0] == 0x31425344 and v[2] == token- levels.append((v[6], v[7]))- except socket.timeout:- break- silent = mode in ("fail", "mute", "silence", "short")- active = (0.03125, 0.25) if mode == "volume" else (0.125, 0.5)- expected = ((0, 0),) if silent else (active, (0, 0))- assert len(levels) >= 5 and all(x in expected for x in levels), levels- if not silent:- assert active in levels, levels- assert levels[-1] == (0, 0)- print(arch, "PASS 4-channel routing, levels, stop:", p.stdout.strip())-with tempfile.TemporaryDirectory() as tmp:- status = Path(tmp) / "status.json"- p = subprocess.Popen(- [- str(root / "broker"),- "--dry-run",- "--token",- token.hex(),- "--status",- str(status),- "--seconds",- "3.5",- ],- stdout=subprocess.PIPE,- stderr=subprocess.PIPE,- text=True,- )- ready = json.loads(p.stdout.readline())- addr = ("127.0.0.1", ready["port"])-- def send(seq, secret=token, ago=0):- s.sendto(- packet.pack(- 0x31425344, 1, secret, 1234, seq, time.time() - 978307200 - ago, 0.3, 0.4, bytes(64)- ),- addr,- )-- send(1)- send(2, b"0" * 16)- send(3, ago=1)- send(1)- time.sleep(1.3)- v = json.loads(status.read_text())- assert v["accepted"] == 1 and v["dropped"] == 3, v- assert v["left"] == v["right"] == 0 and v["peakLeft"] > 0.29, v- # An invalid kind must not advance the replay counter for a real source.- s.sendto(- packet.pack(0x31425344, 99, token, 1234, 100000, time.time() - 978307200, 0, 0, bytes(64)),- addr,- )- sequence = 2- deadline = time.monotonic() + 1.0- while time.monotonic() < deadline:- # Updating a color is independent of an already active rumble command.- rumble = bytes([2, 3, 0, 64, 128]) + bytes(59)- color = bytearray(64)- color[0] = 2- color[2] = 4- color[45:48] = bytes([20, 30, 40])- for report in (rumble, color):- s.sendto(- packet.pack(- 0x31425344, 2, token, 1234, sequence, time.time() - 978307200, 0, 0, report- ),- addr,- )- sequence += 1- time.sleep(0.02)- active = json.loads(status.read_text())- assert active["left"] > 0.49 and active["right"] > 0.24, active- assert active["dropped"] == 4, active- out, err = p.communicate(timeout=5)- assert p.returncode == 0, err- print("PASS token/replay/stale rejection and silence watchdog")diff --git a/controllers/dualsense/test-controls.c b/controllers/dualsense/test-controls.cdeleted file mode 100644index d47308c..0000000--- a/controllers/dualsense/test-controls.c+++ /dev/null@@ -1,51 +0,0 @@-#include "Controls.h"-#include "protocol.h"-#include <assert.h>-#include <stdio.h>-int main(void) {- uint8_t state[47] = {0}, previous[47] = {0}, out[47];- state[1] = 4 | 16;- state[44] = 217;- state[45] = 255;- state[43] = 4;- assert(DSBControlDelta(state, previous, false, out));- assert(out[1] == 20);- memcpy(previous, state, 47);- state[0] = 4;- state[10] = 0x21;- state[11] = 0xfe;- assert(DSBControlDelta(state, previous, true, out));- assert(out[0] == 4 && out[1] == 0);- assert(out[43] == 0 && out[44] == 0 && out[45] == 0);- memcpy(previous, state, 47);- assert(!DSBControlDelta(state, previous, true, out));- state[10] = 5;- state[11] = 0;- assert(DSBControlDelta(state, previous, true, out));- assert(out[0] == 4 && out[10] == 5 && out[1] == 0);- memcpy(previous, state, 47);- state[44] = 0;- state[45] = 0;- assert(DSBControlDelta(state, previous, true, out));- assert(out[0] == 0 && out[1] == 4);- memcpy(previous, state, 47);- state[43] = 2;- assert(DSBControlDelta(state, previous, true, out));- assert(out[0] == 0 && out[1] == 16 && out[43] == 2);- uint8_t release[64];- DSBTriggerRelease(4, release);- assert(release[1] == 4 && release[11] == 5 && release[22] == 0);- DSBTriggerRelease(8, release);- assert(release[1] == 8 && release[11] == 0 && release[22] == 5);- DSBTriggerRelease(0, release);- assert(release[1] == 0 && release[11] == 0 && release[22] == 0);- uint8_t token[16];- assert(DSBParseToken("0123456789aBcDeF0123456789aBcDeF", token));- assert(token[0] == 1 && token[7] == 0xef);- assert(!DSBParseToken(NULL, token));- assert(!DSBParseToken("1234", token));- assert(!DSBParseToken("1z23456789abcdef0123456789abcdef", token));- assert(!DSBParseToken(" 123456789abcdef0123456789abcdef", token));- puts("PASS: changing triggers/rumble never replays old RGB/player state; actual color/release "- "changes preserved");-}diff --git a/controllers/dualsense/test-launch.py b/controllers/dualsense/test-launch.pydeleted file mode 100644index 97c60e4..0000000--- a/controllers/dualsense/test-launch.py+++ /dev/null@@ -1,142 +0,0 @@-"""Native launcher lifecycle, using a fake broker; never opens a controller."""--import json-import os-from pathlib import Path-import shutil-import signal-import stat-import subprocess-import sys-import tempfile-import time--build = Path(os.environ["DSB_TEST_BUILD"]).resolve()-with tempfile.TemporaryDirectory(prefix="bridgeplay dualsense ") as tmp:- root = Path(tmp)- shutil.copy2(build / "launch", root / "launch")- (root / "bridge.dylib").touch()- broker = root / "broker"- broker.write_text(- "#!"- + sys.executable- + "\n"- + """-import json, os, signal, sys, time-if '--probe' in sys.argv:- usb = int(os.environ.get('TEST_USB', '0'))- print(json.dumps(dict(bluetooth=0 if usb else 1, usb=usb, eligible=not usb)), flush=True)- sys.exit()-if os.environ.get('TEST_BAD_READY'):- print('{}', flush=True)-else:- print(json.dumps(dict(ready=True, port=54565, pid=os.getpid())), flush=True)-if os.environ.get('TEST_REMOVE_ONCE'):- from pathlib import Path- marker = Path(__file__).with_name('removed-once')- if not marker.exists():- marker.touch()- time.sleep(.2)- sys.exit(10)-signal.signal(signal.SIGTERM, lambda *_: sys.exit())-while True: time.sleep(.02)-"""- )- broker.chmod(0o755)- child = root / "child.py"- child.write_text(- """import json, os, sys, time-keys = ('DSB_RAW', 'DSB_PCM', 'DSB_LIBRARY', 'DSB_SESSION')-print(json.dumps({k: os.environ.get(k) for k in keys}), flush=True)-time.sleep(float(os.environ.get('TEST_CHILD_SLEEP', '0')))-sys.exit(int(os.environ.get('TEST_CHILD_EXIT', '0')))-"""- )- args = [str(root / "launch"), sys.executable, str(child)]- clean = {k: v for k, v in os.environ.items() if not k.startswith("DSB_")}- clean.update(STEAM_COMPAT_APP_ID="999999", STEAM_COMPAT_DATA_PATH=str(root / "prefix"))- for route, raw, usb, disabled in [- ("steam-input", "0", "0", "0"),- ("original-usb", "1", "1", "0"),- ("disabled", "1", "0", "1"),- ("pcm", "1", "0", "0"),- ]:- env = dict(clean, NOTPROTON_RAW_CONTROLLERS=raw, TEST_USB=usb, DSB_DISABLED=disabled)- result = subprocess.run(args, env=env, capture_output=True, text=True, timeout=12)- assert result.returncode == 0, (route, result.stderr)- observed = json.loads(result.stdout.splitlines()[-1])- assert observed["DSB_SESSION"] == "1"- if route == "pcm":- assert observed["DSB_RAW"] == "1:pcm" and observed["DSB_PCM"] == "1", observed- assert observed["DSB_LIBRARY"] == str(root / "bridge.dylib")- else:- assert observed["DSB_RAW"] is None and observed["DSB_LIBRARY"] is None- assert json.loads((root / "sessions/999999-status.json").read_text())["route"] == route- assert not (root / "sessions/999999.json").exists()- print("PASS native launcher:", route, flush=True)-- env = dict(clean, NOTPROTON_RAW_CONTROLLERS="1")- result = subprocess.run(- args, env=dict(env, TEST_CHILD_EXIT="23"), capture_output=True, timeout=12- )- assert result.returncode == 23- result = subprocess.run(- args, env=dict(env, TEST_BAD_READY="1"), capture_output=True, timeout=12- )- assert result.returncode == 70 and not (root / "sessions/999999.json").exists()- print("PASS child exit status and failed initialization cleanup", flush=True)-- resumed = subprocess.Popen(- args,- env=dict(env, TEST_REMOVE_ONCE="1", TEST_CHILD_SLEEP="3"),- stdout=subprocess.PIPE,- stderr=subprocess.PIPE,- )- record = root / "sessions/999999.json"- observed = []- deadline = time.monotonic() + 10- while resumed.poll() is None and time.monotonic() < deadline:- if record.exists():- doc = json.loads(record.read_text())- observed.append(- (doc["brokerPid"], doc["environment"]["DSB_PORT"], doc["environment"]["DSB_TOKEN"])- )- time.sleep(0.025)- out, err = resumed.communicate(timeout=3)- assert resumed.returncode == 0, err- assert len({x[0] for x in observed}) == 2, "physical removal should restart broker once"- assert len({x[1:] for x in observed}) == 1, "reconnect must retain port and session credentials"- assert not record.exists()- print("PASS bounded physical reconnect retains session and port", flush=True)-- owner = subprocess.Popen(- args, env=dict(env, TEST_CHILD_SLEEP="30"), stdout=subprocess.PIPE, stderr=subprocess.PIPE- )- record = root / "sessions/999999.json"- try:- deadline = time.monotonic() + 10- while not record.exists() and time.monotonic() < deadline:- time.sleep(0.02)- assert record.exists()- assert stat.S_IMODE(record.stat().st_mode) == 0o600- assert stat.S_IMODE(record.parent.stat().st_mode) == 0o700- info = json.loads(record.read_text())- assert len(info["environment"]["DSB_TOKEN"]) == 32- rival = subprocess.run(args, env=env, capture_output=True, timeout=10)- assert rival.returncode == 70 and b"owns the wireless bridge" in rival.stderr- assert record.exists(), "rival must not remove the owning session"- owner.send_signal(signal.SIGTERM)- owner.communicate(timeout=8)- assert owner.returncode == 143, owner.returncode- assert not record.exists()- try:- os.kill(info["brokerPid"], 0)- except ProcessLookupError:- pass- else:- raise AssertionError("broker survived launcher termination")- print("PASS credentials, single owner, signal forwarding and broker cleanup", flush=True)- finally:- if owner.poll() is None:- owner.kill()- owner.communicate()diff --git a/controllers/dualsense/test-lifecycle.py b/controllers/dualsense/test-lifecycle.pydeleted file mode 100644index 7189004..0000000--- a/controllers/dualsense/test-lifecycle.py+++ /dev/null@@ -1,63 +0,0 @@-"""Offline: idle audio, silence tail, restart, and trigger/rumble coexistence."""--import json-import os-import socket-import struct-import subprocess-import tempfile-import time-from pathlib import Path--root = Path(os.environ["DSB_TEST_BUILD"]).resolve()-wire = struct.Struct("<II16sIIdff64s")-token = bytes.fromhex("78" * 16)-with tempfile.TemporaryDirectory() as tmp:- path = Path(tmp) / "status.json"- p = subprocess.Popen(- [str(root / "broker"), "--pcm", "--dry-run", "--token", token.hex(), "--status", str(path)],- stdout=subprocess.PIPE,- stderr=subprocess.PIPE,- text=True,- )- s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)- address = ("127.0.0.1", json.loads(p.stdout.readline())["port"])- seq = 0-- def pump(seconds, active):- global seq- end = time.monotonic() + seconds- while time.monotonic() < end:- seq += 1- samples = bytes([40, 216]) * 30 if active else bytes(60)- report = bytes([30, 1, 0, 0]) + samples- s.sendto(- wire.pack(0x31425344, 3, token, 1234, seq, time.time() - 978307200, 0, 0, report),- address,- )- time.sleep(0.01)- return json.loads(path.read_text())-- try:- state = pump(1.2, False)- assert state["pcm"]["reports"] == 0, state- pump(0.6, True)- state = pump(1.3, False)- count = state["pcm"]["reports"]- assert count > 10, state- state = pump(1.1, False)- assert state["pcm"]["reports"] == count, state- pump(0.6, True)- state = pump(1.3, False)- assert state["pcm"]["reports"] > count + 10, state- assert not state["hidErrors"] and not state["hidStalled"], state- p.terminate()- p.communicate(timeout=3)- assert p.returncode == 0- assert json.loads(path.read_text())["state"] == "stopped"- print("PASS: open silent audio produces no PCM; waveform starts/stops/restarts; clean exit")- finally:- if p.poll() is None:- p.kill()- p.wait()- s.close()diff --git a/controllers/dualsense/test-pcm-unit.c b/controllers/dualsense/test-pcm-unit.cdeleted file mode 100644index f42abb8..0000000--- a/controllers/dualsense/test-pcm-unit.c+++ /dev/null@@ -1,58 +0,0 @@-#include <assert.h>-#include <stdio.h>-#include "PCM.h"-int main(void) {- for (int f = 0; f < 2; f++) {- DSBResampler r;- DSBResamplerInit(&r, 48000);- double energy = 0;- unsigned n = 0;- for (int i = 0; i < 48000; i++) {- float v = .5 * sin(2 * M_PI * (f ? 5000 : 50) * i / 48000.);- int8_t out[2];- if (DSBResample(&r, v, -v, out)) {- assert(out[0] == -out[1]);- if (n > 100) {- energy += out[0] * out[0];- }- n++;- }- }- assert(n == 3000);- double rms = sqrt(energy / 2899) / 127;- if (f) {- assert(rms < .01);- } else {- assert(rms > .34 && rms < .37);- }- }- int8_t data[128];- for (int i = 0; i < 128; i++) {- data[i] = i - 64;- }- for (unsigned seq = 0; seq < 512; seq++) {- for (int first = 0; first < 2; first++) {- uint8_t b[206];- unsigned n = DSBPCMReport(b, seq, seq, first, data);- assert(n == (first ? 206 : 142));- assert(b[1] == (seq % 16) * 16);- assert(!memcmp(b + (first ? 13 : 9), data, 128));- assert(b[4] == (first ? 0xfe : 0x62));- assert(b[first ? 10 : 6] == (uint8_t)(seq * 2));- unsigned crc = 0xffffffff;- unsigned char seed = 0xa2;- for (unsigned k = 0; k < n - 3; k++) {- unsigned char v = k ? b[k - 1] : seed;- crc ^= v;- for (int j = 0; j < 8; j++) {- crc = (crc >> 1) ^ ((crc & 1) ? 0xedb88320 : 0);- }- }- crc = ~crc;- assert(b[n - 4] == (crc & 255) && b[n - 3] == ((crc >> 8) & 255) &&- b[n - 2] == ((crc >> 16) & 255) && b[n - 1] == (crc >> 24));- }- }- puts("PASS: signed 50Hz waveform/phase, antialias rejection, 3kHz rate, packet payload, "- "independent CRC and sequence wrap");-}diff --git a/controllers/dualsense/test-pcm.py b/controllers/dualsense/test-pcm.pydeleted file mode 100644index 53b7ffb..0000000--- a/controllers/dualsense/test-pcm.py+++ /dev/null@@ -1,183 +0,0 @@-"""Offline routing/security checks; --hardware is a bounded silent soak."""--import json-import os-import socket-import struct-import subprocess-import sys-import threading-import time-from pathlib import Path--root = Path(os.environ["DSB_TEST_BUILD"]).resolve()-wire = struct.Struct("<II16sIIdff64s")-token = bytes.fromhex("56" * 16)---def packet(seq, report, kind=3, secret=token):- return wire.pack(0x31425344, kind, secret, 1234, seq, time.time() - 978307200, 0, 0, report)---if "--hardware" not in sys.argv:- for arch in ("arm64", "x86_64"):- sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)- sock.bind(("127.0.0.1", 0))- sock.settimeout(0.3)- env = dict(- os.environ,- DSB_PORT=str(sock.getsockname()[1]),- DSB_TOKEN=token.hex(),- DSB_RAW="1:pcm",- DYLD_INSERT_LIBRARIES=str(root / "bridge.dylib"),- )- env.pop("DSB_PCM", None) # Exercise the environment field forwarded by Bridgeplay.- result = subprocess.run(- [str(root / ("audio-test-" + arch))], env=env, capture_output=True, text=True, timeout=5- )- assert result.returncode == 0, result.stderr- chunks = []- while True:- try:- chunks.append(wire.unpack(sock.recv(1024)))- except socket.timeout:- break- assert len(chunks) > 5 and all(p[1] == 3 and p[2] == token for p in chunks)- assert chunks[-1][-1][0] == 0- # Speaker channels are .75 but haptic channels are -.125/.5. Verify- # the signed samples at steady state.- for p in chunks[2:-1]:- assert p[-1][0] == 30- assert all(- abs(a + 16) <= 1 and abs(b - 64) <= 1- for a, b in struct.iter_unpack("bb", p[-1][4:])- )- print(arch, "PASS: PCM routing, speaker isolation, stop, legacy-env forwarding", flush=True)--hardware = "--hardware" in sys.argv-seconds = int(os.environ.get("PCM_SOAK_SECONDS", "60")) if hardware else 3-dest = root / ("pcm-soak-status.json" if hardware else "pcm-dry-status.json")-log = (root / ("pcm-soak.log" if hardware else "pcm-dry.log")).open("w")-args = [- str(root / "broker"),- "--pcm",- "--token",- token.hex(),- "--seconds",- str(seconds + 2),- "--status",- str(dest),-] + ([] if hardware else ["--dry-run"])-p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=log, text=True)-sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)-tick_stop = threading.Event()-tick_thread = None-try:- line = p.stdout.readline()- assert line, line- ready = json.loads(line)- p.pid = ready["pid"]- addr = ("127.0.0.1", ready["port"])- if not hardware and os.environ.get("DSB_TEST_DEFER_TIMERS"):- # Hardware also supplies ~133 HID input events/s, including after an- # effect ends. Authenticated no-op controls reproduce those extra- # notifications in the dry transport.- def ticks():- with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as ticker:- sequence = 0- due = time.monotonic()- while not tick_stop.is_set():- sequence += 1- ticker.sendto(- wire.pack(- 0x31425344,- 2,- token,- 4321,- sequence,- time.time() - 978307200,- 0,- 0,- bytes([2]) + bytes(63),- ),- addr,- )- due += 0.0075- tick_stop.wait(max(0, due - time.monotonic()))-- tick_thread = threading.Thread(target=ticks)- tick_thread.start()- report = bytes([30, 1, 0, 0]) + (bytes(60) if hardware else bytes([16, 240]) * 30)- epoch = time.monotonic()- seq = 0- # Frames this loop sent over 64 ms behind schedule: after a stall here it catches up in- # a burst, and the broker's latency bound rightly drops that backlog.- late_frames = 0- if not hardware:- sock.sendto(packet(seq, report, secret=bytes(16)), addr)- sock.sendto(packet(seq, report) + b"extra", addr)- for i in range(seconds * 100):- seq += 1- if time.monotonic() - (epoch + i * 0.01) > 0.064:- late_frames += report[0]- sock.sendto(packet(seq, report), addr)- if not hardware and i % 10 == 0:- # Exercise serialized simultaneous trigger/LED commands offline.- seq += 1- b = bytearray(64)- b[0] = 2- b[1] = 4- b[2] = 4- b[11:22] = bytes([0x21, 0xFE, 3, 0, 0x90, 0x44, 0x1A, 0, 0, 0, 0])- b[45] = i % 256- sock.sendto(packet(seq, b, kind=2), addr)- remaining = epoch + (i + 1) * 0.01 - time.monotonic()- if remaining > 0:- time.sleep(remaining)- if i % 100 == 99:- state = json.loads(dest.read_text())- assert not state["hidStalled"] and not state["hidErrors"], state- if hardware:- print("silent soak", i // 100 + 1, "s", state["pcm"], flush=True)- seq += 1- sock.sendto(packet(seq, bytes([0, 1, 0, 0]) + bytes(60)), addr)- p.wait(timeout=5)- assert p.returncode == 0, p.returncode- state = json.loads(dest.read_text())- assert not state["hidStalled"], state- # A scheduler pause past 40 ms resyncs and suspends PCM for 0.5 s (plus the- # zero tail and restart). Only the unpaused time owes the 40 reports/s.- active = max(seconds - 0.6 * state["pcm"]["pauses"], 0)- assert (- state["pcm"]["reports"] == 0- if hardware- else state["pcm"]["reports"] > 0 and state["pcm"]["reports"] > active * 40- ), state- # The 64 ms latency bound drops backlog after a scheduling pause. Slow CI- # VMs pause; real hardware idles and must drop nothing.- sent_frames = seconds * 100 * (report[0] if not hardware else 0)- assert (- state["pcm"]["discardedFrames"] == 0- if hardware- else state["pcm"]["discardedFrames"] <= sent_frames // 4 + late_frames- ), (late_frames, state)- if not hardware:- assert state["dropped"] == 2 and state["outputCommands"] > 0, state- print(- "PASS",- (- "hardware idle silence emits no PCM"- if hardware- else "dry transport + authentication + trigger interleave"- ),- state["pcm"],- )-finally:- tick_stop.set()- if tick_thread:- tick_thread.join(timeout=1)- if p.poll() is None:- p.terminate()- p.wait(timeout=3)- log.close()- sock.close()diff --git a/controllers/dualsense/test-trigger-routing.py b/controllers/dualsense/test-trigger-routing.pydeleted file mode 100644index c6d97d6..0000000--- a/controllers/dualsense/test-trigger-routing.py+++ /dev/null@@ -1,104 +0,0 @@-import json-import os-import socket-import struct-import subprocess-import tempfile-import time-from pathlib import Path--root = Path(os.environ["DSB_TEST_BUILD"]).resolve()-wire = struct.Struct("<II16sIIdff64s")-token = bytes.fromhex("34" * 16)-curve = bytes([0x21, 0xFE, 3, 0, 0x90, 0x44, 0x1A, 0, 0, 0, 0])-off = bytes([5]) + bytes(10)-for pcm, grace in ((False, 75), (False, 0), (True, 0)):- with tempfile.TemporaryDirectory() as tmp:- status = Path(tmp) / "state.json"- p = subprocess.Popen(- [- str(root / "broker"),- "--dry-run",- "--trigger-reset-grace-ms",- str(grace),- "--token",- token.hex(),- "--status",- str(status),- # Stopped by terminate() below. A short lifetime ran out on slow CI hosts- # before the loop did, and its shutdown "off" failed the timing check.- "--seconds",- "30",- ]- + (["--pcm"] if pcm else []),- stdout=subprocess.PIPE,- stderr=subprocess.PIPE,- text=True,- )- addr = ("127.0.0.1", json.loads(p.stdout.readline())["port"])- sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)- seq = 0- sent = []-- def send(effect):- global seq- seq += 1- sent.append(time.time())- report = bytearray(64)- report[0] = 2- report[1] = 4- report[11:22] = effect- sock.sendto(- wire.pack(0x31425344, 2, token, 1234, seq, time.time() - 978307200, 0, 0, report),- addr,- )-- # A fixed count, not a 1.2 s window: slow CI hosts oversleep. The genuine release is- # the last off sent, so time it from that send, not from after an oversleep.- for _ in range(110):- send(curve)- send(off)- stopped = time.time()- time.sleep(0.01)- d = json.loads(status.read_text())- t = d["triggers"]- if not grace:- assert t["suppressedR2Resets"] == 0, t- # The broker rewrites status once a second, so a fixed sleep can read a snapshot- # taken before the deferred release fired. Wait for one written well after it:- # packets older than 0.25 s are dropped, so the release is due by stopped + 0.35.- deadline = time.time() + 5- while True:- d = json.loads(status.read_text())- if d["updated"] >= stopped + 0.5 or time.time() > deadline:- break- time.sleep(0.05)- t = d["triggers"]- assert bytes(t["r2"]) == off, t- if grace:- # Resets inside the grace never reach the pad. A pause in this loop longer- # than the grace rightly lets an off through (or fires the deferred release)- # and the next curve follows, so allow two sends per slow gap. Gaps a third- # of the grace count as slow: the broker stamps packets per run-loop pass.- h = t["sentHistory"]- slow = sum(b - a > grace / 3000 for a, b in zip(sent, sent[1:]))- assert t["suppressedR2Resets"] > 50, t- assert len(h) <= 2 + 2 * slow + 2, (slow, t)- assert len(h) == 40 or bytes(h[0]["r2"]) == curve, t- assert bytes(h[-1]["r2"]) == off, t- assert -0.5 < h[-1]["at"] - stopped < 0.5, t- send(curve)- time.sleep(0.06)- p.terminate()- _, err = p.communicate(timeout=3)- assert p.returncode == 0, err- final = json.loads(status.read_text())- assert final["state"] == "stopped", final- assert bytes(final["triggers"]["sentHistory"][-1]["r2"]) == off, final- print(- "PASS pcm="- + str(pcm)- + " grace="- + str(grace)- + ": exact curve preserved; reset bursts handled; genuine release delivered; no change to default behavior"- )diff --git a/controllers/steam-input/README.md b/controllers/steam-input/README.mddeleted file mode 100644index 296e6a5..0000000--- a/controllers/steam-input/README.md+++ /dev/null@@ -1,55 +0,0 @@-# Steam Input rumble in Wine--This adapter forwards the two motor values from Winebus's-`SDL_JoystickRumble` to the native Steam `SteamController008` interface.-It fixes the missing rumble backend for Steam's macOS virtual Xbox gamepad.-Games using the Steam Controller/Input API directly use their existing route.--The adapter is a universal Mach-O library injected into Bridgeplay's Wine-processes. It intercepts Wine's dynamic SDL2 symbol lookup for symbols from-the selected CrossOver runtime.--A device qualifies only when its SDL GUID matches an IOKit device with-`Transport=Virtual`, `Manufacturer=Microsoft`, and `Product=GamePad-N`.-Both Darwin and HIDAPI SDL GUID signatures are supported. The corresponding-Steam gamepad index supplies the controller handle. Unknown devices use-original SDL.--One worker owns the native Steam API and forwards the latest motor values.-It handles effect expiry, explicit stops and device close. While an effect is-active, controller assignments are checked every 20 ms. A missing assignment-is retried until the effect expires; a changed assignment stops the previous-controller before forwarding to its replacement. A re-created SDL device-starts with an empty mailbox. Each slot retains the latest command, and Steam-handles output to the physical controller.--`rumble.cpp` owns SDL interception and the command mailbox. `VirtualGamepad.h`-validates the virtual device identity; `SteamSession.h` owns the native Steam-connection and releases partially initialized sessions on failure.--## Build and use--`make steam-rumble` builds the library; `make steam-rumble-check` tests routing,-SDL hook selection, virtual-device detection, reconnection, player indices,-amplitude preservation, expiry, reassignment, explicit stop, close, shutdown-and launch gating without controller output. The Steam mock implements the-SDK interfaces and rejects unexpected calls, including LED changes. Steamworks-headers are obtained through the project's pinned `lsteamclient/fetch.sh`.--The regular app payload includes `controllers/steam-input/rumble.dylib` and-installs/removes it with the other Bridgeplay runtime components. The run script-enables it for game sessions with direct controller access disabled. To opt-out for a game, set `BRIDGEPLAY_STEAM_RUMBLE=0 %command%` in Steam launch options.-`BRIDGEPLAY_RAW_CONTROLLERS=1` also bypasses it, preserving direct DualSense PCM.-A missing adapter leaves the previous launch behavior intact.--## Validation and limits--Verified with CrossOver 26.3 / SDL 2.30.12 (Rosetta), native Steam Input,-INVERSUS Deluxe and a Bluetooth DualSense. The adapter logs the mapped-virtual slot and the first nonzero rumble forwarded from XInputSetState.--The binary includes arm64 for the FEX runtime, but gameplay under FEX and-multiple simultaneous physical controllers still need hardware validation.-See the [direct-controller bridge](../../docs/dualsense-bluetooth.md) for-LED and PCM transport.diff --git a/controllers/steam-input/SteamSession.h b/controllers/steam-input/SteamSession.hdeleted file mode 100644index b7812ed..0000000--- a/controllers/steam-input/SteamSession.h+++ /dev/null@@ -1,75 +0,0 @@-#pragma once-#include <dlfcn.h>-#include <cstdio>-#include <cstdlib>-#include <unistd.h>-#include "steam_api.h"--// Owned by the rumble worker; no Steam calls run on the SDL input thread.-struct SteamSession {- SteamSession() = default;- SteamSession(const SteamSession &) = delete;- SteamSession &operator=(const SteamSession &) = delete;- ~SteamSession() {- close();- }-- void *library = nullptr;- ISteamClient *client = nullptr;- ISteamController *controller = nullptr;- HSteamPipe pipe = 0;- HSteamUser user = 0;- bool open() {- if (controller) {- return true;- }- const char *path = getenv("STEAM_COMPAT_CLIENT_INSTALL_PATH");- if (!path || !*path) {- return false;- }- char file[4096];- if (snprintf(file, sizeof(file), "%s/steamclient.dylib", path) >= (int)sizeof(file)) {- return false;- }- if (!library) {- library = dlopen(file, RTLD_NOW | RTLD_LOCAL);- }- if (!library) {- return false;- }- auto factory = (void *(*)(const char *, int *))dlsym(library, "CreateInterface");- if (!factory) {- return false;- }- client = (ISteamClient *)factory(STEAMCLIENT_INTERFACE_VERSION, nullptr);- if (!client || !(pipe = client->CreateSteamPipe()) ||- !(user = client->ConnectToGlobalUser(pipe))) {- close();- return false;- }- controller = client->GetISteamController(user, pipe, STEAMCONTROLLER_INTERFACE_VERSION);- if (!controller || !controller->Init()) {- controller = nullptr;- close();- return false;- }- fprintf(stderr, "bridgeplay-rumble: native Steam controller API ready (pid %d)\n", getpid());- return true;- }- void close() {- if (controller) {- controller->Shutdown();- }- if (client && user) {- client->ReleaseUser(pipe, user);- }- if (client && pipe) {- client->BReleaseSteamPipe(pipe);- }- // Steam owns background threads. Keep its image mapped until process exit.- controller = nullptr;- client = nullptr;- user = 0;- pipe = 0;- }-};diff --git a/controllers/steam-input/VirtualGamepad.h b/controllers/steam-input/VirtualGamepad.hdeleted file mode 100644index 69c3f7e..0000000--- a/controllers/steam-input/VirtualGamepad.h+++ /dev/null@@ -1,49 +0,0 @@-#pragma once-#include <stdint.h>-#include <stdio.h>-#include <string.h>--// Steam exposes at most sixteen emulated gamepad indices.-constexpr int kGamepadCount = 16;--struct JoystickGUID {- uint8_t data[16];-};--// SDL2's public GUID format uses a CRC-16/IBM of the original HID name.-// Check the complete GUID, not just the Xbox VID/PID shared by real devices.-static JoystickGUID virtualGamepadGUID(unsigned slot, uint16_t version) {- char name[64];- snprintf(name, sizeof(name), "Microsoft GamePad-%u", slot + 1);- uint16_t crc = 0;- for (const unsigned char *p = (const unsigned char *)name; *p; ++p) {- crc ^= *p;- for (int bit = 0; bit < 8; ++bit) {- crc = (crc >> 1) ^ ((crc & 1) ? 0xa001 : 0);- }- }- return {{3, 0, (uint8_t)crc, (uint8_t)(crc >> 8), 0x5e, 4, 0, 0, 0x8e, 2, 0, 0,- (uint8_t)version, (uint8_t)(version >> 8), 0, 0}};-}--static int virtualGamepadSlot(JoystickGUID guid, const char *transport, const char *manufacturer,- const char *product, int vendor, int model, uint16_t version) {- if (!transport || strcmp(transport, "Virtual") || !manufacturer ||- strcmp(manufacturer, "Microsoft") || !product || vendor != 0x045e || model != 0x028e) {- return -1;- }- unsigned number = 0;- char extra;- if (sscanf(product, "GamePad-%u%c", &number, &extra) != 1 || number < 1 ||- number > kGamepadCount) {- return -1;- }- // SDL HIDAPI uses the same GUID plus its documented driver signature.- // Darwin IOKit leaves that byte zero. Both can enumerate Steam's device.- if (guid.data[14] != 0 && guid.data[14] != 'h') {- return -1;- }- guid.data[14] = 0;- JoystickGUID expected = virtualGamepadGUID(number - 1, version);- return !memcmp(&guid, &expected, sizeof(guid)) ? (int)number - 1 : -1;-}diff --git a/controllers/steam-input/rumble.cpp b/controllers/steam-input/rumble.cppdeleted file mode 100644index ff410d6..0000000--- a/controllers/steam-input/rumble.cpp+++ /dev/null@@ -1,347 +0,0 @@-// Forward Winebus SDL2 rumble for Steam's virtual gamepads to native Steam Input.-#include <CoreFoundation/CoreFoundation.h>-#include <IOKit/IOKitLib.h>-#include <dlfcn.h>-#include <pthread.h>-#include <atomic>-#include <algorithm>-#include <chrono>-#include <cstdlib>-#include <cstring>-#include <limits>-#include <unistd.h>-#include "SteamSession.h"-#include "VirtualGamepad.h"--#ifndef INTERPOSE-#define INTERPOSE(replacement, original) \- __attribute__((used)) static const struct { \- const void *a, *b; \- } ip_##original \- __attribute__((section("__DATA,__interpose"))) = {(void *)replacement, (void *)original}-#endif-static_assert(kGamepadCount == STEAM_CONTROLLER_MAX_COUNT);-constexpr double kMappingPollSeconds = 0.020;-constexpr double kSteamRetrySeconds = 2;--// The mutex protects the slot mailbox; the worker alone owns the Steam session.-using Clock = std::chrono::steady_clock;-static double now() {- return std::chrono::duration<double>(Clock::now().time_since_epoch()).count();-}-static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;-static pthread_cond_t wake = PTHREAD_COND_INITIALIZER;-static pthread_once_t workerOnce = PTHREAD_ONCE_INIT;-static std::atomic<bool> running{true};-static pthread_t workerThread;-static std::atomic<bool> workerStarted{false};-static void *sdlLibrary;-static int (*originalRumble)(void *, uint16_t, uint16_t, uint32_t);-static int (*originalHasRumble)(void *);-static void (*originalClose)(void *);-static JoystickGUID (*getGUID)(void *);-static int32_t (*getInstance)(void *);-static int (*getAttached)(void *);--struct Slot {- int32_t instance = -1;- uint16_t left = 0, right = 0;- double until = 0;- uint64_t generation = 0;-};-static Slot slots[kGamepadCount];--static bool enabled() {- const char *mode = getenv("NOTPROTON_STEAM_RUMBLE");- const char *raw = getenv("NOTPROTON_RAW_CONTROLLERS");- const char *app = getenv("SteamAppId");- return mode && !strcmp(mode, "1") && (!raw || strcmp(raw, "1")) && app && *app;-}-static int readNumberProperty(CFDictionaryRef properties, CFStringRef key) {- int n = 0;- CFTypeRef v = CFDictionaryGetValue(properties, key);- if (v && CFGetTypeID(v) == CFNumberGetTypeID()) {- CFNumberGetValue((CFNumberRef)v, kCFNumberIntType, &n);- }- return n;-}-static void readStringProperty(CFDictionaryRef properties, CFStringRef key, char *out,- size_t capacity) {- out[0] = 0;- CFTypeRef v = CFDictionaryGetValue(properties, key);- if (v && CFGetTypeID(v) == CFStringGetTypeID()) {- CFStringGetCString((CFStringRef)v, out, capacity, kCFStringEncodingUTF8);- }-}-static int lookupSlot(void *joystick) {- if (!getGUID || !getInstance || !getAttached || !getAttached(joystick)) {- return -1;- }- int32_t instance = getInstance(joystick);- if (instance < 0) {- return -1;- }- pthread_mutex_lock(&lock);- for (int i = 0; i < kGamepadCount; ++i) {- if (slots[i].instance == instance) {- pthread_mutex_unlock(&lock);- return i;- }- }- pthread_mutex_unlock(&lock);- JoystickGUID guid = getGUID(joystick);- // Reject physical controllers before consulting IOKit. No device is opened.- if (guid.data[0] != 3 || guid.data[4] != 0x5e || guid.data[5] != 4 || guid.data[8] != 0x8e ||- guid.data[9] != 2) {- return -1;- }- io_iterator_t devices = 0;- if (IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("IOHIDDevice"),- &devices)) {- return -1;- }- int found = -1;- io_service_t device;- while ((device = IOIteratorNext(devices))) {- CFMutableDictionaryRef properties = nullptr;- if (!IORegistryEntryCreateCFProperties(device, &properties, kCFAllocatorDefault, 0)) {- char transport[64], manufacturer[128], product[128];- readStringProperty(properties, CFSTR("Transport"), transport, sizeof(transport));- readStringProperty(properties, CFSTR("Manufacturer"), manufacturer,- sizeof(manufacturer));- readStringProperty(properties, CFSTR("Product"), product, sizeof(product));- int slot = virtualGamepadSlot(guid, transport, manufacturer, product,- readNumberProperty(properties, CFSTR("VendorID")),- readNumberProperty(properties, CFSTR("ProductID")),- readNumberProperty(properties, CFSTR("VersionNumber")));- if (slot >= 0) {- found = slot;- }- CFRelease(properties);- }- IOObjectRelease(device);- }- IOObjectRelease(devices);- if (found >= 0) {- pthread_mutex_lock(&lock);- if (slots[found].instance != instance) {- uint64_t generation = slots[found].generation + 1;- slots[found] = Slot{};- slots[found].instance = instance;- slots[found].generation = generation;- pthread_cond_signal(&wake);- }- pthread_mutex_unlock(&lock);- fprintf(stderr, "bridgeplay-rumble: Steam virtual gamepad slot %d mapped (pid %d)\n", found,- getpid());- }- return found;-}--static void *worker(void *) {- SteamSession steam;- uint64_t seen[kGamepadCount] = {};- ControllerHandle_t active[kGamepadCount] = {};- double retryAt = 0;- while (running) {- Slot snapshot[kGamepadCount];- pthread_mutex_lock(&lock);- memcpy(snapshot, slots, sizeof(slots));- pthread_mutex_unlock(&lock);- double time = now(), next = time + 1;- bool pending = false;- for (int i = 0; i < kGamepadCount; ++i) {- pending |= snapshot[i].generation != seen[i] && snapshot[i].instance >= 0 &&- snapshot[i].until > time;- }- if (!steam.controller && pending && time >= retryAt) {- if (!steam.open()) {- retryAt = now() + kSteamRetrySeconds;- }- }- if (steam.controller) {- steam.controller->RunFrame();- // Use commands received while Steam was opening or RunFrame was blocked.- pthread_mutex_lock(&lock);- memcpy(snapshot, slots, sizeof(slots));- pthread_mutex_unlock(&lock);- time = now();- ControllerHandle_t handles[kGamepadCount] = {};- for (int i = 0; i < kGamepadCount; ++i) {- if (snapshot[i].until > time && snapshot[i].instance >= 0) {- handles[i] = steam.controller->GetControllerForGamepadIndex(i);- }- }- // Stop every old assignment before starting any new one. This also- // handles two controllers exchanging their gamepad indices.- for (int i = 0; i < kGamepadCount; ++i) {- if (active[i] && active[i] != handles[i]) {- steam.controller->TriggerVibration(active[i], 0, 0);- active[i] = 0;- }- }- for (int i = 0; i < kGamepadCount; ++i) {- const Slot &request = snapshot[i];- bool alive = request.until > time && request.instance >= 0;- ControllerHandle_t handle = handles[i];- if (handle && (request.generation != seen[i] || active[i] != handle)) {- steam.controller->TriggerVibration(handle, request.left, request.right);- active[i] = handle;- static bool logged;- if (!logged) {- fprintf(stderr, "bridgeplay-rumble: forwarding rumble via Steam\n");- logged = true;- }- }- if (handle || !alive) {- seen[i] = request.generation;- }- // Retry a missing mapping, and detect reassignment during an effect.- if (alive) {- next = std::min(next, std::min(time + kMappingPollSeconds, request.until));- }- }- }- pthread_mutex_lock(&lock);- bool changed = false;- for (int i = 0; i < kGamepadCount; ++i) {- changed |= slots[i].generation != snapshot[i].generation;- }- if (!changed && running) {- double wait = next - now();- if (wait > 0) {- struct timespec timeout{(time_t)wait, (long)((wait - (time_t)wait) * 1e9)};- pthread_cond_timedwait_relative_np(&wake, &lock, &timeout);- }- }- pthread_mutex_unlock(&lock);- }- if (steam.controller) {- for (auto handle : active) {- if (handle) {- steam.controller->TriggerVibration(handle, 0, 0);- }- }- }- return nullptr;-}-static void startWorker() {- workerStarted = pthread_create(&workerThread, nullptr, worker, nullptr) == 0;-}-static int rumble(void *joystick, uint16_t left, uint16_t right, uint32_t duration) {- int slot = lookupSlot(joystick);- if (slot < 0) {- return originalRumble(joystick, left, right, duration);- }- // Wine probes with zeroes: advertise support without connecting to Steam or- // cancelling rumble owned by another client (e.g. the game's Steam API).- pthread_mutex_lock(&lock);- bool idle = slots[slot].until == 0;- pthread_mutex_unlock(&lock);- if (idle && !(left || right)) {- return 0;- }- pthread_once(&workerOnce, startWorker);- if (!workerStarted) {- return -1;- }- pthread_mutex_lock(&lock);- slots[slot].left = left;- slots[slot].right = right;- // SDL2 uses a zero duration for effects without an automatic expiry.- if (!(left || right)) {- slots[slot].until = 0;- } else if (duration) {- slots[slot].until = now() + std::min(duration, uint32_t{65535}) / 1000.0;- } else {- slots[slot].until = std::numeric_limits<double>::infinity();- }- ++slots[slot].generation;- pthread_cond_signal(&wake);- pthread_mutex_unlock(&lock);- return 0;-}-static int hasRumble(void *joystick) {- if (lookupSlot(joystick) >= 0) {- return 1;- }- return originalHasRumble ? originalHasRumble(joystick) : 0;-}-static void closeJoystick(void *joystick) {- int32_t instance = getInstance ? getInstance(joystick) : -1;- pthread_mutex_lock(&lock);- for (auto &slot : slots) {- if (instance >= 0 && slot.instance == instance) {- slot.instance = -1;- slot.until = 0;- ++slot.generation;- }- }- pthread_cond_signal(&wake);- pthread_mutex_unlock(&lock);- originalClose(joystick);-}-static void *resolve(void *library, const char *symbol) {- void *original = dlsym(library, symbol);- if (getenv("NOTPROTON_STEAM_RUMBLE_TRACE") && !strcmp(symbol, "SDL_JoystickRumble")) {- Dl_info diag{};- dladdr(original, &diag);- fprintf(stderr, "bridgeplay-rumble: resolve pid=%d enabled=%d source=%s root=%s app=%s\n",- getpid(), enabled(), diag.dli_fname ? diag.dli_fname : "?",- getenv("CX_ROOT") ? getenv("CX_ROOT") : "?",- getenv("SteamAppId") ? getenv("SteamAppId") : "?");- }- if (!original || !enabled() ||- (strcmp(symbol, "SDL_JoystickRumble") && strcmp(symbol, "SDL_JoystickHasRumble") &&- strcmp(symbol, "SDL_JoystickClose"))) {- return original;- }- // Never hook Steam's own SDL or an unrelated application/library.- Dl_info image{};- const char *root = getenv("CX_ROOT");- if (!root || !*root || !dladdr(original, &image) || !image.dli_fname ||- strncmp(image.dli_fname, root, strlen(root)) || image.dli_fname[strlen(root)] != '/') {- return original;- }- pthread_mutex_lock(&lock);- if (!sdlLibrary) {- auto guid = (decltype(getGUID))dlsym(library, "SDL_JoystickGetGUID");- auto instance = (decltype(getInstance))dlsym(library, "SDL_JoystickInstanceID");- auto attached = (decltype(getAttached))dlsym(library, "SDL_JoystickGetAttached");- auto rumble = (decltype(originalRumble))dlsym(library, "SDL_JoystickRumble");- auto hasRumble = (decltype(originalHasRumble))dlsym(library, "SDL_JoystickHasRumble");- auto close = (decltype(originalClose))dlsym(library, "SDL_JoystickClose");- if (guid && instance && attached && rumble && close) {- getGUID = guid;- getInstance = instance;- getAttached = attached;- originalRumble = rumble;- originalHasRumble = hasRumble;- originalClose = close;- sdlLibrary = library;- }- }- bool matched = sdlLibrary == library;- pthread_mutex_unlock(&lock);- if (!matched) {- return original;- }- if (!strcmp(symbol, "SDL_JoystickRumble")) {- return (void *)rumble;- }- if (!strcmp(symbol, "SDL_JoystickHasRumble")) {- return (void *)hasRumble;- }- return (void *)closeJoystick;-}-INTERPOSE(resolve, dlsym);-__attribute__((destructor)) static void shutdownBridge() {- if (!workerStarted.exchange(false)) {- return;- }- running = false;- pthread_mutex_lock(&lock);- pthread_cond_signal(&wake);- pthread_mutex_unlock(&lock);- pthread_join(workerThread, nullptr);-}diff --git a/controllers/steam-input/tests/MockSteam.h b/controllers/steam-input/tests/MockSteam.hdeleted file mode 100644index 2150a8f..0000000--- a/controllers/steam-input/tests/MockSteam.h+++ /dev/null@@ -1,10 +0,0 @@-#pragma once-#include <cstdint>--struct RumbleEvent {- uint64_t handle;- uint16_t left, right;-};-struct SessionStats {- unsigned pipes, releasedPipes, users, releasedUsers, initializations, shutdowns;-};diff --git a/controllers/steam-input/tests/hooks.cpp b/controllers/steam-input/tests/hooks.cppdeleted file mode 100644index 6ca9ef8..0000000--- a/controllers/steam-input/tests/hooks.cpp+++ /dev/null@@ -1,172 +0,0 @@-#include <CoreFoundation/CoreFoundation.h>-#include <IOKit/IOKitLib.h>-#include <dlfcn.h>-#include <cassert>-#include <cstring>-#include <string>-#include "../VirtualGamepad.h"--struct Joystick {- int32_t instance;- bool attached = true;- JoystickGUID guid;-};-static CFMutableDictionaryRef deviceProperties;-static bool devicePending, incompleteSDL;-static unsigned enumerations, fallbackCalls, closeCalls;-static const char *imagePath = "/test/CrossOver/lib/libSDL2.dylib";-static JoystickGUID mockGUID(void *j) {- return ((Joystick *)j)->guid;-}-static int32_t mockInstance(void *j) {- return ((Joystick *)j)->instance;-}-static int mockAttached(void *j) {- return ((Joystick *)j)->attached;-}-static int mockRumble(void *, uint16_t, uint16_t, uint32_t) {- ++fallbackCalls;- return -7;-}-static int mockHasRumble(void *) {- return 0;-}-static void mockClose(void *j) {- ((Joystick *)j)->attached = false;- ++closeCalls;-}-static void *mockDlsym(void *, const char *name) {- if (!strcmp(name, "SDL_JoystickGetGUID")) {- return (void *)mockGUID;- }- if (!strcmp(name, "SDL_JoystickInstanceID")) {- return (void *)mockInstance;- }- if (!strcmp(name, "SDL_JoystickGetAttached")) {- return incompleteSDL ? nullptr : (void *)mockAttached;- }- if (!strcmp(name, "SDL_JoystickRumble")) {- return (void *)mockRumble;- }- if (!strcmp(name, "SDL_JoystickHasRumble")) {- return (void *)mockHasRumble;- }- if (!strcmp(name, "SDL_JoystickClose")) {- return (void *)mockClose;- }- return nullptr;-}-static int mockDladdr(const void *, Dl_info *info) {- info->dli_fname = imagePath;- return 1;-}-static kern_return_t mockMatching(mach_port_t, CFDictionaryRef matching, io_iterator_t *iterator) {- CFRelease(matching);- ++enumerations;- devicePending = true;- *iterator = 1;- return KERN_SUCCESS;-}-static io_object_t mockNext(io_iterator_t) {- if (!devicePending) {- return 0;- }- devicePending = false;- return 2;-}-static kern_return_t mockProperties(io_registry_entry_t, CFMutableDictionaryRef *out,- CFAllocatorRef, IOOptionBits) {- *out = CFDictionaryCreateMutableCopy(nullptr, 0, deviceProperties);- return KERN_SUCCESS;-}-static kern_return_t mockRelease(io_object_t) {- return KERN_SUCCESS;-}--#define INTERPOSE(replacement, original)-#define dlsym mockDlsym-#define dladdr mockDladdr-#define IOServiceGetMatchingServices mockMatching-#define IOIteratorNext mockNext-#define IORegistryEntryCreateCFProperties mockProperties-#define IOObjectRelease mockRelease-#include "../rumble.cpp"-#undef dlsym-#undef dladdr-#undef IOServiceGetMatchingServices-#undef IOIteratorNext-#undef IORegistryEntryCreateCFProperties-#undef IOObjectRelease--static void number(CFStringRef key, int value) {- auto property = CFNumberCreate(nullptr, kCFNumberIntType, &value);- CFDictionarySetValue(deviceProperties, key, property);- CFRelease(property);-}-int main() {- void *library = (void *)1;- setenv("NOTPROTON_STEAM_RUMBLE", "1", 1);- setenv("NOTPROTON_RAW_CONTROLLERS", "0", 1);- setenv("SteamAppId", "242680", 1);- setenv("CX_ROOT", "/test/CrossOver", 1);- assert(resolve(library, "missing") == nullptr);- for (const char *key : {"NOTPROTON_STEAM_RUMBLE", "SteamAppId", "CX_ROOT"}) {- std::string saved = getenv(key);- setenv(key, "", 1);- assert(resolve(library, "SDL_JoystickRumble") == (void *)mockRumble);- setenv(key, saved.c_str(), 1);- }- setenv("NOTPROTON_RAW_CONTROLLERS", "1", 1);- assert(resolve(library, "SDL_JoystickRumble") == (void *)mockRumble);- setenv("NOTPROTON_RAW_CONTROLLERS", "0", 1);- for (auto path : {"/Steam/libSDL2.dylib", "/test/CrossOver-other/libSDL2.dylib"}) {- imagePath = path;- assert(resolve(library, "SDL_JoystickRumble") == (void *)mockRumble);- }- imagePath = "/test/CrossOver/lib/libSDL2.dylib";- incompleteSDL = true;- assert(resolve(library, "SDL_JoystickRumble") == (void *)mockRumble);- assert(!getGUID && !originalRumble && !sdlLibrary);- incompleteSDL = false;- assert(resolve(library, "SDL_JoystickRumble") == (void *)rumble);- assert(resolve(library, "SDL_JoystickHasRumble") == (void *)hasRumble);- assert(resolve(library, "SDL_JoystickClose") == (void *)closeJoystick);- assert(resolve((void *)2, "SDL_JoystickRumble") == (void *)mockRumble);-- deviceProperties = CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,- &kCFTypeDictionaryValueCallBacks);- CFDictionarySetValue(deviceProperties, CFSTR("Transport"), CFSTR("Virtual"));- CFDictionarySetValue(deviceProperties, CFSTR("Manufacturer"), CFSTR("Microsoft"));- CFDictionarySetValue(deviceProperties, CFSTR("Product"), CFSTR("GamePad-1"));- number(CFSTR("VendorID"), 0x45e);- number(CFSTR("ProductID"), 0x28e);- number(CFSTR("VersionNumber"), 0);- Joystick physical{10, true, {}};- assert(hasRumble(&physical) == 0 && enumerations == 0);- assert(rumble(&physical, 1, 2, 3) == -7 && fallbackCalls == 1);- Joystick first{11, true, virtualGamepadGUID(0, 0)};- assert(hasRumble(&first) == 1 && enumerations == 1);- assert(hasRumble(&first) == 1 && enumerations == 1); // Cached SDL instance.- assert(rumble(&first, 0, 0, 0) == 0 && !workerStarted);- first.attached = false;- assert(hasRumble(&first) == 0);- slots[0].until = now() + 60;- slots[0].left = 123;- uint64_t oldGeneration = slots[0].generation;- Joystick replacement{12, true, virtualGamepadGUID(0, 0)};- replacement.guid.data[14] = 'h';- assert(hasRumble(&replacement) == 1);- assert(slots[0].instance == 12 && slots[0].until == 0 && slots[0].left == 0);- assert(slots[0].generation > oldGeneration);- closeJoystick(&first);- assert(slots[0].instance == 12); // A late close cannot invalidate the replacement.- closeJoystick(&replacement);- assert(slots[0].instance == -1 && closeCalls == 2);- CFDictionarySetValue(deviceProperties, CFSTR("Transport"), CFSTR("USB"));- Joystick realXbox{13, true, virtualGamepadGUID(0, 0)};- assert(hasRumble(&realXbox) == 0);- assert(!workerStarted);- CFRelease(deviceProperties);- puts("steam-input: SDL symbol gating, IOKit identity, cache, HIDAPI, replacement and close "- "passed");-}diff --git a/controllers/steam-input/tests/launcher.py b/controllers/steam-input/tests/launcher.pydeleted file mode 100644index 49fbab9..0000000--- a/controllers/steam-input/tests/launcher.py+++ /dev/null@@ -1,50 +0,0 @@-"""Exercise launch gating with real shell expansion; no Steam or hardware needed."""--import os-import subprocess-import tempfile-from pathlib import Path--root = Path(__file__).resolve().parents[3]-source = (root / "dylib/feats/compat_run.sh").read_text()-start = source.index('steam_rumble="$np_support/controllers/steam-input/rumble.dylib"')-end = source.index("export NOTPROTON_RUMBLE_LIBRARY", start) + len(- "export NOTPROTON_RUMBLE_LIBRARY"-)-block = source[start:end]-with tempfile.TemporaryDirectory(prefix="bridgeplay rumble ") as tmp:- library = Path(tmp) / "controllers/steam-input/rumble.dylib"- library.parent.mkdir(parents=True)- library.touch()- for verb, raw, setting, expected in [- ("waitforexitandrun", "0", "", True),- ("waitforexitandrun", "1", "", False),- ("waitforexitandrun", "0", "0", False),- ("run", "0", "", False),- ("waitforexitandrun", "", "1", True),- ]:- env = dict(- os.environ,- np_support=tmp,- verb=verb,- NOTPROTON_RAW_CONTROLLERS=raw,- NOTPROTON_STEAM_RUMBLE=setting,- )- for overlay in ("", "overlay"):- command = (- f"DYLD_INSERT_LIBRARIES={overlay}\n"- + block- + '\nprintf "%s|%s" "$NOTPROTON_RUMBLE_LIBRARY" "$DYLD_INSERT_LIBRARIES"'- )- result = subprocess.check_output(["/bin/sh", "-c", command], env=env, text=True)- libraries = str(library) + (f":{overlay}" if overlay else "")- assert result == (f"{library}|{libraries}" if expected else f"|{overlay}"), result- library.unlink()- env.update(verb="waitforexitandrun")- assert subprocess.check_output(["/bin/sh", "-c", command], env=env, text=True) == "|overlay"-for name in ("NOTPROTON_RUMBLE_LIBRARY", "NOTPROTON_STEAM_RUMBLE", "NOTPROTON_RAW_CONTROLLERS"):- assert f"--env {name}=" in source-assert "\\$NOTPROTON_RUMBLE_LIBRARY\\${DYLD_INSERT_LIBRARIES:+" in source-print(- "steam-input: game/helper/raw/disabled/missing-library launch gating and environment forwarding passed"-)diff --git a/controllers/steam-input/tests/mock-steam.cpp b/controllers/steam-input/tests/mock-steam.cppdeleted file mode 100644index f6c2137..0000000--- a/controllers/steam-input/tests/mock-steam.cpp+++ /dev/null@@ -1,350 +0,0 @@-#include "steam_api.h"-#include "MockSteam.h"-#include <atomic>-#include <cassert>-#include <cstdlib>-#include <cstring>-#include <mutex>-#include <unistd.h>-#include <vector>--static std::mutex eventLock;-static std::vector<RumbleEvent> events;-static std::atomic<ControllerHandle_t> handles[STEAM_CONTROLLER_MAX_COUNT];-static std::atomic<unsigned> frameDelay{0};-static std::atomic<bool> frameBlocked{false};-static unsigned failure, pipes, releasedPipes, users, releasedUsers, initializations, shutdowns;--// Implement the SDK interfaces so the compiler checks the ABI. Any unexpected-// API call aborts the test, including attempts to change LEDs or input bindings.-struct ControllerMock final : ISteamController {- bool Init() override {- ++initializations;- return failure != 4;- }- bool Shutdown() override {- ++shutdowns;- return true;- }- void RunFrame() override {- unsigned delay = frameDelay.exchange(0);- if (delay) {- frameBlocked = true;- usleep(delay * 1000);- frameBlocked = false;- }- }- int GetConnectedControllers(ControllerHandle_t *handlesOut) override {- std::abort();- }- ControllerActionSetHandle_t GetActionSetHandle(const char *pszActionSetName) override {- std::abort();- }- void ActivateActionSet(ControllerHandle_t controllerHandle,- ControllerActionSetHandle_t actionSetHandle) override {- std::abort();- }- ControllerActionSetHandle_t GetCurrentActionSet(ControllerHandle_t controllerHandle) override {- std::abort();- }- void ActivateActionSetLayer(ControllerHandle_t controllerHandle,- ControllerActionSetHandle_t actionSetLayerHandle) override {- std::abort();- }- void DeactivateActionSetLayer(ControllerHandle_t controllerHandle,- ControllerActionSetHandle_t actionSetLayerHandle) override {- std::abort();- }- void DeactivateAllActionSetLayers(ControllerHandle_t controllerHandle) override {- std::abort();- }- int GetActiveActionSetLayers(ControllerHandle_t controllerHandle,- ControllerActionSetHandle_t *handlesOut) override {- std::abort();- }- ControllerDigitalActionHandle_t GetDigitalActionHandle(const char *pszActionName) override {- std::abort();- }- ControllerDigitalActionData_t- GetDigitalActionData(ControllerHandle_t controllerHandle,- ControllerDigitalActionHandle_t digitalActionHandle) override {- std::abort();- }- int GetDigitalActionOrigins(ControllerHandle_t controllerHandle,- ControllerActionSetHandle_t actionSetHandle,- ControllerDigitalActionHandle_t digitalActionHandle,- EControllerActionOrigin *originsOut) override {- std::abort();- }- ControllerAnalogActionHandle_t GetAnalogActionHandle(const char *pszActionName) override {- std::abort();- }- ControllerAnalogActionData_t- GetAnalogActionData(ControllerHandle_t controllerHandle,- ControllerAnalogActionHandle_t analogActionHandle) override {- std::abort();- }- int GetAnalogActionOrigins(ControllerHandle_t controllerHandle,- ControllerActionSetHandle_t actionSetHandle,- ControllerAnalogActionHandle_t analogActionHandle,- EControllerActionOrigin *originsOut) override {- std::abort();- }- const char *GetGlyphForActionOrigin(EControllerActionOrigin eOrigin) override {- std::abort();- }- const char *GetStringForActionOrigin(EControllerActionOrigin eOrigin) override {- std::abort();- }- void StopAnalogActionMomentum(ControllerHandle_t controllerHandle,- ControllerAnalogActionHandle_t eAction) override {- std::abort();- }- ControllerMotionData_t GetMotionData(ControllerHandle_t controllerHandle) override {- std::abort();- }- void TriggerHapticPulse(ControllerHandle_t controllerHandle, ESteamControllerPad eTargetPad,- unsigned short usDurationMicroSec) override {- std::abort();- }- void TriggerRepeatedHapticPulse(ControllerHandle_t controllerHandle,- ESteamControllerPad eTargetPad,- unsigned short usDurationMicroSec, unsigned short usOffMicroSec,- unsigned short unRepeat, unsigned int nFlags) override {- std::abort();- }- void TriggerVibration(ControllerHandle_t controllerHandle, unsigned short usLeftSpeed,- unsigned short usRightSpeed) override {- std::lock_guard<std::mutex> guard(eventLock);- events.push_back({controllerHandle, usLeftSpeed, usRightSpeed});- }- void SetLEDColor(ControllerHandle_t controllerHandle, uint8 nColorR, uint8 nColorG,- uint8 nColorB, unsigned int nFlags) override {- std::abort();- }- bool ShowBindingPanel(ControllerHandle_t controllerHandle) override {- std::abort();- }- ESteamInputType GetInputTypeForHandle(ControllerHandle_t controllerHandle) override {- std::abort();- }- ControllerHandle_t GetControllerForGamepadIndex(int nIndex) override {- return handles[nIndex].load();- }- int GetGamepadIndexForController(ControllerHandle_t ulControllerHandle) override {- std::abort();- }- const char *GetStringForXboxOrigin(EXboxOrigin eOrigin) override {- std::abort();- }- const char *GetGlyphForXboxOrigin(EXboxOrigin eOrigin) override {- std::abort();- }- EControllerActionOrigin GetActionOriginFromXboxOrigin(ControllerHandle_t controllerHandle,- EXboxOrigin eOrigin) override {- std::abort();- }- EControllerActionOrigin TranslateActionOrigin(ESteamInputType eDestinationInputType,- EControllerActionOrigin eSourceOrigin) override {- std::abort();- }- bool GetControllerBindingRevision(ControllerHandle_t controllerHandle, int *pMajor,- int *pMinor) override {- std::abort();- }-};-static ControllerMock controller;--struct ClientMock final : ISteamClient {- HSteamPipe CreateSteamPipe() override {- if (failure == 1) {- return 0;- }- ++pipes;- return 1;- }- bool BReleaseSteamPipe(HSteamPipe hSteamPipe) override {- assert(hSteamPipe == 1);- ++releasedPipes;- return true;- }- HSteamUser ConnectToGlobalUser(HSteamPipe hSteamPipe) override {- assert(hSteamPipe == 1);- if (failure == 2) {- return 0;- }- ++users;- return 1;- }- HSteamUser CreateLocalUser(HSteamPipe *phSteamPipe, EAccountType eAccountType) override {- std::abort();- }- void ReleaseUser(HSteamPipe hSteamPipe, HSteamUser hUser) override {- assert(hSteamPipe == 1 && hUser == 1);- ++releasedUsers;- }- ISteamUser *GetISteamUser(HSteamUser hSteamUser, HSteamPipe hSteamPipe,- const char *pchVersion) override {- std::abort();- }- ISteamGameServer *GetISteamGameServer(HSteamUser hSteamUser, HSteamPipe hSteamPipe,- const char *pchVersion) override {- std::abort();- }- void SetLocalIPBinding(const SteamIPAddress_t &unIP, uint16 usPort) override {- std::abort();- }- ISteamFriends *GetISteamFriends(HSteamUser hSteamUser, HSteamPipe hSteamPipe,- const char *pchVersion) override {- std::abort();- }- ISteamUtils *GetISteamUtils(HSteamPipe hSteamPipe, const char *pchVersion) override {- std::abort();- }- ISteamMatchmaking *GetISteamMatchmaking(HSteamUser hSteamUser, HSteamPipe hSteamPipe,- const char *pchVersion) override {- std::abort();- }- ISteamMatchmakingServers *GetISteamMatchmakingServers(HSteamUser hSteamUser,- HSteamPipe hSteamPipe,- const char *pchVersion) override {- std::abort();- }- void *GetISteamGenericInterface(HSteamUser hSteamUser, HSteamPipe hSteamPipe,- const char *pchVersion) override {- std::abort();- }- ISteamUserStats *GetISteamUserStats(HSteamUser hSteamUser, HSteamPipe hSteamPipe,- const char *pchVersion) override {- std::abort();- }- ISteamGameServerStats *GetISteamGameServerStats(HSteamUser hSteamuser, HSteamPipe hSteamPipe,- const char *pchVersion) override {- std::abort();- }- ISteamApps *GetISteamApps(HSteamUser hSteamUser, HSteamPipe hSteamPipe,- const char *pchVersion) override {- std::abort();- }- ISteamNetworking *GetISteamNetworking(HSteamUser hSteamUser, HSteamPipe hSteamPipe,- const char *pchVersion) override {- std::abort();- }- ISteamRemoteStorage *GetISteamRemoteStorage(HSteamUser hSteamuser, HSteamPipe hSteamPipe,- const char *pchVersion) override {- std::abort();- }- ISteamScreenshots *GetISteamScreenshots(HSteamUser hSteamuser, HSteamPipe hSteamPipe,- const char *pchVersion) override {- std::abort();- }- ISteamGameSearch *GetISteamGameSearch(HSteamUser hSteamuser, HSteamPipe hSteamPipe,- const char *pchVersion) override {- std::abort();- }- void RunFrame() override {- std::abort();- }- uint32 GetIPCCallCount() override {- std::abort();- }- void SetWarningMessageHook(SteamAPIWarningMessageHook_t pFunction) override {- std::abort();- }- bool BShutdownIfAllPipesClosed() override {- std::abort();- }- ISteamHTTP *GetISteamHTTP(HSteamUser hSteamuser, HSteamPipe hSteamPipe,- const char *pchVersion) override {- std::abort();- }- ISteamController *GetISteamController(HSteamUser hSteamUser, HSteamPipe hSteamPipe,- const char *pchVersion) override {- assert(hSteamUser == 1 && hSteamPipe == 1);- assert(!strcmp(pchVersion, STEAMCONTROLLER_INTERFACE_VERSION));- return failure == 3 ? nullptr : &controller;- }- ISteamUGC *GetISteamUGC(HSteamUser hSteamUser, HSteamPipe hSteamPipe,- const char *pchVersion) override {- std::abort();- }- ISteamMusic *GetISteamMusic(HSteamUser hSteamuser, HSteamPipe hSteamPipe,- const char *pchVersion) override {- std::abort();- }- ISteamMusicRemote *GetISteamMusicRemote(HSteamUser hSteamuser, HSteamPipe hSteamPipe,- const char *pchVersion) override {- std::abort();- }- ISteamHTMLSurface *GetISteamHTMLSurface(HSteamUser hSteamuser, HSteamPipe hSteamPipe,- const char *pchVersion) override {- std::abort();- }- void DEPRECATED_Set_SteamAPI_CPostAPIResultInProcess(void (*)()) override {- std::abort();- }- void DEPRECATED_Remove_SteamAPI_CPostAPIResultInProcess(void (*)()) override {- std::abort();- }- void Set_SteamAPI_CCheckCallbackRegisteredInProcess(- SteamAPI_CheckCallbackRegistered_t func) override {- std::abort();- }- ISteamInventory *GetISteamInventory(HSteamUser hSteamuser, HSteamPipe hSteamPipe,- const char *pchVersion) override {- std::abort();- }- ISteamVideo *GetISteamVideo(HSteamUser hSteamuser, HSteamPipe hSteamPipe,- const char *pchVersion) override {- std::abort();- }- ISteamParentalSettings *GetISteamParentalSettings(HSteamUser hSteamuser, HSteamPipe hSteamPipe,- const char *pchVersion) override {- std::abort();- }- ISteamInput *GetISteamInput(HSteamUser hSteamUser, HSteamPipe hSteamPipe,- const char *pchVersion) override {- std::abort();- }- ISteamParties *GetISteamParties(HSteamUser hSteamUser, HSteamPipe hSteamPipe,- const char *pchVersion) override {- std::abort();- }- ISteamRemotePlay *GetISteamRemotePlay(HSteamUser hSteamUser, HSteamPipe hSteamPipe,- const char *pchVersion) override {- std::abort();- }- void DestroyAllInterfaces() override {- std::abort();- }-};-static ClientMock client;--extern "C" void *CreateInterface(const char *version, int *) {- assert(!strcmp(version, STEAMCLIENT_INTERFACE_VERSION));- return &client;-}-extern "C" unsigned testCount() {- std::lock_guard<std::mutex> guard(eventLock);- return events.size();-}-extern "C" RumbleEvent testEvent(unsigned i) {- std::lock_guard<std::mutex> guard(eventLock);- return events.at(i);-}-extern "C" void testSetHandle(int slot, ControllerHandle_t handle) {- handles[slot] = handle;-}-extern "C" void testDelayFrame(unsigned milliseconds) {- frameDelay = milliseconds;-}-extern "C" void testFailure(unsigned stage) {- failure = stage;-}-extern "C" SessionStats testStats() {- return {pipes, releasedPipes, users, releasedUsers, initializations, shutdowns};-}--extern "C" bool testFrameBlocked() {- return frameBlocked;-}diff --git a/controllers/steam-input/tests/routing.cpp b/controllers/steam-input/tests/routing.cppdeleted file mode 100644index cab1655..0000000--- a/controllers/steam-input/tests/routing.cpp+++ /dev/null@@ -1,197 +0,0 @@-#include <cassert>-#include <string>-#include "../rumble.cpp"-#include "MockSteam.h"-static unsigned (*countEvents)();-static RumbleEvent (*eventAt)(unsigned);-static unsigned fallbackCalls;-static int32_t instance(void *j) {- return (int32_t)(uintptr_t)j;-}-static int attached(void *j) {- return j != nullptr;-}-static JoystickGUID physicalGUID(void *) {- return {};-}-static int fallback(void *, uint16_t, uint16_t, uint32_t) {- ++fallbackCalls;- return -7;-}-static void noop(void *) {}-static void waitFor(unsigned count) {- for (int i = 0; i < 200 && countEvents() < count; ++i) {- usleep(5000);- }- assert(countEvents() >= count);-}-int main(int argc, char **argv) {- assert(argc == 2);- // Raw Xbox IDs are insufficient; confirm IOKit's Virtual transport and- // original product name, including slot, against SDL's complete GUID.- auto guid = virtualGamepadGUID(0, 0);- const uint8_t recorded[16] = {3, 0, 0x53, 0x25, 0x5e, 4, 0, 0, 0x8e, 2, 0, 0, 0, 0, 0, 0};- assert(!memcmp(guid.data, recorded, 16));- assert(virtualGamepadSlot(guid, "Virtual", "Microsoft", "GamePad-1", 0x45e, 0x28e, 0) == 0);- assert(virtualGamepadSlot(guid, "USB", "Microsoft", "GamePad-1", 0x45e, 0x28e, 0) == -1);- assert(virtualGamepadSlot(guid, "Virtual", "Microsoft", "GamePad-2", 0x45e, 0x28e, 0) == -1);- assert(virtualGamepadSlot(guid, "Virtual", "Microsoft", "GamePad-1junk", 0x45e, 0x28e, 0) ==- -1);- auto hidapi = guid;- hidapi.data[14] = 'h';- assert(virtualGamepadSlot(hidapi, "Virtual", "Microsoft", "GamePad-1", 0x45e, 0x28e, 0) == 0);- hidapi.data[14] = 'm';- assert(virtualGamepadSlot(hidapi, "Virtual", "Microsoft", "GamePad-1", 0x45e, 0x28e, 0) == -1);- for (unsigned i = 0; i < 16; i++) {- char name[32];- snprintf(name, sizeof(name), "GamePad-%u", i + 1);- assert(virtualGamepadSlot(virtualGamepadGUID(i, 7), "Virtual", "Microsoft", name, 0x45e,- 0x28e, 7) == (int)i);- }- setenv("STEAM_COMPAT_CLIENT_INSTALL_PATH", argv[1], 1);- std::string library = std::string(argv[1]) + "/steamclient.dylib";- void *mock = dlopen(library.c_str(), RTLD_NOW | RTLD_LOCAL);- assert(mock);- countEvents = (decltype(countEvents))dlsym(mock, "testCount");- eventAt = (decltype(eventAt))dlsym(mock, "testEvent");- auto setHandle = (void (*)(int, ControllerHandle_t))dlsym(mock, "testSetHandle");- auto delayFrame = (void (*)(unsigned))dlsym(mock, "testDelayFrame");- auto setFailure = (void (*)(unsigned))dlsym(mock, "testFailure");- auto stats = (SessionStats (*)())dlsym(mock, "testStats");- assert(countEvents && eventAt && setHandle && delayFrame && setFailure && stats);- setHandle(0, 100);- setHandle(1, 101);-- for (unsigned failure = 1; failure <= 4; ++failure) {- setFailure(failure);- SteamSession session;- assert(!session.open());- auto counts = stats();- assert(counts.pipes == counts.releasedPipes && counts.users == counts.releasedUsers);- assert(!session.controller && !session.pipe && !session.user);- }- setFailure(0);- {- SteamSession session;- assert(session.open());- }- auto counts = stats();- assert(counts.pipes == counts.releasedPipes && counts.users == counts.releasedUsers);- assert(counts.shutdowns == 1);-- getInstance = instance;- getAttached = attached;- getGUID = physicalGUID;- originalRumble = fallback;- originalClose = noop;- slots[0].instance = 42;- slots[1].instance = 43;- assert(rumble((void *)99, 1, 2, 3) == -7 && fallbackCalls == 1); // physical path- assert(rumble((void *)42, 0, 0, 0) == 0 && !workerStarted); // capability probe- assert(rumble((void *)42, 12345, 54321, 200) == 0);- waitFor(1);- auto e = eventAt(0);- assert(e.handle == 100 && e.left == 12345 && e.right == 54321);- waitFor(2);- e = eventAt(1);- assert(e.handle == 100 && !e.left && !e.right); // expiry- rumble((void *)43, 200, 400, 2000);- waitFor(3);- assert(eventAt(2).handle == 101);- rumble((void *)43, 0, 0, 0);- waitFor(4);- assert(eventAt(3).handle == 101 && !eventAt(3).left); // explicit stop- rumble((void *)42, 333, 444, 2000);- waitFor(5);- closeJoystick((void *)42);- waitFor(6);- assert(!eventAt(5).left); // removal- assert(slots[0].instance == -1);- rumble((void *)43, 500, 600, 2000);- waitFor(7);- // A game can send its first effect while Steam is still publishing the- // virtual-to-physical mapping. It must not need another XInput call.- rumble((void *)43, 0, 0, 0);- waitFor(8);- setHandle(1, 0);- rumble((void *)43, 777, 888, 2000);- usleep(60000);- assert(countEvents() == 8);- setHandle(1, 101);- waitFor(9);- assert(eventAt(8).left == 777 && eventAt(8).right == 888);-- // Mapping changes must stop the old handle before using the replacement,- // even if Wine has not issued another rumble command.- setHandle(1, 201);- waitFor(11);- assert(eventAt(9).handle == 101 && !eventAt(9).left);- assert(eventAt(10).handle == 201 && eventAt(10).left == 777);- setHandle(1, 0);- waitFor(12);- assert(eventAt(11).handle == 201 && !eventAt(11).left);- setHandle(1, 101);- waitFor(13);- assert(eventAt(12).left == 777);- rumble((void *)43, 0, 0, 0);- waitFor(14);-- // A slow Steam update must not resurrect an effect whose deadline passed.- delayFrame(100);- rumble((void *)43, 111, 222, 30);- usleep(160000);- assert(countEvents() == 14);-- // SDL2 leaves a nonzero effect running when duration is zero.- rumble((void *)43, 555, 666, 0);- waitFor(15);- usleep(60000);- assert(countEvents() == 15 && eventAt(14).left == 555);- rumble((void *)43, 0, 0, 0);- waitFor(16);- rumble((void *)43, 123, 456, UINT32_MAX);- waitFor(17);- pthread_mutex_lock(&lock);- double remaining = slots[1].until - now();- pthread_mutex_unlock(&lock);- assert(remaining > 64 && remaining <= 65.535);- // Replace a command while RunFrame is blocked; only the new one may escape.- auto frameBlocked = (bool (*)())dlsym(mock, "testFrameBlocked");- delayFrame(150);- rumble((void *)43, 321, 654, 2000);- for (int i = 0; i < 200 && !frameBlocked(); ++i) {- usleep(1000);- }- assert(frameBlocked());- rumble((void *)43, 500, 600, 2000);- waitFor(18);- assert(eventAt(17).left == 500);-- pthread_mutex_lock(&lock);- slots[0].instance = 44;- pthread_mutex_unlock(&lock);- rumble((void *)44, 1000, 2000, 2000);- waitFor(19);- delayFrame(150);- rumble((void *)43, 501, 601, 2000);- for (int i = 0; i < 200 && !frameBlocked(); ++i) {- usleep(1000);- }- assert(frameBlocked());- setHandle(0, 101);- setHandle(1, 100);- waitFor(23);- assert(eventAt(19).handle == 100 && !eventAt(19).left);- assert(eventAt(20).handle == 101 && !eventAt(20).left);- assert(eventAt(21).handle == 101 && eventAt(21).left == 1000);- assert(eventAt(22).handle == 100 && eventAt(22).left == 501);-- shutdownBridge();- assert(countEvents() == 25 && !eventAt(23).left && !eventAt(24).left);- counts = stats();- assert(counts.pipes == counts.releasedPipes && counts.users == counts.releasedUsers);- shutdownBridge(); // Idempotent cleanup; no duplicate stop or thread join.- assert(countEvents() == 25);- puts("steam-input: routing, fallback, amplitudes, expiry, stop, reassignment, late mapping, "- "slow Steam, zero/max duration, session failures and shutdown passed");-}diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 1179ba4..90d61ae 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -16,9 +16,8 @@ each folder is, which process it ends up in, and where new code belongs.| `win32u-patch/`, `winemac-patch/`, `winebus-patch/`, `winecoreaudio-patch/`, `wined3d-patch/`, `ws2_32-patch/`, `ngx-signer-patch/` | Replacement Wine files inside the engine | Rebuilt binaries are committed in the app's Resources and copied over the engine at setup || `nvapi-shim/` | Windows `nvapi64.dll` in the game (reports an NVIDIA driver so games offer DLSS) | Prebuilt in the app's Resources || `overlay-shim/` | Mac dylib in the game process (HDR, Metal 4, frame generation) | `DYLD_INSERT_LIBRARIES` from the run script, or loaded by lsteamclient |-| `controllers/dualsense/`, `controllers/steam-input/` | Bridge and rumble dylibs in the game, plus a `broker` process on loopback UDP | `DYLD_INSERT_LIBRARIES` from the run script || `native-launch/` (`np-native`), `native-shim/` (`libnp_gamepad.dylib`) | Native Mac games | A Steam launch option re-execs the game with the shim inserted |-| `helpers/` | Small CLIs the dylib and run script call (`iconmaker`, `appinfo`, `game-host`) | Application Support |+| `helpers/` | Small CLIs the dylib and run script call (`iconmaker`, `appinfo`) | Application Support || `gamefixes/` | Per-game defaults read by the run script | Bundled in the app payload and the installer || `installer/` | `Install.command` and its config | Zipped by `scripts/package-installer.sh` || `bridge/`, `scripts/`, `fonts/`, `compat/`, `vendor/` | Build tooling, the Proton font build, the compatibility table, vendored code | Build time only |@@ -41,7 +40,7 @@ each folder is, which process it ends up in, and where new code belongs.| Something Steam does or shows | `dylib/` (and `signatures/` when it needs a new Steam function) || How a game is launched, per-game environment | `dylib/feats/compat_run.sh`, `gamefixes/` || A fix inside Wine | The matching `*-patch/` folder: a patch plus a README with the build recipe and sha256 pins, then the rebuilt binary in the app's Resources |-| Something inside the game process on the Mac side | `overlay-shim/`, `controllers/` |+| Something inside the game process on the Mac side | `overlay-shim/` || Native Mac games | `native-launch/`, `native-shim/` |## Namingdiff --git a/docs/RELEASING.md b/docs/RELEASING.mdindex 5064232..b7fded8 100644--- a/docs/RELEASING.md+++ b/docs/RELEASING.md@@ -163,10 +163,8 @@ coming from ad hoc.| Payload file | Identifier | Runs as ||---|---|---|| `notproton.dylib` | `com.bridgeplay.notproton` | inside Steam; the app re-signs Steam's copy with the local identity below |-| `overlay-shim.dylib`, `game-host.dylib` | `com.bridgeplay.overlay-shim`, `com.notproton.game-host` | inserted into the game's Wine loader |-| `controllers/dualsense/bridge.dylib`, `controllers/steam-input/rumble.dylib` | `com.notproton.dualsense.bridge`, `com.notproton.steam-input.rumble` | inserted into the game's Wine loader |-| `controllers/dualsense/launch`, `controllers/dualsense/broker` | `com.notproton.dualsense.launch`, `com.notproton.dualsense.broker` | child processes of the run script |-| `iconmaker`, `appinfo`, `prepare-game-loader` | `com.bridgeplay.iconmaker`, `com.bridgeplay.appinfo`, `com.notproton.game-metadata` | command-line tools the run script calls |+| `overlay-shim.dylib` | `com.bridgeplay.overlay-shim` | inserted into the game's Wine loader |+| `iconmaker`, `appinfo` | `com.bridgeplay.iconmaker`, `com.bridgeplay.appinfo` | command-line tools the run script calls || `bridge/*-unix-lsteamclient.so` | `com.bridgeplay.lsteamclient` | loaded by Wine |None of them is launched by launchd or LaunchServices, so none is its own responsiblediff --git a/docs/dualsense-bluetooth.md b/docs/dualsense-bluetooth.mddeleted file mode 100644index 8acc646..0000000--- a/docs/dualsense-bluetooth.md+++ /dev/null@@ -1,131 +0,0 @@-# DualSense Bluetooth transport--Bridgeplay builds and packages `controllers/dualsense` with its runtime.-The launcher and broker run per game session; the injected facade contains-arm64 and x86_64 slices.--## Source layout--| File | Responsibility |-| --- | --- |-| `launch.swift` | Route selection, private session credentials, child processes, reconnect limits. |-| `bridge.m` | Wine-local HID identity and report translation; authenticated packet sender. |-| `AudioFacade.m` | Wine's four-channel CoreAudio endpoint, format validation and render thread lifecycle. |-| `broker.m` | Session setup, authenticated receive loop, source mixing, control deltas and diagnostics. |-| `PCMTransport.m` | Single physical output writer, bounded audio FIFO and Bluetooth deadlines. |-| `PCM.h`, `Controls.h`, `protocol.h` | Sample conversion, output field layout and local wire format. |-| `Bridge.h`, `BrokerInternal.h` | Small internal boundaries between translation units. |--The session run loop owns source state. One writer owns Bluetooth sequence-numbers and physical output. `outputLock` protects the FIFO and control-snapshots; cross-thread shutdown flags and counters are atomic. AudioUnit-clients serialize each unit's configuration/lifecycle as with the underlying-API; the render thread reads fixed format/callback data and an atomic volume.-Changing those stream properties during playback is rejected. Uninitializing-or disposing an audio unit stops and joins its renderer. Device master/channel-volume, mute and the render callback's silence flag are applied before sample-conversion.--## Selecting a route--| Setup | Behavior |-| --- | --- |-| Direct controller access, one Bluetooth DualSense, no USB DualSense | Start the per-game bridge and expose a USB-style controller and haptic audio endpoint inside Wine. |-| Physical USB | Keep Wine's existing controller and audio path. |-| Steam Input | Keep Steam's virtual controller path; no raw bridge is started. |-| No supported controller, or more than one | Keep the original path. |-| `DSB_DISABLED=1 %command%` | Bypass the bridge for this launch. |--Use the setting **Let games read controllers directly** in the game's-Steam Properties › Bridgeplay for games with their own DualSense support. The bridge forwards-input (including sensor data), supported output reports for triggers and-lights, traditional rumble, and haptic PCM supplied by the game. Trigger-effects and gyro-to-aim mappings depend on the game's implementation.-Steam Input mappings are available on the Steam Input route.--Steamworks' public `ISteamInput` API exposes rumble, LED color and-`SetDualSenseTriggerEffect`, but not arbitrary PCM sample streaming. PCM-therefore uses the direct-controller route.--## Audio and scheduling--The Wine-local facade exposes a non-default four-channel audio endpoint.-Speaker channels 1/2 are ignored; haptic channels 3/4 retain their signed-waveforms. A 257-tap 1.2 kHz low-pass filter resamples them to 3 kHz, signed-8-bit stereo for Bluetooth, preserving the waveform within that format's-bandwidth and precision.--The broker sends a 206-byte `0x33` initialization report and 142-byte `0x32`-continuation reports, with sequence numbers and CRC. One writer serializes-PCM, trigger, LED and rumble updates. It sends only changed control fields,-so a trigger update cannot repeatedly overwrite Steam's previous LED color.-Silent streams do not send PCM; the audio mode is released after the actual-waveform tail. Buffering is bounded to 64 ms and late samples are discarded-instead of being replayed in a catch-up burst.--HID input, incoming UDP and control changes wake the writer through a Mach-semaphore. A `CFFileDescriptor` source wakes the receiving run loop. An audio-workgroup and realtime policy support deadline scheduling. Event-driven-wakeups avoid timer coalescing while a foreground game owns Game Mode.--The measured Bluetooth link cannot sustain PCM at its reduced background-cadence. This implementation suspends PCM below 100 input reports/second and-discards queued audio on suspension. Game Mode eligibility is supplied by the-separate game-host component, but macOS decides whether to activate it. Check-`pcm.inputHz` and `pcm.suspended` in the status file when diagnosing silence.--Direct PCM is the default. `DSB_PCM=0 %command%` selects Core Haptics envelope-conversion. The optional `pcmGain` in `calibration.json` controls the gain-of that conversion.--## Lifecycle and limits--The launcher holds one controller lock until the compatibility command exits.-The broker accepts only authenticated localhost packets from that session,-rejects replayed and stale data, and stops if its parent exits. Session records-are mode 0600 inside a mode 0700 directory. A confirmed physical disconnection-allows at most three reconnect attempts per minute on the same UDP port;-a stalled writer is not automatically restarted. The session loop checks the-write deadline independently, so a blocked IOKit call cannot hang shutdown. Cleanup releases triggers-only when the game touched them.--Runtime files and diagnostics are under-`~/Library/Application Support/bridgeplay/controllers/dualsense/`.-The `sessions/<AppID>-status.json` file contains transport counters. The-`sessions/<AppID>.json` file contains a temporary credential and should not be-included in issue reports. The launcher removes it on normal exit.--Current scope is one standard DualSense (`054c:0ce6`), on Apple Silicon,-tested with CrossOver 26.3 Rosetta. DualSense Edge, multiple controllers,-mid-game USB/Bluetooth switching and other Wine audio backends have not been-validated. Connect using the desired transport before launching the game.-The audio facade implements the CoreAudio AudioUnit output path used by the-tested Wine runtime.--Games that require Windows controller/audio association metadata may need-additional Wine support to select the haptic endpoint.--## Build and verification--`make dualsense` builds the runtime. `make app-payload` includes it in the-installer and integrity checks. `make dualsense-check` uses fake brokers and-dry transports and runs without controller hardware. Checks cover both CPU-architectures' audio routing, speaker isolation, signed/unsigned integer PCM-and float PCM, volume/mute, invalid formats, silent or short callbacks, stream-uninitialization, resampling, CRC and sequence wrap, authentication,-stale/replayed packets, independent rumble/LED updates, per-trigger cleanup,-exact trigger bytes, silence/restart, deferred timer wakeups, route selection,-private credentials, locking and cleanup. Mock HID tests cover report translation,-repeated reconnects and blocked-driver timeouts without opening a controller.--Transport prototypes were verified on macOS 27 with CrossOver 26.3 Rosetta-and a standard DualSense, using recorded PCM playback and live gameplay with-trigger and LED output. The packaged runtime still requires a hardware smoke-test before release.--## References--- [Steam Input API](https://partner.steamgames.com/doc/api/ISteamInput)-- [SDL DualSense backend](https://github.com/libsdl-org/SDL/blob/main/src/joystick/hidapi/SDL_hidapi_ps5.c)-- [Linux PlayStation HID driver](https://github.com/torvalds/linux/blob/master/drivers/hid/hid-playstation.c)-- [dualsensectl](https://github.com/nowrep/dualsensectl/blob/main/main.c)diff --git a/docs/game-mode-host.md b/docs/game-mode-host.mddeleted file mode 100644index 0fd0340..0000000--- a/docs/game-mode-host.md+++ /dev/null@@ -1,29 +0,0 @@-# Game app identity under Wine--Wine may re-execute a GUI process through a temporary hardlink outside the-game's app bundle. The generated app already has the game's name and icon,-but the executable has Wine's embedded bundle identity. Declaring Game Mode-support only in the external Info.plist is therefore insufficient on the-tested macOS system.--The native `prepare-game-loader` helper updates the embedded metadata in a-separate staged copy, preserves entitlements, signs it, and replaces the-staged loader atomically.-`game-host.dylib` redirects Wine's temporary `execv` only when the executable-argument resolves inside `STEAM_COMPAT_INSTALL_PATH`. Other Wine services and-external launchers retain their original identities. This avoids assigning-the game icon to every service in the prefix.--Both helpers are built and included in the normal app payload. Installation-and integrity checks cover them, and removing Bridgeplay removes them with its-support directory.--This declares eligibility and preserves application identity. macOS still-decides when to activate Game Mode. Fullscreen behavior and process layouts-vary between games. The original implementation was validated on an Apple-Silicon Mac with macOS 27 and CrossOver 26.3 Rosetta; other combinations need-hardware verification before claiming universal compatibility.--Run `make game-host-check` for executable scoping, hardlink isolation,-metadata, code signature, malformed-input and idempotency tests. Existing-launcher routing and environment tests must also pass.diff --git a/dylib/feats/compat_run.sh b/dylib/feats/compat_run.shindex 4b1c4ff..3a4728d 100755--- a/dylib/feats/compat_run.sh+++ b/dylib/feats/compat_run.sh@@ -33,28 +33,6 @@ np_support="$HOME/Library/Application Support/bridgeplay"if [ ! -d "$np_support" ] && [ -d "$HOME/Library/Application Support/notproton" ]; thennp_support="$HOME/Library/Application Support/notproton"fi-controller_bridge="$np_support/controllers/dualsense/launch"-if [ "$verb" = waitforexitandrun ] && [ "${DSB_SESSION:-0}" != 1 ] && [ -x "$controller_bridge" ]; then- exec "$controller_bridge" "$0" "$verb" "$@"-fi-if [ -n "$DSB_LIBRARY" ] && [ -f "$DSB_LIBRARY" ]; then- export DYLD_INSERT_LIBRARIES="$DSB_LIBRARY${DYLD_INSERT_LIBRARIES:+:$DYLD_INSERT_LIBRARIES}"-fi-# Games read pads directly unless the launch options set BRIDGEPLAY_RAW_CONTROLLERS=0-# (the controller block below). Settled once here, since the rumble adapter depends on it.-: "${NOTPROTON_RAW_CONTROLLERS:=1}"-# Steam's macOS virtual Xbox device has input but no SDL2 rumble backend.-# The Wine-local adapter forwards only that device's rumble to native Steam, so it is-# only inserted with direct controller access off (controllers/steam-input/README.md).-steam_rumble="$np_support/controllers/steam-input/rumble.dylib"-NOTPROTON_RUMBLE_LIBRARY=""-if [ "$verb" = waitforexitandrun ] && [ "$NOTPROTON_RAW_CONTROLLERS" != 1 ] \- && [ "${NOTPROTON_STEAM_RUMBLE:-1}" != 0 ] && [ -f "$steam_rumble" ]; then- export NOTPROTON_STEAM_RUMBLE=1- NOTPROTON_RUMBLE_LIBRARY="$steam_rumble"- export DYLD_INSERT_LIBRARIES="$steam_rumble${DYLD_INSERT_LIBRARIES:+:$DYLD_INSERT_LIBRARIES}"-fi-export NOTPROTON_RUMBLE_LIBRARYiconmaker="$np_support/iconmaker"find_client_root() {@@ -328,7 +306,8 @@ echo "app_id=$app_id (STEAM_COMPAT_APP_ID=$STEAM_COMPAT_APP_ID)" >> "$log" 2>&1# macOS Steam has no virtual gamepad Wine could read, so a pad Steam Input claims (and# lists in SDL_GAMECONTROLLER_IGNORE_DEVICES) would reach the game as nothing. Games read# pads directly unless the launch options set BRIDGEPLAY_RAW_CONTROLLERS=0.-if [ "$NOTPROTON_RAW_CONTROLLERS" = "1" ]; then+if [ "${NOTPROTON_RAW_CONTROLLERS:-1}" = "1" ]; then+ NOTPROTON_RAW_CONTROLLERS=1SDL_GAMECONTROLLER_IGNORE_DEVICES=export NOTPROTON_RAW_CONTROLLERS SDL_GAMECONTROLLER_IGNORE_DEVICESfi@@ -2646,7 +2625,6 @@ cat > "$loader_contents/Info.plist" <<PLIST<key>CFBundlePackageType</key><string>APPL</string><key>CFBundleInfoDictionaryVersion</key><string>6.0</string><key>LSApplicationCategoryType</key><string>public.app-category.games</string>- <key>LSSupportsGameMode</key><true/><key>NSHighResolutionCapable</key><true/><key>NSPrincipalClass</key><string>NSApplication</string><key>NSMicrophoneUsageDescription</key><string>This game would like to access your microphone.</string>@@ -2668,19 +2646,18 @@ for f in "$wine_unix"/*; doln -sfn "$f" "$loader_macos/$base"doneln "$WINELOADER" "$loader_macos/wine" 2>/dev/null || cp "$WINELOADER" "$loader_macos/wine"-game_host=""original_loader=$WINELOADERif [ -x "$loader_macos/wine" ]; thenWINELOADER="$loader_app/Contents/MacOS/wine"- if "$np_support/prepare-game-loader" "$loader_macos/wine" "$loader_contents/Info.plist" >> "$log" 2>&1; then- game_host="$np_support/game-host.dylib"- else- # A loader whose signature depends on its own wine.app (CrossOver 27's provisioning- # profile) is killed when run from the game's bundle, so run it where it is.+ # A loader with com.apple.developer.* entitlements (CrossOver 27's, backed by a+ # provisioning profile in its own wine.app) is killed when run from the game's bundle,+ # so it runs where it is.+ if codesign -d --entitlements - "$loader_macos/wine" 2>/dev/null | grep -q 'com\.apple\.developer\.'; thenWINELOADER=$original_loader- echo "embedded loader metadata unsupported; running the engine's own loader" >> "$log" 2>&1 || true+ echo "loader needs its own wine.app; running the engine's own loader" >> "$log" 2>&1 || true+ else+ echo "loader staged in bundle for game mode" >> "$log" 2>&1 || truefi- echo "loader staged in bundle for game mode" >> "$log" 2>&1 || trueelseecho "loader staging failed, game mode unavailable" >> "$log" 2>&1 || truefi@@ -2703,16 +2680,6 @@ elif [ -f "\$shim" ] && [ "\${NOTPROTON_FRAMEGEN:-0}" != 0 ] && [ "\$NOTPROTON_Fexport DYLD_INSERT_LIBRARIES="\$shim"export NOTPROTON_OVERLAY_SHIM="\$shim"fi-if [ -n "\$NOTPROTON_RUMBLE_LIBRARY" ] && [ -f "\$NOTPROTON_RUMBLE_LIBRARY" ]; then- export DYLD_INSERT_LIBRARIES="\$NOTPROTON_RUMBLE_LIBRARY\${DYLD_INSERT_LIBRARIES:+:\$DYLD_INSERT_LIBRARIES}"-fi-export NOTPROTON_GAME_LOADER="$WINELOADER"-if [ -n "\$DSB_LIBRARY" ] && [ -f "\$DSB_LIBRARY" ]; then- export DYLD_INSERT_LIBRARIES="\$DSB_LIBRARY\${DYLD_INSERT_LIBRARIES:+:\$DYLD_INSERT_LIBRARIES}"-fi-if [ -n "$game_host" ]; then- export DYLD_INSERT_LIBRARIES="$game_host\${DYLD_INSERT_LIBRARIES:+:\$DYLD_INSERT_LIBRARIES}"-fi[ -n "\$NOTPROTON_GAME_CWD" ] && cd "\$NOTPROTON_GAME_CWD""$WINELOADER" "\$@"exit \$?@@ -2845,15 +2812,6 @@ for name in $np_env_passed; doecho "=== NOTPROTON_ENV_$name sets $name ===" >> "$log" 2>&1 || truedoneset -- \- --env NOTPROTON_RUMBLE_LIBRARY="${NOTPROTON_RUMBLE_LIBRARY:-}" \- --env NOTPROTON_STEAM_RUMBLE="${NOTPROTON_STEAM_RUMBLE:-}" \- --env NOTPROTON_RAW_CONTROLLERS="${NOTPROTON_RAW_CONTROLLERS:-}" \- --env DSB_SESSION="${DSB_SESSION:-}" \- --env DSB_LIBRARY="${DSB_LIBRARY:-}" \- --env DSB_PORT="${DSB_PORT:-}" \- --env DSB_TOKEN="${DSB_TOKEN:-}" \- --env DSB_RAW="${DSB_RAW:-}" \- --env DSB_PCM="${DSB_PCM:-}" \--env CX_ROOT="$CX_ROOT" \--env CX_HOME="$CX_HOME" \--env WINESERVER="$WINESERVER" \diff --git a/helpers/game-host.c b/helpers/game-host.cdeleted file mode 100644index 4012dd0..0000000--- a/helpers/game-host.c+++ /dev/null@@ -1,110 +0,0 @@-// Keep Wine child processes in the game's existing signed app bundle.-// CrossOver normally execs a renamed temporary hardlink outside that bundle;-// LaunchServices then has no bundle identity for the actual game window.-#include <unistd.h>-#include <stdlib.h>-#include <string.h>-#include <stdio.h>-#include <ctype.h>-#include <limits.h>--// Resolve the executable, not arbitrary command-line arguments. Services and-// launchers outside the Steam install directory keep their normal Wine host.-static int is_game_executable(const char *argument) {- const char *root = getenv("STEAM_COMPAT_INSTALL_PATH");- const char *prefix = getenv("WINEPREFIX");- char normalized[PATH_MAX], candidate[PATH_MAX], real_root[PATH_MAX], real_exe[PATH_MAX];- if (!argument || !root || !realpath(root, real_root)) {- return 0;- }- if (strlcpy(normalized, argument, sizeof(normalized)) >= sizeof(normalized)) {- return 0;- }- for (char *p = normalized; *p; p++) {- if (*p == '\\') {- *p = '/';- }- }- const char *exe = normalized;- // Normalize NT object-manager and Win32 extended path prefixes.- if (!strncmp(exe, "/\?\?/", 4) || !strncmp(exe, "//?/", 4)) {- exe += 4;- }- if (isalpha((unsigned char)exe[0]) && exe[1] == ':' && exe[2] == '/') {- if (!prefix ||- snprintf(candidate, sizeof(candidate), "%s/dosdevices/%c:%s", prefix,- tolower((unsigned char)exe[0]), exe + 2) >= (int)sizeof(candidate)) {- return 0;- }- } else {- if (strlcpy(candidate, exe, sizeof(candidate)) >= sizeof(candidate)) {- return 0;- }- }- if (!realpath(candidate, real_exe)) {- return 0;- }- size_t root_length = strlen(real_root), executable_length = strlen(real_exe);- return executable_length > root_length + 4 && !strncmp(real_exe, real_root, root_length) &&- real_exe[root_length] == '/' && !strcasecmp(real_exe + executable_length - 4, ".exe");-}--static const char *game_loader_for(const char *path, char *const argv[]) {- const char *loader = getenv("NOTPROTON_GAME_LOADER");- const char *tmp = getenv("TMPDIR");- const char *noexec = getenv("WINELOADERNOEXEC");- if (!path || !loader || !tmp || !noexec || strcmp(noexec, "1")) {- return NULL;- }- // TMPDIR may end in '/'. Match its next component, not a string prefix- // such as /tmp/game-other, and only Wine's immediate winetemp directory.- size_t temporary_length = strlen(tmp);- while (temporary_length > 1 && tmp[temporary_length - 1] == '/') {- --temporary_length;- }- if (!temporary_length || strncmp(path, tmp, temporary_length) ||- (temporary_length > 1 && path[temporary_length] != '/')) {- return NULL;- }- // CrossOver appends /winetemp to a directory that may already end in '/'.- const char *next_component = path + temporary_length;- while (*next_component == '/') {- ++next_component;- }- if (strncmp(next_component, "winetemp-", 9)) {- return NULL;- }- const char *loader_suffix = ".app/Contents/MacOS/wine";- size_t loader_length = strlen(loader), suffix_length = strlen(loader_suffix);- // Launchers live in the bridgeplay support folder, or in the notproton one on a home- // the app has not moved over yet.- if ((!strstr(loader, "/Application Support/bridgeplay/launchers/") &&- !strstr(loader, "/Application Support/notproton/launchers/")) ||- loader_length < suffix_length ||- strcmp(loader + loader_length - suffix_length, loader_suffix)) {- return NULL;- }- if (access(loader, X_OK)) {- return NULL;- }- if (!argv || !argv[0] || !is_game_executable(argv[1])) {- return NULL;- }- return loader;-}--static int game_execv(const char *path, char *const argv[]) {- const char *loader = game_loader_for(path, argv);- if (loader) {- fprintf(stderr, "Bridgeplay Game Host: game executable stays inside game app (%s)\n",- strrchr(path, '/') + 1);- return execv(loader, argv);- }- return execv(path, argv);-}-#ifndef GAME_HOST_TEST-__attribute__((used)) static const struct {- const void *new_fn, *old_fn;-} interpose_execv __attribute__((section("__DATA,__interpose"))) = {(const void *)game_execv,- (const void *)execv};-#endifdiff --git a/helpers/prepare-game-loader.swift b/helpers/prepare-game-loader.swiftdeleted file mode 100644index b1ffb41..0000000--- a/helpers/prepare-game-loader.swift+++ /dev/null@@ -1,196 +0,0 @@-// Give the staged Wine loader its game app identity by atomically replacing-// a private copy, preserving the shared runner inode.-import Darwin-import Foundation--enum PrepareError: Error { case invalid(String) }--// Sizes and offsets below are from mach_header_64, segment_command_64 and section_64.-private enum MachOLayout {- static let magic64: UInt64 = 0xfeed_facf- static let segment64: UInt64 = 0x19- static let headerSize = 32- static let segmentSize = 72- static let sectionSize = 80-}--func readLittleEndianInteger(_ data: Data, _ offset: Int, _ size: Int) throws -> UInt64 {- guard offset >= 0, (1...8).contains(size), offset <= data.count - size else {- throw PrepareError.invalid("Truncated Mach-O")- }- return (0..<size).reduce(0) { $0 | UInt64(data[offset + $1]) << ($1 * 8) }-}--func embeddedPlistSection(_ data: Data) throws -> Range<Int>? {- guard try readLittleEndianInteger(data, 0, 4) == MachOLayout.magic64 else {- throw PrepareError.invalid("Expected a thin 64-bit Wine loader")- }- let count = Int(try readLittleEndianInteger(data, 16, 4))- let commandBytes = Int(try readLittleEndianInteger(data, 20, 4))- guard data.count >= MachOLayout.headerSize,- commandBytes <= data.count - MachOLayout.headerSize,- count <= commandBytes / 8- else {- throw PrepareError.invalid("Invalid Mach-O load command table")- }- let commandsEnd = MachOLayout.headerSize + commandBytes- var position = MachOLayout.headerSize- var plist: Range<Int>?- for _ in 0..<count {- guard position <= commandsEnd - 8 else {- throw PrepareError.invalid("Truncated Mach-O load command")- }- let command = try readLittleEndianInteger(data, position, 4)- let size = Int(try readLittleEndianInteger(data, position + 4, 4))- guard size >= 8, size % 8 == 0, size <= commandsEnd - position else {- throw PrepareError.invalid("Invalid Mach-O load command size")- }- if command == MachOLayout.segment64 {- guard size >= MachOLayout.segmentSize else {- throw PrepareError.invalid("Truncated Mach-O segment")- }- let sections = Int(try readLittleEndianInteger(data, position + 64, 4))- guard sections <= (size - MachOLayout.segmentSize) / MachOLayout.sectionSize else {- throw PrepareError.invalid("Invalid section table")- }- for index in 0..<sections {- let entry = position + MachOLayout.segmentSize + index * MachOLayout.sectionSize- let name = String(- decoding: data[entry..<entry + 16].prefix { $0 != 0 }, as: UTF8.self)- let segment = String(- decoding: data[entry + 16..<entry + 32].prefix { $0 != 0 }, as: UTF8.self)- if name == "__info_plist" && segment == "__TEXT" {- let length = try readLittleEndianInteger(data, entry + 40, 8)- let start = Int(try readLittleEndianInteger(data, entry + 48, 4))- guard plist == nil, start >= commandsEnd, start <= data.count,- length <= UInt64(data.count - start)- else {- throw PrepareError.invalid("Invalid embedded plist section")- }- plist = start..<start + Int(length)- }- }- }- position += size- }- guard position == commandsEnd else {- throw PrepareError.invalid("Mach-O command count does not match its table")- }- return plist-}--func runCodesign(_ arguments: [String], stderr: Bool = false) throws -> Data {- let process = Process()- let output = Pipe()- process.executableURL = URL(fileURLWithPath: "/usr/bin/codesign")- process.arguments = arguments- if stderr { process.standardError = output } else { process.standardOutput = output }- try process.run()- let data = output.fileHandleForReading.readDataToEndOfFile()- process.waitUntilExit()- guard process.terminationStatus == 0 else { throw PrepareError.invalid("codesign failed") }- return data-}--func prepare(_ target: URL, _ info: URL) throws {- let original = try Data(contentsOf: target)- guard let section = try embeddedPlistSection(original) else {- print("Game Mode: no embedded plist; keeping app metadata")- return- }- var bytes = original.subdata(in: section)- while bytes.last == 0 || bytes.last == 32 { bytes.removeLast() }- guard- let old = try PropertyListSerialization.propertyList(from: bytes, format: nil)- as? [String: Any],- let app = try PropertyListSerialization.propertyList(- from: Data(contentsOf: info), format: nil) as? [String: Any],- let identity = app["CFBundleIdentifier"] as? String,- identity.hasPrefix("com.notproton.launcher."),- let name = app["CFBundleName"] as? String,- target.lastPathComponent == "wine"- else {- throw PrepareError.invalid("Not a staged Bridgeplay game loader")- }- var updated = old.filter {- [- "CFBundleAllowMixedLocalizations", "CFBundleDevelopmentRegion",- "CFBundleInfoDictionaryVersion", "CFBundleShortVersionString", "CFBundleVersion",- // Keeps Wine's helper processes (services, explorer, steam.exe) out of the Dock;- // a process that opens a window still becomes a regular app.- "LSUIElement",- ].contains($0.key)- }- updated.merge([- "CFBundleIdentifier": identity, "CFBundleName": name,- "CFBundleExecutable": "wine", "CFBundlePackageType": "APPL",- "NSPrincipalClass": "WineApplication",- "NSHighResolutionCapable": true, "LSApplicationCategoryType": "public.app-category.games",- "LSSupportsGameMode": true,- ]) { _, new in new }- let xml = try PropertyListSerialization.data(- fromPropertyList: updated, format: .xml, options: 0)- let compact = Data(- String(decoding: xml, as: UTF8.self).split(separator: "\n")- .map { $0.trimmingCharacters(in: .whitespaces) }.joined().utf8)- guard compact.count <= section.count else {- throw PrepareError.invalid("Game metadata exceeds reserved section")- }- var replacement = original- replacement.replaceSubrange(- section, with: compact + Data(repeating: 32, count: section.count - compact.count))- if replacement == original { return }- let files = FileManager.default- let temporary = target.deletingLastPathComponent().appendingPathComponent(- ".game-loader-" + UUID().uuidString)- try files.createDirectory(at: temporary, withIntermediateDirectories: false)- defer { try? files.removeItem(at: temporary) }- let staged = temporary.appendingPathComponent("wine")- try replacement.write(to: staged)- let attributes = try files.attributesOfItem(atPath: target.path)- try files.setAttributes(- [.posixPermissions: attributes[.posixPermissions] ?? 0o755], ofItemAtPath: staged.path)- // CrossOver's loader is signed with the hardened runtime and entitlements; WineCX's is not- // signed at all and WineHQ's is signed ad hoc without the hardened runtime. Adding the- // hardened runtime to those would turn on library validation, which refuses their- // ntdll.so ("different Team IDs") and the DYLD_INSERT_LIBRARIES the launcher relies on,- // so only a loader that already had it keeps it.- let details = (try? runCodesign(["-dv", target.path], stderr: true)).map {- String(decoding: $0, as: UTF8.self)- }- let signed = details != nil- let hardened = details?.split(separator: "\n").contains {- $0.hasPrefix("CodeDirectory") && $0.contains("runtime")- } ?? false- let entitlements = signed ? try runCodesign(["-d", "--entitlements", ":-", target.path]) : Data()- var arguments = ["--force", "--sign", "-", "--identifier", identity]- if hardened { arguments += ["--options", "runtime"] }- if !entitlements.isEmpty {- let parsed = try PropertyListSerialization.propertyList(from: entitlements, format: nil)- // An ad hoc signature can't carry com.apple.developer.* entitlements (CrossOver 27's- // cross-architecture-support): macOS kills the re-signed loader at launch, so the run- // script keeps the original signed one instead.- if let restricted = (parsed as? [String: Any])?.keys.first(where: { $0.hasPrefix("com.apple.developer.") }) {- throw PrepareError.invalid("\(restricted) only works under the original signature")- }- let file = temporary.appendingPathComponent("entitlements.plist")- try entitlements.write(to: file)- arguments += ["--entitlements", file.path]- }- _ = try runCodesign(arguments + [staged.path])- _ = try runCodesign(["--verify", "--strict", staged.path])- guard rename(staged.path, target.path) == 0 else {- throw PrepareError.invalid("Atomic replacement failed: \(errno)")- }- print("Game Mode: staged Wine metadata updated for \(identity)")-}--do {- guard CommandLine.arguments.count == 3 else { exit(64) }- try prepare(- URL(fileURLWithPath: CommandLine.arguments[1]),- URL(fileURLWithPath: CommandLine.arguments[2]))-} catch {- fputs("Game Mode: \(error)\n", stderr)- exit(1)-}diff --git a/helpers/tests/game-host.py b/helpers/tests/game-host.pydeleted file mode 100644index 21079fc..0000000--- a/helpers/tests/game-host.py+++ /dev/null@@ -1,150 +0,0 @@-"""Game child identity must not spread to Wine/Ubisoft helper processes."""--from pathlib import Path-import os, subprocess, tempfile--root = Path(__file__).resolve().parent.parent-with tempfile.TemporaryDirectory(prefix="dsb-host-") as tmp:- t = Path(tmp)- game = t / "Games" / "Example Game"- game.mkdir(parents=True)- sibling = t / "Games" / "Example Game Tools"- sibling.mkdir()- prefix = t / "prefix"- (prefix / "dosdevices").mkdir(parents=True)- (prefix / "drive_c/windows/system32").mkdir(parents=True)- (prefix / "drive_c/Program Files/Ubisoft").mkdir(parents=True)- (prefix / "dosdevices/s:").symlink_to(t / "Games", target_is_directory=True)- (prefix / "dosdevices/c:").symlink_to("../drive_c", target_is_directory=True)- (prefix / "dosdevices/z:").symlink_to("/", target_is_directory=True)- loader = t / "Application Support/bridgeplay/launchers/999/Game.app/Contents/MacOS/wine"- loader.parent.mkdir(parents=True)- loader.write_text("")- loader.chmod(0o755)- exe = game / "Binaries/Win64/game.exe"- exe.parent.mkdir(parents=True)- exe.touch()- service = prefix / "drive_c/windows/system32/winedevice.exe"- service.touch()- launcher = prefix / "drive_c/Program Files/Ubisoft/upc.exe"- launcher.touch()- other = sibling / "tool.exe"- other.touch()- (game / "escape.exe").symlink_to(service)- (t / "Steam").symlink_to(game, target_is_directory=True)- probe = t / "probe.c"- probe.write_text(- '#define GAME_HOST_TEST\n#include "'- + str(root / "game-host.c")- + '"\nint main(int argc,char **argv){char *child[]={argv[1],argc>2?argv[2]:NULL,argc>3?argv[3]:NULL,NULL};puts(game_loader_for(argv[1],child)?"game":"original");}\n'- )- subprocess.run(- [- "clang",- "-O2",- "-Wall",- "-Wextra",- "-Wno-unused-function",- str(probe),- "-o",- str(t / "probe"),- ],- check=True,- )- env = dict(- os.environ,- NOTPROTON_GAME_LOADER=str(loader),- WINEPREFIX=str(prefix),- WINELOADERNOEXEC="1",- STEAM_COMPAT_INSTALL_PATH=str(t / "Steam"),- )- temp_loader = os.environ["TMPDIR"].rstrip("/") + "/winetemp-123/game.exe"- cases = [- ("S:\\Example Game\\Binaries\\Win64\\game.exe", True),- ("\\??\\s:\\Example Game\\Binaries\\Win64\\game.exe", True),- ("\\\\?\\S:\\Example Game\\Binaries\\Win64\\game.exe", True),- (str(exe), True),- ("Binaries/Win64/game.exe", True),- ("C:\\windows\\system32\\winedevice.exe", False),- ("C:\\Program Files\\Ubisoft\\upc.exe", False),- (str(other), False),- (str(game / "escape.exe"), False),- ("S:\\Example Game\\missing.exe", False),- ("game.exe", False),- ("", False),- ]- for argument, expected in cases:- got = subprocess.check_output(- [str(t / "probe"), temp_loader, argument], env=env, cwd=game, text=True- ).strip()- assert got == ("game" if expected else "original"), (argument, got)- for args in (- [str(t / "probe"), "/tmp/unrelated-wine", str(exe)],- [str(t / "probe"), temp_loader, str(launcher), str(exe)],- [str(t / "probe"), temp_loader],- ):- assert subprocess.check_output(args, env=env, text=True).strip() == "original"- # A similarly named temporary directory or executable is not a Wine re-exec.- temp_root = os.environ["TMPDIR"].rstrip("/")- for candidate in (- temp_root + "-other/winetemp-123/game.exe",- temp_root + "/unrelated/winetemp-123/game.exe",- temp_root + "//unrelated/winetemp-123/game.exe",- ):- assert (- subprocess.check_output(- [str(t / "probe"), candidate, str(exe)], env=env, text=True- ).strip()- == "original"- )- # CrossOver appends /winetemp to confstr's already slash-terminated directory.- for separators in ("/", "//", "///"):- candidate = temp_root + separators + "winetemp-123/game.exe"- for temporary_root in (temp_root, temp_root + "/"):- assert (- subprocess.check_output(- [str(t / "probe"), candidate, str(exe)],- env=dict(env, TMPDIR=temporary_root),- text=True,- ).strip()- == "game"- ), (candidate, temporary_root)- other_loader = loader.with_name("wine-other")- other_loader.touch()- other_loader.chmod(0o755)- assert (- subprocess.check_output(- [str(t / "probe"), temp_loader, str(exe)],- env=dict(env, NOTPROTON_GAME_LOADER=str(other_loader)),- text=True,- ).strip()- == "original"- )- # A home the app has not moved over yet keeps its launchers under notproton.- legacy_loader = t / "Application Support/notproton/launchers/999/Game.app/Contents/MacOS/wine"- legacy_loader.parent.mkdir(parents=True)- legacy_loader.write_text("")- legacy_loader.chmod(0o755)- assert (- subprocess.check_output(- [str(t / "probe"), temp_loader, str(exe)],- env=dict(env, NOTPROTON_GAME_LOADER=str(legacy_loader)),- text=True,- ).strip()- == "game"- )- elsewhere = t / "Application Support/other/launchers/999/Game.app/Contents/MacOS/wine"- elsewhere.parent.mkdir(parents=True)- elsewhere.write_text("")- elsewhere.chmod(0o755)- assert (- subprocess.check_output(- [str(t / "probe"), temp_loader, str(exe)],- env=dict(env, NOTPROTON_GAME_LOADER=str(elsewhere)),- text=True,- ).strip()- == "original"- )- print(- "PASS: only actual game executables retain game identity; services, launcher, escapes and argument-only matches excluded"- )diff --git a/helpers/tests/game-metadata.py b/helpers/tests/game-metadata.pydeleted file mode 100644index 2d6609e..0000000--- a/helpers/tests/game-metadata.py+++ /dev/null@@ -1,113 +0,0 @@-"""Validate identity, signing and hardlink isolation on a synthetic Wine loader."""--import os, pathlib, plistlib, struct, subprocess, sys, tempfile--tool = pathlib.Path(sys.argv[1]).resolve()-with tempfile.TemporaryDirectory(prefix="np-game-metadata-") as folder:- root = pathlib.Path(folder)- old = {- "CFBundleIdentifier": "com.codeweavers.CrossOver.wineloader",- "CFBundleName": "Wine",- "CFBundleVersion": "1",- }- embedded = root / "embedded.plist"- embedded.write_bytes(plistlib.dumps(old).ljust(4096, b" "))- c = root / "fixture.c"- c.write_text("int main(void) { return 0; }\n")- runner = root / "runner"- subprocess.run(- [- "clang",- str(c),- "-Wl,-sectcreate,__TEXT,__info_plist," + str(embedded),- "-o",- str(runner),- ],- check=True,- )- subprocess.run(["codesign", "-s", "-", str(runner)], check=True)- wine = root / "wine"- os.link(runner, wine)- before = runner.read_bytes()- info = root / "Info.plist"- info.write_bytes(- plistlib.dumps(- {"CFBundleIdentifier": "com.notproton.launcher.999", "CFBundleName": "Example Game"}- )- )- subprocess.run([str(tool), str(wine), str(info)], check=True)- assert runner.read_bytes() == before, "shared runner inode was modified"- assert runner.stat().st_ino != wine.stat().st_ino- subprocess.run(["codesign", "--verify", "--strict", str(wine)], check=True)-- def flags(path):- out = subprocess.run(["codesign", "-dv", str(path)], capture_output=True, text=True).stderr- return next(l for l in out.splitlines() if l.startswith("CodeDirectory"))-- # WineHQ's loader is ad hoc without the hardened runtime; adding it breaks ntdll.so loading- assert "runtime" not in flags(wine), "a loader without the hardened runtime gained it"- (root / "hardened").mkdir()- hardened = root / "hardened" / "wine"- subprocess.run(["clang", str(c), "-Wl,-sectcreate,__TEXT,__info_plist," + str(embedded),- "-o", str(hardened)], check=True)- subprocess.run(["codesign", "-s", "-", "--options", "runtime", str(hardened)], check=True)- subprocess.run([str(tool), str(hardened), str(info)], check=True)- assert "runtime" in flags(hardened), "a hardened loader lost the hardened runtime"- # An ad hoc re-sign can't keep a com.apple.developer.* entitlement (macOS kills it at launch)- (root / "restricted").mkdir()- restricted = root / "restricted" / "wine"- subprocess.run(["clang", str(c), "-Wl,-sectcreate,__TEXT,__info_plist," + str(embedded),- "-o", str(restricted)], check=True)- ents = root / "restricted.plist"- ents.write_bytes(plistlib.dumps({"com.apple.developer.cross-architecture-support": True,- "com.apple.security.cs.disable-library-validation": True}))- subprocess.run(["codesign", "-s", "-", "--options", "runtime", "--entitlements", str(ents),- str(restricted)], check=True)- untouched = restricted.read_bytes()- result = subprocess.run([str(tool), str(restricted), str(info)], capture_output=True)- assert result.returncode != 0, "a loader with a restricted entitlement was re-signed"- assert restricted.read_bytes() == untouched, "a refused loader was modified"- blob = wine.read_bytes()- assert b"com.notproton.launcher.999" in blob and b"LSSupportsGameMode" in blob- subprocess.run([str(tool), str(wine), str(info)], check=True)- assert wine.read_bytes() == blob, "second preparation is not idempotent"- info.write_bytes(plistlib.dumps({"CFBundleIdentifier": "unrelated.app", "CFBundleName": "Bad"}))- assert subprocess.run([str(tool), str(wine), str(info)], capture_output=True).returncode != 0- assert wine.read_bytes() == blob- info.write_bytes(- plistlib.dumps(- {"CFBundleIdentifier": "com.notproton.launcher.999", "CFBundleName": "Example Game"}- )- )- command_offset = 32- plist_section = None- for _ in range(struct.unpack_from("<I", before, 16)[0]):- command, size = struct.unpack_from("<II", before, command_offset)- if command == 0x19:- for index in range(struct.unpack_from("<I", before, command_offset + 64)[0]):- section = command_offset + 72 + index * 80- if before[section : section + 16].rstrip(b"\0") == b"__info_plist":- plist_section = section- command_offset += size- assert plist_section is not None-- def reject(label, data):- wine.write_bytes(data)- result = subprocess.run([str(tool), str(wine), str(info)], capture_output=True)- assert result.returncode != 0, label- assert wine.read_bytes() == data, "failed parse must not modify " + label-- reject("non Mach-O", b"not a Mach-O")- for label, offset, value in (- ("commands beyond file", 20, len(before) + 4096),- ("command count mismatch", 16, struct.unpack_from("<I", before, 16)[0] + 1),- ("short segment", 36, 8),- ("section overlaps header", plist_section + 48, 8),- ("section outside file", plist_section + 48, len(before) + 1),- ):- malformed = bytearray(before)- struct.pack_into("<I", malformed, offset, value)- reject(label, malformed)- print(- "PASS metadata: scoped identity, valid signature, unchanged runner, idempotency, invalid input rejection"- )