Debian Codegraph @

src/voip/WebRTCSession.cpp

raw symbols SCIP
1 // SPDX-FileCopyrightText: Nheko Contributors
2 //
3 // SPDX-License-Identifier: GPL-3.0-or-later
4
5 #include <QGuiApplication>
6 #include <QQmlEngine>
7 #include <QQuickItem>
8 #include <algorithm>
9 #include <cctype>
10 #include <chrono>
11 #include <cstdlib>
12 #include <cstring>
13 #include <optional>
14 #include <string_view>
15 #include <thread>
16 #include <utility>
17
18 #include "CallDevices.h"
19 #include "ChatPage.h"
20 #include "Logging.h"
21 #include "UserSettingsPage.h"
22 #include "WebRTCSession.h"
23 #include "voip/ScreenCastPortal.h"
24
25 #ifdef GSTREAMER_AVAILABLE
26 #include "MainWindow.h"
27 extern "C"
28 {
29 #include "gst/gl/gstgldisplay.h"
30 #include "gst/gst.h"
31 #include "gst/sdp/sdp.h"
32
33 #define GST_USE_UNSTABLE_API
34 #include "gst/webrtc/webrtc.h"
35 }
36
37 #if !GST_CHECK_VERSION(1, 20, 0)
38 #define gst_element_request_pad_simple gst_element_get_request_pad
39 #endif
40
41 #endif
42
43 // https://github.com/vector-im/riot-web/issues/10173
44 #define STUN_SERVER "stun://turn.matrix.org:3478"
45
46 using webrtc::CallType;
47 using webrtc::ScreenShareType;
48 using webrtc::State;
49
50 WebRTCSession::WebRTCSession()
51 : devices_(CallDevices::instance())
52 {
53 // qmlRegisterUncreatableMetaObject(webrtc::staticMetaObject,
54 // "im.nheko",
55 // 1,
56 // 0,
57 // "CallType",
58 // QStringLiteral("Can't instantiate enum"));
59
60 // qmlRegisterUncreatableMetaObject(webrtc::staticMetaObject,
61 // "im.nheko",
62 // 1,
63 // 0,
64 // "ScreenShareType",
65 // QStringLiteral("Can't instantiate enum"));
66
67 // qmlRegisterUncreatableMetaObject(webrtc::staticMetaObject,
68 // "im.nheko",
69 // 1,
70 // 0,
71 // "WebRTCState",
72 // QStringLiteral("Can't instantiate enum"));
73
74 connect(this, &WebRTCSession::stateChanged, this, &WebRTCSession::setState);
75 init();
76 }
77
78 bool
79 WebRTCSession::init(std::string *errorMessage)
80 {
81 #ifdef GSTREAMER_AVAILABLE
82 if (initialised_)
83 return true;
84
85 GError *error = nullptr;
86 if (!gst_init_check(nullptr, nullptr, &error)) {
87 std::string strError("WebRTC: failed to initialise GStreamer: ");
88 if (error) {
89 strError += error->message;
90 g_error_free(error);
91 }
92 nhlog::ui()->error(strError);
93 if (errorMessage)
94 *errorMessage = strError;
95 return false;
96 }
97
98 initialised_ = true;
99 gchar *version = gst_version_string();
100 nhlog::ui()->info("WebRTC: initialised {}", version);
101 g_free(version);
102 devices_.init();
103 return true;
104 #else
105 (void)errorMessage;
106 return false;
107 #endif
108 }
109
110 #ifdef GSTREAMER_AVAILABLE
111 namespace {
112
113 std::string localsdp_;
114 std::vector<mtx::events::voip::CallCandidates::Candidate> localcandidates_;
115 bool haveAudioStream_ = false;
116 bool haveVideoStream_ = false;
117 GstPad *localPiPSinkPad_ = nullptr;
118 GstPad *remotePiPSinkPad_ = nullptr;
119
120 gboolean
121 newBusMessage(GstBus *bus G_GNUC_UNUSED, GstMessage *msg, gpointer user_data)
122 {
123 WebRTCSession *session = static_cast<WebRTCSession *>(user_data);
124 switch (GST_MESSAGE_TYPE(msg)) {
125 case GST_MESSAGE_EOS:
126 nhlog::ui()->error("WebRTC: end of stream");
127 session->end();
128 break;
129 case GST_MESSAGE_ERROR:
130 GError *error;
131 gchar *debug;
132 gst_message_parse_error(msg, &error, &debug);
133 nhlog::ui()->error(
134 "WebRTC: error from element {}: {}", GST_OBJECT_NAME(msg->src), error->message);
135 g_clear_error(&error);
136 g_free(debug);
137 session->end();
138 break;
139 default:
140 break;
141 }
142 return TRUE;
143 }
144
145 GstWebRTCSessionDescription *
146 parseSDP(const std::string &sdp, GstWebRTCSDPType type)
147 {
148 GstSDPMessage *msg;
149 gst_sdp_message_new(&msg);
150 if (gst_sdp_message_parse_buffer((guint8 *)sdp.c_str(), static_cast<guint>(sdp.size()), msg) ==
151 GST_SDP_OK) {
152 return gst_webrtc_session_description_new(type, msg);
153 } else {
154 nhlog::ui()->error("WebRTC: failed to parse remote session description");
155 gst_sdp_message_free(msg);
156 return nullptr;
157 }
158 }
159
160 void
161 setLocalDescription(GstPromise *promise, gpointer webrtc)
162 {
163 const GstStructure *reply = gst_promise_get_reply(promise);
164 gboolean isAnswer = gst_structure_id_has_field(reply, g_quark_from_string("answer"));
165 GstWebRTCSessionDescription *gstsdp = nullptr;
166 gst_structure_get(
167 reply, isAnswer ? "answer" : "offer", GST_TYPE_WEBRTC_SESSION_DESCRIPTION, &gstsdp, nullptr);
168 gst_promise_unref(promise);
169 g_signal_emit_by_name(webrtc, "set-local-description", gstsdp, nullptr);
170
171 gchar *sdp = gst_sdp_message_as_text(gstsdp->sdp);
172 localsdp_ = std::string(sdp);
173 g_free(sdp);
174 gst_webrtc_session_description_free(gstsdp);
175
176 nhlog::ui()->debug(
177 "WebRTC: local description set ({}):\n{}", isAnswer ? "answer" : "offer", localsdp_);
178 }
179
180 void
181 createOffer(GstElement *webrtc)
182 {
183 // create-offer first, then set-local-description
184 GstPromise *promise = gst_promise_new_with_change_func(setLocalDescription, webrtc, nullptr);
185 g_signal_emit_by_name(webrtc, "create-offer", nullptr, promise);
186 }
187
188 void
189 createAnswer(GstPromise *promise, gpointer webrtc)
190 {
191 // create-answer first, then set-local-description
192 gst_promise_unref(promise);
193 promise = gst_promise_new_with_change_func(setLocalDescription, webrtc, nullptr);
194 g_signal_emit_by_name(webrtc, "create-answer", nullptr, promise);
195 }
196
197 void
198 iceGatheringStateChanged(GstElement *webrtc,
199 GParamSpec *pspec G_GNUC_UNUSED,
200 gpointer user_data G_GNUC_UNUSED)
201 {
202 GstWebRTCICEGatheringState newState;
203 g_object_get(webrtc, "ice-gathering-state", &newState, nullptr);
204 if (newState == GST_WEBRTC_ICE_GATHERING_STATE_COMPLETE) {
205 nhlog::ui()->debug("WebRTC: GstWebRTCICEGatheringState -> Complete");
206 if (WebRTCSession::instance().isOffering()) {
207 emit WebRTCSession::instance().offerCreated(localsdp_, localcandidates_);
208 emit WebRTCSession::instance().stateChanged(State::OFFERSENT);
209 } else {
210 emit WebRTCSession::instance().answerCreated(localsdp_, localcandidates_);
211 emit WebRTCSession::instance().stateChanged(State::ANSWERSENT);
212 }
213 }
214 }
215
216 void
217 addLocalICECandidate(GstElement *webrtc G_GNUC_UNUSED,
218 guint mlineIndex,
219 gchar *candidate,
220 gpointer G_GNUC_UNUSED)
221 {
222 nhlog::ui()->debug("WebRTC: local candidate: (m-line:{}):{}", mlineIndex, candidate);
223 localcandidates_.push_back({std::string() /*max-bundle*/, (uint16_t)mlineIndex, candidate});
224 }
225
226 void
227 iceConnectionStateChanged(GstElement *webrtc,
228 GParamSpec *pspec G_GNUC_UNUSED,
229 gpointer user_data G_GNUC_UNUSED)
230 {
231 GstWebRTCICEConnectionState newState;
232 g_object_get(webrtc, "ice-connection-state", &newState, nullptr);
233 switch (newState) {
234 case GST_WEBRTC_ICE_CONNECTION_STATE_CHECKING:
235 nhlog::ui()->debug("WebRTC: GstWebRTCICEConnectionState -> Checking");
236 emit WebRTCSession::instance().stateChanged(State::CONNECTING);
237 break;
238 case GST_WEBRTC_ICE_CONNECTION_STATE_FAILED:
239 nhlog::ui()->error("WebRTC: GstWebRTCICEConnectionState -> Failed");
240 emit WebRTCSession::instance().stateChanged(State::ICEFAILED);
241 break;
242 default:
243 break;
244 }
245 }
246
247 // https://gitlab.freedesktop.org/gstreamer/gst-plugins-bad/-/issues/1164
248 struct KeyFrameRequestData
249 {
250 GstElement *pipe = nullptr;
251 GstElement *decodebin = nullptr;
252 gint packetsLost = 0;
253 guint timerid = 0;
254 std::string statsField;
255 } keyFrameRequestData_;
256
257 void
258 sendKeyFrameRequest()
259 {
260 GstPad *sinkpad = gst_element_get_static_pad(keyFrameRequestData_.decodebin, "sink");
261 if (!gst_pad_push_event(sinkpad,
262 gst_event_new_custom(GST_EVENT_CUSTOM_UPSTREAM,
263 gst_structure_new_empty("GstForceKeyUnit"))))
264 nhlog::ui()->error("WebRTC: key frame request failed");
265 else
266 nhlog::ui()->debug("WebRTC: sent key frame request");
267
268 gst_object_unref(sinkpad);
269 }
270
271 void
272 testPacketLoss_(GstPromise *promise, gpointer G_GNUC_UNUSED)
273 {
274 const GstStructure *reply = gst_promise_get_reply(promise);
275 gint packetsLost = 0;
276 GstStructure *rtpStats;
277 if (!gst_structure_get(
278 reply, keyFrameRequestData_.statsField.c_str(), GST_TYPE_STRUCTURE, &rtpStats, nullptr)) {
279 nhlog::ui()->error("WebRTC: get-stats: no field: {}", keyFrameRequestData_.statsField);
280 gst_promise_unref(promise);
281 return;
282 }
283 gst_structure_get_int(rtpStats, "packets-lost", &packetsLost);
284 gst_structure_free(rtpStats);
285 gst_promise_unref(promise);
286 if (packetsLost > keyFrameRequestData_.packetsLost) {
287 nhlog::ui()->debug("WebRTC: inbound video lost packet count: {}", packetsLost);
288 keyFrameRequestData_.packetsLost = packetsLost;
289 sendKeyFrameRequest();
290 }
291 }
292
293 gboolean
294 testPacketLoss(gpointer G_GNUC_UNUSED)
295 {
296 if (keyFrameRequestData_.pipe) {
297 GstElement *webrtc = gst_bin_get_by_name(GST_BIN(keyFrameRequestData_.pipe), "webrtcbin");
298 GstPromise *promise = gst_promise_new_with_change_func(testPacketLoss_, nullptr, nullptr);
299 g_signal_emit_by_name(webrtc, "get-stats", nullptr, promise);
300 gst_object_unref(webrtc);
301 return TRUE;
302 }
303 return FALSE;
304 }
305
306 void
307 setWaitForKeyFrame(GstBin *decodebin G_GNUC_UNUSED, GstElement *element, gpointer G_GNUC_UNUSED)
308 {
309 // Unconditionally enable keyframe wait and requesting keyframes, so that we do that for
310 // every decode, not just vp8 decoding
311 g_object_set(element, "wait-for-keyframe", TRUE, "request-keyframe", TRUE, nullptr);
312 }
313
314 GstElement *
315 newAudioSinkChain(GstElement *pipe)
316 {
317 GstElement *queue = gst_element_factory_make("queue", nullptr);
318 GstElement *convert = gst_element_factory_make("audioconvert", nullptr);
319 GstElement *resample = gst_element_factory_make("audioresample", nullptr);
320 GstElement *sink = gst_element_factory_make("autoaudiosink", nullptr);
321 gst_bin_add_many(GST_BIN(pipe), queue, convert, resample, sink, nullptr);
322 gst_element_link_many(queue, convert, resample, sink, nullptr);
323 gst_element_sync_state_with_parent(queue);
324 gst_element_sync_state_with_parent(convert);
325 gst_element_sync_state_with_parent(resample);
326 gst_element_sync_state_with_parent(sink);
327 return queue;
328 }
329
330 GstElement *
331 newVideoSinkChain(GstElement *pipe)
332 {
333 // use compositor for now; acceleration needs investigation
334 GstElement *queue = gst_element_factory_make("queue", nullptr);
335
336 auto graphicsApi = MainWindow::instance()->graphicsApi();
337 GstElement *compositor = gst_element_factory_make(
338 graphicsApi == QSGRendererInterface::OpenGL ? "compositor" : "d3d11compositor", "compositor");
339 g_object_set(compositor, "background", 1, nullptr);
340 switch (graphicsApi) {
341 case QSGRendererInterface::OpenGL: {
342 GstElement *qmlglsink = gst_element_factory_make("qml6glsink", nullptr);
343 GstElement *glsinkbin = gst_element_factory_make("glsinkbin", nullptr);
344
345 g_object_set(qmlglsink, "widget", WebRTCSession::instance().getVideoItem(), nullptr);
346 g_object_set(glsinkbin, "sink", qmlglsink, nullptr);
347 gst_bin_add_many(GST_BIN(pipe), queue, compositor, glsinkbin, nullptr);
348 gst_element_link_many(queue, compositor, glsinkbin, nullptr);
349
350 gst_element_sync_state_with_parent(queue);
351 gst_element_sync_state_with_parent(compositor);
352 gst_element_sync_state_with_parent(glsinkbin);
353
354 // to propagate context (hopefully)
355 gst_element_set_state(qmlglsink, GST_STATE_READY);
356
357 // Workaround: On wayland, when egl is used, gstreamer might terminate the display
358 // connection. Prevent that by "leaking" a reference to the display. See
359 // https://gitlab.freedesktop.org/gstreamer/gstreamer/-/merge_requests/3743
360 if (QGuiApplication::platformName() == QStringLiteral("wayland")) {
361 auto context = gst_element_get_context(qmlglsink, "gst.gl.GLDisplay");
362 if (context) {
363 GstGLDisplay *display;
364 gst_context_get_gl_display(context, &display);
365 }
366 }
367 } break;
368 case QSGRendererInterface::Direct3D11: {
369 GstElement *d3d11upload = gst_element_factory_make("d3d11upload", nullptr);
370 GstElement *d3d11colorconvert = gst_element_factory_make("d3d11colorconvert", nullptr);
371 GstElement *qmld3d11sink = gst_element_factory_make("qml6d3d11sink", nullptr);
372
373 g_object_set(qmld3d11sink, "widget", WebRTCSession::instance().getVideoItem(), nullptr);
374 gst_bin_add_many(
375 GST_BIN(pipe), queue, d3d11upload, compositor, d3d11colorconvert, qmld3d11sink, nullptr);
376 gst_element_link_many(
377 queue, d3d11upload, compositor, d3d11colorconvert, qmld3d11sink, nullptr);
378
379 gst_element_sync_state_with_parent(queue);
380 gst_element_sync_state_with_parent(compositor);
381 gst_element_sync_state_with_parent(d3d11upload);
382 gst_element_sync_state_with_parent(d3d11colorconvert);
383
384 // to propagate context (hopefully)
385 gst_element_set_state(qmld3d11sink, GST_STATE_READY);
386 } break;
387 default:
388 break;
389 }
390
391 return queue;
392 }
393
394 std::pair<int, int>
395 getResolution(GstPad *pad)
396 {
397 std::pair<int, int> ret;
398 GstCaps *caps = gst_pad_get_current_caps(pad);
399 const GstStructure *s = gst_caps_get_structure(caps, 0);
400 gst_structure_get_int(s, "width", &ret.first);
401 gst_structure_get_int(s, "height", &ret.second);
402 gst_caps_unref(caps);
403 return ret;
404 }
405
406 std::pair<int, int>
407 getResolution(GstElement *pipe, const gchar *elementName, const gchar *padName)
408 {
409 GstElement *element = gst_bin_get_by_name(GST_BIN(pipe), elementName);
410 GstPad *pad = gst_element_get_static_pad(element, padName);
411 auto ret = getResolution(pad);
412 gst_object_unref(pad);
413 gst_object_unref(element);
414 return ret;
415 }
416
417 std::pair<int, int>
418 getPiPDimensions(const std::pair<int, int> &resolution, int fullWidth, double scaleFactor)
419 {
420 double pipWidth = fullWidth * scaleFactor;
421 double pipHeight = static_cast<double>(resolution.second) / resolution.first * pipWidth;
422 return {
423 static_cast<int>(std::ceil(pipWidth)),
424 static_cast<int>(std::ceil(pipHeight)),
425 };
426 }
427
428 void
429 addLocalPiP(GstElement *pipe, const std::pair<int, int> &videoCallSize)
430 {
431 // embed localUser's camera into received video (CallType::VIDEO)
432 // OR embed screen share into received video (CallType::SCREEN)
433 GstElement *tee = gst_bin_get_by_name(GST_BIN(pipe), "videosrctee");
434 if (!tee)
435 return;
436
437 GstElement *queue = gst_element_factory_make("queue", nullptr);
438 gst_bin_add(GST_BIN(pipe), queue);
439 gst_element_link(tee, queue);
440 gst_element_sync_state_with_parent(queue);
441 gst_object_unref(tee);
442
443 GstElement *compositor = gst_bin_get_by_name(GST_BIN(pipe), "compositor");
444 localPiPSinkPad_ = gst_element_request_pad_simple(compositor, "sink_%u");
445 g_object_set(localPiPSinkPad_, "zorder", 2, nullptr);
446
447 bool isVideo = WebRTCSession::instance().callType() == CallType::VIDEO;
448 const gchar *element = isVideo ? "camerafilter" : "screenshare";
449 const gchar *pad = isVideo ? "sink" : "src";
450 auto resolution = getResolution(pipe, element, pad);
451 auto pipSize = getPiPDimensions(resolution, videoCallSize.first, 0.25);
452 nhlog::ui()->debug("WebRTC: local picture-in-picture: {}x{}", pipSize.first, pipSize.second);
453 g_object_set(localPiPSinkPad_, "width", pipSize.first, "height", pipSize.second, nullptr);
454 gint offset = videoCallSize.first / 80;
455 g_object_set(localPiPSinkPad_, "xpos", offset, "ypos", offset, nullptr);
456
457 GstPad *srcpad = gst_element_get_static_pad(queue, "src");
458 if (GST_PAD_LINK_FAILED(gst_pad_link(srcpad, localPiPSinkPad_)))
459 nhlog::ui()->error("WebRTC: failed to link local PiP elements");
460 gst_object_unref(srcpad);
461 gst_object_unref(compositor);
462 }
463
464 void
465 addRemotePiP(GstElement *pipe)
466 {
467 // embed localUser's camera into screen image being shared
468 if (remotePiPSinkPad_) {
469 auto camRes = getResolution(pipe, "camerafilter", "sink");
470 auto shareRes = getResolution(pipe, "screenshare", "src");
471 auto pipSize = getPiPDimensions(camRes, shareRes.first, 0.2);
472 nhlog::ui()->debug(
473 "WebRTC: screen share picture-in-picture: {}x{}", pipSize.first, pipSize.second);
474
475 gint offset = shareRes.first / 100;
476 g_object_set(remotePiPSinkPad_, "zorder", 2, nullptr);
477 g_object_set(remotePiPSinkPad_, "width", pipSize.first, "height", pipSize.second, nullptr);
478 g_object_set(remotePiPSinkPad_,
479 "xpos",
480 shareRes.first - pipSize.first - offset,
481 "ypos",
482 shareRes.second - pipSize.second - offset,
483 nullptr);
484 }
485 }
486
487 void
488 addLocalVideo(GstElement *pipe)
489 {
490 GstElement *queue = newVideoSinkChain(pipe);
491 GstElement *tee = gst_bin_get_by_name(GST_BIN(pipe), "videosrctee");
492 GstPad *srcpad = gst_element_request_pad_simple(tee, "src_%u");
493 GstPad *sinkpad = gst_element_get_static_pad(queue, "sink");
494 if (GST_PAD_LINK_FAILED(gst_pad_link(srcpad, sinkpad)))
495 nhlog::ui()->error("WebRTC: failed to link videosrctee -> video sink chain");
496 gst_object_unref(srcpad);
497 }
498
499 void
500 linkNewPad(GstElement *decodebin, GstPad *newpad, GstElement *pipe)
501 {
502 GstPad *sinkpad = gst_element_get_static_pad(decodebin, "sink");
503 GstCaps *sinkcaps = gst_pad_get_current_caps(sinkpad);
504 const GstStructure *structure = gst_caps_get_structure(sinkcaps, 0);
505
506 gchar *mediaType = nullptr;
507 guint ssrc = 0;
508 gst_structure_get(
509 structure, "media", G_TYPE_STRING, &mediaType, "ssrc", G_TYPE_UINT, &ssrc, nullptr);
510 gst_caps_unref(sinkcaps);
511 gst_object_unref(sinkpad);
512
513 WebRTCSession *session = &WebRTCSession::instance();
514 GstElement *queue = nullptr;
515 if (!std::strcmp(mediaType, "audio")) {
516 nhlog::ui()->debug("WebRTC: received incoming audio stream");
517 haveAudioStream_ = true;
518 queue = newAudioSinkChain(pipe);
519 } else if (!std::strcmp(mediaType, "video")) {
520 nhlog::ui()->debug("WebRTC: received incoming video stream");
521 if (!session->getVideoItem()) {
522 g_free(mediaType);
523 nhlog::ui()->error("WebRTC: video call item not set");
524 return;
525 }
526 haveVideoStream_ = true;
527 keyFrameRequestData_.statsField =
528 std::string("rtp-inbound-stream-stats_") + std::to_string(ssrc);
529 queue = newVideoSinkChain(pipe);
530 auto videoCallSize = getResolution(newpad);
531 nhlog::ui()->info(
532 "WebRTC: incoming video resolution: {}x{}", videoCallSize.first, videoCallSize.second);
533 addLocalPiP(pipe, videoCallSize);
534 } else {
535 g_free(mediaType);
536 nhlog::ui()->error("WebRTC: unknown pad type: {}", GST_PAD_NAME(newpad));
537 return;
538 }
539
540 GstPad *queuepad = gst_element_get_static_pad(queue, "sink");
541 if (queuepad) {
542 if (GST_PAD_LINK_FAILED(gst_pad_link(newpad, queuepad)))
543 nhlog::ui()->error("WebRTC: unable to link new pad");
544 else {
545 if (session->callType() == CallType::VOICE ||
546 (haveAudioStream_ && (haveVideoStream_ || session->isRemoteVideoRecvOnly()))) {
547 emit session->stateChanged(State::CONNECTED);
548 if (haveVideoStream_) {
549 keyFrameRequestData_.pipe = pipe;
550 keyFrameRequestData_.decodebin = decodebin;
551 keyFrameRequestData_.timerid =
552 g_timeout_add_seconds(3, testPacketLoss, nullptr);
553 }
554 addRemotePiP(pipe);
555 if (session->isRemoteVideoRecvOnly())
556 addLocalVideo(pipe);
557 }
558 }
559 gst_object_unref(queuepad);
560 }
561 g_free(mediaType);
562
563 GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS(GST_BIN(pipe), GST_DEBUG_GRAPH_SHOW_VERBOSE, "newpad");
564 }
565
566 void
567 addDecodeBin(GstElement *webrtc G_GNUC_UNUSED, GstPad *newpad, GstElement *pipe)
568 {
569 if (GST_PAD_DIRECTION(newpad) != GST_PAD_SRC)
570 return;
571
572 nhlog::ui()->debug("WebRTC: received incoming stream");
573 GstElement *decodebin = gst_element_factory_make("decodebin", nullptr);
574 // hardware decoding needs investigation; eg rendering fails if vaapi plugin installed
575 g_object_set(decodebin, "force-sw-decoders", TRUE, nullptr);
576 g_signal_connect(decodebin, "pad-added", G_CALLBACK(linkNewPad), pipe);
577 g_signal_connect(decodebin, "element-added", G_CALLBACK(setWaitForKeyFrame), nullptr);
578 gst_bin_add(GST_BIN(pipe), decodebin);
579 gst_element_sync_state_with_parent(decodebin);
580 GstPad *sinkpad = gst_element_get_static_pad(decodebin, "sink");
581 if (GST_PAD_LINK_FAILED(gst_pad_link(newpad, sinkpad)))
582 nhlog::ui()->error("WebRTC: unable to link decodebin");
583 gst_object_unref(sinkpad);
584 }
585
586 bool
587 contains(std::string_view str1, std::string_view str2)
588 {
589 return std::search(str1.cbegin(),
590 str1.cend(),
591 str2.cbegin(),
592 str2.cend(),
593 [](unsigned char c1, unsigned char c2) {
594 return std::tolower(c1) == std::tolower(c2);
595 }) != str1.cend();
596 }
597
598 bool
599 getMediaAttributes(const GstSDPMessage *sdp,
600 const char *mediaType,
601 const char *encoding,
602 int &payloadType,
603 bool &recvOnly,
604 bool &sendOnly)
605 {
606 payloadType = -1;
607 recvOnly = false;
608 sendOnly = false;
609 for (guint mlineIndex = 0; mlineIndex < gst_sdp_message_medias_len(sdp); ++mlineIndex) {
610 const GstSDPMedia *media = gst_sdp_message_get_media(sdp, mlineIndex);
611 if (!std::strcmp(gst_sdp_media_get_media(media), mediaType)) {
612 recvOnly = gst_sdp_media_get_attribute_val(media, "recvonly") != nullptr;
613 sendOnly = gst_sdp_media_get_attribute_val(media, "sendonly") != nullptr;
614 const gchar *rtpval = nullptr;
615 for (guint n = 0; n == 0 || rtpval; ++n) {
616 rtpval = gst_sdp_media_get_attribute_val_n(media, "rtpmap", n);
617 if (rtpval && contains(rtpval, encoding)) {
618 payloadType = std::atoi(rtpval);
619 break;
620 }
621 }
622 return true;
623 }
624 }
625 return false;
626 }
627 }
628
629 bool
630 WebRTCSession::havePlugins(bool isVideo,
631 bool isScreenshare,
632 ScreenShareType screenShareType,
633 std::string *errorMessage)
634 {
635 if (!initialised_ && !init(errorMessage))
636 return false;
637
638 static constexpr std::initializer_list<const char *> audio_elements = {"audioconvert",
639 "audioresample",
640 "autoaudiosink",
641 "capsfilter",
642 "decodebin",
643 "opusenc",
644 "queue",
645 "rtpopuspay",
646 "volume",
647 "webrtcbin",
648 "nicesrc",
649 "nicesink"};
650
651 static constexpr std::initializer_list<const char *> gl_video_elements = {
652 "compositor",
653 "glsinkbin",
654 "glupload",
655 "qml6glsink",
656 "rtpvp8pay",
657 "tee",
658 "videoconvert",
659 "videoscale",
660 "vp8enc",
661 };
662
663 static constexpr std::initializer_list<const char *> d3d11_video_elements = {
664 "compositor",
665 "d3d11colorconvert",
666 "d3d11videosink",
667 "d3d11upload",
668 "qml6d3d11sink",
669 "rtpvp8pay",
670 "tee",
671 "videoconvert",
672 "videoscale",
673 "vp8enc",
674 };
675
676 std::string strError("Missing GStreamer elements: ");
677 GstRegistry *registry = gst_registry_get();
678
679 auto check_plugins = [&strError,
680 registry](const std::initializer_list<const char *> &elements) {
681 bool havePlugins = true;
682 for (const auto &element : elements) {
683 GstPluginFeature *plugin =
684 gst_registry_find_feature(registry, element, GST_TYPE_ELEMENT_FACTORY);
685 if (!plugin) {
686 havePlugins = false;
687 strError += std::string(element) + " ";
688 continue;
689 }
690 gst_object_unref(plugin);
691 }
692
693 return havePlugins;
694 };
695
696 haveVoicePlugins_ = check_plugins(audio_elements);
697
698 // check both elements at once
699 if (isVideo) {
700 switch (MainWindow::instance()->graphicsApi()) {
701 case QSGRendererInterface::OpenGL:
702 haveVideoPlugins_ = check_plugins(gl_video_elements);
703 break;
704 case QSGRendererInterface::Direct3D11:
705 haveVideoPlugins_ = check_plugins(d3d11_video_elements);
706 break;
707 default:
708 haveVideoPlugins_ = false;
709 break;
710 }
711 }
712
713 bool haveScreensharePlugins = false;
714 if (isScreenshare) {
715 haveScreensharePlugins = check_plugins({"videorate"});
716 if (haveScreensharePlugins) {
717 if (QGuiApplication::platformName() == QStringLiteral("wayland")) {
718 haveScreensharePlugins = check_plugins({"waylandsink"});
719 } else if (QGuiApplication::platformName() == QStringLiteral("windows")) {
720 haveScreensharePlugins = check_plugins({"d3d11videosink"});
721 } else {
722 haveScreensharePlugins = check_plugins({"ximagesink"});
723 }
724 }
725 if (haveScreensharePlugins) {
726 if (screenShareType == ScreenShareType::X11) {
727 haveScreensharePlugins = check_plugins({"ximagesrc"});
728 } else if (screenShareType == ScreenShareType::D3D11) {
729 haveScreensharePlugins =
730 check_plugins({"d3d11screencapturesrc", "d3d11download", "d3d11convert"});
731 } else {
732 haveScreensharePlugins = check_plugins({"pipewiresrc"});
733 }
734 }
735 }
736
737 if (!haveVoicePlugins_ || (isVideo && !haveVideoPlugins_) ||
738 (isScreenshare && !haveScreensharePlugins)) {
739 nhlog::ui()->error(strError);
740 if (errorMessage)
741 *errorMessage = strError;
742 return false;
743 }
744
745 if (isVideo || isScreenshare) {
746 switch (MainWindow::instance()->graphicsApi()) {
747 case QSGRendererInterface::OpenGL: {
748 // load qmlglsink to register GStreamer's GstGLVideoItem QML type
749 GstElement *qmlglsink = gst_element_factory_make("qml6glsink", nullptr);
750 gst_object_unref(qmlglsink);
751 } break;
752 case QSGRendererInterface::Direct3D11: {
753 GstElement *qmld3d11sink = gst_element_factory_make("qml6d3d11sink", nullptr);
754 gst_object_unref(qmld3d11sink);
755 } break;
756 default:
757 break;
758 }
759 }
760 return true;
761 }
762
763 bool
764 WebRTCSession::createOffer(CallType callType,
765 ScreenShareType screenShareType,
766 uint32_t shareWindowId)
767 {
768 clear();
769 isOffering_ = true;
770 callType_ = callType;
771 screenShareType_ = screenShareType;
772 shareWindowId_ = shareWindowId;
773
774 // opus and vp8 rtp payload types must be defined dynamically
775 // therefore from the range [96-127]
776 // see for example https://tools.ietf.org/html/rfc7587
777 constexpr int opusPayloadType = 111;
778 constexpr int vp8PayloadType = 96;
779 return startPipeline(opusPayloadType, vp8PayloadType);
780 }
781
782 bool
783 WebRTCSession::acceptOffer(const std::string &sdp)
784 {
785 nhlog::ui()->debug("WebRTC: received offer:\n{}", sdp);
786 if (state_ != State::DISCONNECTED)
787 return false;
788
789 clear();
790 GstWebRTCSessionDescription *offer = parseSDP(sdp, GST_WEBRTC_SDP_TYPE_OFFER);
791 if (!offer)
792 return false;
793
794 int opusPayloadType;
795 bool recvOnly;
796 bool sendOnly;
797 if (getMediaAttributes(offer->sdp, "audio", "opus", opusPayloadType, recvOnly, sendOnly)) {
798 if (opusPayloadType == -1) {
799 nhlog::ui()->error("WebRTC: remote audio offer - no opus encoding");
800 gst_webrtc_session_description_free(offer);
801 return false;
802 }
803 } else {
804 nhlog::ui()->error("WebRTC: remote offer - no audio media");
805 gst_webrtc_session_description_free(offer);
806 return false;
807 }
808
809 int vp8PayloadType;
810 bool isVideo = getMediaAttributes(
811 offer->sdp, "video", "vp8", vp8PayloadType, isRemoteVideoRecvOnly_, isRemoteVideoSendOnly_);
812 if (isVideo && vp8PayloadType == -1) {
813 nhlog::ui()->error("WebRTC: remote video offer - no vp8 encoding");
814 gst_webrtc_session_description_free(offer);
815 return false;
816 }
817 callType_ = isVideo ? CallType::VIDEO : CallType::VOICE;
818
819 if (!startPipeline(opusPayloadType, vp8PayloadType)) {
820 gst_webrtc_session_description_free(offer);
821 return false;
822 }
823
824 // avoid a race that sometimes leaves the generated answer without media tracks (a=ssrc
825 // lines)
826 std::this_thread::sleep_for(std::chrono::milliseconds(200));
827
828 // set-remote-description first, then create-answer
829 GstPromise *promise = gst_promise_new_with_change_func(createAnswer, webrtc_, nullptr);
830 g_signal_emit_by_name(webrtc_, "set-remote-description", offer, promise);
831 gst_webrtc_session_description_free(offer);
832
833 GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS(GST_BIN(pipe_), GST_DEBUG_GRAPH_SHOW_VERBOSE, "accept");
834
835 return true;
836 }
837
838 bool
839 WebRTCSession::acceptNegotiation(const std::string &sdp)
840 {
841 nhlog::ui()->debug("WebRTC: received negotiation offer:\n{}", sdp);
842 if (state_ == State::DISCONNECTED)
843 return false;
844 return false;
845 }
846
847 bool
848 WebRTCSession::acceptAnswer(const std::string &sdp)
849 {
850 nhlog::ui()->debug("WebRTC: received answer:\n{}", sdp);
851 if (state_ != State::OFFERSENT)
852 return false;
853
854 GstWebRTCSessionDescription *answer = parseSDP(sdp, GST_WEBRTC_SDP_TYPE_ANSWER);
855 if (!answer) {
856 end();
857 return false;
858 }
859
860 if (callType_ != CallType::VOICE) {
861 int unused;
862 if (!getMediaAttributes(
863 answer->sdp, "video", "vp8", unused, isRemoteVideoRecvOnly_, isRemoteVideoSendOnly_))
864 isRemoteVideoRecvOnly_ = true;
865 }
866
867 g_signal_emit_by_name(webrtc_, "set-remote-description", answer, nullptr);
868 gst_webrtc_session_description_free(answer);
869 return true;
870 }
871
872 void
873 WebRTCSession::acceptICECandidates(
874 const std::vector<mtx::events::voip::CallCandidates::Candidate> &candidates)
875 {
876 if (state_ >= State::INITIATED) {
877 for (const auto &c : candidates) {
878 nhlog::ui()->debug(
879 "WebRTC: remote candidate: (m-line:{}):{}", c.sdpMLineIndex, c.candidate);
880 if (!c.candidate.empty()) {
881 g_signal_emit_by_name(
882 webrtc_, "add-ice-candidate", c.sdpMLineIndex, c.candidate.c_str());
883 }
884 }
885 }
886 }
887
888 bool
889 WebRTCSession::startPipeline(int opusPayloadType, int vp8PayloadType)
890 {
891 if (state_ != State::DISCONNECTED)
892 return false;
893
894 emit stateChanged(State::INITIATING);
895
896 if (!createPipeline(opusPayloadType, vp8PayloadType)) {
897 end();
898 return false;
899 }
900
901 webrtc_ = gst_bin_get_by_name(GST_BIN(pipe_), "webrtcbin");
902
903 if (ChatPage::instance()->userSettings()->useStunServer()) {
904 nhlog::ui()->info("WebRTC: setting STUN server: {}", STUN_SERVER);
905 g_object_set(webrtc_, "stun-server", STUN_SERVER, nullptr);
906 }
907
908 for (const auto &uri : turnServers_) {
909 nhlog::ui()->info("WebRTC: setting TURN server: {}", uri);
910 gboolean udata;
911 g_signal_emit_by_name(webrtc_, "add-turn-server", uri.c_str(), (gpointer)(&udata));
912 }
913 if (turnServers_.empty())
914 nhlog::ui()->warn("WebRTC: no TURN server provided");
915
916 // generate the offer when the pipeline goes to PLAYING
917 if (isOffering_)
918 g_signal_connect(webrtc_, "on-negotiation-needed", G_CALLBACK(::createOffer), nullptr);
919
920 // on-ice-candidate is emitted when a local ICE candidate has been gathered
921 g_signal_connect(webrtc_, "on-ice-candidate", G_CALLBACK(addLocalICECandidate), nullptr);
922
923 // capture ICE failure
924 g_signal_connect(
925 webrtc_, "notify::ice-connection-state", G_CALLBACK(iceConnectionStateChanged), nullptr);
926
927 // incoming streams trigger pad-added
928 gst_element_set_state(pipe_, GST_STATE_READY);
929 g_signal_connect(webrtc_, "pad-added", G_CALLBACK(addDecodeBin), pipe_);
930
931 // capture ICE gathering completion
932 g_signal_connect(
933 webrtc_, "notify::ice-gathering-state", G_CALLBACK(iceGatheringStateChanged), nullptr);
934
935 // webrtcbin lifetime is the same as that of the pipeline
936 gst_object_unref(webrtc_);
937
938 // start the pipeline
939 GstStateChangeReturn ret = gst_element_set_state(pipe_, GST_STATE_PLAYING);
940 if (ret == GST_STATE_CHANGE_FAILURE) {
941 nhlog::ui()->error("WebRTC: unable to start pipeline");
942 end();
943 return false;
944 }
945
946 GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS(GST_BIN(pipe_), GST_DEBUG_GRAPH_SHOW_VERBOSE, "start");
947
948 GstBus *bus = gst_pipeline_get_bus(GST_PIPELINE(pipe_));
949 busWatchId_ = gst_bus_add_watch(bus, newBusMessage, this);
950 gst_object_unref(bus);
951 emit stateChanged(State::INITIATED);
952 return true;
953 }
954
955 bool
956 WebRTCSession::createPipeline(int opusPayloadType, int vp8PayloadType)
957 {
958 GstDevice *device = devices_.audioDevice();
959 if (!device)
960 return false;
961
962 GstElement *source = gst_device_create_element(device, nullptr);
963 GstElement *volume = gst_element_factory_make("volume", "srclevel");
964 GstElement *convert = gst_element_factory_make("audioconvert", nullptr);
965 GstElement *resample = gst_element_factory_make("audioresample", nullptr);
966 GstElement *queue1 = gst_element_factory_make("queue", nullptr);
967 GstElement *opusenc = gst_element_factory_make("opusenc", nullptr);
968 GstElement *rtp = gst_element_factory_make("rtpopuspay", nullptr);
969 GstElement *queue2 = gst_element_factory_make("queue", nullptr);
970 GstElement *capsfilter = gst_element_factory_make("capsfilter", nullptr);
971
972 GstCaps *rtpcaps = gst_caps_new_simple("application/x-rtp",
973 "media",
974 G_TYPE_STRING,
975 "audio",
976 "encoding-name",
977 G_TYPE_STRING,
978 "OPUS",
979 "payload",
980 G_TYPE_INT,
981 opusPayloadType,
982 nullptr);
983 g_object_set(capsfilter, "caps", rtpcaps, nullptr);
984 gst_caps_unref(rtpcaps);
985
986 GstElement *webrtcbin = gst_element_factory_make("webrtcbin", "webrtcbin");
987 g_object_set(webrtcbin, "bundle-policy", GST_WEBRTC_BUNDLE_POLICY_MAX_BUNDLE, nullptr);
988
989 pipe_ = gst_pipeline_new(nullptr);
990 gst_bin_add_many(GST_BIN(pipe_),
991 source,
992 volume,
993 convert,
994 resample,
995 queue1,
996 opusenc,
997 rtp,
998 queue2,
999 capsfilter,
1000 webrtcbin,
1001 nullptr);
1002
1003 if (!gst_element_link_many(source,
1004 volume,
1005 convert,
1006 resample,
1007 queue1,
1008 opusenc,
1009 rtp,
1010 queue2,
1011 capsfilter,
1012 webrtcbin,
1013 nullptr)) {
1014 nhlog::ui()->error("WebRTC: failed to link audio pipeline elements");
1015 return false;
1016 }
1017
1018 GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS(GST_BIN(pipe_), GST_DEBUG_GRAPH_SHOW_VERBOSE, "created");
1019
1020 return callType_ == CallType::VOICE || isRemoteVideoSendOnly_
1021 ? true
1022 : addVideoPipeline(vp8PayloadType);
1023 }
1024
1025 bool
1026 WebRTCSession::addVideoPipeline(int vp8PayloadType)
1027 {
1028 // allow incoming video calls despite localUser having no webcam
1029 if (callType_ == CallType::VIDEO && !devices_.haveCamera())
1030 return !isOffering_;
1031
1032 auto settings = ChatPage::instance()->userSettings();
1033 GstElement *camerafilter = nullptr;
1034 GstElement *videoconvert = gst_element_factory_make("videoconvert", nullptr);
1035 GstElement *tee = gst_element_factory_make("tee", "videosrctee");
1036 gst_bin_add_many(GST_BIN(pipe_), videoconvert, tee, nullptr);
1037
1038 if (callType_ == CallType::VIDEO || (settings->screenSharePiP() && devices_.haveCamera())) {
1039 std::pair<int, int> resolution;
1040 std::pair<int, int> frameRate;
1041 GstDevice *device = devices_.videoDevice(resolution, frameRate);
1042 if (!device)
1043 return false;
1044
1045 GstElement *camera = gst_device_create_element(device, nullptr);
1046 GstCaps *caps = gst_caps_new_simple("video/x-raw",
1047 "width",
1048 G_TYPE_INT,
1049 resolution.first,
1050 "height",
1051 G_TYPE_INT,
1052 resolution.second,
1053 "framerate",
1054 GST_TYPE_FRACTION,
1055 frameRate.first,
1056 frameRate.second,
1057 nullptr);
1058 camerafilter = gst_element_factory_make("capsfilter", "camerafilter");
1059 g_object_set(camerafilter, "caps", caps, nullptr);
1060 gst_caps_unref(caps);
1061
1062 gst_bin_add_many(GST_BIN(pipe_), camera, camerafilter, nullptr);
1063 if (!gst_element_link_many(camera, videoconvert, camerafilter, nullptr)) {
1064 nhlog::ui()->error("WebRTC: failed to link camera elements");
1065 return false;
1066 }
1067 if (callType_ == CallType::VIDEO && !gst_element_link(camerafilter, tee)) {
1068 nhlog::ui()->error("WebRTC: failed to link camerafilter -> tee");
1069 return false;
1070 }
1071 }
1072
1073 if (callType_ == CallType::SCREEN) {
1074 nhlog::ui()->debug("WebRTC: screen share frame rate: {} fps",
1075 settings->screenShareFrameRate());
1076 nhlog::ui()->debug("WebRTC: screen share picture-in-picture: {}",
1077 settings->screenSharePiP());
1078 nhlog::ui()->debug("WebRTC: screen share request remote camera: {}",
1079 settings->screenShareRemoteVideo());
1080 nhlog::ui()->debug("WebRTC: screen share hide mouse cursor: {}",
1081 settings->screenShareHideCursor());
1082
1083 GstElement *screencastsrc = nullptr;
1084
1085 if (screenShareType_ == ScreenShareType::X11) {
1086 GstElement *ximagesrc = gst_element_factory_make("ximagesrc", "screenshare");
1087 if (!ximagesrc) {
1088 nhlog::ui()->error("WebRTC: failed to create ximagesrc");
1089 return false;
1090 }
1091 g_object_set(ximagesrc, "use-damage", FALSE, nullptr);
1092 g_object_set(ximagesrc, "xid", shareWindowId_, nullptr);
1093 g_object_set(ximagesrc, "show-pointer", !settings->screenShareHideCursor(), nullptr);
1094 g_object_set(ximagesrc, "do-timestamp", (gboolean)1, nullptr);
1095
1096 gst_bin_add(GST_BIN(pipe_), ximagesrc);
1097 screencastsrc = ximagesrc;
1098 } else if (screenShareType_ == ScreenShareType::D3D11) {
1099 GstElement *d3d11screensrc =
1100 gst_element_factory_make("d3d11screencapturesrc", "screenshare");
1101 if (!d3d11screensrc) {
1102 nhlog::ui()->error("WebRTC: failed to create d3d11screencapturesrc");
1103 gst_object_unref(pipe_);
1104 pipe_ = nullptr;
1105 return false;
1106 }
1107 g_object_set(
1108 d3d11screensrc, "window-handle", static_cast<guint64>(shareWindowId_), nullptr);
1109 g_object_set(
1110 d3d11screensrc, "show-cursor", !settings->screenShareHideCursor(), nullptr);
1111 g_object_set(d3d11screensrc, "do-timestamp", (gboolean)1, nullptr);
1112 gst_bin_add(GST_BIN(pipe_), d3d11screensrc);
1113
1114 GstElement *d3d11convert = gst_element_factory_make("d3d11convert", nullptr);
1115 gst_bin_add(GST_BIN(pipe_), d3d11convert);
1116 if (!gst_element_link(d3d11screensrc, d3d11convert)) {
1117 nhlog::ui()->error("WebRTC: failed to link d3d11screencapturesrc -> d3d11convert");
1118 return false;
1119 }
1120
1121 GstElement *d3d11download = gst_element_factory_make("d3d11download", nullptr);
1122 gst_bin_add(GST_BIN(pipe_), d3d11download);
1123 if (!gst_element_link(d3d11convert, d3d11download)) {
1124 nhlog::ui()->error("WebRTC: failed to link d3d11convert -> d3d11download");
1125 return false;
1126 }
1127 screencastsrc = d3d11download;
1128 } else {
1129 ScreenCastPortal &sc_portal = ScreenCastPortal::instance();
1130 GstElement *pipewiresrc = gst_element_factory_make("pipewiresrc", "screenshare");
1131 if (!pipewiresrc) {
1132 nhlog::ui()->error("WebRTC: failed to create pipewiresrc");
1133 gst_object_unref(pipe_);
1134 pipe_ = nullptr;
1135 return false;
1136 }
1137
1138 const ScreenCastPortal::Stream *stream = sc_portal.getStream();
1139 if (stream == nullptr) {
1140 nhlog::ui()->error("xdg-desktop-portal stream not started");
1141 gst_object_unref(pipe_);
1142 pipe_ = nullptr;
1143 return false;
1144 }
1145 g_object_set(pipewiresrc, "fd", (gint)stream->fd.fileDescriptor(), nullptr);
1146 std::string path = std::to_string(stream->nodeId);
1147 g_object_set(pipewiresrc, "path", path.c_str(), nullptr);
1148 g_object_set(pipewiresrc, "do-timestamp", (gboolean)1, nullptr);
1149 gst_bin_add(GST_BIN(pipe_), pipewiresrc);
1150 GstElement *videorate = gst_element_factory_make("videorate", nullptr);
1151 gst_bin_add(GST_BIN(pipe_), videorate);
1152 if (!gst_element_link(pipewiresrc, videorate)) {
1153 nhlog::ui()->error("WebRTC: failed to link pipewiresrc -> videorate");
1154 return false;
1155 }
1156 screencastsrc = videorate;
1157 }
1158
1159 GstCaps *caps = gst_caps_new_simple("video/x-raw",
1160 "format",
1161 G_TYPE_STRING,
1162 "I420", // For vp8enc
1163 "framerate",
1164 GST_TYPE_FRACTION,
1165 settings->screenShareFrameRate(),
1166 1,
1167 nullptr);
1168 GstElement *capsfilter = gst_element_factory_make("capsfilter", nullptr);
1169 g_object_set(capsfilter, "caps", caps, nullptr);
1170 gst_caps_unref(caps);
1171 gst_bin_add(GST_BIN(pipe_), capsfilter);
1172
1173 if (settings->screenSharePiP() && devices_.haveCamera()) {
1174 GstElement *compositor = gst_element_factory_make("compositor", nullptr);
1175 g_object_set(compositor, "background", 1, nullptr);
1176 gst_bin_add(GST_BIN(pipe_), compositor);
1177 if (!gst_element_link_many(screencastsrc, compositor, capsfilter, tee, nullptr)) {
1178 nhlog::ui()->error("WebRTC: failed to link screen share elements");
1179 return false;
1180 }
1181
1182 GstPad *srcpad = gst_element_get_static_pad(camerafilter, "src");
1183 remotePiPSinkPad_ = gst_element_request_pad_simple(compositor, "sink_%u");
1184 if (GST_PAD_LINK_FAILED(gst_pad_link(srcpad, remotePiPSinkPad_))) {
1185 nhlog::ui()->error("WebRTC: failed to link camerafilter -> compositor");
1186 gst_object_unref(srcpad);
1187 return false;
1188 }
1189 gst_object_unref(srcpad);
1190 } else if (!gst_element_link_many(screencastsrc, videoconvert, capsfilter, tee, nullptr)) {
1191 nhlog::ui()->error("WebRTC: failed to link screen share elements");
1192 return false;
1193 }
1194 }
1195
1196 GstElement *queue = gst_element_factory_make("queue", nullptr);
1197 GstElement *vp8enc = gst_element_factory_make("vp8enc", nullptr);
1198 g_object_set(vp8enc, "deadline", 1, nullptr);
1199 g_object_set(vp8enc, "error-resilient", 1, nullptr);
1200 GstElement *rtpvp8pay = gst_element_factory_make("rtpvp8pay", nullptr);
1201 GstElement *rtpqueue = gst_element_factory_make("queue", nullptr);
1202 GstElement *rtpcapsfilter = gst_element_factory_make("capsfilter", nullptr);
1203 GstCaps *rtpcaps = gst_caps_new_simple("application/x-rtp",
1204 "media",
1205 G_TYPE_STRING,
1206 "video",
1207 "encoding-name",
1208 G_TYPE_STRING,
1209 "VP8",
1210 "payload",
1211 G_TYPE_INT,
1212 vp8PayloadType,
1213 nullptr);
1214 g_object_set(rtpcapsfilter, "caps", rtpcaps, nullptr);
1215 gst_caps_unref(rtpcaps);
1216
1217 gst_bin_add_many(GST_BIN(pipe_), queue, vp8enc, rtpvp8pay, rtpqueue, rtpcapsfilter, nullptr);
1218
1219 GstElement *webrtcbin = gst_bin_get_by_name(GST_BIN(pipe_), "webrtcbin");
1220 if (!gst_element_link_many(
1221 tee, queue, vp8enc, rtpvp8pay, rtpqueue, rtpcapsfilter, webrtcbin, nullptr)) {
1222 nhlog::ui()->error("WebRTC: failed to link rtp video elements");
1223 gst_object_unref(webrtcbin);
1224 return false;
1225 }
1226
1227 if (callType_ == CallType::SCREEN &&
1228 !ChatPage::instance()->userSettings()->screenShareRemoteVideo()) {
1229 GArray *transceivers;
1230 g_signal_emit_by_name(webrtcbin, "get-transceivers", &transceivers);
1231 GstWebRTCRTPTransceiver *transceiver =
1232 g_array_index(transceivers, GstWebRTCRTPTransceiver *, 1);
1233 g_object_set(
1234 transceiver, "direction", GST_WEBRTC_RTP_TRANSCEIVER_DIRECTION_SENDONLY, nullptr);
1235 g_array_unref(transceivers);
1236 }
1237
1238 gst_object_unref(webrtcbin);
1239
1240 GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS(GST_BIN(pipe_), GST_DEBUG_GRAPH_SHOW_VERBOSE, "addvideo");
1241 return true;
1242 }
1243
1244 bool
1245 WebRTCSession::haveLocalPiP() const
1246 {
1247 if (state_ >= State::INITIATED) {
1248 if (callType_ == CallType::VOICE || isRemoteVideoRecvOnly_)
1249 return false;
1250 else if (callType_ == CallType::SCREEN)
1251 return true;
1252 else {
1253 GstElement *tee = gst_bin_get_by_name(GST_BIN(pipe_), "videosrctee");
1254 if (tee) {
1255 gst_object_unref(tee);
1256 return true;
1257 }
1258 }
1259 }
1260 return false;
1261 }
1262
1263 bool
1264 WebRTCSession::isMicMuted() const
1265 {
1266 if (state_ < State::INITIATED)
1267 return false;
1268
1269 GstElement *srclevel = gst_bin_get_by_name(GST_BIN(pipe_), "srclevel");
1270 gboolean muted;
1271 g_object_get(srclevel, "mute", &muted, nullptr);
1272 gst_object_unref(srclevel);
1273 return muted;
1274 }
1275
1276 bool
1277 WebRTCSession::toggleMicMute()
1278 {
1279 if (state_ < State::INITIATED)
1280 return false;
1281
1282 GstElement *srclevel = gst_bin_get_by_name(GST_BIN(pipe_), "srclevel");
1283 gboolean muted;
1284 g_object_get(srclevel, "mute", &muted, nullptr);
1285 g_object_set(srclevel, "mute", !muted, nullptr);
1286 gst_object_unref(srclevel);
1287
1288 GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS(GST_BIN(pipe_), GST_DEBUG_GRAPH_SHOW_VERBOSE, "togglemute");
1289
1290 return !muted;
1291 }
1292
1293 void
1294 WebRTCSession::toggleLocalPiP()
1295 {
1296 if (localPiPSinkPad_) {
1297 guint zorder;
1298 g_object_get(localPiPSinkPad_, "zorder", &zorder, nullptr);
1299 g_object_set(localPiPSinkPad_, "zorder", zorder ? 0 : 2, nullptr);
1300 }
1301 }
1302
1303 void
1304 WebRTCSession::clear()
1305 {
1306 callType_ = webrtc::CallType::VOICE;
1307 isOffering_ = false;
1308 isRemoteVideoRecvOnly_ = false;
1309 isRemoteVideoSendOnly_ = false;
1310 videoItem_ = nullptr;
1311 pipe_ = nullptr;
1312 webrtc_ = nullptr;
1313 busWatchId_ = 0;
1314 shareWindowId_ = 0;
1315 haveAudioStream_ = false;
1316 haveVideoStream_ = false;
1317 localPiPSinkPad_ = nullptr;
1318 remotePiPSinkPad_ = nullptr;
1319 localsdp_.clear();
1320 localcandidates_.clear();
1321 }
1322
1323 void
1324 WebRTCSession::end()
1325 {
1326 nhlog::ui()->debug("WebRTC: ending session");
1327 keyFrameRequestData_ = KeyFrameRequestData{};
1328 if (pipe_) {
1329 GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS(GST_BIN(pipe_), GST_DEBUG_GRAPH_SHOW_VERBOSE, "end");
1330
1331 gst_element_set_state(pipe_, GST_STATE_NULL);
1332 gst_object_unref(pipe_);
1333 pipe_ = nullptr;
1334 if (busWatchId_) {
1335 g_source_remove(busWatchId_);
1336 busWatchId_ = 0;
1337 }
1338 }
1339
1340 clear();
1341 if (state_ != State::DISCONNECTED)
1342 emit stateChanged(State::DISCONNECTED);
1343 }
1344
1345 #else
1346
1347 bool
1348 WebRTCSession::havePlugins(bool, bool, ScreenShareType, std::string *)
1349 {
1350 return false;
1351 }
1352
1353 bool
1354 WebRTCSession::haveLocalPiP() const
1355 {
1356 return false;
1357 }
1358
1359 // clang-format off
1360 // clang-format < 12 is buggy on this
1361 bool
1362 WebRTCSession::createOffer(webrtc::CallType,
1363 ScreenShareType screenShareType,
1364 uint32_t)
1365 {
1366 (void)screenShareType;
1367 return false;
1368 }
1369 // clang-format on
1370
1371 bool
1372 WebRTCSession::acceptNegotiation(const std::string &)
1373 {
1374 return false;
1375 }
1376
1377 bool
1378 WebRTCSession::acceptOffer(const std::string &)
1379 {
1380 return false;
1381 }
1382
1383 bool
1384 WebRTCSession::acceptAnswer(const std::string &)
1385 {
1386 return false;
1387 }
1388
1389 void
1390 WebRTCSession::acceptICECandidates(
1391 const std::vector<mtx::events::voip::CallCandidates::Candidate> &)
1392 {
1393 }
1394
1395 bool
1396 WebRTCSession::isMicMuted() const
1397 {
1398 return false;
1399 }
1400
1401 bool
1402 WebRTCSession::toggleMicMute()
1403 {
1404 return false;
1405 }
1406
1407 void
1408 WebRTCSession::toggleLocalPiP()
1409 {
1410 }
1411
1412 void
1413 WebRTCSession::end()
1414 {
1415 }
1416
1417 #endif
1418
1419 #include "moc_WebRTCSession.cpp"