feat(video): add support for legacy MPEG-2 and H.263+ encoders (#5194)

This commit is contained in:
Dave Lane authored and GitHub committed 2026-11-22 19:07:41 -05:00
1 parent 6b54f99fd8
commit 5f7d08e8d6
27 files changed
+1794 -448

No files matched your search

+1 -1
View File
@@ -29,7 +29,7 @@ function(sunshine_forward_dependency_headers source_dir include_prefix)
endfunction()
sunshine_forward_dependency_headers("${moonlight-common-c_SOURCE_DIR}/src" "moonlight-common-c/src"
Input.h Limelight.h Limelight-internal.h Rtsp.h)
Input.h Limelight.h Limelight-internal.h Rtsp.h VideoFormats.h)
sunshine_forward_dependency_headers("${simple_web_server_SOURCE_DIR}" "Simple-Web-Server"
client_http.hpp client_https.hpp crypto.hpp server_http.hpp server_https.hpp)
+82
View File
@@ -2281,6 +2281,88 @@ consent prompt for directory ACLs, so the Web UI shows setup steps for correctin
</tr>
</table>
### mpeg2_mode
<table>
<tr>
<td>Description</td>
<td colspan="2">
Allows any client implementing the Sunshine codec extension to request MPEG-2/H.262 video streams.
Support is unadvertised by default and must be enabled here. Sunshine probes MPEG-2 independently of
H.264, preferring the selected backend before trying other available backends. Enabling H.263+ does not
displace a working hardware MPEG-2 encoder. Streams using different encoder backends use separate
capture workers.
@warning{MPEG-2 may be more CPU-intensive to encode than modern hardware-accelerated codecs when hardware
encoding is unavailable.}
</td>
</tr>
<tr>
<td>Default</td>
<td colspan="2">@code{}
0
@endcode</td>
</tr>
<tr>
<td>Example</td>
<td colspan="2">@code{}
mpeg2_mode = 2
@endcode</td>
</tr>
<tr>
<td rowspan="3">Choices</td>
<td>0</td>
<td>preserve modern codec automatic selection and keep MPEG-2 unadvertised</td>
</tr>
<tr>
<td>1</td>
<td>do not advertise support for MPEG-2</td>
</tr>
<tr>
<td>2</td>
<td>advertise support for MPEG-2/H.262 video after a successful encoder probe</td>
</tr>
</table>
### h263p_mode
<table>
<tr>
<td>Description</td>
<td colspan="2">
Allows any client implementing the Sunshine codec extension to request H.263+ video streams.
Support is unadvertised by default and must be enabled here. Sunshine selects and probes its H.263+
backend independently of MPEG-2 and modern codecs; H.264 support is not a prerequisite.
The stream width and height must both be multiples of four after applying any resolution cap.
@warning{H.263+ uses software encoding in Sunshine and may reduce host performance.}
</td>
</tr>
<tr>
<td>Default</td>
<td colspan="2">@code{}
0
@endcode</td>
</tr>
<tr>
<td>Example</td>
<td colspan="2">@code{}
h263p_mode = 2
@endcode</td>
</tr>
<tr>
<td rowspan="3">Choices</td>
<td>0</td>
<td>preserve modern codec automatic selection and keep H.263+ unadvertised</td>
</tr>
<tr>
<td>1</td>
<td>do not advertise support for H.263+</td>
</tr>
<tr>
<td>2</td>
<td>advertise support for H.263+ video after a successful encoder probe</td>
</tr>
</table>
### capture
<table>
+1 -1
View File
@@ -85,7 +85,7 @@ CPMDeclarePackage(libvirtualhid
# moonlight-common-c
# renovate: datasource=git-refs depName=moonlight-stream/moonlight-common-c
# ref=master
set(MOONLIGHT_COMMON_C_COMMIT 94c65fd364d17b223f00a8763c9a5d94a66cb8dd)
set(MOONLIGHT_COMMON_C_COMMIT b4ee1cea3d19e13c0b37c26585e6b1ee174effcb)
CPMDeclarePackage(moonlight-common-c
NAME moonlight-common-c
GIT_REPOSITORY https://github.com/moonlight-stream/moonlight-common-c.git
@@ -8,7 +8,7 @@
"ref": "master"
},
"url": "https://github.com/moonlight-stream/moonlight-common-c.git",
"commit": "94c65fd364d17b223f00a8763c9a5d94a66cb8dd",
"commit": "b4ee1cea3d19e13c0b37c26585e6b1ee174effcb",
"dest": "flatpak-cpm/moonlight-common-c"
}
]
+4
View File
@@ -713,6 +713,8 @@ namespace config {
0, // hevc_mode
0, // av1_mode
0, // mpeg2_mode
0, // h263p_mode
2, // min_threads
@@ -1661,6 +1663,8 @@ namespace config {
int_f(vars, "qp", video.qp);
int_between_f(vars, "hevc_mode", video.hevc_mode, {0, 3});
int_between_f(vars, "av1_mode", video.av1_mode, {0, 3});
int_between_f(vars, "mpeg2_mode", video.mpeg2_mode, {0, 2});
int_between_f(vars, "h263p_mode", video.h263p_mode, {0, 2});
int_f(vars, "min_threads", video.min_threads);
std::string max_stream_resolution;
+2
View File
@@ -75,6 +75,8 @@ namespace config {
int hevc_mode; ///< HEVC support mode advertised to clients.
int av1_mode; ///< AV1 support mode advertised to clients.
int mpeg2_mode; ///< MPEG-2 codec advertisement mode.
int h263p_mode; ///< H.263+ codec advertisement mode.
int min_threads; ///< Minimum number of threads or slices for CPU encoding.
+9 -2
View File
@@ -1205,8 +1205,9 @@ namespace nvhttp {
}
uint32_t get_codec_mode_flags() {
uint32_t codec_mode_flags = SCM_H264;
if (video::last_encoder_probe_supported_yuv444_for_codec[0]) {
const auto &modes = video::probed_codec_modes();
uint32_t codec_mode_flags = modes.h264 ? SCM_H264 : 0;
if (modes.h264 && video::last_encoder_probe_supported_yuv444_for_codec[0]) {
codec_mode_flags |= SCM_H264_HIGH8_444;
}
if (video::active_hevc_mode >= 2) {
@@ -1234,6 +1235,12 @@ namespace nvhttp {
if ((video::active_av1_mode == 4 || video::active_av1_mode == 5) && video::last_encoder_probe_supported_dynamic_range_yuv444_for_codec[2]) {
codec_mode_flags |= SCM_AV1_HIGH10_444;
}
if (modes.mpeg2 >= 2) {
codec_mode_flags |= SCM_MPEG2;
}
if (modes.h263p == 2) {
codec_mode_flags |= SCM_H263P;
}
return codec_mode_flags;
}
+82
View File
@@ -0,0 +1,82 @@
/**
* @file src/platform/linux/kms_display.h
* @brief Display enumeration data for one KMS capture backend.
*/
#pragma once
// standard includes
#include <algorithm>
#include <charconv>
#include <cstddef>
#include <cstdint>
#include <map>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
// local includes
#include "display_geometry.h"
namespace platf::kms {
/**
* @brief Connector identity and geometry for one KMS monitor.
*/
struct monitor_t {
std::uint32_t type; ///< DRM connector type.
std::uint32_t index; ///< Index within the connector type.
std::uint32_t monitor_index; ///< Index in the capture backend's display list.
touch_port_t viewport; ///< Monitor geometry for capture and absolute input.
};
/**
* @brief DRM card and its monitor descriptors indexed by CRTC ID.
*/
struct card_descriptor_t {
std::string path; ///< DRM card device path.
std::map<std::uint32_t, monitor_t> crtc_to_monitor; ///< Monitors associated with the card.
};
/**
* @brief A display discovered on a particular card and plane.
*/
struct output_t {
std::string name; ///< DRM connector name.
std::size_t card_index; ///< Index into this enumeration's card descriptors.
std::uint32_t plane_id; ///< ID of the DRM plane that was scanning out this output.
std::uint32_t crtc_id; ///< CRTC the plane was attached to during enumeration.
};
/**
* @brief Display names, card descriptors, and desktop geometry enumerated together for one memory type.
*/
struct display_enumeration_t {
std::vector<output_t> outputs; ///< Displays in capture order.
std::vector<card_descriptor_t> cards; ///< DRM cards in capture order.
desktop_geometry_t desktop; ///< Geometry of this enumeration's available outputs.
/**
* @brief Map a connector name or a legacy numeric display name to a capture index.
*
* @param name Display name from the stream or host configuration.
* @return Display index, zero for the default name, or no value for an unknown connector.
*/
std::optional<std::size_t> display_index(std::string_view name) const {
if (name.empty()) {
return 0;
}
std::size_t index;
const auto [end, parse_error] = std::from_chars(name.data(), name.data() + name.size(), index);
if (end == name.data() + name.size() && parse_error == std::errc {}) {
return index;
}
auto position = std::ranges::find(outputs, name, &output_t::name);
if (position == outputs.end()) {
return std::nullopt;
}
return static_cast<std::size_t>(position - outputs.begin());
}
};
} // namespace platf::kms
+156 -286
View File
@@ -24,8 +24,8 @@
// local includes
#include "cuda.h"
#include "display_geometry.h"
#include "graphics.h"
#include "kms_display.h"
#include "kms_plane.h"
#include "src/config.h"
#include "src/logging.h"
@@ -344,8 +344,6 @@ namespace platf {
*/
using conn_type_count_t = std::map<std::uint32_t, std::uint32_t>;
static platf::touch_port_t env_bounds {}; ///< Full desktop origin and extents for absolute input.
/**
* @brief Convert a DRM plane type value to a diagnostic string.
*
@@ -384,31 +382,6 @@ namespace platf {
bool connected; ///< Whether the DRM connector is connected.
};
/**
* @brief KMS monitor capture state and DRM resources.
*/
struct monitor_t {
// Connector attributes
std::uint32_t type; ///< Type.
std::uint32_t index; ///< Index.
// Monitor index in the global list
std::uint32_t monitor_index; ///< Monitor index.
platf::touch_port_t viewport; ///< Viewport.
};
/**
* @brief DRM card, device path, and render-node metadata.
*/
struct card_descriptor_t {
std::string path; ///< Path.
std::map<std::uint32_t, monitor_t> crtc_to_monitor; ///< Crtc to monitor.
};
static std::vector<card_descriptor_t> card_descriptors;
static std::uint32_t from_view(const std::string_view &string) {
#ifndef DOXYGEN
#define _CONVERT(x, y) \
@@ -1102,30 +1075,6 @@ namespace platf {
BOOST_LOG(debug) << ss.str();
}
/**
* @brief Map display name to monitor index
*
* @param display_name Name of the display to determine monitor index for (or monitor index string value)
* @return monitor's display index
*/
static int64_t map_display_name_to_monitor_index(const std::string_view &display_name) {
// Handle (legacy) monitor index strings by converting them to integer
if (display_name.empty() || std::ranges::all_of(display_name, ::isdigit)) {
return util::from_view(display_name);
}
// display_name is a connector name (not empty and containing non-digits)
for (auto &card_descriptor : kms::card_descriptors) {
for (const auto &monitor_descriptor : card_descriptor.crtc_to_monitor | std::views::values) {
if (display_name == std::format("{}-{}", drmModeGetConnectorTypeName(monitor_descriptor.type), monitor_descriptor.index)) {
BOOST_LOG(info) << "Mapped '"sv << display_name << "' to kmsgrab monitor index " << monitor_descriptor.monitor_index;
return monitor_descriptor.monitor_index;
}
}
}
BOOST_LOG(warning) << "Couldn't map '"sv << display_name << "' to a monitor index. Falling back to first monitor in list (index=0).";
return 0; // Fallback to first index if nothing can be matched
}
/**
* @brief Base KMS display capture backend shared by RAM and VRAM paths.
*/
@@ -1146,209 +1095,129 @@ namespace platf {
*
* @param display_name Display name.
* @param config Configuration values to apply.
* @param enumeration Displays and geometry for this capture backend.
* @return 0 on success; nonzero or negative platform status on failure.
*/
int init(const std::string &display_name, const ::video::config_t &config) {
int init(const std::string &display_name, const ::video::config_t &config, const display_enumeration_t &enumeration) {
delay = ::video::capture_frame_interval(config);
int monitor_index = map_display_name_to_monitor_index(display_name);
int monitor = 0;
const auto index = enumeration.display_index(display_name);
if (!index.has_value()) {
BOOST_LOG(warning) << "Couldn't map '"sv << display_name << "' to a kmsgrab monitor. Falling back to the first output."sv;
}
const auto monitor_index = index.value_or(0);
if (monitor_index >= enumeration.outputs.size()) {
BOOST_LOG(error) << "Couldn't find monitor ["sv << monitor_index << ']';
return -1;
}
fs::path card_dir {"/dev/dri"sv};
for (auto &entry : fs::directory_iterator {card_dir}) {
auto file = entry.path().filename();
const auto &output = enumeration.outputs[monitor_index];
const auto &descriptor = enumeration.cards[output.card_index];
if (card.init(descriptor.path.c_str())) {
return -1;
}
auto filestring = file.generic_string();
if (filestring.size() < 4 || std::string_view {filestring}.substr(0, 4) != "card"sv) {
continue;
}
plane_t plane {drmModeGetPlane(card.fd.el, output.plane_id)};
if (!plane || !plane->fb_id || plane->crtc_id != output.crtc_id) {
BOOST_LOG(warning) << "KMS output changed during capture initialization: "sv << output.name;
return -1;
}
kms::card_t card;
if (card.init(entry.path().c_str())) {
continue;
}
auto fb = card.fb(plane.get());
if (!fb) {
BOOST_LOG(error) << "Couldn't get drm fb for plane ["sv << plane->fb_id << "]: "sv << strerror(errno);
return -1;
}
// Skip non-Nvidia cards if we're looking for CUDA devices
// unless NVENC is selected manually by the user
if (mem_type == mem_type_e::cuda && !card.is_nvidia()) {
BOOST_LOG(debug) << file << " is not a CUDA device"sv;
if (config::video.encoder != "nvenc") {
continue;
}
}
if (!fb->handles[0]) {
BOOST_LOG(error) << "Couldn't get handle for DRM Framebuffer ["sv << plane->fb_id << "]: Probably not permitted"sv;
return -1;
}
// Skip Nvidia cards if we're looking for VAAPI devices
// This is important for hybrid GPU laptops where the display
// may be connected through NVIDIA but rendering happens on Intel
if (mem_type == mem_type_e::vaapi && card.is_nvidia()) {
BOOST_LOG(debug) << file << " is an NVIDIA card, skipping for VAAPI"sv;
continue;
}
auto end = std::end(card);
for (auto plane = std::begin(card); plane != end; ++plane) {
// Skip unused planes
if (!plane->fb_id) {
continue;
}
if (card.is_cursor(plane->plane_id)) {
continue;
}
if (monitor != monitor_index) {
++monitor;
continue;
}
auto fb = card.fb(plane.get());
if (!fb) {
BOOST_LOG(error) << "Couldn't get drm fb for plane ["sv << plane->fb_id << "]: "sv << strerror(errno);
return -1;
}
if (!fb->handles[0]) {
BOOST_LOG(error) << "Couldn't get handle for DRM Framebuffer ["sv << plane->fb_id << "]: Probably not permitted"sv;
return -1;
}
for (int i = 0; i < 4; ++i) {
if (!fb->handles[i]) {
break;
}
auto fb_fd = card.handleFD(fb->handles[i]);
if (fb_fd.el < 0) {
BOOST_LOG(error) << "Couldn't get primary file descriptor for Framebuffer ["sv << fb->fb_id << "]: "sv << strerror(errno);
continue;
}
}
auto crtc = card.crtc(plane->crtc_id);
if (!crtc) {
BOOST_LOG(error) << "Couldn't get CRTC info: "sv << strerror(errno);
continue;
}
BOOST_LOG(info) << "Found monitor for DRM screencasting"sv;
// We need to find the correct /dev/dri/card{nr} to correlate the crtc_id with the monitor descriptor
auto pos = std::find_if(std::begin(card_descriptors), std::end(card_descriptors), [&](card_descriptor_t &cd) {
return cd.path == filestring;
});
if (pos == std::end(card_descriptors)) {
// This code path shouldn't happen, but it's there just in case.
// card_descriptors is part of the guesswork after all.
BOOST_LOG(error) << "Couldn't find ["sv << entry.path() << "]: This shouldn't have happened :/"sv;
return -1;
}
// TODO: surf_sd = fb->to_sd();
kms::print(plane.get(), fb.get(), crtc.get());
img_width = fb->width;
img_height = fb->height;
img_offset_x = crtc->x;
img_offset_y = crtc->y;
this->env_offset_x = ::platf::kms::env_bounds.offset_x;
this->env_offset_y = ::platf::kms::env_bounds.offset_y;
this->env_width = ::platf::kms::env_bounds.width;
this->env_height = ::platf::kms::env_bounds.height;
this->env_logical_width = ::platf::kms::env_bounds.logical_width;
this->env_logical_height = ::platf::kms::env_bounds.logical_height;
auto monitor_pos = pos->crtc_to_monitor.find(plane->crtc_id);
if (monitor_pos != std::end(pos->crtc_to_monitor)) {
auto &viewport = monitor_pos->second.viewport;
width = viewport.width;
height = viewport.height;
logical_width = viewport.logical_width;
logical_height = viewport.logical_height;
switch (card.get_panel_orientation(plane->plane_id)) {
case DRM_MODE_ROTATE_270:
BOOST_LOG(debug) << "Detected panel orientation at 90, swapping width and height.";
width = viewport.height;
height = viewport.width;
break;
case DRM_MODE_ROTATE_90:
case DRM_MODE_ROTATE_180:
BOOST_LOG(warning) << "Panel orientation is unsupported, screen capture may not work correctly.";
break;
}
offset_x = viewport.offset_x;
offset_y = viewport.offset_y;
output_name = viewport.output_name;
}
// This code path shouldn't happen, but it's there just in case.
// crtc_to_monitor is part of the guesswork after all.
else {
BOOST_LOG(warning) << "Couldn't find crtc_id, this shouldn't have happened :\\"sv;
width = crtc->width;
height = crtc->height;
offset_x = crtc->x;
offset_y = crtc->y;
}
plane_id = plane->plane_id;
crtc_id = plane->crtc_id;
crtc_index = card.get_crtc_index_by_id(plane->crtc_id);
// Find the connector for this CRTC
kms::conn_type_count_t conn_type_count;
for (auto &connector : card.monitors(conn_type_count)) {
if (connector.crtc_id == crtc_id) {
BOOST_LOG(info) << "Found connector ID ["sv << connector.connector_id << ']';
connector_id = connector.connector_id;
auto connector_props = card.connector_props(*connector_id);
hdr_metadata_blob_id = card.prop_value_by_name(connector_props, "HDR_OUTPUT_METADATA"sv);
}
}
this->card = std::move(card);
goto break_loop;
for (int i = 0; i < 4 && fb->handles[i]; ++i) {
auto fb_fd = card.handleFD(fb->handles[i]);
if (fb_fd.el < 0) {
BOOST_LOG(error) << "Couldn't get primary file descriptor for Framebuffer ["sv << fb->fb_id << "]: "sv << strerror(errno);
}
}
BOOST_LOG(error) << "Couldn't find monitor ["sv << monitor_index << ']';
return -1;
auto crtc = card.crtc(plane->crtc_id);
if (!crtc) {
BOOST_LOG(error) << "Couldn't get CRTC info: "sv << strerror(errno);
return -1;
}
// Neatly break from nested for loop
break_loop:
BOOST_LOG(info) << "Found monitor for DRM screencasting: "sv << output.name;
kms::print(plane.get(), fb.get(), crtc.get());
img_width = fb->width;
img_height = fb->height;
img_offset_x = crtc->x;
img_offset_y = crtc->y;
enumeration.desktop.apply(*this);
const auto &viewport = descriptor.crtc_to_monitor.at(plane->crtc_id).viewport;
width = viewport.width;
height = viewport.height;
logical_width = viewport.logical_width;
logical_height = viewport.logical_height;
switch (card.get_panel_orientation(plane->plane_id)) {
case DRM_MODE_ROTATE_270:
BOOST_LOG(debug) << "Detected panel orientation at 90, swapping width and height.";
width = viewport.height;
height = viewport.width;
break;
case DRM_MODE_ROTATE_90:
case DRM_MODE_ROTATE_180:
BOOST_LOG(warning) << "Panel orientation is unsupported, screen capture may not work correctly.";
break;
}
offset_x = viewport.offset_x;
offset_y = viewport.offset_y;
output_name = viewport.output_name;
plane_id = plane->plane_id;
crtc_id = plane->crtc_id;
crtc_index = card.get_crtc_index_by_id(plane->crtc_id);
// Find the connector for this CRTC
kms::conn_type_count_t conn_type_count;
for (auto &connector : card.monitors(conn_type_count)) {
if (connector.crtc_id == crtc_id) {
BOOST_LOG(info) << "Found connector ID ["sv << connector.connector_id << ']';
connector_id = connector.connector_id;
auto connector_props = card.connector_props(*connector_id);
hdr_metadata_blob_id = card.prop_value_by_name(connector_props, "HDR_OUTPUT_METADATA"sv);
}
}
// Look for the cursor plane for this CRTC
cursor_plane_id = -1;
auto end = std::end(card);
for (auto plane = std::begin(card); plane != end; ++plane) {
if (!card.is_cursor(plane->plane_id)) {
for (auto cursor_plane = std::begin(card); cursor_plane != end; ++cursor_plane) {
if (!card.is_cursor(cursor_plane->plane_id)) {
continue;
}
// NB: We do not skip unused planes here because cursor planes
// will look unused if the cursor is currently hidden.
if (!(plane->possible_crtcs & (1 << crtc_index))) {
if (!(cursor_plane->possible_crtcs & (1 << crtc_index))) {
// Skip cursor planes for other CRTCs
continue;
} else if (plane->possible_crtcs != (1 << crtc_index)) {
} else if (cursor_plane->possible_crtcs != (1 << crtc_index)) {
// We assume a 1:1 mapping between cursor planes and CRTCs, which seems to
// match the behavior of drivers in the real world. If it's violated, we'll
// proceed anyway but print a warning in the log.
BOOST_LOG(warning) << "Cursor plane spans multiple CRTCs!"sv;
}
BOOST_LOG(info) << "Found cursor plane ["sv << plane->plane_id << ']';
cursor_plane_id = plane->plane_id;
BOOST_LOG(info) << "Found cursor plane ["sv << cursor_plane->plane_id << ']';
cursor_plane_id = cursor_plane->plane_id;
break;
}
@@ -1760,15 +1629,16 @@ namespace platf {
*
* @param display_name Display name.
* @param config Configuration values to apply.
* @param enumeration Displays and geometry for this capture backend.
* @return 0 on success; nonzero or negative platform status on failure.
*/
int init(const std::string &display_name, const ::video::config_t &config) {
int init(const std::string &display_name, const ::video::config_t &config, const display_enumeration_t &enumeration) {
if (!gbm::create_device) {
BOOST_LOG(warning) << "libgbm not initialized"sv;
return -1;
}
if (display_t::init(display_name, config)) {
if (display_t::init(display_name, config, enumeration)) {
return -1;
}
@@ -2169,10 +2039,11 @@ namespace platf {
*
* @param display_name Display name.
* @param config Configuration values to apply.
* @param enumeration Displays and geometry for this capture backend.
* @return 0 on success; nonzero or negative platform status on failure.
*/
int init(const std::string &display_name, const ::video::config_t &config) {
if (display_t::init(display_name, config)) {
int init(const std::string &display_name, const ::video::config_t &config, const display_enumeration_t &enumeration) {
if (display_t::init(display_name, config, enumeration)) {
return -1;
}
@@ -2198,34 +2069,6 @@ namespace platf {
} // namespace kms
/**
* @brief Create a KMS display capture backend.
*
* @param hwdevice_type Hardware device type requested for capture or encode.
* @param display_name Display name.
* @param config Configuration values to apply.
* @return KMS display backend, or nullptr when initialization fails.
*/
std::shared_ptr<display_t> kms_display(mem_type_e hwdevice_type, const std::string &display_name, const ::video::config_t &config) {
if (hwdevice_type == mem_type_e::vaapi || hwdevice_type == mem_type_e::cuda || hwdevice_type == mem_type_e::vulkan) {
auto disp = std::make_shared<kms::display_vram_t>(hwdevice_type);
if (!disp->init(display_name, config)) {
return disp;
}
// In the case of failure, attempt the old method for VAAPI
}
auto disp = std::make_shared<kms::display_ram_t>(hwdevice_type);
if (disp->init(display_name, config)) {
return nullptr;
}
return disp;
}
/**
* On Wayland, it's not possible to determine the position of the monitor on the desktop with KMS.
* Wayland does allow applications to query attached monitors on the desktop,
@@ -2293,16 +2136,13 @@ namespace platf {
BOOST_LOG(info) << "--------- End of KMS monitor list ---------"sv;
}
// A list of names of displays accepted as display_name
/**
* @brief Enumerate display names accepted by the KMS backend.
* @brief Enumerate the displays, planes, and geometry available to one KMS backend.
*
* @param hwdevice_type Hardware device type requested for capture or encode.
* @return KMS display names, or an empty list when KMS capture is unavailable.
* @return An independent snapshot of the available KMS displays.
*/
std::vector<std::string> kms_display_names(mem_type_e hwdevice_type) {
int count = 0;
static kms::display_enumeration_t enumerate_kms_displays(mem_type_e hwdevice_type) {
if (!fs::exists("/dev/dri")) {
BOOST_LOG(warning) << "Couldn't find /dev/dri, kmsgrab won't be enabled"sv;
return {};
@@ -2315,8 +2155,7 @@ namespace platf {
kms::conn_type_count_t conn_type_count;
std::vector<kms::card_descriptor_t> cds;
std::vector<std::string> display_names;
kms::display_enumeration_t enumeration;
fs::path card_dir {"/dev/dri"sv};
for (auto &entry : fs::directory_iterator {card_dir}) {
@@ -2387,45 +2226,76 @@ namespace platf {
}
auto it = crtc_to_monitor.find(plane->crtc_id);
if (it != std::end(crtc_to_monitor)) {
it->second.viewport = platf::touch_port_t {
.offset_x = (int) crtc->x,
.offset_y = (int) crtc->y,
.width = (int) crtc->width,
.height = (int) crtc->height,
};
it->second.monitor_index = count;
if (it == crtc_to_monitor.end()) {
continue;
}
const auto output_name = std::format("{}-{}", drmModeGetConnectorTypeName(it->second.type), it->second.index);
it->second.viewport = platf::touch_port_t {
.offset_x = (int) crtc->x,
.offset_y = (int) crtc->y,
.width = (int) crtc->width,
.height = (int) crtc->height,
.output_name = output_name,
};
it->second.monitor_index = enumeration.outputs.size();
kms::print(plane.get(), fb.get(), crtc.get());
it->second.viewport.output_name = std::format("{}-{}", drmModeGetConnectorTypeName(it->second.type), it->second.index);
display_names.emplace_back(it->second.viewport.output_name);
count++;
enumeration.outputs.emplace_back(output_name, enumeration.cards.size(), plane->plane_id, plane->crtc_id);
}
cds.emplace_back(kms::card_descriptor_t {
std::move(file),
std::move(crtc_to_monitor),
});
enumeration.cards.emplace_back(entry.path().string(), std::move(crtc_to_monitor));
}
if (!wl::init()) {
correlate_to_wayland(cds);
correlate_to_wayland(enumeration.cards);
}
platf::desktop_geometry_t desktop;
for (const auto &card_descriptor : cds) {
for (const auto &card_descriptor : enumeration.cards) {
for (const auto &[_, monitor_descriptor] : card_descriptor.crtc_to_monitor) {
desktop.add(monitor_descriptor.viewport);
enumeration.desktop.add(monitor_descriptor.viewport);
}
}
kms::env_bounds = desktop.bounds();
BOOST_LOG(debug) << "Desktop resolution: "sv << kms::env_bounds.width << 'x' << kms::env_bounds.height;
const auto &bounds = enumeration.desktop.bounds();
BOOST_LOG(debug) << "Desktop resolution: "sv << bounds.width << 'x' << bounds.height;
kms::card_descriptors = std::move(cds);
return enumeration;
}
/**
* @brief Enumerate display names accepted by the KMS backend.
*
* @param hwdevice_type Hardware device type requested for capture or encode.
* @return KMS display names, or an empty list when KMS capture is unavailable.
*/
std::vector<std::string> kms_display_names(mem_type_e hwdevice_type) {
auto enumeration = enumerate_kms_displays(hwdevice_type);
auto display_names = enumeration.outputs | std::views::transform(&kms::output_t::name) | std::ranges::to<std::vector>();
BOOST_LOG(debug) << "Final KMS display_names return list: " << (display_names | std::views::join_with(' ') | std::ranges::to<std::string>());
return display_names;
}
/**
* @brief Create a KMS capture display from its own enumeration of the available outputs.
*
* @param hwdevice_type Hardware device type requested for capture or encode.
* @param display_name Display name.
* @param config Configuration values to apply.
* @return KMS display backend, or nullptr when initialization fails.
*/
std::shared_ptr<display_t> kms_display(mem_type_e hwdevice_type, const std::string &display_name, const ::video::config_t &config) {
const auto enumeration = enumerate_kms_displays(hwdevice_type);
if (hwdevice_type == mem_type_e::vaapi || hwdevice_type == mem_type_e::cuda || hwdevice_type == mem_type_e::vulkan) {
auto disp = std::make_shared<kms::display_vram_t>(hwdevice_type);
if (!disp->init(display_name, config, enumeration)) {
return disp;
}
}
auto disp = std::make_shared<kms::display_ram_t>(hwdevice_type);
if (disp->init(display_name, config, enumeration)) {
return nullptr;
}
return disp;
}
} // namespace platf
+41 -9
View File
@@ -28,6 +28,7 @@ extern "C" {
#include "input.h"
#include "logging.h"
#include "network.h"
#include "nvhttp.h"
#include "rtsp.h"
#include "stream.h"
#include "sync.h"
@@ -41,6 +42,23 @@ using asio::ip::udp;
using namespace std::literals;
namespace rtsp_stream {
std::string describe_video_codecs(uint32_t codec_modes) {
std::string result;
if (codec_modes & SCM_MASK_HEVC) {
result += "sprop-parameter-sets=AAAAAU\r\n";
}
if (codec_modes & SCM_MASK_AV1) {
result += "a=rtpmap:98 AV1/90000\r\n";
}
if (codec_modes & SCM_MPEG2) {
result += "a=rtpmap:98 MPV/90000\r\n";
}
if (codec_modes & SCM_H263P) {
result += "a=rtpmap:98 H263-1998/90000\r\n";
}
return result;
}
/**
* @brief Release msg resources.
*
@@ -902,13 +920,7 @@ namespace rtsp_stream {
ss << "a=x-nv-video[0].refPicInvalidation:1"sv << std::endl;
}
if (video::active_hevc_mode != 1) {
ss << "sprop-parameter-sets=AAAAAU"sv << std::endl;
}
if (video::active_av1_mode != 1) {
ss << "a=rtpmap:98 AV1/90000"sv << std::endl;
}
ss << describe_video_codecs(nvhttp::get_codec_mode_flags());
if (!session.surround_params.empty()) {
// If we have our own surround parameters, advertise them twice first
@@ -1230,20 +1242,40 @@ namespace rtsp_stream {
config.monitor.bitrate = (int) configuredBitrateKbps;
}
if (config.monitor.videoFormat == 1 && video::active_hevc_mode == 1) {
if (config.monitor.videoFormat == video::format_hevc && video::active_hevc_mode == 1) {
BOOST_LOG(warning) << "HEVC is disabled, yet the client requested HEVC"sv;
respond(sock, session, &option, 400, "BAD REQUEST", req->sequenceNumber, {});
return;
}
if (config.monitor.videoFormat == 2 && video::active_av1_mode == 1) {
if (config.monitor.videoFormat == video::format_av1 && video::active_av1_mode == 1) {
BOOST_LOG(warning) << "AV1 is disabled, yet the client requested AV1"sv;
respond(sock, session, &option, 400, "BAD REQUEST", req->sequenceNumber, {});
return;
}
if (config.monitor.videoFormat == video::format_mpeg2 && video::probed_codec_modes().mpeg2 < 2) {
BOOST_LOG(warning) << "MPEG-2 is disabled, yet the client requested MPEG-2"sv;
respond(sock, session, &option, 400, "BAD REQUEST", req->sequenceNumber, {});
return;
}
if (config.monitor.videoFormat == video::format_h263p && video::probed_codec_modes().h263p != 2) {
BOOST_LOG(warning) << "H.263+ is disabled, yet the client requested H.263+"sv;
respond(sock, session, &option, 400, "BAD REQUEST", req->sequenceNumber, {});
return;
}
if (config.monitor.videoFormat == video::format_h263p && (config.monitor.width <= 0 || config.monitor.height <= 0 || config.monitor.width % 4 != 0 || config.monitor.height % 4 != 0)) {
BOOST_LOG(warning) << "H.263+ requires a positive width and height divisible by four"sv;
respond(sock, session, &option, 400, "BAD REQUEST", req->sequenceNumber, {});
return;
}
// Check that any required encryption is enabled
auto encryption_mode = net::encryption_mode_for_address(sock.remote_endpoint().address());
if (encryption_mode == config::ENCRYPTION_MODE_MANDATORY && (config.encryptionFlagsEnabled & (SS_ENC_VIDEO | SS_ENC_AUDIO)) != (SS_ENC_VIDEO | SS_ENC_AUDIO)) {
+9
View File
@@ -9,12 +9,21 @@
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <string>
// local includes
#include "crypto.h"
#include "thread_safe.h"
namespace rtsp_stream {
/**
* @brief Describe the codecs advertised by a host, independently of client identity.
*
* @param codec_modes Validated ServerCodecModeSupport capability bits.
* @return GameStream DESCRIBE codec attributes; these do not change RTP packetization.
*/
std::string describe_video_codecs(uint32_t codec_modes);
constexpr auto RTSP_SETUP_PORT = 21; ///< GameStream base-port offset used for the RTSP setup listener.
#pragma pack(push, 1)
+6 -4
View File
@@ -10,6 +10,7 @@
#include <condition_variable>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <vector>
@@ -699,14 +700,15 @@ namespace safe {
/**
* @brief Return a shared reference to the protected object.
*
* @return Reference handle that keeps the protected object alive.
* @return Reference handle that keeps the protected object alive, or an empty handle after failed initialization.
*/
[[nodiscard]] ptr_t ref() {
std::lock_guard lg {_lock};
if (!_count) {
new (_object_buf.data()) element_type;
if (_construct(*reinterpret_cast<element_type *>(_object_buf.data())) != 0) {
auto *object = new (_object_buf.data()) element_type;
if (_construct(*object) != 0) {
std::destroy_at(object);
return ptr_t {nullptr};
}
}
@@ -722,7 +724,7 @@ namespace safe {
std::array<std::uint8_t, sizeof(element_type)> _object_buf;
std::uint32_t _count;
std::uint32_t _count = 0; ///< Number of active references, including dynamically allocated storage.
std::mutex _lock;
};
+429 -134
View File
@@ -36,6 +36,7 @@ extern "C" {
#include "platform/common.h"
#include "sync.h"
#include "video.h"
#include "video_capture_groups.h"
#ifdef _WIN32
extern "C" {
@@ -76,6 +77,18 @@ namespace video {
#endif
}
namespace {
/**
* @brief Identify the legacy video formats supported for compatibility clients.
*
* @param video_format Requested GameStream video codec identifier.
* @return Whether the format is MPEG-2 or H.263+.
*/
bool is_legacy_video_format(int video_format) {
return video_format == format_mpeg2 || video_format == format_h263p;
}
} // namespace
/**
* @brief Release context resources.
*/
@@ -698,6 +711,7 @@ namespace video {
safe::mail_raw_t::event_t<input::touch_port_t> touch_port_events; ///< Event carrying updated touch viewport metadata.
config_t config; ///< Stream or encoder configuration captured for the worker.
const encoder_t *encoder_p; ///< Encoder selected for this stream's video format.
int frame_nr; ///< Next capture-frame number assigned to encoded packets.
stream::session_t *channel_data; ///< Stream session forwarded to packet senders.
};
@@ -725,6 +739,7 @@ namespace video {
struct capture_ctx_t {
img_event_t images; ///< Queue of captured images waiting for encode.
config_t config; ///< Stream or encoder configuration captured for the worker.
const encoder_t *encoder_p; ///< Encoder selected for this stream's video format.
};
/**
@@ -735,7 +750,6 @@ namespace video {
std::jthread capture_thread; ///< Capture thread.
safe::signal_t reinit_event; ///< Reinit event.
const encoder_t *encoder_p; ///< Encoder p.
sync_util::sync_t<std::weak_ptr<platf::display_t>> display_wp; ///< Display wp.
};
@@ -744,21 +758,11 @@ namespace video {
*/
struct capture_thread_sync_ctx_t {
encode_session_ctx_queue_t encode_session_ctx_queue {30}; ///< Encode session ctx queue.
std::jthread capture_thread; ///< Worker owned by this encoder's capture group.
};
/**
* @brief Start the synchronous multi-client capture thread.
*
* @param ctx Unused state required by the shared capture lifetime callback signature.
* @return 0 when the capture thread is started.
*/
int start_capture_sync(capture_thread_sync_ctx_t &ctx);
/**
* @brief Leave synchronous capture cleanup to the capture thread.
*
* @param ctx Unused state required by the shared capture lifetime callback signature.
*/
void end_capture_sync(capture_thread_sync_ctx_t &ctx);
int start_capture_sync(capture_thread_sync_ctx_t &context);
void end_capture_sync(capture_thread_sync_ctx_t &context);
/**
* @brief Start the asynchronous capture thread.
*
@@ -773,9 +777,45 @@ namespace video {
*/
void end_capture_async(capture_thread_async_ctx_t &ctx);
// Keep a reference counter to ensure the capture thread only runs when other threads have a reference to the capture thread
auto capture_thread_async = safe::make_shared<capture_thread_async_ctx_t>(start_capture_async, end_capture_async); ///< Capture thread async.
auto capture_thread_sync = safe::make_shared<capture_thread_sync_ctx_t>(start_capture_sync, end_capture_sync); ///< Capture thread sync.
namespace {
/**
* @brief Access the monitor switch requests shared by the capture workers.
*
* @return Monitor switch state for active capture groups.
*/
display_switch_state_t &capture_display_switches() {
static display_switch_state_t switches;
return switches;
}
/**
* @brief Access the pool whose references keep each encoder's capture worker alive.
*
* @tparam Context Capture worker context.
* @tparam Start Callback starting one worker.
* @tparam Stop Callback stopping one worker.
* @return Pool of capture workers for the specified context type.
*/
template<class Context, int (*Start)(Context &), void (*Stop)(Context &)>
capture_group_pool_t<Context> &capture_groups() {
auto &switches = capture_display_switches();
static capture_group_pool_t<Context> groups {
[&switches](Context &context) {
switches.start_worker();
const auto status = Start(context);
if (status != 0) {
switches.stop_worker();
}
return status;
},
[&switches](Context &context) {
Stop(context);
switches.stop_worker();
},
};
return groups;
}
} // namespace
#ifdef _WIN32
/**
@@ -820,6 +860,8 @@ namespace video {
"h264_nvenc"s,
{}, // capabilities
},
{}, // MPEG-2
{}, // H.263+
PARALLEL_ENCODING | REF_FRAMES_INVALIDATION | YUV444_SUPPORT | ASYNC_TEARDOWN // flags
};
#elif !defined(__APPLE__)
@@ -922,6 +964,8 @@ namespace video {
"h264_nvenc"s,
{}, // capabilities
},
{}, // MPEG-2
{}, // H.263+
PARALLEL_ENCODING | YUV444_SUPPORT
};
#endif
@@ -1038,6 +1082,27 @@ namespace video {
"h264_qsv"s,
{}, // capabilities
},
{
// Common options
{
{"preset"s, &config::video.qsv.qsv_preset},
{"forced_idr"s, 1},
{"async_depth"s, 1},
{"low_delay_brc"s, 1},
{"low_power"s, 1},
},
{}, // SDR-specific options
{}, // HDR-specific options
{}, // YUV444 SDR-specific options
{}, // YUV444 HDR-specific options
{
// Fallback options
{"low_power"s, 0},
},
"mpeg2_qsv"s,
{}, // capabilities
},
{}, // H.263+
PARALLEL_ENCODING | CBR_WITH_VBR | RELAXED_COMPLIANCE | NO_RC_BUF_LIMIT | YUV444_SUPPORT
};
@@ -1152,6 +1217,8 @@ namespace video {
"h264_amf"s,
{}, // capabilities
},
{}, // MPEG-2
{}, // H.263+
PARALLEL_ENCODING
};
@@ -1215,6 +1282,8 @@ namespace video {
"h264_mf"s,
{}, // capabilities
},
{}, // MPEG-2
{}, // H.263+
PARALLEL_ENCODING | FIXED_GOP_SIZE // MF encoder doesn't support on-demand IDR frames
};
#endif
@@ -1292,6 +1361,32 @@ namespace video {
"libx264"s,
{}, // capabilities
},
{
{
// Required when AV_CODEC_FLAG_CLOSED_GOP is set.
{"sc_threshold"s, 1000000000},
},
{}, // SDR-specific options
{}, // HDR-specific options
{}, // YUV444 SDR-specific options
{}, // YUV444 HDR-specific options
{}, // Fallback options
"mpeg2video"s,
{}, // capabilities
},
{
{
// Required when AV_CODEC_FLAG_CLOSED_GOP is set.
{"sc_threshold"s, 1000000000},
},
{}, // SDR-specific options
{}, // HDR-specific options
{}, // YUV444 SDR-specific options
{}, // YUV444 HDR-specific options
{}, // Fallback options
"h263p"s,
{}, // capabilities
},
H264_ONLY | PARALLEL_ENCODING | ALWAYS_REPROBE | YUV444_SUPPORT
};
@@ -1358,6 +1453,20 @@ namespace video {
"h264_vaapi"s,
{}, // capabilities
},
encoder_t::codec_t {
.common_options = {
{"async_depth"s, 1},
{"idr_interval"s, std::numeric_limits<int>::max()},
},
.sdr_options = {},
.hdr_options = {},
.sdr444_options = {},
.hdr444_options = {},
.fallback_options = {},
.name = "mpeg2_vaapi"s,
.capabilities = {},
},
{}, // H.263+
// RC buffer size will be set in platform code if supported
LIMITED_GOP_SIZE | PARALLEL_ENCODING | NO_RC_BUF_LIMIT
};
@@ -1432,6 +1541,8 @@ namespace video {
"h264_vulkan"s,
{}, // capabilities
},
{}, // MPEG-2
{}, // H.263+
LIMITED_GOP_SIZE | PARALLEL_ENCODING
};
#endif // SUNSHINE_BUILD_VULKAN
@@ -1483,6 +1594,8 @@ namespace video {
"h264_vt"s,
{}, // capabilities
},
{}, // MPEG-2
{}, // H.263+
PARALLEL_ENCODING
};
#endif
@@ -1509,6 +1622,31 @@ namespace video {
};
static encoder_t *chosen_encoder;
namespace {
/**
* @brief Track the selected backend and advertised modes from encoder probing.
*/
struct encoder_probe_state_t {
std::array<encoder_t *, VIDEO_FORMAT_COUNT> encoders_by_format {}; ///< Backend selected for each wire codec.
probed_codec_modes_t modes; ///< Baseline and legacy codec modes from the probe.
};
/**
* @brief Access the state refreshed by encoder probing.
*
* @return Selected encoder backends and codec modes.
*/
encoder_probe_state_t &encoder_probe_state() {
static encoder_probe_state_t state;
return state;
}
} // namespace
probed_codec_modes_t &probed_codec_modes() {
return encoder_probe_state().modes;
}
int active_hevc_mode; ///< HEVC mode selected by the most recent encoder probe.
int active_av1_mode; ///< AV1 mode selected by the most recent encoder probe.
bool last_encoder_probe_supported_ref_frames_invalidation = false; ///< Whether the last probe found reference-frame invalidation support.
@@ -1516,6 +1654,43 @@ namespace video {
std::array<bool, 3> last_encoder_probe_supported_dynamic_range_for_codec = {}; ///< 10-bit 4:2:0 support discovered for each probed codec.
std::array<bool, 3> last_encoder_probe_supported_dynamic_range_yuv444_for_codec = {}; ///< 10-bit YUV444 support discovered for each probed codec.
/**
* @brief Check whether an encoder passed validation for a requested video format.
*
* @param encoder Encoder whose codec capabilities should be checked.
* @param video_format Requested GameStream video codec identifier.
* @return Whether the encoder supports the requested video format.
*/
bool encoder_supports_video_format(const encoder_t &encoder, int video_format) {
switch (video_format) {
case format_mpeg2:
return encoder.mpeg2[encoder_t::PASSED];
case format_h263p:
return encoder.h263p[encoder_t::PASSED];
case format_h264:
return encoder.h264[encoder_t::PASSED];
case format_hevc:
return encoder.hevc[encoder_t::PASSED];
case format_av1:
return encoder.av1[encoder_t::PASSED];
default:
return false;
}
}
/**
* @brief Select the encoder for a modern or legacy video stream.
*
* @param config Video configuration requested by the client.
* @return Selected encoder, or nullptr when encoder probing found no suitable backend.
*/
encoder_t *encoder_for_config(const config_t &config) {
if (config.videoFormat < 0 || config.videoFormat >= VIDEO_FORMAT_COUNT) {
return nullptr;
}
return encoder_probe_state().encoders_by_format[config.videoFormat];
}
/**
* @brief Recreate a display capture object after a capture failure.
*
@@ -1599,13 +1774,11 @@ namespace video {
* @param capture_ctx_queue Capture context queue.
* @param display_wp Weak pointer holder for the active display.
* @param reinit_event Signal raised while the display is being reinitialized.
* @param encoder Selected encoder.
*/
void captureThread(
std::shared_ptr<safe::queue_t<capture_ctx_t>> capture_ctx_queue,
sync_util::sync_t<std::weak_ptr<platf::display_t>> &display_wp,
safe::signal_t &reinit_event,
const encoder_t &encoder
safe::signal_t &reinit_event
) {
std::vector<capture_ctx_t> capture_ctxs;
@@ -1622,6 +1795,7 @@ namespace video {
});
auto switch_display_event = mail::man->event<int>(mail::switch_display);
std::uint64_t applied_display_generation = 0;
// Wait for the initial capture context or a request to stop the queue
auto initial_capture_ctx = capture_ctx_queue->pop();
@@ -1629,12 +1803,14 @@ namespace video {
return;
}
capture_ctxs.emplace_back(std::move(*initial_capture_ctx));
const auto &encoder = *capture_ctxs.front().encoder_p;
// Get all the monitor names now, rather than at boot, to
// get the most up-to-date list available monitors
std::vector<std::string> display_names;
int display_p = -1;
refresh_displays(encoder.platform_formats->dev_type, display_names, display_p);
capture_display_switches().poll(switch_display_event).apply(display_p, display_names.size(), applied_display_generation);
auto disp = platf::display(encoder.platform_formats->dev_type, display_names[display_p], capture_ctxs.front().config);
if (!disp) {
return;
@@ -1745,7 +1921,7 @@ namespace video {
while (capture_ctx_queue->running()) {
bool artificial_reinit = false;
auto push_captured_image_callback = [&capture_ctxs, &capture_ctx_queue, &switch_display_event, &artificial_reinit](std::shared_ptr<platf::img_t> &&img, bool frame_captured) {
auto push_captured_image_callback = [&capture_ctxs, &capture_ctx_queue, &switch_display_event, &applied_display_generation, &artificial_reinit](std::shared_ptr<platf::img_t> &&img, bool frame_captured) {
KITTY_WHILE_LOOP(auto capture_ctx = std::begin(capture_ctxs), capture_ctx != std::end(capture_ctxs), {
if (!capture_ctx->images->running()) {
capture_ctx = capture_ctxs.erase(capture_ctx);
@@ -1768,7 +1944,7 @@ namespace video {
capture_ctxs.emplace_back(std::move(*capture_ctx_queue->pop()));
}
if (switch_display_event->peek()) {
if (capture_display_switches().poll(switch_display_event).generation != applied_display_generation) {
artificial_reinit = true;
return false;
}
@@ -1826,9 +2002,7 @@ namespace video {
refresh_displays(encoder.platform_formats->dev_type, display_names, display_p);
// Process any pending display switch with the new list of displays
if (switch_display_event->peek()) {
display_p = std::clamp(*switch_display_event->pop(), 0, static_cast<int>(display_names.size()) - 1);
}
capture_display_switches().poll(switch_display_event).apply(display_p, display_names.size(), applied_display_generation);
// reset_display() will sleep between retries
reset_display(disp, encoder.platform_formats->dev_type, display_names[display_p], capture_ctxs.front().config);
@@ -2074,7 +2248,7 @@ namespace video {
bool hardware = platform_formats->avcodec_base_dev_type != AV_HWDEVICE_TYPE_NONE;
auto &video_format = encoder.codec_from_config(config);
if (!video_format[encoder_t::PASSED] || !disp->is_codec_supported(video_format.name, config)) {
if (video_format.name.empty() || !video_format[encoder_t::PASSED] || !disp->is_codec_supported(video_format.name, config)) {
BOOST_LOG(error) << encoder.name << ": "sv << video_format.name << " mode not supported"sv;
return nullptr;
}
@@ -2110,6 +2284,9 @@ namespace video {
(colorspace.bit_depth == 10 && config.chromaSamplingType == 0) ? platform_formats->avcodec_pix_fmt_10bit :
(colorspace.bit_depth == 10 && config.chromaSamplingType == 1) ? platform_formats->avcodec_pix_fmt_yuv444_10bit :
AV_PIX_FMT_NONE;
if (!hardware && is_legacy_video_format(config.videoFormat)) {
sw_fmt = AV_PIX_FMT_YUV420P;
}
// Allow up to 1 retry to apply the set of fallback options.
//
@@ -2126,13 +2303,13 @@ namespace video {
ctx->time_base = AVRational {fps.den, fps.num};
switch (config.videoFormat) {
case 0:
case format_h264:
// 10-bit h264 encoding is not supported by our streaming protocol
assert(!config.dynamicRange);
ctx->profile = select_h264_profile(video_format.name, config, config::video.amd.amd_coder);
break;
case 1:
case format_hevc:
if (config.chromaSamplingType == 1) {
// HEVC uses the same RExt profile for both 8 and 10 bit YUV 4:4:4 encoding
ctx->profile = AV_PROFILE_HEVC_REXT;
@@ -2141,23 +2318,33 @@ namespace video {
}
break;
case 2:
case format_av1:
// AV1 supports both 8 and 10 bit encoding with the same Main profile
// but YUV 4:4:4 sampling requires High profile
ctx->profile = (config.chromaSamplingType == 1) ? AV_PROFILE_AV1_HIGH : AV_PROFILE_AV1_MAIN;
break;
case format_mpeg2:
ctx->profile = AV_PROFILE_MPEG2_MAIN;
break;
case format_h263p:
break;
}
// B-frames delay decoder output, so never use them
ctx->max_b_frames = 0;
// Use an infinite GOP length since I-frames are generated on demand
// Exception: encoders with FIXED_GOP_SIZE flag don't support on-demand IDR
if (encoder.flags & FIXED_GOP_SIZE) {
// Fixed GOP for encoders that don't support on-demand IDR (e.g. Media Foundation)
if (is_legacy_video_format(config.videoFormat)) {
// FFmpeg's legacy encoders reject the infinite GOP value used by modern codecs.
ctx->gop_size = 600;
ctx->keyint_min = 1;
} else if (encoder.flags & FIXED_GOP_SIZE) {
// Fixed GOP for encoders that don't support on-demand IDR (e.g. Media Foundation).
ctx->gop_size = 120; // ~2 seconds at 60 FPS - larger to reduce oversized IDR frame frequency
ctx->keyint_min = 120;
} else {
// Use an infinite GOP length since I-frames are generated on demand.
ctx->gop_size = encoder.flags & LIMITED_GOP_SIZE ?
std::numeric_limits<std::int16_t>::max() :
std::numeric_limits<int>::max();
@@ -2323,12 +2510,14 @@ namespace video {
ctx->rc_min_rate = bitrate;
}
if (encoder.flags & RELAXED_COMPLIANCE) {
if ((encoder.flags & RELAXED_COMPLIANCE) || config.videoFormat == format_h263p) {
ctx->strict_std_compliance = FF_COMPLIANCE_UNOFFICIAL;
}
if (!(encoder.flags & NO_RC_BUF_LIMIT)) {
if (!hardware && (ctx->slices > 1 || config.videoFormat == 1)) {
if (is_legacy_video_format(config.videoFormat)) {
ctx->rc_buffer_size = bitrate;
} else if (!hardware && (ctx->slices > 1 || config.videoFormat == format_hevc)) {
// Use a larger rc_buffer_size for software encoding when slices are enabled,
// because libx264 can severely degrade quality if the buffer is too small.
// libx265 encounters this issue more frequently, so always scale the
@@ -2789,16 +2978,16 @@ namespace video {
* @param encode_session_ctx_queue Pending synchronized session context queue.
* @param display_names Cached display names.
* @param display_p Active display index.
* @param applied_display_generation Last monitor switch applied by this worker.
* @return Encoder loop result.
*/
encode_e encode_run_sync(
std::vector<std::unique_ptr<sync_session_ctx_t>> &synced_session_ctxs,
encode_session_ctx_queue_t &encode_session_ctx_queue,
std::vector<std::string> &display_names,
int &display_p
int &display_p,
std::uint64_t &applied_display_generation
) {
const auto &encoder = *chosen_encoder;
std::shared_ptr<platf::display_t> disp;
auto switch_display_event = mail::man->event<int>(mail::switch_display);
@@ -2812,14 +3001,14 @@ namespace video {
synced_session_ctxs.emplace_back(std::make_unique<sync_session_ctx_t>(std::move(*ctx)));
}
const auto &encoder = *synced_session_ctxs.front()->encoder_p;
while (encode_session_ctx_queue.running()) {
// Refresh display names since a display removal might have caused the reinitialization
refresh_displays(encoder.platform_formats->dev_type, display_names, display_p);
// Process any pending display switch with the new list of displays
if (switch_display_event->peek()) {
display_p = std::clamp(*switch_display_event->pop(), 0, static_cast<int>(display_names.size()) - 1);
}
capture_display_switches().poll(switch_display_event).apply(display_p, display_names.size(), applied_display_generation);
// reset_display() will sleep between retries
reset_display(disp, encoder.platform_formats->dev_type, display_names[display_p], synced_session_ctxs.front()->config);
@@ -2914,7 +3103,7 @@ namespace video {
++pos;
})
if (switch_display_event->peek()) {
if (capture_display_switches().poll(switch_display_event).generation != applied_display_generation) {
ec = platf::capture_e::reinit;
return false;
}
@@ -2944,13 +3133,13 @@ namespace video {
/**
* @brief Run synchronous capture and encode work on the capture thread.
*
* @param capture_context Encoder-specific worker state kept alive by its stream handles.
*/
void captureThreadSync() {
auto ref = capture_thread_sync.ref();
void captureThreadSync(capture_thread_sync_ctx_t &capture_context) {
std::vector<std::unique_ptr<sync_session_ctx_t>> synced_session_ctxs;
auto &ctx = ref->encode_session_ctx_queue;
auto &ctx = capture_context.encode_session_ctx_queue;
auto lg = util::fail_guard([&ctx, &synced_session_ctxs]() {
ctx.stop();
@@ -2971,7 +3160,8 @@ namespace video {
std::vector<std::string> display_names;
int display_p = -1;
while (encode_run_sync(synced_session_ctxs, ctx, display_names, display_p) == encode_e::reinit) {}
std::uint64_t applied_display_generation = 0;
while (encode_run_sync(synced_session_ctxs, ctx, display_names, display_p, applied_display_generation) == encode_e::reinit) {}
}
/**
@@ -2979,11 +3169,13 @@ namespace video {
*
* @param mail Session mail bus.
* @param config Video configuration.
* @param encoder Encoder selected for the requested video format.
* @param channel_data Stream session carried with each encoded packet.
*/
void capture_async(
safe::mail_t mail,
config_t &config,
const encoder_t &encoder,
stream::session_t *channel_data
) {
auto shutdown_event = mail->event<bool>(mail::shutdown);
@@ -2994,12 +3186,12 @@ namespace video {
shutdown_event->raise(true);
});
auto ref = capture_thread_async.ref();
auto ref = capture_groups<capture_thread_async_ctx_t, start_capture_async, end_capture_async>().ref(&encoder);
if (!ref) {
return;
}
ref->capture_ctx_queue->raise(capture_ctx_t {images, config});
ref->capture_ctx_queue->raise(capture_ctx_t {images, config, &encoder});
if (!ref->capture_ctx_queue->running()) {
return;
@@ -3030,8 +3222,6 @@ namespace video {
display = ref->display_wp->lock();
}
auto &encoder = *chosen_encoder;
auto encode_device = make_encode_device(*display, encoder, config);
if (!encode_device) {
return;
@@ -3059,7 +3249,7 @@ namespace video {
display,
std::move(encode_device),
ref->reinit_event,
*ref->encoder_p,
encoder,
channel_data
);
}
@@ -3077,16 +3267,24 @@ namespace video {
config_t config,
stream::session_t *channel_data
) {
config = resolve_dynamic_range(*chosen_encoder, config);
auto idr_events = mail->event<bool>(mail::idr);
auto encoder = encoder_for_config(config);
if (!encoder || !encoder_supports_video_format(*encoder, config.videoFormat)) {
BOOST_LOG(error) << "No encoder is available for video format ["sv << config.videoFormat << ']';
return;
}
config = resolve_dynamic_range(*encoder, config);
idr_events->raise(true);
if (chosen_encoder->flags & PARALLEL_ENCODING) {
capture_async(std::move(mail), config, channel_data);
if (encoder->flags & PARALLEL_ENCODING) {
capture_async(std::move(mail), config, *encoder, channel_data);
} else {
safe::signal_t join_event;
auto ref = capture_thread_sync.ref();
auto ref = capture_groups<capture_thread_sync_ctx_t, start_capture_sync, end_capture_sync>().ref(encoder);
if (!ref) {
return;
}
ref->encode_session_ctx_queue.raise(sync_session_ctx_t {
&join_event,
mail->event<bool>(mail::shutdown),
@@ -3095,6 +3293,7 @@ namespace video {
mail->event<hdr_info_t>(mail::hdr),
mail->event<input::touch_port_t>(mail::touch_port),
config,
encoder,
1,
channel_data,
});
@@ -3171,6 +3370,46 @@ namespace video {
return flag;
}
bool validate_legacy_codec(encoder_t &encoder, int video_format) {
if (!is_legacy_video_format(video_format)) {
return false;
}
auto &codec = video_format == format_mpeg2 ? encoder.mpeg2 : encoder.h263p;
codec.capabilities.reset();
if (codec.name.empty() || !encoder.platform_formats) {
return false;
}
config_t config {1920, 1080, 60, 6000, 1000, 1, 1, 1, video_format, 0, 0, 0};
std::shared_ptr<platf::display_t> display;
reset_display(display, encoder.platform_formats->dev_type, display_device::map_output_name(config::video.output_name), config);
if (!display || !display->is_codec_supported(codec.name, config)) {
return false;
}
codec[encoder_t::PASSED] = true;
codec[encoder_t::REF_FRAMES_RESTRICT] = true;
const auto max_ref_frames = validate_config(display, encoder, config);
config.numRefFrames = 0;
const auto autoselect = max_ref_frames >= 0 ? max_ref_frames : validate_config(display, encoder, config);
codec.capabilities.reset();
codec[encoder_t::REF_FRAMES_RESTRICT] = max_ref_frames >= 0;
codec[encoder_t::PASSED] = autoselect >= 0;
return codec[encoder_t::PASSED];
}
encoder_t *select_legacy_encoder(std::span<encoder_t *const> candidates, int video_format, const codec_probe_t &probe) {
if (!is_legacy_video_format(video_format)) {
return nullptr;
}
for (auto *encoder : candidates) {
if (encoder && probe(*encoder, video_format)) {
return encoder;
}
}
return nullptr;
}
/**
* @brief Validate encoder before it is used.
*/
@@ -3228,8 +3467,8 @@ namespace video {
encoder.h264[encoder_t::PASSED] = true;
if (test_hevc) {
config_max_ref_frames.videoFormat = 1;
config_autoselect.videoFormat = 1;
config_max_ref_frames.videoFormat = format_hevc;
config_autoselect.videoFormat = format_hevc;
if (disp->is_codec_supported(encoder.hevc.name, config_autoselect)) {
auto max_ref_frames_hevc = validate_config(disp, encoder, config_max_ref_frames);
@@ -3256,8 +3495,8 @@ namespace video {
}
if (test_av1) {
config_max_ref_frames.videoFormat = 2;
config_autoselect.videoFormat = 2;
config_max_ref_frames.videoFormat = format_av1;
config_autoselect.videoFormat = format_av1;
if (disp->is_codec_supported(encoder.av1.name, config_autoselect)) {
auto max_ref_frames_av1 = validate_config(disp, encoder, config_max_ref_frames);
@@ -3350,12 +3589,12 @@ namespace video {
encoder.h264[encoder_t::DYNAMIC_RANGE] = false;
encoder.h264[encoder_t::DYNAMIC_RANGE_YUV444] = false;
test_yuv444(encoder.hevc, 1);
test_yuv420_hdr(encoder.hevc, 1);
test_yuv444_hdr(encoder.hevc, 1);
test_yuv444(encoder.av1, 2);
test_yuv420_hdr(encoder.av1, 2);
test_yuv444_hdr(encoder.av1, 2);
test_yuv444(encoder.hevc, format_hevc);
test_yuv420_hdr(encoder.hevc, format_hevc);
test_yuv444_hdr(encoder.hevc, format_hevc);
test_yuv444(encoder.av1, format_av1);
test_yuv420_hdr(encoder.av1, format_av1);
test_yuv444_hdr(encoder.av1, format_av1);
}
encoder.h264[encoder_t::VUI_PARAMETERS] = encoder.h264[encoder_t::VUI_PARAMETERS] && !config::sunshine.flags[config::flag::FORCE_VIDEO_HEADER_REPLACE];
@@ -3373,6 +3612,7 @@ namespace video {
}
void reset_encoder_probe_results() {
probed_codec_modes().h264 = false;
last_encoder_probe_supported_ref_frames_invalidation = false;
last_encoder_probe_supported_yuv444_for_codec = {};
last_encoder_probe_supported_dynamic_range_for_codec = {};
@@ -3380,6 +3620,7 @@ namespace video {
}
void record_encoder_probe_results(const encoder_t &encoder) {
probed_codec_modes().h264 = encoder.h264[encoder_t::PASSED];
last_encoder_probe_supported_ref_frames_invalidation = (encoder.flags & REF_FRAMES_INVALIDATION);
last_encoder_probe_supported_yuv444_for_codec[0] = encoder.h264[encoder_t::PASSED] &&
encoder.h264[encoder_t::YUV444];
@@ -3401,6 +3642,23 @@ namespace video {
encoder.av1[encoder_t::DYNAMIC_RANGE_YUV444];
}
/**
* @brief Determine the advertised mode of an automatically configured modern codec.
*
* @param codec Codec capabilities from the selected encoder.
* @return The mode matching the supported profiles, or 1 when unavailable.
*/
static int auto_codec_mode(const encoder_t::codec_t &codec) {
if (!codec[encoder_t::PASSED]) {
return 1;
}
return 2 + static_cast<int>(codec[encoder_t::DYNAMIC_RANGE]) + 2 * static_cast<int>(codec[encoder_t::DYNAMIC_RANGE_YUV444]);
}
bool is_encoder_probe_cacheable(const encoder_t *encoder) {
return encoder && !(encoder->flags & ALWAYS_REPROBE);
}
int probe_encoders() {
if (!allow_encoder_probing(display_device::enumerate_devices())) {
// Error already logged
@@ -3408,17 +3666,21 @@ namespace video {
}
auto encoder_list = encoders;
auto &[codec_encoders, modes] = encoder_probe_state();
// If we already have a good encoder, check to see if another probe is required
if (chosen_encoder && !(chosen_encoder->flags & ALWAYS_REPROBE) && !platf::needs_encoder_reenumeration()) {
// Legacy settings are read at startup. Cache their results alongside the modern probe.
if (is_encoder_probe_cacheable(chosen_encoder) && !platf::needs_encoder_reenumeration()) {
return 0;
}
// Restart encoder selection
auto previous_encoder = chosen_encoder;
chosen_encoder = nullptr;
codec_encoders.fill(nullptr);
active_hevc_mode = config::video.hevc_mode;
active_av1_mode = config::video.av1_mode;
modes.mpeg2 = config::video.mpeg2_mode;
modes.h263p = config::video.h263p_mode;
reset_encoder_probe_results();
auto adjust_encoder_constraints_hevc = [&](encoder_t *encoder) {
@@ -3525,7 +3787,7 @@ namespace video {
});
if (chosen_encoder == nullptr) {
BOOST_LOG(error) << "Couldn't find any working encoder that meets HEVC/AV1 requirements"sv;
BOOST_LOG(error) << "Couldn't find any working encoder that meets codec requirements"sv;
}
}
@@ -3552,7 +3814,40 @@ namespace video {
});
}
if (chosen_encoder == nullptr) {
if (chosen_encoder) {
for (int format : {format_h264, format_hevc, format_av1}) {
if (encoder_supports_video_format(*chosen_encoder, format)) {
codec_encoders[format] = chosen_encoder;
}
}
}
// A failed modern probe must not remove a valid legacy encoder from consideration.
std::vector<encoder_t *> legacy_candidates(std::begin(encoders), std::end(encoders));
auto prioritize = [&](encoder_t *encoder) {
const auto position = std::find(legacy_candidates.begin(), legacy_candidates.end(), encoder);
if (position != legacy_candidates.end()) {
std::rotate(legacy_candidates.begin(), position, std::next(position));
}
};
prioritize(chosen_encoder);
for (auto *encoder : encoders) {
if (encoder->name == config::video.encoder) {
prioritize(encoder);
break;
}
}
for (const auto &[format, mode] : {std::pair {format_mpeg2, &modes.mpeg2}, std::pair {format_h263p, &modes.h263p}}) {
if (*mode == 2) {
codec_encoders[format] = select_legacy_encoder(legacy_candidates, format, validate_legacy_codec);
if (!codec_encoders[format]) {
BOOST_LOG(warning) << "No encoder supports legacy video format [" << format << ']';
*mode = 1;
}
}
}
if (!chosen_encoder && !codec_encoders[format_mpeg2] && !codec_encoders[format_h263p]) {
const auto output_name {display_device::map_output_name(config::video.output_name)};
BOOST_LOG(fatal) << "Unable to find display or encoder during startup."sv;
if (!config::video.adapter_name.empty() || !output_name.empty()) {
@@ -3567,71 +3862,68 @@ namespace video {
BOOST_LOG(info) << "// Ignore any errors mentioned above, they are not relevant. //"sv;
BOOST_LOG(info);
auto &encoder = *chosen_encoder;
if (chosen_encoder) {
auto &encoder = *chosen_encoder;
record_encoder_probe_results(encoder);
record_encoder_probe_results(encoder);
BOOST_LOG(debug) << "------ h264 ------"sv;
for (int x = 0; x < encoder_t::MAX_FLAGS; ++x) {
auto flag = static_cast<encoder_t::flag_e>(x);
BOOST_LOG(debug) << encoder_t::from_flag(flag) << (encoder.h264[flag] ? ": supported"sv : ": unsupported"sv);
}
BOOST_LOG(debug) << "-------------------"sv;
BOOST_LOG(info) << "Found H.264 encoder: "sv << encoder.h264.name << " ["sv << encoder.name << ']';
if (encoder.hevc[encoder_t::PASSED]) {
BOOST_LOG(debug) << "------ hevc ------"sv;
BOOST_LOG(debug) << "------ h264 ------"sv;
for (int x = 0; x < encoder_t::MAX_FLAGS; ++x) {
auto flag = static_cast<encoder_t::flag_e>(x);
BOOST_LOG(debug) << encoder_t::from_flag(flag) << (encoder.hevc[flag] ? ": supported"sv : ": unsupported"sv);
BOOST_LOG(debug) << encoder_t::from_flag(flag) << (encoder.h264[flag] ? ": supported"sv : ": unsupported"sv);
}
BOOST_LOG(debug) << "-------------------"sv;
BOOST_LOG(info) << "Found H.264 encoder: "sv << encoder.h264.name << " ["sv << encoder.name << ']';
BOOST_LOG(info) << "Found HEVC encoder: "sv << encoder.hevc.name << " ["sv << encoder.name << ']';
}
if (encoder.av1[encoder_t::PASSED]) {
BOOST_LOG(debug) << "------ av1 ------"sv;
for (int x = 0; x < encoder_t::MAX_FLAGS; ++x) {
auto flag = static_cast<encoder_t::flag_e>(x);
BOOST_LOG(debug) << encoder_t::from_flag(flag) << (encoder.av1[flag] ? ": supported"sv : ": unsupported"sv);
}
BOOST_LOG(debug) << "-------------------"sv;
BOOST_LOG(info) << "Found AV1 encoder: "sv << encoder.av1.name << " ["sv << encoder.name << ']';
}
// 2 - passed
// 3 - HDR yuv420
// 4 - HDR yuv444
// 5 - HDR yuv420 & HDR yuv444
if (active_hevc_mode == 0) {
active_hevc_mode = 1;
if (encoder.hevc[encoder_t::PASSED]) {
active_hevc_mode = 2;
if (encoder.hevc[encoder_t::DYNAMIC_RANGE]) {
active_hevc_mode += 1;
}
if (encoder.hevc[encoder_t::DYNAMIC_RANGE_YUV444]) {
active_hevc_mode += 2;
BOOST_LOG(debug) << "------ hevc ------"sv;
for (int x = 0; x < encoder_t::MAX_FLAGS; ++x) {
auto flag = static_cast<encoder_t::flag_e>(x);
BOOST_LOG(debug) << encoder_t::from_flag(flag) << (encoder.hevc[flag] ? ": supported"sv : ": unsupported"sv);
}
BOOST_LOG(debug) << "-------------------"sv;
BOOST_LOG(info) << "Found HEVC encoder: "sv << encoder.hevc.name << " ["sv << encoder.name << ']';
}
if (encoder.av1[encoder_t::PASSED]) {
BOOST_LOG(debug) << "------ av1 ------"sv;
for (int x = 0; x < encoder_t::MAX_FLAGS; ++x) {
auto flag = static_cast<encoder_t::flag_e>(x);
BOOST_LOG(debug) << encoder_t::from_flag(flag) << (encoder.av1[flag] ? ": supported"sv : ": unsupported"sv);
}
BOOST_LOG(debug) << "-------------------"sv;
BOOST_LOG(info) << "Found AV1 encoder: "sv << encoder.av1.name << " ["sv << encoder.name << ']';
}
if (active_hevc_mode == 0) {
active_hevc_mode = auto_codec_mode(encoder.hevc);
BOOST_LOG(debug) << "ENCODER STATUS ACTIVE_HEVC_MODE: "sv << active_hevc_mode;
}
if (active_av1_mode == 0) {
active_av1_mode = auto_codec_mode(encoder.av1);
BOOST_LOG(debug) << "ENCODER STATUS ACTIVE_AV1_MODE: "sv << active_av1_mode;
}
} else {
active_hevc_mode = 1;
active_av1_mode = 1;
}
for (int format : {format_mpeg2, format_h263p}) {
if (auto *backend = codec_encoders[format]) {
config_t config {};
config.videoFormat = format;
BOOST_LOG(info) << "Found legacy encoder: " << backend->codec_from_config(config).name << " [" << backend->name << ']';
}
BOOST_LOG(debug) << "ENCODER STATUS ACTIVE_HEVC_MODE: "sv << active_hevc_mode;
}
if (active_av1_mode == 0) {
active_av1_mode = 1;
if (encoder.av1[encoder_t::PASSED]) {
active_av1_mode = 2;
if (encoder.av1[encoder_t::DYNAMIC_RANGE]) {
active_av1_mode += 1;
}
if (encoder.av1[encoder_t::DYNAMIC_RANGE_YUV444]) {
active_av1_mode += 2;
}
}
BOOST_LOG(debug) << "ENCODER STATUS ACTIVE_AV1_MODE: "sv << active_av1_mode;
if (modes.mpeg2 == 0) {
modes.mpeg2 = 1;
}
if (modes.h263p == 0) {
modes.h263p = 1;
}
return 0;
@@ -3759,7 +4051,6 @@ namespace video {
* @brief Start capture async.
*/
int start_capture_async(capture_thread_async_ctx_t &capture_thread_ctx) {
capture_thread_ctx.encoder_p = chosen_encoder;
capture_thread_ctx.reinit_event.reset();
capture_thread_ctx.capture_ctx_queue = std::make_shared<safe::queue_t<capture_ctx_t>>(30);
@@ -3768,8 +4059,7 @@ namespace video {
captureThread,
capture_thread_ctx.capture_ctx_queue,
std::ref(capture_thread_ctx.display_wp),
std::ref(capture_thread_ctx.reinit_event),
std::ref(*capture_thread_ctx.encoder_p)
std::ref(capture_thread_ctx.reinit_event)
};
return 0;
@@ -3785,19 +4075,24 @@ namespace video {
}
/**
* @brief Start capture sync.
* @details The shared lifetime callback supplies unused state; the thread accesses the shared capture queue directly.
* @brief Start the synchronous worker for one encoder capture group.
*
* @param context Encoder-specific queue and owned worker thread.
* @return Zero after starting the worker.
*/
int start_capture_sync(capture_thread_sync_ctx_t &) {
std::jthread {&captureThreadSync}.detach();
int start_capture_sync(capture_thread_sync_ctx_t &context) {
context.capture_thread = std::jthread {captureThreadSync, std::ref(context)};
return 0;
}
/**
* @brief Leave synchronous capture cleanup to the capture thread.
* @brief Stop and join a synchronous group before destroying its queue.
*
* @param context Encoder-specific worker whose last stream has left.
*/
void end_capture_sync(capture_thread_sync_ctx_t &) {
// The capture thread stops its queue and signals its sessions when it exits.
void end_capture_sync(capture_thread_sync_ctx_t &context) {
context.encode_session_ctx_queue.stop();
context.capture_thread.join();
}
/**
+69 -6
View File
@@ -7,7 +7,9 @@
// standard includes
#include <chrono>
#include <deque>
#include <functional>
#include <optional>
#include <span>
#include <string_view>
#include <utility>
#include <vector>
@@ -34,6 +36,13 @@ namespace stream {
}
namespace video {
inline constexpr int format_h264 = 0; ///< H.264 High profile wire identifier.
inline constexpr int format_hevc = 1; ///< HEVC Main/Main10 wire identifier.
inline constexpr int format_av1 = 2; ///< AV1 Main/Main10 wire identifier.
inline constexpr int format_mpeg2 = 3; ///< MPEG-2/H.262 wire identifier.
inline constexpr int format_h263p = 4; ///< H.263+ wire identifier.
constexpr int VIDEO_FORMAT_COUNT = format_h263p + 1; ///< Number of supported wire codec identifiers.
/**
* @brief Encoding configuration requested by a remote client.
@@ -47,7 +56,7 @@ namespace video {
int slicesPerFrame; ///< Number of slices per frame.
int numRefFrames; ///< Maximum number of reference frames.
int encoderCscMode; ///< Requested color range and SDR colorspace; HDR always uses BT.2020 and ST2084.
int videoFormat; ///< Video codec format: 0 = H.264, 1 = HEVC, 2 = AV1.
int videoFormat; ///< GameStream wire identifier for the requested video codec.
int dynamicRange; ///< Encoding color depth: 0 = 8-bit, 1 = 10-bit.
int chromaSamplingType; ///< Chroma sampling type: 0 = 4:2:0, 1 = 4:4:4.
int enableIntraRefresh; ///< Intra refresh setting: 0 = disabled, 1 = enabled.
@@ -444,7 +453,7 @@ namespace video {
const std::unique_ptr<const encoder_platform_formats_t> platform_formats; ///< Platform-specific memory and pixel formats accepted by the encoder.
/**
* @brief Codec capabilities for AV1, HEVC, or H.264.
* @brief Codec capabilities for a modern or legacy video format.
*/
struct codec_t {
std::vector<option_t> common_options; ///< Options applied to every encode mode for this codec.
@@ -481,24 +490,30 @@ namespace video {
codec_t av1; ///< AV1 codec capability and option set.
codec_t hevc; ///< HEVC codec capability and option set.
codec_t h264; ///< H.264 codec capability and option set.
codec_t mpeg2; ///< MPEG-2 codec capability and option set.
codec_t h263p; ///< H.263+ codec capability and option set.
/**
* @brief Select the codec descriptor requested by a stream configuration.
*
* @param config Configuration values to apply.
* @return Codec descriptor for H.264, HEVC, or AV1.
* @return Codec descriptor for H.264, HEVC, AV1, MPEG-2, or H.263+.
*/
const codec_t &codec_from_config(const config_t &config) const {
switch (config.videoFormat) {
default:
BOOST_LOG(error) << "Unknown video format " << config.videoFormat << ", falling back to H.264";
// fallthrough
case 0:
case format_h264:
return h264;
case 1:
case format_hevc:
return hevc;
case 2:
case format_av1:
return av1;
case format_mpeg2:
return mpeg2;
case format_h263p:
return h263p;
}
}
@@ -765,6 +780,46 @@ namespace video {
*/
using hdr_info_t = std::unique_ptr<hdr_info_raw_t>;
/**
* @brief Callback used to probe one encoder for one requested legacy codec.
*/
using codec_probe_t = std::function<bool(encoder_t &, int)>;
/**
* @brief Probe MPEG-2 or H.263+ independently of H.264 support.
*
* @param encoder Backend whose requested codec should be validated.
* @param video_format MPEG-2 or H.263+ wire codec identifier.
* @return Whether the backend successfully encoded the requested legacy codec.
*/
bool validate_legacy_codec(encoder_t &encoder, int video_format);
/**
* @brief Choose the first backend that passes a codec-specific probe.
*
* @param candidates Backend preference order, including software fallbacks.
* @param video_format Requested legacy codec identifier.
* @param probe Callback validating only the requested codec.
* @return Selected backend, or nullptr when no candidate passes.
*/
encoder_t *select_legacy_encoder(std::span<encoder_t *const> candidates, int video_format, const codec_probe_t &probe);
/**
* @brief Encoder probe results for baseline H.264 and the legacy codec modes.
*/
struct probed_codec_modes_t {
bool h264 = false; ///< Whether baseline H.264 passed its probe.
int mpeg2 = 0; ///< Active MPEG-2 advertisement mode.
int h263p = 0; ///< Active H.263+ advertisement mode.
};
/**
* @brief Access the codec modes owned by the encoder probe.
*
* @return Current H.264 probe result and legacy codec advertisement modes.
*/
probed_codec_modes_t &probed_codec_modes();
extern int active_hevc_mode;
extern int active_av1_mode;
extern bool last_encoder_probe_supported_ref_frames_invalidation;
@@ -816,6 +871,14 @@ namespace video {
*/
bool validate_encoder(encoder_t &encoder, bool expect_failure);
/**
* @brief Determine whether a backend permits reusing its probe results while the hardware remains unchanged.
*
* @param encoder Previously validated backend, or nullptr before a successful probe.
* @return True when the backend's results can be cached.
*/
bool is_encoder_probe_cacheable(const encoder_t *encoder);
/**
* @brief Probe encoders and select the preferred encoder.
* This is called once at startup and each time a stream is launched to
+136
View File
@@ -0,0 +1,136 @@
/**
* @file src/video_capture_groups.h
* @brief Share capture workers only between streams using the same encoder backend.
*/
#pragma once
// standard includes
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <utility>
// local includes
#include "thread_safe.h"
namespace video {
struct encoder_t;
/**
* @brief Broadcast the latest monitor request to every active capture group.
*/
class display_switch_state_t {
public:
/**
* @brief Monitor request observed by one capture worker.
*/
struct request_t {
std::uint64_t generation = 0; ///< Changes whenever a monitor request is consumed.
std::optional<int> index; ///< Requested monitor index for the current stream epoch.
/**
* @brief Apply a switch once to this worker's refreshed display list.
*
* @param display_index Selected display, already kept by name across re-enumeration.
* @param display_count Number of displays in the refreshed list.
* @param applied_generation Last switch applied by this worker.
*/
void apply(int &display_index, std::size_t display_count, std::uint64_t &applied_generation) const {
if (generation == applied_generation || !index.has_value() || display_count == 0) {
return;
}
display_index = std::clamp(*index, 0, static_cast<int>(display_count) - 1);
applied_generation = generation;
}
};
/**
* @brief Start a capture group, resetting stale requests between streaming sessions.
*/
void start_worker() {
std::lock_guard lock {mutex_};
if (workers_++ == 0) {
request_ = {};
}
}
/**
* @brief Release a stopped capture group's participation in the stream epoch.
*/
void stop_worker() {
std::lock_guard lock {mutex_};
--workers_;
}
/**
* @brief Consume pending requests once and share their generation with every worker.
*
* @param event Shared monitor-switch event produced by input handling.
* @return Most recent request, even when another worker consumed the raw event.
*/
request_t poll(const safe::mail_raw_t::event_t<int> &event) {
std::lock_guard lock {mutex_};
if (const auto request = event->try_pop(); request.has_value()) {
request_.index = *request;
++request_.generation;
}
return request_;
}
private:
std::mutex mutex_; ///< Serializes event consumption and capture group lifetimes.
std::size_t workers_ = 0; ///< Number of active backend capture groups.
request_t request_; ///< Latest request shared during this streaming epoch.
};
/**
* @brief Maintain independent capture worker lifetimes for encoder backends.
*
* @tparam T Capture worker context managed by safe::shared_t.
*/
template<class T>
class capture_group_pool_t {
public:
using group_t = safe::shared_t<T>; ///< Reference-counted capture worker storage.
using ptr_t = typename group_t::ptr_t; ///< Handle keeping one backend's worker alive.
/**
* @brief Configure the callbacks that start and stop each capture worker.
*
* @param construct Callback starting a newly referenced backend group.
* @param destruct Callback stopping a group after its final stream leaves.
*/
capture_group_pool_t(typename group_t::construct_f construct, typename group_t::destruct_f destruct):
construct_ {std::move(construct)},
destruct_ {std::move(destruct)} {
}
/**
* @brief Acquire the capture worker belonging to a stream's encoder backend.
*
* @param encoder Stable encoder identity; null does not acquire a group.
* @return Shared worker handle, or an empty handle when startup fails.
*/
ptr_t ref(const encoder_t *encoder) {
if (!encoder) {
return {};
}
std::lock_guard lock {mutex_};
auto &group = groups_[encoder];
if (!group) {
group = std::make_unique<group_t>(construct_, destruct_);
}
return group->ref();
}
private:
typename group_t::construct_f construct_; ///< Worker startup callback.
typename group_t::destruct_f destruct_; ///< Worker shutdown callback.
std::mutex mutex_; ///< Protects stable group allocation.
std::map<const encoder_t *, std::unique_ptr<group_t>> groups_; ///< One group per encoder backend.
};
} // namespace video
@@ -103,6 +103,8 @@
"min_threads": 2,
"hevc_mode": 0,
"av1_mode": 0,
"mpeg2_mode": 0,
"h263p_mode": 0,
"capture": "",
"fp16_sdr_gamma_encoded": "disabled",
"encoder": ""
@@ -59,6 +59,28 @@ const config = ref(props.config)
<div class="form-text">{{ $t('config.av1_mode_desc') }}</div>
</div>
<!-- MPEG-2 Support -->
<div class="mb-3">
<label for="mpeg2_mode" class="form-label">{{ $t('config.mpeg2_mode') }}</label>
<select id="mpeg2_mode" class="form-select" v-model="config.mpeg2_mode">
<option value="0">{{ $t('config.mpeg2_mode_0') }}</option>
<option value="1">{{ $t('config.mpeg2_mode_1') }}</option>
<option value="2">{{ $t('config.mpeg2_mode_2') }}</option>
</select>
<div class="form-text">{{ $t('config.mpeg2_mode_desc') }}</div>
</div>
<!-- H.263+ Support -->
<div class="mb-3">
<label for="h263p_mode" class="form-label">{{ $t('config.h263p_mode') }}</label>
<select id="h263p_mode" class="form-select" v-model="config.h263p_mode">
<option value="0">{{ $t('config.h263p_mode_0') }}</option>
<option value="1">{{ $t('config.h263p_mode_1') }}</option>
<option value="2">{{ $t('config.h263p_mode_2') }}</option>
</select>
<div class="form-text">{{ $t('config.h263p_mode_desc') }}</div>
</div>
<!-- Capture -->
<div class="mb-3" v-if="platform !== 'macos'">
<label for="capture" class="form-label">{{ $t('config.capture') }}</label>
@@ -283,6 +283,11 @@
"gamepad_xseries": "Xbox Series",
"global_prep_cmd": "Command Preparations",
"global_prep_cmd_desc": "Configure a list of commands to be executed before or after running any application. If any of the specified preparation commands fail, the application launch process will be aborted.",
"h263p_mode": "H.263+ Support",
"h263p_mode_0": "Sunshine will preserve modern codec automatic selection and keep H.263+ unadvertised",
"h263p_mode_1": "Sunshine will not advertise support for H.263+",
"h263p_mode_2": "Sunshine will advertise support for H.263+ video",
"h263p_mode_desc": "Advertise H.263+ video to any client implementing the Sunshine codec extension. Disabled by default. Sunshine uses software encoding without changing the backends selected for MPEG-2 or modern codecs.",
"hevc_mode": "HEVC Support",
"hevc_mode_0": "Sunshine will advertise support for HEVC based on encoder capabilities (recommended)",
"hevc_mode_1": "Sunshine will not advertise support for HEVC",
@@ -335,6 +340,11 @@
"min_log_level_5": "Fatal",
"min_log_level_6": "None",
"min_log_level_desc": "The minimum log level printed to standard out",
"mpeg2_mode": "MPEG-2 Support",
"mpeg2_mode_0": "Sunshine will preserve modern codec automatic selection and keep MPEG-2 unadvertised",
"mpeg2_mode_1": "Sunshine will not advertise support for MPEG-2",
"mpeg2_mode_2": "Sunshine will advertise support for MPEG-2/H.262 video",
"mpeg2_mode_desc": "Advertise MPEG-2/H.262 video to any client implementing the Sunshine codec extension. Disabled by default. Sunshine selects its backend independently of H.263+ and modern codecs, using hardware encoding when supported.",
"min_threads": "Minimum CPU Thread Count",
"min_threads_desc": "Increasing the value slightly reduces encoding efficiency, but the tradeoff is usually worth it to gain the use of more CPU cores for encoding. The ideal value is the lowest value that can reliably encode at your desired streaming settings on your hardware.",
"misc": "Miscellaneous options",
+4
View File
@@ -300,3 +300,7 @@ if (WIN32)
)
endif()
endif ()
# Exercise the same negotiation implementation used by the client transport.
target_sources(${PROJECT_NAME} PRIVATE
"${moonlight-common-c_SOURCE_DIR}/src/VideoFormats.c")
@@ -12,6 +12,7 @@
// local includes
#include "src/platform/linux/display_geometry.h"
#include "src/platform/linux/kms_display.h"
#include "src/video.h"
namespace {
@@ -46,6 +47,44 @@ namespace {
};
} // namespace
/**
* @brief One backend can refresh its outputs while another keeps its original connector and input bounds.
*/
TEST(KmsDisplayEnumerationTest, KeepsPlaneAndDesktopGeometryWithTheSelectedBackend) {
platf::kms::display_enumeration_t hardware;
hardware.cards.push_back({"/dev/dri/card1", {}});
hardware.outputs.emplace_back("DP-1", 0U, 31U, 51U);
hardware.desktop.add({.offset_x = 0, .offset_y = 0, .width = 1920, .height = 1080});
platf::kms::display_enumeration_t software;
software.cards.push_back({"/dev/dri/card0", {}});
software.cards.push_back({"/dev/dri/card1", {}});
software.outputs.emplace_back("HDMI-A-1", 0U, 57U, 67U);
software.outputs.emplace_back("DP-1", 1U, 31U, 51U);
software.desktop.add({.offset_x = -1280, .offset_y = 0, .width = 1280, .height = 720});
software.desktop.add({.offset_x = 0, .offset_y = 0, .width = 1920, .height = 1080});
EXPECT_EQ(hardware.display_index(""), 0U);
EXPECT_EQ(software.display_index("1"), 1U);
EXPECT_FALSE(hardware.display_index("HDMI-A-1"));
const auto software_index = software.display_index("DP-1");
const auto hardware_index = hardware.display_index("DP-1");
ASSERT_EQ(software_index, 1U);
ASSERT_EQ(hardware_index, 0U);
EXPECT_EQ(software.cards[software.outputs[*software_index].card_index].path, "/dev/dri/card1");
EXPECT_EQ(hardware.outputs[*hardware_index].plane_id, 31U);
EXPECT_EQ(hardware.outputs[*hardware_index].crtc_id, 51U);
geometry_display_t hardware_display;
geometry_display_t software_display;
hardware.desktop.apply(hardware_display);
software.desktop.apply(software_display);
EXPECT_EQ(hardware_display.env_width, 1920);
EXPECT_EQ(hardware_display.env_offset_x, 0);
EXPECT_EQ(software_display.env_width, 3200);
EXPECT_EQ(software_display.env_offset_x, -1280);
}
TEST(LinuxDisplayGeometryTest, EmptyAndInvalidMonitorsDoNotCreateAnInputDesktop) {
platf::desktop_geometry_t desktop;
EXPECT_EQ(desktop.bounds().width, 0);
+221
View File
@@ -0,0 +1,221 @@
/**
* @file tests/unit/test_legacy_codec_roundtrip.cpp
* @brief Round-trip negotiated legacy codecs through production encoding and client-side decoding.
*/
// test includes
#include "../tests_common.h"
// standard includes
#include <algorithm>
#include <chrono>
#include <cstddef>
#include <memory>
#include <optional>
#include <vector>
// lib includes
extern "C" {
#include <moonlight-common-c/src/VideoFormats.h>
}
// local includes
#include <src/rtsp.h>
#include <src/video.h>
namespace video {
/**
* @brief Create the production conversion device without starting desktop capture.
* @param display Deterministic display supplying CPU frames.
* @param encoder Backend under test.
* @param config Negotiated client configuration.
* @return Production encode device.
*/
std::unique_ptr<platf::encode_device_t> make_encode_device(platf::display_t &display, const encoder_t &encoder, const config_t &config);
/**
* @brief Create a production encoding session for deterministic test frames.
* @param display Display geometry and codec support.
* @param encoder Backend under test.
* @param config Negotiated client configuration.
* @param width Capture width.
* @param height Capture height.
* @param device Frame conversion device.
* @return Production encode session.
*/
std::unique_ptr<encode_session_t> make_encode_session(platf::display_t *display, const encoder_t &encoder, const config_t &config, int width, int height, std::unique_ptr<platf::encode_device_t> device);
/**
* @brief Encode and queue a frame using the same path as a streaming session.
* @param frame_nr Monotonic frame number.
* @param session Production encode session.
* @param packets Encoded packet queue.
* @param channel_data Unused stream identity for this headless test.
* @param frame_timestamp Optional capture timestamp.
* @return Zero on successful encoding.
*/
int encode(int64_t frame_nr, encode_session_t &session, safe::mail_raw_t::queue_t<packet_t> &packets, stream::session_t *channel_data, std::optional<std::chrono::steady_clock::time_point> frame_timestamp);
} // namespace video
namespace {
/**
* @brief CPU display exercising production color conversion without a desktop or GPU.
*/
class test_display_t: public platf::display_t {
public:
/**
* @brief Set a small frame size accepted by both legacy codecs.
*/
test_display_t() {
width = 176;
height = 144;
env_width = width;
env_height = height;
}
/**
* @brief Keep desktop capture disabled; frames are supplied directly by the test.
* @param push Unused capture callback.
* @param pull Unused image allocation callback.
* @param cursor Unused cursor state.
* @return Successful capture shutdown.
*/
platf::capture_e capture(const push_captured_image_cb_t &push, const pull_free_image_cb_t &pull, bool *cursor) override {
return platf::capture_e::ok;
}
/**
* @brief Leave image allocation to the deterministic test buffer.
* @return Empty image handle.
*/
std::shared_ptr<platf::img_t> alloc_img() override {
return {};
}
/**
* @brief Accept the caller's initialized image.
* @param image Unused image.
* @return Zero on success.
*/
int dummy_img(platf::img_t *image) override {
return 0;
}
/**
* @brief Request production software color conversion.
* @param format Requested encoder pixel format.
* @return CPU encode device wrapped by the production software converter.
*/
std::unique_ptr<platf::avcodec_encode_device_t> make_avcodec_encode_device(platf::pix_fmt_e format) override {
return std::make_unique<platf::avcodec_encode_device_t>();
}
};
/**
* @brief Run the same codec transport contract for MPEG-2 and H.263+.
*/
class LegacyCodecRoundTripTest: public BaseTest, public testing::WithParamInterface<int> {};
} // namespace
/**
* @brief Negotiate a forced codec, encode BGRA frames, and decode the resulting key and inter frames.
*/
TEST_P(LegacyCodecRoundTripTest, DecodesProductionPacketsForTheNegotiatedCodec) {
const auto format = GetParam();
const auto mode = format == VIDEO_FORMAT_MPEG2 ? SCM_MPEG2 : SCM_H263P;
const auto sdp = rtsp_stream::describe_video_codecs(mode);
const auto negotiated = chooseVideoFormat(format, mode, sdp.c_str());
ASSERT_EQ(negotiated, format);
video::config_t config {};
config.videoFormat = getVideoBitStreamFormat(negotiated);
config.width = 176;
config.height = 144;
config.framerate = 30;
config.framerateX100 = 3000;
config.bitrate = 1000;
config.slicesPerFrame = 1;
config.numRefFrames = 1;
config.encoderCscMode = 1;
auto &codec = config.videoFormat == video::format_mpeg2 ? video::software.mpeg2 : video::software.h263p;
const auto saved_capabilities = codec.capabilities;
auto restore = util::fail_guard([&codec, &saved_capabilities] {
codec.capabilities = saved_capabilities;
});
codec[video::encoder_t::PASSED] = true;
test_display_t display;
auto device = video::make_encode_device(display, video::software, config);
ASSERT_TRUE(device);
auto session = video::make_encode_session(&display, video::software, config, display.width, display.height, std::move(device));
ASSERT_TRUE(session);
const auto decoder = avcodec_find_decoder(config.videoFormat == video::format_mpeg2 ? AV_CODEC_ID_MPEG2VIDEO : AV_CODEC_ID_H263P);
ASSERT_NE(decoder, nullptr);
video::avcodec_ctx_t decode_context {avcodec_alloc_context3(decoder)};
ASSERT_TRUE(decode_context);
decode_context->flags |= AV_CODEC_FLAG_LOW_DELAY;
ASSERT_EQ(avcodec_open2(decode_context.get(), decoder, nullptr), 0);
video::avcodec_frame_t decoded {av_frame_alloc()};
ASSERT_TRUE(decoded);
int decoded_frames = 0;
const auto receive = [&] {
int result;
while ((result = avcodec_receive_frame(decode_context.get(), decoded.get())) == 0) {
EXPECT_EQ(decoded->width, config.width);
EXPECT_EQ(decoded->height, config.height);
EXPECT_EQ(decoded->format, AV_PIX_FMT_YUV420P);
++decoded_frames;
av_frame_unref(decoded.get());
}
EXPECT_TRUE(result == AVERROR(EAGAIN) || result == AVERROR_EOF) << result;
};
auto mailbox = std::make_shared<safe::mail_raw_t>();
auto packets = mailbox->queue<video::packet_t>("video");
std::vector<uint8_t> pixels(static_cast<std::size_t>(config.width) * config.height * 4, 64);
platf::img_t image;
image.data = pixels.data();
image.width = config.width;
image.height = config.height;
image.pixel_pitch = 4;
image.row_pitch = config.width * image.pixel_pitch;
int encoded_frames = 0;
bool saw_inter_frame = false;
for (int frame = 0; frame < 5; ++frame) {
pixels[0] = static_cast<uint8_t>(frame * 20);
ASSERT_EQ(session->convert(image), 0);
if (frame == 0) {
session->request_idr_frame();
} else {
session->request_normal_frame();
}
ASSERT_EQ(video::encode(frame, *session, packets, nullptr, std::nullopt), 0);
while (packets->peek()) {
auto packet = packets->pop();
ASSERT_TRUE(packet);
const auto &encoded = packet;
ASSERT_GT(encoded->data_size(), 0);
if (encoded_frames++ == 0) {
EXPECT_TRUE(encoded->is_idr());
} else {
saw_inter_frame |= !encoded->is_idr();
}
auto *av_packet = av_packet_alloc();
ASSERT_NE(av_packet, nullptr);
auto release = util::fail_guard([&av_packet] {
av_packet_free(&av_packet);
});
ASSERT_EQ(av_new_packet(av_packet, static_cast<int>(encoded->data_size())), 0);
std::copy_n(encoded->data(), encoded->data_size(), av_packet->data);
ASSERT_EQ(avcodec_send_packet(decode_context.get(), av_packet), 0);
receive();
}
}
ASSERT_EQ(avcodec_send_packet(decode_context.get(), nullptr), 0);
receive();
EXPECT_GE(encoded_frames, 2);
EXPECT_TRUE(saw_inter_frame);
EXPECT_EQ(decoded_frames, encoded_frames);
}
INSTANTIATE_TEST_SUITE_P(LegacyFormats, LegacyCodecRoundTripTest, testing::Values(VIDEO_FORMAT_MPEG2, VIDEO_FORMAT_H263P));
@@ -0,0 +1,96 @@
/**
* @file tests/unit/test_legacy_codec_selection.cpp
* @brief Verify independent codec probing and shared host/client negotiation.
*/
// test includes
#include "../tests_common.h"
// standard includes
#include <array>
#include <string>
#include <vector>
// lib includes
extern "C" {
#include <moonlight-common-c/src/VideoFormats.h>
}
// local includes
#include <src/rtsp.h>
#include <src/video.h>
/**
* @brief H.263+ software fallback does not displace an available hardware MPEG-2 backend.
*/
TEST(LegacyCodecSelectionTest, SelectsEachCodecIndependentlyWithoutRequiringH264) {
video::encoder_t hardware {};
video::encoder_t software {};
const std::array candidates {&hardware, &software};
std::vector<int> probes;
const auto probe = [&](video::encoder_t &encoder, int format) {
probes.push_back(format);
return &encoder == &software || format == video::format_mpeg2;
};
EXPECT_EQ(video::select_legacy_encoder(candidates, video::format_mpeg2, probe), &hardware);
EXPECT_EQ(video::select_legacy_encoder(candidates, video::format_h263p, probe), &software);
EXPECT_FALSE(hardware.h264[video::encoder_t::PASSED]);
EXPECT_FALSE(software.h264[video::encoder_t::PASSED]);
EXPECT_EQ(probes, (std::vector<int> {video::format_mpeg2, video::format_h263p, video::format_h263p}));
}
/**
* @brief Unsupported codecs and failed probes never return an unrelated backend.
*/
TEST(LegacyCodecSelectionTest, RejectsInvalidFormatsAndUnavailableBackends) {
video::encoder_t backend {};
const std::array candidates {static_cast<video::encoder_t *>(nullptr), &backend};
int probes = 0;
const auto reject = [&probes](auto &, int) {
++probes;
return false;
};
EXPECT_EQ(video::select_legacy_encoder(candidates, video::format_h264, reject), nullptr);
EXPECT_EQ(probes, 0);
EXPECT_EQ(video::select_legacy_encoder(candidates, video::format_mpeg2, reject), nullptr);
EXPECT_EQ(probes, 1);
EXPECT_FALSE(video::validate_legacy_codec(backend, video::format_av1));
EXPECT_FALSE(video::validate_legacy_codec(backend, video::format_mpeg2));
EXPECT_FALSE(video::validate_legacy_codec(backend, video::format_h263p));
}
/**
* @brief Any implementing client can negotiate an advertised legacy codec using shared wire values.
*/
TEST(LegacyCodecNegotiationTest, MatchesSunshineAdvertisementsAndStrictClientRequests) {
constexpr uint32_t modes = SCM_H264 | SCM_HEVC | SCM_AV1_MAIN8 | SCM_MPEG2 | SCM_H263P;
const auto sdp = rtsp_stream::describe_video_codecs(modes);
EXPECT_EQ(chooseVideoFormat(VIDEO_FORMAT_H264 | VIDEO_FORMAT_AV1_MAIN8 | VIDEO_FORMAT_MPEG2, modes, sdp.c_str()), VIDEO_FORMAT_AV1_MAIN8);
EXPECT_EQ(chooseVideoFormat(VIDEO_FORMAT_MPEG2, modes, sdp.c_str()), VIDEO_FORMAT_MPEG2);
EXPECT_EQ(chooseVideoFormat(VIDEO_FORMAT_H263P, modes, sdp.c_str()), VIDEO_FORMAT_H263P);
EXPECT_EQ(getVideoBitStreamFormat(VIDEO_FORMAT_MPEG2), video::format_mpeg2);
EXPECT_EQ(getVideoBitStreamFormat(VIDEO_FORMAT_H263P), video::format_h263p);
for (const auto mode : {SCM_MPEG2, SCM_H263P}) {
const auto legacy_sdp = rtsp_stream::describe_video_codecs(mode);
const auto supported = VIDEO_FORMAT_H264 | VIDEO_FORMAT_MPEG2 | VIDEO_FORMAT_H263P;
const auto selected = chooseVideoFormat(supported, mode, legacy_sdp.c_str());
EXPECT_EQ(selected, mode == SCM_MPEG2 ? VIDEO_FORMAT_MPEG2 : VIDEO_FORMAT_H263P);
}
EXPECT_TRUE(rtsp_stream::describe_video_codecs(0).empty());
EXPECT_EQ(chooseVideoFormat(VIDEO_FORMAT_MPEG2, SCM_H264, rtsp_stream::describe_video_codecs(SCM_H264).c_str()), 0);
}
/**
* @brief Legacy advertisement does not invalidate a successful probe on unchanged hardware.
*/
TEST(LegacyCodecSelectionTest, ReusesCachedHardwareProbeWithLegacySupport) {
const auto previous_modes = video::probed_codec_modes();
auto restore = util::fail_guard([previous_modes] {
video::probed_codec_modes() = previous_modes;
});
video::probed_codec_modes() = {true, 2, 2};
video::encoder_t hardware {};
EXPECT_TRUE(video::is_encoder_probe_cacheable(&hardware));
EXPECT_FALSE(video::is_encoder_probe_cacheable(&video::software));
EXPECT_FALSE(video::is_encoder_probe_cacheable(nullptr));
}
+16 -1
View File
@@ -50,6 +50,7 @@ protected:
* @brief Save the global probe state.
*/
void SetUp() override {
codec_modes_ = video::probed_codec_modes();
hevc_mode_ = video::active_hevc_mode;
av1_mode_ = video::active_av1_mode;
yuv444_ = video::last_encoder_probe_supported_yuv444_for_codec;
@@ -61,6 +62,7 @@ protected:
* @brief Restore the global probe state.
*/
void TearDown() override {
video::probed_codec_modes() = codec_modes_;
video::active_hevc_mode = hevc_mode_;
video::active_av1_mode = av1_mode_;
video::last_encoder_probe_supported_yuv444_for_codec = yuv444_;
@@ -69,6 +71,7 @@ protected:
}
private:
video::probed_codec_modes_t codec_modes_; ///< Saved H.264 and legacy codec modes.
int hevc_mode_ = 0; ///< Saved HEVC mode.
int av1_mode_ = 0; ///< Saved AV1 mode.
std::array<bool, 3> yuv444_ {}; ///< Saved 8-bit 4:4:4 results.
@@ -89,7 +92,7 @@ using CodecProbeAdvertisementTest = CodecProbeStateTest;
TEST_F(CodecProbeAdvertisementTest, Probed8Bit444Without10Bit444AdvertisesOnly8Bit444) {
using namespace std::literals;
video::encoder_t encoder {"test"sv, {}, {}, {}, {}, 0};
video::encoder_t encoder {"test"sv, {}, {}, {}, {}, {}, {}, 0};
for (auto *codec : {&encoder.h264, &encoder.hevc, &encoder.av1}) {
(*codec)[video::encoder_t::PASSED] = true;
(*codec)[video::encoder_t::YUV444] = true;
@@ -146,3 +149,15 @@ INSTANTIATE_TEST_SUITE_P(
flags_case_t {codec_e::av1, 3, true, true, true, SCM_AV1_MAIN8 | SCM_AV1_MAIN10 | SCM_AV1_HIGH8_444}
)
);
/**
* @brief A legacy-only host advertises available codecs without inventing H.264 support.
*/
TEST_F(CodecProbeAdvertisementTest, LegacyOnlyHostDoesNotAdvertiseH264) {
video::reset_encoder_probe_results();
video::active_hevc_mode = 1;
video::active_av1_mode = 1;
video::probed_codec_modes().mpeg2 = 2;
video::probed_codec_modes().h263p = 2;
EXPECT_EQ(nvhttp::get_codec_mode_flags(), static_cast<uint32_t>(SCM_MPEG2 | SCM_H263P));
}
+98
View File
@@ -12,6 +12,7 @@
// standard includes
#include <array>
#include <format>
#include <string>
#include <utility>
#include <vector>
@@ -24,7 +25,9 @@ extern "C" {
// local includes
#include <src/audio.h>
#include <src/config.h>
#include <src/rtsp.h>
#include <src/video.h>
/**
* @brief The Moonlight compatibility header can be included first before using the C RTSP parser.
@@ -88,6 +91,16 @@ namespace rtsp_stream {
*/
void cmd_describe(rtsp_server_t *, boost::asio::ip::tcp::socket &sock, launch_session_t &session, msg_t &&req);
/**
* @brief Validate ANNOUNCE input before creating a stream.
*
* @param server RTSP server, unused when validation rejects the request.
* @param sock Connected client socket.
* @param session Launch session.
* @param req Parsed ANNOUNCE request.
*/
void cmd_announce(rtsp_server_t *server, boost::asio::ip::tcp::socket &sock, launch_session_t &session, msg_t &&req);
/**
* @brief Respond to PLAY through the common dispatcher signature.
* @param sock Connected client socket.
@@ -185,3 +198,88 @@ TEST(RtspDescribeTest, SurroundParamsCompensateClientRotationForEveryStreamConfi
EXPECT_EQ(advertised[x], expected[x].second) << "stream config " << expected[x].first;
}
}
/**
* @brief Reject invalid H.263+ resolutions before negotiating stream encryption.
*/
TEST(RtspAnnounceTest, ValidatesH263PlusDimensionsAfterApplyingResolutionCap) {
using boost::asio::ip::tcp;
auto &h263p = video::probed_codec_modes().h263p;
auto &lan_encryption = config::stream.lan_encryption_mode;
auto &max_width = config::video.max_stream_width;
auto &max_height = config::video.max_stream_height;
auto restore = util::fail_guard([old_h263p = h263p, old_encryption = lan_encryption, old_width = max_width, old_height = max_height] {
video::probed_codec_modes().h263p = old_h263p;
config::stream.lan_encryption_mode = old_encryption;
config::video.max_stream_width = old_width;
config::video.max_stream_height = old_height;
});
h263p = 2;
// Valid resolutions reach the encryption gate without starting a stream.
lan_encryption = config::ENCRYPTION_MODE_MANDATORY;
/**
* @brief One ANNOUNCE request and the expected validation response.
*/
struct announce_case_t {
int format; ///< Requested video codec.
int width; ///< Requested width in pixels.
int height; ///< Requested height in pixels.
int cap_width; ///< Maximum width in pixels, or zero to disable capping.
int cap_height; ///< Maximum height in pixels, or zero to disable capping.
int status; ///< Expected RTSP status code.
};
const std::array cases {
announce_case_t {video::format_h263p, 640, 480, 0, 0, 403},
announce_case_t {video::format_h263p, 1366, 768, 0, 0, 400},
announce_case_t {video::format_h263p, 640, 478, 0, 0, 400},
announce_case_t {video::format_h263p, 0, 480, 0, 0, 400},
announce_case_t {video::format_h263p, 640, -4, 0, 0, 400},
announce_case_t {video::format_h263p, 1920, 1080, 1366, 800, 400},
announce_case_t {video::format_h263p, 1920, 1080, 1280, 720, 403},
announce_case_t {video::format_h264, 1366, 768, 0, 0, 403},
};
for (const auto &test_case : cases) {
SCOPED_TRACE(std::format("{}x{} (cap {}x{}, codec {})", test_case.width, test_case.height, test_case.cap_width, test_case.cap_height, test_case.format));
max_width = test_case.cap_width;
max_height = test_case.cap_height;
const auto sdp = std::format(
"a=x-nv-audio.surround.numChannels:2\r\n"
"a=x-nv-audio.surround.channelMask:3\r\n"
"a=x-nv-audio.surround.AudioQuality:0\r\n"
"a=x-nv-video[0].packetSize:1024\r\n"
"a=x-nv-video[0].clientViewportWd:{}\r\n"
"a=x-nv-video[0].clientViewportHt:{}\r\n"
"a=x-nv-video[0].maxFPS:60\r\n"
"a=x-nv-vqos[0].bw.maximumBitrateKbps:3000\r\n"
"a=x-nv-video[0].videoEncoderSlicesPerFrame:1\r\n"
"a=x-nv-video[0].maxNumReferenceFrames:1\r\n"
"a=x-nv-vqos[0].bitStreamFormat:{}\r\n",
test_case.width,
test_case.height,
test_case.format
);
auto message = std::format("ANNOUNCE rtsp://localhost RTSP/1.0\r\nCSeq: 42\r\nContent-Length: {}\r\n\r\n{}", sdp.size(), sdp);
rtsp_stream::msg_t request {new RTSP_MESSAGE {}};
ASSERT_EQ(parseRtspMessage(request.get(), message.data(), message.size()), RTSP_ERROR_SUCCESS);
boost::asio::io_context io;
tcp::acceptor acceptor {io, {boost::asio::ip::address_v4::loopback(), 0}};
tcp::socket client {io};
client.connect(acceptor.local_endpoint());
auto server_socket = acceptor.accept();
rtsp_stream::launch_session_t session {};
rtsp_stream::cmd_announce(nullptr, server_socket, session, std::move(request));
server_socket.shutdown(tcp::socket::shutdown_send);
std::string response;
boost::system::error_code read_error;
boost::asio::read(client, boost::asio::dynamic_buffer(response), read_error);
ASSERT_EQ(read_error, boost::asio::error::eof);
EXPECT_TRUE(response.starts_with(std::format("RTSP/1.0 {} ", test_case.status))) << response;
}
}
+53 -3
View File
@@ -116,6 +116,26 @@ TEST(VideoFormatMappingTest, MapsSupportedPixelFormatsAndRejectsUnsupportedOnes)
}
}
/**
* @brief Each supported video format selects its matching encoder codec descriptor.
*/
TEST(VideoCodecSelectionTest, SelectsModernAndLegacyCodecDescriptors) {
video::encoder_t encoder {};
const std::array cases {
std::pair {video::format_h264, &video::encoder_t::h264},
std::pair {video::format_hevc, &video::encoder_t::hevc},
std::pair {video::format_av1, &video::encoder_t::av1},
std::pair {video::format_mpeg2, &video::encoder_t::mpeg2},
std::pair {video::format_h263p, &video::encoder_t::h263p},
};
for (const auto &[format, codec] : cases) {
video::config_t config {};
config.videoFormat = format;
EXPECT_EQ(&encoder.codec_from_config(config), &(encoder.*codec)) << format;
}
}
struct EncoderTest: PlatformTestSuite, testing::WithParamInterface<video::encoder_t *> {
void SetUp() override {
BaseTest::SetUp();
@@ -231,6 +251,8 @@ TEST_P(DynamicRangeTest, Resolve) {
{},
{},
{},
{},
{},
0,
};
encoder.h264.name = "h264_test";
@@ -292,7 +314,7 @@ struct EncoderProbeResultsTest: testing::Test {
};
TEST_F(EncoderProbeResultsTest, FailedCodecProbeDoesNotPublishCapabilities) {
video::encoder_t encoder {"test"sv, {}, {}, {}, {}, 0};
video::encoder_t encoder {"test"sv, {}, {}, {}, {}, {}, {}, 0};
for (auto *codec : {&encoder.h264, &encoder.hevc, &encoder.av1}) {
(*codec)[video::encoder_t::PASSED] = false;
(*codec)[video::encoder_t::YUV444] = true;
@@ -311,7 +333,7 @@ TEST_F(EncoderProbeResultsTest, FailedCodecProbeDoesNotPublishCapabilities) {
TEST_F(EncoderProbeResultsTest, SubsequentProbeReplacesPriorResults) {
constexpr uint32_t ref_frames_invalidation = 1 << 8; // Mirrors REF_FRAMES_INVALIDATION in video.cpp.
video::encoder_t first {"first"sv, {}, {}, {}, {}, ref_frames_invalidation};
video::encoder_t first {"first"sv, {}, {}, {}, {}, {}, {}, ref_frames_invalidation};
for (auto *codec : {&first.h264, &first.hevc, &first.av1}) {
(*codec)[video::encoder_t::PASSED] = true;
(*codec)[video::encoder_t::YUV444] = true;
@@ -320,7 +342,7 @@ TEST_F(EncoderProbeResultsTest, SubsequentProbeReplacesPriorResults) {
}
// The second encoder only supports plain 8-bit 4:2:0 H.264.
video::encoder_t second {"second"sv, {}, {}, {}, {}, 0};
video::encoder_t second {"second"sv, {}, {}, {}, {}, {}, {}, 0};
second.h264[video::encoder_t::PASSED] = true;
video::record_encoder_probe_results(first);
@@ -430,6 +452,34 @@ INSTANTIATE_TEST_SUITE_P(
)
);
/**
* @brief The software backend probes MPEG-2 even when its H.264 encoder is unavailable.
*/
TEST_F(PlatformTestSuite, SoftwareEncoderSupportsForcedMpeg2) {
const auto h264_name = video::software.h264.name;
auto restore = util::fail_guard([&] {
video::software.h264.name = h264_name;
});
video::software.h264.name = "unavailable_h264_encoder";
ASSERT_TRUE(video::validate_legacy_codec(video::software, video::format_mpeg2));
EXPECT_TRUE(video::software.mpeg2[video::encoder_t::PASSED]);
}
/**
* @brief The software backend probes H.263+ even when its H.264 encoder is unavailable.
*/
TEST_F(PlatformTestSuite, SoftwareEncoderSupportsForcedH263Plus) {
const auto h264_name = video::software.h264.name;
auto restore = util::fail_guard([&] {
video::software.h264.name = h264_name;
});
video::software.h264.name = "unavailable_h264_encoder";
ASSERT_TRUE(video::validate_legacy_codec(video::software, video::format_h263p));
EXPECT_TRUE(video::software.h263p[video::encoder_t::PASSED]);
}
struct FramerateX100Test: BaseTest, testing::WithParamInterface<std::tuple<std::int32_t, AVRational>> {};
TEST_P(FramerateX100Test, Run) {
+184
View File
@@ -0,0 +1,184 @@
/**
* @file tests/unit/test_video_capture_groups.cpp
* @brief Regressions for capture groups with mixed encoder backends.
*/
// test includes
#include "../tests_common.h"
// standard includes
#include <array>
#include <cstdint>
#include <memory>
#include <vector>
// local includes
#include <src/video.h>
#include <src/video_capture_groups.h>
namespace {
/**
* @brief Capture context whose backend identity and pending frames must stay isolated.
*/
struct capture_context_t {
int backend = 0; ///< Identity assigned by the capture backend.
std::vector<int> pending_frames; ///< Frames waiting only for this group's clients.
};
/**
* @brief Exercise software-first and hardware-first session arrival orders.
*/
class CaptureGroupOrderTest: public BaseTest, public testing::WithParamInterface<bool> {};
} // namespace
/**
* @brief Sessions on different backends never inherit the first session's capture context.
*/
TEST_P(CaptureGroupOrderTest, SeparatesBackendsAndRetainsOtherClientsAfterOneLeaves) {
int starts = 0;
int stops = 0;
video::capture_group_pool_t<capture_context_t> groups {
[&starts](auto &) {
++starts;
return 0;
},
[&stops](auto &) {
++stops;
},
};
video::encoder_t hardware {};
video::encoder_t software {};
const auto *first_encoder = GetParam() ? &software : &hardware;
const auto *second_encoder = GetParam() ? &hardware : &software;
auto first = groups.ref(first_encoder);
auto second = groups.ref(second_encoder);
ASSERT_TRUE(first);
ASSERT_TRUE(second);
EXPECT_NE(first.get(), second.get());
first->backend = 1;
second->backend = 2;
first->pending_frames.push_back(10);
second->pending_frames.push_back(20);
auto same_backend = groups.ref(first_encoder);
EXPECT_EQ(same_backend.get(), first.get());
EXPECT_EQ(starts, 2);
first = {};
EXPECT_EQ(stops, 0);
EXPECT_EQ(same_backend->pending_frames, std::vector<int> {10});
same_backend = {};
EXPECT_EQ(stops, 1);
EXPECT_EQ(second->backend, 2);
EXPECT_EQ(second->pending_frames, std::vector<int> {20});
second = {};
EXPECT_EQ(stops, 2);
auto restarted = groups.ref(first_encoder);
EXPECT_EQ(starts, 3);
EXPECT_TRUE(restarted->pending_frames.empty());
EXPECT_EQ(restarted->backend, 0);
EXPECT_FALSE(groups.ref(nullptr));
}
INSTANTIATE_TEST_SUITE_P(SessionArrivalOrder, CaptureGroupOrderTest, testing::Bool());
/**
* @brief A monitor request reaches every active group after its raw event has been consumed.
*/
TEST(VideoCaptureMonitorTest, BroadcastsRequestsAndResetsBetweenStreamEpochs) {
video::display_switch_state_t state;
auto mailbox = std::make_shared<safe::mail_raw_t>();
auto request = mailbox->event<int>("monitor");
state.start_worker();
state.start_worker();
request->raise(2);
const auto hardware = state.poll(request);
const auto software = state.poll(request);
ASSERT_TRUE(hardware.index);
EXPECT_EQ(*hardware.index, 2);
EXPECT_EQ(software.index, hardware.index);
EXPECT_EQ(software.generation, hardware.generation);
EXPECT_FALSE(request->peek());
request->raise(0);
EXPECT_GT(state.poll(request).generation, software.generation);
state.start_worker();
EXPECT_EQ(state.poll(request).index, 0);
state.stop_worker();
state.stop_worker();
state.stop_worker();
state.start_worker();
EXPECT_FALSE(state.poll(request).index);
state.stop_worker();
}
/**
* @brief A capture reinit preserves the selected output when display ordering changes.
*/
TEST(VideoCaptureMonitorTest, EachWorkerAppliesARequestOnlyOnce) {
video::display_switch_state_t state;
auto mailbox = std::make_shared<safe::mail_raw_t>();
auto request = mailbox->event<int>("monitor");
state.start_worker();
state.start_worker();
std::uint64_t hardware_generation = 0;
std::uint64_t software_generation = 0;
int hardware_index = 0;
int software_index = 0;
state.poll(request).apply(hardware_index, 2, hardware_generation);
EXPECT_EQ(hardware_index, 0);
request->raise(1);
state.poll(request).apply(hardware_index, 2, hardware_generation);
ASSERT_EQ(hardware_index, 1);
state.poll(request).apply(software_index, 0, software_generation);
EXPECT_EQ(software_generation, 0);
state.poll(request).apply(software_index, 2, software_generation);
ASSERT_EQ(software_index, 1);
EXPECT_EQ(software_generation, hardware_generation);
// The selected output moved from position 1 to position 0 in the refreshed list.
hardware_index = 0;
state.poll(request).apply(hardware_index, 2, hardware_generation);
EXPECT_EQ(hardware_index, 0);
EXPECT_EQ(software_index, 1);
request->raise(4);
state.poll(request).apply(hardware_index, 2, hardware_generation);
EXPECT_EQ(hardware_index, 1);
EXPECT_GT(hardware_generation, software_generation);
state.stop_worker();
state.stop_worker();
}
/**
* @brief Failed capture startup destroys its context and permits a fresh retry.
*/
TEST(VideoCaptureGroupTest, CleansUpFailedStartupBeforeRetry) {
/**
* @brief Track resources owned by a capture worker during startup and shutdown.
*/
struct context_t {
std::shared_ptr<int> lifetime; ///< Resource whose lifetime follows the capture context.
};
auto resource = std::make_shared<int>(1);
int starts = 0;
int stops = 0;
video::capture_group_pool_t<context_t> groups {
[&resource, &starts](auto &context) {
context.lifetime = resource;
return ++starts == 1 ? -1 : 0;
},
[&stops](auto &) {
++stops;
},
};
video::encoder_t encoder {};
EXPECT_FALSE(groups.ref(&encoder));
EXPECT_EQ(resource.use_count(), 1);
EXPECT_EQ(stops, 0);
auto retry = groups.ref(&encoder);
ASSERT_TRUE(retry);
EXPECT_EQ(resource.use_count(), 2);
retry = {};
EXPECT_EQ(stops, 1);
EXPECT_EQ(resource.use_count(), 1);
}
+21
View File
@@ -1,6 +1,7 @@
import { mount } from '@vue/test-utils'
import { describe, expect, it } from 'vitest'
import configTabs from '../../src_assets/common/assets/web/configs/config_tabs.json'
import DisplayDeviceOptions from '../../src_assets/common/assets/web/configs/tabs/audiovideo/DisplayDeviceOptions.vue'
import Advanced from '../../src_assets/common/assets/web/configs/tabs/Advanced.vue'
import General from '../../src_assets/common/assets/web/configs/tabs/General.vue'
@@ -133,6 +134,26 @@ describe('network configuration', () => {
})
})
describe('legacy codec configuration', () => {
it.each(['mpeg2_mode', 'h263p_mode'])('loads the default and updates %s for each advertised mode', async key => {
const config = structuredClone(configTabs.find(tab => tab.id === 'advanced').options)
const wrapper = mount(Advanced, {
props: { platform: 'linux', config },
global: globalOptions,
})
const select = wrapper.get(`#${key}`)
expect(config[key]).toBe(0)
expect(select.element.value).toBe('0')
expect(select.findAll('option').map(option => option.attributes('value'))).toEqual(['0', '1', '2'])
for (const value of ['2', '1', '0']) {
await select.setValue(value)
expect(config[key]).toBe(value)
}
})
})
describe('FEC configuration', () => {
it.each([0, 1, 20, 99, 100])('accepts %i percent and updates the configuration', async percentage => {
const config = { fec_percentage: 20 }