| 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 |
| 107 | assert(_thread->IsCurrent()); |
| 108 | assert(_stateUpdated != nullptr); |
| 109 | assert(_signalingDataEmitted != nullptr); |
| 110 |
| 111 | _preferredCodecs = descriptor.config.preferredVideoCodecs; |
| 112 |
| 113 | _sendSignalingMessage = [=](const Message &message) { |
| 114 | if (const auto prepared = _signaling.prepareForSending(message)) { |
| 115 | _signalingDataEmitted(prepared->bytes); |
| 116 | return prepared->counter; |
| 117 | } |
| 118 | return uint32_t(0); |
| 119 | }; |
| 120 | _sendTransportMessage = [=](Message &&message) { |
| 121 | _networkManager->perform([message = std::move(message)](NetworkManager *networkManager) { |
| 122 | networkManager->sendMessage(message); |
| 123 | }); |
| 124 | }; |
| 125 | } |
| 126 |
| 127 | Manager::~Manager() { |
| 128 | assert(_thread->IsCurrent()); |
| 129 | } |
| 130 |
| 131 | void Manager::sendSignalingAsync(int delayMs, int cause) { |
| 132 | auto task = [weak = std::weak_ptr<Manager>(shared_from_this()), cause] { |
| 133 | const auto strong = weak.lock(); |
| 134 | if (!strong) { |
| 135 | return; |
| 136 | } |
| 137 | if (const auto prepared = strong->_signaling.prepareForSendingService(cause)) { |
| 138 | strong->_signalingDataEmitted(prepared->bytes); |
| 139 | } |
| 140 | }; |
| 141 | if (delayMs) { |
| 142 | _thread->PostDelayedTask(std::move(task), webrtc::TimeDelta::Millis(delayMs)); |
| 143 | } else { |
| 144 | _thread->PostTask(std::move(task)); |
| 145 | } |
| 146 | } |
| 147 |
| 148 | void Manager::start() { |
| 149 | const auto weak = std::weak_ptr<Manager>(shared_from_this()); |
| 150 | const auto thread = _thread; |
| 151 | const auto sendSignalingMessage = [=](Message &&message) { |
| 152 | thread->PostTask([=, message = std::move(message)]() mutable { |
| 153 | const auto strong = weak.lock(); |
| 154 | if (!strong) { |
| 155 | return; |
| 156 | } |
| 157 | strong->_sendSignalingMessage(std::move(message)); |
| 158 | }); |
| 159 | }; |
| 160 | _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 { |
| 161 | return new NetworkManager( |
| 162 | StaticThreads::getNetworkThread(), |
| 163 | encryptionKey, |
| 164 | enableP2P, |
| 165 | enableTCP, |
| 166 | enableStunMarking, |
| 167 | rtcServers, |
| 168 | std::move(proxy), |
| 169 | [=](const NetworkManager::State &state) { |
| 170 | thread->PostTask([=] { |
| 171 | const auto strong = weak.lock(); |
| 172 | if (!strong) { |
| 173 | return; |
| 174 | } |
| 175 | State mappedState; |
| 176 | if (state.isFailed) { |
| 177 | mappedState = State::Failed; |
| 178 | } else { |
| 179 | mappedState = state.isReadyToSendData |
| 180 | ? State::Established |
| 181 | : State::Reconnecting; |
| 182 | } |
| 183 | bool isFirstConnection = false; |
| 184 | if (state.isReadyToSendData) { |
| 185 | if (!strong->_didConnectOnce) { |
| 186 | strong->_didConnectOnce = true; |
| 187 | isFirstConnection = true; |
| 188 | } |
| 189 | } |
| 190 | strong->_state = mappedState; |
| 191 | strong->_stateUpdated(mappedState); |
| 192 |
| 193 | strong->_mediaManager->perform([=](MediaManager *mediaManager) { |
| 194 | mediaManager->setIsConnected(state.isReadyToSendData); |
| 195 | }); |
| 196 |
| 197 | if (isFirstConnection) { |
| 198 | strong->sendInitialSignalingMessages(); |
| 199 | } |
| 200 | }); |
| 201 | }, |
| 202 | [=](DecryptedMessage &&message) { |
| 203 | thread->PostTask([=, message = std::move(message)]() mutable { |
| 204 | if (const auto strong = weak.lock()) { |
| 205 | strong->receiveMessage(std::move(message)); |
| 206 | } |
| 207 | }); |
| 208 | }, |
| 209 | sendSignalingMessage, |
| 210 | [=](int delayMs, int cause) { |
| 211 | const auto task = [=] { |
| 212 | if (const auto strong = weak.lock()) { |
| 213 | strong->_networkManager->perform([=](NetworkManager *networkManager) { |
| 214 | networkManager->sendTransportService(cause); |
| 215 | }); |
| 216 | } |
| 217 | }; |
| 218 | if (delayMs) { |
| 219 | thread->PostDelayedTask(task, webrtc::TimeDelta::Millis(delayMs)); |
| 220 | } else { |
| 221 | thread->PostTask(task); |
| 222 | } |
| 223 | }); |
| 224 | })); |
| 225 | bool isOutgoing = _encryptionKey.isOutgoing; |
| 226 | _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]() { |
| 227 | return new MediaManager( |
| 228 | StaticThreads::getMediaThread(), |
| 229 | isOutgoing, |
| 230 | protocolVersion, |
| 231 | mediaDevicesConfig, |
| 232 | videoCapture, |
| 233 | sendSignalingMessage, |
| 234 | [=](Message &&message) { |
| 235 | thread->PostTask([=, message = std::move(message)]() mutable { |
| 236 | const auto strong = weak.lock(); |
| 237 | if (!strong) { |
| 238 | return; |
| 239 | } |
| 240 | strong->_sendTransportMessage(std::move(message)); |
| 241 | }); |
| 242 | }, |
| 243 | signalBarsUpdated, |
| 244 | audioLevelsUpdated, |
| 245 | createAudioDeviceModule, |
| 246 | enableHighBitrateVideo, |
| 247 | preferredCodecs, |
| 248 | platformContext); |
| 249 | })); |
| 250 | _networkManager->perform([](NetworkManager *networkManager) { |
| 251 | networkManager->start(); |
| 252 | }); |
| 253 | _mediaManager->perform([](MediaManager *mediaManager) { |
| 254 | mediaManager->start(); |
| 255 | }); |
| 256 | } |
| 257 |
| 258 | void Manager::receiveSignalingData(const std::vector<uint8_t> &data) { |
| 259 | if (auto decrypted = _signaling.handleIncomingPacket((const char*)data.data(), data.size())) { |
| 260 | receiveMessage(std::move(decrypted->main)); |
| 261 | for (auto &message : decrypted->additional) { |
| 262 | receiveMessage(std::move(message)); |
| 263 | } |
| 264 | } |
| 265 | } |
| 266 |
| 267 | void Manager::receiveMessage(DecryptedMessage &&message) { |
| 268 | const auto data = &message.message.data; |
| 269 | if (const auto candidatesList = absl::get_if<CandidatesListMessage>(data)) { |
| 270 | _networkManager->perform([message = std::move(message)](NetworkManager *networkManager) mutable { |
| 271 | networkManager->receiveSignalingMessage(std::move(message)); |
| 272 | }); |
| 273 | } else if (const auto videoFormats = absl::get_if<VideoFormatsMessage>(data)) { |
| 274 | _mediaManager->perform([message = std::move(message)](MediaManager *mediaManager) mutable { |
| 275 | mediaManager->receiveMessage(std::move(message)); |
| 276 | }); |
| 277 | } else if (const auto remoteMediaState = absl::get_if<RemoteMediaStateMessage>(data)) { |
| 278 | if (_remoteMediaStateUpdated) { |
| 279 | _remoteMediaStateUpdated( |
| 280 | remoteMediaState->audio, |
| 281 | remoteMediaState->video); |
| 282 | } |
| 283 | _mediaManager->perform([video = remoteMediaState->video](MediaManager *mediaManager) { |
| 284 | mediaManager->remoteVideoStateUpdated(video); |
| 285 | }); |
| 286 | } else if (const auto remoteBatteryLevelIsLow = absl::get_if<RemoteBatteryLevelIsLowMessage>(data)) { |
| 287 | if (_remoteBatteryLevelIsLowUpdated) { |
| 288 | _remoteBatteryLevelIsLowUpdated(remoteBatteryLevelIsLow->batteryLow); |
| 289 | } |
| 290 | } else if (const auto remoteNetworkStatus = absl::get_if<RemoteNetworkStatusMessage>(data)) { |
| 291 | _remoteNetworkIsLowCost = remoteNetworkStatus->isLowCost; |
| 292 | _remoteIsLowDataRequested = remoteNetworkStatus->isLowDataRequested; |
| 293 | updateCurrentResolvedNetworkStatus(); |
| 294 | } else { |
| 295 | if (const auto videoParameters = absl::get_if<VideoParametersMessage>(data)) { |
| 296 | float value = ((float)videoParameters->aspectRatio) / 1000.0; |
| 297 | if (_remotePrefferedAspectRatioUpdated) { |
| 298 | _remotePrefferedAspectRatioUpdated(value); |
| 299 | } |
| 300 | } |
| 301 | _mediaManager->perform([=, message = std::move(message)](MediaManager *mediaManager) mutable { |
| 302 | mediaManager->receiveMessage(std::move(message)); |
| 303 | }); |
| 304 | } |
| 305 | } |
| 306 |
| 307 | void Manager::setVideoCapture(std::shared_ptr<VideoCaptureInterface> videoCapture) { |
| 308 | assert(_didConnectOnce); |
| 309 |
| 310 | if (_videoCapture == videoCapture) { |
| 311 | return; |
| 312 | } |
| 313 | _videoCapture = videoCapture; |
| 314 | _mediaManager->perform([videoCapture](MediaManager *mediaManager) { |
| 315 | mediaManager->setSendVideo(videoCapture); |
| 316 | }); |
| 317 | } |
| 318 |
| 319 | void Manager::sendVideoDeviceUpdated() { |
| 320 | _mediaManager->perform([](MediaManager *mediaManager) { |
| 321 | mediaManager->sendVideoDeviceUpdated(); |
| 322 | }); |
| 323 | } |
| 324 |
| 325 | void Manager::setRequestedVideoAspect(float aspect) { |
| 326 | _mediaManager->perform([aspect](MediaManager *mediaManager) { |
| 327 | mediaManager->setRequestedVideoAspect(aspect); |
| 328 | }); |
| 329 | } |
| 330 |
| 331 | void Manager::setMuteOutgoingAudio(bool mute) { |
| 332 | _mediaManager->perform([mute](MediaManager *mediaManager) { |
| 333 | mediaManager->setMuteOutgoingAudio(mute); |
| 334 | }); |
| 335 | } |
| 336 |
| 337 | void Manager::setIncomingVideoOutput(std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) { |
| 338 | _mediaManager->perform([sink](MediaManager *mediaManager) { |
| 339 | mediaManager->setIncomingVideoOutput(sink); |
| 340 | }); |
| 341 | } |
| 342 |
| 343 | void Manager::setIsLowBatteryLevel(bool isLowBatteryLevel) { |
| 344 | _sendTransportMessage({ RemoteBatteryLevelIsLowMessage{ isLowBatteryLevel } }); |
| 345 | } |
| 346 |
| 347 | void Manager::setIsLocalNetworkLowCost(bool isLocalNetworkLowCost) { |
| 348 | if (isLocalNetworkLowCost != _localNetworkIsLowCost) { |
| 349 | _networkManager->perform([isLocalNetworkLowCost](NetworkManager *networkManager) { |
| 350 | networkManager->setIsLocalNetworkLowCost(isLocalNetworkLowCost); |
| 351 | }); |
| 352 |
| 353 | _localNetworkIsLowCost = isLocalNetworkLowCost; |
| 354 | updateCurrentResolvedNetworkStatus(); |
| 355 | } |
| 356 | } |
| 357 |
| 358 | void Manager::getNetworkStats(std::function<void (TrafficStats, CallStats)> completion) { |
| 359 | _networkManager->perform([thread = _thread, weak = std::weak_ptr<Manager>(shared_from_this()), completion = std::move(completion), statsLogPath = _statsLogPath](NetworkManager *networkManager) { |
| 360 | auto networkStats = networkManager->getNetworkStats(); |
| 361 |
| 362 | CallStats callStats; |
| 363 | networkManager->fillCallStats(callStats); |
| 364 |
| 365 | thread->PostTask([weak, networkStats, completion = std::move(completion), callStats = std::move(callStats), statsLogPath = statsLogPath] { |
| 366 | const auto strong = weak.lock(); |
| 367 | if (!strong) { |
| 368 | return; |
| 369 | } |
| 370 |
| 371 | strong->_mediaManager->perform([networkStats, completion = std::move(completion), callStatsValue = std::move(callStats), statsLogPath = statsLogPath](MediaManager *mediaManager) { |
| 372 | CallStats callStats = std::move(callStatsValue); |
| 373 | mediaManager->fillCallStats(callStats); |
| 374 | dumpStatsLog(statsLogPath, callStats); |
| 375 | completion(networkStats, callStats); |
| 376 | }); |
| 377 | }); |
| 378 | }); |
| 379 | } |
| 380 |
| 381 | void Manager::updateCurrentResolvedNetworkStatus() { |
| 382 | bool localIsLowDataRequested = false; |
| 383 | switch (_dataSaving) { |
| 384 | case DataSaving::Never: |
| 385 | localIsLowDataRequested = false; |
| 386 | break; |
| 387 | case DataSaving::Mobile: |
| 388 | localIsLowDataRequested = !_localNetworkIsLowCost; |
| 389 | break; |
| 390 | case DataSaving::Always: |
| 391 | localIsLowDataRequested = true; |
| 392 | default: |
| 393 | break; |
| 394 | } |
| 395 |
| 396 | ResolvedNetworkStatus localStatus; |
| 397 | localStatus.isLowCost = _localNetworkIsLowCost; |
| 398 | localStatus.isLowDataRequested = localIsLowDataRequested; |
| 399 |
| 400 | if (!_currentResolvedLocalNetworkStatus.has_value() || *_currentResolvedLocalNetworkStatus != localStatus) { |
| 401 | _currentResolvedLocalNetworkStatus = localStatus; |
| 402 |
| 403 | switch (_protocolVersion) { |
| 404 | case ProtocolVersion::V1: |
| 405 | if (_didConnectOnce) { |
| 406 | _sendTransportMessage({ RemoteNetworkStatusMessage{ localStatus.isLowCost, localStatus.isLowDataRequested } }); |
| 407 | } |
| 408 | break; |
| 409 | default: |
| 410 | break; |
| 411 | } |
| 412 | } |
| 413 |
| 414 | ResolvedNetworkStatus status; |
| 415 | status.isLowCost = _localNetworkIsLowCost && _remoteNetworkIsLowCost; |
| 416 | status.isLowDataRequested = localIsLowDataRequested || _remoteIsLowDataRequested; |
| 417 |
| 418 | if (!_currentResolvedNetworkStatus.has_value() || *_currentResolvedNetworkStatus != status) { |
| 419 | _currentResolvedNetworkStatus = status; |
| 420 | _mediaManager->perform([status](MediaManager *mediaManager) { |
| 421 | mediaManager->setNetworkParameters(status.isLowCost, status.isLowDataRequested); |
| 422 | }); |
| 423 | } |
| 424 | } |
| 425 |
| 426 | void Manager::sendInitialSignalingMessages() { |
| 427 | if (_currentResolvedLocalNetworkStatus.has_value()) { |
| 428 | switch (_protocolVersion) { |
| 429 | case ProtocolVersion::V1: |
| 430 | _sendTransportMessage({ RemoteNetworkStatusMessage{ _currentResolvedLocalNetworkStatus->isLowCost, _currentResolvedLocalNetworkStatus->isLowDataRequested } }); |
| 431 | break; |
| 432 | default: |
| 433 | break; |
| 434 | } |
| 435 | } |
| 436 | } |
| 437 |
| 438 | void Manager::setAudioInputDevice(std::string id) { |
| 439 | _mediaManager->perform([id](MediaManager *mediaManager) { |
| 440 | mediaManager->setAudioInputDevice(id); |
| 441 | }); |
| 442 | } |
| 443 |
| 444 | void Manager::setAudioOutputDevice(std::string id) { |
| 445 | _mediaManager->perform([id](MediaManager *mediaManager) { |
| 446 | mediaManager->setAudioOutputDevice(id); |
| 447 | }); |
| 448 | } |
| 449 |
| 450 | void Manager::setInputVolume(float level) { |
| 451 | _mediaManager->perform([level](MediaManager *mediaManager) { |
| 452 | mediaManager->setInputVolume(level); |
| 453 | }); |
| 454 | } |
| 455 |
| 456 | void Manager::setOutputVolume(float level) { |
| 457 | _mediaManager->perform([level](MediaManager *mediaManager) { |
| 458 | mediaManager->setOutputVolume(level); |
| 459 | }); |
| 460 | } |
| 461 |
| 462 | void Manager::addExternalAudioSamples(std::vector<uint8_t> &&samples) { |
| 463 | _mediaManager->perform([samples = std::move(samples)](MediaManager *mediaManager) mutable { |
| 464 | mediaManager->addExternalAudioSamples(std::move(samples)); |
| 465 | }); |
| 466 | } |
| 467 |
| 468 | } // namespace tgcalls |
| 469 |