Skip to content

feat: add input-only streaming mode (input and audio without video capture) - #6104

Open
sramteare wants to merge 8 commits into
SunshineStream:masterfrom
sramteare:feature/input-only
Open

sramteare wants to merge 8 commits into
SunshineStream:masterfrom
sramteare:feature/input-only

Conversation

@sramteare

Copy link
Copy Markdown
Contributor

Description

Adds an opt-in Input Only streaming mode: sessions that capture no video at all, keep input and audio fully live, and serve a single blank IDR frame (re-served on IDR/RFI requests) so unmodified Moonlight clients stay connected past their 10 second no-video watchdog.

  • New enable_input_only_mode option (default disabled) in the input config section, exposed in the Web UI under Inputs and documented in docs/configuration.md.
  • When enabled, a synthetic "Input Only" app is appended to the app list. Existing app IDs are unchanged, and the placeholder ID is derived from the name hash so clients see a stable entry.
  • Launch and resume propagate an input_only flag through the RTSP session into the video pipeline. The capture thread skips the capture backend entirely while only input-only sessions are active; each input-only session is seeded with an opaque black frame and gets a fresh IDR on request, so the client's first-frame checks pass without any captured content leaking to it.
  • Placeholder lifecycle: the placeholder app runs only when no other app is running, is replaced transparently when a real app is launched over it, and is terminated when the last session ends so the host does not report a phantom running app.
  • Display configuration is never applied for input-only sessions; the configure_display/revert paths are skipped for them. Audio and input behave exactly as in a normal session, including gamepads.

Motivation

Remote-control and assist scenarios (tablets as input surfaces, low-bandwidth links, headless hosts) where video is unnecessary but input latency and audio fidelity matter. Prior art: Apollo's "Input Only" mode. This variant keeps audio alive and requires no client changes.

Limitations

  • Moonlight clients quit the running app before starting a different one (/cancel, then require currentgame == 0), so an input-only session cannot coexist with a different app running on the host from the same client. Multiple clients can join the same input-only session via resume.
  • Switching apps while another client is streaming still ends the shared app session (existing upstream /cancel semantics, unchanged here).

Testing

  • test_sunshine: 881 tests pass, including new coverage for config parsing, placeholder lifetime and is_input_only_running(), blank-frame packing (BGRA/NV12/pitch inference), and placeholder cleanup.
  • Manual end-to-end on Ubuntu 24.04 (Wayland/portal capture, software and NVENC encoders): iPad (Input Only) and MacBook (Desktop) clients; black screen with working input and audio, idle sessions stay connected, resume returns to Input Only, placeholder cleanup on last disconnect, and the Desktop → Input Only → Desktop sequence.

This PR was generated by opencode running Qwen3.8-Flash-Next, high thinking level.

ripper and others added 4 commits November 13, 2026 23:07
…t deadlock, sync-path frame leak, resume, placeholder cleanup, id race)
proc_t::terminate() called rtsp_stream::session_count() to decide whether
gamepads still have a live session to serve. That helper joins every
stopping session, so reaching it from stream::session::join() (the last
client of the input-only placeholder) made the teardown thread wait on
itself until the 10 second hang watchdog aborted Sunshine.

Use the non-blocking stream::session::running_session_count() snapshot
instead. The counter is decremented before the placeholder cleanup runs,
so gamepads are still terminated exactly when the last session is gone,
while app-swap termination keeps them alive.
@sramteare

Copy link
Copy Markdown
Contributor Author

This PR was generated by opencode running Qwen3.8-Flash-Next, high thinking level.

@ReenigneArcher ReenigneArcher left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two introduced defects need attention: the blank-frame fill writes through an opaque Windows GPU texture pointer, and resume can lose its input-only mode when it synchronously cleans up the last stopping session.

Validation: all 218 web tests passed; an extracted fill_blank_image ASan harness reproduced the overwrite with a mock opaque object, and a focused control-flow model reproduced the resume ordering. These are not Windows hardware or full streaming tests. No native build was run. CI, lint and CodeQL await maintainer approval.

Review completed by Codex | Model: unavailable | Thinking: unavailable

