Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
2ffc3ae
feat(audio): add keep_default_sink option to capture without swapping…
mikefaille Oct 8, 2026
f9ac778
fix(linux): clear Sonar findings on audio sink lifecycle
mikefaille Oct 15, 2026
894bf46
fix(linux): log suppressed exception in audio server teardown
mikefaille Oct 15, 2026
77a5a78
fix(audio): capture host sink when keep-default has no configured sink
mikefaille Oct 17, 2026
2ec6d80
fix(web): cover shared keep_default_sink checkbox in UI tests
mikefaille Oct 17, 2026
f875ce4
feat(audio): support keep_default_sink on Windows and macOS
mikefaille Oct 17, 2026
edf6c3e
fix(audio): add default case to capture-routing channel switch
mikefaille Oct 17, 2026
efcd6e3
fix(web): share AudioVideo mount helper between UI tests
mikefaille Oct 17, 2026
627882c
feat(audio): unify keep-default capture with process loopback and cap…
mikefaille Nov 9, 2026
dcb684c
feat(audio): harden capture with session guard, params bundle, and he…
mikefaille Nov 9, 2026
29cb270
refactor(audio): modernize capture plumbing with C++23 idioms
mikefaille Nov 10, 2026
b4073e8
refactor(audio): address valid Sonar findings in capture path and tests
mikefaille Nov 10, 2026
5b334af
refactor(audio): use CTAD for live_count and report test guard restor…
mikefaille Nov 10, 2026
734e3ab
docs(audio): drop duplicated param docs from select_audio_capture_sin…
mikefaille Nov 10, 2026
34dacf5
style(tests): consolidate include groups in audio tests
mikefaille Nov 10, 2026
8cdf346
refactor(audio): centralize recorded capture-target state in audio_co…
mikefaille Nov 10, 2026
7a669d4
refactor(audio): share keep-default capture body and hook paired targ…
mikefaille Nov 11, 2026
4382c56
fix(audio): create microphone outside the capture-target lock
mikefaille Nov 16, 2026
e1250fd
fix(config): scope legacy external_audio migration to Windows with a …
mikefaille Nov 16, 2026
2f92bd3
fix(tests): drop blank line at EOF from trim surgery
mikefaille Nov 17, 2026
5721311
fix(windows/audio): drop stray brace left by trim surgery in micropho…
mikefaille Nov 17, 2026
cb8247f
fix(process): serialize lifecycle transitions and harden termination
mikefaille Nov 17, 2026
9e4c5a8
feat(windows/audio): capture launched process tree with WASAPI loopback
mikefaille Nov 17, 2026
f345d54
fix(process): make running() polls non-blocking with try-gated cleanup
mikefaille Nov 17, 2026
c1b1c98
test(process): pin non-blocking polls, ordering, and identity oracles
mikefaille Nov 17, 2026
6edc7aa
Merge lifecycle hardening fixes into Windows process-tree capture
mikefaille Nov 17, 2026
48ae5e3
fix(windows/audio): harden loopback tests, docs, and activation coverage
mikefaille Nov 17, 2026
007a08d
Merge branch 'master' into feat/audio-lifecycle-hardening
mikefaille Nov 17, 2026
2f69cd0
test: collapse duplicated gated-launch setups into a shared fixture
mikefaille Nov 17, 2026
e1a687d
Merge branch 'feat/audio-lifecycle-hardening' of mikefaille/Sunshine
mikefaille Nov 17, 2026
98a5c8f
Merge branch 'feat/audio-lifecycle-hardening' into feat/windows-proce…
mikefaille Nov 17, 2026
91cd128
test(windows): share the loopback probe setup across microphone tests
mikefaille Nov 17, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 28 additions & 12 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -835,6 +835,10 @@ consent prompt for directory ACLs, so the Web UI shows setup steps for correctin
}
@attention{If you want to mute the host speakers, use
[virtual_sink](#virtual_sink) instead.}
@tip{On FreeBSD/Linux, Sunshine also provides its own null sinks (for example
`sink-sunshine-stereo`). Enter one here to capture a private mix you route
yourself; combined with [keep_default_sink](#keep_default_sink), the host
default output is left untouched.}
</td>
</tr>
<tr>
Expand Down Expand Up @@ -939,23 +943,36 @@ consent prompt for directory ACLs, so the Web UI shows setup steps for correctin
</tr>
</table>

### external_audio
### keep_default_sink

<table>
<tr>
<td>Description</td>
<td colspan="2">
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.
<br>
<br>
In this mode, [virtual_sink](#virtual_sink), automatic Steam audio driver installation,
and Moonlight's host-playback toggle do not affect routing. Configure local playback and the audio
sent to the selected endpoint in your external mixer. If the endpoint is unavailable, audio capture
fails rather than falling back to another endpoint. Video streaming can continue without audio.
@note{This option is only supported on Windows. Other platforms retain their existing behavior.}
This replaces the Windows-only <code>external_audio</code> option. An existing
<code>external_audio = enabled</code> setting is migrated to <code>keep_default_sink = enabled</code>
on upgrade, unless <code>keep_default_sink</code> is also set. Unlike the old Windows mode, an
explicit [audio_sink](#audio_sink) is no longer required. Note that [virtual_sink](#virtual_sink)
and Moonlight's host-playback selection only apply on the swap path; in keep-default mode the
capture target is the configured <code>audio_sink</code>, or the host sink when none is configured.
@note{Platform behavior:<br>
<strong>Windows:</strong> 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. When no
<code>audio_sink</code> is configured and Sunshine launched the application, Windows may instead
capture the launched process tree with WASAPI process loopback, so other applications stay out of
the stream; endpoint capture remains the fallback.<br>
<strong>Linux:</strong> 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.<br>
<strong>FreeBSD:</strong> captures the configured sink's monitor, or the host sink's monitor when
none is configured, without changing the default sink.<br>
<strong>macOS:</strong> honors the option natively through a system tap or the selected input,
without touching the default output.}
</td>
</tr>
<tr>
Expand All @@ -967,8 +984,7 @@ consent prompt for directory ACLs, so the Web UI shows setup steps for correctin
<tr>
<td>Example</td>
<td colspan="2">@code{}
external_audio = enabled
audio_sink = My Streaming Mix
keep_default_sink = enabled
@endcode</td>
</tr>
</table>
Expand Down
196 changes: 163 additions & 33 deletions src/audio.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
*/
// standard includes
#include <array>
#include <mutex>
#include <thread>

// lib includes
Expand Down Expand Up @@ -33,6 +34,28 @@ namespace audio {
static void stop_audio_control(audio_ctx_t &);
static void apply_surround_params(opus_stream_config_t &stream, const stream_params_t &params);

/**
* @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,
* the post-creation re-check, and the exit clear, but never across
* microphone creation itself, which can wait on endpoint activation;
* the re-check keeps one session from keeping a microphone created
* after another session replaced the shared target.
*
* Lock order: this outer mutex is always taken before the backend-internal
* `platf::audio_control_t::capture_state_mutex_`, acquired inside
* `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.
*
Expand Down Expand Up @@ -152,10 +175,102 @@ 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_, process_id_);
}

/**
* @brief Refresh the capture target, then create the microphone for it.
*/
std::unique_ptr<platf::mic_t> session_capture_target_t::create_microphone(
bool process_capture_supported,
const std::function<platf::process_identity_t()> &capture_process_identity_provider,
const platf::microphone_params_t &mic_params
) {
// Refresh the capture target before every microphone creation so a
// process that appears or exits between reinitializations is reflected.
// Only the refresh runs under the lock: microphone creation can wait
// seconds on endpoint activation, and holding the lock across it would
// stall every other session's teardown. The refresh is recorded even
// when microphone creation fails so teardown still releases this
// session's target. After creation the recorded target is re-checked
// under the lock; a microphone created while another session replaced
// the target is discarded and creation retries once with a fresh
// refresh, preserving the original refresh/microphone pairing.
for (int attempt = 0; attempt < 2; ++attempt) {
const auto identity = capture_process_identity_provider ? capture_process_identity_provider() : platf::process_identity_t {};
// Gate the whole bundle, not just the PID: the handed-off creation
// marker is the backend's revalidation baseline, and a marker paired
// with a zeroed PID would name no process at all.
const auto effective_identity = should_capture_process_tree(intent_, process_capture_supported, identity.process_id) ? identity : platf::process_identity_t {};
{
std::lock_guard lock {*mutex_};
process_id_ = effective_identity.process_id;
control_->set_capture_target(intent_, effective_identity);
recorded_ = true;
}
auto mic = control_->microphone(mic_params);
if (!process_capture_supported) {
return mic;
}
std::lock_guard lock {*mutex_};
// The re-check detects replacement by another session, not PID reuse:
// the handed-off creation marker is the backend's baseline, and the
// backend revalidates it again before capturing.
if (control_->snapshot_capture_target_record().matches(intent_, process_id_)) {
return mic;
}
BOOST_LOG(info) << "Capture target changed during microphone creation; discarding and retrying"sv;
}
// Both attempts observed a replaced target. The last refresh stays
// recorded so teardown still releases this session's target.
return nullptr;
}

/**
* @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 it still holds this session's intent
* and PID.
*/
void capture(safe::mail_t mail, config_t config, stream::session_t *channel_data) {
void capture(safe::mail_t mail, config_t config, stream::session_t *channel_data, std::function<platf::process_identity_t()> capture_process_identity_provider) {
auto shutdown_event = mail->event<bool>(mail::shutdown);
if (!config::audio.stream) {
shutdown_event->view();
Expand Down Expand Up @@ -184,46 +299,54 @@ 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);
const auto process_capture_supported = control->supports_process_capture();

// 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)
<< "], process capture supported ["sv << process_capture_supported << ']';
// If the selected sink cannot be selected, there is no audio to capture.
if (!select_audio_capture_sink(*control, routing)) {
return;
}
}

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<std::uint32_t>(stream.sampleRate),
static_cast<std::uint32_t>(frame_size),
continuous_audio,
host_audio
};
auto mic = capture_target.create_microphone(process_capture_supported, capture_process_identity_provider, mic_params);
if (!mic) {
return;
}
Expand Down Expand Up @@ -260,7 +383,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(process_capture_supported, capture_process_identity_provider, mic_params);
if (!mic) {
BOOST_LOG(warning) << "Couldn't re-initialize audio input"sv;
}
Expand All @@ -284,6 +407,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;
Expand Down Expand Up @@ -336,7 +465,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;
}
Expand Down
Loading