{{ $t('config.capture') }}
diff --git a/src_assets/common/assets/web/public/assets/locale/en.json b/src_assets/common/assets/web/public/assets/locale/en.json
index b914ed17d..b43f200d7 100644
--- a/src_assets/common/assets/web/public/assets/locale/en.json
+++ b/src_assets/common/assets/web/public/assets/locale/en.json
@@ -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",
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index d71406ba6..7c35ab70a 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -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")
diff --git a/tests/unit/platform/linux/test_display_geometry.cpp b/tests/unit/platform/linux/test_display_geometry.cpp
index 202f5d7a3..8a1812f9b 100644
--- a/tests/unit/platform/linux/test_display_geometry.cpp
+++ b/tests/unit/platform/linux/test_display_geometry.cpp
@@ -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);
diff --git a/tests/unit/test_legacy_codec_roundtrip.cpp b/tests/unit/test_legacy_codec_roundtrip.cpp
new file mode 100644
index 000000000..b16480617
--- /dev/null
+++ b/tests/unit/test_legacy_codec_roundtrip.cpp
@@ -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
+#include
+#include
+#include
+#include
+#include
+
+// lib includes
+extern "C" {
+#include
+}
+
+// local includes
+#include
+#include
+
+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 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 make_encode_session(platf::display_t *display, const encoder_t &encoder, const config_t &config, int width, int height, std::unique_ptr 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 &packets, stream::session_t *channel_data, std::optional 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 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 make_avcodec_encode_device(platf::pix_fmt_e format) override {
+ return std::make_unique();
+ }
+ };
+
+ /**
+ * @brief Run the same codec transport contract for MPEG-2 and H.263+.
+ */
+ class LegacyCodecRoundTripTest: public BaseTest, public testing::WithParamInterface {};
+} // 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();
+ auto packets = mailbox->queue("video");
+ std::vector pixels(static_cast(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(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(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));
diff --git a/tests/unit/test_legacy_codec_selection.cpp b/tests/unit/test_legacy_codec_selection.cpp
new file mode 100644
index 000000000..25f1dde02
--- /dev/null
+++ b/tests/unit/test_legacy_codec_selection.cpp
@@ -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
+#include
+#include
+
+// lib includes
+extern "C" {
+#include
+}
+
+// local includes
+#include
+#include
+
+/**
+ * @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 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 {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(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));
+}
diff --git a/tests/unit/test_nvhttp_codec_flags.cpp b/tests/unit/test_nvhttp_codec_flags.cpp
index 2c6336ebf..565c8ea7a 100644
--- a/tests/unit/test_nvhttp_codec_flags.cpp
+++ b/tests/unit/test_nvhttp_codec_flags.cpp
@@ -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 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(SCM_MPEG2 | SCM_H263P));
+}
diff --git a/tests/unit/test_rtsp.cpp b/tests/unit/test_rtsp.cpp
index fa610b4a4..8bd935e80 100644
--- a/tests/unit/test_rtsp.cpp
+++ b/tests/unit/test_rtsp.cpp
@@ -12,6 +12,7 @@
// standard includes
#include
+#include
#include
#include
#include
@@ -24,7 +25,9 @@ extern "C" {
// local includes
#include
+#include
#include
+#include
/**
* @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;
+ }
+}
diff --git a/tests/unit/test_video.cpp b/tests/unit/test_video.cpp
index 5476aeb3e..82630928e 100644
--- a/tests/unit/test_video.cpp
+++ b/tests/unit/test_video.cpp
@@ -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 {
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> {};
TEST_P(FramerateX100Test, Run) {
diff --git a/tests/unit/test_video_capture_groups.cpp b/tests/unit/test_video_capture_groups.cpp
new file mode 100644
index 000000000..091ea8c4d
--- /dev/null
+++ b/tests/unit/test_video_capture_groups.cpp
@@ -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
+#include
+#include
+#include
+
+// local includes
+#include
+#include
+
+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 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 {};
+} // 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 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 {10});
+ same_backend = {};
+ EXPECT_EQ(stops, 1);
+ EXPECT_EQ(second->backend, 2);
+ EXPECT_EQ(second->pending_frames, std::vector {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();
+ auto request = mailbox->event("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();
+ auto request = mailbox->event("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 lifetime; ///< Resource whose lifetime follows the capture context.
+ };
+
+ auto resource = std::make_shared(1);
+ int starts = 0;
+ int stops = 0;
+ video::capture_group_pool_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);
+}
diff --git a/tests/web/Configuration.test.js b/tests/web/Configuration.test.js
index 04f7a2aa1..78d2aa421 100644
--- a/tests/web/Configuration.test.js
+++ b/tests/web/Configuration.test.js
@@ -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 }