-
-
-
{{ $t('config.audio_sink') }}
-
-
- {{ $tp('config.audio_sink_desc') }}
-
-
- tools\audio-info.exe
-
-
- pacmd list-sinks | grep "name:"
- pactl list short sinks
-
-
- pacmd list-sinks | grep "name:"
- pactl list short sinks
-
-
- Soundflower
- BlackHole .
-
-
+
+
+ {{ $t('config.audio_capture_target') }}
+
+
+
+
+
+
+
+
+
+ {{ $t('config.audio_capture_target_silent') }}
+ {{ $t('config.audio_capture_target_silent_outcome') }}
+ {{ $t('config.audio_capture_target_silent_desc_macos') }}
+
-
+
+
+
+ {{ $t('config.audio_capture_target_current') }}
+ {{ $t('config.audio_capture_target_current_outcome') }}
+
+
+
+
+
+
+ {{ $t('config.audio_capture_target_specific') }}
+ {{ $t('config.audio_capture_target_specific_outcome') }}
+
+
+
+
{{ $t('config.audio_capture_how_it_works') }}: {{ $t(howItWorksKey) }}
+
+
+
+ {{ $t('config.audio_capture_owner_legend') }}
+
+
+ {{ $t('config.audio_capture_owner_sunshine') }}
+
+
+
+ {{ $t('config.audio_capture_owner_self') }}
+
+
+
{{ $t('config.audio_capture_target_specific_sunshine_desc_macos') }}
+
+
+
+ {{ $t('config.audio_capture_effective_target') }}: {{ captureTarget === 'silent' && platform === 'windows' && config.virtual_sink && config.virtual_sink.trim() ? config.virtual_sink : $t(effectiveTargetKey) }} — {{ $t('config.audio_capture_effective_retained') }}
+
+
+
+
{{ $t('config.audio_sink') }}
+
+
{{ $t('config.audio_capture_sink_needed') }}
+
{{ $t('config.audio_capture_sink_kept_hint') }}
+
+ {{ $tp('config.audio_sink_desc') }}
+
+
+ tools\audio-info.exe
+
+
+ pacmd list-sinks | grep "name:"
+ pactl list short sinks
+
+
+ pacmd list-sinks | grep "name:"
+ pactl list short sinks
+
+
+ BlackHole .
+
+
+
+
+
+
-
+
-
+
+
+
-
-
+
+
+ {{ $t('config.video_capture') }}
-
-
-
-
-
-
+
-
+ />
-
-
-
-
-
-
+ />
+
+
+
+
diff --git a/src_assets/common/assets/web/public/assets/locale/en.json b/src_assets/common/assets/web/public/assets/locale/en.json
index b914ed17db2..70b432aa558 100644
--- a/src_assets/common/assets/web/public/assets/locale/en.json
+++ b/src_assets/common/assets/web/public/assets/locale/en.json
@@ -152,10 +152,53 @@
"amd_vbaq": "AMF Variance Based Adaptive Quantization (VBAQ)",
"amd_vbaq_desc": "The human visual system is typically less sensitive to artifacts in highly textured areas. In VBAQ mode, pixel variance is used to indicate the complexity of spatial textures, allowing the encoder to allocate more bits to smoother areas. Enabling this feature leads to improvements in subjective visual quality with some content.",
"apply_note": "Click 'Apply' to restart Sunshine and apply changes. This will terminate any running sessions.",
+ "audio_capture_effective_retained": "Custom name kept for Custom device only",
+ "audio_capture_effective_target": "Streaming will capture",
+ "audio_capture_effective_target_current_freebsd": "Current default sink at session start",
+ "audio_capture_effective_target_current_linux": "Current default sink at session start",
+ "audio_capture_effective_target_current_macos": "System audio tap (default output unchanged)",
+ "audio_capture_effective_target_current_windows": "Current default device at session start",
+ "audio_capture_effective_target_silent_freebsd": "Sunshine null sink (automatic)",
+ "audio_capture_effective_target_silent_linux": "Sunshine null sink (automatic)",
+ "audio_capture_effective_target_silent_macos": "Not available on macOS; use Custom device with BlackHole",
+ "audio_capture_effective_target_silent_windows": "Steam Streaming Speakers (automatic)",
+ "audio_capture_how_it_works": "How this works",
+ "audio_capture_owner_self": "I route apps myself",
+ "audio_capture_owner_legend": "Who routes apps to the device",
+ "audio_capture_owner_sunshine": "Sunshine sets the device below as the default while streaming",
+ "audio_capture_target": "Audio Capture",
+ "audio_capture_target_current": "Play on this PC too",
+ "audio_capture_target_current_desc_freebsd": "This PC keeps playing sound. Sunshine listens in on the speaker your apps already use (the default sink) without changing it, and copies the sound to your client.",
+ "audio_capture_target_current_desc_linux": "This PC keeps playing sound. Sunshine listens in on the speaker your apps already use (the default sink) without changing it, and copies the sound to your client.",
+ "audio_capture_target_current_desc_macos": "Sunshine listens through a system-wide copy of all sound (the system audio tap) without changing the default output. Whether this Mac plays sound follows Moonlight's host playback setting.",
+ "audio_capture_target_current_desc_windows": "This PC keeps playing sound. Sunshine listens in on the device your apps already use (the default device) without changing it, and copies the sound to your client.",
+ "audio_capture_target_current_outcome": "Sound on this PC and on the client",
+ "audio_capture_target_silent": "Quiet streaming",
+ "audio_capture_target_silent_desc_freebsd": "The client hears the audio while this PC stays silent when Moonlight host playback is off. Sunshine creates a pretend speaker that makes no sound (a null sink) and listens to what apps play into it.",
+ "audio_capture_target_silent_desc_linux": "The client hears the audio while this PC stays silent when Moonlight host playback is off. Sunshine creates a pretend speaker that makes no sound (a null sink) and listens to what apps play into it.",
+ "audio_capture_target_silent_desc_macos": "Not available on macOS. For silent or separated capture, use Custom device with a virtual device (BlackHole) and route the game to it yourself.",
+ "audio_capture_target_silent_desc_windows": "The client hears the audio while this PC stays silent when Moonlight host playback is off. Sunshine uses a virtual speaker that makes no sound (Steam Streaming Speakers, or the virtual device below); if none is available, it uses the current device.",
+ "audio_capture_target_silent_outcome": "Silent on this PC, sound on the client",
+ "audio_capture_target_specific": "Custom device",
+ "audio_capture_target_specific_desc_freebsd": "Capture one exact speaker by name (one sink). Sunshine does not change the default sink; point your apps at this sink yourself.",
+ "audio_capture_target_specific_desc_linux": "Capture one exact speaker by name (one sink). Sunshine does not change the default sink; point your apps at this sink yourself.",
+ "audio_capture_target_specific_desc_macos": "Capture one exact input, such as a virtual device (BlackHole). Route Mac output to it yourself; Sunshine does not route applications.",
+ "audio_capture_target_specific_desc_windows": "Capture one exact device by name. Sunshine does not change the Windows default; point your apps at this device yourself.",
+ "audio_capture_target_specific_outcome": "Capture one exact device; you route apps to it",
+ "audio_capture_target_specific_sunshine_desc_freebsd": "Sunshine makes this speaker the main one for every app while streaming (sets it as the default sink), then puts the previous default back afterwards; applications follow automatically.",
+ "audio_capture_target_specific_sunshine_desc_linux": "Sunshine makes this speaker the main one for every app while streaming (sets it as the default sink), then puts the previous default back afterwards; applications follow automatically.",
+ "audio_capture_target_specific_sunshine_desc_macos": "Not applicable on macOS. Sunshine cannot set the default output; capture this input exactly and route Mac output to it yourself, for example with BlackHole.",
+ "audio_capture_target_specific_sunshine_desc_windows": "Sunshine makes this device the main one for every app while streaming (sets it as the Windows default), then puts the previous default back afterwards; applications follow automatically.",
+ "audio_capture_sink_needed": "Enter a sink name to use Custom device.",
+ "audio_capture_save_blocked": "Custom device capture needs a sink name before the settings can be saved.",
+ "audio_capture_sink_kept_hint": "Used only by Custom device — your text is kept when you switch modes.",
"audio_sink": "Audio Sink",
- "audio_sink_desc_linux": "The name of the audio sink used for Audio Loopback. If you do not specify this variable, pulseaudio will select the default monitor device. You can find the name of the audio sink using either command. For pactl, copy the sink name (second column) into this field:",
- "audio_sink_desc_macos": "The name of the audio sink used for Audio Loopback. Leave this blank to use the built-in system audio capture. Alternatively, specify a virtual device such as Soundflower or BlackHole if you prefer.",
- "audio_sink_desc_windows": "Manually specify a specific audio device to capture. If unset, the device is chosen automatically. We strongly recommend leaving this field blank to use automatic device selection! If you have multiple audio devices with identical names, you can get the Device ID using the following command:",
+ "audio_sink_desc_linux": "Enter the exact sink name. You can find it using either command. For pactl, copy the sink name (second column) into this field:",
+ "audio_sink_desc_freebsd": "Enter the exact sink name.",
+ "audio_sink_desc_macos": "Enter the exact input name, such as BlackHole 2ch.",
+ "audio_sink_desc_windows": "Enter the exact device name or Device ID. You can find it using the following command:",
+ "audio_sink_placeholder_linux": "sink-sunshine-stereo",
+ "audio_sink_placeholder_freebsd": "sink-sunshine-stereo",
"audio_sink_placeholder_macos": "BlackHole 2ch",
"audio_sink_placeholder_windows": "Speakers (High Definition Audio Device)",
"av1_mode": "AV1 Support",
@@ -249,8 +292,6 @@
"encoder_desc": "Force a specific encoder, otherwise Sunshine will select the best available option. Note: If you specify a hardware encoder on Windows, it must match the GPU where the display is connected.",
"encoder_software": "Software",
"encoders": "Encoders",
- "external_audio": "Externally Managed Audio",
- "external_audio_desc": "Capture only the configured Audio Sink without changing Windows defaults or device formats. Requires an explicit Audio Sink. Virtual Sink selection, automatic Steam audio driver installation, and Moonlight's host-playback toggle are ignored; manage playback and application routing in your audio mixer.",
"external_ip": "External IP",
"external_ip_desc": "If no external IP address is given, Sunshine will automatically detect external IP",
"fec_percentage": "FEC Percentage",
@@ -292,7 +333,7 @@
"high_resolution_scrolling": "High Resolution Scrolling Support",
"high_resolution_scrolling_desc": "When enabled, Sunshine will pass through high resolution scroll events from Moonlight clients. This can be useful to disable for older applications that scroll too fast with high resolution scroll events.",
"install_steam_audio_drivers": "Install Steam Audio Drivers",
- "install_steam_audio_drivers_desc": "If Steam is installed, this will automatically install the Steam Streaming Speakers driver to support 5.1/7.1 surround sound and muting host audio.",
+ "install_steam_audio_drivers_desc": "Windows only. If Steam is installed, this installs the supported Steam Streaming Speakers virtual adapter for Quiet streaming, including 5.1/7.1 surround. Administrator rights may be required.",
"key_repeat_delay": "Key Repeat Delay",
"key_repeat_delay_desc": "Control how fast keys will repeat themselves. The initial delay in milliseconds before repeating keys.",
"key_repeat_frequency": "Key Repeat Frequency",
@@ -475,8 +516,9 @@
"vk_quality_speed": "speed -- prefer speed",
"vk_quality_balanced": "balanced -- balanced (default)",
"vk_quality_quality": "quality -- prefer quality",
+ "video_capture": "Video Capture",
"virtual_sink": "Virtual Sink",
- "virtual_sink_desc": "Manually specify a virtual audio device to use. If unset, the device is chosen automatically. We strongly recommend leaving this field blank to use automatic device selection!",
+ "virtual_sink_desc": "Windows virtual device used by Quiet streaming. Leave blank to use the supported Steam Streaming Speakers adapter automatically, or name another virtual device to use instead. We recommend leaving this field blank!",
"virtual_sink_placeholder": "Steam Streaming Speakers",
"vt_coder": "VideoToolbox Coder",
"vt_realtime": "VideoToolbox Realtime Encoding",
diff --git a/tests/integration/test_config_consistency.cpp b/tests/integration/test_config_consistency.cpp
index 5051ec6e72d..7ff0e8d1f19 100644
--- a/tests/integration/test_config_consistency.cpp
+++ b/tests/integration/test_config_consistency.cpp
@@ -369,7 +369,8 @@ TEST_F(ConfigConsistencyTest, AllConfigOptionsExistInAllFiles) {
// Options that are internal/special and shouldn't be in UI/docs
const std::set> internalOptions = {
- "flags" // Internal config flags, not user-configurable
+ "flags", // Internal config flags, not user-configurable
+ "external_audio" // Deprecated migration-only key, unified into keep_default_sink: remove this exception together with the external_audio migration shim in config parsing (legacy_external_audio in src/config.cpp) when that migration is dropped
};
std::vector missingFromFiles;
diff --git a/tests/unit/platform/linux/test_audio.cpp b/tests/unit/platform/linux/test_audio.cpp
index 19b962c5528..0fbd6f5d598 100644
--- a/tests/unit/platform/linux/test_audio.cpp
+++ b/tests/unit/platform/linux/test_audio.cpp
@@ -1,6 +1,6 @@
/**
* @file tests/unit/platform/linux/test_audio.cpp
- * @brief Tests for the Linux audio capture channel map.
+ * @brief Tests for Linux audio sink handling and the capture channel map.
*/
#ifdef __linux__
@@ -16,6 +16,7 @@
#include
// local includes
+ #include "src/config.h"
#include "src/platform/common.h"
#include "src/thread_safe.h"
@@ -155,4 +156,79 @@ TEST(LinuxAudioCallbackTest, TranslatesSuccessAndFailureWithoutContext) {
}
}
+namespace {
+ /**
+ * @brief Restore the keep_default_sink setting when a test scope ends.
+ */
+ class keep_default_sink_guard_t {
+ public:
+ /**
+ * @brief Save the current keep_default_sink value.
+ */
+ keep_default_sink_guard_t():
+ original_ {config::audio.keep_default_sink} {
+ }
+
+ /**
+ * @brief Restore the saved keep_default_sink value.
+ */
+ ~keep_default_sink_guard_t() {
+ config::audio.keep_default_sink = original_;
+ }
+
+ private:
+ bool original_; ///< Value present before the test changed the setting.
+ };
+} // namespace
+
+TEST(KeepDefaultSinkAudioTest, CaptureSinkKeepsHostDefaultSink) {
+ keep_default_sink_guard_t guard;
+ config::audio.keep_default_sink = true;
+
+ auto control = platf::audio_control();
+ if (!control) {
+ GTEST_SKIP() << "PulseAudio is unavailable in this environment";
+ }
+
+ ASSERT_TRUE(control->supports_keep_default_sink());
+
+ auto before = control->sink_info();
+ ASSERT_TRUE(before.has_value());
+
+ // A nonexistent sink proves the capture path never swaps: set_sink would fail with -1.
+ EXPECT_EQ(control->capture_sink("sunshine-test-nonexistent-sink"), 0);
+ // The sink must be recorded for the monitor lookup in microphone().
+ EXPECT_EQ(control->snapshot_capture_sink_record(), "sunshine-test-nonexistent-sink");
+
+ auto after = control->sink_info();
+ ASSERT_TRUE(after.has_value());
+ EXPECT_EQ(after->host, before->host);
+}
+
+TEST(NullSinkOwnershipTest, AdoptedSinksSurvivePeerTeardown) {
+ auto first = platf::audio_control();
+ if (!first) {
+ GTEST_SKIP() << "PulseAudio is unavailable in this environment";
+ }
+
+ auto first_sink = first->sink_info();
+ ASSERT_TRUE(first_sink.has_value());
+ ASSERT_TRUE(first_sink->null.has_value()) << "Sunshine null sinks missing from the graph";
+
+ // A second session adopts the same sinks; tearing it down must not unload
+ // sinks it didn't create (previously this yanked routed streams back to
+ // the host default on every disconnect).
+ {
+ auto second = platf::audio_control();
+ ASSERT_TRUE(second) << "PulseAudio rejected a second control connection";
+ auto second_sink = second->sink_info();
+ ASSERT_TRUE(second_sink.has_value());
+ ASSERT_TRUE(second_sink->null.has_value());
+ }
+
+ auto after = first->sink_info();
+ ASSERT_TRUE(after.has_value());
+ EXPECT_TRUE(after->null.has_value()) << "Peer teardown unloaded adopted null sinks";
+}
+
#endif // __linux__
diff --git a/tests/unit/platform/macos/test_av_audio.mm b/tests/unit/platform/macos/test_av_audio.mm
index 0df9d42604d..3f1861e949c 100644
--- a/tests/unit/platform/macos/test_av_audio.mm
+++ b/tests/unit/platform/macos/test_av_audio.mm
@@ -20,6 +20,11 @@
#import
#include
+namespace platf::tests {
+ bool keep_default_supported();
+ int capture_sink_status(const std::string &sink);
+} // namespace platf::tests
+
namespace {
bool permission_probe_unmuted = false; ///< Whether the test tap leaves host audio audible.
int permission_probe_result = 0; ///< Simulated Core Audio tap setup result.
@@ -548,4 +553,12 @@ int test_permission_tap_setup(AVAudio *audio, [[maybe_unused]] SEL selector, UIn
}
}
+/**
+ * @brief macOS capture never touches the default output, with or without keep-default.
+ */
+TEST(MacosAudioControlTest, KeepDefaultModeCapturesWithoutSwapping) {
+ EXPECT_TRUE(platf::tests::keep_default_supported());
+ EXPECT_EQ(platf::tests::capture_sink_status("any-sink"), 0);
+}
+
#endif // __APPLE__
diff --git a/tests/unit/platform/windows/test_audio.cpp b/tests/unit/platform/windows/test_audio.cpp
index 192db905170..f90d58951bb 100644
--- a/tests/unit/platform/windows/test_audio.cpp
+++ b/tests/unit/platform/windows/test_audio.cpp
@@ -9,6 +9,7 @@
#ifdef _WIN32
// standard includes
#include
+ #include
#include
#include
#include
@@ -27,9 +28,15 @@
namespace platf::audio::tests {
std::vector virtual_sink_waveformats(WORD channel_count);
int initialize_audio_control(const std::function> &create_instance);
- std::optional configured_sink_info();
- int set_external_sink(const std::string &sink);
+ int set_keep_default_sink(const std::string &sink);
+ bool keep_default_supported();
+ std::string capture_assigned_sink(const std::string &sink);
+ bool installs_default_callback(const std::string &sink, bool keep_default);
+ bool resets_default_device(bool keep_default);
+ bool installs_steam_drivers(bool keep_default, bool install_requested);
+ void reset_with_keep_default();
bool sink_device_available(const std::string &sink, IMMDeviceEnumerator *device_enum);
+ std::optional reported_sinks(IMMDeviceEnumerator *device_enum);
bool microphone_available(const std::string &assigned_sink, const std::string &configured_sink, IMMDeviceEnumerator *device_enum);
bool capture_follows_default_device(IMMDeviceEnumerator *device_enum, IMMDevice *capture_device);
capture_e simulate_default_device_change(bool follows_default_device, bool install_callback, bool render_device_changed, int &callback_count);
@@ -216,6 +223,9 @@ namespace {
HRESULT STDMETHODCALLTYPE GetDefaultAudioEndpoint(EDataFlow, ERole, IMMDevice **resolved_device) override {
++get_default_device_calls;
+ if (FAILED(get_default_status)) {
+ return get_default_status;
+ }
device.AddRef();
*resolved_device = &device;
return S_OK;
@@ -248,6 +258,7 @@ namespace {
fake_device_collection_t collection;
HRESULT enumeration_status = S_OK;
HRESULT get_device_status = S_OK;
+ HRESULT get_default_status = S_OK;
int get_device_calls = 0;
int get_default_device_calls = 0;
std::wstring last_requested_id;
@@ -323,11 +334,11 @@ TEST(WindowsAudioTest, DefaultDeviceIsUsedWhenNoSinkWasRequested) {
/**
* @brief Preserve global audio configuration while exercising capture-only mode.
*/
-class ExternalAudioTest: public testing::Test {
+class WindowsKeepDefaultTest: public testing::Test {
protected:
void SetUp() override {
previous = config::audio;
- config::audio.external_audio = true;
+ config::audio.keep_default_sink = true;
config::audio.sink = "configured-id";
config::audio.virtual_sink = "ignored-virtual-sink";
policy_requests = 0;
@@ -394,88 +405,60 @@ class ExternalAudioTest: public testing::Test {
inline static HRESULT enumerator_status = S_OK; ///< Simulated enumeration initialization result.
};
-TEST_F(ExternalAudioTest, InitializesWithoutPolicyInterface) {
+TEST_F(WindowsKeepDefaultTest, InitializesWithoutPolicyInterface) {
EXPECT_EQ(platf::audio::tests::initialize_audio_control(&create_capture_interface), 0);
EXPECT_EQ(policy_request_count(), 0);
EXPECT_EQ(enumerator_request_count(), 1);
}
-TEST_F(ExternalAudioTest, InitializationRequiresEndpointEnumerator) {
+TEST_F(WindowsKeepDefaultTest, InitializationRequiresEndpointEnumerator) {
fail_enumerator_initialization();
EXPECT_NE(platf::audio::tests::initialize_audio_control(&create_capture_interface), 0);
EXPECT_EQ(policy_request_count(), 0);
EXPECT_EQ(enumerator_request_count(), 1);
}
-TEST_F(ExternalAudioTest, DisabledModeStillRequiresPolicyInterface) {
- config::audio.external_audio = false;
+TEST_F(WindowsKeepDefaultTest, DisabledModeStillRequiresPolicyInterface) {
+ config::audio.keep_default_sink = false;
EXPECT_NE(platf::audio::tests::initialize_audio_control(&create_capture_interface), 0);
EXPECT_EQ(policy_request_count(), 1);
EXPECT_EQ(enumerator_request_count(), 0);
}
-TEST_F(ExternalAudioTest, RequiresExplicitSink) {
- config::audio.sink.clear();
- EXPECT_EXIT(std::exit(platf::audio::tests::configured_sink_info() ? 1 : 0), testing::ExitedWithCode(0), "");
- fake_device_enumerator_t enumerator {L"endpoint-id"};
- EXPECT_FALSE(platf::audio::tests::microphone_available({}, {}, &enumerator));
- EXPECT_EQ(enumerator.get_default_device_calls, 0);
- EXPECT_EQ(enumerator.get_device_calls, 0);
+TEST_F(WindowsKeepDefaultTest, SinkChangesDoNotAccessPolicyOrFormatInterfaces) {
+ EXPECT_EXIT(std::exit(platf::audio::tests::set_keep_default_sink("virtual-Stereoendpoint-id")), testing::ExitedWithCode(0), "");
+ EXPECT_EXIT(std::exit(platf::audio::tests::set_keep_default_sink("other-endpoint")), testing::ExitedWithCode(0), "");
}
-TEST_F(ExternalAudioTest, SkipsDefaultAndVirtualDeviceDiscovery) {
- EXPECT_EXIT(
- {
- const auto sinks = platf::audio::tests::configured_sink_info();
- std::exit(sinks && sinks->host == "configured-id" && !sinks->null ? 0 : 1);
- },
- testing::ExitedWithCode(0),
- ""
- );
-}
-
-TEST_F(ExternalAudioTest, SinkChangesDoNotAccessPolicyOrFormatInterfaces) {
- EXPECT_EXIT(std::exit(platf::audio::tests::set_external_sink("virtual-Stereoendpoint-id")), testing::ExitedWithCode(0), "");
- EXPECT_EXIT(std::exit(platf::audio::tests::set_external_sink("other-endpoint")), testing::ExitedWithCode(0), "");
-}
-
-TEST_F(ExternalAudioTest, ConfiguredSinkWinsOverAssignedSink) {
- fake_device_enumerator_t enumerator {L"configured-id"};
- EXPECT_FALSE(platf::audio::tests::microphone_available("virtual-Stereoother-id", "configured-id", &enumerator));
- EXPECT_EQ(enumerator.last_requested_id, L"configured-id");
+TEST_F(WindowsKeepDefaultTest, AssignedSinkWinsOverConfiguredSink) {
+ fake_device_enumerator_t enumerator {L"assigned-id"};
+ EXPECT_FALSE(platf::audio::tests::microphone_available("assigned-id", "configured-id", &enumerator));
+ EXPECT_EQ(enumerator.last_requested_id, L"assigned-id");
EXPECT_EQ(enumerator.get_default_device_calls, 0);
}
-TEST_F(ExternalAudioTest, MissingSinkDoesNotFallBackToDefault) {
+TEST_F(WindowsKeepDefaultTest, MissingSinkDoesNotFallBackToDefault) {
fake_device_enumerator_t enumerator {L"endpoint-id"};
EXPECT_FALSE(platf::audio::tests::microphone_available({}, "missing-id", &enumerator));
EXPECT_EQ(enumerator.get_default_device_calls, 0);
}
-TEST_F(ExternalAudioTest, DisconnectedSinkDoesNotFallBackToDefault) {
+TEST_F(WindowsKeepDefaultTest, DisconnectedSinkDoesNotFallBackToDefault) {
fake_device_enumerator_t enumerator {L"configured-id"};
enumerator.device.state = DEVICE_STATE_UNPLUGGED;
EXPECT_FALSE(platf::audio::tests::microphone_available({}, "configured-id", &enumerator));
EXPECT_EQ(enumerator.get_default_device_calls, 0);
}
-TEST_F(ExternalAudioTest, DisabledModePreservesAssignedSinkPriority) {
- config::audio.external_audio = false;
- fake_device_enumerator_t enumerator {L"assigned-id"};
- EXPECT_FALSE(platf::audio::tests::microphone_available("assigned-id", "configured-id", &enumerator));
- EXPECT_EQ(enumerator.last_requested_id, L"assigned-id");
- EXPECT_EQ(enumerator.get_default_device_calls, 0);
-}
-
-TEST_F(ExternalAudioTest, DisabledModePreservesDefaultFallback) {
- config::audio.external_audio = false;
+TEST_F(WindowsKeepDefaultTest, DisabledModePreservesDefaultFallback) {
+ config::audio.keep_default_sink = false;
fake_device_enumerator_t enumerator {L"endpoint-id"};
EXPECT_TRUE(platf::audio::tests::capture_follows_default_device(&enumerator, nullptr));
EXPECT_EQ(enumerator.get_default_device_calls, 1);
EXPECT_EQ(enumerator.get_device_calls, 0);
}
-TEST_F(ExternalAudioTest, ReactivatedSinkCanBeResolvedAgain) {
+TEST_F(WindowsKeepDefaultTest, ReactivatedSinkCanBeResolvedAgain) {
fake_device_enumerator_t enumerator {L"configured-id"};
enumerator.device.state = DEVICE_STATE_UNPLUGGED;
EXPECT_FALSE(platf::audio::tests::sink_device_available("configured-id", &enumerator));
@@ -484,6 +467,45 @@ TEST_F(ExternalAudioTest, ReactivatedSinkCanBeResolvedAgain) {
EXPECT_EQ(enumerator.get_default_device_calls, 0);
}
+TEST_F(WindowsKeepDefaultTest, KeepsConfiguredSinkWhenDefaultUnavailable) {
+ fake_device_enumerator_t enumerator {L"configured-id"};
+ enumerator.get_default_status = E_FAIL;
+
+ const auto sinks = platf::audio::tests::reported_sinks(&enumerator);
+
+ ASSERT_TRUE(sinks.has_value());
+ EXPECT_EQ(sinks->host, "configured-id");
+ EXPECT_FALSE(sinks->null.has_value());
+ EXPECT_EQ(enumerator.get_default_device_calls, 1);
+}
+
+TEST_F(WindowsKeepDefaultTest, EmptyConfigStillUsesDefaultEndpointAsHost) {
+ config::audio.sink.clear();
+ fake_device_enumerator_t enumerator {L"endpoint-id"};
+
+ const auto sinks = platf::audio::tests::reported_sinks(&enumerator);
+
+ ASSERT_TRUE(sinks.has_value());
+ EXPECT_EQ(sinks->host, "endpoint-id");
+ EXPECT_EQ(enumerator.get_default_device_calls, 1);
+}
+
+TEST_F(WindowsKeepDefaultTest, EmptyConfigWithoutDefaultReportsNoSink) {
+ config::audio.sink.clear();
+ fake_device_enumerator_t enumerator {L"endpoint-id"};
+ enumerator.get_default_status = E_FAIL;
+
+ EXPECT_FALSE(platf::audio::tests::reported_sinks(&enumerator).has_value());
+}
+
+TEST_F(WindowsKeepDefaultTest, DisabledModeWithoutDefaultReportsNoSink) {
+ config::audio.keep_default_sink = false;
+ fake_device_enumerator_t enumerator {L"configured-id"};
+ enumerator.get_default_status = E_FAIL;
+
+ EXPECT_FALSE(platf::audio::tests::reported_sinks(&enumerator).has_value());
+}
+
TEST(WindowsAudioTest, DefaultCaptureSelectsDefaultEndpoint) {
fake_device_enumerator_t enumerator {L"endpoint-id"};
@@ -589,4 +611,25 @@ TEST(WindowsAudioTest, DefaultChangeWithoutCallbackStillReinitializes) {
);
EXPECT_EQ(callback_count, 0);
}
+
+TEST(WindowsAudioTest, KeepDefaultModeCapturesWithoutSwapping) {
+ EXPECT_TRUE(platf::audio::tests::keep_default_supported());
+ EXPECT_EQ(platf::audio::tests::capture_assigned_sink("endpoint-id"), "endpoint-id");
+}
+
+TEST(WindowsAudioTest, KeepDefaultModeInstallsNoReassertionCallback) {
+ constexpr const char *virtual_sink = "virtual-Stereoendpoint-id";
+ EXPECT_TRUE(platf::audio::tests::installs_default_callback(virtual_sink, false));
+ EXPECT_FALSE(platf::audio::tests::installs_default_callback(virtual_sink, true));
+ EXPECT_FALSE(platf::audio::tests::installs_default_callback("endpoint-id", false));
+}
+
+TEST(WindowsAudioTest, HandsOffModeSkipsDefaultResetAndDriverInstall) {
+ EXPECT_TRUE(platf::audio::tests::resets_default_device(false));
+ EXPECT_FALSE(platf::audio::tests::resets_default_device(true));
+ EXPECT_TRUE(platf::audio::tests::installs_steam_drivers(false, true));
+ EXPECT_FALSE(platf::audio::tests::installs_steam_drivers(true, true));
+ EXPECT_FALSE(platf::audio::tests::installs_steam_drivers(false, false));
+ platf::audio::tests::reset_with_keep_default();
+}
#endif
diff --git a/tests/unit/test_audio.cpp b/tests/unit/test_audio.cpp
index 8561cb3d9c5..2ab0863f533 100644
--- a/tests/unit/test_audio.cpp
+++ b/tests/unit/test_audio.cpp
@@ -6,8 +6,20 @@
// test includes
#include "../tests_common.h"
+// standard includes
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
// local includes
#include
+#include
#include
#include
@@ -114,3 +126,970 @@ TEST_P(AudioTest, TestEncode) {
timer.join();
capture.join();
}
+
+// The routing policy is pure: resolvable at compile time, no I/O, no globals.
+static_assert(!resolve_sink_routing_policy(true, true).swap_at_startup);
+static_assert(!resolve_sink_routing_policy(true, true).restore_at_teardown);
+static_assert(resolve_sink_routing_policy(true, false).swap_at_startup);
+static_assert(resolve_sink_routing_policy(true, false).restore_at_teardown);
+
+TEST(SinkRoutingPolicyTest, KeepsDefaultOnlyWhenRequestedAndSupported) {
+ const auto keep = resolve_sink_routing_policy(true, true);
+ EXPECT_FALSE(keep.swap_at_startup);
+ EXPECT_FALSE(keep.restore_at_teardown);
+
+ // Unsupported backends keep legacy swap-and-restore even when requested:
+ // the (true, false) row is the MUST-1 regression pin (startup swapped,
+ // teardown skipped, host default stranded).
+ for (const auto &[requested, supported] : {std::pair {false, false}, {false, true}, {true, false}}) {
+ const auto legacy = resolve_sink_routing_policy(requested, supported);
+ EXPECT_TRUE(legacy.swap_at_startup);
+ EXPECT_TRUE(legacy.restore_at_teardown);
+ }
+}
+
+TEST(SinkRoutingPolicyTest, StartupAndTeardownNeverDiverge) {
+ for (const auto requested : {false, true}) {
+ for (const auto supported : {false, true}) {
+ const auto policy = resolve_sink_routing_policy(requested, supported);
+ EXPECT_EQ(policy.swap_at_startup, policy.restore_at_teardown);
+ }
+ }
+}
+
+namespace {
+ /**
+ * @brief Virtual sink names shared by the capture-routing tests.
+ */
+ std::optional test_null_sinks() {
+ return platf::sink_t::null_t {"virtual-stereo", "virtual-surround51", "virtual-surround71"};
+ }
+} // namespace
+
+/**
+ * @brief Capture-only startup must target the host sink when nothing is configured.
+ *
+ * Regression test: without a swap, applications stay on the host default, so
+ * capturing the virtual sink's monitor would yield silence.
+ */
+TEST(CaptureRoutingTest, CaptureOnlyUsesHostSinkWhenNothingConfigured) {
+ for (const auto host_audio : {false, true}) {
+ const auto routing = resolve_capture_routing(true, true, host_audio, 2, "hw-default", "", test_null_sinks());
+ EXPECT_FALSE(routing.swap_at_startup) << "host_audio=" << host_audio;
+ EXPECT_FALSE(routing.restore_at_teardown) << "host_audio=" << host_audio;
+ EXPECT_EQ(routing.target, "hw-default") << "host_audio=" << host_audio;
+ }
+}
+
+/**
+ * @brief Capture-only startup must target the configured sink when one is set.
+ */
+TEST(CaptureRoutingTest, CaptureOnlyUsesConfiguredSinkWhenSet) {
+ for (const auto host_audio : {false, true}) {
+ const auto routing = resolve_capture_routing(true, true, host_audio, 2, "hw-default", "eq-sink", test_null_sinks());
+ EXPECT_FALSE(routing.swap_at_startup) << "host_audio=" << host_audio;
+ EXPECT_FALSE(routing.restore_at_teardown) << "host_audio=" << host_audio;
+ EXPECT_EQ(routing.target, "eq-sink") << "host_audio=" << host_audio;
+ }
+}
+
+/**
+ * @brief Swap-path startup must preserve the historical virtual sink selection.
+ */
+TEST(CaptureRoutingTest, SwapPathKeepsVirtualSinkSelection) {
+ const auto stereo = resolve_capture_routing(false, true, false, 2, "hw-default", "", test_null_sinks());
+ EXPECT_TRUE(stereo.swap_at_startup);
+ EXPECT_TRUE(stereo.restore_at_teardown);
+ EXPECT_EQ(stereo.target, "virtual-stereo");
+
+ const auto surround = resolve_capture_routing(false, true, false, 6, "hw-default", "", test_null_sinks());
+ EXPECT_TRUE(surround.swap_at_startup);
+ EXPECT_EQ(surround.target, "virtual-surround51");
+
+ const auto configured = resolve_capture_routing(false, true, true, 2, "hw-default", "eq-sink", test_null_sinks());
+ EXPECT_TRUE(configured.swap_at_startup);
+ EXPECT_TRUE(configured.restore_at_teardown);
+ EXPECT_EQ(configured.target, "eq-sink");
+
+ // An explicit audio_sink pin beats the virtual sink even when host playback is off.
+ const auto configured_muted = resolve_capture_routing(false, true, false, 2, "hw-default", "eq-sink", test_null_sinks());
+ EXPECT_TRUE(configured_muted.swap_at_startup);
+ EXPECT_TRUE(configured_muted.restore_at_teardown);
+ EXPECT_EQ(configured_muted.target, "eq-sink");
+
+ // Legacy backends take the swap path even when keep-default is requested.
+ const auto legacy = resolve_capture_routing(true, false, false, 2, "hw-default", "", test_null_sinks());
+ EXPECT_TRUE(legacy.swap_at_startup);
+ EXPECT_TRUE(legacy.restore_at_teardown);
+ EXPECT_EQ(legacy.target, "virtual-stereo");
+}
+
+/**
+ * @brief Startup without virtual sinks must fall back to the host sink.
+ */
+TEST(CaptureRoutingTest, FallsBackToHostWithoutVirtualSinks) {
+ const auto routing = resolve_capture_routing(true, true, false, 2, "hw-default", "", std::nullopt);
+ EXPECT_FALSE(routing.swap_at_startup);
+ EXPECT_FALSE(routing.restore_at_teardown);
+ EXPECT_EQ(routing.target, "hw-default");
+
+ // Swap path with no alternative: the target is already the host, so there is nothing to restore.
+ const auto swap = resolve_capture_routing(false, true, false, 2, "hw-default", "", std::nullopt);
+ EXPECT_TRUE(swap.swap_at_startup);
+ EXPECT_FALSE(swap.restore_at_teardown);
+ EXPECT_EQ(swap.target, "hw-default");
+}
+
+/**
+ * @brief The shared intent must map the three UI choices onto config state.
+ */
+TEST(AudioCaptureIntentTest, ResolvesIntentFromConfig) {
+ using intent = platf::audio_capture_intent_e;
+ EXPECT_EQ(resolve_audio_capture_intent(false, ""), intent::client_only);
+ EXPECT_EQ(resolve_audio_capture_intent(true, ""), intent::host_and_client);
+ EXPECT_EQ(resolve_audio_capture_intent(false, "eq-sink"), intent::pinned_sink);
+ EXPECT_EQ(resolve_audio_capture_intent(true, "eq-sink"), intent::pinned_sink);
+}
+
+/**
+ * @brief Intent names must stay stable for the capture-mode log line.
+ */
+TEST(AudioCaptureIntentTest, NamesEveryIntent) {
+ using intent = platf::audio_capture_intent_e;
+ EXPECT_EQ(audio_capture_intent_name(intent::client_only), "client_only");
+ EXPECT_EQ(audio_capture_intent_name(intent::host_and_client), "host_and_client");
+ EXPECT_EQ(audio_capture_intent_name(intent::pinned_sink), "pinned_sink");
+}
+
+namespace {
+ /**
+ * @brief Minimal backend that never learned the keep-default behavior.
+ */
+ class legacy_audio_control_t: public platf::audio_control_t {
+ public:
+ int set_sink(const std::string &) override {
+ set_sink_called = true;
+ return 0;
+ }
+
+ // Keep the params-bundle overload visible: the positional override below would otherwise hide it.
+ using platf::audio_control_t::microphone;
+
+ std::unique_ptr microphone(const std::uint8_t *, int, std::uint32_t, std::uint32_t, bool, bool) override {
+ return nullptr;
+ }
+
+ bool is_sink_available(const std::string &) override {
+ return true;
+ }
+
+ std::optional sink_info() override {
+ return std::nullopt;
+ }
+
+ bool set_sink_called = false; ///< Whether the legacy swap path ran.
+ };
+} // namespace
+
+/**
+ * @brief A backend that never learned keep-default must keep swap-and-restore.
+ *
+ * Fail-without-fix: if the capture_sink() default stops delegating to
+ * set_sink(), legacy backends silently capture nothing (returning success
+ * while selecting no sink) instead of taking the historical swap path.
+ */
+TEST(AudioControlAdapterTest, LegacyBackendKeepsSwapBehavior) {
+ legacy_audio_control_t control;
+ EXPECT_FALSE(control.supports_keep_default_sink());
+ EXPECT_EQ(control.capture_sink("any-sink"), 0);
+ EXPECT_TRUE(control.set_sink_called);
+}
+
+/**
+ * @brief Recording a capture target must be a safe no-op on legacy backends.
+ *
+ * Fail-without-fix: if the set_capture_target() default gains behavior (or
+ * crashes on backends without target storage), every legacy session breaks,
+ * since the guard refreshes unconditionally before microphone creation.
+ */
+TEST(AudioControlAdapterTest, DefaultCaptureTargetSetterIsNoOp) {
+ legacy_audio_control_t control;
+ control.set_capture_target(platf::audio_capture_intent_e::host_and_client, 1234);
+ control.set_capture_target(platf::audio_capture_intent_e::client_only, 0);
+ EXPECT_FALSE(control.set_sink_called);
+}
+
+/**
+ * @brief Releasing a capture target must be a safe no-op on legacy backends.
+ *
+ * Fail-without-fix: if the clear_capture_target() default gains behavior (or
+ * crashes on backends without target storage), every legacy session teardown
+ * breaks, since the guard releases unconditionally when a target was recorded.
+ */
+TEST(AudioControlAdapterTest, DefaultCaptureTargetClearIsNoOp) {
+ legacy_audio_control_t control;
+ control.clear_capture_target(platf::audio_capture_intent_e::host_and_client, 1234);
+ control.clear_capture_target(platf::audio_capture_intent_e::client_only, 0);
+ EXPECT_FALSE(control.set_sink_called);
+}
+
+namespace {
+ /**
+ * @brief Backend that records which sink the availability probe checks.
+ */
+ class probe_audio_control_t: public platf::audio_control_t {
+ public:
+ /**
+ * @brief Create a probe backend with a controlled keep-default capability.
+ * @param supports_keep Whether capture_sink() is supported without swapping.
+ */
+ explicit probe_audio_control_t(bool supports_keep):
+ supports_keep {supports_keep} {
+ }
+
+ int set_sink(const std::string &) override {
+ return 0;
+ }
+
+ // Keep the params-bundle overload visible: the positional override below would otherwise hide it.
+ using platf::audio_control_t::microphone;
+
+ std::unique_ptr microphone(const std::uint8_t *, int, std::uint32_t, std::uint32_t, bool, bool) override {
+ return nullptr;
+ }
+
+ bool is_sink_available(const std::string &sink) override {
+ probed_sink = sink;
+ return true;
+ }
+
+ std::optional sink_info() override {
+ return std::nullopt;
+ }
+
+ bool supports_keep_default_sink() const override {
+ return supports_keep;
+ }
+
+ bool supports_keep; ///< Whether this backend supports keep-default capture.
+ std::string probed_sink; ///< Sink most recently passed to is_sink_available().
+ };
+
+ /**
+ * @brief Build an audio context whose host sink differs from the configured sink.
+ * @param supports_keep Whether the fake backend supports keep-default capture.
+ * @param probed Receives the fake backend so tests can inspect the probed sink.
+ * @return Audio context with host sink "hw-default".
+ */
+ audio_ctx_t make_probe_ctx(bool supports_keep, probe_audio_control_t *&probed) {
+ auto control = std::make_unique(supports_keep);
+ probed = control.get();
+
+ audio_ctx_t ctx {};
+ ctx.control = std::move(control);
+ ctx.restore_sink = false;
+ ctx.sink.host = "hw-default";
+ return ctx;
+ }
+
+ /**
+ * @brief Preserve the global audio config while a probe test rewrites it.
+ */
+ struct audio_config_guard_t {
+ audio_config_guard_t() = default;
+ audio_config_guard_t(const audio_config_guard_t &) = delete;
+ audio_config_guard_t &operator=(const audio_config_guard_t &) = delete;
+ audio_config_guard_t(audio_config_guard_t &&) = delete;
+ audio_config_guard_t &operator=(audio_config_guard_t &&) = delete;
+
+ bool keep_default_sink = config::audio.keep_default_sink; ///< Saved keep_default_sink value.
+ std::string sink = config::audio.sink; ///< Saved audio_sink value.
+
+ ~audio_config_guard_t() noexcept {
+ try {
+ config::audio.keep_default_sink = keep_default_sink;
+ config::audio.sink = sink;
+ } catch (...) {
+ // Teardown restore must not throw during stack unwinding: report via noexcept fputs
+ // (Boost.Log allocates/may throw, so it cannot be used in this noexcept destructor).
+ std::fputs("audio_config_guard_t: failed to restore audio config\n", stderr);
+ }
+ }
+ };
+} // namespace
+
+TEST(SinkAvailabilityProbeTest, KeepDefaultProbesConfiguredSink) {
+ const audio_config_guard_t guard;
+ config::audio.keep_default_sink = true;
+ config::audio.sink = "configured-sink";
+
+ probe_audio_control_t *probed = nullptr;
+ auto ctx = make_probe_ctx(true, probed);
+
+ EXPECT_TRUE(is_audio_ctx_sink_available(ctx));
+ EXPECT_EQ(probed->probed_sink, "configured-sink");
+}
+
+TEST(SinkAvailabilityProbeTest, KeepDefaultWithoutConfiguredSinkProbesHostSink) {
+ const audio_config_guard_t guard;
+ config::audio.keep_default_sink = true;
+ config::audio.sink.clear();
+
+ probe_audio_control_t *probed = nullptr;
+ auto ctx = make_probe_ctx(true, probed);
+
+ EXPECT_TRUE(is_audio_ctx_sink_available(ctx));
+ EXPECT_EQ(probed->probed_sink, "hw-default");
+}
+
+TEST(SinkAvailabilityProbeTest, SwapModeProbesHostSink) {
+ const audio_config_guard_t guard;
+ config::audio.keep_default_sink = false;
+ config::audio.sink = "configured-sink";
+
+ probe_audio_control_t *probed = nullptr;
+ auto ctx = make_probe_ctx(true, probed);
+
+ EXPECT_TRUE(is_audio_ctx_sink_available(ctx));
+ EXPECT_EQ(probed->probed_sink, "hw-default");
+}
+
+TEST(SinkAvailabilityProbeTest, UnsupportedBackendProbesHostSink) {
+ const audio_config_guard_t guard;
+ config::audio.keep_default_sink = true;
+ config::audio.sink = "configured-sink";
+
+ probe_audio_control_t *probed = nullptr;
+ auto ctx = make_probe_ctx(false, probed);
+
+ EXPECT_TRUE(is_audio_ctx_sink_available(ctx));
+ EXPECT_EQ(probed->probed_sink, "hw-default");
+}
+
+namespace {
+ /**
+ * @brief Microphone stub that never blocks the capture loop.
+ */
+ class stub_mic_t: public platf::mic_t {
+ public:
+ /**
+ * @brief Report a timeout instead of delivering samples.
+ * @param frame_buffer Destination for captured samples, left untouched.
+ * @return Timeout status so the capture loop keeps polling.
+ */
+ platf::capture_e sample(std::vector &frame_buffer) override {
+ (void) frame_buffer;
+ return platf::capture_e::timeout;
+ }
+ };
+
+ /**
+ * @brief Backend that records the capture() orchestration calls for verification.
+ */
+ class recording_audio_control_t: public platf::audio_control_t {
+ public:
+ int set_sink(const std::string &sink) override {
+ calls.push_back("set_sink:" + sink);
+ return set_sink_status;
+ }
+
+ bool supports_keep_default_sink() const override {
+ return supports_keep;
+ }
+
+ int capture_sink(const std::string &sink) override {
+ calls.push_back("capture_sink:" + sink);
+ return capture_sink_status;
+ }
+
+ /**
+ * @brief Record the refreshed capture target.
+ * @param intent Capture intent resolved from the audio configuration.
+ * @param process_id Operating-system PID to capture, or 0 for endpoint capture.
+ */
+ void set_capture_target(platf::audio_capture_intent_e intent, std::uint32_t process_id) override {
+ calls.emplace_back("set_capture_target");
+ set_intent = intent;
+ set_process_id = process_id;
+ }
+
+ /**
+ * @brief Record the released capture target.
+ * @param intent Capture intent recorded by the session being torn down.
+ * @param process_id PID recorded by the session being torn down, or 0 for endpoint capture.
+ */
+ void clear_capture_target(platf::audio_capture_intent_e intent, std::uint32_t process_id) override {
+ calls.emplace_back("clear_capture_target");
+ clear_intent = intent;
+ clear_process_id = process_id;
+ }
+
+ // Keep the params-bundle overload visible: the positional override below would otherwise hide it.
+ using platf::audio_control_t::microphone;
+
+ std::unique_ptr microphone(const std::uint8_t *mapping, int channels, std::uint32_t sample_rate, std::uint32_t frame_size, bool continuous_audio, bool host_audio_enabled) override {
+ calls.emplace_back("microphone");
+ mic_mapping = mapping;
+ mic_channels = channels;
+ mic_sample_rate = sample_rate;
+ mic_frame_size = frame_size;
+ mic_continuous_audio = continuous_audio;
+ mic_host_audio_enabled = host_audio_enabled;
+ if (fail_microphone) {
+ return nullptr;
+ }
+ return std::make_unique();
+ }
+
+ bool is_sink_available(const std::string &) override {
+ return true;
+ }
+
+ std::optional sink_info() override {
+ return std::nullopt;
+ }
+
+ /**
+ * @brief Find the position of a recorded call in the call sequence.
+ * @param prefix Call name prefix to search for.
+ * @return Index of the first matching call, or calls.size() when absent.
+ */
+ std::size_t call_index(std::string_view prefix) const {
+ for (std::size_t i = 0; i < calls.size(); ++i) {
+ if (calls[i].compare(0, prefix.size(), prefix) == 0) {
+ return i;
+ }
+ }
+ return calls.size();
+ }
+
+ bool supports_keep = true; ///< Whether capture_sink() is supported without swapping.
+ int set_sink_status = 0; ///< Status returned by set_sink().
+ int capture_sink_status = 0; ///< Status returned by capture_sink().
+ bool fail_microphone = false; ///< Whether microphone() returns nullptr.
+ std::vector calls; ///< Recorded call sequence in invocation order.
+ platf::audio_capture_intent_e set_intent = platf::audio_capture_intent_e::client_only; ///< Intent from the last refresh.
+ std::uint32_t set_process_id = 0; ///< PID from the last refresh.
+ platf::audio_capture_intent_e clear_intent = platf::audio_capture_intent_e::client_only; ///< Intent from the last release.
+ std::uint32_t clear_process_id = 0; ///< PID from the last release.
+ const std::uint8_t *mic_mapping = nullptr; ///< Mapping from the last microphone() call.
+ int mic_channels = 0; ///< Channels from the last microphone() call.
+ std::uint32_t mic_sample_rate = 0; ///< Sample rate from the last microphone() call.
+ std::uint32_t mic_frame_size = 0; ///< Frame size from the last microphone() call.
+ bool mic_continuous_audio = false; ///< Continuous flag from the last microphone() call.
+ bool mic_host_audio_enabled = false; ///< Host-audio flag from the last microphone() call.
+ };
+
+ /**
+ * @brief Build a capture-only routing that never swaps the host default.
+ * @return Startup plan targeting the saved host sink.
+ */
+ capture_routing_t make_capture_routing() {
+ return resolve_capture_routing(true, true, false, 2, "hw-default", "", std::nullopt);
+ }
+
+ /**
+ * @brief Build a swap routing that swaps to the virtual sink and restores it.
+ * @return Startup plan targeting the virtual stereo sink.
+ */
+ capture_routing_t make_swap_routing() {
+ return resolve_capture_routing(false, true, false, 2, "hw-default", "", test_null_sinks());
+ }
+
+ /**
+ * @brief Build a swap routing with nothing to restore.
+ * @return Startup plan targeting the host sink it already points at.
+ */
+ capture_routing_t make_swap_without_restore_routing() {
+ return resolve_capture_routing(false, true, false, 2, "hw-default", "", std::nullopt);
+ }
+
+ /**
+ * @brief Build microphone parameters matching the stereo test layout.
+ * @return Capture parameters for a 5 ms stereo frame at 48 kHz.
+ */
+ platf::microphone_params_t make_mic_params() {
+ platf::microphone_params_t params {};
+ params.mapping = nullptr;
+ params.channels = 2;
+ params.sample_rate = 48000;
+ params.frame_size = 240;
+ params.continuous_audio = false;
+ params.host_audio_enabled = false;
+ return params;
+ }
+} // namespace
+
+/**
+ * @brief The capture-only path must capture without swapping the host default.
+ *
+ * Fail-without-fix: if the dispatch branches swap, a keep-default session
+ * calls set_sink() and steals the host default it promised to leave alone;
+ * the missing capture_sink() call below is that regression.
+ */
+TEST(CaptureSinkDispatchTest, CapturePathUsesCaptureSink) {
+ recording_audio_control_t control;
+ const auto routing = make_capture_routing();
+ ASSERT_FALSE(routing.swap_at_startup);
+
+ EXPECT_TRUE(select_audio_capture_sink(control, routing));
+ EXPECT_EQ(control.call_index("capture_sink:hw-default"), 0U);
+ EXPECT_EQ(control.call_index("set_sink"), control.calls.size());
+}
+
+/**
+ * @brief A failed capture-only selection must abort before any refresh.
+ *
+ * Fail-without-fix: if select_audio_capture_sink() returns true on a
+ * capture_sink() failure, capture() proceeds to refresh and microphone
+ * creation against a sink that was never selected, capturing silence (or the
+ * wrong endpoint) instead of aborting startup.
+ */
+TEST(CaptureSinkDispatchTest, CaptureFailureAbortsStartup) {
+ recording_audio_control_t control;
+ control.capture_sink_status = -1;
+
+ EXPECT_FALSE(select_audio_capture_sink(control, make_capture_routing()));
+ EXPECT_EQ(control.call_index("set_sink"), control.calls.size());
+ EXPECT_EQ(control.call_index("set_capture_target"), control.calls.size());
+}
+
+/**
+ * @brief The swap path must swap the host default instead of capturing.
+ *
+ * Fail-without-fix: if the dispatch branches swap, a quiet-streaming session
+ * calls capture_sink() and never moves applications onto the virtual sink, so
+ * the host keeps playing aloud while the client captures the wrong endpoint.
+ */
+TEST(CaptureSinkDispatchTest, SwapPathUsesSetSink) {
+ recording_audio_control_t control;
+ const auto routing = make_swap_routing();
+ ASSERT_TRUE(routing.swap_at_startup);
+ ASSERT_TRUE(routing.restore_at_teardown);
+
+ EXPECT_TRUE(select_audio_capture_sink(control, routing));
+ EXPECT_EQ(control.call_index("set_sink:" + routing.target), 0U);
+ EXPECT_EQ(control.call_index("capture_sink"), control.calls.size());
+}
+
+/**
+ * @brief A failed swap must abort before any refresh.
+ *
+ * Fail-without-fix: if select_audio_capture_sink() returns true on a
+ * set_sink() failure, capture() records a restore flag for a swap that never
+ * happened and then captures the unswapped default, stranding teardown
+ * symmetry and streaming the wrong source.
+ */
+TEST(CaptureSinkDispatchTest, SwapFailureAbortsStartup) {
+ recording_audio_control_t control;
+ control.set_sink_status = -1;
+
+ EXPECT_FALSE(select_audio_capture_sink(control, make_swap_routing()));
+ EXPECT_EQ(control.call_index("capture_sink"), control.calls.size());
+ EXPECT_EQ(control.call_index("set_capture_target"), control.calls.size());
+}
+
+/**
+ * @brief A swap with nothing to restore must skip the sink call entirely.
+ *
+ * Fail-without-fix: if the no-restore skip is dropped, startup reasserts the
+ * host default as a swap even though the target already is the host sink,
+ * needlessly disturbing routing (and any default-device watchers) for a no-op.
+ */
+TEST(CaptureSinkDispatchTest, SwapWithoutRestoreSkipsSinkCall) {
+ recording_audio_control_t control;
+ const auto routing = make_swap_without_restore_routing();
+ ASSERT_TRUE(routing.swap_at_startup);
+ ASSERT_FALSE(routing.restore_at_teardown);
+
+ EXPECT_TRUE(select_audio_capture_sink(control, routing));
+ EXPECT_TRUE(control.calls.empty());
+}
+
+/**
+ * @brief The endpoint target must be recorded ahead of microphone creation.
+ *
+ * Fail-without-fix: if the guard skips the refresh (or creates the microphone
+ * first), the backend captures a stale target from a previous session instead
+ * of this session's intent, and the set-before-microphone ordering below breaks.
+ */
+TEST(CaptureRefreshTest, EndpointTargetIsRecordedBeforeMicrophone) {
+ recording_audio_control_t control;
+ std::mutex mutex;
+ session_capture_target_t target {control, platf::audio_capture_intent_e::host_and_client, mutex};
+
+ auto mic = target.create_microphone(make_mic_params());
+
+ EXPECT_TRUE(static_cast(mic));
+ EXPECT_TRUE(target.recorded());
+ EXPECT_EQ(control.set_intent, platf::audio_capture_intent_e::host_and_client);
+ EXPECT_EQ(control.set_process_id, 0u);
+ EXPECT_LT(control.call_index("set_capture_target"), control.call_index("microphone"));
+}
+
+/**
+ * @brief Endpoint capture must record PID 0 for every intent.
+ *
+ * Fail-without-fix: if the guard records anything but the endpoint target,
+ * a session captures a process it never selected instead of the endpoint,
+ * defeating silence or the configured sink pin.
+ */
+TEST(CaptureRefreshTest, EndpointCasesRecordZeroPid) {
+ using intent = platf::audio_capture_intent_e;
+
+ for (const auto case_intent : {intent::host_and_client, intent::client_only, intent::pinned_sink}) {
+ recording_audio_control_t control;
+ std::mutex mutex;
+ session_capture_target_t target {control, case_intent, mutex};
+
+ auto mic = target.create_microphone(make_mic_params());
+
+ EXPECT_TRUE(static_cast(mic));
+ EXPECT_TRUE(target.recorded());
+ EXPECT_EQ(control.set_process_id, 0u);
+ EXPECT_EQ(control.set_intent, case_intent);
+ EXPECT_LT(control.call_index("set_capture_target"), control.call_index("microphone"));
+ }
+}
+
+/**
+ * @brief A microphone failure must still leave the refreshed target behind for teardown.
+ *
+ * Fail-without-fix: if the guard only records the target on microphone
+ * success, a failed creation leaks the shared target (no teardown release
+ * ever runs for it) and the next session inherits a target this session
+ * recorded but never owned.
+ */
+TEST(CaptureRefreshTest, MicrophoneFailureStillRecordsTarget) {
+ recording_audio_control_t control;
+ control.fail_microphone = true;
+ std::mutex mutex;
+
+ {
+ session_capture_target_t target {control, platf::audio_capture_intent_e::host_and_client, mutex};
+
+ EXPECT_FALSE(static_cast(target.create_microphone(make_mic_params())));
+ EXPECT_TRUE(target.recorded());
+ EXPECT_EQ(control.set_process_id, 0u);
+ }
+
+ // The failed refresh still owns a target, so scope exit must release it.
+ EXPECT_EQ(control.clear_intent, platf::audio_capture_intent_e::host_and_client);
+ EXPECT_EQ(control.clear_process_id, 0u);
+}
+
+/**
+ * @brief The restore flag must follow the routing decision in both modes.
+ *
+ * capture() assigns routing.restore_at_teardown directly, so this pins the
+ * decision values that flow into that assignment, including the
+ * swap-without-restore edge.
+ *
+ * Fail-without-fix: if the capture-only routing ever reports restore=true,
+ * teardown restores a sink that was never swapped, yanking the user's live
+ * default; if the swap routing reports restore=false, teardown strands the
+ * virtual sink as the host default after the stream ends.
+ */
+TEST(CaptureRestoreTest, RecordsRoutingRestoreDecision) {
+ audio_ctx_t ctx {};
+ ctx.restore_sink = true;
+ ctx.restore_sink = make_capture_routing().restore_at_teardown;
+ EXPECT_FALSE(ctx.restore_sink);
+
+ ctx.restore_sink = make_swap_routing().restore_at_teardown;
+ EXPECT_TRUE(ctx.restore_sink);
+
+ ctx.restore_sink = make_swap_without_restore_routing().restore_at_teardown;
+ EXPECT_FALSE(ctx.restore_sink);
+}
+
+/**
+ * @brief Teardown without a refresh must leave the shared target untouched.
+ *
+ * Fail-without-fix: if the guard clears unconditionally, a session that
+ * aborted before any refresh (for example a failed sink selection) wipes a
+ * survivor session's live target on its way out.
+ */
+TEST(CaptureReleaseTest, SkipsClearWhenNothingRecorded) {
+ recording_audio_control_t control;
+ std::mutex mutex;
+
+ {
+ session_capture_target_t target {control, platf::audio_capture_intent_e::host_and_client, mutex};
+ EXPECT_FALSE(target.recorded());
+ }
+
+ EXPECT_TRUE(control.calls.empty());
+}
+
+/**
+ * @brief Teardown after a refresh must release exactly the recorded target.
+ *
+ * Fail-without-fix: if the guard releases a stale target instead of the last
+ * recorded one, the backend keeps the dead session's target (leaking capture
+ * state) or wipes a survivor's newer target.
+ */
+TEST(CaptureReleaseTest, ClearsRecordedTarget) {
+ recording_audio_control_t control;
+ std::mutex mutex;
+
+ {
+ session_capture_target_t target {control, platf::audio_capture_intent_e::host_and_client, mutex};
+ auto mic = target.create_microphone(make_mic_params());
+ ASSERT_TRUE(static_cast(mic));
+ // Release lands on scope exit, so only the refresh and creation run here.
+ ASSERT_EQ(control.calls.size(), 2U);
+ }
+
+ ASSERT_EQ(control.calls.size(), 3U);
+ EXPECT_EQ(control.calls[2], "clear_capture_target");
+ EXPECT_EQ(control.clear_intent, platf::audio_capture_intent_e::host_and_client);
+ EXPECT_EQ(control.clear_process_id, 0u);
+}
+
+/**
+ * @brief The startup sequence must dispatch, refresh, create, and release in order.
+ *
+ * Fail-without-fix: a dispatch-branch swap shows up as the wrong sink call
+ * here, a dropped refresh as a missing set_capture_target before microphone(),
+ * and a leaked guard as a missing trailing clear_capture_target.
+ */
+TEST(CaptureOrchestrationTest, StartupSequenceRunsDispatchRefreshCreateAndRelease) {
+ for (const auto &routing : {make_capture_routing(), make_swap_routing()}) {
+ recording_audio_control_t control;
+ std::mutex mutex;
+ audio_ctx_t ctx {};
+
+ {
+ session_capture_target_t target {control, platf::audio_capture_intent_e::host_and_client, mutex};
+
+ ctx.restore_sink = routing.restore_at_teardown;
+ EXPECT_EQ(ctx.restore_sink, routing.restore_at_teardown);
+ ASSERT_TRUE(select_audio_capture_sink(control, routing));
+ auto mic = target.create_microphone(make_mic_params());
+ ASSERT_TRUE(static_cast(mic));
+ ASSERT_EQ(control.calls.size(), 3U);
+ }
+
+ const std::string expected_sink_call = routing.swap_at_startup ? "set_sink:" + routing.target : "capture_sink:" + routing.target;
+ ASSERT_EQ(control.calls.size(), 4U);
+ EXPECT_EQ(control.calls[0], expected_sink_call);
+ EXPECT_EQ(control.calls[1], "set_capture_target");
+ EXPECT_EQ(control.calls[2], "microphone");
+ EXPECT_EQ(control.calls[3], "clear_capture_target");
+ EXPECT_EQ(control.clear_process_id, 0u);
+ }
+}
+
+/**
+ * @brief The parameter-bundle microphone() must forward every field to the positional override.
+ *
+ * Fail-without-fix: if the forwarding overload drops, reorders, or mistypes a
+ * field, backends capture the wrong layout (channels, rate, frame size) or the
+ * wrong mode (continuous, host audio) while the call still succeeds.
+ */
+TEST(AudioControlAdapterTest, StructMicrophoneForwardsEveryField) {
+ recording_audio_control_t control;
+ platf::audio_control_t &base = control;
+ const std::array mapping {0, 1, 4, 5, 2, 3};
+ const platf::microphone_params_t params {mapping.data(), 6, 48000, 480, true, true};
+
+ auto mic = base.microphone(params);
+
+ EXPECT_TRUE(static_cast(mic));
+ ASSERT_EQ(control.calls.size(), 1U);
+ EXPECT_EQ(control.calls[0], "microphone");
+ EXPECT_EQ(control.mic_mapping, mapping.data());
+ EXPECT_EQ(control.mic_channels, 6);
+ EXPECT_EQ(control.mic_sample_rate, 48000u);
+ EXPECT_EQ(control.mic_frame_size, 480u);
+ EXPECT_TRUE(control.mic_continuous_audio);
+ EXPECT_TRUE(control.mic_host_audio_enabled);
+}
+
+namespace {
+ /**
+ * @brief Minimal backend that stores through the shared base record.
+ *
+ * Drives the protected opt-in helpers through the production virtuals so
+ * the centralized sink storage is pinned without platform hardware. Models
+ * the Linux call pattern (record-only `capture_sink()`, record-on-success
+ * `set_sink()`).
+ */
+ class recorded_audio_control_t: public platf::audio_control_t {
+ public:
+ int set_sink(const std::string &sink) override {
+ record_capture_sink(sink);
+ return 0;
+ }
+
+ bool supports_keep_default_sink() const override {
+ return true;
+ }
+
+ int capture_sink(const std::string &sink) override {
+ return record_keep_default_capture_sink(sink);
+ }
+
+ // Keep the params-bundle overload visible: the positional override below would otherwise hide it.
+ using platf::audio_control_t::microphone;
+
+ std::unique_ptr microphone(const std::uint8_t *, int, std::uint32_t, std::uint32_t, bool, bool) override {
+ return std::make_unique();
+ }
+
+ bool is_sink_available(const std::string &) override {
+ return true;
+ }
+
+ std::optional sink_info() override {
+ return std::nullopt;
+ }
+
+ using platf::audio_control_t::snapshot_recorded_sink;
+ };
+
+ /**
+ * @brief Backend modeling the macOS no-op capture contract.
+ *
+ * Mirrors `macos_audio_control_t`: `capture_sink()` never records, and the
+ * inherited `set_capture_target()`/`clear_capture_target()` no-ops leave
+ * the shared sink record alone.
+ */
+ class macos_like_audio_control_t: public platf::audio_control_t {
+ public:
+ int set_sink(const std::string &) override {
+ return 0;
+ }
+
+ bool supports_keep_default_sink() const override {
+ return true;
+ }
+
+ int capture_sink(const std::string &) override {
+ return 0;
+ }
+
+ // Keep the params-bundle overload visible: the positional override below would otherwise hide it.
+ using platf::audio_control_t::microphone;
+
+ std::unique_ptr microphone(const std::uint8_t *, int, std::uint32_t, std::uint32_t, bool, bool) override {
+ return nullptr;
+ }
+
+ bool is_sink_available(const std::string &) override {
+ return true;
+ }
+
+ std::optional sink_info() override {
+ return std::nullopt;
+ }
+
+ using platf::audio_control_t::snapshot_recorded_sink;
+ };
+} // namespace
+
+/**
+ * @brief The shared sink record must start empty before any session records.
+ *
+ * Fail-without-fix: if the base record is not value-initialized, the first
+ * microphone() consumes a garbage sink instead of falling back to the
+ * configured or default sink.
+ */
+TEST(BaseRecordTest, RecordedSinkStartsEmpty) {
+ recorded_audio_control_t control;
+ EXPECT_TRUE(control.snapshot_recorded_sink().empty());
+}
+
+/**
+ * @brief A recorded sink snapshot must stay stable while the shared value changes.
+ *
+ * Fail-without-fix: if snapshots alias the shared string, the
+ * default-endpoint callback reasserts a sink another session rewrote
+ * concurrently instead of the copy taken at install time.
+ */
+TEST(BaseRecordTest, CaptureSinkRecordIsStableAcrossRewrite) {
+ recorded_audio_control_t control;
+ EXPECT_EQ(control.capture_sink("sink-a"), 0);
+ const auto snapshot = control.snapshot_recorded_sink();
+ EXPECT_EQ(control.capture_sink("sink-b"), 0);
+ EXPECT_EQ(snapshot, "sink-a");
+ EXPECT_EQ(control.snapshot_recorded_sink(), "sink-b");
+}
+
+/**
+ * @brief The swap path must overwrite the same shared record the capture path reads.
+ *
+ * Fail-without-fix: if `set_sink()` keeps a separate store, a swap session
+ * captures the previously recorded sink instead of the swapped one.
+ */
+TEST(BaseRecordTest, SetSinkOverwritesRecordedSink) {
+ recorded_audio_control_t control;
+ EXPECT_EQ(control.capture_sink("capture-sink"), 0);
+ EXPECT_EQ(control.set_sink("swapped-sink"), 0);
+ EXPECT_EQ(control.snapshot_recorded_sink(), "swapped-sink");
+}
+
+/**
+ * @brief Concurrent sessions must always snapshot a consistent record.
+ *
+ * Fail-without-fix: without the base mutex, concurrent record and snapshot
+ * calls tear the sink string. Completing with every snapshot reading a
+ * written value is the regression pin. The loop also writes through
+ * `set_sink()`, the exact production call the default-endpoint callback
+ * makes, so the callback-to-record path is pinned under the same lock.
+ */
+TEST(BaseRecordTest, ConcurrentControlAccessStaysConsistent) {
+ recorded_audio_control_t control;
+ std::atomic consistent {true};
+ const auto worker = [&](std::uint32_t pid) {
+ for (int i = 0; i < 50 && consistent.load(std::memory_order_relaxed); ++i) {
+ control.capture_sink("sink-" + std::to_string(pid));
+ if (control.snapshot_recorded_sink().compare(0, 5, "sink-") != 0) {
+ consistent.store(false, std::memory_order_relaxed);
+ }
+ if (control.set_sink("sink-" + std::to_string(pid)) != 0) {
+ consistent.store(false, std::memory_order_relaxed);
+ }
+ if (control.snapshot_recorded_sink().compare(0, 5, "sink-") != 0) {
+ consistent.store(false, std::memory_order_relaxed);
+ }
+ }
+ };
+ {
+ std::vector threads;
+ threads.reserve(4);
+ for (std::uint32_t pid = 1; pid <= 4; ++pid) {
+ threads.emplace_back(worker, pid);
+ }
+ }
+ EXPECT_TRUE(consistent.load(std::memory_order_relaxed));
+}
+
+/**
+ * @brief A macOS-style no-op backend must leave the shared record untouched.
+ *
+ * Fail-without-fix: if the base virtual defaults gain behavior, the by-design
+ * macOS no-op (which never calls the opt-in helpers) starts recording a sink
+ * that microphone() never consumes, stranding state for the next session.
+ */
+TEST(BaseRecordTest, MacOsLikeNoOpLeavesRecordUntouched) {
+ macos_like_audio_control_t control;
+ EXPECT_EQ(control.capture_sink("any-sink"), 0);
+ control.set_capture_target(platf::audio_capture_intent_e::host_and_client, 1234);
+ control.clear_capture_target(platf::audio_capture_intent_e::host_and_client, 1234);
+ EXPECT_TRUE(control.snapshot_recorded_sink().empty());
+}
+
+/**
+ * @brief The shared keep-default helper must record the sink and report success.
+ *
+ * Fail-without-fix: if `capture_sink()` stops routing through the shared
+ * helper, backend copies drift and one backend records a sink another path
+ * cannot see.
+ */
+TEST(BaseRecordTest, KeepDefaultHelperRecordsAndReturnsZero) {
+ recorded_audio_control_t control;
+ EXPECT_EQ(control.capture_sink("keep-default-sink"), 0);
+ EXPECT_EQ(control.snapshot_recorded_sink(), "keep-default-sink");
+}
diff --git a/tests/unit/test_config.cpp b/tests/unit/test_config.cpp
index f3bb7ceaf1c..9230d563109 100644
--- a/tests/unit/test_config.cpp
+++ b/tests/unit/test_config.cpp
@@ -428,3 +428,81 @@ INSTANTIATE_TEST_SUITE_P(
StreamResolutionCapCase {100, 100, 10000, 2, true, 100, 2}
)
);
+
+/**
+ * @brief Verify the keep_default_sink option parses into the audio configuration.
+ */
+TEST(KeepDefaultSinkConfigTest, ParsesEnabledAndDisabledValues) {
+ const bool original_keep_default_sink = config::audio.keep_default_sink;
+
+ config::apply_config_for_test("keep_default_sink = enabled\n");
+ EXPECT_TRUE(config::audio.keep_default_sink);
+
+ config::apply_config_for_test("keep_default_sink = disabled\n");
+ EXPECT_FALSE(config::audio.keep_default_sink);
+
+ config::audio.keep_default_sink = original_keep_default_sink;
+}
+
+/**
+ * @brief Verify a missing keep_default_sink key leaves the current value unchanged.
+ */
+TEST(KeepDefaultSinkConfigTest, MissingKeyLeavesValueUnchanged) {
+ const bool original_keep_default_sink = config::audio.keep_default_sink;
+
+ config::audio.keep_default_sink = true;
+ config::apply_config_for_test("");
+ EXPECT_TRUE(config::audio.keep_default_sink);
+
+ config::audio.keep_default_sink = false;
+ config::apply_config_for_test("");
+ EXPECT_FALSE(config::audio.keep_default_sink);
+
+ config::audio.keep_default_sink = original_keep_default_sink;
+}
+
+/**
+ * @brief Verify the deprecated external_audio key migrates only in its original scope.
+ *
+ * The legacy key only ever took effect on Windows with an explicit
+ * `audio_sink`, so the migration enables keep_default_sink only there.
+ */
+TEST(KeepDefaultSinkConfigTest, LegacyExternalAudioEnablesKeepDefaultSink) {
+ const bool original_keep_default_sink = config::audio.keep_default_sink;
+ const std::string original_sink = config::audio.sink;
+
+ config::audio.keep_default_sink = false;
+ config::apply_config_for_test("audio_sink = pinned-sink\nexternal_audio = enabled\n");
+#ifdef _WIN32
+ EXPECT_TRUE(config::audio.keep_default_sink);
+#else
+ EXPECT_FALSE(config::audio.keep_default_sink);
+#endif
+
+ config::audio.keep_default_sink = false;
+ config::audio.sink.clear();
+ config::apply_config_for_test("external_audio = enabled\n");
+ EXPECT_FALSE(config::audio.keep_default_sink);
+
+ config::audio.keep_default_sink = false;
+ config::apply_config_for_test("audio_sink = pinned-sink\nexternal_audio = disabled\n");
+ EXPECT_FALSE(config::audio.keep_default_sink);
+
+ config::audio.keep_default_sink = original_keep_default_sink;
+ config::audio.sink = original_sink;
+}
+
+/**
+ * @brief Verify an explicit keep_default_sink value wins over the legacy external_audio key.
+ */
+TEST(KeepDefaultSinkConfigTest, ExplicitKeepDefaultSinkWinsOverLegacyExternalAudio) {
+ const bool original_keep_default_sink = config::audio.keep_default_sink;
+
+ config::apply_config_for_test("external_audio = enabled\nkeep_default_sink = disabled\n");
+ EXPECT_FALSE(config::audio.keep_default_sink);
+
+ config::apply_config_for_test("external_audio = disabled\nkeep_default_sink = enabled\n");
+ EXPECT_TRUE(config::audio.keep_default_sink);
+
+ config::audio.keep_default_sink = original_keep_default_sink;
+}
diff --git a/tests/web/ConfigAudioCapture.test.js b/tests/web/ConfigAudioCapture.test.js
new file mode 100644
index 00000000000..26ef87ad9cf
--- /dev/null
+++ b/tests/web/ConfigAudioCapture.test.js
@@ -0,0 +1,173 @@
+import { flushPromises, mount } from '@vue/test-utils'
+import { ref } from 'vue'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('../../src_assets/common/assets/web/Navbar.vue', () => ({
+ default: { template: '
' },
+}))
+
+import Config from '../../src_assets/common/assets/web/Config.vue'
+
+async function mountConfig(serverConfig = {}, platform = 'windows') {
+ const fetchMock = vi.fn(async (url, options) => {
+ if (url === './api/config' && !options) {
+ return { json: async () => ({ platform, version: 'test', status: true, ...serverConfig }) }
+ }
+ if (url === './api/config' && options?.method === 'POST') {
+ return { status: 200, json: async () => ({ status: true }) }
+ }
+ throw new Error(`Unexpected fetch: ${url}`)
+ })
+ vi.stubGlobal('fetch', fetchMock)
+ window.HTMLElement.prototype.scrollIntoView = vi.fn()
+
+ const wrapper = mount(Config, {
+ attachTo: document.body,
+ global: {
+ mocks: { $t: key => key },
+ provide: {
+ platform: ref(platform),
+ i18n: { t: key => key },
+ },
+ stubs: {
+ General: true,
+ Inputs: true,
+ Network: true,
+ Files: true,
+ Advanced: true,
+ ContainerEncoders: true,
+ AdapterNameSelector: true,
+ DisplayOutputSelector: true,
+ DisplayDeviceOptions: true,
+ DisplayModesSettings: true,
+ Checkbox: false,
+ Check: true,
+ Plus: true,
+ },
+ },
+ })
+ await flushPromises()
+ return { wrapper, fetchMock }
+}
+
+function postsToConfig(fetchMock) {
+ return fetchMock.mock.calls.filter(([url, options]) => url === './api/config' && options?.method === 'POST')
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+ document.body.innerHTML = ''
+ delete window.HTMLElement.prototype.scrollIntoView
+})
+
+describe('config search reveal', () => {
+ it('reveals matches nested inside grouping fieldsets', async () => {
+ const { wrapper } = await mountConfig()
+ document.body.insertAdjacentHTML('beforeend',
+ '')
+
+ const input = document.getElementById('adapter_name')
+ document.querySelectorAll('.config-page .mb-3').forEach(el => {
+ el.style.display = 'none'
+ el.dataset.searchHidden = '1'
+ })
+ wrapper.vm.revealSearchMatch(input)
+
+ expect(document.getElementById('outer-group').style.display).toBe('')
+ expect(document.getElementById('outer-group').dataset.searchHidden).toBeUndefined()
+ expect(document.getElementById('unrelated-group').style.display).toBe('none')
+ wrapper.unmount()
+ })
+
+ it('stops revealing at the page boundary', async () => {
+ const { wrapper } = await mountConfig()
+ document.body.insertAdjacentHTML('beforeend',
+ '')
+ document.querySelectorAll('.config-page .mb-3').forEach(el => {
+ el.style.display = 'none'
+ el.dataset.searchHidden = '1'
+ })
+
+ wrapper.vm.revealSearchMatch(document.getElementById('solo'))
+
+ expect(document.getElementById('solo-group').style.display).toBe('')
+ expect(document.querySelector('.config-page').style.display).not.toBe('none')
+ wrapper.unmount()
+ })
+
+ it('leaves ancestors hidden by something other than search alone', async () => {
+ const { wrapper } = await mountConfig()
+ document.body.insertAdjacentHTML('beforeend',
+ '
')
+ // Hidden without the search flag: not this search's doing.
+ document.getElementById('plain-group').style.display = 'none'
+
+ wrapper.vm.revealSearchMatch(document.getElementById('deep'))
+
+ expect(document.getElementById('plain-group').style.display).toBe('none')
+ wrapper.unmount()
+ })
+})
+
+describe('save validation gate', () => {
+ it('blocks the POST and alerts when audio capture is invalid', async () => {
+ const { wrapper, fetchMock } = await mountConfig({ audio_sink: '', keep_default_sink: 'disabled' })
+ wrapper.vm.currentTab = 'av'
+ await wrapper.vm.$nextTick()
+ await wrapper.get('#audio_capture_target_specific').setValue(true)
+
+ const saved = await wrapper.vm.save()
+
+ expect(saved).toBe(false)
+ expect(postsToConfig(fetchMock)).toHaveLength(0)
+ expect(wrapper.vm.saveBlocked).toBe('audio_capture')
+ expect(wrapper.find('.alert-danger').exists()).toBe(true)
+ wrapper.unmount()
+ })
+
+ it('saves normally when audio capture is valid', async () => {
+ const { wrapper, fetchMock } = await mountConfig({ audio_sink: 'some-sink' })
+ wrapper.vm.currentTab = 'av'
+ await wrapper.vm.$nextTick()
+ await wrapper.get('#audio_capture_target_specific').setValue(true)
+ await wrapper.get('#audio_sink').setValue('named-target')
+
+ const saved = await wrapper.vm.save()
+
+ expect(saved).toBe(true)
+ expect(postsToConfig(fetchMock)).toHaveLength(1)
+ expect(wrapper.vm.saveBlocked).toBeNull()
+ wrapper.unmount()
+ })
+
+ it('saves normally when the audio tab is not mounted', async () => {
+ const { wrapper, fetchMock } = await mountConfig({ audio_sink: 'some-sink' })
+ expect(wrapper.vm.currentTab).not.toBe('av')
+
+ const saved = await wrapper.vm.save()
+
+ expect(saved).toBe(true)
+ expect(postsToConfig(fetchMock)).toHaveLength(1)
+ wrapper.unmount()
+ })
+
+ it('clears a previous block on the next save attempt', async () => {
+ const { wrapper } = await mountConfig({ audio_sink: '', keep_default_sink: 'disabled' })
+ wrapper.vm.currentTab = 'av'
+ await wrapper.vm.$nextTick()
+ await wrapper.get('#audio_capture_target_specific').setValue(true)
+ await wrapper.vm.save()
+ expect(wrapper.vm.saveBlocked).toBe('audio_capture')
+
+ await wrapper.get('#audio_sink').setValue('named-target')
+ await wrapper.vm.save()
+
+ expect(wrapper.vm.saveBlocked).toBeNull()
+ expect(wrapper.find('.alert-danger').exists()).toBe(false)
+ wrapper.unmount()
+ })
+})
diff --git a/tests/web/ConfigBool.test.js b/tests/web/ConfigBool.test.js
new file mode 100644
index 00000000000..277b45ca07c
--- /dev/null
+++ b/tests/web/ConfigBool.test.js
@@ -0,0 +1,13 @@
+import { describe, expect, it } from 'vitest'
+
+import { isConfigBoolEnabled } from '../../src_assets/common/assets/web/config_bool'
+
+describe('isConfigBoolEnabled', () => {
+ it.each([true, 1, 'true', 'yes', 'enable', 'enabled', 'on', '1', 'TRUE', 'On'])('treats %s as enabled', value => {
+ expect(isConfigBoolEnabled(value)).toBe(true)
+ })
+
+ it.each([false, 0, 'disabled', 'false', 'no', 'off', '0', '', undefined, null])('treats %s as disabled', value => {
+ expect(isConfigBoolEnabled(value)).toBe(false)
+ })
+})
diff --git a/tests/web/ConfigMigration.test.js b/tests/web/ConfigMigration.test.js
new file mode 100644
index 00000000000..a85b9314a2d
--- /dev/null
+++ b/tests/web/ConfigMigration.test.js
@@ -0,0 +1,98 @@
+import { flushPromises, shallowMount } from '@vue/test-utils'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('../../src_assets/common/assets/web/Navbar.vue', () => ({
+ default: { template: '
' },
+}))
+
+import Config from '../../src_assets/common/assets/web/Config.vue'
+
+async function mountConfig(serverConfig, platform = 'windows') {
+ const fetchMock = vi.fn(async (url, options) => {
+ if (url === './api/config' && !options) {
+ return { json: async () => ({ platform, version: 'test', status: true, ...serverConfig }) }
+ }
+ if (url === './api/config' && options?.method === 'POST') {
+ return { status: 200, json: async () => ({ status: true }) }
+ }
+ throw new Error(`Unexpected fetch: ${url}`)
+ })
+ vi.stubGlobal('fetch', fetchMock)
+
+ const wrapper = shallowMount(Config, {
+ global: {
+ mocks: { $t: key => key },
+ },
+ })
+ await flushPromises()
+ return { wrapper, fetchMock }
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals()
+ document.body.innerHTML = ''
+})
+
+describe('external_audio upgrade migration', () => {
+ it.each(['enabled', 'true', 'on', 'yes', '1', 'TRUE', 'On'])('maps legacy external_audio=%s to keep_default_sink', async legacyValue => {
+ const { wrapper } = await mountConfig({ external_audio: legacyValue, audio_sink: 'pinned-sink' })
+
+ expect(wrapper.vm.config.keep_default_sink).toBe('enabled')
+ expect(wrapper.vm.config).not.toHaveProperty('external_audio')
+ wrapper.unmount()
+ })
+
+ it('keeps the migrated value disabled when the legacy key is disabled', async () => {
+ const { wrapper } = await mountConfig({ external_audio: 'disabled' })
+
+ expect(wrapper.vm.config.keep_default_sink).toBe('disabled')
+ expect(wrapper.vm.config).not.toHaveProperty('external_audio')
+ wrapper.unmount()
+ })
+
+ it('lets an explicit keep_default_sink win over the legacy key', async () => {
+ const { wrapper } = await mountConfig({ external_audio: 'enabled', keep_default_sink: 'disabled' })
+
+ expect(wrapper.vm.config.keep_default_sink).toBe('disabled')
+ expect(wrapper.vm.config).not.toHaveProperty('external_audio')
+ wrapper.unmount()
+ })
+
+ it('migrates when keep_default_sink is present but empty', async () => {
+ const { wrapper } = await mountConfig({ external_audio: 'enabled', keep_default_sink: '', audio_sink: 'pinned-sink' })
+
+ expect(wrapper.vm.config.keep_default_sink).toBe('enabled')
+ expect(wrapper.vm.config).not.toHaveProperty('external_audio')
+ wrapper.unmount()
+ })
+
+ it('does not migrate on non-Windows platforms', async () => {
+ const { wrapper } = await mountConfig({ external_audio: 'enabled', audio_sink: 'pinned-sink' }, 'linux')
+
+ expect(wrapper.vm.config.keep_default_sink).toBe('disabled')
+ expect(wrapper.vm.config).not.toHaveProperty('external_audio')
+ wrapper.unmount()
+ })
+
+ it('does not migrate without an explicit audio_sink', async () => {
+ const { wrapper } = await mountConfig({ external_audio: 'enabled' })
+
+ expect(wrapper.vm.config.keep_default_sink).toBe('disabled')
+ expect(wrapper.vm.config).not.toHaveProperty('external_audio')
+ wrapper.unmount()
+ })
+
+ it('sends neither key when a migrated user unchecks and saves', async () => {
+ const { wrapper, fetchMock } = await mountConfig({ external_audio: 'enabled', audio_sink: 'pinned-sink' })
+
+ wrapper.vm.config.keep_default_sink = 'disabled'
+ await wrapper.vm.save()
+
+ const postCall = fetchMock.mock.calls.find(([, options]) => options?.method === 'POST')
+ expect(postCall).toBeDefined()
+ const sent = JSON.parse(postCall[1].body)
+ expect(sent).not.toHaveProperty('external_audio')
+ expect(sent).not.toHaveProperty('keep_default_sink')
+ wrapper.unmount()
+ })
+})
diff --git a/tests/web/ExternalAudio.test.js b/tests/web/ExternalAudio.test.js
deleted file mode 100644
index b921818dce9..00000000000
--- a/tests/web/ExternalAudio.test.js
+++ /dev/null
@@ -1,81 +0,0 @@
-import { mount } from '@vue/test-utils'
-import { afterEach, describe, expect, it, vi } from 'vitest'
-import { ref } from 'vue'
-
-import AudioVideo from '../../src_assets/common/assets/web/configs/tabs/AudioVideo.vue'
-import configTabs from '../../src_assets/common/assets/web/configs/config_tabs.json'
-import configDocumentation from '../../docs/configuration.md?raw'
-import configurationShortcuts from '../../docs/configuration.js?raw'
-
-function mountAudioVideo(platform) {
- const config = structuredClone(configTabs.find(tab => tab.id === 'av').options)
- const wrapper = mount(AudioVideo, {
- props: { platform, config },
- global: {
- mocks: { $t: key => key },
- provide: {
- platform: ref(platform),
- i18n: { t: key => key },
- },
- stubs: {
- AdapterNameSelector: true,
- DisplayOutputSelector: true,
- DisplayDeviceOptions: true,
- DisplayModesSettings: true,
- },
- },
- })
- return { wrapper, config }
-}
-
-afterEach(() => {
- vi.restoreAllMocks()
- document.body.innerHTML = ''
-})
-
-describe('externally managed audio configuration', () => {
- it('renders after the existing Windows audio controls and preserves its saved value', async () => {
- const { wrapper, config } = mountAudioVideo('windows')
- expect(wrapper.findAll('input').map(input => input.attributes('id'))).toEqual([
- 'audio_sink',
- 'virtual_sink',
- 'install_steam_audio_drivers',
- 'stream_audio',
- 'external_audio',
- ])
- expect(config.external_audio).toBe('disabled')
- expect(wrapper.get('#external_audio').element.checked).toBe(false)
- await wrapper.get('#external_audio').setValue(true)
- expect(config.external_audio).toBe('enabled')
- await wrapper.get('#external_audio').setValue(false)
- expect(config.external_audio).toBe('disabled')
- wrapper.unmount()
- })
-
- it.each(['linux', 'freebsd', 'macos'])('keeps the Windows-only option hidden on %s', platform => {
- const { wrapper } = mountAudioVideo(platform)
- expect(wrapper.find('#external_audio').exists()).toBe(false)
- expect(wrapper.find('#stream_audio').exists()).toBe(true)
- wrapper.unmount()
- })
-
- it('provides the standard documentation table and a working configuration shortcut', () => {
- const section = configDocumentation.split('### external_audio\n')[1].split('\n### ')[0]
- // Doxygen emits configuration headings as h2 and gives tables this class.
- document.body.innerHTML = ' '
- + 'external_audio ' + section.replace('', '')
- const rows = [...document.querySelectorAll('tr')]
- expect(rows.map(row => row.cells[0].textContent.trim())).toEqual(['Description', 'Default', 'Example'])
- expect(rows[0].textContent).toContain('This option is only supported on Windows.')
- expect(rows[1].textContent).toContain('disabled')
- expect(rows[2].textContent).toContain('external_audio = enabled')
-
- new Function('document', configurationShortcuts)(document)
- document.dispatchEvent(new Event('DOMContentLoaded'))
- const button = document.querySelector('.open-button')
- expect(button.textContent).toBe('Open configuration')
- const open = vi.spyOn(window, 'open').mockImplementation(() => null)
- button.click()
- expect(open).toHaveBeenCalledWith('https://localhost:47990/config/#external_audio', '_blank', 'noopener')
- })
-})
diff --git a/tests/web/KeepDefaultSink.test.js b/tests/web/KeepDefaultSink.test.js
new file mode 100644
index 00000000000..dd6ec83296e
--- /dev/null
+++ b/tests/web/KeepDefaultSink.test.js
@@ -0,0 +1,360 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import configDocumentation from '../../docs/configuration.md?raw'
+import configurationShortcuts from '../../docs/configuration.js?raw'
+import { mountAudioVideo } from './audioVideoMount.js'
+import en from '../../src_assets/common/assets/web/public/assets/locale/en.json'
+
+afterEach(() => {
+ vi.restoreAllMocks()
+ document.body.innerHTML = ''
+})
+
+describe('keep default sink configuration', () => {
+ it.each(['windows', 'linux', 'macos', 'freebsd'])('renders the capture target choices on %s', async platform => {
+ const { wrapper, config } = mountAudioVideo(platform)
+ expect(wrapper.find('#keep_default_sink').exists()).toBe(true)
+ expect(wrapper.find('#external_audio').exists()).toBe(false)
+ expect(wrapper.text()).toContain('config.audio_capture_target_silent')
+ expect(wrapper.text()).toContain('config.audio_capture_target_current')
+ expect(wrapper.text()).toContain('config.audio_capture_target_specific')
+
+ const expectInsight = choice => {
+ const insights = wrapper.findAll('#audio_capture_how_it_works')
+ expect(insights).toHaveLength(1)
+ expect(insights[0].text()).toContain('config.audio_capture_how_it_works')
+ const ownerSunshine = choice === 'specific' && wrapper.find('#audio_capture_owner_sunshine').exists()
+ && wrapper.get('#audio_capture_owner_sunshine').element.checked
+ const expectedKey = ownerSunshine ? 'specific_sunshine' : choice
+ expect(insights[0].text()).toContain(`config.audio_capture_target_${expectedKey}_desc_${platform}`)
+ for (const otherChoice of ['silent', 'current', 'specific', 'specific_sunshine'].filter(candidate => candidate !== expectedKey)) {
+ expect(insights[0].text()).not.toContain(`config.audio_capture_target_${otherChoice}_desc_${platform}`)
+ }
+ for (const other of ['windows', 'linux', 'macos', 'freebsd'].filter(candidate => candidate !== platform)) {
+ expect(insights[0].text()).not.toContain(`config.audio_capture_target_${expectedKey}_desc_${other}`)
+ }
+ }
+
+ if (platform === 'macos') {
+ expect(wrapper.get('#audio_capture_target_silent').element.disabled).toBe(true)
+ expect(wrapper.get('#audio_capture_target_silent').element.checked).toBe(false)
+ expect(wrapper.text()).toContain('config.audio_capture_target_silent_desc_macos')
+ expect(wrapper.get('#audio_capture_target_current').element.checked).toBe(true)
+ expectInsight('current')
+ // A blank sink mounts as Play on this PC here, so mount syncs the saved keys to match.
+ expect(config.keep_default_sink).toBe('enabled')
+ expect(config.audio_sink).toBe('')
+ } else {
+ expect(wrapper.get('#audio_capture_target_silent').element.checked).toBe(true)
+ expectInsight('silent')
+ expect(config.keep_default_sink).toBe('disabled')
+ expect(config.audio_sink).toBe('')
+
+ await wrapper.get('#audio_capture_target_current').setValue(true)
+ expectInsight('current')
+ expect(config.keep_default_sink).toBe('enabled')
+ expect(config.audio_sink).toBe('')
+ expect(wrapper.get('#audio_sink').element.disabled).toBe(true)
+ }
+
+ await wrapper.get('#audio_capture_target_specific').setValue(true)
+ expectInsight('specific')
+ // This flow enters Custom from Play on this PC too, so self is the owner.
+ expect(config.keep_default_sink).toBe('enabled')
+ if (platform !== 'macos') {
+ expect(wrapper.get('#audio_capture_owner_self').element.checked).toBe(true)
+ }
+ expect(wrapper.get('#audio_sink').element.disabled).toBe(false)
+ await wrapper.get('#audio_sink').setValue('named-target')
+ expect(config.audio_sink).toBe('named-target')
+ expect(config.keep_default_sink).toBe('enabled')
+
+ if (platform !== 'macos') {
+ await wrapper.get('#audio_capture_target_silent').setValue(true)
+ expectInsight('silent')
+ expect(config.keep_default_sink).toBe('disabled')
+ expect(config.audio_sink).toBe('')
+ expect(wrapper.get('#audio_sink').element.disabled).toBe(true)
+ expect(wrapper.findAll('#audio_sink')).toHaveLength(1)
+ expect(wrapper.get('#audio_sink').element.value).toBe('named-target')
+ expect(wrapper.get('#audio_capture_effective_target').text()).toContain(`config.audio_capture_effective_target_silent_${platform}`)
+ expect(wrapper.get('#audio_capture_effective_target').text()).toContain('config.audio_capture_effective_retained')
+ expect(wrapper.find('#audio_capture_owner_sunshine').exists()).toBe(false)
+
+ await wrapper.get('#audio_capture_target_specific').setValue(true)
+ expectInsight('specific')
+ expect(wrapper.get('#audio_sink').element.value).toBe('named-target')
+ expect(config.audio_sink).toBe('named-target')
+ } else {
+ expect(wrapper.text()).toContain('config.audio_capture_target_silent_desc_macos')
+ }
+ wrapper.unmount()
+ })
+
+ it('renders only the shared audio choices on Windows', () => {
+ const { wrapper } = mountAudioVideo('windows')
+ expect(wrapper.findAll('input').map(input => input.attributes('id'))).toEqual([
+ 'stream_audio',
+ 'audio_capture_target_silent',
+ 'audio_capture_target_current',
+ 'audio_capture_target_specific',
+ 'audio_sink',
+ 'virtual_sink',
+ 'install_steam_audio_drivers',
+ ])
+ wrapper.unmount()
+ })
+
+ it('keeps a manually routed null sink editable as the specific target', async () => {
+ const { wrapper, config } = mountAudioVideo('linux')
+ await wrapper.get('#audio_capture_target_specific').setValue(true)
+ await wrapper.get('#audio_capture_owner_self').setValue(true)
+ await wrapper.get('#audio_sink').setValue('sink-sunshine-stereo')
+ expect(config.keep_default_sink).toBe('enabled')
+ expect(config.audio_sink).toBe('sink-sunshine-stereo')
+ expect(wrapper.get('#audio_sink').element.disabled).toBe(false)
+ expect(wrapper.get('#audio_sink').element.value).toBe('sink-sunshine-stereo')
+ wrapper.unmount()
+ })
+
+ it('mounts a legacy disabled named sink as Custom with Sunshine as routing owner', async () => {
+ const { wrapper, config } = mountAudioVideo('linux', { audio_sink: 'legacy-sink', keep_default_sink: 'disabled' })
+ expect(wrapper.get('#audio_capture_target_specific').element.checked).toBe(true)
+ expect(wrapper.get('#audio_capture_owner_sunshine').element.checked).toBe(true)
+ expect(config.keep_default_sink).toBe('disabled')
+ expect(config.audio_sink).toBe('legacy-sink')
+ await wrapper.get('#audio_sink').setValue('renamed-sink')
+ expect(config.keep_default_sink).toBe('disabled')
+ expect(config.audio_sink).toBe('renamed-sink')
+ wrapper.unmount()
+ })
+
+ it('mounts a legacy enabled named sink as Custom with self as routing owner', () => {
+ const { wrapper, config } = mountAudioVideo('windows', { audio_sink: 'legacy-sink', keep_default_sink: 'enabled' })
+ expect(wrapper.get('#audio_capture_target_specific').element.checked).toBe(true)
+ expect(wrapper.get('#audio_capture_owner_self').element.checked).toBe(true)
+ expect(config.keep_default_sink).toBe('enabled')
+ expect(config.audio_sink).toBe('legacy-sink')
+ wrapper.unmount()
+ })
+
+ it('defaults Custom entered directly from Quiet to Sunshine routing', async () => {
+ const { wrapper, config } = mountAudioVideo('linux')
+ await wrapper.get('#audio_capture_target_specific').setValue(true)
+ expect(wrapper.get('#audio_capture_owner_sunshine').element.checked).toBe(true)
+ expect(config.keep_default_sink).toBe('disabled')
+ await wrapper.get('#audio_sink').setValue('named-target')
+ expect(config.keep_default_sink).toBe('disabled')
+ expect(config.audio_sink).toBe('named-target')
+ wrapper.unmount()
+ })
+
+ it('defaults Custom entered from Play on this PC to self routing', async () => {
+ const { wrapper, config } = mountAudioVideo('linux')
+ await wrapper.get('#audio_capture_target_current').setValue(true)
+ await wrapper.get('#audio_capture_target_specific').setValue(true)
+ expect(wrapper.get('#audio_capture_owner_self').element.checked).toBe(true)
+ expect(config.keep_default_sink).toBe('enabled')
+ wrapper.unmount()
+ })
+
+ it('flips only keep_default_sink when the routing owner changes', async () => {
+ const { wrapper, config } = mountAudioVideo('linux', { audio_sink: 'named-target', keep_default_sink: 'disabled' })
+ await wrapper.get('#audio_capture_owner_self').setValue(true)
+ expect(config.keep_default_sink).toBe('enabled')
+ expect(config.audio_sink).toBe('named-target')
+ await wrapper.get('#audio_capture_owner_sunshine').setValue(true)
+ expect(config.keep_default_sink).toBe('disabled')
+ expect(config.audio_sink).toBe('named-target')
+ wrapper.unmount()
+ })
+
+ it('disables the audio controls when Stream Audio is off', async () => {
+ const { wrapper } = mountAudioVideo('linux', { stream_audio: 'disabled' })
+ expect(wrapper.get('#audio_capture_target_silent').element.disabled).toBe(true)
+ expect(wrapper.get('#audio_capture_target_current').element.disabled).toBe(true)
+ expect(wrapper.get('#audio_capture_target_specific').element.disabled).toBe(true)
+ expect(wrapper.get('#audio_sink').element.disabled).toBe(true)
+ await wrapper.get('#stream_audio').setValue(true)
+ expect(wrapper.get('#audio_capture_target_silent').element.disabled).toBe(false)
+ expect(wrapper.get('#audio_capture_target_current').element.disabled).toBe(false)
+ wrapper.unmount()
+ })
+
+ it('warns when Custom device has no sink name', async () => {
+ const { wrapper } = mountAudioVideo('linux')
+ await wrapper.get('#audio_capture_target_specific').setValue(true)
+ expect(wrapper.get('#audio_sink').classes()).toContain('is-invalid')
+ expect(wrapper.text()).toContain('config.audio_capture_sink_needed')
+ await wrapper.get('#audio_sink').setValue('named-target')
+ expect(wrapper.get('#audio_sink').classes()).not.toContain('is-invalid')
+ wrapper.unmount()
+ })
+
+ it('shows outcome subtitles and both capture section titles', () => {
+ const { wrapper } = mountAudioVideo('linux')
+ expect(wrapper.find('#video_capture').exists()).toBe(true)
+ const audioSection = wrapper.get('#keep_default_sink').element
+ const videoSection = wrapper.get('#video_capture').element
+ expect(audioSection.compareDocumentPosition(videoSection) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
+ expect(wrapper.text()).toContain('config.video_capture')
+ expect(wrapper.text()).toContain('config.audio_capture_target_silent_outcome')
+ expect(wrapper.text()).toContain('config.audio_capture_target_current_outcome')
+ expect(wrapper.text()).toContain('config.audio_capture_target_specific_outcome')
+ wrapper.unmount()
+ })
+
+ it('shows the Windows virtual sink as the Quiet effective target', () => {
+ const { wrapper } = mountAudioVideo('windows', { virtual_sink: 'My Virtual Sink' })
+ expect(wrapper.get('#audio_capture_effective_target').text()).toContain('My Virtual Sink')
+ wrapper.unmount()
+ })
+
+ it('hides the routing owner choice on macOS', async () => {
+ const { wrapper } = mountAudioVideo('macos', { audio_sink: 'BlackHole 2ch', keep_default_sink: 'enabled' })
+ expect(wrapper.find('#audio_capture_owner_sunshine').exists()).toBe(false)
+ expect(wrapper.find('#audio_capture_owner_self').exists()).toBe(false)
+ expect(wrapper.text()).toContain('config.audio_capture_target_specific_sunshine_desc_macos')
+ wrapper.unmount()
+ })
+
+ it('trims whitespace from a custom sink before saving it', async () => {
+ const { wrapper, config } = mountAudioVideo('linux')
+ await wrapper.get('#audio_capture_target_specific').setValue(true)
+ await wrapper.get('#audio_sink').setValue(' sink-sunshine-stereo ')
+ expect(config.audio_sink).toBe('sink-sunshine-stereo')
+ wrapper.unmount()
+ })
+
+ it('provides the standard documentation table and a working configuration shortcut', () => {
+ const section = configDocumentation.split('### keep_default_sink\n')[1].split('\n### ')[0]
+ // Doxygen emits configuration headings as h2 and gives tables this class.
+ document.body.innerHTML = ' '
+ + 'keep_default_sink ' + section.replace('', '')
+ const rows = [...document.querySelectorAll('tr')]
+ expect(rows.map(row => row.cells[0].textContent.trim())).toEqual(['Description', 'Default', 'Example'])
+ expect(rows[1].textContent).toContain('disabled')
+ expect(rows[2].textContent).toContain('keep_default_sink = enabled')
+
+ new Function('document', configurationShortcuts)(document)
+ document.dispatchEvent(new Event('DOMContentLoaded'))
+ const button = document.querySelector('.open-button')
+ expect(button.textContent).toBe('Open configuration')
+ const open = vi.spyOn(window, 'open').mockImplementation(() => null)
+ button.click()
+ expect(open).toHaveBeenCalledWith('https://localhost:47990/config/#keep_default_sink', '_blank', 'noopener')
+ })
+
+ it.each([
+ ['windows', 'silent', true],
+ ['windows', 'current', false],
+ ['windows', 'specific', false],
+ ['linux', 'silent', false],
+ ['macos', 'current', false],
+ ])('shows the virtual sink field on %s + %s only when expected (%s)', async (platform, target, visible) => {
+ const { wrapper } = mountAudioVideo(platform)
+ const radio = { silent: '#audio_capture_target_silent', current: '#audio_capture_target_current', specific: '#audio_capture_target_specific' }[target]
+ await wrapper.get(radio).setValue(true)
+ expect(wrapper.find('#virtual_sink').exists()).toBe(visible)
+ expect(wrapper.find('#install_steam_audio_drivers').exists()).toBe(visible)
+ if (visible) {
+ expect(wrapper.get('#virtual_sink').element.disabled).toBe(false)
+ }
+ wrapper.unmount()
+ })
+
+ it('disables the virtual sink and routing owner controls when Stream Audio is off', async () => {
+ const { wrapper } = mountAudioVideo('windows')
+ await wrapper.get('#audio_capture_target_silent').setValue(true)
+ expect(wrapper.get('#virtual_sink').element.disabled).toBe(false)
+ await wrapper.get('#stream_audio').setValue(false)
+ expect(wrapper.get('#virtual_sink').element.disabled).toBe(true)
+ expect(wrapper.get('#install_steam_audio_drivers').element.closest('fieldset').disabled).toBe(true)
+ await wrapper.get('#stream_audio').setValue(true)
+ expect(wrapper.get('#virtual_sink').element.disabled).toBe(false)
+ expect(wrapper.get('#install_steam_audio_drivers').element.closest('fieldset').disabled).toBe(false)
+ wrapper.unmount()
+ })
+
+ it('writes only the capture keys for each target and leaves the rest untouched', async () => {
+ const before = { virtual_sink: 'My Sink', stream_audio: 'enabled' }
+ const { wrapper, config } = mountAudioVideo('linux', { ...before, audio_sink: '', keep_default_sink: 'disabled' })
+ await wrapper.get('#audio_capture_target_current').setValue(true)
+ expect(config.keep_default_sink).toBe('enabled')
+ expect(config.audio_sink).toBe('')
+ await wrapper.get('#audio_capture_target_specific').setValue(true)
+ await wrapper.get('#audio_sink').setValue(' spaced-sink ')
+ expect(config.audio_sink).toBe('spaced-sink')
+ expect(config.virtual_sink).toBe(before.virtual_sink)
+ expect(config.stream_audio).toBe(before.stream_audio)
+ wrapper.unmount()
+ })
+
+ it('validates the capture selection for the save gate', async () => {
+ const { wrapper } = mountAudioVideo('linux')
+ expect(wrapper.vm.validateAudioCapture()).toBe(true)
+ await wrapper.get('#audio_capture_target_specific').setValue(true)
+ expect(wrapper.vm.validateAudioCapture()).toBe(false)
+ await wrapper.get('#audio_sink').setValue('named-target')
+ expect(wrapper.vm.validateAudioCapture()).toBe(true)
+ wrapper.unmount()
+ })
+
+ it('links the sink input to its validation message for assistive tech', async () => {
+ const { wrapper } = mountAudioVideo('linux')
+ await wrapper.get('#audio_capture_target_specific').setValue(true)
+ expect(wrapper.get('#audio_sink').attributes('aria-describedby')).toBe('audio_sink_feedback')
+ expect(wrapper.find('#audio_sink_feedback').exists()).toBe(true)
+ await wrapper.get('#audio_sink').setValue('named-target')
+ expect(wrapper.get('#audio_sink').attributes('aria-describedby')).toBeUndefined()
+ wrapper.unmount()
+ })
+})
+
+describe('audio sink platform guidance', () => {
+ it('describes silent, current, and specific capture in platform terms', () => {
+ expect(en.config.video_capture).toBe('Video Capture')
+ expect(en.config.audio_capture_target_silent_outcome).toBe('Silent on this PC, sound on the client')
+ expect(en.config.audio_capture_target_current_outcome).toBe('Sound on this PC and on the client')
+ expect(en.config.audio_capture_target_specific_outcome).toBe('Capture one exact device; you route apps to it')
+ expect(en.config.audio_capture_sink_needed).toBeDefined()
+ expect(en.config.audio_capture_sink_kept_hint).toBeDefined()
+ expect(en.config.audio_capture_target_silent).toBe('Quiet streaming')
+ expect(en.config.audio_capture_target_current).toBe('Play on this PC too')
+ expect(en.config.audio_capture_target_specific).toBe('Custom device')
+ expect(en.config.audio_capture_how_it_works).toBe('How this works')
+ expect(en.config.audio_sink_placeholder_linux).toBe('sink-sunshine-stereo')
+ expect(en.config.audio_sink_placeholder_freebsd).toBe('sink-sunshine-stereo')
+ expect(en.config.audio_sink_placeholder_macos).toBe('BlackHole 2ch')
+ expect(en.config.audio_sink_placeholder_windows).toBe('Speakers (High Definition Audio Device)')
+ for (const platform of ['linux', 'freebsd', 'macos', 'windows']) {
+ expect(en.config[`audio_sink_desc_${platform}`]).toBeDefined()
+ expect(en.config[`audio_capture_target_current_desc_${platform}`]).toBeDefined()
+ expect(en.config[`audio_capture_target_specific_desc_${platform}`]).toBeDefined()
+ }
+ for (const platform of ['linux', 'freebsd', 'windows']) {
+ expect(en.config[`audio_capture_target_silent_desc_${platform}`]).toMatch(/client hears/i)
+ }
+ expect(en.config.audio_capture_target_silent_desc_linux).toMatch(/null sink/)
+ expect(en.config.audio_capture_target_silent_desc_windows).toMatch(/Steam Streaming Speakers/)
+ expect(en.config.audio_capture_target_silent_desc_macos).toMatch(/BlackHole/)
+ expect(en.config.audio_capture_target_silent_desc_macos).toMatch(/Not available/)
+ expect(en.config.audio_capture_target_current_desc_macos).toMatch(/system audio tap/)
+ expect(en.config.audio_capture_owner_sunshine).toBe('Sunshine sets the device below as the default while streaming')
+ expect(en.config.audio_capture_owner_self).toBe('I route apps myself')
+ expect(en.config.audio_capture_effective_target).toBe('Streaming will capture')
+ expect(en.config.audio_capture_effective_retained).toBe('Custom name kept for Custom device only')
+ for (const platform of ['linux', 'freebsd', 'macos', 'windows']) {
+ expect(en.config[`audio_capture_target_specific_sunshine_desc_${platform}`]).toBeDefined()
+ expect(en.config[`audio_capture_effective_target_silent_${platform}`]).toBeDefined()
+ expect(en.config[`audio_capture_effective_target_current_${platform}`]).toBeDefined()
+ }
+ expect(en.config.audio_capture_effective_target_silent_linux).toMatch(/null sink/)
+ expect(en.config.audio_capture_target_specific_sunshine_desc_macos).toMatch(/Not applicable/)
+ expect(en.config.audio_sink_desc_macos).not.toMatch(/Soundflower/)
+ expect(en.config.virtual_sink_desc).toMatch(/Steam Streaming Speakers/)
+ expect(en.config.virtual_sink_desc).toMatch(/Leave blank/)
+ expect(en.config.install_steam_audio_drivers_desc).toMatch(/Windows only/)
+ expect(en.config.install_steam_audio_drivers_desc).toMatch(/Steam Streaming Speakers/)
+ })
+})
diff --git a/tests/web/audioVideoMount.js b/tests/web/audioVideoMount.js
new file mode 100644
index 00000000000..9e829f4d48f
--- /dev/null
+++ b/tests/web/audioVideoMount.js
@@ -0,0 +1,26 @@
+import { mount } from '@vue/test-utils'
+import { ref } from 'vue'
+
+import AudioVideo from '../../src_assets/common/assets/web/configs/tabs/AudioVideo.vue'
+import configTabs from '../../src_assets/common/assets/web/configs/config_tabs.json'
+
+export function mountAudioVideo(platform, overrides = {}) {
+ const config = { ...structuredClone(configTabs.find(tab => tab.id === 'av').options), ...overrides }
+ const wrapper = mount(AudioVideo, {
+ props: { platform, config },
+ global: {
+ mocks: { $t: key => key },
+ provide: {
+ platform: ref(platform),
+ i18n: { t: key => key },
+ },
+ stubs: {
+ AdapterNameSelector: true,
+ DisplayOutputSelector: true,
+ DisplayDeviceOptions: true,
+ DisplayModesSettings: true,
+ },
+ },
+ })
+ return { wrapper, config }
+}