diff --git a/docs/configuration.md b/docs/configuration.md index 6024df7cdb6..619539fd984 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -821,7 +821,6 @@ consent prompt for directory ACLs, so the Web UI shows setup steps for correctin
Sunshine can only access microphones on macOS due to system limitations. To stream system audio use - [Soundflower](https://github.com/mattingalls/Soundflower) or [BlackHole](https://github.com/ExistentialAudio/BlackHole).

@@ -835,6 +834,18 @@ 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.} +
+
+ In the Web UI Audio Capture choices: a blank value with + [keep_default_sink](#keep_default_sink) disabled is Quiet streaming; a blank value + with it enabled is Play on this PC too; a named value is Custom device, + where I route apps myself enables [keep_default_sink](#keep_default_sink) and + Sunshine sets it as the default leaves it disabled so Sunshine sets the named + sink as the default while streaming and restores the previous default afterwards. @@ -868,14 +879,24 @@ consent prompt for directory ACLs, so the Web UI shows setup steps for correctin Description The audio device that's virtual, like Steam Streaming Speakers. This allows Sunshine to stream audio, - while muting the speakers. + while muting the speakers. It applies only to the Quiet streaming path + ([keep_default_sink](#keep_default_sink) disabled; the Windows Web UI shows it only for Quiet + streaming) and is ignored for Play on this PC too and for Custom device + with I route apps myself. A named [audio_sink](#audio_sink) always wins over + this virtual sink, including when Moonlight host playback is off. @tip{See [audio_sink](#audio_sink)!} - @tip{These are some options for virtual sound devices. - * Stream Streaming Speakers (Linux, macOS, Windows) + @tip{This option is Windows only. Some options for virtual sound devices on Windows: + * Steam Streaming Speakers * Steam must be installed. * Enable [install_steam_audio_drivers](#install_steam_audio_drivers) or use Steam Remote Play at least once to install the drivers. - * [Virtual Audio Cable](https://vb-audio.com/Cable) (macOS, Windows) + * [Virtual Audio Cable](https://vb-audio.com/Cable) +
+
+ On FreeBSD/Linux, leave this option unset and use Quiet streaming instead: + Sunshine captures its own null sinks (for example `sink-sunshine-stereo`) automatically. + On macOS, use Custom device with + [BlackHole](https://github.com/ExistentialAudio/BlackHole) and route the game to it yourself. } @@ -939,23 +960,48 @@ consent prompt for directory ACLs, so the Web UI shows setup steps for correctin -### external_audio +### keep_default_sink @@ -967,8 +1013,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. +
+
+ 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) + only affects sink selection on the swap path; in keep-default mode the + capture target is the configured audio_sink, or the host sink when none is configured. + Moonlight's host-playback selection likewise only affects sink selection on the swap path, + except on macOS where it still controls the system tap mute behavior (muted tap versus tap plus + speakers) in keep-default mode.

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

external_audio

' + section.replace('', '
') - const rows = [...document.querySelectorAll('tr')] - expect(rows.map(row => row.cells[0].textContent.trim())).toEqual(['Description', 'Default', 'Example']) - expect(rows[0].textContent).toContain('This option is only supported on Windows.') - expect(rows[1].textContent).toContain('disabled') - expect(rows[2].textContent).toContain('external_audio = enabled') - - new Function('document', configurationShortcuts)(document) - document.dispatchEvent(new Event('DOMContentLoaded')) - const button = document.querySelector('.open-button') - expect(button.textContent).toBe('Open configuration') - const open = vi.spyOn(window, 'open').mockImplementation(() => null) - button.click() - expect(open).toHaveBeenCalledWith('https://localhost:47990/config/#external_audio', '_blank', 'noopener') - }) -}) diff --git a/tests/web/KeepDefaultSink.test.js b/tests/web/KeepDefaultSink.test.js new file mode 100644 index 00000000000..dd6ec83296e --- /dev/null +++ b/tests/web/KeepDefaultSink.test.js @@ -0,0 +1,360 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +import configDocumentation from '../../docs/configuration.md?raw' +import configurationShortcuts from '../../docs/configuration.js?raw' +import { mountAudioVideo } from './audioVideoMount.js' +import en from '../../src_assets/common/assets/web/public/assets/locale/en.json' + +afterEach(() => { + vi.restoreAllMocks() + document.body.innerHTML = '' +}) + +describe('keep default sink configuration', () => { + it.each(['windows', 'linux', 'macos', 'freebsd'])('renders the capture target choices on %s', async platform => { + const { wrapper, config } = mountAudioVideo(platform) + expect(wrapper.find('#keep_default_sink').exists()).toBe(true) + expect(wrapper.find('#external_audio').exists()).toBe(false) + expect(wrapper.text()).toContain('config.audio_capture_target_silent') + expect(wrapper.text()).toContain('config.audio_capture_target_current') + expect(wrapper.text()).toContain('config.audio_capture_target_specific') + + const expectInsight = choice => { + const insights = wrapper.findAll('#audio_capture_how_it_works') + expect(insights).toHaveLength(1) + expect(insights[0].text()).toContain('config.audio_capture_how_it_works') + const ownerSunshine = choice === 'specific' && wrapper.find('#audio_capture_owner_sunshine').exists() + && wrapper.get('#audio_capture_owner_sunshine').element.checked + const expectedKey = ownerSunshine ? 'specific_sunshine' : choice + expect(insights[0].text()).toContain(`config.audio_capture_target_${expectedKey}_desc_${platform}`) + for (const otherChoice of ['silent', 'current', 'specific', 'specific_sunshine'].filter(candidate => candidate !== expectedKey)) { + expect(insights[0].text()).not.toContain(`config.audio_capture_target_${otherChoice}_desc_${platform}`) + } + for (const other of ['windows', 'linux', 'macos', 'freebsd'].filter(candidate => candidate !== platform)) { + expect(insights[0].text()).not.toContain(`config.audio_capture_target_${expectedKey}_desc_${other}`) + } + } + + if (platform === 'macos') { + expect(wrapper.get('#audio_capture_target_silent').element.disabled).toBe(true) + expect(wrapper.get('#audio_capture_target_silent').element.checked).toBe(false) + expect(wrapper.text()).toContain('config.audio_capture_target_silent_desc_macos') + expect(wrapper.get('#audio_capture_target_current').element.checked).toBe(true) + expectInsight('current') + // A blank sink mounts as Play on this PC here, so mount syncs the saved keys to match. + expect(config.keep_default_sink).toBe('enabled') + expect(config.audio_sink).toBe('') + } else { + expect(wrapper.get('#audio_capture_target_silent').element.checked).toBe(true) + expectInsight('silent') + expect(config.keep_default_sink).toBe('disabled') + expect(config.audio_sink).toBe('') + + await wrapper.get('#audio_capture_target_current').setValue(true) + expectInsight('current') + expect(config.keep_default_sink).toBe('enabled') + expect(config.audio_sink).toBe('') + expect(wrapper.get('#audio_sink').element.disabled).toBe(true) + } + + await wrapper.get('#audio_capture_target_specific').setValue(true) + expectInsight('specific') + // This flow enters Custom from Play on this PC too, so self is the owner. + expect(config.keep_default_sink).toBe('enabled') + if (platform !== 'macos') { + expect(wrapper.get('#audio_capture_owner_self').element.checked).toBe(true) + } + expect(wrapper.get('#audio_sink').element.disabled).toBe(false) + await wrapper.get('#audio_sink').setValue('named-target') + expect(config.audio_sink).toBe('named-target') + expect(config.keep_default_sink).toBe('enabled') + + if (platform !== 'macos') { + await wrapper.get('#audio_capture_target_silent').setValue(true) + expectInsight('silent') + expect(config.keep_default_sink).toBe('disabled') + expect(config.audio_sink).toBe('') + expect(wrapper.get('#audio_sink').element.disabled).toBe(true) + expect(wrapper.findAll('#audio_sink')).toHaveLength(1) + expect(wrapper.get('#audio_sink').element.value).toBe('named-target') + expect(wrapper.get('#audio_capture_effective_target').text()).toContain(`config.audio_capture_effective_target_silent_${platform}`) + expect(wrapper.get('#audio_capture_effective_target').text()).toContain('config.audio_capture_effective_retained') + expect(wrapper.find('#audio_capture_owner_sunshine').exists()).toBe(false) + + await wrapper.get('#audio_capture_target_specific').setValue(true) + expectInsight('specific') + expect(wrapper.get('#audio_sink').element.value).toBe('named-target') + expect(config.audio_sink).toBe('named-target') + } else { + expect(wrapper.text()).toContain('config.audio_capture_target_silent_desc_macos') + } + wrapper.unmount() + }) + + it('renders only the shared audio choices on Windows', () => { + const { wrapper } = mountAudioVideo('windows') + expect(wrapper.findAll('input').map(input => input.attributes('id'))).toEqual([ + 'stream_audio', + 'audio_capture_target_silent', + 'audio_capture_target_current', + 'audio_capture_target_specific', + 'audio_sink', + 'virtual_sink', + 'install_steam_audio_drivers', + ]) + wrapper.unmount() + }) + + it('keeps a manually routed null sink editable as the specific target', async () => { + const { wrapper, config } = mountAudioVideo('linux') + await wrapper.get('#audio_capture_target_specific').setValue(true) + await wrapper.get('#audio_capture_owner_self').setValue(true) + await wrapper.get('#audio_sink').setValue('sink-sunshine-stereo') + expect(config.keep_default_sink).toBe('enabled') + expect(config.audio_sink).toBe('sink-sunshine-stereo') + expect(wrapper.get('#audio_sink').element.disabled).toBe(false) + expect(wrapper.get('#audio_sink').element.value).toBe('sink-sunshine-stereo') + wrapper.unmount() + }) + + it('mounts a legacy disabled named sink as Custom with Sunshine as routing owner', async () => { + const { wrapper, config } = mountAudioVideo('linux', { audio_sink: 'legacy-sink', keep_default_sink: 'disabled' }) + expect(wrapper.get('#audio_capture_target_specific').element.checked).toBe(true) + expect(wrapper.get('#audio_capture_owner_sunshine').element.checked).toBe(true) + expect(config.keep_default_sink).toBe('disabled') + expect(config.audio_sink).toBe('legacy-sink') + await wrapper.get('#audio_sink').setValue('renamed-sink') + expect(config.keep_default_sink).toBe('disabled') + expect(config.audio_sink).toBe('renamed-sink') + wrapper.unmount() + }) + + it('mounts a legacy enabled named sink as Custom with self as routing owner', () => { + const { wrapper, config } = mountAudioVideo('windows', { audio_sink: 'legacy-sink', keep_default_sink: 'enabled' }) + expect(wrapper.get('#audio_capture_target_specific').element.checked).toBe(true) + expect(wrapper.get('#audio_capture_owner_self').element.checked).toBe(true) + expect(config.keep_default_sink).toBe('enabled') + expect(config.audio_sink).toBe('legacy-sink') + wrapper.unmount() + }) + + it('defaults Custom entered directly from Quiet to Sunshine routing', async () => { + const { wrapper, config } = mountAudioVideo('linux') + await wrapper.get('#audio_capture_target_specific').setValue(true) + expect(wrapper.get('#audio_capture_owner_sunshine').element.checked).toBe(true) + expect(config.keep_default_sink).toBe('disabled') + await wrapper.get('#audio_sink').setValue('named-target') + expect(config.keep_default_sink).toBe('disabled') + expect(config.audio_sink).toBe('named-target') + wrapper.unmount() + }) + + it('defaults Custom entered from Play on this PC to self routing', async () => { + const { wrapper, config } = mountAudioVideo('linux') + await wrapper.get('#audio_capture_target_current').setValue(true) + await wrapper.get('#audio_capture_target_specific').setValue(true) + expect(wrapper.get('#audio_capture_owner_self').element.checked).toBe(true) + expect(config.keep_default_sink).toBe('enabled') + wrapper.unmount() + }) + + it('flips only keep_default_sink when the routing owner changes', async () => { + const { wrapper, config } = mountAudioVideo('linux', { audio_sink: 'named-target', keep_default_sink: 'disabled' }) + await wrapper.get('#audio_capture_owner_self').setValue(true) + expect(config.keep_default_sink).toBe('enabled') + expect(config.audio_sink).toBe('named-target') + await wrapper.get('#audio_capture_owner_sunshine').setValue(true) + expect(config.keep_default_sink).toBe('disabled') + expect(config.audio_sink).toBe('named-target') + wrapper.unmount() + }) + + it('disables the audio controls when Stream Audio is off', async () => { + const { wrapper } = mountAudioVideo('linux', { stream_audio: 'disabled' }) + expect(wrapper.get('#audio_capture_target_silent').element.disabled).toBe(true) + expect(wrapper.get('#audio_capture_target_current').element.disabled).toBe(true) + expect(wrapper.get('#audio_capture_target_specific').element.disabled).toBe(true) + expect(wrapper.get('#audio_sink').element.disabled).toBe(true) + await wrapper.get('#stream_audio').setValue(true) + expect(wrapper.get('#audio_capture_target_silent').element.disabled).toBe(false) + expect(wrapper.get('#audio_capture_target_current').element.disabled).toBe(false) + wrapper.unmount() + }) + + it('warns when Custom device has no sink name', async () => { + const { wrapper } = mountAudioVideo('linux') + await wrapper.get('#audio_capture_target_specific').setValue(true) + expect(wrapper.get('#audio_sink').classes()).toContain('is-invalid') + expect(wrapper.text()).toContain('config.audio_capture_sink_needed') + await wrapper.get('#audio_sink').setValue('named-target') + expect(wrapper.get('#audio_sink').classes()).not.toContain('is-invalid') + wrapper.unmount() + }) + + it('shows outcome subtitles and both capture section titles', () => { + const { wrapper } = mountAudioVideo('linux') + expect(wrapper.find('#video_capture').exists()).toBe(true) + const audioSection = wrapper.get('#keep_default_sink').element + const videoSection = wrapper.get('#video_capture').element + expect(audioSection.compareDocumentPosition(videoSection) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() + expect(wrapper.text()).toContain('config.video_capture') + expect(wrapper.text()).toContain('config.audio_capture_target_silent_outcome') + expect(wrapper.text()).toContain('config.audio_capture_target_current_outcome') + expect(wrapper.text()).toContain('config.audio_capture_target_specific_outcome') + wrapper.unmount() + }) + + it('shows the Windows virtual sink as the Quiet effective target', () => { + const { wrapper } = mountAudioVideo('windows', { virtual_sink: 'My Virtual Sink' }) + expect(wrapper.get('#audio_capture_effective_target').text()).toContain('My Virtual Sink') + wrapper.unmount() + }) + + it('hides the routing owner choice on macOS', async () => { + const { wrapper } = mountAudioVideo('macos', { audio_sink: 'BlackHole 2ch', keep_default_sink: 'enabled' }) + expect(wrapper.find('#audio_capture_owner_sunshine').exists()).toBe(false) + expect(wrapper.find('#audio_capture_owner_self').exists()).toBe(false) + expect(wrapper.text()).toContain('config.audio_capture_target_specific_sunshine_desc_macos') + wrapper.unmount() + }) + + it('trims whitespace from a custom sink before saving it', async () => { + const { wrapper, config } = mountAudioVideo('linux') + await wrapper.get('#audio_capture_target_specific').setValue(true) + await wrapper.get('#audio_sink').setValue(' sink-sunshine-stereo ') + expect(config.audio_sink).toBe('sink-sunshine-stereo') + wrapper.unmount() + }) + + it('provides the standard documentation table and a working configuration shortcut', () => { + const section = configDocumentation.split('### keep_default_sink\n')[1].split('\n### ')[0] + // Doxygen emits configuration headings as h2 and gives tables this class. + document.body.innerHTML = '' + + '

keep_default_sink

' + section.replace('
', '
') + const rows = [...document.querySelectorAll('tr')] + expect(rows.map(row => row.cells[0].textContent.trim())).toEqual(['Description', 'Default', 'Example']) + expect(rows[1].textContent).toContain('disabled') + expect(rows[2].textContent).toContain('keep_default_sink = enabled') + + new Function('document', configurationShortcuts)(document) + document.dispatchEvent(new Event('DOMContentLoaded')) + const button = document.querySelector('.open-button') + expect(button.textContent).toBe('Open configuration') + const open = vi.spyOn(window, 'open').mockImplementation(() => null) + button.click() + expect(open).toHaveBeenCalledWith('https://localhost:47990/config/#keep_default_sink', '_blank', 'noopener') + }) + + it.each([ + ['windows', 'silent', true], + ['windows', 'current', false], + ['windows', 'specific', false], + ['linux', 'silent', false], + ['macos', 'current', false], + ])('shows the virtual sink field on %s + %s only when expected (%s)', async (platform, target, visible) => { + const { wrapper } = mountAudioVideo(platform) + const radio = { silent: '#audio_capture_target_silent', current: '#audio_capture_target_current', specific: '#audio_capture_target_specific' }[target] + await wrapper.get(radio).setValue(true) + expect(wrapper.find('#virtual_sink').exists()).toBe(visible) + expect(wrapper.find('#install_steam_audio_drivers').exists()).toBe(visible) + if (visible) { + expect(wrapper.get('#virtual_sink').element.disabled).toBe(false) + } + wrapper.unmount() + }) + + it('disables the virtual sink and routing owner controls when Stream Audio is off', async () => { + const { wrapper } = mountAudioVideo('windows') + await wrapper.get('#audio_capture_target_silent').setValue(true) + expect(wrapper.get('#virtual_sink').element.disabled).toBe(false) + await wrapper.get('#stream_audio').setValue(false) + expect(wrapper.get('#virtual_sink').element.disabled).toBe(true) + expect(wrapper.get('#install_steam_audio_drivers').element.closest('fieldset').disabled).toBe(true) + await wrapper.get('#stream_audio').setValue(true) + expect(wrapper.get('#virtual_sink').element.disabled).toBe(false) + expect(wrapper.get('#install_steam_audio_drivers').element.closest('fieldset').disabled).toBe(false) + wrapper.unmount() + }) + + it('writes only the capture keys for each target and leaves the rest untouched', async () => { + const before = { virtual_sink: 'My Sink', stream_audio: 'enabled' } + const { wrapper, config } = mountAudioVideo('linux', { ...before, audio_sink: '', keep_default_sink: 'disabled' }) + await wrapper.get('#audio_capture_target_current').setValue(true) + expect(config.keep_default_sink).toBe('enabled') + expect(config.audio_sink).toBe('') + await wrapper.get('#audio_capture_target_specific').setValue(true) + await wrapper.get('#audio_sink').setValue(' spaced-sink ') + expect(config.audio_sink).toBe('spaced-sink') + expect(config.virtual_sink).toBe(before.virtual_sink) + expect(config.stream_audio).toBe(before.stream_audio) + wrapper.unmount() + }) + + it('validates the capture selection for the save gate', async () => { + const { wrapper } = mountAudioVideo('linux') + expect(wrapper.vm.validateAudioCapture()).toBe(true) + await wrapper.get('#audio_capture_target_specific').setValue(true) + expect(wrapper.vm.validateAudioCapture()).toBe(false) + await wrapper.get('#audio_sink').setValue('named-target') + expect(wrapper.vm.validateAudioCapture()).toBe(true) + wrapper.unmount() + }) + + it('links the sink input to its validation message for assistive tech', async () => { + const { wrapper } = mountAudioVideo('linux') + await wrapper.get('#audio_capture_target_specific').setValue(true) + expect(wrapper.get('#audio_sink').attributes('aria-describedby')).toBe('audio_sink_feedback') + expect(wrapper.find('#audio_sink_feedback').exists()).toBe(true) + await wrapper.get('#audio_sink').setValue('named-target') + expect(wrapper.get('#audio_sink').attributes('aria-describedby')).toBeUndefined() + wrapper.unmount() + }) +}) + +describe('audio sink platform guidance', () => { + it('describes silent, current, and specific capture in platform terms', () => { + expect(en.config.video_capture).toBe('Video Capture') + expect(en.config.audio_capture_target_silent_outcome).toBe('Silent on this PC, sound on the client') + expect(en.config.audio_capture_target_current_outcome).toBe('Sound on this PC and on the client') + expect(en.config.audio_capture_target_specific_outcome).toBe('Capture one exact device; you route apps to it') + expect(en.config.audio_capture_sink_needed).toBeDefined() + expect(en.config.audio_capture_sink_kept_hint).toBeDefined() + expect(en.config.audio_capture_target_silent).toBe('Quiet streaming') + expect(en.config.audio_capture_target_current).toBe('Play on this PC too') + expect(en.config.audio_capture_target_specific).toBe('Custom device') + expect(en.config.audio_capture_how_it_works).toBe('How this works') + expect(en.config.audio_sink_placeholder_linux).toBe('sink-sunshine-stereo') + expect(en.config.audio_sink_placeholder_freebsd).toBe('sink-sunshine-stereo') + expect(en.config.audio_sink_placeholder_macos).toBe('BlackHole 2ch') + expect(en.config.audio_sink_placeholder_windows).toBe('Speakers (High Definition Audio Device)') + for (const platform of ['linux', 'freebsd', 'macos', 'windows']) { + expect(en.config[`audio_sink_desc_${platform}`]).toBeDefined() + expect(en.config[`audio_capture_target_current_desc_${platform}`]).toBeDefined() + expect(en.config[`audio_capture_target_specific_desc_${platform}`]).toBeDefined() + } + for (const platform of ['linux', 'freebsd', 'windows']) { + expect(en.config[`audio_capture_target_silent_desc_${platform}`]).toMatch(/client hears/i) + } + expect(en.config.audio_capture_target_silent_desc_linux).toMatch(/null sink/) + expect(en.config.audio_capture_target_silent_desc_windows).toMatch(/Steam Streaming Speakers/) + expect(en.config.audio_capture_target_silent_desc_macos).toMatch(/BlackHole/) + expect(en.config.audio_capture_target_silent_desc_macos).toMatch(/Not available/) + expect(en.config.audio_capture_target_current_desc_macos).toMatch(/system audio tap/) + expect(en.config.audio_capture_owner_sunshine).toBe('Sunshine sets the device below as the default while streaming') + expect(en.config.audio_capture_owner_self).toBe('I route apps myself') + expect(en.config.audio_capture_effective_target).toBe('Streaming will capture') + expect(en.config.audio_capture_effective_retained).toBe('Custom name kept for Custom device only') + for (const platform of ['linux', 'freebsd', 'macos', 'windows']) { + expect(en.config[`audio_capture_target_specific_sunshine_desc_${platform}`]).toBeDefined() + expect(en.config[`audio_capture_effective_target_silent_${platform}`]).toBeDefined() + expect(en.config[`audio_capture_effective_target_current_${platform}`]).toBeDefined() + } + expect(en.config.audio_capture_effective_target_silent_linux).toMatch(/null sink/) + expect(en.config.audio_capture_target_specific_sunshine_desc_macos).toMatch(/Not applicable/) + expect(en.config.audio_sink_desc_macos).not.toMatch(/Soundflower/) + expect(en.config.virtual_sink_desc).toMatch(/Steam Streaming Speakers/) + expect(en.config.virtual_sink_desc).toMatch(/Leave blank/) + expect(en.config.install_steam_audio_drivers_desc).toMatch(/Windows only/) + expect(en.config.install_steam_audio_drivers_desc).toMatch(/Steam Streaming Speakers/) + }) +}) diff --git a/tests/web/audioVideoMount.js b/tests/web/audioVideoMount.js new file mode 100644 index 00000000000..9e829f4d48f --- /dev/null +++ b/tests/web/audioVideoMount.js @@ -0,0 +1,26 @@ +import { mount } from '@vue/test-utils' +import { ref } from 'vue' + +import AudioVideo from '../../src_assets/common/assets/web/configs/tabs/AudioVideo.vue' +import configTabs from '../../src_assets/common/assets/web/configs/config_tabs.json' + +export function mountAudioVideo(platform, overrides = {}) { + const config = { ...structuredClone(configTabs.find(tab => tab.id === 'av').options), ...overrides } + const wrapper = mount(AudioVideo, { + props: { platform, config }, + global: { + mocks: { $t: key => key }, + provide: { + platform: ref(platform), + i18n: { t: key => key }, + }, + stubs: { + AdapterNameSelector: true, + DisplayOutputSelector: true, + DisplayDeviceOptions: true, + DisplayModesSettings: true, + }, + }, + }) + return { wrapper, config } +}