Comment thread src/video.cpp
if (pixel_pitch == 4) {
for (auto y = 0; y < img.height; ++y) {
auto row = img.data + static_cast<std::size_t>(y) * img.row_pitch;
std::fill_n(row, static_cast<std::size_t>(img.width) * 4, (std::uint8_t) 0x00);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Do not write CPU pixels through GPU-backed image handles

On the Windows VRAM path, display_vram_t::complete_img() sets img.data to img.capture_texture.get() (an ID3D11Texture2D*), while SDR images still report pixel_pitch == 4 and row_pitch == width * 4. Both new input-only call sites therefore reach this fill and overwrite the COM object/adjacent memory instead of filling texture pixels, crashing or corrupting the host when an input-only hardware-encoded session starts. I reproduced the out-of-bounds write using this exact function and an opaque-object mock under ASan; I have not run Windows hardware.

Make black-image initialization backend-aware, or require an explicit CPU-buffer capability before writing data; retain the existing D3D blank-frame handling for VRAM images. Add separate RAM-buffer and opaque GPU-image coverage rather than testing only byte arrays.

Review completed by Codex | Model: unavailable | Thinking: unavailable

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The opaque-pointer overwrite is fixed in aedaf68c: an extracted-function ASan/UBSan check now leaves the mock GPU object untouched while still filling RAM pixels. However, the existing D3D blank path does not initialize every supported output format.

For DXGI_FORMAT_AYUV, DXGI_FORMAT_R16_UINT, and DXGI_FORMAT_Y410, init_output() deliberately leaves rtvs_cleared = false because the integer RTV must be cleared by drawing. That draw is inside if (!img.blank) in d3d_base_encode_device::convert(). Input-only sessions only feed blank dummy images, so the deferred clear is never reached and these 4:4:4 encoder targets are submitted without being initialized to black. NV12/P010 have the immediate clear and are not this case.

Please make the backend initialize a black output even when its first/all inputs are blank, including the integer RTV path, rather than relying on a nonblank capture to trigger the clear. Add coverage for first-frame blank conversion in both the immediate-clear and deferred-clear format families. This is a source-path finding; I have not run Windows hardware or established the exact visible output.

Review completed by Codex | Model: unavailable | Thinking: unavailable

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified the follow-up in 78c44c9d: the deferred black clear now runs before the blank-frame check, so AYUV/R16_UINT/Y410 no longer depend on receiving captured content. The production conversion calls the tested helper, and failed clear creation leaves the targets uncleared and returns an error rather than submitting them.

I compiled the actual extracted helpers with ASan/UBSan and checked both format families, first/repeated blank frames, a later captured frame, clear failure/retry, and frame-error propagation. Those checks and git diff --check passed. The added Windows tests cover the reported blank-first-frame regression. This verifies the control flow, not D3D execution or visible output: Windows compilation/hardware playback remain untested here, and exact-head CI, lint and CodeQL await maintainer approval.

Review completed by Codex | Model: unavailable | Thinking: unavailable

Comment thread src/nvhttp.cpp Outdated
// If only the synthetic "Input Only" placeholder is running, a resume must not
// silently upgrade into a full desktop-capture session. The placeholder is recognized
// even if input-only mode was turned off after it started.
launch_session->input_only = proc::proc.is_input_only_running();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Revalidate the running app after session cleanup before resuming

When the last input-only session is STOPPING, the earlier current_appid check passes while its placeholder still exists. rtsp_stream::session_count() then calls server.clear(false) → stream::session::join() synchronously; the new last-session cleanup terminates that placeholder. This line consequently reads false, and /resume proceeds down the normal display/capture path despite having no app to resume. That can turn a reconnect to an input-only stream into captured video.

Perform the cleanup before taking the app/mode snapshot and reject a resume if the placeholder disappeared (or explicitly recreate it while retaining input-only mode). Add a handler-level regression for a last input-only session in STOPPING: the resume must either fail cleanly or remain input-only, never configure/capture the desktop. The source chain and a focused control-flow model confirm the ordering; a live-client reproduction remains untested.

Review completed by Codex | Model: unavailable | Thinking: unavailable

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The production ordering is corrected in aedaf68c: cleanup runs before the app/mode snapshot, and the handler rejects app_id == 0 before configuring the display. An extracted resolve_resume_state() harness with a cleanup stub that terminates the placeholder during session_count() passes.

The new ResolveResumeState_SnapshotsAfterPlaceholderCleanup test does not actually guard that ordering: it terminates the placeholder before calling the helper. It would still pass if the helper were changed back to snapshot first and clean up afterward. Please exercise a stopping session whose cleanup terminates the placeholder during the helper call (or inject that cleanup in a focused test seam), and assert the result has no app and cannot reach display configuration/capture. The current opaque-GPU test does cover its new guard.

All 218 web tests and git diff --check passed independently. I have not run the native suite or live-client recovery; CI, lint and CodeQL still await maintainer approval.

Review completed by Codex | Model: unavailable | Thinking: unavailable

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified the test correction in 78c44c9d. The injected cleanup now terminates the placeholder during resolve_resume_state(), before the app/mode snapshot, and asserts both resume and display configuration are rejected. Unlike the previous test, this guards the ordering that caused the original failure. The handler uses those same guards before configuring the display or launching the resumed session.

An extracted-function harness with the cleanup callback and the app/mode/session-state combinations passed under ASan/UBSan. I have not run the full native suite or a live reconnect test. This addresses my resume-ordering/test concern.

Review completed by Codex | Model: unavailable | Thinking: unavailable

…ter cleanup

fill_blank_image() now returns early when img_t::is_cpu_buffer() is false.
On the Windows VRAM path data is an ID3D11Texture2D pointer, so the previous
fill corrupted the texture object instead of writing pixels. Blank VRAM
frames are already rendered black by the encoder conversion path.

/resume now resolves the app and input-only snapshots after joining stopping
sessions. The last input-only session's teardown can terminate the
placeholder, and resuming the pre-cleanup state fell back to desktop capture.

Adds regression coverage for opaque GPU images and for the resume snapshot
taken after placeholder cleanup.
@sramteare

Copy link
Copy Markdown
Contributor Author

Pushed aedaf68c addressing both findings:

P1 – GPU-backed image fill: platf::img_t now exposes is_cpu_buffer() (default true). img_d3d_t overrides it to false because data is an ID3D11Texture2D * there, and fill_blank_image() returns early for those images. Blank VRAM frames keep using the existing D3D path (the encoder conversion skips drawing for blank images and the render targets are cleared to black). Added FillBlankImageTest.SkipsOpaqueGpuBackedImages using an opaque mock image.

P1 – resume ordering: the handler now takes the app/mode/session snapshot through nvhttp::resolve_resume_state(), which joins stopping sessions first and then reads proc::proc.running() / is_input_only_running(). If the placeholder was terminated by that cleanup, /resume returns 503 "No running app to resume" instead of configuring the display and capturing the desktop. Added ProcessInputOnlyTest.ResolveResumeState_SnapshotsAfterPlaceholderCleanup.

Full suite: 883 passed / 0 failed (Linux, software encoder), clang-format clean.

This comment was generated by opencode running Qwen3.8-Flash-Next, high thinking level.

@sramteare

Copy link
Copy Markdown
Contributor Author

Pushed 78c44c9d addressing both follow-up comments:

  1. D3D11 deferred RTV clear on blank frames (src/platform/windows/display.h, src/platform/windows/display_vram.cpp, tests/unit/platform/windows/test_display_vram.cpp):

    • Extracted platf::dxgi::requires_drawn_rtv_clear(DXGI_FORMAT) and platf::dxgi::convert_d3d_frame(...) and wired d3d_base_encode_device::init_output() and d3d_base_encode_device::convert() through them so integer 4:4:4 output targets (DXGI_FORMAT_AYUV, DXGI_FORMAT_R16_UINT, DXGI_FORMAT_Y410) run the black RTV clear draw before the first frame even when img.blank is true (and fail conversion with -1 without setting rtvs_cleared if creating the black clear texture fails, while unbinding SRV slot 0 after both clear and frame draws).
    • Added unit coverage in WindowsRtvClearTest for format-family classification (ClassifiesImmediateAndDeferredClearFormats), first-frame blank conversion in the immediate-clear family (FirstFrameBlankConversionInImmediateClearFormatFamily for NV12/P010), first-frame and subsequent blank/non-blank conversion in the deferred-clear family (FirstFrameBlankConversionInDeferredClearFormatFamily for AYUV/R16_UINT/Y410), and clear failure handling (DeferredClearFailureOnBlankFirstFrameFailsConversion).
  2. Resume stopping-session cleanup seam & display guard (src/nvhttp.h, src/nvhttp.cpp, tests/unit/test_process.cpp):

    • Added an overload nvhttp::resolve_resume_state(const std::function<bool()> &cleanup_stopping_sessions) plus resume_state_t::can_resume() and resume_state_t::should_configure_display() used by nvhttp::resume().
    • Updated ProcessInputOnlyTest.ResolveResumeState_SnapshotsAfterPlaceholderCleanup so the injected cleanup callback verifies the placeholder is still running on entry, terminates it during the cleanup step, and asserts that the resulting resume_state_t has app_id == 0, !can_resume(), and !should_configure_display().

This comment was generated by opencode running Qwen3.8-Flash-Next, high thinking level.

@ReenigneArcher ReenigneArcher left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The earlier Windows GPU-pointer/deferred-clear and resume-ordering findings are addressed in 78c44c9d. Two other paths still need correction: NvFBC's dummy CUDA texture is never initialized before encoding, and /launch can skip recreating a placeholder removed by stopping-session cleanup. The newly added tests also need Doxygen briefs.

Validation: all 218 web tests passed; all 11 changed C++ source/test translation units passed Windows UCRT64 -fsyntax-only checks using the existing build's dependency flags; clang-format 23 and git diff --check passed. Extracted current D3D/resume helpers passed focused behavior checks, and a mock-surface/lifecycle harness demonstrated the null-data bypass and stale launch decision. These checks are not a full native test run or hardware streaming validation.

The current head merges cleanly with master. Sonar and Read the Docs pass; exact-head CI, lint, and CodeQL await maintainer approval.

Review completed by Codex | Model: gpt-6.1-sol | Thinking: xhigh

Comment thread src/video.cpp
// leave the buffer uninitialized (or zero the alpha channel), which decodes
// as a green screen on some clients.
if (config.input_only) {
fill_blank_image(*dummy_img);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Initialize the NvFBC CUDA texture before encoding the blank frame

With Linux capture = nvfbc and NVENC, cuda::nvfbc::display_t::alloc_img() allocates img.tex but sets img.data = nullptr; its dummy_img() does nothing. Consequently this fill returns at the null-data guard, and cuda_vram_t::convert() immediately samples the untouched CUDA array. The Windows blank-image handling does not cover this backend. An input-only session therefore encodes indeterminate GPU contents instead of a guaranteed black frame, potentially exposing reused image data.

Initialize the backend's dummy CUDA array before conversion, and propagate an initialization failure. For example, replace cuda::nvfbc::display_t::dummy_img() and its documentation in src/platform/linux/cuda.cpp with:

/**
 * @brief Upload an opaque black frame into an NvFBC dummy image.
 *
 * @param img Image whose CUDA array will receive the black pixels.
 * @return 0 on success, or the CUDA upload error.
 */
int dummy_img(platf::img_t *img) override {
  std::vector<std::uint8_t> pixels(static_cast<std::size_t>(img->row_pitch) * img->height, 0);

  platf::img_t black;
  black.data = pixels.data();
  black.width = img->width;
  black.height = img->height;
  black.pixel_pitch = img->pixel_pitch;
  black.row_pitch = img->row_pitch;
  video::fill_blank_image(black);

  cuda::sws_t upload;
  return upload.load_ram(black, static_cast<cuda::img_t *>(img)->tex.array);
}

This reuses the existing synchronous RAM-to-array uploader. Add a CUDA regression that starts with a nonblack texture, initializes the dummy, converts it, and checks black RGB/neutral chroma; also test upload failure. I verified the source chain and the null-data bypass with an extracted-helper/mock-surface harness. The replacement above has not been compiled or tested with Linux CUDA hardware.

Review completed by Codex | Model: gpt-6.1-sol | Thinking: xhigh

Comment thread src/nvhttp.cpp Outdated

// An input-only session does not conflict with an already running app. Only
// launch the placeholder app when nothing is running yet.
if (current_appid == 0) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Recheck the app after launch performs stopping-session cleanup

A reconnect through /launch can arrive while the last input-only stream is STOPPING. current_appid was read at line 1414 while the placeholder still existed, but the subsequent rtsp_stream::session_count() synchronously joins that stream and terminates the placeholder. This condition then skips execute() using the stale ID, so the new input-only stream starts with no running placeholder. Its later /resume returns 503, and starting a real app no longer recognizes the active input-only clients when deciding whether to preserve their gamepads.

The resume fix addresses the same cleanup side effect, but this launch path still needs to refresh its state. At minimum recheck the live registry here:

Suggested change
if (current_appid == 0) {
if (proc::proc.running() == 0) {

A focused snapshot/cleanup model reproduces the skipped placeholder and verifies this condition restores the decision to execute it; I have not run a live reconnect. Add launch-path coverage where cleanup terminates a last stopping placeholder, then assert the replacement placeholder is running and remains resumable.

Review completed by Codex | Model: gpt-6.1-sol | Thinking: xhigh

)
);

TEST(WindowsRtvClearTest, ClassifiesImmediateAndDeferredClearFormats) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Document the newly added regression tests

The four new WindowsRtvClearTest cases, the new ProcessInputOnlyTest cases, and the new FillBlankImageTest cases lack primary Doxygen comments. Each new test needs a descriptive @brief block under this repository's documentation requirement; the documented fixture/helper alone does not document the individual cases. For example:

Suggested change
TEST(WindowsRtvClearTest, ClassifiesImmediateAndDeferredClearFormats) {
/**
* @brief Verify which encoder formats require a drawn render-target clear.
*/
TEST(WindowsRtvClearTest, ClassifiesImmediateAndDeferredClearFormats) {

Please apply the same form to the remaining newly added cases. The current test translation units passed Windows syntax checks; this documentation-only suggestion has not been run through a Doxygen build.

Review completed by Codex | Model: gpt-6.1-sol | Thinking: xhigh

@sramteare

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review and catches, @ReenigneArcher!

Pushed f8cfc9bb addressing all three findings:

  1. [P1] NvFBC CUDA dummy texture initialization (src/platform/linux/cuda.cpp, src/platform/linux/cuda.h, src/platform/linux/cuda.cu, tests/unit/platform/linux/test_cuda.cpp):

    • Added cuda::fill_dummy_img_black(const platf::img_t *img, cudaArray_t array) and wired cuda::nvfbc::display_t::dummy_img() through it so NvFBC dummy images are populated with opaque black via video::fill_blank_image() + sws_t::load_ram() (propagating invalid-descriptor and upload errors) instead of leaving GPU memory uninitialized.
    • Added CudaNvFbcDummyImgTest.FillReplacesTextureContentsWithBlack (seeds a CUDA array with red, runs fill_dummy_img_black(), converts via the production NV12 kernel, and checks Y == 0 and U/V == 128 ± 1) and CudaNvFbcDummyImgTest.ReportsInvalidImagesAndUnallocatedTextures.
  2. [P2] /launch post-cleanup app recheck (src/nvhttp.h, src/nvhttp.cpp, tests/unit/test_process.cpp):

    • Added nvhttp::launch_state_t and nvhttp::resolve_launch_state() (with a cleanup-callback test seam) so nvhttp::launch() snapshots proc::proc.running() after rtsp_stream::session_count() joins stopping sessions and uses launch_state.should_execute_placeholder() instead of the stale pre-cleanup current_appid.
    • Added ProcessInputOnlyTest.ResolveLaunchState_ReexecutesPlaceholderAfterCleanup covering a STOPPING last input-only session whose teardown terminates the placeholder during resolve_launch_state().
  3. [P2] Doxygen @brief comments on newly added tests:

    • Added /** @brief ... */ blocks to all newly added cases in tests/unit/platform/windows/test_display_vram.cpp, tests/unit/test_process.cpp, tests/unit/test_video.cpp, and tests/unit/platform/linux/test_cuda.cpp.

Verified on Linux with SUNSHINE_ENABLE_CUDA=ON:

  • test_sunshine --gtest_filter="*InputOnly*:*FillBlank*:*Cuda*:*CUDA*:*NvFBC*": 149/149 passed (including the GPU kernel test on an RTX PRO 6000).
  • Full test_sunshine suite: 1076 passed, 8 skipped, 0 failed (1084 total).
  • uv run --locked lb-update-clang-format and git diff --check: clean.

Copy link
Copy Markdown
Member

Rechecked f8cfc9bb: the NvFBC dummy-image path now uploads opaque black before conversion and returns initialization/upload errors to callers that abort rather than encode an uninitialized image. The seeded-texture regression exercises the production upload and conversion kernel. The launch snapshot now follows stopping-session cleanup, and the new regression removes the placeholder inside that cleanup before verifying replacement and input-only resume. The new test briefs are present. These address my three outstanding findings.

I independently compiled the extracted current black-fill/upload and launch-state helpers with mocked CUDA upload/context creation and process state. Black BGRA bytes, upload-error propagation, context-creation failure, invalid descriptors, and cleanup ordering passed under ASan/UBSan (leak checking disabled because this runner's ptrace environment prevents LeakSanitizer). git diff --check passed. These checks do not validate GPU execution, the full native suite, or a live NvFBC/reconnect session; the reported CUDA hardware and full-suite results remain contributor validation. Exact-head CI, lint and CodeQL await maintainer approval.

Review completed by Codex | Model: unavailable | Thinking: unavailable

Resolve the src/video.cpp conflicts with master's monitor-switch API
(SunshineStream#5194): the input-only idle paths and do_reinit now use
capture_display_switches().poll(...) generation compares and .apply(...)
instead of switch_display_event->peek()/pop().

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sonarqubecloud

sonarqubecloud Bot commented Dec 6, 2026

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
41 New issues

See analysis details on SonarQube Cloud

Catch issues before they fail your Quality Gate with our IDE extension SonarQube for IDE

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants