From 2ffc3ae840f3d94ce30d86d8f267a8d7c2884c97 Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Wed, 7 Oct 2026 17:25:28 -0700 Subject: [PATCH 01/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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 9e4c5a81ef2d0aa2d3de1fb712120f75daaa1e54 Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Mon, 16 Nov 2026 23:00:41 -0700 Subject: [PATCH 23/28] feat(windows/audio): capture launched process tree with WASAPI loopback --- docs/configuration.md | 5 +- src/audio.cpp | 72 +- src/audio.h | 57 +- src/platform/windows/audio.cpp | 1884 +++++++++++++++++++- src/platform/windows/audio_tests.h | 59 + src/stream.cpp | 2 +- tests/unit/platform/windows/test_audio.cpp | 508 +++++- tests/unit/test_audio.cpp | 170 +- 8 files changed, 2610 insertions(+), 147 deletions(-) create mode 100644 src/platform/windows/audio_tests.h diff --git a/docs/configuration.md b/docs/configuration.md index 7be293aff7d..20bc33fbefc 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -963,7 +963,10 @@ consent prompt for directory ACLs, so the Web UI shows setup steps for correctin @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.
+ Steam driver install, the startup default-device reset, and default reinstallation. When no + audio_sink is configured and Sunshine launched the application, Windows may instead + capture the launched process tree with WASAPI process loopback, so other applications stay out of + the stream; endpoint capture remains the fallback.
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 diff --git a/src/audio.cpp b/src/audio.cpp index dc381bf0d03..256485a0b0b 100644 --- a/src/audio.cpp +++ b/src/audio.cpp @@ -38,10 +38,11 @@ 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 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. + * session_capture_target_t guard holds this mutex across the refresh, + * the post-creation re-check, and the exit clear, but never across + * microphone creation itself, which can wait on endpoint activation; + * the re-check keeps one session from keeping a microphone created + * after another session replaced the shared target. * * Lock order: this outer mutex is always taken before the backend-internal * `platf::audio_control_t::capture_state_mutex_`, acquired inside @@ -207,24 +208,50 @@ namespace audio { return; } std::lock_guard lock {*mutex_}; - control_->clear_capture_target(intent_, 0); + control_->clear_capture_target(intent_, process_id_); } /** - * @brief Refresh the endpoint capture target, then create the microphone for it. + * @brief Refresh the 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. 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::unique_ptr session_capture_target_t::create_microphone( + bool process_capture_supported, + const std::function &capture_process_identity_provider, + const platf::microphone_params_t &mic_params + ) { + // Refresh the capture target before every microphone creation so a + // process that appears or exits between reinitializations is reflected. + // Only the refresh runs under the lock: microphone creation can wait + // seconds 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. After creation the recorded target is re-checked + // under the lock; a microphone created while another session replaced + // the target is discarded and creation retries once with a fresh + // refresh, preserving the original refresh/microphone pairing. + for (int attempt = 0; attempt < 2; ++attempt) { + const auto identity = capture_process_identity_provider ? capture_process_identity_provider() : platf::process_identity_t {}; + // Gate the whole bundle, not just the PID: the handed-off creation + // marker is the backend's revalidation baseline, and a marker paired + // with a zeroed PID would name no process at all. + const auto effective_identity = should_capture_process_tree(intent_, process_capture_supported, identity.process_id) ? identity : platf::process_identity_t {}; + { + std::lock_guard lock {*mutex_}; + process_id_ = effective_identity.process_id; + control_->set_capture_target(intent_, effective_identity); + recorded_ = true; + } + auto mic = control_->microphone(mic_params); + if (!process_capture_supported) { + return mic; + } std::lock_guard lock {*mutex_}; - control_->set_capture_target(intent_, platf::process_identity_t {0, 0}); - recorded_ = true; + if (control_->snapshot_capture_target_record().matches(intent_, process_id_)) { + return mic; + } + BOOST_LOG(info) << "Capture target changed during microphone creation; discarding and retrying"sv; } - return control_->microphone(mic_params); + return nullptr; } /** @@ -235,9 +262,10 @@ namespace audio { * 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. + * releases the shared target only when it still holds this session's intent + * and PID. */ - void capture(safe::mail_t mail, config_t config, stream::session_t *channel_data) { + void capture(safe::mail_t mail, config_t config, stream::session_t *channel_data, std::function capture_process_identity_provider) { auto shutdown_event = mail->event(mail::shutdown); if (!config::audio.stream) { shutdown_event->view(); @@ -267,6 +295,7 @@ namespace audio { } const auto capture_intent = resolve_audio_capture_intent(config::audio.keep_default_sink, config::audio.sink); + const auto process_capture_supported = control->supports_process_capture(); // One RAII owner for the session's shared capture target. Destruction // releases exactly the last recorded target, or nothing when no refresh @@ -293,7 +322,8 @@ namespace audio { << "], 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) << ']'; + << "], capture intent ["sv << audio_capture_intent_name(capture_intent) + << "], process capture supported ["sv << process_capture_supported << ']'; // If the selected sink cannot be selected, there is no audio to capture. if (!select_audio_capture_sink(*control, routing)) { return; @@ -311,7 +341,7 @@ namespace audio { continuous_audio, host_audio }; - auto mic = capture_target.create_microphone(mic_params); + auto mic = capture_target.create_microphone(process_capture_supported, capture_process_identity_provider, mic_params); if (!mic) { return; } @@ -348,7 +378,7 @@ namespace audio { BOOST_LOG(info) << "Reinitializing audio capture"sv; mic.reset(); do { - mic = capture_target.create_microphone(mic_params); + mic = capture_target.create_microphone(process_capture_supported, capture_process_identity_provider, 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 f8a41b1f899..1a9a279426b 100644 --- a/src/audio.h +++ b/src/audio.h @@ -246,6 +246,24 @@ namespace audio { return "unknown"; } + /** + * @brief Whether the launched process tree should be captured directly. + * + * Silence takes priority for client-only intent: per-process capture is + * only selected for host-and-client intent, where capturing the game + * process must not defeat a silent route. A pinned sink always wins, + * because a configured sink resolves to pinned intent. + * + * @param intent User-level capture intent. + * @param process_capture_supported Whether the backend captures a process tree. + * @param process_id Launched application PID, or 0 when unavailable. + * @return True when the backend should capture the process tree. + */ + [[nodiscard]] constexpr bool should_capture_process_tree(platf::audio_capture_intent_e intent, bool process_capture_supported, std::uint32_t process_id) noexcept { + using enum platf::audio_capture_intent_e; + return intent == host_and_client && process_capture_supported && process_id != 0; + } + /** * @brief Select the capture sink for startup without touching the capture target. * @@ -264,12 +282,12 @@ 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()) 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. + * the 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. */ @@ -293,18 +311,25 @@ namespace audio { session_capture_target_t &operator=(const session_capture_target_t &) = delete; /** - * @brief Refresh the endpoint capture target, then create the microphone for it. + * @brief Refresh the 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 covers - * only the refresh, never microphone creation itself. The endpoint form - * always records PID 0: per-process capture is not selected here. + * only the refresh and the post-creation re-check, never microphone + * creation itself; when the recorded target changed during creation the + * microphone is discarded and creation retries once. * + * @param process_capture_supported Whether the backend captures a process tree. + * @param capture_process_identity_provider Optional callable returning the launched application identity ({0, 0} for endpoint capture). * @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); + [[nodiscard]] std::unique_ptr create_microphone( + bool process_capture_supported, + const std::function &capture_process_identity_provider, + const platf::microphone_params_t &mic_params + ); /** * @brief Get the capture intent owned by this session. @@ -314,6 +339,14 @@ namespace audio { return intent_; } + /** + * @brief Get the PID from the last refresh, or 0 when no refresh ran. + * @return Effective PID recorded via set_capture_target(). + */ + [[nodiscard]] std::uint32_t process_id() const noexcept { + return process_id_; + } + /** * @brief Check whether this session recorded a target that teardown will release. * @return True after the first create_microphone() call. @@ -326,6 +359,7 @@ namespace audio { 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_; ///< Non-owning mutex serializing refresh, creation, and release; typically audio::capture_target_mutex(). + std::uint32_t process_id_ = 0; ///< PID from the last refresh, or 0 for endpoint capture. bool recorded_ = false; ///< Whether this session called set_capture_target(). }; @@ -348,8 +382,9 @@ namespace audio { * @param mail Mailbox used to publish encoded audio packets. * @param config Audio capture and encoder settings. * @param channel_data Stream session that receives the encoded packets. + * @param capture_process_identity_provider Optional callable returning the launched application identity ({0, 0} for endpoint capture). */ - void capture(safe::mail_t mail, config_t config, stream::session_t *channel_data); + void capture(safe::mail_t mail, config_t config, stream::session_t *channel_data, std::function capture_process_identity_provider = {}); /** * @brief Get the reference to the audio context. diff --git a/src/platform/windows/audio.cpp b/src/platform/windows/audio.cpp index cefe4928941..b93bcee1884 100644 --- a/src/platform/windows/audio.cpp +++ b/src/platform/windows/audio.cpp @@ -6,25 +6,41 @@ // standard includes #include +#include +#include +#include #include #include +#include +#include +#include #include +#include #include #include +#include // platform includes #include #include #include #include +#include #include #include +#if __has_include() + #include + #define SUNSHINE_HAS_AUDIOCLIENT_ACTIVATION_PARAMS 1 +#endif // local includes #include "src/config.h" #include "src/logging.h" #include "src/platform/common.h" #include "utf_utils.h" +#ifdef SUNSHINE_TESTS + #include "audio_tests.h" +#endif // Must be the last included file // clang-format off @@ -350,69 +366,574 @@ namespace platf::audio { }; /** - * @brief Create audio client. + * @brief Whether per-process loopback capture should be attempted. * - * @param device D3D, audio, or platform device used by the operation. - * @param format Pixel, audio, or protocol format being converted. - * @return Constructed audio client object. + * The configured-sink pin needs no separate check here: the shared guard + * maps a non-empty sink to pinned_sink intent and records PID 0 for every + * non-host-and-client case, so a nonzero PID with host-and-client intent + * already implies no pin. See audio::should_capture_process_tree(). + * + * @param process_id Revalidated application PID, or 0 for endpoint capture. + * @param intent Capture intent recorded for the next microphone() call. + * @return True only for host-and-client intent with a known PID. */ - audio_client_t make_audio_client(device_t &device, const format_t &format) { - audio_client_t audio_client; - auto status = device->Activate( - IID_IAudioClient, - CLSCTX_ALL, - nullptr, - (void **) &audio_client - ); + [[nodiscard]] constexpr bool use_process_loopback(std::uint32_t process_id, audio_capture_intent_e intent) noexcept { + using enum audio_capture_intent_e; + return intent == host_and_client && process_id != 0; + } - if (FAILED(status)) { - BOOST_LOG(error) << "Couldn't activate Device: [0x"sv << util::hex(status).to_string_view() << ']'; + // Process identities use the shared platf::process_identity_t: the PID and + // creation marker arrive as one handed-off bundle from the owned child + // handle, so this backend stores the baseline verbatim instead of querying + // it by PID (see platf::process_identity_t). - return nullptr; + /** + * @brief Whether a current process identity is the recorded capture target. + * + * This is the pure comparison seam for PID-reuse hardening: it performs no + * OS calls, so tests can exercise it with synthetic identities. + * + * @param recorded Identity recorded when the capture target was set. + * @param current Identity queried immediately before activation. + * @return True only when both identities name the same nonzero PID with the same nonzero creation time. + */ + [[nodiscard]] constexpr bool process_identity_matches(const process_identity_t &recorded, const process_identity_t ¤t) noexcept { + return recorded.process_id != 0 && current.process_id == recorded.process_id && recorded.creation_time != 0 && current.creation_time == recorded.creation_time; + } + + /** + * @brief Whether the recorded capture target still refers to a live process. + * + * @param recorded Identity recorded when the capture target was set. + * @param current Identity queried immediately before activation, or empty when the process exited or could not be opened. + * @return True only when a current identity is available and matches the recorded identity. + */ + [[nodiscard]] constexpr bool capture_target_is_live(const process_identity_t &recorded, const std::optional ¤t) noexcept { + return current.has_value() && process_identity_matches(recorded, *current); + } + + /** + * @brief Resolve the PID that may be used for process-loopback activation. + * + * @param recorded Identity recorded when the capture target was set. + * @param current Identity queried immediately before activation, or empty when the process exited or could not be opened. + * @return The recorded PID when the target is still the same live process, or 0 to select endpoint capture. + */ + [[nodiscard]] constexpr std::uint32_t effective_capture_process_id(const process_identity_t &recorded, const std::optional ¤t) noexcept { + return capture_target_is_live(recorded, current) ? recorded.process_id : 0; + } + + /** + * @brief Whether an activated process-loopback client still captures the validated target. + * + * The PID is revalidated immediately after activation because it may have + * exited or been reused while ActivateAudioInterfaceAsync was resolving it. + * This is the pure discard-decision seam: it performs no OS calls, so tests + * can exercise it with synthetic PID pairs. + * + * @param activated_process_id PID the completed activation was started for. + * @param revalidated_process_id PID revalidation still accepts, or 0 when the target exited or was reused. + * @return True only when revalidation still accepts the activated PID. + */ + [[nodiscard]] constexpr bool activated_process_target_is_current(std::uint32_t activated_process_id, std::uint32_t revalidated_process_id) noexcept { + return activated_process_id != 0 && revalidated_process_id == activated_process_id; + } + + /** + * @brief Query the current identity of a process. + * + * The process handle is held only for the duration of this call. Failure to + * open the process (including access denied), failure to read its times, or + * a process that has already exited all fail closed by returning no identity. + * + * @param process_id Operating-system PID to query, or 0 for no process. + * @return Current process identity, or empty when it cannot be verified as live. + */ + std::optional query_process_identity(std::uint32_t process_id) { + if (process_id == 0) { + return std::nullopt; + } + handle_t process; + process.reset(OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, process_id)); + if (!process) { + const auto last_error = GetLastError(); + BOOST_LOG(debug) << "Cannot open process ["sv << process_id << "] to verify its capture identity: [0x"sv << util::hex(last_error).to_string_view() << ']'; + return std::nullopt; + } + DWORD exit_code {}; + if (!GetExitCodeProcess(process.get(), &exit_code) || exit_code != STILL_ACTIVE) { + BOOST_LOG(debug) << "Process ["sv << process_id << "] is no longer running; it will not be used for process loopback capture"sv; + return std::nullopt; + } + FILETIME creation_time {}; + FILETIME exit_time {}; + FILETIME kernel_time {}; + FILETIME user_time {}; + if (!GetProcessTimes(process.get(), &creation_time, &exit_time, &kernel_time, &user_time)) { + const auto last_error = GetLastError(); + BOOST_LOG(debug) << "Cannot read creation time for process ["sv << process_id << "]: [0x"sv << util::hex(last_error).to_string_view() << ']'; + return std::nullopt; + } + const auto combined_creation_time = (static_cast(creation_time.dwHighDateTime) << 32) | static_cast(creation_time.dwLowDateTime); + if (combined_creation_time == 0) { + return std::nullopt; + } + return process_identity_t {process_id, combined_creation_time}; + } + + /** + * @brief Activator that creates and initializes a process-loopback audio client. + */ + using process_loopback_activator_t = std::function; + + /** + * @brief Activation step that returns an activated, not yet initialized, process-loopback audio client for a PID. + * + * This is the injectable seam around `activate_process_loopback_audio_client()`: production passes the real + * WASAPI activation, while tests pass a fake so the wrapper in `make_process_loopback_audio_client()` can be + * exercised without audio hardware. + */ + using process_loopback_activation_t = std::function; + + constexpr DWORD process_loopback_activation_timeout_ms {10000}; ///< Deadline for asynchronous process-loopback activation. + +#ifdef SUNSHINE_HAS_AUDIOCLIENT_ACTIVATION_PARAMS + /** + * @brief Build activation parameters for process-loopback capture. + * + * @param process_id Launched application PID to capture. + * @return Activation parameters including the target process tree. + */ + [[nodiscard]] AUDIOCLIENT_ACTIVATION_PARAMS make_process_loopback_activation_params(std::uint32_t process_id) noexcept { + AUDIOCLIENT_ACTIVATION_PARAMS params {}; + params.ActivationType = AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK; + params.ProcessLoopbackParams.TargetProcessId = process_id; + params.ProcessLoopbackParams.ProcessLoopbackMode = PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE; + return params; + } + + /** + * @brief Fill a PROPVARIANT with a heap-owned copy of loopback activation parameters. + * + * ActivateAudioInterfaceAsync reads the VT_BLOB payload asynchronously, so + * the bytes must outlive the call. The copy is heap-allocated with + * CoTaskMemAlloc, which makes PropVariantClear() always safe: it frees the + * heap copy and can never free a stack address. + * + * @param prop PROPVARIANT to fill; it must be PropVariantInit'd and empty. + * @param params Activation parameters to copy into the heap blob. + * @return S_OK when the blob was installed, E_OUTOFMEMORY when the copy cannot be allocated. + */ + HRESULT init_process_loopback_activation_blob(PROPVARIANT &prop, const AUDIOCLIENT_ACTIVATION_PARAMS ¶ms) { + prop.vt = VT_BLOB; + prop.blob.cbSize = sizeof(params); + prop.blob.pBlobData = static_cast(CoTaskMemAlloc(sizeof(params))); + if (!prop.blob.pBlobData) { + prop.vt = VT_EMPTY; + prop.blob.cbSize = 0; + return E_OUTOFMEMORY; } + std::memcpy(prop.blob.pBlobData, ¶ms, sizeof(params)); + return S_OK; + } +#endif + + /** + * @brief How initialize_audio_client() reacts when GetMixFormat fails. + */ + enum class mix_format_failure_e { + fail, ///< Return no client. + tolerate, ///< Keep the created format and continue. + }; + /** + * @brief Initialize an activated audio client for shared loopback capture. + * + * @param audio_client Activated WASAPI audio client. + * @param format Requested capture format. + * @param mix_format_failure Whether GetMixFormat failure keeps the created format. + * @return Initialized audio client, or nullptr on failure. + */ + audio_client_t initialize_audio_client(audio_client_t audio_client, const format_t &format, mix_format_failure_e mix_format_failure) { + using enum mix_format_failure_e; + if (!audio_client) { + return nullptr; + } WAVEFORMATEXTENSIBLE capture_waveformat = create_waveformat(sample_format_e::f32, format.channel_count, format.capture_waveformat_channel_mask); - { wave_format_t mixer_waveformat; - status = audio_client->GetMixFormat(&mixer_waveformat); + auto status = audio_client->GetMixFormat(&mixer_waveformat); if (FAILED(status)) { - BOOST_LOG(error) << "Couldn't get mix format for audio device: [0x"sv << util::hex(status).to_string_view() << ']'; - return nullptr; - } - - // Prefer the native channel layout of captured audio device when channel counts match - if (mixer_waveformat->nChannels == format.channel_count && mixer_waveformat->wFormatTag == WAVE_FORMAT_EXTENSIBLE && mixer_waveformat->cbSize >= 22) { - auto waveformatext_pointer = reinterpret_cast(mixer_waveformat.get()); - capture_waveformat.dwChannelMask = waveformatext_pointer->dwChannelMask; + if (mix_format_failure == fail) { + BOOST_LOG(error) << "Couldn't get mix format for audio device: [0x"sv << util::hex(status).to_string_view() << ']'; + return nullptr; + } + BOOST_LOG(warning) << "Couldn't get mix format for process loopback client: [0x"sv << util::hex(status).to_string_view() << ']'; + } else { + if (mixer_waveformat->nChannels == format.channel_count && mixer_waveformat->wFormatTag == WAVE_FORMAT_EXTENSIBLE && mixer_waveformat->cbSize >= 22) { + auto waveformatext_pointer = reinterpret_cast(mixer_waveformat.get()); + capture_waveformat.dwChannelMask = waveformatext_pointer->dwChannelMask; + } + BOOST_LOG(info) << "Audio mixer format is "sv << mixer_waveformat->wBitsPerSample << "-bit, "sv + << mixer_waveformat->nSamplesPerSec << " Hz, "sv + << ((mixer_waveformat->nSamplesPerSec != 48000) ? "will be resampled to 48000 by Windows"sv : "no resampling needed"sv); } - - BOOST_LOG(info) << "Audio mixer format is "sv << mixer_waveformat->wBitsPerSample << "-bit, "sv - << mixer_waveformat->nSamplesPerSec << " Hz, "sv - << ((mixer_waveformat->nSamplesPerSec != 48000) ? "will be resampled to 48000 by Windows"sv : "no resampling needed"sv); } - - status = audio_client->Initialize( + auto status = audio_client->Initialize( AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_LOOPBACK | AUDCLNT_STREAMFLAGS_EVENTCALLBACK | - AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY, // Enable automatic resampling to 48 KHz + AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY, 0, 0, (LPWAVEFORMATEX) &capture_waveformat, nullptr ); - if (status) { BOOST_LOG(error) << "Couldn't initialize audio client for ["sv << format.name << "]: [0x"sv << util::hex(status).to_string_view() << ']'; return nullptr; } - BOOST_LOG(info) << "Audio capture format is "sv << logging::bracket(waveformat_to_pretty_string(capture_waveformat)); - return audio_client; } +#if defined(SUNSHINE_HAS_AUDIOCLIENT_ACTIVATION_PARAMS) && defined(VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK) + /** + * @brief Completion handler for asynchronous WASAPI process-loopback activation. + * + * The callback fills in the result fields and then signals the completion event. + * The waiter reads the fields only after a signaled wait; on timeout it must not + * touch them at all, because the callback may still be running or arrive later. + * A signaled wait also makes the callback's writes visible to the waiter: the + * wait/signal functions act as memory barriers. + * https://learn.microsoft.com/en-us/windows/win32/sync/synchronization-and-multiprocessor-issues + */ + class process_loopback_completion_handler_t final: public IActivateAudioInterfaceCompletionHandler, public IAgileObject { + public: + /** + * @brief Construct the handler and its completion event. + */ + process_loopback_completion_handler_t() { + event_handle = CreateEventA(nullptr, TRUE, FALSE, nullptr); + } + + /** + * @brief Destroy the handler and close its completion event. + */ + ~process_loopback_completion_handler_t() { + if (event_handle) { + CloseHandle(event_handle); + } + } + + /** + * @brief Query a supported COM interface. + * @param riid Requested interface identifier. + * @param ppvInterface Receives the interface pointer. + * @return S_OK when supported, E_NOINTERFACE otherwise. + */ + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, VOID **ppvInterface) override { // NOSONAR(cpp:S5008): IUnknown::QueryInterface requires a void double pointer in the COM ABI. + if (!ppvInterface) { + return E_POINTER; + } + if (riid == IID_IUnknown || riid == __uuidof(IActivateAudioInterfaceCompletionHandler)) { + *ppvInterface = static_cast(this); + } else if (riid == __uuidof(IAgileObject)) { + *ppvInterface = static_cast(this); + } else { + *ppvInterface = nullptr; + return E_NOINTERFACE; + } + AddRef(); + return S_OK; + } + + /** + * @brief Increment the reference count. + * @return New reference count. + */ + ULONG STDMETHODCALLTYPE AddRef() override { + return ++ref_count; + } + + /** + * @brief Decrement the reference count, deleting when it reaches zero. + * @return New reference count. + */ + ULONG STDMETHODCALLTYPE Release() override { + auto count = --ref_count; + if (count == 0) { + delete this; + } + return count; + } + + /** + * @brief Record asynchronous activation completion and signal the waiter. + * @param activate_operation Completed activation operation. + * @return S_OK after recording the result. + */ + HRESULT STDMETHODCALLTYPE ActivateCompleted(IActivateAudioInterfaceAsyncOperation *activate_operation) override { + if (!activate_operation) { + activate_result = E_POINTER; + activation_hresult = E_POINTER; + query_interface_result = E_POINTER; + if (event_handle) { + SetEvent(event_handle); + } + return S_OK; + } + IUnknown *unknown = nullptr; + activate_result = activate_operation->GetActivateResult(&activation_hresult, &unknown); + if (SUCCEEDED(activate_result) && SUCCEEDED(activation_hresult) && unknown) { + IAudioClient *raw_client = nullptr; + query_interface_result = unknown->QueryInterface(IID_IAudioClient, (void **) &raw_client); // NOSONAR(cpp:S5008): IUnknown::QueryInterface requires a void double pointer in the COM ABI. + if (SUCCEEDED(query_interface_result) && raw_client) { + activated_client.reset(raw_client); + } else { + if (raw_client) { + raw_client->Release(); + } + BOOST_LOG(warning) << "Process loopback QueryInterface(IAudioClient) failed: [0x"sv << util::hex(query_interface_result).to_string_view() << ']'; + } + } + if (unknown) { + unknown->Release(); + } + if (event_handle) { + SetEvent(event_handle); + } + return S_OK; + } + + HANDLE event_handle = nullptr; ///< Event signaled when activation completes. + HRESULT activate_result = E_PENDING; ///< Result of GetActivateResult. + HRESULT activation_hresult = E_PENDING; ///< Activation HRESULT reported by the operation. + HRESULT query_interface_result = E_PENDING; ///< Result of QueryInterface for IAudioClient, or E_PENDING when not attempted. + audio_client_t activated_client; ///< Activated audio client, when activation succeeds. + + private: + std::atomic ref_count {1}; ///< COM reference count. + }; + + /** + * @brief Wait for loopback activation completion and collect its result. + * + * Consumes the caller's handler reference on every path. When the wait reports + * anything but WAIT_OBJECT_0 the completion fields are never touched, because the + * callback may still be running or arrive later; a signaled wait means the callback + * has finished writing them. A late callback stays alive through the reference + * Windows itself holds until the operation completes; the handler must not be + * freed before the callback runs. + * https://learn.microsoft.com/en-us/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-activateaudiointerfaceasync + * + * The handler must be non-null with a live caller reference; the caller must not + * touch it after return, even on timeout, because the late callback is covered by + * the operation's own reference. + * + * When `wait_timed_out` is provided and the wait expires, the caller + * reference is NOT consumed: `*wait_timed_out` is set and ownership of + * that reference returns to the caller, which must keep the handler (and + * any activation blob the pending operation may still read) alive until + * the completion event fires, then release it. + * + * @param handler Completion handler passed to ActivateAudioInterfaceAsync; its caller reference is consumed unless the wait times out with `wait_timed_out` provided. + * @param process_id Launched application PID being captured, used for diagnostics. + * @param timeout_ms Wait deadline in milliseconds. + * @param wait_timed_out Optional out-flag set when the wait expires without consuming the caller reference. + * @return Activated (not yet initialized) audio client, or nullptr on failure or timeout. + */ + audio_client_t collect_process_loopback_activation(process_loopback_completion_handler_t *handler, std::uint32_t process_id, DWORD timeout_ms = process_loopback_activation_timeout_ms, bool *wait_timed_out = nullptr) { + auto wait_result = WaitForSingleObject(handler->event_handle, timeout_ms); + if (wait_result != WAIT_OBJECT_0) { + BOOST_LOG(warning) << "Process loopback activation timed out for process ["sv << process_id + << "]: wait returned [0x"sv << util::hex(wait_result).to_string_view() << "] after timeout ["sv << timeout_ms + << " ms]; completion results unavailable"sv; + if (wait_timed_out) { + *wait_timed_out = true; + return nullptr; + } + handler->Release(); + return nullptr; + } + audio_client_t client; + if (SUCCEEDED(handler->activate_result) && SUCCEEDED(handler->activation_hresult) && SUCCEEDED(handler->query_interface_result) && handler->activated_client) { + client = std::move(handler->activated_client); + } else { + BOOST_LOG(warning) << "Process loopback activation did not complete successfully for process ["sv << process_id + << "]: wait returned [0x"sv << util::hex(wait_result).to_string_view() << "] after timeout ["sv << timeout_ms + << " ms], GetActivateResult returned [0x"sv << util::hex(handler->activate_result).to_string_view() + << "], activation returned [0x"sv << util::hex(handler->activation_hresult).to_string_view() + << "], QueryInterface(IAudioClient) returned [0x"sv << util::hex(handler->query_interface_result).to_string_view() << ']'; + } + handler->Release(); + return client; + } + + /** + * @brief Activate a WASAPI audio client for a process tree via ActivateAudioInterfaceAsync. + * + * @param process_id Launched application PID to capture. + * @return Activated (not yet initialized) audio client, or nullptr on failure. + */ + audio_client_t activate_process_loopback_audio_client(std::uint32_t process_id) { + auto *handler = new process_loopback_completion_handler_t(); + if (!handler->event_handle) { + BOOST_LOG(warning) << "Process loopback activation for process ["sv << process_id << "] failed to create its completion event: [0x"sv << util::hex(GetLastError()).to_string_view() << ']'; + handler->Release(); + return nullptr; + } + // Unlike Microsoft's ApplicationLoopback sample, which borrows the address of + // the stack-local params for the activation blob, the payload here is a + // heap copy: init_process_loopback_activation_blob() allocates it with + // CoTaskMemAlloc, so the prop_var_t destructor's PropVariantClear() always + // frees a heap address and can never free the stack. The prop_var_t itself + // is heap-allocated too, because on a wait timeout the pending operation + // may still read the blob and call the handler: both must outlive this + // stack frame until the completion event fires (handled below). + const auto params = make_process_loopback_activation_params(process_id); + auto *activation_prop = new prop_var_t(); + if (FAILED(init_process_loopback_activation_blob(activation_prop->prop, params))) { + BOOST_LOG(warning) << "Process loopback activation for process ["sv << process_id << "] could not allocate its activation blob"sv; + delete activation_prop; + handler->Release(); + return nullptr; + } + IActivateAudioInterfaceAsyncOperation *operation = nullptr; + auto status = ActivateAudioInterfaceAsync( + VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, + IID_IAudioClient, + &activation_prop->prop, + handler, + &operation + ); + if (operation) { + operation->Release(); + } + if (FAILED(status)) { + BOOST_LOG(warning) << "Process loopback activation failed to start for process ["sv << process_id << "]: ActivateAudioInterfaceAsync returned [0x"sv << util::hex(status).to_string_view() << ']'; + delete activation_prop; + handler->Release(); + return nullptr; + } + // collect_process_loopback_activation() consumes the caller's handler + // reference unless the wait times out; on timeout keep the handler and + // activation blob alive on a detached waiter until the pending + // operation completes, instead of freeing state it may still read. + bool wait_timed_out = false; + auto client = collect_process_loopback_activation(handler, process_id, process_loopback_activation_timeout_ms, &wait_timed_out); + if (wait_timed_out) { + try { + std::thread {[handler, activation_prop]() { + WaitForSingleObject(handler->event_handle, INFINITE); + delete activation_prop; + handler->Release(); + }}.detach(); + } catch (...) { + // No waiter could be started; leak the handler and blob on purpose + // rather than free state the pending operation may still read. + BOOST_LOG(warning) << "Process loopback activation for process ["sv << process_id << "] timed out and its cleanup waiter could not start; leaking its activation state until process exit"sv; + } + return nullptr; + } + delete activation_prop; + return client; + } +#endif + + /** + * @brief Create and initialize a process-loopback audio client using a supplied activation step. + * + * @param process_id Launched application PID to capture. + * @param format Requested capture format. + * @param activation Activation step returning an activated, not yet initialized, client for the PID. + * @return Initialized audio client, or nullptr when activation is missing or initialization fails. + */ + audio_client_t make_process_loopback_audio_client(std::uint32_t process_id, const format_t &format, const process_loopback_activation_t &activation) { + if (!activation) { + BOOST_LOG(warning) << "Process loopback activation is unavailable for process ["sv << process_id << ']'; + return nullptr; + } + return initialize_audio_client(activation(process_id), format, mix_format_failure_e::tolerate); + } + + /** + * @brief Create and initialize a process-loopback audio client for a PID. + * + * @param process_id Launched application PID to capture. + * @param format Requested capture format. + * @return Initialized audio client, or nullptr when process loopback is unavailable or fails. + */ + audio_client_t make_process_loopback_audio_client(std::uint32_t process_id, const format_t &format) { +#if defined(SUNSHINE_HAS_AUDIOCLIENT_ACTIVATION_PARAMS) && defined(VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK) + return make_process_loopback_audio_client(process_id, format, process_loopback_activation_t {&activate_process_loopback_audio_client}); +#else + (void) process_id; + (void) format; + return nullptr; +#endif + } + + /** + * @brief Whether WASAPI process loopback can work on this build and OS. + * + * Process loopback needs the activation-parameter headers at compile time + * and Windows build 20348 or later (Windows 11 / Server 2022) at runtime. + * The version is read through `RtlGetVersion` so application-manifest + * version lies cannot mask the real build, and the result is cached. + * + * @return True when process-loopback activation is worth attempting. + */ + [[nodiscard]] bool process_loopback_supported() { +#if defined(SUNSHINE_HAS_AUDIOCLIENT_ACTIVATION_PARAMS) && defined(VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK) + static const bool supported = []() { + using rtl_get_version_t = LONG(WINAPI *)(PRTL_OSVERSIONINFOW); + const auto ntdll = GetModuleHandleW(L"ntdll.dll"); + if (!ntdll) { + return false; + } + const auto rtl_get_version = reinterpret_cast(GetProcAddress(ntdll, "RtlGetVersion")); + if (!rtl_get_version) { + return false; + } + RTL_OSVERSIONINFOW version {}; + version.dwOSVersionInfoSize = sizeof(version); + if (rtl_get_version(&version) != 0) { + return false; + } + return version.dwMajorVersion > 10 || (version.dwMajorVersion == 10 && version.dwBuildNumber >= 20348); + }(); + return supported; +#else + return false; +#endif + } + + /** + * @brief Create audio client. + * + * @param device D3D, audio, or platform device used by the operation. + * @param format Pixel, audio, or protocol format being converted. + * @return Constructed audio client object. + */ + audio_client_t make_audio_client(device_t &device, const format_t &format) { + audio_client_t audio_client; + auto status = device->Activate( + IID_IAudioClient, + CLSCTX_ALL, + nullptr, + (void **) &audio_client + ); + + if (FAILED(status)) { + BOOST_LOG(error) << "Couldn't activate Device: [0x"sv << util::hex(status).to_string_view() << ']'; + + return nullptr; + } + + return initialize_audio_client(std::move(audio_client), format, mix_format_failure_e::fail); + } + /** * @brief Query the default Windows render endpoint. * @@ -600,14 +1121,15 @@ namespace platf::audio { /** * @brief Initialize WASAPI capture for the selected audio endpoint. * - * @param sample_rate Audio sample rate in hertz. - * @param frame_size Number of samples captured per audio frame. - * @param channels_out Channels out. - * @param continuous Whether silent audio should continue to be emitted. + * Only the channels, frame size, and continuous flag are used: WASAPI + * capture is fixed at 48 kHz float, the Opus mapping is encoder-side, and + * host-audio routing is resolved by the shared capture layer. + * + * @param params Microphone capture parameters for the requested layout. * @param capture_device Endpoint device to capture from; the default render device is used when empty. * @return 0 on success; nonzero or negative platform status on failure. */ - int init(std::uint32_t sample_rate, std::uint32_t frame_size, std::uint32_t channels_out, bool continuous, device_t capture_device) { + int init(const microphone_params_t ¶ms, device_t capture_device) { audio_event.reset(CreateEventA(nullptr, FALSE, FALSE, nullptr)); if (!audio_event) { BOOST_LOG(error) << "Couldn't create Event handle"sv; @@ -645,9 +1167,9 @@ namespace platf::audio { } for (const auto &format : formats) { - if (format.channel_count != channels_out) { + if (format.channel_count != params.channels) { BOOST_LOG(debug) << "Skipping audio format ["sv << format.name << "] with channel count ["sv - << format.channel_count << " != "sv << channels_out << ']'; + << format.channel_count << " != "sv << params.channels << ']'; continue; } @@ -656,7 +1178,7 @@ namespace platf::audio { if (audio_client) { BOOST_LOG(debug) << "Found audio format ["sv << format.name << ']'; - channels = channels_out; + channels = params.channels; break; } } @@ -666,21 +1188,64 @@ namespace platf::audio { return -1; } - REFERENCE_TIME default_latency; - audio_client->GetDevicePeriod(&default_latency, nullptr); - default_latency_ms = default_latency / 1000; - continuous_audio = continuous; - - std::uint32_t frames; - status = audio_client->GetBufferSize(&frames); - if (FAILED(status)) { - BOOST_LOG(error) << "Couldn't acquire the number of audio frames [0x"sv << util::hex(status).to_string_view() << ']'; + return finish_capture_init(params); + } + /** + * @brief Initialize WASAPI capture for a specific process tree. + * + * @param params Microphone capture parameters for the requested layout. + * @param process_id Launched application PID to capture. + * @param activator Activator creating an initialized process-loopback client. + * @return 0 on success; nonzero or negative platform status on failure. + */ + int init_process_loopback(const microphone_params_t ¶ms, std::uint32_t process_id, const process_loopback_activator_t &activator) { + audio_event.reset(CreateEventA(nullptr, FALSE, FALSE, nullptr)); + if (!audio_event) { + BOOST_LOG(error) << "Couldn't create Event handle"sv; return -1; } - - // *2 --> needs to fit double - sample_buf = util::buffer_t {std::max(frames, frame_size) * 2 * channels_out}; + follows_default_device = false; + for (const auto &format : formats) { + if (format.channel_count != params.channels) { + continue; + } + audio_client = activator(process_id, format); + if (audio_client) { + channels = params.channels; + break; + } + } + if (!audio_client) { + BOOST_LOG(warning) << "Couldn't create process loopback audio client"sv; + return -1; + } + return finish_capture_init(params); + } + + /** + * @brief Finish capture initialization after an audio client is initialized. + * + * @param params Microphone capture parameters for the requested layout. + * @return 0 on success; nonzero or negative platform status on failure. + */ + int finish_capture_init(const microphone_params_t ¶ms) { + HRESULT status; + REFERENCE_TIME default_latency = 100000; + audio_client->GetDevicePeriod(&default_latency, nullptr); + default_latency_ms = default_latency / 1000; + continuous_audio = params.continuous_audio; + + std::uint32_t frames; + status = audio_client->GetBufferSize(&frames); + if (FAILED(status)) { + BOOST_LOG(error) << "Couldn't acquire the number of audio frames [0x"sv << util::hex(status).to_string_view() << ']'; + + return -1; + } + + // *2 --> needs to fit double + sample_buf = util::buffer_t {std::max(frames, params.frame_size) * 2 * static_cast(params.channels)}; sample_buf_pos = std::begin(sample_buf); status = audio_client->GetService(IID_IAudioCaptureClient, (void **) &audio_capture); @@ -871,6 +1436,11 @@ namespace platf::audio { */ class audio_control_t: public ::platf::audio_control_t { public: + // The positional microphone() override below hides the parameter-bundle + // overload; unhide it so new code (and the test seams) can call the bundle + // form on this type directly instead of via a base-class reference. + using ::platf::audio_control_t::microphone; + /** * @brief Query host and virtual sink names available to Sunshine. * @@ -992,9 +1562,126 @@ namespace platf::audio { return device; } + /** + * @brief Consistent copy of the recorded capture target. + */ + struct capture_target_snapshot_t { + audio_capture_intent_e intent; ///< Intent for the next microphone() call. + std::uint32_t process_id; ///< PID for process-loopback capture, or 0 for endpoint capture. + process_identity_t identity; ///< Creation-time identity recorded with `process_id`, empty when unverifiable. + }; + + /** + * @brief Copy the recorded capture target under the base capture mutex. + * + * Holds `capture_state_mutex_` once so the intent, PID, and identity form + * one consistent snapshot with the shared `recorded_target_` record. + * + * @return Intent, PID, and identity as one consistent snapshot. + */ + capture_target_snapshot_t snapshot_capture_target() const { + std::lock_guard lock {capture_state_mutex_}; + return {recorded_target_.intent, recorded_target_.process_id, capture_target_identity}; + } + + /** + * @brief Copy the assigned sink name under the base capture mutex. + * + * @return Sink assigned while Sunshine captures host audio, possibly empty. + */ + std::string snapshot_assigned_sink() const { + return snapshot_recorded_sink(); + } + + /** + * @brief Record the capture target for the next microphone() call. + * + * Thread-safe: the intent, PID, and identity are stored as one snapshot + * under `capture_state_mutex_`, so microphone() never sees a mismatched + * triple. The identity arrives pre-queried from the owned child handle + * under the process lifecycle lock and is stored verbatim as the + * revalidation baseline: querying it here by PID instead would reopen the + * reuse window the handoff closes (an exited process whose PID was already + * reused would record the replacement's creation time and defeat both the + * pre-activation and post-activation checks). An unverifiable baseline + * fails closed at validation time, where the PID resolves to endpoint capture. + * + * @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(audio_capture_intent_e intent, process_identity_t identity) override { + if (identity.process_id == 0) { + identity = {}; + } + std::lock_guard lock {capture_state_mutex_}; + recorded_target_.intent = intent; + recorded_target_.process_id = identity.process_id; + capture_target_identity = identity; + } + + /** + * @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. + * + * @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(audio_capture_intent_e intent, std::uint32_t process_id) override { + clear_recorded_capture_target_if_matches(intent, process_id); + } + +#ifdef SUNSHINE_TESTS + /** + * @brief Install a test override for the process-loopback activator used by microphone(). + * + * Tests install a counting activator that returns no client so the + * loopback-attempt and activation-failure fallback can be exercised + * without audio hardware. Production never calls this; an empty override + * selects the real WASAPI activator. + * + * @param activator Activator microphone() uses instead of the production one. + */ + void set_test_loopback_activator(process_loopback_activator_t activator) { + test_loopback_activator = std::move(activator); + } +#endif + + /** + * @brief Revalidate the recorded capture target immediately before activation. + * + * Snapshots the target under `capture_state_mutex_`, then revalidates without + * holding the lock so process queries never block other sessions. + * + * @return Recorded PID when it still refers to the same live process, or 0 when the process exited, the PID was reused, or its identity cannot be verified. + */ + std::uint32_t validated_capture_process_id() { + return validated_snapshot_process_id(snapshot_capture_target()); + } + + /** + * @brief Whether the Windows backend can capture one launched process tree. + * + * @return True only when this build and OS support WASAPI process loopback. + */ + bool supports_process_capture() const override { + return process_loopback_supported(); + } + /** * @brief Create a microphone capture stream for the requested layout. * + * Positional override per the shared design; new callers use the + * parameter-bundle overload unhidden above. Operates on mutex-guarded + * snapshots of the capture target and assigned sink, so concurrent + * sessions cannot change either mid-creation. The default-endpoint + * callback reasserts the snapshot taken here, never the shared string. + * Test builds may override the loopback activator via + * set_test_loopback_activator(); production always uses the WASAPI activator. + * * @param mapping Opus channel mapping table for the requested layout. * @param channels Number of audio channels in the stream. * @param sample_rate Audio sample rate in hertz. @@ -1003,17 +1690,57 @@ namespace platf::audio { * @param host_audio_enabled Whether host playback should remain enabled during capture. * @return Microphone capture object for the requested audio layout. */ - 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 { + 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 { + const microphone_params_t params {mapping, channels, sample_rate, frame_size, continuous_audio, host_audio_enabled}; + const auto capture_snapshot = snapshot_capture_target(); + const auto target_process_id = validated_snapshot_process_id(capture_snapshot); + if (use_process_loopback(target_process_id, capture_snapshot.intent)) { + auto process_mic = std::make_unique(); + auto loopback_activator = process_loopback_activator_t {static_cast(&make_process_loopback_audio_client)}; +#ifdef SUNSHINE_TESTS + // Tests install a failing activator to exercise the loopback-attempt + // and activation-failure fallback without audio hardware. + if (test_loopback_activator) { + loopback_activator = test_loopback_activator; + } +#endif + if (!process_mic->init_process_loopback(params, target_process_id, loopback_activator)) { + // The PID may have exited or been reused while activation was + // resolving it, so revalidate after activation and discard on + // mismatch instead of capturing the wrong process. + if (activated_process_target_is_current(target_process_id, validated_snapshot_process_id(capture_snapshot))) { + BOOST_LOG(info) << "Capturing audio from process ["sv << target_process_id << "] via process loopback"sv; + return process_mic; + } + BOOST_LOG(warning) << "Process ["sv << target_process_id << "] exited or its PID was reused during activation; falling back to endpoint capture"sv; + } else { + BOOST_LOG(warning) << "Process loopback capture failed for process ["sv << target_process_id << "]; falling back to endpoint capture"sv; + } + } + auto mic = std::make_unique(); + // An explicit sink pin stays pinned. With keep-default and no configured + // sink, the assigned sink is only the host sink recorded at startup, so + // capture must follow the Windows default instead of resolving that + // snapshot after the startup endpoint disappears. + const bool follow_default_device = should_follow_default_device(); + + // Snapshot the assigned sink once: the default-endpoint callback installed + // below runs on the capture thread and must reassert this copy, never a + // shared string that another session may rewrite concurrently. + const auto assigned_sink_snapshot = snapshot_assigned_sink(); + // Prefer the session's assigned sink; otherwise use the configured sink. - const auto &requested_sink = assigned_sink.empty() ? config::audio.sink : assigned_sink; + const auto requested_sink = assigned_sink_snapshot.empty() ? config::audio.sink : assigned_sink_snapshot; // 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 // from the sink or changes during the session. device_t capture_device; - if (!requested_sink.empty()) { + if (follow_default_device) { + BOOST_LOG(info) << "Capturing audio from the Windows default sink"sv; + } else if (!requested_sink.empty()) { capture_device = get_sink_device(requested_sink); if (!capture_device) { BOOST_LOG(error) << "Couldn't resolve audio sink ["sv << requested_sink << "] to a capture device"sv; @@ -1023,16 +1750,16 @@ namespace platf::audio { BOOST_LOG(info) << "Capturing audio from sink ["sv << requested_sink << ']'; } - if (mic->init(sample_rate, frame_size, channels, continuous_audio, std::move(capture_device))) { + if (mic->init(params, std::move(capture_device))) { return nullptr; } // 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); + if (should_install_default_callback(assigned_sink_snapshot)) { + mic->default_endpt_changed_cb = [this, sink = assigned_sink_snapshot] { + BOOST_LOG(info) << "Resetting sink to ["sv << sink << "] after default changed"; + set_sink(sink); }; } @@ -1112,13 +1839,17 @@ namespace platf::audio { /** * @brief Update the sink value on the backend. * + * Thread-safe: only the assigned-sink store is guarded; the endpoint + * switch itself runs outside `capture_state_mutex_`. Safe to call from the + * default-endpoint callback on the capture thread. + * * @param sink Audio sink name to route or capture. * @return Status from updating sink. */ int set_sink(const std::string &sink) override { if (config::audio.keep_default_sink) { // Keep-default never swaps the host default; capture follows the recorded endpoint. - assigned_sink = sink; + record_capture_sink(sink); return 0; } @@ -1145,7 +1876,7 @@ namespace platf::audio { // Remember the assigned sink name, so we have it for later if we need to set it // back after another application changes it if (!failure) { - assigned_sink = sink; + record_capture_sink(sink); } return failure; @@ -1163,17 +1894,28 @@ namespace platf::audio { /** * @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. + * Records the target for microphone() under the base capture mutex; 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 record_keep_default_capture_sink(sink); + } - return 0; + /** + * @brief Whether endpoint capture should follow the Windows default device. + * + * Only the automatically captured host sink follows the default: an + * explicit `audio_sink` pin stays pinned, and the swap path keeps + * capturing its assigned (virtual) endpoint. + * + * @return True when keep-default is enabled with no configured sink. + */ + [[nodiscard]] bool should_follow_default_device() const noexcept { + return config::audio.keep_default_sink && config::audio.sink.empty(); } /** @@ -1256,8 +1998,58 @@ namespace platf::audio { }; } + /** + * @brief Identity and property store read from one enumerated endpoint. + */ + struct endpoint_probe_t { + std::wstring device_id; ///< Device identifier string. + prop_t prop; ///< Opened property store for endpoint metadata. + }; + + /** + * @brief Read one enumerated endpoint's identity and property store. + * + * Every Item(), GetId(), and OpenPropertyStore() HRESULT is checked; an + * entry that cannot be read reports std::nullopt so the caller skips it + * instead of risking a null device id or a null property store dereference. + * + * @param collection Enumerated active render endpoints. + * @param index Endpoint index within the collection, used for diagnostics. + * @return Probe data, or std::nullopt when the endpoint cannot be read. + */ + static std::optional probe_audio_endpoint(collection_t &collection, int index) { + device_t device; + auto status = collection->Item(index, &device); + if (FAILED(status) || !device) { + BOOST_LOG(warning) << "Skipping endpoint ["sv << index << "] that could not be read: [0x"sv << util::hex(status).to_string_view() << ']'; + return std::nullopt; + } + + wstring_t wstring_id; + status = device->GetId(&wstring_id); + if (FAILED(status) || !wstring_id.get()) { + BOOST_LOG(warning) << "Skipping endpoint ["sv << index << "] without a readable device id: [0x"sv << util::hex(status).to_string_view() << ']'; + return std::nullopt; + } + + prop_t prop; + status = device->OpenPropertyStore(STGM_READ, &prop); + if (FAILED(status) || !prop) { + BOOST_LOG(warning) << "Skipping endpoint ["sv << index << "] without a readable property store: [0x"sv << util::hex(status).to_string_view() << ']'; + return std::nullopt; + } + + return endpoint_probe_t {std::wstring {wstring_id.get()}, std::move(prop)}; + } + /** * @brief Search for currently present audio device_id using multiple match fields. + * + * Entries that cannot be read are skipped: every Item(), GetId(), and + * OpenPropertyStore() HRESULT is checked, and a failed entry continues to + * the next device instead of risking a null device id or a null property + * store dereference. + * * @param match_list Pairs of match fields and values * @return Optional pair of matched field and device_id */ @@ -1274,19 +2066,20 @@ namespace platf::audio { } UINT count = 0; - collection->GetCount(&count); + status = collection->GetCount(&count); + if (FAILED(status)) { + BOOST_LOG(error) << "Couldn't count endpoints: [0x"sv << util::hex(status).to_string_view() << ']'; + return std::nullopt; + } std::vector matched(match_list.size()); for (auto x = 0; x < count; ++x) { - audio::device_t device; - collection->Item(x, &device); - - audio::wstring_t wstring_id; - device->GetId(&wstring_id); - std::wstring device_id = wstring_id.get(); - - audio::prop_t prop; - device->OpenPropertyStore(STGM_READ, &prop); + auto probe = probe_audio_endpoint(collection, x); + if (!probe) { + continue; + } + std::wstring device_id = std::move(probe->device_id); + audio::prop_t prop = std::move(probe->prop); prop_var_t adapter_friendly_name; prop_var_t device_friendly_name; @@ -1517,7 +2310,45 @@ namespace platf::audio { policy_t policy; ///< Windows policy configuration interface used to switch default audio devices. audio::device_enum_t device_enum; ///< Device enumerator used to query and watch audio endpoints. - std::string assigned_sink; ///< Sink assigned while Sunshine captures host audio, captured directly by the microphone. + + private: + /** + * @brief Revalidate a capture-target snapshot immediately before or after activation. + * + * Operates only on the given snapshot plus a fresh process query, so + * callers must not hold `capture_state_mutex_` while revalidation runs. + * + * @param snapshot Capture target snapshot to revalidate. + * @return Snapshot PID when it still refers to the same live process, or 0 for endpoint capture. + */ + static std::uint32_t validated_snapshot_process_id(const capture_target_snapshot_t &snapshot) { + if (snapshot.process_id == 0) { + return 0; + } + const auto current = query_process_identity(snapshot.process_id); + const auto effective = effective_capture_process_id(snapshot.identity, current); + if (effective == 0) { + BOOST_LOG(warning) << "Capture target process ["sv << snapshot.process_id << "] exited or its PID was reused; falling back to endpoint capture"sv; + } + return effective; + } + +#ifdef SUNSHINE_TESTS + process_loopback_activator_t test_loopback_activator; ///< Test override for the loopback activator used by microphone(), empty in production. +#endif + /** + * @brief Reset the WASAPI creation-time identity paired with the recorded target. + * + * Invoked by the base `clear_recorded_capture_target_if_matches()` while holding + * `capture_state_mutex_`, so the intent/PID/identity reset stays atomic under one + * lock hold. Non-reentrant by design: plain struct reset only, no OS queries, + * no base-helper calls. + */ + void on_capture_target_cleared() override { + capture_target_identity = {}; + } + + process_identity_t capture_target_identity {}; ///< Creation-time identity recorded with the PID, guarded by the base `capture_state_mutex_`, empty when unverifiable. }; #ifdef SUNSHINE_TESTS @@ -1582,7 +2413,811 @@ namespace platf::audio { return {}; } - return control.assigned_sink; + return control.snapshot_assigned_sink(); + } + + /** + * @brief Exercise the process-loopback predicate without audio hardware. + * @param process_id Revalidated application PID, or 0 for endpoint capture. + * @param intent Capture intent recorded for the next microphone() call. + * @return True when process loopback should be attempted. + */ + bool use_process_loopback(std::uint32_t process_id, audio_capture_intent_e intent) { + return platf::audio::use_process_loopback(process_id, intent); + } + + #ifdef SUNSHINE_HAS_AUDIOCLIENT_ACTIVATION_PARAMS + /** + * @brief Build process-loopback activation parameters for a PID. + * @param process_id Launched application PID to capture. + * @return Activation parameters including the target process tree. + */ + AUDIOCLIENT_ACTIVATION_PARAMS make_process_loopback_activation_params(std::uint32_t process_id) { + return platf::audio::make_process_loopback_activation_params(process_id); + } + + /** + * @brief Build a heap-owned activation blob and verify it clears safely. + * + * Pins the regression-proof property of the production activation blob: + * the payload is a heap copy (never the address of the stack params), and + * PropVariantClear() releases it cleanly. + * + * @param process_id Launched application PID to capture. + * @return True when the blob holds a heap copy of the params and clears cleanly. + */ + bool activation_blob_holds_heap_copy(std::uint32_t process_id) { + const auto params = platf::audio::make_process_loopback_activation_params(process_id); + PROPVARIANT prop {}; + PropVariantInit(&prop); + if (FAILED(platf::audio::init_process_loopback_activation_blob(prop, params))) { + return false; + } + const bool holds_copy = prop.vt == VT_BLOB && + prop.blob.cbSize == sizeof(params) && + prop.blob.pBlobData != nullptr && + prop.blob.pBlobData != reinterpret_cast(¶ms) && + std::memcmp(prop.blob.pBlobData, ¶ms, sizeof(params)) == 0; + const auto clear_status = PropVariantClear(&prop); + return holds_copy && SUCCEEDED(clear_status) && prop.vt == VT_EMPTY; + } + #endif + + /** + * @brief Exercise process-loopback initialization with an activator that always fails. + * @return True when initialization fails as expected (the fallback trigger). + */ + bool process_loopback_fails_with_null_activator() { + mic_wasapi_t mic; + process_loopback_activator_t activator = [](std::uint32_t, const format_t &) -> audio_client_t { + return nullptr; + }; + const microphone_params_t params {nullptr, 2, 48000, 240, false, false}; + return mic.init_process_loopback(params, 1234, activator) != 0; + } + + /** + * @brief Fake IAudioClient with a controllable Initialize result for process-loopback wrapper tests. + */ + class fake_process_loopback_audio_client_t final: public IAudioClient { + public: + /** + * @brief Construct a fake client returning the given result from Initialize(). + * @param initialize_status HRESULT returned by Initialize(). + */ + explicit fake_process_loopback_audio_client_t(HRESULT initialize_status): + initialize_status {initialize_status} { + ++live_count; + } + + /** + * @brief Destroy the fake client, releasing its lifetime count. + */ + ~fake_process_loopback_audio_client_t() { + --live_count; + } + + /** + * @brief Query a supported COM interface. + * @param riid Requested interface identifier. + * @param object Receives the interface pointer. + * @return S_OK when supported, E_NOINTERFACE otherwise. + */ + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **object) override { // NOSONAR(cpp:S5008): IUnknown::QueryInterface requires a void double pointer in the COM ABI. + if (!object) { + return E_POINTER; + } + if (riid == IID_IUnknown || riid == __uuidof(IAudioClient)) { + *object = static_cast(this); + AddRef(); + return S_OK; + } + *object = nullptr; + return E_NOINTERFACE; + } + + /** + * @brief Increment the reference count. + * @return New reference count. + */ + ULONG STDMETHODCALLTYPE AddRef() override { + return ++ref_count; + } + + /** + * @brief Decrement the reference count, deleting when it reaches zero. + * @return New reference count. + */ + ULONG STDMETHODCALLTYPE Release() override { + auto count = --ref_count; + if (count == 0) { + delete this; + } + return count; + } + + /** + * @brief Simulate client initialization with the configured result. + * @return Configured Initialize() result. + */ + HRESULT STDMETHODCALLTYPE Initialize(AUDCLNT_SHAREMODE, DWORD, REFERENCE_TIME, REFERENCE_TIME, const WAVEFORMATEX *, LPCGUID) override { + return initialize_status; + } + + /** + * @brief Report an empty buffer. + * @param buffer_frames Receives the buffer size in frames. + * @return S_OK after reporting zero frames. + */ + HRESULT STDMETHODCALLTYPE GetBufferSize(UINT32 *buffer_frames) override { + if (buffer_frames) { + *buffer_frames = 0; + } + return S_OK; + } + + /** + * @brief Report zero stream latency. + * @param latency Receives the stream latency. + * @return S_OK after reporting zero latency. + */ + HRESULT STDMETHODCALLTYPE GetStreamLatency(REFERENCE_TIME *latency) override { + if (latency) { + *latency = 0; + } + return S_OK; + } + + /** + * @brief Report zero padding frames. + * @param padding_frames Receives the padding size in frames. + * @return S_OK after reporting zero frames. + */ + HRESULT STDMETHODCALLTYPE GetCurrentPadding(UINT32 *padding_frames) override { + if (padding_frames) { + *padding_frames = 0; + } + return S_OK; + } + + /** + * @brief Reject format support queries, which wrapper tests do not use. + * @return E_NOTIMPL. + */ + HRESULT STDMETHODCALLTYPE IsFormatSupported(AUDCLNT_SHAREMODE, const WAVEFORMATEX *, WAVEFORMATEX **closest_match) override { + if (closest_match) { + *closest_match = nullptr; + } + return E_NOTIMPL; + } + + /** + * @brief Fail mix-format lookup so the tolerated failure path is exercised. + * @param device_format Receives the device format on success. + * @return E_FAIL to exercise the tolerated mix-format failure. + */ + HRESULT STDMETHODCALLTYPE GetMixFormat(WAVEFORMATEX **device_format) override { + if (device_format) { + *device_format = nullptr; + } + return E_FAIL; + } + + /** + * @brief Report zero device periods. + * @param default_period Receives the default device period. + * @param minimum_period Receives the minimum device period. + * @return S_OK after reporting zero periods. + */ + HRESULT STDMETHODCALLTYPE GetDevicePeriod(REFERENCE_TIME *default_period, REFERENCE_TIME *minimum_period) override { + if (default_period) { + *default_period = 0; + } + if (minimum_period) { + *minimum_period = 0; + } + return S_OK; + } + + /** + * @brief Simulate starting capture. + * @return S_OK. + */ + HRESULT STDMETHODCALLTYPE Start() override { + return S_OK; + } + + /** + * @brief Simulate stopping capture. + * @return S_OK. + */ + HRESULT STDMETHODCALLTYPE Stop() override { + return S_OK; + } + + /** + * @brief Simulate resetting capture. + * @return S_OK. + */ + HRESULT STDMETHODCALLTYPE Reset() override { + return S_OK; + } + + /** + * @brief Accept an event handle without storing it. + * @return S_OK. + */ + HRESULT STDMETHODCALLTYPE SetEventHandle(HANDLE) override { + return S_OK; + } + + /** + * @brief Reject service queries, which wrapper tests do not use. + * @param object Receives the requested service. + * @return E_NOTIMPL. + */ + HRESULT STDMETHODCALLTYPE GetService(REFIID, void **object) override { // NOSONAR(cpp:S5008): IUnknown::QueryInterface requires a void double pointer in the COM ABI. + if (object) { + *object = nullptr; + } + return E_NOTIMPL; + } + + static inline std::atomic live_count {0}; ///< Live fake-client count for leak checks. + + private: + HRESULT initialize_status; ///< HRESULT returned by Initialize(). + std::atomic ref_count {1}; ///< COM reference count. + }; + + #if defined(SUNSHINE_HAS_AUDIOCLIENT_ACTIVATION_PARAMS) && defined(VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK) + /** + * @brief Fake async operation reporting successful activation of a supplied interface. + */ + class fake_process_loopback_async_operation_t final: public IActivateAudioInterfaceAsyncOperation { + public: + /** + * @brief Construct a fake operation serving the given interface. + * @param served_interface Interface returned from GetActivateResult; the operation holds its own reference. + */ + explicit fake_process_loopback_async_operation_t(IUnknown *served_interface): + served_interface {served_interface} { + if (served_interface) { + served_interface->AddRef(); + } + } + + /** + * @brief Destroy the operation, releasing the served interface. + */ + ~fake_process_loopback_async_operation_t() { + if (served_interface) { + served_interface->Release(); + } + } + + /** + * @brief Query a supported COM interface. + * @param riid Requested interface identifier. + * @param object Receives the interface pointer. + * @return S_OK when supported, E_NOINTERFACE otherwise. + */ + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **object) override { // NOSONAR(cpp:S5008): IUnknown::QueryInterface requires a void double pointer in the COM ABI. + if (!object) { + return E_POINTER; + } + if (riid == IID_IUnknown || riid == __uuidof(IActivateAudioInterfaceAsyncOperation)) { + *object = static_cast(this); + AddRef(); + return S_OK; + } + *object = nullptr; + return E_NOINTERFACE; + } + + /** + * @brief Increment the reference count. + * @return New reference count. + */ + ULONG STDMETHODCALLTYPE AddRef() override { + return ++ref_count; + } + + /** + * @brief Decrement the reference count, deleting when it reaches zero. + * @return New reference count. + */ + ULONG STDMETHODCALLTYPE Release() override { + auto count = --ref_count; + if (count == 0) { + delete this; + } + return count; + } + + /** + * @brief Report successful activation of the served interface. + * @param activation_hresult Receives the activation HRESULT. + * @param activated_interface Receives the served interface. + * @return S_OK. + */ + HRESULT STDMETHODCALLTYPE GetActivateResult(HRESULT *activation_hresult, IUnknown **activated_interface) override { + if (!activation_hresult || !activated_interface) { + return E_POINTER; + } + *activation_hresult = S_OK; + *activated_interface = served_interface; + if (served_interface) { + served_interface->AddRef(); + } + return S_OK; + } + + private: + IUnknown *served_interface {}; ///< Served interface held with an owning reference, or nullptr. + std::atomic ref_count {1}; ///< COM reference count. + }; + + /** + * @brief Verify timeout, failure, and success activation paths discard and deliver safely. + * + * Drives the real completion handler through the production wait-and-collect path + * in phases: a null completion arriving strictly after a short timeout must be + * discarded without delivering a client, a late success completion must likewise be + * discarded without leaking its client, an invalid wait handle must report no + * client, a pre-signaled failure must report no client, a pre-signaled success + * must deliver its client, and the same success through the default timeout + * argument must deliver it the way production calls it. The timeout phases hold + * the worker behind a gate event + * so the completion provably starts only after the wait expired, and hold an extra + * handler reference while waiting to model the reference Windows retains until the + * callback runs, so the late callback always sees a live handler. A final overlap + * loop hammers the race to pin crash-freedom and lifetime balance. + * + * The stress loop pins crash-freedom and lifetime balance only; it does not prove + * overlap occurred. Data-race freedom is unverified: the msys2/ucrt64 MinGW + * toolchain has no ThreadSanitizer support. + * + * @return 0 when every phase passes; otherwise the failing-phase id. Setup failures + * (a missing completion event or gate handle) reuse the id of the phase they belong to. + */ + int process_loopback_completion_after_timeout_is_discarded() { + constexpr int kPhasePassed {0}; ///< All phases passed. + constexpr int kPhaseTimeoutOrdering {1}; ///< Timeout setup failed, or the wait did not expire before the late null completion started. + constexpr int kPhaseTimeoutDiscard {2}; ///< Expired wait delivered a client for the late null completion. + constexpr int kPhaseLateSuccess {3}; ///< Late-success setup failed, the wait did not expire first, or the expired wait delivered a client. + constexpr int kPhaseWaitFailed {4}; ///< Invalid-handle wait delivered a client. + constexpr int kPhaseSignaledFailure {5}; ///< Pre-signaled failure setup failed or delivered a client. + constexpr int kPhaseSignaledSuccess {6}; ///< Pre-signaled success setup failed or delivered no client. + constexpr int kPhaseStress {7}; ///< Overlap stress iteration setup failed. + constexpr int kPhaseLifetime {8}; ///< A fake client leaked across the late-success phase or the stress loop. + constexpr int kPhaseDefaultTimeout {9}; ///< Pre-signaled success through the default timeout delivered no client. + constexpr DWORD kShortTimeoutMs {10}; ///< Timeout that expires while the gated completion is still held. + constexpr DWORD kSignaledWaitMs {1000}; ///< Wait allowing pre-signaled completions to report. + constexpr DWORD kGateWaitMs {5000}; ///< Bound on the gated worker wait so a stuck gate fails instead of hanging. + { + auto *handler = new platf::audio::process_loopback_completion_handler_t(); + if (!handler->event_handle) { + handler->Release(); + return kPhaseTimeoutOrdering; + } + handler->AddRef(); // Model the reference Windows holds until the callback runs. + HANDLE gate = CreateEventA(nullptr, TRUE, FALSE, nullptr); + if (!gate) { + handler->Release(); + handler->Release(); + return kPhaseTimeoutOrdering; + } + std::atomic completion_started {false}; + std::thread late_completion([handler, gate, &completion_started] { + WaitForSingleObject(gate, kGateWaitMs); + completion_started.store(true, std::memory_order_release); + handler->ActivateCompleted(nullptr); + handler->Release(); + }); + bool wait_timed_out = false; + auto client = platf::audio::collect_process_loopback_activation(handler, 1234, kShortTimeoutMs, &wait_timed_out); + const bool expired_before_completion = !completion_started.load(std::memory_order_acquire); + SetEvent(gate); + late_completion.join(); + CloseHandle(gate); + if (wait_timed_out) { + // Model the production detached waiter releasing the retained + // caller reference once the late completion has run. + handler->Release(); + } + if (!expired_before_completion || !wait_timed_out) { + return kPhaseTimeoutOrdering; + } + if (client) { + return kPhaseTimeoutDiscard; + } + } + { + const int live_baseline = fake_process_loopback_audio_client_t::live_count.load(); + { + auto *served_client = new fake_process_loopback_audio_client_t(S_OK); + fake_process_loopback_async_operation_t operation(served_client); + served_client->Release(); + auto *handler = new platf::audio::process_loopback_completion_handler_t(); + if (!handler->event_handle) { + handler->Release(); + return kPhaseLateSuccess; + } + handler->AddRef(); // Model the reference Windows holds until the callback runs. + HANDLE gate = CreateEventA(nullptr, TRUE, FALSE, nullptr); + if (!gate) { + handler->Release(); + handler->Release(); + return kPhaseLateSuccess; + } + std::atomic completion_started {false}; + std::thread late_completion([handler, gate, &completion_started, &operation] { + WaitForSingleObject(gate, kGateWaitMs); + completion_started.store(true, std::memory_order_release); + handler->ActivateCompleted(&operation); + handler->Release(); + }); + bool wait_timed_out = false; + auto client = platf::audio::collect_process_loopback_activation(handler, 1234, kShortTimeoutMs, &wait_timed_out); + const bool expired_before_completion = !completion_started.load(std::memory_order_acquire); + SetEvent(gate); + late_completion.join(); + CloseHandle(gate); + if (wait_timed_out) { + handler->Release(); + } + if (!expired_before_completion || !wait_timed_out || client) { + return kPhaseLateSuccess; + } + } + if (fake_process_loopback_audio_client_t::live_count.load() != live_baseline) { + return kPhaseLifetime; + } + } + { + auto *handler = new platf::audio::process_loopback_completion_handler_t(); + if (!handler->event_handle) { + handler->Release(); + return kPhaseWaitFailed; + } + // Production never passes an invalid handle (activate_process_loopback_audio_client checks + // creation), so this pins the shared non-signaled wait branch rather than a production path. + CloseHandle(handler->event_handle); + handler->event_handle = nullptr; + auto client = platf::audio::collect_process_loopback_activation(handler, 1234, kSignaledWaitMs); + if (client) { + return kPhaseWaitFailed; + } + } + { + auto *handler = new platf::audio::process_loopback_completion_handler_t(); + if (!handler->event_handle) { + handler->Release(); + return kPhaseSignaledFailure; + } + handler->ActivateCompleted(nullptr); + auto client = platf::audio::collect_process_loopback_activation(handler, 1234, kSignaledWaitMs); + if (client) { + return kPhaseSignaledFailure; + } + } + { + auto *served_client = new fake_process_loopback_audio_client_t(S_OK); + fake_process_loopback_async_operation_t operation(served_client); + served_client->Release(); + auto *handler = new platf::audio::process_loopback_completion_handler_t(); + if (!handler->event_handle) { + handler->Release(); + return kPhaseSignaledSuccess; + } + handler->ActivateCompleted(&operation); + auto client = platf::audio::collect_process_loopback_activation(handler, 1234, kSignaledWaitMs); + if (!client) { + return kPhaseSignaledSuccess; + } + } + { + // Same success shape production uses: default timeout argument with a pre-signaled event. + auto *served_client = new fake_process_loopback_audio_client_t(S_OK); + fake_process_loopback_async_operation_t operation(served_client); + served_client->Release(); + auto *handler = new platf::audio::process_loopback_completion_handler_t(); + if (!handler->event_handle) { + handler->Release(); + return kPhaseDefaultTimeout; + } + handler->ActivateCompleted(&operation); + auto client = platf::audio::collect_process_loopback_activation(handler, 1234); + if (!client) { + return kPhaseDefaultTimeout; + } + } + { + const int live_baseline = fake_process_loopback_audio_client_t::live_count.load(); + for (int i = 0; i < 25; ++i) { + auto *served_client = new fake_process_loopback_audio_client_t(S_OK); + fake_process_loopback_async_operation_t operation(served_client); + served_client->Release(); + auto *handler = new platf::audio::process_loopback_completion_handler_t(); + if (!handler->event_handle) { + handler->Release(); + return kPhaseStress; + } + handler->AddRef(); // Model the reference Windows holds until the callback runs. + std::thread racer([handler, &operation, i] { + if (i % 2 != 0) { + ::Sleep(1); + } + if (i % 2 == 0) { + handler->ActivateCompleted(&operation); + } else { + handler->ActivateCompleted(nullptr); + } + handler->Release(); + }); + bool wait_timed_out = false; + auto client = platf::audio::collect_process_loopback_activation(handler, 1234, (i % 3 == 0) ? 0 : 1, &wait_timed_out); + (void) client; // Either outcome is legal under the race; only crash-freedom and lifetime are pinned. + racer.join(); + if (wait_timed_out) { + handler->Release(); + } + } + if (fake_process_loopback_audio_client_t::live_count.load() != live_baseline) { + return kPhaseLifetime; + } + } + return kPhasePassed; + } + #endif + + /** + * @brief Exercise the process-loopback wrapper with a fake activation that succeeds. + * @return True when the wrapper returns an initialized client. + */ + bool process_loopback_wrapper_succeeds_with_fake_activation() { + process_loopback_activation_t activation = [](std::uint32_t) { + audio_client_t client; + client.reset(new fake_process_loopback_audio_client_t(S_OK)); + return client; + }; + auto client = make_process_loopback_audio_client(1234, formats[0], activation); + return static_cast(client); + } + + /** + * @brief Exercise the process-loopback wrapper with an activation that returns no client. + * @return True when the wrapper returns no client. + */ + bool process_loopback_wrapper_fails_with_null_activation() { + process_loopback_activation_t activation = [](std::uint32_t) -> audio_client_t { + return nullptr; + }; + return !make_process_loopback_audio_client(1234, formats[0], activation); + } + + /** + * @brief Exercise the process-loopback wrapper with no activation step installed. + * @return True when the wrapper returns no client. + */ + bool process_loopback_wrapper_fails_with_empty_activation() { + process_loopback_activation_t activation; + return !make_process_loopback_audio_client(1234, formats[0], activation); + } + + /** + * @brief Exercise the process-loopback wrapper when client initialization fails. + * @return True when the wrapper returns no client. + */ + bool process_loopback_wrapper_fails_when_initialization_fails() { + process_loopback_activation_t activation = [](std::uint32_t) { + audio_client_t client; + client.reset(new fake_process_loopback_audio_client_t(E_FAIL)); + return client; + }; + return !make_process_loopback_audio_client(1234, formats[0], activation); + } + + /** + * @brief Record a capture PID through the production setter. + * @param process_id PID to record. + * @param creation_time Creation marker to record with the PID. + * @return PID stored on the control. + */ + std::uint32_t recorded_capture_process_id(std::uint32_t process_id, std::uint64_t creation_time) { + audio_control_t control; + control.set_capture_target(audio_capture_intent_e::host_and_client, process_identity_t {process_id, creation_time}); + return control.snapshot_capture_target().process_id; + } + + /** + * @brief Record a capture identity through the production setter. + * + * The baseline is stored verbatim without a PID query, so even a + * fabricated identity for a nonexistent PID round-trips unchanged; only + * validation resolves it to endpoint capture. + * + * @param process_id PID to record. + * @param creation_time Creation marker to record with the PID. + * @return Creation marker stored on the control. + */ + std::uint64_t recorded_capture_creation_time(std::uint32_t process_id, std::uint64_t creation_time) { + audio_control_t control; + control.set_capture_target(audio_capture_intent_e::host_and_client, process_identity_t {process_id, creation_time}); + return control.snapshot_capture_target().identity.creation_time; + } + + /** + * @brief Exercise the pure process-identity comparison with synthetic identities. + * @param recorded_process_id PID recorded with the capture target. + * @param recorded_creation_time Creation time recorded with the capture target. + * @param current_process_id PID queried before activation. + * @param current_creation_time Creation time queried before activation. + * @return True when the current identity is the recorded process. + */ + bool process_identity_matches(std::uint32_t recorded_process_id, std::uint64_t recorded_creation_time, std::uint32_t current_process_id, std::uint64_t current_creation_time) { + return platf::audio::process_identity_matches( + process_identity_t {recorded_process_id, recorded_creation_time}, + process_identity_t {current_process_id, current_creation_time} + ); + } + + /** + * @brief Exercise the pure effective-PID resolution with synthetic identities. + * @param recorded_process_id PID recorded with the capture target. + * @param recorded_creation_time Creation time recorded with the capture target. + * @param current_available Whether a current identity could be queried at all. + * @param current_process_id PID queried before activation. + * @param current_creation_time Creation time queried before activation. + * @return Recorded PID when still valid, or 0 for endpoint capture. + */ + std::uint32_t effective_capture_process_id(std::uint32_t recorded_process_id, std::uint64_t recorded_creation_time, bool current_available, std::uint32_t current_process_id, std::uint64_t current_creation_time) { + std::optional current; + if (current_available) { + current = process_identity_t {current_process_id, current_creation_time}; + } + return platf::audio::effective_capture_process_id( + process_identity_t {recorded_process_id, recorded_creation_time}, + current + ); + } + + /** + * @brief Exercise recorded-target validation through the production control. + * @param process_id PID to record and immediately revalidate. + * @param creation_time Creation marker recorded as the validation baseline. + * @return PID accepted for process loopback, or 0 for endpoint capture. + */ + std::uint32_t validated_capture_target_for_pid(std::uint32_t process_id, std::uint64_t creation_time) { + audio_control_t control; + control.set_capture_target(audio_capture_intent_e::host_and_client, process_identity_t {process_id, creation_time}); + return control.validated_capture_process_id(); + } + + /** + * @brief Exercise the post-activation discard decision with synthetic PIDs. + * @param activated_process_id PID the completed activation was started for. + * @param revalidated_process_id PID revalidation still accepts, or 0 when the target exited or was reused. + * @return True when revalidation still accepts the activated PID. + */ + bool activated_process_target_is_current(std::uint32_t activated_process_id, std::uint32_t revalidated_process_id) { + return platf::audio::activated_process_target_is_current(activated_process_id, revalidated_process_id); + } + + /** + * @brief Set a capture target then conditionally clear it, reporting the stored intent. + * + * @param set_intent Intent recorded by set_capture_target(). + * @param set_pid PID recorded by set_capture_target(). + * @param clear_intent Intent passed to clear_capture_target(). + * @param clear_pid PID passed to clear_capture_target(). + * @return Intent stored on the control after the conditional clear. + */ + audio_capture_intent_e intent_after_conditional_clear(audio_capture_intent_e set_intent, std::uint32_t set_pid, audio_capture_intent_e clear_intent, std::uint32_t clear_pid) { + audio_control_t control; + // The clear contract matches on intent and PID only; the marker is unverifiable here by design. + control.set_capture_target(set_intent, process_identity_t {set_pid, 0}); + control.clear_capture_target(clear_intent, clear_pid); + return control.snapshot_capture_target().intent; + } + + /** + * @brief Set a capture target then conditionally clear it, reporting the stored PID. + * + * @param set_intent Intent recorded by set_capture_target(). + * @param set_pid PID recorded by set_capture_target(). + * @param clear_intent Intent passed to clear_capture_target(). + * @param clear_pid PID passed to clear_capture_target(). + * @return PID stored on the control after the conditional clear. + */ + std::uint32_t pid_after_conditional_clear(audio_capture_intent_e set_intent, std::uint32_t set_pid, audio_capture_intent_e clear_intent, std::uint32_t clear_pid) { + audio_control_t control; + // The clear contract matches on intent and PID only; the marker is unverifiable here by design. + control.set_capture_target(set_intent, process_identity_t {set_pid, 0}); + control.clear_capture_target(clear_intent, clear_pid); + return control.snapshot_capture_target().process_id; + } + + /** + * @brief Record this process as the capture target, conditionally clear it, and report the stored identity. + * + * The current process is the deterministic verifiable target: its PID and + * creation time are read directly from the owned process handle, so the + * recorded identity is nonzero until `on_capture_target_cleared()` runs. + * + * @param matching_clear Whether the clear uses the recorded intent and PID. + * @return Identity creation time stored on the control after the clear. + */ + std::uint64_t identity_creation_time_after_conditional_clear(bool matching_clear) { + audio_control_t control; + const auto process_id = static_cast(GetCurrentProcessId()); + FILETIME creation_time {}; + FILETIME exit_time {}; + FILETIME kernel_time {}; + FILETIME user_time {}; + std::uint64_t combined_creation_time = 0; + if (GetProcessTimes(GetCurrentProcess(), &creation_time, &exit_time, &kernel_time, &user_time)) { + combined_creation_time = (static_cast(creation_time.dwHighDateTime) << 32) | static_cast(creation_time.dwLowDateTime); + } + control.set_capture_target(audio_capture_intent_e::host_and_client, process_identity_t {process_id, combined_creation_time}); + control.clear_capture_target(audio_capture_intent_e::host_and_client, matching_clear ? process_id : process_id + 1); + return control.snapshot_capture_target().identity.creation_time; + } + + /** + * @brief Verify an assigned-sink snapshot stays stable while the shared value changes. + * + * The default-endpoint callback reasserts the snapshot taken at install + * time; this proves later writes cannot mutate a previously taken copy. + * + * @return True when the first snapshot keeps the old sink after a rewrite. + */ + bool assigned_sink_snapshot_is_stable() { + audio_control_t control; + control.capture_sink("sink-a"); + const auto snapshot = control.snapshot_assigned_sink(); + control.capture_sink("sink-b"); + return snapshot == "sink-a" && control.snapshot_assigned_sink() == "sink-b"; + } + + /** + * @brief Hammer the guarded control state from multiple threads. + * + * Exercises capture-target set/clear/snapshot together with assigned-sink + * writes and snapshots. Every snapshot must read one of the written + * values; completing without a data race is the regression pin. + * + * @return True when every snapshot read a consistent value. + */ + bool concurrent_control_access_is_consistent() { + using enum audio_capture_intent_e; + 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(std::format("sink-{}", pid)); + if (control.snapshot_assigned_sink().compare(0, 5, "sink-") != 0) { + consistent.store(false, std::memory_order_relaxed); + } + control.set_capture_target(host_and_client, process_identity_t {pid, pid}); + const auto target = control.snapshot_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); + } + }; + { + std::vector threads; + threads.reserve(4); + for (std::uint32_t pid = 1; pid <= 4; ++pid) { + threads.emplace_back(worker, pid); + } + } + return consistent.load(std::memory_order_relaxed); } /** @@ -1654,6 +3289,23 @@ namespace platf::audio { return static_cast(control.get_sink_device(sink)); } + /** + * @brief Run endpoint lookup against a test-supplied enumerator, reporting match success. + * + * Exercises the production find_device_id() path, including its + * skip-on-failure handling for unreadable entries, without audio hardware. + * + * @param match_name Endpoint name to match across all supported fields. + * @param device_enum Device enumerator supplied by the test. + * @return True when the endpoint resolves to an active device. + */ + bool find_device_matches(const std::wstring &match_name, IMMDeviceEnumerator *device_enum) { + audio_control_t control; + device_enum->AddRef(); + control.device_enum.reset(device_enum); + return static_cast(control.find_device_id(control.match_all_fields(match_name))); + } + /** * @brief Report host and virtual sinks through the production discovery path. * @@ -1670,6 +3322,9 @@ namespace platf::audio { /** * @brief Exercise microphone creation with controlled assigned and configured sinks. * + * Calls through the parameter-bundle overload, so the shared params shape + * is the exercised path on this backend. + * * @param assigned_sink Sink selected by the shared audio context. * @param configured_sink Sink configured by the user. * @param device_enum Device enumerator supplied by the test. @@ -1679,14 +3334,75 @@ namespace platf::audio { audio_control_t control; device_enum->AddRef(); control.device_enum.reset(device_enum); - control.assigned_sink = assigned_sink; + control.capture_sink(assigned_sink); + const microphone_params_t params {nullptr, 2, 48000, 240, false, false}; auto previous_configured_sink = std::exchange(config::audio.sink, configured_sink); - auto microphone = control.microphone(nullptr, 2, 48000, 240, false, false); + auto microphone = control.microphone(params); config::audio.sink = std::move(previous_configured_sink); return static_cast(microphone); } + /** + * @brief Exercise microphone() end to end with a recorded capture target and a failing test activator. + * + * Records the given capture target through the production setter, installs + * a counting activator that returns no client, and runs the production + * microphone() via the parameter-bundle overload. A valid target proves + * the loopback-attempt branch ran when the activator was invoked; the + * failing activator then proves the activation-failure fallback by + * resolving the endpoint path afterwards. The current process identity is + * the deterministic valid target: its PID and creation time are read from + * the owned handle, while PID 0, an unverifiable marker, a mismatched + * marker, or a mismatched intent must never attempt loopback. + * + * @param probe Capture probe: sinks, intent, identity, enumerator, and keep-default flag in; attempt evidence out. + * @return True when process-loopback activation was attempted. + */ + bool microphone_attempts_loopback_for_target(microphone_loopback_probe_t &probe) { + audio_control_t control; + probe.device_enum->AddRef(); + control.device_enum.reset(probe.device_enum); + control.capture_sink(probe.assigned_sink); + control.set_capture_target(probe.intent, process_identity_t {probe.process_id, probe.creation_time}); + control.set_test_loopback_activator([&probe](std::uint32_t attempted_pid, const format_t &) -> audio_client_t { + probe.attempted_process_id = attempted_pid; + return nullptr; + }); + + probe.attempted_process_id = 0; + const microphone_params_t params {nullptr, 2, 48000, 240, false, false}; + auto previous_configured_sink = std::exchange(config::audio.sink, probe.configured_sink); + auto previous_keep_default = std::exchange(config::audio.keep_default_sink, probe.keep_default); + auto microphone = control.microphone(params); + config::audio.sink = std::move(previous_configured_sink); + config::audio.keep_default_sink = previous_keep_default; + probe.microphone_returned = static_cast(microphone); + return probe.attempted_process_id != 0; + } + + /** + * @brief Report whether endpoint capture follows the Windows default device. + * + * Exercises the production should_follow_default_device() decision without + * requiring microphone initialization (which builds its own enumerator and + * needs audio hardware), so the blank keep-default follow behavior is + * pinned directly instead of via untouched-enumerator call counts. + * + * @param configured_sink Configured audio sink tested with, possibly empty. + * @param keep_default keep_default_sink value tested with. + * @return True when endpoint capture follows the default endpoint. + */ + bool microphone_follows_default_device(const std::string &configured_sink, bool keep_default) { + audio_control_t control; + auto previous_configured_sink = std::exchange(config::audio.sink, configured_sink); + auto previous_keep_default = std::exchange(config::audio.keep_default_sink, keep_default); + const bool follows = control.should_follow_default_device(); + config::audio.sink = std::move(previous_configured_sink); + config::audio.keep_default_sink = previous_keep_default; + return follows; + } + /** * @brief Select a default or explicit capture endpoint through the production selection path. * diff --git a/src/platform/windows/audio_tests.h b/src/platform/windows/audio_tests.h new file mode 100644 index 00000000000..b9533c7cce8 --- /dev/null +++ b/src/platform/windows/audio_tests.h @@ -0,0 +1,59 @@ +/** + * @file src/platform/windows/audio_tests.h + * @brief Test-only seams for Windows audio capture. + * + * Included only from SUNSHINE_TESTS translation units: the backend + * implementation and the Windows audio unit tests. Production builds never + * include this header. + */ +#pragma once + +// standard includes +#include +#include + +// platform includes +#include + +// local includes +#include "src/platform/common.h" + +namespace platf::audio::tests { + /** + * @brief Input and output bundle for microphone_attempts_loopback_for_target(). + * + * The input fields describe the capture the test wants to exercise; the + * seam fills the output fields with the attempt evidence. Call sites use + * designated initializers so each input is named and outputs default to + * "no attempt". + */ + struct microphone_loopback_probe_t { + std::string assigned_sink; ///< Sink selected by the shared audio context. + std::string configured_sink; ///< Sink configured by the user, possibly empty. + platf::audio_capture_intent_e intent {platf::audio_capture_intent_e::client_only}; ///< Capture intent recorded for the next microphone() call. + std::uint32_t process_id {}; ///< PID recorded for the next microphone() call, or 0 for endpoint capture. + std::uint64_t creation_time {}; ///< Creation marker recorded with the PID, or 0 for an unverifiable baseline. + IMMDeviceEnumerator *device_enum {}; ///< Device enumerator supplied by the test. + bool keep_default {}; ///< keep_default_sink value tested with. + std::uint32_t attempted_process_id {}; ///< Receives the PID passed to the activator, or 0 when loopback was never attempted. + bool microphone_returned {}; ///< Receives whether microphone() returned a microphone. + }; + + /** + * @brief Exercise microphone() end to end with a recorded capture target and a failing test activator. + * + * Records the given capture target through the production setter, installs + * a counting activator that returns no client, and runs the production + * microphone() via the parameter-bundle overload. A valid target proves + * the loopback-attempt branch ran when the activator was invoked; the + * failing activator then proves the activation-failure fallback by + * resolving the endpoint path afterwards. The current process identity is + * the deterministic valid target: its PID and creation time are read from + * the owned handle, while PID 0, an unverifiable marker, a mismatched + * marker, or a mismatched intent must never attempt loopback. + * + * @param probe Capture probe: sinks, intent, identity, enumerator, and keep-default flag in; attempt evidence out. + * @return True when process-loopback activation was attempted. + */ + bool microphone_attempts_loopback_for_target(microphone_loopback_probe_t &probe); +} // namespace platf::audio::tests diff --git a/src/stream.cpp b/src/stream.cpp index a222b4045e2..b28806ea5f3 100644 --- a/src/stream.cpp +++ b/src/stream.cpp @@ -2254,7 +2254,7 @@ namespace stream { session->audio.qos = platf::enable_socket_qos(ref->audio_sock.native_handle(), address, session->audio.peer.port(), platf::qos_data_type_e::audio, config::stream.dscp_tagging && session->config.audioQosType != 0); BOOST_LOG(debug) << "Start capturing Audio"sv; - audio::capture(session->mail, session->config.audio, session); + audio::capture(session->mail, session->config.audio, session, proc::app_process_identity_provider(proc::proc)); } namespace session { diff --git a/tests/unit/platform/windows/test_audio.cpp b/tests/unit/platform/windows/test_audio.cpp index f90d58951bb..7dec032e808 100644 --- a/tests/unit/platform/windows/test_audio.cpp +++ b/tests/unit/platform/windows/test_audio.cpp @@ -1,25 +1,39 @@ /** * @file tests/unit/platform/windows/test_audio.cpp - * @brief Tests for Windows audio sink selection and endpoint-change handling. + * @brief Tests for Windows audio capture: sink selection, capture targets, process loopback, and endpoint-change handling. + * + * The microphone seams below drive the backend through the shared + * parameter-bundle overload, so every microphone_* case also pins the params + * shape end to end on this backend. */ // test includes #include "../../../tests_common.h" #ifdef _WIN32 + // test includes + #include "src/platform/windows/audio_tests.h" + // standard includes #include #include #include #include #include + #include + #include #include #include + #include // platform includes #include #include #include + #if __has_include() + #include + #define SUNSHINE_TEST_HAS_AUDIOCLIENT_ACTIVATION_PARAMS 1 + #endif // local includes #include "src/config.h" @@ -38,8 +52,34 @@ namespace platf::audio::tests { 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 microphone_follows_default_device(const std::string &configured_sink, bool keep_default); 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); + bool use_process_loopback(std::uint32_t process_id, platf::audio_capture_intent_e intent); + bool process_loopback_fails_with_null_activator(); + bool process_loopback_wrapper_succeeds_with_fake_activation(); + bool process_loopback_wrapper_fails_with_null_activation(); + bool process_loopback_wrapper_fails_with_empty_activation(); + bool process_loopback_wrapper_fails_when_initialization_fails(); + std::uint32_t recorded_capture_process_id(std::uint32_t process_id, std::uint64_t creation_time); + std::uint64_t recorded_capture_creation_time(std::uint32_t process_id, std::uint64_t creation_time); + bool process_identity_matches(std::uint32_t recorded_process_id, std::uint64_t recorded_creation_time, std::uint32_t current_process_id, std::uint64_t current_creation_time); + std::uint32_t effective_capture_process_id(std::uint32_t recorded_process_id, std::uint64_t recorded_creation_time, bool current_available, std::uint32_t current_process_id, std::uint64_t current_creation_time); + std::uint32_t validated_capture_target_for_pid(std::uint32_t process_id, std::uint64_t creation_time); + platf::audio_capture_intent_e intent_after_conditional_clear(platf::audio_capture_intent_e set_intent, std::uint32_t set_pid, platf::audio_capture_intent_e clear_intent, std::uint32_t clear_pid); + std::uint32_t pid_after_conditional_clear(platf::audio_capture_intent_e set_intent, std::uint32_t set_pid, platf::audio_capture_intent_e clear_intent, std::uint32_t clear_pid); + std::uint64_t identity_creation_time_after_conditional_clear(bool matching_clear); + bool assigned_sink_snapshot_is_stable(); + bool concurrent_control_access_is_consistent(); + bool find_device_matches(const std::wstring &match_name, IMMDeviceEnumerator *device_enum); + bool activated_process_target_is_current(std::uint32_t activated_process_id, std::uint32_t revalidated_process_id); + #ifdef SUNSHINE_TEST_HAS_AUDIOCLIENT_ACTIVATION_PARAMS + AUDIOCLIENT_ACTIVATION_PARAMS make_process_loopback_activation_params(std::uint32_t process_id); + bool activation_blob_holds_heap_copy(std::uint32_t process_id); + #endif + #if defined(SUNSHINE_TEST_HAS_AUDIOCLIENT_ACTIVATION_PARAMS) && defined(VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK) + int process_loopback_completion_after_timeout_is_discarded(); + #endif } // namespace platf::audio::tests namespace { @@ -123,12 +163,20 @@ namespace { } HRESULT STDMETHODCALLTYPE OpenPropertyStore(DWORD, IPropertyStore **property_store) override { + if (FAILED(open_store_status)) { + return open_store_status; + } + properties.AddRef(); *property_store = &properties; return S_OK; } HRESULT STDMETHODCALLTYPE GetId(LPWSTR *device_id) override { + if (FAILED(get_id_status)) { + return get_id_status; + } + const auto byte_count = (id.size() + 1) * sizeof(wchar_t); *device_id = static_cast(CoTaskMemAlloc(byte_count)); if (!*device_id) { @@ -151,13 +199,15 @@ namespace { std::wstring id; fake_property_store_t properties; HRESULT state_status = S_OK; + HRESULT get_id_status = S_OK; + HRESULT open_store_status = S_OK; DWORD state = DEVICE_STATE_ACTIVE; }; class fake_device_collection_t final: public IMMDeviceCollection { public: explicit fake_device_collection_t(fake_device_t &device): - device {device} { + devices {&device} { } HRESULT STDMETHODCALLTYPE QueryInterface(REFIID, void **object) override { // NOSONAR(cpp:S5008): required by the Windows COM interface @@ -174,21 +224,31 @@ namespace { } HRESULT STDMETHODCALLTYPE GetCount(UINT *device_count) override { - *device_count = 1; + if (FAILED(count_status)) { + return count_status; + } + + *device_count = static_cast(devices.size()); return S_OK; } HRESULT STDMETHODCALLTYPE Item(UINT index, IMMDevice **item) override { - if (index != 0) { + if (FAILED(item_status)) { + return item_status; + } + + if (index >= devices.size()) { return E_INVALIDARG; } - device.AddRef(); - *item = &device; + devices[index]->AddRef(); + *item = devices[index]; return S_OK; } - fake_device_t &device; + std::vector devices; + HRESULT count_status = S_OK; + HRESULT item_status = S_OK; }; class fake_device_enumerator_t final: public IMMDeviceEnumerator { @@ -254,8 +314,14 @@ namespace { return S_OK; } + void add_device(std::unique_ptr extra_device) { + collection.devices.push_back(extra_device.get()); + extra_devices.push_back(std::move(extra_device)); + } + fake_device_t device; fake_device_collection_t collection; + std::vector> extra_devices; HRESULT enumeration_status = S_OK; HRESULT get_device_status = S_OK; HRESULT get_default_status = S_OK; @@ -263,6 +329,27 @@ namespace { int get_default_device_calls = 0; std::wstring last_requested_id; }; + + /** + * @brief Read the test process creation marker from the owned process handle. + * + * Mirrors the production handoff: the marker is queried from an owned handle + * rather than by PID, so it always names this process. Tests pass it as the + * recorded baseline for the deterministic valid target, or perturb it to + * model a PID reused by a different process. + * + * @return Combined creation marker, or 0 when the query fails. + */ + std::uint64_t current_process_creation_time() { + FILETIME creation_time {}; + FILETIME exit_time {}; + FILETIME kernel_time {}; + FILETIME user_time {}; + if (!GetProcessTimes(GetCurrentProcess(), &creation_time, &exit_time, &kernel_time, &user_time)) { + return 0; + } + return (static_cast(creation_time.dwHighDateTime) << 32) | static_cast(creation_time.dwLowDateTime); + } } // namespace TEST(WindowsAudioTest, PreservesVirtualSpeakerFormatPreferenceAndChannelMasks) { @@ -437,6 +524,43 @@ TEST_F(WindowsKeepDefaultTest, AssignedSinkWinsOverConfiguredSink) { EXPECT_EQ(enumerator.get_default_device_calls, 0); } +TEST_F(WindowsKeepDefaultTest, ExplicitSinkPinStaysPinned) { + fake_device_enumerator_t enumerator {L"configured-id"}; + EXPECT_FALSE(platf::audio::tests::microphone_available("configured-id", "configured-id", &enumerator)); + EXPECT_EQ(enumerator.get_device_calls, 1); + EXPECT_EQ(enumerator.last_requested_id, L"configured-id"); + EXPECT_EQ(enumerator.get_default_device_calls, 0); +} + +TEST_F(WindowsKeepDefaultTest, BlankConfigCaptureFollowsDefaultDespiteAssignedHostSink) { + // The assigned host sink is only a startup snapshot: with keep-default and a + // blank sink the endpoint decision follows the Windows default instead of + // resolving that snapshot. microphone() builds its own enumerator on that + // path, so call counts on an injected enumerator cannot pin this behavior; + // the follow decision below does. + EXPECT_TRUE(platf::audio::tests::microphone_follows_default_device({}, true)); + EXPECT_FALSE(platf::audio::tests::microphone_follows_default_device("configured-id", true)); + EXPECT_FALSE(platf::audio::tests::microphone_follows_default_device({}, false)); + + // A render-default change must rearm a following capture. + int callback_count = 0; + EXPECT_EQ( + platf::audio::tests::simulate_default_device_change(true, true, true, callback_count), + platf::capture_e::reinit + ); + EXPECT_EQ(callback_count, 1); +} + +TEST_F(WindowsKeepDefaultTest, VirtualAssignedCaptureDoesNotFollowDefault) { + config::audio.keep_default_sink = false; + fake_device_enumerator_t enumerator {L"endpoint-id"}; + EXPECT_FALSE(platf::audio::tests::microphone_available("virtual-Stereoendpoint-id", {}, &enumerator)); + EXPECT_EQ(enumerator.get_device_calls, 1); + EXPECT_EQ(enumerator.last_requested_id, L"endpoint-id"); + EXPECT_EQ(enumerator.get_default_device_calls, 0); + EXPECT_TRUE(platf::audio::tests::installs_default_callback("virtual-Stereoendpoint-id", false)); +} + TEST_F(WindowsKeepDefaultTest, MissingSinkDoesNotFallBackToDefault) { fake_device_enumerator_t enumerator {L"endpoint-id"}; EXPECT_FALSE(platf::audio::tests::microphone_available({}, "missing-id", &enumerator)); @@ -572,6 +696,33 @@ TEST(WindowsAudioTest, RejectsUnavailableResolvedEndpoints) { EXPECT_FALSE(platf::audio::tests::sink_device_available("virtual-Stereoendpoint-id", &inactive_enumerator)); } +TEST(WindowsAudioTest, EndpointLookupSkipsUnreadableEntries) { + fake_device_enumerator_t enumerator {L"broken-id"}; + enumerator.device.get_id_status = E_FAIL; + enumerator.add_device(std::make_unique(L"endpoint-id", L"Friendly Endpoint")); + + EXPECT_TRUE(platf::audio::tests::find_device_matches(L"endpoint-id", &enumerator)); + EXPECT_TRUE(platf::audio::tests::find_device_matches(L"Friendly Endpoint", &enumerator)); +} + +TEST(WindowsAudioTest, EndpointLookupFailsClosedWhenEntriesAreUnreadable) { + fake_device_enumerator_t id_failure {L"endpoint-id"}; + id_failure.device.get_id_status = E_FAIL; + EXPECT_FALSE(platf::audio::tests::find_device_matches(L"endpoint-id", &id_failure)); + + fake_device_enumerator_t store_failure {L"endpoint-id"}; + store_failure.device.open_store_status = E_FAIL; + EXPECT_FALSE(platf::audio::tests::find_device_matches(L"endpoint-id", &store_failure)); + + fake_device_enumerator_t count_failure {L"endpoint-id"}; + count_failure.collection.count_status = E_FAIL; + EXPECT_FALSE(platf::audio::tests::find_device_matches(L"endpoint-id", &count_failure)); + + fake_device_enumerator_t item_failure {L"endpoint-id"}; + item_failure.collection.item_status = E_FAIL; + EXPECT_FALSE(platf::audio::tests::find_device_matches(L"endpoint-id", &item_failure)); +} + TEST(WindowsAudioTest, DefaultFollowingCaptureReinitializesAfterRenderEndpointChange) { int callback_count = 0; @@ -624,6 +775,349 @@ TEST(WindowsAudioTest, KeepDefaultModeInstallsNoReassertionCallback) { EXPECT_FALSE(platf::audio::tests::installs_default_callback("endpoint-id", false)); } +TEST(WindowsAudioTest, ProcessLoopbackRequiresHostAndClientIntentAndPid) { + using intent = platf::audio_capture_intent_e; + // No PID means endpoint capture regardless of intent. + EXPECT_FALSE(platf::audio::tests::use_process_loopback(0, intent::client_only)); + EXPECT_FALSE(platf::audio::tests::use_process_loopback(0, intent::host_and_client)); + EXPECT_FALSE(platf::audio::tests::use_process_loopback(0, intent::pinned_sink)); + // Quiet streaming with a PID must not bypass the silent virtual endpoint. + EXPECT_FALSE(platf::audio::tests::use_process_loopback(1234, intent::client_only)); + // A pinned sink never selects process capture; the shared guard maps a + // configured sink to this intent and records PID 0, so the backend needs no + // separate sink check (see AudioCaptureIntentTest and + // AudioCaptureProcessTreeTest in tests/unit/test_audio.cpp). + EXPECT_FALSE(platf::audio::tests::use_process_loopback(1234, intent::pinned_sink)); + // The only true row: Play on this PC too with a PID. + EXPECT_TRUE(platf::audio::tests::use_process_loopback(1234, intent::host_and_client)); +} + +TEST(WindowsAudioTest, CaptureProcessSetterStoresPid) { + EXPECT_EQ(platf::audio::tests::recorded_capture_process_id(1234, 100), 1234u); + EXPECT_EQ(platf::audio::tests::recorded_capture_process_id(0, 0), 0u); +} + +TEST(WindowsAudioTest, CaptureProcessSetterStoresIdentityVerbatim) { + // The baseline is stored without a PID query, so even a fabricated identity + // for a nonexistent PID round-trips unchanged; only validation resolves it + // to endpoint capture. A setter that re-queried by PID would record a zero + // marker for 42424242 instead. + EXPECT_EQ(platf::audio::tests::recorded_capture_creation_time(42424242, 0xBEEFCAFEu), 0xBEEFCAFEu); + EXPECT_EQ(platf::audio::tests::recorded_capture_process_id(42424242, 0xBEEFCAFEu), 42424242u); + EXPECT_EQ(platf::audio::tests::recorded_capture_creation_time(0, 0xBEEFCAFEu), 0u); +} + +TEST(WindowsAudioTest, MicrophoneAttemptsLoopbackForCurrentProcessTarget) { + fake_device_enumerator_t enumerator {L"endpoint-id"}; + const auto current_process_id = static_cast(::GetCurrentProcessId()); + ASSERT_NE(current_process_id, 0u); + const auto creation_time = current_process_creation_time(); + ASSERT_NE(creation_time, 0u); + + platf::audio::tests::microphone_loopback_probe_t probe { + .assigned_sink = "endpoint-id", + .configured_sink = {}, + .intent = platf::audio_capture_intent_e::host_and_client, + .process_id = current_process_id, + .creation_time = creation_time, + .device_enum = &enumerator, + .keep_default = false, + }; + EXPECT_TRUE(platf::audio::tests::microphone_attempts_loopback_for_target(probe)); + EXPECT_EQ(probe.attempted_process_id, current_process_id); +} + +TEST(WindowsAudioTest, MicrophoneFallsBackToEndpointWhenActivationFails) { + fake_device_enumerator_t enumerator {L"endpoint-id"}; + const auto current_process_id = static_cast(::GetCurrentProcessId()); + ASSERT_NE(current_process_id, 0u); + const auto creation_time = current_process_creation_time(); + ASSERT_NE(creation_time, 0u); + + platf::audio::tests::microphone_loopback_probe_t probe { + .assigned_sink = "endpoint-id", + .configured_sink = {}, + .intent = platf::audio_capture_intent_e::host_and_client, + .process_id = current_process_id, + .creation_time = creation_time, + .device_enum = &enumerator, + .keep_default = false, + }; + EXPECT_TRUE(platf::audio::tests::microphone_attempts_loopback_for_target(probe)); + EXPECT_EQ(probe.attempted_process_id, current_process_id); + // The failing activator falls back to endpoint capture: the assigned sink is + // resolved through the injected enumerator, and endpoint initialization + // fails without audio hardware. + EXPECT_EQ(enumerator.get_device_calls, 1); + EXPECT_EQ(enumerator.last_requested_id, L"endpoint-id"); + EXPECT_FALSE(probe.microphone_returned); +} + +TEST(WindowsAudioTest, MicrophoneSkipsLoopbackWithoutCaptureTarget) { + fake_device_enumerator_t enumerator {L"endpoint-id"}; + + platf::audio::tests::microphone_loopback_probe_t probe { + .assigned_sink = "endpoint-id", + .configured_sink = {}, + .intent = platf::audio_capture_intent_e::host_and_client, + .process_id = 0, + .device_enum = &enumerator, + .keep_default = false, + }; + EXPECT_FALSE(platf::audio::tests::microphone_attempts_loopback_for_target(probe)); + EXPECT_EQ(probe.attempted_process_id, 0u); + EXPECT_EQ(enumerator.get_device_calls, 1); + EXPECT_FALSE(probe.microphone_returned); +} + +TEST(WindowsAudioTest, MicrophoneSkipsLoopbackForSilentIntent) { + fake_device_enumerator_t enumerator {L"endpoint-id"}; + const auto current_process_id = static_cast(::GetCurrentProcessId()); + ASSERT_NE(current_process_id, 0u); + const auto creation_time = current_process_creation_time(); + ASSERT_NE(creation_time, 0u); + + platf::audio::tests::microphone_loopback_probe_t probe { + .assigned_sink = "endpoint-id", + .configured_sink = {}, + .intent = platf::audio_capture_intent_e::client_only, + .process_id = current_process_id, + .creation_time = creation_time, + .device_enum = &enumerator, + .keep_default = false, + }; + EXPECT_FALSE(platf::audio::tests::microphone_attempts_loopback_for_target(probe)); + EXPECT_EQ(probe.attempted_process_id, 0u); + EXPECT_EQ(enumerator.get_device_calls, 1); + EXPECT_FALSE(probe.microphone_returned); +} + +TEST(WindowsAudioTest, MicrophoneAttemptsLoopbackForBlankKeepDefaultTarget) { + fake_device_enumerator_t enumerator {L"endpoint-id"}; + const auto current_process_id = static_cast(::GetCurrentProcessId()); + ASSERT_NE(current_process_id, 0u); + const auto creation_time = current_process_creation_time(); + ASSERT_NE(creation_time, 0u); + + platf::audio::tests::microphone_loopback_probe_t probe { + .assigned_sink = "endpoint-id", + .configured_sink = {}, + .intent = platf::audio_capture_intent_e::host_and_client, + .process_id = current_process_id, + .creation_time = creation_time, + .device_enum = &enumerator, + .keep_default = true, + }; + EXPECT_TRUE(platf::audio::tests::microphone_attempts_loopback_for_target(probe)); + EXPECT_EQ(probe.attempted_process_id, current_process_id); + // The follow-default fallback builds its own enumerator, so the injected one stays untouched. + EXPECT_EQ(enumerator.get_device_calls, 0); +} + +TEST(WindowsAudioTest, MicrophoneSkipsLoopbackForPinnedIntent) { + fake_device_enumerator_t enumerator {L"endpoint-id"}; + const auto current_process_id = static_cast(::GetCurrentProcessId()); + ASSERT_NE(current_process_id, 0u); + const auto creation_time = current_process_creation_time(); + ASSERT_NE(creation_time, 0u); + + // Even with a live PID, a pinned sink stays pinned: the backend never + // attempts loopback for pinned intent, independent of the guard recording + // PID 0 for such sessions upstream. + platf::audio::tests::microphone_loopback_probe_t probe { + .assigned_sink = "endpoint-id", + .configured_sink = "endpoint-id", + .intent = platf::audio_capture_intent_e::pinned_sink, + .process_id = current_process_id, + .creation_time = creation_time, + .device_enum = &enumerator, + .keep_default = true, + }; + EXPECT_FALSE(platf::audio::tests::microphone_attempts_loopback_for_target(probe)); + EXPECT_EQ(probe.attempted_process_id, 0u); + EXPECT_EQ(enumerator.get_device_calls, 1); + EXPECT_EQ(enumerator.last_requested_id, L"endpoint-id"); + EXPECT_FALSE(probe.microphone_returned); +} + +TEST(WindowsAudioTest, MicrophoneLoopbackDecisionIgnoresConfiguredSink) { + fake_device_enumerator_t enumerator {L"endpoint-id"}; + const auto current_process_id = static_cast(::GetCurrentProcessId()); + ASSERT_NE(current_process_id, 0u); + const auto creation_time = current_process_creation_time(); + ASSERT_NE(creation_time, 0u); + + // The backend decides on intent and revalidated PID only: a configured sink + // no longer blocks the attempt here because the shared guard already maps a + // configured sink to pinned intent (and PID 0) before the backend runs. + platf::audio::tests::microphone_loopback_probe_t probe { + .assigned_sink = "endpoint-id", + .configured_sink = "other-sink", + .intent = platf::audio_capture_intent_e::host_and_client, + .process_id = current_process_id, + .creation_time = creation_time, + .device_enum = &enumerator, + .keep_default = false, + }; + EXPECT_TRUE(platf::audio::tests::microphone_attempts_loopback_for_target(probe)); + EXPECT_EQ(probe.attempted_process_id, current_process_id); + // The failing activator falls back to endpoint capture against the assigned sink. + EXPECT_EQ(enumerator.get_device_calls, 1); + EXPECT_EQ(enumerator.last_requested_id, L"endpoint-id"); + EXPECT_FALSE(probe.microphone_returned); +} + +TEST(WindowsAudioTest, MicrophoneRejectsStaleIdentityAfterPidReuse) { + fake_device_enumerator_t enumerator {L"endpoint-id"}; + const auto current_process_id = static_cast(::GetCurrentProcessId()); + ASSERT_NE(current_process_id, 0u); + const auto creation_time = current_process_creation_time(); + ASSERT_NE(creation_time, 0u); + + // The recorded baseline names the original occupant; the live PID now names + // a different process (same PID, different marker). Validation must reject + // the stale baseline so no loopback activation targets the replacement, and + // endpoint fallback must resolve through the assigned sink instead. + platf::audio::tests::microphone_loopback_probe_t probe { + .assigned_sink = "endpoint-id", + .configured_sink = {}, + .intent = platf::audio_capture_intent_e::host_and_client, + .process_id = current_process_id, + .creation_time = creation_time + 1, + .device_enum = &enumerator, + .keep_default = false, + }; + EXPECT_FALSE(platf::audio::tests::microphone_attempts_loopback_for_target(probe)); + EXPECT_EQ(probe.attempted_process_id, 0u); + EXPECT_EQ(enumerator.get_device_calls, 1); + EXPECT_EQ(enumerator.last_requested_id, L"endpoint-id"); + EXPECT_FALSE(probe.microphone_returned); +} + +TEST(WindowsAudioTest, ConditionalClearResetsMatchingTarget) { + using intent = platf::audio_capture_intent_e; + EXPECT_EQ(platf::audio::tests::pid_after_conditional_clear(intent::host_and_client, 1234, intent::host_and_client, 1234), 0u); + EXPECT_EQ(platf::audio::tests::intent_after_conditional_clear(intent::host_and_client, 1234, intent::host_and_client, 1234), intent::client_only); +} + +TEST(WindowsAudioTest, ConditionalClearPreservesMismatchedTarget) { + using intent = platf::audio_capture_intent_e; + // A survivor that recorded a different PID keeps its target. + EXPECT_EQ(platf::audio::tests::pid_after_conditional_clear(intent::host_and_client, 1234, intent::host_and_client, 5678), 1234u); + EXPECT_EQ(platf::audio::tests::intent_after_conditional_clear(intent::host_and_client, 1234, intent::host_and_client, 5678), intent::host_and_client); + // A survivor that recorded a different intent keeps its target. + EXPECT_EQ(platf::audio::tests::pid_after_conditional_clear(intent::host_and_client, 1234, intent::client_only, 1234), 1234u); + EXPECT_EQ(platf::audio::tests::intent_after_conditional_clear(intent::host_and_client, 1234, intent::client_only, 1234), intent::host_and_client); + // An endpoint clear cannot wipe a process target and vice versa. + EXPECT_EQ(platf::audio::tests::pid_after_conditional_clear(intent::host_and_client, 1234, intent::host_and_client, 0), 1234u); + EXPECT_EQ(platf::audio::tests::pid_after_conditional_clear(intent::client_only, 0, intent::host_and_client, 1234), 0u); + EXPECT_EQ(platf::audio::tests::intent_after_conditional_clear(intent::client_only, 0, intent::host_and_client, 1234), intent::client_only); +} + +TEST(WindowsAudioTest, ConditionalClearResetsRecordedIdentity) { + // A matching clear runs on_capture_target_cleared(), resetting the paired + // creation-time identity; a mismatched clear must preserve it. + EXPECT_EQ(platf::audio::tests::identity_creation_time_after_conditional_clear(true), 0u); + EXPECT_NE(platf::audio::tests::identity_creation_time_after_conditional_clear(false), 0u); +} + +TEST(WindowsAudioTest, AssignedSinkSnapshotStaysStableAcrossRewrite) { + EXPECT_TRUE(platf::audio::tests::assigned_sink_snapshot_is_stable()); +} + +TEST(WindowsAudioTest, ConcurrentControlAccessStaysConsistent) { + EXPECT_TRUE(platf::audio::tests::concurrent_control_access_is_consistent()); +} + +TEST(WindowsAudioTest, ProcessIdentityAcceptsSameIdentity) { + EXPECT_TRUE(platf::audio::tests::process_identity_matches(1234, 100, 1234, 100)); + EXPECT_EQ(platf::audio::tests::effective_capture_process_id(1234, 100, true, 1234, 100), 1234u); +} + +TEST(WindowsAudioTest, ProcessIdentityRejectsDifferentCreationTime) { + // Same PID with a different creation time is a reused PID, not the recorded process. + EXPECT_FALSE(platf::audio::tests::process_identity_matches(1234, 100, 1234, 200)); + EXPECT_EQ(platf::audio::tests::effective_capture_process_id(1234, 100, true, 1234, 200), 0u); +} + +TEST(WindowsAudioTest, ProcessIdentityRejectsZeroPid) { + EXPECT_FALSE(platf::audio::tests::process_identity_matches(0, 0, 0, 0)); + EXPECT_FALSE(platf::audio::tests::process_identity_matches(0, 100, 0, 100)); + EXPECT_EQ(platf::audio::tests::effective_capture_process_id(0, 0, true, 0, 0), 0u); + EXPECT_EQ(platf::audio::tests::validated_capture_target_for_pid(0, 0), 0u); +} + +TEST(WindowsAudioTest, ProcessIdentityRejectsDifferentPidAndMissingCreationTime) { + EXPECT_FALSE(platf::audio::tests::process_identity_matches(1234, 100, 5678, 100)); + EXPECT_FALSE(platf::audio::tests::process_identity_matches(1234, 0, 1234, 0)); + EXPECT_EQ(platf::audio::tests::effective_capture_process_id(1234, 0, true, 1234, 0), 0u); +} + +TEST(WindowsAudioTest, ProcessIdentityRejectsExitedOrUnavailableProcess) { + // No current identity models an exited process or a failed OpenProcess/GetProcessTimes query. + EXPECT_EQ(platf::audio::tests::effective_capture_process_id(1234, 100, false, 1234, 100), 0u); + EXPECT_EQ(platf::audio::tests::effective_capture_process_id(1234, 100, false, 0, 0), 0u); +} + +TEST(WindowsAudioTest, ValidatedCaptureTargetAcceptsCurrentProcessAndRejectsUnavailablePid) { + const auto current_process_id = static_cast(::GetCurrentProcessId()); + ASSERT_NE(current_process_id, 0u); + const auto creation_time = current_process_creation_time(); + ASSERT_NE(creation_time, 0u); + EXPECT_EQ(platf::audio::tests::validated_capture_target_for_pid(current_process_id, creation_time), current_process_id); + EXPECT_EQ(platf::audio::tests::validated_capture_target_for_pid(0xFFFFFFFFu, 100), 0u); + // A live PID with a stale marker models reuse: the original process exited + // and its PID now names a different process, so validation must reject it. + EXPECT_EQ(platf::audio::tests::validated_capture_target_for_pid(current_process_id, creation_time + 1), 0u); +} + +TEST(WindowsAudioTest, ActivatedProcessTargetSurvivesOnlyMatchingRevalidation) { + EXPECT_TRUE(platf::audio::tests::activated_process_target_is_current(1234, 1234)); + EXPECT_FALSE(platf::audio::tests::activated_process_target_is_current(1234, 0)); + EXPECT_FALSE(platf::audio::tests::activated_process_target_is_current(1234, 5678)); + EXPECT_FALSE(platf::audio::tests::activated_process_target_is_current(0, 0)); + EXPECT_FALSE(platf::audio::tests::activated_process_target_is_current(0, 1234)); +} + +TEST(WindowsAudioTest, ProcessLoopbackFailsWithNullActivator) { + EXPECT_TRUE(platf::audio::tests::process_loopback_fails_with_null_activator()); +} + +TEST(WindowsAudioTest, ProcessLoopbackWrapperSucceedsWithFakeActivation) { + EXPECT_TRUE(platf::audio::tests::process_loopback_wrapper_succeeds_with_fake_activation()); +} + +TEST(WindowsAudioTest, ProcessLoopbackWrapperFailsWithNullActivation) { + EXPECT_TRUE(platf::audio::tests::process_loopback_wrapper_fails_with_null_activation()); +} + +TEST(WindowsAudioTest, ProcessLoopbackWrapperFailsWithEmptyActivation) { + EXPECT_TRUE(platf::audio::tests::process_loopback_wrapper_fails_with_empty_activation()); +} + +TEST(WindowsAudioTest, ProcessLoopbackWrapperFailsWhenInitializationFails) { + EXPECT_TRUE(platf::audio::tests::process_loopback_wrapper_fails_when_initialization_fails()); +} + + #ifdef SUNSHINE_TEST_HAS_AUDIOCLIENT_ACTIVATION_PARAMS +TEST(WindowsAudioTest, ProcessLoopbackActivationParamsIncludeProcessTree) { + const auto params = platf::audio::tests::make_process_loopback_activation_params(1234); + EXPECT_EQ(params.ActivationType, AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK); + EXPECT_EQ(params.ProcessLoopbackParams.TargetProcessId, 1234u); + EXPECT_EQ(params.ProcessLoopbackParams.ProcessLoopbackMode, PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE); +} + +TEST(WindowsAudioTest, ProcessLoopbackActivationBlobIsHeapOwnedAndClearable) { + EXPECT_TRUE(platf::audio::tests::activation_blob_holds_heap_copy(1234)); +} + #endif + + #if defined(SUNSHINE_TEST_HAS_AUDIOCLIENT_ACTIVATION_PARAMS) && defined(VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK) +TEST(WindowsAudioTest, ProcessLoopbackCompletionAfterTimeoutIsDiscarded) { + EXPECT_EQ(platf::audio::tests::process_loopback_completion_after_timeout_is_discarded(), 0); +} + #endif + TEST(WindowsAudioTest, HandsOffModeSkipsDefaultResetAndDriverInstall) { EXPECT_TRUE(platf::audio::tests::resets_default_device(false)); EXPECT_FALSE(platf::audio::tests::resets_default_device(true)); diff --git a/tests/unit/test_audio.cpp b/tests/unit/test_audio.cpp index a7bd040b709..896bdba720a 100644 --- a/tests/unit/test_audio.cpp +++ b/tests/unit/test_audio.cpp @@ -7,10 +7,12 @@ #include "../tests_common.h" // standard includes +#include #include #include #include #include +#include #include #include #include @@ -251,6 +253,22 @@ TEST(AudioCaptureIntentTest, ResolvesIntentFromConfig) { EXPECT_EQ(resolve_audio_capture_intent(true, "eq-sink"), intent::pinned_sink); } +/** + * @brief Process capture must keep silence first and let a pinned sink win. + */ +TEST(AudioCaptureProcessTreeTest, SelectsProcessTreeFromIntentSupportAndPid) { + using intent = platf::audio_capture_intent_e; + + // Client-only never selects process capture, even with a PID. + EXPECT_FALSE(should_capture_process_tree(intent::client_only, true, 1234)); + // Host-and-client selects the process tree only when supported and a PID is known. + EXPECT_TRUE(should_capture_process_tree(intent::host_and_client, true, 1234)); + EXPECT_FALSE(should_capture_process_tree(intent::host_and_client, true, 0)); + EXPECT_FALSE(should_capture_process_tree(intent::host_and_client, false, 1234)); + // A pinned sink always wins. + EXPECT_FALSE(should_capture_process_tree(intent::pinned_sink, true, 1234)); +} + /** * @brief Intent names must stay stable for the capture-mode log line. */ @@ -564,6 +582,12 @@ namespace { if (fail_microphone) { return nullptr; } + if (retarget_once) { + // Model another session replacing the shared target while this + // microphone was being created without the outer mutex held. + retarget_once = false; + record_capture_target(set_intent, set_process_id + 1); + } return std::make_unique(); } @@ -594,6 +618,7 @@ namespace { 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. + bool retarget_once = false; ///< Whether the next microphone() replaces the recorded target mid-creation. 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. @@ -735,46 +760,88 @@ TEST(CaptureSinkDispatchTest, SwapWithoutRestoreSkipsSinkCall) { } /** - * @brief The endpoint target must be recorded ahead of microphone creation. + * @brief A provided identity must reach set_capture_target 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. + * of the launched game, and the set-before-microphone ordering below breaks. */ -TEST(CaptureRefreshTest, EndpointTargetIsRecordedBeforeMicrophone) { +TEST(CaptureRefreshTest, ProviderIdentityIsRecordedBeforeMicrophone) { recording_audio_control_t control; std::mutex mutex; session_capture_target_t target {control, platf::audio_capture_intent_e::host_and_client, mutex}; + const std::function provider = [] { + return platf::process_identity_t {1234u, 91011u}; + }; - auto mic = target.create_microphone(make_mic_params()); + auto mic = target.create_microphone(true, provider, make_mic_params()); EXPECT_TRUE(static_cast(mic)); EXPECT_TRUE(target.recorded()); + EXPECT_EQ(target.process_id(), 1234u); EXPECT_EQ(control.set_intent, platf::audio_capture_intent_e::host_and_client); - EXPECT_EQ(control.set_process_id, 0u); + EXPECT_EQ(control.set_process_id, 1234u); + EXPECT_EQ(control.set_creation_time, 91011u); EXPECT_LT(control.call_index("set_capture_target"), control.call_index("microphone")); } /** - * @brief Endpoint capture must record PID 0 for every intent. + * @brief The handed-off creation marker must reach the backend verbatim. * - * 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. + * The marker is the backend's PID-reuse baseline: it is captured from the + * owned child handle under the process lifecycle lock, so the backend stores + * it without re-querying. Fail-without-fix: if the guard drops the marker + * (or passes a zeroed bundle), the backend records an unverifiable baseline + * and every process-capture session silently degrades to endpoint capture. + */ +TEST(CaptureRefreshTest, ProviderIdentityReachesBackendVerbatim) { + recording_audio_control_t control; + std::mutex mutex; + session_capture_target_t target {control, platf::audio_capture_intent_e::host_and_client, mutex}; + const std::function provider = [] { + return platf::process_identity_t {4242u, 0xBEEFCAFEu}; + }; + + auto mic = target.create_microphone(true, provider, make_mic_params()); + + ASSERT_TRUE(static_cast(mic)); + EXPECT_EQ(control.set_process_id, 4242u); + EXPECT_EQ(control.set_creation_time, 0xBEEFCAFEu); +} + +/** + * @brief Endpoint capture must record a zeroed identity for every non-process case. + * + * Fail-without-fix: if the guard records the raw provider PID without the + * should_capture_process_tree() gate, a client-only or pinned session (or an + * unsupported backend) captures the game process instead of the endpoint, + * defeating silence or the configured sink pin. Gating the PID while leaking + * the marker would likewise name no process at all. */ 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}) { + const std::function provider = [] { + return platf::process_identity_t {1234u, 91011u}; + }; + const std::function empty_provider; + + for (const auto &[case_intent, supported, case_provider] : { + std::tuple {intent::host_and_client, true, empty_provider}, + std::tuple {intent::host_and_client, false, provider}, + std::tuple {intent::client_only, true, provider}, + std::tuple {intent::pinned_sink, true, provider}, + }) { 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()); + auto mic = target.create_microphone(supported, case_provider, make_mic_params()); EXPECT_TRUE(static_cast(mic)); EXPECT_TRUE(target.recorded()); + EXPECT_EQ(target.process_id(), 0u); EXPECT_EQ(control.set_process_id, 0u); + EXPECT_EQ(control.set_creation_time, 0u); EXPECT_EQ(control.set_intent, case_intent); EXPECT_LT(control.call_index("set_capture_target"), control.call_index("microphone")); } @@ -792,18 +859,45 @@ TEST(CaptureRefreshTest, MicrophoneFailureStillRecordsTarget) { recording_audio_control_t control; control.fail_microphone = true; std::mutex mutex; + const std::function provider = [] { + return platf::process_identity_t {1234u, 91011u}; + }; { 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_FALSE(static_cast(target.create_microphone(true, provider, make_mic_params()))); EXPECT_TRUE(target.recorded()); - EXPECT_EQ(control.set_process_id, 0u); + EXPECT_EQ(target.process_id(), 1234u); + EXPECT_EQ(control.set_process_id, 1234u); } // 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); + EXPECT_EQ(control.clear_process_id, 1234u); +} + +/** + * @brief A target replaced during microphone creation must discard that microphone and retry. + * + * Microphone creation no longer runs under the outer mutex, so the + * post-creation re-check is what preserves the refresh/microphone pairing. + */ +TEST(CaptureRefreshTest, RetargetDuringCreationDiscardsAndRetries) { + recording_audio_control_t control; + control.retarget_once = true; + std::mutex mutex; + const std::function provider = [] { + return platf::process_identity_t {1234u, 91011u}; + }; + session_capture_target_t target {control, platf::audio_capture_intent_e::host_and_client, mutex}; + + auto mic = target.create_microphone(true, provider, make_mic_params()); + + EXPECT_TRUE(static_cast(mic)); + EXPECT_EQ(std::count(control.calls.begin(), control.calls.end(), "set_capture_target"), 2); + EXPECT_EQ(std::count(control.calls.begin(), control.calls.end(), "microphone"), 2); + EXPECT_EQ(control.snapshot_capture_target_record().process_id, 1234u); } /** @@ -853,17 +947,20 @@ TEST(CaptureReleaseTest, SkipsClearWhenNothingRecorded) { /** * @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. + * Fail-without-fix: if the guard releases a stale or zeroed PID instead of + * the last recorded one, the backend's clear-if-match keeps the dead session's + * target (leaking process capture) or wipes a survivor's newer target. */ TEST(CaptureReleaseTest, ClearsRecordedTarget) { recording_audio_control_t control; std::mutex mutex; + const std::function provider = [] { + return platf::process_identity_t {1234u, 91011u}; + }; { session_capture_target_t target {control, platf::audio_capture_intent_e::host_and_client, mutex}; - auto mic = target.create_microphone(make_mic_params()); + auto mic = target.create_microphone(true, provider, 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); @@ -872,7 +969,7 @@ TEST(CaptureReleaseTest, ClearsRecordedTarget) { 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); + EXPECT_EQ(control.clear_process_id, 1234u); } /** @@ -886,6 +983,9 @@ TEST(CaptureOrchestrationTest, StartupSequenceRunsDispatchRefreshCreateAndReleas for (const auto &routing : {make_capture_routing(), make_swap_routing()}) { recording_audio_control_t control; std::mutex mutex; + const std::function provider = [] { + return platf::process_identity_t {1234u, 91011u}; + }; audio_ctx_t ctx {}; { @@ -894,7 +994,7 @@ TEST(CaptureOrchestrationTest, StartupSequenceRunsDispatchRefreshCreateAndReleas 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()); + auto mic = target.create_microphone(true, provider, make_mic_params()); ASSERT_TRUE(static_cast(mic)); ASSERT_EQ(control.calls.size(), 3U); } @@ -905,7 +1005,7 @@ TEST(CaptureOrchestrationTest, StartupSequenceRunsDispatchRefreshCreateAndReleas 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); + EXPECT_EQ(control.clear_process_id, 1234u); } } @@ -1246,6 +1346,32 @@ TEST(BaseRecordTest, MacOsLikeNoOpLeavesRecordUntouched) { EXPECT_EQ(control.snapshot_recorded_capture_target().process_id, 0u); } +/** + * @brief The session guard must refresh and release the real base record. + * + * Fail-without-fix: if the guard talks to a mirror instead of the shared + * store, a failed microphone creation leaks the recorded target and the next + * session inherits a target this session recorded but never owned. + */ +TEST(BaseRecordTest, SessionGuardReleasesRealBaseRecord) { + recorded_audio_control_t control; + std::mutex mutex; + const std::function provider = [] { + return platf::process_identity_t {1234u, 91011u}; + }; + + { + session_capture_target_t target {control, platf::audio_capture_intent_e::host_and_client, mutex}; + auto mic = target.create_microphone(true, provider, make_mic_params()); + ASSERT_TRUE(static_cast(mic)); + EXPECT_TRUE(target.recorded()); + EXPECT_EQ(control.snapshot_recorded_capture_target().process_id, 1234u); + } + + 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. * From f345d5476c158b6981cad1d6337b2eacd297072c Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Tue, 17 Nov 2026 00:26:18 -0700 Subject: [PATCH 24/28] 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 25/28] 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 48ae5e3f55e906812e5993d4dc5fb107df411a69 Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Tue, 17 Nov 2026 01:08:57 -0700 Subject: [PATCH 26/28] fix(windows/audio): harden loopback tests, docs, and activation coverage Drive the real activation entry point in tests via an injectable API seam with success/failure/timeout phases; assert paired identity in the concurrency oracle; cover collect() failure combinations and the end-to-end loopback success path; correct the one-lock docs; add mutable-provider and teardown-concurrency tests. --- src/audio.cpp | 5 + src/audio.h | 18 +- src/platform/windows/audio.cpp | 451 ++++++++++++++++++++- src/platform/windows/audio_tests.h | 17 + tests/unit/platform/windows/test_audio.cpp | 46 +++ tests/unit/test_audio.cpp | 138 +++++++ 6 files changed, 651 insertions(+), 24 deletions(-) diff --git a/src/audio.cpp b/src/audio.cpp index 256485a0b0b..01014d87db0 100644 --- a/src/audio.cpp +++ b/src/audio.cpp @@ -246,11 +246,16 @@ namespace audio { return mic; } std::lock_guard lock {*mutex_}; + // The re-check detects replacement by another session, not PID reuse: + // the handed-off creation marker is the backend's baseline, and the + // backend revalidates it again before capturing. if (control_->snapshot_capture_target_record().matches(intent_, process_id_)) { return mic; } BOOST_LOG(info) << "Capture target changed during microphone creation; discarding and retrying"sv; } + // Both attempts observed a replaced target. The last refresh stays + // recorded so teardown still releases this session's target. return nullptr; } diff --git a/src/audio.h b/src/audio.h index 1a9a279426b..ccc867848b7 100644 --- a/src/audio.h +++ b/src/audio.h @@ -282,12 +282,14 @@ namespace audio { * @brief RAII owner of one session's shared capture target. * * Sessions share one audio control. Every create_microphone() call refreshes - * the 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 target (set_capture_target()) under one lock acquisition, so a refresh + * can never be dropped or interleaved with another session's refresh. + * Microphone creation itself runs unlocked, followed by a re-check that + * discards a microphone built for a superseded target and retries once. + * 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. */ @@ -298,7 +300,7 @@ namespace audio { * * @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. + * @param mutex Serializes target refresh, post-creation re-check, and target release across sessions. Microphone creation runs unlocked. */ session_capture_target_t(platf::audio_control_t &control, platf::audio_capture_intent_e intent, std::mutex &mutex); @@ -358,7 +360,7 @@ namespace audio { private: 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_; ///< Non-owning mutex serializing refresh, creation, and release; typically audio::capture_target_mutex(). + std::mutex *mutex_; ///< Non-owning mutex serializing refresh, re-check, and release; typically audio::capture_target_mutex(). std::uint32_t process_id_ = 0; ///< PID from the last refresh, or 0 for endpoint capture. bool recorded_ = false; ///< Whether this session called set_capture_target(). }; diff --git a/src/platform/windows/audio.cpp b/src/platform/windows/audio.cpp index b93bcee1884..63617339855 100644 --- a/src/platform/windows/audio.cpp +++ b/src/platform/windows/audio.cpp @@ -461,6 +461,9 @@ namespace platf::audio { return std::nullopt; } DWORD exit_code {}; + // A live handle alone proves nothing: an exited process keeps a valid handle + // whose exit code is its real (non-STILL_ACTIVE) status, so both the call + // succeeding and the code itself are required to treat the PID as live. if (!GetExitCodeProcess(process.get(), &exit_code) || exit_code != STILL_ACTIVE) { BOOST_LOG(debug) << "Process ["sv << process_id << "] is no longer running; it will not be used for process loopback capture"sv; return std::nullopt; @@ -770,13 +773,25 @@ namespace platf::audio { return client; } + /** + * @brief ActivateAudioInterfaceAsync entry point signature, injectable for deterministic tests. + * + * Production passes the real WASAPI API; tests bind a fake that drives the + * completion handler on a worker thread, so the real activation path below + * (blob ownership, timeout waiter, reference discipline) is exercised + * without audio hardware. + */ + using activate_audio_interface_async_fn_t = std::function; + /** * @brief Activate a WASAPI audio client for a process tree via ActivateAudioInterfaceAsync. * * @param process_id Launched application PID to capture. + * @param timeout_ms Wait deadline in milliseconds. + * @param activate_fn Asynchronous activation entry point, real by default. * @return Activated (not yet initialized) audio client, or nullptr on failure. */ - audio_client_t activate_process_loopback_audio_client(std::uint32_t process_id) { + audio_client_t activate_process_loopback_audio_client(std::uint32_t process_id, DWORD timeout_ms = process_loopback_activation_timeout_ms, const activate_audio_interface_async_fn_t &activate_fn = activate_audio_interface_async_fn_t {ActivateAudioInterfaceAsync}) { auto *handler = new process_loopback_completion_handler_t(); if (!handler->event_handle) { BOOST_LOG(warning) << "Process loopback activation for process ["sv << process_id << "] failed to create its completion event: [0x"sv << util::hex(GetLastError()).to_string_view() << ']'; @@ -800,7 +815,7 @@ namespace platf::audio { return nullptr; } IActivateAudioInterfaceAsyncOperation *operation = nullptr; - auto status = ActivateAudioInterfaceAsync( + auto status = activate_fn( VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, IID_IAudioClient, &activation_prop->prop, @@ -821,8 +836,12 @@ namespace platf::audio { // activation blob alive on a detached waiter until the pending // operation completes, instead of freeing state it may still read. bool wait_timed_out = false; - auto client = collect_process_loopback_activation(handler, process_id, process_loopback_activation_timeout_ms, &wait_timed_out); + auto client = collect_process_loopback_activation(handler, process_id, timeout_ms, &wait_timed_out); if (wait_timed_out) { + // The unbounded wait is deliberate: Windows always completes the pending + // operation with a callback eventually, so the waiter retires the blob + // and handler exactly once. A bounded wait here would only reintroduce + // the free-while-pending hazard this waiter exists to prevent. try { std::thread {[handler, activation_prop]() { WaitForSingleObject(handler->event_handle, INFINITE); @@ -2479,14 +2498,80 @@ namespace platf::audio { /** * @brief Fake IAudioClient with a controllable Initialize result for process-loopback wrapper tests. */ + /** + * @brief Minimal fake capture client served only to satisfy GetService(). + * + * Exists so end-to-end loopback tests can drive microphone() through a + * succeeding activator: endpoint initialization requires a capture client + * service, but no test samples audio through it, so every method reports + * unimplemented. + */ + class fake_process_loopback_capture_client_t final: public IAudioCaptureClient { + public: + fake_process_loopback_capture_client_t() { + ++live_count; + } + + /** + * @brief Destroy the fake capture client, releasing its lifetime count. + */ + ~fake_process_loopback_capture_client_t() { + --live_count; + } + + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **object) override { // NOSONAR(cpp:S5008): IUnknown::QueryInterface requires a void double pointer in the COM ABI. + if (!object) { + return E_POINTER; + } + if (riid == IID_IUnknown || riid == __uuidof(IAudioCaptureClient)) { + *object = static_cast(this); + AddRef(); + return S_OK; + } + *object = nullptr; + return E_NOINTERFACE; + } + + ULONG STDMETHODCALLTYPE AddRef() override { + return ++ref_count; + } + + ULONG STDMETHODCALLTYPE Release() override { + auto count = --ref_count; + if (count == 0) { + delete this; + } + return count; + } + + HRESULT STDMETHODCALLTYPE GetBuffer(BYTE **, UINT32 *, DWORD *, UINT64 *, UINT64 *) override { + return E_NOTIMPL; + } + + HRESULT STDMETHODCALLTYPE ReleaseBuffer(UINT32) override { + return E_NOTIMPL; + } + + HRESULT STDMETHODCALLTYPE GetNextPacketSize(UINT32 *) override { + return E_NOTIMPL; + } + + static inline std::atomic live_count {0}; ///< Live fake-capture-client count for leak checks. + + private: + std::atomic ref_count {1}; ///< COM reference count. + }; + class fake_process_loopback_audio_client_t final: public IAudioClient { public: /** * @brief Construct a fake client returning the given result from Initialize(). * @param initialize_status HRESULT returned by Initialize(). + * @param serve_capture_client Whether GetService() serves a fake capture client instead of failing. */ - explicit fake_process_loopback_audio_client_t(HRESULT initialize_status): - initialize_status {initialize_status} { + explicit fake_process_loopback_audio_client_t(HRESULT initialize_status, bool serve_capture_client = false): + initialize_status {initialize_status}, + serve_capture_client {serve_capture_client} { ++live_count; } @@ -2652,21 +2737,35 @@ namespace platf::audio { } /** - * @brief Reject service queries, which wrapper tests do not use. + * @brief Serve a fake capture client when enabled, else reject service queries. + * + * Wrapper tests leave serving disabled and never reach this branch; the + * end-to-end loopback test enables it so finish_capture_init() succeeds + * without audio hardware. + * * @param object Receives the requested service. - * @return E_NOTIMPL. + * @return S_OK with a fake capture client when serving, else E_NOTIMPL. */ - HRESULT STDMETHODCALLTYPE GetService(REFIID, void **object) override { // NOSONAR(cpp:S5008): IUnknown::QueryInterface requires a void double pointer in the COM ABI. + HRESULT STDMETHODCALLTYPE GetService(REFIID riid, void **object) override { // NOSONAR(cpp:S5008): IUnknown::QueryInterface requires a void double pointer in the COM ABI. if (object) { *object = nullptr; } - return E_NOTIMPL; + if (!serve_capture_client || !object) { + return object ? E_NOTIMPL : E_POINTER; + } + if (riid != IID_IAudioCaptureClient && riid != IID_IUnknown) { + return E_NOINTERFACE; + } + auto *capture = new fake_process_loopback_capture_client_t(); + *object = static_cast(capture); + return S_OK; } static inline std::atomic live_count {0}; ///< Live fake-client count for leak checks. private: HRESULT initialize_status; ///< HRESULT returned by Initialize(). + bool serve_capture_client = false; ///< Whether GetService() serves a fake capture client. std::atomic ref_count {1}; ///< COM reference count. }; @@ -2679,9 +2778,13 @@ namespace platf::audio { /** * @brief Construct a fake operation serving the given interface. * @param served_interface Interface returned from GetActivateResult; the operation holds its own reference. + * @param activate_result Result reported as the GetActivateResult return value. + * @param activation_hresult Result reported as the activation HRESULT. */ - explicit fake_process_loopback_async_operation_t(IUnknown *served_interface): - served_interface {served_interface} { + explicit fake_process_loopback_async_operation_t(IUnknown *served_interface, HRESULT activate_result = S_OK, HRESULT activation_hresult = S_OK): + served_interface {served_interface}, + activate_result {activate_result}, + activation_hresult {activation_hresult} { if (served_interface) { served_interface->AddRef(); } @@ -2745,16 +2848,18 @@ namespace platf::audio { if (!activation_hresult || !activated_interface) { return E_POINTER; } - *activation_hresult = S_OK; + *activation_hresult = this->activation_hresult; *activated_interface = served_interface; if (served_interface) { served_interface->AddRef(); } - return S_OK; + return activate_result; } private: IUnknown *served_interface {}; ///< Served interface held with an owning reference, or nullptr. + HRESULT activate_result {S_OK}; ///< Reported GetActivateResult return value. + HRESULT activation_hresult {S_OK}; ///< Reported activation HRESULT. std::atomic ref_count {1}; ///< COM reference count. }; @@ -2970,6 +3075,265 @@ namespace platf::audio { } return kPhasePassed; } + + /** + * @brief Hostile IUnknown violating the QueryInterface success contract. + * + * Real implementations null the out-pointer on failure, but the production + * handler defensively releases a non-null object anyway; this fake pins + * that branch by returning E_FAIL while handing out a referenced self. + */ + class fake_hostile_unknown_t final: public IUnknown { + public: + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID, void **object) override { // NOSONAR(cpp:S5008): IUnknown::QueryInterface requires a void double pointer in the COM ABI. + if (object) { + *object = this; + AddRef(); + } + return E_FAIL; + } + + ULONG STDMETHODCALLTYPE AddRef() override { + return ++ref_count; + } + + ULONG STDMETHODCALLTYPE Release() override { + auto count = --ref_count; + if (count == 0) { + delete this; + } + return count; + } + + private: + std::atomic ref_count {1}; ///< COM reference count. + }; + + /** + * @brief Verify collect() rejects every failure combination of the completion fields. + * + * The timeout test above pins wait/ordering semantics; this covers the result + * matrix instead: a failed GetActivateResult return, a failed activation + * HRESULT with a successful return, a null served interface under success + * results, and a hostile QueryInterface that fails while returning an + * object. Each phase pre-signals synchronously, so no timing is involved, + * and each asserts the client count returns to baseline. + * + * @return 0 when every phase passes; otherwise the failing-phase id. + */ + int collect_reports_failure_combinations() { + constexpr int kPhasePassed {0}; ///< All phases passed. + constexpr int kPhaseActivateResult {1}; ///< FAILED GetActivateResult return delivered a client. + constexpr int kPhaseActivationHresult {2}; ///< FAILED activation HRESULT delivered a client. + constexpr int kPhaseNullInterface {3}; ///< Null served interface under success results delivered a client. + constexpr int kPhaseHostileQueryInterface {4}; ///< Hostile QueryInterface failure delivered a client. + constexpr DWORD kSignaledWaitMs {1000}; ///< Wait allowing pre-signaled completions to report. + { + const int live_baseline = fake_process_loopback_audio_client_t::live_count.load(); + auto *served_client = new fake_process_loopback_audio_client_t(S_OK); + fake_process_loopback_async_operation_t operation(served_client, E_FAIL, S_OK); + served_client->Release(); + auto *handler = new platf::audio::process_loopback_completion_handler_t(); + if (!handler->event_handle) { + handler->Release(); + return kPhaseActivateResult; + } + handler->ActivateCompleted(&operation); + auto client = platf::audio::collect_process_loopback_activation(handler, 1234, kSignaledWaitMs); + if (client || fake_process_loopback_audio_client_t::live_count.load() != live_baseline) { + return kPhaseActivateResult; + } + } + { + const int live_baseline = fake_process_loopback_audio_client_t::live_count.load(); + auto *served_client = new fake_process_loopback_audio_client_t(S_OK); + fake_process_loopback_async_operation_t operation(served_client, S_OK, E_FAIL); + served_client->Release(); + auto *handler = new platf::audio::process_loopback_completion_handler_t(); + if (!handler->event_handle) { + handler->Release(); + return kPhaseActivationHresult; + } + handler->ActivateCompleted(&operation); + auto client = platf::audio::collect_process_loopback_activation(handler, 1234, kSignaledWaitMs); + if (client || fake_process_loopback_audio_client_t::live_count.load() != live_baseline) { + return kPhaseActivationHresult; + } + } + { + const int live_baseline = fake_process_loopback_audio_client_t::live_count.load(); + fake_process_loopback_async_operation_t operation(nullptr); + auto *handler = new platf::audio::process_loopback_completion_handler_t(); + if (!handler->event_handle) { + handler->Release(); + return kPhaseNullInterface; + } + handler->ActivateCompleted(&operation); + auto client = platf::audio::collect_process_loopback_activation(handler, 1234, kSignaledWaitMs); + if (client || fake_process_loopback_audio_client_t::live_count.load() != live_baseline) { + return kPhaseNullInterface; + } + } + { + const int live_baseline = fake_process_loopback_audio_client_t::live_count.load(); + auto *hostile = new fake_hostile_unknown_t(); + fake_process_loopback_async_operation_t operation(hostile); + hostile->Release(); + auto *handler = new platf::audio::process_loopback_completion_handler_t(); + if (!handler->event_handle) { + handler->Release(); + return kPhaseHostileQueryInterface; + } + handler->ActivateCompleted(&operation); + auto client = platf::audio::collect_process_loopback_activation(handler, 1234, kSignaledWaitMs); + if (client || fake_process_loopback_audio_client_t::live_count.load() != live_baseline) { + return kPhaseHostileQueryInterface; + } + } + return kPhasePassed; + } + + /** + * @brief Scripted ActivateAudioInterfaceAsync replacement for real-path activation tests. + * + * Records the PROPVARIANT blob the production code passes, then completes + * asynchronously on a joined worker thread so the real wait/collect path + * runs. The worker must be joined (via join() or destruction) before + * reading final observations; all observations except the blob bytes are + * written before completion and are stable once the worker joins. + */ + struct scripted_activate_audio_interface_async_t { + HRESULT immediate_result = S_OK; ///< Synchronous return; FAILED skips completion entirely. + DWORD complete_delay_ms = 20; ///< Worker delay before completing. + bool called = false; ///< Whether the fake API was invoked. + VARTYPE seen_vt = VT_EMPTY; ///< Observed blob variant type. + ULONG seen_blob_size = 0; ///< Observed blob byte count. + std::vector seen_blob_bytes; ///< Observed blob bytes. + fake_process_loopback_async_operation_t *operation = nullptr; ///< Heap operation owned until join(). + std::thread worker; ///< Completion worker, joined before assertions. + + ~scripted_activate_audio_interface_async_t() { + join(); + } + + /** + * @brief Bind the script as an activation entry point for the real function. + * @return Callable matching activate_audio_interface_async_fn_t. + */ + [[nodiscard]] activate_audio_interface_async_fn_t bind() { + return [this](LPCWSTR, REFIID, PROPVARIANT *prop, IActivateAudioInterfaceCompletionHandler *handler, IActivateAudioInterfaceAsyncOperation **operation_out) -> HRESULT { + called = true; + if (prop && prop->vt == VT_BLOB && prop->blob.pBlobData) { + seen_vt = VT_BLOB; + seen_blob_size = prop->blob.cbSize; + seen_blob_bytes.assign(prop->blob.pBlobData, prop->blob.pBlobData + prop->blob.cbSize); + } + if (FAILED(immediate_result)) { + *operation_out = nullptr; + return immediate_result; + } + auto *served = new fake_process_loopback_audio_client_t(S_OK); + operation = new fake_process_loopback_async_operation_t(served); + served->Release(); + operation->AddRef(); // Caller reference; production releases it immediately. + *operation_out = operation; + handler->AddRef(); // Model the reference Windows holds until the callback runs. + // The worker borrows the script-owned operation (released by join(), + // which always runs before the script is destroyed); only the + // Windows-role handler reference is released here. + worker = std::thread([this, handler] { + ::Sleep(complete_delay_ms); + handler->ActivateCompleted(operation); + handler->Release(); + }); + return S_OK; + }; + } + + /** + * @brief Join the completion worker and release the script-owned operation. + */ + void join() { + if (worker.joinable()) { + worker.join(); + } + if (operation) { + operation->Release(); + operation = nullptr; + } + } + }; + + /** + * @brief Drive the real activation entry point through success, failure, and timeout paths. + * + * Unlike the collect-level tests, which hand-drive a handler, this binds a + * scripted ActivateAudioInterfaceAsync into the real + * activate_process_loopback_audio_client(), so blob ownership, the + * immediate-failure path, and the timeout detached-waiter path all execute. + * Each phase asserts the exact blob bytes handed to the API alongside the + * client outcome, and the timeout phase polls the fake-client count back + * to baseline to prove the detached waiter retired the late completion. + * + * @return 0 when every phase passes; otherwise the failing-phase id. + */ + int real_activation_paths_cover_success_failure_and_timeout() { + constexpr int kPhasePassed {0}; ///< All phases passed. + constexpr int kPhaseSuccess {1}; ///< Async success did not deliver an exact-blob client. + constexpr int kPhaseImmediateFailure {2}; ///< Immediate API failure delivered a client or leaked. + constexpr int kPhaseTimeout {3}; ///< Timeout did not discard, or the waiter did not retire the late completion. + constexpr DWORD kShortTimeoutMs {10}; ///< Wait expiring before the scripted late completion. + constexpr DWORD kLateCompleteMs {100}; ///< Scripted completion delay, strictly after the short timeout. + const auto expected_params = platf::audio::make_process_loopback_activation_params(1234); + const auto blob_matches = [&](const scripted_activate_audio_interface_async_t &script) { + return script.called && script.seen_vt == VT_BLOB && script.seen_blob_size == sizeof(expected_params) && + script.seen_blob_bytes.size() == sizeof(expected_params) && + std::memcmp(script.seen_blob_bytes.data(), &expected_params, sizeof(expected_params)) == 0; + }; + { + const int live_baseline = fake_process_loopback_audio_client_t::live_count.load(); + scripted_activate_audio_interface_async_t script; + auto client = platf::audio::activate_process_loopback_audio_client(1234, 1000, script.bind()); + script.join(); + const bool delivered = static_cast(client); + client.reset(); + if (!delivered || !blob_matches(script) || fake_process_loopback_audio_client_t::live_count.load() != live_baseline) { + return kPhaseSuccess; + } + } + { + const int live_baseline = fake_process_loopback_audio_client_t::live_count.load(); + scripted_activate_audio_interface_async_t script; + script.immediate_result = E_FAIL; + auto client = platf::audio::activate_process_loopback_audio_client(1234, 1000, script.bind()); + script.join(); + if (client || !blob_matches(script) || fake_process_loopback_audio_client_t::live_count.load() != live_baseline) { + return kPhaseImmediateFailure; + } + } + { + const int live_baseline = fake_process_loopback_audio_client_t::live_count.load(); + scripted_activate_audio_interface_async_t script; + script.complete_delay_ms = kLateCompleteMs; + auto client = platf::audio::activate_process_loopback_audio_client(1234, kShortTimeoutMs, script.bind()); + const bool discarded = !client; + script.join(); + // The production detached waiter retires the late completion + // asynchronously; poll for its effects with a generous deadline. + bool retired = false; + for (int i = 0; i < 100; ++i) { + if (fake_process_loopback_audio_client_t::live_count.load() == live_baseline) { + retired = true; + break; + } + ::Sleep(50); + } + if (!discarded || !blob_matches(script) || !retired) { + return kPhaseTimeout; + } + } + return kPhasePassed; + } #endif /** @@ -3186,7 +3550,9 @@ namespace platf::audio { * * Exercises capture-target set/clear/snapshot together with assigned-sink * writes and snapshots. Every snapshot must read one of the written - * values; completing without a data race is the regression pin. + * values, including the paired creation marker: each worker records + * identity {pid, pid}, so a snapshot whose marker does not match its PID + * is torn and fails. Completing without a data race is the regression pin. * * @return True when every snapshot read a consistent value. */ @@ -3202,8 +3568,9 @@ namespace platf::audio { } control.set_capture_target(host_and_client, process_identity_t {pid, pid}); const auto target = control.snapshot_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); + const bool valid_target = (target.intent == host_and_client && target.process_id >= 1 && target.process_id <= 4 && + target.identity.process_id == target.process_id && target.identity.creation_time == target.process_id) || + (target.intent == client_only && target.process_id == 0 && target.identity.process_id == 0 && target.identity.creation_time == 0); if (!valid_target) { consistent.store(false, std::memory_order_relaxed); } @@ -3381,6 +3748,58 @@ namespace platf::audio { return probe.attempted_process_id != 0; } + /** + * @brief Exercise microphone() end to end through a succeeding loopback activation. + * + * Records the given capture target through the production setter, installs + * an activator that initializes a fake client (serving a fake capture + * client so finish_capture_init() succeeds without audio hardware), and + * runs the production microphone(). The endpoint fallback path creates no + * fake clients, so exactly one live fake client paired with the attempt + * proves the loopback branch — including post-activation revalidation — + * returned the microphone rather than the fallback. + * + * @param probe Capture probe: sinks, intent, identity, enumerator, and keep-default flag in; attempt evidence out. + * @return True when loopback activation succeeded and its microphone was returned without leaking. + */ + bool microphone_returns_loopback_for_valid_target(microphone_loopback_probe_t &probe) { + audio_control_t control; + probe.device_enum->AddRef(); + control.device_enum.reset(probe.device_enum); + control.capture_sink(probe.assigned_sink); + control.set_capture_target(probe.intent, process_identity_t {probe.process_id, probe.creation_time}); + control.set_test_loopback_activator([&probe](std::uint32_t attempted_pid, const format_t &format) -> audio_client_t { + probe.attempted_process_id = attempted_pid; + process_loopback_activation_t activation = [](std::uint32_t) { + audio_client_t client; + client.reset(new fake_process_loopback_audio_client_t(S_OK, true)); + return client; + }; + return make_process_loopback_audio_client(attempted_pid, format, activation); + }); + + probe.attempted_process_id = 0; + const int live_baseline = fake_process_loopback_audio_client_t::live_count.load(); + const int capture_baseline = fake_process_loopback_capture_client_t::live_count.load(); + const microphone_params_t params {nullptr, 2, 48000, 240, false, false}; + auto previous_configured_sink = std::exchange(config::audio.sink, probe.configured_sink); + auto previous_keep_default = std::exchange(config::audio.keep_default_sink, probe.keep_default); + { + auto microphone = control.microphone(params); + if (!microphone || probe.attempted_process_id != probe.process_id || fake_process_loopback_audio_client_t::live_count.load() != live_baseline + 1 || fake_process_loopback_capture_client_t::live_count.load() != capture_baseline + 1) { + config::audio.sink = std::move(previous_configured_sink); + config::audio.keep_default_sink = previous_keep_default; + probe.microphone_returned = static_cast(microphone); + return false; + } + } + config::audio.sink = std::move(previous_configured_sink); + config::audio.keep_default_sink = previous_keep_default; + probe.microphone_returned = true; + return fake_process_loopback_audio_client_t::live_count.load() == live_baseline && + fake_process_loopback_capture_client_t::live_count.load() == capture_baseline; + } + /** * @brief Report whether endpoint capture follows the Windows default device. * diff --git a/src/platform/windows/audio_tests.h b/src/platform/windows/audio_tests.h index b9533c7cce8..bf4c0b15a41 100644 --- a/src/platform/windows/audio_tests.h +++ b/src/platform/windows/audio_tests.h @@ -56,4 +56,21 @@ namespace platf::audio::tests { * @return True when process-loopback activation was attempted. */ bool microphone_attempts_loopback_for_target(microphone_loopback_probe_t &probe); + + /** + * @brief Exercise microphone() end to end through a succeeding loopback activation. + * + * Records the given capture target through the production setter, installs + * an activator that initializes a fake client, and runs the production + * microphone(). The endpoint fallback path creates no fake clients, so a + * returned microphone paired with exactly one live fake client proves the + * loopback branch — including post-activation revalidation — returned it + * rather than the fallback. The current process identity is the + * deterministic valid target: its PID and creation time are read from the + * owned handle. + * + * @param probe Capture probe: sinks, intent, identity, enumerator, and keep-default flag in; attempt evidence out. + * @return True when loopback activation succeeded and its microphone was returned without leaking. + */ + bool microphone_returns_loopback_for_valid_target(microphone_loopback_probe_t &probe); } // namespace platf::audio::tests diff --git a/tests/unit/platform/windows/test_audio.cpp b/tests/unit/platform/windows/test_audio.cpp index 7dec032e808..3898ad55a14 100644 --- a/tests/unit/platform/windows/test_audio.cpp +++ b/tests/unit/platform/windows/test_audio.cpp @@ -79,6 +79,8 @@ namespace platf::audio::tests { #endif #if defined(SUNSHINE_TEST_HAS_AUDIOCLIENT_ACTIVATION_PARAMS) && defined(VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK) int process_loopback_completion_after_timeout_is_discarded(); + int collect_reports_failure_combinations(); + int real_activation_paths_cover_success_failure_and_timeout(); #endif } // namespace platf::audio::tests @@ -827,6 +829,30 @@ TEST(WindowsAudioTest, MicrophoneAttemptsLoopbackForCurrentProcessTarget) { EXPECT_EQ(probe.attempted_process_id, current_process_id); } +TEST(WindowsAudioTest, MicrophoneReturnsLoopbackForValidTarget) { + fake_device_enumerator_t enumerator {L"endpoint-id"}; + const auto current_process_id = static_cast(::GetCurrentProcessId()); + ASSERT_NE(current_process_id, 0u); + const auto creation_time = current_process_creation_time(); + ASSERT_NE(creation_time, 0u); + + platf::audio::tests::microphone_loopback_probe_t probe { + .assigned_sink = "endpoint-id", + .configured_sink = {}, + .intent = platf::audio_capture_intent_e::host_and_client, + .process_id = current_process_id, + .creation_time = creation_time, + .device_enum = &enumerator, + .keep_default = false, + }; + // The endpoint fallback creates no fake clients, so a returned microphone + // proves the loopback branch — including post-activation revalidation — + // succeeded rather than falling back. + EXPECT_TRUE(platf::audio::tests::microphone_returns_loopback_for_valid_target(probe)); + EXPECT_EQ(probe.attempted_process_id, current_process_id); + EXPECT_TRUE(probe.microphone_returned); +} + TEST(WindowsAudioTest, MicrophoneFallsBackToEndpointWhenActivationFails) { fake_device_enumerator_t enumerator {L"endpoint-id"}; const auto current_process_id = static_cast(::GetCurrentProcessId()); @@ -1109,6 +1135,12 @@ TEST(WindowsAudioTest, ProcessLoopbackActivationParamsIncludeProcessTree) { TEST(WindowsAudioTest, ProcessLoopbackActivationBlobIsHeapOwnedAndClearable) { EXPECT_TRUE(platf::audio::tests::activation_blob_holds_heap_copy(1234)); +} + #else +TEST(WindowsAudioTest, ProcessLoopbackActivationParamsUnavailable) { + // Production loopback is compiled out under the same SDK detection, so a + // visible skip here is consistent coverage reporting, not a silent gap. + GTEST_SKIP() << "Requires Windows SDK with audioclientactivationparams.h"; } #endif @@ -1116,6 +1148,20 @@ TEST(WindowsAudioTest, ProcessLoopbackActivationBlobIsHeapOwnedAndClearable) { TEST(WindowsAudioTest, ProcessLoopbackCompletionAfterTimeoutIsDiscarded) { EXPECT_EQ(platf::audio::tests::process_loopback_completion_after_timeout_is_discarded(), 0); } + +TEST(WindowsAudioTest, CollectReportsFailureCombinations) { + EXPECT_EQ(platf::audio::tests::collect_reports_failure_combinations(), 0); +} + +TEST(WindowsAudioTest, RealActivationPathsCoverSuccessFailureAndTimeout) { + EXPECT_EQ(platf::audio::tests::real_activation_paths_cover_success_failure_and_timeout(), 0); +} + #else +TEST(WindowsAudioTest, ProcessLoopbackActivationUnavailable) { + // Production loopback is compiled out under the same SDK detection, so a + // visible skip here is consistent coverage reporting, not a silent gap. + GTEST_SKIP() << "Requires Windows SDK with process-loopback activation support"; +} #endif TEST(WindowsAudioTest, HandsOffModeSkipsDefaultResetAndDriverInstall) { diff --git a/tests/unit/test_audio.cpp b/tests/unit/test_audio.cpp index 896bdba720a..07d47532d17 100644 --- a/tests/unit/test_audio.cpp +++ b/tests/unit/test_audio.cpp @@ -900,6 +900,144 @@ TEST(CaptureRefreshTest, RetargetDuringCreationDiscardsAndRetries) { EXPECT_EQ(control.snapshot_capture_target_record().process_id, 1234u); } +/** + * @brief A provider identity change must be picked up on reinitialization. + * + * The provider is queried on every create_microphone() call, so an app that + * exited and relaunched between reinitializations (same PID slot, new + * creation marker, or a different PID entirely) must refresh the recorded + * target instead of reusing the stale one. + * + * Fail-without-fix: if the guard cached the first identity, the backend + * would keep capturing the exited process while its PID belongs to another. + */ +TEST(CaptureRefreshTest, ProviderIdentityChangeIsPickedUpOnReinitialization) { + recording_audio_control_t control; + std::mutex mutex; + std::atomic provider_calls {0}; + const std::function provider = [&provider_calls] { + return provider_calls.fetch_add(1) == 0 ? platf::process_identity_t {1234u, 91011u} : platf::process_identity_t {5678u, 121314u}; + }; + session_capture_target_t target {control, platf::audio_capture_intent_e::host_and_client, mutex}; + + auto first_mic = target.create_microphone(true, provider, make_mic_params()); + ASSERT_TRUE(static_cast(first_mic)); + EXPECT_EQ(control.set_process_id, 1234u); + EXPECT_EQ(control.set_creation_time, 91011u); + + auto second_mic = target.create_microphone(true, provider, make_mic_params()); + + EXPECT_TRUE(static_cast(second_mic)); + EXPECT_EQ(target.process_id(), 5678u); + EXPECT_EQ(control.set_process_id, 5678u); + EXPECT_EQ(control.set_creation_time, 121314u); + EXPECT_EQ(control.snapshot_capture_target_record().process_id, 5678u); +} + +/** + * @brief Backend that counts capture-target refreshes and releases atomically. + * + * Unlike recording_audio_control_t, whose call log is not thread-safe, this + * stub is safe for concurrent create_microphone() calls: it records through + * the shared base helpers and counts operations with atomics. + */ +class counting_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; + } + + bool supports_process_capture() const override { + return true; + } + + int capture_sink(const std::string &) override { + return 0; + } + + void set_capture_target(platf::audio_capture_intent_e intent, platf::process_identity_t identity) override { + set_count.fetch_add(1); + record_capture_target(intent, identity.process_id); + } + + void clear_capture_target(platf::audio_capture_intent_e intent, std::uint32_t process_id) override { + clear_count.fetch_add(1); + clear_recorded_capture_target_if_matches(intent, process_id); + } + + 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; + } + + std::atomic set_count {0}; ///< Refreshes observed across threads. + std::atomic clear_count {0}; ///< Releases observed across threads. +}; + +/** + * @brief Concurrent refreshes and teardowns must stay balanced and consistent. + * + * Two sessions share one control and mutex while one thread reinitializes and + * the other constructs, creates through, and destroys its guard repeatedly. + * Fail-without-fix: an unserialized refresh/release pair corrupts the shared + * record or skews the counts; the final snapshot must always name one of the + * two sessions' targets and every destroyed guard must have released. + */ +TEST(CaptureReleaseTest, ConcurrentRefreshAndTeardownStayBalanced) { + counting_audio_control_t control; + std::mutex mutex; + const std::function provider_a = [] { + return platf::process_identity_t {1111u, 22222u}; + }; + const std::function provider_b = [] { + return platf::process_identity_t {3333u, 44444u}; + }; + session_capture_target_t target_a {control, platf::audio_capture_intent_e::host_and_client, mutex}; + + constexpr int kIterations = 50; + std::jthread refresher([&] { + for (int i = 0; i < kIterations; ++i) { + (void) target_a.create_microphone(true, provider_a, make_mic_params()); + } + }); + std::jthread churner([&] { + for (int i = 0; i < kIterations; ++i) { + session_capture_target_t target_b {control, platf::audio_capture_intent_e::host_and_client, mutex}; + (void) target_b.create_microphone(true, provider_b, make_mic_params()); + } + }); + refresher.join(); + churner.join(); + + // Each creation refreshes once, plus one retry when it observes a mid-creation + // replacement, so the count is bounded rather than exact. Every destroyed + // guard released exactly once; target_a outlives these assertions. + EXPECT_GE(control.set_count.load(), 2 * kIterations); + EXPECT_LE(control.set_count.load(), 4 * kIterations); + EXPECT_EQ(control.clear_count.load(), kIterations); + const auto snapshot = control.snapshot_capture_target_record(); + // The final snapshot is always one complete write: either session's triple, + // or the cleared record when the last operation was a matching release. + // Anything else (a torn intent/PID mix) fails. + const bool matches_a = snapshot.intent == platf::audio_capture_intent_e::host_and_client && snapshot.process_id == 1111u; + const bool matches_b = snapshot.intent == platf::audio_capture_intent_e::host_and_client && snapshot.process_id == 3333u; + const bool matches_cleared = snapshot.intent == platf::audio_capture_intent_e::client_only && snapshot.process_id == 0u; + EXPECT_TRUE(matches_a || matches_b || matches_cleared); +} + /** * @brief The restore flag must follow the routing decision in both modes. * From 2f69cd0a8c1584a35ffb5e0942b7fc402aafffc7 Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Tue, 17 Nov 2026 03:14:55 -0700 Subject: [PATCH 27/28] 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 From 91cd1281c999542485e045a365bf0a694a8c422f Mon Sep 17 00:00:00 2001 From: Michael Faille Date: Tue, 17 Nov 2026 03:33:09 -0700 Subject: [PATCH 28/28] test(windows): share the loopback probe setup across microphone tests Eight microphone tests repeated the same 17-line probe setup (live PID and creation marker plus the baseline probe literal), flagged as 34 duplicated lines on PR #6124. Add make_current_process_probe() for the shared baseline; each test keeps its environment asserts and overrides only the fields its case varies (intent, configured sink, keep_default, stale marker). The PID-0 endpoint test keeps its distinct literal. --- tests/unit/platform/windows/test_audio.cpp | 166 +++++++-------------- 1 file changed, 57 insertions(+), 109 deletions(-) diff --git a/tests/unit/platform/windows/test_audio.cpp b/tests/unit/platform/windows/test_audio.cpp index 3898ad55a14..1e132a09f7d 100644 --- a/tests/unit/platform/windows/test_audio.cpp +++ b/tests/unit/platform/windows/test_audio.cpp @@ -352,6 +352,27 @@ namespace { } return (static_cast(creation_time.dwHighDateTime) << 32) | static_cast(creation_time.dwLowDateTime); } + + /** + * @brief Build a loopback probe targeting the current process. + * + * Fills the shared baseline (endpoint-id sinks, host_and_client intent, live + * PID and creation marker); tests override individual fields for their case. + * + * @param enumerator Device enumerator the probe resolves endpoints through. + * @return Probe ready for the microphone() test seams. + */ + platf::audio::tests::microphone_loopback_probe_t make_current_process_probe(fake_device_enumerator_t &enumerator) { + return { + .assigned_sink = "endpoint-id", + .configured_sink = {}, + .intent = platf::audio_capture_intent_e::host_and_client, + .process_id = static_cast(::GetCurrentProcessId()), + .creation_time = current_process_creation_time(), + .device_enum = &enumerator, + .keep_default = false, + }; + } } // namespace TEST(WindowsAudioTest, PreservesVirtualSpeakerFormatPreferenceAndChannelMasks) { @@ -811,66 +832,36 @@ TEST(WindowsAudioTest, CaptureProcessSetterStoresIdentityVerbatim) { TEST(WindowsAudioTest, MicrophoneAttemptsLoopbackForCurrentProcessTarget) { fake_device_enumerator_t enumerator {L"endpoint-id"}; - const auto current_process_id = static_cast(::GetCurrentProcessId()); - ASSERT_NE(current_process_id, 0u); - const auto creation_time = current_process_creation_time(); - ASSERT_NE(creation_time, 0u); + auto probe = make_current_process_probe(enumerator); + ASSERT_NE(probe.process_id, 0u); + ASSERT_NE(probe.creation_time, 0u); - platf::audio::tests::microphone_loopback_probe_t probe { - .assigned_sink = "endpoint-id", - .configured_sink = {}, - .intent = platf::audio_capture_intent_e::host_and_client, - .process_id = current_process_id, - .creation_time = creation_time, - .device_enum = &enumerator, - .keep_default = false, - }; EXPECT_TRUE(platf::audio::tests::microphone_attempts_loopback_for_target(probe)); - EXPECT_EQ(probe.attempted_process_id, current_process_id); + EXPECT_EQ(probe.attempted_process_id, probe.process_id); } TEST(WindowsAudioTest, MicrophoneReturnsLoopbackForValidTarget) { fake_device_enumerator_t enumerator {L"endpoint-id"}; - const auto current_process_id = static_cast(::GetCurrentProcessId()); - ASSERT_NE(current_process_id, 0u); - const auto creation_time = current_process_creation_time(); - ASSERT_NE(creation_time, 0u); + auto probe = make_current_process_probe(enumerator); + ASSERT_NE(probe.process_id, 0u); + ASSERT_NE(probe.creation_time, 0u); - platf::audio::tests::microphone_loopback_probe_t probe { - .assigned_sink = "endpoint-id", - .configured_sink = {}, - .intent = platf::audio_capture_intent_e::host_and_client, - .process_id = current_process_id, - .creation_time = creation_time, - .device_enum = &enumerator, - .keep_default = false, - }; // The endpoint fallback creates no fake clients, so a returned microphone // proves the loopback branch — including post-activation revalidation — // succeeded rather than falling back. EXPECT_TRUE(platf::audio::tests::microphone_returns_loopback_for_valid_target(probe)); - EXPECT_EQ(probe.attempted_process_id, current_process_id); + EXPECT_EQ(probe.attempted_process_id, probe.process_id); EXPECT_TRUE(probe.microphone_returned); } TEST(WindowsAudioTest, MicrophoneFallsBackToEndpointWhenActivationFails) { fake_device_enumerator_t enumerator {L"endpoint-id"}; - const auto current_process_id = static_cast(::GetCurrentProcessId()); - ASSERT_NE(current_process_id, 0u); - const auto creation_time = current_process_creation_time(); - ASSERT_NE(creation_time, 0u); + auto probe = make_current_process_probe(enumerator); + ASSERT_NE(probe.process_id, 0u); + ASSERT_NE(probe.creation_time, 0u); - platf::audio::tests::microphone_loopback_probe_t probe { - .assigned_sink = "endpoint-id", - .configured_sink = {}, - .intent = platf::audio_capture_intent_e::host_and_client, - .process_id = current_process_id, - .creation_time = creation_time, - .device_enum = &enumerator, - .keep_default = false, - }; EXPECT_TRUE(platf::audio::tests::microphone_attempts_loopback_for_target(probe)); - EXPECT_EQ(probe.attempted_process_id, current_process_id); + EXPECT_EQ(probe.attempted_process_id, probe.process_id); // The failing activator falls back to endpoint capture: the assigned sink is // resolved through the injected enumerator, and endpoint initialization // fails without audio hardware. @@ -898,20 +889,11 @@ TEST(WindowsAudioTest, MicrophoneSkipsLoopbackWithoutCaptureTarget) { TEST(WindowsAudioTest, MicrophoneSkipsLoopbackForSilentIntent) { fake_device_enumerator_t enumerator {L"endpoint-id"}; - const auto current_process_id = static_cast(::GetCurrentProcessId()); - ASSERT_NE(current_process_id, 0u); - const auto creation_time = current_process_creation_time(); - ASSERT_NE(creation_time, 0u); + auto probe = make_current_process_probe(enumerator); + ASSERT_NE(probe.process_id, 0u); + ASSERT_NE(probe.creation_time, 0u); - platf::audio::tests::microphone_loopback_probe_t probe { - .assigned_sink = "endpoint-id", - .configured_sink = {}, - .intent = platf::audio_capture_intent_e::client_only, - .process_id = current_process_id, - .creation_time = creation_time, - .device_enum = &enumerator, - .keep_default = false, - }; + probe.intent = platf::audio_capture_intent_e::client_only; EXPECT_FALSE(platf::audio::tests::microphone_attempts_loopback_for_target(probe)); EXPECT_EQ(probe.attempted_process_id, 0u); EXPECT_EQ(enumerator.get_device_calls, 1); @@ -920,45 +902,29 @@ TEST(WindowsAudioTest, MicrophoneSkipsLoopbackForSilentIntent) { TEST(WindowsAudioTest, MicrophoneAttemptsLoopbackForBlankKeepDefaultTarget) { fake_device_enumerator_t enumerator {L"endpoint-id"}; - const auto current_process_id = static_cast(::GetCurrentProcessId()); - ASSERT_NE(current_process_id, 0u); - const auto creation_time = current_process_creation_time(); - ASSERT_NE(creation_time, 0u); + auto probe = make_current_process_probe(enumerator); + ASSERT_NE(probe.process_id, 0u); + ASSERT_NE(probe.creation_time, 0u); - platf::audio::tests::microphone_loopback_probe_t probe { - .assigned_sink = "endpoint-id", - .configured_sink = {}, - .intent = platf::audio_capture_intent_e::host_and_client, - .process_id = current_process_id, - .creation_time = creation_time, - .device_enum = &enumerator, - .keep_default = true, - }; + probe.keep_default = true; EXPECT_TRUE(platf::audio::tests::microphone_attempts_loopback_for_target(probe)); - EXPECT_EQ(probe.attempted_process_id, current_process_id); + EXPECT_EQ(probe.attempted_process_id, probe.process_id); // The follow-default fallback builds its own enumerator, so the injected one stays untouched. EXPECT_EQ(enumerator.get_device_calls, 0); } TEST(WindowsAudioTest, MicrophoneSkipsLoopbackForPinnedIntent) { fake_device_enumerator_t enumerator {L"endpoint-id"}; - const auto current_process_id = static_cast(::GetCurrentProcessId()); - ASSERT_NE(current_process_id, 0u); - const auto creation_time = current_process_creation_time(); - ASSERT_NE(creation_time, 0u); + auto probe = make_current_process_probe(enumerator); + ASSERT_NE(probe.process_id, 0u); + ASSERT_NE(probe.creation_time, 0u); // Even with a live PID, a pinned sink stays pinned: the backend never // attempts loopback for pinned intent, independent of the guard recording // PID 0 for such sessions upstream. - platf::audio::tests::microphone_loopback_probe_t probe { - .assigned_sink = "endpoint-id", - .configured_sink = "endpoint-id", - .intent = platf::audio_capture_intent_e::pinned_sink, - .process_id = current_process_id, - .creation_time = creation_time, - .device_enum = &enumerator, - .keep_default = true, - }; + probe.configured_sink = "endpoint-id"; + probe.intent = platf::audio_capture_intent_e::pinned_sink; + probe.keep_default = true; EXPECT_FALSE(platf::audio::tests::microphone_attempts_loopback_for_target(probe)); EXPECT_EQ(probe.attempted_process_id, 0u); EXPECT_EQ(enumerator.get_device_calls, 1); @@ -968,25 +934,16 @@ TEST(WindowsAudioTest, MicrophoneSkipsLoopbackForPinnedIntent) { TEST(WindowsAudioTest, MicrophoneLoopbackDecisionIgnoresConfiguredSink) { fake_device_enumerator_t enumerator {L"endpoint-id"}; - const auto current_process_id = static_cast(::GetCurrentProcessId()); - ASSERT_NE(current_process_id, 0u); - const auto creation_time = current_process_creation_time(); - ASSERT_NE(creation_time, 0u); + auto probe = make_current_process_probe(enumerator); + ASSERT_NE(probe.process_id, 0u); + ASSERT_NE(probe.creation_time, 0u); // The backend decides on intent and revalidated PID only: a configured sink // no longer blocks the attempt here because the shared guard already maps a // configured sink to pinned intent (and PID 0) before the backend runs. - platf::audio::tests::microphone_loopback_probe_t probe { - .assigned_sink = "endpoint-id", - .configured_sink = "other-sink", - .intent = platf::audio_capture_intent_e::host_and_client, - .process_id = current_process_id, - .creation_time = creation_time, - .device_enum = &enumerator, - .keep_default = false, - }; + probe.configured_sink = "other-sink"; EXPECT_TRUE(platf::audio::tests::microphone_attempts_loopback_for_target(probe)); - EXPECT_EQ(probe.attempted_process_id, current_process_id); + EXPECT_EQ(probe.attempted_process_id, probe.process_id); // The failing activator falls back to endpoint capture against the assigned sink. EXPECT_EQ(enumerator.get_device_calls, 1); EXPECT_EQ(enumerator.last_requested_id, L"endpoint-id"); @@ -995,24 +952,15 @@ TEST(WindowsAudioTest, MicrophoneLoopbackDecisionIgnoresConfiguredSink) { TEST(WindowsAudioTest, MicrophoneRejectsStaleIdentityAfterPidReuse) { fake_device_enumerator_t enumerator {L"endpoint-id"}; - const auto current_process_id = static_cast(::GetCurrentProcessId()); - ASSERT_NE(current_process_id, 0u); - const auto creation_time = current_process_creation_time(); - ASSERT_NE(creation_time, 0u); + auto probe = make_current_process_probe(enumerator); + ASSERT_NE(probe.process_id, 0u); + ASSERT_NE(probe.creation_time, 0u); // The recorded baseline names the original occupant; the live PID now names // a different process (same PID, different marker). Validation must reject // the stale baseline so no loopback activation targets the replacement, and // endpoint fallback must resolve through the assigned sink instead. - platf::audio::tests::microphone_loopback_probe_t probe { - .assigned_sink = "endpoint-id", - .configured_sink = {}, - .intent = platf::audio_capture_intent_e::host_and_client, - .process_id = current_process_id, - .creation_time = creation_time + 1, - .device_enum = &enumerator, - .keep_default = false, - }; + probe.creation_time += 1; EXPECT_FALSE(platf::audio::tests::microphone_attempts_loopback_for_target(probe)); EXPECT_EQ(probe.attempted_process_id, 0u); EXPECT_EQ(enumerator.get_device_calls, 1);