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