QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
MockVideoStreamServer.cc
Go to the documentation of this file.
1#include <gst/gst.h>
2
3#ifdef QGC_GST_RTSP_SERVER
4#include <glib.h>
5// gdbusintrospection.h, which rtsp-server.h pulls in, has a `signals` member that collides with Qt's `signals`
6// keyword macro (the app target's precompiled header defines it first).
7#pragma push_macro("signals")
8#undef signals
9#include <gst/rtsp-server/rtsp-server.h>
10#pragma pop_macro("signals")
11#endif
12
13#include "GstScoped.h"
15#include "QGCLoggingCategory.h"
16
17QGC_LOGGING_CATEGORY(MockVideoStreamServerLog, "VideoManager.MockVideoStreamServer")
18
19namespace {
20
21// Shared test pattern source. videotestsrc's "ball" pattern makes motion obvious so a
22// stalled pipeline is easy to spot by eye. 8-bit 4:2:0, as cameras send: left to choose, an
23// encoder takes its richest format, which for a Windows x265enc is 12-bit 4:4:4.
24constexpr const char* kTestSource =
25 "videotestsrc is-live=true pattern=ball ! "
26 "video/x-raw,width=1280,height=720,framerate=30/1 ! "
27 "videoconvert ! video/x-raw,format=I420";
28
29// SPS and PPS ahead of every keyframe, which a receiver joining an MPEG-TS stream needs (RTP payloaders insert them
30// themselves): openh264enc sends them only with the first.
31constexpr const char* kH264InBandHeaders = "h264parse config-interval=-1";
32
33// Receivers join mid-stream and wait for the next keyframe, so the encoders key every second. Their fastest settings
34// keep a 720p encode real-time on a loaded CI runner; x265's medium preset and 250-frame default GOP do not.
35// H.264 prefers openh264enc, which is BSD-licensed and in the plugin allowlist, so every platform ships it; x264enc and
36// x265enc are GPL, so only a desktop GStreamer that installs them provides them, and mobile builds never bundle them.
37constexpr const char* kOpenH264Encoder = "openh264enc complexity=low rate-control=bitrate bitrate=2000000 gop-size=30";
38constexpr const char* kX264Encoder = "x264enc tune=zerolatency speed-preset=ultrafast bitrate=2000 key-int-max=30";
39// No x265 thread pool: its workers run below normal priority, so they starve while every core is busy, and the
40// stream falls to a few frames a second. One thread at normal priority encodes this stream several times real-time.
41constexpr const char* kH265Encoder =
42 "x265enc tune=zerolatency speed-preset=ultrafast bitrate=2000 key-int-max=30 option-string=pools=none";
43
44// The H.264 encoder description for gst_parse_launch, or nullptr when no H.264 encoder is installed.
45const char* h264Encoder()
46{
47 if (GStreamer::hasElementFactory("openh264enc")) {
48 return kOpenH264Encoder;
49 }
50 if (GStreamer::hasElementFactory("x264enc")) {
51 return kX264Encoder;
52 }
53 return nullptr;
54}
55
56// GStreamer init is owned by QGC's central VideoBackend/GStreamer::initialize() path
57// (environment prep, static plugin registration, logging). Never call gst_init() here —
58// running it first would bypass that setup and turn the central init into a no-op.
59bool gstInitialized()
60{
61 if (!gst_is_initialized()) {
62 qCWarning(MockVideoStreamServerLog)
63 << "GStreamer not initialized; QGC's central GStreamer init must run before serving a mock stream";
64 return false;
65 }
66 return true;
67}
68
69} // namespace
70
75
77{
78 if (!gstInitialized() || !GStreamer::hasElementFactory("videotestsrc")) {
79 return false;
80 }
81#ifndef QGC_GST_RTSP_SERVER
82 if ((type == StreamType::RtspH264) || (type == StreamType::RtspH265)) {
83 return false;
84 }
85#endif
86
87 switch (type) {
90 return h264Encoder() != nullptr;
93 // mpegtsmux and h264parse ship in gst-plugins-bad and can be absent even when the encoder is present.
94 return (h264Encoder() != nullptr) && GStreamer::hasElementFactory("mpegtsmux") &&
98 return GStreamer::hasElementFactory("x265enc");
99 }
100
101 return false;
102}
103
104bool MockVideoStreamServer::start(StreamType type, const QString& host, quint16 port)
105{
106 stop();
107
108 if (!isStreamTypeAvailable(type)) {
109 qCWarning(MockVideoStreamServerLog) << "Requested stream type is not available in this GStreamer install";
110 return false;
111 }
112
113 if ((type == StreamType::RtspH264) || (type == StreamType::RtspH265)) {
114#ifdef QGC_GST_RTSP_SERVER
115 const int boundPort = _startRtsp(type, host, port);
116 if (boundPort <= 0) {
117 return false;
118 }
119 _servedUri = QStringLiteral("rtsp://%1:%2/test").arg(host, QString::number(boundPort));
120 qCDebug(MockVideoStreamServerLog) << "Serving" << _servedUri;
121 return true;
122#else
123 qCWarning(MockVideoStreamServerLog) << "RTSP requested but gst-rtsp-server is not available";
124 return false;
125#endif
126 }
127
128 QString launch;
129 QString uri;
130 const QString portString = QString::number(port);
131 switch (type) {
133 launch = QStringLiteral("%1 ! %2 ! rtph264pay config-interval=1 pt=96 ! udpsink host=%3 port=%4")
134 .arg(kTestSource, h264Encoder(), host, portString);
135 uri = QStringLiteral("udp://%1:%2").arg(host, portString);
136 break;
138 launch = QStringLiteral("%1 ! %2 ! rtph265pay config-interval=1 pt=96 ! udpsink host=%3 port=%4")
139 .arg(kTestSource, kH265Encoder, host, portString);
140 uri = QStringLiteral("udp265://%1:%2").arg(host, portString);
141 break;
143 launch = QStringLiteral("%1 ! %2 ! %3 ! mpegtsmux ! udpsink host=%4 port=%5")
144 .arg(kTestSource, h264Encoder(), kH264InBandHeaders, host, portString);
145 uri = QStringLiteral("mpegts://%1:%2").arg(host, portString);
146 break;
148 launch = QStringLiteral("%1 ! %2 ! %3 ! mpegtsmux ! tcpserversink name=server host=%4 port=%5")
149 .arg(kTestSource, h264Encoder(), kH264InBandHeaders, host, portString);
150 uri = QStringLiteral("tcp://%1:%2").arg(host, portString);
151 break;
154 return false; // handled above
155 }
156
157 if (!_startPipeline(launch)) {
158 return false;
159 }
160
161 if ((type == StreamType::MpegTsTcp) && (port == 0)) {
162 GstElement* const server = gst_bin_get_by_name(GST_BIN(_pipeline), "server");
163 gint boundPort = 0;
164 g_object_get(server, "current-port", &boundPort, nullptr);
165 gst_object_unref(server);
166 uri = QStringLiteral("tcp://%1:%2").arg(host, QString::number(boundPort));
167 }
168
169 _servedUri = uri;
170 qCDebug(MockVideoStreamServerLog) << "Serving" << _servedUri << "via" << launch;
171 return true;
172}
173
174bool MockVideoStreamServer::_startPipeline(const QString& launch)
175{
176 GError* error = nullptr;
177 GstElement* pipeline = gst_parse_launch(launch.toUtf8().constData(), &error);
178 if (error) {
179 qCWarning(MockVideoStreamServerLog) << "Failed to build pipeline:" << error->message;
180 g_error_free(error);
181 if (pipeline) {
182 gst_object_unref(pipeline);
183 }
184 return false;
185 }
186
187 if (gst_element_set_state(pipeline, GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE) {
188 qCWarning(MockVideoStreamServerLog) << "Failed to set pipeline to PLAYING";
189 gst_object_unref(pipeline);
190 return false;
191 }
192
193 _pipeline = pipeline;
194 return true;
195}
196
198{
199 if (_pipeline) {
200 gst_element_set_state(_pipeline, GST_STATE_NULL);
201 gst_object_unref(_pipeline);
202 _pipeline = nullptr;
203 }
204
205#ifdef QGC_GST_RTSP_SERVER
206 _stopRtsp();
207#endif
208
209 _servedUri.clear();
210}
211
212#ifdef QGC_GST_RTSP_SERVER
213int MockVideoStreamServer::_startRtsp(StreamType type, const QString& host, quint16 port)
214{
215 _rtspContext = g_main_context_new();
216
217 GstRTSPServer* server = gst_rtsp_server_new();
218 const QByteArray address = host.toUtf8();
219 const QByteArray service = QByteArray::number(port);
220 gst_rtsp_server_set_address(server, address.constData());
221 gst_rtsp_server_set_service(server, service.constData());
222
223 GstRTSPMountPoints* mounts = gst_rtsp_server_get_mount_points(server);
224 GstRTSPMediaFactory* factory = gst_rtsp_media_factory_new();
225 const QString launch =
226 (type == StreamType::RtspH265)
227 ? QStringLiteral("( %1 ! %2 ! rtph265pay name=pay0 pt=96 )").arg(kTestSource, kH265Encoder)
228 : QStringLiteral("( %1 ! %2 ! rtph264pay name=pay0 pt=96 )").arg(kTestSource, h264Encoder());
229 gst_rtsp_media_factory_set_launch(factory, launch.toUtf8().constData());
230 gst_rtsp_media_factory_set_shared(factory, TRUE);
231 gst_rtsp_mount_points_add_factory(mounts, "/test", factory);
232 g_object_unref(mounts);
233
234 if (gst_rtsp_server_attach(server, _rtspContext) == 0) {
235 qCWarning(MockVideoStreamServerLog) << "Failed to attach RTSP server on port" << port;
236 gst_object_unref(server);
237 g_main_context_unref(_rtspContext);
238 _rtspContext = nullptr;
239 return 0;
240 }
241 const int boundPort = gst_rtsp_server_get_bound_port(server);
242
243 _rtspServer = server;
244 _rtspLoop = g_main_loop_new(_rtspContext, FALSE);
245
246 _rtspThread = std::thread([this]() {
247 g_main_context_push_thread_default(_rtspContext);
248 g_main_loop_run(_rtspLoop);
249 g_main_context_pop_thread_default(_rtspContext);
250 });
251
252 return boundPort;
253}
254
255void MockVideoStreamServer::_stopRtsp()
256{
257 if (_rtspLoop) {
258 // Quit from inside the loop's context: g_main_loop_run() sets the running flag on entry, so a quit
259 // issued before the thread enters it would be lost and join() would hang.
260 g_main_context_invoke(
261 _rtspContext,
262 [](gpointer loop) -> gboolean {
263 g_main_loop_quit(static_cast<GMainLoop*>(loop));
264 return G_SOURCE_REMOVE;
265 },
266 _rtspLoop);
267 }
268 if (_rtspThread.joinable()) {
269 _rtspThread.join();
270 }
271 if (_rtspLoop) {
272 g_main_loop_unref(_rtspLoop);
273 _rtspLoop = nullptr;
274 }
275 if (_rtspServer) {
276 gst_object_unref(_rtspServer);
277 _rtspServer = nullptr;
278 }
279 if (_rtspContext) {
280 g_main_context_unref(_rtspContext);
281 _rtspContext = nullptr;
282 }
283}
284#endif // QGC_GST_RTSP_SERVER
struct _GstElement GstElement
#define QGC_LOGGING_CATEGORY(name, categoryStr)
@ MpegTsTcp
MPEG-TS over TCP -> tcp://.
@ RtpUdpH265
RTP/H.265 over UDP -> udp265://.
@ RtpUdpH264
RTP/H.264 over UDP -> udp://.
@ MpegTsUdp
MPEG-TS over UDP -> mpegts://.
void stop()
Stop the stream and release all resources. Safe to call when not running.
static bool isStreamTypeAvailable(StreamType type)
bool start(StreamType type, const QString &host, quint16 port)
bool hasElementFactory(const char *name)
Definition GstScoped.h:183