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
feat(dualsense): add Bluetooth PCM transport for direct controllers
sn0wst0rm85f5314075d4
diff --git a/.github/workflows/app.yml b/.github/workflows/app.ymlindex 18c8110..1a5f791 100644--- a/.github/workflows/app.yml+++ b/.github/workflows/app.yml@@ -132,6 +132,11 @@ jobs:- name: Run the Swift testsrun: make -s app-tests+ - name: Check game identity and controller transports without hardware+ run: |+ make game-host-check+ make dualsense-check+- name: Package the app bundlerun: |mkdir -p out/artifactdiff --git a/Makefile b/Makefileindex 0c7d797..12ed296 100644--- a/Makefile+++ b/Makefile@@ -489,7 +489,50 @@ game-host-check: $(GAME_HOST) $(GAME_METADATA)python3 helpers/tests/game-host.pypython3 helpers/tests/game-metadata.py $(GAME_METADATA)-helpers-install: $(ICONMAKER) $(APPINFO) $(GAME_HOST) $(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++helpers-install: $(ICONMAKER) $(APPINFO) $(GAME_HOST) $(GAME_METADATA) $(DUALSENSE_RUNTIME)+ $(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)$(call install_atomically,$(ICONMAKER),$(SUPPORT_DIR)/iconmaker)@@ -565,8 +608,10 @@ bridge:fonts:fonts/build.sh-app-payload: $(TARGET) $(OVERLAY_SHIM) $(ICONMAKER) $(APPINFO) $(GAME_HOST) $(GAME_METADATA)+app-payload: $(TARGET) $(OVERLAY_SHIM) $(ICONMAKER) $(APPINFO) $(GAME_HOST) $(GAME_METADATA) $(DUALSENSE_RUNTIME)@mkdir -p "$(APP_PAYLOAD)/signatures/macos.arm64"+ @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"diff --git a/app/Sources/NotProtonApp/Model/InstallPayload.swift b/app/Sources/NotProtonApp/Model/InstallPayload.swiftindex 3237749..715a614 100644--- a/app/Sources/NotProtonApp/Model/InstallPayload.swift+++ b/app/Sources/NotProtonApp/Model/InstallPayload.swift@@ -5,7 +5,10 @@ import Foundationenum InstallPayload {static let step = String(localized: "Find NotProton's components")- static let runtimeFiles = ["prepare-game-loader", "game-host.dylib"]+ static let runtimeFiles = [+ "prepare-game-loader", "game-host.dylib",+ "controllers/dualsense/launch", "controllers/dualsense/broker", "controllers/dualsense/bridge.dylib",+ ]struct Located: Sendable {var runtime: [String: URL] = [:]diff --git a/app/Tests/NotProtonAppTests/SteamInstallerTests.swift b/app/Tests/NotProtonAppTests/SteamInstallerTests.swiftindex acaaf91..162af1c 100644--- a/app/Tests/NotProtonAppTests/SteamInstallerTests.swift+++ b/app/Tests/NotProtonAppTests/SteamInstallerTests.swift@@ -159,6 +159,13 @@ 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.mnew file mode 100644index 0000000..b4a34cc--- /dev/null+++ b/controllers/dualsense/AudioFacade.m@@ -0,0 +1,544 @@+// 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.hnew file mode 100644index 0000000..0cea7ab--- /dev/null+++ b/controllers/dualsense/Bridge.h@@ -0,0 +1,15 @@+#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.hnew file mode 100644index 0000000..49eada7--- /dev/null+++ b/controllers/dualsense/BrokerInternal.h@@ -0,0 +1,38 @@+#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.hnew file mode 100644index 0000000..01ea400--- /dev/null+++ b/controllers/dualsense/Calibration.h@@ -0,0 +1,16 @@+#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.hnew file mode 100644index 0000000..4d0c9b9--- /dev/null+++ b/controllers/dualsense/Controls.h@@ -0,0 +1,46 @@+#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.hnew file mode 100644index 0000000..bda153e--- /dev/null+++ b/controllers/dualsense/PCM.h@@ -0,0 +1,88 @@+#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.mnew file mode 100644index 0000000..a61421f--- /dev/null+++ b/controllers/dualsense/PCMTransport.m@@ -0,0 +1,461 @@+#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.cnew file mode 100644index 0000000..d32c1ac--- /dev/null+++ b/controllers/dualsense/audio-test.c@@ -0,0 +1,149 @@+#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);+ 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.mnew file mode 100644index 0000000..dae955d--- /dev/null+++ b/controllers/dualsense/bridge.m@@ -0,0 +1,248 @@+// 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.mnew file mode 100644index 0000000..b177cc9--- /dev/null+++ b/controllers/dualsense/broker.m@@ -0,0 +1,871 @@+#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());+ NSString *calibrationPath = [NSHomeDirectory()+ stringByAppendingPathComponent:+ @"Library/Application Support/notproton/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.hnew file mode 100644index 0000000..840996e--- /dev/null+++ b/controllers/dualsense/descriptor.h@@ -0,0 +1,20 @@+/* 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.mnew file mode 100644index 0000000..cdbf3f0--- /dev/null+++ b/controllers/dualsense/hid-test.m@@ -0,0 +1,108 @@+#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.swiftnew file mode 100644index 0000000..15caa77--- /dev/null+++ b/controllers/dualsense/launch.swift@@ -0,0 +1,267 @@+// 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.mnew file mode 100644index 0000000..b482123--- /dev/null+++ b/controllers/dualsense/output-test.m@@ -0,0 +1,66 @@+#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.hnew file mode 100644index 0000000..d7b5445--- /dev/null+++ b/controllers/dualsense/protocol.h@@ -0,0 +1,44 @@+#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.pynew file mode 100644index 0000000..854c03b--- /dev/null+++ b/controllers/dualsense/test-bridge.py@@ -0,0 +1,128 @@+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))+s.settimeout(1)+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.cnew file mode 100644index 0000000..d47308c--- /dev/null+++ b/controllers/dualsense/test-controls.c@@ -0,0 +1,51 @@+#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.pynew file mode 100644index 0000000..1e91d7c--- /dev/null+++ b/controllers/dualsense/test-launch.py@@ -0,0 +1,142 @@+"""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="notproton 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.pynew file mode 100644index 0000000..7189004--- /dev/null+++ b/controllers/dualsense/test-lifecycle.py@@ -0,0 +1,63 @@+"""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.cnew file mode 100644index 0000000..f42abb8--- /dev/null+++ b/controllers/dualsense/test-pcm-unit.c@@ -0,0 +1,58 @@+#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.pynew file mode 100644index 0000000..a4f1eba--- /dev/null+++ b/controllers/dualsense/test-pcm.py@@ -0,0 +1,166 @@+"""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 NotProton.+ 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+ 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+ 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+ assert (+ state["pcm"]["reports"] == 0 if hardware else state["pcm"]["reports"] > seconds * 40+ ), state+ assert state["pcm"]["discardedFrames"] == 0, 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.pynew file mode 100644index 0000000..202dc25--- /dev/null+++ b/controllers/dualsense/test-trigger-routing.py@@ -0,0 +1,86 @@+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),+ "--seconds",+ "5",+ ]+ + (["--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++ def send(effect):+ global seq+ seq += 1+ 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,+ )++ end = time.monotonic() + 1.2+ while time.monotonic() < end:+ send(curve)+ send(off)+ time.sleep(0.01)+ d = json.loads(status.read_text())+ t = d["triggers"]+ if grace:+ assert bytes(t["r2"]) == curve and t["suppressedR2Resets"] > 50, t+ assert len(t["sentHistory"]) == 1 and bytes(t["sentHistory"][0]["r2"]) == curve, t+ else:+ assert t["suppressedR2Resets"] == 0, t+ stopped = time.time()+ time.sleep(1.1)+ t = json.loads(status.read_text())["triggers"]+ assert bytes(t["r2"]) == off, t+ if grace:+ assert (+ len(t["sentHistory"]) == 2 and 0 <= t["sentHistory"][-1]["at"] - stopped < 0.12+ ), 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/docs/dualsense-bluetooth.md b/docs/dualsense-bluetooth.mdnew file mode 100644index 0000000..8a8eb32--- /dev/null+++ b/docs/dualsense-bluetooth.md@@ -0,0 +1,131 @@+# DualSense Bluetooth transport++NotProton 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 Steam's per-game Compatibility setting **Let games read controllers+directly** 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/notproton/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/dylib/feats/compat_run.sh b/dylib/feats/compat_run.shindex 8759b1c..fa85924 100755--- a/dylib/feats/compat_run.sh+++ b/dylib/feats/compat_run.sh@@ -18,6 +18,13 @@ case "$verb" inesacnp_support="$HOME/Library/Application Support/notproton"+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# cxcompatdb resolves its database through CX_HOME and logs an error for# every module loaded without it :(export CX_HOME="$HOME/Library/Application Support/CrossOver"@@ -2039,6 +2046,9 @@ elif [ -f "\$shim" ] && [ "\${NOTPROTON_FRAMEGEN:-0}" != 0 ] && [ "\$NOTPROTON_Fexport NOTPROTON_OVERLAY_SHIM="\$shim"fiexport NOTPROTON_GAME_LOADER="$WINELOADER"+if [ -n "\$DSB_LIBRARY" ] && [ -f "\$DSB_LIBRARY" ]; then+ export DYLD_INSERT_LIBRARIES="\$DSB_LIBRARY\${DYLD_INSERT_LIBRARIES:+:\$DYLD_INSERT_LIBRARIES}"+fiif [ -n "$game_host" ]; thenexport DYLD_INSERT_LIBRARIES="$game_host\${DYLD_INSERT_LIBRARIES:+:\$DYLD_INSERT_LIBRARIES}"fi@@ -2183,6 +2193,12 @@ for name in $(env | sed -nE 's/^(CX_APPLEGPTK_LIBD3DSHARED_PATH|SDL_GAMECONTROLLset -- --env "$name=$value" "$@"doneset -- \+ --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" \