| 6 |
| 7 | namespace tgcalls { |
| 8 | namespace { |
| 9 |
| 10 | rtc::Thread *makeNetworkThread() { |
| 11 | static std::unique_ptr<rtc::Thread> value = rtc::Thread::CreateWithSocketServer(); |
| 12 | value->SetName("WebRTC-Network", nullptr); |
| 13 | value->Start(); |
| 14 | return value.get(); |
| 15 | } |
| 16 |
| 17 | rtc::Thread *getNetworkThread() { |
| 18 | static rtc::Thread *value = makeNetworkThread(); |
| 19 | return value; |
| 20 | } |
| 21 |
| 22 | rtc::Thread *makeMediaThread() { |
| 23 | static std::unique_ptr<rtc::Thread> value = rtc::Thread::Create(); |
| 24 | value->SetName("WebRTC-Media", nullptr); |
| 25 | value->Start(); |
| 26 | return value.get(); |
| 27 | } |
| 28 |
| 29 | void dumpStatsLog(const FilePath &path, const CallStats &stats) { |
| 30 | if (path.data.empty()) { |
| 31 | return; |
| 32 | } |
| 33 | std::ofstream file; |
| 34 | file.open(path.data); |
| 35 |
| 36 | file << "{"; |
| 37 | file << "\"v\":\"" << 1 << "\""; |
| 38 | file << ","; |
| 39 |
| 40 | file << "\"codec\":\"" << stats.outgoingCodec << "\""; |
| 41 | file << ","; |
| 42 |
| 43 | file << "\"bitrate\":["; |
| 44 | bool addComma = false; |
| 45 | for (auto &it : stats.bitrateRecords) { |
| 46 | if (addComma) { |
| 47 | file << ","; |
| 48 | } |
| 49 | file << "{"; |
| 50 | file << "\"t\":\"" << it.timestamp << "\""; |
| 51 | file << ","; |
| 52 | file << "\"b\":\"" << it.bitrate << "\""; |
| 53 | file << "}"; |
| 54 | addComma = true; |
| 55 | } |
| 56 | file << "]"; |
| 57 | file << ","; |
| 58 |
| 59 | file << "\"network\":["; |
| 60 | addComma = false; |
| 61 | for (auto &it : stats.networkRecords) { |
| 62 | if (addComma) { |
| 63 | file << ","; |
| 64 | } |
| 65 | file << "{"; |
| 66 | file << "\"t\":\"" << it.timestamp << "\""; |
| 67 | file << ","; |
| 68 | file << "\"e\":\"" << (int)(it.endpointType) << "\""; |
| 69 | file << ","; |
| 70 | file << "\"w\":\"" << (it.isLowCost ? 1 : 0) << "\""; |
| 71 | file << "}"; |
| 72 | addComma = true; |
| 73 | } |
| 74 | file << "]"; |
| 75 |
| 76 | file << "}"; |
| 77 |
| 78 | file.close(); |
| 79 | } |
| 80 |
| 81 | } // namespace |
| 82 |
| 83 | bool Manager::ResolvedNetworkStatus::operator==(const ResolvedNetworkStatus &rhs) { |
| 84 | if (rhs.isLowCost != isLowCost) { |
| 85 | return false; |
| 86 | } |
| 87 | if (rhs.isLowDataRequested != isLowDataRequested) { |
| 88 | return false; |
| 89 | } |
| 90 | return true; |
| 91 | } |
| 92 |
| 93 | bool Manager::ResolvedNetworkStatus::operator!=(const ResolvedNetworkStatus &rhs) { |
| 94 | return !(*this == rhs); |
| 95 | } |
| 96 |
| 97 | rtc::Thread *Manager::getMediaThread() { |
| 98 | static rtc::Thread *value = makeMediaThread(); |
| 99 | return value; |
| 100 | } |
| 101 |
| 102 | Manager::Manager(rtc::Thread *thread, Descriptor &&descriptor) : |
| 103 | _thread(thread), |
| 104 | _encryptionKey(descriptor.encryptionKey), |
| 105 | _signaling( |
| 106 | EncryptedConnection::Type::Signaling, |
| 107 | _encryptionKey, |
| 108 | [=](int delayMs, int cause) { sendSignalingAsync(delayMs, cause); }), |
| 109 | _enableP2P(descriptor.config.enableP2P), |
| 110 | _enableTCP(descriptor.config.allowTCP), |
| 111 | _enableStunMarking(descriptor.config.enableStunMarking), |
| 112 | _protocolVersion(descriptor.config.protocolVersion), |
| 113 | _statsLogPath(descriptor.config.statsLogPath), |
| 114 | _rtcServers(std::move(descriptor.rtcServers)), |
| 115 | _proxy(std::move(descriptor.proxy)), |
| 116 | _mediaDevicesConfig(std::move(descriptor.mediaDevicesConfig)), |
| 117 | _videoCapture(std::move(descriptor.videoCapture)), |
| 118 | _stateUpdated(std::move(descriptor.stateUpdated)), |
| 119 | _remoteMediaStateUpdated(std::move(descriptor.remoteMediaStateUpdated)), |
| 120 | _remoteBatteryLevelIsLowUpdated(std::move(descriptor.remoteBatteryLevelIsLowUpdated)), |
| 121 | _remotePrefferedAspectRatioUpdated(std::move(descriptor.remotePrefferedAspectRatioUpdated)), |
| 122 | _signalingDataEmitted(std::move(descriptor.signalingDataEmitted)), |
| 123 | _signalBarsUpdated(std::move(descriptor.signalBarsUpdated)), |
| 124 | _audioLevelUpdated(std::move(descriptor.audioLevelUpdated)), |
| 125 | _enableHighBitrateVideo(descriptor.config.enableHighBitrateVideo), |
| 126 | _dataSaving(descriptor.config.dataSaving), |
| 127 | _platformContext(descriptor.platformContext) { |
| 128 |
| 129 | assert(_thread->IsCurrent()); |
| 130 | assert(_stateUpdated != nullptr); |
| 131 | assert(_signalingDataEmitted != nullptr); |
| 132 |
| 133 | _preferredCodecs = descriptor.config.preferredVideoCodecs; |
| 134 |
| 135 | _sendSignalingMessage = [=](const Message &message) { |
| 136 | if (const auto prepared = _signaling.prepareForSending(message)) { |
| 137 | _signalingDataEmitted(prepared->bytes); |
| 138 | return prepared->counter; |
| 139 | } |
| 140 | return uint32_t(0); |
| 141 | }; |
| 142 | _sendTransportMessage = [=](Message &&message) { |
| 143 | _networkManager->perform(RTC_FROM_HERE, [message = std::move(message)](NetworkManager *networkManager) { |
| 144 | networkManager->sendMessage(message); |
| 145 | }); |
| 146 | }; |
| 147 | } |
| 148 |
| 149 | Manager::~Manager() { |
| 150 | assert(_thread->IsCurrent()); |
| 151 | } |
| 152 |
| 153 | void Manager::sendSignalingAsync(int delayMs, int cause) { |
| 154 | auto task = [weak = std::weak_ptr<Manager>(shared_from_this()), cause] { |
| 155 | const auto strong = weak.lock(); |
| 156 | if (!strong) { |
| 157 | return; |
| 158 | } |
| 159 | if (const auto prepared = strong->_signaling.prepareForSendingService(cause)) { |
| 160 | strong->_signalingDataEmitted(prepared->bytes); |
| 161 | } |
| 162 | }; |
| 163 | if (delayMs) { |
| 164 | _thread->PostDelayedTask(RTC_FROM_HERE, std::move(task), delayMs); |
| 165 | } else { |
| 166 | _thread->PostTask(RTC_FROM_HERE, std::move(task)); |
| 167 | } |
| 168 | } |
| 169 |
| 170 | void Manager::start() { |
| 171 | const auto weak = std::weak_ptr<Manager>(shared_from_this()); |
| 172 | const auto thread = _thread; |
| 173 | const auto sendSignalingMessage = [=](Message &&message) { |
| 174 | thread->PostTask(RTC_FROM_HERE, [=, message = std::move(message)]() mutable { |
| 175 | const auto strong = weak.lock(); |
| 176 | if (!strong) { |
| 177 | return; |
| 178 | } |
| 179 | strong->_sendSignalingMessage(std::move(message)); |
| 180 | }); |
| 181 | }; |
| 182 | _networkManager.reset(new ThreadLocalObject<NetworkManager>(getNetworkThread(), [weak, thread, sendSignalingMessage, encryptionKey = _encryptionKey, enableP2P = _enableP2P, enableTCP = _enableTCP, enableStunMarking = _enableStunMarking, rtcServers = _rtcServers, proxy = std::move(_proxy)] () mutable { |
| 183 | return new NetworkManager( |
| 184 | getNetworkThread(), |
| 185 | encryptionKey, |
| 186 | enableP2P, |
| 187 | enableTCP, |
| 188 | enableStunMarking, |
| 189 | rtcServers, |
| 190 | std::move(proxy), |
| 191 | [=](const NetworkManager::State &state) { |
| 192 | thread->PostTask(RTC_FROM_HERE, [=] { |
| 193 | const auto strong = weak.lock(); |
| 194 | if (!strong) { |
| 195 | return; |
| 196 | } |
| 197 | State mappedState; |
| 198 | if (state.isFailed) { |
| 199 | mappedState = State::Failed; |
| 200 | } else { |
| 201 | mappedState = state.isReadyToSendData |
| 202 | ? State::Established |
| 203 | : State::Reconnecting; |
| 204 | } |
| 205 | bool isFirstConnection = false; |
| 206 | if (state.isReadyToSendData) { |
| 207 | if (!strong->_didConnectOnce) { |
| 208 | strong->_didConnectOnce = true; |
| 209 | isFirstConnection = true; |
| 210 | } |
| 211 | } |
| 212 | strong->_state = mappedState; |
| 213 | strong->_stateUpdated(mappedState); |
| 214 |
| 215 | strong->_mediaManager->perform(RTC_FROM_HERE, [=](MediaManager *mediaManager) { |
| 216 | mediaManager->setIsConnected(state.isReadyToSendData); |
| 217 | }); |
| 218 |
| 219 | if (isFirstConnection) { |
| 220 | strong->sendInitialSignalingMessages(); |
| 221 | } |
| 222 | }); |
| 223 | }, |
| 224 | [=](DecryptedMessage &&message) { |
| 225 | thread->PostTask(RTC_FROM_HERE, [=, message = std::move(message)]() mutable { |
| 226 | if (const auto strong = weak.lock()) { |
| 227 | strong->receiveMessage(std::move(message)); |
| 228 | } |
| 229 | }); |
| 230 | }, |
| 231 | sendSignalingMessage, |
| 232 | [=](int delayMs, int cause) { |
| 233 | const auto task = [=] { |
| 234 | if (const auto strong = weak.lock()) { |
| 235 | strong->_networkManager->perform(RTC_FROM_HERE, [=](NetworkManager *networkManager) { |
| 236 | networkManager->sendTransportService(cause); |
| 237 | }); |
| 238 | } |
| 239 | }; |
| 240 | if (delayMs) { |
| 241 | thread->PostDelayedTask(RTC_FROM_HERE, task, delayMs); |
| 242 | } else { |
| 243 | thread->PostTask(RTC_FROM_HERE, task); |
| 244 | } |
| 245 | }); |
| 246 | })); |
| 247 | bool isOutgoing = _encryptionKey.isOutgoing; |
| 248 | _mediaManager.reset(new ThreadLocalObject<MediaManager>(getMediaThread(), [weak, isOutgoing, protocolVersion = _protocolVersion, thread, sendSignalingMessage, videoCapture = _videoCapture, mediaDevicesConfig = _mediaDevicesConfig, enableHighBitrateVideo = _enableHighBitrateVideo, signalBarsUpdated = _signalBarsUpdated, audioLevelUpdated = _audioLevelUpdated, preferredCodecs = _preferredCodecs, platformContext = _platformContext]() { |
| 249 | return new MediaManager( |
| 250 | getMediaThread(), |
| 251 | isOutgoing, |
| 252 | protocolVersion, |
| 253 | mediaDevicesConfig, |
| 254 | videoCapture, |
| 255 | sendSignalingMessage, |
| 256 | [=](Message &&message) { |
| 257 | thread->PostTask(RTC_FROM_HERE, [=, message = std::move(message)]() mutable { |
| 258 | const auto strong = weak.lock(); |
| 259 | if (!strong) { |
| 260 | return; |
| 261 | } |
| 262 | strong->_sendTransportMessage(std::move(message)); |
| 263 | }); |
| 264 | }, |
| 265 | signalBarsUpdated, |
| 266 | audioLevelUpdated, |
| 267 | enableHighBitrateVideo, |
| 268 | preferredCodecs, |
| 269 | platformContext); |
| 270 | })); |
| 271 | _networkManager->perform(RTC_FROM_HERE, [](NetworkManager *networkManager) { |
| 272 | networkManager->start(); |
| 273 | }); |
| 274 | _mediaManager->perform(RTC_FROM_HERE, [](MediaManager *mediaManager) { |
| 275 | mediaManager->start(); |
| 276 | }); |
| 277 | } |
| 278 |
| 279 | void Manager::receiveSignalingData(const std::vector<uint8_t> &data) { |
| 280 | if (auto decrypted = _signaling.handleIncomingPacket((const char*)data.data(), data.size())) { |
| 281 | receiveMessage(std::move(decrypted->main)); |
| 282 | for (auto &message : decrypted->additional) { |
| 283 | receiveMessage(std::move(message)); |
| 284 | } |
| 285 | } |
| 286 | } |
| 287 |
| 288 | void Manager::receiveMessage(DecryptedMessage &&message) { |
| 289 | const auto data = &message.message.data; |
| 290 | if (const auto candidatesList = absl::get_if<CandidatesListMessage>(data)) { |
| 291 | _networkManager->perform(RTC_FROM_HERE, [message = std::move(message)](NetworkManager *networkManager) mutable { |
| 292 | networkManager->receiveSignalingMessage(std::move(message)); |
| 293 | }); |
| 294 | } else if (const auto videoFormats = absl::get_if<VideoFormatsMessage>(data)) { |
| 295 | _mediaManager->perform(RTC_FROM_HERE, [message = std::move(message)](MediaManager *mediaManager) mutable { |
| 296 | mediaManager->receiveMessage(std::move(message)); |
| 297 | }); |
| 298 | } else if (const auto remoteMediaState = absl::get_if<RemoteMediaStateMessage>(data)) { |
| 299 | if (_remoteMediaStateUpdated) { |
| 300 | _remoteMediaStateUpdated( |
| 301 | remoteMediaState->audio, |
| 302 | remoteMediaState->video); |
| 303 | } |
| 304 | _mediaManager->perform(RTC_FROM_HERE, [video = remoteMediaState->video](MediaManager *mediaManager) { |
| 305 | mediaManager->remoteVideoStateUpdated(video); |
| 306 | }); |
| 307 | } else if (const auto remoteBatteryLevelIsLow = absl::get_if<RemoteBatteryLevelIsLowMessage>(data)) { |
| 308 | if (_remoteBatteryLevelIsLowUpdated) { |
| 309 | _remoteBatteryLevelIsLowUpdated(remoteBatteryLevelIsLow->batteryLow); |
| 310 | } |
| 311 | } else if (const auto remoteNetworkStatus = absl::get_if<RemoteNetworkStatusMessage>(data)) { |
| 312 | _remoteNetworkIsLowCost = remoteNetworkStatus->isLowCost; |
| 313 | _remoteIsLowDataRequested = remoteNetworkStatus->isLowDataRequested; |
| 314 | updateCurrentResolvedNetworkStatus(); |
| 315 | } else { |
| 316 | if (const auto videoParameters = absl::get_if<VideoParametersMessage>(data)) { |
| 317 | float value = ((float)videoParameters->aspectRatio) / 1000.0; |
| 318 | if (_remotePrefferedAspectRatioUpdated) { |
| 319 | _remotePrefferedAspectRatioUpdated(value); |
| 320 | } |
| 321 | } |
| 322 | _mediaManager->perform(RTC_FROM_HERE, [=, message = std::move(message)](MediaManager *mediaManager) mutable { |
| 323 | mediaManager->receiveMessage(std::move(message)); |
| 324 | }); |
| 325 | } |
| 326 | } |
| 327 |
| 328 | void Manager::setVideoCapture(std::shared_ptr<VideoCaptureInterface> videoCapture) { |
| 329 | assert(_didConnectOnce); |
| 330 |
| 331 | if (_videoCapture == videoCapture) { |
| 332 | return; |
| 333 | } |
| 334 | _videoCapture = videoCapture; |
| 335 | _mediaManager->perform(RTC_FROM_HERE, [videoCapture](MediaManager *mediaManager) { |
| 336 | mediaManager->setSendVideo(videoCapture); |
| 337 | }); |
| 338 | } |
| 339 |
| 340 | void Manager::setRequestedVideoAspect(float aspect) { |
| 341 | _mediaManager->perform(RTC_FROM_HERE, [aspect](MediaManager *mediaManager) { |
| 342 | mediaManager->setRequestedVideoAspect(aspect); |
| 343 | }); |
| 344 | } |
| 345 |
| 346 | void Manager::setMuteOutgoingAudio(bool mute) { |
| 347 | _mediaManager->perform(RTC_FROM_HERE, [mute](MediaManager *mediaManager) { |
| 348 | mediaManager->setMuteOutgoingAudio(mute); |
| 349 | }); |
| 350 | } |
| 351 |
| 352 | void Manager::setIncomingVideoOutput(std::shared_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) { |
| 353 | _mediaManager->perform(RTC_FROM_HERE, [sink](MediaManager *mediaManager) { |
| 354 | mediaManager->setIncomingVideoOutput(sink); |
| 355 | }); |
| 356 | } |
| 357 |
| 358 | void Manager::setIsLowBatteryLevel(bool isLowBatteryLevel) { |
| 359 | _sendTransportMessage({ RemoteBatteryLevelIsLowMessage{ isLowBatteryLevel } }); |
| 360 | } |
| 361 |
| 362 | void Manager::setIsLocalNetworkLowCost(bool isLocalNetworkLowCost) { |
| 363 | if (isLocalNetworkLowCost != _localNetworkIsLowCost) { |
| 364 | _networkManager->perform(RTC_FROM_HERE, [isLocalNetworkLowCost](NetworkManager *networkManager) { |
| 365 | networkManager->setIsLocalNetworkLowCost(isLocalNetworkLowCost); |
| 366 | }); |
| 367 |
| 368 | _localNetworkIsLowCost = isLocalNetworkLowCost; |
| 369 | updateCurrentResolvedNetworkStatus(); |
| 370 | } |
| 371 | } |
| 372 |
| 373 | void Manager::getNetworkStats(std::function<void (TrafficStats, CallStats)> completion) { |
| 374 | _networkManager->perform(RTC_FROM_HERE, [thread = _thread, weak = std::weak_ptr<Manager>(shared_from_this()), completion = std::move(completion), statsLogPath = _statsLogPath](NetworkManager *networkManager) { |
| 375 | auto networkStats = networkManager->getNetworkStats(); |
| 376 |
| 377 | CallStats callStats; |
| 378 | networkManager->fillCallStats(callStats); |
| 379 |
| 380 | thread->PostTask(RTC_FROM_HERE, [weak, networkStats, completion = std::move(completion), callStats = std::move(callStats), statsLogPath = statsLogPath] { |
| 381 | const auto strong = weak.lock(); |
| 382 | if (!strong) { |
| 383 | return; |
| 384 | } |
| 385 |
| 386 | strong->_mediaManager->perform(RTC_FROM_HERE, [networkStats, completion = std::move(completion), callStatsValue = std::move(callStats), statsLogPath = statsLogPath](MediaManager *mediaManager) { |
| 387 | CallStats callStats = std::move(callStatsValue); |
| 388 | mediaManager->fillCallStats(callStats); |
| 389 | dumpStatsLog(statsLogPath, callStats); |
| 390 | completion(networkStats, callStats); |
| 391 | }); |
| 392 | }); |
| 393 | }); |
| 394 | } |
| 395 |
| 396 | void Manager::updateCurrentResolvedNetworkStatus() { |
| 397 | bool localIsLowDataRequested = false; |
| 398 | switch (_dataSaving) { |
| 399 | case DataSaving::Never: |
| 400 | localIsLowDataRequested = false; |
| 401 | break; |
| 402 | case DataSaving::Mobile: |
| 403 | localIsLowDataRequested = !_localNetworkIsLowCost; |
| 404 | break; |
| 405 | case DataSaving::Always: |
| 406 | localIsLowDataRequested = true; |
| 407 | default: |
| 408 | break; |
| 409 | } |
| 410 |
| 411 | ResolvedNetworkStatus localStatus; |
| 412 | localStatus.isLowCost = _localNetworkIsLowCost; |
| 413 | localStatus.isLowDataRequested = localIsLowDataRequested; |
| 414 |
| 415 | if (!_currentResolvedLocalNetworkStatus.has_value() || *_currentResolvedLocalNetworkStatus != localStatus) { |
| 416 | _currentResolvedLocalNetworkStatus = localStatus; |
| 417 |
| 418 | switch (_protocolVersion) { |
| 419 | case ProtocolVersion::V1: |
| 420 | if (_didConnectOnce) { |
| 421 | _sendTransportMessage({ RemoteNetworkStatusMessage{ localStatus.isLowCost, localStatus.isLowDataRequested } }); |
| 422 | } |
| 423 | break; |
| 424 | default: |
| 425 | break; |
| 426 | } |
| 427 | } |
| 428 |
| 429 | ResolvedNetworkStatus status; |
| 430 | status.isLowCost = _localNetworkIsLowCost && _remoteNetworkIsLowCost; |
| 431 | status.isLowDataRequested = localIsLowDataRequested || _remoteIsLowDataRequested; |
| 432 |
| 433 | if (!_currentResolvedNetworkStatus.has_value() || *_currentResolvedNetworkStatus != status) { |
| 434 | _currentResolvedNetworkStatus = status; |
| 435 | _mediaManager->perform(RTC_FROM_HERE, [status](MediaManager *mediaManager) { |
| 436 | mediaManager->setNetworkParameters(status.isLowCost, status.isLowDataRequested); |
| 437 | }); |
| 438 | } |
| 439 | } |
| 440 |
| 441 | void Manager::sendInitialSignalingMessages() { |
| 442 | if (_currentResolvedLocalNetworkStatus.has_value()) { |
| 443 | switch (_protocolVersion) { |
| 444 | case ProtocolVersion::V1: |
| 445 | _sendTransportMessage({ RemoteNetworkStatusMessage{ _currentResolvedLocalNetworkStatus->isLowCost, _currentResolvedLocalNetworkStatus->isLowDataRequested } }); |
| 446 | break; |
| 447 | default: |
| 448 | break; |
| 449 | } |
| 450 | } |
| 451 | } |
| 452 |
| 453 | void Manager::setAudioInputDevice(std::string id) { |
| 454 | _mediaManager->perform(RTC_FROM_HERE, [id](MediaManager *mediaManager) { |
| 455 | mediaManager->setAudioInputDevice(id); |
| 456 | }); |
| 457 | } |
| 458 |
| 459 | void Manager::setAudioOutputDevice(std::string id) { |
| 460 | _mediaManager->perform(RTC_FROM_HERE, [id](MediaManager *mediaManager) { |
| 461 | mediaManager->setAudioOutputDevice(id); |
| 462 | }); |
| 463 | } |
| 464 |
| 465 | void Manager::setInputVolume(float level) { |
| 466 | _mediaManager->perform(RTC_FROM_HERE, [level](MediaManager *mediaManager) { |
| 467 | mediaManager->setInputVolume(level); |
| 468 | }); |
| 469 | } |
| 470 |
| 471 | void Manager::setOutputVolume(float level) { |
| 472 | _mediaManager->perform(RTC_FROM_HERE, [level](MediaManager *mediaManager) { |
| 473 | mediaManager->setOutputVolume(level); |
| 474 | }); |
| 475 | } |
| 476 |
| 477 | } // namespace tgcalls |
| 478 |