Skip to content
Merged
7 changes: 6 additions & 1 deletion PATCHES.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ MSYS2 does not package libdatachannel, so Windows builds always take the FetchCo
| `src/webrtc/protocol.{h,cpp}` | Gateway protocol version 2, ported and extended: stream settings and supported modes (now with 30/60/90/120 fps per mode), message parsing and construction, TV-shown PIN pairing and LAN discovery messages. |
| `src/webrtc/tv_auth.{h,cpp}` | Pairing requests (the TV shows a 4-digit PIN that the Web UI approves; one attempt, 5 minutes), paired-TV store (`webrtc_tv_clients.json` in Sunshine's config directory) and HMAC-SHA256 nonce authentication. |
| `src/webrtc/sdp.{h,cpp}` | Samsung Game Mode `imageattr`, single-codec offers, HEVC Main10 `fmtp` and level checks. |
| `src/webrtc/link_pacing.h` | Fits the stream to the TV's link: paced rate, bitrate limit, RTP payload size, NACK history, and one keyframe on its way at a time. |
| `src/webrtc/input_bridge.{h,cpp}` | Gamepad snapshots → Moonlight controller packets fed to `input::passthrough()`, so Sunshine's own controller emulation handles them; long-press Start mouse mode; rumble relayed to the TV. |

Stream parameters, chosen to match what the Gateway negotiated through moonlight-common-c:
Expand All @@ -103,7 +104,11 @@ Stream parameters, chosen to match what the Gateway negotiated through moonlight
| Frame rate | 60 (`framerateX100` 6000) | |
| Slices / reference frames | 1 / 1 | No reference-frame invalidation; losses recover through NACK and PLI→IDR. |
| Colour | Rec.709 limited (`encoderCscMode` 2); HDR: Rec.2020 PQ, 10-bit (`4`, `dynamicRange` 1) | HDR fails with an error when the captured display is not HDR, never silently SDR. |
| Video bitrate | TV bitrate − min(512, ⅕) − min(500, ⅒) kbps | Same audio and overhead deductions as Sunshine's RTSP path, without the 20 % FEC share. |
| Video bitrate | TV bitrate, at most 60 % of the TV's reported link, − min(512, ⅕) − min(500, ⅒) kbps | Same audio and overhead deductions as Sunshine's RTSP path, without the 20 % FEC share. The link limit leaves room for keyframes on a 100 Mbps TV port. |
| Pacing | 800 Mbps in 1 ms bursts; 90 % of the TV's link when it reports one | Retransmissions go through the same pacer, ahead of the frame being sent, and between frames too. |
| RTP payload | 1380 bytes when the TV reports Ethernet or Wi-Fi, otherwise libdatachannel's 1220 | 1380 still fits a 1500-byte frame with IPv6 and every header. |
| Retransmission history | 4096 packets, up to 1 MiB waiting to be resent | Holds a whole 4K keyframe; libdatachannel keeps 512. A packet already waiting is not queued twice. |
| Keyframe requests | One keyframe on its way at a time, then 250 ms of grace, doubling up to 2 s while the TV keeps asking | The TV repeats PLI until a keyframe arrives; one IDR per request overflowed the link. Five quiet seconds start over at 250 ms. |
| Audio | Opus stereo, 48 kHz, 5 ms packets, high quality (512 kbps) | As Moonlight requests on a LAN. |
| RTP timestamps | From each frame's capture time | Monotonic; falls back to 1/60 s steps. |
| IDR byte replacements | Applied before packetizing | As `stream.cpp` does for encoders without VUI parameters. |
Expand Down
1 change: 1 addition & 0 deletions cmake/compile_definitions/common.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,7 @@ set(SUNSHINE_TARGET_FILES
"${CMAKE_SOURCE_DIR}/src/stat_trackers.cpp"
"${CMAKE_SOURCE_DIR}/src/webrtc/input_bridge.cpp"
"${CMAKE_SOURCE_DIR}/src/webrtc/input_bridge.h"
"${CMAKE_SOURCE_DIR}/src/webrtc/link_pacing.h"
"${CMAKE_SOURCE_DIR}/src/webrtc/protocol.cpp"
"${CMAKE_SOURCE_DIR}/src/webrtc/protocol.h"
"${CMAKE_SOURCE_DIR}/src/webrtc/sdp.cpp"
Expand Down
41 changes: 37 additions & 4 deletions src/platform/windows/display.h
Original file line number Diff line number Diff line change
Expand Up @@ -367,15 +367,22 @@ namespace platf::dxgi {
output_t output; ///< DXGI output duplicated for capture.
device_t device; ///< D3D11 device used for desktop duplication capture.
device_ctx_t device_ctx; ///< D3D11 device context used for copy and render operations.
DXGI_RATIONAL display_refresh_rate; ///< Display refresh rate.
int display_refresh_rate_rounded; ///< Display refresh rate rounded.
DXGI_RATIONAL display_refresh_rate {}; ///< Display refresh rate; zero when the backend does not know it.
int display_refresh_rate_rounded = 0; ///< Display refresh rate rounded.
/**
* @brief Frame timestamps are the display ticks the frames were presented on.
*
* When the display rate is a multiple of the client rate, every other frame then lands exactly
* one tick before its slot; see arrival_tolerance().
*/
bool timestamps_on_display_ticks = false;

DXGI_MODE_ROTATION display_rotation = DXGI_MODE_ROTATION_UNSPECIFIED; ///< Display rotation.
int width_before_rotation; ///< Width before rotation.
int height_before_rotation; ///< Height before rotation.

int client_frame_rate; ///< Client frame rate.
DXGI_RATIONAL client_frame_rate_strict; ///< Client frame rate strict.
int client_frame_rate = 0; ///< Client frame rate.
DXGI_RATIONAL client_frame_rate_strict {}; ///< Client frame rate strict.

DXGI_FORMAT capture_format; ///< Capture format.
D3D_FEATURE_LEVEL feature_level; ///< Feature level.
Expand Down Expand Up @@ -961,6 +968,21 @@ namespace platf::dxgi {
*/
mosaic_rect_t mosaic_rect(int cells, int canvas_width, int canvas_height);

/**
* @brief Capture rate for a client frame rate on a display refresh rate.
*
* An exact X100 client rate is used as is. On a display with a fractional refresh rate
* (e.g. 59.94 Hz) a client rate just above it is lowered to match. A refresh rate the
* backend does not know (zero) keeps the client rate.
*
* @param display_refresh_rate Display refresh rate, or zero when unknown.
* @param display_refresh_rate_rounded Display refresh rate rounded, or zero when unknown.
* @param client_frame_rate Client frame rate.
* @param client_frame_rate_strict Exact client frame rate, or zero.
* @return Capture rate.
*/
DXGI_RATIONAL adjust_capture_rate(DXGI_RATIONAL display_refresh_rate, int display_refresh_rate_rounded, int client_frame_rate, DXGI_RATIONAL client_frame_rate_strict);

/**
* Display backend that reads the frames published by the OpenStreamMS RemoteIdd driver.
*
Expand Down Expand Up @@ -1014,6 +1036,17 @@ namespace platf::dxgi {
}

private:
/**
* @brief Take the refresh rate of the seat's display, which only Desktop Duplication sets.
*
* Without it capture() samples a client-rate grid that lines up with the display ticks: a
* 120 Hz seat streamed at 60 fps then sends odd or even frames depending on timer jitter
* (the motion stutters), and the capture takes the driver's texture just as the driver
* publishes the next frame. With it, capture() sends frames as they arrive, capped at the
* client rate. Single-session mode only: the mosaic keeps the grid.
*/
void read_refresh_rate();

/**
* @brief One session of a mosaic stream and its rectangle on the canvas.
*/
Expand Down
49 changes: 25 additions & 24 deletions src/platform/windows/display_base.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -225,32 +225,33 @@ namespace platf::dxgi {
release_frame();
}

capture_e display_base_t::capture(const push_captured_image_cb_t &push_captured_image_cb, const pull_free_image_cb_t &pull_free_image_cb, bool *cursor) {
auto adjust_client_frame_rate = [&]() -> DXGI_RATIONAL {
// Use exactly the requested rate if the client sent an X100 value
if (client_frame_rate_strict.Numerator > 0) {
return client_frame_rate_strict;
DXGI_RATIONAL adjust_capture_rate(DXGI_RATIONAL display_refresh_rate, int display_refresh_rate_rounded, int client_frame_rate, DXGI_RATIONAL client_frame_rate_strict) {
// Use exactly the requested rate if the client sent an X100 value
if (client_frame_rate_strict.Numerator > 0) {
return client_frame_rate_strict;
}
// Adjust capture frame interval when display refresh rate is not integral but very close to requested fps.
// A backend that does not know the refresh rate leaves it at zero; never divide by it.
if (display_refresh_rate.Denominator > 1 && display_refresh_rate_rounded > 0 && client_frame_rate > 0) {
DXGI_RATIONAL candidate = display_refresh_rate;
if (client_frame_rate % display_refresh_rate_rounded == 0) {
candidate.Numerator *= client_frame_rate / display_refresh_rate_rounded;
} else if (display_refresh_rate_rounded % client_frame_rate == 0) {
candidate.Denominator *= display_refresh_rate_rounded / client_frame_rate;
}
// Adjust capture frame interval when display refresh rate is not integral but very close to requested fps.
if (display_refresh_rate.Denominator > 1) {
DXGI_RATIONAL candidate = display_refresh_rate;
if (client_frame_rate % display_refresh_rate_rounded == 0) {
candidate.Numerator *= client_frame_rate / display_refresh_rate_rounded;
} else if (display_refresh_rate_rounded % client_frame_rate == 0) {
candidate.Denominator *= display_refresh_rate_rounded / client_frame_rate;
}
double candidate_rate = (double) candidate.Numerator / candidate.Denominator;
// Can only decrease requested fps, otherwise client may start accumulating frames and suffer increased latency.
if (client_frame_rate > candidate_rate && candidate_rate / client_frame_rate > 0.99) {
BOOST_LOG(info) << "Adjusted capture rate to " << candidate_rate << "fps to better match display";
return candidate;
}
double candidate_rate = (double) candidate.Numerator / candidate.Denominator;
// Can only decrease requested fps, otherwise client may start accumulating frames and suffer increased latency.
if (client_frame_rate > candidate_rate && candidate_rate / client_frame_rate > 0.99) {
BOOST_LOG(info) << "Adjusted capture rate to " << candidate_rate << "fps to better match display";
return candidate;
}
}

return {(uint32_t) client_frame_rate, 1};
};
return {(uint32_t) client_frame_rate, 1};
}

DXGI_RATIONAL client_frame_rate_adjusted = adjust_client_frame_rate();
capture_e display_base_t::capture(const push_captured_image_cb_t &push_captured_image_cb, const pull_free_image_cb_t &pull_free_image_cb, bool *cursor) {
DXGI_RATIONAL client_frame_rate_adjusted = adjust_capture_rate(display_refresh_rate, display_refresh_rate_rounded, client_frame_rate, client_frame_rate_strict);
std::optional<std::chrono::steady_clock::time_point> frame_pacing_group_start;
uint32_t frame_pacing_group_frames = 0;

Expand All @@ -263,10 +264,10 @@ namespace platf::dxgi {
if (display_refresh_rate.Numerator > 0 && display_refresh_rate.Denominator > 0) {
const double display_rate = (double) display_refresh_rate.Numerator / display_refresh_rate.Denominator;
const double client_rate = (double) client_frame_rate_adjusted.Numerator / client_frame_rate_adjusted.Denominator;
if (display_rate >= client_rate * 1.5) {
if (use_arrival_pacing(display_rate, client_rate, timestamps_on_display_ticks)) {
const std::chrono::nanoseconds period = std::chrono::nanoseconds(1s) * client_frame_rate_adjusted.Denominator / client_frame_rate_adjusted.Numerator;
const std::chrono::nanoseconds tick = std::chrono::nanoseconds(1s) * display_refresh_rate.Denominator / display_refresh_rate.Numerator;
arrival_limiter.emplace(period, std::min(tick, period / 2));
arrival_limiter.emplace(period, arrival_tolerance(tick, period, timestamps_on_display_ticks));
BOOST_LOG(info) << "Capturing frames as they arrive, capped at " << client_rate << "fps (display " << display_rate << "Hz)";
}
}
Expand Down
17 changes: 17 additions & 0 deletions src/platform/windows/display_remoteidd.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,7 @@ namespace platf::dxgi {
return -1;
}
BOOST_LOG(info) << "RemoteIdd: reading frames for session "sv << session;
read_refresh_rate();
return 0;
}

Expand Down Expand Up @@ -287,6 +288,22 @@ namespace platf::dxgi {
return 0;
}

void display_ridd_vram_t::read_refresh_rate() {
DXGI_OUTPUT_DESC desc {};
DEVMODEW mode {};
mode.dmSize = sizeof(mode);
// 0 and 1 mean "the hardware default": the rate stays unknown and capture() keeps its grid.
if (!output || FAILED(output->GetDesc(&desc)) || !EnumDisplaySettingsW(desc.DeviceName, ENUM_CURRENT_SETTINGS, &mode) || mode.dmDisplayFrequency <= 1) {
BOOST_LOG(info) << "RemoteIdd: display refresh rate unknown"sv;
return;
}
display_refresh_rate = {static_cast<UINT>(mode.dmDisplayFrequency), 1};
display_refresh_rate_rounded = static_cast<int>(mode.dmDisplayFrequency);
// The driver stamps each frame with the QPC time IddCx presented it at.
timestamps_on_display_ticks = true;
BOOST_LOG(info) << "RemoteIdd: display refresh rate ["sv << mode.dmDisplayFrequency << "Hz]"sv;
}

bool display_ridd_vram_t::layout_changed() {
auto now = std::chrono::steady_clock::now();
if (now < next_layout_check) {
Expand Down
35 changes: 18 additions & 17 deletions src/platform/windows/display_vram.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1939,6 +1939,23 @@ namespace platf::dxgi {
return capture_e::reinit;
}

// Get the destination ready before taking the driver's texture: a free image and its lock
// can wait for the encoder, and while this holds the shared texture the driver cannot
// publish into it (it keeps the frame aside and the stream gets it late).
std::shared_ptr<platf::img_t> img;
if (!pull_free_image_cb(img)) {
return capture_e::interrupted;
}
auto d3d_img = std::static_pointer_cast<img_d3d_t>(img);
if (complete_img(d3d_img.get(), false) != 0) {
return capture_e::capture_error;
}
texture_lock_helper lock_helper(d3d_img->capture_mutex.get());
if (!lock_helper.lock()) {
BOOST_LOG(error) << "Failed to lock capture texture";
return capture_e::capture_error;
}

ID3D11Texture2D *raw = nullptr;
RemoteIddFrameInfo frame;
if (!consumer->Acquire(static_cast<DWORD>(timeout.count()), &raw, &frame)) {
Expand All @@ -1961,24 +1978,8 @@ namespace platf::dxgi {
return capture_e::reinit;
}

std::shared_ptr<platf::img_t> img;
if (!pull_free_image_cb(img)) {
return capture_e::interrupted;
}

auto d3d_img = std::static_pointer_cast<img_d3d_t>(img);
d3d_img->blank = false;
if (complete_img(d3d_img.get(), false) != 0) {
return capture_e::capture_error;
}
{
texture_lock_helper lock_helper(d3d_img->capture_mutex.get());
if (!lock_helper.lock()) {
BOOST_LOG(error) << "Failed to lock capture texture";
return capture_e::capture_error;
}
device_ctx->CopyResource(d3d_img->capture_texture.get(), src.get());
}
device_ctx->CopyResource(d3d_img->capture_texture.get(), src.get());

auto frame_timestamp = std::chrono::steady_clock::now();
if (frame.QpcPresent) {
Expand Down
39 changes: 39 additions & 0 deletions src/platform/windows/frame_rate_limiter.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,49 @@
#pragma once

// standard includes
#include <algorithm>
#include <chrono>
#include <optional>

namespace platf::dxgi {
/**
* @brief How much earlier than its slot the limiter accepts a frame.
*
* @details One display tick, so that a frame composed on the tick before its slot still goes
* out. When the timestamps are the ticks themselves and the display rate is a multiple of the
* client rate (a 120 Hz display streamed at 60 fps), every other frame lands exactly one tick
* before its slot and timestamp jitter decides whether it is taken: the stream alternates
* between odd and even frames and the motion stutters. Half a tick keeps that choice away from
* the boundary. Never more than half a client period, so the cap still holds.
*
* @param tick Display refresh interval.
* @param period Client frame period.
* @param on_ticks Frame timestamps are the display ticks the frames were presented on.
* @return Early-arrival tolerance for frame_rate_limiter_t.
*/
inline std::chrono::nanoseconds arrival_tolerance(std::chrono::nanoseconds tick, std::chrono::nanoseconds period, bool on_ticks) {
return std::min(on_ticks ? tick / 2 : tick, period / 2);
}

/**
* @brief Whether capture should send frames as they arrive instead of on a client-rate grid.
*
* @details A grid over a faster display loses the cadence: at 90 fps over 120 Hz it sends runs
* of consecutive frames and then skips, where three frames out of four in a steady 1-1-2
* pattern are expected. With timestamps on the display ticks the limiter keeps that pattern at
* any rate clearly above the client's; a display at the client rate stays on the grid, where
* every frame already has its own slot. Composed timestamps (Desktop Duplication of an RDP
* session) switch only well above the client rate, as before.
*
* @param display_rate Display refresh rate in Hz.
* @param client_rate Client frame rate in frames per second.
* @param on_ticks Frame timestamps are the display ticks the frames were presented on.
* @return True to use frame_rate_limiter_t.
*/
inline bool use_arrival_pacing(double display_rate, double client_rate, bool on_ticks) {
return display_rate >= client_rate * (on_ticks ? 1.1 : 1.5);
}

/**
* @brief Passes captured frames as they arrive while capping their average rate.
*
Expand Down
8 changes: 7 additions & 1 deletion src/platform/windows/misc.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1799,6 +1799,12 @@ namespace platf {

/**
* @brief Convert the difference between two QPC readings to nanoseconds.
*
* Ticks times nanoseconds per tick (1e9 / frequency). It used to multiply by the frequency
* instead, which with the usual 10 MHz counter gave a hundredth of a nanosecond per tick: every
* frame timestamp came out as the moment of capture instead of the present, and so did the RTP
* timestamps and the host latency sent to clients. In floating point: ticks * 1e9 overflows
* int64 after about 15 minutes at 10 MHz.
*/
std::chrono::nanoseconds qpc_time_difference(int64_t performance_counter1, int64_t performance_counter2) {
auto get_frequency = []() {
Expand All @@ -1808,7 +1814,7 @@ namespace platf {
return frequency.QuadPart;
};
if (static const double frequency = get_frequency(); frequency) {
return std::chrono::nanoseconds((int64_t) ((performance_counter1 - performance_counter2) * frequency / std::nano::den));
return std::chrono::nanoseconds((int64_t) (static_cast<double>(performance_counter1 - performance_counter2) * std::nano::den / frequency));
}
return {};
}
Expand Down
2 changes: 1 addition & 1 deletion src/platform/windows/remoteidd/SharedFrame.h
Original file line number Diff line number Diff line change
Expand Up @@ -115,5 +115,5 @@ inline bool RemoteIddSlotRead(const RemoteIddSharedSlot* slot, RemoteIddFrameInf
// RemoteIddSlotPublish(...), SetEvent(Ready).
// Sunshine: WaitForSingleObject(Ready) -> RemoteIddSlotRead -> AcquireSync(0) ->
// codifica -> ReleaseSync(0) -> SetEvent(Done).
// El driver NO espera a Done ni al keyed mutex (AcquireSync con timeout 0): si
// El driver NO espera a Done, y al keyed mutex como mucho medio milisegundo: si
// Sunshine va lento, se pierde el frame intermedio, nunca se bloquea la sesión.
Loading
Loading