From 2ffc3ae840f3d94ce30d86d8f267a8d7c2884c97 Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Wed, 7 Oct 2026 17:25:28 -0700 Subject: [PATCH 01/25] feat(audio): add keep_default_sink option to capture without swapping host default Adds the keep_default_sink config key controlling whether audio capture swaps the host default sink. - Config: new keep_default_sink key (default disabled) with validation. - Policy: when enabled, capture keeps the host default sink untouched; teardown restores only state this session changed. - UI: AudioVideo tab toggle plus locale strings. - Docs: configuration.md documents the new key. - Tests: config, audio, and linux audio unit coverage. --- docs/configuration.md | 25 ++++ src/audio.cpp | 23 +++- src/audio.h | 31 +++++ src/config.cpp | 2 + src/config.h | 1 + src/platform/common.h | 25 ++++ src/platform/linux/audio.cpp | 124 ++++++++++++++---- .../assets/web/configs/config_tabs.json | 1 + .../assets/web/configs/tabs/AudioVideo.vue | 8 ++ .../assets/web/public/assets/locale/en.json | 2 + tests/unit/platform/linux/test_audio.cpp | 81 +++++++++++- tests/unit/test_audio.cpp | 64 +++++++++ tests/unit/test_config.cpp | 32 +++++ 13 files changed, 385 insertions(+), 34 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 6024df7cdb6..cd6c36e65d7 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -973,6 +973,31 @@ consent prompt for directory ACLs, so the Web UI shows setup steps for correctin +### keep_default_sink + + + + + + + + + + + + + + +
Description + Capture the selected audio sink without changing the host default sink. When disabled, Sunshine sets the + selected sink as the host default sink while streaming. + @note{This option is only supported on Linux.} +
Default@code{} + disabled + @endcode
Example@code{} + keep_default_sink = enabled + @endcode
+ ### adapter_name diff --git a/src/audio.cpp b/src/audio.cpp index 00ddb12dc3d..577a3f74a96 100644 --- a/src/audio.cpp +++ b/src/audio.cpp @@ -211,10 +211,22 @@ namespace audio { // Only the first to start a session may change the default sink if (!ref->sink_flag->exchange(true, std::memory_order_acquire)) { - // If the selected sink is different than the current one, change sinks. - ref->restore_sink = ref->sink.host != *sink; - if (ref->restore_sink) { - if (control->set_sink(*sink)) { + // One decision point for swap-vs-capture: the recorded restore flag keeps + // teardown symmetric with startup on every platform, including backends + // that never learned the keep-default behavior. + const auto policy = resolve_sink_routing_policy(config::audio.keep_default_sink, control->supports_keep_default_sink()); + + if (policy.swap_at_startup) { + // If the selected sink is different than the current one, change sinks. + // Conjoin the policy's restore flag so teardown honors the same decision + // object startup used; the policy keeps both fields in agreement. + ref->restore_sink = policy.restore_at_teardown && ref->sink.host != *sink; + if (ref->restore_sink && control->set_sink(*sink)) { + return; + } + } else { + ref->restore_sink = false; + if (control->capture_sink(*sink)) { return; } } @@ -336,7 +348,8 @@ namespace audio { } void stop_audio_control(audio_ctx_t &ctx) { - // restore audio-sink if applicable + // restore audio-sink if applicable. Startup recorded whether it swapped; + // keep-default sessions never swap, so there is nothing to restore. if (!ctx.restore_sink) { return; } diff --git a/src/audio.h b/src/audio.h index a67092510ab..d866b925137 100644 --- a/src/audio.h +++ b/src/audio.h @@ -94,6 +94,37 @@ namespace audio { platf::sink_t sink; ///< Original sink captured before Sunshine switched devices. }; + /** + * @brief Startup/teardown sink behavior resolved for one capture session. + * + * Both fields always agree: a session either swaps the host default and + * restores it, or captures without touching it. Recording one decision at + * startup keeps teardown symmetric on every platform. + */ + struct sink_routing_policy_t { + bool swap_at_startup; ///< Whether startup may change the host default sink. + bool restore_at_teardown; ///< Whether teardown must restore the previous sink. + }; + + /** + * @brief Resolve the sink routing policy from the user request and backend capability. + * + * Pure function: no I/O, no global state. Backends that never learned the + * keep-default behavior get the historical swap-and-restore path even when + * the option is enabled, so enabling it can never strand a foreign default. + * + * @param keep_default_requested Value of config::audio.keep_default_sink. + * @param platform_supports_keep_default Value of platf::audio_control_t::supports_keep_default_sink(). + * @return Policy with matching startup and teardown behavior. + */ + [[nodiscard]] constexpr sink_routing_policy_t resolve_sink_routing_policy(bool keep_default_requested, bool platform_supports_keep_default) noexcept { + if (keep_default_requested && platform_supports_keep_default) { + return {false, false}; + } + + return {true, true}; + } + /** * @brief Byte buffer used for encoded audio packet payloads. */ diff --git a/src/config.cpp b/src/config.cpp index 77d2d466e3d..084f9e76ebc 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -804,6 +804,7 @@ namespace config { true, // stream audio true, // install_steam_drivers false, // external_audio + false, // keep_default_sink }; /** @@ -1811,6 +1812,7 @@ namespace config { bool_f(vars, "stream_audio", audio.stream); bool_f(vars, "install_steam_audio_drivers", audio.install_steam_drivers); bool_f(vars, "external_audio", audio.external_audio); + bool_f(vars, "keep_default_sink", audio.keep_default_sink); string_restricted_f(vars, "origin_web_ui_allowed", nvhttp.origin_web_ui_allowed, {"pc"sv, "lan"sv, "wan"sv}); diff --git a/src/config.h b/src/config.h index dc890e2ee40..692c159bbe5 100644 --- a/src/config.h +++ b/src/config.h @@ -242,6 +242,7 @@ namespace config { bool stream; ///< Enable audio streaming to clients bool install_steam_drivers; ///< Install Steam audio drivers for enhanced compatibility bool external_audio; ///< Windows capture-only mode; an external router owns endpoint defaults and formats. + bool keep_default_sink; ///< Capture the selected sink without changing the host default sink }; /** diff --git a/src/platform/common.h b/src/platform/common.h index b2616887be3..da97ccdb6a3 100644 --- a/src/platform/common.h +++ b/src/platform/common.h @@ -893,6 +893,31 @@ namespace platf { */ virtual int set_sink(const std::string &sink) = 0; + /** + * @brief Whether the backend can capture a sink without changing the host default. + * + * Backends that return true must implement capture_sink(). Legacy backends + * return false and keep the historical swap-and-restore behavior. + * + * @return True when capture_sink() captures without touching the host default. + */ + virtual bool supports_keep_default_sink() const { + return false; + } + + /** + * @brief Capture the given sink without changing the host default. + * + * Only called when supports_keep_default_sink() is true. The default + * implementation preserves legacy behavior by swapping via set_sink(). + * + * @param sink Audio sink name to capture. + * @return Status from selecting the capture sink. + */ + virtual int capture_sink(const std::string &sink) { + return set_sink(sink); + } + /** * @brief Create a microphone capture stream for the requested layout. * diff --git a/src/platform/linux/audio.cpp b/src/platform/linux/audio.cpp index f13e0db7cc2..2e82abb5248 100644 --- a/src/platform/linux/audio.cpp +++ b/src/platform/linux/audio.cpp @@ -333,11 +333,24 @@ namespace platf { ctx_t ctx; ///< PulseAudio threaded mainloop context. std::string requested_sink; ///< Requested sink. + static constexpr const char *stereo_name = "sink-sunshine-stereo"; ///< Persistent stereo null sink name. + static constexpr const char *surround51_name = "sink-sunshine-surround51"; ///< Persistent 5.1 null sink name. + static constexpr const char *surround71_name = "sink-sunshine-surround71"; ///< Persistent 7.1 null sink name. + + /** + * @brief Lifecycle state for one Sunshine null sink. + */ + struct null_sink_t { + std::uint32_t module = PA_INVALID_INDEX; ///< Owning PulseAudio module index, when module-backed. + bool present = false; ///< Sink exists in the graph (pre-existing or loaded by this session). + bool owned = false; ///< Loaded by this session; safe to unload on teardown. + }; + struct { - std::uint32_t stereo = PA_INVALID_INDEX; ///< PulseAudio module index for the stereo null sink. - std::uint32_t surround51 = PA_INVALID_INDEX; ///< PulseAudio module index for the 5.1 null sink. - std::uint32_t surround71 = PA_INVALID_INDEX; ///< PulseAudio module index for the 7.1 null sink. - } index; ///< PulseAudio module indexes for Sunshine-created null sinks. + null_sink_t stereo; ///< Stereo null sink lifecycle. + null_sink_t surround51; ///< 5.1 null sink lifecycle. + null_sink_t surround71; ///< 7.1 null sink lifecycle. + } index; ///< Per-sink lifecycle bookkeeping. std::unique_ptr> events; ///< Event queue receiving PulseAudio context state changes. std::unique_ptr> events_cb; ///< Callback that translates PulseAudio context updates into events. @@ -464,10 +477,6 @@ namespace platf { * @return Host and virtual sink names when the backend can report them. */ std::optional sink_info() override { - constexpr auto stereo = "sink-sunshine-stereo"; - constexpr auto surround51 = "sink-sunshine-surround51"; - constexpr auto surround71 = "sink-sunshine-surround71"; - auto alarm = safe::make_alarm(); sink_t sink; @@ -487,17 +496,29 @@ namespace platf { return; } - // Ensure Sunshine won't create a sink that already exists. - if (!std::strcmp(sink_info->name, stereo)) { - index.stereo = sink_info->owner_module; + // Adopt sinks that already exist (persistent PipeWire config or a live + // session): reuse them, but never unload what we didn't create. The + // present guard also keeps repeat sink_info() calls from demoting + // owned sinks to adopted. + if (!std::strcmp(sink_info->name, stereo_name)) { + if (!index.stereo.present) { + index.stereo.module = sink_info->owner_module; + index.stereo.present = true; + } ++nullcount; - } else if (!std::strcmp(sink_info->name, surround51)) { - index.surround51 = sink_info->owner_module; + } else if (!std::strcmp(sink_info->name, surround51_name)) { + if (!index.surround51.present) { + index.surround51.module = sink_info->owner_module; + index.surround51.present = true; + } ++nullcount; - } else if (!std::strcmp(sink_info->name, surround71)) { - index.surround71 = sink_info->owner_module; + } else if (!std::strcmp(sink_info->name, surround71_name)) { + if (!index.surround71.present) { + index.surround71.module = sink_info->owner_module; + index.surround71.present = true; + } ++nullcount; } @@ -520,29 +541,35 @@ namespace platf { auto sink_name = get_default_sink_name(); sink.host = sink_name; - if (index.stereo == PA_INVALID_INDEX) { - index.stereo = load_null(stereo, speaker::map_stereo.data(), static_cast(speaker::map_stereo.size())); - if (index.stereo == PA_INVALID_INDEX) { + if (!index.stereo.present) { + index.stereo.module = load_null(stereo_name, speaker::map_stereo.data(), static_cast(speaker::map_stereo.size())); + if (index.stereo.module == PA_INVALID_INDEX) { BOOST_LOG(warning) << "Couldn't create virtual sink for stereo: "sv << pa_strerror(pa_context_errno(ctx.get())); } else { + index.stereo.present = true; + index.stereo.owned = true; ++nullcount; } } - if (index.surround51 == PA_INVALID_INDEX) { - index.surround51 = load_null(surround51, speaker::map_surround51.data(), static_cast(speaker::map_surround51.size())); - if (index.surround51 == PA_INVALID_INDEX) { + if (!index.surround51.present) { + index.surround51.module = load_null(surround51_name, speaker::map_surround51.data(), static_cast(speaker::map_surround51.size())); + if (index.surround51.module == PA_INVALID_INDEX) { BOOST_LOG(warning) << "Couldn't create virtual sink for surround-51: "sv << pa_strerror(pa_context_errno(ctx.get())); } else { + index.surround51.present = true; + index.surround51.owned = true; ++nullcount; } } - if (index.surround71 == PA_INVALID_INDEX) { - index.surround71 = load_null(surround71, speaker::map_surround71.data(), static_cast(speaker::map_surround71.size())); - if (index.surround71 == PA_INVALID_INDEX) { + if (!index.surround71.present) { + index.surround71.module = load_null(surround71_name, speaker::map_surround71.data(), static_cast(speaker::map_surround71.size())); + if (index.surround71.module == PA_INVALID_INDEX) { BOOST_LOG(warning) << "Couldn't create virtual sink for surround-71: "sv << pa_strerror(pa_context_errno(ctx.get())); } else { + index.surround71.present = true; + index.surround71.owned = true; ++nullcount; } } @@ -552,7 +579,7 @@ namespace platf { } if (nullcount == 3) { - sink.null = std::make_optional(sink_t::null_t {stereo, surround51, surround71}); + sink.null = std::make_optional(sink_t::null_t {stereo_name, surround51_name, surround71_name}); } return std::make_optional(std::move(sink)); @@ -657,6 +684,28 @@ namespace platf { return true; } + /** + * @brief Whether the backend can capture a sink without changing the host default. + * + * @return Always true: capture_sink() records the target for the monitor lookup. + */ + bool supports_keep_default_sink() const override { + return true; + } + + /** + * @brief Capture the given sink without changing the host default. + * + * @param sink Audio sink name to capture. + * @return Always 0: selecting a capture target cannot fail here. + */ + int capture_sink(const std::string &sink) override { + BOOST_LOG(info) << "Keeping host default sink; capturing ["sv << sink << "] without swapping"sv; + requested_sink = sink; + + return 0; + } + /** * @brief Update the sink value on the backend. * @@ -693,10 +742,29 @@ namespace platf { return 0; } + /** + * @brief Unload a null sink loaded by this session; leave adopted sinks alone. + * + * Adopted sinks (persistent PipeWire config or another session's) stay + * loaded: unloading them would yank routed streams back to the host + * default mid-game. + * + * @param sink Lifecycle state for the sink. + * @param name Sink name for logging. + */ + void unload_owned(null_sink_t &sink, const char *name) { + if (!sink.owned) { + BOOST_LOG(debug) << "Leaving adopted null-sink ["sv << name << "] loaded"sv; + return; + } + + unload_null(sink.module); + } + ~server_t() override { - unload_null(index.stereo); - unload_null(index.surround51); - unload_null(index.surround71); + unload_owned(index.stereo, stereo_name); + unload_owned(index.surround51, surround51_name); + unload_owned(index.surround71, surround71_name); if (worker.joinable()) { pa_context_disconnect(ctx.get()); diff --git a/src_assets/common/assets/web/configs/config_tabs.json b/src_assets/common/assets/web/configs/config_tabs.json index 5a6154154f0..fce854371b4 100644 --- a/src_assets/common/assets/web/configs/config_tabs.json +++ b/src_assets/common/assets/web/configs/config_tabs.json @@ -43,6 +43,7 @@ "stream_audio": "enabled", "install_steam_audio_drivers": "enabled", "external_audio": "disabled", + "keep_default_sink": "disabled", "adapter_name": "", "output_name": "", "dd_configuration_option": "disabled", diff --git a/src_assets/common/assets/web/configs/tabs/AudioVideo.vue b/src_assets/common/assets/web/configs/tabs/AudioVideo.vue index 0d70a736bc3..c7d3a673e2c 100644 --- a/src_assets/common/assets/web/configs/tabs/AudioVideo.vue +++ b/src_assets/common/assets/web/configs/tabs/AudioVideo.vue @@ -87,6 +87,14 @@ const config = ref(props.config) + + + 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); + + 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/test_audio.cpp b/tests/unit/test_audio.cpp index 8561cb3d9c5..72136cd9b93 100644 --- a/tests/unit/test_audio.cpp +++ b/tests/unit/test_audio.cpp @@ -114,3 +114,67 @@ 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 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; + } + + 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 + +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); +} diff --git a/tests/unit/test_config.cpp b/tests/unit/test_config.cpp index f3bb7ceaf1c..8af8427bd48 100644 --- a/tests/unit/test_config.cpp +++ b/tests/unit/test_config.cpp @@ -428,3 +428,35 @@ 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; +} From f9ac77875855e19284f71b71efcd119f3077319a Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Wed, 14 Oct 2026 22:00:29 -0700 Subject: [PATCH 02/25] fix(linux): clear Sonar findings on audio sink lifecycle Rename shadowed module field (S1669), extract adopt_sink/ensure_sink helpers from the duplicated sink setup blocks (S3776), shrink the oversized enumeration lambda (S1188), and guard destructor teardown against throwing unloads (S1048). Behavior unchanged. --- src/platform/linux/audio.cpp | 127 ++++++++++++++++++----------------- 1 file changed, 64 insertions(+), 63 deletions(-) diff --git a/src/platform/linux/audio.cpp b/src/platform/linux/audio.cpp index 2e82abb5248..4eef90e1640 100644 --- a/src/platform/linux/audio.cpp +++ b/src/platform/linux/audio.cpp @@ -341,7 +341,7 @@ namespace platf { * @brief Lifecycle state for one Sunshine null sink. */ struct null_sink_t { - std::uint32_t module = PA_INVALID_INDEX; ///< Owning PulseAudio module index, when module-backed. + std::uint32_t module_index = PA_INVALID_INDEX; ///< Owning PulseAudio module index, when module-backed. bool present = false; ///< Sink exists in the graph (pre-existing or loaded by this session). bool owned = false; ///< Loaded by this session; safe to unload on teardown. }; @@ -471,6 +471,55 @@ namespace platf { return 0; } + /** + * @brief Adopt a pre-existing Sunshine null sink found during enumeration. + * @details Reuses sinks from persistent configuration or a live session without taking + * ownership, so teardown never unloads what this session didn't create. The present + * guard also keeps repeat sink_info() calls from demoting owned sinks to adopted. + * + * @param sink Lifecycle state for the sink. + * @param name Sunshine null sink name to match. + * @param found PulseAudio introspection info for the enumerated sink. + * @param nullcount Running count of Sunshine virtual sinks found. + */ + void adopt_sink(null_sink_t &sink, const char *name, const pa_sink_info *found, int &nullcount) { + if (std::strcmp(found->name, name)) { + return; + } + + if (!sink.present) { + sink.module_index = found->owner_module; + sink.present = true; + } + + ++nullcount; + } + + /** + * @brief Create the Sunshine null sink for one layout when it is missing. + * + * @param sink Lifecycle state for the sink. + * @param name Sunshine null sink name to create. + * @param channel_mapping Channel mapping. + * @param channels Number of audio channels in the stream. + * @param layout Human-readable layout name for logging. + * @param nullcount Running count of Sunshine virtual sinks found. + */ + void ensure_sink(null_sink_t &sink, const char *name, const std::uint8_t *channel_mapping, int channels, const char *layout, int &nullcount) { + if (sink.present) { + return; + } + + sink.module_index = load_null(name, channel_mapping, channels); + if (sink.module_index == PA_INVALID_INDEX) { + BOOST_LOG(warning) << "Couldn't create virtual sink for "sv << layout << ": "sv << pa_strerror(pa_context_errno(ctx.get())); + } else { + sink.present = true; + sink.owned = true; + ++nullcount; + } + } + /** * @brief Query host and virtual sink names available to Sunshine. * @@ -496,32 +545,9 @@ namespace platf { return; } - // Adopt sinks that already exist (persistent PipeWire config or a live - // session): reuse them, but never unload what we didn't create. The - // present guard also keeps repeat sink_info() calls from demoting - // owned sinks to adopted. - if (!std::strcmp(sink_info->name, stereo_name)) { - if (!index.stereo.present) { - index.stereo.module = sink_info->owner_module; - index.stereo.present = true; - } - - ++nullcount; - } else if (!std::strcmp(sink_info->name, surround51_name)) { - if (!index.surround51.present) { - index.surround51.module = sink_info->owner_module; - index.surround51.present = true; - } - - ++nullcount; - } else if (!std::strcmp(sink_info->name, surround71_name)) { - if (!index.surround71.present) { - index.surround71.module = sink_info->owner_module; - index.surround71.present = true; - } - - ++nullcount; - } + adopt_sink(index.stereo, stereo_name, sink_info, nullcount); + adopt_sink(index.surround51, surround51_name, sink_info, nullcount); + adopt_sink(index.surround71, surround71_name, sink_info, nullcount); }; op_t op {pa_context_get_sink_info_list(ctx.get(), cb, &f)}; @@ -541,38 +567,9 @@ namespace platf { auto sink_name = get_default_sink_name(); sink.host = sink_name; - if (!index.stereo.present) { - index.stereo.module = load_null(stereo_name, speaker::map_stereo.data(), static_cast(speaker::map_stereo.size())); - if (index.stereo.module == PA_INVALID_INDEX) { - BOOST_LOG(warning) << "Couldn't create virtual sink for stereo: "sv << pa_strerror(pa_context_errno(ctx.get())); - } else { - index.stereo.present = true; - index.stereo.owned = true; - ++nullcount; - } - } - - if (!index.surround51.present) { - index.surround51.module = load_null(surround51_name, speaker::map_surround51.data(), static_cast(speaker::map_surround51.size())); - if (index.surround51.module == PA_INVALID_INDEX) { - BOOST_LOG(warning) << "Couldn't create virtual sink for surround-51: "sv << pa_strerror(pa_context_errno(ctx.get())); - } else { - index.surround51.present = true; - index.surround51.owned = true; - ++nullcount; - } - } - - if (!index.surround71.present) { - index.surround71.module = load_null(surround71_name, speaker::map_surround71.data(), static_cast(speaker::map_surround71.size())); - if (index.surround71.module == PA_INVALID_INDEX) { - BOOST_LOG(warning) << "Couldn't create virtual sink for surround-71: "sv << pa_strerror(pa_context_errno(ctx.get())); - } else { - index.surround71.present = true; - index.surround71.owned = true; - ++nullcount; - } - } + ensure_sink(index.stereo, stereo_name, speaker::map_stereo.data(), static_cast(speaker::map_stereo.size()), "stereo", nullcount); + ensure_sink(index.surround51, surround51_name, speaker::map_surround51.data(), static_cast(speaker::map_surround51.size()), "surround-51", nullcount); + ensure_sink(index.surround71, surround71_name, speaker::map_surround71.data(), static_cast(speaker::map_surround71.size()), "surround-71", nullcount); if (sink_name.empty()) { BOOST_LOG(warning) << "Couldn't find an active default sink. Continuing with virtual audio only."sv; @@ -758,13 +755,17 @@ namespace platf { return; } - unload_null(sink.module); + unload_null(sink.module_index); } ~server_t() override { - unload_owned(index.stereo, stereo_name); - unload_owned(index.surround51, surround51_name); - unload_owned(index.surround71, surround71_name); + try { + unload_owned(index.stereo, stereo_name); + unload_owned(index.surround51, surround51_name); + unload_owned(index.surround71, surround71_name); + } catch (...) { + // Teardown must not throw: unload failures were already logged above. + } if (worker.joinable()) { pa_context_disconnect(ctx.get()); From 894bf466562c7a38c9090a1b77a995c6699f7027 Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Wed, 14 Oct 2026 23:14:31 -0700 Subject: [PATCH 03/25] fix(linux): log suppressed exception in audio server teardown Give the destructor's catch-all a log statement so the intentionally suppressed unload path is not an empty handler (S2486). Teardown stays non-throwing. --- src/platform/linux/audio.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/platform/linux/audio.cpp b/src/platform/linux/audio.cpp index 4eef90e1640..8a1e619e321 100644 --- a/src/platform/linux/audio.cpp +++ b/src/platform/linux/audio.cpp @@ -765,6 +765,7 @@ namespace platf { unload_owned(index.surround71, surround71_name); } catch (...) { // Teardown must not throw: unload failures were already logged above. + BOOST_LOG(warning) << "Suppressed unexpected exception while unloading null-sinks during teardown"sv; } if (worker.joinable()) { From 77a5a78d06896ed209f3be069395c8de25e1bc52 Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Fri, 16 Oct 2026 23:45:18 -0700 Subject: [PATCH 04/25] fix(audio): capture host sink when keep-default has no configured sink Route the capture-only path at the configured sink, or the saved host sink when nothing is configured, instead of the virtual sink. Without a swap, applications stay on the host default, so capturing the virtual sink's monitor yields silence when host playback is muted. Extract the startup selection plus swap-vs-capture policy into the pure resolve_capture_routing() helper so the empty/configured sink by HOST_AUDIO matrix is covered by unit tests, and pin the historical virtual-sink selection on the swap path. --- src/audio.cpp | 51 +++++++------------------ src/audio.h | 74 ++++++++++++++++++++++++++++++++++++ tests/unit/test_audio.cpp | 79 ++++++++++++++++++++++++++++++++++++++- 3 files changed, 166 insertions(+), 38 deletions(-) diff --git a/src/audio.cpp b/src/audio.cpp index 577a3f74a96..324003b606f 100644 --- a/src/audio.cpp +++ b/src/audio.cpp @@ -184,51 +184,28 @@ namespace audio { return; } - // Order of priority: - // 1. Virtual sink - // 2. Audio sink - // 3. Host - std::string *sink = &ref->sink.host; - if (!config::audio.sink.empty()) { - sink = &config::audio.sink; - } - - // Prefer the virtual sink if host playback is disabled or there's no other sink - if (ref->sink.null && (!config.flags[config_t::HOST_AUDIO] || sink->empty())) { - auto &null = *ref->sink.null; - switch (stream.channelCount) { - case 2: - sink = &null.stereo; - break; - case 6: - sink = &null.surround51; - break; - case 8: - sink = &null.surround71; - break; - } - } - // Only the first to start a session may change the default sink if (!ref->sink_flag->exchange(true, std::memory_order_acquire)) { // One decision point for swap-vs-capture: the recorded restore flag keeps // teardown symmetric with startup on every platform, including backends // that never learned the keep-default behavior. - const auto policy = resolve_sink_routing_policy(config::audio.keep_default_sink, control->supports_keep_default_sink()); - - if (policy.swap_at_startup) { + const auto routing = resolve_capture_routing( + config::audio.keep_default_sink, + control->supports_keep_default_sink(), + config.flags[config_t::HOST_AUDIO], + stream.channelCount, + ref->sink.host, + config::audio.sink, + ref->sink.null + ); + ref->restore_sink = routing.restore_at_teardown; + if (routing.swap_at_startup) { // If the selected sink is different than the current one, change sinks. - // Conjoin the policy's restore flag so teardown honors the same decision - // object startup used; the policy keeps both fields in agreement. - ref->restore_sink = policy.restore_at_teardown && ref->sink.host != *sink; - if (ref->restore_sink && control->set_sink(*sink)) { - return; - } - } else { - ref->restore_sink = false; - if (control->capture_sink(*sink)) { + if (ref->restore_sink && control->set_sink(routing.target)) { return; } + } else if (control->capture_sink(routing.target)) { + return; } } diff --git a/src/audio.h b/src/audio.h index d866b925137..696e66fe728 100644 --- a/src/audio.h +++ b/src/audio.h @@ -11,6 +11,8 @@ #include #include +#include +#include namespace stream { struct session_t; @@ -125,6 +127,78 @@ namespace audio { return {true, true}; } + /** + * @brief Capture startup plan: which sink to select and whether to swap the host default. + */ + struct capture_routing_t { + bool swap_at_startup; ///< True selects set_sink(); false selects capture_sink(). + bool restore_at_teardown; ///< Whether teardown must restore the previous sink. + std::string target; ///< Sink name to pass to set_sink() or capture_sink(). + }; + + /** + * @brief Resolve the capture startup plan from session inputs. + * + * Pure function: no I/O, no global state. Encodes the historical sink + * selection (virtual sink when host playback is muted or nothing else is + * selected) together with the swap-vs-capture policy. The capture-only path + * targets the configured sink, or the saved host sink when nothing is + * configured: without a swap, applications stay on the host default, so + * capturing the virtual sink's monitor would yield silence. + * + * @param keep_default_requested Value of config::audio.keep_default_sink. + * @param platform_supports_keep_default Value of platf::audio_control_t::supports_keep_default_sink(). + * @param host_audio_enabled Whether host playback stays enabled (Moonlight HOST_AUDIO flag). + * @param channel_count Stream channel count selecting the virtual sink layout. + * @param host_sink Saved host default sink name. + * @param config_sink Configured audio_sink value, possibly empty. + * @param null_sinks Virtual sink names reported by the backend, when any. + * @return Startup plan with matching swap, restore, and target behavior. + */ + [[nodiscard]] inline capture_routing_t resolve_capture_routing( + bool keep_default_requested, + bool platform_supports_keep_default, + bool host_audio_enabled, + int channel_count, + const std::string &host_sink, + const std::string &config_sink, + const std::optional &null_sinks + ) { + // Order of priority: virtual sink, audio sink, host. + std::string selected = host_sink; + if (!config_sink.empty()) { + selected = config_sink; + } + + // Prefer the virtual sink if host playback is disabled or there's no other sink. + if (null_sinks && (!host_audio_enabled || selected.empty())) { + switch (channel_count) { + case 2: + selected = null_sinks->stereo; + break; + case 6: + selected = null_sinks->surround51; + break; + case 8: + selected = null_sinks->surround71; + break; + } + } + + const auto policy = resolve_sink_routing_policy(keep_default_requested, platform_supports_keep_default); + capture_routing_t routing {}; + routing.swap_at_startup = policy.swap_at_startup; + if (policy.swap_at_startup) { + routing.restore_at_teardown = policy.restore_at_teardown && host_sink != selected; + routing.target = selected; + } else { + routing.restore_at_teardown = false; + routing.target = config_sink.empty() ? host_sink : config_sink; + } + + return routing; + } + /** * @brief Byte buffer used for encoded audio packet payloads. */ diff --git a/tests/unit/test_audio.cpp b/tests/unit/test_audio.cpp index 72136cd9b93..9141be4ebb2 100644 --- a/tests/unit/test_audio.cpp +++ b/tests/unit/test_audio.cpp @@ -129,7 +129,7 @@ TEST(SinkRoutingPolicyTest, KeepsDefaultOnlyWhenRequestedAndSupported) { // 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}}) { + 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); @@ -145,6 +145,83 @@ TEST(SinkRoutingPolicyTest, StartupAndTeardownNeverDiverge) { } } +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"); + + // 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"); +} + namespace { /** * @brief Minimal backend that never learned the keep-default behavior. From 2ec6d807676548ba0756346a47796f231707ed8f Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Fri, 16 Oct 2026 23:45:22 -0700 Subject: [PATCH 05/25] fix(web): cover shared keep_default_sink checkbox in UI tests Include the new shared checkbox in the Windows control-list assertion and add round-trip coverage rendering it on Windows, Linux, and macOS. --- tests/web/ExternalAudio.test.js | 1 + tests/web/KeepDefaultSink.test.js | 45 +++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 tests/web/KeepDefaultSink.test.js diff --git a/tests/web/ExternalAudio.test.js b/tests/web/ExternalAudio.test.js index b921818dce9..303609cb2e9 100644 --- a/tests/web/ExternalAudio.test.js +++ b/tests/web/ExternalAudio.test.js @@ -42,6 +42,7 @@ describe('externally managed audio configuration', () => { 'install_steam_audio_drivers', 'stream_audio', 'external_audio', + 'keep_default_sink', ]) expect(config.external_audio).toBe('disabled') expect(wrapper.get('#external_audio').element.checked).toBe(false) diff --git a/tests/web/KeepDefaultSink.test.js b/tests/web/KeepDefaultSink.test.js new file mode 100644 index 00000000000..619fa445f58 --- /dev/null +++ b/tests/web/KeepDefaultSink.test.js @@ -0,0 +1,45 @@ +import { mount } from '@vue/test-utils' +import { afterEach, describe, expect, it } 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' + +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(() => { + document.body.innerHTML = '' +}) + +describe('keep default sink configuration', () => { + it.each(['windows', 'linux', 'macos'])('renders the shared checkbox on %s and preserves its saved value', async platform => { + const { wrapper, config } = mountAudioVideo(platform) + expect(wrapper.find('#keep_default_sink').exists()).toBe(true) + expect(config.keep_default_sink).toBe('disabled') + expect(wrapper.get('#keep_default_sink').element.checked).toBe(false) + await wrapper.get('#keep_default_sink').setValue(true) + expect(config.keep_default_sink).toBe('enabled') + await wrapper.get('#keep_default_sink').setValue(false) + expect(config.keep_default_sink).toBe('disabled') + wrapper.unmount() + }) +}) From f875ce4c644cd36d35eaee4bc12eef1b2d401625 Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Fri, 16 Oct 2026 23:45:22 -0700 Subject: [PATCH 06/25] feat(audio): support keep_default_sink on Windows and macOS Share the keep-default routing contract across backends. Windows records the capture target for direct WASAPI capture and guards the default reassertion callback, the startup default-device reset, and the Steam driver install behind hands-off-mode predicates, composing with the existing external_audio behavior. macOS reports support natively since tap/input capture never touches the default output. Document the per-platform behavior. --- docs/configuration.md | 6 +- src/platform/macos/microphone.mm | 47 ++++++ src/platform/windows/audio.cpp | 158 +++++++++++++++++- .../assets/web/public/assets/locale/en.json | 2 +- tests/unit/platform/macos/test_av_audio.mm | 13 ++ tests/unit/platform/windows/test_audio.cpp | 31 ++++ 6 files changed, 250 insertions(+), 7 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index cd6c36e65d7..6408842fc09 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -981,7 +981,11 @@ consent prompt for directory ACLs, so the Web UI shows setup steps for correctin diff --git a/src/platform/macos/microphone.mm b/src/platform/macos/microphone.mm index 72776e73d14..f07520d7ea1 100644 --- a/src/platform/macos/microphone.mm +++ b/src/platform/macos/microphone.mm @@ -81,6 +81,30 @@ int set_sink(const std::string &sink) override { return 0; } + /** + * @brief Whether the backend can capture a sink without changing the host default. + * + * @return Always true: macOS captures through a system tap or a selected + * input, neither of which changes the default output device. + */ + bool supports_keep_default_sink() const override { + return true; + } + + /** + * @brief Capture the given sink without changing the host default. + * + * No-op by design: microphone() already selects the system tap (empty sink) + * or the configured input without touching default output routing. + * + * @param sink Audio sink name to capture. + * @return Always 0: selecting a capture target cannot fail here. + */ + int capture_sink(const std::string &sink) override { + BOOST_LOG(info) << "Keeping host default output; capturing ["sv << sink << "] through the macOS tap or input"sv; + return 0; + } + /** * @brief Create a microphone capture stream for the requested layout. * @@ -158,4 +182,27 @@ bool is_sink_available(const std::string &sink) override { std::unique_ptr audio_control() { return std::make_unique(); } + +#ifdef SUNSHINE_TESTS + namespace tests { + /** + * @brief Exercise keep-default support detection without audio hardware. + * @return True when the backend captures without changing the host default. + */ + bool keep_default_supported() { + macos_audio_control_t control; + return control.supports_keep_default_sink(); + } + + /** + * @brief Exercise capture-only sink selection without audio hardware. + * @param sink Sink a caller attempts to capture. + * @return Status from the production capture setter. + */ + int capture_sink_status(const std::string &sink) { + macos_audio_control_t control; + return control.capture_sink(sink); + } + } // namespace tests +#endif } // namespace platf diff --git a/src/platform/windows/audio.cpp b/src/platform/windows/audio.cpp index d12d015c0d3..d6686e66423 100644 --- a/src/platform/windows/audio.cpp +++ b/src/platform/windows/audio.cpp @@ -1028,9 +1028,9 @@ namespace platf::audio { return nullptr; } - // If this is a virtual sink, set a callback that will change the sink back if it's changed - auto virtual_sink_info = extract_virtual_sink_info(assigned_sink); - if (virtual_sink_info && !config::audio.external_audio) { + // If this is a virtual sink, set a callback that will change the sink back if it's changed. + // Hands-off modes never reinstall: capture follows the recorded endpoint directly. + if (should_install_default_callback(assigned_sink)) { mic->default_endpt_changed_cb = [this] { BOOST_LOG(info) << "Resetting sink to ["sv << assigned_sink << "] after default changed"; set_sink(assigned_sink); @@ -1150,6 +1150,66 @@ namespace platf::audio { return failure; } + /** + * @brief Whether the backend can capture a sink without changing the host default. + * + * @return Always true: capture_sink() records the target for direct WASAPI capture. + */ + bool supports_keep_default_sink() const override { + return true; + } + + /** + * @brief Capture the given sink without changing the host default. + * + * Records the target for microphone(); unlike set_sink(), this never calls + * SetDefaultEndpoint and never installs the Steam drivers. + * + * @param sink Audio sink name to capture. + * @return Always 0: recording a capture target cannot fail here. + */ + int capture_sink(const std::string &sink) override { + BOOST_LOG(info) << "Keeping host default sink; capturing ["sv << sink << "] without swapping"sv; + assigned_sink = sink; + + return 0; + } + + /** + * @brief Whether a default-endpoint change may reinstall the assigned sink. + * + * Keep-default sessions must never reassert the default: capture follows the + * recorded endpoint directly, so default changes are simply observed. + * + * @param sink Assigned sink name that would be reinstalled. + * @return True when the reassertion callback may be installed. + */ + bool should_install_default_callback(const std::string &sink) { + return static_cast(extract_virtual_sink_info(sink)) && !config::audio.external_audio && + !config::audio.keep_default_sink; + } + + /** + * @brief Whether startup may move the default away from Steam Streaming Speakers. + * + * @return False in hands-off modes that never touch the host default. + */ + bool should_reset_default_device() { + return !config::audio.external_audio && !config::audio.keep_default_sink; + } + + /** + * @brief Whether the Steam Streaming Speakers driver may be installed. + * + * Installing a driver reconfigures the audio subsystem (device arrival makes + * Windows re-evaluate defaults), which keep-default sessions must not trigger. + * + * @return False in hands-off modes that never touch the host audio graph. + */ + bool should_install_steam_drivers() { + return !config::audio.external_audio && !config::audio.keep_default_sink && config::audio.install_steam_drivers; + } + /** * @brief Enumerates supported match field options. */ @@ -1276,7 +1336,7 @@ namespace platf::audio { * @brief Resets the default audio device from Steam Streaming Speakers. */ void reset_default_device() { - if (config::audio.external_audio) { + if (!should_reset_default_device()) { return; } @@ -1509,6 +1569,93 @@ namespace platf::audio { return control.set_sink(sink); } + /** + * @brief Exercise keep-default support detection without initializing Windows policy interfaces. + * @return True when the backend captures without changing the host default. + */ + bool keep_default_supported() { + audio_control_t control; + return control.supports_keep_default_sink(); + } + + /** + * @brief Exercise capture-only sink recording without policy interfaces. + * @param sink Sink a caller attempts to capture. + * @return Sink recorded for direct capture, or empty when recording failed. + */ + std::string capture_assigned_sink(const std::string &sink) { + audio_control_t control; + if (control.capture_sink(sink)) { + return {}; + } + + return control.assigned_sink; + } + + /** + * @brief Exercise the default-callback guard with controlled hands-off modes. + * @param sink Assigned sink name that would be reinstalled. + * @param keep_default keep_default_sink value to test with. + * @param external_audio external_audio value to test with. + * @return True when the production guard installs the reassertion callback. + */ + bool installs_default_callback(const std::string &sink, bool keep_default, bool external_audio) { + audio_control_t control; + auto previous_keep = std::exchange(config::audio.keep_default_sink, keep_default); + auto previous_external = std::exchange(config::audio.external_audio, external_audio); + bool installed = control.should_install_default_callback(sink); + config::audio.keep_default_sink = previous_keep; + config::audio.external_audio = previous_external; + return installed; + } + + /** + * @brief Exercise the startup-reset guard with controlled hands-off modes. + * @param keep_default keep_default_sink value to test with. + * @param external_audio external_audio value to test with. + * @return True when the production guard permits resetting the default device. + */ + bool resets_default_device(bool keep_default, bool external_audio) { + audio_control_t control; + auto previous_keep = std::exchange(config::audio.keep_default_sink, keep_default); + auto previous_external = std::exchange(config::audio.external_audio, external_audio); + bool resets = control.should_reset_default_device(); + config::audio.keep_default_sink = previous_keep; + config::audio.external_audio = previous_external; + return resets; + } + + /** + * @brief Exercise the driver-install guard with controlled hands-off modes. + * @param keep_default keep_default_sink value to test with. + * @param external_audio external_audio value to test with. + * @param install_requested install_steam_drivers value to test with. + * @return True when the production guard permits installing the Steam drivers. + */ + bool installs_steam_drivers(bool keep_default, bool external_audio, bool install_requested) { + audio_control_t control; + auto previous_keep = std::exchange(config::audio.keep_default_sink, keep_default); + auto previous_external = std::exchange(config::audio.external_audio, external_audio); + auto previous_install = std::exchange(config::audio.install_steam_drivers, install_requested); + bool installs = control.should_install_steam_drivers(); + config::audio.keep_default_sink = previous_keep; + config::audio.external_audio = previous_external; + config::audio.install_steam_drivers = previous_install; + return installs; + } + + /** + * @brief Exercise the startup reset with keep-default enabled and null policy interfaces. + * + * Surviving this call proves the guard returns before touching policy or enumerator. + */ + void reset_with_keep_default() { + audio_control_t control; + auto previous_keep = std::exchange(config::audio.keep_default_sink, true); + control.reset_default_device(); + config::audio.keep_default_sink = previous_keep; + } + /** * @brief Resolve a sink through the production Windows endpoint lookup. * @@ -1623,7 +1770,8 @@ namespace platf { // Install Steam Streaming Speakers if needed. We do this during audio_control() to ensure // the sink information returned includes the new Steam Streaming Speakers device. - if (!config::audio.external_audio && config::audio.install_steam_drivers && !control->find_device_id(control->match_steam_speakers())) { + // Hands-off modes skip the install: driver installation reconfigures the audio subsystem. + if (control->should_install_steam_drivers() && !control->find_device_id(control->match_steam_speakers())) { // This is best effort. Don't fail if it doesn't work. control->install_steam_audio_drivers(); } 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 d1784b50c84..7f9e9337913 100644 --- a/src_assets/common/assets/web/public/assets/locale/en.json +++ b/src_assets/common/assets/web/public/assets/locale/en.json @@ -294,7 +294,7 @@ "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.", "keep_default_sink": "Keep Default Sink", - "keep_default_sink_desc": "Capture the selected audio sink without changing the host default sink. Only takes effect on Linux; ignored on other platforms.", + "keep_default_sink_desc": "Capture the selected audio sink without changing the host default sink. Supported on Linux, Windows, and macOS; backends without support keep the previous swap behavior.", "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", 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..add421f3557 100644 --- a/tests/unit/platform/windows/test_audio.cpp +++ b/tests/unit/platform/windows/test_audio.cpp @@ -29,6 +29,12 @@ namespace platf::audio::tests { int initialize_audio_control(const std::function> &create_instance); std::optional configured_sink_info(); int set_external_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 external_audio); + bool resets_default_device(bool keep_default, bool external_audio); + bool installs_steam_drivers(bool keep_default, bool external_audio, bool install_requested); + void reset_with_keep_default(); bool sink_device_available(const std::string &sink, 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); @@ -589,4 +595,29 @@ 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, false)); + EXPECT_FALSE(platf::audio::tests::installs_default_callback(virtual_sink, true, false)); + EXPECT_FALSE(platf::audio::tests::installs_default_callback(virtual_sink, false, true)); + EXPECT_FALSE(platf::audio::tests::installs_default_callback(virtual_sink, true, true)); + EXPECT_FALSE(platf::audio::tests::installs_default_callback("endpoint-id", false, false)); +} + +TEST(WindowsAudioTest, HandsOffModesSkipDefaultResetAndDriverInstall) { + EXPECT_TRUE(platf::audio::tests::resets_default_device(false, false)); + EXPECT_FALSE(platf::audio::tests::resets_default_device(true, false)); + EXPECT_FALSE(platf::audio::tests::resets_default_device(false, true)); + EXPECT_TRUE(platf::audio::tests::installs_steam_drivers(false, false, true)); + EXPECT_FALSE(platf::audio::tests::installs_steam_drivers(true, false, true)); + EXPECT_FALSE(platf::audio::tests::installs_steam_drivers(false, true, true)); + EXPECT_FALSE(platf::audio::tests::installs_steam_drivers(false, false, false)); + platf::audio::tests::reset_with_keep_default(); +} #endif From edf6c3e17a9a5e5bc6adaaec436d32ccb630db63 Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Sat, 17 Oct 2026 00:57:42 -0700 Subject: [PATCH 07/25] fix(audio): add default case to capture-routing channel switch Satisfies Sonar cpp:S3562 on the new code. Behavior unchanged: layouts other than stereo/5.1/7.1 keep the previously selected sink. --- src/audio.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/audio.h b/src/audio.h index 696e66fe728..864dba13fa8 100644 --- a/src/audio.h +++ b/src/audio.h @@ -182,6 +182,8 @@ namespace audio { case 8: selected = null_sinks->surround71; break; + default: + break; } } From efcd6e3a972bbfa139e9ed740b0dbc34c6289e6a Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Sat, 17 Oct 2026 02:54:40 -0700 Subject: [PATCH 08/25] fix(web): share AudioVideo mount helper between UI tests Extract the duplicated mountAudioVideo helper into audioVideoMount.js so the keep_default_sink suite and the external_audio suite use one copy. Clears the Sonar new-code duplication gate. --- tests/web/ExternalAudio.test.js | 26 +------------------------- tests/web/KeepDefaultSink.test.js | 26 +------------------------- tests/web/audioVideoMount.js | 26 ++++++++++++++++++++++++++ 3 files changed, 28 insertions(+), 50 deletions(-) create mode 100644 tests/web/audioVideoMount.js diff --git a/tests/web/ExternalAudio.test.js b/tests/web/ExternalAudio.test.js index 303609cb2e9..b2d264e8d35 100644 --- a/tests/web/ExternalAudio.test.js +++ b/tests/web/ExternalAudio.test.js @@ -1,32 +1,8 @@ -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 } -} +import { mountAudioVideo } from './audioVideoMount.js' afterEach(() => { vi.restoreAllMocks() diff --git a/tests/web/KeepDefaultSink.test.js b/tests/web/KeepDefaultSink.test.js index 619fa445f58..bb0370d8e56 100644 --- a/tests/web/KeepDefaultSink.test.js +++ b/tests/web/KeepDefaultSink.test.js @@ -1,30 +1,6 @@ -import { mount } from '@vue/test-utils' import { afterEach, describe, expect, it } 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' - -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 } -} +import { mountAudioVideo } from './audioVideoMount.js' afterEach(() => { document.body.innerHTML = '' diff --git a/tests/web/audioVideoMount.js b/tests/web/audioVideoMount.js new file mode 100644 index 00000000000..adf756bf784 --- /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) { + 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 } +} From 627882cac595307aad0c87ca8d6517140b971492 Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Mon, 9 Nov 2026 11:37:41 -0700 Subject: [PATCH 09/25] feat(audio): unify keep-default capture with process loopback and capture-target UI --- docs/configuration.md | 64 +++----- src/audio.cpp | 14 ++ src/audio.h | 46 +++++- src/config.cpp | 10 +- src/config.h | 3 +- src/platform/common.h | 24 +++ src/platform/windows/audio.cpp | 90 +++++----- src_assets/common/assets/web/Config.vue | 22 +++ src_assets/common/assets/web/config_bool.js | 15 ++ .../assets/web/configs/config_tabs.json | 1 - .../assets/web/configs/tabs/AudioVideo.vue | 12 -- .../assets/web/public/assets/locale/en.json | 2 - tests/integration/test_config_consistency.cpp | 3 +- tests/unit/platform/windows/test_audio.cpp | 140 ++++++++-------- tests/unit/test_audio.cpp | 154 ++++++++++++++++++ tests/unit/test_config.cpp | 32 ++++ tests/web/ConfigBool.test.js | 13 ++ tests/web/ConfigMigration.test.js | 82 ++++++++++ tests/web/ExternalAudio.test.js | 58 ------- 19 files changed, 552 insertions(+), 233 deletions(-) create mode 100644 src_assets/common/assets/web/config_bool.js create mode 100644 tests/web/ConfigBool.test.js create mode 100644 tests/web/ConfigMigration.test.js delete mode 100644 tests/web/ExternalAudio.test.js diff --git a/docs/configuration.md b/docs/configuration.md index 6408842fc09..7be293aff7d 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -835,6 +835,10 @@ consent prompt for directory ACLs, so the Web UI shows setup steps for correctin } @attention{If you want to mute the host speakers, use [virtual_sink](#virtual_sink) instead.} + @tip{On FreeBSD/Linux, Sunshine also provides its own null sinks (for example + `sink-sunshine-stereo`). Enter one here to capture a private mix you route + yourself; combined with [keep_default_sink](#keep_default_sink), the host + default output is left untouched.} @@ -939,53 +943,33 @@ consent prompt for directory ACLs, so the Web UI shows setup steps for correctin
Capture the selected audio sink without changing the host default sink. When disabled, Sunshine sets the selected sink as the host default sink while streaming. - @note{This option is only supported on Linux.} + @note{Platform support: Linux captures the configured sink (or the host sink when nothing is + configured) and adopts pre-existing null sinks instead of unloading them. Windows captures the + target endpoint directly, skips the Steam driver install and the startup default-device reset, + and never reinstalls the default when it changes. macOS already captures through a system tap + or the selected input without touching the default output, so the option is honored natively.}
-### external_audio +### keep_default_sink - - - - - - - - - -
Description - Enables capture-only operation when an external audio router manages application playback. - An explicit [audio_sink](#audio_sink) is required; use an endpoint ID when names are ambiguous. - Sunshine captures that endpoint directly without changing or restoring Windows default devices - or endpoint formats. + Capture the selected audio sink without changing the host default sink. When disabled, Sunshine sets + the selected (or virtual) sink as the host default sink while streaming on platforms that swap + defaults; macOS never changes the default output.

- In this mode, [virtual_sink](#virtual_sink), automatic Steam audio driver installation, - and Moonlight's host-playback toggle do not affect routing. Configure local playback and the audio - sent to the selected endpoint in your external mixer. If the endpoint is unavailable, audio capture - fails rather than falling back to another endpoint. Video streaming can continue without audio. - @note{This option is only supported on Windows. Other platforms retain their existing behavior.} -
Default@code{} - disabled - @endcode
Example@code{} - external_audio = enabled - audio_sink = My Streaming Mix - @endcode
- -### keep_default_sink - - - - - diff --git a/src/audio.cpp b/src/audio.cpp index 324003b606f..fefeb7e0bb3 100644 --- a/src/audio.cpp +++ b/src/audio.cpp @@ -184,6 +184,8 @@ namespace audio { return; } + const auto capture_intent = resolve_audio_capture_intent(config::audio.keep_default_sink, config::audio.sink); + // Only the first to start a session may change the default sink if (!ref->sink_flag->exchange(true, std::memory_order_acquire)) { // One decision point for swap-vs-capture: the recorded restore flag keeps @@ -199,6 +201,12 @@ namespace audio { ref->sink.null ); ref->restore_sink = routing.restore_at_teardown; + BOOST_LOG(info) << "Audio capture mode ["sv << (routing.swap_at_startup ? "swap-and-restore"sv : "capture-keep-default"sv) + << "], target ["sv << routing.target + << "], restore_at_teardown ["sv << routing.restore_at_teardown + << "], keep_default_sink requested ["sv << config::audio.keep_default_sink + << "], keep_default_sink supported ["sv << control->supports_keep_default_sink() + << "], capture intent ["sv << audio_capture_intent_name(capture_intent) << ']'; if (routing.swap_at_startup) { // If the selected sink is different than the current one, change sinks. if (ref->restore_sink && control->set_sink(routing.target)) { @@ -273,6 +281,12 @@ namespace audio { return false; } + // Keep-default captures the configured sink, so probe that endpoint rather + // than the host default recorded at startup. + if (config::audio.keep_default_sink && !config::audio.sink.empty() && ctx.control->supports_keep_default_sink()) { + return ctx.control->is_sink_available(config::audio.sink); + } + const std::string &sink = ctx.sink.host.empty() ? config::audio.sink : ctx.sink.host; if (sink.empty()) { return false; diff --git a/src/audio.h b/src/audio.h index 864dba13fa8..73afdfb0dfb 100644 --- a/src/audio.h +++ b/src/audio.h @@ -11,8 +11,11 @@ #include #include +#include +#include #include #include +#include namespace stream { struct session_t; @@ -140,8 +143,8 @@ namespace audio { * @brief Resolve the capture startup plan from session inputs. * * Pure function: no I/O, no global state. Encodes the historical sink - * selection (virtual sink when host playback is muted or nothing else is - * selected) together with the swap-vs-capture policy. The capture-only path + * selection (virtual sink when host playback is muted and no sink is + * configured) together with the swap-vs-capture policy. The capture-only path * targets the configured sink, or the saved host sink when nothing is * configured: without a swap, applications stay on the host default, so * capturing the virtual sink's monitor would yield silence. @@ -164,14 +167,15 @@ namespace audio { const std::string &config_sink, const std::optional &null_sinks ) { - // Order of priority: virtual sink, audio sink, host. + // Order of priority: explicit audio sink, virtual sink, host. std::string selected = host_sink; if (!config_sink.empty()) { selected = config_sink; } // Prefer the virtual sink if host playback is disabled or there's no other sink. - if (null_sinks && (!host_audio_enabled || selected.empty())) { + // An explicit audio_sink pin always wins: the user chose that target on purpose. + if (config_sink.empty() && null_sinks && (!host_audio_enabled || selected.empty())) { switch (channel_count) { case 2: selected = null_sinks->stereo; @@ -201,6 +205,40 @@ namespace audio { return routing; } + /** + * @brief Resolve the user-level capture intent from the audio configuration. + * + * @param keep_default_requested Value of config::audio.keep_default_sink. + * @param config_sink Value of config::audio.sink. + * @return Pinned intent when a sink is configured, host-and-client for + * keep-default (Play on this PC too), and client-only otherwise + * (Quiet streaming). + */ + [[nodiscard]] inline platf::audio_capture_intent_e resolve_audio_capture_intent(bool keep_default_requested, const std::string &config_sink) { + if (!config_sink.empty()) { + return platf::audio_capture_intent_e::pinned_sink; + } + return keep_default_requested ? platf::audio_capture_intent_e::host_and_client : platf::audio_capture_intent_e::client_only; + } + + /** + * @brief Stable name of a capture intent, for logging. + * + * @param intent Capture intent to name. + * @return Intent name without the enum prefix. + */ + [[nodiscard]] inline std::string_view audio_capture_intent_name(platf::audio_capture_intent_e intent) { + switch (intent) { + case platf::audio_capture_intent_e::client_only: + return "client_only"; + case platf::audio_capture_intent_e::host_and_client: + return "host_and_client"; + case platf::audio_capture_intent_e::pinned_sink: + return "pinned_sink"; + } + return "unknown"; + } + /** * @brief Byte buffer used for encoded audio packet payloads. */ diff --git a/src/config.cpp b/src/config.cpp index 084f9e76ebc..eb18b24fcce 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -803,7 +803,6 @@ namespace config { {}, // virtual_sink true, // stream audio true, // install_steam_drivers - false, // external_audio false, // keep_default_sink }; @@ -1811,7 +1810,14 @@ namespace config { string_f(vars, "virtual_sink", audio.virtual_sink); bool_f(vars, "stream_audio", audio.stream); bool_f(vars, "install_steam_audio_drivers", audio.install_steam_drivers); - bool_f(vars, "external_audio", audio.external_audio); + // One-time upgrade migration, not a supported option: parse the legacy key + // before keep_default_sink so an explicit new key below always wins. + bool legacy_external_audio = false; + bool_f(vars, "external_audio", legacy_external_audio); + if (legacy_external_audio) { + audio.keep_default_sink = true; + BOOST_LOG(warning) << "external_audio is deprecated; use keep_default_sink instead"sv; + } bool_f(vars, "keep_default_sink", audio.keep_default_sink); string_restricted_f(vars, "origin_web_ui_allowed", nvhttp.origin_web_ui_allowed, {"pc"sv, "lan"sv, "wan"sv}); diff --git a/src/config.h b/src/config.h index 692c159bbe5..b381126c351 100644 --- a/src/config.h +++ b/src/config.h @@ -241,8 +241,7 @@ namespace config { std::string virtual_sink; ///< Virtual audio sink for audio routing bool stream; ///< Enable audio streaming to clients bool install_steam_drivers; ///< Install Steam audio drivers for enhanced compatibility - bool external_audio; ///< Windows capture-only mode; an external router owns endpoint defaults and formats. - bool keep_default_sink; ///< Capture the selected sink without changing the host default sink + bool keep_default_sink; ///< Capture the selected sink without changing the host default sink; on Windows an external router may own endpoint defaults and formats }; /** diff --git a/src/platform/common.h b/src/platform/common.h index da97ccdb6a3..d67810f364e 100644 --- a/src/platform/common.h +++ b/src/platform/common.h @@ -6,6 +6,7 @@ // standard includes #include +#include #include #include #include @@ -880,6 +881,15 @@ namespace platf { virtual ~mic_t() = default; }; + /** + * @brief User-level audio capture intent, independent of platform mechanism. + */ + enum class audio_capture_intent_e { + client_only, ///< Client hears the audio; the host should stay silent. + host_and_client, ///< Audio plays on the host and is also streamed. + pinned_sink, ///< Capture one explicitly configured sink, device, or input. + }; + /** * @brief Platform audio controller that manages sinks and microphone capture. */ @@ -918,6 +928,20 @@ namespace platf { return set_sink(sink); } + /** + * @brief Record the capture target for the next microphone() call. + * + * The default implementation is a no-op so backends without per-process + * capture are unchanged. Backends that support process loopback override + * this to store the intent and PID together, so microphone() never sees + * a mismatched pair. A PID of 0 selects ordinary endpoint or sink capture. + * + * @param intent Capture intent resolved from the audio configuration. + * @param process_id Operating-system PID to capture, or 0 for endpoint capture. + */ + virtual void set_capture_target([[maybe_unused]] audio_capture_intent_e intent, [[maybe_unused]] std::uint32_t process_id) { + } + /** * @brief Create a microphone capture stream for the requested layout. * diff --git a/src/platform/windows/audio.cpp b/src/platform/windows/audio.cpp index d6686e66423..a86429c9b11 100644 --- a/src/platform/windows/audio.cpp +++ b/src/platform/windows/audio.cpp @@ -878,19 +878,17 @@ namespace platf::audio { std::optional sink_info() override { sink_t sink; - if (config::audio.external_audio) { - if (config::audio.sink.empty()) { - BOOST_LOG(error) << "external_audio requires an explicit audio_sink"; - return std::nullopt; - } - sink.host = config::audio.sink; - return sink; - } - // Fill host sink name with the device_id of the current default audio device. { auto device = default_device(device_enum); if (!device) { + // Keep-default with a configured sink does not need a default: capture that + // endpoint directly, but only when it resolves to an active device right now. + if (config::audio.keep_default_sink && !config::audio.sink.empty() && get_sink_device(config::audio.sink)) { + BOOST_LOG(warning) << "No default audio device available; capturing configured sink ["sv << config::audio.sink << ']'; + sink.host = config::audio.sink; + return sink; + } return std::nullopt; } @@ -900,6 +898,11 @@ namespace platf::audio { sink.host = utf_utils::to_utf8(id.get()); } + // Keep-default routing never selects the virtual sink, so skip its discovery. + if (config::audio.keep_default_sink) { + return sink; + } + // Prepare to search for the device_id of the virtual audio sink device, // this device can be either user-configured or // the Steam Streaming Speakers we use by default. @@ -1001,14 +1004,11 @@ namespace platf::audio { */ std::unique_ptr microphone(const std::uint8_t *mapping, int channels, std::uint32_t sample_rate, std::uint32_t frame_size, bool continuous_audio, [[maybe_unused]] bool host_audio_enabled) override { auto mic = std::make_unique(); + } - // External routing pins capture to the configured sink; otherwise prefer the session's assigned sink. - const auto &requested_sink = config::audio.external_audio || assigned_sink.empty() ? config::audio.sink : assigned_sink; - if (config::audio.external_audio && requested_sink.empty()) { - BOOST_LOG(error) << "external_audio requires an explicit audio_sink"; - return nullptr; - } + // Prefer the session's assigned sink; otherwise use the configured sink. + const auto &requested_sink = assigned_sink.empty() ? config::audio.sink : assigned_sink; // Capture the requested sink directly instead of relying on it being the default // render device, so that capture keeps working when the default device differs @@ -1117,7 +1117,9 @@ namespace platf::audio { * @return Status from updating sink. */ int set_sink(const std::string &sink) override { - if (config::audio.external_audio) { + if (config::audio.keep_default_sink) { + // Keep-default never swaps the host default; capture follows the recorded endpoint. + assigned_sink = sink; return 0; } @@ -1185,8 +1187,7 @@ namespace platf::audio { * @return True when the reassertion callback may be installed. */ bool should_install_default_callback(const std::string &sink) { - return static_cast(extract_virtual_sink_info(sink)) && !config::audio.external_audio && - !config::audio.keep_default_sink; + return static_cast(extract_virtual_sink_info(sink)) && !config::audio.keep_default_sink; } /** @@ -1195,7 +1196,7 @@ namespace platf::audio { * @return False in hands-off modes that never touch the host default. */ bool should_reset_default_device() { - return !config::audio.external_audio && !config::audio.keep_default_sink; + return !config::audio.keep_default_sink; } /** @@ -1207,7 +1208,7 @@ namespace platf::audio { * @return False in hands-off modes that never touch the host audio graph. */ bool should_install_steam_drivers() { - return !config::audio.external_audio && !config::audio.keep_default_sink && config::audio.install_steam_drivers; + return !config::audio.keep_default_sink && config::audio.install_steam_drivers; } /** @@ -1476,7 +1477,7 @@ namespace platf::audio { */ template int init(const CreateInstance &create_instance = &CoCreateInstance) { - if (!config::audio.external_audio) { + if (!config::audio.keep_default_sink) { auto status = create_instance( CLSID_CPolicyConfigClient, nullptr, @@ -1550,20 +1551,11 @@ namespace platf::audio { } /** - * @brief Exercise sink discovery without initializing Windows policy interfaces. - * @return Sinks reported by the production controller for the current configuration. - */ - std::optional configured_sink_info() { - audio_control_t control; - return control.sink_info(); - } - - /** - * @brief Exercise the external-routing sink-change guard without policy interfaces. + * @brief Exercise the keep-default sink-change guard without policy interfaces. * @param sink Sink a caller attempts to select. * @return Status from the production sink setter. */ - int set_external_sink(const std::string &sink) { + int set_keep_default_sink(const std::string &sink) { audio_control_t control; control.reset_default_device(); return control.set_sink(sink); @@ -1593,53 +1585,44 @@ namespace platf::audio { } /** - * @brief Exercise the default-callback guard with controlled hands-off modes. + * @brief Exercise the default-callback guard with a controlled keep-default mode. * @param sink Assigned sink name that would be reinstalled. * @param keep_default keep_default_sink value to test with. - * @param external_audio external_audio value to test with. * @return True when the production guard installs the reassertion callback. */ - bool installs_default_callback(const std::string &sink, bool keep_default, bool external_audio) { + bool installs_default_callback(const std::string &sink, bool keep_default) { audio_control_t control; auto previous_keep = std::exchange(config::audio.keep_default_sink, keep_default); - auto previous_external = std::exchange(config::audio.external_audio, external_audio); bool installed = control.should_install_default_callback(sink); config::audio.keep_default_sink = previous_keep; - config::audio.external_audio = previous_external; return installed; } /** - * @brief Exercise the startup-reset guard with controlled hands-off modes. + * @brief Exercise the startup-reset guard with a controlled keep-default mode. * @param keep_default keep_default_sink value to test with. - * @param external_audio external_audio value to test with. * @return True when the production guard permits resetting the default device. */ - bool resets_default_device(bool keep_default, bool external_audio) { + bool resets_default_device(bool keep_default) { audio_control_t control; auto previous_keep = std::exchange(config::audio.keep_default_sink, keep_default); - auto previous_external = std::exchange(config::audio.external_audio, external_audio); bool resets = control.should_reset_default_device(); config::audio.keep_default_sink = previous_keep; - config::audio.external_audio = previous_external; return resets; } /** - * @brief Exercise the driver-install guard with controlled hands-off modes. + * @brief Exercise the driver-install guard with a controlled keep-default mode. * @param keep_default keep_default_sink value to test with. - * @param external_audio external_audio value to test with. * @param install_requested install_steam_drivers value to test with. * @return True when the production guard permits installing the Steam drivers. */ - bool installs_steam_drivers(bool keep_default, bool external_audio, bool install_requested) { + bool installs_steam_drivers(bool keep_default, bool install_requested) { audio_control_t control; auto previous_keep = std::exchange(config::audio.keep_default_sink, keep_default); - auto previous_external = std::exchange(config::audio.external_audio, external_audio); auto previous_install = std::exchange(config::audio.install_steam_drivers, install_requested); bool installs = control.should_install_steam_drivers(); config::audio.keep_default_sink = previous_keep; - config::audio.external_audio = previous_external; config::audio.install_steam_drivers = previous_install; return installs; } @@ -1670,6 +1653,19 @@ namespace platf::audio { return static_cast(control.get_sink_device(sink)); } + /** + * @brief Report host and virtual sinks through the production discovery path. + * + * @param device_enum Device enumerator supplied by the test. + * @return Sinks reported for the current configuration, when any. + */ + std::optional reported_sinks(IMMDeviceEnumerator *device_enum) { + audio_control_t control; + device_enum->AddRef(); + control.device_enum.reset(device_enum); + return control.sink_info(); + } + /** * @brief Exercise microphone creation with controlled assigned and configured sinks. * diff --git a/src_assets/common/assets/web/Config.vue b/src_assets/common/assets/web/Config.vue index c8129d4ccaa..f4c4187f6bf 100644 --- a/src_assets/common/assets/web/Config.vue +++ b/src_assets/common/assets/web/Config.vue @@ -142,6 +142,7 @@ import { computed, toRaw } from 'vue' import Navbar from './Navbar.vue' import { apiFetch } from './fetch_utils' + import { isConfigBoolEnabled } from './config_bool' import configTabs from './configs/config_tabs.json' import General from './configs/tabs/General.vue' import Inputs from './configs/tabs/Inputs.vue' @@ -191,6 +192,25 @@ ); } + /** + * Migrate the legacy external_audio option into keep_default_sink. + * + * An explicit keep_default_sink value wins; the legacy key is always dropped so + * the next save persists only the unified key. + * + * @param {Object} config Configuration object to migrate in place. + */ + function migrateExternalAudioConfig(config) { + if (!Object.hasOwn(config, 'external_audio')) { + return; + } + const keepDefaultSink = config.keep_default_sink; + if ((keepDefaultSink === undefined || keepDefaultSink === '') && isConfigBoolEnabled(config.external_audio)) { + config.keep_default_sink = 'enabled'; + } + delete config.external_audio; + } + export default { components: { Navbar, @@ -292,6 +312,8 @@ delete this.config.status; delete this.config.version; + migrateExternalAudioConfig(this.config); + // Parse the special options before population if available const specialOptions = ["dd_mode_remapping", "global_prep_cmd"] for (const optionKey of specialOptions) { diff --git a/src_assets/common/assets/web/config_bool.js b/src_assets/common/assets/web/config_bool.js new file mode 100644 index 00000000000..ac692b010d9 --- /dev/null +++ b/src_assets/common/assets/web/config_bool.js @@ -0,0 +1,15 @@ +/** + * Check whether a configuration value enables a boolean option. + * + * Mirrors config::to_bool in src/config.cpp; keep this set in sync with the backend. + * + * @param {*} value Configuration value. + * @returns {boolean} Whether the value enables the option. + */ +export function isConfigBoolEnabled(value) { + if (value === true || value === 1) { + return true + } + const normalized = String(value ?? '').toLowerCase(); + return ['true', 'yes', 'enable', 'enabled', 'on'].includes(normalized) || normalized.includes('1'); +} diff --git a/src_assets/common/assets/web/configs/config_tabs.json b/src_assets/common/assets/web/configs/config_tabs.json index fce854371b4..2e3a9eaec3a 100644 --- a/src_assets/common/assets/web/configs/config_tabs.json +++ b/src_assets/common/assets/web/configs/config_tabs.json @@ -42,7 +42,6 @@ "virtual_sink": "", "stream_audio": "enabled", "install_steam_audio_drivers": "enabled", - "external_audio": "disabled", "keep_default_sink": "disabled", "adapter_name": "", "output_name": "", diff --git a/src_assets/common/assets/web/configs/tabs/AudioVideo.vue b/src_assets/common/assets/web/configs/tabs/AudioVideo.vue index c7d3a673e2c..d24ab3c7886 100644 --- a/src_assets/common/assets/web/configs/tabs/AudioVideo.vue +++ b/src_assets/common/assets/web/configs/tabs/AudioVideo.vue @@ -75,18 +75,6 @@ const config = ref(props.config) default="true" > - - - - > 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/windows/test_audio.cpp b/tests/unit/platform/windows/test_audio.cpp index add421f3557..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,15 +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 external_audio); - bool resets_default_device(bool keep_default, bool external_audio); - bool installs_steam_drivers(bool keep_default, bool external_audio, bool install_requested); + 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); @@ -222,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; @@ -254,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; @@ -329,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; @@ -400,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)); @@ -490,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"}; @@ -603,21 +619,17 @@ TEST(WindowsAudioTest, KeepDefaultModeCapturesWithoutSwapping) { TEST(WindowsAudioTest, KeepDefaultModeInstallsNoReassertionCallback) { constexpr const char *virtual_sink = "virtual-Stereoendpoint-id"; - EXPECT_TRUE(platf::audio::tests::installs_default_callback(virtual_sink, false, false)); - EXPECT_FALSE(platf::audio::tests::installs_default_callback(virtual_sink, true, false)); - EXPECT_FALSE(platf::audio::tests::installs_default_callback(virtual_sink, false, true)); - EXPECT_FALSE(platf::audio::tests::installs_default_callback(virtual_sink, true, true)); - EXPECT_FALSE(platf::audio::tests::installs_default_callback("endpoint-id", false, false)); + 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, HandsOffModesSkipDefaultResetAndDriverInstall) { - EXPECT_TRUE(platf::audio::tests::resets_default_device(false, false)); - EXPECT_FALSE(platf::audio::tests::resets_default_device(true, false)); - EXPECT_FALSE(platf::audio::tests::resets_default_device(false, true)); - EXPECT_TRUE(platf::audio::tests::installs_steam_drivers(false, false, true)); - EXPECT_FALSE(platf::audio::tests::installs_steam_drivers(true, false, true)); - EXPECT_FALSE(platf::audio::tests::installs_steam_drivers(false, true, true)); - EXPECT_FALSE(platf::audio::tests::installs_steam_drivers(false, false, 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 9141be4ebb2..c46430a2b8c 100644 --- a/tests/unit/test_audio.cpp +++ b/tests/unit/test_audio.cpp @@ -8,6 +8,7 @@ // local includes #include +#include #include #include @@ -199,6 +200,12 @@ TEST(CaptureRoutingTest, SwapPathKeepsVirtualSinkSelection) { 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); @@ -222,6 +229,27 @@ TEST(CaptureRoutingTest, FallsBackToHostWithoutVirtualSinks) { 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. @@ -255,3 +283,129 @@ TEST(AudioControlAdapterTest, LegacyBackendKeepsSwapBehavior) { EXPECT_EQ(control.capture_sink("any-sink"), 0); EXPECT_TRUE(control.set_sink_called); } + +TEST(AudioControlAdapterTest, DefaultCaptureTargetSetterIsNoOp) { + legacy_audio_control_t control; + // Recording a capture target must be a safe no-op on legacy backends. + 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); +} + +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; + } + + 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 { + 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() { + config::audio.keep_default_sink = keep_default_sink; + config::audio.sink = sink; + } + }; +} // 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"); +} diff --git a/tests/unit/test_config.cpp b/tests/unit/test_config.cpp index 8af8427bd48..e2aaa04da37 100644 --- a/tests/unit/test_config.cpp +++ b/tests/unit/test_config.cpp @@ -460,3 +460,35 @@ TEST(KeepDefaultSinkConfigTest, MissingKeyLeavesValueUnchanged) { config::audio.keep_default_sink = original_keep_default_sink; } + +/** + * @brief Verify the deprecated external_audio key enables keep_default_sink. + */ +TEST(KeepDefaultSinkConfigTest, LegacyExternalAudioEnablesKeepDefaultSink) { + const bool original_keep_default_sink = config::audio.keep_default_sink; + + config::audio.keep_default_sink = false; + config::apply_config_for_test("external_audio = enabled\n"); + EXPECT_TRUE(config::audio.keep_default_sink); + + config::audio.keep_default_sink = false; + config::apply_config_for_test("external_audio = disabled\n"); + EXPECT_FALSE(config::audio.keep_default_sink); + + config::audio.keep_default_sink = original_keep_default_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/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..50b75054555 --- /dev/null +++ b/tests/web/ConfigMigration.test.js @@ -0,0 +1,82 @@ +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) { + const fetchMock = vi.fn(async (url, options) => { + if (url === './api/config' && !options) { + return { json: async () => ({ platform: 'windows', 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 }) + + 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: '' }) + + expect(wrapper.vm.config.keep_default_sink).toBe('enabled') + 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' }) + + 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 b2d264e8d35..00000000000 --- a/tests/web/ExternalAudio.test.js +++ /dev/null @@ -1,58 +0,0 @@ -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' - -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', - 'keep_default_sink', - ]) - 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('
Description - Capture the selected audio sink without changing the host default sink. When disabled, Sunshine sets the - selected sink as the host default sink while streaming. - @note{Platform support: Linux captures the configured sink (or the host sink when nothing is - configured) and adopts pre-existing null sinks instead of unloading them. Windows captures the - target endpoint directly, skips the Steam driver install and the startup default-device reset, - and never reinstalls the default when it changes. macOS already captures through a system tap - or the selected input without touching the default output, so the option is honored natively.} + This replaces the Windows-only external_audio option. An existing + external_audio = enabled setting is migrated to keep_default_sink = enabled + on upgrade, unless keep_default_sink is also set. Unlike the old Windows mode, an + explicit [audio_sink](#audio_sink) is no longer required. Note that [virtual_sink](#virtual_sink) + and Moonlight's host-playback selection only apply on the swap path; in keep-default mode the + capture target is the configured audio_sink, or the host sink when none is configured. + @note{Platform behavior:
+ Windows: captures the target endpoint directly and is hands-off, so an external + router such as VoiceMeeter or GoXLR keeps owning endpoint defaults and formats; it also skips the + Steam driver install, the startup default-device reset, and default reinstallation.
+ Linux: captures the configured sink's monitor, or the host sink's monitor when + none is configured, and adopts pre-existing null sinks instead of unloading them.
+ FreeBSD: captures the configured sink's monitor, or the host sink's monitor when + none is configured, without changing the default sink.
+ macOS: honors the option natively through a system tap or the selected input, + without touching the default output.}
', '
') - 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') - }) -}) From dcb684c9d05c4bb395e32ba1f1cfaad8b46d4d80 Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Mon, 9 Nov 2026 15:56:45 -0700 Subject: [PATCH 10/25] feat(audio): harden capture with session guard, params bundle, and heap-owned activation blob Unify keep-default capture under one shared key with a thread-safe session guard, a microphone params bundle, and WASAPI process loopback using a heap-owned activation blob plus PID revalidation. --- src/audio.cpp | 98 +++++++- src/audio.h | 89 +++++++ src/platform/common.h | 47 ++++ tests/unit/test_audio.cpp | 472 +++++++++++++++++++++++++++++++++++++- 4 files changed, 697 insertions(+), 9 deletions(-) diff --git a/src/audio.cpp b/src/audio.cpp index fefeb7e0bb3..2b05ee171f8 100644 --- a/src/audio.cpp +++ b/src/audio.cpp @@ -4,6 +4,7 @@ */ // standard includes #include +#include #include // lib includes @@ -33,6 +34,17 @@ namespace audio { static void stop_audio_control(audio_ctx_t &); static void apply_surround_params(opus_stream_config_t &stream, const stream_params_t ¶ms); + /** + * @brief Serializes capture-target refresh, microphone creation, and target release across concurrent sessions. + * + * All capture() threads share one audio control. Each session's + * session_capture_target_t guard holds this mutex across every + * refresh/microphone pair (and across the exit clear), which keeps one + * session from resetting the shared target between another session's + * refresh and microphone creation. + */ + static std::mutex capture_target_mutex; + /** * @brief Select the Opus stream configuration for a channel count and quality tier. * @@ -152,8 +164,69 @@ namespace audio { } } + /** + * @brief Select the capture sink for startup without touching the capture target. + * + * @param control Platform audio controller used for sink selection. + * @param routing Startup plan resolved by resolve_capture_routing(). + * @return True when capture may proceed; false when sink selection failed and the caller must abort. + */ + bool select_audio_capture_sink(platf::audio_control_t &control, const capture_routing_t &routing) { + if (routing.swap_at_startup) { + // The target is already the host sink when there is nothing to restore, + // so the swap is skipped entirely instead of reasserting the default. + if (routing.restore_at_teardown && control.set_sink(routing.target)) { + return false; + } + } else if (control.capture_sink(routing.target)) { + return false; + } + return true; + } + + /** + * @brief Create a guard that owns no target until the first refresh. + */ + session_capture_target_t::session_capture_target_t(platf::audio_control_t &control, platf::audio_capture_intent_e intent, std::mutex &mutex): + control_ {&control}, + intent_ {intent}, + mutex_ {&mutex} { + } + + /** + * @brief Destroy the guard, releasing the recorded target when one exists. + */ + session_capture_target_t::~session_capture_target_t() { + if (!recorded_) { + return; + } + std::lock_guard lock {*mutex_}; + control_->clear_capture_target(intent_, 0); + } + + /** + * @brief Refresh the endpoint capture target, then create the microphone for it. + */ + std::unique_ptr session_capture_target_t::create_microphone(const platf::microphone_params_t &mic_params) { + // Refresh the endpoint target before every microphone creation. The lock + // covers the refresh/microphone pair, and the refresh is recorded even + // when microphone creation fails so teardown still releases this + // session's target. + std::lock_guard lock {*mutex_}; + control_->set_capture_target(intent_, 0); + recorded_ = true; + return control_->microphone(mic_params); + } + /** * @brief Run the capture loop for this backend. + * + * Sessions share one audio control: sink selection runs through + * select_audio_capture_sink(), the restore flag is assigned directly from + * the resolved routing, and one session_capture_target_t guard owns the + * shared target for the session. Both microphone call sites (startup and + * reinitialization) are the same single guard call, and guard destruction + * releases the shared target only when a refresh ran. */ void capture(safe::mail_t mail, config_t config, stream::session_t *channel_data) { auto shutdown_event = mail->event(mail::shutdown); @@ -186,6 +259,11 @@ namespace audio { const auto capture_intent = resolve_audio_capture_intent(config::audio.keep_default_sink, config::audio.sink); + // One RAII owner for the session's shared capture target. Destruction + // releases exactly the last recorded target, or nothing when no refresh + // ran, so one session cannot wipe another session's recorded target. + session_capture_target_t capture_target {*control, capture_intent, capture_target_mutex}; + // Only the first to start a session may change the default sink if (!ref->sink_flag->exchange(true, std::memory_order_acquire)) { // One decision point for swap-vs-capture: the recorded restore flag keeps @@ -207,12 +285,8 @@ namespace audio { << "], keep_default_sink requested ["sv << config::audio.keep_default_sink << "], keep_default_sink supported ["sv << control->supports_keep_default_sink() << "], capture intent ["sv << audio_capture_intent_name(capture_intent) << ']'; - if (routing.swap_at_startup) { - // If the selected sink is different than the current one, change sinks. - if (ref->restore_sink && control->set_sink(routing.target)) { - return; - } - } else if (control->capture_sink(routing.target)) { + // If the selected sink cannot be selected, there is no audio to capture. + if (!select_audio_capture_sink(*control, routing)) { return; } } @@ -220,7 +294,15 @@ namespace audio { auto frame_size = config.packetDuration * stream.sampleRate / 1000; bool host_audio = config.flags[config_t::HOST_AUDIO]; bool continuous_audio = config.flags[config_t::CONTINUOUS_AUDIO]; - auto mic = control->microphone(stream.mapping, stream.channelCount, stream.sampleRate, frame_size, continuous_audio, host_audio); + const platf::microphone_params_t mic_params { + stream.mapping, + stream.channelCount, + static_cast(stream.sampleRate), + static_cast(frame_size), + continuous_audio, + host_audio + }; + auto mic = capture_target.create_microphone(mic_params); if (!mic) { return; } @@ -257,7 +339,7 @@ namespace audio { BOOST_LOG(info) << "Reinitializing audio capture"sv; mic.reset(); do { - mic = control->microphone(stream.mapping, stream.channelCount, stream.sampleRate, frame_size, continuous_audio, host_audio); + mic = capture_target.create_microphone(mic_params); if (!mic) { BOOST_LOG(warning) << "Couldn't re-initialize audio input"sv; } diff --git a/src/audio.h b/src/audio.h index 73afdfb0dfb..2969c217e78 100644 --- a/src/audio.h +++ b/src/audio.h @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -149,6 +150,10 @@ namespace audio { * configured: without a swap, applications stay on the host default, so * capturing the virtual sink's monitor would yield silence. * + * The seven positional parameters are an accepted deviation from the bundle + * rule: one call site, one pure function, and bundling would only rename the + * same seven inputs. + * * @param keep_default_requested Value of config::audio.keep_default_sink. * @param platform_supports_keep_default Value of platf::audio_control_t::supports_keep_default_sink(). * @param host_audio_enabled Whether host playback stays enabled (Moonlight HOST_AUDIO flag). @@ -239,6 +244,90 @@ namespace audio { return "unknown"; } + /** + * @brief Select the capture sink for startup without touching the capture target. + * + * Encodes the swap-vs-capture dispatch used by capture(): the swap path swaps + * the host default via set_sink(), the capture-only path captures via + * capture_sink(). A swap with nothing to restore skips the sink call entirely + * because the target is already the host sink. + * + * @param control Platform audio controller used for sink selection. + * @param routing Startup plan resolved by resolve_capture_routing(). + * @return True when capture may proceed; false when sink selection failed and the caller must abort. + */ + bool select_audio_capture_sink(platf::audio_control_t &control, const capture_routing_t &routing); + + /** + * @brief RAII owner of one session's shared capture target. + * + * Sessions share one audio control. Every create_microphone() call refreshes + * the endpoint target (set_capture_target()) and creates the microphone + * under one lock acquisition, so a refresh can never be dropped or + * interleaved with another session's refresh. Destruction releases exactly + * the last recorded target via clear_capture_target(), or nothing when no + * refresh ever ran (for example after an aborted sink selection), so one + * session cannot wipe another session's recorded target on its way out. + * + * The referenced control and mutex must outlive the guard. + */ + class session_capture_target_t { + public: + /** + * @brief Create a guard that owns no target until the first refresh. + * + * @param control Platform audio controller holding the shared capture target. + * @param intent Capture intent resolved from the audio configuration. + * @param mutex Serializes refresh, microphone creation, and target release across sessions. + */ + session_capture_target_t(platf::audio_control_t &control, platf::audio_capture_intent_e intent, std::mutex &mutex); + + /** + * @brief Destroy the guard, releasing the recorded target when one exists. + */ + ~session_capture_target_t(); + + session_capture_target_t(const session_capture_target_t &) = delete; + session_capture_target_t &operator=(const session_capture_target_t &) = delete; + + /** + * @brief Refresh the endpoint capture target, then create the microphone for it. + * + * The refresh always runs before microphone creation so a dropped refresh + * is observable: set_capture_target() is called on every invocation, + * including reinitializations and microphone failures. The lock is held + * across the refresh/microphone pair so the shared target cannot change + * in between. The endpoint form always records PID 0: per-process capture + * is not selected here. + * + * @param mic_params Microphone capture parameters for the requested layout. + * @return Microphone capture object, or nullptr when creation failed. + */ + [[nodiscard]] std::unique_ptr create_microphone(const platf::microphone_params_t &mic_params); + + /** + * @brief Get the capture intent owned by this session. + * @return Capture intent passed to the constructor. + */ + [[nodiscard]] platf::audio_capture_intent_e intent() const noexcept { + return intent_; + } + + /** + * @brief Check whether this session recorded a target that teardown will release. + * @return True after the first create_microphone() call. + */ + [[nodiscard]] bool recorded() const noexcept { + return recorded_; + } + + private: + platf::audio_control_t *control_; ///< Controller holding the shared capture target. + platf::audio_capture_intent_e intent_; ///< Capture intent recorded by this session. + std::mutex *mutex_; ///< Mutex serializing refresh, creation, and release. + bool recorded_ = false; ///< Whether this session called set_capture_target(). + }; + /** * @brief Byte buffer used for encoded audio packet payloads. */ diff --git a/src/platform/common.h b/src/platform/common.h index d67810f364e..5352ca6c09e 100644 --- a/src/platform/common.h +++ b/src/platform/common.h @@ -890,6 +890,22 @@ namespace platf { pinned_sink, ///< Capture one explicitly configured sink, device, or input. }; + /** + * @brief Microphone capture parameters for audio_control_t::microphone(). + * + * Groups the six capture arguments into one named bundle so call sites pass + * a single struct instead of a long positional list. Field order matches the + * positional microphone() override for a mechanical translation. + */ + struct microphone_params_t { + const std::uint8_t *mapping = nullptr; ///< Opus channel mapping table for the requested layout. + int channels = 2; ///< Number of audio channels in the stream. + std::uint32_t sample_rate = 48000; ///< Audio sample rate in hertz. + std::uint32_t frame_size = 0; ///< Number of samples captured per audio frame. + bool continuous_audio = false; ///< Whether silent audio should continue to be emitted. + bool host_audio_enabled = false; ///< Whether host playback should remain enabled during capture. + }; + /** * @brief Platform audio controller that manages sinks and microphone capture. */ @@ -942,6 +958,21 @@ namespace platf { virtual void set_capture_target([[maybe_unused]] audio_capture_intent_e intent, [[maybe_unused]] std::uint32_t process_id) { } + /** + * @brief Release the recorded capture target when it still belongs to the caller. + * + * The default implementation is a no-op so backends without per-process + * capture are unchanged. Backends that store a capture target override + * this to reset to endpoint capture only when the stored intent and PID + * still equal the given ones, so one exiting session cannot wipe another + * session's recorded 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. + */ + virtual void clear_capture_target([[maybe_unused]] audio_capture_intent_e intent, [[maybe_unused]] std::uint32_t process_id) { + } + /** * @brief Create a microphone capture stream for the requested layout. * @@ -955,6 +986,22 @@ namespace platf { */ virtual std::unique_ptr microphone(const std::uint8_t *mapping, int channels, std::uint32_t sample_rate, std::uint32_t frame_size, bool continuous, [[maybe_unused]] bool host_audio_enabled) = 0; + /** + * @brief Create a microphone capture stream from a parameter bundle. + * + * Non-virtual convenience wrapper: forwards every field to the positional + * microphone() override, so backends keep overriding that form. New code + * calls this overload; derived classes that override the positional form + * hide it for direct calls, so callers must use a base-class reference or + * add a using-declaration. + * + * @param params Capture parameters forwarded to the positional override. + * @return Microphone capture object for the requested audio layout. + */ + std::unique_ptr microphone(const microphone_params_t ¶ms) { + return microphone(params.mapping, params.channels, params.sample_rate, params.frame_size, params.continuous_audio, params.host_audio_enabled); + } + /** * @brief Check if the audio sink is available in the system. * @param sink Sink to be checked. diff --git a/tests/unit/test_audio.cpp b/tests/unit/test_audio.cpp index c46430a2b8c..d64979c1a13 100644 --- a/tests/unit/test_audio.cpp +++ b/tests/unit/test_audio.cpp @@ -6,6 +6,11 @@ // test includes #include "../tests_common.h" +// standard includes +#include +#include +#include + // local includes #include #include @@ -277,6 +282,13 @@ namespace { }; } // 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()); @@ -284,14 +296,34 @@ TEST(AudioControlAdapterTest, LegacyBackendKeepsSwapBehavior) { 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; - // Recording a capture target must be a safe no-op on legacy backends. 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. @@ -409,3 +441,441 @@ TEST(SinkAvailabilityProbeTest, UnsupportedBackendProbesHostSink) { 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; + } + + 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(const std::string &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::uint8_t mapping[] = {0, 1, 4, 5, 2, 3}; + const platf::microphone_params_t params {mapping, 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); + 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); +} From 29cb270f64c35f0bdbc2fb99ad2fe161dcc13185 Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Tue, 10 Nov 2026 09:34:03 -0700 Subject: [PATCH 11/25] refactor(audio): modernize capture plumbing with C++23 idioms Behavior-preserving modernization of the audio capture path: string_view for read-only string parameters, using-enum with exhaustive switches, constexpr/noexcept/nodiscard on pure predicates and intent helpers, const-correct virtual-sink helpers, explicit wstring materialization at the UTF-8 boundary, a params-bundle using-declaration for the Linux backend, and documented no-op capture-target defaults. No behavior change. --- src/audio.cpp | 9 +++++++-- src/audio.h | 30 ++++++++++++++++-------------- src/platform/common.h | 2 ++ src/platform/linux/audio.cpp | 3 +++ src/platform/windows/audio.cpp | 25 ++++++++++++++----------- 5 files changed, 42 insertions(+), 27 deletions(-) diff --git a/src/audio.cpp b/src/audio.cpp index 2b05ee171f8..899c0b60478 100644 --- a/src/audio.cpp +++ b/src/audio.cpp @@ -42,8 +42,13 @@ namespace audio { * refresh/microphone pair (and across the exit clear), which keeps one * session from resetting the shared target between another session's * refresh and microphone creation. + * + * @return Reference to the process-lifetime capture-target mutex. */ - static std::mutex capture_target_mutex; + std::mutex &capture_target_mutex() { + static std::mutex mutex; + return mutex; + } /** * @brief Select the Opus stream configuration for a channel count and quality tier. @@ -262,7 +267,7 @@ namespace audio { // One RAII owner for the session's shared capture target. Destruction // releases exactly the last recorded target, or nothing when no refresh // ran, so one session cannot wipe another session's recorded target. - session_capture_target_t capture_target {*control, capture_intent, capture_target_mutex}; + session_capture_target_t capture_target {*control, capture_intent, capture_target_mutex()}; // Only the first to start a session may change the default sink if (!ref->sink_flag->exchange(true, std::memory_order_acquire)) { diff --git a/src/audio.h b/src/audio.h index 2969c217e78..214d0bb15c8 100644 --- a/src/audio.h +++ b/src/audio.h @@ -168,14 +168,14 @@ namespace audio { bool platform_supports_keep_default, bool host_audio_enabled, int channel_count, - const std::string &host_sink, - const std::string &config_sink, + std::string_view host_sink, + std::string_view config_sink, const std::optional &null_sinks ) { // Order of priority: explicit audio sink, virtual sink, host. - std::string selected = host_sink; + std::string selected {host_sink}; if (!config_sink.empty()) { - selected = config_sink; + selected = std::string {config_sink}; } // Prefer the virtual sink if host playback is disabled or there's no other sink. @@ -204,7 +204,7 @@ namespace audio { routing.target = selected; } else { routing.restore_at_teardown = false; - routing.target = config_sink.empty() ? host_sink : config_sink; + routing.target = config_sink.empty() ? std::string {host_sink} : std::string {config_sink}; } return routing; @@ -219,11 +219,12 @@ namespace audio { * keep-default (Play on this PC too), and client-only otherwise * (Quiet streaming). */ - [[nodiscard]] inline platf::audio_capture_intent_e resolve_audio_capture_intent(bool keep_default_requested, const std::string &config_sink) { + [[nodiscard]] constexpr platf::audio_capture_intent_e resolve_audio_capture_intent(bool keep_default_requested, std::string_view config_sink) noexcept { + using enum platf::audio_capture_intent_e; if (!config_sink.empty()) { - return platf::audio_capture_intent_e::pinned_sink; + return pinned_sink; } - return keep_default_requested ? platf::audio_capture_intent_e::host_and_client : platf::audio_capture_intent_e::client_only; + return keep_default_requested ? host_and_client : client_only; } /** @@ -232,13 +233,14 @@ namespace audio { * @param intent Capture intent to name. * @return Intent name without the enum prefix. */ - [[nodiscard]] inline std::string_view audio_capture_intent_name(platf::audio_capture_intent_e intent) { + [[nodiscard]] constexpr std::string_view audio_capture_intent_name(platf::audio_capture_intent_e intent) noexcept { + using enum platf::audio_capture_intent_e; switch (intent) { - case platf::audio_capture_intent_e::client_only: + case client_only: return "client_only"; - case platf::audio_capture_intent_e::host_and_client: + case host_and_client: return "host_and_client"; - case platf::audio_capture_intent_e::pinned_sink: + case pinned_sink: return "pinned_sink"; } return "unknown"; @@ -322,9 +324,9 @@ namespace audio { } private: - platf::audio_control_t *control_; ///< Controller holding the shared capture target. + platf::audio_control_t *control_; ///< Non-owning controller holding the shared capture target; must outlive the guard. platf::audio_capture_intent_e intent_; ///< Capture intent recorded by this session. - std::mutex *mutex_; ///< Mutex serializing refresh, creation, and release. + std::mutex *mutex_; ///< Non-owning mutex serializing refresh, creation, and release; typically audio::capture_target_mutex(). bool recorded_ = false; ///< Whether this session called set_capture_target(). }; diff --git a/src/platform/common.h b/src/platform/common.h index 5352ca6c09e..5780697b902 100644 --- a/src/platform/common.h +++ b/src/platform/common.h @@ -956,6 +956,7 @@ namespace platf { * @param process_id Operating-system PID to capture, or 0 for endpoint capture. */ virtual void set_capture_target([[maybe_unused]] audio_capture_intent_e intent, [[maybe_unused]] std::uint32_t process_id) { + // Intentionally empty: backends without per-process capture inherit this no-op. } /** @@ -971,6 +972,7 @@ namespace platf { * @param process_id PID recorded by the session being torn down, or 0 for endpoint capture. */ virtual void clear_capture_target([[maybe_unused]] audio_capture_intent_e intent, [[maybe_unused]] std::uint32_t process_id) { + // Intentionally empty: backends without per-process capture inherit this no-op. } /** diff --git a/src/platform/linux/audio.cpp b/src/platform/linux/audio.cpp index 8a1e619e321..21a99fe70fb 100644 --- a/src/platform/linux/audio.cpp +++ b/src/platform/linux/audio.cpp @@ -329,6 +329,9 @@ namespace platf { }; public: + // Keep the params-bundle overload visible: the positional override below would otherwise hide it. + using audio_control_t::microphone; + loop_t loop; ///< PulseAudio threaded mainloop instance. ctx_t ctx; ///< PulseAudio threaded mainloop context. std::string requested_sink; ///< Requested sink. diff --git a/src/platform/windows/audio.cpp b/src/platform/windows/audio.cpp index a86429c9b11..e3c69afe8a8 100644 --- a/src/platform/windows/audio.cpp +++ b/src/platform/windows/audio.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include @@ -944,17 +945,17 @@ namespace platf::audio { * @return A pair of device_id and format reference if the sink name matches * our naming scheme for virtual audio sinks, `std::nullopt` otherwise. */ - std::optional>> extract_virtual_sink_info(const std::string &sink) { + std::optional>> extract_virtual_sink_info(std::string_view sink) const { // Encoding format: // [virtual-(format name)]device_id - std::string current = sink; + std::string_view current = sink; if (auto prefix = "virtual-"sv; current.find(prefix) == 0) { current = current.substr(prefix.size(), current.size() - prefix.size()); for (const auto &format : formats) { auto &name = format.name; if (current.find(name) == 0) { - auto device_id = utf_utils::from_utf8(current.substr(name.size(), current.size() - name.size())); + auto device_id = utf_utils::from_utf8(std::string {current.substr(name.size(), current.size() - name.size())}); return std::make_pair(device_id, std::reference_wrapper(format)); } } @@ -1186,7 +1187,7 @@ namespace platf::audio { * @param sink Assigned sink name that would be reinstalled. * @return True when the reassertion callback may be installed. */ - bool should_install_default_callback(const std::string &sink) { + [[nodiscard]] bool should_install_default_callback(std::string_view sink) const { return static_cast(extract_virtual_sink_info(sink)) && !config::audio.keep_default_sink; } @@ -1195,7 +1196,7 @@ namespace platf::audio { * * @return False in hands-off modes that never touch the host default. */ - bool should_reset_default_device() { + [[nodiscard]] bool should_reset_default_device() const noexcept { return !config::audio.keep_default_sink; } @@ -1207,7 +1208,7 @@ namespace platf::audio { * * @return False in hands-off modes that never touch the host audio graph. */ - bool should_install_steam_drivers() { + [[nodiscard]] bool should_install_steam_drivers() const noexcept { return !config::audio.keep_default_sink && config::audio.install_steam_drivers; } @@ -1247,13 +1248,13 @@ namespace platf::audio { * @param name Endpoint name or identifier to match across all fields. * @return Field list requiring every supported endpoint field to match the name. */ - audio_control_t::match_fields_list_t match_all_fields(const std::wstring &name) { + audio_control_t::match_fields_list_t match_all_fields(std::wstring_view name) { using enum match_field_e; return { - {device_id, name}, // {0.0.0.00000000}.{29dd7668-45b2-4846-882d-950f55bf7eb8} - {device_friendly_name, name}, // Digital Audio (S/PDIF) (High Definition Audio Device) - {device_description, name}, // Digital Audio (S/PDIF) - {adapter_friendly_name, name}, // High Definition Audio Device + {device_id, std::wstring {name}}, // {0.0.0.00000000}.{29dd7668-45b2-4846-882d-950f55bf7eb8} + {device_friendly_name, std::wstring {name}}, // Digital Audio (S/PDIF) (High Definition Audio Device) + {device_description, std::wstring {name}}, // Digital Audio (S/PDIF) + {adapter_friendly_name, std::wstring {name}}, // High Definition Audio Device }; } @@ -1300,6 +1301,8 @@ namespace platf::audio { for (size_t i = 0; i < match_list.size(); i++) { if (matched[i].empty()) { const wchar_t *match_value = nullptr; + // Note: no using-enum here; the enumerator names would shadow the + // device_id/device_friendly_name/adapter_friendly_name locals below. switch (match_list[i].first) { case match_field_e::device_id: match_value = device_id.c_str(); From b4073e8fffb720f0f1e4e3c25c9213f5ffd96d94 Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Tue, 10 Nov 2026 09:34:17 -0700 Subject: [PATCH 12/25] refactor(audio): address valid Sonar findings in capture path and tests Production: extract the find_device_id endpoint probe, rename shadowed error locals, std::format for sink names, dropped redundant lambda return types, CTAD atomics, using-enum in the concurrency seam, and the macOS params-bundle using-declaration. Tests: noexcept guard destructor with deleted copies, three params-bundle using-declarations, string_view call_index, std::array mapping. Behavior-preserving throughout. --- src/platform/macos/microphone.mm | 3 +++ tests/unit/test_audio.cpp | 35 +++++++++++++++++++++++++------- 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/src/platform/macos/microphone.mm b/src/platform/macos/microphone.mm index f07520d7ea1..2741ddafb52 100644 --- a/src/platform/macos/microphone.mm +++ b/src/platform/macos/microphone.mm @@ -70,6 +70,9 @@ capture_e sample(std::vector &sample_in) override { AVCaptureDevice *audio_capture_device {}; ///< Audio capture device. public: + // Keep the params-bundle overload visible: the positional override below would otherwise hide it. + using audio_control_t::microphone; + /** * @brief Update the sink value on the backend. * diff --git a/tests/unit/test_audio.cpp b/tests/unit/test_audio.cpp index d64979c1a13..993b51d63a9 100644 --- a/tests/unit/test_audio.cpp +++ b/tests/unit/test_audio.cpp @@ -7,8 +7,10 @@ #include "../tests_common.h" // standard includes +#include #include #include +#include #include // local includes @@ -266,6 +268,9 @@ namespace { 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; } @@ -342,6 +347,9 @@ namespace { 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; } @@ -384,12 +392,22 @@ namespace { * @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() { - config::audio.keep_default_sink = keep_default_sink; - config::audio.sink = sink; + ~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. + } } }; } // namespace @@ -500,6 +518,9 @@ namespace { 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; @@ -527,7 +548,7 @@ namespace { * @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(const std::string &prefix) const { + 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; @@ -864,15 +885,15 @@ TEST(CaptureOrchestrationTest, StartupSequenceRunsDispatchRefreshCreateAndReleas TEST(AudioControlAdapterTest, StructMicrophoneForwardsEveryField) { recording_audio_control_t control; platf::audio_control_t &base = control; - const std::uint8_t mapping[] = {0, 1, 4, 5, 2, 3}; - const platf::microphone_params_t params {mapping, 6, 48000, 480, true, true}; + 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); + 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); From 5b334af7f58f91a2e7bd92f00d98c1e61a5fe760 Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Tue, 10 Nov 2026 10:16:03 -0700 Subject: [PATCH 13/25] refactor(audio): use CTAD for live_count and report test guard restore failures --- tests/unit/test_audio.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/unit/test_audio.cpp b/tests/unit/test_audio.cpp index 993b51d63a9..7c6211dcd7c 100644 --- a/tests/unit/test_audio.cpp +++ b/tests/unit/test_audio.cpp @@ -8,6 +8,7 @@ // standard includes #include +#include #include #include #include @@ -406,7 +407,9 @@ namespace { config::audio.keep_default_sink = keep_default_sink; config::audio.sink = sink; } catch (...) { - // Teardown restore must not throw during stack unwinding. + // 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); } } }; From 734e3abf7b68df8e79fc69b1774eeef5a2436f1b Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Tue, 10 Nov 2026 14:34:16 -0700 Subject: [PATCH 14/25] docs(audio): drop duplicated param docs from select_audio_capture_sink definition --- src/audio.cpp | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/audio.cpp b/src/audio.cpp index 899c0b60478..869514022d3 100644 --- a/src/audio.cpp +++ b/src/audio.cpp @@ -171,10 +171,6 @@ namespace audio { /** * @brief Select the capture sink for startup without touching the capture target. - * - * @param control Platform audio controller used for sink selection. - * @param routing Startup plan resolved by resolve_capture_routing(). - * @return True when capture may proceed; false when sink selection failed and the caller must abort. */ bool select_audio_capture_sink(platf::audio_control_t &control, const capture_routing_t &routing) { if (routing.swap_at_startup) { From 34dacf5dce0f9e19549ae3e415dce61fb5e89822 Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Tue, 10 Nov 2026 14:34:16 -0700 Subject: [PATCH 15/25] style(tests): consolidate include groups in audio tests --- tests/unit/platform/linux/test_audio.cpp | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/tests/unit/platform/linux/test_audio.cpp b/tests/unit/platform/linux/test_audio.cpp index 1f58f298c8a..734a153e0e1 100644 --- a/tests/unit/platform/linux/test_audio.cpp +++ b/tests/unit/platform/linux/test_audio.cpp @@ -16,15 +16,10 @@ #include // local includes + #include "src/config.h" #include "src/platform/common.h" #include "src/thread_safe.h" - // test includes - #include "../../../tests_common.h" - - // local includes - #include "src/config.h" - namespace platf { bool fill_canonical_channel_map(int channels, pa_channel_map &pa_map); From 8cdf346d4e3cbf8b5696e3cf84fc2448a6de3cb5 Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Tue, 10 Nov 2026 15:06:15 -0700 Subject: [PATCH 16/25] refactor(audio): centralize recorded capture-target state in audio_control_t base --- src/audio.cpp | 5 + src/platform/common.h | 29 ++++++ src/platform/linux/audio.cpp | 11 ++- tests/unit/test_audio.cpp | 178 +++++++++++++++++++++++++++++++++++ 4 files changed, 219 insertions(+), 4 deletions(-) diff --git a/src/audio.cpp b/src/audio.cpp index 869514022d3..f7edc74c833 100644 --- a/src/audio.cpp +++ b/src/audio.cpp @@ -43,6 +43,11 @@ namespace audio { * session from resetting the shared target between another session's * refresh and microphone creation. * + * Lock order: this outer mutex is always taken before the backend-internal + * `platf::audio_control_t::capture_state_mutex_`, acquired inside + * `set_capture_target()`/`microphone()`/`clear_capture_target()`. Backends + * never take this mutex, so the order cannot invert. + * * @return Reference to the process-lifetime capture-target mutex. */ std::mutex &capture_target_mutex() { diff --git a/src/platform/common.h b/src/platform/common.h index 5780697b902..012aa6ecb90 100644 --- a/src/platform/common.h +++ b/src/platform/common.h @@ -1022,6 +1022,35 @@ namespace platf { * @brief Destroy the audio control. */ virtual ~audio_control_t() = default; + + protected: + mutable std::mutex capture_state_mutex_; ///< Guards `recorded_sink_` against concurrent sessions. + std::string recorded_sink_; ///< Sink recorded for later consumption in microphone(), possibly empty. + + /** + * @brief Record a capture sink for later consumption in microphone(). + * + * Thread-safe: the store runs under `capture_state_mutex_`, so concurrent + * sessions cannot tear the recorded sink mid-write. Opt-in helper only: + * the `capture_sink()` virtual keeps its legacy delegation so backends + * without keep-default capture are unchanged. + * + * @param sink Audio sink name to capture. + */ + void record_capture_sink(const std::string &sink) { + std::lock_guard lock {capture_state_mutex_}; + recorded_sink_ = sink; + } + + /** + * @brief Copy the recorded sink name under `capture_state_mutex_`. + * + * @return Recorded sink name, possibly empty when nothing was recorded. + */ + [[nodiscard]] std::string snapshot_recorded_sink() const { + std::lock_guard lock {capture_state_mutex_}; + return recorded_sink_; + } }; /** diff --git a/src/platform/linux/audio.cpp b/src/platform/linux/audio.cpp index 21a99fe70fb..03588e1eaba 100644 --- a/src/platform/linux/audio.cpp +++ b/src/platform/linux/audio.cpp @@ -334,7 +334,6 @@ namespace platf { loop_t loop; ///< PulseAudio threaded mainloop instance. ctx_t ctx; ///< PulseAudio threaded mainloop context. - std::string requested_sink; ///< Requested sink. static constexpr const char *stereo_name = "sink-sunshine-stereo"; ///< Persistent stereo null sink name. static constexpr const char *surround51_name = "sink-sunshine-surround51"; ///< Persistent 5.1 null sink name. @@ -670,7 +669,7 @@ namespace platf { // the new one just set! auto sink_name = config::audio.sink; if (sink_name.empty()) { - sink_name = requested_sink; + sink_name = snapshot_recorded_sink(); } if (sink_name.empty()) { sink_name = get_default_sink_name(); @@ -696,12 +695,16 @@ namespace platf { /** * @brief Capture the given sink without changing the host default. * + * Records the target under the base capture mutex for the monitor + * lookup in microphone(); this locking is new versus the previously + * unlocked store, but unobservable on the single-threaded capture path. + * * @param sink Audio sink name to capture. * @return Always 0: selecting a capture target cannot fail here. */ int capture_sink(const std::string &sink) override { BOOST_LOG(info) << "Keeping host default sink; capturing ["sv << sink << "] without swapping"sv; - requested_sink = sink; + record_capture_sink(sink); return 0; } @@ -737,7 +740,7 @@ namespace platf { return -1; } - requested_sink = sink; + record_capture_sink(sink); return 0; } diff --git a/tests/unit/test_audio.cpp b/tests/unit/test_audio.cpp index 7c6211dcd7c..6ddd664fce2 100644 --- a/tests/unit/test_audio.cpp +++ b/tests/unit/test_audio.cpp @@ -8,10 +8,13 @@ // standard includes #include +#include +#include #include #include #include #include +#include #include // local includes @@ -903,3 +906,178 @@ TEST(AudioControlAdapterTest, StructMicrophoneForwardsEveryField) { 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 { + record_capture_sink(sink); + 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 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()); +} From 7a669d4319733b6407669e37837a732c2cac3f1e Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Wed, 11 Nov 2026 02:45:21 -0700 Subject: [PATCH 17/25] refactor(audio): share keep-default capture body and hook paired target clear Hoist the identical keep-default capture_sink bodies into a protected base helper so both backends record through one path, and reset Windows creation-time identity via an on_capture_target_cleared() hook fired under the same lock hold as the shared record reset. --- src/platform/common.h | 17 +++++++++++++++++ src/platform/linux/audio.cpp | 5 +---- tests/unit/test_audio.cpp | 17 +++++++++++++++-- 3 files changed, 33 insertions(+), 6 deletions(-) diff --git a/src/platform/common.h b/src/platform/common.h index 012aa6ecb90..78560cfbfb2 100644 --- a/src/platform/common.h +++ b/src/platform/common.h @@ -1042,6 +1042,23 @@ namespace platf { recorded_sink_ = sink; } + /** + * @brief Capture the given sink without changing the host default. + * + * Shared keep-default body for backends whose capture path only records + * the target for `microphone()`: logs the decision, stores the sink under + * `capture_state_mutex_` via `record_capture_sink()`, and reports success. + * Backends that only observe the sink (macOS) keep their own override. + * + * @param sink Audio sink name to capture. + * @return Always 0: recording a capture target cannot fail here. + */ + int record_keep_default_capture_sink(const std::string &sink) { + BOOST_LOG(info) << "Keeping host default sink; capturing ["sv << sink << "] without swapping"sv; + record_capture_sink(sink); + return 0; + } + /** * @brief Copy the recorded sink name under `capture_state_mutex_`. * diff --git a/src/platform/linux/audio.cpp b/src/platform/linux/audio.cpp index 03588e1eaba..fd596e816ac 100644 --- a/src/platform/linux/audio.cpp +++ b/src/platform/linux/audio.cpp @@ -703,10 +703,7 @@ namespace platf { * @return Always 0: selecting a capture target cannot fail here. */ int capture_sink(const std::string &sink) override { - BOOST_LOG(info) << "Keeping host default sink; capturing ["sv << sink << "] without swapping"sv; - record_capture_sink(sink); - - return 0; + return record_keep_default_capture_sink(sink); } /** diff --git a/tests/unit/test_audio.cpp b/tests/unit/test_audio.cpp index 6ddd664fce2..bf56a7a6564 100644 --- a/tests/unit/test_audio.cpp +++ b/tests/unit/test_audio.cpp @@ -928,8 +928,7 @@ namespace { } int capture_sink(const std::string &sink) override { - record_capture_sink(sink); - return 0; + return record_keep_default_capture_sink(sink); } // Keep the params-bundle overload visible: the positional override below would otherwise hide it. @@ -1081,3 +1080,17 @@ TEST(BaseRecordTest, MacOsLikeNoOpLeavesRecordUntouched) { 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"); +} + From 4382c56f4dc1e35e59a04736c2e67ee7615286bd Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Sun, 15 Nov 2026 20:30:24 -0700 Subject: [PATCH 18/25] fix(audio): create microphone outside the capture-target lock --- src/audio.cpp | 25 +++++++++++++----------- src/audio.h | 13 ++++++------ src/platform/common.h | 9 +++++++++ tests/unit/platform/linux/test_audio.cpp | 2 ++ 4 files changed, 31 insertions(+), 18 deletions(-) diff --git a/src/audio.cpp b/src/audio.cpp index f7edc74c833..060753afbd1 100644 --- a/src/audio.cpp +++ b/src/audio.cpp @@ -38,10 +38,10 @@ namespace audio { * @brief Serializes capture-target refresh, microphone creation, and target release across concurrent sessions. * * All capture() threads share one audio control. Each session's - * session_capture_target_t guard holds this mutex across every - * refresh/microphone pair (and across the exit clear), which keeps one - * session from resetting the shared target between another session's - * refresh and microphone creation. + * session_capture_target_t guard holds this mutex across the refresh + * and the exit clear, but never across microphone creation itself, + * which can wait on endpoint activation; holding the lock across it + * would stall every other session's teardown. * * Lock order: this outer mutex is always taken before the backend-internal * `platf::audio_control_t::capture_state_mutex_`, acquired inside @@ -214,13 +214,16 @@ namespace audio { * @brief Refresh the endpoint capture target, then create the microphone for it. */ std::unique_ptr session_capture_target_t::create_microphone(const platf::microphone_params_t &mic_params) { - // Refresh the endpoint target before every microphone creation. The lock - // covers the refresh/microphone pair, and the refresh is recorded even - // when microphone creation fails so teardown still releases this - // session's target. - std::lock_guard lock {*mutex_}; - control_->set_capture_target(intent_, 0); - recorded_ = true; + // Refresh the endpoint target before every microphone creation. Only the + // refresh runs under the lock: microphone creation can wait on endpoint + // activation, and holding the lock across it would stall every other + // session's teardown. The refresh is recorded even when microphone + // creation fails so teardown still releases this session's target. + { + std::lock_guard lock {*mutex_}; + control_->set_capture_target(intent_, 0); + recorded_ = true; + } return control_->microphone(mic_params); } diff --git a/src/audio.h b/src/audio.h index 214d0bb15c8..f8a41b1f899 100644 --- a/src/audio.h +++ b/src/audio.h @@ -264,9 +264,9 @@ namespace audio { * @brief RAII owner of one session's shared capture target. * * Sessions share one audio control. Every create_microphone() call refreshes - * the endpoint target (set_capture_target()) and creates the microphone - * under one lock acquisition, so a refresh can never be dropped or - * interleaved with another session's refresh. Destruction releases exactly + * the endpoint target (set_capture_target()) under one lock acquisition, + * so a refresh can never be dropped or interleaved with another session's + * refresh, then creates the microphone without holding the lock. Destruction releases exactly * the last recorded target via clear_capture_target(), or nothing when no * refresh ever ran (for example after an aborted sink selection), so one * session cannot wipe another session's recorded target on its way out. @@ -297,10 +297,9 @@ namespace audio { * * The refresh always runs before microphone creation so a dropped refresh * is observable: set_capture_target() is called on every invocation, - * including reinitializations and microphone failures. The lock is held - * across the refresh/microphone pair so the shared target cannot change - * in between. The endpoint form always records PID 0: per-process capture - * is not selected here. + * including reinitializations and microphone failures. The lock covers + * only the refresh, never microphone creation itself. The endpoint form + * always records PID 0: per-process capture is not selected here. * * @param mic_params Microphone capture parameters for the requested layout. * @return Microphone capture object, or nullptr when creation failed. diff --git a/src/platform/common.h b/src/platform/common.h index 78560cfbfb2..e519009f93f 100644 --- a/src/platform/common.h +++ b/src/platform/common.h @@ -975,6 +975,15 @@ namespace platf { // Intentionally empty: backends without per-process capture inherit this no-op. } + /** + * @brief Copy the recorded capture sink. + * + * @return Recorded sink name, possibly empty when nothing was recorded. + */ + [[nodiscard]] std::string snapshot_capture_sink_record() const { + return snapshot_recorded_sink(); + } + /** * @brief Create a microphone capture stream for the requested layout. * diff --git a/tests/unit/platform/linux/test_audio.cpp b/tests/unit/platform/linux/test_audio.cpp index 734a153e0e1..0fbd6f5d598 100644 --- a/tests/unit/platform/linux/test_audio.cpp +++ b/tests/unit/platform/linux/test_audio.cpp @@ -197,6 +197,8 @@ TEST(KeepDefaultSinkAudioTest, CaptureSinkKeepsHostDefaultSink) { // 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()); From e1250fdc5c1058e211d108fb462730da6cc240fe Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Sun, 15 Nov 2026 20:30:24 -0700 Subject: [PATCH 19/25] fix(config): scope legacy external_audio migration to Windows with a sink --- src/config.cpp | 9 +++++++-- src_assets/common/assets/web/Config.vue | 18 +++++++++++++---- tests/unit/test_config.cpp | 20 ++++++++++++++++--- tests/web/ConfigMigration.test.js | 26 ++++++++++++++++++++----- 4 files changed, 59 insertions(+), 14 deletions(-) diff --git a/src/config.cpp b/src/config.cpp index eb18b24fcce..30e794639d9 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -1811,13 +1811,18 @@ namespace config { bool_f(vars, "stream_audio", audio.stream); bool_f(vars, "install_steam_audio_drivers", audio.install_steam_drivers); // One-time upgrade migration, not a supported option: parse the legacy key - // before keep_default_sink so an explicit new key below always wins. + // before keep_default_sink so an explicit new key below always wins. The + // legacy key only ever took effect on Windows with an explicit + // `audio_sink`, so the migration keeps that exact scope instead of + // changing routing on other platforms or without a pinned sink. bool legacy_external_audio = false; bool_f(vars, "external_audio", legacy_external_audio); - if (legacy_external_audio) { +#ifdef _WIN32 + if (legacy_external_audio && !audio.sink.empty()) { audio.keep_default_sink = true; BOOST_LOG(warning) << "external_audio is deprecated; use keep_default_sink instead"sv; } +#endif bool_f(vars, "keep_default_sink", audio.keep_default_sink); string_restricted_f(vars, "origin_web_ui_allowed", nvhttp.origin_web_ui_allowed, {"pc"sv, "lan"sv, "wan"sv}); diff --git a/src_assets/common/assets/web/Config.vue b/src_assets/common/assets/web/Config.vue index f4c4187f6bf..ea8f8e0d586 100644 --- a/src_assets/common/assets/web/Config.vue +++ b/src_assets/common/assets/web/Config.vue @@ -196,16 +196,26 @@ * Migrate the legacy external_audio option into keep_default_sink. * * An explicit keep_default_sink value wins; the legacy key is always dropped so - * the next save persists only the unified key. + * the next save persists only the unified key. The legacy key only ever took + * effect on Windows with an explicit audio_sink, so the migration keeps that + * exact scope instead of changing routing elsewhere. * * @param {Object} config Configuration object to migrate in place. + * @param {string} platform Platform reported by the server. */ - function migrateExternalAudioConfig(config) { + function migrateExternalAudioConfig(config, platform) { if (!Object.hasOwn(config, 'external_audio')) { return; } const keepDefaultSink = config.keep_default_sink; - if ((keepDefaultSink === undefined || keepDefaultSink === '') && isConfigBoolEnabled(config.external_audio)) { + const audioSink = config.audio_sink; + if ( + platform === 'windows' && + typeof audioSink === 'string' && + audioSink !== '' && + (keepDefaultSink === undefined || keepDefaultSink === '') && + isConfigBoolEnabled(config.external_audio) + ) { config.keep_default_sink = 'enabled'; } delete config.external_audio; @@ -312,7 +322,7 @@ delete this.config.status; delete this.config.version; - migrateExternalAudioConfig(this.config); + migrateExternalAudioConfig(this.config, this.platform); // Parse the special options before population if available const specialOptions = ["dd_mode_remapping", "global_prep_cmd"] diff --git a/tests/unit/test_config.cpp b/tests/unit/test_config.cpp index e2aaa04da37..9230d563109 100644 --- a/tests/unit/test_config.cpp +++ b/tests/unit/test_config.cpp @@ -462,20 +462,34 @@ TEST(KeepDefaultSinkConfigTest, MissingKeyLeavesValueUnchanged) { } /** - * @brief Verify the deprecated external_audio key enables 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("external_audio = enabled\n"); + 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("external_audio = disabled\n"); + 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; } /** diff --git a/tests/web/ConfigMigration.test.js b/tests/web/ConfigMigration.test.js index 50b75054555..a85b9314a2d 100644 --- a/tests/web/ConfigMigration.test.js +++ b/tests/web/ConfigMigration.test.js @@ -7,10 +7,10 @@ vi.mock('../../src_assets/common/assets/web/Navbar.vue', () => ({ import Config from '../../src_assets/common/assets/web/Config.vue' -async function mountConfig(serverConfig) { +async function mountConfig(serverConfig, platform = 'windows') { const fetchMock = vi.fn(async (url, options) => { if (url === './api/config' && !options) { - return { json: async () => ({ platform: 'windows', version: 'test', status: true, ...serverConfig }) } + return { json: async () => ({ platform, version: 'test', status: true, ...serverConfig }) } } if (url === './api/config' && options?.method === 'POST') { return { status: 200, json: async () => ({ status: true }) } @@ -35,7 +35,7 @@ afterEach(() => { 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 }) + 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') @@ -59,15 +59,31 @@ describe('external_audio upgrade migration', () => { }) it('migrates when keep_default_sink is present but empty', async () => { - const { wrapper } = await mountConfig({ external_audio: 'enabled', keep_default_sink: '' }) + 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' }) + const { wrapper, fetchMock } = await mountConfig({ external_audio: 'enabled', audio_sink: 'pinned-sink' }) wrapper.vm.config.keep_default_sink = 'disabled' await wrapper.vm.save() From 2f92bd3c7cf82419ad286364ccd51591f75464c8 Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Mon, 16 Nov 2026 20:59:51 -0700 Subject: [PATCH 20/25] fix(tests): drop blank line at EOF from trim surgery --- tests/unit/test_audio.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/unit/test_audio.cpp b/tests/unit/test_audio.cpp index bf56a7a6564..2ab0863f533 100644 --- a/tests/unit/test_audio.cpp +++ b/tests/unit/test_audio.cpp @@ -1093,4 +1093,3 @@ TEST(BaseRecordTest, KeepDefaultHelperRecordsAndReturnsZero) { EXPECT_EQ(control.capture_sink("keep-default-sink"), 0); EXPECT_EQ(control.snapshot_recorded_sink(), "keep-default-sink"); } - From 57213112618b6ab5fa50765b7bd2f8f227f436e1 Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Mon, 16 Nov 2026 21:02:28 -0700 Subject: [PATCH 21/25] fix(windows/audio): drop stray brace left by trim surgery in microphone() The d3dc65fa surgery dropped the process-loopback if-block but kept its closing brace after 'auto mic', which would close microphone() early and break the Windows build (unseen on Linux where this TU is excluded). --- src/platform/windows/audio.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/platform/windows/audio.cpp b/src/platform/windows/audio.cpp index e3c69afe8a8..cefe4928941 100644 --- a/src/platform/windows/audio.cpp +++ b/src/platform/windows/audio.cpp @@ -1005,8 +1005,6 @@ namespace platf::audio { */ std::unique_ptr microphone(const std::uint8_t *mapping, int channels, std::uint32_t sample_rate, std::uint32_t frame_size, bool continuous_audio, [[maybe_unused]] bool host_audio_enabled) override { auto mic = std::make_unique(); - } - // Prefer the session's assigned sink; otherwise use the configured sink. const auto &requested_sink = assigned_sink.empty() ? config::audio.sink : assigned_sink; From cb8247f78afd10cc55d4aac90618f375a2fbdc1d Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Mon, 16 Nov 2026 22:55:48 -0700 Subject: [PATCH 22/25] fix(process): serialize lifecycle transitions and harden termination Harden proc_t launch/cleanup: snapshot app state and claim termination atomically with a lifecycle generation, serialize app_process_id/identity reads with the lifecycle mutex, lock getters and reaper, and gate complete execute/running/terminate transitions with proc_transition_mutex so an overlapping web close/stream cleanup cannot run the old snapshot's undo or display revert after the successor's preparation. Carry the shared capture-target record (identity struct, record, snapshot helpers, mutex, conditional clear, hook) in platf::audio_control_t with a mechanical audio.cpp call-site update, plus lifecycle and BaseRecord regression coverage including a latch-controlled overlap test and the P2 test-guard correction for the identity-producer test. --- src/audio.cpp | 2 +- src/nvhttp.cpp | 2 +- src/platform/common.h | 181 +++++++++++++++- src/process.cpp | 415 +++++++++++++++++++++++++++--------- src/process.h | 122 ++++++++++- tests/unit/test_audio.cpp | 322 ++++++++++++++++++++++++++-- tests/unit/test_process.cpp | 307 ++++++++++++++++++++++++++ 7 files changed, 1226 insertions(+), 125 deletions(-) diff --git a/src/audio.cpp b/src/audio.cpp index 060753afbd1..dc381bf0d03 100644 --- a/src/audio.cpp +++ b/src/audio.cpp @@ -221,7 +221,7 @@ namespace audio { // creation fails so teardown still releases this session's target. { std::lock_guard lock {*mutex_}; - control_->set_capture_target(intent_, 0); + control_->set_capture_target(intent_, platf::process_identity_t {0, 0}); recorded_ = true; } return control_->microphone(mic_params); diff --git a/src/nvhttp.cpp b/src/nvhttp.cpp index 7601cb89690..e43128c0f73 100644 --- a/src/nvhttp.cpp +++ b/src/nvhttp.cpp @@ -1351,7 +1351,7 @@ namespace nvhttp { apps.put(".status_code", 200); - for (auto &proc : proc::proc.get_apps()) { + for (auto &proc : std::as_const(proc::proc).get_apps()) { pt::ptree app; app.put("IsHdrSupported"s, video::active_hevc_mode >= 3 ? 1 : 0); diff --git a/src/platform/common.h b/src/platform/common.h index e519009f93f..f2bafe1ebc0 100644 --- a/src/platform/common.h +++ b/src/platform/common.h @@ -890,6 +890,29 @@ namespace platf { pinned_sink, ///< Capture one explicitly configured sink, device, or input. }; + /** + * @brief Whether a recorded capture target still matches the expected session target. + * + * Pure function: no I/O, no global state. Sessions share one audio control, + * so an exiting session must only release the shared target when it still + * holds that session's intent and PID; otherwise it would wipe a survivor's + * target that was recorded after its own. + * + * @param recorded_intent Intent currently stored on the audio control. + * @param recorded_process_id PID currently stored on the audio control. + * @param expected_intent Intent recorded by the session being torn down. + * @param expected_process_id PID recorded by the session being torn down. + * @return True only when both the intent and the PID still match. + */ + [[nodiscard]] constexpr bool capture_target_matches( + audio_capture_intent_e recorded_intent, + std::uint32_t recorded_process_id, + audio_capture_intent_e expected_intent, + std::uint32_t expected_process_id + ) noexcept { + return recorded_intent == expected_intent && recorded_process_id == expected_process_id; + } + /** * @brief Microphone capture parameters for audio_control_t::microphone(). * @@ -906,6 +929,58 @@ namespace platf { bool host_audio_enabled = false; ///< Whether host playback should remain enabled during capture. }; + /** + * @brief Operating-system identity of a launched process for capture routing. + * + * A PID alone can be reused after the original process exits. Pairing it with + * an OS creation marker distinguishes the recorded process from a later + * process that happens to receive the same PID. The marker is opaque: + * backends must only compare it for equality, never interpret it. A zero + * marker means the identity is unverifiable (no process, or the platform + * cannot query creation markers); backends must fail closed to endpoint + * capture in that case. + * + * The identity is captured from the owned child handle under the process + * lifecycle lock and carried through the audio handoff as one bundle, so the + * baseline always names the launched process even if its PID is later + * reused. Backends must store the handed-off marker verbatim as their + * revalidation baseline instead of querying it by PID, which would reopen + * the reuse window the handoff closes. + */ + struct process_identity_t { + std::uint32_t process_id {}; ///< Operating-system PID, or 0 for endpoint capture. + std::uint64_t creation_time {}; ///< Opaque OS creation marker, or 0 when unverifiable. + }; + + /** + * @brief Recorded per-process capture target shared by audio backends. + * + * Windows and Linux record the sink selected at startup so microphone() can + * consume it later; Windows additionally records the intent and PID for + * process-loopback capture. The record carries at most the intent and the + * PID: the creation marker travels with set_capture_target() but its storage, + * identity queries, and revalidation stay backend-side because they depend on + * WASAPI-only process APIs. + */ + struct capture_target_record_t { + audio_capture_intent_e intent {audio_capture_intent_e::client_only}; ///< Intent for the next microphone() call. + std::uint32_t process_id {}; ///< PID for process-loopback capture, or 0 for endpoint capture. + + /** + * @brief Check whether this record still matches the expected session target. + * + * Delegates to `capture_target_matches()` so sessions share one + * compare-and-reset contract. + * + * @param expected_intent Intent recorded by the session being torn down. + * @param expected_process_id PID recorded by the session being torn down. + * @return True only when both the intent and the PID still match. + */ + [[nodiscard]] bool matches(audio_capture_intent_e expected_intent, std::uint32_t expected_process_id) const noexcept { + return capture_target_matches(intent, process_id, expected_intent, expected_process_id); + } + }; + /** * @brief Platform audio controller that manages sinks and microphone capture. */ @@ -931,6 +1006,15 @@ namespace platf { return false; } + /** + * @brief Whether the backend can capture one launched process tree. + * + * @return True when set_capture_target() may select per-process capture. + */ + virtual bool supports_process_capture() const { + return false; + } + /** * @brief Capture the given sink without changing the host default. * @@ -949,13 +1033,15 @@ namespace platf { * * The default implementation is a no-op so backends without per-process * capture are unchanged. Backends that support process loopback override - * this to store the intent and PID together, so microphone() never sees + * this to store the intent and identity together, so microphone() never sees * a mismatched pair. A PID of 0 selects ordinary endpoint or sink capture. + * The creation marker arrives pre-queried from the owned child handle and + * must be stored verbatim as the revalidation baseline. * * @param intent Capture intent resolved from the audio configuration. - * @param process_id Operating-system PID to capture, or 0 for endpoint capture. + * @param identity Operating-system identity to capture, or {0, 0} for endpoint capture. */ - virtual void set_capture_target([[maybe_unused]] audio_capture_intent_e intent, [[maybe_unused]] std::uint32_t process_id) { + virtual void set_capture_target([[maybe_unused]] audio_capture_intent_e intent, [[maybe_unused]] process_identity_t identity) { // Intentionally empty: backends without per-process capture inherit this no-op. } @@ -975,6 +1061,19 @@ namespace platf { // Intentionally empty: backends without per-process capture inherit this no-op. } + /** + * @brief Copy the recorded capture target. + * + * Public read of the shared record so `audio::session_capture_target_t` + * can verify, after creating a microphone without holding the outer + * capture-target mutex, that the target it refreshed is still recorded. + * + * @return Intent and PID as one consistent snapshot. + */ + [[nodiscard]] capture_target_record_t snapshot_capture_target_record() const { + return snapshot_recorded_capture_target(); + } + /** * @brief Copy the recorded capture sink. * @@ -1033,8 +1132,9 @@ namespace platf { virtual ~audio_control_t() = default; protected: - mutable std::mutex capture_state_mutex_; ///< Guards `recorded_sink_` against concurrent sessions. + mutable std::mutex capture_state_mutex_; ///< Guards `recorded_sink_` and `recorded_target_` against concurrent sessions. std::string recorded_sink_; ///< Sink recorded for later consumption in microphone(), possibly empty. + capture_target_record_t recorded_target_; ///< Intent and PID recorded for the next microphone() call. /** * @brief Record a capture sink for later consumption in microphone(). @@ -1077,6 +1177,79 @@ namespace platf { std::lock_guard lock {capture_state_mutex_}; return recorded_sink_; } + + /** + * @brief Record the capture target for the next microphone() call. + * + * Thread-safe: the intent and PID are stored as one snapshot under + * `capture_state_mutex_`, so microphone() never sees a mismatched pair. + * Opt-in helper only: the `set_capture_target()` virtual stays a no-op so + * backends without per-process capture are unchanged. + * + * @param intent Capture intent resolved from the audio configuration. + * @param process_id Operating-system PID to capture, or 0 for endpoint capture. + */ + void record_capture_target(audio_capture_intent_e intent, std::uint32_t process_id) { + std::lock_guard lock {capture_state_mutex_}; + recorded_target_.intent = intent; + recorded_target_.process_id = process_id; + } + + /** + * @brief Copy the recorded capture target under `capture_state_mutex_`. + * + * Named `snapshot_recorded_capture_target()` (rather than reusing the + * Windows `snapshot_capture_target()` name) because the Windows snapshot + * carries an additional process identity and C++ cannot overload on the + * return type alone. + * + * @return Intent and PID as one consistent snapshot. + */ + [[nodiscard]] capture_target_record_t snapshot_recorded_capture_target() const { + std::lock_guard lock {capture_state_mutex_}; + return recorded_target_; + } + + /** + * @brief Reset backend-side state paired with the recorded capture target. + * + * Called by `clear_recorded_capture_target_if_matches()` while holding + * `capture_state_mutex_` after the shared record was reset. The default is + * a no-op. Overrides must be non-reentrant: they must not call any + * `record_*`/`snapshot_*`/`clear_*` helper (non-recursive mutex would + * deadlock) and must not perform OS, provider, or PulseAudio calls — no + * lock is ever held across such calls. + */ + virtual void on_capture_target_cleared() { + // Intentionally empty: backends without paired state inherit this no-op. + } + + /** + * @brief Release the recorded capture target when it still belongs to the caller. + * + * Thread-safe: the compare-and-reset runs under `capture_state_mutex_`. + * The target resets to endpoint capture only when the stored intent and + * PID still equal the given ones, so one exiting session cannot wipe + * another session's recorded target. Opt-in helper only: the + * `clear_capture_target()` virtual stays a no-op so backends without + * per-process capture are unchanged. After the shared record resets, + * `on_capture_target_cleared()` runs under the same lock hold so paired + * backend state resets atomically with the shared record. + * + * @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. + * @return True when the stored target matched and was reset. + */ + bool clear_recorded_capture_target_if_matches(audio_capture_intent_e intent, std::uint32_t process_id) { + std::lock_guard lock {capture_state_mutex_}; + if (!recorded_target_.matches(intent, process_id)) { + return false; + } + recorded_target_.intent = audio_capture_intent_e::client_only; + recorded_target_.process_id = 0; + on_capture_target_cleared(); + return true; + } }; /** diff --git a/src/process.cpp b/src/process.cpp index 90c79ae3891..eba1d0882e7 100644 --- a/src/process.cpp +++ b/src/process.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -50,6 +51,27 @@ namespace proc { proc_t proc; ///< Global process registry used to track and terminate child processes. + /** + * @brief Serialize access to proc_t lifecycle state shared across threads. + * + * Lock order: proc_transition_mutex() is always taken before this mutex, + * and audio::capture_target_mutex() is always taken before this mutex + * (the capture process-identity provider must be invoked under that mutex), + * and this mutex is never taken in the reverse order. + * This mutex is never held across blocking process waits, prep/undo + * command waits, or display/input calls: lifecycle operations snapshot + * or claim the shared state under this mutex and work on locals after + * releasing it. The only process queries made under it are the + * non-blocking `child::running()`/`native_exit_code()` checks and the + * non-blocking `platf::process_group_running()` group query. + * + * @return Reference to the process-lifetime lifecycle mutex. + */ + std::mutex &proc_lifecycle_mutex() { + static std::mutex mutex; + return mutex; + } + /** * @brief RAII helper that runs shutdown cleanup when destroyed. */ @@ -212,97 +234,145 @@ namespace proc { return true; } + /** + * @brief Serialize complete launch and cleanup transitions independently of state reads. + * + * @return Process-lifetime transition mutex. + */ + std::mutex &proc_transition_mutex() { + static std::mutex mutex; + return mutex; + } + int proc_t::execute(int app_id, std::shared_ptr launch_session) { - // Ensure starting from a clean slate - terminate(); + std::lock_guard transition {proc_transition_mutex()}; + return execute_impl(app_id, std::move(launch_session)); + } - auto iter = std::find_if(_apps.begin(), _apps.end(), [&app_id](const auto app) { - return app.id == std::to_string(app_id); - }); + int proc_t::execute_impl(int app_id, std::shared_ptr launch_session) { + // Ensure starting from a clean slate + terminate_impl(); + + // Snapshot the app and environment under the lock, then run every + // prep/detached/launch wait on the locals. Shared state is only + // republished in short locked sections that verify `generation`, so a + // concurrent terminate or successor launch is never overwritten. + ctx_t app; + boost::process::v1::environment env; + std::uint64_t generation = 0; + { + std::lock_guard lock {proc_lifecycle_mutex()}; + auto iter = std::find_if(_apps.begin(), _apps.end(), [&app_id](const auto &listed_app) { + return listed_app.id == std::to_string(app_id); + }); + + if (iter == _apps.end()) { + BOOST_LOG(error) << "Couldn't find app with ID ["sv << app_id << ']'; + return 404; + } - if (iter == _apps.end()) { - BOOST_LOG(error) << "Couldn't find app with ID ["sv << app_id << ']'; - return 404; + _app_id = app_id; + _app = *iter; + _app_prep_begin = std::begin(_app.prep_cmds); + _app_prep_it = _app_prep_begin; + _app_prep_completed = 0; + generation = ++_lifecycle_generation; + app = _app; + env = _env; } - _app_id = app_id; - _app = *iter; - _app_prep_begin = std::begin(_app.prep_cmds); - _app_prep_it = _app_prep_begin; - // Add Stream-specific environment variables - _env["SUNSHINE_APP_ID"] = std::to_string(_app_id); - _env["SUNSHINE_APP_NAME"] = _app.name; - _env["SUNSHINE_CLIENT_NAME"] = launch_session->client_name; - _env["SUNSHINE_CLIENT_WIDTH"] = std::to_string(launch_session->width); - _env["SUNSHINE_CLIENT_HEIGHT"] = std::to_string(launch_session->height); - _env["SUNSHINE_CLIENT_FPS"] = std::to_string(launch_session->fps); - _env["SUNSHINE_CLIENT_HDR"] = launch_session->enable_hdr ? "true" : "false"; - _env["SUNSHINE_CLIENT_GCMAP"] = std::to_string(launch_session->gcmap); - _env["SUNSHINE_CLIENT_HOST_AUDIO"] = launch_session->host_audio ? "true" : "false"; - _env["SUNSHINE_CLIENT_ENABLE_SOPS"] = launch_session->enable_sops ? "true" : "false"; + env["SUNSHINE_APP_ID"] = std::to_string(app_id); + env["SUNSHINE_APP_NAME"] = app.name; + env["SUNSHINE_CLIENT_NAME"] = launch_session->client_name; + env["SUNSHINE_CLIENT_WIDTH"] = std::to_string(launch_session->width); + env["SUNSHINE_CLIENT_HEIGHT"] = std::to_string(launch_session->height); + env["SUNSHINE_CLIENT_FPS"] = std::to_string(launch_session->fps); + env["SUNSHINE_CLIENT_HDR"] = launch_session->enable_hdr ? "true" : "false"; + env["SUNSHINE_CLIENT_GCMAP"] = std::to_string(launch_session->gcmap); + env["SUNSHINE_CLIENT_HOST_AUDIO"] = launch_session->host_audio ? "true" : "false"; + env["SUNSHINE_CLIENT_ENABLE_SOPS"] = launch_session->enable_sops ? "true" : "false"; int channelCount = launch_session->surround_info & 65535; switch (channelCount) { case 2: - _env["SUNSHINE_CLIENT_AUDIO_CONFIGURATION"] = "2.0"; + env["SUNSHINE_CLIENT_AUDIO_CONFIGURATION"] = "2.0"; break; case 6: - _env["SUNSHINE_CLIENT_AUDIO_CONFIGURATION"] = "5.1"; + env["SUNSHINE_CLIENT_AUDIO_CONFIGURATION"] = "5.1"; break; case 8: - _env["SUNSHINE_CLIENT_AUDIO_CONFIGURATION"] = "7.1"; + env["SUNSHINE_CLIENT_AUDIO_CONFIGURATION"] = "7.1"; break; } - _env["SUNSHINE_CLIENT_AUDIO_SURROUND_PARAMS"] = launch_session->surround_params; + env["SUNSHINE_CLIENT_AUDIO_SURROUND_PARAMS"] = launch_session->surround_params; - if (!_app.output.empty() && _app.output != "null"sv) { + { + // Publish the session environment so a concurrent terminate undoes + // prep commands with it and `update_apps_and_env()` preserves it. + std::lock_guard lock {proc_lifecycle_mutex()}; + if (_lifecycle_generation != generation) { + return -1; + } + _env = env; + } + + // The pipe stays local until the launch is published, so a concurrent + // terminate can never close a FILE this launch is still spawning with. + file_t pipe; + if (!app.output.empty() && app.output != "null"sv) { #ifdef _WIN32 // fopen() interprets the filename as an ANSI string on Windows, so we must convert it // to UTF-16 and use the wchar_t variants for proper Unicode log file path support. - auto woutput = utf_utils::from_utf8(_app.output); + auto woutput = utf_utils::from_utf8(app.output); // Use _SH_DENYNO to allow us to open this log file again for writing even if it is // still open from a previous execution. This is required to handle the case of a // detached process executing again while the previous process is still running. - _pipe.reset(_wfsopen(woutput.c_str(), L"a", _SH_DENYNO)); + pipe.reset(_wfsopen(woutput.c_str(), L"a", _SH_DENYNO)); #else - _pipe.reset(fopen(_app.output.c_str(), "a")); + pipe.reset(fopen(app.output.c_str(), "a")); #endif } std::error_code ec; - // Executed when returning from function - auto fg = util::fail_guard([this]() { - terminate(); + // Executed when returning from function; generation-checked so failing + // cleanup for this launch cannot terminate a successor app. + auto fg = util::fail_guard([this, generation]() { + terminate_impl(generation); }); - for (; _app_prep_it != std::end(_app.prep_cmds); ++_app_prep_it) { - auto &cmd = *_app_prep_it; + for (std::size_t prep_index = 0; prep_index < app.prep_cmds.size(); ++prep_index) { + const auto &cmd = app.prep_cmds[prep_index]; // Skip empty commands - if (cmd.do_cmd.empty()) { - continue; + if (!cmd.do_cmd.empty()) { + const auto command = prepare_command(cmd.do_cmd); + boost::filesystem::path working_dir = app.working_dir.empty() ? + find_working_directory(command, env) : + boost::filesystem::path(app.working_dir); + BOOST_LOG(info) << "Executing Do Cmd: ["sv << command << ']'; + auto child = platf::run_command(cmd.elevated, true, command, working_dir, env, pipe.get(), ec, nullptr); + + if (!wait_for_prep_command(child, command, ec, app.cmd.empty())) { + return -1; + } } - const auto command = prepare_command(cmd.do_cmd); - boost::filesystem::path working_dir = _app.working_dir.empty() ? - find_working_directory(command, _env) : - boost::filesystem::path(_app.working_dir); - BOOST_LOG(info) << "Executing Do Cmd: ["sv << command << ']'; - auto child = platf::run_command(cmd.elevated, true, command, working_dir, _env, _pipe.get(), ec, nullptr); - - if (!wait_for_prep_command(child, command, ec, _app.cmd.empty())) { + std::lock_guard lock {proc_lifecycle_mutex()}; + if (_lifecycle_generation != generation) { return -1; } + _app_prep_completed = prep_index + 1; + _app_prep_it = std::begin(_app.prep_cmds) + static_cast(_app_prep_completed); } - for (auto &cmd : _app.detached) { + for (auto &cmd : app.detached) { const auto command = prepare_command(cmd); - boost::filesystem::path working_dir = _app.working_dir.empty() ? - find_working_directory(command, _env) : - boost::filesystem::path(_app.working_dir); + boost::filesystem::path working_dir = app.working_dir.empty() ? + find_working_directory(command, env) : + boost::filesystem::path(app.working_dir); BOOST_LOG(info) << "Spawning ["sv << command << "] in ["sv << working_dir << ']'; - auto child = platf::run_command(_app.elevated, true, command, working_dir, _env, _pipe.get(), ec, nullptr); + auto child = platf::run_command(app.elevated, true, command, working_dir, env, pipe.get(), ec, nullptr); if (ec) { BOOST_LOG(warning) << "Couldn't spawn ["sv << command << "]: System: "sv << ec.message(); } else { @@ -310,85 +380,209 @@ namespace proc { } } - if (_app.cmd.empty()) { + if (app.cmd.empty()) { BOOST_LOG(info) << "Executing [Desktop]"sv; + std::lock_guard lock {proc_lifecycle_mutex()}; + if (_lifecycle_generation != generation) { + return -1; + } placebo = true; + _pipe = std::move(pipe); + _app_launch_time = std::chrono::steady_clock::now(); } else { - const auto command = prepare_command(_app.cmd); - boost::filesystem::path working_dir = _app.working_dir.empty() ? - find_working_directory(command, _env) : - boost::filesystem::path(_app.working_dir); + const auto command = prepare_command(app.cmd); + boost::filesystem::path working_dir = app.working_dir.empty() ? + find_working_directory(command, env) : + boost::filesystem::path(app.working_dir); BOOST_LOG(info) << "Executing: ["sv << command << "] in ["sv << working_dir << ']'; - _process = platf::run_command(_app.elevated, true, command, working_dir, _env, _pipe.get(), ec, &_process_group); + boost::process::v1::group launched_group; + auto launched_process = platf::run_command(app.elevated, true, command, working_dir, env, pipe.get(), ec, &launched_group); if (ec) { BOOST_LOG(warning) << "Couldn't run ["sv << command << "]: System: "sv << ec.message(); return -1; } + bool superseded = false; + { + std::lock_guard lock {proc_lifecycle_mutex()}; + if (_lifecycle_generation != generation) { + superseded = true; + } else { + _process = std::move(launched_process); + _process_group = std::move(launched_group); + _pipe = std::move(pipe); + _app_launch_time = std::chrono::steady_clock::now(); + } + } + if (superseded) { + // A terminate or successor launch claimed the lifecycle while this + // process was starting; stop only the process launched here. + terminate_process_group(launched_process, launched_group, app.exit_timeout); + return -1; + } } - _app_launch_time = std::chrono::steady_clock::now(); - fg.disable(); return 0; } + std::uint32_t proc_t::app_process_id() { + return app_process_identity().process_id; + } + + /** + * @brief Return the operating-system identity of the launched application root process. + */ + platf::process_identity_t proc_t::app_process_identity() { + std::lock_guard lock {proc_lifecycle_mutex()}; + if (placebo || !_process.valid() || !_process.running()) { + return {}; + } +#ifdef _WIN32 + // Query the creation marker from the owned child handle while the lock pins + // it to the launched process: even if the PID is reused later, the recorded + // baseline still names this process, so revalidation rejects the replacement. + FILETIME creation_time {}; + FILETIME exit_time {}; + FILETIME kernel_time {}; + FILETIME user_time {}; + if (!GetProcessTimes(_process.native_handle(), &creation_time, &exit_time, &kernel_time, &user_time)) { + return {}; + } + const auto combined_creation_time = (static_cast(creation_time.dwHighDateTime) << 32) | static_cast(creation_time.dwLowDateTime); + if (combined_creation_time == 0) { + return {}; + } + return {static_cast(_process.id()), combined_creation_time}; +#else + // POSIX backends never select per-process capture, so no creation marker is needed. + return {static_cast(_process.id()), 0}; +#endif + } + int proc_t::running() { + std::lock_guard transition {proc_transition_mutex()}; + return running_impl(); + } + + int proc_t::running_impl() { + // Snapshot the decision inputs under the lock, then re-verify the + // generation before committing. The cleanup claim happens in the same + // lock hold as the final decision, so a successor launched in between + // is never the process cleaned up. The `wait_all` group query runs + // under the lock as well: on POSIX it reaps via `waitpid()`, so leaving + // it unlocked would let a concurrent poll's reaper steal the root + // child's exit status before `_process.running()` captures it. + struct running_snapshot_t { + int app_id {}; ///< App id observed in the snapshot. + std::uint64_t generation {}; ///< Lifecycle generation observed in the snapshot. + bool placebo {}; ///< Whether the Desktop placebo session was active. + }; + + // On POSIX, reap exited children on every poll (including the snapshot + // early returns below), as HEAD did; serialize against `bp::wait()` and + // `platf::process_group_running()` via the lifecycle mutex. #ifndef _WIN32 - // On POSIX OSes, we must periodically wait for our children to avoid - // them becoming zombies. This must be synchronized carefully with - // calls to bp::wait() and platf::process_group_running() which both - // invoke waitpid() under the hood. auto reaper = util::fail_guard([]() { + std::lock_guard lock {proc_lifecycle_mutex()}; while (waitpid(-1, nullptr, WNOHANG) > 0); }); #endif - if (placebo) { - return _app_id; - } else if (_app.wait_all && _process_group && platf::process_group_running((std::uintptr_t) _process_group.native_handle())) { - // The app is still running if any process in the group is still running - return _app_id; - } else if (_process.running()) { - // The app is still running only if the initial process launched is still running - return _app_id; - } else if (_app.auto_detach && _process.native_exit_code() == 0 && std::chrono::steady_clock::now() - _app_launch_time < 5s) { - BOOST_LOG(info) << "App exited gracefully within 5 seconds of launch. Treating the app as a detached command."sv; - BOOST_LOG(info) << "Adjust this behavior in the Applications tab or apps.json if this is not what you want."sv; - placebo = true; - return _app_id; + running_snapshot_t snapshot; + { + std::lock_guard lock {proc_lifecycle_mutex()}; + snapshot.app_id = _app_id; + snapshot.generation = _lifecycle_generation; + snapshot.placebo = placebo; + } + + if (snapshot.placebo) { + return snapshot.app_id; + } + + std::optional claimed; + { + std::lock_guard lock {proc_lifecycle_mutex()}; + if (_lifecycle_generation != snapshot.generation) { + // State changed while unlocked; report the current app, if any. + return _app_id > 0 ? _app_id : 0; + } + if (placebo) { + return _app_id; + } else if (_app.wait_all && _process_group && platf::process_group_running((std::uintptr_t) _process_group.native_handle())) { + // The app is still running if any process in the group is still running. + return _app_id; + } else if (_process.running()) { + // The app is still running only if the initial process launched is still running + return _app_id; + } else if (_app.auto_detach && _process.native_exit_code() == 0 && std::chrono::steady_clock::now() - _app_launch_time < 5s) { + BOOST_LOG(info) << "App exited gracefully within 5 seconds of launch. Treating the app as a detached command."sv; + BOOST_LOG(info) << "Adjust this behavior in the Applications tab or apps.json if this is not what you want."sv; + placebo = true; + return _app_id; + } + + // Claim cleanup atomically with the decision: the move-out below is + // what a later terminate would have raced with a successor launch. + if (_process) { + BOOST_LOG(info) << "App exited with code ["sv << _process.native_exit_code() << ']'; + claimed = claim_termination_locked(); + } } - // Perform cleanup actions now if needed - if (_process) { - BOOST_LOG(info) << "App exited with code ["sv << _process.native_exit_code() << ']'; - terminate(); + if (claimed) { + finish_termination(std::move(*claimed)); } return 0; } void proc_t::terminate() { - input::terminate_gamepads(); - std::error_code ec; + std::lock_guard transition {proc_transition_mutex()}; + terminate_impl(); + } + + auto proc_t::claim_termination_locked() -> termination_snapshot_t { + termination_snapshot_t snapshot; + ++_lifecycle_generation; placebo = false; - terminate_process_group(_process, _process_group, _app.exit_timeout); + snapshot.process = std::move(_process); _process = boost::process::v1::child(); + snapshot.process_group = std::move(_process_group); _process_group = boost::process::v1::group(); + snapshot.app = _app; + snapshot.env = _env; + snapshot.pipe = std::move(_pipe); + _pipe = file_t {}; + snapshot.prep_completed = std::min(_app_prep_completed, snapshot.app.prep_cmds.size()); + _app_prep_completed = 0; + _app_prep_it = _app_prep_begin; + snapshot.exit_timeout = _app.exit_timeout; + snapshot.has_run = _app_id > 0; + snapshot.app_name = _app.name; + _app_id = -1; + return snapshot; + } - for (; _app_prep_it != _app_prep_begin; --_app_prep_it) { - auto &cmd = *(_app_prep_it - 1); + void proc_t::finish_termination(termination_snapshot_t &&snapshot) { + input::terminate_gamepads(); + std::error_code ec; + terminate_process_group(snapshot.process, snapshot.process_group, snapshot.exit_timeout); + + for (std::size_t prep_index = snapshot.prep_completed; prep_index > 0; --prep_index) { + const auto &cmd = snapshot.app.prep_cmds[prep_index - 1]; if (cmd.undo_cmd.empty()) { continue; } const auto command = prepare_command(cmd.undo_cmd); - boost::filesystem::path working_dir = _app.working_dir.empty() ? - find_working_directory(command, _env) : - boost::filesystem::path(_app.working_dir); + boost::filesystem::path working_dir = snapshot.app.working_dir.empty() ? + find_working_directory(command, snapshot.env) : + boost::filesystem::path(snapshot.app.working_dir); BOOST_LOG(info) << "Executing Undo Cmd: ["sv << command << ']'; - auto child = platf::run_command(cmd.elevated, true, command, working_dir, _env, _pipe.get(), ec, nullptr); + auto child = platf::run_command(cmd.elevated, true, command, working_dir, snapshot.env, snapshot.pipe.get(), ec, nullptr); if (ec) { BOOST_LOG(warning) << "System: "sv << ec.message(); @@ -402,24 +596,39 @@ namespace proc { } } - _pipe.reset(); - - bool has_run = _app_id > 0; + snapshot.pipe.reset(); // Only show the Stopped notification if we actually have an app to stop // Since terminate() is always run when a new app has started - if (proc::proc.get_last_run_app_name().length() > 0 && has_run) { + if (!snapshot.app_name.empty() && snapshot.has_run) { #if defined SUNSHINE_TRAY && SUNSHINE_TRAY >= 1 - system_tray::update_tray_stopped(proc::proc.get_last_run_app_name()); + system_tray::update_tray_stopped(snapshot.app_name); #endif display_device::revert_configuration(); } + } - _app_id = -1; + void proc_t::terminate_impl(std::optional expected_generation) { + std::optional claimed; + { + std::lock_guard lock {proc_lifecycle_mutex()}; + if (expected_generation && *expected_generation != _lifecycle_generation) { + return; + } + claimed = claim_termination_locked(); + } + finish_termination(std::move(*claimed)); } - const std::vector &proc_t::get_apps() const { + std::function app_process_identity_provider(proc_t &target) { + return [&target]() { + return target.app_process_identity(); + }; + } + + std::vector proc_t::get_apps() const { + std::lock_guard lock {proc_lifecycle_mutex()}; return _apps; } @@ -432,19 +641,25 @@ namespace proc { // Returns default image if image configuration is not set. // Returns http content-type header compatible image type. std::string proc_t::get_app_image(int app_id) { - auto iter = std::find_if(_apps.begin(), _apps.end(), [&app_id](const auto app) { - return app.id == std::to_string(app_id); - }); - auto app_image_path = iter == _apps.end() ? std::string() : iter->image_path; + std::string app_image_path; + { + std::lock_guard lock {proc_lifecycle_mutex()}; + auto iter = std::find_if(_apps.begin(), _apps.end(), [&app_id](const auto &listed_app) { + return listed_app.id == std::to_string(app_id); + }); + app_image_path = iter == _apps.end() ? std::string() : iter->image_path; + } return validate_app_image_path(app_image_path); } std::string proc_t::get_last_run_app_name() { + std::lock_guard lock {proc_lifecycle_mutex()}; return _app.name; } void proc_t::update_apps_and_env(proc_t &&other) { + std::lock_guard lock {proc_lifecycle_mutex()}; if (_app_id > 0 || placebo) { // Preserve session-specific environment variables for the running app for (const auto &var : _env) { diff --git a/src/process.h b/src/process.h index 774b0bacd26..cafef6fe72d 100644 --- a/src/process.h +++ b/src/process.h @@ -13,6 +13,8 @@ #endif // standard includes +#include +#include #include #include @@ -117,17 +119,50 @@ namespace proc { */ int running(); + /** + * @brief Return the operating-system PID of the launched application root process. + * + * Returns 0 for the Desktop/placebo session, when no application has been + * launched, and when the root process is no longer running. Callers use 0 + * to fall back to ordinary endpoint audio capture. Implemented via + * app_process_identity() so the PID always agrees with the handed-off identity. + * + * @return Launched root process PID, or 0 when unavailable. + */ + std::uint32_t app_process_id(); + + /** + * @brief Return the operating-system identity of the launched application root process. + * + * The PID and creation marker are captured together from the owned child + * handle under the lifecycle lock, so the pair always names the launched + * process even if its PID is later reused. Returns {0, 0} for the + * Desktop/placebo session, when no application has been launched, when the + * root process is no longer running, and when the creation marker cannot + * be queried. Callers use a zero PID to fall back to ordinary endpoint + * audio capture. + * + * @return Launched root process identity, or {0, 0} when unavailable. + */ + platf::process_identity_t app_process_identity(); + ~proc_t(); /** - * @brief Return the configured applications. + * @brief Return a copy of the configured applications. + * + * The copy is taken under the lifecycle mutex, so callers may iterate it + * without racing `update_apps_and_env()`. * - * @return Immutable application list owned by the process manager. + * @return Copy of the application list owned by the process manager. */ - const std::vector &get_apps() const; + std::vector get_apps() const; /** * @brief Return the configured applications. * + * The mutable reference is for configuration reload and test setup only; + * callers must not hold it across lifecycle operations on other threads. + * * @return Mutable application list owned by the process manager. */ std::vector &get_apps(); @@ -170,7 +205,76 @@ namespace proc { #endif private: + /** + * @brief Implementation of execute() that calls terminate_impl() directly for internal cleanup. + * + * @param app_id App ID. + * @param launch_session Launch session. + * @return Process exit code or launch error status. + */ + int execute_impl(int app_id, std::shared_ptr launch_session); + + /** + * @brief Implementation of running() that may call terminate_impl() directly for cleanup. + * + * @return `_app_id` if a process is running, otherwise returns `0`. + */ + int running_impl(); + + /** + * @brief State claimed atomically for one termination. + * + * `claim_termination_locked()` moves the process handles and copies the + * app/environment out under the lifecycle mutex; `finish_termination()` + * then performs every wait and undo command on this snapshot without + * holding the mutex, so a successor app launched in the meantime is + * never terminated or undone by mistake. + */ + struct termination_snapshot_t { + boost::process::v1::child process; ///< Launched root process claimed for termination. + boost::process::v1::group process_group; ///< Process group claimed for termination. + ctx_t app; ///< Copy of the app context whose prep commands are undone. + boost::process::v1::environment env; ///< Copy of the environment for undo commands. + file_t pipe; ///< Output pipe claimed with the app, closed after the undo commands. + std::size_t prep_completed {}; ///< Number of leading prep commands to undo, in reverse order. + std::chrono::seconds exit_timeout {}; ///< Graceful-exit timeout copied from the app context. + bool has_run {}; ///< Whether an app had been launched when the claim was taken. + std::string app_name; ///< Name of the claimed app, for the stopped notification. + }; + + /** + * @brief Claim the current process state for termination. + * + * The caller must hold the lifecycle mutex. Claiming bumps + * `_lifecycle_generation`, moves `_process`/`_process_group`/`_pipe` + * out, and copies `_app`/`_env`, so the decision to clean up and the + * state being cleaned up are one atomic step. + * + * @return Snapshot carrying everything `finish_termination()` needs. + */ + termination_snapshot_t claim_termination_locked(); + + /** + * @brief Terminate a claimed snapshot and run its undo commands. + * + * Runs without the lifecycle mutex: every wait operates on the snapshot, + * never on member state a successor launch may already own. + * + * @param snapshot State previously returned by `claim_termination_locked()`. + */ + void finish_termination(termination_snapshot_t &&snapshot); + + /** + * @brief Implementation of terminate() used by public wrappers and internal callers. + * + * @param expected_generation When set, terminate only when the lifecycle + * generation still matches, so stale cleanup cannot kill a successor app. + */ + void terminate_impl(std::optional expected_generation = std::nullopt); + int _app_id; + std::uint64_t _lifecycle_generation {}; ///< Bumped on every launch claim and termination claim, guarded by the lifecycle mutex. + std::size_t _app_prep_completed {}; ///< Prep commands completed for `_app`, guarded by the lifecycle mutex. boost::process::v1::environment _env; std::vector _apps; @@ -243,4 +347,16 @@ namespace proc { void terminate_process_group(boost::process::v1::child &child_process, boost::process::v1::group &group, std::chrono::seconds exit_timeout); extern proc_t proc; + + /** + * @brief Build the capture process-identity provider handed to audio capture. + * + * The returned callable reports `target.app_process_identity()` at each call, so + * audio (re)initialization always sees the currently launched app. It + * borrows `target`; the caller keeps it alive for the provider's lifetime. + * + * @param target Process manager whose launched app identity is reported. + * @return Provider returning the launched root identity, or {0, 0} when unavailable. + */ + std::function app_process_identity_provider(proc_t &target); } // namespace proc diff --git a/tests/unit/test_audio.cpp b/tests/unit/test_audio.cpp index 2ab0863f533..a7bd040b709 100644 --- a/tests/unit/test_audio.cpp +++ b/tests/unit/test_audio.cpp @@ -261,6 +261,25 @@ TEST(AudioCaptureIntentTest, NamesEveryIntent) { EXPECT_EQ(audio_capture_intent_name(intent::pinned_sink), "pinned_sink"); } +// The target match is pure: resolvable at compile time, no I/O, no globals. +static_assert(platf::capture_target_matches(platf::audio_capture_intent_e::host_and_client, 1234, platf::audio_capture_intent_e::host_and_client, 1234)); +static_assert(!platf::capture_target_matches(platf::audio_capture_intent_e::host_and_client, 1234, platf::audio_capture_intent_e::host_and_client, 5678)); +static_assert(!platf::capture_target_matches(platf::audio_capture_intent_e::host_and_client, 1234, platf::audio_capture_intent_e::client_only, 1234)); + +/** + * @brief The exit clear must only release a target that still matches. + */ +TEST(CaptureTargetMatchTest, MatchesOnlyWhenIntentAndPidAgree) { + using intent = platf::audio_capture_intent_e; + EXPECT_TRUE(platf::capture_target_matches(intent::host_and_client, 1234, intent::host_and_client, 1234)); + EXPECT_TRUE(platf::capture_target_matches(intent::client_only, 0, intent::client_only, 0)); + EXPECT_FALSE(platf::capture_target_matches(intent::host_and_client, 1234, intent::host_and_client, 5678)); + EXPECT_FALSE(platf::capture_target_matches(intent::host_and_client, 1234, intent::client_only, 1234)); + EXPECT_FALSE(platf::capture_target_matches(intent::host_and_client, 1234, intent::host_and_client, 0)); + EXPECT_FALSE(platf::capture_target_matches(intent::client_only, 0, intent::host_and_client, 1234)); + EXPECT_FALSE(platf::capture_target_matches(intent::pinned_sink, 1234, intent::host_and_client, 1234)); +} + namespace { /** * @brief Minimal backend that never learned the keep-default behavior. @@ -314,8 +333,9 @@ TEST(AudioControlAdapterTest, LegacyBackendKeepsSwapBehavior) { */ 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.supports_process_capture()); + control.set_capture_target(platf::audio_capture_intent_e::host_and_client, platf::process_identity_t {1234, 0}); + control.set_capture_target(platf::audio_capture_intent_e::client_only, platf::process_identity_t {0, 0}); EXPECT_FALSE(control.set_sink_called); } @@ -497,6 +517,10 @@ namespace { return supports_keep; } + bool supports_process_capture() const override { + return supports_process; + } + int capture_sink(const std::string &sink) override { calls.push_back("capture_sink:" + sink); return capture_sink_status; @@ -505,12 +529,14 @@ namespace { /** * @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. + * @param identity Operating-system identity to capture, or {0, 0} for endpoint capture. */ - void set_capture_target(platf::audio_capture_intent_e intent, std::uint32_t process_id) override { + void set_capture_target(platf::audio_capture_intent_e intent, platf::process_identity_t identity) override { calls.emplace_back("set_capture_target"); set_intent = intent; - set_process_id = process_id; + set_process_id = identity.process_id; + set_creation_time = identity.creation_time; + record_capture_target(intent, identity.process_id); } /** @@ -564,12 +590,14 @@ namespace { } bool supports_keep = true; ///< Whether capture_sink() is supported without swapping. + bool supports_process = true; ///< Whether set_capture_target() may select per-process capture. 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. + std::uint64_t set_creation_time = 0; ///< Creation marker 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. @@ -912,9 +940,10 @@ 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()`). + * the centralized sink and capture-target storage is pinned without + * platform hardware. Models the Linux call pattern (record-only + * `capture_sink()`, record-on-success `set_sink()`) and the Windows + * intent/PID bookkeeping through the one shared store. */ class recorded_audio_control_t: public platf::audio_control_t { public: @@ -927,10 +956,32 @@ namespace { return true; } + bool supports_process_capture() const override { + return true; + } + int capture_sink(const std::string &sink) override { return record_keep_default_capture_sink(sink); } + /** + * @brief Record the refreshed capture target in the shared base record. + * @param intent Capture intent resolved from the audio configuration. + * @param identity Operating-system identity to capture, or {0, 0} for endpoint capture. + */ + void set_capture_target(platf::audio_capture_intent_e intent, platf::process_identity_t identity) override { + record_capture_target(intent, identity.process_id); + } + + /** + * @brief Release the shared base record when it still belongs to the caller. + * @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 { + clear_recorded_capture_target_if_matches(intent, process_id); + } + // Keep the params-bundle overload visible: the positional override below would otherwise hide it. using platf::audio_control_t::microphone; @@ -946,6 +997,7 @@ namespace { return std::nullopt; } + using platf::audio_control_t::snapshot_recorded_capture_target; using platf::audio_control_t::snapshot_recorded_sink; }; @@ -954,7 +1006,7 @@ namespace { * * 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. + * the shared base record alone. */ class macos_like_audio_control_t: public platf::audio_control_t { public: @@ -985,6 +1037,7 @@ namespace { return std::nullopt; } + using platf::audio_control_t::snapshot_recorded_capture_target; using platf::audio_control_t::snapshot_recorded_sink; }; } // namespace @@ -1030,16 +1083,117 @@ TEST(BaseRecordTest, SetSinkOverwritesRecordedSink) { EXPECT_EQ(control.snapshot_recorded_sink(), "swapped-sink"); } +/** + * @brief The record matcher must agree only when both intent and PID agree. + * + * Fail-without-fix: if `matches()` drops either comparison, an exiting + * session wipes a survivor's target that shares only one field with its own. + */ +TEST(BaseRecordTest, CaptureTargetRecordMatchesIntentAndPid) { + using intent = platf::audio_capture_intent_e; + const platf::capture_target_record_t record {intent::host_and_client, 1234}; + EXPECT_TRUE(record.matches(intent::host_and_client, 1234)); + EXPECT_FALSE(record.matches(intent::host_and_client, 5678)); + EXPECT_FALSE(record.matches(intent::host_and_client, 0)); + EXPECT_FALSE(record.matches(intent::client_only, 1234)); + EXPECT_FALSE(record.matches(intent::pinned_sink, 1234)); + const platf::capture_target_record_t endpoint {}; + EXPECT_EQ(endpoint.intent, intent::client_only); + EXPECT_EQ(endpoint.process_id, 0u); + EXPECT_TRUE(endpoint.matches(intent::client_only, 0)); + EXPECT_FALSE(endpoint.matches(intent::host_and_client, 1234)); +} + +/** + * @brief Recording a capture target must store the intent and PID together. + * + * Fail-without-fix: if the setter stores only one field, microphone() + * captures with a mismatched intent/PID pair from two sessions. + */ +TEST(BaseRecordTest, CaptureTargetSetterStoresIntentAndPid) { + recorded_audio_control_t control; + control.set_capture_target(platf::audio_capture_intent_e::host_and_client, platf::process_identity_t {1234, 0}); + EXPECT_EQ(control.snapshot_recorded_capture_target().intent, platf::audio_capture_intent_e::host_and_client); + EXPECT_EQ(control.snapshot_recorded_capture_target().process_id, 1234u); + control.set_capture_target(platf::audio_capture_intent_e::client_only, platf::process_identity_t {0, 0}); + EXPECT_EQ(control.snapshot_recorded_capture_target().intent, platf::audio_capture_intent_e::client_only); + EXPECT_EQ(control.snapshot_recorded_capture_target().process_id, 0u); +} + +/** + * @brief Clearing a matching target must reset the record to endpoint capture. + * + * Fail-without-fix: if the clear-if-match keeps the dead session's target, + * the next session inherits process capture it never requested. + */ +TEST(BaseRecordTest, ConditionalClearResetsMatchingTarget) { + using intent = platf::audio_capture_intent_e; + recorded_audio_control_t control; + control.set_capture_target(intent::host_and_client, platf::process_identity_t {1234, 0}); + control.clear_capture_target(intent::host_and_client, 1234); + EXPECT_EQ(control.snapshot_recorded_capture_target().intent, intent::client_only); + EXPECT_EQ(control.snapshot_recorded_capture_target().process_id, 0u); +} + +/** + * @brief Clearing a mismatched target must preserve the survivor's record. + * + * Fail-without-fix: if the clear runs unconditionally, an exiting session + * wipes a survivor session's live target on its way out. + */ +TEST(BaseRecordTest, ConditionalClearPreservesMismatchedTarget) { + using intent = platf::audio_capture_intent_e; + recorded_audio_control_t control; + control.set_capture_target(intent::host_and_client, platf::process_identity_t {1234, 0}); + // A survivor that recorded a different PID keeps its target. + control.clear_capture_target(intent::host_and_client, 5678); + EXPECT_EQ(control.snapshot_recorded_capture_target().intent, intent::host_and_client); + EXPECT_EQ(control.snapshot_recorded_capture_target().process_id, 1234u); + // A survivor that recorded a different intent keeps its target. + control.clear_capture_target(intent::client_only, 1234); + EXPECT_EQ(control.snapshot_recorded_capture_target().intent, intent::host_and_client); + EXPECT_EQ(control.snapshot_recorded_capture_target().process_id, 1234u); + // An endpoint clear cannot wipe a process target and vice versa. + control.clear_capture_target(intent::host_and_client, 0); + EXPECT_EQ(control.snapshot_recorded_capture_target().process_id, 1234u); + control.set_capture_target(intent::client_only, platf::process_identity_t {0, 0}); + control.clear_capture_target(intent::host_and_client, 1234); + EXPECT_EQ(control.snapshot_recorded_capture_target().intent, intent::client_only); + EXPECT_EQ(control.snapshot_recorded_capture_target().process_id, 0u); +} + +/** + * @brief An exiting session must not wipe a survivor's recorded target. + * + * Drives the real shared base record: the second refresh overwrites the + * first, so releasing the stale target preserves the survivor, while + * releasing the current target resets to endpoint capture. + */ +TEST(BaseRecordTest, ExitingSessionPreservesSurvivorTarget) { + using intent = platf::audio_capture_intent_e; + recorded_audio_control_t control; + control.set_capture_target(intent::host_and_client, platf::process_identity_t {1111, 0}); + control.set_capture_target(intent::host_and_client, platf::process_identity_t {2222, 0}); + control.clear_capture_target(intent::host_and_client, 1111); + EXPECT_EQ(control.snapshot_recorded_capture_target().intent, intent::host_and_client); + EXPECT_EQ(control.snapshot_recorded_capture_target().process_id, 2222u); + control.clear_capture_target(intent::host_and_client, 2222); + EXPECT_EQ(control.snapshot_recorded_capture_target().intent, intent::client_only); + EXPECT_EQ(control.snapshot_recorded_capture_target().process_id, 0u); +} + /** * @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. + * calls tear the sink string or mix an intent from one session with a PID + * from another. 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) { + using enum platf::audio_capture_intent_e; recorded_audio_control_t control; std::atomic consistent {true}; const auto worker = [&](std::uint32_t pid) { @@ -1054,6 +1208,14 @@ TEST(BaseRecordTest, ConcurrentControlAccessStaysConsistent) { if (control.snapshot_recorded_sink().compare(0, 5, "sink-") != 0) { consistent.store(false, std::memory_order_relaxed); } + control.set_capture_target(host_and_client, platf::process_identity_t {pid, 0}); + const auto target = control.snapshot_recorded_capture_target(); + const bool valid_target = (target.intent == host_and_client && target.process_id >= 1 && target.process_id <= 4) || + (target.intent == client_only && target.process_id == 0); + if (!valid_target) { + consistent.store(false, std::memory_order_relaxed); + } + control.clear_capture_target(host_and_client, pid); } }; { @@ -1070,17 +1232,100 @@ TEST(BaseRecordTest, ConcurrentControlAccessStaysConsistent) { * @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. + * macOS no-op (which never calls the opt-in helpers) starts recording a + * target 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.set_capture_target(platf::audio_capture_intent_e::host_and_client, platf::process_identity_t {1234, 999}); control.clear_capture_target(platf::audio_capture_intent_e::host_and_client, 1234); EXPECT_TRUE(control.snapshot_recorded_sink().empty()); + EXPECT_EQ(control.snapshot_recorded_capture_target().intent, platf::audio_capture_intent_e::client_only); + EXPECT_EQ(control.snapshot_recorded_capture_target().process_id, 0u); } +/** + * @brief Backend stub pairing a fake identity with the shared base record. + * + * Models the Windows `on_capture_target_cleared()` override: the hook resets + * the paired identity exactly when the shared record resets. + */ +class hook_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 &sink) override { + return record_keep_default_capture_sink(sink); + } + + /** + * @brief Record the capture target and mark the fake identity as paired. + * + * Stores the intent, PID, and paired identity under one `capture_state_mutex_` + * hold, mirroring the production Windows setter, so the stub never exposes a + * split write. + * @param intent Capture intent resolved from the audio configuration. + * @param identity Operating-system identity to capture, or {0, 0} for endpoint capture. + */ + void set_capture_target(platf::audio_capture_intent_e intent, platf::process_identity_t identity) override { + std::lock_guard lock {capture_state_mutex_}; + recorded_target_.intent = intent; + recorded_target_.process_id = identity.process_id; + paired_identity = identity.process_id; + } + + /** + * @brief Release the shared base record when it still belongs to the caller. + * @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 { + clear_recorded_capture_target_if_matches(intent, 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 *, 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; + } + +protected: + /** + * @brief Reset the paired fake identity when the shared record resets. + * + * Runs under `capture_state_mutex_` via the base clearer: plain field + * resets only, no base-helper calls, so the hook stays non-reentrant. + */ + void on_capture_target_cleared() override { + paired_identity = 0; + hook_fired = true; + } + +public: + using platf::audio_control_t::snapshot_recorded_capture_target; + using platf::audio_control_t::snapshot_recorded_sink; + + bool hook_fired = false; ///< Whether `on_capture_target_cleared()` ran. + std::uint32_t paired_identity = 0; ///< Fake backend-side identity paired with the recorded target. +}; + /** * @brief The shared keep-default helper must record the sink and report success. * @@ -1093,3 +1338,48 @@ TEST(BaseRecordTest, KeepDefaultHelperRecordsAndReturnsZero) { EXPECT_EQ(control.capture_sink("keep-default-sink"), 0); EXPECT_EQ(control.snapshot_recorded_sink(), "keep-default-sink"); } + +/** + * @brief A matching clear must reset the shared record and fire the hook. + * + * Fail-without-fix: if the clearer skips the hook, paired backend state + * (Windows creation-time identity) survives the reset and the next session + * revalidates against a stale identity. + */ +TEST(BaseRecordTest, ClearMatchResetsTripleAndFiresHook) { + using intent = platf::audio_capture_intent_e; + hook_audio_control_t control; + control.set_capture_target(intent::host_and_client, platf::process_identity_t {1234, 0}); + EXPECT_EQ(control.paired_identity, 1234u); + control.clear_capture_target(intent::host_and_client, 1234); + EXPECT_TRUE(control.hook_fired); + EXPECT_EQ(control.snapshot_recorded_capture_target().intent, intent::client_only); + EXPECT_EQ(control.snapshot_recorded_capture_target().process_id, 0u); + EXPECT_EQ(control.paired_identity, 0u); +} + +/** + * @brief A mismatched clear must preserve the record and skip the hook. + * + * Fail-without-fix: if the clearer fires the hook unconditionally, an + * exiting session wipes a survivor's paired backend state while keeping the + * shared record, leaving the two out of sync. + */ +TEST(BaseRecordTest, ClearMismatchPreservesTripleAndSkipsHook) { + using intent = platf::audio_capture_intent_e; + hook_audio_control_t control; + control.set_capture_target(intent::host_and_client, platf::process_identity_t {1234, 0}); + control.clear_capture_target(intent::host_and_client, 5678); + EXPECT_FALSE(control.hook_fired); + EXPECT_EQ(control.snapshot_recorded_capture_target().process_id, 1234u); + EXPECT_EQ(control.paired_identity, 1234u); + control.clear_capture_target(intent::client_only, 1234); + EXPECT_FALSE(control.hook_fired); + EXPECT_EQ(control.snapshot_recorded_capture_target().intent, intent::host_and_client); + EXPECT_EQ(control.paired_identity, 1234u); + control.set_capture_target(intent::client_only, platf::process_identity_t {0, 0}); + control.clear_capture_target(intent::host_and_client, 1234); + EXPECT_FALSE(control.hook_fired); + EXPECT_EQ(control.snapshot_recorded_capture_target().intent, intent::client_only); + EXPECT_EQ(control.paired_identity, 0u); +} diff --git a/tests/unit/test_process.cpp b/tests/unit/test_process.cpp index 68269cee9e5..7bc64e95bf2 100644 --- a/tests/unit/test_process.cpp +++ b/tests/unit/test_process.cpp @@ -6,10 +6,14 @@ #include "../tests_common.h" // standard includes +#include +#include +#include #include #include #include #include +#include #include #include #include @@ -23,6 +27,7 @@ #include #else // lib includes + #include #include #endif @@ -654,6 +659,308 @@ TEST_F(ProcessRefreshTest, UpdateAppsAndEnv_UpdatesAppsList) { EXPECT_EQ(target.get_apps()[1].name, "AppC"); } +TEST_F(ProcessUpdateTest, AppProcessIdIsZeroForDesktopPlacebo) { + EXPECT_EQ(proc::proc.app_process_id(), 0u); +} + +#ifndef _WIN32 +TEST(ProcessTest, AppProcessIdTracksRealChildLifecycle) { + boost::process::v1::environment env = boost::this_process::environment(); + proc::ctx_t ctx {}; + ctx.name = "Sleeper"; + ctx.id = "7"; + ctx.cmd = "sleep 30"; + std::vector apps; + apps.push_back(std::move(ctx)); + proc::proc_t target(std::move(env), std::move(apps)); + auto launch_session = std::make_shared(); + ASSERT_EQ(target.execute(7, launch_session), 0); + const auto expected_pid = target.app_process_id(); + EXPECT_NE(expected_pid, 0u); + std::atomic saw_unexpected_pid {false}; + std::atomic reader_calls {0}; + std::latch reader_ready {1}; + std::jthread reader {[&](std::stop_token stop_token) { + bool signaled = false; + while (!stop_token.stop_requested()) { + const auto pid = target.app_process_id(); + if (pid != 0u && pid != expected_pid) { + saw_unexpected_pid.store(true); + } + reader_calls.fetch_add(1); + if (!signaled) { + signaled = true; + reader_ready.count_down(); + } + } + }}; + reader_ready.wait(); + target.terminate(); + reader.request_stop(); + reader.join(); + EXPECT_GT(reader_calls.load(), 0u); + EXPECT_FALSE(saw_unexpected_pid.load()); + EXPECT_EQ(target.app_process_id(), 0u); +} + +#endif + +/** + * @brief Verify the provider handed to audio capture tracks the launched app. + * + * `stream.cpp` passes `proc::app_process_identity_provider(proc::proc)` to + * `audio::capture()`; this pins that the provider reports the live child + * identity and falls back to {0, 0} after termination. + */ +TEST(ProcessTest, AppProcessIdentityProviderTracksRealChildLifecycle) { + boost::process::v1::environment env = boost::this_process::environment(); + proc::ctx_t ctx {}; + ctx.name = "Sleeper"; + ctx.id = "7"; +#ifdef _WIN32 + ctx.cmd = R"(cmd.exe /c ping.exe -n 31 127.0.0.1 >NUL)"; +#else + ctx.cmd = "sleep 30"; +#endif + std::vector apps; + apps.push_back(std::move(ctx)); + proc::proc_t target(std::move(env), std::move(apps)); + const auto provider = proc::app_process_identity_provider(target); + + EXPECT_EQ(provider().process_id, 0u); + EXPECT_EQ(provider().creation_time, 0u); + auto launch_session = std::make_shared(); + ASSERT_EQ(target.execute(7, launch_session), 0); + EXPECT_NE(provider().process_id, 0u); +#ifdef _WIN32 + // The marker is queried from the owned child handle, so it is verifiable for a live child. + EXPECT_NE(provider().creation_time, 0u); +#else + // POSIX backends never select per-process capture, so no marker is reported. + EXPECT_EQ(provider().creation_time, 0u); +#endif + EXPECT_EQ(provider().process_id, target.app_process_id()); + + target.terminate(); + EXPECT_EQ(provider().process_id, 0u); + EXPECT_EQ(provider().creation_time, 0u); +} + +#ifndef _WIN32 + +/** + * @brief Verify running() cleanup after a relaunch never terminates the successor app. + */ +TEST(ProcessTest, RunningAfterRelaunchKeepsSuccessorAlive) { + boost::process::v1::environment env = boost::this_process::environment(); + std::vector apps; + for (const auto id : {"7", "8"}) { + proc::ctx_t ctx {}; + ctx.name = "Sleeper"; + ctx.id = id; + ctx.cmd = "sleep 30"; + apps.push_back(std::move(ctx)); + } + proc::proc_t target(std::move(env), std::move(apps)); + auto launch_session = std::make_shared(); + + ASSERT_EQ(target.execute(7, launch_session), 0); + const auto first_pid = target.app_process_id(); + ASSERT_NE(first_pid, 0u); + target.terminate(); + EXPECT_EQ(target.running(), 0); + + ASSERT_EQ(target.execute(8, launch_session), 0); + const auto successor_pid = target.app_process_id(); + ASSERT_NE(successor_pid, 0u); + EXPECT_EQ(target.running(), 8); + EXPECT_EQ(target.running(), 8); + EXPECT_EQ(target.app_process_id(), successor_pid); + + target.terminate(); + EXPECT_EQ(target.running(), 0); +} + +/** + * @brief Verify a launch overlapping prior cleanup waits for that cleanup to finish. + * + * Blocks A's undo on a file gate, attempts B's launch concurrently, releases A, + * and verifies B's prep setting survives. Without the transition gate, B's prep + * runs while A's termination is still blocked, and A's undo then overwrites B's + * setting after B starts. Display revert runs in the same finish_termination() + * critical section as the undo, so the file ordering also pins that no old + * display-revert runs after B starts. Sequential relaunch coverage alone cannot + * catch this: it never overlaps cleanup with the next launch. + */ +TEST(ProcessTest, OverlappingLaunchWaitsForPriorCleanup) { + const auto tmp_root = fs::temp_directory_path() / std::format("sunshine-proc-overlap-{}", ::getpid()); + const auto setting_file = tmp_root / "setting"; + const auto gate_file = tmp_root / "gate"; + const auto undo_started_file = tmp_root / "undo_started"; + std::error_code fs_ec; + fs::remove_all(tmp_root, fs_ec); + fs::create_directories(tmp_root, fs_ec); + ASSERT_FALSE(fs_ec) << fs_ec.message(); + const auto remove_tmp = util::fail_guard([&tmp_root]() { + std::error_code ec; + fs::remove_all(tmp_root, ec); + }); + + // Prep commands run without a shell, so stage the file writes and the gate + // wait as executable scripts instead of `sh -c` one-liners with quotes. + const auto do_a_script = tmp_root / "do_a.sh"; + const auto undo_a_script = tmp_root / "undo_a.sh"; + const auto do_b_script = tmp_root / "do_b.sh"; + { + std::ofstream {do_a_script} << "#!/bin/sh\necho A-prep > \"" << setting_file.string() << "\"\n"; + std::ofstream {undo_a_script} << "#!/bin/sh\ntouch \"" << undo_started_file.string() << "\"\nwhile [ ! -f \"" << gate_file.string() + << "\" ]; do sleep 0.01; done\necho A-undo > \"" << setting_file.string() << "\"\n"; + std::ofstream {do_b_script} << "#!/bin/sh\necho B-prep > \"" << setting_file.string() << "\"\n"; + } + for (const auto &script : {do_a_script, undo_a_script, do_b_script}) { + std::error_code perm_ec; + fs::permissions(script, fs::perms::owner_exec | fs::perms::group_exec | fs::perms::others_exec, fs::perm_options::add, perm_ec); + ASSERT_FALSE(perm_ec) << perm_ec.message(); + } + proc::ctx_t app_a {}; + app_a.name = "AppA"; + app_a.id = "7"; + app_a.cmd = "sleep 30"; + app_a.prep_cmds.emplace_back(do_a_script.string(), undo_a_script.string(), false); + proc::ctx_t app_b {}; + app_b.name = "AppB"; + app_b.id = "8"; + app_b.cmd = "sleep 30"; + app_b.prep_cmds.emplace_back(do_b_script.string(), std::string {}, false); + std::vector apps; + apps.push_back(std::move(app_a)); + apps.push_back(std::move(app_b)); + boost::process::v1::environment env = boost::this_process::environment(); + proc::proc_t target(std::move(env), std::move(apps)); + auto launch_session = std::make_shared(); + const auto terminate_target = util::fail_guard([&target]() { + target.terminate(); + }); + + ASSERT_EQ(target.execute(7, launch_session), 0); + ASSERT_NE(target.app_process_id(), 0u); + + const auto read_setting = [&setting_file]() { + std::ifstream input {setting_file}; + std::string content((std::istreambuf_iterator(input)), std::istreambuf_iterator()); + while (!content.empty() && (content.back() == '\n' || content.back() == '\r')) { + content.pop_back(); + } + return content; + }; + ASSERT_EQ(read_setting(), "A-prep"); + + // Terminate A in the background: its undo signals start, then blocks on the gate. + std::jthread terminate_thread {[&target]() { + target.terminate(); + }}; + bool undo_started = false; + for (int attempt = 0; attempt < 500 && !undo_started; ++attempt) { + std::error_code ec; + if (fs::exists(undo_started_file, ec) && !ec) { + undo_started = true; + } else { + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + } + // Always release the gate so the background threads can finish even on failure. + auto release_gate = util::fail_guard([&gate_file]() { + std::ofstream {gate_file}; + }); + ASSERT_TRUE(undo_started) << "A's undo did not start; cannot overlap B's launch"; + + // Attempt B's launch while A's cleanup is blocked. The transition gate must hold it. + std::atomic b_attempting {false}; + std::atomic b_launch_done {false}; + std::atomic b_launch_result {-999}; + std::latch b_started {1}; + std::jthread b_thread {[&target, &launch_session, &b_attempting, &b_launch_done, &b_launch_result, &b_started]() { + b_attempting.store(true); + b_started.count_down(); + const int result = target.execute(8, launch_session); + b_launch_result.store(result); + b_launch_done.store(true); + }}; + b_started.wait(); + ASSERT_TRUE(b_attempting.load()); + // Give B a chance to (incorrectly) run its prep while A is still blocked. + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + EXPECT_FALSE(b_launch_done.load()) << "B's launch finished while A's cleanup was still blocked"; + EXPECT_EQ(read_setting(), "A-prep") << "B's prep ran before A's undo finished"; + + // Release A's undo; both threads must then complete with B's setting intact. + { + std::ofstream gate {gate_file}; + ASSERT_TRUE(static_cast(gate)) << "failed to release the undo gate"; + } + terminate_thread.join(); + b_thread.join(); + release_gate.disable(); + EXPECT_EQ(b_launch_result.load(), 0); + EXPECT_EQ(read_setting(), "B-prep") << "A's undo overwrote B's prep after B started"; + EXPECT_EQ(target.running(), 8); + EXPECT_NE(target.app_process_id(), 0u); +} + +/** + * @brief Verify `running()` reaps exited children on the Desktop placebo poll. + * + * The placebo early return in `proc_t::running_impl()` must still run the + * POSIX `waitpid()` reaper; otherwise exited detached children linger as + * zombies for the whole Desktop session. + */ +TEST(ProcessTest, RunningReapsExitedChildOnPlaceboPoll) { + boost::process::v1::environment env = boost::this_process::environment(); + proc::ctx_t ctx {}; + ctx.name = "Desktop"; + ctx.id = "42"; + std::vector apps; + apps.push_back(std::move(ctx)); + proc::proc_t target(std::move(env), std::move(apps)); + auto launch_session = std::make_shared(); + ASSERT_EQ(target.execute(42, launch_session), 0); + const auto cleanup = util::fail_guard([&target]() { + target.terminate(); + }); + ASSERT_EQ(target.running(), 42); + + const pid_t child = fork(); + ASSERT_NE(child, -1); + if (child == 0) { + _exit(0); + } + const auto reap_sacrificial = util::fail_guard([child]() { + // Test-local cleanup only; never masks the assertion below. + while (waitpid(child, nullptr, WNOHANG) > 0); + }); + + // Wait until the sacrificial child is an unreaped zombie, peeking with + // `waitid()`/`WNOWAIT` so the test itself never reaps it. + bool is_zombie = false; + for (int attempt = 0; attempt < 1000 && !is_zombie; ++attempt) { + siginfo_t info {}; + if (waitid(P_PID, static_cast(child), &info, WEXITED | WNOHANG | WNOWAIT) == 0 && info.si_pid == child) { + is_zombie = true; + } else { + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + } + ASSERT_TRUE(is_zombie) << "sacrificial child did not become a zombie"; + + EXPECT_EQ(target.running(), 42); + + siginfo_t info {}; + errno = 0; + EXPECT_EQ(waitid(P_PID, static_cast(child), &info, WEXITED | WNOHANG | WNOWAIT), -1); + EXPECT_EQ(errno, ECHILD) << "running() left the exited child as a zombie"; +} +#endif + TEST_F(ProcessUpdateTest, UpdateAppsAndEnv_PreservesRunningState) { proc::proc.update_apps_and_env(buildNewSource()); From f345d5476c158b6981cad1d6337b2eacd297072c Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Tue, 17 Nov 2026 00:26:18 -0700 Subject: [PATCH 23/25] fix(process): make running() polls non-blocking with try-gated cleanup Pollers (stream loop, nvhttp launch/resume/cancel/serverinfo) no longer block on the transition gate: running() classifies state under the lifecycle mutex only, reports mid-launch as busy (fail closed), and takes the transition gate with try_to_lock only when an exited app needs cleanup. On contention the last-known app id is reported and the transition owner performs the cleanup. The POSIX blanket reaper runs only when the gate is idle and after the root checks, so it can neither steal prep/undo wait statuses nor lose the root exit code (Boost keeps still_active after an external reap, which would break auto_detach detection). finish_termination() still runs under the transition hold, preserving the undo/display-revert-before-successor-prep ordering. Also corrects the lifecycle/audio lock-order docs (the two mutexes are never nested in either direction), documents the identity-type home in platf/common.h, and rewords the POSIX zero-marker comment as a fail-closed contract instead of a backend prediction. --- src/platform/common.h | 5 ++ src/process.cpp | 147 +++++++++++++++++++++++------------------- src/process.h | 32 +++++++-- 3 files changed, 112 insertions(+), 72 deletions(-) diff --git a/src/platform/common.h b/src/platform/common.h index f2bafe1ebc0..47e329eee47 100644 --- a/src/platform/common.h +++ b/src/platform/common.h @@ -932,6 +932,11 @@ namespace platf { /** * @brief Operating-system identity of a launched process for capture routing. * + * Handoff vocabulary shared by the process lifecycle (producer), audio + * session guards (carrier), and platform backends (consumers). It lives in + * platf rather than process.h/audio.h so backends see it without including + * the process manager or audio capture. + * * A PID alone can be reused after the original process exits. Pairing it with * an OS creation marker distinguishes the recorded process from a later * process that happens to receive the same PID. The marker is opaque: diff --git a/src/process.cpp b/src/process.cpp index eba1d0882e7..a63d58da29c 100644 --- a/src/process.cpp +++ b/src/process.cpp @@ -55,9 +55,18 @@ namespace proc { * @brief Serialize access to proc_t lifecycle state shared across threads. * * Lock order: proc_transition_mutex() is always taken before this mutex, - * and audio::capture_target_mutex() is always taken before this mutex - * (the capture process-identity provider must be invoked under that mutex), - * and this mutex is never taken in the reverse order. + * and this mutex is never taken in the reverse order. There is deliberately + * no lock order between this mutex and audio::capture_target_mutex(): the + * two are never nested in either direction. The capture process-identity + * provider takes only this mutex (via app_process_identity()) and must + * always be invoked outside audio::capture_target_mutex(); audio takes the + * capture mutex only around set/clear_capture_target(), never around the + * provider call or microphone creation (see audio::capture_target_mutex()). + * Readers that must never block (proc_t::running(), app_process_identity(), + * and the getters) take only this mutex; execute(), terminate(), and + * running()'s cleanup path take proc_transition_mutex() first and this mutex + * second. finish_termination() runs under the transition mutex, never under + * this mutex. * This mutex is never held across blocking process waits, prep/undo * command waits, or display/input calls: lifecycle operations snapshot * or claim the shared state under this mutex and work on locals after @@ -455,87 +464,89 @@ namespace proc { } return {static_cast(_process.id()), combined_creation_time}; #else - // POSIX backends never select per-process capture, so no creation marker is needed. + // POSIX reports {pid, 0}: a zero marker means unverifiable (common.h + // process_identity_t), so any future per-process backend fails closed to + // endpoint capture; the PID stays populated for logging/identity pairing. return {static_cast(_process.id()), 0}; #endif } int proc_t::running() { - std::lock_guard transition {proc_transition_mutex()}; - return running_impl(); - } - - int proc_t::running_impl() { - // Snapshot the decision inputs under the lock, then re-verify the - // generation before committing. The cleanup claim happens in the same - // lock hold as the final decision, so a successor launched in between - // is never the process cleaned up. The `wait_all` group query runs - // under the lock as well: on POSIX it reaps via `waitpid()`, so leaving - // it unlocked would let a concurrent poll's reaper steal the root - // child's exit status before `_process.running()` captures it. - struct running_snapshot_t { - int app_id {}; ///< App id observed in the snapshot. - std::uint64_t generation {}; ///< Lifecycle generation observed in the snapshot. - bool placebo {}; ///< Whether the Desktop placebo session was active. - }; - - // On POSIX, reap exited children on every poll (including the snapshot - // early returns below), as HEAD did; serialize against `bp::wait()` and - // `platf::process_group_running()` via the lifecycle mutex. -#ifndef _WIN32 - auto reaper = util::fail_guard([]() { - std::lock_guard lock {proc_lifecycle_mutex()}; - while (waitpid(-1, nullptr, WNOHANG) > 0); - }); -#endif - - running_snapshot_t snapshot; - { - std::lock_guard lock {proc_lifecycle_mutex()}; - snapshot.app_id = _app_id; - snapshot.generation = _lifecycle_generation; - snapshot.placebo = placebo; - } - - if (snapshot.placebo) { - return snapshot.app_id; - } - + // Try-gated transition hold: pollers never block on unbounded prep/undo + // waits. When the gate is idle this also serializes the POSIX blanket + // reaper below against in-flight prep/undo `child.wait()` calls, so no + // exit status is stolen; when busy the reaper is skipped and any needed + // cleanup is left to the transition owner (stale-busy report). + std::unique_lock transition {proc_transition_mutex(), std::try_to_lock}; + const bool transition_idle = transition.owns_lock(); + + int report = 0; std::optional claimed; { std::lock_guard lock {proc_lifecycle_mutex()}; - if (_lifecycle_generation != snapshot.generation) { - // State changed while unlocked; report the current app, if any. - return _app_id > 0 ? _app_id : 0; - } - if (placebo) { - return _app_id; - } else if (_app.wait_all && _process_group && platf::process_group_running((std::uintptr_t) _process_group.native_handle())) { - // The app is still running if any process in the group is still running. - return _app_id; - } else if (_process.running()) { - // The app is still running only if the initial process launched is still running - return _app_id; - } else if (_app.auto_detach && _process.native_exit_code() == 0 && std::chrono::steady_clock::now() - _app_launch_time < 5s) { - BOOST_LOG(info) << "App exited gracefully within 5 seconds of launch. Treating the app as a detached command."sv; - BOOST_LOG(info) << "Adjust this behavior in the Applications tab or apps.json if this is not what you want."sv; - placebo = true; - return _app_id; + const auto action = decide_running_locked(); + if (action == running_action_t::report_app) { + report = _app_id; + } else if (action == running_action_t::needs_cleanup) { + if (transition_idle) { + BOOST_LOG(info) << "App exited with code ["sv << _process.native_exit_code() << ']'; + claimed = claim_termination_locked(); + } else { + // A transition owner is in flight and owns the corpse (every + // transition holder claims at entry); report the last-known app id + // instead of blocking on it. + report = _app_id; + } } - - // Claim cleanup atomically with the decision: the move-out below is - // what a later terminate would have raced with a successor launch. - if (_process) { - BOOST_LOG(info) << "App exited with code ["sv << _process.native_exit_code() << ']'; - claimed = claim_termination_locked(); +#ifndef _WIN32 + // Blanket-reap AFTER the root checks above so `_process.running()` + // captures the root exit status first, and only when the transition + // gate is idle so the reaper cannot steal a prep/undo wait status. + if (transition_idle) { + while (waitpid(-1, nullptr, WNOHANG) > 0); } +#endif } if (claimed) { + // finish_termination() runs under the transition hold (never under the + // lifecycle mutex), so a concurrent execute() prep cannot run until the + // undo/display-revert ordering it preserves has completed. finish_termination(std::move(*claimed)); } - return 0; + return report; + } + + auto proc_t::decide_running_locked() -> running_action_t { + if (placebo) { + return running_action_t::report_app; + } + if (_app_id <= 0) { + // Idle (0), or already claimed by a transition owner (-1): nothing to + // report or clean up. + return running_action_t::report_zero; + } + if (!_process.valid()) { + // Launch in flight: execute() publishes _app_id before spawning the + // child. Fail closed (busy) rather than reporting an exited app. + return running_action_t::report_app; + } + if (_app.wait_all && _process_group && platf::process_group_running((std::uintptr_t) _process_group.native_handle())) { + // The app is still running if any process in the group is still running. + return running_action_t::report_app; + } + if (_process.running()) { + // The app is still running only if the initial process launched is still running + return running_action_t::report_app; + } + if (_app.auto_detach && _process.native_exit_code() == 0 && std::chrono::steady_clock::now() - _app_launch_time < 5s) { + BOOST_LOG(info) << "App exited gracefully within 5 seconds of launch. Treating the app as a detached command."sv; + BOOST_LOG(info) << "Adjust this behavior in the Applications tab or apps.json if this is not what you want."sv; + placebo = true; + return running_action_t::report_app; + } + return running_action_t::needs_cleanup; } void proc_t::terminate() { diff --git a/src/process.h b/src/process.h index cafef6fe72d..f2847f0e3af 100644 --- a/src/process.h +++ b/src/process.h @@ -115,7 +115,16 @@ namespace proc { int execute(int app_id, std::shared_ptr launch_session); /** - * @return `_app_id` if a process is running, otherwise returns `0` + * @brief Report the currently running app without ever blocking on a transition. + * + * The fast path takes only the lifecycle mutex. When an exited app needs + * cleanup, the transition gate is taken with `try_to_lock`, so a poller + * never waits on unbounded prep/undo command waits. If the gate is busy, + * the last-known app id is reported (fail closed) and the transition + * owner performs the cleanup. A mid-launch app (id published, child not + * yet spawned) likewise reports its id. + * + * @return `_app_id` if an app is running, launching, or its cleanup is owned elsewhere; otherwise `0`. */ int running(); @@ -215,11 +224,23 @@ namespace proc { int execute_impl(int app_id, std::shared_ptr launch_session); /** - * @brief Implementation of running() that may call terminate_impl() directly for cleanup. + * @brief Fast-path classification for running(), decided under the lifecycle mutex. + */ + enum class running_action_t { + report_app, ///< Report the current app id: running, placebo, or mid-launch busy. + report_zero, ///< Report 0: idle, or already claimed by a transition owner. + needs_cleanup, ///< Exited corpse with claimable state; cleanup follows when the transition gate is idle. + }; + + /** + * @brief Classify the current lifecycle state for running(). + * + * The caller must hold the lifecycle mutex. Besides reading state, this + * may promote a quickly-exited app to the detached (placebo) session. * - * @return `_app_id` if a process is running, otherwise returns `0`. + * @return Action the caller takes after (optionally) reaping and claiming. */ - int running_impl(); + running_action_t decide_running_locked(); /** * @brief State claimed atomically for one termination. @@ -354,6 +375,9 @@ namespace proc { * The returned callable reports `target.app_process_identity()` at each call, so * audio (re)initialization always sees the currently launched app. It * borrows `target`; the caller keeps it alive for the provider's lifetime. + * Invoke the provider outside audio::capture_target_mutex(); it takes + * proc_lifecycle_mutex() internally, so invoking it under the capture mutex + * would nest the two. * * @param target Process manager whose launched app identity is reported. * @return Provider returning the launched root identity, or {0, 0} when unavailable. From c1b1c98e9ed5093b3903105306dbdbaad7a63ae4 Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Tue, 17 Nov 2026 00:26:18 -0700 Subject: [PATCH 24/25] test(process): pin non-blocking polls, ordering, and identity oracles Adds gated overlap tests proving running() answers promptly during execute()/terminate()/owned-cleanup (each fails on the blocking implementation), a poller hammer across natural exit and racing terminate, a terminate-during-launch drain test, and an OS-death cleanup test with successor relaunch. Hardens the PID oracle (kill liveness + /proc cmdline identity + sample count) and the provider test (Windows exact-match marker vs an independent OS query, placebo {0,0} branch). --- tests/unit/test_process.cpp | 610 +++++++++++++++++++++++++++++++++++- 1 file changed, 603 insertions(+), 7 deletions(-) diff --git a/tests/unit/test_process.cpp b/tests/unit/test_process.cpp index 7bc64e95bf2..0213f8e7936 100644 --- a/tests/unit/test_process.cpp +++ b/tests/unit/test_process.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -27,6 +28,7 @@ #include #else // lib includes + #include #include #include #endif @@ -678,16 +680,22 @@ TEST(ProcessTest, AppProcessIdTracksRealChildLifecycle) { const auto expected_pid = target.app_process_id(); EXPECT_NE(expected_pid, 0u); std::atomic saw_unexpected_pid {false}; - std::atomic reader_calls {0}; + std::atomic saw_dead_pid {false}; + std::atomic nonzero_samples {0}; std::latch reader_ready {1}; std::jthread reader {[&](std::stop_token stop_token) { bool signaled = false; while (!stop_token.stop_requested()) { const auto pid = target.app_process_id(); - if (pid != 0u && pid != expected_pid) { - saw_unexpected_pid.store(true); + if (pid != 0u) { + nonzero_samples.fetch_add(1); + if (pid != expected_pid) { + saw_unexpected_pid.store(true); + } + if (::kill(static_cast(pid), 0) != 0) { + saw_dead_pid.store(true); + } } - reader_calls.fetch_add(1); if (!signaled) { signaled = true; reader_ready.count_down(); @@ -695,11 +703,20 @@ TEST(ProcessTest, AppProcessIdTracksRealChildLifecycle) { } }}; reader_ready.wait(); + // Identity oracle: the reported PID must name the live `sleep` child, so a + // constant-but-wrong PID fails even when it names some other live process. + { + std::ifstream cmdline {std::format("/proc/{}/cmdline", expected_pid), std::ios::binary}; + const std::string content((std::istreambuf_iterator(cmdline)), std::istreambuf_iterator()); + EXPECT_NE(content.find("sleep"), std::string::npos) << "reported PID does not name the sleep child"; + } + std::this_thread::sleep_for(std::chrono::milliseconds(100)); target.terminate(); reader.request_stop(); reader.join(); - EXPECT_GT(reader_calls.load(), 0u); + EXPECT_GE(nonzero_samples.load(), 10u) << "too few live samples to pin lifecycle agreement"; EXPECT_FALSE(saw_unexpected_pid.load()); + EXPECT_FALSE(saw_dead_pid.load()); EXPECT_EQ(target.app_process_id(), 0u); } @@ -722,8 +739,12 @@ TEST(ProcessTest, AppProcessIdentityProviderTracksRealChildLifecycle) { #else ctx.cmd = "sleep 30"; #endif + proc::ctx_t desktop {}; + desktop.name = "Desktop"; + desktop.id = "42"; std::vector apps; apps.push_back(std::move(ctx)); + apps.push_back(std::move(desktop)); proc::proc_t target(std::move(env), std::move(apps)); const auto provider = proc::app_process_identity_provider(target); @@ -735,8 +756,24 @@ TEST(ProcessTest, AppProcessIdentityProviderTracksRealChildLifecycle) { #ifdef _WIN32 // The marker is queried from the owned child handle, so it is verifiable for a live child. EXPECT_NE(provider().creation_time, 0u); + // Exact-match oracle: the marker must equal an independent OS query, so a + // constant-but-wrong marker fails. + { + HANDLE handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, provider().process_id); + ASSERT_NE(handle, nullptr); + FILETIME creation {}; + FILETIME exit_time {}; + FILETIME kernel_time {}; + FILETIME user_time {}; + ASSERT_TRUE(GetProcessTimes(handle, &creation, &exit_time, &kernel_time, &user_time)); + CloseHandle(handle); + const auto queried_creation_time = (static_cast(creation.dwHighDateTime) << 32) | static_cast(creation.dwLowDateTime); + EXPECT_NE(queried_creation_time, 0u); + EXPECT_EQ(provider().creation_time, queried_creation_time); + } #else - // POSIX backends never select per-process capture, so no marker is reported. + // POSIX reports a zero marker, so the EXPECT below requires creation_time 0u + // (unverifiable by contract, not by backend prediction). EXPECT_EQ(provider().creation_time, 0u); #endif EXPECT_EQ(provider().process_id, target.app_process_id()); @@ -744,10 +781,93 @@ TEST(ProcessTest, AppProcessIdentityProviderTracksRealChildLifecycle) { target.terminate(); EXPECT_EQ(provider().process_id, 0u); EXPECT_EQ(provider().creation_time, 0u); + + // The Desktop placebo session reports {0, 0} on every platform. + ASSERT_EQ(target.execute(42, launch_session), 0); + EXPECT_EQ(provider().process_id, 0u); + EXPECT_EQ(provider().creation_time, 0u); + target.terminate(); + EXPECT_EQ(provider().process_id, 0u); + EXPECT_EQ(provider().creation_time, 0u); } #ifndef _WIN32 +namespace { + /** + * @brief Scratch directory for file-gate concurrency tests, removed on destruction. + */ + struct gate_dir_t { + fs::path root; ///< Scratch root; gate, setting, and script files live here. + + /** + * @brief Create an empty scratch directory for one test. + * + * @param name Test-unique directory infix. + */ + explicit gate_dir_t(const char *name) { + root = fs::temp_directory_path() / std::format("sunshine-proc-{}-{}", name, ::getpid()); + std::error_code ec; + fs::remove_all(root, ec); + fs::create_directories(root, ec); + } + + ~gate_dir_t() { + std::error_code ec; + fs::remove_all(root, ec); + } + }; + + /** + * @brief Write an executable `sh` script for a prep/undo command. + * + * Prep commands run without a shell, so file writes and gate waits are + * staged as scripts instead of `sh -c` one-liners with quotes. + * + * @param path Script file to write. + * @param body Script body after the shebang line. + */ + void write_gate_script(const fs::path &path, const std::string &body) { + std::ofstream {path} << "#!/bin/sh\n" + << body; + std::error_code ec; + fs::permissions(path, fs::perms::owner_exec | fs::perms::group_exec | fs::perms::others_exec, fs::perm_options::add, ec); + } + + /** + * @brief Poll for a file-gate signal with a bounded wait. + * + * @param path Signal file to wait for. + * @param attempts Number of 10ms polls before giving up. + * @return True when the file appeared before the deadline. + */ + bool wait_for_gate_file(const fs::path &path, int attempts = 500) { + for (int attempt = 0; attempt < attempts; ++attempt) { + std::error_code ec; + if (fs::exists(path, ec) && !ec) { + return true; + } + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + return false; + } + + /** + * @brief Read a small text file, stripping trailing newlines. + * + * @param path File to read. + * @return Trimmed file content, or empty when the file is missing. + */ + std::string read_trimmed_gate_file(const fs::path &path) { + std::ifstream input {path}; + std::string content((std::istreambuf_iterator(input)), std::istreambuf_iterator()); + while (!content.empty() && (content.back() == '\n' || content.back() == '\r')) { + content.pop_back(); + } + return content; + } +} // namespace + /** * @brief Verify running() cleanup after a relaunch never terminates the successor app. */ @@ -910,7 +1030,7 @@ TEST(ProcessTest, OverlappingLaunchWaitsForPriorCleanup) { /** * @brief Verify `running()` reaps exited children on the Desktop placebo poll. * - * The placebo early return in `proc_t::running_impl()` must still run the + * The placebo report in `proc_t::running()` must still run the * POSIX `waitpid()` reaper; otherwise exited detached children linger as * zombies for the whole Desktop session. */ @@ -959,6 +1079,482 @@ TEST(ProcessTest, RunningReapsExitedChildOnPlaceboPoll) { EXPECT_EQ(waitid(P_PID, static_cast(child), &info, WEXITED | WNOHANG | WNOWAIT), -1); EXPECT_EQ(errno, ECHILD) << "running() left the exited child as a zombie"; } + +/** + * @brief Verify running() answers promptly while execute() is blocked in a prep wait. + * + * The prep script signals start, then waits on a file gate; execute() runs on + * a background thread holding the transition gate. running() must report the + * in-flight app id (launch-busy) within the deadline instead of blocking on + * the gate. Fails on the pre-fix blocking running(), which waits for release. + */ +TEST(ProcessTest, RunningReportsLaunchInFlightDuringGatedPrep) { + gate_dir_t dir {"t1-exec-gate"}; + ASSERT_TRUE(fs::exists(dir.root)); + const auto setting_file = dir.root / "setting"; + const auto gate_file = dir.root / "gate"; + const auto started_file = dir.root / "started"; + const auto do_script = dir.root / "do.sh"; + write_gate_script( + do_script, + std::format( + "touch \"{}\"\nwhile [ ! -f \"{}\" ]; do sleep 0.01; done\necho G-prep > \"{}\"\n", + started_file.string(), + gate_file.string(), + setting_file.string() + ) + ); + + proc::ctx_t ctx {}; + ctx.name = "Gated"; + ctx.id = "7"; + ctx.cmd = "sleep 30"; + ctx.prep_cmds.emplace_back(do_script.string(), std::string {}, false); + std::vector apps; + apps.push_back(std::move(ctx)); + boost::process::v1::environment env = boost::this_process::environment(); + proc::proc_t target(std::move(env), std::move(apps)); + auto launch_session = std::make_shared(); + const auto terminate_target = util::fail_guard([&target]() { + target.terminate(); + }); + + std::atomic exec_result {-999}; + std::jthread exec_thread {[&target, &launch_session, &exec_result]() { + exec_result.store(target.execute(7, launch_session)); + }}; + // Always release the gate so the background thread can finish even on failure. + auto release_gate = util::fail_guard([&gate_file]() { + std::ofstream {gate_file}; + }); + ASSERT_TRUE(wait_for_gate_file(started_file)) << "gated prep did not start; cannot overlap the poll"; + + auto poll = std::async(std::launch::async, [&target]() { + return target.running(); + }); + if (poll.wait_for(std::chrono::seconds(2)) != std::future_status::ready) { + // Release the gate before failing so the background thread, and the async + // poll waiting on it, can finish instead of hanging teardown. + std::ofstream {gate_file}; + release_gate.disable(); + FAIL() << "running() blocked on execute()'s prep wait"; + } + EXPECT_EQ(poll.get(), 7); + + { + std::ofstream gate {gate_file}; + ASSERT_TRUE(static_cast(gate)) << "failed to release the prep gate"; + } + exec_thread.join(); + release_gate.disable(); + EXPECT_EQ(exec_result.load(), 0); + EXPECT_EQ(read_trimmed_gate_file(setting_file), "G-prep"); + EXPECT_EQ(target.running(), 7); +} + +/** + * @brief Verify running() answers promptly while terminate() is blocked in an undo wait. + * + * terminate() claims first (publishing _app_id -1), then blocks on the gated + * undo holding the transition gate. running() must report 0 from the + * post-claim fast read within the deadline. Fails on the pre-fix blocking + * running(), which waits for release. + */ +TEST(ProcessTest, RunningReportsZeroDuringGatedUndo) { + gate_dir_t dir {"t2-term-gate"}; + ASSERT_TRUE(fs::exists(dir.root)); + const auto setting_file = dir.root / "setting"; + const auto gate_file = dir.root / "gate"; + const auto undo_started_file = dir.root / "undo_started"; + const auto do_script = dir.root / "do.sh"; + const auto undo_script = dir.root / "undo.sh"; + write_gate_script(do_script, std::format("echo A-prep > \"{}\"\n", setting_file.string())); + write_gate_script( + undo_script, + std::format( + "touch \"{}\"\nwhile [ ! -f \"{}\" ]; do sleep 0.01; done\necho A-undo > \"{}\"\n", + undo_started_file.string(), + gate_file.string(), + setting_file.string() + ) + ); + + proc::ctx_t ctx {}; + ctx.name = "Gated"; + ctx.id = "7"; + ctx.cmd = "sleep 30"; + ctx.prep_cmds.emplace_back(do_script.string(), undo_script.string(), false); + std::vector apps; + apps.push_back(std::move(ctx)); + boost::process::v1::environment env = boost::this_process::environment(); + proc::proc_t target(std::move(env), std::move(apps)); + auto launch_session = std::make_shared(); + const auto terminate_target = util::fail_guard([&target]() { + target.terminate(); + }); + ASSERT_EQ(target.execute(7, launch_session), 0); + ASSERT_EQ(read_trimmed_gate_file(setting_file), "A-prep"); + + std::jthread terminate_thread {[&target]() { + target.terminate(); + }}; + // Always release the gate so the background thread can finish even on failure. + auto release_gate = util::fail_guard([&gate_file]() { + std::ofstream {gate_file}; + }); + ASSERT_TRUE(wait_for_gate_file(undo_started_file)) << "gated undo did not start; cannot overlap the poll"; + + auto poll = std::async(std::launch::async, [&target]() { + return target.running(); + }); + if (poll.wait_for(std::chrono::seconds(2)) != std::future_status::ready) { + // Release the gate before failing so the background thread, and the async + // poll waiting on it, can finish instead of hanging teardown. + std::ofstream {gate_file}; + release_gate.disable(); + FAIL() << "running() blocked on terminate()'s undo wait"; + } + EXPECT_EQ(poll.get(), 0); + + { + std::ofstream gate {gate_file}; + ASSERT_TRUE(static_cast(gate)) << "failed to release the undo gate"; + } + terminate_thread.join(); + release_gate.disable(); + EXPECT_EQ(target.running(), 0); + EXPECT_EQ(target.app_process_id(), 0u); + EXPECT_EQ(read_trimmed_gate_file(setting_file), "A-undo"); +} + +/** + * @brief Verify running()-driven cleanup still orders a concurrent launch after the undo. + * + * A exits naturally (detected via app_process_id() only, so the corpse stays + * unclaimed); a background running() claims it and blocks in the gated undo + * holding the transition gate. B's concurrent launch must wait: its prep must + * not run while the gate is closed, and after release B's setting wins. A + * second poll during the owned cleanup answers promptly with the post-claim 0 + * instead of blocking, which is what distinguishes the try-gated design from a + * blocking cleanup gate. Fails pre-fix: the first running() either blocks + * nothing (no ordering without the gate) or, under a blocking gate, the + * second poll stalls past the deadline. + */ +TEST(ProcessTest, RunningCleanupPreservesLaunchOrdering) { + gate_dir_t dir {"t3-cleanup-order"}; + ASSERT_TRUE(fs::exists(dir.root)); + const auto setting_file = dir.root / "setting"; + const auto gate_file = dir.root / "gate"; + const auto undo_started_file = dir.root / "undo_started"; + const auto do_a_script = dir.root / "do_a.sh"; + const auto undo_a_script = dir.root / "undo_a.sh"; + const auto do_b_script = dir.root / "do_b.sh"; + write_gate_script(do_a_script, std::format("echo A-prep > \"{}\"\n", setting_file.string())); + write_gate_script( + undo_a_script, + std::format( + "touch \"{}\"\nwhile [ ! -f \"{}\" ]; do sleep 0.01; done\necho A-undo > \"{}\"\n", + undo_started_file.string(), + gate_file.string(), + setting_file.string() + ) + ); + write_gate_script(do_b_script, std::format("echo B-prep > \"{}\"\n", setting_file.string())); + + proc::ctx_t app_a {}; + app_a.name = "AppA"; + app_a.id = "7"; + app_a.cmd = "true"; + app_a.prep_cmds.emplace_back(do_a_script.string(), undo_a_script.string(), false); + proc::ctx_t app_b {}; + app_b.name = "AppB"; + app_b.id = "8"; + app_b.cmd = "sleep 30"; + app_b.prep_cmds.emplace_back(do_b_script.string(), std::string {}, false); + std::vector apps; + apps.push_back(std::move(app_a)); + apps.push_back(std::move(app_b)); + boost::process::v1::environment env = boost::this_process::environment(); + proc::proc_t target(std::move(env), std::move(apps)); + auto launch_session = std::make_shared(); + const auto terminate_target = util::fail_guard([&target]() { + target.terminate(); + }); + ASSERT_EQ(target.execute(7, launch_session), 0); + ASSERT_EQ(read_trimmed_gate_file(setting_file), "A-prep"); + + // Detect the natural exit via the identity getter only: any running() call + // here would claim the cleanup this test overlaps with B's launch. + bool exited = false; + for (int attempt = 0; attempt < 500 && !exited; ++attempt) { + if (target.app_process_id() == 0u) { + exited = true; + } else { + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + } + ASSERT_TRUE(exited) << "A did not exit naturally"; + + std::atomic cleanup_result {-999}; + std::jthread cleanup_thread {[&target, &cleanup_result]() { + cleanup_result.store(target.running()); + }}; + // Always release the gate so the background threads can finish even on failure. + auto release_gate = util::fail_guard([&gate_file]() { + std::ofstream {gate_file}; + }); + ASSERT_TRUE(wait_for_gate_file(undo_started_file)) << "cleanup undo did not start; cannot overlap B's launch"; + + std::atomic b_launch_done {false}; + std::atomic b_launch_result {-999}; + std::jthread b_thread {[&target, &launch_session, &b_launch_done, &b_launch_result]() { + const int result = target.execute(8, launch_session); + b_launch_result.store(result); + b_launch_done.store(true); + }}; + // Give B a chance to (incorrectly) run its prep while A's cleanup is still blocked. + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + EXPECT_FALSE(b_launch_done.load()) << "B's launch finished while A's cleanup was still blocked"; + EXPECT_EQ(read_trimmed_gate_file(setting_file), "A-prep") << "B's prep ran before A's undo finished"; + + // A second poll while the cleanup owns the gate answers promptly instead of + // blocking on it; the corpse is already claimed, so it reports 0. + auto poll = std::async(std::launch::async, [&target]() { + return target.running(); + }); + if (poll.wait_for(std::chrono::seconds(2)) != std::future_status::ready) { + // Release the gate before failing so the background threads, and the async + // poll waiting on them, can finish instead of hanging teardown. + std::ofstream {gate_file}; + release_gate.disable(); + FAIL() << "second running() blocked on the owned cleanup"; + } + EXPECT_EQ(poll.get(), 0); + + { + std::ofstream gate {gate_file}; + ASSERT_TRUE(static_cast(gate)) << "failed to release the undo gate"; + } + cleanup_thread.join(); + b_thread.join(); + release_gate.disable(); + EXPECT_EQ(cleanup_result.load(), 0); + EXPECT_EQ(b_launch_result.load(), 0); + EXPECT_EQ(read_trimmed_gate_file(setting_file), "B-prep") << "A's undo overwrote B's prep after B started"; + EXPECT_EQ(target.running(), 8); +} + +/** + * @brief Hammer running() across steady run, natural exit, and racing terminate. + * + * Poller threads report only {0, 7} while the main thread drives a natural + * exit and then a racing terminate; the test passing at all (cleanly, under + * ASan/TSan) pins the single-hold reaper/claim atomicity. Guard-only: it + * asserts no promptness or ordering, which the gated tests above pin. + */ +TEST(ProcessTest, RunningConcurrentPollsStayConsistentDuringExitAndTerminate) { + boost::process::v1::environment env = boost::this_process::environment(); + proc::ctx_t ctx {}; + ctx.name = "Sleeper"; + ctx.id = "7"; + ctx.cmd = "sleep 30"; + std::vector apps; + apps.push_back(std::move(ctx)); + proc::proc_t target(std::move(env), std::move(apps)); + auto launch_session = std::make_shared(); + const auto terminate_target = util::fail_guard([&target]() { + target.terminate(); + }); + + std::atomic saw_bad_id {false}; + const auto hammer = [&target, &saw_bad_id](std::stop_token stop_token) { + while (!stop_token.stop_requested()) { + const int id = target.running(); + if (id != 0 && id != 7) { + saw_bad_id.store(true); + } + (void) target.app_process_id(); + } + }; + + // Phase 1: steady run, then a natural exit raced with the pollers. + ASSERT_EQ(target.execute(7, launch_session), 0); + { + std::vector pollers; + for (int i = 0; i < 4; ++i) { + pollers.emplace_back(hammer); + } + const auto stop_pollers = util::fail_guard([&pollers]() { + for (auto &poller : pollers) { + poller.request_stop(); + } + }); + const auto pid = target.app_process_id(); + ASSERT_NE(pid, 0u); + ASSERT_EQ(::kill(static_cast(pid), SIGKILL), 0); + bool cleaned = false; + for (int attempt = 0; attempt < 500 && !cleaned; ++attempt) { + if (target.running() == 0) { + cleaned = true; + } else { + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + } + EXPECT_TRUE(cleaned) << "natural exit was never cleaned up under the hammer"; + } + + // Phase 2: steady run, then a racing terminate. + ASSERT_EQ(target.execute(7, launch_session), 0); + { + std::vector pollers; + for (int i = 0; i < 4; ++i) { + pollers.emplace_back(hammer); + } + const auto stop_pollers = util::fail_guard([&pollers]() { + for (auto &poller : pollers) { + poller.request_stop(); + } + }); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + target.terminate(); + EXPECT_EQ(target.running(), 0); + EXPECT_EQ(target.app_process_id(), 0u); + } + + EXPECT_FALSE(saw_bad_id.load()) << "poller observed an id outside {0, 7}"; +} + +/** + * @brief Verify terminate() during a gated launch waits, then drains once released. + * + * execute() holds the transition gate across the prep wait, so terminate() + * cannot interleave: it blocks until the gate releases, execute() reports 0, + * and terminate() then undoes the completed prep. The final state stays + * consistent: terminal reports are 0 and a successor launch works. + */ +TEST(ProcessTest, TerminateDuringLaunchDrainsAfterGateRelease) { + gate_dir_t dir {"b4-term-launch"}; + ASSERT_TRUE(fs::exists(dir.root)); + const auto setting_file = dir.root / "setting"; + const auto gate_file = dir.root / "gate"; + const auto started_file = dir.root / "started"; + const auto do_script = dir.root / "do.sh"; + const auto undo_script = dir.root / "undo.sh"; + write_gate_script( + do_script, + std::format( + "touch \"{}\"\nwhile [ ! -f \"{}\" ]; do sleep 0.01; done\necho L-prep > \"{}\"\n", + started_file.string(), + gate_file.string(), + setting_file.string() + ) + ); + write_gate_script(undo_script, std::format("echo L-undo > \"{}\"\n", setting_file.string())); + + proc::ctx_t ctx {}; + ctx.name = "Gated"; + ctx.id = "7"; + ctx.cmd = "sleep 30"; + ctx.prep_cmds.emplace_back(do_script.string(), undo_script.string(), false); + std::vector apps; + apps.push_back(std::move(ctx)); + boost::process::v1::environment env = boost::this_process::environment(); + proc::proc_t target(std::move(env), std::move(apps)); + auto launch_session = std::make_shared(); + const auto terminate_target = util::fail_guard([&target]() { + target.terminate(); + }); + + std::atomic exec_result {-999}; + std::jthread exec_thread {[&target, &launch_session, &exec_result]() { + exec_result.store(target.execute(7, launch_session)); + }}; + // Always release the gate so the background thread can finish even on failure. + auto release_gate = util::fail_guard([&gate_file]() { + std::ofstream {gate_file}; + }); + ASSERT_TRUE(wait_for_gate_file(started_file)) << "gated prep did not start; cannot overlap terminate()"; + + // Launch in flight: pollers fail closed with the new id while prep is gated. + EXPECT_EQ(target.running(), 7); + + // terminate() blocks on execute()'s transition until the releaser opens the gate. + std::jthread releaser {[&gate_file]() { + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + std::ofstream {gate_file}; + }}; + target.terminate(); + releaser.join(); + exec_thread.join(); + release_gate.disable(); + + EXPECT_EQ(exec_result.load(), 0); + EXPECT_EQ(target.running(), 0); + EXPECT_EQ(target.app_process_id(), 0u); + EXPECT_EQ(read_trimmed_gate_file(setting_file), "L-undo") << "terminate did not undo the completed prep"; + + // A successor launch works on the consistent state. + ASSERT_EQ(target.execute(7, launch_session), 0); + EXPECT_EQ(target.running(), 7); +} + +/** + * @brief Verify an OS-killed app is cleaned up by running(), with undo and successor intact. + * + * After SIGKILL, the death is detected via app_process_id() only, so the + * corpse stays unclaimed until the single running() call triggers the cleanup: + * the undo must not have run before it, and must have run after it. A + * successor launch then works. Pins the natural-death path distinctly from + * the terminate() path. + */ +TEST(ProcessTest, NaturalDeathCleansUpViaRunning) { + gate_dir_t dir {"b4-os-death"}; + ASSERT_TRUE(fs::exists(dir.root)); + const auto setting_file = dir.root / "setting"; + const auto do_script = dir.root / "do.sh"; + const auto undo_script = dir.root / "undo.sh"; + write_gate_script(do_script, std::format("echo A-prep > \"{}\"\n", setting_file.string())); + write_gate_script(undo_script, std::format("echo A-undo > \"{}\"\n", setting_file.string())); + + proc::ctx_t ctx {}; + ctx.name = "Sleeper"; + ctx.id = "7"; + ctx.cmd = "sleep 30"; + ctx.prep_cmds.emplace_back(do_script.string(), undo_script.string(), false); + std::vector apps; + apps.push_back(std::move(ctx)); + boost::process::v1::environment env = boost::this_process::environment(); + proc::proc_t target(std::move(env), std::move(apps)); + auto launch_session = std::make_shared(); + const auto terminate_target = util::fail_guard([&target]() { + target.terminate(); + }); + ASSERT_EQ(target.execute(7, launch_session), 0); + ASSERT_EQ(read_trimmed_gate_file(setting_file), "A-prep"); + const auto pid = target.app_process_id(); + ASSERT_NE(pid, 0u); + ASSERT_EQ(::kill(static_cast(pid), 0), 0); + ASSERT_EQ(::kill(static_cast(pid), SIGKILL), 0); + + bool dead = false; + for (int attempt = 0; attempt < 500 && !dead; ++attempt) { + if (target.app_process_id() == 0u) { + dead = true; + } else { + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + } + ASSERT_TRUE(dead) << "killed app was never observed dead"; + ASSERT_EQ(read_trimmed_gate_file(setting_file), "A-prep") << "undo ran before running() claimed the corpse"; + + EXPECT_EQ(target.running(), 0); + EXPECT_EQ(target.app_process_id(), 0u); + EXPECT_EQ(read_trimmed_gate_file(setting_file), "A-undo") << "running() cleanup did not run the undo"; + + // A successor launch works on the consistent state. + ASSERT_EQ(target.execute(7, launch_session), 0); + EXPECT_EQ(target.running(), 7); +} #endif TEST_F(ProcessUpdateTest, UpdateAppsAndEnv_PreservesRunningState) { From 2f69cd0a8c1584a35ffb5e0942b7fc402aafffc7 Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Tue, 17 Nov 2026 03:14:55 -0700 Subject: [PATCH 25/25] test: collapse duplicated gated-launch setups into a shared fixture The six gated lifecycle tests each hand-rolled the same $\sim0-line setup (scratch dir, marker scripts, app contexts, process manager, guards), which SonarCloud flags as 148 duplicated lines on PR #6123. Replace the six setups with gated_launch_t: one config list per test selects markers, gating, and commands, while the fixture owns the directory, scripts, apps, target, background-launch thread, deadline poll, and gate release. The Overlapping test additionally drops its bespoke tmp dir, script writer, and read/wait loops in favor of the existing gate helpers. Test bodies keep only their orchestration and assertions; all markers and gate behavior are unchanged. The hook audio control fake now derives from the recording fake instead of duplicating its 50 lines, keeping its two intentional differences documented. --- tests/unit/test_audio.cpp | 35 +- tests/unit/test_process.cpp | 649 ++++++++++++++++-------------------- 2 files changed, 292 insertions(+), 392 deletions(-) diff --git a/tests/unit/test_audio.cpp b/tests/unit/test_audio.cpp index a7bd040b709..63a1ca688cf 100644 --- a/tests/unit/test_audio.cpp +++ b/tests/unit/test_audio.cpp @@ -1252,18 +1252,15 @@ TEST(BaseRecordTest, MacOsLikeNoOpLeavesRecordUntouched) { * Models the Windows `on_capture_target_cleared()` override: the hook resets * the paired identity exactly when the shared record resets. */ -class hook_audio_control_t: public platf::audio_control_t { +class hook_audio_control_t: public recorded_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 &sink) override { - return record_keep_default_capture_sink(sink); + // Stays at the base default: these tests pin record/hook pairing, not capture support. + bool supports_process_capture() const override { + return false; } /** @@ -1282,30 +1279,6 @@ class hook_audio_control_t: public platf::audio_control_t { paired_identity = identity.process_id; } - /** - * @brief Release the shared base record when it still belongs to the caller. - * @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 { - clear_recorded_capture_target_if_matches(intent, 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 *, 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; - } - protected: /** * @brief Reset the paired fake identity when the shared record resets. diff --git a/tests/unit/test_process.cpp b/tests/unit/test_process.cpp index 0213f8e7936..1512fe67834 100644 --- a/tests/unit/test_process.cpp +++ b/tests/unit/test_process.cpp @@ -15,9 +15,13 @@ #include #include #include +#include #include +#include #include #include +#include +#include // lib includes #include @@ -866,6 +870,192 @@ namespace { } return content; } + + /** + * @brief Per-app setup for a gated-launch scenario. + */ + struct gated_app_config_t { + std::string name; ///< Application name. + std::string id; ///< Application id. + std::string cmd; ///< Command line to launch. + std::string do_marker; ///< Marker the do script writes to the setting file. + bool do_gated = false; ///< Do script signals start, then waits on the gate. + std::string undo_marker; ///< Marker the undo script writes; empty means no undo script. + bool undo_gated = false; ///< Undo script signals start, then waits on the gate. + }; + + /** + * @brief Owns the files, scripts, and process manager for one gated-launch test. + * + * The gated lifecycle tests share the same setup: a scratch directory, marker + * scripts, app contexts, and a process manager with a launch session. The + * fixture also carries the background-launch thread and releases the gate on + * destruction, so each test body keeps only its orchestration and assertions. + */ + struct gated_launch_t { + gate_dir_t dir; ///< Scratch root; created first, removed last. + fs::path setting_file; ///< Marker file the scripts write. + fs::path gate_file; ///< Gate file; creating it releases gated scripts. + fs::path signal_file; ///< Signal file gated scripts touch on entry. + std::shared_ptr session; ///< Session for execute(). + proc::proc_t target; ///< Process manager under test. + std::atomic exec_result {-999}; ///< Background execute() result. + std::jthread exec_thread; ///< Background execute() thread, joined explicitly. + + /** + * @brief Build the scenario: directories, scripts, apps, and process manager. + * + * @param tag Test-unique directory infix. + * @param configs One entry per app under test. + */ + gated_launch_t(const char *tag, std::vector configs); + + /** + * @brief Terminate the target and release the gate unless disarmed. + * + * Replaces the per-test terminate/release guards: firing here covers both + * normal completion and early assertion exits. + */ + ~gated_launch_t(); + + /** + * @brief Run execute() for one app on the background thread. + * + * @param id App id to launch; the result lands in exec_result. + */ + void launch_in_background(int id); + + /** + * @brief Poll running() with a deadline, releasing the gate on timeout. + * + * @return Poll result, or nullopt when the deadline expired. + */ + std::optional poll_running_or_release_gate(); + + /** + * @brief Create the gate file, reporting success for assertion. + * + * @return True when the file opened for writing. + */ + bool open_gate_file(); + + /** + * @brief Disarm the destructor's gate release after an explicit release. + */ + void disarm_gate_release(); + + private: + bool gate_armed_ = true; ///< Destructor releases the gate unless disarmed. + + /** + * @brief Build app contexts with prep commands wired to the scenario scripts. + * + * @param root Scratch root holding the scripts. + * @param configs One entry per app under test. + * @return App list for proc_t construction. + */ + static std::vector build_apps(const fs::path &root, const std::vector &configs); + + /** + * @brief Write each app's marker scripts. + * + * @param configs One entry per app under test. + */ + void write_scripts(const std::vector &configs); + + /** + * @brief Render one marker-script body. + * + * @param marker Marker written to the setting file. + * @param gated Signal start, then wait on the gate before writing. + * @return Script body after the shebang line. + */ + std::string marker_script_body(const std::string &marker, bool gated); + }; + + gated_launch_t::gated_launch_t(const char *tag, std::vector configs): + dir {tag}, + setting_file {dir.root / "setting"}, + gate_file {dir.root / "gate"}, + signal_file {dir.root / "started"}, + session {std::make_shared()}, + target {boost::this_process::environment(), build_apps(dir.root, configs)} { + write_scripts(configs); + } + + gated_launch_t::~gated_launch_t() { + target.terminate(); + if (gate_armed_) { + std::ofstream {gate_file}; + } + } + + void gated_launch_t::launch_in_background(int id) { + exec_thread = std::jthread {[this, id]() { + exec_result.store(target.execute(id, session)); + }}; + } + + std::optional gated_launch_t::poll_running_or_release_gate() { + auto poll = std::async(std::launch::async, [this]() { + return target.running(); + }); + if (poll.wait_for(std::chrono::seconds(2)) != std::future_status::ready) { + std::ofstream {gate_file}; + gate_armed_ = false; + return std::nullopt; + } + return poll.get(); + } + + bool gated_launch_t::open_gate_file() { + std::ofstream gate {gate_file}; + return static_cast(gate); + } + + void gated_launch_t::disarm_gate_release() { + gate_armed_ = false; + } + + std::vector gated_launch_t::build_apps(const fs::path &root, const std::vector &configs) { + std::vector apps; + for (const auto &config : configs) { + proc::ctx_t ctx {}; + ctx.name = config.name; + ctx.id = config.id; + ctx.cmd = config.cmd; + std::string undo_path; + if (!config.undo_marker.empty()) { + undo_path = (root / std::format("undo_{}.sh", config.id)).string(); + } + ctx.prep_cmds.emplace_back((root / std::format("do_{}.sh", config.id)).string(), std::move(undo_path), false); + apps.push_back(std::move(ctx)); + } + return apps; + } + + void gated_launch_t::write_scripts(const std::vector &configs) { + for (const auto &config : configs) { + write_gate_script(dir.root / std::format("do_{}.sh", config.id), marker_script_body(config.do_marker, config.do_gated)); + if (!config.undo_marker.empty()) { + write_gate_script(dir.root / std::format("undo_{}.sh", config.id), marker_script_body(config.undo_marker, config.undo_gated)); + } + } + } + + std::string gated_launch_t::marker_script_body(const std::string &marker, bool gated) { + if (!gated) { + return std::format("echo {} > \"{}\"\n", marker, setting_file.string()); + } + return std::format( + "touch \"{}\"\nwhile [ ! -f \"{}\" ]; do sleep 0.01; done\necho {} > \"{}\"\n", + signal_file.string(), + gate_file.string(), + marker, + setting_file.string() + ); + } + } // namespace /** @@ -913,96 +1103,32 @@ TEST(ProcessTest, RunningAfterRelaunchKeepsSuccessorAlive) { * catch this: it never overlaps cleanup with the next launch. */ TEST(ProcessTest, OverlappingLaunchWaitsForPriorCleanup) { - const auto tmp_root = fs::temp_directory_path() / std::format("sunshine-proc-overlap-{}", ::getpid()); - const auto setting_file = tmp_root / "setting"; - const auto gate_file = tmp_root / "gate"; - const auto undo_started_file = tmp_root / "undo_started"; - std::error_code fs_ec; - fs::remove_all(tmp_root, fs_ec); - fs::create_directories(tmp_root, fs_ec); - ASSERT_FALSE(fs_ec) << fs_ec.message(); - const auto remove_tmp = util::fail_guard([&tmp_root]() { - std::error_code ec; - fs::remove_all(tmp_root, ec); - }); + gated_launch_t launch {"overlap", { + {"AppA", "7", "sleep 30", "A-prep", false, "A-undo", true}, + {"AppB", "8", "sleep 30", "B-prep"}, + }}; + ASSERT_TRUE(fs::exists(launch.dir.root)); - // Prep commands run without a shell, so stage the file writes and the gate - // wait as executable scripts instead of `sh -c` one-liners with quotes. - const auto do_a_script = tmp_root / "do_a.sh"; - const auto undo_a_script = tmp_root / "undo_a.sh"; - const auto do_b_script = tmp_root / "do_b.sh"; - { - std::ofstream {do_a_script} << "#!/bin/sh\necho A-prep > \"" << setting_file.string() << "\"\n"; - std::ofstream {undo_a_script} << "#!/bin/sh\ntouch \"" << undo_started_file.string() << "\"\nwhile [ ! -f \"" << gate_file.string() - << "\" ]; do sleep 0.01; done\necho A-undo > \"" << setting_file.string() << "\"\n"; - std::ofstream {do_b_script} << "#!/bin/sh\necho B-prep > \"" << setting_file.string() << "\"\n"; - } - for (const auto &script : {do_a_script, undo_a_script, do_b_script}) { - std::error_code perm_ec; - fs::permissions(script, fs::perms::owner_exec | fs::perms::group_exec | fs::perms::others_exec, fs::perm_options::add, perm_ec); - ASSERT_FALSE(perm_ec) << perm_ec.message(); - } - proc::ctx_t app_a {}; - app_a.name = "AppA"; - app_a.id = "7"; - app_a.cmd = "sleep 30"; - app_a.prep_cmds.emplace_back(do_a_script.string(), undo_a_script.string(), false); - proc::ctx_t app_b {}; - app_b.name = "AppB"; - app_b.id = "8"; - app_b.cmd = "sleep 30"; - app_b.prep_cmds.emplace_back(do_b_script.string(), std::string {}, false); - std::vector apps; - apps.push_back(std::move(app_a)); - apps.push_back(std::move(app_b)); - boost::process::v1::environment env = boost::this_process::environment(); - proc::proc_t target(std::move(env), std::move(apps)); - auto launch_session = std::make_shared(); - const auto terminate_target = util::fail_guard([&target]() { - target.terminate(); - }); - - ASSERT_EQ(target.execute(7, launch_session), 0); - ASSERT_NE(target.app_process_id(), 0u); + ASSERT_EQ(launch.target.execute(7, launch.session), 0); + ASSERT_NE(launch.target.app_process_id(), 0u); - const auto read_setting = [&setting_file]() { - std::ifstream input {setting_file}; - std::string content((std::istreambuf_iterator(input)), std::istreambuf_iterator()); - while (!content.empty() && (content.back() == '\n' || content.back() == '\r')) { - content.pop_back(); - } - return content; - }; - ASSERT_EQ(read_setting(), "A-prep"); + ASSERT_EQ(read_trimmed_gate_file(launch.setting_file), "A-prep"); // Terminate A in the background: its undo signals start, then blocks on the gate. - std::jthread terminate_thread {[&target]() { - target.terminate(); + std::jthread terminate_thread {[&launch]() { + launch.target.terminate(); }}; - bool undo_started = false; - for (int attempt = 0; attempt < 500 && !undo_started; ++attempt) { - std::error_code ec; - if (fs::exists(undo_started_file, ec) && !ec) { - undo_started = true; - } else { - std::this_thread::sleep_for(std::chrono::milliseconds(10)); - } - } - // Always release the gate so the background threads can finish even on failure. - auto release_gate = util::fail_guard([&gate_file]() { - std::ofstream {gate_file}; - }); - ASSERT_TRUE(undo_started) << "A's undo did not start; cannot overlap B's launch"; + ASSERT_TRUE(wait_for_gate_file(launch.signal_file)) << "A's undo did not start; cannot overlap B's launch"; // Attempt B's launch while A's cleanup is blocked. The transition gate must hold it. std::atomic b_attempting {false}; std::atomic b_launch_done {false}; std::atomic b_launch_result {-999}; std::latch b_started {1}; - std::jthread b_thread {[&target, &launch_session, &b_attempting, &b_launch_done, &b_launch_result, &b_started]() { + std::jthread b_thread {[&launch, &b_attempting, &b_launch_done, &b_launch_result, &b_started]() { b_attempting.store(true); b_started.count_down(); - const int result = target.execute(8, launch_session); + const int result = launch.target.execute(8, launch.session); b_launch_result.store(result); b_launch_done.store(true); }}; @@ -1011,20 +1137,17 @@ TEST(ProcessTest, OverlappingLaunchWaitsForPriorCleanup) { // Give B a chance to (incorrectly) run its prep while A is still blocked. std::this_thread::sleep_for(std::chrono::milliseconds(500)); EXPECT_FALSE(b_launch_done.load()) << "B's launch finished while A's cleanup was still blocked"; - EXPECT_EQ(read_setting(), "A-prep") << "B's prep ran before A's undo finished"; + EXPECT_EQ(read_trimmed_gate_file(launch.setting_file), "A-prep") << "B's prep ran before A's undo finished"; // Release A's undo; both threads must then complete with B's setting intact. - { - std::ofstream gate {gate_file}; - ASSERT_TRUE(static_cast(gate)) << "failed to release the undo gate"; - } + ASSERT_TRUE(launch.open_gate_file()) << "failed to release the undo gate"; terminate_thread.join(); b_thread.join(); - release_gate.disable(); + launch.disarm_gate_release(); EXPECT_EQ(b_launch_result.load(), 0); - EXPECT_EQ(read_setting(), "B-prep") << "A's undo overwrote B's prep after B started"; - EXPECT_EQ(target.running(), 8); - EXPECT_NE(target.app_process_id(), 0u); + EXPECT_EQ(read_trimmed_gate_file(launch.setting_file), "B-prep") << "A's undo overwrote B's prep after B started"; + EXPECT_EQ(launch.target.running(), 8); + EXPECT_NE(launch.target.app_process_id(), 0u); } /** @@ -1089,67 +1212,21 @@ TEST(ProcessTest, RunningReapsExitedChildOnPlaceboPoll) { * the gate. Fails on the pre-fix blocking running(), which waits for release. */ TEST(ProcessTest, RunningReportsLaunchInFlightDuringGatedPrep) { - gate_dir_t dir {"t1-exec-gate"}; - ASSERT_TRUE(fs::exists(dir.root)); - const auto setting_file = dir.root / "setting"; - const auto gate_file = dir.root / "gate"; - const auto started_file = dir.root / "started"; - const auto do_script = dir.root / "do.sh"; - write_gate_script( - do_script, - std::format( - "touch \"{}\"\nwhile [ ! -f \"{}\" ]; do sleep 0.01; done\necho G-prep > \"{}\"\n", - started_file.string(), - gate_file.string(), - setting_file.string() - ) - ); - - proc::ctx_t ctx {}; - ctx.name = "Gated"; - ctx.id = "7"; - ctx.cmd = "sleep 30"; - ctx.prep_cmds.emplace_back(do_script.string(), std::string {}, false); - std::vector apps; - apps.push_back(std::move(ctx)); - boost::process::v1::environment env = boost::this_process::environment(); - proc::proc_t target(std::move(env), std::move(apps)); - auto launch_session = std::make_shared(); - const auto terminate_target = util::fail_guard([&target]() { - target.terminate(); - }); - - std::atomic exec_result {-999}; - std::jthread exec_thread {[&target, &launch_session, &exec_result]() { - exec_result.store(target.execute(7, launch_session)); - }}; - // Always release the gate so the background thread can finish even on failure. - auto release_gate = util::fail_guard([&gate_file]() { - std::ofstream {gate_file}; - }); - ASSERT_TRUE(wait_for_gate_file(started_file)) << "gated prep did not start; cannot overlap the poll"; - - auto poll = std::async(std::launch::async, [&target]() { - return target.running(); - }); - if (poll.wait_for(std::chrono::seconds(2)) != std::future_status::ready) { - // Release the gate before failing so the background thread, and the async - // poll waiting on it, can finish instead of hanging teardown. - std::ofstream {gate_file}; - release_gate.disable(); - FAIL() << "running() blocked on execute()'s prep wait"; - } - EXPECT_EQ(poll.get(), 7); - - { - std::ofstream gate {gate_file}; - ASSERT_TRUE(static_cast(gate)) << "failed to release the prep gate"; - } - exec_thread.join(); - release_gate.disable(); - EXPECT_EQ(exec_result.load(), 0); - EXPECT_EQ(read_trimmed_gate_file(setting_file), "G-prep"); - EXPECT_EQ(target.running(), 7); + gated_launch_t launch {"t1-exec-gate", {{"Gated", "7", "sleep 30", "G-prep", true}}}; + ASSERT_TRUE(fs::exists(launch.dir.root)); + + launch.launch_in_background(7); + ASSERT_TRUE(wait_for_gate_file(launch.signal_file)) << "gated prep did not start; cannot overlap the poll"; + + const auto poll_result = launch.poll_running_or_release_gate(); + ASSERT_TRUE(poll_result.has_value()) << "running() blocked on execute()'s prep wait"; + EXPECT_EQ(*poll_result, 7); + ASSERT_TRUE(launch.open_gate_file()) << "failed to release the prep gate"; + launch.exec_thread.join(); + launch.disarm_gate_release(); + EXPECT_EQ(launch.exec_result.load(), 0); + EXPECT_EQ(read_trimmed_gate_file(launch.setting_file), "G-prep"); + EXPECT_EQ(launch.target.running(), 7); } /** @@ -1161,70 +1238,25 @@ TEST(ProcessTest, RunningReportsLaunchInFlightDuringGatedPrep) { * running(), which waits for release. */ TEST(ProcessTest, RunningReportsZeroDuringGatedUndo) { - gate_dir_t dir {"t2-term-gate"}; - ASSERT_TRUE(fs::exists(dir.root)); - const auto setting_file = dir.root / "setting"; - const auto gate_file = dir.root / "gate"; - const auto undo_started_file = dir.root / "undo_started"; - const auto do_script = dir.root / "do.sh"; - const auto undo_script = dir.root / "undo.sh"; - write_gate_script(do_script, std::format("echo A-prep > \"{}\"\n", setting_file.string())); - write_gate_script( - undo_script, - std::format( - "touch \"{}\"\nwhile [ ! -f \"{}\" ]; do sleep 0.01; done\necho A-undo > \"{}\"\n", - undo_started_file.string(), - gate_file.string(), - setting_file.string() - ) - ); + gated_launch_t launch {"t2-term-gate", {{"Gated", "7", "sleep 30", "A-prep", false, "A-undo", true}}}; + ASSERT_TRUE(fs::exists(launch.dir.root)); + ASSERT_EQ(launch.target.execute(7, launch.session), 0); + ASSERT_EQ(read_trimmed_gate_file(launch.setting_file), "A-prep"); - proc::ctx_t ctx {}; - ctx.name = "Gated"; - ctx.id = "7"; - ctx.cmd = "sleep 30"; - ctx.prep_cmds.emplace_back(do_script.string(), undo_script.string(), false); - std::vector apps; - apps.push_back(std::move(ctx)); - boost::process::v1::environment env = boost::this_process::environment(); - proc::proc_t target(std::move(env), std::move(apps)); - auto launch_session = std::make_shared(); - const auto terminate_target = util::fail_guard([&target]() { - target.terminate(); - }); - ASSERT_EQ(target.execute(7, launch_session), 0); - ASSERT_EQ(read_trimmed_gate_file(setting_file), "A-prep"); - - std::jthread terminate_thread {[&target]() { - target.terminate(); + std::jthread terminate_thread {[&launch]() { + launch.target.terminate(); }}; - // Always release the gate so the background thread can finish even on failure. - auto release_gate = util::fail_guard([&gate_file]() { - std::ofstream {gate_file}; - }); - ASSERT_TRUE(wait_for_gate_file(undo_started_file)) << "gated undo did not start; cannot overlap the poll"; + ASSERT_TRUE(wait_for_gate_file(launch.signal_file)) << "gated undo did not start; cannot overlap the poll"; - auto poll = std::async(std::launch::async, [&target]() { - return target.running(); - }); - if (poll.wait_for(std::chrono::seconds(2)) != std::future_status::ready) { - // Release the gate before failing so the background thread, and the async - // poll waiting on it, can finish instead of hanging teardown. - std::ofstream {gate_file}; - release_gate.disable(); - FAIL() << "running() blocked on terminate()'s undo wait"; - } - EXPECT_EQ(poll.get(), 0); - - { - std::ofstream gate {gate_file}; - ASSERT_TRUE(static_cast(gate)) << "failed to release the undo gate"; - } + const auto poll_result = launch.poll_running_or_release_gate(); + ASSERT_TRUE(poll_result.has_value()) << "running() blocked on terminate()'s undo wait"; + EXPECT_EQ(*poll_result, 0); + ASSERT_TRUE(launch.open_gate_file()) << "failed to release the undo gate"; terminate_thread.join(); - release_gate.disable(); - EXPECT_EQ(target.running(), 0); - EXPECT_EQ(target.app_process_id(), 0u); - EXPECT_EQ(read_trimmed_gate_file(setting_file), "A-undo"); + launch.disarm_gate_release(); + EXPECT_EQ(launch.target.running(), 0); + EXPECT_EQ(launch.target.app_process_id(), 0u); + EXPECT_EQ(read_trimmed_gate_file(launch.setting_file), "A-undo"); } /** @@ -1241,53 +1273,19 @@ TEST(ProcessTest, RunningReportsZeroDuringGatedUndo) { * second poll stalls past the deadline. */ TEST(ProcessTest, RunningCleanupPreservesLaunchOrdering) { - gate_dir_t dir {"t3-cleanup-order"}; - ASSERT_TRUE(fs::exists(dir.root)); - const auto setting_file = dir.root / "setting"; - const auto gate_file = dir.root / "gate"; - const auto undo_started_file = dir.root / "undo_started"; - const auto do_a_script = dir.root / "do_a.sh"; - const auto undo_a_script = dir.root / "undo_a.sh"; - const auto do_b_script = dir.root / "do_b.sh"; - write_gate_script(do_a_script, std::format("echo A-prep > \"{}\"\n", setting_file.string())); - write_gate_script( - undo_a_script, - std::format( - "touch \"{}\"\nwhile [ ! -f \"{}\" ]; do sleep 0.01; done\necho A-undo > \"{}\"\n", - undo_started_file.string(), - gate_file.string(), - setting_file.string() - ) - ); - write_gate_script(do_b_script, std::format("echo B-prep > \"{}\"\n", setting_file.string())); - - proc::ctx_t app_a {}; - app_a.name = "AppA"; - app_a.id = "7"; - app_a.cmd = "true"; - app_a.prep_cmds.emplace_back(do_a_script.string(), undo_a_script.string(), false); - proc::ctx_t app_b {}; - app_b.name = "AppB"; - app_b.id = "8"; - app_b.cmd = "sleep 30"; - app_b.prep_cmds.emplace_back(do_b_script.string(), std::string {}, false); - std::vector apps; - apps.push_back(std::move(app_a)); - apps.push_back(std::move(app_b)); - boost::process::v1::environment env = boost::this_process::environment(); - proc::proc_t target(std::move(env), std::move(apps)); - auto launch_session = std::make_shared(); - const auto terminate_target = util::fail_guard([&target]() { - target.terminate(); - }); - ASSERT_EQ(target.execute(7, launch_session), 0); - ASSERT_EQ(read_trimmed_gate_file(setting_file), "A-prep"); + gated_launch_t launch {"t3-cleanup-order", { + {"AppA", "7", "true", "A-prep", false, "A-undo", true}, + {"AppB", "8", "sleep 30", "B-prep"}, + }}; + ASSERT_TRUE(fs::exists(launch.dir.root)); + ASSERT_EQ(launch.target.execute(7, launch.session), 0); + ASSERT_EQ(read_trimmed_gate_file(launch.setting_file), "A-prep"); // Detect the natural exit via the identity getter only: any running() call // here would claim the cleanup this test overlaps with B's launch. bool exited = false; for (int attempt = 0; attempt < 500 && !exited; ++attempt) { - if (target.app_process_id() == 0u) { + if (launch.target.app_process_id() == 0u) { exited = true; } else { std::this_thread::sleep_for(std::chrono::milliseconds(10)); @@ -1296,52 +1294,36 @@ TEST(ProcessTest, RunningCleanupPreservesLaunchOrdering) { ASSERT_TRUE(exited) << "A did not exit naturally"; std::atomic cleanup_result {-999}; - std::jthread cleanup_thread {[&target, &cleanup_result]() { - cleanup_result.store(target.running()); + std::jthread cleanup_thread {[&launch, &cleanup_result]() { + cleanup_result.store(launch.target.running()); }}; - // Always release the gate so the background threads can finish even on failure. - auto release_gate = util::fail_guard([&gate_file]() { - std::ofstream {gate_file}; - }); - ASSERT_TRUE(wait_for_gate_file(undo_started_file)) << "cleanup undo did not start; cannot overlap B's launch"; + ASSERT_TRUE(wait_for_gate_file(launch.signal_file)) << "cleanup undo did not start; cannot overlap B's launch"; std::atomic b_launch_done {false}; std::atomic b_launch_result {-999}; - std::jthread b_thread {[&target, &launch_session, &b_launch_done, &b_launch_result]() { - const int result = target.execute(8, launch_session); + std::jthread b_thread {[&launch, &b_launch_done, &b_launch_result]() { + const int result = launch.target.execute(8, launch.session); b_launch_result.store(result); b_launch_done.store(true); }}; // Give B a chance to (incorrectly) run its prep while A's cleanup is still blocked. std::this_thread::sleep_for(std::chrono::milliseconds(500)); EXPECT_FALSE(b_launch_done.load()) << "B's launch finished while A's cleanup was still blocked"; - EXPECT_EQ(read_trimmed_gate_file(setting_file), "A-prep") << "B's prep ran before A's undo finished"; + EXPECT_EQ(read_trimmed_gate_file(launch.setting_file), "A-prep") << "B's prep ran before A's undo finished"; // A second poll while the cleanup owns the gate answers promptly instead of // blocking on it; the corpse is already claimed, so it reports 0. - auto poll = std::async(std::launch::async, [&target]() { - return target.running(); - }); - if (poll.wait_for(std::chrono::seconds(2)) != std::future_status::ready) { - // Release the gate before failing so the background threads, and the async - // poll waiting on them, can finish instead of hanging teardown. - std::ofstream {gate_file}; - release_gate.disable(); - FAIL() << "second running() blocked on the owned cleanup"; - } - EXPECT_EQ(poll.get(), 0); - - { - std::ofstream gate {gate_file}; - ASSERT_TRUE(static_cast(gate)) << "failed to release the undo gate"; - } + const auto poll_result = launch.poll_running_or_release_gate(); + ASSERT_TRUE(poll_result.has_value()) << "second running() blocked on the owned cleanup"; + EXPECT_EQ(*poll_result, 0); + ASSERT_TRUE(launch.open_gate_file()) << "failed to release the undo gate"; cleanup_thread.join(); b_thread.join(); - release_gate.disable(); + launch.disarm_gate_release(); EXPECT_EQ(cleanup_result.load(), 0); EXPECT_EQ(b_launch_result.load(), 0); - EXPECT_EQ(read_trimmed_gate_file(setting_file), "B-prep") << "A's undo overwrote B's prep after B started"; - EXPECT_EQ(target.running(), 8); + EXPECT_EQ(read_trimmed_gate_file(launch.setting_file), "B-prep") << "A's undo overwrote B's prep after B started"; + EXPECT_EQ(launch.target.running(), 8); } /** @@ -1433,69 +1415,33 @@ TEST(ProcessTest, RunningConcurrentPollsStayConsistentDuringExitAndTerminate) { * consistent: terminal reports are 0 and a successor launch works. */ TEST(ProcessTest, TerminateDuringLaunchDrainsAfterGateRelease) { - gate_dir_t dir {"b4-term-launch"}; - ASSERT_TRUE(fs::exists(dir.root)); - const auto setting_file = dir.root / "setting"; - const auto gate_file = dir.root / "gate"; - const auto started_file = dir.root / "started"; - const auto do_script = dir.root / "do.sh"; - const auto undo_script = dir.root / "undo.sh"; - write_gate_script( - do_script, - std::format( - "touch \"{}\"\nwhile [ ! -f \"{}\" ]; do sleep 0.01; done\necho L-prep > \"{}\"\n", - started_file.string(), - gate_file.string(), - setting_file.string() - ) - ); - write_gate_script(undo_script, std::format("echo L-undo > \"{}\"\n", setting_file.string())); - - proc::ctx_t ctx {}; - ctx.name = "Gated"; - ctx.id = "7"; - ctx.cmd = "sleep 30"; - ctx.prep_cmds.emplace_back(do_script.string(), undo_script.string(), false); - std::vector apps; - apps.push_back(std::move(ctx)); - boost::process::v1::environment env = boost::this_process::environment(); - proc::proc_t target(std::move(env), std::move(apps)); - auto launch_session = std::make_shared(); - const auto terminate_target = util::fail_guard([&target]() { - target.terminate(); - }); + gated_launch_t launch {"b4-term-launch", {{"Gated", "7", "sleep 30", "L-prep", true, "L-undo", false}}}; + ASSERT_TRUE(fs::exists(launch.dir.root)); - std::atomic exec_result {-999}; - std::jthread exec_thread {[&target, &launch_session, &exec_result]() { - exec_result.store(target.execute(7, launch_session)); - }}; - // Always release the gate so the background thread can finish even on failure. - auto release_gate = util::fail_guard([&gate_file]() { - std::ofstream {gate_file}; - }); - ASSERT_TRUE(wait_for_gate_file(started_file)) << "gated prep did not start; cannot overlap terminate()"; + launch.launch_in_background(7); + ASSERT_TRUE(wait_for_gate_file(launch.signal_file)) << "gated prep did not start; cannot overlap terminate()"; // Launch in flight: pollers fail closed with the new id while prep is gated. - EXPECT_EQ(target.running(), 7); + EXPECT_EQ(launch.target.running(), 7); // terminate() blocks on execute()'s transition until the releaser opens the gate. - std::jthread releaser {[&gate_file]() { + std::jthread releaser {[&launch]() { std::this_thread::sleep_for(std::chrono::milliseconds(300)); - std::ofstream {gate_file}; + std::ofstream {launch.gate_file}; }}; - target.terminate(); + launch.target.terminate(); releaser.join(); - exec_thread.join(); - release_gate.disable(); + launch.exec_thread.join(); + launch.disarm_gate_release(); - EXPECT_EQ(exec_result.load(), 0); - EXPECT_EQ(target.running(), 0); - EXPECT_EQ(target.app_process_id(), 0u); - EXPECT_EQ(read_trimmed_gate_file(setting_file), "L-undo") << "terminate did not undo the completed prep"; + EXPECT_EQ(launch.exec_result.load(), 0); + EXPECT_EQ(launch.target.running(), 0); + EXPECT_EQ(launch.target.app_process_id(), 0u); + EXPECT_EQ(read_trimmed_gate_file(launch.setting_file), "L-undo") << "terminate did not undo the completed prep"; // A successor launch works on the consistent state. - ASSERT_EQ(target.execute(7, launch_session), 0); - EXPECT_EQ(target.running(), 7); + ASSERT_EQ(launch.target.execute(7, launch.session), 0); + EXPECT_EQ(launch.target.running(), 7); } /** @@ -1508,52 +1454,33 @@ TEST(ProcessTest, TerminateDuringLaunchDrainsAfterGateRelease) { * the terminate() path. */ TEST(ProcessTest, NaturalDeathCleansUpViaRunning) { - gate_dir_t dir {"b4-os-death"}; - ASSERT_TRUE(fs::exists(dir.root)); - const auto setting_file = dir.root / "setting"; - const auto do_script = dir.root / "do.sh"; - const auto undo_script = dir.root / "undo.sh"; - write_gate_script(do_script, std::format("echo A-prep > \"{}\"\n", setting_file.string())); - write_gate_script(undo_script, std::format("echo A-undo > \"{}\"\n", setting_file.string())); - - proc::ctx_t ctx {}; - ctx.name = "Sleeper"; - ctx.id = "7"; - ctx.cmd = "sleep 30"; - ctx.prep_cmds.emplace_back(do_script.string(), undo_script.string(), false); - std::vector apps; - apps.push_back(std::move(ctx)); - boost::process::v1::environment env = boost::this_process::environment(); - proc::proc_t target(std::move(env), std::move(apps)); - auto launch_session = std::make_shared(); - const auto terminate_target = util::fail_guard([&target]() { - target.terminate(); - }); - ASSERT_EQ(target.execute(7, launch_session), 0); - ASSERT_EQ(read_trimmed_gate_file(setting_file), "A-prep"); - const auto pid = target.app_process_id(); + gated_launch_t launch {"b4-os-death", {{"Sleeper", "7", "sleep 30", "A-prep", false, "A-undo", false}}}; + ASSERT_TRUE(fs::exists(launch.dir.root)); + ASSERT_EQ(launch.target.execute(7, launch.session), 0); + ASSERT_EQ(read_trimmed_gate_file(launch.setting_file), "A-prep"); + const auto pid = launch.target.app_process_id(); ASSERT_NE(pid, 0u); ASSERT_EQ(::kill(static_cast(pid), 0), 0); ASSERT_EQ(::kill(static_cast(pid), SIGKILL), 0); bool dead = false; for (int attempt = 0; attempt < 500 && !dead; ++attempt) { - if (target.app_process_id() == 0u) { + if (launch.target.app_process_id() == 0u) { dead = true; } else { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } ASSERT_TRUE(dead) << "killed app was never observed dead"; - ASSERT_EQ(read_trimmed_gate_file(setting_file), "A-prep") << "undo ran before running() claimed the corpse"; + ASSERT_EQ(read_trimmed_gate_file(launch.setting_file), "A-prep") << "undo ran before running() claimed the corpse"; - EXPECT_EQ(target.running(), 0); - EXPECT_EQ(target.app_process_id(), 0u); - EXPECT_EQ(read_trimmed_gate_file(setting_file), "A-undo") << "running() cleanup did not run the undo"; + EXPECT_EQ(launch.target.running(), 0); + EXPECT_EQ(launch.target.app_process_id(), 0u); + EXPECT_EQ(read_trimmed_gate_file(launch.setting_file), "A-undo") << "running() cleanup did not run the undo"; // A successor launch works on the consistent state. - ASSERT_EQ(target.execute(7, launch_session), 0); - EXPECT_EQ(target.running(), 7); + ASSERT_EQ(launch.target.execute(7, launch.session), 0); + EXPECT_EQ(launch.target.running(), 7); } #endif