| #include "VideoCapturerInterface.h" |
| 6 | #include "v2/NativeNetworkingImpl.h" |
| 7 | #include "v2/Signaling.h" |
| 8 | #include "v2/ContentNegotiation.h" |
| 9 |
| 10 | #include "CodecSelectHelper.h" |
| 11 |
| 12 | #include "api/audio_codecs/audio_decoder_factory_template.h" |
| 13 | #include "api/audio_codecs/audio_encoder_factory_template.h" |
| 14 | #include "api/audio_codecs/opus/audio_decoder_opus.h" |
| 15 | #include "api/audio_codecs/opus/audio_decoder_multi_channel_opus.h" |
| 16 | #include "api/audio_codecs/opus/audio_encoder_opus.h" |
| 17 | #include "api/audio_codecs/L16/audio_decoder_L16.h" |
| 18 | #include "api/audio_codecs/L16/audio_encoder_L16.h" |
| 19 | #include "api/task_queue/default_task_queue_factory.h" |
| 20 | #include "media/engine/webrtc_media_engine.h" |
| 21 | #include "system_wrappers/include/field_trial.h" |
| 22 | #include "api/video/builtin_video_bitrate_allocator_factory.h" |
| 23 | #include "call/call.h" |
| 24 | #include "api/call/audio_sink.h" |
| 25 | #include "modules/audio_processing/audio_buffer.h" |
| 26 | #include "absl/strings/match.h" |
| 27 | #include "audio/audio_state.h" |
| 28 | #include "modules/audio_coding/neteq/default_neteq_factory.h" |
| 29 | #include "modules/audio_coding/include/audio_coding_module.h" |
| 30 | #include "api/candidate.h" |
| 31 | #include "api/jsep_ice_candidate.h" |
| 32 | #include "pc/used_ids.h" |
| 33 | #include "media/base/sdp_video_format_utils.h" |
| 34 | #include "pc/media_session.h" |
| 35 | #include "rtc_base/rtc_certificate_generator.h" |
| 36 | #include "pc/peer_connection.h" |
| 37 | #include "pc/peer_connection_proxy.h" |
| 38 | #include "api/rtc_event_log/rtc_event_log_factory.h" |
| 39 | #include "api/stats/rtc_stats_report.h" |
| 40 | #include "api/enable_media.h" |
| 41 | #include "p2p/client/basic_port_allocator.h" |
| 42 | #include "p2p/base/basic_packet_socket_factory.h" |
| 43 | #include "rtc_base/network.h" |
| 44 | #include "p2p/base/default_ice_transport_factory.h" |
| 45 |
| 46 | #include "AudioFrame.h" |
| 47 | #include "ThreadLocalObject.h" |
| 48 | #include "Manager.h" |
| 49 | #include "NetworkManager.h" |
| 50 | #include "VideoCaptureInterfaceImpl.h" |
| 51 | #include "platform/PlatformInterface.h" |
| 52 | #include "LogSinkImpl.h" |
| 53 | #include "CodecSelectHelper.h" |
| 54 | #include "AudioDeviceHelper.h" |
| 55 | #include "SignalingEncryption.h" |
| 56 | #include "ReflectorRelayPortFactory.h" |
| 57 | #include "v2/SignalingConnection.h" |
| 58 | #include "v2/ExternalSignalingConnection.h" |
| 59 | #include "v2/SignalingSctpConnection.h" |
| 60 | #include "v2/ReflectorRelayPortFactory.h" |
| 61 | #ifdef WEBRTC_IOS |
| 62 | #include "platform/darwin/iOS/tgcalls_audio_device_module_ios.h" |
| 63 | #endif |
| 64 | #include <random> |
| 65 | #include <sstream> |
| 66 | #include <map> |
| 67 |
| 68 | #include "third-party/json11.hpp" |
| 69 | #include "utils/gzip.h" |
| 70 |
| 71 | namespace tgcalls { |
| 72 | namespace { |
| 73 |
| 74 | enum class SignalingProtocolVersion { |
| 75 | V1, |
| 76 | V2 |
| 77 | }; |
| 78 |
| 79 | SignalingProtocolVersion signalingProtocolVersion(std::string const &version) { |
| 80 | if (version == "10.0.0") { |
| 81 | return SignalingProtocolVersion::V1; |
| 82 | } else if (version == "11.0.0") { |
| 83 | return SignalingProtocolVersion::V2; |
| 84 | } else { |
| 85 | RTC_LOG(LS_ERROR) << "signalingProtocolVersion: unknown version " << version; |
| 86 |
| 87 | return SignalingProtocolVersion::V2; |
| 88 | } |
| 89 | } |
| 90 |
| 91 | bool signalingProtocolSupportsCompression(SignalingProtocolVersion version) { |
| 92 | switch (version) { |
| 93 | case SignalingProtocolVersion::V1: |
| 94 | return false; |
| 95 | case SignalingProtocolVersion::V2: |
| 96 | return true; |
| 97 | default: |
| 98 | RTC_DCHECK_NOTREACHED(); |
| 99 | break; |
| 100 | } |
| 101 | return false; |
| 102 | } |
| 103 |
| 104 | static VideoCaptureInterfaceObject *GetVideoCaptureAssumingSameThread(VideoCaptureInterface *videoCapture) { |
| 105 | return videoCapture |
| 106 | ? static_cast<VideoCaptureInterfaceImpl*>(videoCapture)->object()->getSyncAssumingSameThread() |
| 107 | : nullptr; |
| 108 | } |
| 109 |
| 110 | class SetSessionDescriptionObserver : public webrtc::SetLocalDescriptionObserverInterface, public webrtc::SetRemoteDescriptionObserverInterface { |
| 111 | public: |
| 112 | SetSessionDescriptionObserver(std::function<void(webrtc::RTCError)> &&completion) : |
| 113 | _completion(std::move(completion)) { |
| 114 | } |
| 115 |
| 116 | virtual void OnSetLocalDescriptionComplete(webrtc::RTCError error) override { |
| 117 | OnCompelete(error); |
| 118 | } |
| 119 |
| 120 | virtual void OnSetRemoteDescriptionComplete(webrtc::RTCError error) override { |
| 121 | OnCompelete(error); |
| 122 | } |
| 123 |
| 124 | private: |
| 125 | void OnCompelete(webrtc::RTCError error) { |
| 126 | _completion(error); |
| 127 | } |
| 128 |
| 129 | std::function<void(webrtc::RTCError)> _completion; |
| 130 | }; |
| 131 |
| 132 | class PeerConnectionDelegateAdapter: public webrtc::PeerConnectionObserver { |
| 133 | public: |
| 134 | struct Parameters { |
| 135 | std::function<void()> onRenegotiationNeeded; |
| 136 | std::function<void(const webrtc::IceCandidateInterface *)> onIceCandidate; |
| 137 | std::function<void(webrtc::PeerConnectionInterface::SignalingState state)> onSignalingChange; |
| 138 | std::function<void(webrtc::PeerConnectionInterface::IceConnectionState state)> onConnectionChange; |
| 139 | std::function<void(webrtc::scoped_refptr<webrtc::DataChannelInterface>)> onDataChannel; |
| 140 | std::function<void(webrtc::scoped_refptr<webrtc::RtpTransceiverInterface>)> onTransceiverAdded; |
| 141 | std::function<void(webrtc::scoped_refptr<webrtc::RtpReceiverInterface>)> onTransceiverRemoved; |
| 142 | std::function<void(const cricket::CandidatePairChangeEvent &)> onCandidatePairChangeEvent; |
| 143 | }; |
| 144 |
| 145 | public: |
| 146 | PeerConnectionDelegateAdapter( |
| 147 | Parameters &¶meters |
| 148 | ) : _parameters(std::move(parameters)) { |
| 149 | } |
| 150 |
| 151 | ~PeerConnectionDelegateAdapter() override { |
| 152 | } |
| 153 |
| 154 | void OnSignalingChange(webrtc::PeerConnectionInterface::SignalingState new_state) override { |
| 155 | if (_parameters.onSignalingChange) { |
| 156 | _parameters.onSignalingChange(new_state); |
| 157 | } |
| 158 | } |
| 159 |
| 160 | void OnAddStream(webrtc::scoped_refptr<webrtc::MediaStreamInterface> stream) override { |
| 161 | } |
| 162 |
| 163 | void OnRemoveStream(webrtc::scoped_refptr<webrtc::MediaStreamInterface> stream) override { |
| 164 | } |
| 165 |
| 166 | void OnTrack(webrtc::scoped_refptr<webrtc::RtpTransceiverInterface> transceiver) override { |
| 167 | if (_parameters.onTransceiverAdded) { |
| 168 | _parameters.onTransceiverAdded(transceiver); |
| 169 | } |
| 170 | } |
| 171 |
| 172 | void OnDataChannel(webrtc::scoped_refptr<webrtc::DataChannelInterface> data_channel) override { |
| 173 | if (_parameters.onDataChannel) { |
| 174 | _parameters.onDataChannel(data_channel); |
| 175 | } |
| 176 | } |
| 177 |
| 178 | void OnRenegotiationNeeded() override { |
| 179 | if (_parameters.onRenegotiationNeeded) { |
| 180 | _parameters.onRenegotiationNeeded(); |
| 181 | } |
| 182 | } |
| 183 |
| 184 | void OnIceConnectionChange(webrtc::PeerConnectionInterface::IceConnectionState new_state) override { |
| 185 | if (_parameters.onConnectionChange) { |
| 186 | _parameters.onConnectionChange(new_state); |
| 187 | } |
| 188 | } |
| 189 |
| 190 | void OnStandardizedIceConnectionChange(webrtc::PeerConnectionInterface::IceConnectionState new_state) override { |
| 191 | } |
| 192 |
| 193 | void OnConnectionChange(webrtc::PeerConnectionInterface::PeerConnectionState new_state) override { |
| 194 | } |
| 195 |
| 196 | void OnIceGatheringChange(webrtc::PeerConnectionInterface::IceGatheringState new_state) override { |
| 197 | } |
| 198 |
| 199 | void OnIceCandidate(const webrtc::IceCandidateInterface *candidate) override { |
| 200 | if (_parameters.onIceCandidate) { |
| 201 | _parameters.onIceCandidate(candidate); |
| 202 | } |
| 203 | } |
| 204 |
| 205 | void OnIceCandidatesRemoved(const std::vector<cricket::Candidate> &candidates) override { |
| 206 | } |
| 207 |
| 208 | void OnIceSelectedCandidatePairChanged(const cricket::CandidatePairChangeEvent &event) override { |
| 209 | if (_parameters.onCandidatePairChangeEvent) { |
| 210 | _parameters.onCandidatePairChangeEvent(event); |
| 211 | } |
| 212 | } |
| 213 |
| 214 | void OnAddTrack(webrtc::scoped_refptr<webrtc::RtpReceiverInterface> receiver, const std::vector<webrtc::scoped_refptr<webrtc::MediaStreamInterface>> &streams) override { |
| 215 |
| 216 | } |
| 217 |
| 218 | void OnRemoveTrack(webrtc::scoped_refptr<webrtc::RtpReceiverInterface> receiver) override { |
| 219 | if (_parameters.onTransceiverRemoved) { |
| 220 | _parameters.onTransceiverRemoved(receiver); |
| 221 | } |
| 222 | } |
| 223 |
| 224 | private: |
| 225 | Parameters _parameters; |
| 226 | }; |
| 227 |
| 228 | class StatsCollectorCallbackAdapter : public webrtc::RTCStatsCollectorCallback { |
| 229 | public: |
| 230 | StatsCollectorCallbackAdapter(std::function<void(const webrtc::scoped_refptr<const webrtc::RTCStatsReport> &)> &&completion_) : |
| 231 | completion(std::move(completion_)) { |
| 232 | } |
| 233 |
| 234 | void OnStatsDelivered(const webrtc::scoped_refptr<const webrtc::RTCStatsReport> &report) override { |
| 235 | completion(report); |
| 236 | } |
| 237 |
| 238 | private: |
| 239 | std::function<void(const webrtc::scoped_refptr<const webrtc::RTCStatsReport> &)> completion; |
| 240 | }; |
| 241 |
| 242 | class VideoSinkImpl : public rtc::VideoSinkInterface<webrtc::VideoFrame> { |
| 243 | public: |
| 244 | VideoSinkImpl() { |
| 245 | } |
| 246 |
| 247 | virtual ~VideoSinkImpl() { |
| 248 | } |
| 249 |
| 250 | virtual void OnFrame(const webrtc::VideoFrame& frame) override { |
| 251 | //_lastFrame = frame; |
| 252 | for (int i = (int)(_sinks.size()) - 1; i >= 0; i--) { |
| 253 | auto strong = _sinks[i].lock(); |
| 254 | if (!strong) { |
| 255 | _sinks.erase(_sinks.begin() + i); |
| 256 | } else { |
| 257 | strong->OnFrame(frame); |
| 258 | } |
| 259 | } |
| 260 | } |
| 261 |
| 262 | virtual void OnDiscardedFrame() override { |
| 263 | for (int i = (int)(_sinks.size()) - 1; i >= 0; i--) { |
| 264 | auto strong = _sinks[i].lock(); |
| 265 | if (!strong) { |
| 266 | _sinks.erase(_sinks.begin() + i); |
| 267 | } else { |
| 268 | strong->OnDiscardedFrame(); |
| 269 | } |
| 270 | } |
| 271 | } |
| 272 |
| 273 | void addSink(std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> impl) { |
| 274 | _sinks.push_back(impl); |
| 275 | if (_lastFrame) { |
| 276 | auto strong = impl.lock(); |
| 277 | if (strong) { |
| 278 | strong->OnFrame(_lastFrame.value()); |
| 279 | } |
| 280 | } |
| 281 | } |
| 282 |
| 283 | private: |
| 284 | std::vector<std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>>> _sinks; |
| 285 | absl::optional<webrtc::VideoFrame> _lastFrame; |
| 286 | }; |
| 287 |
| 288 | class DataChannelObserverImpl : public webrtc::DataChannelObserver { |
| 289 | public: |
| 290 | struct Parameters { |
| 291 | std::function<void()> onStateChange; |
| 292 | std::function<void(webrtc::DataBuffer const &)> onMessage; |
| 293 | }; |
| 294 |
| 295 | public: |
| 296 | DataChannelObserverImpl(Parameters &¶meters) : |
| 297 | _parameters(std::move(parameters)) { |
| 298 | } |
| 299 |
| 300 | virtual void OnStateChange() override { |
| 301 | if (_parameters.onStateChange) { |
| 302 | _parameters.onStateChange(); |
| 303 | } |
| 304 | } |
| 305 |
| 306 | virtual void OnMessage(webrtc::DataBuffer const &buffer) override { |
| 307 | if (_parameters.onMessage) { |
| 308 | _parameters.onMessage(buffer); |
| 309 | } |
| 310 | } |
| 311 |
| 312 | virtual ~DataChannelObserverImpl() { |
| 313 | } |
| 314 |
| 315 | private: |
| 316 | Parameters _parameters; |
| 317 | }; |
| 318 |
| 319 | template<typename T> |
| 320 | struct StateLogRecord { |
| 321 | int64_t timestamp = 0; |
| 322 | T record; |
| 323 |
| 324 | explicit StateLogRecord(int32_t timestamp_, T &&record_) : |
| 325 | timestamp(timestamp_), |
| 326 | record(std::move(record_)) { |
| 327 | } |
| 328 | }; |
| 329 |
| 330 | struct NetworkStateLogRecord { |
| 331 | bool isConnected = false; |
| 332 | bool isFailed = false; |
| 333 | absl::optional<InstanceNetworking::RouteDescription> route; |
| 334 | absl::optional<InstanceNetworking::ConnectionDescription> connection; |
| 335 |
| 336 | bool operator==(NetworkStateLogRecord const &rhs) const { |
| 337 | if (isConnected != rhs.isConnected) { |
| 338 | return false; |
| 339 | } |
| 340 | if (isFailed != rhs.isFailed) { |
| 341 | return false; |
| 342 | } |
| 343 | if (route != rhs.route) { |
| 344 | return false; |
| 345 | } |
| 346 | if (connection != rhs.connection) { |
| 347 | return false; |
| 348 | } |
| 349 |
| 350 | return true; |
| 351 | } |
| 352 | }; |
| 353 |
| 354 | struct NetworkBitrateLogRecord { |
| 355 | int32_t bitrate = 0; |
| 356 | }; |
| 357 |
| 358 | } // namespace |
| 359 |
| 360 | class InstanceV2ReferenceImplInternal : public std::enable_shared_from_this<InstanceV2ReferenceImplInternal> { |
| 361 | public: |
| 362 | InstanceV2ReferenceImplInternal(Descriptor &&descriptor, std::shared_ptr<Threads> threads) : |
| 363 | _signalingProtocolVersion(signalingProtocolVersion(descriptor.version)), |
| 364 | _threads(threads), |
| 365 | _rtcServers(descriptor.rtcServers), |
| 366 | _proxy(std::move(descriptor.proxy)), |
| 367 | _enableP2P(descriptor.config.enableP2P), |
| 368 | _encryptionKey(std::move(descriptor.encryptionKey)), |
| 369 | _stateUpdated(descriptor.stateUpdated), |
| 370 | _signalBarsUpdated(descriptor.signalBarsUpdated), |
| 371 | _audioLevelsUpdated(descriptor.audioLevelsUpdated), |
| 372 | _remoteBatteryLevelIsLowUpdated(descriptor.remoteBatteryLevelIsLowUpdated), |
| 373 | _remoteMediaStateUpdated(descriptor.remoteMediaStateUpdated), |
| 374 | _remotePrefferedAspectRatioUpdated(descriptor.remotePrefferedAspectRatioUpdated), |
| 375 | _signalingDataEmitted(descriptor.signalingDataEmitted), |
| 376 | _createAudioDeviceModule(descriptor.createAudioDeviceModule), |
| 377 | _createWrappedAudioDeviceModule(descriptor.createWrappedAudioDeviceModule), |
| 378 | _statsLogPath(descriptor.config.statsLogPath), |
| 379 | _eventLog(std::make_unique<webrtc::RtcEventLogNull>()), |
| 380 | _taskQueueFactory(webrtc::CreateDefaultTaskQueueFactory()), |
| 381 | _videoCapture(descriptor.videoCapture), |
| 382 | _platformContext(descriptor.platformContext) { |
| 383 | webrtc::field_trial::InitFieldTrialsFromString( |
| 384 | "WebRTC-DataChannel-Dcsctp/Enabled/" |
| 385 | "WebRTC-Audio-iOS-Holding/Enabled/" |
| 386 | ); |
| 387 | } |
| 388 |
| 389 | ~InstanceV2ReferenceImplInternal() { |
| 390 | _currentStrongSink.reset(); |
| 391 |
| 392 | _threads->getWorkerThread()->BlockingCall([&]() { |
| 393 | _audioDeviceModule = nullptr; |
| 394 | }); |
| 395 |
| 396 | if (_dataChannel) { |
| 397 | _dataChannel->UnregisterObserver(); |
| 398 | _dataChannel = nullptr; |
| 399 | } |
| 400 | _dataChannelObserver.reset(); |
| 401 |
| 402 | _peerConnection = nullptr; |
| 403 | _peerConnectionObserver.reset(); |
| 404 | _peerConnectionFactory = nullptr; |
| 405 | } |
| 406 |
| 407 | void start() { |
| 408 | const auto weak = std::weak_ptr<InstanceV2ReferenceImplInternal>(shared_from_this()); |
| 409 |
| 410 | PlatformInterface::SharedInstance()->configurePlatformAudio(); |
| 411 |
| 412 | RTC_DCHECK(_threads->getMediaThread()->IsCurrent()); |
| 413 |
| 414 | if (_signalingProtocolVersion == SignalingProtocolVersion::V2) { |
| 415 | _signalingConnection = std::make_unique<SignalingSctpConnection>( |
| 416 | _threads, |
| 417 | [threads = _threads, weak](const std::vector<uint8_t> &data) { |
| 418 | threads->getMediaThread()->PostTask([weak, data] { |
| 419 | const auto strong = weak.lock(); |
| 420 | if (!strong) { |
| 421 | return; |
| 422 | } |
| 423 |
| 424 | strong->onSignalingData(data); |
| 425 | }); |
| 426 | }, |
| 427 | [signalingDataEmitted = _signalingDataEmitted](const std::vector<uint8_t> &data) { |
| 428 | signalingDataEmitted(data); |
| 429 | } |
| 430 | ); |
| 431 | } |
| 432 | if (!_signalingConnection) { |
| 433 | _signalingConnection = std::make_unique<ExternalSignalingConnection>( |
| 434 | [threads = _threads, weak](const std::vector<uint8_t> &data) { |
| 435 | threads->getMediaThread()->PostTask([weak, data] { |
| 436 | const auto strong = weak.lock(); |
| 437 | if (!strong) { |
| 438 | return; |
| 439 | } |
| 440 |
| 441 | strong->onSignalingData(data); |
| 442 | }); |
| 443 | }, |
| 444 | [signalingDataEmitted = _signalingDataEmitted](const std::vector<uint8_t> &data) { |
| 445 | signalingDataEmitted(data); |
| 446 | } |
| 447 | ); |
| 448 | } |
| 449 |
| 450 | _signalingConnection->start(); |
| 451 |
| 452 | _threads->getWorkerThread()->BlockingCall([&]() { |
| 453 | _audioDeviceModule = createAudioDeviceModule(); |
| 454 | }); |
| 455 |
| 456 | webrtc::PeerConnectionFactoryDependencies peerConnectionFactoryDependencies; |
| 457 | peerConnectionFactoryDependencies.network_thread = _threads->getNetworkThread(); |
| 458 | peerConnectionFactoryDependencies.signaling_thread = _threads->getMediaThread(); |
| 459 | peerConnectionFactoryDependencies.worker_thread = _threads->getWorkerThread(); |
| 460 | peerConnectionFactoryDependencies.task_queue_factory = webrtc::CreateDefaultTaskQueueFactory(); |
| 461 | peerConnectionFactoryDependencies.network_monitor_factory = PlatformInterface::SharedInstance()->createNetworkMonitorFactory(); |
| 462 |
| 463 | peerConnectionFactoryDependencies.adm = _audioDeviceModule; |
| 464 |
| 465 | webrtc:: AudioProcessingBuilder builder; |
| 466 | peerConnectionFactoryDependencies.audio_processing = builder.Create(); |
| 467 |
| 468 | peerConnectionFactoryDependencies.audio_encoder_factory = webrtc::CreateAudioEncoderFactory<webrtc::AudioEncoderOpus>(); |
| 469 | peerConnectionFactoryDependencies.audio_decoder_factory = webrtc::CreateAudioDecoderFactory<webrtc::AudioDecoderOpus>(); |
| 470 |
| 471 | peerConnectionFactoryDependencies.video_encoder_factory = PlatformInterface::SharedInstance()->makeVideoEncoderFactory(_platformContext, true); |
| 472 | peerConnectionFactoryDependencies.video_decoder_factory = PlatformInterface::SharedInstance()->makeVideoDecoderFactory(_platformContext); |
| 473 |
| 474 | webrtc::EnableMedia(peerConnectionFactoryDependencies); |
| 475 |
| 476 | peerConnectionFactoryDependencies.event_log_factory = std::make_unique<webrtc::RtcEventLogFactory>(peerConnectionFactoryDependencies.task_queue_factory.get()); |
| 477 |
| 478 | _peerConnectionFactory = webrtc::CreateModularPeerConnectionFactory(std::move(peerConnectionFactoryDependencies)); |
| 479 |
| 480 | webrtc::PeerConnectionDependencies peerConnectionDependencies(nullptr); |
| 481 |
| 482 | PeerConnectionDelegateAdapter::Parameters delegateParameters; |
| 483 | delegateParameters.onRenegotiationNeeded = [weak, threads = _threads]() { |
| 484 | threads->getMediaThread()->PostTask([weak]() { |
| 485 | const auto strong = weak.lock(); |
| 486 | if (!strong) { |
| 487 | return; |
| 488 | } |
| 489 |
| 490 | if (strong->_didBeginNegotiation) { |
| 491 | if (strong->_encryptionKey.isOutgoing || strong->_peerConnection->remote_description()) { |
| 492 | strong->sendLocalDescription(); |
| 493 | } |
| 494 | } else { |
| 495 | RTC_LOG(LS_INFO) << "onRenegotiationNeeded: not sending local description"; |
| 496 | } |
| 497 | }); |
| 498 | }; |
| 499 | delegateParameters.onIceCandidate = [weak](const webrtc::IceCandidateInterface *iceCandidate) { |
| 500 | const auto strong = weak.lock(); |
| 501 | if (!strong) { |
| 502 | return; |
| 503 | } |
| 504 | strong->sendIceCandidate(iceCandidate); |
| 505 | }; |
| 506 | delegateParameters.onSignalingChange = [weak](webrtc::PeerConnectionInterface::SignalingState state) { |
| 507 | const auto strong = weak.lock(); |
| 508 | if (!strong) { |
| 509 | return; |
| 510 | } |
| 511 | /*switch (state) { |
| 512 | case webrtc::PeerConnectionInterface::SignalingState::kStable: { |
| 513 | State mappedState = State::Established; |
| 514 | strong->_stateUpdated(mappedState); |
| 515 | break; |
| 516 | } |
| 517 | default: { |
| 518 | State mappedState = State::Reconnecting; |
| 519 | strong->_stateUpdated(mappedState); |
| 520 | break; |
| 521 | } |
| 522 | }*/ |
| 523 | }; |
| 524 | delegateParameters.onConnectionChange = [weak](webrtc::PeerConnectionInterface::IceConnectionState state) { |
| 525 | const auto strong = weak.lock(); |
| 526 | if (!strong) { |
| 527 | return; |
| 528 | } |
| 529 |
| 530 | bool isConnected = false; |
| 531 | bool isFailed = false; |
| 532 |
| 533 | switch (state) { |
| 534 | case webrtc::PeerConnectionInterface::IceConnectionState::kIceConnectionConnected: { |
| 535 | isConnected = true; |
| 536 | break; |
| 537 | } |
| 538 | case webrtc::PeerConnectionInterface::IceConnectionState::kIceConnectionCompleted: { |
| 539 | isConnected = true; |
| 540 | break; |
| 541 | } |
| 542 | case webrtc::PeerConnectionInterface::IceConnectionState::kIceConnectionFailed: { |
| 543 | isFailed = true; |
| 544 | break; |
| 545 | } |
| 546 | default: { |
| 547 | break; |
| 548 | } |
| 549 | } |
| 550 |
| 551 | if (strong->_isConnected != isConnected || strong->_isFailed != isFailed) { |
| 552 | strong->_isConnected = isConnected; |
| 553 | strong->_isFailed = isFailed; |
| 554 |
| 555 | strong->onNetworkStateUpdated(); |
| 556 | } |
| 557 | }; |
| 558 | delegateParameters.onDataChannel = [weak](webrtc::scoped_refptr<webrtc::DataChannelInterface> dataChannel) { |
| 559 | const auto strong = weak.lock(); |
| 560 | if (!strong) { |
| 561 | return; |
| 562 | } |
| 563 |
| 564 | if (!strong->_dataChannel) { |
| 565 | strong->attachDataChannel(dataChannel); |
| 566 | } else { |
| 567 | RTC_LOG(LS_WARNING) << "onDataChannel invoked, but data channel already exists"; |
| 568 | } |
| 569 | }; |
| 570 | delegateParameters.onTransceiverAdded = [weak](webrtc::scoped_refptr<webrtc::RtpTransceiverInterface> transceiver) { |
| 571 | const auto strong = weak.lock(); |
| 572 | if (!strong) { |
| 573 | return; |
| 574 | } |
| 575 |
| 576 | if (!transceiver->mid()) { |
| 577 | return; |
| 578 | } |
| 579 | std::string mid = transceiver->mid().value(); |
| 580 |
| 581 | switch (transceiver->media_type()) { |
| 582 | case cricket::MediaType::MEDIA_TYPE_VIDEO: { |
| 583 | if (strong->_incomingVideoTransceivers.find(mid) == strong->_incomingVideoTransceivers.end()) { |
| 584 | strong->_incomingVideoTransceivers.insert(std::make_pair(mid, transceiver)); |
| 585 |
| 586 | strong->connectIncomingVideoSink(transceiver); |
| 587 | } |
| 588 | break; |
| 589 | } |
| 590 | default: { |
| 591 | break; |
| 592 | } |
| 593 | } |
| 594 | }; |
| 595 | delegateParameters.onTransceiverRemoved = [weak](webrtc::scoped_refptr<webrtc::RtpReceiverInterface> receiver) { |
| 596 | const auto strong = weak.lock(); |
| 597 | if (!strong) { |
| 598 | return; |
| 599 | } |
| 600 |
| 601 | std::string mid = receiver->track()->id(); |
| 602 | if (mid.empty()) { |
| 603 | return; |
| 604 | } |
| 605 |
| 606 | const auto transceiver = strong->_incomingVideoTransceivers.find(mid); |
| 607 | if (transceiver != strong->_incomingVideoTransceivers.end()) { |
| 608 | strong->disconnectIncomingVideoSink(); |
| 609 |
| 610 | strong->_incomingVideoTransceivers.erase(transceiver); |
| 611 | } |
| 612 | }; |
| 613 | delegateParameters.onCandidatePairChangeEvent = [weak](const cricket::CandidatePairChangeEvent &event) { |
| 614 | const auto strong = weak.lock(); |
| 615 | if (!strong) { |
| 616 | return; |
| 617 | } |
| 618 |
| 619 | InstanceNetworking::ConnectionDescription connectionDescription; |
| 620 |
| 621 | connectionDescription.local = InstanceNetworking::connectionDescriptionFromCandidate(event.selected_candidate_pair.local); |
| 622 | connectionDescription.remote = InstanceNetworking::connectionDescriptionFromCandidate(event.selected_candidate_pair.remote); |
| 623 |
| 624 | if (!strong->_currentConnectionDescription || strong->_currentConnectionDescription.value() != connectionDescription) { |
| 625 | strong->_currentConnectionDescription = std::move(connectionDescription); |
| 626 | strong->onNetworkStateUpdated(); |
| 627 | } |
| 628 | }; |
| 629 | _peerConnectionObserver = std::make_unique<PeerConnectionDelegateAdapter>(std::move(delegateParameters)); |
| 630 |
| 631 | peerConnectionDependencies.observer = _peerConnectionObserver.get(); |
| 632 |
| 633 | _networkMonitorFactory = PlatformInterface::SharedInstance()->createNetworkMonitorFactory(); |
| 634 | _socketFactory = std::make_unique<rtc::BasicPacketSocketFactory>(_threads->getNetworkThread()->socketserver()); |
| 635 | _networkManager = std::make_unique<rtc::BasicNetworkManager>(_networkMonitorFactory.get(), _threads->getNetworkThread()->socketserver()); |
| 636 | _relayPortFactory = std::make_unique<ReflectorRelayPortFactory>(_rtcServers, false, 0, _threads->getNetworkThread()->socketserver()); |
| 637 |
| 638 | auto portAllocator = std::make_unique<cricket::BasicPortAllocator>(_networkManager.get(), _socketFactory.get(), nullptr, _relayPortFactory.get()); |
| 639 | peerConnectionDependencies.allocator = std::move(portAllocator); |
| 640 |
| 641 | webrtc::PeerConnectionInterface::RTCConfiguration peerConnectionConfiguration; |
| 642 | if (_enableP2P) { |
| 643 | peerConnectionConfiguration.type = webrtc::PeerConnectionInterface::IceTransportsType::kAll; |
| 644 | } else { |
| 645 | peerConnectionConfiguration.type = webrtc::PeerConnectionInterface::IceTransportsType::kRelay; |
| 646 | } |
| 647 | peerConnectionConfiguration.tcp_candidate_policy = webrtc::PeerConnectionInterface::TcpCandidatePolicy::kTcpCandidatePolicyDisabled; |
| 648 | peerConnectionConfiguration.enable_ice_renomination = true; |
| 649 | peerConnectionConfiguration.sdp_semantics = webrtc::SdpSemantics::kUnifiedPlan; |
| 650 | peerConnectionConfiguration.bundle_policy = webrtc::PeerConnectionInterface::kBundlePolicyMaxBundle; |
| 651 | peerConnectionConfiguration.rtcp_mux_policy = webrtc::PeerConnectionInterface::RtcpMuxPolicy::kRtcpMuxPolicyRequire; |
| 652 | peerConnectionConfiguration.enable_implicit_rollback = true; |
| 653 | peerConnectionConfiguration.continual_gathering_policy = webrtc::PeerConnectionInterface::ContinualGatheringPolicy::GATHER_CONTINUALLY; |
| 654 | peerConnectionConfiguration.audio_jitter_buffer_fast_accelerate = true; |
| 655 | peerConnectionConfiguration.prioritize_most_likely_ice_candidate_pairs = true; |
| 656 |
| 657 | for (auto &server : _rtcServers) { |
| 658 | if (server.isTcp) { |
| 659 | continue; |
| 660 | } |
| 661 |
| 662 | rtc::SocketAddress address(server.host, server.port); |
| 663 | if (!address.IsComplete()) { |
| 664 | RTC_LOG(LS_ERROR) << "Invalid ICE server host: " << server.host; |
| 665 | continue; |
| 666 | } |
| 667 |
| 668 | if (server.isTurn) { |
| 669 | webrtc::PeerConnectionInterface::IceServer mappedServer; |
| 670 |
| 671 | mappedServer.urls.push_back( |
| 672 | "turn:" + address.HostAsURIString() + ":" + std::to_string(server.port)); |
| 673 | mappedServer.username = server.login; |
| 674 | mappedServer.password = server.password; |
| 675 |
| 676 | peerConnectionConfiguration.servers.push_back(mappedServer); |
| 677 | } else { |
| 678 | webrtc::PeerConnectionInterface::IceServer mappedServer; |
| 679 |
| 680 | mappedServer.urls.push_back( |
| 681 | "stun:" + address.HostAsURIString() + ":" + std::to_string(server.port)); |
| 682 |
| 683 | peerConnectionConfiguration.servers.push_back(mappedServer); |
| 684 | } |
| 685 | } |
| 686 |
| 687 | auto peerConnectionOrError = _peerConnectionFactory->CreatePeerConnectionOrError(peerConnectionConfiguration, std::move(peerConnectionDependencies)); |
| 688 | if (peerConnectionOrError.ok()) { |
| 689 | _peerConnection = peerConnectionOrError.value(); |
| 690 | } |
| 691 |
| 692 | if (_peerConnection) { |
| 693 | RTC_LOG(LS_INFO) << "Creating Data Channel"; |
| 694 |
| 695 | if (_encryptionKey.isOutgoing) { |
| 696 | webrtc::DataChannelInit dataChannelInit; |
| 697 | webrtc::RTCErrorOr<webrtc::scoped_refptr<webrtc::DataChannelInterface>> dataChannelOrError = _peerConnection->CreateDataChannelOrError("data", &dataChannelInit); |
| 698 | if (dataChannelOrError.ok()) { |
| 699 | attachDataChannel(dataChannelOrError.value()); |
| 700 | } |
| 701 | } |
| 702 |
| 703 | webrtc::RtpTransceiverInit transceiverInit; |
| 704 | transceiverInit.stream_ids = { "0" }; |
| 705 |
| 706 | cricket::AudioOptions audioSourceOptions; |
| 707 | webrtc::scoped_refptr<webrtc::AudioSourceInterface> audioSource = _peerConnectionFactory->CreateAudioSource(audioSourceOptions); |
| 708 |
| 709 | webrtc::scoped_refptr<webrtc::AudioTrackInterface> audioTrack = _peerConnectionFactory->CreateAudioTrack("0", audioSource.get()); |
| 710 | webrtc::RTCErrorOr<webrtc::scoped_refptr<webrtc::RtpTransceiverInterface>> audioTransceiverOrError = _peerConnection->AddTransceiver(audioTrack, transceiverInit); |
| 711 | if (audioTransceiverOrError.ok()) { |
| 712 | _outgoingAudioTrack = audioTrack; |
| 713 | _outgoingAudioTransceiver = audioTransceiverOrError.value(); |
| 714 |
| 715 | webrtc::RtpParameters parameters = _outgoingAudioTransceiver->sender()->GetParameters(); |
| 716 | if (parameters.encodings.empty()) { |
| 717 | parameters.encodings.push_back(webrtc::RtpEncodingParameters()); |
| 718 | } |
| 719 | parameters.encodings[0].max_bitrate_bps = 32 * 1024; |
| 720 | _outgoingAudioTransceiver->sender()->SetParameters(parameters); |
| 721 |
| 722 | _outgoingAudioTrack->set_enabled(true); |
| 723 | } |
| 724 | } |
| 725 |
| 726 | if (_videoCapture) { |
| 727 | setVideoCapture(_videoCapture); |
| 728 | } |
| 729 |
| 730 | _signalingEncryptedConnection = std::make_unique<EncryptedConnection>( |
| 731 | EncryptedConnection::Type::Signaling, |
| 732 | _encryptionKey, |
| 733 | [weak, threads = _threads](int delayMs, int cause) { |
| 734 | if (delayMs == 0) { |
| 735 | threads->getMediaThread()->PostTask([weak, cause]() { |
| 736 | const auto strong = weak.lock(); |
| 737 | if (!strong) { |
| 738 | return; |
| 739 | } |
| 740 |
| 741 | strong->sendPendingSignalingServiceData(cause); |
| 742 | }); |
| 743 | } else { |
| 744 | threads->getMediaThread()->PostDelayedTask([weak, cause]() { |
| 745 | const auto strong = weak.lock(); |
| 746 | if (!strong) { |
| 747 | return; |
| 748 | } |
| 749 |
| 750 | strong->sendPendingSignalingServiceData(cause); |
| 751 | }, webrtc::TimeDelta::Millis(delayMs)); |
| 752 | } |
| 753 | } |
| 754 | ); |
| 755 |
| 756 | beginSignaling(); |
| 757 |
| 758 | beginLogTimer(0); |
| 759 | } |
| 760 |
| 761 | void sendPendingSignalingServiceData(int cause) { |
| 762 | commitSendSignalingMessage(_signalingEncryptedConnection->prepareForSendingService(cause)); |
| 763 | } |
| 764 |
| 765 | void sendSignalingMessage(signaling::Message const &message) { |
| 766 | auto data = message.serialize(); |
| 767 | sendRawSignalingMessage(data); |
| 768 | } |
| 769 |
| 770 | void sendRawSignalingMessage(std::vector<uint8_t> const &data) { |
| 771 | RTC_LOG(LS_INFO) << "sendSignalingMessage: " << std::string(data.begin(), data.end()); |
| 772 |
| 773 | if (_signalingConnection && _signalingEncryptedConnection) { |
| 774 | switch (_signalingProtocolVersion) { |
| 775 | case SignalingProtocolVersion::V1: { |
| 776 | rtc::CopyOnWriteBuffer message; |
| 777 | message.AppendData(data.data(), data.size()); |
| 778 |
| 779 | commitSendSignalingMessage(_signalingEncryptedConnection->prepareForSendingRawMessage(message, true)); |
| 780 |
| 781 | break; |
| 782 | } |
| 783 | case SignalingProtocolVersion::V2: { |
| 784 | std::vector<uint8_t> packetData; |
| 785 | if (signalingProtocolSupportsCompression(_signalingProtocolVersion)) { |
| 786 | if (const auto compressedData = gzipData(data)) { |
| 787 | packetData = std::move(compressedData.value()); |
| 788 | } else { |
| 789 | RTC_LOG(LS_ERROR) << "Could not gzip signaling message"; |
| 790 | } |
| 791 | } else { |
| 792 | packetData = data; |
| 793 | } |
| 794 |
| 795 | if (const auto message = _signalingEncryptedConnection->encryptRawPacket(rtc::CopyOnWriteBuffer(packetData.data(), packetData.size()))) { |
| 796 | _signalingConnection->send(std::vector<uint8_t>(message.value().data(), message.value().data() + message.value().size())); |
| 797 | } else { |
| 798 | RTC_LOG(LS_ERROR) << "Could not encrypt signaling message"; |
| 799 | } |
| 800 | break; |
| 801 | } |
| 802 | default: { |
| 803 | RTC_DCHECK_NOTREACHED(); |
| 804 |
| 805 | break; |
| 806 | } |
| 807 | } |
| 808 | } else { |
| 809 | RTC_LOG(LS_ERROR) << "sendSignalingMessage encryption not available"; |
| 810 | } |
| 811 | } |
| 812 |
| 813 | void commitSendSignalingMessage(absl::optional<EncryptedConnection::EncryptedPacket> packet) { |
| 814 | if (!packet) { |
| 815 | return; |
| 816 | } |
| 817 |
| 818 | if (_signalingConnection) { |
| 819 | _signalingConnection->send(packet.value().bytes); |
| 820 | } |
| 821 | } |
| 822 |
| 823 | void beginLogTimer(int delayMs) { |
| 824 | const auto weak = std::weak_ptr<InstanceV2ReferenceImplInternal>(shared_from_this()); |
| 825 | _threads->getMediaThread()->PostDelayedTask([weak]() { |
| 826 | auto strong = weak.lock(); |
| 827 | if (!strong) { |
| 828 | return; |
| 829 | } |
| 830 |
| 831 | strong->writeStateLogRecords(); |
| 832 |
| 833 | strong->beginLogTimer(1000); |
| 834 | }, webrtc::TimeDelta::Millis(delayMs)); |
| 835 | } |
| 836 |
| 837 | void writeStateLogRecords() { |
| 838 | const auto weak = std::weak_ptr<InstanceV2ReferenceImplInternal>(shared_from_this()); |
| 839 | auto call = ((webrtc::PeerConnectionProxyWithInternal<webrtc::PeerConnection> *)_peerConnection.get())->internal()->call_ptr(); |
| 840 | if (!call) { |
| 841 | return; |
| 842 | } |
| 843 |
| 844 | _threads->getWorkerThread()->PostTask([weak, call]() { |
| 845 | auto strong = weak.lock(); |
| 846 | if (!strong) { |
| 847 | return; |
| 848 | } |
| 849 |
| 850 | auto stats = call->GetStats(); |
| 851 | float sendBitrateKbps = ((float)stats.send_bandwidth_bps / 1024.0f); |
| 852 |
| 853 | strong->_threads->getMediaThread()->PostTask([weak, sendBitrateKbps]() { |
| 854 | auto strong = weak.lock(); |
| 855 | if (!strong) { |
| 856 | return; |
| 857 | } |
| 858 |
| 859 | float bitrateNorm = 16.0f; |
| 860 | if (strong->_outgoingVideoTransceiver) { |
| 861 | bitrateNorm = 600.0f; |
| 862 | } |
| 863 |
| 864 | float signalBarsNorm = 4.0f; |
| 865 | float adjustedQuality = sendBitrateKbps / bitrateNorm; |
| 866 | adjustedQuality = fmaxf(0.0f, adjustedQuality); |
| 867 | adjustedQuality = fminf(1.0f, adjustedQuality); |
| 868 | if (strong->_signalBarsUpdated) { |
| 869 | strong->_signalBarsUpdated((int)(adjustedQuality * signalBarsNorm)); |
| 870 | } |
| 871 |
| 872 | NetworkBitrateLogRecord networkBitrateLogRecord; |
| 873 | networkBitrateLogRecord.bitrate = (int32_t)sendBitrateKbps; |
| 874 |
| 875 | strong->_networkBitrateLogRecords.emplace_back(rtc::TimeMillis(), std::move(networkBitrateLogRecord)); |
| 876 | }); |
| 877 | }); |
| 878 | } |
| 879 |
| 880 | void sendLocalDescription() { |
| 881 | const auto weak = std::weak_ptr<InstanceV2ReferenceImplInternal>(shared_from_this()); |
| 882 |
| 883 | _isMakingOffer = true; |
| 884 |
| 885 | webrtc::scoped_refptr<webrtc::SetLocalDescriptionObserverInterface> observer(new rtc::RefCountedObject<SetSessionDescriptionObserver>([threads = _threads, weak](webrtc::RTCError error) { |
| 886 | threads->getMediaThread()->PostTask([weak]() { |
| 887 | const auto strong = weak.lock(); |
| 888 | if (!strong) { |
| 889 | return; |
| 890 | } |
| 891 |
| 892 | strong->doSendLocalDescription(); |
| 893 |
| 894 | strong->_isMakingOffer = false; |
| 895 |
| 896 | strong->maybeCommitPendingIceCandidates(); |
| 897 | }); |
| 898 | })); |
| 899 | RTC_LOG(LS_INFO) << "Calling SetLocalDescription"; |
| 900 | _peerConnection->SetLocalDescription(observer); |
| 901 | } |
| 902 |
| 903 | void sendIceCandidate(const webrtc::IceCandidateInterface *iceCandidate) { |
| 904 | std::string sdp; |
| 905 | iceCandidate->ToString(&sdp); |
| 906 |
| 907 | json11::Json::object jsonCandidate; |
| 908 | jsonCandidate.insert(std::make_pair("@type", json11::Json("candidate"))); |
| 909 | jsonCandidate.insert(std::make_pair("sdp", json11::Json(sdp))); |
| 910 | jsonCandidate.insert(std::make_pair("mid", json11::Json(iceCandidate->sdp_mid()))); |
| 911 | jsonCandidate.insert(std::make_pair("mline", json11::Json(iceCandidate->sdp_mline_index()))); |
| 912 |
| 913 | auto jsonData = json11::Json(std::move(jsonCandidate)); |
| 914 | auto jsonResult = jsonData.dump(); |
| 915 | sendRawSignalingMessage(std::vector<uint8_t>(jsonResult.begin(), jsonResult.end())); |
| 916 | } |
| 917 |
| 918 | void doSendLocalDescription() { |
| 919 | auto localDescription = _peerConnection->local_description(); |
| 920 | if (localDescription) { |
| 921 | std::string sdp; |
| 922 | localDescription->ToString(&sdp); |
| 923 | std::string type = localDescription->type(); |
| 924 |
| 925 | json11::Json::object jsonDescription; |
| 926 | jsonDescription.insert(std::make_pair("@type", json11::Json(type))); |
| 927 | jsonDescription.insert(std::make_pair("sdp", json11::Json(sdp))); |
| 928 |
| 929 | auto jsonData = json11::Json(std::move(jsonDescription)); |
| 930 | auto jsonResult = jsonData.dump(); |
| 931 | sendRawSignalingMessage(std::vector<uint8_t>(jsonResult.begin(), jsonResult.end())); |
| 932 | } |
| 933 | } |
| 934 |
| 935 | void beginSignaling() { |
| 936 | _didBeginNegotiation = true; |
| 937 |
| 938 | if (_encryptionKey.isOutgoing) { |
| 939 | sendLocalDescription(); |
| 940 | } |
| 941 | } |
| 942 |
| 943 | void receiveSignalingData(const std::vector<uint8_t> &data) { |
| 944 | if (_signalingConnection) { |
| 945 | _signalingConnection->receiveExternal(data); |
| 946 | } |
| 947 | } |
| 948 |
| 949 | void onSignalingData(const std::vector<uint8_t> &data) { |
| 950 | if (_signalingEncryptedConnection) { |
| 951 | switch (_signalingProtocolVersion) { |
| 952 | case SignalingProtocolVersion::V1: { |
| 953 | if (const auto packet = _signalingEncryptedConnection->handleIncomingRawPacket((const char *)data.data(), data.size())) { |
| 954 | processSignalingMessage(packet.value().main.message); |
| 955 |
| 956 | for (const auto &additional : packet.value().additional) { |
| 957 | processSignalingMessage(additional.message); |
| 958 | } |
| 959 | } |
| 960 |
| 961 | break; |
| 962 | } |
| 963 | case SignalingProtocolVersion::V2: { |
| 964 | if (const auto message = _signalingEncryptedConnection->decryptRawPacket(rtc::CopyOnWriteBuffer(data.data(), data.size()))) { |
| 965 | processSignalingMessage(message.value()); |
| 966 | } else { |
| 967 | RTC_LOG(LS_ERROR) << "receiveSignalingData could not decrypt signaling data"; |
| 968 | } |
| 969 |
| 970 | break; |
| 971 | } |
| 972 | default: { |
| 973 | RTC_DCHECK_NOTREACHED(); |
| 974 |
| 975 | break; |
| 976 | } |
| 977 | } |
| 978 | } else { |
| 979 | RTC_LOG(LS_ERROR) << "receiveSignalingData encryption not available"; |
| 980 | } |
| 981 | } |
| 982 |
| 983 | void processSignalingMessage(rtc::CopyOnWriteBuffer const &data) { |
| 984 | std::vector<uint8_t> decryptedData = std::vector<uint8_t>(data.data(), data.data() + data.size()); |
| 985 |
| 986 | if (isGzip(decryptedData)) { |
| 987 | if (const auto decompressedData = gunzipData(decryptedData, 2 * 1024 * 1024)) { |
| 988 | processSignalingData(decompressedData.value()); |
| 989 | } else { |
| 990 | RTC_LOG(LS_ERROR) << "receiveSignalingData could not decompress gzipped data"; |
| 991 | } |
| 992 | } else { |
| 993 | processSignalingData(decryptedData); |
| 994 | } |
| 995 | } |
| 996 |
| 997 | void processSignalingData(const std::vector<uint8_t> &data) { |
| 998 | RTC_LOG(LS_INFO) << "processSignalingData: " << std::string(data.begin(), data.end()); |
| 999 |
| 1000 | std::string parsingError; |
| 1001 | auto json = json11::Json::parse(std::string(data.begin(), data.end()), parsingError); |
| 1002 | if (json.type() != json11::Json::OBJECT) { |
| 1003 | RTC_LOG(LS_ERROR) << "Signaling: message must be an object"; |
| 1004 | return; |
| 1005 | } |
| 1006 |
| 1007 | const auto jsonType = json.object_items().find("@type"); |
| 1008 | if (jsonType == json.object_items().end()) { |
| 1009 | RTC_LOG(LS_ERROR) << "Signaling: @type is missing"; |
| 1010 | return; |
| 1011 | } |
| 1012 | std::string type = jsonType->second.string_value(); |
| 1013 |
| 1014 | if (type == "offer" || type == "answer") { |
| 1015 | const auto jsonSdp = json.object_items().find("sdp"); |
| 1016 | if (jsonSdp == json.object_items().end()) { |
| 1017 | RTC_LOG(LS_ERROR) << "Signaling: sdp is missing"; |
| 1018 | return; |
| 1019 | } |
| 1020 | std::string sdp = jsonSdp->second.string_value(); |
| 1021 | handleRemoteSdp(type, sdp); |
| 1022 | } else if (type == "candidate") { |
| 1023 | auto jsonMid = json.object_items().find("mid"); |
| 1024 | if (jsonMid == json.object_items().end()) { |
| 1025 | return; |
| 1026 | } |
| 1027 |
| 1028 | auto jsonMLineIndex = json.object_items().find("mline"); |
| 1029 | if (jsonMLineIndex == json.object_items().end()) { |
| 1030 | return; |
| 1031 | } |
| 1032 |
| 1033 | auto jsonSdp = json.object_items().find("sdp"); |
| 1034 | if (jsonSdp == json.object_items().end()) { |
| 1035 | return; |
| 1036 | } |
| 1037 |
| 1038 | webrtc::SdpParseError parseError; |
| 1039 | webrtc::IceCandidateInterface *iceCandidate = webrtc::CreateIceCandidate(jsonMid->second.string_value(), jsonMLineIndex->second.int_value(), jsonSdp->second.string_value(), &parseError); |
| 1040 | if (iceCandidate) { |
| 1041 | std::unique_ptr<webrtc::IceCandidateInterface> candidarePtr; |
| 1042 | candidarePtr.reset(iceCandidate); |
| 1043 |
| 1044 | _pendingIceCandidates.push_back(std::move(candidarePtr)); |
| 1045 | maybeCommitPendingIceCandidates(); |
| 1046 | } |
| 1047 | } else { |
| 1048 | const auto message = signaling::Message::parse(data); |
| 1049 | if (!message) { |
| 1050 | return; |
| 1051 | } |
| 1052 | const auto messageData = &message->data; |
| 1053 |
| 1054 | if (const auto mediaState = absl::get_if<signaling::MediaStateMessage>(messageData)) { |
| 1055 | AudioState mappedAudioState; |
| 1056 | if (mediaState->isMuted) { |
| 1057 | mappedAudioState = AudioState::Muted; |
| 1058 | } else { |
| 1059 | mappedAudioState = AudioState::Active; |
| 1060 | } |
| 1061 |
| 1062 | VideoState mappedVideoState; |
| 1063 | switch (mediaState->videoState) { |
| 1064 | case signaling::MediaStateMessage::VideoState::Inactive: { |
| 1065 | mappedVideoState = VideoState::Inactive; |
| 1066 | break; |
| 1067 | } |
| 1068 | case signaling::MediaStateMessage::VideoState::Suspended: { |
| 1069 | mappedVideoState = VideoState::Paused; |
| 1070 | break; |
| 1071 | } |
| 1072 | case signaling::MediaStateMessage::VideoState::Active: { |
| 1073 | mappedVideoState = VideoState::Active; |
| 1074 | break; |
| 1075 | } |
| 1076 | default: { |
| 1077 | RTC_FATAL() << "Unknown videoState"; |
| 1078 | break; |
| 1079 | } |
| 1080 | } |
| 1081 |
| 1082 | VideoState mappedScreencastState; |
| 1083 | switch (mediaState->screencastState) { |
| 1084 | case signaling::MediaStateMessage::VideoState::Inactive: { |
| 1085 | mappedScreencastState = VideoState::Inactive; |
| 1086 | break; |
| 1087 | } |
| 1088 | case signaling::MediaStateMessage::VideoState::Suspended: { |
| 1089 | mappedScreencastState = VideoState::Paused; |
| 1090 | break; |
| 1091 | } |
| 1092 | case signaling::MediaStateMessage::VideoState::Active: { |
| 1093 | mappedScreencastState = VideoState::Active; |
| 1094 | break; |
| 1095 | } |
| 1096 | default: { |
| 1097 | RTC_FATAL() << "Unknown videoState"; |
| 1098 | break; |
| 1099 | } |
| 1100 | } |
| 1101 |
| 1102 | VideoState effectiveVideoState = mappedVideoState; |
| 1103 | if (mappedScreencastState == VideoState::Active || mappedScreencastState == VideoState::Paused) { |
| 1104 | effectiveVideoState = mappedScreencastState; |
| 1105 | } |
| 1106 |
| 1107 | if (_remoteMediaStateUpdated) { |
| 1108 | _remoteMediaStateUpdated(mappedAudioState, effectiveVideoState); |
| 1109 | } |
| 1110 |
| 1111 | if (_remoteBatteryLevelIsLowUpdated) { |
| 1112 | _remoteBatteryLevelIsLowUpdated(mediaState->isBatteryLow); |
| 1113 | } |
| 1114 | } |
| 1115 | } |
| 1116 | } |
| 1117 |
| 1118 | void handleRemoteSdp(std::string const &type, std::string const &sdp) { |
| 1119 | webrtc::SdpParseError sdpParseError; |
| 1120 | std::unique_ptr<webrtc::SessionDescriptionInterface> remoteDescription(webrtc::CreateSessionDescription(type, sdp, &sdpParseError)); |
| 1121 | if (!remoteDescription) { |
| 1122 | RTC_LOG(LS_ERROR) << "Failed to parse remote SDP"; |
| 1123 | return; |
| 1124 | } |
| 1125 |
| 1126 | bool isReadyForOffer = !_isMakingOffer && (_peerConnection->signaling_state() == webrtc::PeerConnectionInterface::SignalingState::kStable || _isSettingRemoteAnswerPending); |
| 1127 | bool isOfferCollision = (type == "offer") && !isReadyForOffer; |
| 1128 | bool ignoreOffer = !_encryptionKey.isOutgoing && isOfferCollision; |
| 1129 | if (ignoreOffer) { |
| 1130 | RTC_LOG(LS_INFO) << "Ingoring remote sdp"; |
| 1131 | return; |
| 1132 | } |
| 1133 |
| 1134 | _isSettingRemoteAnswerPending = type == "answer"; |
| 1135 |
| 1136 | const auto weak = std::weak_ptr<InstanceV2ReferenceImplInternal>(shared_from_this()); |
| 1137 | webrtc::scoped_refptr<webrtc::SetRemoteDescriptionObserverInterface> observer(new rtc::RefCountedObject<SetSessionDescriptionObserver>([threads = _threads, weak, type](webrtc::RTCError error) { |
| 1138 | threads->getMediaThread()->PostTask([weak, type]() { |
| 1139 | const auto strong = weak.lock(); |
| 1140 | if (!strong) { |
| 1141 | return; |
| 1142 | } |
| 1143 |
| 1144 | strong->_isSettingRemoteAnswerPending = false; |
| 1145 |
| 1146 | strong->maybeCommitPendingIceCandidates(); |
| 1147 |
| 1148 | if (type == "offer") { |
| 1149 | strong->sendLocalDescription(); |
| 1150 | } |
| 1151 | }); |
| 1152 | })); |
| 1153 | RTC_LOG(LS_INFO) << "Calling SetRemoteDescription"; |
| 1154 | _peerConnection->SetRemoteDescription(std::move(remoteDescription), observer); |
| 1155 | } |
| 1156 |
| 1157 | void maybeCommitPendingIceCandidates() { |
| 1158 | if (_pendingIceCandidates.size() == 0) { |
| 1159 | return; |
| 1160 | } |
| 1161 |
| 1162 | if (_peerConnection->local_description() && _peerConnection->remote_description()) { |
| 1163 | for (const auto &candidate : _pendingIceCandidates) { |
| 1164 | if (candidate) { |
| 1165 | _peerConnection->AddIceCandidate(candidate.get()); |
| 1166 | } |
| 1167 | } |
| 1168 |
| 1169 | _pendingIceCandidates.clear(); |
| 1170 | } |
| 1171 | } |
| 1172 |
| 1173 | void onNetworkStateUpdated() { |
| 1174 | NetworkStateLogRecord record; |
| 1175 | record.isConnected = _isConnected; |
| 1176 | record.connection = _currentConnectionDescription; |
| 1177 | record.isFailed = _isFailed; |
| 1178 |
| 1179 | if (!_currentNetworkStateLogRecord || !(_currentNetworkStateLogRecord.value() == record)) { |
| 1180 | _currentNetworkStateLogRecord = record; |
| 1181 | _networkStateLogRecords.emplace_back(rtc::TimeMillis(), std::move(record)); |
| 1182 | } |
| 1183 |
| 1184 | State mappedState; |
| 1185 | if (_isFailed) { |
| 1186 | mappedState = State::Failed; |
| 1187 | } else if (_isConnected) { |
| 1188 | mappedState = State::Established; |
| 1189 | } else { |
| 1190 | mappedState = State::Reconnecting; |
| 1191 | } |
| 1192 | _stateUpdated(mappedState); |
| 1193 | } |
| 1194 |
| 1195 | void attachDataChannel(webrtc::scoped_refptr<webrtc::DataChannelInterface> dataChannel) { |
| 1196 | const auto weak = std::weak_ptr<InstanceV2ReferenceImplInternal>(shared_from_this()); |
| 1197 |
| 1198 | DataChannelObserverImpl::Parameters dataChannelObserverParams; |
| 1199 | dataChannelObserverParams.onStateChange = [threads = _threads, weak]() { |
| 1200 | threads->getMediaThread()->PostTask([weak]() { |
| 1201 | const auto strong = weak.lock(); |
| 1202 | if (!strong) { |
| 1203 | return; |
| 1204 | } |
| 1205 |
| 1206 | strong->onDataChannelStateUpdated(); |
| 1207 | }); |
| 1208 | }; |
| 1209 | dataChannelObserverParams.onMessage = [threads = _threads, weak](webrtc::DataBuffer const &buffer) { |
| 1210 | const auto strong = weak.lock(); |
| 1211 | if (!strong) { |
| 1212 | return; |
| 1213 | } |
| 1214 |
| 1215 | std::string message(buffer.data.data(), buffer.data.data() + buffer.data.size()); |
| 1216 |
| 1217 | if (!buffer.binary) { |
| 1218 | RTC_LOG(LS_INFO) << "dataChannelMessage received: " << message; |
| 1219 | std::vector<uint8_t> data(message.begin(), message.end()); |
| 1220 | strong->processSignalingData(data); |
| 1221 | } else { |
| 1222 | RTC_LOG(LS_INFO) << "dataChannelMessage rejecting binary message"; |
| 1223 | } |
| 1224 | }; |
| 1225 | _dataChannelObserver = std::make_unique<DataChannelObserverImpl>(std::move(dataChannelObserverParams)); |
| 1226 | _dataChannel = dataChannel; |
| 1227 |
| 1228 | onDataChannelStateUpdated(); |
| 1229 |
| 1230 | _dataChannel->RegisterObserver(_dataChannelObserver.get()); |
| 1231 | } |
| 1232 |
| 1233 | void onDataChannelStateUpdated() { |
| 1234 | if (_dataChannel) { |
| 1235 | switch (_dataChannel->state()) { |
| 1236 | case webrtc::DataChannelInterface::DataState::kOpen: { |
| 1237 | if (!_isDataChannelOpen) { |
| 1238 | _isDataChannelOpen = true; |
| 1239 | sendMediaState(); |
| 1240 | } |
| 1241 | break; |
| 1242 | } |
| 1243 | default: { |
| 1244 | _isDataChannelOpen = false; |
| 1245 | break; |
| 1246 | } |
| 1247 | } |
| 1248 | } |
| 1249 | } |
| 1250 |
| 1251 | void sendDataChannelMessage(signaling::Message const &message) { |
| 1252 | if (!_isDataChannelOpen) { |
| 1253 | RTC_LOG(LS_ERROR) << "sendDataChannelMessage called, but data channel is not open"; |
| 1254 | return; |
| 1255 | } |
| 1256 | auto data = message.serialize(); |
| 1257 | std::string stringData(data.begin(), data.end()); |
| 1258 | RTC_LOG(LS_INFO) << "sendDataChannelMessage: " << stringData; |
| 1259 | if (_dataChannel) { |
| 1260 | _dataChannel->Send(webrtc::DataBuffer(stringData)); |
| 1261 | } |
| 1262 | } |
| 1263 |
| 1264 | void onDataChannelMessage(std::string const &message) { |
| 1265 | RTC_LOG(LS_INFO) << "dataChannelMessage received: " << message; |
| 1266 | std::vector<uint8_t> data(message.begin(), message.end()); |
| 1267 | processSignalingData(data); |
| 1268 | } |
| 1269 |
| 1270 | void sendMediaState() { |
| 1271 | if (!_isDataChannelOpen) { |
| 1272 | return; |
| 1273 | } |
| 1274 | signaling::Message message; |
| 1275 | signaling::MediaStateMessage data; |
| 1276 | data.isMuted = _isMicrophoneMuted; |
| 1277 | data.isBatteryLow = _isBatteryLow; |
| 1278 | if (_outgoingVideoTransceiver) { |
| 1279 | if (_videoCapture) { |
| 1280 | data.videoState = signaling::MediaStateMessage::VideoState::Active; |
| 1281 | } else { |
| 1282 | data.videoState = signaling::MediaStateMessage::VideoState::Inactive; |
| 1283 | } |
| 1284 | } else { |
| 1285 | data.videoState = signaling::MediaStateMessage::VideoState::Inactive; |
| 1286 | data.videoRotation = signaling::MediaStateMessage::VideoRotation::Rotation0; |
| 1287 | } |
| 1288 | message.data = std::move(data); |
| 1289 | sendDataChannelMessage(message); |
| 1290 | } |
| 1291 |
| 1292 | void sendCandidate(const cricket::Candidate &candidate) { |
| 1293 | cricket::Candidate patchedCandidate = candidate; |
| 1294 | patchedCandidate.set_component(1); |
| 1295 |
| 1296 | signaling::CandidatesMessage data; |
| 1297 |
| 1298 | signaling::IceCandidate serializedCandidate; |
| 1299 |
| 1300 | webrtc::JsepIceCandidate iceCandidate{ std::string(), 0 }; |
| 1301 | iceCandidate.SetCandidate(patchedCandidate); |
| 1302 | std::string serialized; |
| 1303 | const auto success = iceCandidate.ToString(&serialized); |
| 1304 | assert(success); |
| 1305 | (void)success; |
| 1306 |
| 1307 | serializedCandidate.sdpString = serialized; |
| 1308 |
| 1309 | data.iceCandidates.push_back(std::move(serializedCandidate)); |
| 1310 |
| 1311 | signaling::Message message; |
| 1312 | message.data = std::move(data); |
| 1313 | sendSignalingMessage(message); |
| 1314 | } |
| 1315 |
| 1316 | void setVideoCapture(std::shared_ptr<VideoCaptureInterface> videoCapture) { |
| 1317 | _isPerformingConfiguration = true; |
| 1318 |
| 1319 | if (_outgoingVideoTransceiver) { |
| 1320 | _peerConnection->RemoveTrackOrError(_outgoingVideoTransceiver->sender()); |
| 1321 | } |
| 1322 | if (_outgoingVideoTrack) { |
| 1323 | _outgoingVideoTrack = nullptr; |
| 1324 | } |
| 1325 | _outgoingVideoTransceiver = nullptr; |
| 1326 |
| 1327 | auto videoCaptureImpl = GetVideoCaptureAssumingSameThread(videoCapture.get()); |
| 1328 | if (videoCaptureImpl) { |
| 1329 | if (videoCaptureImpl->isScreenCapture()) { |
| 1330 | } else { |
| 1331 | _videoCapture = videoCapture; |
| 1332 |
| 1333 | auto videoTrack = _peerConnectionFactory->CreateVideoTrack(videoCaptureImpl->source(), "1"); |
| 1334 | if (videoTrack) { |
| 1335 | webrtc::RtpTransceiverInit transceiverInit; |
| 1336 | transceiverInit.stream_ids = { "0" }; |
| 1337 |
| 1338 | webrtc::RTCErrorOr<webrtc::scoped_refptr<webrtc::RtpTransceiverInterface>> videoTransceiverOrError = _peerConnection->AddTransceiver(videoTrack, transceiverInit); |
| 1339 | if (videoTransceiverOrError.ok()) { |
| 1340 | _outgoingVideoTrack = videoTrack; |
| 1341 | _outgoingVideoTransceiver = videoTransceiverOrError.value(); |
| 1342 |
| 1343 | auto currentCapabilities = _peerConnectionFactory->GetRtpSenderCapabilities(cricket::MediaType::MEDIA_TYPE_VIDEO); |
| 1344 |
| 1345 | std::vector<std::string> codecPreferences = { |
| 1346 | #ifndef WEBRTC_DISABLE_H265 |
| 1347 | cricket::kH265CodecName, |
| 1348 | #endif |
| 1349 | cricket::kH264CodecName |
| 1350 | }; |
| 1351 |
| 1352 | for (const auto &codecCapability : currentCapabilities.codecs) { |
| 1353 | if (std::find_if(codecPreferences.begin(), codecPreferences.end(), [&](std::string const &value) { |
| 1354 | return value == codecCapability.name; |
| 1355 | }) != codecPreferences.end()) { |
| 1356 | continue; |
| 1357 | } |
| 1358 | codecPreferences.push_back(codecCapability.name); |
| 1359 | } |
| 1360 |
| 1361 | std::vector<webrtc::RtpCodecCapability> codecCapabilities; |
| 1362 | for (const auto &name : codecPreferences) { |
| 1363 | for (const auto &codecCapability : currentCapabilities.codecs) { |
| 1364 | if (codecCapability.name == name) { |
| 1365 | codecCapabilities.push_back(codecCapability); |
| 1366 |
| 1367 | break; |
| 1368 | } |
| 1369 | } |
| 1370 | } |
| 1371 |
| 1372 | _outgoingVideoTransceiver->SetCodecPreferences(codecCapabilities); |
| 1373 |
| 1374 | webrtc::RtpParameters parameters = _outgoingVideoTransceiver->sender()->GetParameters(); |
| 1375 | if (parameters.encodings.empty()) { |
| 1376 | parameters.encodings.push_back(webrtc::RtpEncodingParameters()); |
| 1377 | } |
| 1378 | parameters.encodings[0].max_bitrate_bps = 1200 * 1024; |
| 1379 | _outgoingVideoTransceiver->sender()->SetParameters(parameters); |
| 1380 |
| 1381 | _outgoingVideoTrack->set_enabled(true); |
| 1382 | } |
| 1383 | } |
| 1384 | } |
| 1385 | } |
| 1386 |
| 1387 | _isPerformingConfiguration = false; |
| 1388 |
| 1389 | if (_didBeginNegotiation) { |
| 1390 | sendMediaState(); |
| 1391 | sendLocalDescription(); |
| 1392 | } |
| 1393 | } |
| 1394 |
| 1395 | void setRequestedVideoAspect(float aspect) { |
| 1396 | } |
| 1397 |
| 1398 | void setNetworkType(NetworkType networkType) { |
| 1399 | } |
| 1400 |
| 1401 | void setMuteMicrophone(bool muteMicrophone) { |
| 1402 | if (_isMicrophoneMuted != muteMicrophone) { |
| 1403 | _isMicrophoneMuted = muteMicrophone; |
| 1404 |
| 1405 | if (_outgoingAudioTrack) { |
| 1406 | _outgoingAudioTrack->set_enabled(!_isMicrophoneMuted); |
| 1407 | } |
| 1408 |
| 1409 | sendMediaState(); |
| 1410 | } |
| 1411 | } |
| 1412 |
| 1413 | void connectIncomingVideoSink(webrtc::scoped_refptr<webrtc::RtpTransceiverInterface> transceiver) { |
| 1414 | if (_currentStrongSink) { |
| 1415 | webrtc::VideoTrackInterface *videoTrack = (webrtc::VideoTrackInterface *)transceiver->receiver()->track().get(); |
| 1416 | videoTrack->AddOrUpdateSink(_currentStrongSink.get(), rtc::VideoSinkWants()); |
| 1417 | } |
| 1418 | } |
| 1419 |
| 1420 | void disconnectIncomingVideoSink() { |
| 1421 | } |
| 1422 |
| 1423 | void setIncomingVideoOutput(std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) { |
| 1424 | _currentStrongSink = sink.lock(); |
| 1425 |
| 1426 | if (_currentStrongSink) { |
| 1427 | if (!_incomingVideoTransceivers.empty()) { |
| 1428 | connectIncomingVideoSink(_incomingVideoTransceivers.begin()->second); |
| 1429 | } |
| 1430 | } |
| 1431 |
| 1432 | /*if (_incomingVideoChannel) { |
| 1433 | _incomingVideoChannel->addSink(sink); |
| 1434 | } |
| 1435 | if (_incomingScreencastChannel) { |
| 1436 | _incomingScreencastChannel->addSink(sink); |
| 1437 | }*/ |
| 1438 | } |
| 1439 |
| 1440 | void setAudioInputDevice(std::string id) { |
| 1441 | SetAudioInputDeviceById(_audioDeviceModule.get(), id); |
| 1442 | } |
| 1443 |
| 1444 | void setAudioOutputDevice(std::string id) { |
| 1445 | SetAudioOutputDeviceById(_audioDeviceModule.get(), id); |
| 1446 | } |
| 1447 |
| 1448 | void setIsLowBatteryLevel(bool isLowBatteryLevel) { |
| 1449 | if (_isBatteryLow != isLowBatteryLevel) { |
| 1450 | _isBatteryLow = isLowBatteryLevel; |
| 1451 | sendMediaState(); |
| 1452 | } |
| 1453 | } |
| 1454 |
| 1455 | void stop(std::function<void(FinalState)> completion) { |
| 1456 | _peerConnection->Close(); |
| 1457 |
| 1458 | FinalState finalState; |
| 1459 |
| 1460 | json11::Json::object statsLog; |
| 1461 |
| 1462 | statsLog.insert(std::make_pair("v", std::move(3))); |
| 1463 |
| 1464 | for (int i = (int)_networkStateLogRecords.size() - 1; i >= 1; i--) { |
| 1465 | // coalesce events within 5ms |
| 1466 | if (_networkStateLogRecords[i].timestamp - _networkStateLogRecords[i - 1].timestamp < 5) { |
| 1467 | _networkStateLogRecords.erase(_networkStateLogRecords.begin() + i - 1); |
| 1468 | } |
| 1469 | } |
| 1470 |
| 1471 | json11::Json::array jsonNetworkStateLogRecords; |
| 1472 | int64_t baseTimestamp = 0; |
| 1473 | for (const auto &record : _networkStateLogRecords) { |
| 1474 | json11::Json::object jsonRecord; |
| 1475 |
| 1476 | if (baseTimestamp == 0) { |
| 1477 | baseTimestamp = record.timestamp; |
| 1478 | } |
| 1479 | jsonRecord.insert(std::make_pair("t", json11::Json(std::to_string(record.timestamp - baseTimestamp)))); |
| 1480 | jsonRecord.insert(std::make_pair("c", json11::Json(record.record.isConnected ? 1 : 0))); |
| 1481 | if (record.record.route) { |
| 1482 | jsonRecord.insert(std::make_pair("local", json11::Json(record.record.route->localDescription))); |
| 1483 | jsonRecord.insert(std::make_pair("remote", json11::Json(record.record.route->remoteDescription))); |
| 1484 | } |
| 1485 | if (record.record.connection) { |
| 1486 | json11::Json::object jsonConnection; |
| 1487 |
| 1488 | auto serializeCandidate = [](InstanceNetworking::ConnectionDescription::CandidateDescription const &candidate) -> json11::Json::object { |
| 1489 | json11::Json::object jsonCandidate; |
| 1490 |
| 1491 | jsonCandidate.insert(std::make_pair("type", json11::Json(candidate.type))); |
| 1492 | jsonCandidate.insert(std::make_pair("protocol", json11::Json(candidate.protocol))); |
| 1493 | jsonCandidate.insert(std::make_pair("address", json11::Json(candidate.address))); |
| 1494 |
| 1495 | return jsonCandidate; |
| 1496 | }; |
| 1497 |
| 1498 | jsonConnection.insert(std::make_pair("local", serializeCandidate(record.record.connection->local))); |
| 1499 | jsonConnection.insert(std::make_pair("remote", serializeCandidate(record.record.connection->remote))); |
| 1500 |
| 1501 | jsonRecord.insert(std::make_pair("network", std::move(jsonConnection))); |
| 1502 | } |
| 1503 | if (record.record.isFailed) { |
| 1504 | jsonRecord.insert(std::make_pair("failed", json11::Json(1))); |
| 1505 | } |
| 1506 |
| 1507 | jsonNetworkStateLogRecords.push_back(std::move(jsonRecord)); |
| 1508 | } |
| 1509 | statsLog.insert(std::make_pair("network", std::move(jsonNetworkStateLogRecords))); |
| 1510 |
| 1511 | json11::Json::array jsonNetworkBitrateLogRecords; |
| 1512 | for (const auto &record : _networkBitrateLogRecords) { |
| 1513 | json11::Json::object jsonRecord; |
| 1514 |
| 1515 | jsonRecord.insert(std::make_pair("b", json11::Json(record.record.bitrate))); |
| 1516 |
| 1517 | jsonNetworkBitrateLogRecords.push_back(std::move(jsonRecord)); |
| 1518 | } |
| 1519 | statsLog.insert(std::make_pair("bitrate", std::move(jsonNetworkBitrateLogRecords))); |
| 1520 |
| 1521 | auto jsonStatsLog = json11::Json(std::move(statsLog)); |
| 1522 |
| 1523 | if (!_statsLogPath.data.empty()) { |
| 1524 | std::ofstream file; |
| 1525 | file.open(_statsLogPath.data); |
| 1526 |
| 1527 | file << jsonStatsLog.dump(); |
| 1528 |
| 1529 | file.close(); |
| 1530 | } |
| 1531 |
| 1532 | completion(finalState); |
| 1533 | } |
| 1534 |
| 1535 | /*void adjustBitratePreferences(bool resetStartBitrate) { |
| 1536 | if (_outgoingAudioChannel) { |
| 1537 | _outgoingAudioChannel->setMaxBitrate(32 * 1024); |
| 1538 | } |
| 1539 | if (_outgoingVideoChannel) { |
| 1540 | _outgoingVideoChannel->setMaxBitrate(1000 * 1024); |
| 1541 | } |
| 1542 | }*/ |
| 1543 |
| 1544 | private: |
| 1545 | webrtc::scoped_refptr<webrtc::AudioDeviceModule> createAudioDeviceModule() { |
| 1546 | const auto create = [&](webrtc::AudioDeviceModule::AudioLayer layer) { |
| 1547 | #ifdef WEBRTC_IOS |
| 1548 | return rtc::make_ref_counted<webrtc::tgcalls_ios_adm::AudioDeviceModuleIOS>(false, false, false, 1); |
| 1549 | #else |
| 1550 | return webrtc::AudioDeviceModule::Create( |
| 1551 | layer, |
| 1552 | _taskQueueFactory.get()); |
| 1553 | #endif |
| 1554 | }; |
| 1555 | const auto check = [&](const webrtc::scoped_refptr<webrtc::AudioDeviceModule> &result) { |
| 1556 | return (result && result->Init() == 0) ? result : nullptr; |
| 1557 | }; |
| 1558 | if (_createWrappedAudioDeviceModule) { |
| 1559 | auto result = _createWrappedAudioDeviceModule(_taskQueueFactory.get()); |
| 1560 | if (result) { |
| 1561 | return result; |
| 1562 | } |
| 1563 | } |
| 1564 | if (_createAudioDeviceModule) { |
| 1565 | if (const auto result = check(_createAudioDeviceModule(_taskQueueFactory.get()))) { |
| 1566 | return result; |
| 1567 | } |
| 1568 | } |
| 1569 | return check(create(webrtc::AudioDeviceModule::kPlatformDefaultAudio)); |
| 1570 | } |
| 1571 |
| 1572 | private: |
| 1573 | SignalingProtocolVersion _signalingProtocolVersion; |
| 1574 | std::shared_ptr<Threads> _threads; |
| 1575 | std::vector<RtcServer> _rtcServers; |
| 1576 | std::unique_ptr<Proxy> _proxy; |
| 1577 | bool _enableP2P = false; |
| 1578 | EncryptionKey _encryptionKey; |
| 1579 | std::function<void(State)> _stateUpdated; |
| 1580 | std::function<void(int)> _signalBarsUpdated; |
| 1581 | std::function<void(float, float)> _audioLevelsUpdated; |
| 1582 | std::function<void(bool)> _remoteBatteryLevelIsLowUpdated; |
| 1583 | std::function<void(AudioState, VideoState)> _remoteMediaStateUpdated; |
| 1584 | std::function<void(float)> _remotePrefferedAspectRatioUpdated; |
| 1585 | std::function<void(const std::vector<uint8_t> &)> _signalingDataEmitted; |
| 1586 | std::function<webrtc::scoped_refptr<webrtc::AudioDeviceModule>(webrtc::TaskQueueFactory*)> _createAudioDeviceModule; |
| 1587 | std::function<webrtc::scoped_refptr<WrappedAudioDeviceModule>(webrtc::TaskQueueFactory*)> _createWrappedAudioDeviceModule; |
| 1588 | FilePath _statsLogPath; |
| 1589 |
| 1590 | std::unique_ptr<SignalingConnection> _signalingConnection; |
| 1591 | std::unique_ptr<EncryptedConnection> _signalingEncryptedConnection; |
| 1592 |
| 1593 | bool _isConnected = false; |
| 1594 | bool _isFailed = false; |
| 1595 | absl::optional<InstanceNetworking::ConnectionDescription> _currentConnectionDescription; |
| 1596 |
| 1597 | absl::optional<NetworkStateLogRecord> _currentNetworkStateLogRecord; |
| 1598 | std::vector<StateLogRecord<NetworkStateLogRecord>> _networkStateLogRecords; |
| 1599 | std::vector<StateLogRecord<NetworkBitrateLogRecord>> _networkBitrateLogRecords; |
| 1600 |
| 1601 | bool _didBeginNegotiation = false; |
| 1602 | bool _isMakingOffer = false; |
| 1603 | bool _isSettingRemoteAnswerPending = false; |
| 1604 | bool _isPerformingConfiguration = false; |
| 1605 |
| 1606 | webrtc::scoped_refptr<webrtc::AudioTrackInterface> _outgoingAudioTrack; |
| 1607 | webrtc::scoped_refptr<webrtc::RtpTransceiverInterface> _outgoingAudioTransceiver; |
| 1608 | bool _isMicrophoneMuted = false; |
| 1609 |
| 1610 | webrtc::scoped_refptr<webrtc::VideoTrackInterface> _outgoingVideoTrack; |
| 1611 | webrtc::scoped_refptr<webrtc::RtpTransceiverInterface> _outgoingVideoTransceiver; |
| 1612 |
| 1613 | std::map<std::string, webrtc::scoped_refptr<webrtc::RtpTransceiverInterface>> _incomingVideoTransceivers; |
| 1614 |
| 1615 | std::vector<std::unique_ptr<webrtc::IceCandidateInterface>> _pendingIceCandidates; |
| 1616 |
| 1617 | std::unique_ptr<DataChannelObserverImpl> _dataChannelObserver; |
| 1618 | webrtc::scoped_refptr<webrtc::DataChannelInterface> _dataChannel; |
| 1619 | bool _isDataChannelOpen = false; |
| 1620 |
| 1621 | std::unique_ptr<webrtc::RtcEventLogNull> _eventLog; |
| 1622 | std::unique_ptr<webrtc::TaskQueueFactory> _taskQueueFactory; |
| 1623 |
| 1624 | std::unique_ptr<rtc::NetworkMonitorFactory> _networkMonitorFactory; |
| 1625 | std::unique_ptr<rtc::BasicPacketSocketFactory> _socketFactory; |
| 1626 | std::unique_ptr<rtc::BasicNetworkManager> _networkManager; |
| 1627 | std::unique_ptr<cricket::RelayPortFactoryInterface> _relayPortFactory; |
| 1628 |
| 1629 | webrtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> _peerConnectionFactory; |
| 1630 | std::unique_ptr<PeerConnectionDelegateAdapter> _peerConnectionObserver; |
| 1631 | webrtc::scoped_refptr<webrtc::PeerConnectionInterface> _peerConnection; |
| 1632 |
| 1633 | webrtc::LocalAudioSinkAdapter _audioSource; |
| 1634 |
| 1635 | webrtc::scoped_refptr<webrtc::AudioDeviceModule> _audioDeviceModule; |
| 1636 |
| 1637 | bool _isBatteryLow = false; |
| 1638 |
| 1639 | std::shared_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> _currentStrongSink; |
| 1640 |
| 1641 | std::shared_ptr<VideoCaptureInterface> _videoCapture; |
| 1642 | std::shared_ptr<PlatformContext> _platformContext; |
| 1643 | }; |
| 1644 |
| 1645 | InstanceV2ReferenceImpl::InstanceV2ReferenceImpl(Descriptor &&descriptor) { |
| 1646 | if (descriptor.config.logPath.data.size() != 0) { |
| 1647 | _logSink = std::make_unique<LogSinkImpl>(descriptor.config.logPath); |
| 1648 | } |
| 1649 | rtc::LogMessage::LogToDebug(rtc::LS_INFO); |
| 1650 | rtc::LogMessage::SetLogToStderr(false); |
| 1651 | if (_logSink) { |
| 1652 | rtc::LogMessage::AddLogToStream(_logSink.get(), rtc::LS_INFO); |
| 1653 | } |
| 1654 |
| 1655 | _threads = StaticThreads::getThreads(); |
| 1656 | _internal.reset(new ThreadLocalObject<InstanceV2ReferenceImplInternal>(_threads->getMediaThread(), [descriptor = std::move(descriptor), threads = _threads]() mutable { |
| 1657 | return std::make_shared<InstanceV2ReferenceImplInternal>(std::move(descriptor), threads); |
| 1658 | })); |
| 1659 | _internal->perform([](InstanceV2ReferenceImplInternal *internal) { |
| 1660 | internal->start(); |
| 1661 | }); |
| 1662 | } |
| 1663 |
| 1664 | InstanceV2ReferenceImpl::~InstanceV2ReferenceImpl() { |
| 1665 | rtc::LogMessage::RemoveLogToStream(_logSink.get()); |
| 1666 | } |
| 1667 |
| 1668 | void InstanceV2ReferenceImpl::receiveSignalingData(const std::vector<uint8_t> &data) { |
| 1669 | _internal->perform([data](InstanceV2ReferenceImplInternal *internal) { |
| 1670 | internal->receiveSignalingData(data); |
| 1671 | }); |
| 1672 | } |
| 1673 |
| 1674 | void InstanceV2ReferenceImpl::setVideoCapture(std::shared_ptr<VideoCaptureInterface> videoCapture) { |
| 1675 | _internal->perform([videoCapture](InstanceV2ReferenceImplInternal *internal) { |
| 1676 | internal->setVideoCapture(videoCapture); |
| 1677 | }); |
| 1678 | } |
| 1679 |
| 1680 | void InstanceV2ReferenceImpl::setRequestedVideoAspect(float aspect) { |
| 1681 | _internal->perform([aspect](InstanceV2ReferenceImplInternal *internal) { |
| 1682 | internal->setRequestedVideoAspect(aspect); |
| 1683 | }); |
| 1684 | } |
| 1685 |
| 1686 | void InstanceV2ReferenceImpl::setNetworkType(NetworkType networkType) { |
| 1687 | _internal->perform([networkType](InstanceV2ReferenceImplInternal *internal) { |
| 1688 | internal->setNetworkType(networkType); |
| 1689 | }); |
| 1690 | } |
| 1691 |
| 1692 | void InstanceV2ReferenceImpl::setMuteMicrophone(bool muteMicrophone) { |
| 1693 | _internal->perform([muteMicrophone](InstanceV2ReferenceImplInternal *internal) { |
| 1694 | internal->setMuteMicrophone(muteMicrophone); |
| 1695 | }); |
| 1696 | } |
| 1697 |
| 1698 | void InstanceV2ReferenceImpl::setIncomingVideoOutput(std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) { |
| 1699 | _internal->perform([sink](InstanceV2ReferenceImplInternal *internal) { |
| 1700 | internal->setIncomingVideoOutput(sink); |
| 1701 | }); |
| 1702 | } |
| 1703 |
| 1704 | void InstanceV2ReferenceImpl::setAudioInputDevice(std::string id) { |
| 1705 | _internal->perform([id](InstanceV2ReferenceImplInternal *internal) { |
| 1706 | internal->setAudioInputDevice(id); |
| 1707 | }); |
| 1708 | } |
| 1709 |
| 1710 | void InstanceV2ReferenceImpl::setAudioOutputDevice(std::string id) { |
| 1711 | _internal->perform([id](InstanceV2ReferenceImplInternal *internal) { |
| 1712 | internal->setAudioOutputDevice(id); |
| 1713 | }); |
| 1714 | } |
| 1715 |
| 1716 | void InstanceV2ReferenceImpl::setIsLowBatteryLevel(bool isLowBatteryLevel) { |
| 1717 | _internal->perform([isLowBatteryLevel](InstanceV2ReferenceImplInternal *internal) { |
| 1718 | internal->setIsLowBatteryLevel(isLowBatteryLevel); |
| 1719 | }); |
| 1720 | } |
| 1721 |
| 1722 | void InstanceV2ReferenceImpl::setInputVolume(float level) { |
| 1723 | } |
| 1724 |
| 1725 | void InstanceV2ReferenceImpl::setOutputVolume(float level) { |
| 1726 | } |
| 1727 |
| 1728 | void InstanceV2ReferenceImpl::setAudioOutputDuckingEnabled(bool enabled) { |
| 1729 | } |
| 1730 |
| 1731 | void InstanceV2ReferenceImpl::setAudioOutputGainControlEnabled(bool enabled) { |
| 1732 | } |
| 1733 |
| 1734 | void InstanceV2ReferenceImpl::setEchoCancellationStrength(int strength) { |
| 1735 | } |
| 1736 |
| 1737 | std::vector<std::string> InstanceV2ReferenceImpl::GetVersions() { |
| 1738 | std::vector<std::string> result; |
| 1739 | result.push_back("10.0.0"); |
| 1740 | result.push_back("11.0.0"); |
| 1741 | return result; |
| 1742 | } |
| 1743 |
| 1744 | int InstanceV2ReferenceImpl::GetConnectionMaxLayer() { |
| 1745 | return 92; |
| 1746 | } |
| 1747 |
| 1748 | std::string InstanceV2ReferenceImpl::getLastError() { |
| 1749 | return ""; |
| 1750 | } |
| 1751 |
| 1752 | std::string InstanceV2ReferenceImpl::getDebugInfo() { |
| 1753 | return ""; |
| 1754 | } |
| 1755 |
| 1756 | int64_t InstanceV2ReferenceImpl::getPreferredRelayId() { |
| 1757 | return 0; |
| 1758 | } |
| 1759 |
| 1760 | TrafficStats InstanceV2ReferenceImpl::getTrafficStats() { |
| 1761 | return {}; |
| 1762 | } |
| 1763 |
| 1764 | PersistentState InstanceV2ReferenceImpl::getPersistentState() { |
| 1765 | return {}; |
| 1766 | } |
| 1767 |
| 1768 | void InstanceV2ReferenceImpl::stop(std::function<void(FinalState)> completion) { |
| 1769 | std::string debugLog; |
| 1770 | if (_logSink) { |
| 1771 | debugLog = _logSink->result(); |
| 1772 | } |
| 1773 | _internal->perform([completion, debugLog = std::move(debugLog)](InstanceV2ReferenceImplInternal *internal) mutable { |
| 1774 | internal->stop([completion, debugLog = std::move(debugLog)](FinalState finalState) mutable { |
| 1775 | finalState.debugLog = debugLog; |
| 1776 | completion(finalState); |
| 1777 | }); |
| 1778 | }); |
| 1779 | } |
| 1780 |
| 1781 | template <> |
| 1782 | bool Register<InstanceV2ReferenceImpl>() { |
| 1783 | return Meta::RegisterOne<InstanceV2ReferenceImpl>(); |
| 1784 | } |
| 1785 |
| 1786 | } // namespace tgcalls |
| 1787 |