diff --git a/docs/configuration.md b/docs/configuration.md index 6024df7cdb6..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,23 +943,33 @@ consent prompt for directory ACLs, so the Web UI shows setup steps for correctin -### external_audio +### keep_default_sink @@ -967,8 +981,7 @@ consent prompt for directory ACLs, so the Web UI shows setup steps for correctin
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.} + 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.}
Example @code{} - external_audio = enabled - audio_sink = My Streaming Mix + keep_default_sink = enabled @endcode
diff --git a/src/audio.cpp b/src/audio.cpp index 00ddb12dc3d..dc381bf0d03 100644 --- a/src/audio.cpp +++ b/src/audio.cpp @@ -4,6 +4,7 @@ */ // standard includes #include +#include #include // lib includes @@ -33,6 +34,27 @@ 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 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 + * `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() { + static std::mutex mutex; + return mutex; + } + /** * @brief Select the Opus stream configuration for a channel count and quality tier. * @@ -152,8 +174,68 @@ namespace audio { } } + /** + * @brief Select the capture sink for startup without touching the capture target. + */ + 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. 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_, platf::process_identity_t {0, 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); @@ -184,46 +266,52 @@ 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; - } + const auto capture_intent = resolve_audio_capture_intent(config::audio.keep_default_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; - } - } + // 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)) { - // 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)) { - return; - } + // 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 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; + 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 the selected sink cannot be selected, there is no audio to capture. + if (!select_audio_capture_sink(*control, routing)) { + return; } } 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; } @@ -260,7 +348,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; } @@ -284,6 +372,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; @@ -336,7 +430,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..f8a41b1f899 100644 --- a/src/audio.h +++ b/src/audio.h @@ -11,6 +11,12 @@ #include #include +#include +#include +#include +#include +#include +#include namespace stream { struct session_t; @@ -94,6 +100,235 @@ 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 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 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. + * + * 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). + * @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, + 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}; + if (!config_sink.empty()) { + selected = std::string {config_sink}; + } + + // Prefer the virtual sink if host playback is disabled or there's no other sink. + // 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; + break; + case 6: + selected = null_sinks->surround51; + break; + case 8: + selected = null_sinks->surround71; + break; + default: + 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() ? std::string {host_sink} : std::string {config_sink}; + } + + 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]] 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 pinned_sink; + } + return keep_default_requested ? host_and_client : 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]] 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 client_only: + return "client_only"; + case host_and_client: + return "host_and_client"; + case pinned_sink: + return "pinned_sink"; + } + 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()) 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 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 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. + */ + [[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_; ///< 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(). + bool recorded_ = false; ///< Whether this session called set_capture_target(). + }; + /** * @brief Byte buffer used for encoded audio packet payloads. */ diff --git a/src/config.cpp b/src/config.cpp index 77d2d466e3d..30e794639d9 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -803,7 +803,7 @@ namespace config { {}, // virtual_sink true, // stream audio true, // install_steam_drivers - false, // external_audio + false, // keep_default_sink }; /** @@ -1810,7 +1810,20 @@ 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. 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); +#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/config.h b/src/config.h index dc890e2ee40..b381126c351 100644 --- a/src/config.h +++ b/src/config.h @@ -241,7 +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; on Windows an external router may own endpoint defaults and formats }; /** 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 b2616887be3..47e329eee47 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,111 @@ 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 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(). + * + * 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 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: + * 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. */ @@ -893,6 +999,95 @@ 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 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. + * + * 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 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 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 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]] process_identity_t identity) { + // Intentionally empty: backends without per-process capture inherit this no-op. + } + + /** + * @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) { + // 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. + * + * @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. * @@ -906,6 +1101,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. @@ -924,6 +1135,126 @@ namespace platf { * @brief Destroy the audio control. */ virtual ~audio_control_t() = default; + + protected: + 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(). + * + * 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 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_`. + * + * @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_; + } + + /** + * @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/platform/linux/audio.cpp b/src/platform/linux/audio.cpp index f13e0db7cc2..fd596e816ac 100644 --- a/src/platform/linux/audio.cpp +++ b/src/platform/linux/audio.cpp @@ -329,15 +329,30 @@ 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. + + 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_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. + }; 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. @@ -458,16 +473,61 @@ 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. * * @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,20 +547,9 @@ 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; - - ++nullcount; - } else if (!std::strcmp(sink_info->name, surround51)) { - index.surround51 = sink_info->owner_module; - - ++nullcount; - } else if (!std::strcmp(sink_info->name, surround71)) { - index.surround71 = sink_info->owner_module; - - ++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)}; @@ -520,39 +569,16 @@ 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) { - BOOST_LOG(warning) << "Couldn't create virtual sink for stereo: "sv << pa_strerror(pa_context_errno(ctx.get())); - } else { - ++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) { - BOOST_LOG(warning) << "Couldn't create virtual sink for surround-51: "sv << pa_strerror(pa_context_errno(ctx.get())); - } else { - ++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) { - BOOST_LOG(warning) << "Couldn't create virtual sink for surround-71: "sv << pa_strerror(pa_context_errno(ctx.get())); - } else { - ++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; } 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)); @@ -643,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(); @@ -657,6 +683,29 @@ 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. + * + * 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 { + return record_keep_default_capture_sink(sink); + } + /** * @brief Update the sink value on the backend. * @@ -688,15 +737,39 @@ namespace platf { return -1; } - requested_sink = sink; + record_capture_sink(sink); 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_index); + } + ~server_t() override { - unload_null(index.stereo); - unload_null(index.surround51); - unload_null(index.surround71); + 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. + BOOST_LOG(warning) << "Suppressed unexpected exception while unloading null-sinks during teardown"sv; + } if (worker.joinable()) { pa_context_disconnect(ctx.get()); diff --git a/src/platform/macos/microphone.mm b/src/platform/macos/microphone.mm index 72776e73d14..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. * @@ -81,6 +84,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 +185,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..cefe4928941 100644 --- a/src/platform/windows/audio.cpp +++ b/src/platform/windows/audio.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include @@ -878,19 +879,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 +899,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. @@ -941,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)); } } @@ -1002,13 +1006,8 @@ 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 @@ -1028,9 +1027,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); @@ -1117,7 +1116,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; } @@ -1150,6 +1151,65 @@ 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. + */ + [[nodiscard]] bool should_install_default_callback(std::string_view sink) const { + return static_cast(extract_virtual_sink_info(sink)) && !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. + */ + [[nodiscard]] bool should_reset_default_device() const noexcept { + return !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. + */ + [[nodiscard]] bool should_install_steam_drivers() const noexcept { + return !config::audio.keep_default_sink && config::audio.install_steam_drivers; + } + /** * @brief Enumerates supported match field options. */ @@ -1186,13 +1246,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 }; } @@ -1239,6 +1299,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(); @@ -1276,7 +1338,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; } @@ -1416,7 +1478,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, @@ -1490,23 +1552,92 @@ namespace platf::audio { } /** - * @brief Exercise sink discovery without initializing Windows policy interfaces. - * @return Sinks reported by the production controller for the current configuration. + * @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. */ - std::optional configured_sink_info() { + int set_keep_default_sink(const std::string &sink) { audio_control_t control; - return control.sink_info(); + control.reset_default_device(); + return control.set_sink(sink); } /** - * @brief Exercise the external-routing sink-change guard without policy interfaces. - * @param sink Sink a caller attempts to select. - * @return Status from the production sink setter. + * @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 a controlled keep-default mode. + * @param sink Assigned sink name that would be reinstalled. + * @param keep_default keep_default_sink 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) { + audio_control_t control; + auto previous_keep = std::exchange(config::audio.keep_default_sink, keep_default); + bool installed = control.should_install_default_callback(sink); + config::audio.keep_default_sink = previous_keep; + return installed; + } + + /** + * @brief Exercise the startup-reset guard with a controlled keep-default mode. + * @param keep_default keep_default_sink value to test with. + * @return True when the production guard permits resetting the default device. */ - int set_external_sink(const std::string &sink) { + bool resets_default_device(bool keep_default) { audio_control_t control; + auto previous_keep = std::exchange(config::audio.keep_default_sink, keep_default); + bool resets = control.should_reset_default_device(); + config::audio.keep_default_sink = previous_keep; + return resets; + } + + /** + * @brief Exercise the driver-install guard with a controlled keep-default mode. + * @param keep_default keep_default_sink 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 install_requested) { + audio_control_t control; + auto previous_keep = std::exchange(config::audio.keep_default_sink, keep_default); + 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.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(); - return control.set_sink(sink); + config::audio.keep_default_sink = previous_keep; } /** @@ -1523,6 +1654,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. * @@ -1623,7 +1767,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/process.cpp b/src/process.cpp index 90c79ae3891..a63d58da29c 100644 --- a/src/process.cpp +++ b/src/process.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -50,6 +51,36 @@ 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 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 + * 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 +243,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; + + { + // 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; + } - if (!_app.output.empty() && _app.output != "null"sv) { + // 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 +389,211 @@ 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 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() { + // 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()}; + 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; + } + } #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([]() { - while (waitpid(-1, nullptr, WNOHANG) > 0); - }); + // 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 report; + } + + auto proc_t::decide_running_locked() -> running_action_t { 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()) { + 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 _app_id; - } else if (_app.auto_detach && _process.native_exit_code() == 0 && std::chrono::steady_clock::now() - _app_launch_time < 5s) { + 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 _app_id; + return running_action_t::report_app; } - - // Perform cleanup actions now if needed - if (_process) { - BOOST_LOG(info) << "App exited with code ["sv << _process.native_exit_code() << ']'; - terminate(); - } - - return 0; + return running_action_t::needs_cleanup; } 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; + } + + 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 (; _app_prep_it != _app_prep_begin; --_app_prep_it) { - auto &cmd = *(_app_prep_it - 1); + 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 +607,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 +652,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..f2847f0e3af 100644 --- a/src/process.h +++ b/src/process.h @@ -13,6 +13,8 @@ #endif // standard includes +#include +#include #include #include @@ -113,21 +115,63 @@ 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(); + /** + * @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 +214,88 @@ 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 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 Action the caller takes after (optionally) reaping and claiming. + */ + running_action_t decide_running_locked(); + + /** + * @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 +368,19 @@ 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. + * 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. + */ + std::function app_process_identity_provider(proc_t &target); } // namespace proc diff --git a/src_assets/common/assets/web/Config.vue b/src_assets/common/assets/web/Config.vue index c8129d4ccaa..ea8f8e0d586 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,35 @@ ); } + /** + * 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 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, platform) { + if (!Object.hasOwn(config, 'external_audio')) { + return; + } + const keepDefaultSink = config.keep_default_sink; + 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; + } + export default { components: { Navbar, @@ -292,6 +322,8 @@ delete this.config.status; delete this.config.version; + migrateExternalAudioConfig(this.config, this.platform); + // 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 5a6154154f0..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,7 @@ "virtual_sink": "", "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..d24ab3c7886 100644 --- a/src_assets/common/assets/web/configs/tabs/AudioVideo.vue +++ b/src_assets/common/assets/web/configs/tabs/AudioVideo.vue @@ -75,17 +75,13 @@ 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/linux/test_audio.cpp b/tests/unit/platform/linux/test_audio.cpp index 19b962c5528..0fbd6f5d598 100644 --- a/tests/unit/platform/linux/test_audio.cpp +++ b/tests/unit/platform/linux/test_audio.cpp @@ -1,6 +1,6 @@ /** * @file tests/unit/platform/linux/test_audio.cpp - * @brief Tests for the Linux audio capture channel map. + * @brief Tests for Linux audio sink handling and the capture channel map. */ #ifdef __linux__ @@ -16,6 +16,7 @@ #include // local includes + #include "src/config.h" #include "src/platform/common.h" #include "src/thread_safe.h" @@ -155,4 +156,79 @@ TEST(LinuxAudioCallbackTest, TranslatesSuccessAndFailureWithoutContext) { } } +namespace { + /** + * @brief Restore the keep_default_sink setting when a test scope ends. + */ + class keep_default_sink_guard_t { + public: + /** + * @brief Save the current keep_default_sink value. + */ + keep_default_sink_guard_t(): + original_ {config::audio.keep_default_sink} { + } + + /** + * @brief Restore the saved keep_default_sink value. + */ + ~keep_default_sink_guard_t() { + config::audio.keep_default_sink = original_; + } + + private: + bool original_; ///< Value present before the test changed the setting. + }; +} // namespace + +TEST(KeepDefaultSinkAudioTest, CaptureSinkKeepsHostDefaultSink) { + keep_default_sink_guard_t guard; + config::audio.keep_default_sink = true; + + auto control = platf::audio_control(); + if (!control) { + GTEST_SKIP() << "PulseAudio is unavailable in this environment"; + } + + ASSERT_TRUE(control->supports_keep_default_sink()); + + auto before = control->sink_info(); + ASSERT_TRUE(before.has_value()); + + // A nonexistent sink proves the capture path never swaps: set_sink would fail with -1. + EXPECT_EQ(control->capture_sink("sunshine-test-nonexistent-sink"), 0); + // The sink must be recorded for the monitor lookup in microphone(). + EXPECT_EQ(control->snapshot_capture_sink_record(), "sunshine-test-nonexistent-sink"); + + auto after = control->sink_info(); + ASSERT_TRUE(after.has_value()); + EXPECT_EQ(after->host, before->host); +} + +TEST(NullSinkOwnershipTest, AdoptedSinksSurvivePeerTeardown) { + auto first = platf::audio_control(); + if (!first) { + GTEST_SKIP() << "PulseAudio is unavailable in this environment"; + } + + auto first_sink = first->sink_info(); + ASSERT_TRUE(first_sink.has_value()); + ASSERT_TRUE(first_sink->null.has_value()) << "Sunshine null sinks missing from the graph"; + + // A second session adopts the same sinks; tearing it down must not unload + // sinks it didn't create (previously this yanked routed streams back to + // the host default on every disconnect). + { + auto second = platf::audio_control(); + ASSERT_TRUE(second) << "PulseAudio rejected a second control connection"; + auto second_sink = second->sink_info(); + ASSERT_TRUE(second_sink.has_value()); + ASSERT_TRUE(second_sink->null.has_value()); + } + + auto after = first->sink_info(); + ASSERT_TRUE(after.has_value()); + EXPECT_TRUE(after->null.has_value()) << "Peer teardown unloaded adopted null sinks"; +} + #endif // __linux__ diff --git a/tests/unit/platform/macos/test_av_audio.mm b/tests/unit/platform/macos/test_av_audio.mm index 0df9d42604d..3f1861e949c 100644 --- a/tests/unit/platform/macos/test_av_audio.mm +++ b/tests/unit/platform/macos/test_av_audio.mm @@ -20,6 +20,11 @@ #import #include +namespace platf::tests { + bool keep_default_supported(); + int capture_sink_status(const std::string &sink); +} // namespace platf::tests + namespace { bool permission_probe_unmuted = false; ///< Whether the test tap leaves host audio audible. int permission_probe_result = 0; ///< Simulated Core Audio tap setup result. @@ -548,4 +553,12 @@ int test_permission_tap_setup(AVAudio *audio, [[maybe_unused]] SEL selector, UIn } } +/** + * @brief macOS capture never touches the default output, with or without keep-default. + */ +TEST(MacosAudioControlTest, KeepDefaultModeCapturesWithoutSwapping) { + EXPECT_TRUE(platf::tests::keep_default_supported()); + EXPECT_EQ(platf::tests::capture_sink_status("any-sink"), 0); +} + #endif // __APPLE__ diff --git a/tests/unit/platform/windows/test_audio.cpp b/tests/unit/platform/windows/test_audio.cpp index 192db905170..f90d58951bb 100644 --- a/tests/unit/platform/windows/test_audio.cpp +++ b/tests/unit/platform/windows/test_audio.cpp @@ -9,6 +9,7 @@ #ifdef _WIN32 // standard includes #include + #include #include #include #include @@ -27,9 +28,15 @@ namespace platf::audio::tests { std::vector virtual_sink_waveformats(WORD channel_count); int initialize_audio_control(const std::function> &create_instance); - std::optional configured_sink_info(); - int set_external_sink(const std::string &sink); + int set_keep_default_sink(const std::string &sink); + bool keep_default_supported(); + std::string capture_assigned_sink(const std::string &sink); + bool installs_default_callback(const std::string &sink, bool keep_default); + bool resets_default_device(bool keep_default); + bool installs_steam_drivers(bool keep_default, bool install_requested); + void reset_with_keep_default(); bool sink_device_available(const std::string &sink, IMMDeviceEnumerator *device_enum); + std::optional reported_sinks(IMMDeviceEnumerator *device_enum); bool microphone_available(const std::string &assigned_sink, const std::string &configured_sink, IMMDeviceEnumerator *device_enum); bool capture_follows_default_device(IMMDeviceEnumerator *device_enum, IMMDevice *capture_device); capture_e simulate_default_device_change(bool follows_default_device, bool install_callback, bool render_device_changed, int &callback_count); @@ -216,6 +223,9 @@ namespace { HRESULT STDMETHODCALLTYPE GetDefaultAudioEndpoint(EDataFlow, ERole, IMMDevice **resolved_device) override { ++get_default_device_calls; + if (FAILED(get_default_status)) { + return get_default_status; + } device.AddRef(); *resolved_device = &device; return S_OK; @@ -248,6 +258,7 @@ namespace { fake_device_collection_t collection; HRESULT enumeration_status = S_OK; HRESULT get_device_status = S_OK; + HRESULT get_default_status = S_OK; int get_device_calls = 0; int get_default_device_calls = 0; std::wstring last_requested_id; @@ -323,11 +334,11 @@ TEST(WindowsAudioTest, DefaultDeviceIsUsedWhenNoSinkWasRequested) { /** * @brief Preserve global audio configuration while exercising capture-only mode. */ -class ExternalAudioTest: public testing::Test { +class WindowsKeepDefaultTest: public testing::Test { protected: void SetUp() override { previous = config::audio; - config::audio.external_audio = true; + config::audio.keep_default_sink = true; config::audio.sink = "configured-id"; config::audio.virtual_sink = "ignored-virtual-sink"; policy_requests = 0; @@ -394,88 +405,60 @@ class ExternalAudioTest: public testing::Test { inline static HRESULT enumerator_status = S_OK; ///< Simulated enumeration initialization result. }; -TEST_F(ExternalAudioTest, InitializesWithoutPolicyInterface) { +TEST_F(WindowsKeepDefaultTest, InitializesWithoutPolicyInterface) { EXPECT_EQ(platf::audio::tests::initialize_audio_control(&create_capture_interface), 0); EXPECT_EQ(policy_request_count(), 0); EXPECT_EQ(enumerator_request_count(), 1); } -TEST_F(ExternalAudioTest, InitializationRequiresEndpointEnumerator) { +TEST_F(WindowsKeepDefaultTest, InitializationRequiresEndpointEnumerator) { fail_enumerator_initialization(); EXPECT_NE(platf::audio::tests::initialize_audio_control(&create_capture_interface), 0); EXPECT_EQ(policy_request_count(), 0); EXPECT_EQ(enumerator_request_count(), 1); } -TEST_F(ExternalAudioTest, DisabledModeStillRequiresPolicyInterface) { - config::audio.external_audio = false; +TEST_F(WindowsKeepDefaultTest, DisabledModeStillRequiresPolicyInterface) { + config::audio.keep_default_sink = false; EXPECT_NE(platf::audio::tests::initialize_audio_control(&create_capture_interface), 0); EXPECT_EQ(policy_request_count(), 1); EXPECT_EQ(enumerator_request_count(), 0); } -TEST_F(ExternalAudioTest, RequiresExplicitSink) { - config::audio.sink.clear(); - EXPECT_EXIT(std::exit(platf::audio::tests::configured_sink_info() ? 1 : 0), testing::ExitedWithCode(0), ""); - fake_device_enumerator_t enumerator {L"endpoint-id"}; - EXPECT_FALSE(platf::audio::tests::microphone_available({}, {}, &enumerator)); - EXPECT_EQ(enumerator.get_default_device_calls, 0); - EXPECT_EQ(enumerator.get_device_calls, 0); +TEST_F(WindowsKeepDefaultTest, SinkChangesDoNotAccessPolicyOrFormatInterfaces) { + EXPECT_EXIT(std::exit(platf::audio::tests::set_keep_default_sink("virtual-Stereoendpoint-id")), testing::ExitedWithCode(0), ""); + EXPECT_EXIT(std::exit(platf::audio::tests::set_keep_default_sink("other-endpoint")), testing::ExitedWithCode(0), ""); } -TEST_F(ExternalAudioTest, SkipsDefaultAndVirtualDeviceDiscovery) { - EXPECT_EXIT( - { - const auto sinks = platf::audio::tests::configured_sink_info(); - std::exit(sinks && sinks->host == "configured-id" && !sinks->null ? 0 : 1); - }, - testing::ExitedWithCode(0), - "" - ); -} - -TEST_F(ExternalAudioTest, SinkChangesDoNotAccessPolicyOrFormatInterfaces) { - EXPECT_EXIT(std::exit(platf::audio::tests::set_external_sink("virtual-Stereoendpoint-id")), testing::ExitedWithCode(0), ""); - EXPECT_EXIT(std::exit(platf::audio::tests::set_external_sink("other-endpoint")), testing::ExitedWithCode(0), ""); -} - -TEST_F(ExternalAudioTest, ConfiguredSinkWinsOverAssignedSink) { - fake_device_enumerator_t enumerator {L"configured-id"}; - EXPECT_FALSE(platf::audio::tests::microphone_available("virtual-Stereoother-id", "configured-id", &enumerator)); - EXPECT_EQ(enumerator.last_requested_id, L"configured-id"); +TEST_F(WindowsKeepDefaultTest, AssignedSinkWinsOverConfiguredSink) { + fake_device_enumerator_t enumerator {L"assigned-id"}; + EXPECT_FALSE(platf::audio::tests::microphone_available("assigned-id", "configured-id", &enumerator)); + EXPECT_EQ(enumerator.last_requested_id, L"assigned-id"); EXPECT_EQ(enumerator.get_default_device_calls, 0); } -TEST_F(ExternalAudioTest, MissingSinkDoesNotFallBackToDefault) { +TEST_F(WindowsKeepDefaultTest, MissingSinkDoesNotFallBackToDefault) { fake_device_enumerator_t enumerator {L"endpoint-id"}; EXPECT_FALSE(platf::audio::tests::microphone_available({}, "missing-id", &enumerator)); EXPECT_EQ(enumerator.get_default_device_calls, 0); } -TEST_F(ExternalAudioTest, DisconnectedSinkDoesNotFallBackToDefault) { +TEST_F(WindowsKeepDefaultTest, DisconnectedSinkDoesNotFallBackToDefault) { fake_device_enumerator_t enumerator {L"configured-id"}; enumerator.device.state = DEVICE_STATE_UNPLUGGED; EXPECT_FALSE(platf::audio::tests::microphone_available({}, "configured-id", &enumerator)); EXPECT_EQ(enumerator.get_default_device_calls, 0); } -TEST_F(ExternalAudioTest, DisabledModePreservesAssignedSinkPriority) { - config::audio.external_audio = false; - fake_device_enumerator_t enumerator {L"assigned-id"}; - EXPECT_FALSE(platf::audio::tests::microphone_available("assigned-id", "configured-id", &enumerator)); - EXPECT_EQ(enumerator.last_requested_id, L"assigned-id"); - EXPECT_EQ(enumerator.get_default_device_calls, 0); -} - -TEST_F(ExternalAudioTest, DisabledModePreservesDefaultFallback) { - config::audio.external_audio = false; +TEST_F(WindowsKeepDefaultTest, DisabledModePreservesDefaultFallback) { + config::audio.keep_default_sink = false; fake_device_enumerator_t enumerator {L"endpoint-id"}; EXPECT_TRUE(platf::audio::tests::capture_follows_default_device(&enumerator, nullptr)); EXPECT_EQ(enumerator.get_default_device_calls, 1); EXPECT_EQ(enumerator.get_device_calls, 0); } -TEST_F(ExternalAudioTest, ReactivatedSinkCanBeResolvedAgain) { +TEST_F(WindowsKeepDefaultTest, ReactivatedSinkCanBeResolvedAgain) { fake_device_enumerator_t enumerator {L"configured-id"}; enumerator.device.state = DEVICE_STATE_UNPLUGGED; EXPECT_FALSE(platf::audio::tests::sink_device_available("configured-id", &enumerator)); @@ -484,6 +467,45 @@ TEST_F(ExternalAudioTest, ReactivatedSinkCanBeResolvedAgain) { EXPECT_EQ(enumerator.get_default_device_calls, 0); } +TEST_F(WindowsKeepDefaultTest, KeepsConfiguredSinkWhenDefaultUnavailable) { + fake_device_enumerator_t enumerator {L"configured-id"}; + enumerator.get_default_status = E_FAIL; + + const auto sinks = platf::audio::tests::reported_sinks(&enumerator); + + ASSERT_TRUE(sinks.has_value()); + EXPECT_EQ(sinks->host, "configured-id"); + EXPECT_FALSE(sinks->null.has_value()); + EXPECT_EQ(enumerator.get_default_device_calls, 1); +} + +TEST_F(WindowsKeepDefaultTest, EmptyConfigStillUsesDefaultEndpointAsHost) { + config::audio.sink.clear(); + fake_device_enumerator_t enumerator {L"endpoint-id"}; + + const auto sinks = platf::audio::tests::reported_sinks(&enumerator); + + ASSERT_TRUE(sinks.has_value()); + EXPECT_EQ(sinks->host, "endpoint-id"); + EXPECT_EQ(enumerator.get_default_device_calls, 1); +} + +TEST_F(WindowsKeepDefaultTest, EmptyConfigWithoutDefaultReportsNoSink) { + config::audio.sink.clear(); + fake_device_enumerator_t enumerator {L"endpoint-id"}; + enumerator.get_default_status = E_FAIL; + + EXPECT_FALSE(platf::audio::tests::reported_sinks(&enumerator).has_value()); +} + +TEST_F(WindowsKeepDefaultTest, DisabledModeWithoutDefaultReportsNoSink) { + config::audio.keep_default_sink = false; + fake_device_enumerator_t enumerator {L"configured-id"}; + enumerator.get_default_status = E_FAIL; + + EXPECT_FALSE(platf::audio::tests::reported_sinks(&enumerator).has_value()); +} + TEST(WindowsAudioTest, DefaultCaptureSelectsDefaultEndpoint) { fake_device_enumerator_t enumerator {L"endpoint-id"}; @@ -589,4 +611,25 @@ TEST(WindowsAudioTest, DefaultChangeWithoutCallbackStillReinitializes) { ); EXPECT_EQ(callback_count, 0); } + +TEST(WindowsAudioTest, KeepDefaultModeCapturesWithoutSwapping) { + EXPECT_TRUE(platf::audio::tests::keep_default_supported()); + EXPECT_EQ(platf::audio::tests::capture_assigned_sink("endpoint-id"), "endpoint-id"); +} + +TEST(WindowsAudioTest, KeepDefaultModeInstallsNoReassertionCallback) { + constexpr const char *virtual_sink = "virtual-Stereoendpoint-id"; + EXPECT_TRUE(platf::audio::tests::installs_default_callback(virtual_sink, false)); + EXPECT_FALSE(platf::audio::tests::installs_default_callback(virtual_sink, true)); + EXPECT_FALSE(platf::audio::tests::installs_default_callback("endpoint-id", false)); +} + +TEST(WindowsAudioTest, HandsOffModeSkipsDefaultResetAndDriverInstall) { + EXPECT_TRUE(platf::audio::tests::resets_default_device(false)); + EXPECT_FALSE(platf::audio::tests::resets_default_device(true)); + EXPECT_TRUE(platf::audio::tests::installs_steam_drivers(false, true)); + EXPECT_FALSE(platf::audio::tests::installs_steam_drivers(true, true)); + EXPECT_FALSE(platf::audio::tests::installs_steam_drivers(false, false)); + platf::audio::tests::reset_with_keep_default(); +} #endif diff --git a/tests/unit/test_audio.cpp b/tests/unit/test_audio.cpp index 8561cb3d9c5..63a1ca688cf 100644 --- a/tests/unit/test_audio.cpp +++ b/tests/unit/test_audio.cpp @@ -6,8 +6,20 @@ // test includes #include "../tests_common.h" +// standard includes +#include +#include +#include +#include +#include +#include +#include +#include +#include + // local includes #include +#include #include #include @@ -114,3 +126,1233 @@ TEST_P(AudioTest, TestEncode) { timer.join(); capture.join(); } + +// The routing policy is pure: resolvable at compile time, no I/O, no globals. +static_assert(!resolve_sink_routing_policy(true, true).swap_at_startup); +static_assert(!resolve_sink_routing_policy(true, true).restore_at_teardown); +static_assert(resolve_sink_routing_policy(true, false).swap_at_startup); +static_assert(resolve_sink_routing_policy(true, false).restore_at_teardown); + +TEST(SinkRoutingPolicyTest, KeepsDefaultOnlyWhenRequestedAndSupported) { + const auto keep = resolve_sink_routing_policy(true, true); + EXPECT_FALSE(keep.swap_at_startup); + EXPECT_FALSE(keep.restore_at_teardown); + + // Unsupported backends keep legacy swap-and-restore even when requested: + // the (true, false) row is the MUST-1 regression pin (startup swapped, + // teardown skipped, host default stranded). + for (const auto &[requested, supported] : {std::pair {false, false}, {false, true}, {true, false}}) { + const auto legacy = resolve_sink_routing_policy(requested, supported); + EXPECT_TRUE(legacy.swap_at_startup); + EXPECT_TRUE(legacy.restore_at_teardown); + } +} + +TEST(SinkRoutingPolicyTest, StartupAndTeardownNeverDiverge) { + for (const auto requested : {false, true}) { + for (const auto supported : {false, true}) { + const auto policy = resolve_sink_routing_policy(requested, supported); + EXPECT_EQ(policy.swap_at_startup, policy.restore_at_teardown); + } + } +} + +namespace { + /** + * @brief Virtual sink names shared by the capture-routing tests. + */ + std::optional test_null_sinks() { + return platf::sink_t::null_t {"virtual-stereo", "virtual-surround51", "virtual-surround71"}; + } +} // namespace + +/** + * @brief Capture-only startup must target the host sink when nothing is configured. + * + * Regression test: without a swap, applications stay on the host default, so + * capturing the virtual sink's monitor would yield silence. + */ +TEST(CaptureRoutingTest, CaptureOnlyUsesHostSinkWhenNothingConfigured) { + for (const auto host_audio : {false, true}) { + const auto routing = resolve_capture_routing(true, true, host_audio, 2, "hw-default", "", test_null_sinks()); + EXPECT_FALSE(routing.swap_at_startup) << "host_audio=" << host_audio; + EXPECT_FALSE(routing.restore_at_teardown) << "host_audio=" << host_audio; + EXPECT_EQ(routing.target, "hw-default") << "host_audio=" << host_audio; + } +} + +/** + * @brief Capture-only startup must target the configured sink when one is set. + */ +TEST(CaptureRoutingTest, CaptureOnlyUsesConfiguredSinkWhenSet) { + for (const auto host_audio : {false, true}) { + const auto routing = resolve_capture_routing(true, true, host_audio, 2, "hw-default", "eq-sink", test_null_sinks()); + EXPECT_FALSE(routing.swap_at_startup) << "host_audio=" << host_audio; + EXPECT_FALSE(routing.restore_at_teardown) << "host_audio=" << host_audio; + EXPECT_EQ(routing.target, "eq-sink") << "host_audio=" << host_audio; + } +} + +/** + * @brief Swap-path startup must preserve the historical virtual sink selection. + */ +TEST(CaptureRoutingTest, SwapPathKeepsVirtualSinkSelection) { + const auto stereo = resolve_capture_routing(false, true, false, 2, "hw-default", "", test_null_sinks()); + EXPECT_TRUE(stereo.swap_at_startup); + EXPECT_TRUE(stereo.restore_at_teardown); + EXPECT_EQ(stereo.target, "virtual-stereo"); + + const auto surround = resolve_capture_routing(false, true, false, 6, "hw-default", "", test_null_sinks()); + EXPECT_TRUE(surround.swap_at_startup); + EXPECT_EQ(surround.target, "virtual-surround51"); + + const auto configured = resolve_capture_routing(false, true, true, 2, "hw-default", "eq-sink", test_null_sinks()); + EXPECT_TRUE(configured.swap_at_startup); + EXPECT_TRUE(configured.restore_at_teardown); + EXPECT_EQ(configured.target, "eq-sink"); + + // An explicit audio_sink pin beats the virtual sink even when host playback is off. + const auto configured_muted = resolve_capture_routing(false, true, false, 2, "hw-default", "eq-sink", test_null_sinks()); + EXPECT_TRUE(configured_muted.swap_at_startup); + EXPECT_TRUE(configured_muted.restore_at_teardown); + EXPECT_EQ(configured_muted.target, "eq-sink"); + + // Legacy backends take the swap path even when keep-default is requested. + const auto legacy = resolve_capture_routing(true, false, false, 2, "hw-default", "", test_null_sinks()); + EXPECT_TRUE(legacy.swap_at_startup); + EXPECT_TRUE(legacy.restore_at_teardown); + EXPECT_EQ(legacy.target, "virtual-stereo"); +} + +/** + * @brief Startup without virtual sinks must fall back to the host sink. + */ +TEST(CaptureRoutingTest, FallsBackToHostWithoutVirtualSinks) { + const auto routing = resolve_capture_routing(true, true, false, 2, "hw-default", "", std::nullopt); + EXPECT_FALSE(routing.swap_at_startup); + EXPECT_FALSE(routing.restore_at_teardown); + EXPECT_EQ(routing.target, "hw-default"); + + // Swap path with no alternative: the target is already the host, so there is nothing to restore. + const auto swap = resolve_capture_routing(false, true, false, 2, "hw-default", "", std::nullopt); + EXPECT_TRUE(swap.swap_at_startup); + EXPECT_FALSE(swap.restore_at_teardown); + EXPECT_EQ(swap.target, "hw-default"); +} + +/** + * @brief The shared intent must map the three UI choices onto config state. + */ +TEST(AudioCaptureIntentTest, ResolvesIntentFromConfig) { + using intent = platf::audio_capture_intent_e; + EXPECT_EQ(resolve_audio_capture_intent(false, ""), intent::client_only); + EXPECT_EQ(resolve_audio_capture_intent(true, ""), intent::host_and_client); + EXPECT_EQ(resolve_audio_capture_intent(false, "eq-sink"), intent::pinned_sink); + EXPECT_EQ(resolve_audio_capture_intent(true, "eq-sink"), intent::pinned_sink); +} + +/** + * @brief Intent names must stay stable for the capture-mode log line. + */ +TEST(AudioCaptureIntentTest, NamesEveryIntent) { + using intent = platf::audio_capture_intent_e; + EXPECT_EQ(audio_capture_intent_name(intent::client_only), "client_only"); + EXPECT_EQ(audio_capture_intent_name(intent::host_and_client), "host_and_client"); + EXPECT_EQ(audio_capture_intent_name(intent::pinned_sink), "pinned_sink"); +} + +// 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. + */ + class legacy_audio_control_t: public platf::audio_control_t { + public: + int set_sink(const std::string &) override { + set_sink_called = true; + return 0; + } + + // Keep the params-bundle overload visible: the positional override below would otherwise hide it. + using platf::audio_control_t::microphone; + + std::unique_ptr microphone(const std::uint8_t *, int, std::uint32_t, std::uint32_t, bool, bool) override { + return nullptr; + } + + bool is_sink_available(const std::string &) override { + return true; + } + + std::optional sink_info() override { + return std::nullopt; + } + + bool set_sink_called = false; ///< Whether the legacy swap path ran. + }; +} // namespace + +/** + * @brief A backend that never learned keep-default must keep swap-and-restore. + * + * Fail-without-fix: if the capture_sink() default stops delegating to + * set_sink(), legacy backends silently capture nothing (returning success + * while selecting no sink) instead of taking the historical swap path. + */ +TEST(AudioControlAdapterTest, LegacyBackendKeepsSwapBehavior) { + legacy_audio_control_t control; + EXPECT_FALSE(control.supports_keep_default_sink()); + EXPECT_EQ(control.capture_sink("any-sink"), 0); + EXPECT_TRUE(control.set_sink_called); +} + +/** + * @brief Recording a capture target must be a safe no-op on legacy backends. + * + * Fail-without-fix: if the set_capture_target() default gains behavior (or + * crashes on backends without target storage), every legacy session breaks, + * since the guard refreshes unconditionally before microphone creation. + */ +TEST(AudioControlAdapterTest, DefaultCaptureTargetSetterIsNoOp) { + legacy_audio_control_t control; + 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); +} + +/** + * @brief Releasing a capture target must be a safe no-op on legacy backends. + * + * Fail-without-fix: if the clear_capture_target() default gains behavior (or + * crashes on backends without target storage), every legacy session teardown + * breaks, since the guard releases unconditionally when a target was recorded. + */ +TEST(AudioControlAdapterTest, DefaultCaptureTargetClearIsNoOp) { + legacy_audio_control_t control; + control.clear_capture_target(platf::audio_capture_intent_e::host_and_client, 1234); + control.clear_capture_target(platf::audio_capture_intent_e::client_only, 0); + EXPECT_FALSE(control.set_sink_called); +} + +namespace { + /** + * @brief Backend that records which sink the availability probe checks. + */ + class probe_audio_control_t: public platf::audio_control_t { + public: + /** + * @brief Create a probe backend with a controlled keep-default capability. + * @param supports_keep Whether capture_sink() is supported without swapping. + */ + explicit probe_audio_control_t(bool supports_keep): + supports_keep {supports_keep} { + } + + int set_sink(const std::string &) override { + return 0; + } + + // Keep the params-bundle overload visible: the positional override below would otherwise hide it. + using platf::audio_control_t::microphone; + + std::unique_ptr microphone(const std::uint8_t *, int, std::uint32_t, std::uint32_t, bool, bool) override { + return nullptr; + } + + bool is_sink_available(const std::string &sink) override { + probed_sink = sink; + return true; + } + + std::optional sink_info() override { + return std::nullopt; + } + + bool supports_keep_default_sink() const override { + return supports_keep; + } + + bool supports_keep; ///< Whether this backend supports keep-default capture. + std::string probed_sink; ///< Sink most recently passed to is_sink_available(). + }; + + /** + * @brief Build an audio context whose host sink differs from the configured sink. + * @param supports_keep Whether the fake backend supports keep-default capture. + * @param probed Receives the fake backend so tests can inspect the probed sink. + * @return Audio context with host sink "hw-default". + */ + audio_ctx_t make_probe_ctx(bool supports_keep, probe_audio_control_t *&probed) { + auto control = std::make_unique(supports_keep); + probed = control.get(); + + audio_ctx_t ctx {}; + ctx.control = std::move(control); + ctx.restore_sink = false; + ctx.sink.host = "hw-default"; + return ctx; + } + + /** + * @brief Preserve the global audio config while a probe test rewrites it. + */ + struct audio_config_guard_t { + audio_config_guard_t() = default; + audio_config_guard_t(const audio_config_guard_t &) = delete; + audio_config_guard_t &operator=(const audio_config_guard_t &) = delete; + audio_config_guard_t(audio_config_guard_t &&) = delete; + audio_config_guard_t &operator=(audio_config_guard_t &&) = delete; + + bool keep_default_sink = config::audio.keep_default_sink; ///< Saved keep_default_sink value. + std::string sink = config::audio.sink; ///< Saved audio_sink value. + + ~audio_config_guard_t() noexcept { + try { + config::audio.keep_default_sink = keep_default_sink; + config::audio.sink = sink; + } catch (...) { + // Teardown restore must not throw during stack unwinding: report via noexcept fputs + // (Boost.Log allocates/may throw, so it cannot be used in this noexcept destructor). + std::fputs("audio_config_guard_t: failed to restore audio config\n", stderr); + } + } + }; +} // namespace + +TEST(SinkAvailabilityProbeTest, KeepDefaultProbesConfiguredSink) { + const audio_config_guard_t guard; + config::audio.keep_default_sink = true; + config::audio.sink = "configured-sink"; + + probe_audio_control_t *probed = nullptr; + auto ctx = make_probe_ctx(true, probed); + + EXPECT_TRUE(is_audio_ctx_sink_available(ctx)); + EXPECT_EQ(probed->probed_sink, "configured-sink"); +} + +TEST(SinkAvailabilityProbeTest, KeepDefaultWithoutConfiguredSinkProbesHostSink) { + const audio_config_guard_t guard; + config::audio.keep_default_sink = true; + config::audio.sink.clear(); + + probe_audio_control_t *probed = nullptr; + auto ctx = make_probe_ctx(true, probed); + + EXPECT_TRUE(is_audio_ctx_sink_available(ctx)); + EXPECT_EQ(probed->probed_sink, "hw-default"); +} + +TEST(SinkAvailabilityProbeTest, SwapModeProbesHostSink) { + const audio_config_guard_t guard; + config::audio.keep_default_sink = false; + config::audio.sink = "configured-sink"; + + probe_audio_control_t *probed = nullptr; + auto ctx = make_probe_ctx(true, probed); + + EXPECT_TRUE(is_audio_ctx_sink_available(ctx)); + EXPECT_EQ(probed->probed_sink, "hw-default"); +} + +TEST(SinkAvailabilityProbeTest, UnsupportedBackendProbesHostSink) { + const audio_config_guard_t guard; + config::audio.keep_default_sink = true; + config::audio.sink = "configured-sink"; + + probe_audio_control_t *probed = nullptr; + auto ctx = make_probe_ctx(false, probed); + + EXPECT_TRUE(is_audio_ctx_sink_available(ctx)); + EXPECT_EQ(probed->probed_sink, "hw-default"); +} + +namespace { + /** + * @brief Microphone stub that never blocks the capture loop. + */ + class stub_mic_t: public platf::mic_t { + public: + /** + * @brief Report a timeout instead of delivering samples. + * @param frame_buffer Destination for captured samples, left untouched. + * @return Timeout status so the capture loop keeps polling. + */ + platf::capture_e sample(std::vector &frame_buffer) override { + (void) frame_buffer; + return platf::capture_e::timeout; + } + }; + + /** + * @brief Backend that records the capture() orchestration calls for verification. + */ + class recording_audio_control_t: public platf::audio_control_t { + public: + int set_sink(const std::string &sink) override { + calls.push_back("set_sink:" + sink); + return set_sink_status; + } + + bool supports_keep_default_sink() const override { + return supports_keep; + } + + 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; + } + + /** + * @brief Record the refreshed capture target. + * @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 { + calls.emplace_back("set_capture_target"); + set_intent = intent; + set_process_id = identity.process_id; + set_creation_time = identity.creation_time; + record_capture_target(intent, identity.process_id); + } + + /** + * @brief Record the released capture target. + * @param intent Capture intent recorded by the session being torn down. + * @param process_id PID recorded by the session being torn down, or 0 for endpoint capture. + */ + void clear_capture_target(platf::audio_capture_intent_e intent, std::uint32_t process_id) override { + calls.emplace_back("clear_capture_target"); + clear_intent = intent; + clear_process_id = process_id; + } + + // Keep the params-bundle overload visible: the positional override below would otherwise hide it. + using platf::audio_control_t::microphone; + + std::unique_ptr microphone(const std::uint8_t *mapping, int channels, std::uint32_t sample_rate, std::uint32_t frame_size, bool continuous_audio, bool host_audio_enabled) override { + calls.emplace_back("microphone"); + mic_mapping = mapping; + mic_channels = channels; + mic_sample_rate = sample_rate; + mic_frame_size = frame_size; + mic_continuous_audio = continuous_audio; + mic_host_audio_enabled = host_audio_enabled; + if (fail_microphone) { + return nullptr; + } + return std::make_unique(); + } + + bool is_sink_available(const std::string &) override { + return true; + } + + std::optional sink_info() override { + return std::nullopt; + } + + /** + * @brief Find the position of a recorded call in the call sequence. + * @param prefix Call name prefix to search for. + * @return Index of the first matching call, or calls.size() when absent. + */ + std::size_t call_index(std::string_view prefix) const { + for (std::size_t i = 0; i < calls.size(); ++i) { + if (calls[i].compare(0, prefix.size(), prefix) == 0) { + return i; + } + } + return calls.size(); + } + + bool supports_keep = true; ///< Whether capture_sink() is supported without swapping. + 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. + int mic_channels = 0; ///< Channels from the last microphone() call. + std::uint32_t mic_sample_rate = 0; ///< Sample rate from the last microphone() call. + std::uint32_t mic_frame_size = 0; ///< Frame size from the last microphone() call. + bool mic_continuous_audio = false; ///< Continuous flag from the last microphone() call. + bool mic_host_audio_enabled = false; ///< Host-audio flag from the last microphone() call. + }; + + /** + * @brief Build a capture-only routing that never swaps the host default. + * @return Startup plan targeting the saved host sink. + */ + capture_routing_t make_capture_routing() { + return resolve_capture_routing(true, true, false, 2, "hw-default", "", std::nullopt); + } + + /** + * @brief Build a swap routing that swaps to the virtual sink and restores it. + * @return Startup plan targeting the virtual stereo sink. + */ + capture_routing_t make_swap_routing() { + return resolve_capture_routing(false, true, false, 2, "hw-default", "", test_null_sinks()); + } + + /** + * @brief Build a swap routing with nothing to restore. + * @return Startup plan targeting the host sink it already points at. + */ + capture_routing_t make_swap_without_restore_routing() { + return resolve_capture_routing(false, true, false, 2, "hw-default", "", std::nullopt); + } + + /** + * @brief Build microphone parameters matching the stereo test layout. + * @return Capture parameters for a 5 ms stereo frame at 48 kHz. + */ + platf::microphone_params_t make_mic_params() { + platf::microphone_params_t params {}; + params.mapping = nullptr; + params.channels = 2; + params.sample_rate = 48000; + params.frame_size = 240; + params.continuous_audio = false; + params.host_audio_enabled = false; + return params; + } +} // namespace + +/** + * @brief The capture-only path must capture without swapping the host default. + * + * Fail-without-fix: if the dispatch branches swap, a keep-default session + * calls set_sink() and steals the host default it promised to leave alone; + * the missing capture_sink() call below is that regression. + */ +TEST(CaptureSinkDispatchTest, CapturePathUsesCaptureSink) { + recording_audio_control_t control; + const auto routing = make_capture_routing(); + ASSERT_FALSE(routing.swap_at_startup); + + EXPECT_TRUE(select_audio_capture_sink(control, routing)); + EXPECT_EQ(control.call_index("capture_sink:hw-default"), 0U); + EXPECT_EQ(control.call_index("set_sink"), control.calls.size()); +} + +/** + * @brief A failed capture-only selection must abort before any refresh. + * + * Fail-without-fix: if select_audio_capture_sink() returns true on a + * capture_sink() failure, capture() proceeds to refresh and microphone + * creation against a sink that was never selected, capturing silence (or the + * wrong endpoint) instead of aborting startup. + */ +TEST(CaptureSinkDispatchTest, CaptureFailureAbortsStartup) { + recording_audio_control_t control; + control.capture_sink_status = -1; + + EXPECT_FALSE(select_audio_capture_sink(control, make_capture_routing())); + EXPECT_EQ(control.call_index("set_sink"), control.calls.size()); + EXPECT_EQ(control.call_index("set_capture_target"), control.calls.size()); +} + +/** + * @brief The swap path must swap the host default instead of capturing. + * + * Fail-without-fix: if the dispatch branches swap, a quiet-streaming session + * calls capture_sink() and never moves applications onto the virtual sink, so + * the host keeps playing aloud while the client captures the wrong endpoint. + */ +TEST(CaptureSinkDispatchTest, SwapPathUsesSetSink) { + recording_audio_control_t control; + const auto routing = make_swap_routing(); + ASSERT_TRUE(routing.swap_at_startup); + ASSERT_TRUE(routing.restore_at_teardown); + + EXPECT_TRUE(select_audio_capture_sink(control, routing)); + EXPECT_EQ(control.call_index("set_sink:" + routing.target), 0U); + EXPECT_EQ(control.call_index("capture_sink"), control.calls.size()); +} + +/** + * @brief A failed swap must abort before any refresh. + * + * Fail-without-fix: if select_audio_capture_sink() returns true on a + * set_sink() failure, capture() records a restore flag for a swap that never + * happened and then captures the unswapped default, stranding teardown + * symmetry and streaming the wrong source. + */ +TEST(CaptureSinkDispatchTest, SwapFailureAbortsStartup) { + recording_audio_control_t control; + control.set_sink_status = -1; + + EXPECT_FALSE(select_audio_capture_sink(control, make_swap_routing())); + EXPECT_EQ(control.call_index("capture_sink"), control.calls.size()); + EXPECT_EQ(control.call_index("set_capture_target"), control.calls.size()); +} + +/** + * @brief A swap with nothing to restore must skip the sink call entirely. + * + * Fail-without-fix: if the no-restore skip is dropped, startup reasserts the + * host default as a swap even though the target already is the host sink, + * needlessly disturbing routing (and any default-device watchers) for a no-op. + */ +TEST(CaptureSinkDispatchTest, SwapWithoutRestoreSkipsSinkCall) { + recording_audio_control_t control; + const auto routing = make_swap_without_restore_routing(); + ASSERT_TRUE(routing.swap_at_startup); + ASSERT_FALSE(routing.restore_at_teardown); + + EXPECT_TRUE(select_audio_capture_sink(control, routing)); + EXPECT_TRUE(control.calls.empty()); +} + +/** + * @brief The endpoint target must be recorded ahead of microphone creation. + * + * Fail-without-fix: if the guard skips the refresh (or creates the microphone + * first), the backend captures a stale target from a previous session instead + * of this session's intent, and the set-before-microphone ordering below breaks. + */ +TEST(CaptureRefreshTest, EndpointTargetIsRecordedBeforeMicrophone) { + recording_audio_control_t control; + std::mutex mutex; + session_capture_target_t target {control, platf::audio_capture_intent_e::host_and_client, mutex}; + + auto mic = target.create_microphone(make_mic_params()); + + EXPECT_TRUE(static_cast(mic)); + EXPECT_TRUE(target.recorded()); + EXPECT_EQ(control.set_intent, platf::audio_capture_intent_e::host_and_client); + EXPECT_EQ(control.set_process_id, 0u); + EXPECT_LT(control.call_index("set_capture_target"), control.call_index("microphone")); +} + +/** + * @brief Endpoint capture must record PID 0 for every intent. + * + * Fail-without-fix: if the guard records anything but the endpoint target, + * a session captures a process it never selected instead of the endpoint, + * defeating silence or the configured sink pin. + */ +TEST(CaptureRefreshTest, EndpointCasesRecordZeroPid) { + using intent = platf::audio_capture_intent_e; + + for (const auto case_intent : {intent::host_and_client, intent::client_only, intent::pinned_sink}) { + recording_audio_control_t control; + std::mutex mutex; + session_capture_target_t target {control, case_intent, mutex}; + + auto mic = target.create_microphone(make_mic_params()); + + EXPECT_TRUE(static_cast(mic)); + EXPECT_TRUE(target.recorded()); + EXPECT_EQ(control.set_process_id, 0u); + EXPECT_EQ(control.set_intent, case_intent); + EXPECT_LT(control.call_index("set_capture_target"), control.call_index("microphone")); + } +} + +/** + * @brief A microphone failure must still leave the refreshed target behind for teardown. + * + * Fail-without-fix: if the guard only records the target on microphone + * success, a failed creation leaks the shared target (no teardown release + * ever runs for it) and the next session inherits a target this session + * recorded but never owned. + */ +TEST(CaptureRefreshTest, MicrophoneFailureStillRecordsTarget) { + recording_audio_control_t control; + control.fail_microphone = true; + std::mutex mutex; + + { + session_capture_target_t target {control, platf::audio_capture_intent_e::host_and_client, mutex}; + + EXPECT_FALSE(static_cast(target.create_microphone(make_mic_params()))); + EXPECT_TRUE(target.recorded()); + EXPECT_EQ(control.set_process_id, 0u); + } + + // The failed refresh still owns a target, so scope exit must release it. + EXPECT_EQ(control.clear_intent, platf::audio_capture_intent_e::host_and_client); + EXPECT_EQ(control.clear_process_id, 0u); +} + +/** + * @brief The restore flag must follow the routing decision in both modes. + * + * capture() assigns routing.restore_at_teardown directly, so this pins the + * decision values that flow into that assignment, including the + * swap-without-restore edge. + * + * Fail-without-fix: if the capture-only routing ever reports restore=true, + * teardown restores a sink that was never swapped, yanking the user's live + * default; if the swap routing reports restore=false, teardown strands the + * virtual sink as the host default after the stream ends. + */ +TEST(CaptureRestoreTest, RecordsRoutingRestoreDecision) { + audio_ctx_t ctx {}; + ctx.restore_sink = true; + ctx.restore_sink = make_capture_routing().restore_at_teardown; + EXPECT_FALSE(ctx.restore_sink); + + ctx.restore_sink = make_swap_routing().restore_at_teardown; + EXPECT_TRUE(ctx.restore_sink); + + ctx.restore_sink = make_swap_without_restore_routing().restore_at_teardown; + EXPECT_FALSE(ctx.restore_sink); +} + +/** + * @brief Teardown without a refresh must leave the shared target untouched. + * + * Fail-without-fix: if the guard clears unconditionally, a session that + * aborted before any refresh (for example a failed sink selection) wipes a + * survivor session's live target on its way out. + */ +TEST(CaptureReleaseTest, SkipsClearWhenNothingRecorded) { + recording_audio_control_t control; + std::mutex mutex; + + { + session_capture_target_t target {control, platf::audio_capture_intent_e::host_and_client, mutex}; + EXPECT_FALSE(target.recorded()); + } + + EXPECT_TRUE(control.calls.empty()); +} + +/** + * @brief Teardown after a refresh must release exactly the recorded target. + * + * Fail-without-fix: if the guard releases a stale target instead of the last + * recorded one, the backend keeps the dead session's target (leaking capture + * state) or wipes a survivor's newer target. + */ +TEST(CaptureReleaseTest, ClearsRecordedTarget) { + recording_audio_control_t control; + std::mutex mutex; + + { + session_capture_target_t target {control, platf::audio_capture_intent_e::host_and_client, mutex}; + auto mic = target.create_microphone(make_mic_params()); + ASSERT_TRUE(static_cast(mic)); + // Release lands on scope exit, so only the refresh and creation run here. + ASSERT_EQ(control.calls.size(), 2U); + } + + ASSERT_EQ(control.calls.size(), 3U); + EXPECT_EQ(control.calls[2], "clear_capture_target"); + EXPECT_EQ(control.clear_intent, platf::audio_capture_intent_e::host_and_client); + EXPECT_EQ(control.clear_process_id, 0u); +} + +/** + * @brief The startup sequence must dispatch, refresh, create, and release in order. + * + * Fail-without-fix: a dispatch-branch swap shows up as the wrong sink call + * here, a dropped refresh as a missing set_capture_target before microphone(), + * and a leaked guard as a missing trailing clear_capture_target. + */ +TEST(CaptureOrchestrationTest, StartupSequenceRunsDispatchRefreshCreateAndRelease) { + for (const auto &routing : {make_capture_routing(), make_swap_routing()}) { + recording_audio_control_t control; + std::mutex mutex; + audio_ctx_t ctx {}; + + { + session_capture_target_t target {control, platf::audio_capture_intent_e::host_and_client, mutex}; + + ctx.restore_sink = routing.restore_at_teardown; + EXPECT_EQ(ctx.restore_sink, routing.restore_at_teardown); + ASSERT_TRUE(select_audio_capture_sink(control, routing)); + auto mic = target.create_microphone(make_mic_params()); + ASSERT_TRUE(static_cast(mic)); + ASSERT_EQ(control.calls.size(), 3U); + } + + const std::string expected_sink_call = routing.swap_at_startup ? "set_sink:" + routing.target : "capture_sink:" + routing.target; + ASSERT_EQ(control.calls.size(), 4U); + EXPECT_EQ(control.calls[0], expected_sink_call); + EXPECT_EQ(control.calls[1], "set_capture_target"); + EXPECT_EQ(control.calls[2], "microphone"); + EXPECT_EQ(control.calls[3], "clear_capture_target"); + EXPECT_EQ(control.clear_process_id, 0u); + } +} + +/** + * @brief The parameter-bundle microphone() must forward every field to the positional override. + * + * Fail-without-fix: if the forwarding overload drops, reorders, or mistypes a + * field, backends capture the wrong layout (channels, rate, frame size) or the + * wrong mode (continuous, host audio) while the call still succeeds. + */ +TEST(AudioControlAdapterTest, StructMicrophoneForwardsEveryField) { + recording_audio_control_t control; + platf::audio_control_t &base = control; + const std::array mapping {0, 1, 4, 5, 2, 3}; + const platf::microphone_params_t params {mapping.data(), 6, 48000, 480, true, true}; + + auto mic = base.microphone(params); + + EXPECT_TRUE(static_cast(mic)); + ASSERT_EQ(control.calls.size(), 1U); + EXPECT_EQ(control.calls[0], "microphone"); + EXPECT_EQ(control.mic_mapping, mapping.data()); + EXPECT_EQ(control.mic_channels, 6); + EXPECT_EQ(control.mic_sample_rate, 48000u); + EXPECT_EQ(control.mic_frame_size, 480u); + EXPECT_TRUE(control.mic_continuous_audio); + EXPECT_TRUE(control.mic_host_audio_enabled); +} + +namespace { + /** + * @brief Minimal backend that stores through the shared base record. + * + * Drives the protected opt-in helpers through the production virtuals so + * the centralized sink 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: + int set_sink(const std::string &sink) override { + record_capture_sink(sink); + 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 &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; + + 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_capture_target; + 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 base 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_capture_target; + 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 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 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) { + 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); + } + 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); + } + }; + { + 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 + * 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, 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 recorded_audio_control_t { +public: + int set_sink(const std::string &) override { + return 0; + } + + // Stays at the base default: these tests pin record/hook pairing, not capture support. + bool supports_process_capture() const override { + return false; + } + + /** + * @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; + } + +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. + * + * 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"); +} + +/** + * @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_config.cpp b/tests/unit/test_config.cpp index f3bb7ceaf1c..9230d563109 100644 --- a/tests/unit/test_config.cpp +++ b/tests/unit/test_config.cpp @@ -428,3 +428,81 @@ INSTANTIATE_TEST_SUITE_P( StreamResolutionCapCase {100, 100, 10000, 2, true, 100, 2} ) ); + +/** + * @brief Verify the keep_default_sink option parses into the audio configuration. + */ +TEST(KeepDefaultSinkConfigTest, ParsesEnabledAndDisabledValues) { + const bool original_keep_default_sink = config::audio.keep_default_sink; + + config::apply_config_for_test("keep_default_sink = enabled\n"); + EXPECT_TRUE(config::audio.keep_default_sink); + + config::apply_config_for_test("keep_default_sink = disabled\n"); + EXPECT_FALSE(config::audio.keep_default_sink); + + config::audio.keep_default_sink = original_keep_default_sink; +} + +/** + * @brief Verify a missing keep_default_sink key leaves the current value unchanged. + */ +TEST(KeepDefaultSinkConfigTest, MissingKeyLeavesValueUnchanged) { + const bool original_keep_default_sink = config::audio.keep_default_sink; + + config::audio.keep_default_sink = true; + config::apply_config_for_test(""); + EXPECT_TRUE(config::audio.keep_default_sink); + + config::audio.keep_default_sink = false; + config::apply_config_for_test(""); + EXPECT_FALSE(config::audio.keep_default_sink); + + config::audio.keep_default_sink = original_keep_default_sink; +} + +/** + * @brief Verify the deprecated external_audio key migrates only in its original scope. + * + * The legacy key only ever took effect on Windows with an explicit + * `audio_sink`, so the migration enables keep_default_sink only there. + */ +TEST(KeepDefaultSinkConfigTest, LegacyExternalAudioEnablesKeepDefaultSink) { + const bool original_keep_default_sink = config::audio.keep_default_sink; + const std::string original_sink = config::audio.sink; + + config::audio.keep_default_sink = false; + config::apply_config_for_test("audio_sink = pinned-sink\nexternal_audio = enabled\n"); +#ifdef _WIN32 + EXPECT_TRUE(config::audio.keep_default_sink); +#else + EXPECT_FALSE(config::audio.keep_default_sink); +#endif + + config::audio.keep_default_sink = false; + config::audio.sink.clear(); + config::apply_config_for_test("external_audio = enabled\n"); + EXPECT_FALSE(config::audio.keep_default_sink); + + config::audio.keep_default_sink = false; + config::apply_config_for_test("audio_sink = pinned-sink\nexternal_audio = disabled\n"); + EXPECT_FALSE(config::audio.keep_default_sink); + + config::audio.keep_default_sink = original_keep_default_sink; + config::audio.sink = original_sink; +} + +/** + * @brief Verify an explicit keep_default_sink value wins over the legacy external_audio key. + */ +TEST(KeepDefaultSinkConfigTest, ExplicitKeepDefaultSinkWinsOverLegacyExternalAudio) { + const bool original_keep_default_sink = config::audio.keep_default_sink; + + config::apply_config_for_test("external_audio = enabled\nkeep_default_sink = disabled\n"); + EXPECT_FALSE(config::audio.keep_default_sink); + + config::apply_config_for_test("external_audio = disabled\nkeep_default_sink = enabled\n"); + EXPECT_TRUE(config::audio.keep_default_sink); + + config::audio.keep_default_sink = original_keep_default_sink; +} diff --git a/tests/unit/test_process.cpp b/tests/unit/test_process.cpp index 68269cee9e5..1512fe67834 100644 --- a/tests/unit/test_process.cpp +++ b/tests/unit/test_process.cpp @@ -6,13 +6,22 @@ #include "../tests_common.h" // standard includes +#include +#include +#include #include #include #include #include +#include +#include +#include #include +#include #include #include +#include +#include // lib includes #include @@ -23,6 +32,8 @@ #include #else // lib includes + #include + #include #include #endif @@ -654,6 +665,825 @@ 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 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) { + 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); + } + } + if (!signaled) { + signaled = true; + reader_ready.count_down(); + } + } + }}; + 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_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); +} + +#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 + 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); + + 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); + // 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 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()); + + 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; + } + + /** + * @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 + +/** + * @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) { + 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)); + + ASSERT_EQ(launch.target.execute(7, launch.session), 0); + ASSERT_NE(launch.target.app_process_id(), 0u); + + 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 {[&launch]() { + launch.target.terminate(); + }}; + 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 {[&launch, &b_attempting, &b_launch_done, &b_launch_result, &b_started]() { + b_attempting.store(true); + b_started.count_down(); + const int result = launch.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_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. + ASSERT_TRUE(launch.open_gate_file()) << "failed to release the undo gate"; + terminate_thread.join(); + b_thread.join(); + launch.disarm_gate_release(); + EXPECT_EQ(b_launch_result.load(), 0); + 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); +} + +/** + * @brief Verify `running()` reaps exited children on the Desktop placebo poll. + * + * 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. + */ +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"; +} + +/** + * @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) { + 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); +} + +/** + * @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) { + 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"); + + std::jthread terminate_thread {[&launch]() { + launch.target.terminate(); + }}; + ASSERT_TRUE(wait_for_gate_file(launch.signal_file)) << "gated undo 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 terminate()'s undo wait"; + EXPECT_EQ(*poll_result, 0); + ASSERT_TRUE(launch.open_gate_file()) << "failed to release the undo gate"; + terminate_thread.join(); + 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"); +} + +/** + * @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) { + 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 (launch.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 {[&launch, &cleanup_result]() { + cleanup_result.store(launch.target.running()); + }}; + 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 {[&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(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. + 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(); + launch.disarm_gate_release(); + EXPECT_EQ(cleanup_result.load(), 0); + EXPECT_EQ(b_launch_result.load(), 0); + 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); +} + +/** + * @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) { + gated_launch_t launch {"b4-term-launch", {{"Gated", "7", "sleep 30", "L-prep", true, "L-undo", false}}}; + 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 terminate()"; + + // Launch in flight: pollers fail closed with the new id while prep is gated. + EXPECT_EQ(launch.target.running(), 7); + + // terminate() blocks on execute()'s transition until the releaser opens the gate. + std::jthread releaser {[&launch]() { + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + std::ofstream {launch.gate_file}; + }}; + launch.target.terminate(); + releaser.join(); + launch.exec_thread.join(); + launch.disarm_gate_release(); + + 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(launch.target.execute(7, launch.session), 0); + EXPECT_EQ(launch.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) { + 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 (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(launch.setting_file), "A-prep") << "undo ran before running() claimed the corpse"; + + 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(launch.target.execute(7, launch.session), 0); + EXPECT_EQ(launch.target.running(), 7); +} +#endif + TEST_F(ProcessUpdateTest, UpdateAppsAndEnv_PreservesRunningState) { proc::proc.update_apps_and_env(buildNewSource()); diff --git a/tests/web/ConfigBool.test.js b/tests/web/ConfigBool.test.js new file mode 100644 index 00000000000..277b45ca07c --- /dev/null +++ b/tests/web/ConfigBool.test.js @@ -0,0 +1,13 @@ +import { describe, expect, it } from 'vitest' + +import { isConfigBoolEnabled } from '../../src_assets/common/assets/web/config_bool' + +describe('isConfigBoolEnabled', () => { + it.each([true, 1, 'true', 'yes', 'enable', 'enabled', 'on', '1', 'TRUE', 'On'])('treats %s as enabled', value => { + expect(isConfigBoolEnabled(value)).toBe(true) + }) + + it.each([false, 0, 'disabled', 'false', 'no', 'off', '0', '', undefined, null])('treats %s as disabled', value => { + expect(isConfigBoolEnabled(value)).toBe(false) + }) +}) diff --git a/tests/web/ConfigMigration.test.js b/tests/web/ConfigMigration.test.js new file mode 100644 index 00000000000..a85b9314a2d --- /dev/null +++ b/tests/web/ConfigMigration.test.js @@ -0,0 +1,98 @@ +import { flushPromises, shallowMount } from '@vue/test-utils' +import { afterEach, describe, expect, it, vi } from 'vitest' + +vi.mock('../../src_assets/common/assets/web/Navbar.vue', () => ({ + default: { template: '
' }, +})) + +import Config from '../../src_assets/common/assets/web/Config.vue' + +async function mountConfig(serverConfig, platform = 'windows') { + const fetchMock = vi.fn(async (url, options) => { + if (url === './api/config' && !options) { + return { json: async () => ({ platform, version: 'test', status: true, ...serverConfig }) } + } + if (url === './api/config' && options?.method === 'POST') { + return { status: 200, json: async () => ({ status: true }) } + } + throw new Error(`Unexpected fetch: ${url}`) + }) + vi.stubGlobal('fetch', fetchMock) + + const wrapper = shallowMount(Config, { + global: { + mocks: { $t: key => key }, + }, + }) + await flushPromises() + return { wrapper, fetchMock } +} + +afterEach(() => { + vi.unstubAllGlobals() + document.body.innerHTML = '' +}) + +describe('external_audio upgrade migration', () => { + it.each(['enabled', 'true', 'on', 'yes', '1', 'TRUE', 'On'])('maps legacy external_audio=%s to keep_default_sink', async legacyValue => { + const { wrapper } = await mountConfig({ external_audio: legacyValue, audio_sink: 'pinned-sink' }) + + expect(wrapper.vm.config.keep_default_sink).toBe('enabled') + expect(wrapper.vm.config).not.toHaveProperty('external_audio') + wrapper.unmount() + }) + + it('keeps the migrated value disabled when the legacy key is disabled', async () => { + const { wrapper } = await mountConfig({ external_audio: 'disabled' }) + + expect(wrapper.vm.config.keep_default_sink).toBe('disabled') + expect(wrapper.vm.config).not.toHaveProperty('external_audio') + wrapper.unmount() + }) + + it('lets an explicit keep_default_sink win over the legacy key', async () => { + const { wrapper } = await mountConfig({ external_audio: 'enabled', keep_default_sink: 'disabled' }) + + expect(wrapper.vm.config.keep_default_sink).toBe('disabled') + expect(wrapper.vm.config).not.toHaveProperty('external_audio') + wrapper.unmount() + }) + + it('migrates when keep_default_sink is present but empty', async () => { + const { wrapper } = await mountConfig({ external_audio: 'enabled', keep_default_sink: '', audio_sink: 'pinned-sink' }) + + expect(wrapper.vm.config.keep_default_sink).toBe('enabled') + expect(wrapper.vm.config).not.toHaveProperty('external_audio') + wrapper.unmount() + }) + + it('does not migrate on non-Windows platforms', async () => { + const { wrapper } = await mountConfig({ external_audio: 'enabled', audio_sink: 'pinned-sink' }, 'linux') + + expect(wrapper.vm.config.keep_default_sink).toBe('disabled') + expect(wrapper.vm.config).not.toHaveProperty('external_audio') + wrapper.unmount() + }) + + it('does not migrate without an explicit audio_sink', async () => { + const { wrapper } = await mountConfig({ external_audio: 'enabled' }) + + expect(wrapper.vm.config.keep_default_sink).toBe('disabled') + expect(wrapper.vm.config).not.toHaveProperty('external_audio') + wrapper.unmount() + }) + + it('sends neither key when a migrated user unchecks and saves', async () => { + const { wrapper, fetchMock } = await mountConfig({ external_audio: 'enabled', audio_sink: 'pinned-sink' }) + + wrapper.vm.config.keep_default_sink = 'disabled' + await wrapper.vm.save() + + const postCall = fetchMock.mock.calls.find(([, options]) => options?.method === 'POST') + expect(postCall).toBeDefined() + const sent = JSON.parse(postCall[1].body) + expect(sent).not.toHaveProperty('external_audio') + expect(sent).not.toHaveProperty('keep_default_sink') + wrapper.unmount() + }) +}) diff --git a/tests/web/ExternalAudio.test.js b/tests/web/ExternalAudio.test.js deleted file mode 100644 index b921818dce9..00000000000 --- a/tests/web/ExternalAudio.test.js +++ /dev/null @@ -1,81 +0,0 @@ -import { mount } from '@vue/test-utils' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { ref } from 'vue' - -import AudioVideo from '../../src_assets/common/assets/web/configs/tabs/AudioVideo.vue' -import configTabs from '../../src_assets/common/assets/web/configs/config_tabs.json' -import configDocumentation from '../../docs/configuration.md?raw' -import configurationShortcuts from '../../docs/configuration.js?raw' - -function mountAudioVideo(platform) { - const config = structuredClone(configTabs.find(tab => tab.id === 'av').options) - const wrapper = mount(AudioVideo, { - props: { platform, config }, - global: { - mocks: { $t: key => key }, - provide: { - platform: ref(platform), - i18n: { t: key => key }, - }, - stubs: { - AdapterNameSelector: true, - DisplayOutputSelector: true, - DisplayDeviceOptions: true, - DisplayModesSettings: true, - }, - }, - }) - return { wrapper, config } -} - -afterEach(() => { - vi.restoreAllMocks() - document.body.innerHTML = '' -}) - -describe('externally managed audio configuration', () => { - it('renders after the existing Windows audio controls and preserves its saved value', async () => { - const { wrapper, config } = mountAudioVideo('windows') - expect(wrapper.findAll('input').map(input => input.attributes('id'))).toEqual([ - 'audio_sink', - 'virtual_sink', - 'install_steam_audio_drivers', - 'stream_audio', - 'external_audio', - ]) - expect(config.external_audio).toBe('disabled') - expect(wrapper.get('#external_audio').element.checked).toBe(false) - await wrapper.get('#external_audio').setValue(true) - expect(config.external_audio).toBe('enabled') - await wrapper.get('#external_audio').setValue(false) - expect(config.external_audio).toBe('disabled') - wrapper.unmount() - }) - - it.each(['linux', 'freebsd', 'macos'])('keeps the Windows-only option hidden on %s', platform => { - const { wrapper } = mountAudioVideo(platform) - expect(wrapper.find('#external_audio').exists()).toBe(false) - expect(wrapper.find('#stream_audio').exists()).toBe(true) - wrapper.unmount() - }) - - it('provides the standard documentation table and a working configuration shortcut', () => { - const section = configDocumentation.split('### external_audio\n')[1].split('\n### ')[0] - // Doxygen emits configuration headings as h2 and gives tables this class. - document.body.innerHTML = '' - + '

external_audio

' + section.replace('', '
') - const rows = [...document.querySelectorAll('tr')] - expect(rows.map(row => row.cells[0].textContent.trim())).toEqual(['Description', 'Default', 'Example']) - expect(rows[0].textContent).toContain('This option is only supported on Windows.') - expect(rows[1].textContent).toContain('disabled') - expect(rows[2].textContent).toContain('external_audio = enabled') - - new Function('document', configurationShortcuts)(document) - document.dispatchEvent(new Event('DOMContentLoaded')) - const button = document.querySelector('.open-button') - expect(button.textContent).toBe('Open configuration') - const open = vi.spyOn(window, 'open').mockImplementation(() => null) - button.click() - expect(open).toHaveBeenCalledWith('https://localhost:47990/config/#external_audio', '_blank', 'noopener') - }) -}) diff --git a/tests/web/KeepDefaultSink.test.js b/tests/web/KeepDefaultSink.test.js new file mode 100644 index 00000000000..bb0370d8e56 --- /dev/null +++ b/tests/web/KeepDefaultSink.test.js @@ -0,0 +1,21 @@ +import { afterEach, describe, expect, it } from 'vitest' + +import { mountAudioVideo } from './audioVideoMount.js' + +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() + }) +}) 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 } +}