Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion src/platform/windows/ds5/ds5_sidecar_client.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ namespace platf::ds5 {
adaptive_triggers = 102,
led = 103,
haptics_pcm = 104,
audio_policy_violation = 105,
error = 255,
};

Expand Down Expand Up @@ -274,6 +275,7 @@ namespace platf::ds5 {
std::atomic_int global_index { -1 };
std::uint8_t client_index = 0;
bool audio_haptics_requested = false;
bool force_hid_fallback = false;
feedback_queue_t feedback_queue;
std::uint32_t next_request_id = 1;

Expand Down Expand Up @@ -361,6 +363,18 @@ namespace platf::ds5 {
}
}
break;
case message_e::audio_policy_violation:
if (p.size() == 4 && p[0] == owned_index) {
static constexpr std::array<std::string_view, 3> role_names {
"console", "multimedia", "communications"
};
const auto role = p[2] < role_names.size() ? role_names[p[2]] : "unknown"sv;
force_hid_fallback = true;
audio_haptics_requested = false;
BOOST_LOG(warning) << "The virtual DualSense audio endpoint became the Windows "sv
<< role << " default; falling back to HID-only DualSense"sv;
}
break;
case message_e::error:
BOOST_LOG(warning) << "DualSense sidecar reported an asynchronous error"sv;
break;
Expand Down Expand Up @@ -514,7 +528,7 @@ namespace platf::ds5 {
}

