diff --git a/PATCHES.md b/PATCHES.md index 1c6062b6250..65399086b1d 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 go through the same pacer, ahead of the frame being sent, and between frames too. | +| RTP payload | 1380 bytes when the TV reports Ethernet or Wi-Fi, otherwise libdatachannel's 1220 | 1380 still fits a 1500-byte frame with IPv6 and every header. | +| Retransmission history | 4096 packets, up to 1 MiB waiting to be resent | Holds a whole 4K keyframe; libdatachannel keeps 512. A packet already waiting is not queued twice. | +| Keyframe requests | One keyframe on its way at a time, then 250 ms of grace, doubling up to 2 s while the TV keeps asking | The TV repeats PLI until a keyframe arrives; one IDR per request overflowed the link. Five quiet seconds start over at 250 ms. | | Audio | Opus stereo, 48 kHz, 5 ms packets, high quality (512 kbps) | As Moonlight requests on a LAN. | | RTP timestamps | From each frame's capture time | Monotonic; falls back to 1/60 s steps. | | IDR byte replacements | Applied before packetizing | As `stream.cpp` does for encoders without VUI parameters. | 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/platform/windows/display.h b/src/platform/windows/display.h index d35871dbd7b..f00cf880029 100644 --- a/src/platform/windows/display.h +++ b/src/platform/windows/display.h @@ -367,15 +367,22 @@ namespace platf::dxgi { output_t output; ///< DXGI output duplicated for capture. device_t device; ///< D3D11 device used for desktop duplication capture. device_ctx_t device_ctx; ///< D3D11 device context used for copy and render operations. - DXGI_RATIONAL display_refresh_rate; ///< Display refresh rate. - int display_refresh_rate_rounded; ///< Display refresh rate rounded. + DXGI_RATIONAL display_refresh_rate {}; ///< Display refresh rate; zero when the backend does not know it. + int display_refresh_rate_rounded = 0; ///< Display refresh rate rounded. + /** + * @brief Frame timestamps are the display ticks the frames were presented on. + * + * When the display rate is a multiple of the client rate, every other frame then lands exactly + * one tick before its slot; see arrival_tolerance(). + */ + bool timestamps_on_display_ticks = false; DXGI_MODE_ROTATION display_rotation = DXGI_MODE_ROTATION_UNSPECIFIED; ///< Display rotation. int width_before_rotation; ///< Width before rotation. int height_before_rotation; ///< Height before rotation. - int client_frame_rate; ///< Client frame rate. - DXGI_RATIONAL client_frame_rate_strict; ///< Client frame rate strict. + int client_frame_rate = 0; ///< Client frame rate. + DXGI_RATIONAL client_frame_rate_strict {}; ///< Client frame rate strict. DXGI_FORMAT capture_format; ///< Capture format. D3D_FEATURE_LEVEL feature_level; ///< Feature level. @@ -961,6 +968,21 @@ namespace platf::dxgi { */ mosaic_rect_t mosaic_rect(int cells, int canvas_width, int canvas_height); + /** + * @brief Capture rate for a client frame rate on a display refresh rate. + * + * An exact X100 client rate is used as is. On a display with a fractional refresh rate + * (e.g. 59.94 Hz) a client rate just above it is lowered to match. A refresh rate the + * backend does not know (zero) keeps the client rate. + * + * @param display_refresh_rate Display refresh rate, or zero when unknown. + * @param display_refresh_rate_rounded Display refresh rate rounded, or zero when unknown. + * @param client_frame_rate Client frame rate. + * @param client_frame_rate_strict Exact client frame rate, or zero. + * @return Capture rate. + */ + DXGI_RATIONAL adjust_capture_rate(DXGI_RATIONAL display_refresh_rate, int display_refresh_rate_rounded, int client_frame_rate, DXGI_RATIONAL client_frame_rate_strict); + /** * Display backend that reads the frames published by the OpenStreamMS RemoteIdd driver. * @@ -1014,6 +1036,17 @@ namespace platf::dxgi { } private: + /** + * @brief Take the refresh rate of the seat's display, which only Desktop Duplication sets. + * + * Without it capture() samples a client-rate grid that lines up with the display ticks: a + * 120 Hz seat streamed at 60 fps then sends odd or even frames depending on timer jitter + * (the motion stutters), and the capture takes the driver's texture just as the driver + * publishes the next frame. With it, capture() sends frames as they arrive, capped at the + * client rate. Single-session mode only: the mosaic keeps the grid. + */ + void read_refresh_rate(); + /** * @brief One session of a mosaic stream and its rectangle on the canvas. */ diff --git a/src/platform/windows/display_base.cpp b/src/platform/windows/display_base.cpp index 99f662f2827..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; @@ -263,10 +264,10 @@ namespace platf::dxgi { if (display_refresh_rate.Numerator > 0 && display_refresh_rate.Denominator > 0) { const double display_rate = (double) display_refresh_rate.Numerator / display_refresh_rate.Denominator; const double client_rate = (double) client_frame_rate_adjusted.Numerator / client_frame_rate_adjusted.Denominator; - if (display_rate >= client_rate * 1.5) { + if (use_arrival_pacing(display_rate, client_rate, timestamps_on_display_ticks)) { const std::chrono::nanoseconds period = std::chrono::nanoseconds(1s) * client_frame_rate_adjusted.Denominator / client_frame_rate_adjusted.Numerator; const std::chrono::nanoseconds tick = std::chrono::nanoseconds(1s) * display_refresh_rate.Denominator / display_refresh_rate.Numerator; - arrival_limiter.emplace(period, std::min(tick, period / 2)); + arrival_limiter.emplace(period, arrival_tolerance(tick, period, timestamps_on_display_ticks)); BOOST_LOG(info) << "Capturing frames as they arrive, capped at " << client_rate << "fps (display " << display_rate << "Hz)"; } } 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/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/src/platform/windows/frame_rate_limiter.h b/src/platform/windows/frame_rate_limiter.h index 3f224df5ee2..e41409ce2a5 100644 --- a/src/platform/windows/frame_rate_limiter.h +++ b/src/platform/windows/frame_rate_limiter.h @@ -5,10 +5,49 @@ #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 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/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/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. diff --git a/src/webrtc/link_pacing.h b/src/webrtc/link_pacing.h new file mode 100644 index 00000000000..84bf0b4b947 --- /dev/null +++ b/src/webrtc/link_pacing.h @@ -0,0 +1,335 @@ +/** + * @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 +#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 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. + */ + 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, and waits longer between them while the + * TV keeps asking. + */ + 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) { + 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. + */ + 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. + 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/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..e28a54ee990 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,53 +295,130 @@ namespace webrtc_stream { } /** - * @brief Bytes sent per millisecond at most: 80% of 1 Gbps, the GameStream sender's rate. + * @brief Retransmissions waiting for @ref frame_pacer_t. */ - constexpr std::size_t PACED_BYTES_PER_MS = 1'000'000'000ULL * 80 / 100 / 8 / 1000; + using resend_queue_t = link_pacing::resend_queue_t; /** - * @brief Paces a frame's RTP packets the way the GameStream sender does. + * @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. 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 paced_nack_responder_t final: public rtc::MediaHandler { + public: + /** + * @brief Answer NACKs through the given queue. + * @param resends Queue shared with the pacer. + */ + explicit paced_nack_responder_t(std::shared_ptr resends): + _responder {std::make_shared(link_pacing::NACK_HISTORY_PACKETS)}, + _resends {std::move(resends)} { + } + + 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)); + }); + } + + 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 _resends; ///< Where the requested packets wait for the pacer. + }; + + /** + * @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 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. + * 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. + * + * 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 resends Retransmissions queued by @ref paced_nack_responder_t. + */ + frame_pacer_t(int kbps, std::shared_ptr resends): + _clock {kbps}, + _resends {std::move(resends)} { + } + 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; + // 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) { - if (group_bytes >= PACED_BYTES_PER_MS) { - wait_until(frame_start + paced_duration(frame_bytes)); - group_bytes = 0; + if (_resends->pending()) { + send_resends(send); } - frame_bytes += message->size(); - group_bytes += message->size(); - send(std::move(message)); + send_paced(std::move(message), send); } messages.clear(); - _next_frame_start = frame_start + paced_duration(frame_bytes); + } + + /** + * @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 Time the given number of bytes takes at the paced rate. - * @param bytes Bytes sent. - * @return Duration. + * @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. */ - 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)}; + void send_resends(const rtc::message_callback &send) { + for (auto &packet : _resends->take()) { + send_paced(std::move(packet), send); + } } /** @@ -348,6 +426,9 @@ namespace webrtc_stream { * @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; @@ -359,8 +440,10 @@ namespace webrtc_stream { } } + link_pacing::pacing_clock_t _clock; ///< When the link will be clear. + 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. - std::chrono::steady_clock::time_point _next_frame_start {}; ///< When the previous frame's pacing ends. }; /** @@ -394,9 +477,13 @@ 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 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. @@ -420,27 +507,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 +1343,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 +1537,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->resends)); packetizer->addToChain(std::make_shared([weak_stream] { const auto stream = weak_stream.lock(); if (!stream) { @@ -1447,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()); + 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()) { @@ -1641,7 +1756,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; @@ -1699,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) { @@ -1729,6 +1864,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/platform/windows/test_frame_rate_limiter.cpp b/tests/unit/platform/windows/test_frame_rate_limiter.cpp index eb5d520d8ad..e468d40b4c8 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,58 @@ 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 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. + */ +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_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(); diff --git a/tests/unit/platform/windows/test_remoteidd.cpp b/tests/unit/platform/windows/test_remoteidd.cpp index 4afc41cc96f..d85723426cc 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 @@ -331,6 +332,258 @@ 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 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); +} + +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"; + } + + 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, 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; + + 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; + }); + + 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(); + + 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)); + } + } +} // 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;"; + } + } + // 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; +} + +/** + * @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;"; + } + } + // 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; +} + /** * @brief Part names map to the cells of the 2x2 grid; unknown names to none. */ @@ -634,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 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..19accf7e707 --- /dev/null +++ b/tests/unit/webrtc/test_webrtc_link_pacing.cpp @@ -0,0 +1,200 @@ +/** + * @file tests/unit/webrtc/test_webrtc_link_pacing.cpp + * @brief Tests for fitting the TV stream to the TV's network link. + */ + +// test includes +#include "../../tests_common.h" + +// standard includes +#include +#include +#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, HoldsWhatFollowsALargePacketGroup) { + pacing_clock_t pacer {90'000}; + const auto start = std::chrono::steady_clock::time_point {} + 1s; + // 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); + 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)); +} + +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); +} 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) {