From b4af94f3bc2a094ec4c168739f04a8681db6530a Mon Sep 17 00:00:00 2001 From: mlopezsegura <90263997+mlopezsegura@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:53:43 +0100 Subject: [PATCH 1/8] fix(windows): hold the RemoteIdd texture only while copying it The RemoteIdd snapshot took the driver's shared texture first and then waited, with it held, for a free image and for the encoder to release that image's capture texture. When the encoder ran late, every frame the driver presented in that window found the texture busy and was dropped, which showed up as an occasional skip of one or two frames, more often while the image pool was still being filled at the start of a stream. Get the destination image ready and locked before taking the driver's texture, so it is held only for the copy. Co-Authored-By: Claude Opus 5.5 --- src/platform/windows/display_vram.cpp | 35 ++++++------ .../unit/platform/windows/test_remoteidd.cpp | 57 +++++++++++++++++++ 2 files changed, 75 insertions(+), 17 deletions(-) diff --git a/src/platform/windows/display_vram.cpp b/src/platform/windows/display_vram.cpp index 585c9d00f6b..1d8e604d39b 100644 --- a/src/platform/windows/display_vram.cpp +++ b/src/platform/windows/display_vram.cpp @@ -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 img; + if (!pull_free_image_cb(img)) { + return capture_e::interrupted; + } + auto d3d_img = std::static_pointer_cast(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(timeout.count()), &raw, &frame)) { @@ -1961,24 +1978,8 @@ namespace platf::dxgi { return capture_e::reinit; } - std::shared_ptr img; - if (!pull_free_image_cb(img)) { - return capture_e::interrupted; - } - - auto d3d_img = std::static_pointer_cast(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) { diff --git a/tests/unit/platform/windows/test_remoteidd.cpp b/tests/unit/platform/windows/test_remoteidd.cpp index 4afc41cc96f..e3cc4fdd082 100644 --- a/tests/unit/platform/windows/test_remoteidd.cpp +++ b/tests/unit/platform/windows/test_remoteidd.cpp @@ -331,6 +331,63 @@ TEST(RemoteIddCaptureTest, CapturesPublishedFramesAt240Hz) { EXPECT_LE(p99, 4.0); } +/** + * @brief Waiting for a free image (the encoder) does not keep the driver's texture busy. + * + * The driver never waits for the shared texture: a frame that finds it held is kept aside + * and reaches the stream late, or not at all if a newer one replaces it. + */ +TEST(RemoteIddCaptureTest, DoesNotHoldDriverTextureWhileWaitingForAnImage) { + ComPtr pdev; + ComPtr pctx; + if (!create_device(pdev, pctx)) { + GTEST_SKIP() << "No D3D11 hardware device"; + } + + const auto session = unique_session(4); + osms::ridd::FramePublisher publisher(pdev, pctx, session, test_ns, nullptr); + frame_source_t boot; + ASSERT_TRUE(boot.init(pdev.Get(), 64, 64)); + ASSERT_EQ(publisher.Publish(boot.texture.Get(), 0), osms::ridd::FramePublisher::Result::Published); + + SetEnvironmentVariableW(L"OSMS_RIDD_NS", test_ns); + SetEnvironmentVariableW(L"OSMS_RIDD_SESSION", std::to_wstring(session).c_str()); + auto restore_capture = config::video.capture; + config::video.capture = "remoteidd"; + auto cleanup = util::fail_guard([&]() { + config::video.capture = restore_capture; + SetEnvironmentVariableW(L"OSMS_RIDD_NS", nullptr); + SetEnvironmentVariableW(L"OSMS_RIDD_SESSION", nullptr); + }); + + video::config_t config {1920, 1080, 60, 0, 20000, 1, 1, 0, 1, 0, 0, 0}; + auto disp = std::dynamic_pointer_cast(platf::display(platf::mem_type_e::dxgi, "", config)); + if (!disp) { + GTEST_SKIP() << "No display output to initialize the capture backend"; + } + + frame_source_t src; + ASSERT_TRUE(src.init(pdev.Get(), disp->width_before_rotation, disp->height_before_rotation)); + src.paint(pctx.Get(), publisher.LastFrameId() + 1); + ASSERT_EQ(publisher.Publish(src.texture.Get(), 0), osms::ridd::FramePublisher::Result::Published); + + // The encoder is slow to hand back an image; the session presents meanwhile. + std::vector> pool; + auto published_while_waiting = osms::ridd::FramePublisher::Result::Failed; + auto pull = [&](std::shared_ptr &out) { + src.paint(pctx.Get(), publisher.LastFrameId() + 1); + published_while_waiting = publisher.Publish(src.texture.Get(), 0); + pool.push_back(disp->alloc_img()); + out = pool.back(); + return true; + }; + + std::shared_ptr img; + ASSERT_EQ(disp->snapshot(pull, img, 100ms, false), platf::capture_e::ok); + disp->release_snapshot(); + EXPECT_EQ(published_while_waiting, osms::ridd::FramePublisher::Result::Published); +} + /** * @brief Part names map to the cells of the 2x2 grid; unknown names to none. */ From 57dbfb7b789bb790a240f98b1747a9a12d6e51fe Mon Sep 17 00:00:00 2001 From: mlopezsegura <90263997+mlopezsegura@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:10:38 +0100 Subject: [PATCH 2/8] fix(windows): convert QPC differences to nanoseconds qpc_time_difference multiplied the tick difference by the counter frequency instead of dividing by it, so with the usual 10 MHz counter every difference came out ten thousand times too small. Frame timestamps were therefore the moment of capture rather than the present, and so were the RTP timestamps and the host latency reported to clients. Convert in floating point: ticks times 1e9 overflows int64 after about 15 minutes at 10 MHz. Co-Authored-By: Claude Opus 5.5 --- src/platform/windows/misc.cpp | 8 +++++- tests/unit/platform/windows/test_misc.cpp | 32 ++++++++++++++++++++++- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/src/platform/windows/misc.cpp b/src/platform/windows/misc.cpp index 95848029ce1..e050db7fab3 100644 --- a/src/platform/windows/misc.cpp +++ b/src/platform/windows/misc.cpp @@ -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 = []() { @@ -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(performance_counter1 - performance_counter2) * std::nano::den / frequency)); } return {}; } diff --git a/tests/unit/platform/windows/test_misc.cpp b/tests/unit/platform/windows/test_misc.cpp index bc98f1bea3f..11735110908 100644 --- a/tests/unit/platform/windows/test_misc.cpp +++ b/tests/unit/platform/windows/test_misc.cpp @@ -1,6 +1,6 @@ /** * @file tests/unit/platform/windows/test_misc.cpp - * @brief Tests for Windows thread priority mapping. + * @brief Tests for Windows thread priority mapping and QPC time conversion. */ // test includes @@ -9,6 +9,7 @@ #ifdef _WIN32 // standard includes #include + #include #include // platform includes @@ -16,8 +17,37 @@ // local includes #include + #include #include +using namespace std::chrono_literals; + +/** + * @brief A QPC difference of one frequency's worth of ticks is one second, and so on. + */ +TEST(WindowsQpcTest, ConvertsTickDifferencesToNanoseconds) { + LARGE_INTEGER frequency; + ASSERT_TRUE(QueryPerformanceFrequency(&frequency)); + const int64_t base = 1'000'000; + EXPECT_EQ(platf::qpc_time_difference(base + frequency.QuadPart, base), 1s); + // A millisecond is not a whole number of ticks on every counter. + EXPECT_NEAR(static_cast(platf::qpc_time_difference(base + frequency.QuadPart / 1000, base).count()), 1e6, 1e3); + EXPECT_EQ(platf::qpc_time_difference(base, base + frequency.QuadPart), -1s); + // An hour of ticks, beyond what ticks * 1e9 can hold in int64 at 10 MHz. + EXPECT_EQ(platf::qpc_time_difference(base + frequency.QuadPart * 3600, base), 3600s); +} + +/** + * @brief A timestamp rebuilt from a QPC reading lands where steady_clock was at that reading. + */ +TEST(WindowsQpcTest, RebuildsPastTimestamps) { + const auto then_qpc = platf::qpc_counter(); + const auto then = std::chrono::steady_clock::now(); + Sleep(20); + const auto rebuilt = std::chrono::steady_clock::now() - platf::qpc_time_difference(platf::qpc_counter(), then_qpc); + EXPECT_LT(std::chrono::abs(rebuilt - then), 1ms); +} + TEST(WindowsThreadPriorityTest, MapsEveryPriorityAndIgnoresUnknownValues) { using enum platf::thread_priority_e; const auto thread = GetCurrentThread(); From 79bdee5a843b1331d3f6fec75689740cbe0a43b4 Mon Sep 17 00:00:00 2001 From: mlopezsegura <90263997+mlopezsegura@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:10:39 +0100 Subject: [PATCH 3/8] fix(windows): pace RemoteIdd capture by arrival when the seat outruns the client Only Desktop Duplication set display_refresh_rate, and display_base_t left it uninitialized, so with RemoteIdd capture() never knew the display rate and sampled a client-rate grid. A seat at 120 Hz streamed at 60 fps then lined the grid up with the display ticks: whether a slot took the odd or the even frame depended on timer and delivery jitter, so the stream mixed one- and three-frame steps (measured: 30-50% of frames) and the capture grabbed the driver's texture just as the driver published the next frame. RemoteIdd now reads the refresh rate of its display, so capture() sends frames as they arrive, capped at the client rate. With timestamps on the display ticks the limiter tolerates half a tick instead of a whole one: a whole tick puts every other frame exactly on its slot boundary and the same flip comes back. The rate fields now start at zero for backends that do not set them. Co-Authored-By: Claude Opus 5.5 --- src/platform/windows/display.h | 22 ++- src/platform/windows/display_base.cpp | 2 +- src/platform/windows/display_remoteidd.cpp | 17 ++ src/platform/windows/frame_rate_limiter.h | 20 +++ .../windows/test_frame_rate_limiter.cpp | 52 +++++++ .../unit/platform/windows/test_remoteidd.cpp | 146 ++++++++++++++++++ 6 files changed, 256 insertions(+), 3 deletions(-) diff --git a/src/platform/windows/display.h b/src/platform/windows/display.h index d35871dbd7b..f8d0a6646e7 100644 --- a/src/platform/windows/display.h +++ b/src/platform/windows/display.h @@ -367,8 +367,15 @@ 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. @@ -1014,6 +1021,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. */ diff --git a/src/platform/windows/display_base.cpp b/src/platform/windows/display_base.cpp index 99f662f2827..a8d2c99b65e 100644 --- a/src/platform/windows/display_base.cpp +++ b/src/platform/windows/display_base.cpp @@ -266,7 +266,7 @@ namespace platf::dxgi { if (display_rate >= client_rate * 1.5) { 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)"; } } diff --git a/src/platform/windows/display_remoteidd.cpp b/src/platform/windows/display_remoteidd.cpp index e57ec0e3c35..01d30809753 100644 --- a/src/platform/windows/display_remoteidd.cpp +++ b/src/platform/windows/display_remoteidd.cpp @@ -218,6 +218,7 @@ namespace platf::dxgi { return -1; } BOOST_LOG(info) << "RemoteIdd: reading frames for session "sv << session; + read_refresh_rate(); return 0; } @@ -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(mode.dmDisplayFrequency), 1}; + display_refresh_rate_rounded = static_cast(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) { diff --git a/src/platform/windows/frame_rate_limiter.h b/src/platform/windows/frame_rate_limiter.h index 3f224df5ee2..44354d38d95 100644 --- a/src/platform/windows/frame_rate_limiter.h +++ b/src/platform/windows/frame_rate_limiter.h @@ -5,10 +5,30 @@ #pragma once // standard includes +#include #include #include 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 Passes captured frames as they arrive while capping their average rate. * diff --git a/tests/unit/platform/windows/test_frame_rate_limiter.cpp b/tests/unit/platform/windows/test_frame_rate_limiter.cpp index eb5d520d8ad..0832b04ab91 100644 --- a/tests/unit/platform/windows/test_frame_rate_limiter.cpp +++ b/tests/unit/platform/windows/test_frame_rate_limiter.cpp @@ -10,6 +10,7 @@ // standard includes #include #include + #include // local includes #include @@ -20,6 +21,24 @@ using limiter_t = platf::dxgi::frame_rate_limiter_t; namespace { constexpr std::chrono::nanoseconds period_60 {16'666'667}; constexpr std::chrono::nanoseconds tick_125 {8'000'000}; + constexpr std::chrono::nanoseconds tick_120 {8'333'333}; + + /** + * @brief Indices of the frames a limiter accepts from a display at twice the client rate that + * presents on every tick, with timestamps a few microseconds off the tick. + */ + std::vector accepted_on_double_rate_display(std::chrono::nanoseconds tolerance) { + limiter_t limiter {period_60, tolerance}; + const auto origin = limiter_t::clock::time_point {} + 1h; + std::vector accepted; + for (int i = 0; i < 600; ++i) { + const std::chrono::microseconds jitter {(i * 7919) % 41 - 20}; + if (limiter.accept(origin + tick_120 * i + jitter)) { + accepted.push_back(i); + } + } + return accepted; + } /** * @brief Count the frames a limiter accepts when content is presented at @p content_period and @@ -107,4 +126,37 @@ TEST(FrameRateLimiterTests, CapsFasterContentToClientRate) { TEST(FrameRateLimiterTests, PassesSlowerContent) { EXPECT_EQ(accepted_frames(20ms, tick_125, 10s), 500); } + +/** + * @brief Composed frames may arrive one display tick before their slot. + */ +TEST(FrameRateLimiterTests, ToleratesOneTickForComposedFrames) { + EXPECT_EQ(platf::dxgi::arrival_tolerance(tick_125, period_60, false), tick_125); +} + +/** + * @brief Timestamps on the display ticks get half a tick. + */ +TEST(FrameRateLimiterTests, ToleratesHalfATickForTimestampsOnTicks) { + EXPECT_EQ(platf::dxgi::arrival_tolerance(tick_120, period_60, true), tick_120 / 2); +} + +/** + * @brief The tolerance never exceeds half a client period, or the cap would not hold. + */ +TEST(FrameRateLimiterTests, ToleranceNeverExceedsHalfAPeriod) { + EXPECT_EQ(platf::dxgi::arrival_tolerance(20ms, period_60, false), period_60 / 2); + EXPECT_EQ(platf::dxgi::arrival_tolerance(40ms, period_60, true), period_60 / 2); +} + +/** + * @brief A 120 Hz display streamed at 60 fps gives every other frame, never two in a row. + */ +TEST(FrameRateLimiterTests, TakesEveryOtherFrameOfADoubleRateDisplay) { + const auto accepted = accepted_on_double_rate_display(platf::dxgi::arrival_tolerance(tick_120, period_60, true)); + ASSERT_EQ(accepted.size(), 300u); + for (size_t i = 1; i < accepted.size(); ++i) { + EXPECT_EQ(accepted[i] - accepted[i - 1], 2) << "frame " << accepted[i]; + } +} #endif diff --git a/tests/unit/platform/windows/test_remoteidd.cpp b/tests/unit/platform/windows/test_remoteidd.cpp index e3cc4fdd082..48a88cdab24 100644 --- a/tests/unit/platform/windows/test_remoteidd.cpp +++ b/tests/unit/platform/windows/test_remoteidd.cpp @@ -388,6 +388,152 @@ TEST(RemoteIddCaptureTest, DoesNotHoldDriverTextureWhileWaitingForAnImage) { EXPECT_EQ(published_while_waiting, osms::ridd::FramePublisher::Result::Published); } +/** + * @brief The backend takes the refresh rate of its display, which only Desktop Duplication set. + */ +TEST(RemoteIddCaptureTest, ReadsTheDisplayRefreshRate) { + ComPtr pdev; + ComPtr pctx; + if (!create_device(pdev, pctx)) { + GTEST_SKIP() << "No D3D11 hardware device"; + } + + const auto session = unique_session(8); + osms::ridd::FramePublisher publisher(pdev, pctx, session, test_ns, nullptr); + frame_source_t boot; + ASSERT_TRUE(boot.init(pdev.Get(), 64, 64)); + ASSERT_EQ(publisher.Publish(boot.texture.Get(), 0), osms::ridd::FramePublisher::Result::Published); + + SetEnvironmentVariableW(L"OSMS_RIDD_NS", test_ns); + SetEnvironmentVariableW(L"OSMS_RIDD_SESSION", std::to_wstring(session).c_str()); + auto restore_capture = config::video.capture; + config::video.capture = "remoteidd"; + auto cleanup = util::fail_guard([&]() { + config::video.capture = restore_capture; + SetEnvironmentVariableW(L"OSMS_RIDD_NS", nullptr); + SetEnvironmentVariableW(L"OSMS_RIDD_SESSION", nullptr); + }); + + video::config_t config {1920, 1080, 60, 0, 20000, 1, 1, 0, 1, 0, 0, 0}; + auto disp = std::dynamic_pointer_cast(platf::display(platf::mem_type_e::dxgi, "", config)); + if (!disp) { + GTEST_SKIP() << "No display output to initialize the capture backend"; + } + + DXGI_OUTPUT_DESC desc {}; + ASSERT_TRUE(SUCCEEDED(disp->output->GetDesc(&desc))); + DEVMODEW mode {}; + mode.dmSize = sizeof(mode); + if (!EnumDisplaySettingsW(desc.DeviceName, ENUM_CURRENT_SETTINGS, &mode) || mode.dmDisplayFrequency <= 1) { + EXPECT_EQ(disp->display_refresh_rate.Numerator, 0u); + EXPECT_FALSE(disp->timestamps_on_display_ticks); + return; + } + EXPECT_EQ(disp->display_refresh_rate.Numerator, mode.dmDisplayFrequency); + EXPECT_EQ(disp->display_refresh_rate.Denominator, 1u); + EXPECT_EQ(disp->display_refresh_rate_rounded, static_cast(mode.dmDisplayFrequency)); + EXPECT_TRUE(disp->timestamps_on_display_ticks); +} + +/** + * @brief A seat at 120 Hz streamed at 60 fps sends every other frame, evenly spaced. + * + * Before the backend knew its refresh rate, capture() sampled a 60 fps grid that fell on the + * display ticks, and whether it took the odd or the even frame depended on timer jitter. + */ +TEST(RemoteIddCaptureTest, SendsEveryOtherFrameOfA120HzSeatAt60Fps) { + ComPtr pdev; + ComPtr pctx; + if (!create_device(pdev, pctx)) { + GTEST_SKIP() << "No D3D11 hardware device"; + } + + const auto session = unique_session(9); + osms::ridd::FramePublisher publisher(pdev, pctx, session, test_ns, nullptr); + frame_source_t boot; + ASSERT_TRUE(boot.init(pdev.Get(), 64, 64)); + ASSERT_EQ(publisher.Publish(boot.texture.Get(), 0), osms::ridd::FramePublisher::Result::Published); + + SetEnvironmentVariableW(L"OSMS_RIDD_NS", test_ns); + SetEnvironmentVariableW(L"OSMS_RIDD_SESSION", std::to_wstring(session).c_str()); + auto restore_capture = config::video.capture; + config::video.capture = "remoteidd"; + auto cleanup = util::fail_guard([&]() { + config::video.capture = restore_capture; + SetEnvironmentVariableW(L"OSMS_RIDD_NS", nullptr); + SetEnvironmentVariableW(L"OSMS_RIDD_SESSION", nullptr); + }); + + video::config_t config {1920, 1080, 60, 0, 20000, 1, 1, 0, 1, 0, 0, 0}; + auto disp = std::dynamic_pointer_cast(platf::display(platf::mem_type_e::dxgi, "", config)); + if (!disp) { + GTEST_SKIP() << "No display output to initialize the capture backend"; + } + // The seat's display, whatever the monitor of the machine running the test. + disp->display_refresh_rate = {120, 1}; + disp->display_refresh_rate_rounded = 120; + disp->timestamps_on_display_ticks = true; + + frame_source_t src; + ASSERT_TRUE(src.init(pdev.Get(), disp->width_before_rotation, disp->height_before_rotation)); + src.paint(pctx.Get(), publisher.LastFrameId() + 1); + ASSERT_EQ(publisher.Publish(src.texture.Get(), 0), osms::ridd::FramePublisher::Result::Published); + + // IddCx stamps each frame with the tick it is presented on; the driver publishes it somewhat + // later, by an amount that varies with the load of the session (here up to 1.5 ms). + LARGE_INTEGER freq, qpc0; + QueryPerformanceFrequency(&freq); + QueryPerformanceCounter(&qpc0); + const auto steady0 = std::chrono::steady_clock::now(); + const auto tick = std::chrono::nanoseconds(1'000'000'000 / 120); + std::atomic producing {true}; + std::thread producer([&]() { + for (int i = 1; producing && i < 120 * 5; ++i) { + sleep_until_precise(steady0 + tick * i + std::chrono::microseconds((i * 7919) % 1500)); + src.paint(pctx.Get(), publisher.LastFrameId() + 1); + publisher.Publish(src.texture.Get(), static_cast(qpc0.QuadPart + freq.QuadPart * i / 120)); + } + producing = false; + }); + + std::vector> pool; + auto pull = [&](std::shared_ptr &out) { + auto it = std::find_if(pool.begin(), pool.end(), [](auto &img) { + return img.use_count() == 1; + }); + if (it == pool.end()) { + pool.push_back(disp->alloc_img()); + it = pool.end() - 1; + } + out = *it; + return true; + }; + std::vector sent; + auto push = [&](std::shared_ptr &&img, bool frame_captured) { + if (frame_captured && img && img->frame_timestamp) { + sent.push_back(*img->frame_timestamp); + } + return producing && sent.size() < 120; + }; + bool cursor = false; + auto status = disp->capture(push, pull, &cursor); + producing = false; + producer.join(); + + EXPECT_EQ(status, platf::capture_e::ok); + ASSERT_GE(sent.size(), 100u); + // The first frames settle the schedule; after that, two display ticks between frames sent. + int uneven = 0; + for (size_t i = 5; i < sent.size(); ++i) { + const double ticks = std::chrono::duration(sent[i] - sent[i - 1]) / tick; + if (ticks < 1.5 || ticks > 2.5) { + ++uneven; + ADD_FAILURE() << "frame " << i << " sent " << ticks << " ticks after the previous one"; + } + } + EXPECT_EQ(uneven, 0); +} + /** * @brief Part names map to the cells of the 2x2 grid; unknown names to none. */ From f45e9ffeb05273384b0d8b54592ca7c18c8ffd83 Mon Sep 17 00:00:00 2001 From: mlopezsegura <90263997+mlopezsegura@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:10:39 +0100 Subject: [PATCH 4/8] docs(remoteidd): note the driver's short wait for the shared texture Keep the copy of SharedFrame.h in step with the driver, which now waits up to half a millisecond for the consumer to release the texture. Co-Authored-By: Claude Opus 5.5 --- src/platform/windows/remoteidd/SharedFrame.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/platform/windows/remoteidd/SharedFrame.h b/src/platform/windows/remoteidd/SharedFrame.h index 03a9a4d78b6..835eb01b482 100644 --- a/src/platform/windows/remoteidd/SharedFrame.h +++ b/src/platform/windows/remoteidd/SharedFrame.h @@ -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. From aea0274abc655ee9dafd0908ebefdf8e3ad0c883 Mon Sep 17 00:00:00 2001 From: mlopezsegura <90263997+mlopezsegura@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:26:00 +0100 Subject: [PATCH 5/8] fix(windows): pace RemoteIdd by arrival whenever the seat is faster The limiter only took over at 1.5 times the client rate, so a seat at 120 Hz streamed at 90 fps stayed on the grid. There it sent runs of consecutive frames, fell behind and skipped, instead of three frames out of four in a steady 1-1-2. With timestamps on the display ticks the limiter keeps that pattern at any rate clearly above the client's (1.1 times); composed timestamps keep the old 1.5 threshold. The capture tests now stream a 120 Hz seat at 60 and at 90 fps and check the content steps of the frames sent. They tolerate 2% of stray steps for a busy machine; the grid broke the pattern far more often. Co-Authored-By: Claude Opus 5.5 --- src/platform/windows/display_base.cpp | 2 +- src/platform/windows/frame_rate_limiter.h | 19 ++ .../windows/test_frame_rate_limiter.cpp | 21 ++ .../unit/platform/windows/test_remoteidd.cpp | 220 +++++++++++------- 4 files changed, 176 insertions(+), 86 deletions(-) diff --git a/src/platform/windows/display_base.cpp b/src/platform/windows/display_base.cpp index a8d2c99b65e..af7725cc5ac 100644 --- a/src/platform/windows/display_base.cpp +++ b/src/platform/windows/display_base.cpp @@ -263,7 +263,7 @@ 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, arrival_tolerance(tick, period, timestamps_on_display_ticks)); diff --git a/src/platform/windows/frame_rate_limiter.h b/src/platform/windows/frame_rate_limiter.h index 44354d38d95..e41409ce2a5 100644 --- a/src/platform/windows/frame_rate_limiter.h +++ b/src/platform/windows/frame_rate_limiter.h @@ -29,6 +29,25 @@ namespace platf::dxgi { 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. * diff --git a/tests/unit/platform/windows/test_frame_rate_limiter.cpp b/tests/unit/platform/windows/test_frame_rate_limiter.cpp index 0832b04ab91..e468d40b4c8 100644 --- a/tests/unit/platform/windows/test_frame_rate_limiter.cpp +++ b/tests/unit/platform/windows/test_frame_rate_limiter.cpp @@ -149,6 +149,27 @@ TEST(FrameRateLimiterTests, ToleranceNeverExceedsHalfAPeriod) { EXPECT_EQ(platf::dxgi::arrival_tolerance(40ms, period_60, true), period_60 / 2); } +/** + * @brief Composed timestamps switch to arrival pacing only well above the client rate. + */ +TEST(FrameRateLimiterTests, PacesComposedFramesByArrivalOnlyWellAboveClientRate) { + EXPECT_TRUE(platf::dxgi::use_arrival_pacing(250, 60, false)); + EXPECT_TRUE(platf::dxgi::use_arrival_pacing(120, 60, false)); + EXPECT_FALSE(platf::dxgi::use_arrival_pacing(120, 90, false)); + EXPECT_FALSE(platf::dxgi::use_arrival_pacing(60, 60, false)); +} + +/** + * @brief Timestamps on the display ticks switch as soon as the display is clearly faster. + */ +TEST(FrameRateLimiterTests, PacesTickedFramesByArrivalWhenDisplayIsFaster) { + EXPECT_TRUE(platf::dxgi::use_arrival_pacing(120, 60, true)); + EXPECT_TRUE(platf::dxgi::use_arrival_pacing(120, 90, true)); + EXPECT_TRUE(platf::dxgi::use_arrival_pacing(144, 120, true)); + EXPECT_FALSE(platf::dxgi::use_arrival_pacing(120, 120, true)); + EXPECT_FALSE(platf::dxgi::use_arrival_pacing(60, 59.94, true)); +} + /** * @brief A 120 Hz display streamed at 60 fps gives every other frame, never two in a row. */ diff --git a/tests/unit/platform/windows/test_remoteidd.cpp b/tests/unit/platform/windows/test_remoteidd.cpp index 48a88cdab24..9e1c1d4d8d0 100644 --- a/tests/unit/platform/windows/test_remoteidd.cpp +++ b/tests/unit/platform/windows/test_remoteidd.cpp @@ -11,6 +11,7 @@ #include #include #include + #include #include #include #include @@ -435,103 +436,152 @@ TEST(RemoteIddCaptureTest, ReadsTheDisplayRefreshRate) { EXPECT_TRUE(disp->timestamps_on_display_ticks); } -/** - * @brief A seat at 120 Hz streamed at 60 fps sends every other frame, evenly spaced. - * - * Before the backend knew its refresh rate, capture() sampled a 60 fps grid that fell on the - * display ticks, and whether it took the odd or the even frame depended on timer jitter. - */ -TEST(RemoteIddCaptureTest, SendsEveryOtherFrameOfA120HzSeatAt60Fps) { - ComPtr pdev; - ComPtr pctx; - if (!create_device(pdev, pctx)) { - GTEST_SKIP() << "No D3D11 hardware device"; - } +namespace { + /** + * @brief Stream a seat whose display runs at 120 Hz to a client at @p client_fps and collect, + * for each frame sent after the first few, how many display ticks its content moved on. + * + * IddCx stamps each frame with the tick it is presented on; the driver publishes it somewhat + * later, by an amount that varies with the load of the session (here up to 1.5 ms). Skips the + * calling test when there is no GPU or display to run on. + */ + void stream_120hz_seat(UINT32 session, int client_fps, std::vector &steps) { + ComPtr pdev; + ComPtr pctx; + if (!create_device(pdev, pctx)) { + GTEST_SKIP() << "No D3D11 hardware device"; + } - const auto session = unique_session(9); - osms::ridd::FramePublisher publisher(pdev, pctx, session, test_ns, nullptr); - frame_source_t boot; - ASSERT_TRUE(boot.init(pdev.Get(), 64, 64)); - ASSERT_EQ(publisher.Publish(boot.texture.Get(), 0), osms::ridd::FramePublisher::Result::Published); + osms::ridd::FramePublisher publisher(pdev, pctx, session, test_ns, nullptr); + frame_source_t boot; + ASSERT_TRUE(boot.init(pdev.Get(), 64, 64)); + ASSERT_EQ(publisher.Publish(boot.texture.Get(), 0), osms::ridd::FramePublisher::Result::Published); + + SetEnvironmentVariableW(L"OSMS_RIDD_NS", test_ns); + SetEnvironmentVariableW(L"OSMS_RIDD_SESSION", std::to_wstring(session).c_str()); + auto restore_capture = config::video.capture; + config::video.capture = "remoteidd"; + auto cleanup = util::fail_guard([&]() { + config::video.capture = restore_capture; + SetEnvironmentVariableW(L"OSMS_RIDD_NS", nullptr); + SetEnvironmentVariableW(L"OSMS_RIDD_SESSION", nullptr); + }); - SetEnvironmentVariableW(L"OSMS_RIDD_NS", test_ns); - SetEnvironmentVariableW(L"OSMS_RIDD_SESSION", std::to_wstring(session).c_str()); - auto restore_capture = config::video.capture; - config::video.capture = "remoteidd"; - auto cleanup = util::fail_guard([&]() { - config::video.capture = restore_capture; - SetEnvironmentVariableW(L"OSMS_RIDD_NS", nullptr); - SetEnvironmentVariableW(L"OSMS_RIDD_SESSION", nullptr); - }); + video::config_t config {1920, 1080, client_fps, 0, 20000, 1, 1, 0, 1, 0, 0, 0}; + auto disp = std::dynamic_pointer_cast(platf::display(platf::mem_type_e::dxgi, "", config)); + if (!disp) { + GTEST_SKIP() << "No display output to initialize the capture backend"; + } + // The seat's display, whatever the monitor of the machine running the test. + disp->display_refresh_rate = {120, 1}; + disp->display_refresh_rate_rounded = 120; + disp->timestamps_on_display_ticks = true; - video::config_t config {1920, 1080, 60, 0, 20000, 1, 1, 0, 1, 0, 0, 0}; - auto disp = std::dynamic_pointer_cast(platf::display(platf::mem_type_e::dxgi, "", config)); - if (!disp) { - GTEST_SKIP() << "No display output to initialize the capture backend"; - } - // The seat's display, whatever the monitor of the machine running the test. - disp->display_refresh_rate = {120, 1}; - disp->display_refresh_rate_rounded = 120; - disp->timestamps_on_display_ticks = true; + frame_source_t src; + ASSERT_TRUE(src.init(pdev.Get(), disp->width_before_rotation, disp->height_before_rotation)); + src.paint(pctx.Get(), publisher.LastFrameId() + 1); + ASSERT_EQ(publisher.Publish(src.texture.Get(), 0), osms::ridd::FramePublisher::Result::Published); - frame_source_t src; - ASSERT_TRUE(src.init(pdev.Get(), disp->width_before_rotation, disp->height_before_rotation)); - src.paint(pctx.Get(), publisher.LastFrameId() + 1); - ASSERT_EQ(publisher.Publish(src.texture.Get(), 0), osms::ridd::FramePublisher::Result::Published); + LARGE_INTEGER freq, qpc0; + QueryPerformanceFrequency(&freq); + QueryPerformanceCounter(&qpc0); + const auto steady0 = std::chrono::steady_clock::now(); + const auto tick = std::chrono::nanoseconds(1'000'000'000 / 120); + std::atomic producing {true}; + std::thread producer([&]() { + for (int i = 1; producing && i < 120 * 5; ++i) { + sleep_until_precise(steady0 + tick * i + std::chrono::microseconds((i * 7919) % 1500)); + src.paint(pctx.Get(), publisher.LastFrameId() + 1); + publisher.Publish(src.texture.Get(), static_cast(qpc0.QuadPart + freq.QuadPart * i / 120)); + } + producing = false; + }); - // IddCx stamps each frame with the tick it is presented on; the driver publishes it somewhat - // later, by an amount that varies with the load of the session (here up to 1.5 ms). - LARGE_INTEGER freq, qpc0; - QueryPerformanceFrequency(&freq); - QueryPerformanceCounter(&qpc0); - const auto steady0 = std::chrono::steady_clock::now(); - const auto tick = std::chrono::nanoseconds(1'000'000'000 / 120); - std::atomic producing {true}; - std::thread producer([&]() { - for (int i = 1; producing && i < 120 * 5; ++i) { - sleep_until_precise(steady0 + tick * i + std::chrono::microseconds((i * 7919) % 1500)); - src.paint(pctx.Get(), publisher.LastFrameId() + 1); - publisher.Publish(src.texture.Get(), static_cast(qpc0.QuadPart + freq.QuadPart * i / 120)); - } + std::vector> pool; + auto pull = [&](std::shared_ptr &out) { + auto it = std::find_if(pool.begin(), pool.end(), [](auto &img) { + return img.use_count() == 1; + }); + if (it == pool.end()) { + pool.push_back(disp->alloc_img()); + it = pool.end() - 1; + } + out = *it; + return true; + }; + std::vector sent; + const auto wanted = static_cast(client_fps) * 2; + auto push = [&](std::shared_ptr &&img, bool frame_captured) { + if (frame_captured && img && img->frame_timestamp) { + sent.push_back(*img->frame_timestamp); + } + return producing && sent.size() < wanted; + }; + bool cursor = false; + auto status = disp->capture(push, pull, &cursor); producing = false; - }); + producer.join(); - std::vector> pool; - auto pull = [&](std::shared_ptr &out) { - auto it = std::find_if(pool.begin(), pool.end(), [](auto &img) { - return img.use_count() == 1; - }); - if (it == pool.end()) { - pool.push_back(disp->alloc_img()); - it = pool.end() - 1; + EXPECT_EQ(status, platf::capture_e::ok); + ASSERT_GE(sent.size(), wanted * 9 / 10); + // The first frames settle the schedule. + for (size_t i = 5; i < sent.size(); ++i) { + steps.push_back(std::lround(std::chrono::duration(sent[i] - sent[i - 1]) / tick)); } - out = *it; - return true; - }; - std::vector sent; - auto push = [&](std::shared_ptr &&img, bool frame_captured) { - if (frame_captured && img && img->frame_timestamp) { - sent.push_back(*img->frame_timestamp); + } +} // namespace + +/** + * @brief A seat at 120 Hz streamed at 60 fps sends every other frame, evenly spaced. + * + * Before the backend knew its refresh rate, capture() sampled a 60 fps grid that fell on the + * display ticks, and whether it took the odd or the even frame depended on delivery and timer + * jitter: the content moved one or three ticks instead of two. + */ +TEST(RemoteIddCaptureTest, SendsEveryOtherFrameOfA120HzSeatAt60Fps) { + std::vector steps; + stream_120hz_seat(unique_session(9), 60, steps); + if (IsSkipped() || HasFatalFailure()) { + return; + } + std::string uneven; + for (size_t i = 0; i < steps.size(); ++i) { + if (steps[i] != 2) { + uneven += " frame " + std::to_string(i + 5) + ": " + std::to_string(steps[i]) + " ticks;"; } - return producing && sent.size() < 120; - }; - bool cursor = false; - auto status = disp->capture(push, pull, &cursor); - producing = false; - producer.join(); + } + // A stray scheduling delay on a busy machine may cost one; the grid got it wrong 30-50% of the time. + EXPECT_LE(std::ranges::count_if(steps, [](long s) { + return s != 2; + }), + static_cast(steps.size() / 50)) + << uneven; +} - EXPECT_EQ(status, platf::capture_e::ok); - ASSERT_GE(sent.size(), 100u); - // The first frames settle the schedule; after that, two display ticks between frames sent. - int uneven = 0; - for (size_t i = 5; i < sent.size(); ++i) { - const double ticks = std::chrono::duration(sent[i] - sent[i - 1]) / tick; - if (ticks < 1.5 || ticks > 2.5) { - ++uneven; - ADD_FAILURE() << "frame " << i << " sent " << ticks << " ticks after the previous one"; +/** + * @brief A seat at 120 Hz streamed at 90 fps sends three frames out of four, in a steady 1-1-2. + * + * On the grid it sent runs of consecutive frames and then fell behind and skipped. + */ +TEST(RemoteIddCaptureTest, SendsThreeOfFourFramesOfA120HzSeatAt90Fps) { + std::vector steps; + stream_120hz_seat(unique_session(7), 90, steps); + if (IsSkipped() || HasFatalFailure()) { + return; + } + std::string uneven; + std::ptrdiff_t breaks = 0; + for (size_t i = 0; i < steps.size(); ++i) { + const bool bad_step = steps[i] != 1 && steps[i] != 2; + const bool two_skips = i >= 1 && steps[i] == 2 && steps[i - 1] == 2; + const bool three_in_a_row = i >= 2 && steps[i] == 1 && steps[i - 1] == 1 && steps[i - 2] == 1; + if (bad_step || two_skips || three_in_a_row) { + ++breaks; + uneven += " frame " + std::to_string(i + 5) + ": " + std::to_string(steps[i]) + " ticks;"; } } - EXPECT_EQ(uneven, 0); + // A stray scheduling delay on a busy machine may cost one; the grid broke the pattern constantly. + EXPECT_LE(breaks, static_cast(steps.size() / 50)) << uneven; } /** From 6ae4402da8153b77bb9c2b55bbd5aef64618248d Mon Sep 17 00:00:00 2001 From: mlopezsegura <90263997+mlopezsegura@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:01:05 +0100 Subject: [PATCH 6/8] fix(webrtc): fit the TV stream to the TV's network link At 4K and 80 Mbps a Samsung TV on its 100 Mbps Ethernet port lost parts of large frames, asked for a keyframe, and every PLI was answered with a new 1-3 MB IDR: up to 26 a second, which overflowed the link and the PC's UDP send buffer (25,000 packets dropped in a second) and left the picture black for seconds. - One keyframe on its way at a time: requests while one is being encoded or sent, and for 250 ms after it has gone out, are taken as having crossed it. - Retransmission history of 4096 packets instead of 512, enough for a whole 4K keyframe, so a lost packet is resent instead of a new IDR. - The TV may report its link (network.type, network.linkKbps). Video is then paced at 90 % of the link instead of 800 Mbps, the bitrate is kept to 60 % of it, and retransmissions are charged to the same budget. TVs that report nothing are paced as before. - RTP payloads of 1380 bytes on Ethernet or Wi-Fi instead of 1220. Co-Authored-By: Claude Opus 5.5 --- PATCHES.md | 7 +- cmake/compile_definitions/common.cmake | 1 + src/webrtc/link_pacing.h | 210 ++++++++++++++++++ src/webrtc/protocol.cpp | 10 + src/webrtc/protocol.h | 2 + src/webrtc/webrtc_stream.cpp | 156 +++++++++---- tests/unit/webrtc/test_webrtc_link_pacing.cpp | 120 ++++++++++ tests/unit/webrtc/test_webrtc_protocol.cpp | 40 ++++ 8 files changed, 502 insertions(+), 44 deletions(-) create mode 100644 src/webrtc/link_pacing.h create mode 100644 tests/unit/webrtc/test_webrtc_link_pacing.cpp diff --git a/PATCHES.md b/PATCHES.md index 1c6062b6250..7938e82ea5a 100644 --- a/PATCHES.md +++ b/PATCHES.md @@ -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: @@ -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 are charged to the same budget. | +| 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 | Holds a whole 4K keyframe; libdatachannel keeps 512. | +| Keyframe requests | One keyframe on its way at a time, then 250 ms of grace | The TV repeats PLI until a keyframe arrives; one IDR per request overflowed the link. | | 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. | diff --git a/cmake/compile_definitions/common.cmake b/cmake/compile_definitions/common.cmake index 3379e2b2e57..5116319438b 100644 --- a/cmake/compile_definitions/common.cmake +++ b/cmake/compile_definitions/common.cmake @@ -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" diff --git a/src/webrtc/link_pacing.h b/src/webrtc/link_pacing.h new file mode 100644 index 00000000000..9585103e64b --- /dev/null +++ b/src/webrtc/link_pacing.h @@ -0,0 +1,210 @@ +/** + * @file src/webrtc/link_pacing.h + * @brief Declarations for fitting the TV stream to the TV's network link. + * + * A TV on a 100 Mbps port cannot take what a PC on a gigabit port can send. Video sent faster + * than the TV's link overflows the switch in front of it, the TV asks for the lost packets and + * for a new keyframe, and every keyframe is many times the size of an ordinary frame, so it + * overflows the link again: a picture that stays black for seconds while the PC sends more than + * ever. Everything here keeps the stream inside the link instead: the rate packets leave at, + * the bitrate the encoder targets, and how often a keyframe may be sent. + */ +#pragma once + +// standard includes +#include +#include +#include +#include +#include +#include + +namespace webrtc_stream::link_pacing { + + /** + * @brief Rate video is paced at when the TV does not report its link: 80% of 1 Gbps, the + * GameStream sender's rate. + */ + constexpr int DEFAULT_PACED_KBPS = 800'000; + + /** + * @brief Share of a reported link the paced video may fill. The rest is Ethernet, IP, UDP and + * SRTP overhead, audio and input. + */ + constexpr int LINK_PACING_PERCENT = 90; + + /** + * @brief Share of a reported link the stream's bitrate may use. + * + * A keyframe is ten or twenty times an average frame. The difference between the paced rate and + * the bitrate is what carries it, and what lets the frames queued behind it catch up, in a + * fraction of a second rather than several. + */ + constexpr int LINK_STREAM_PERCENT = 60; + + constexpr int MIN_LINK_KBPS = 10'000; ///< Slowest link a TV may report. + constexpr int MAX_LINK_KBPS = 100'000'000; ///< Fastest link a TV may report. + + /** + * @brief Packets kept to answer the TV's retransmission requests. + * + * A 4K keyframe is up to a few thousand packets. With fewer kept, a packet lost at the start + * of one can no longer be resent by the time the TV asks for it, and the TV asks for a whole + * new keyframe instead. + */ + constexpr std::size_t NACK_HISTORY_PACKETS = 4096; + + /** + * @brief RTP payload per packet when the TV is on the local network. + * + * Room is left in a 1500-byte frame for IPv6, UDP, the SRTP tag, the RTP header and its + * extensions. libdatachannel's default of 1220 assumes a 1280-byte path, which a LAN is not, + * and costs the TV one packet in eight more to receive and decrypt. + */ + constexpr std::size_t LAN_MAX_FRAGMENT_SIZE = 1380; + + /** + * @brief How long after a keyframe has gone out further requests are taken as having crossed it. + * + * The TV keeps asking until a keyframe arrives, several times per frame while one is on its way. + * Encoding one per request sent a dozen multi-megabyte keyframes a second, which is what kept + * the link overflowing. + */ + constexpr std::chrono::milliseconds KEYFRAME_SETTLE {250}; + + /** + * @brief How long a requested keyframe may take to be encoded and sent before a new request + * is honoured anyway. + */ + constexpr std::chrono::milliseconds KEYFRAME_PENDING_TIMEOUT {1000}; + + /** + * @brief Data sent ahead of the paced rate at most, as one burst. + */ + constexpr std::chrono::microseconds PACING_BURST {1000}; + + /** + * @brief Rate to pace video at. + * @param link_kbps The TV's link in kilobits per second, or 0 when it is unknown. + * @return Kilobits per second. + */ + constexpr int paced_kbps(int link_kbps) { + return link_kbps > 0 ? std::min(DEFAULT_PACED_KBPS, link_kbps / 100 * LINK_PACING_PERCENT) : DEFAULT_PACED_KBPS; + } + + /** + * @brief Total stream bitrate, limited to what the TV's link can carry with keyframes. + * @param requested_kbps Bitrate the TV asked for. + * @param link_kbps The TV's link in kilobits per second, or 0 when it is unknown. + * @return Kilobits per second. + */ + constexpr int stream_bitrate_kbps(int requested_kbps, int link_kbps) { + return link_kbps > 0 ? std::min(requested_kbps, link_kbps / 100 * LINK_STREAM_PERCENT) : requested_kbps; + } + + /** + * @brief Largest RTP payload for a TV. + * @param network_type How the TV is connected: "ethernet", "wifi" or "unknown". + * @return The payload size, or nothing to keep libdatachannel's default. + */ + constexpr std::optional max_fragment_size(std::string_view network_type) { + if (network_type == "ethernet" || network_type == "wifi") { + return LAN_MAX_FRAGMENT_SIZE; + } + return std::nullopt; + } + + /** + * @brief Releases packets at a fixed rate, in bursts of at most @ref PACING_BURST. + * + * It tracks when the link will have sent everything handed to it so far. A packet leaves at once + * while that is less than a burst away; otherwise it waits until the link is clear. An idle link + * earns no credit: what was not sent while it was idle is not sent later as one large burst. + */ + class pacing_clock_t { + public: + /** + * @brief Pace at the given rate. + * @param kbps Kilobits per second. + */ + explicit pacing_clock_t(int kbps): + _bytes_per_ms {std::max(1, std::int64_t {kbps} / 8)} { + } + + /** + * @brief Account for bytes about to be sent and say whether to wait first. + * @param bytes The packet's bytes, plus any the link carried meanwhile outside the pacer. + * @param now Current time. + * @return When the packet may leave, or nothing when it may leave now. + */ + std::optional admit(std::size_t bytes, std::chrono::steady_clock::time_point now) { + if (_link_clear_at < now) { + _link_clear_at = now; + } + std::optional due; + if (_link_clear_at - now > PACING_BURST) { + due = _link_clear_at; + } + _link_clear_at += duration(bytes); + return due; + } + + /** + * @brief Time the given bytes take at the paced rate. + * @param bytes Bytes. + * @return Duration. + */ + std::chrono::nanoseconds duration(std::size_t bytes) const { + return std::chrono::nanoseconds {static_cast(bytes) * 1'000'000 / _bytes_per_ms}; + } + + /** + * @brief Bytes the paced rate sends per millisecond. + * @return Bytes. + */ + std::int64_t bytes_per_ms() const { + return _bytes_per_ms; + } + + private: + std::int64_t _bytes_per_ms; ///< Paced rate. + std::chrono::steady_clock::time_point _link_clear_at {}; ///< When the link will have sent everything admitted so far. + }; + + /** + * @brief Lets one keyframe be on its way at a time. + */ + class keyframe_gate_t { + public: + /** + * @brief Decide whether a keyframe request should make the encoder send one. + * @param now Current time. + * @return True when a keyframe should be encoded. + */ + bool request(std::chrono::steady_clock::time_point now) { + if (_pending && now - _requested_at < KEYFRAME_PENDING_TIMEOUT) { + return false; + } + if (_sent_at && now - *_sent_at < KEYFRAME_SETTLE) { + return false; + } + _pending = true; + _requested_at = now; + return true; + } + + /** + * @brief Note that a keyframe has gone out in full, requested or not. + * @param now Current time. + */ + void sent(std::chrono::steady_clock::time_point now) { + _pending = false; + _sent_at = now; + } + + private: + bool _pending = false; ///< A keyframe has been asked of the encoder and not sent yet. + std::chrono::steady_clock::time_point _requested_at {}; ///< When it was asked for. + std::optional _sent_at; ///< When the last keyframe went out. + }; +} // namespace webrtc_stream::link_pacing diff --git a/src/webrtc/protocol.cpp b/src/webrtc/protocol.cpp index 1ed31157ce0..696fce0b0bb 100644 --- a/src/webrtc/protocol.cpp +++ b/src/webrtc/protocol.cpp @@ -7,6 +7,7 @@ #include // local includes +#include "link_pacing.h" #include "protocol.h" namespace webrtc_stream::protocol { @@ -122,6 +123,12 @@ namespace webrtc_stream::protocol { settings.bitrate_kbps = video.at("bitrateKbps").get(); settings.hdr = video.at("hdr").get(); settings.audio_channels = audio.at("channels").get(); + // Optional: TVs from before it send nothing, and are paced as before. + if (const auto network = message.find("network"); network != message.end()) { + const auto type = network->value("type", std::string {"unknown"}); + settings.network_type = type == "ethernet" || type == "wifi" ? type : "unknown"; + settings.link_kbps = network->value("linkKbps", 0); + } if (const auto error = validate_stream_settings(settings)) { throw protocol_error_t("unsupported-settings", *error); } @@ -242,6 +249,9 @@ namespace webrtc_stream::protocol { if (std::ranges::find(SUPPORTED_BITRATES_KBPS, settings.bitrate_kbps) == SUPPORTED_BITRATES_KBPS.end()) { return "Unsupported bitrate"; } + if (settings.link_kbps != 0 && (settings.link_kbps < link_pacing::MIN_LINK_KBPS || settings.link_kbps > link_pacing::MAX_LINK_KBPS)) { + return "Unsupported network link speed"; + } return std::nullopt; } diff --git a/src/webrtc/protocol.h b/src/webrtc/protocol.h index 36cf41bba93..baad85680ed 100644 --- a/src/webrtc/protocol.h +++ b/src/webrtc/protocol.h @@ -60,6 +60,8 @@ namespace webrtc_stream::protocol { video_codec_e codec = video_codec_e::h264; ///< Video codec. bool hdr = false; ///< Whether a 10-bit BT.2020 PQ stream is requested. int audio_channels = 2; ///< Audio channel count; only stereo is supported. + std::string network_type = "unknown"; ///< How the TV is connected: "ethernet", "wifi" or "unknown". + int link_kbps = 0; ///< The TV's network link in kilobits per second, or 0 when it does not know it. /** * @brief Compare two settings field by field. diff --git a/src/webrtc/webrtc_stream.cpp b/src/webrtc/webrtc_stream.cpp index bdcd83c34c1..7e92c4768c9 100644 --- a/src/webrtc/webrtc_stream.cpp +++ b/src/webrtc/webrtc_stream.cpp @@ -30,6 +30,7 @@ // local includes #include "input_bridge.h" +#include "link_pacing.h" #include "protocol.h" #include "sdp.h" #include "src/audio.h" @@ -294,55 +295,87 @@ namespace webrtc_stream { } /** - * @brief Bytes sent per millisecond at most: 80% of 1 Gbps, the GameStream sender's rate. + * @brief Bytes resent on the TV's request, counted by @ref counted_nack_responder_t and + * charged to the link by @ref frame_pacer_t. */ - constexpr std::size_t PACED_BYTES_PER_MS = 1'000'000'000ULL * 80 / 100 / 8 / 1000; + using resent_bytes_t = std::atomic; /** - * @brief Paces a frame's RTP packets the way the GameStream sender does. + * @brief Answers the TV's retransmission requests, and tells the pacer how much it resent. * - * The packetizer hands over a whole frame at once. A 4K keyframe is hundreds of packets, - * and written back to back they overflow the UDP socket's send buffer, which drops them - * without telling anyone. The TV is left without the keyframe it asked for, asks again and - * receives another burst, and the picture stays black while audio, a few small packets - * at a time, carries on. Sending a millisecond's worth at most, then waiting for the next - * millisecond, keeps every frame inside the buffer at the cost of a few milliseconds on the - * largest ones. It is the last handler of the chain and runs on the video sender thread, - * which has nothing else to do meanwhile; NACK retransmissions do not pass through it. + * libdatachannel's responder, with room for a whole 4K keyframe. Retransmissions leave from + * the network thread, outside the pacer; counting them lets the pacer hold back the next + * packets by as much, so the link as a whole stays at the paced rate, which matters most + * exactly when the TV is losing packets. + */ + class counted_nack_responder_t final: public rtc::MediaHandler { + public: + /** + * @brief Answer NACKs and count what is resent. + * @param resent_bytes Counter shared with the pacer. + */ + explicit counted_nack_responder_t(std::shared_ptr resent_bytes): + _responder {std::make_shared(link_pacing::NACK_HISTORY_PACKETS)}, + _resent_bytes {std::move(resent_bytes)} { + } + + void incoming(rtc::message_vector &messages, const rtc::message_callback &send) override { + _responder->incoming(messages, [this, &send](rtc::message_ptr packet) { + _resent_bytes->fetch_add(packet->size(), std::memory_order_relaxed); + send(std::move(packet)); + }); + } + + void outgoing(rtc::message_vector &messages, const rtc::message_callback &send) override { + _responder->outgoing(messages, send); + } + + private: + std::shared_ptr _responder; ///< Keeps the sent packets and finds the requested ones. + std::shared_ptr _resent_bytes; ///< Bytes resent since the pacer last looked. + }; + + /** + * @brief Paces a frame's RTP packets to the TV's link. + * + * The packetizer hands over a whole frame at once. A 4K keyframe is a few thousand packets, + * and written back to back they overflow the UDP socket's send buffer or, sooner, the switch + * port in front of a TV on a slower link, which drop them without telling anyone. The TV is + * left without the keyframe it asked for, asks again and receives another burst, and the + * picture stays black while audio, a few small packets at a time, carries on. Packets leave in + * bursts of a millisecond's worth at the paced rate: the GameStream sender's 800 Mbps when the + * TV does not report its link, and nine tenths of the link when it does. That costs the largest + * frames a few milliseconds, which on a slow link they would spend queued in the switch anyway. + * It is the last handler of the chain and runs on the video sender thread, which has nothing + * else to do meanwhile. */ class frame_pacer_t final: public rtc::MediaHandler { public: + /** + * @brief Pace at the given rate. + * @param kbps Kilobits per second. + * @param resent_bytes Bytes the NACK responder resent outside the pacer. + */ + frame_pacer_t(int kbps, std::shared_ptr resent_bytes): + _clock {kbps}, + _resent_bytes {std::move(resent_bytes)} { + } + void outgoing(rtc::message_vector &messages, const rtc::message_callback &send) override { if (!_timer) { _timer = platf::create_high_precision_timer(); } - // A frame that follows a large one closely starts where that one's pacing ended. - const auto frame_start = std::max(_next_frame_start, std::chrono::steady_clock::now()); - std::size_t frame_bytes = 0; - std::size_t group_bytes = 0; for (auto &message : messages) { - if (group_bytes >= PACED_BYTES_PER_MS) { - wait_until(frame_start + paced_duration(frame_bytes)); - group_bytes = 0; + const auto resent = _resent_bytes->exchange(0, std::memory_order_relaxed); + if (const auto due = _clock.admit(message->size() + resent, std::chrono::steady_clock::now())) { + wait_until(*due); } - frame_bytes += message->size(); - group_bytes += message->size(); send(std::move(message)); } messages.clear(); - _next_frame_start = frame_start + paced_duration(frame_bytes); } private: - /** - * @brief Time the given number of bytes takes at the paced rate. - * @param bytes Bytes sent. - * @return Duration. - */ - static std::chrono::nanoseconds paced_duration(std::size_t bytes) { - return std::chrono::nanoseconds {std::chrono::nanoseconds {1ms}.count() * static_cast(bytes) / static_cast(PACED_BYTES_PER_MS)}; - } - /** * @brief Sleep until a point in time, precisely when the platform allows it. * @param due When to wake. @@ -359,8 +392,9 @@ namespace webrtc_stream { } } + link_pacing::pacing_clock_t _clock; ///< When the link will be clear. + std::shared_ptr _resent_bytes; ///< Bytes resent outside the pacer. std::unique_ptr _timer; ///< Created on the sending thread. - std::chrono::steady_clock::time_point _next_frame_start {}; ///< When the previous frame's pacing ends. }; /** @@ -394,9 +428,12 @@ namespace webrtc_stream { bool stop_requested = false; ///< The stream must end. std::optional failure; ///< Why the host ended the stream. safe::mail_raw_t::event_t idr_event; ///< Keyframe requests, once capture runs. + link_pacing::keyframe_gate_t keyframe_gate; ///< Lets one keyframe be on its way at a time. std::uint32_t pli_requests = 0; ///< Keyframes the TV's WebRTC stack asked for since the last log line. std::uint32_t watchdog_requests = 0; ///< Keyframes the TV app's stall watchdog asked for since the last log line. + std::uint32_t keyframes_encoded = 0; ///< Requests that made the encoder send a keyframe, since the last log line. std::chrono::steady_clock::time_point last_request_log {}; ///< When keyframe requests were last logged. + std::shared_ptr resent_bytes = std::make_shared(0); ///< Retransmitted video bytes not yet charged to the pacer. std::mutex candidate_mutex; ///< Protects candidate buffering. bool has_remote_description = false; ///< Whether the answer was applied. @@ -420,27 +457,41 @@ namespace webrtc_stream { } /** - * @brief Encode the next frame as IDR, logging the requests at most once a second. + * @brief Encode the next frame as IDR, unless one is already on its way, logging the + * requests at most once a second. * - * A PLI storm would otherwise flood the log, while a single line per second still shows - * whether the TV asked at all while its picture was black. + * The TV repeats its request until a keyframe arrives, so while one is being encoded and + * sent, and briefly after, further requests are taken as having crossed it; see + * @ref link_pacing::keyframe_gate_t. A PLI storm would otherwise flood the log, while a + * single line per second still shows whether the TV asked at all while its picture was black. * @param from_watchdog Whether the TV app asked because its picture stopped, rather than its WebRTC stack through PLI. */ void request_keyframe(bool from_watchdog) { std::lock_guard lock(mutex); ++(from_watchdog ? watchdog_requests : pli_requests); - if (idr_event) { + const auto now = std::chrono::steady_clock::now(); + if (idr_event && keyframe_gate.request(now)) { + ++keyframes_encoded; idr_event->raise(true); } - const auto now = std::chrono::steady_clock::now(); if (now - last_request_log >= 1s) { - BOOST_LOG(info) << "WebRTC: session "sv << id << " keyframe requested: "sv << pli_requests << " PLI, "sv << watchdog_requests << " from the TV stall watchdog"sv; + BOOST_LOG(info) << "WebRTC: session "sv << id << " keyframe requested: "sv << pli_requests << " PLI, "sv << watchdog_requests << " from the TV stall watchdog; "sv << keyframes_encoded << " encoded"sv; pli_requests = 0; watchdog_requests = 0; + keyframes_encoded = 0; last_request_log = now; } } + /** + * @brief Note that a keyframe has gone out in full, so requests that crossed it are not + * answered with another. + */ + void keyframe_sent() { + std::lock_guard lock(mutex); + keyframe_gate.sent(std::chrono::steady_clock::now()); + } + /** * @brief Check whether the stream must end. * @return True once a stop was requested. @@ -1242,6 +1293,18 @@ namespace webrtc_stream { connection->stream = stream; } BOOST_LOG(info) << "WebRTC: starting "sv << title << " at "sv << settings.width << 'x' << settings.height << '@' << settings.fps << ", "sv << protocol::codec_name(settings.codec) << ", "sv << settings.bitrate_kbps << " kbps, HDR "sv << (settings.hdr ? "on"sv : "off"sv); + { + const auto stream_kbps = link_pacing::stream_bitrate_kbps(settings.bitrate_kbps, settings.link_kbps); + auto line = std::string {"WebRTC: TV network "} + settings.network_type; + if (settings.link_kbps > 0) { + line += ", " + std::to_string(settings.link_kbps / 1000) + " Mbps link"; + } + line += "; video paced at " + std::to_string(link_pacing::paced_kbps(settings.link_kbps) / 1000) + " Mbps"; + if (stream_kbps < settings.bitrate_kbps) { + line += ", bitrate limited to " + std::to_string(stream_kbps) + " kbps"; + } + BOOST_LOG(info) << line; + } send_session_status(connection, stream, "starting"); send_session_status(connection, stream, "starting-webrtc"); @@ -1424,21 +1487,22 @@ namespace webrtc_stream { stream->video_track = stream->peer->addTrack(video); stream->video_rtp = std::make_shared(VIDEO_SSRC, RTP_CNAME, sdp::VIDEO_PAYLOAD_TYPE, VIDEO_CLOCK_RATE); + const auto fragment_size = link_pacing::max_fragment_size(settings.network_type).value_or(rtc::RtpPacketizer::DefaultMaxFragmentSize); std::shared_ptr packetizer; switch (settings.codec) { case protocol::video_codec_e::hevc: - packetizer = std::make_shared(rtc::NalUnit::Separator::StartSequence, stream->video_rtp); + packetizer = std::make_shared(rtc::NalUnit::Separator::StartSequence, stream->video_rtp, fragment_size); break; case protocol::video_codec_e::av1: // Each encoded frame is one AV1 temporal unit of size-delimited OBUs. - packetizer = std::make_shared(rtc::AV1RtpPacketizer::Packetization::TemporalUnit, stream->video_rtp); + packetizer = std::make_shared(rtc::AV1RtpPacketizer::Packetization::TemporalUnit, stream->video_rtp, fragment_size); break; case protocol::video_codec_e::h264: - packetizer = std::make_shared(rtc::NalUnit::Separator::StartSequence, stream->video_rtp); + packetizer = std::make_shared(rtc::NalUnit::Separator::StartSequence, stream->video_rtp, fragment_size); break; } packetizer->addToChain(std::make_shared(stream->video_rtp)); - packetizer->addToChain(std::make_shared()); + packetizer->addToChain(std::make_shared(stream->resent_bytes)); packetizer->addToChain(std::make_shared([weak_stream] { const auto stream = weak_stream.lock(); if (!stream) { @@ -1447,7 +1511,7 @@ namespace webrtc_stream { // Sunshine encodes the next frame as IDR; no intermediate client has to ask for it. stream->request_keyframe(false); })); - packetizer->addToChain(std::make_shared()); + packetizer->addToChain(std::make_shared(link_pacing::paced_kbps(settings.link_kbps), stream->resent_bytes)); stream->video_track->setMediaHandler(packetizer); stream->video_track->onOpen([weak_stream] { if (const auto stream = weak_stream.lock()) { @@ -1641,7 +1705,9 @@ namespace webrtc_stream { video_config.framerate = settings.fps; video_config.framerateX100 = settings.fps * 100; // WebRTC needs no GameStream FEC, so only the audio and RTP overhead come off the total. - video_config.bitrate = settings.bitrate_kbps - std::min(512, settings.bitrate_kbps / 5) - std::min(500, settings.bitrate_kbps / 10); + // A TV that reports its link gets no more than the link can carry with keyframes. + const auto stream_kbps = link_pacing::stream_bitrate_kbps(settings.bitrate_kbps, settings.link_kbps); + video_config.bitrate = stream_kbps - std::min(512, stream_kbps / 5) - std::min(500, stream_kbps / 10); video_config.slicesPerFrame = 1; // The TV recovers losses through NACK and keyframes, not reference frame invalidation. video_config.numRefFrames = 1; @@ -1729,6 +1795,10 @@ namespace webrtc_stream { last_timestamp = timestamp; try { stream->video_track->sendFrame(reinterpret_cast(payload.data()), payload.size(), rtc::FrameInfo(stream->video_rtp->startTimestamp + timestamp)); + // sendFrame returns once the pacer has let the last packet out. + if (packet->is_idr()) { + stream->keyframe_sent(); + } } catch (const std::exception &e) { BOOST_LOG(warning) << "WebRTC: video frame not sent: "sv << e.what(); stream->request_stop(); diff --git a/tests/unit/webrtc/test_webrtc_link_pacing.cpp b/tests/unit/webrtc/test_webrtc_link_pacing.cpp new file mode 100644 index 00000000000..3bbb30ad2e5 --- /dev/null +++ b/tests/unit/webrtc/test_webrtc_link_pacing.cpp @@ -0,0 +1,120 @@ +/** + * @file tests/unit/webrtc/test_webrtc_link_pacing.cpp + * @brief Tests for fitting the TV stream to the TV's network link. + */ +// lib includes +#include + +// local includes +#include "src/webrtc/link_pacing.h" + +using namespace webrtc_stream::link_pacing; +using namespace std::chrono_literals; + +TEST(WebrtcLinkPacingTest, PacesAtTheGameStreamRateWithoutAReportedLink) { + EXPECT_EQ(paced_kbps(0), 800'000); + EXPECT_EQ(stream_bitrate_kbps(80'000, 0), 80'000); + EXPECT_EQ(max_fragment_size("unknown"), std::nullopt); +} + +TEST(WebrtcLinkPacingTest, FitsAHundredMegabitPort) { + EXPECT_EQ(paced_kbps(100'000), 90'000); + EXPECT_EQ(stream_bitrate_kbps(80'000, 100'000), 60'000); + EXPECT_EQ(stream_bitrate_kbps(40'000, 100'000), 40'000); +} + +TEST(WebrtcLinkPacingTest, NeverPacesFasterThanTheGameStreamRate) { + EXPECT_EQ(paced_kbps(1'000'000), 800'000); + EXPECT_EQ(paced_kbps(10'000'000), 800'000); +} + +TEST(WebrtcLinkPacingTest, UsesFullSizePacketsOnTheLocalNetwork) { + EXPECT_EQ(max_fragment_size("ethernet"), LAN_MAX_FRAGMENT_SIZE); + EXPECT_EQ(max_fragment_size("wifi"), LAN_MAX_FRAGMENT_SIZE); + // IPv6 + UDP + SRTP tag + RTP header + extensions must still fit a 1500-byte frame. + EXPECT_LE(LAN_MAX_FRAGMENT_SIZE + 40 + 8 + 10 + 12 + 40, 1500u); +} + +TEST(WebrtcLinkPacingTest, SendsABurstThenWaitsForTheLinkToClear) { + pacing_clock_t pacer {90'000}; + ASSERT_EQ(pacer.bytes_per_ms(), 11'250); + const auto start = std::chrono::steady_clock::time_point {} + 1s; + + // A millisecond's worth leaves at once. + int sent_at_once = 0; + while (!pacer.admit(1'250, start)) { + ++sent_at_once; + } + EXPECT_EQ(sent_at_once, 10); +} + +TEST(WebrtcLinkPacingTest, HoldsAFrameToThePacedRate) { + pacing_clock_t pacer {90'000}; + auto now = std::chrono::steady_clock::time_point {} + 1s; + const auto start = now; + // 1 MB, the size of a 4K keyframe, at 90 Mbps. + for (int packet = 0; packet < 800; ++packet) { + if (const auto due = pacer.admit(1'250, now)) { + ASSERT_GE(*due, now); + now = *due; + } + } + const auto elapsed = std::chrono::duration_cast(now - start); + EXPECT_GT(elapsed, 86ms); + EXPECT_LT(elapsed, 90ms); +} + +TEST(WebrtcLinkPacingTest, EarnsNoCreditWhileIdle) { + pacing_clock_t pacer {90'000}; + const auto start = std::chrono::steady_clock::time_point {} + 1s; + EXPECT_EQ(pacer.admit(1'250, start), std::nullopt); + + // A second later the link has long been clear, but only a burst leaves at once again. + int sent_at_once = 0; + while (!pacer.admit(1'250, start + 1s)) { + ++sent_at_once; + } + EXPECT_EQ(sent_at_once, 10); +} + +TEST(WebrtcLinkPacingTest, ChargesRetransmissionsToTheLink) { + pacing_clock_t pacer {90'000}; + const auto start = std::chrono::steady_clock::time_point {} + 1s; + // 112 500 bytes resent while the pacer was not looking: ten milliseconds of link. + EXPECT_EQ(pacer.admit(112'500, start), std::nullopt); + const auto due = pacer.admit(1'250, start); + ASSERT_TRUE(due); + EXPECT_EQ(*due - start, 10ms); +} + +TEST(WebrtcLinkPacingTest, AnswersRepeatedRequestsWithOneKeyframe) { + keyframe_gate_t gate; + const auto start = std::chrono::steady_clock::time_point {} + 1s; + EXPECT_TRUE(gate.request(start)); + // The TV asks again with every frame until the keyframe arrives. + EXPECT_FALSE(gate.request(start + 16ms)); + EXPECT_FALSE(gate.request(start + 100ms)); + gate.sent(start + 150ms); + // Requests that crossed it on the way are not answered with another. + EXPECT_FALSE(gate.request(start + 200ms)); + EXPECT_FALSE(gate.request(start + 150ms + KEYFRAME_SETTLE - 1ms)); + // A TV still asking after that did not get it. + EXPECT_TRUE(gate.request(start + 150ms + KEYFRAME_SETTLE)); +} + +TEST(WebrtcLinkPacingTest, RequestsAgainWhenAKeyframeNeverLeaves) { + keyframe_gate_t gate; + const auto start = std::chrono::steady_clock::time_point {} + 1s; + EXPECT_TRUE(gate.request(start)); + EXPECT_FALSE(gate.request(start + KEYFRAME_PENDING_TIMEOUT - 1ms)); + EXPECT_TRUE(gate.request(start + KEYFRAME_PENDING_TIMEOUT)); +} + +TEST(WebrtcLinkPacingTest, SettlesAfterKeyframesTheEncoderSentOnItsOwn) { + keyframe_gate_t gate; + const auto start = std::chrono::steady_clock::time_point {} + 1s; + // The stream's first frame is a keyframe nobody asked for. + gate.sent(start); + EXPECT_FALSE(gate.request(start + 50ms)); + EXPECT_TRUE(gate.request(start + KEYFRAME_SETTLE)); +} diff --git a/tests/unit/webrtc/test_webrtc_protocol.cpp b/tests/unit/webrtc/test_webrtc_protocol.cpp index fceccbf27ab..0683e98f60f 100644 --- a/tests/unit/webrtc/test_webrtc_protocol.cpp +++ b/tests/unit/webrtc/test_webrtc_protocol.cpp @@ -77,6 +77,46 @@ TEST(WebrtcProtocolTest, ParsesStartSession) { EXPECT_EQ(message.type, "start-session"); EXPECT_EQ(start.app_id, "7"); EXPECT_EQ(start.settings, settings(3840, 2160, video_codec_e::hevc, true, 50000)); + EXPECT_EQ(start.settings.network_type, "unknown"); + EXPECT_EQ(start.settings.link_kbps, 0); +} + +TEST(WebrtcProtocolTest, ParsesTheTvsNetworkLink) { + const auto message = parse_client_message( + R"({"version":2,"type":"start-session","appId":"7",)" + R"("video":{"width":3840,"height":2160,"fps":60,"codec":"av1","bitrateKbps":60000,"hdr":false},)" + R"("audio":{"channels":2},"network":{"type":"ethernet","linkKbps":100000}})" + ); + const auto &start = std::get(message.payload); + EXPECT_EQ(start.settings.network_type, "ethernet"); + EXPECT_EQ(start.settings.link_kbps, 100000); + + const auto wifi = parse_client_message( + R"({"version":2,"type":"switch-session","appId":"7",)" + R"("video":{"width":1920,"height":1080,"fps":60,"codec":"hevc","bitrateKbps":20000,"hdr":false},)" + R"("audio":{"channels":2},"network":{"type":"wifi"}})" + ); + EXPECT_EQ(std::get(wifi.payload).settings.network_type, "wifi"); + EXPECT_EQ(std::get(wifi.payload).settings.link_kbps, 0); +} + +TEST(WebrtcProtocolTest, TreatsAnUnknownNetworkTypeAsUnknown) { + const auto message = parse_client_message( + R"({"version":2,"type":"start-session","appId":"7",)" + R"("video":{"width":1920,"height":1080,"fps":60,"codec":"hevc","bitrateKbps":20000,"hdr":false},)" + R"("audio":{"channels":2},"network":{"type":"cellular"}})" + ); + EXPECT_EQ(std::get(message.payload).settings.network_type, "unknown"); +} + +TEST(WebrtcProtocolTest, RejectsImplausibleLinkSpeeds) { + const std::string prefix = R"({"version":2,"type":"start-session","appId":"7",)" + R"("video":{"width":1920,"height":1080,"fps":60,"codec":"hevc","bitrateKbps":20000,"hdr":false},)" + R"("audio":{"channels":2},"network":)"; + EXPECT_EQ(protocol_error_code(prefix + R"({"type":"ethernet","linkKbps":500}})"), "unsupported-settings"); + EXPECT_EQ(protocol_error_code(prefix + R"({"type":"ethernet","linkKbps":-1}})"), "unsupported-settings"); + EXPECT_EQ(protocol_error_code(prefix + R"({"type":"ethernet","linkKbps":"fast"}})"), "invalid-message"); + EXPECT_EQ(protocol_error_code(prefix + R"("ethernet"})"), "invalid-message"); } TEST(WebrtcProtocolTest, RejectsVersionOneAndMalformedMessages) { From af42aed1d90635166947740834751fe5e2b27584 Mon Sep 17 00:00:00 2001 From: mlopezsegura <90263997+mlopezsegura@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:41:22 +0100 Subject: [PATCH 7/8] fix(webrtc): pace retransmissions and back off repeated keyframes The first TV test, with a TV that did not report its link, was worse than before: 109,000 packets dropped in six minutes and IDRs of up to 5 MB. The larger NACK history let a single request resend megabytes at once from the network thread, outside the pacer, overflowing the 1 MiB UDP send buffer; and 250 ms between keyframes was not enough while the TV kept losing them. - Retransmissions are queued (once per packet, at most 1 MiB) and sent by the pacer at the paced rate, ahead of the frame being sent and, between frames, from the video sender thread. - The wait after a keyframe doubles, up to 2 s, each time the TV asks again soon after one; five quiet seconds start over at 250 ms. - Tests use tests_common.h. Co-Authored-By: Claude Opus 5.5 --- PATCHES.md | 6 +- src/webrtc/link_pacing.h | 131 +++++++++++++++- src/webrtc/webrtc_stream.cpp | 141 +++++++++++++----- tests/unit/webrtc/test_webrtc_link_pacing.cpp | 88 ++++++++++- 4 files changed, 320 insertions(+), 46 deletions(-) diff --git a/PATCHES.md b/PATCHES.md index 7938e82ea5a..65399086b1d 100644 --- a/PATCHES.md +++ b/PATCHES.md @@ -105,10 +105,10 @@ Stream parameters, chosen to match what the Gateway negotiated through moonlight | 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, 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 are charged to the same budget. | +| 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 | Holds a whole 4K keyframe; libdatachannel keeps 512. | -| Keyframe requests | One keyframe on its way at a time, then 250 ms of grace | The TV repeats PLI until a keyframe arrives; one IDR per request overflowed the link. | +| 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. | diff --git a/src/webrtc/link_pacing.h b/src/webrtc/link_pacing.h index 9585103e64b..84bf0b4b947 100644 --- a/src/webrtc/link_pacing.h +++ b/src/webrtc/link_pacing.h @@ -13,11 +13,15 @@ // standard includes #include +#include #include #include #include +#include #include #include +#include +#include namespace webrtc_stream::link_pacing { @@ -72,6 +76,29 @@ namespace webrtc_stream::link_pacing { */ constexpr std::chrono::milliseconds KEYFRAME_SETTLE {250}; + /** + * @brief Longest wait between keyframes while the TV keeps asking for them. + * + * A TV that asks again soon after a keyframe has gone out most likely lost it on a link it + * overflows, and the next one would go the same way. Each such request doubles the wait, up to + * this, so the link gets time to drain instead of another keyframe of several megabytes. + */ + constexpr std::chrono::milliseconds KEYFRAME_SETTLE_MAX {2000}; + + /** + * @brief Requests later than this after the last keyframe start the wait from @ref KEYFRAME_SETTLE again. + */ + constexpr std::chrono::milliseconds KEYFRAME_QUIET {5000}; + + /** + * @brief Retransmissions waiting to be sent at most, in bytes. + * + * Retransmissions go through the pacer like the frames, so that a TV asking for thousands of + * packets at once does not overflow the send buffer, which is what turned one loss into + * thousands. Beyond this much the TV would get them too late to use, and it asks for a keyframe. + */ + constexpr std::size_t RESEND_QUEUE_BYTES = 1024 * 1024; + /** * @brief How long a requested keyframe may take to be encoded and sent before a new request * is honoured anyway. @@ -172,7 +199,8 @@ namespace webrtc_stream::link_pacing { }; /** - * @brief Lets one keyframe be on its way at a time. + * @brief Lets one keyframe be on its way at a time, and waits longer between them while the + * TV keeps asking. */ class keyframe_gate_t { public: @@ -185,14 +213,27 @@ namespace webrtc_stream::link_pacing { if (_pending && now - _requested_at < KEYFRAME_PENDING_TIMEOUT) { return false; } - if (_sent_at && now - *_sent_at < KEYFRAME_SETTLE) { - return false; + if (_sent_at) { + const auto since = now - *_sent_at; + if (since < _settle) { + return false; + } + // Asked again soon after the last one: the next waits twice as long. + _settle = since < KEYFRAME_QUIET ? std::min(_settle * 2, KEYFRAME_SETTLE_MAX) : KEYFRAME_SETTLE; } _pending = true; _requested_at = now; return true; } + /** + * @brief How long after the last keyframe further requests are ignored now. + * @return The current wait. + */ + std::chrono::milliseconds settle() const { + return _settle; + } + /** * @brief Note that a keyframe has gone out in full, requested or not. * @param now Current time. @@ -206,5 +247,89 @@ namespace webrtc_stream::link_pacing { bool _pending = false; ///< A keyframe has been asked of the encoder and not sent yet. std::chrono::steady_clock::time_point _requested_at {}; ///< When it was asked for. std::optional _sent_at; ///< When the last keyframe went out. + std::chrono::milliseconds _settle {KEYFRAME_SETTLE}; ///< Current wait after a keyframe. + }; + + /** + * @brief Retransmissions the TV asked for, waiting for the pacer. + * + * Filled on the network thread, emptied by the video sender thread. A packet already waiting is + * not queued twice, however often the TV asks for it, and beyond @ref RESEND_QUEUE_BYTES further + * requests are dropped. + * @tparam Packet Shared pointer to a packet with a `size()`. + */ + template + class resend_queue_t { + public: + /** + * @brief Hold at most the given number of bytes. + * @param max_bytes Limit. + */ + explicit resend_queue_t(std::size_t max_bytes = RESEND_QUEUE_BYTES): + _max_bytes {max_bytes} { + } + + /** + * @brief Queue a packet to resend. + * @param sequence Its RTP sequence number. + * @param packet The packet. + * @return False when it was dropped because the queue is full. + */ + bool push(std::uint16_t sequence, Packet packet) { + std::lock_guard lock(_mutex); + if (std::ranges::find(_sequences, sequence) != _sequences.end()) { + return true; + } + const auto bytes = static_cast(packet->size()); + if (_bytes + bytes > _max_bytes) { + ++_dropped; + return false; + } + _bytes += bytes; + _sequences.push_back(sequence); + _packets.push_back(std::move(packet)); + _pending.store(true, std::memory_order_release); + return true; + } + + /** + * @brief Whether any packet is waiting, without taking the lock. + * @return True when @ref take would return something. + */ + bool pending() const { + return _pending.load(std::memory_order_acquire); + } + + /** + * @brief Take every waiting packet, oldest first. + * @return The packets. + */ + std::vector take() { + std::lock_guard lock(_mutex); + std::vector packets; + packets.swap(_packets); + _sequences.clear(); + _bytes = 0; + _pending.store(false, std::memory_order_release); + return packets; + } + + /** + * @brief Packets dropped because the queue was full, since the last call. + * @return The count. + */ + std::uint64_t take_dropped() { + std::lock_guard lock(_mutex); + return std::exchange(_dropped, 0); + } + + private: + std::size_t _max_bytes; ///< Limit. + std::mutex _mutex; ///< Protects everything below. + std::vector _packets; ///< Waiting packets, oldest first. + std::vector _sequences; ///< Their sequence numbers. + std::size_t _bytes = 0; ///< Their size. + std::uint64_t _dropped = 0; ///< Dropped since the last report. + std::atomic _pending {false}; ///< Whether @ref _packets is not empty. }; } // namespace webrtc_stream::link_pacing diff --git a/src/webrtc/webrtc_stream.cpp b/src/webrtc/webrtc_stream.cpp index 7e92c4768c9..e28a54ee990 100644 --- a/src/webrtc/webrtc_stream.cpp +++ b/src/webrtc/webrtc_stream.cpp @@ -295,34 +295,44 @@ namespace webrtc_stream { } /** - * @brief Bytes resent on the TV's request, counted by @ref counted_nack_responder_t and - * charged to the link by @ref frame_pacer_t. + * @brief Retransmissions waiting for @ref frame_pacer_t. */ - using resent_bytes_t = std::atomic; + using resend_queue_t = link_pacing::resend_queue_t; /** - * @brief Answers the TV's retransmission requests, and tells the pacer how much it resent. + * @brief Read an RTP packet's sequence number. + * @param packet RTP packet. + * @return The sequence number, or 0 for a packet too short to have one. + */ + std::uint16_t rtp_sequence(const rtc::Message &packet) { + if (packet.size() < 4) { + return 0; + } + return static_cast((std::to_integer(packet[2]) << 8) | std::to_integer(packet[3])); + } + + /** + * @brief Answers the TV's retransmission requests through the pacer. * - * libdatachannel's responder, with room for a whole 4K keyframe. Retransmissions leave from - * the network thread, outside the pacer; counting them lets the pacer hold back the next - * packets by as much, so the link as a whole stays at the paced rate, which matters most - * exactly when the TV is losing packets. + * libdatachannel's responder, with room for a whole 4K keyframe. It finds the packets the TV + * asks for, but instead of sending them at once from the network thread, which let a request + * for thousands of packets overflow the send buffer, it queues them for the pacer. */ - class counted_nack_responder_t final: public rtc::MediaHandler { + class paced_nack_responder_t final: public rtc::MediaHandler { public: /** - * @brief Answer NACKs and count what is resent. - * @param resent_bytes Counter shared with the pacer. + * @brief Answer NACKs through the given queue. + * @param resends Queue shared with the pacer. */ - explicit counted_nack_responder_t(std::shared_ptr resent_bytes): + explicit paced_nack_responder_t(std::shared_ptr resends): _responder {std::make_shared(link_pacing::NACK_HISTORY_PACKETS)}, - _resent_bytes {std::move(resent_bytes)} { + _resends {std::move(resends)} { } - void incoming(rtc::message_vector &messages, const rtc::message_callback &send) override { - _responder->incoming(messages, [this, &send](rtc::message_ptr packet) { - _resent_bytes->fetch_add(packet->size(), std::memory_order_relaxed); - send(std::move(packet)); + void incoming(rtc::message_vector &messages, [[maybe_unused]] const rtc::message_callback &send) override { + _responder->incoming(messages, [this](rtc::message_ptr packet) { + const auto sequence = rtp_sequence(*packet); + _resends->push(sequence, std::move(packet)); }); } @@ -332,11 +342,11 @@ namespace webrtc_stream { private: std::shared_ptr _responder; ///< Keeps the sent packets and finds the requested ones. - std::shared_ptr _resent_bytes; ///< Bytes resent since the pacer last looked. + std::shared_ptr _resends; ///< Where the requested packets wait for the pacer. }; /** - * @brief Paces a frame's RTP packets to the TV's link. + * @brief Paces a frame's RTP packets, and the retransmissions the TV asks for, to the TV's link. * * The packetizer hands over a whole frame at once. A 4K keyframe is a few thousand packets, * and written back to back they overflow the UDP socket's send buffer or, sooner, the switch @@ -346,41 +356,79 @@ namespace webrtc_stream { * bursts of a millisecond's worth at the paced rate: the GameStream sender's 800 Mbps when the * TV does not report its link, and nine tenths of the link when it does. That costs the largest * frames a few milliseconds, which on a slow link they would spend queued in the switch anyway. - * It is the last handler of the chain and runs on the video sender thread, which has nothing - * else to do meanwhile. + * + * Retransmissions share the same rate and go first, since a frame already on screen is waiting + * for them. It runs on the video sender thread, within a frame's send and, between frames, + * from @ref send_waiting_resends. */ class frame_pacer_t final: public rtc::MediaHandler { public: /** * @brief Pace at the given rate. * @param kbps Kilobits per second. - * @param resent_bytes Bytes the NACK responder resent outside the pacer. + * @param resends Retransmissions queued by @ref paced_nack_responder_t. */ - frame_pacer_t(int kbps, std::shared_ptr resent_bytes): + frame_pacer_t(int kbps, std::shared_ptr resends): _clock {kbps}, - _resent_bytes {std::move(resent_bytes)} { + _resends {std::move(resends)} { } void outgoing(rtc::message_vector &messages, const rtc::message_callback &send) override { - if (!_timer) { - _timer = platf::create_high_precision_timer(); - } + // The track's transport, valid for as long as the track: the video sender thread, the + // only one that uses it, ends before the track does. + _send = send; for (auto &message : messages) { - const auto resent = _resent_bytes->exchange(0, std::memory_order_relaxed); - if (const auto due = _clock.admit(message->size() + resent, std::chrono::steady_clock::now())) { - wait_until(*due); + if (_resends->pending()) { + send_resends(send); } - send(std::move(message)); + send_paced(std::move(message), send); } messages.clear(); } + /** + * @brief Send queued retransmissions while no frame is being sent. + * + * Called from the video sender thread between frames, so a retransmission does not wait for + * the next frame. + */ + void send_waiting_resends() { + if (_send && _resends->pending()) { + send_resends(_send); + } + } + private: + /** + * @brief Send one packet once the link has room for it. + * @param message Packet. + * @param send Transport. + */ + void send_paced(rtc::message_ptr message, const rtc::message_callback &send) { + if (const auto due = _clock.admit(message->size(), std::chrono::steady_clock::now())) { + wait_until(*due); + } + send(std::move(message)); + } + + /** + * @brief Send every queued retransmission at the paced rate. + * @param send Transport. + */ + void send_resends(const rtc::message_callback &send) { + for (auto &packet : _resends->take()) { + send_paced(std::move(packet), send); + } + } + /** * @brief Sleep until a point in time, precisely when the platform allows it. * @param due When to wake. */ void wait_until(std::chrono::steady_clock::time_point due) { + if (!_timer) { + _timer = platf::create_high_precision_timer(); + } const auto now = std::chrono::steady_clock::now(); if (now >= due) { return; @@ -393,7 +441,8 @@ namespace webrtc_stream { } link_pacing::pacing_clock_t _clock; ///< When the link will be clear. - std::shared_ptr _resent_bytes; ///< Bytes resent outside the pacer. + std::shared_ptr _resends; ///< Retransmissions the TV asked for. + rtc::message_callback _send; ///< The track's transport, from the last frame. std::unique_ptr _timer; ///< Created on the sending thread. }; @@ -433,7 +482,8 @@ namespace webrtc_stream { std::uint32_t watchdog_requests = 0; ///< Keyframes the TV app's stall watchdog asked for since the last log line. std::uint32_t keyframes_encoded = 0; ///< Requests that made the encoder send a keyframe, since the last log line. std::chrono::steady_clock::time_point last_request_log {}; ///< When keyframe requests were last logged. - std::shared_ptr resent_bytes = std::make_shared(0); ///< Retransmitted video bytes not yet charged to the pacer. + std::shared_ptr resends = std::make_shared(); ///< Retransmissions waiting for the pacer. + std::shared_ptr video_pacer; ///< Paces video and retransmissions; see @ref frame_pacer_t. std::mutex candidate_mutex; ///< Protects candidate buffering. bool has_remote_description = false; ///< Whether the answer was applied. @@ -1502,7 +1552,7 @@ namespace webrtc_stream { break; } packetizer->addToChain(std::make_shared(stream->video_rtp)); - packetizer->addToChain(std::make_shared(stream->resent_bytes)); + packetizer->addToChain(std::make_shared(stream->resends)); packetizer->addToChain(std::make_shared([weak_stream] { const auto stream = weak_stream.lock(); if (!stream) { @@ -1511,7 +1561,8 @@ namespace webrtc_stream { // Sunshine encodes the next frame as IDR; no intermediate client has to ask for it. stream->request_keyframe(false); })); - packetizer->addToChain(std::make_shared(link_pacing::paced_kbps(settings.link_kbps), stream->resent_bytes)); + stream->video_pacer = std::make_shared(link_pacing::paced_kbps(settings.link_kbps), stream->resends); + packetizer->addToChain(stream->video_pacer); stream->video_track->setMediaHandler(packetizer); stream->video_track->onOpen([weak_stream] { if (const auto stream = weak_stream.lock()) { @@ -1765,7 +1816,25 @@ namespace webrtc_stream { std::uint32_t idr_frames = 0; std::size_t largest_idr = 0; std::chrono::steady_clock::time_point last_idr_log {}; - while (auto packet = video_packets->pop()) { + std::chrono::steady_clock::time_point last_resend_log {}; + while (true) { + // Between frames, retransmissions the TV asked for go out without waiting for the next one. + auto packet = video_packets->pop(1ms); + if (!packet) { + if (!video_packets->running()) { + break; + } + if (stream->video_pacer) { + stream->video_pacer->send_waiting_resends(); + } + continue; + } + if (const auto now = std::chrono::steady_clock::now(); now - last_resend_log >= 1s) { + if (const auto dropped = stream->resends->take_dropped()) { + BOOST_LOG(warning) << "WebRTC: session "sv << stream->id << " dropped "sv << dropped << " retransmission(s) the TV asked for too late to send"sv; + } + last_resend_log = now; + } std::string_view payload {reinterpret_cast(packet->data()), packet->data_size()}; std::vector replaced; if (packet->is_idr() && packet->replacements) { diff --git a/tests/unit/webrtc/test_webrtc_link_pacing.cpp b/tests/unit/webrtc/test_webrtc_link_pacing.cpp index 3bbb30ad2e5..19accf7e707 100644 --- a/tests/unit/webrtc/test_webrtc_link_pacing.cpp +++ b/tests/unit/webrtc/test_webrtc_link_pacing.cpp @@ -2,8 +2,14 @@ * @file tests/unit/webrtc/test_webrtc_link_pacing.cpp * @brief Tests for fitting the TV stream to the TV's network link. */ -// lib includes -#include + +// test includes +#include "../../tests_common.h" + +// standard includes +#include +#include +#include // local includes #include "src/webrtc/link_pacing.h" @@ -77,10 +83,10 @@ TEST(WebrtcLinkPacingTest, EarnsNoCreditWhileIdle) { EXPECT_EQ(sent_at_once, 10); } -TEST(WebrtcLinkPacingTest, ChargesRetransmissionsToTheLink) { +TEST(WebrtcLinkPacingTest, HoldsWhatFollowsALargePacketGroup) { pacing_clock_t pacer {90'000}; const auto start = std::chrono::steady_clock::time_point {} + 1s; - // 112 500 bytes resent while the pacer was not looking: ten milliseconds of link. + // 112 500 bytes admitted at once: ten milliseconds of link before the next packet. EXPECT_EQ(pacer.admit(112'500, start), std::nullopt); const auto due = pacer.admit(1'250, start); ASSERT_TRUE(due); @@ -118,3 +124,77 @@ TEST(WebrtcLinkPacingTest, SettlesAfterKeyframesTheEncoderSentOnItsOwn) { EXPECT_FALSE(gate.request(start + 50ms)); EXPECT_TRUE(gate.request(start + KEYFRAME_SETTLE)); } + +TEST(WebrtcLinkPacingTest, WaitsLongerWhileTheTvKeepsAsking) { + keyframe_gate_t gate; + auto sent = std::chrono::steady_clock::time_point {} + 1s; + gate.sent(sent); + // Each keyframe the TV asks for again soon after doubles the wait before the next. + for (const auto wait : {250ms, 500ms, 1000ms, 2000ms}) { + ASSERT_EQ(gate.settle(), wait); + EXPECT_FALSE(gate.request(sent + wait - 1ms)); + EXPECT_TRUE(gate.request(sent + wait)); + sent += wait + 10ms; + gate.sent(sent); + } + EXPECT_EQ(gate.settle(), KEYFRAME_SETTLE_MAX); + EXPECT_TRUE(gate.request(sent + KEYFRAME_SETTLE_MAX)); + EXPECT_EQ(gate.settle(), KEYFRAME_SETTLE_MAX); +} + +TEST(WebrtcLinkPacingTest, StartsOverAfterAQuietSpell) { + keyframe_gate_t gate; + const auto sent = std::chrono::steady_clock::time_point {} + 1s; + gate.sent(sent); + EXPECT_TRUE(gate.request(sent + 300ms)); + gate.sent(sent + 320ms); + EXPECT_EQ(gate.settle(), 500ms); + EXPECT_TRUE(gate.request(sent + 320ms + KEYFRAME_QUIET)); + EXPECT_EQ(gate.settle(), KEYFRAME_SETTLE); +} + +namespace { + using packet_t = std::shared_ptr>; + + packet_t packet(std::size_t bytes) { + return std::make_shared>(bytes); + } +} // namespace + +TEST(WebrtcLinkPacingTest, QueuesEachRetransmissionOnce) { + resend_queue_t queue; + EXPECT_FALSE(queue.pending()); + EXPECT_TRUE(queue.push(7, packet(1200))); + // The TV asks again for a packet that is still waiting: it is not queued twice. + EXPECT_TRUE(queue.push(7, packet(1200))); + EXPECT_TRUE(queue.push(8, packet(1200))); + EXPECT_TRUE(queue.pending()); + EXPECT_EQ(queue.take().size(), 2u); + EXPECT_FALSE(queue.pending()); + EXPECT_TRUE(queue.take().empty()); + // Once sent, it may be lost again and asked for again. + EXPECT_TRUE(queue.push(7, packet(1200))); + EXPECT_EQ(queue.take().size(), 1u); +} + +TEST(WebrtcLinkPacingTest, DropsRetransmissionsBeyondItsLimit) { + resend_queue_t queue {3000}; + EXPECT_TRUE(queue.push(1, packet(1200))); + EXPECT_TRUE(queue.push(2, packet(1200))); + EXPECT_FALSE(queue.push(3, packet(1200))); + EXPECT_FALSE(queue.push(4, packet(1200))); + EXPECT_EQ(queue.take_dropped(), 2u); + EXPECT_EQ(queue.take_dropped(), 0u); + EXPECT_EQ(queue.take().size(), 2u); + // Taken, there is room again. + EXPECT_TRUE(queue.push(3, packet(1200))); +} + +TEST(WebrtcLinkPacingTest, HoldsAMegabyteOfRetransmissionsByDefault) { + resend_queue_t queue; + std::uint16_t sequence = 0; + while (queue.push(sequence, packet(1024))) { + ++sequence; + } + EXPECT_EQ(sequence, RESEND_QUEUE_BYTES / 1024); +} From dc2076ba4ec58e85a25b0080b2cb4cfa212cd654 Mon Sep 17 00:00:00 2001 From: mlopezsegura <90263997+mlopezsegura@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:04:39 +0100 Subject: [PATCH 8/8] fix(windows): never divide by an unknown display refresh rate capture() lowered the client rate to a fractional display rate with client_frame_rate % display_refresh_rate_rounded whenever the refresh-rate denominator was above 1. Only Desktop Duplication set those fields, and display_ridd_vram_t has its own constructor, so with RemoteIdd capture they held whatever was on the heap. A denominator above 1 with a rounded rate of 0 crashed Sunshine with STATUS_INTEGER_DIVIDE_BY_ZERO on the first capture after a seat started (OpenstreamCo/OpenStreamMultiSeat#106). The fields already start at zero; the adjustment now also skips a rounded rate or client rate of zero. It moves to adjust_capture_rate() so it can be tested, and the client rate fields start at zero too. Co-Authored-By: Claude Opus 5.5 --- src/platform/windows/display.h | 19 +++++++- src/platform/windows/display_base.cpp | 45 ++++++++++--------- .../unit/platform/windows/test_remoteidd.cpp | 29 ++++++++++++ 3 files changed, 69 insertions(+), 24 deletions(-) diff --git a/src/platform/windows/display.h b/src/platform/windows/display.h index f8d0a6646e7..f00cf880029 100644 --- a/src/platform/windows/display.h +++ b/src/platform/windows/display.h @@ -381,8 +381,8 @@ namespace platf::dxgi { 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. @@ -968,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. * diff --git a/src/platform/windows/display_base.cpp b/src/platform/windows/display_base.cpp index af7725cc5ac..62e50b3f08f 100644 --- a/src/platform/windows/display_base.cpp +++ b/src/platform/windows/display_base.cpp @@ -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 frame_pacing_group_start; uint32_t frame_pacing_group_frames = 0; diff --git a/tests/unit/platform/windows/test_remoteidd.cpp b/tests/unit/platform/windows/test_remoteidd.cpp index 9e1c1d4d8d0..d85723426cc 100644 --- a/tests/unit/platform/windows/test_remoteidd.cpp +++ b/tests/unit/platform/windows/test_remoteidd.cpp @@ -887,4 +887,33 @@ TEST(RemoteIddCaptureTest, ReinitializesWhenMosaicLayoutChanges) { std::shared_ptr again; EXPECT_EQ(mosaic->snapshot(pull, again, 10ms, false), platf::capture_e::reinit); } + +namespace { + void expect_rate(DXGI_RATIONAL rate, UINT numerator, UINT denominator) { + EXPECT_EQ(rate.Numerator, numerator); + EXPECT_EQ(rate.Denominator, denominator); + } +} // namespace + +TEST(RemoteIddCaptureRateTest, KeepsClientRateWhenRefreshRateIsUnknown) { + // RemoteIdd leaves the refresh rate at zero when the display does not report one. + expect_rate(platf::dxgi::adjust_capture_rate({0, 0}, 0, 60, {0, 0}), 60, 1); +} + +TEST(RemoteIddCaptureRateTest, DoesNotDivideByAZeroRoundedRate) { + // A fractional refresh rate that rounds to zero used to divide by zero (issue #106). + expect_rate(platf::dxgi::adjust_capture_rate({1, 1000}, 0, 60, {0, 0}), 60, 1); + expect_rate(platf::dxgi::adjust_capture_rate({60000, 1001}, 60, 0, {0, 0}), 0, 1); +} + +TEST(RemoteIddCaptureRateTest, MatchesAFractionalDisplayRate) { + expect_rate(platf::dxgi::adjust_capture_rate({60000, 1001}, 60, 60, {0, 0}), 60000, 1001); + expect_rate(platf::dxgi::adjust_capture_rate({60000, 1001}, 60, 120, {0, 0}), 120000, 1001); + expect_rate(platf::dxgi::adjust_capture_rate({120000, 1001}, 120, 60, {0, 0}), 120000, 2002); +} + +TEST(RemoteIddCaptureRateTest, KeepsIntegralAndExactRates) { + expect_rate(platf::dxgi::adjust_capture_rate({120, 1}, 120, 60, {0, 0}), 60, 1); + expect_rate(platf::dxgi::adjust_capture_rate({60000, 1001}, 60, 60, {5994, 100}), 5994, 100); +} #endif