client_index = id.clientRelativeIndex;
audio_haptics_requested = audio_haptics;
audio_haptics_requested = audio_haptics && !force_hid_fallback;
online = true;
BOOST_LOG(info) << "DualSense sidecar attached controller "sv << id.globalIndex
<< (reply.payload[1] ? " with native four-channel haptics" : " (HID only)");
Expand All @@ -529,6 +543,9 @@ namespace platf::ds5 {
if (reader.joinable()) {
reader.join();
}
// A new allocation is an explicit user/session request. Only the
// automatic recovery of the current allocation inherits the fallback.
force_hid_fallback = false;
if (!connect_and_attach(id, audio_haptics)) {
return false;
}
Expand Down
27 changes: 27 additions & 0 deletions tests/tools/ds5_fake_sidecar.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,14 @@ int main(int argc, char **argv) {
// The test process opts this peer into emitting async feedback ahead of the
// attach reply, exercising the Core client's transaction multiplexing.
const auto interleave = GetEnvironmentVariableW(L"SUNSHINE_DS5_TEST_INTERLEAVE", nullptr, 0) > 0;
const auto audio_policy_fallback =
GetEnvironmentVariableW(L"SUNSHINE_DS5_TEST_AUDIO_POLICY_FALLBACK", nullptr, 0) > 0;
const auto policy_once_name = L"Local\\sunshine-ds5-test-policy-once-" + event_suffix;
const auto policy_once_event = OpenEventW(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE,
policy_once_name.c_str());
const auto hid_fallback_name = L"Local\\sunshine-ds5-test-hid-fallback-" + event_suffix;
const auto hid_fallback_event = OpenEventW(EVENT_MODIFY_STATE, FALSE,
hid_fallback_name.c_str());
const auto crash_once_name = L"Local\\sunshine-ds5-test-crash-once-" + event_suffix;
const auto crash_once_event = OpenEventW(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE,
crash_once_name.c_str());
Expand Down Expand Up @@ -133,7 +141,24 @@ int main(int argc, char **argv) {
}
std::vector<std::uint8_t> response(8);
response[0] = payload[0];
if (audio_policy_fallback && payload[2] == 1) {
response[1] = 1;
}
if (!reply(pipe, 4, request_id, response)) break;
if (audio_policy_fallback && policy_once_event &&
WaitForSingleObject(policy_once_event, 0) == WAIT_TIMEOUT) {
// The first process accepts the composite attach, then reports the
// same asynchronous violation as the real endpoint guard and exits.
FlushFileBuffers(pipe);
SetEvent(policy_once_event);
if (!reply(pipe, 105, 0, { payload[0], payload[1], 0, 0 })) break;
FlushFileBuffers(pipe);
break;
}
if (audio_policy_fallback && policy_once_event && hid_fallback_event &&
WaitForSingleObject(policy_once_event, 0) == WAIT_OBJECT_0 && payload[2] == 0) {
SetEvent(hid_fallback_event);
}
if (crash_always_event) {
// Ensure Core has consumed the attach reply before simulating the
// post-attach crash; otherwise the test races pipe teardown.
Expand Down Expand Up @@ -163,6 +188,8 @@ int main(int argc, char **argv) {
}

if (marker_event) CloseHandle(marker_event);
if (hid_fallback_event) CloseHandle(hid_fallback_event);
if (policy_once_event) CloseHandle(policy_once_event);
if (recovery_wait_event) CloseHandle(recovery_wait_event);
if (recovery_started_event) CloseHandle(recovery_started_event);
if (recovered_event) CloseHandle(recovered_event);
Expand Down
43 changes: 43 additions & 0 deletions tests/unit/platform/windows/test_ds5_sidecar_client.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,18 @@ namespace {

std::wstring suffix;
};

struct environment_scope_t {
environment_scope_t(const wchar_t *variable, const wchar_t *value): variable(variable) {
SetEnvironmentVariableW(variable, value);
}

~environment_scope_t() {
SetEnvironmentVariableW(variable.c_str(), nullptr);
}

std::wstring variable;
};
} // namespace

TEST(Ds5SidecarClientTests, UnassignedIndexIsNotOwned) {
Expand Down Expand Up @@ -176,6 +188,37 @@ TEST(Ds5SidecarClientTests, RelaunchesOnceAfterUnexpectedExit) {
client.free(0);
}

TEST(Ds5SidecarClientTests, FallsBackToHidOnlyWhenVirtualAudioBecomesDefault) {
config_scope_t restore_config;
config::input.ds5_enabled = true;
config::input.ds5_sidecar_path = SUNSHINE_DS5_FAKE_SIDECAR_PATH;

event_namespace_scope_t events(L"audio-policy-fallback");
environment_scope_t enable_policy_fallback(L"SUNSHINE_DS5_TEST_AUDIO_POLICY_FALLBACK", L"1");
const auto continue_name = L"Local\\sunshine-ds5-test-continue-" + events.suffix;
const auto policy_once_name = L"Local\\sunshine-ds5-test-policy-once-" + events.suffix;
const auto hid_fallback_name = L"Local\\sunshine-ds5-test-hid-fallback-" + events.suffix;
handle_scope_t continue_event(CreateEventW(nullptr, FALSE, FALSE, continue_name.c_str()));
handle_scope_t policy_once_event(CreateEventW(nullptr, TRUE, FALSE, policy_once_name.c_str()));
handle_scope_t hid_fallback_event(CreateEventW(nullptr, FALSE, FALSE, hid_fallback_name.c_str()));
ASSERT_NE(continue_event.handle, nullptr);
ASSERT_NE(policy_once_event.handle, nullptr);
ASSERT_NE(hid_fallback_event.handle, nullptr);

auto mail = std::make_shared<safe::mail_raw_t>();
auto feedback = mail->queue<platf::gamepad_feedback_msg_t>("ds5-audio-policy-fallback-test");
auto feedback_for_test = feedback;
platf::ds5::sidecar_client_t client;
ASSERT_EQ(client.alloc({ 0, 0 }, std::move(feedback), true), 0);
ASSERT_EQ(WaitForSingleObject(hid_fallback_event.handle, 5000), WAIT_OBJECT_0);
ASSERT_TRUE(SetEvent(continue_event.handle));
const auto marker = feedback_for_test->pop(std::chrono::seconds(2));
ASSERT_TRUE(marker);
EXPECT_EQ(marker->type, platf::gamepad_feedback_e::rumble);
EXPECT_TRUE(client.owns(0));
client.free(0);
}

TEST(Ds5SidecarClientTests, FreeCancelsPendingRecovery) {
config_scope_t restore_config;
config::input.ds5_enabled = true;
Expand Down
56 changes: 35 additions & 21 deletions tools/sunshine-ds5-sidecar/ControllerSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,15 @@ internal sealed class ControllerSession : IDisposable
private const uint Y = 0x8000;
private const uint Touchpad = 0x100000;
private const uint Misc = 0x200000;
private const int AudioInputChannels = 4;
private const int HapticsOutputChannels = 2;
private const int BytesPerSample = 2;
private const int HapticsFramesPerPacket = 240;

private readonly object _stateLock = new();
private readonly object _outputLock = new();
private readonly HMController _controller;
private readonly HMProfile _profile;
private readonly HMAudioOutput? _audioOutput;
private readonly Action<Protocol.Message> _emit;
private DefaultAudioEndpointGuard? _audioEndpointGuard;
private readonly AdaptiveTriggerState _adaptiveTriggers = new();
private HMGamepadState _state;
private readonly Dictionary<uint, int> _touchSlots = new();
Expand Down Expand Up @@ -63,10 +62,13 @@ internal ControllerSession(byte deviceId,
};

_controller.OutputDecoded += OnOutputDecoded;
if (_controller.UsbAudio is not null)
if (profile.Id == DualSenseHapticsAudio.CompositeProfileId)
{
_controller.UsbAudio.Output.FramesReceived += OnAudioFrames;
_controller.UsbAudio.Output.StreamingChanged += OnAudioStreamingChanged;
_audioOutput = _controller.UsbAudio?.Output
?? throw new InvalidDataException("Composite DualSense did not expose its audio output");
DualSenseHapticsAudio.ValidateRuntimeOutput(_audioOutput);
_audioOutput.FramesReceived += OnAudioFrames;
_audioOutput.StreamingChanged += OnAudioStreamingChanged;
}
// Emit a centered, untouched idle frame immediately: without it the
// device reports an all-zero buffer until the first client input,
Expand All @@ -76,7 +78,22 @@ internal ControllerSession(byte deviceId,

internal byte DeviceId { get; }
internal byte ClientControllerNumber { get; }
internal bool HasAudio => _controller.UsbAudio is not null;
internal bool HasAudio => _audioOutput is not null;

internal void StartDefaultAudioEndpointGuard()
{
if (_audioOutput is null || _audioEndpointGuard is not null)
return;
_audioEndpointGuard = new DefaultAudioEndpointGuard(role =>
{
if (Volatile.Read(ref _disposed) != 0)
return;
_emit(new Protocol.Message(
Protocol.MessageType.AudioPolicyViolation,
0,
new[] { DeviceId, ClientControllerNumber, (byte)role, (byte)0 }));
});
}

internal void SubmitInput(ReadOnlySpan<byte> payload)
{
Expand Down Expand Up @@ -281,7 +298,7 @@ private void OnAudioFrames(object? sender, ReadOnlyMemory<byte> pcm)
_audioResidual.AsSpan().CopyTo(combined);
pcm.Span.CopyTo(combined.AsSpan(_audioResidual.Length));
}
var sourceFrameBytes = AudioInputChannels * BytesPerSample;
var sourceFrameBytes = DualSenseHapticsAudio.InputFrameBytes;
var usableBytes = combined.Length - combined.Length % sourceFrameBytes;
_audioResidual = usableBytes == combined.Length ? Array.Empty<byte>() : combined[usableBytes..];

Expand All @@ -291,13 +308,8 @@ private void OnAudioFrames(object? sender, ReadOnlyMemory<byte> pcm)
while (offsetFrames < frameCount)
{
var frames = Math.Min(HapticsFramesPerPacket, frameCount - offsetFrames);
var haptics = new byte[frames * HapticsOutputChannels * BytesPerSample];
for (var frame = 0; frame < frames; frame++)
{
var sourceOffset = (offsetFrames + frame) * sourceFrameBytes + 4;
var targetOffset = frame * 4;
source.Slice(sourceOffset, 4).CopyTo(haptics.AsSpan(targetOffset, 4));
}
var haptics = DualSenseHapticsAudio.Extract(
source.Slice(offsetFrames * sourceFrameBytes, frames * sourceFrameBytes));
var flags = Volatile.Read(ref _hapticsStreaming) != 0 &&
Interlocked.Exchange(ref _hapticsNeedsStart, 0) != 0
? Protocol.HapticsFlags.StreamStart
Expand All @@ -315,14 +327,14 @@ private void EmitHaptics(ReadOnlySpan<byte> pcm, ushort frameCount, Protocol.Hap
payload[0] = DeviceId;
payload[1] = ClientControllerNumber;
payload[2] = (byte)flags;
payload[3] = HapticsOutputChannels;
payload[3] = DualSenseHapticsAudio.OutputChannels;
BinaryPrimitives.WriteUInt16LittleEndian(payload.AsSpan(4, 2), frameCount);
payload[6] = 16;
payload[6] = DualSenseHapticsAudio.BitsPerSample;
BinaryPrimitives.WriteUInt32LittleEndian(payload.AsSpan(8, 4),
unchecked((uint)Interlocked.Increment(ref _hapticsSequence)));
BinaryPrimitives.WriteUInt64LittleEndian(payload.AsSpan(12, 8),
(ulong)ElapsedMicroseconds());
BinaryPrimitives.WriteUInt32LittleEndian(payload.AsSpan(20, 4), 48000);
BinaryPrimitives.WriteUInt32LittleEndian(payload.AsSpan(20, 4), DualSenseHapticsAudio.SampleRateHz);
pcm.CopyTo(payload.AsSpan(24));
_emit(new Protocol.Message(Protocol.MessageType.HapticsPcm, 0, payload));
}
Expand Down Expand Up @@ -424,16 +436,18 @@ public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0)
return;
_audioEndpointGuard?.Dispose();
_audioEndpointGuard = null;
_controller.OutputDecoded -= OnOutputDecoded;
lock (_outputLock)
{
if (_adaptiveTriggers.TryReset(DeviceId, ClientControllerNumber, out var adaptiveTriggers))
_emit(adaptiveTriggers);
}
if (_controller.UsbAudio is not null)
if (_audioOutput is not null)
{
_controller.UsbAudio.Output.FramesReceived -= OnAudioFrames;
_controller.UsbAudio.Output.StreamingChanged -= OnAudioStreamingChanged;
_audioOutput.FramesReceived -= OnAudioFrames;
_audioOutput.StreamingChanged -= OnAudioStreamingChanged;
}
_controller.Dispose();
}
Expand Down
Loading
Loading