| 1 | // SPDX-FileCopyrightText: Nheko Contributors |
| 2 | // |
| 3 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 4 | |
| 5 | #include <algorithm> |
| 6 | #include <cctype> |
| 7 | #include <chrono> |
| 8 | #include <cstdint> |
| 9 | #include <cstdlib> |
| 10 | |
| 11 | #include <QAudioOutput> |
| 12 | #include <QGuiApplication> |
| 13 | #include <QUrl> |
| 14 | |
| 15 | #include "Cache.h" |
| 16 | #include "CallDevices.h" |
| 17 | #include "CallManager.h" |
| 18 | #include "ChatPage.h" |
| 19 | #include "Logging.h" |
| 20 | #include "MatrixClient.h" |
| 21 | #include "UserSettingsPage.h" |
| 22 | #include "Utils.h" |
| 23 | |
| 24 | #include "mtx/responses/turn_server.hpp" |
| 25 | #include "voip/ScreenCastPortal.h" |
| 26 | #include "voip/WebRTCSession.h" |
| 27 | |
| 28 | /* |
| 29 | * Select Answer when one instance of the client supports v0 |
| 30 | */ |
| 31 | |
| 32 | #ifdef XCB_AVAILABLE |
| 33 | #include <xcb/xcb.h> |
| 34 | #include <xcb/xcb_ewmh.h> |
| 35 | #endif |
| 36 | |
| 37 | #ifdef Q_OS_WINDOWS |
| 38 | #include <Windows.h> |
| 39 | #endif |
| 40 | |
| 41 | #ifdef GSTREAMER_AVAILABLE |
| 42 | extern "C" |
| 43 | { |
| 44 | #include "gst/gst.h" |
| 45 | } |
| 46 | #endif |
| 47 | |
| 48 | using namespace mtx::events; |
| 49 | using namespace mtx::events::voip; |
| 50 | |
| 51 | using webrtc::CallType; |
| 52 | using webrtc::ScreenShareType; |
| 53 | //! Session Description Object |
| 54 | typedef RTCSessionDescriptionInit SDO; |
| 55 | |
| 56 | namespace { |
| 57 | std::vector<std::string> |
| 58 | getTurnURIs(const mtx::responses::TurnServer &turnServer); |
| 59 | } |
| 60 | |
| 61 | CallManager * |
| 62 | CallManager::create(QQmlEngine *qmlEngine, QJSEngine *) |
| 63 | { |
| 64 | // The instance has to exist before it is used. We cannot replace it. |
| 65 | auto instance = ChatPage::instance()->callManager(); |
| 66 | Q_ASSERT(instance); |
| 67 | |
| 68 | // The engine has to have the same thread affinity as the singleton. |
| 69 | Q_ASSERT(qmlEngine->thread() == instance->thread()); |
| 70 | |
| 71 | // There can only be one engine accessing the singleton. |
| 72 | static QJSEngine *s_engine = nullptr; |
| 73 | if (s_engine) |
| 74 | Q_ASSERT(qmlEngine == s_engine); |
| 75 | else |
| 76 | s_engine = qmlEngine; |
| 77 | |
| 78 | QJSEngine::setObjectOwnership(instance, QJSEngine::CppOwnership); |
| 79 | return instance; |
| 80 | } |
| 81 | |
| 82 | CallManager::CallManager(QObject *parent) |
| 83 | : QObject(parent) |
| 84 | , session_(WebRTCSession::instance()) |
| 85 | , turnServerTimer_(this) |
| 86 | { |
| 87 | #ifdef GSTREAMER_AVAILABLE |
| 88 | std::string errorMessage; |
| 89 | |
| 90 | if (QGuiApplication::platformName() == QStringLiteral("windows") && |
| 91 | session_.havePlugins(true, true, ScreenShareType::D3D11, &errorMessage)) { |
| 92 | screenShareType_ = ScreenShareType::D3D11; |
| 93 | screenShareTypes_.push_back(ScreenShareType::D3D11); |
| 94 | } else if (std::getenv("DISPLAY")) { |
| 95 | screenShareTypes_.push_back(ScreenShareType::X11); |
| 96 | if (QGuiApplication::platformName() != QStringLiteral("wayland")) { |
| 97 | // Selected by default |
| 98 | screenShareType_ = ScreenShareType::X11; |
| 99 | if (screenShareTypes_.size() >= 2) |
| 100 | std::swap(screenShareTypes_[0], screenShareTypes_[1]); |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | if (QGuiApplication::platformName() != QStringLiteral("windows") && |
| 105 | session_.havePlugins(true, true, ScreenShareType::XDP, &errorMessage)) { |
| 106 | screenShareTypes_.push_back(ScreenShareType::XDP); |
| 107 | screenShareType_ = ScreenShareType::XDP; |
| 108 | } |
| 109 | #endif |
| 110 | |
| 111 | connect( |
| 112 | &session_, |
| 113 | &WebRTCSession::offerCreated, |
| 114 | this, |
| 115 | [this](const std::string &sdp, const std::vector<CallCandidates::Candidate> &candidates) { |
| 116 | nhlog::ui()->debug("WebRTC: call id: {} - sending offer", callid_); |
| 117 | emit newMessage(roomid_, |
| 118 | CallInvite{callid_, |
| 119 | partyid_, |
| 120 | SDO{sdp, SDO::Type::Offer}, |
| 121 | callPartyVersion_, |
| 122 | timeoutms_, |
| 123 | invitee_}); |
| 124 | emit newMessage(roomid_, |
| 125 | CallCandidates{callid_, partyid_, candidates, callPartyVersion_}); |
| 126 | std::string callid(callid_); |
| 127 | QTimer::singleShot(timeoutms_, this, [this, callid]() { |
| 128 | if (session_.state() == webrtc::State::OFFERSENT && callid == callid_) { |
| 129 | hangUp(CallHangUp::Reason::InviteTimeOut); |
| 130 | emit ChatPage::instance()->showNotification( |
| 131 | QStringLiteral("The remote side failed to pick up.")); |
| 132 | } |
| 133 | }); |
| 134 | }); |
| 135 | |
| 136 | connect( |
| 137 | &session_, |
| 138 | &WebRTCSession::answerCreated, |
| 139 | this, |
| 140 | [this](const std::string &sdp, const std::vector<CallCandidates::Candidate> &candidates) { |
| 141 | nhlog::ui()->debug("WebRTC: call id: {} - sending answer", callid_); |
| 142 | emit newMessage( |
| 143 | roomid_, CallAnswer{callid_, partyid_, callPartyVersion_, SDO{sdp, SDO::Type::Answer}}); |
| 144 | emit newMessage(roomid_, |
| 145 | CallCandidates{callid_, partyid_, candidates, callPartyVersion_}); |
| 146 | }); |
| 147 | |
| 148 | connect(&session_, |
| 149 | &WebRTCSession::newICECandidate, |
| 150 | this, |
| 151 | [this](const CallCandidates::Candidate &candidate) { |
| 152 | nhlog::ui()->debug("WebRTC: call id: {} - sending ice candidate", callid_); |
| 153 | emit newMessage(roomid_, |
| 154 | CallCandidates{callid_, partyid_, {candidate}, callPartyVersion_}); |
| 155 | }); |
| 156 | |
| 157 | connect(&turnServerTimer_, &QTimer::timeout, this, &CallManager::retrieveTurnServer); |
| 158 | |
| 159 | connect( |
| 160 | this, &CallManager::turnServerRetrieved, this, [this](const mtx::responses::TurnServer &res) { |
| 161 | nhlog::net()->info("TURN server(s) retrieved from homeserver:"); |
| 162 | nhlog::net()->info("username: {}", res.username); |
| 163 | nhlog::net()->info("ttl: {} seconds", res.ttl); |
| 164 | for (const auto &u : res.uris) |
| 165 | nhlog::net()->info("uri: {}", u); |
| 166 | |
| 167 | // Request new credentials close to expiry |
| 168 | // See https://tools.ietf.org/html/draft-uberti-behave-turn-rest-00 |
| 169 | turnURIs_ = getTurnURIs(res); |
| 170 | uint32_t ttl = std::max(res.ttl, std::uint32_t{3600}); |
| 171 | if (res.ttl < 3600) |
| 172 | nhlog::net()->warn("Setting ttl to 1 hour"); |
| 173 | turnServerTimer_.setInterval(std::chrono::seconds(ttl) * 10 / 9); |
| 174 | }); |
| 175 | |
| 176 | connect(&session_, &WebRTCSession::stateChanged, this, [this](webrtc::State state) { |
| 177 | switch (state) { |
| 178 | case webrtc::State::DISCONNECTED: |
| 179 | playRingtone(QUrl(QStringLiteral("qrc:/media/media/callend.ogg")), false); |
| 180 | clear(); |
| 181 | break; |
| 182 | case webrtc::State::ICEFAILED: { |
| 183 | QString error(QStringLiteral("Call connection failed.")); |
| 184 | if (turnURIs_.empty()) |
| 185 | error += QLatin1String(" Your homeserver has no configured TURN server."); |
| 186 | emit ChatPage::instance()->showNotification(error); |
| 187 | hangUp(CallHangUp::Reason::ICEFailed); |
| 188 | break; |
| 189 | } |
| 190 | default: |
| 191 | break; |
| 192 | } |
| 193 | emit newCallState(); |
| 194 | }); |
| 195 | |
| 196 | connect( |
| 197 | &CallDevices::instance(), &CallDevices::devicesChanged, this, &CallManager::devicesChanged); |
| 198 | |
| 199 | auto audioOutput = new QAudioOutput(&player_); |
| 200 | player_.setAudioOutput(audioOutput); |
| 201 | |
| 202 | connect( |
| 203 | &player_, &QMediaPlayer::mediaStatusChanged, this, [](QMediaPlayer::MediaStatus status) { |
| 204 | nhlog::ui()->debug("WebRTC: ringtone status {}", |
| 205 | QMetaEnum::fromType<QMediaPlayer::MediaStatus>().valueToKey(status)); |
| 206 | }); |
| 207 | |
| 208 | connect(&player_, |
| 209 | &QMediaPlayer::errorOccurred, |
| 210 | this, |
| 211 | [this](QMediaPlayer::Error error, QString errorString) { |
| 212 | stopRingtone(); |
| 213 | switch (error) { |
| 214 | case QMediaPlayer::FormatError: |
| 215 | case QMediaPlayer::ResourceError: |
| 216 | nhlog::ui()->error("WebRTC: valid ringtone file not found"); |
| 217 | break; |
| 218 | case QMediaPlayer::AccessDeniedError: |
| 219 | nhlog::ui()->error("WebRTC: access to ringtone file denied"); |
| 220 | break; |
| 221 | default: |
| 222 | nhlog::ui()->error("WebRTC: unable to play ringtone, {}", |
| 223 | errorString.toStdString()); |
| 224 | break; |
| 225 | } |
| 226 | }); |
| 227 | |
| 228 | #ifdef GSTREAMER_AVAILABLE |
| 229 | connect(&ScreenCastPortal::instance(), |
| 230 | &ScreenCastPortal::readyChanged, |
| 231 | this, |
| 232 | &CallManager::screenShareChanged); |
| 233 | #endif |
| 234 | } |
| 235 | |
| 236 | void |
| 237 | CallManager::sendInvite(const QString &roomid, CallType callType, unsigned int windowIndex) |
| 238 | { |
| 239 | if (isOnCall() || isOnCallOnOtherDevice()) { |
| 240 | if (isOnCallOnOtherDevice_ != "") |
| 241 | emit ChatPage::instance()->showNotification( |
| 242 | QStringLiteral("User is already in a call")); |
| 243 | return; |
| 244 | } |
| 245 | |
| 246 | auto roomInfo = cache::singleRoomInfo(roomid.toStdString()); |
| 247 | |
| 248 | std::string errorMessage; |
| 249 | |
| 250 | callType_ = callType; |
| 251 | roomid_ = roomid; |
| 252 | generateCallID(); |
| 253 | std::vector<RoomMember> members(cache::getMembers(roomid.toStdString())); |
| 254 | const RoomMember *callee; |
| 255 | if (roomInfo.member_count == 1) |
| 256 | callee = &members.front(); |
| 257 | else if (roomInfo.member_count == 2) |
| 258 | callee = members.front().user_id == utils::localUser() ? &members.back() : &members.front(); |
| 259 | else { |
| 260 | emit ChatPage::instance()->showNotification( |
| 261 | QStringLiteral("Calls are limited to rooms with less than two members")); |
| 262 | return; |
| 263 | } |
| 264 | |
| 265 | #ifdef GSTREAMER_AVAILABLE |
| 266 | if (callType == CallType::SCREEN) { |
| 267 | if (screenShareType_ == ScreenShareType::X11 || |
| 268 | screenShareType_ == ScreenShareType::D3D11) { |
| 269 | if (windows_.empty() || windowIndex >= windows_.size()) { |
| 270 | nhlog::ui()->error("WebRTC: window index out of range"); |
| 271 | return; |
| 272 | } |
| 273 | } else { |
| 274 | ScreenCastPortal &sc_portal = ScreenCastPortal::instance(); |
| 275 | if (sc_portal.getStream() == nullptr) { |
| 276 | nhlog::ui()->error("xdg-desktop-portal stream not started"); |
| 277 | return; |
| 278 | } |
| 279 | } |
| 280 | } |
| 281 | #endif |
| 282 | |
| 283 | if (haveCallInvite_) { |
| 284 | nhlog::ui()->debug("WebRTC: Discarding outbound call for inbound call. " |
| 285 | "localUser is polite party"); |
| 286 | if (callParty_ == callee->user_id) { |
| 287 | if (callType == callType_) |
| 288 | acceptInvite(); |
| 289 | else { |
| 290 | emit ChatPage::instance()->showNotification( |
| 291 | QStringLiteral("Can't place call. Call types do not match")); |
| 292 | emit newMessage( |
| 293 | roomid_, |
| 294 | CallHangUp{callid_, partyid_, callPartyVersion_, CallHangUp::Reason::UserBusy}); |
| 295 | } |
| 296 | } else { |
| 297 | emit ChatPage::instance()->showNotification( |
| 298 | QStringLiteral("Already on a call with a different user")); |
| 299 | emit newMessage( |
| 300 | roomid_, |
| 301 | CallHangUp{callid_, partyid_, callPartyVersion_, CallHangUp::Reason::UserBusy}); |
| 302 | } |
| 303 | return; |
| 304 | } |
| 305 | |
| 306 | session_.setTurnServers(turnURIs_); |
| 307 | std::string strCallType = |
| 308 | callType_ == CallType::VOICE ? "voice" : (callType_ == CallType::VIDEO ? "video" : "screen"); |
| 309 | |
| 310 | nhlog::ui()->debug("WebRTC: call id: {} - creating {} invite", callid_, strCallType); |
| 311 | callParty_ = callee->user_id; |
| 312 | callPartyDisplayName_ = callee->display_name.isEmpty() ? callee->user_id : callee->display_name; |
| 313 | callPartyAvatarUrl_ = QString::fromStdString(roomInfo.avatar_url); |
| 314 | invitee_ = callParty_.toStdString(); |
| 315 | emit newInviteState(); |
| 316 | playRingtone(QUrl(QStringLiteral("qrc:/media/media/ringback.ogg")), true); |
| 317 | |
| 318 | uint32_t shareWindowId = |
| 319 | callType == CallType::SCREEN && |
| 320 | (screenShareType_ == ScreenShareType::X11 || screenShareType_ == ScreenShareType::D3D11) |
| 321 | ? windows_[windowIndex].second |
| 322 | : 0; |
| 323 | if (!session_.createOffer(callType, screenShareType_, shareWindowId)) { |
| 324 | emit ChatPage::instance()->showNotification(QStringLiteral("Problem setting up call.")); |
| 325 | endCall(); |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | namespace { |
| 330 | std::string |
| 331 | callHangUpReasonString(CallHangUp::Reason reason) |
| 332 | { |
| 333 | switch (reason) { |
| 334 | case CallHangUp::Reason::ICEFailed: |
| 335 | return "ICE failed"; |
| 336 | case CallHangUp::Reason::InviteTimeOut: |
| 337 | return "Invite time out"; |
| 338 | case CallHangUp::Reason::ICETimeOut: |
| 339 | return "ICE time out"; |
| 340 | case CallHangUp::Reason::UserHangUp: |
| 341 | return "User hung up"; |
| 342 | case CallHangUp::Reason::UserMediaFailed: |
| 343 | return "User media failed"; |
| 344 | case CallHangUp::Reason::UserBusy: |
| 345 | return "User busy"; |
| 346 | case CallHangUp::Reason::UnknownError: |
| 347 | return "Unknown error"; |
| 348 | default: |
| 349 | return "User"; |
| 350 | } |
| 351 | } |
| 352 | } // namespace |
| 353 | |
| 354 | void |
| 355 | CallManager::hangUp(CallHangUp::Reason reason) |
| 356 | { |
| 357 | if (!callid_.empty()) { |
| 358 | nhlog::ui()->debug( |
| 359 | "WebRTC: call id: {} - hanging up ({})", callid_, callHangUpReasonString(reason)); |
| 360 | emit newMessage(roomid_, CallHangUp{callid_, partyid_, callPartyVersion_, reason}); |
| 361 | endCall(); |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | void |
| 366 | CallManager::syncEvent(const mtx::events::collections::TimelineEvents &event) |
| 367 | { |
| 368 | #ifdef GSTREAMER_AVAILABLE |
| 369 | if (handleEvent<CallInvite>(event) || handleEvent<CallCandidates>(event) || |
| 370 | handleEvent<CallNegotiate>(event) || handleEvent<CallSelectAnswer>(event) || |
| 371 | handleEvent<CallAnswer>(event) || handleEvent<CallReject>(event) || |
| 372 | handleEvent<CallHangUp>(event)) |
| 373 | return; |
| 374 | #else |
| 375 | (void)event; |
| 376 | #endif |
| 377 | } |
| 378 | |
| 379 | template<typename T> |
| 380 | bool |
| 381 | CallManager::handleEvent(const mtx::events::collections::TimelineEvents &event) |
| 382 | { |
| 383 | if (std::holds_alternative<RoomEvent<T>>(event)) { |
| 384 | handleEvent(std::get<RoomEvent<T>>(event)); |
| 385 | return true; |
| 386 | } |
| 387 | return false; |
| 388 | } |
| 389 | |
| 390 | void |
| 391 | CallManager::handleEvent(const RoomEvent<CallInvite> &callInviteEvent) |
| 392 | { |
| 393 | const char video[] = "m=video"; |
| 394 | const std::string &sdp = callInviteEvent.content.offer.sdp; |
| 395 | bool isVideo = std::search(sdp.cbegin(), |
| 396 | sdp.cend(), |
| 397 | std::cbegin(video), |
| 398 | std::cend(video) - 1, |
| 399 | [](unsigned char c1, unsigned char c2) { |
| 400 | return std::tolower(c1) == std::tolower(c2); |
| 401 | }) != sdp.cend(); |
| 402 | nhlog::ui()->debug("WebRTC: call id: {} - incoming {} CallInvite from ({},{}) ", |
| 403 | callInviteEvent.content.call_id, |
| 404 | (isVideo ? "video" : "voice"), |
| 405 | callInviteEvent.sender, |
| 406 | callInviteEvent.content.party_id); |
| 407 | |
| 408 | if (callInviteEvent.content.call_id.empty()) |
| 409 | return; |
| 410 | |
| 411 | if (callInviteEvent.sender == utils::localUser().toStdString()) { |
| 412 | if (callInviteEvent.content.party_id == partyid_) |
| 413 | return; |
| 414 | else { |
| 415 | if (callInviteEvent.content.invitee != utils::localUser().toStdString()) { |
| 416 | isOnCallOnOtherDevice_ = callInviteEvent.content.call_id; |
| 417 | emit newCallDeviceState(); |
| 418 | nhlog::ui()->debug("WebRTC: User is on call on other device."); |
| 419 | return; |
| 420 | } |
| 421 | } |
| 422 | } |
| 423 | |
| 424 | auto roomInfo = cache::singleRoomInfo(callInviteEvent.room_id); |
| 425 | callPartyVersion_ = callInviteEvent.content.version; |
| 426 | |
| 427 | const QString &ringtone = UserSettings::instance()->ringtone(); |
| 428 | bool sharesRoom = true; |
| 429 | |
| 430 | std::vector<RoomMember> members(cache::getMembers(callInviteEvent.room_id)); |
| 431 | const RoomMember &caller = |
| 432 | *std::find_if(members.begin(), members.end(), [&](RoomMember member) { |
| 433 | return member.user_id.toStdString() == callInviteEvent.sender; |
| 434 | }); |
| 435 | if (isOnCall() || isOnCallOnOtherDevice()) { |
| 436 | if (isOnCallOnOtherDevice_ != "") |
| 437 | return; |
| 438 | if (callParty_.toStdString() == callInviteEvent.sender) { |
| 439 | if (session_.state() == webrtc::State::OFFERSENT) { |
| 440 | if (callid_ > callInviteEvent.content.call_id) { |
| 441 | endCall(); |
| 442 | callParty_ = caller.user_id; |
| 443 | callPartyDisplayName_ = |
| 444 | caller.display_name.isEmpty() ? caller.user_id : caller.display_name; |
| 445 | callPartyAvatarUrl_ = QString::fromStdString(roomInfo.avatar_url); |
| 446 | |
| 447 | roomid_ = QString::fromStdString(callInviteEvent.room_id); |
| 448 | callid_ = callInviteEvent.content.call_id; |
| 449 | remoteICECandidates_.clear(); |
| 450 | haveCallInvite_ = true; |
| 451 | callType_ = isVideo ? CallType::VIDEO : CallType::VOICE; |
| 452 | inviteSDP_ = callInviteEvent.content.offer.sdp; |
| 453 | emit newInviteState(); |
| 454 | acceptInvite(); |
| 455 | } |
| 456 | return; |
| 457 | } else if (session_.state() < webrtc::State::OFFERSENT) |
| 458 | endCall(); |
| 459 | else |
| 460 | return; |
| 461 | } else |
| 462 | return; |
| 463 | } |
| 464 | |
| 465 | if (callPartyVersion_ == "0") { |
| 466 | if (roomInfo.member_count != 2) { |
| 467 | emit newMessage(QString::fromStdString(callInviteEvent.room_id), |
| 468 | CallHangUp{callInviteEvent.content.call_id, |
| 469 | partyid_, |
| 470 | callPartyVersion_, |
| 471 | CallHangUp::Reason::InviteTimeOut}); |
| 472 | return; |
| 473 | } |
| 474 | } else { |
| 475 | if (caller.user_id == utils::localUser() && |
| 476 | callInviteEvent.content.party_id == partyid_) // remote echo |
| 477 | return; |
| 478 | |
| 479 | if (roomInfo.member_count == 2 || // general call in room with two members |
| 480 | (roomInfo.member_count == 1 && |
| 481 | partyid_ != |
| 482 | callInviteEvent.content.party_id) || // self call, ring if not the same party_id |
| 483 | callInviteEvent.content.invitee == "" || // empty, meant for everyone |
| 484 | callInviteEvent.content.invitee == |
| 485 | utils::localUser().toStdString()) // meant specifically for local user |
| 486 | { |
| 487 | if (roomInfo.member_count > 2) { |
| 488 | // check if shares room |
| 489 | sharesRoom = checkSharesRoom(QString::fromStdString(callInviteEvent.room_id), |
| 490 | callInviteEvent.content.invitee); |
| 491 | } |
| 492 | } else { |
| 493 | emit newMessage(QString::fromStdString(callInviteEvent.room_id), |
| 494 | CallHangUp{callInviteEvent.content.call_id, |
| 495 | partyid_, |
| 496 | callPartyVersion_, |
| 497 | CallHangUp::Reason::InviteTimeOut}); |
| 498 | return; |
| 499 | } |
| 500 | } |
| 501 | |
| 502 | // ring if not mute or does not have direct message room |
| 503 | if (ringtone != QLatin1String("Mute") && sharesRoom) |
| 504 | playRingtone(ringtone == QLatin1String("Default") |
| 505 | ? QUrl(QStringLiteral("qrc:/media/media/ring.ogg")) |
| 506 | : QUrl::fromLocalFile(ringtone), |
| 507 | true); |
| 508 | |
| 509 | callParty_ = caller.user_id; |
| 510 | callPartyDisplayName_ = caller.display_name.isEmpty() ? caller.user_id : caller.display_name; |
| 511 | callPartyAvatarUrl_ = QString::fromStdString(roomInfo.avatar_url); |
| 512 | |
| 513 | roomid_ = QString::fromStdString(callInviteEvent.room_id); |
| 514 | callid_ = callInviteEvent.content.call_id; |
| 515 | remoteICECandidates_.clear(); |
| 516 | |
| 517 | haveCallInvite_ = true; |
| 518 | callType_ = isVideo ? CallType::VIDEO : CallType::VOICE; |
| 519 | inviteSDP_ = callInviteEvent.content.offer.sdp; |
| 520 | emit newInviteState(); |
| 521 | } |
| 522 | |
| 523 | void |
| 524 | CallManager::acceptInvite() |
| 525 | { |
| 526 | // if call was accepted/rejected elsewhere and m.call.select_answer is |
| 527 | // received before acceptInvite |
| 528 | if (!haveCallInvite_) |
| 529 | return; |
| 530 | |
| 531 | stopRingtone(); |
| 532 | std::string errorMessage; |
| 533 | if (!session_.havePlugins(callType_ != CallType::VOICE, |
| 534 | callType_ == CallType::SCREEN, |
| 535 | screenShareType_, |
| 536 | &errorMessage)) { |
| 537 | emit ChatPage::instance()->showNotification(QString::fromStdString(errorMessage)); |
| 538 | hangUp(CallHangUp::Reason::UserMediaFailed); |
| 539 | return; |
| 540 | } |
| 541 | |
| 542 | session_.setTurnServers(turnURIs_); |
| 543 | if (!session_.acceptOffer(inviteSDP_)) { |
| 544 | emit ChatPage::instance()->showNotification(QStringLiteral("Problem setting up call.")); |
| 545 | hangUp(); |
| 546 | return; |
| 547 | } |
| 548 | session_.acceptICECandidates(remoteICECandidates_); |
| 549 | remoteICECandidates_.clear(); |
| 550 | haveCallInvite_ = false; |
| 551 | emit newInviteState(); |
| 552 | } |
| 553 | |
| 554 | void |
| 555 | CallManager::rejectInvite() |
| 556 | { |
| 557 | if (callPartyVersion_ == "0") { |
| 558 | hangUp(); |
| 559 | // send m.call.reject after sending hangup as mentioned in MSC2746 |
| 560 | emit newMessage(roomid_, CallReject{callid_, partyid_, callPartyVersion_}); |
| 561 | } |
| 562 | if (!callid_.empty()) { |
| 563 | nhlog::ui()->debug("WebRTC: call id: {} - rejecting call", callid_); |
| 564 | emit newMessage(roomid_, CallReject{callid_, partyid_, callPartyVersion_}); |
| 565 | endCall(false); |
| 566 | } |
| 567 | } |
| 568 | |
| 569 | void |
| 570 | CallManager::handleEvent(const RoomEvent<CallCandidates> &callCandidatesEvent) |
| 571 | { |
| 572 | if (callCandidatesEvent.sender == utils::localUser().toStdString() && |
| 573 | callCandidatesEvent.content.party_id == partyid_) |
| 574 | return; |
| 575 | nhlog::ui()->debug("WebRTC: call id: {} - incoming CallCandidates from ({}, {})", |
| 576 | callCandidatesEvent.content.call_id, |
| 577 | callCandidatesEvent.sender, |
| 578 | callCandidatesEvent.content.party_id); |
| 579 | |
| 580 | if (callid_ == callCandidatesEvent.content.call_id) { |
| 581 | if (isOnCall()) |
| 582 | session_.acceptICECandidates(callCandidatesEvent.content.candidates); |
| 583 | else { |
| 584 | // CallInvite has been received and we're awaiting localUser to accept or |
| 585 | // reject the call |
| 586 | for (const auto &c : callCandidatesEvent.content.candidates) |
| 587 | remoteICECandidates_.push_back(c); |
| 588 | } |
| 589 | } |
| 590 | } |
| 591 | |
| 592 | void |
| 593 | CallManager::handleEvent(const RoomEvent<CallAnswer> &callAnswerEvent) |
| 594 | { |
| 595 | nhlog::ui()->debug("WebRTC: call id: {} - incoming CallAnswer from ({}, {})", |
| 596 | callAnswerEvent.content.call_id, |
| 597 | callAnswerEvent.sender, |
| 598 | callAnswerEvent.content.party_id); |
| 599 | if (answerSelected_) |
| 600 | return; |
| 601 | |
| 602 | if (callAnswerEvent.sender == utils::localUser().toStdString() && |
| 603 | callid_ == callAnswerEvent.content.call_id) { |
| 604 | if (partyid_ == callAnswerEvent.content.party_id) |
| 605 | return; |
| 606 | |
| 607 | if (!isOnCall()) { |
| 608 | emit ChatPage::instance()->showNotification( |
| 609 | QStringLiteral("Call answered on another device.")); |
| 610 | stopRingtone(); |
| 611 | haveCallInvite_ = false; |
| 612 | if (callPartyVersion_ != "1") { |
| 613 | isOnCallOnOtherDevice_ = callid_; |
| 614 | emit newCallDeviceState(); |
| 615 | } |
| 616 | emit newInviteState(); |
| 617 | } |
| 618 | if (callParty_ != utils::localUser()) |
| 619 | return; |
| 620 | } |
| 621 | |
| 622 | if (isOnCall() && callid_ == callAnswerEvent.content.call_id) { |
| 623 | stopRingtone(); |
| 624 | if (!session_.acceptAnswer(callAnswerEvent.content.answer.sdp)) { |
| 625 | emit ChatPage::instance()->showNotification(QStringLiteral("Problem setting up call.")); |
| 626 | hangUp(); |
| 627 | } |
| 628 | } |
| 629 | emit newMessage( |
| 630 | roomid_, |
| 631 | CallSelectAnswer{callid_, partyid_, callPartyVersion_, callAnswerEvent.content.party_id}); |
| 632 | selectedpartyid_ = callAnswerEvent.content.party_id; |
| 633 | answerSelected_ = true; |
| 634 | } |
| 635 | |
| 636 | void |
| 637 | CallManager::handleEvent(const RoomEvent<CallHangUp> &callHangUpEvent) |
| 638 | { |
| 639 | nhlog::ui()->debug("WebRTC: call id: {} - incoming CallHangUp ({}) from ({}, {})", |
| 640 | callHangUpEvent.content.call_id, |
| 641 | callHangUpReasonString(callHangUpEvent.content.reason), |
| 642 | callHangUpEvent.sender, |
| 643 | callHangUpEvent.content.party_id); |
| 644 | |
| 645 | if (callid_ == callHangUpEvent.content.call_id || |
| 646 | isOnCallOnOtherDevice_ == callHangUpEvent.content.call_id) |
| 647 | endCall(); |
| 648 | } |
| 649 | |
| 650 | void |
| 651 | CallManager::handleEvent(const RoomEvent<CallSelectAnswer> &callSelectAnswerEvent) |
| 652 | { |
| 653 | nhlog::ui()->debug("WebRTC: call id: {} - incoming CallSelectAnswer from ({}, {})", |
| 654 | callSelectAnswerEvent.content.call_id, |
| 655 | callSelectAnswerEvent.sender, |
| 656 | callSelectAnswerEvent.content.party_id); |
| 657 | if (callSelectAnswerEvent.sender == utils::localUser().toStdString()) { |
| 658 | if (callSelectAnswerEvent.content.party_id != partyid_) { |
| 659 | if (std::find(rejectCallPartyIDs_.begin(), |
| 660 | rejectCallPartyIDs_.begin(), |
| 661 | callSelectAnswerEvent.content.selected_party_id) != |
| 662 | rejectCallPartyIDs_.end()) |
| 663 | endCall(); |
| 664 | else { |
| 665 | if (callSelectAnswerEvent.content.selected_party_id == partyid_) |
| 666 | return; |
| 667 | nhlog::ui()->debug("WebRTC: call id: {} - user is on call with this user!", |
| 668 | callSelectAnswerEvent.content.call_id); |
| 669 | isOnCallOnOtherDevice_ = callSelectAnswerEvent.content.call_id; |
| 670 | emit newCallDeviceState(); |
| 671 | } |
| 672 | } |
| 673 | return; |
| 674 | } else if (callid_ == callSelectAnswerEvent.content.call_id) { |
| 675 | if (callSelectAnswerEvent.content.selected_party_id != partyid_) { |
| 676 | bool endAllCalls = false; |
| 677 | if (std::find(rejectCallPartyIDs_.begin(), |
| 678 | rejectCallPartyIDs_.begin(), |
| 679 | callSelectAnswerEvent.content.selected_party_id) != |
| 680 | rejectCallPartyIDs_.end()) |
| 681 | endAllCalls = true; |
| 682 | else { |
| 683 | isOnCallOnOtherDevice_ = callid_; |
| 684 | emit newCallDeviceState(); |
| 685 | } |
| 686 | endCall(endAllCalls); |
| 687 | } else if (session_.state() == webrtc::State::DISCONNECTED) |
| 688 | endCall(); |
| 689 | } |
| 690 | } |
| 691 | |
| 692 | void |
| 693 | CallManager::handleEvent(const RoomEvent<CallReject> &callRejectEvent) |
| 694 | { |
| 695 | nhlog::ui()->debug("WebRTC: call id: {} - incoming CallReject from ({}, {})", |
| 696 | callRejectEvent.content.call_id, |
| 697 | callRejectEvent.sender, |
| 698 | callRejectEvent.content.party_id); |
| 699 | if (answerSelected_) |
| 700 | return; |
| 701 | |
| 702 | rejectCallPartyIDs_.push_back(callRejectEvent.content.party_id); |
| 703 | // check remote echo |
| 704 | if (callRejectEvent.sender == utils::localUser().toStdString()) { |
| 705 | if (callRejectEvent.content.party_id != partyid_ && callParty_ != utils::localUser()) |
| 706 | emit ChatPage::instance()->showNotification( |
| 707 | QStringLiteral("Call rejected on another device.")); |
| 708 | endCall(); |
| 709 | return; |
| 710 | } |
| 711 | |
| 712 | if (callRejectEvent.content.call_id == callid_) { |
| 713 | if (session_.state() == webrtc::State::OFFERSENT) { |
| 714 | // only accept reject if webrtc is in OFFERSENT state, else call has been |
| 715 | // accepted |
| 716 | emit newMessage( |
| 717 | roomid_, |
| 718 | CallSelectAnswer{ |
| 719 | callid_, partyid_, callPartyVersion_, callRejectEvent.content.party_id}); |
| 720 | endCall(); |
| 721 | } |
| 722 | } |
| 723 | } |
| 724 | |
| 725 | void |
| 726 | CallManager::handleEvent(const RoomEvent<CallNegotiate> &callNegotiateEvent) |
| 727 | { |
| 728 | nhlog::ui()->debug("WebRTC: call id: {} - incoming CallNegotiate from ({}, {})", |
| 729 | callNegotiateEvent.content.call_id, |
| 730 | callNegotiateEvent.sender, |
| 731 | callNegotiateEvent.content.party_id); |
| 732 | |
| 733 | std::string negotiationSDP_ = callNegotiateEvent.content.description.sdp; |
| 734 | if (!session_.acceptNegotiation(negotiationSDP_)) { |
| 735 | emit ChatPage::instance()->showNotification(QStringLiteral("Problem accepting new SDP")); |
| 736 | hangUp(); |
| 737 | return; |
| 738 | } |
| 739 | session_.acceptICECandidates(remoteICECandidates_); |
| 740 | remoteICECandidates_.clear(); |
| 741 | } |
| 742 | |
| 743 | bool |
| 744 | CallManager::checkSharesRoom(QString roomid, std::string invitee) const |
| 745 | { |
| 746 | /* |
| 747 | IMPLEMENTATION REQUIRED |
| 748 | Check if room is shared to determine whether to ring or not. |
| 749 | Called from handle callInvite event |
| 750 | */ |
| 751 | if (roomid.toStdString() != "") { |
| 752 | if (invitee == "") { |
| 753 | // check all members |
| 754 | return true; |
| 755 | } else { |
| 756 | return true; |
| 757 | // check if invitee shares a direct room with local user |
| 758 | } |
| 759 | return true; |
| 760 | } |
| 761 | |
| 762 | return true; |
| 763 | } |
| 764 | |
| 765 | void |
| 766 | CallManager::toggleMicMute() |
| 767 | { |
| 768 | session_.toggleMicMute(); |
| 769 | emit micMuteChanged(); |
| 770 | } |
| 771 | |
| 772 | bool |
| 773 | CallManager::callsSupported() |
| 774 | { |
| 775 | #ifdef GSTREAMER_AVAILABLE |
| 776 | return true; |
| 777 | #else |
| 778 | return false; |
| 779 | #endif |
| 780 | } |
| 781 | |
| 782 | QStringList |
| 783 | CallManager::devices(bool isVideo) const |
| 784 | { |
| 785 | QStringList ret; |
| 786 | const QString &defaultDevice = |
| 787 | isVideo ? UserSettings::instance()->camera() : UserSettings::instance()->microphone(); |
| 788 | std::vector<std::string> devices = |
| 789 | CallDevices::instance().names(isVideo, defaultDevice.toStdString()); |
| 790 | assert(devices.size() < std::numeric_limits<int>::max()); |
| 791 | ret.reserve(static_cast<int>(devices.size())); |
| 792 | std::transform(devices.cbegin(), devices.cend(), std::back_inserter(ret), [](const auto &d) { |
| 793 | return QString::fromStdString(d); |
| 794 | }); |
| 795 | |
| 796 | return ret; |
| 797 | } |
| 798 | |
| 799 | void |
| 800 | CallManager::generateCallID() |
| 801 | { |
| 802 | using namespace std::chrono; |
| 803 | uint64_t ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count(); |
| 804 | callid_ = "c" + std::to_string(ms); |
| 805 | } |
| 806 | |
| 807 | void |
| 808 | CallManager::clear(bool endAllCalls) |
| 809 | { |
| 810 | closeScreenShare(); |
| 811 | roomid_.clear(); |
| 812 | callParty_.clear(); |
| 813 | callPartyDisplayName_.clear(); |
| 814 | callPartyAvatarUrl_.clear(); |
| 815 | callid_.clear(); |
| 816 | callType_ = CallType::VOICE; |
| 817 | haveCallInvite_ = false; |
| 818 | answerSelected_ = false; |
| 819 | if (endAllCalls) { |
| 820 | isOnCallOnOtherDevice_ = ""; |
| 821 | rejectCallPartyIDs_.clear(); |
| 822 | emit newCallDeviceState(); |
| 823 | } |
| 824 | emit newInviteState(); |
| 825 | inviteSDP_.clear(); |
| 826 | remoteICECandidates_.clear(); |
| 827 | } |
| 828 | |
| 829 | void |
| 830 | CallManager::endCall(bool endAllCalls) |
| 831 | { |
| 832 | stopRingtone(); |
| 833 | session_.end(); |
| 834 | clear(endAllCalls); |
| 835 | } |
| 836 | |
| 837 | void |
| 838 | CallManager::refreshTurnServer() |
| 839 | { |
| 840 | turnURIs_.clear(); |
| 841 | turnServerTimer_.start(2000); |
| 842 | } |
| 843 | |
| 844 | void |
| 845 | CallManager::retrieveTurnServer() |
| 846 | { |
| 847 | http::client()->get_turn_server( |
| 848 | [this](const mtx::responses::TurnServer &res, mtx::http::RequestErr err) { |
| 849 | if (err) { |
| 850 | turnServerTimer_.setInterval(5000); |
| 851 | return; |
| 852 | } |
| 853 | emit turnServerRetrieved(res); |
| 854 | }); |
| 855 | } |
| 856 | |
| 857 | void |
| 858 | CallManager::playRingtone(const QUrl &ringtone, bool repeat) |
| 859 | { |
| 860 | nhlog::ui()->debug("Trying to play ringtone {}", ringtone.toString().toStdString()); |
| 861 | player_.setLoops(repeat ? QMediaPlayer::Infinite : 1); |
| 862 | player_.setSource(ringtone); |
| 863 | // player_.audioOutput()->setVolume(100); |
| 864 | player_.play(); |
| 865 | } |
| 866 | |
| 867 | void |
| 868 | CallManager::stopRingtone() |
| 869 | { |
| 870 | player_.stop(); |
| 871 | } |
| 872 | |
| 873 | bool |
| 874 | CallManager::screenShareReady() const |
| 875 | { |
| 876 | #ifdef GSTREAMER_AVAILABLE |
| 877 | if (screenShareType_ == ScreenShareType::X11 || screenShareType_ == ScreenShareType::D3D11) { |
| 878 | return true; |
| 879 | } else { |
| 880 | return ScreenCastPortal::instance().ready(); |
| 881 | } |
| 882 | #else |
| 883 | return false; |
| 884 | #endif |
| 885 | } |
| 886 | |
| 887 | QStringList |
| 888 | CallManager::screenShareTypeList() |
| 889 | { |
| 890 | QStringList ret; |
| 891 | ret.reserve(3); |
| 892 | for (ScreenShareType type : screenShareTypes_) { |
| 893 | switch (type) { |
| 894 | case ScreenShareType::X11: |
| 895 | ret.append(tr("X11")); |
| 896 | break; |
| 897 | case ScreenShareType::D3D11: |
| 898 | ret.append("DirectX 11"); |
| 899 | break; |
| 900 | case ScreenShareType::XDP: |
| 901 | ret.append(tr("PipeWire")); |
| 902 | break; |
| 903 | } |
| 904 | } |
| 905 | |
| 906 | return ret; |
| 907 | } |
| 908 | |
| 909 | QStringList |
| 910 | CallManager::windowList() |
| 911 | { |
| 912 | if (std::find(screenShareTypes_.begin(), screenShareTypes_.end(), ScreenShareType::X11) == |
| 913 | screenShareTypes_.end() && |
| 914 | std::find(screenShareTypes_.begin(), screenShareTypes_.end(), ScreenShareType::D3D11) == |
| 915 | screenShareTypes_.end()) { |
| 916 | return {}; |
| 917 | } |
| 918 | |
| 919 | windows_.clear(); |
| 920 | windows_.push_back({tr("Entire screen"), 0}); |
| 921 | |
| 922 | #ifdef XCB_AVAILABLE |
| 923 | std::unique_ptr<xcb_connection_t, std::function<void(xcb_connection_t *)>> connection( |
| 924 | xcb_connect(nullptr, nullptr), [](xcb_connection_t *c) { xcb_disconnect(c); }); |
| 925 | if (xcb_connection_has_error(connection.get())) { |
| 926 | nhlog::ui()->error("Failed to connect to X server"); |
| 927 | return {}; |
| 928 | } |
| 929 | |
| 930 | xcb_ewmh_connection_t ewmh; |
| 931 | if (!xcb_ewmh_init_atoms_replies( |
| 932 | &ewmh, xcb_ewmh_init_atoms(connection.get(), &ewmh), nullptr)) { |
| 933 | nhlog::ui()->error("Failed to connect to EWMH server"); |
| 934 | return {}; |
| 935 | } |
| 936 | std::unique_ptr<xcb_ewmh_connection_t, std::function<void(xcb_ewmh_connection_t *)>> |
| 937 | ewmhconnection(&ewmh, [](xcb_ewmh_connection_t *c) { xcb_ewmh_connection_wipe(c); }); |
| 938 | |
| 939 | for (int i = 0; i < ewmh.nb_screens; i++) { |
| 940 | xcb_ewmh_get_windows_reply_t clients; |
| 941 | if (!xcb_ewmh_get_client_list_reply( |
| 942 | &ewmh, xcb_ewmh_get_client_list(&ewmh, i), &clients, nullptr)) { |
| 943 | nhlog::ui()->error("Failed to request window list"); |
| 944 | return {}; |
| 945 | } |
| 946 | |
| 947 | for (uint32_t w = 0; w < clients.windows_len; w++) { |
| 948 | xcb_window_t window = clients.windows[w]; |
| 949 | |
| 950 | std::string name; |
| 951 | xcb_ewmh_get_utf8_strings_reply_t data; |
| 952 | auto getName = [](xcb_ewmh_get_utf8_strings_reply_t *r) { |
| 953 | std::string name(r->strings, r->strings_len); |
| 954 | xcb_ewmh_get_utf8_strings_reply_wipe(r); |
| 955 | return name; |
| 956 | }; |
| 957 | |
| 958 | xcb_get_property_cookie_t cookie = xcb_ewmh_get_wm_name(&ewmh, window); |
| 959 | if (xcb_ewmh_get_wm_name_reply(&ewmh, cookie, &data, nullptr)) |
| 960 | name = getName(&data); |
| 961 | |
| 962 | cookie = xcb_ewmh_get_wm_visible_name(&ewmh, window); |
| 963 | if (xcb_ewmh_get_wm_visible_name_reply(&ewmh, cookie, &data, nullptr)) |
| 964 | name = getName(&data); |
| 965 | |
| 966 | windows_.push_back({QString::fromStdString(name), window}); |
| 967 | } |
| 968 | xcb_ewmh_get_windows_reply_wipe(&clients); |
| 969 | } |
| 970 | #endif |
| 971 | #ifdef Q_OS_WINDOWS |
| 972 | for (HWND windowHandle = GetTopWindow(nullptr); windowHandle != nullptr; |
| 973 | windowHandle = GetNextWindow(windowHandle, GW_HWNDNEXT)) { |
| 974 | if (!IsWindowVisible(windowHandle)) |
| 975 | continue; |
| 976 | |
| 977 | int titleLength = GetWindowTextLengthW(windowHandle); |
| 978 | if (titleLength == 0) |
| 979 | continue; |
| 980 | |
| 981 | if (GetWindowLong(windowHandle, GWL_EXSTYLE) & WS_EX_TOOLWINDOW) |
| 982 | continue; |
| 983 | |
| 984 | TITLEBARINFO titleInfo; |
| 985 | titleInfo.cbSize = sizeof(titleInfo); |
| 986 | GetTitleBarInfo(windowHandle, &titleInfo); |
| 987 | if (titleInfo.rgstate[0] & STATE_SYSTEM_INVISIBLE) |
| 988 | continue; |
| 989 | |
| 990 | wchar_t *windowTitle = new wchar_t[titleLength + 1]; |
| 991 | GetWindowTextW(windowHandle, windowTitle, titleLength + 1); |
| 992 | |
| 993 | windows_.push_back( |
| 994 | {QString::fromWCharArray(windowTitle), reinterpret_cast<uint64_t>(windowHandle)}); |
| 995 | } |
| 996 | #endif |
| 997 | QStringList ret; |
| 998 | assert(windows_.size() < std::numeric_limits<int>::max()); |
| 999 | ret.reserve(static_cast<int>(windows_.size())); |
| 1000 | for (const auto &w : windows_) |
| 1001 | ret.append(w.first); |
| 1002 | |
| 1003 | return ret; |
| 1004 | } |
| 1005 | |
| 1006 | #ifdef GSTREAMER_AVAILABLE |
| 1007 | namespace { |
| 1008 | |
| 1009 | GstElement *pipe_ = nullptr; |
| 1010 | unsigned int busWatchId_ = 0; |
| 1011 | |
| 1012 | void |
| 1013 | close_preview_stream() |
| 1014 | { |
| 1015 | if (pipe_) { |
| 1016 | gst_element_set_state(GST_ELEMENT(pipe_), GST_STATE_NULL); |
| 1017 | gst_object_unref(pipe_); |
| 1018 | pipe_ = nullptr; |
| 1019 | } |
| 1020 | if (busWatchId_) { |
| 1021 | g_source_remove(busWatchId_); |
| 1022 | busWatchId_ = 0; |
| 1023 | } |
| 1024 | } |
| 1025 | |
| 1026 | gboolean |
| 1027 | newBusMessage(GstBus *bus G_GNUC_UNUSED, GstMessage *msg, gpointer G_GNUC_UNUSED) |
| 1028 | { |
| 1029 | switch (GST_MESSAGE_TYPE(msg)) { |
| 1030 | case GST_MESSAGE_EOS: |
| 1031 | close_preview_stream(); |
| 1032 | break; |
| 1033 | case GST_MESSAGE_ERROR: { |
| 1034 | GError *err = nullptr; |
| 1035 | gchar *dbg_info = nullptr; |
| 1036 | gst_message_parse_error(msg, &err, &dbg_info); |
| 1037 | nhlog::ui()->error("GST error: {}", dbg_info); |
| 1038 | g_error_free(err); |
| 1039 | g_free(dbg_info); |
| 1040 | close_preview_stream(); |
| 1041 | break; |
| 1042 | } |
| 1043 | default: |
| 1044 | break; |
| 1045 | } |
| 1046 | return TRUE; |
| 1047 | } |
| 1048 | |
| 1049 | static GstElement * |
| 1050 | make_preview_sink() |
| 1051 | { |
| 1052 | if (QGuiApplication::platformName() == QStringLiteral("wayland")) { |
| 1053 | return gst_element_factory_make("waylandsink", nullptr); |
| 1054 | } else if (QGuiApplication::platformName() == QStringLiteral("windows")) { |
| 1055 | return gst_element_factory_make("d3d11videosink", nullptr); |
| 1056 | } else { |
| 1057 | return gst_element_factory_make("ximagesink", nullptr); |
| 1058 | } |
| 1059 | } |
| 1060 | } // namespace |
| 1061 | #endif |
| 1062 | |
| 1063 | void |
| 1064 | CallManager::previewWindow(unsigned int index) const |
| 1065 | { |
| 1066 | #ifdef GSTREAMER_AVAILABLE |
| 1067 | if (!gst_is_initialized()) |
| 1068 | return; |
| 1069 | |
| 1070 | if (pipe_ != nullptr) { |
| 1071 | nhlog::ui()->warn("Preview already started"); |
| 1072 | return; |
| 1073 | } |
| 1074 | |
| 1075 | if (screenShareType_ == ScreenShareType::X11 && |
| 1076 | (windows_.empty() || index >= windows_.size())) { |
| 1077 | nhlog::ui()->error("X11 screencast not available"); |
| 1078 | return; |
| 1079 | } |
| 1080 | |
| 1081 | if (screenShareType_ == ScreenShareType::D3D11 && |
| 1082 | (windows_.empty() || index >= windows_.size())) { |
| 1083 | nhlog::ui()->error("D3D11 screencast not available"); |
| 1084 | return; |
| 1085 | } |
| 1086 | |
| 1087 | auto settings = ChatPage::instance()->userSettings(); |
| 1088 | |
| 1089 | pipe_ = gst_pipeline_new(nullptr); |
| 1090 | |
| 1091 | GstElement *videoconvert = gst_element_factory_make("videoconvert", nullptr); |
| 1092 | GstElement *videoscale = gst_element_factory_make("videoscale", nullptr); |
| 1093 | GstElement *capsfilter = gst_element_factory_make("capsfilter", nullptr); |
| 1094 | GstElement *preview_sink = make_preview_sink(); |
| 1095 | GstElement *videorate = gst_element_factory_make("videorate", nullptr); |
| 1096 | |
| 1097 | gst_bin_add_many( |
| 1098 | GST_BIN(pipe_), videorate, videoconvert, videoscale, capsfilter, preview_sink, nullptr); |
| 1099 | |
| 1100 | GstCaps *caps = gst_caps_new_simple( |
| 1101 | "video/x-raw", "framerate", GST_TYPE_FRACTION, settings->screenShareFrameRate(), 1, nullptr); |
| 1102 | g_object_set(capsfilter, "caps", caps, nullptr); |
| 1103 | gst_caps_unref(caps); |
| 1104 | |
| 1105 | GstElement *screencastsrc = nullptr; |
| 1106 | if (screenShareType_ == ScreenShareType::X11) { |
| 1107 | GstElement *ximagesrc = gst_element_factory_make("ximagesrc", nullptr); |
| 1108 | if (!ximagesrc) { |
| 1109 | nhlog::ui()->error("Failed to create ximagesrc"); |
| 1110 | gst_object_unref(pipe_); |
| 1111 | pipe_ = nullptr; |
| 1112 | return; |
| 1113 | } |
| 1114 | g_object_set(ximagesrc, "use-damage", FALSE, nullptr); |
| 1115 | g_object_set(ximagesrc, "xid", windows_[index].second, nullptr); |
| 1116 | g_object_set(ximagesrc, "show-pointer", !settings->screenShareHideCursor(), nullptr); |
| 1117 | g_object_set(ximagesrc, "do-timestamp", (gboolean)1, nullptr); |
| 1118 | |
| 1119 | gst_bin_add(GST_BIN(pipe_), ximagesrc); |
| 1120 | screencastsrc = ximagesrc; |
| 1121 | } else if (screenShareType_ == ScreenShareType::D3D11) { |
| 1122 | GstElement *d3d11screensrc = gst_element_factory_make("d3d11screencapturesrc", nullptr); |
| 1123 | if (!d3d11screensrc) { |
| 1124 | nhlog::ui()->error("Failed to create d3d11screencapturesrc"); |
| 1125 | gst_object_unref(pipe_); |
| 1126 | pipe_ = nullptr; |
| 1127 | return; |
| 1128 | } |
| 1129 | g_object_set(d3d11screensrc, "window-handle", windows_[index].second, nullptr); |
| 1130 | g_object_set(d3d11screensrc, "show-cursor", !settings->screenShareHideCursor(), nullptr); |
| 1131 | |
| 1132 | gst_bin_add(GST_BIN(pipe_), d3d11screensrc); |
| 1133 | screencastsrc = d3d11screensrc; |
| 1134 | } else { |
| 1135 | ScreenCastPortal &sc_portal = ScreenCastPortal::instance(); |
| 1136 | const ScreenCastPortal::Stream *stream = sc_portal.getStream(); |
| 1137 | if (stream == nullptr) { |
| 1138 | nhlog::ui()->error("xdg-desktop-portal stream not started"); |
| 1139 | gst_object_unref(pipe_); |
| 1140 | pipe_ = nullptr; |
| 1141 | return; |
| 1142 | } |
| 1143 | GstElement *pipewiresrc = gst_element_factory_make("pipewiresrc", nullptr); |
| 1144 | g_object_set(pipewiresrc, "fd", (gint)stream->fd.fileDescriptor(), nullptr); |
| 1145 | std::string path = std::to_string(stream->nodeId); |
| 1146 | g_object_set(pipewiresrc, "path", path.c_str(), nullptr); |
| 1147 | g_object_set(pipewiresrc, "do-timestamp", (gboolean)1, nullptr); |
| 1148 | |
| 1149 | gst_bin_add(GST_BIN(pipe_), pipewiresrc); |
| 1150 | screencastsrc = pipewiresrc; |
| 1151 | } |
| 1152 | |
| 1153 | if (!gst_element_link_many( |
| 1154 | screencastsrc, videorate, videoconvert, videoscale, capsfilter, preview_sink, nullptr)) { |
| 1155 | nhlog::ui()->error("Failed to link preview window elements"); |
| 1156 | gst_object_unref(pipe_); |
| 1157 | pipe_ = nullptr; |
| 1158 | return; |
| 1159 | } |
| 1160 | |
| 1161 | if (gst_element_set_state(pipe_, GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE) { |
| 1162 | nhlog::ui()->error("Unable to start preview pipeline"); |
| 1163 | gst_object_unref(pipe_); |
| 1164 | pipe_ = nullptr; |
| 1165 | return; |
| 1166 | } |
| 1167 | |
| 1168 | GstBus *bus = gst_pipeline_get_bus(GST_PIPELINE(pipe_)); |
| 1169 | busWatchId_ = gst_bus_add_watch(bus, newBusMessage, nullptr); |
| 1170 | gst_object_unref(bus); |
| 1171 | #else |
| 1172 | (void)index; |
| 1173 | #endif |
| 1174 | } |
| 1175 | |
| 1176 | void |
| 1177 | CallManager::setupScreenShareXDP() |
| 1178 | { |
| 1179 | #ifdef GSTREAMER_AVAILABLE |
| 1180 | ScreenCastPortal &sc_portal = ScreenCastPortal::instance(); |
| 1181 | sc_portal.init(); |
| 1182 | #endif |
| 1183 | } |
| 1184 | |
| 1185 | void |
| 1186 | CallManager::setScreenShareType(unsigned int index) |
| 1187 | { |
| 1188 | #ifdef GSTREAMER_AVAILABLE |
| 1189 | closeScreenShare(); |
| 1190 | if (index >= screenShareTypes_.size()) |
| 1191 | nhlog::ui()->error("WebRTC: Screen share type index out of range"); |
| 1192 | screenShareType_ = screenShareTypes_[index]; |
| 1193 | emit screenShareChanged(); |
| 1194 | #else |
| 1195 | (void)index; |
| 1196 | #endif |
| 1197 | } |
| 1198 | |
| 1199 | void |
| 1200 | CallManager::closeScreenShare() |
| 1201 | { |
| 1202 | #ifdef GSTREAMER_AVAILABLE |
| 1203 | close_preview_stream(); |
| 1204 | if (!isOnCall()) { |
| 1205 | ScreenCastPortal &sc_portal = ScreenCastPortal::instance(); |
| 1206 | sc_portal.close(); |
| 1207 | } |
| 1208 | #endif |
| 1209 | } |
| 1210 | |
| 1211 | namespace { |
| 1212 | std::vector<std::string> |
| 1213 | getTurnURIs(const mtx::responses::TurnServer &turnServer) |
| 1214 | { |
| 1215 | // gstreamer expects: turn(s)://username:password@host:port?transport=udp(tcp) |
| 1216 | // where username and password are percent-encoded |
| 1217 | std::vector<std::string> ret; |
| 1218 | for (const auto &uri : turnServer.uris) { |
| 1219 | if (auto c = uri.find(':'); c == std::string::npos) { |
| 1220 | nhlog::ui()->error("Invalid TURN server uri: {}", uri); |
| 1221 | continue; |
| 1222 | } else { |
| 1223 | std::string scheme = std::string(uri, 0, c); |
| 1224 | if (scheme != "turn" && scheme != "turns") { |
| 1225 | nhlog::ui()->error("Invalid TURN server uri: {}", uri); |
| 1226 | continue; |
| 1227 | } |
| 1228 | |
| 1229 | QString encodedUri = |
| 1230 | QString::fromStdString(scheme) + "://" + |
| 1231 | QUrl::toPercentEncoding(QString::fromStdString(turnServer.username)) + ":" + |
| 1232 | QUrl::toPercentEncoding(QString::fromStdString(turnServer.password)) + "@" + |
| 1233 | QString::fromStdString(std::string(uri, ++c)); |
| 1234 | ret.push_back(encodedUri.toStdString()); |
| 1235 | } |
| 1236 | } |
| 1237 | return ret; |
| 1238 | } |
| 1239 | } // namespace |
| 1240 | |
| 1241 | #include "moc_CallManager.cpp" |