| #include "VideoCapturerInterface.h" |
| 6 | #include "v2/NativeNetworkingImpl.h" |
| 7 | #include "v2/DirectNetworkingImpl.h" |
| 8 | #include "v2/Signaling.h" |
| 9 | #include "v2/ContentNegotiation.h" |
| 10 |
| 11 | #include "CodecSelectHelper.h" |
| 12 | #include "platform/PlatformInterface.h" |
| 13 |
| 14 | #include "api/audio_codecs/audio_decoder_factory_template.h" |
| 15 | #include "api/audio_codecs/audio_encoder_factory_template.h" |
| 16 | #include "api/audio_codecs/opus/audio_decoder_opus.h" |
| 17 | #include "api/audio_codecs/opus/audio_decoder_multi_channel_opus.h" |
| 18 | #include "api/audio_codecs/opus/audio_encoder_opus.h" |
| 19 | #include "api/audio_codecs/L16/audio_decoder_L16.h" |
| 20 | #include "api/audio_codecs/L16/audio_encoder_L16.h" |
| 21 | #include "api/task_queue/default_task_queue_factory.h" |
| 22 | #include "media/engine/webrtc_media_engine.h" |
| 23 | #include "system_wrappers/include/field_trial.h" |
| 24 | #include "api/video/builtin_video_bitrate_allocator_factory.h" |
| 25 | #include "call/call.h" |
| 26 | #include "api/call/audio_sink.h" |
| 27 | #include "modules/audio_processing/audio_buffer.h" |
| 28 | #include "absl/strings/match.h" |
| 29 | #include "pc/channel.h" |
| 30 | #include "audio/audio_state.h" |
| 31 | #include "modules/audio_coding/neteq/default_neteq_factory.h" |
| 32 | #include "modules/audio_coding/include/audio_coding_module.h" |
| 33 | #include "api/candidate.h" |
| 34 | #include "api/jsep_ice_candidate.h" |
| 35 | #include "pc/used_ids.h" |
| 36 | #include "media/base/sdp_video_format_utils.h" |
| 37 | #include "pc/media_session.h" |
| 38 | #include "rtc_base/rtc_certificate_generator.h" |
| 39 |
| 40 | #include "AudioFrame.h" |
| 41 | #include "ThreadLocalObject.h" |
| 42 | #include "Manager.h" |
| 43 | #include "NetworkManager.h" |
| 44 | #include "VideoCaptureInterfaceImpl.h" |
| 45 | #include "platform/PlatformInterface.h" |
| 46 | #include "LogSinkImpl.h" |
| 47 | #include "CodecSelectHelper.h" |
| 48 | #include "AudioDeviceHelper.h" |
| 49 | #include "SignalingEncryption.h" |
| 50 | #ifdef WEBRTC_IOS |
| 51 | #include "platform/darwin/iOS/tgcalls_audio_device_module_ios.h" |
| 52 | #endif |
| 53 | #include <random> |
| 54 | #include <sstream> |
| 55 |
| 56 | #include "FieldTrialsConfig.h" |
| 57 |
| 58 | #include "third-party/json11.hpp" |
| 59 |
| 60 | #include "ChannelManager.h" |
| 61 | #include "SignalingConnection.h" |
| 62 | #include "ExternalSignalingConnection.h" |
| 63 | #include "SignalingSctpConnection.h" |
| 64 | #include "utils/gzip.h" |
| 65 |
| 66 | namespace tgcalls { |
| 67 | namespace { |
| 68 |
| 69 | enum class SignalingProtocolVersion { |
| 70 | V1, |
| 71 | V2, |
| 72 | V3 |
| 73 | }; |
| 74 |
| 75 | SignalingProtocolVersion signalingProtocolVersion(std::string const &version) { |
| 76 | if (version == "7.0.0") { |
| 77 | return SignalingProtocolVersion::V1; |
| 78 | } else if (version == "8.0.0") { |
| 79 | return SignalingProtocolVersion::V2; |
| 80 | } else if (version == "9.0.0") { |
| 81 | return SignalingProtocolVersion::V2; |
| 82 | } else { |
| 83 | RTC_LOG(LS_ERROR) << "signalingProtocolVersion: unknown version " << version; |
| 84 |
| 85 | return SignalingProtocolVersion::V2; |
| 86 | } |
| 87 | } |
| 88 |
| 89 | bool signalingProtocolSupportsCompression(SignalingProtocolVersion version) { |
| 90 | switch (version) { |
| 91 | case SignalingProtocolVersion::V1: |
| 92 | case SignalingProtocolVersion::V2: |
| 93 | return false; |
| 94 | case SignalingProtocolVersion::V3: |
| 95 | return true; |
| 96 | default: |
| 97 | RTC_DCHECK_NOTREACHED(); |
| 98 | break; |
| 99 | } |
| 100 | return false; |
| 101 | } |
| 102 |
| 103 | static VideoCaptureInterfaceObject *GetVideoCaptureAssumingSameThread(VideoCaptureInterface *videoCapture) { |
| 104 | return videoCapture |
| 105 | ? static_cast<VideoCaptureInterfaceImpl*>(videoCapture)->object()->getSyncAssumingSameThread() |
| 106 | : nullptr; |
| 107 | } |
| 108 |
| 109 | class OutgoingAudioChannel : public sigslot::has_slots<> { |
| 110 | public: |
| 111 | OutgoingAudioChannel( |
| 112 | webrtc::Call *call, |
| 113 | ChannelManager *channelManager, |
| 114 | rtc::UniqueRandomIdGenerator *uniqueRandomIdGenerator, |
| 115 | webrtc::LocalAudioSinkAdapter *audioSource, |
| 116 | webrtc::RtpTransport *rtpTransport, |
| 117 | signaling::MediaContent const &mediaContent, |
| 118 | std::shared_ptr<Threads> threads |
| 119 | ) : |
| 120 | _threads(threads), |
| 121 | _ssrc(mediaContent.ssrc), |
| 122 | _call(call), |
| 123 | _channelManager(channelManager), |
| 124 | _audioSource(audioSource) { |
| 125 | cricket::AudioOptions audioOptions; |
| 126 | bool _disableOutgoingAudioProcessing = false; |
| 127 |
| 128 | if (_disableOutgoingAudioProcessing) { |
| 129 | audioOptions.echo_cancellation = false; |
| 130 | audioOptions.noise_suppression = false; |
| 131 | audioOptions.auto_gain_control = false; |
| 132 | audioOptions.highpass_filter = false; |
| 133 | //audioOptions.typing_detection = false; |
| 134 | //audioOptions.residual_echo_detector = false; |
| 135 | } else { |
| 136 | audioOptions.echo_cancellation = true; |
| 137 | audioOptions.noise_suppression = true; |
| 138 | } |
| 139 |
| 140 | const auto contentId = std::to_string(_ssrc); |
| 141 |
| 142 | std::vector<std::string> streamIds; |
| 143 | streamIds.push_back(contentId); |
| 144 |
| 145 | _outgoingAudioChannel = _channelManager->CreateVoiceChannel(call, cricket::MediaConfig(), contentId, false, NativeNetworkingImpl::getDefaulCryptoOptions(), audioOptions); |
| 146 | _threads->getNetworkThread()->BlockingCall([&]() { |
| 147 | _outgoingAudioChannel->SetRtpTransport(rtpTransport); |
| 148 | }); |
| 149 |
| 150 | std::vector<cricket::AudioCodec> codecs; |
| 151 | for (const auto &payloadType : mediaContent.payloadTypes) { |
| 152 | if (payloadType.name == "opus") { |
| 153 | cricket::AudioCodec codec(payloadType.id, payloadType.name, payloadType.clockrate, 0, payloadType.channels); |
| 154 |
| 155 | codec.SetParam(cricket::kCodecParamUseInbandFec, 1); |
| 156 | codec.SetParam(cricket::kCodecParamPTime, 60); |
| 157 |
| 158 | for (const auto &feedbackType : payloadType.feedbackTypes) { |
| 159 | codec.AddFeedbackParam(cricket::FeedbackParam(feedbackType.type, feedbackType.subtype)); |
| 160 | } |
| 161 |
| 162 | codecs.push_back(std::move(codec)); |
| 163 |
| 164 | break; |
| 165 | } |
| 166 | } |
| 167 |
| 168 | auto outgoingAudioDescription = std::make_unique<cricket::AudioContentDescription>(); |
| 169 | for (const auto &rtpExtension : mediaContent.rtpExtensions) { |
| 170 | outgoingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(rtpExtension.uri, rtpExtension.id)); |
| 171 | } |
| 172 | outgoingAudioDescription->set_rtcp_mux(true); |
| 173 | outgoingAudioDescription->set_rtcp_reduced_size(true); |
| 174 | outgoingAudioDescription->set_direction(webrtc::RtpTransceiverDirection::kSendOnly); |
| 175 | outgoingAudioDescription->set_codecs(codecs); |
| 176 | outgoingAudioDescription->set_bandwidth(-1); |
| 177 | outgoingAudioDescription->AddStream(cricket::StreamParams::CreateLegacy(_ssrc)); |
| 178 |
| 179 | auto incomingAudioDescription = std::make_unique<cricket::AudioContentDescription>(); |
| 180 | for (const auto &rtpExtension : mediaContent.rtpExtensions) { |
| 181 | incomingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(rtpExtension.uri, rtpExtension.id)); |
| 182 | } |
| 183 | incomingAudioDescription->set_rtcp_mux(true); |
| 184 | incomingAudioDescription->set_rtcp_reduced_size(true); |
| 185 | incomingAudioDescription->set_direction(webrtc::RtpTransceiverDirection::kRecvOnly); |
| 186 | incomingAudioDescription->set_codecs(codecs); |
| 187 | incomingAudioDescription->set_bandwidth(-1); |
| 188 |
| 189 | _threads->getWorkerThread()->BlockingCall([&]() { |
| 190 | _outgoingAudioChannel->SetPayloadTypeDemuxingEnabled(false); |
| 191 | std::string errorDesc; |
| 192 | _outgoingAudioChannel->SetLocalContent(outgoingAudioDescription.get(), webrtc::SdpType::kOffer, errorDesc); |
| 193 | _outgoingAudioChannel->SetRemoteContent(incomingAudioDescription.get(), webrtc::SdpType::kAnswer, errorDesc); |
| 194 | }); |
| 195 |
| 196 | setIsMuted(false); |
| 197 | } |
| 198 |
| 199 | ~OutgoingAudioChannel() { |
| 200 | _outgoingAudioChannel->Enable(false); |
| 201 | _threads->getNetworkThread()->BlockingCall([&]() { |
| 202 | _outgoingAudioChannel->SetRtpTransport(nullptr); |
| 203 | }); |
| 204 | _channelManager->DestroyChannel(_outgoingAudioChannel); |
| 205 | _outgoingAudioChannel = nullptr; |
| 206 | } |
| 207 |
| 208 | void setIsMuted(bool isMuted) { |
| 209 | if (_isMuted != isMuted) { |
| 210 | _isMuted = isMuted; |
| 211 |
| 212 | _outgoingAudioChannel->Enable(!_isMuted); |
| 213 | _threads->getWorkerThread()->BlockingCall([&]() { |
| 214 | _outgoingAudioChannel->media_channel()->SetAudioSend(_ssrc, !_isMuted, nullptr, _audioSource); |
| 215 | }); |
| 216 | } |
| 217 | } |
| 218 |
| 219 | uint32_t ssrc() const { |
| 220 | return _ssrc; |
| 221 | } |
| 222 |
| 223 | void setMaxBitrate(int bitrate) { |
| 224 | _threads->getWorkerThread()->BlockingCall([&]() { |
| 225 | webrtc::RtpParameters initialParameters = _outgoingAudioChannel->media_channel()->GetRtpSendParameters(_ssrc); |
| 226 | webrtc::RtpParameters updatedParameters = initialParameters; |
| 227 |
| 228 | if (updatedParameters.encodings.empty()) { |
| 229 | updatedParameters.encodings.push_back(webrtc::RtpEncodingParameters()); |
| 230 | } |
| 231 |
| 232 | updatedParameters.encodings[0].max_bitrate_bps = bitrate; |
| 233 |
| 234 | if (initialParameters != updatedParameters) { |
| 235 | _outgoingAudioChannel->media_channel()->SetRtpSendParameters(_ssrc, updatedParameters); |
| 236 | } |
| 237 | }); |
| 238 | } |
| 239 |
| 240 | private: |
| 241 | void OnSentPacket_w(const rtc::SentPacket& sent_packet) { |
| 242 | _call->OnSentPacket(sent_packet); |
| 243 | } |
| 244 |
| 245 | private: |
| 246 | std::shared_ptr<Threads> _threads; |
| 247 | uint32_t _ssrc = 0; |
| 248 | webrtc::Call *_call = nullptr; |
| 249 | ChannelManager *_channelManager = nullptr; |
| 250 | webrtc::LocalAudioSinkAdapter *_audioSource = nullptr; |
| 251 | cricket::VoiceChannel *_outgoingAudioChannel = nullptr; |
| 252 |
| 253 | bool _isMuted = true; |
| 254 | }; |
| 255 |
| 256 | namespace { |
| 257 | class AudioSinkImpl: public webrtc::AudioSinkInterface { |
| 258 | public: |
| 259 | AudioSinkImpl(std::function<void(float, float)> update) : |
| 260 | _update(update) { |
| 261 | } |
| 262 |
| 263 | virtual ~AudioSinkImpl() { |
| 264 | } |
| 265 |
| 266 | virtual void OnData(const Data& audio) override { |
| 267 | if (_update && audio.channels == 1) { |
| 268 | const int16_t *samples = (const int16_t *)audio.data; |
| 269 | int numberOfSamplesInFrame = (int)audio.samples_per_channel; |
| 270 |
| 271 | int16_t currentPeak = 0; |
| 272 | for (int i = 0; i < numberOfSamplesInFrame; i++) { |
| 273 | int16_t sample = samples[i]; |
| 274 | if (sample < 0) { |
| 275 | sample = -sample; |
| 276 | } |
| 277 | if (_peak < sample) { |
| 278 | _peak = sample; |
| 279 | } |
| 280 | if (currentPeak < sample) { |
| 281 | currentPeak = sample; |
| 282 | } |
| 283 | _peakCount += 1; |
| 284 | } |
| 285 |
| 286 | if (_peakCount >= 4400) { |
| 287 | float level = ((float)(_peak)) / 8000.0f; |
| 288 | _peak = 0; |
| 289 | _peakCount = 0; |
| 290 | _update(0, level); |
| 291 | } |
| 292 | } |
| 293 | } |
| 294 |
| 295 | private: |
| 296 | std::function<void(float, float)> _update; |
| 297 |
| 298 | int _peakCount = 0; |
| 299 | uint16_t _peak = 0; |
| 300 | }; |
| 301 |
| 302 | } |
| 303 |
| 304 | class IncomingV2AudioChannel : public sigslot::has_slots<> { |
| 305 | public: |
| 306 | IncomingV2AudioChannel( |
| 307 | ChannelManager *channelManager, |
| 308 | webrtc::Call *call, |
| 309 | webrtc::RtpTransport *rtpTransport, |
| 310 | rtc::UniqueRandomIdGenerator *randomIdGenerator, |
| 311 | signaling::MediaContent const &mediaContent, |
| 312 | std::function<void(float, float)> &&onAudioLevelUpdated, |
| 313 | std::shared_ptr<Threads> threads) : |
| 314 | _threads(threads), |
| 315 | _ssrc(mediaContent.ssrc), |
| 316 | _channelManager(channelManager), |
| 317 | _call(call) { |
| 318 | _creationTimestamp = rtc::TimeMillis(); |
| 319 |
| 320 | cricket::AudioOptions audioOptions; |
| 321 | audioOptions.audio_jitter_buffer_fast_accelerate = true; |
| 322 | audioOptions.audio_jitter_buffer_min_delay_ms = 50; |
| 323 |
| 324 | const auto streamId = std::to_string(_ssrc); |
| 325 |
| 326 | _audioChannel = _channelManager->CreateVoiceChannel(call, cricket::MediaConfig(), streamId, false, NativeNetworkingImpl::getDefaulCryptoOptions(), audioOptions); |
| 327 | _threads->getNetworkThread()->BlockingCall([&]() { |
| 328 | _audioChannel->SetRtpTransport(rtpTransport); |
| 329 | }); |
| 330 |
| 331 | std::vector<cricket::AudioCodec> codecs; |
| 332 | for (const auto &payloadType : mediaContent.payloadTypes) { |
| 333 | cricket::AudioCodec codec(payloadType.id, payloadType.name, payloadType.clockrate, 0, payloadType.channels); |
| 334 | for (const auto ¶meter : payloadType.parameters) { |
| 335 | codec.SetParam(parameter.first, parameter.second); |
| 336 | } |
| 337 | for (const auto &feedbackType : payloadType.feedbackTypes) { |
| 338 | codec.AddFeedbackParam(cricket::FeedbackParam(feedbackType.type, feedbackType.subtype)); |
| 339 | } |
| 340 | codecs.push_back(std::move(codec)); |
| 341 | } |
| 342 |
| 343 | auto outgoingAudioDescription = std::make_unique<cricket::AudioContentDescription>(); |
| 344 | for (const auto &rtpExtension : mediaContent.rtpExtensions) { |
| 345 | outgoingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(rtpExtension.uri, rtpExtension.id)); |
| 346 | } |
| 347 |
| 348 | outgoingAudioDescription->set_rtcp_mux(true); |
| 349 | outgoingAudioDescription->set_rtcp_reduced_size(true); |
| 350 | outgoingAudioDescription->set_direction(webrtc::RtpTransceiverDirection::kRecvOnly); |
| 351 | outgoingAudioDescription->set_codecs(codecs); |
| 352 | outgoingAudioDescription->set_bandwidth(-1); |
| 353 |
| 354 | auto incomingAudioDescription = std::make_unique<cricket::AudioContentDescription>(); |
| 355 | for (const auto &rtpExtension : mediaContent.rtpExtensions) { |
| 356 | incomingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(rtpExtension.uri, rtpExtension.id)); |
| 357 | } |
| 358 | incomingAudioDescription->set_rtcp_mux(true); |
| 359 | incomingAudioDescription->set_rtcp_reduced_size(true); |
| 360 | incomingAudioDescription->set_direction(webrtc::RtpTransceiverDirection::kSendOnly); |
| 361 | incomingAudioDescription->set_codecs(codecs); |
| 362 | incomingAudioDescription->set_bandwidth(-1); |
| 363 | cricket::StreamParams streamParams = cricket::StreamParams::CreateLegacy(mediaContent.ssrc); |
| 364 | streamParams.set_stream_ids({ streamId }); |
| 365 | incomingAudioDescription->AddStream(streamParams); |
| 366 |
| 367 | threads->getWorkerThread()->BlockingCall([this, &outgoingAudioDescription, &incomingAudioDescription, onAudioLevelUpdated = std::move(onAudioLevelUpdated), ssrc = mediaContent.ssrc]() { |
| 368 | _audioChannel->SetPayloadTypeDemuxingEnabled(false); |
| 369 | std::string errorDesc; |
| 370 | _audioChannel->SetLocalContent(outgoingAudioDescription.get(), webrtc::SdpType::kOffer, errorDesc); |
| 371 | _audioChannel->SetRemoteContent(incomingAudioDescription.get(), webrtc::SdpType::kAnswer, errorDesc); |
| 372 |
| 373 | std::unique_ptr<AudioSinkImpl> audioLevelSink(new AudioSinkImpl(std::move(onAudioLevelUpdated))); |
| 374 | _audioChannel->media_channel()->SetRawAudioSink(ssrc, std::move(audioLevelSink)); |
| 375 | }); |
| 376 |
| 377 | outgoingAudioDescription.reset(); |
| 378 | incomingAudioDescription.reset(); |
| 379 |
| 380 |
| 381 | //std::unique_ptr<AudioSinkImpl> audioLevelSink(new AudioSinkImpl(onAudioLevelUpdated, _ssrc, std::move(onAudioFrame))); |
| 382 | //_audioChannel->media_channel()->SetRawAudioSink(ssrc.networkSsrc, std::move(audioLevelSink)); |
| 383 |
| 384 | _audioChannel->Enable(true); |
| 385 |
| 386 | } |
| 387 |
| 388 | ~IncomingV2AudioChannel() { |
| 389 | _audioChannel->Enable(false); |
| 390 | _threads->getNetworkThread()->BlockingCall([&]() { |
| 391 | _audioChannel->SetRtpTransport(nullptr); |
| 392 | }); |
| 393 | _channelManager->DestroyChannel(_audioChannel); |
| 394 | _audioChannel = nullptr; |
| 395 | } |
| 396 |
| 397 | void setVolume(double value) { |
| 398 | _audioChannel->media_channel()->SetOutputVolume(_ssrc, value); |
| 399 | } |
| 400 |
| 401 | void updateActivity() { |
| 402 | _activityTimestamp = rtc::TimeMillis(); |
| 403 | } |
| 404 |
| 405 | int64_t getActivity() { |
| 406 | return _activityTimestamp; |
| 407 | } |
| 408 |
| 409 | uint32_t ssrc() const { |
| 410 | return _ssrc; |
| 411 | } |
| 412 |
| 413 | private: |
| 414 | void OnSentPacket_w(const rtc::SentPacket& sent_packet) { |
| 415 | _call->OnSentPacket(sent_packet); |
| 416 | } |
| 417 |
| 418 | private: |
| 419 | std::shared_ptr<Threads> _threads; |
| 420 | uint32_t _ssrc = 0; |
| 421 | // Memory is managed by _channelManager |
| 422 | cricket::VoiceChannel *_audioChannel = nullptr; |
| 423 | // Memory is managed externally |
| 424 | ChannelManager *_channelManager = nullptr; |
| 425 | webrtc::Call *_call = nullptr; |
| 426 | int64_t _creationTimestamp = 0; |
| 427 | int64_t _activityTimestamp = 0; |
| 428 | }; |
| 429 |
| 430 | class OutgoingVideoChannel : public sigslot::has_slots<>, public std::enable_shared_from_this<OutgoingVideoChannel> { |
| 431 | public: |
| 432 | OutgoingVideoChannel( |
| 433 | std::shared_ptr<Threads> threads, |
| 434 | ChannelManager *channelManager, |
| 435 | webrtc::Call *call, |
| 436 | webrtc::RtpTransport *rtpTransport, |
| 437 | rtc::UniqueRandomIdGenerator *randomIdGenerator, |
| 438 | webrtc::VideoBitrateAllocatorFactory *videoBitrateAllocatorFactory, |
| 439 | std::function<void()> rotationUpdated, |
| 440 | signaling::MediaContent const &mediaContent, |
| 441 | bool isScreencast |
| 442 | ) : |
| 443 | _threads(threads), |
| 444 | _mainSsrc(mediaContent.ssrc), |
| 445 | _call(call), |
| 446 | _channelManager(channelManager), |
| 447 | _rotationUpdated(rotationUpdated) { |
| 448 | cricket::VideoOptions videoOptions; |
| 449 | videoOptions.is_screencast = isScreencast; |
| 450 |
| 451 | _outgoingVideoChannel = _channelManager->CreateVideoChannel(call, cricket::MediaConfig(), std::to_string(mediaContent.ssrc), false, NativeNetworkingImpl::getDefaulCryptoOptions(), videoOptions, videoBitrateAllocatorFactory); |
| 452 | _threads->getNetworkThread()->BlockingCall([&]() { |
| 453 | _outgoingVideoChannel->SetRtpTransport(rtpTransport); |
| 454 | }); |
| 455 |
| 456 | std::vector<cricket::VideoCodec> unsortedCodecs; |
| 457 | for (const auto &payloadType : mediaContent.payloadTypes) { |
| 458 | cricket::VideoCodec codec(payloadType.id, payloadType.name); |
| 459 | for (const auto ¶meter : payloadType.parameters) { |
| 460 | codec.SetParam(parameter.first, parameter.second); |
| 461 | } |
| 462 | for (const auto &feedbackType : payloadType.feedbackTypes) { |
| 463 | codec.AddFeedbackParam(cricket::FeedbackParam(feedbackType.type, feedbackType.subtype)); |
| 464 | } |
| 465 | unsortedCodecs.push_back(std::move(codec)); |
| 466 | } |
| 467 |
| 468 | std::vector<std::string> codecPreferences = { |
| 469 | #ifndef WEBRTC_DISABLE_H265 |
| 470 | cricket::kH265CodecName, |
| 471 | #endif |
| 472 | cricket::kH264CodecName |
| 473 | }; |
| 474 |
| 475 | std::vector<cricket::VideoCodec> codecs; |
| 476 | for (const auto &name : codecPreferences) { |
| 477 | for (const auto &codec : unsortedCodecs) { |
| 478 | if (codec.name == name) { |
| 479 | codecs.push_back(codec); |
| 480 | } |
| 481 | } |
| 482 | } |
| 483 | for (const auto &codec : unsortedCodecs) { |
| 484 | if (std::find(codecs.begin(), codecs.end(), codec) == codecs.end()) { |
| 485 | codecs.push_back(codec); |
| 486 | } |
| 487 | } |
| 488 |
| 489 | auto outgoingVideoDescription = std::make_unique<cricket::VideoContentDescription>(); |
| 490 | for (const auto &rtpExtension : mediaContent.rtpExtensions) { |
| 491 | outgoingVideoDescription->AddRtpHeaderExtension(rtpExtension); |
| 492 | } |
| 493 |
| 494 | outgoingVideoDescription->set_rtcp_mux(true); |
| 495 | outgoingVideoDescription->set_rtcp_reduced_size(true); |
| 496 | outgoingVideoDescription->set_direction(webrtc::RtpTransceiverDirection::kSendOnly); |
| 497 | outgoingVideoDescription->set_codecs(codecs); |
| 498 | outgoingVideoDescription->set_bandwidth(-1); |
| 499 |
| 500 | cricket::StreamParams videoSendStreamParams; |
| 501 |
| 502 | for (const auto &ssrcGroup : mediaContent.ssrcGroups) { |
| 503 | for (auto ssrc : ssrcGroup.ssrcs) { |
| 504 | if (!videoSendStreamParams.has_ssrc(ssrc)) { |
| 505 | videoSendStreamParams.ssrcs.push_back(ssrc); |
| 506 | } |
| 507 | } |
| 508 |
| 509 | cricket::SsrcGroup mappedGroup(ssrcGroup.semantics, ssrcGroup.ssrcs); |
| 510 | videoSendStreamParams.ssrc_groups.push_back(std::move(mappedGroup)); |
| 511 | } |
| 512 |
| 513 | videoSendStreamParams.cname = "cname"; |
| 514 |
| 515 | outgoingVideoDescription->AddStream(videoSendStreamParams); |
| 516 |
| 517 | auto incomingVideoDescription = std::make_unique<cricket::VideoContentDescription>(); |
| 518 | for (const auto &rtpExtension : mediaContent.rtpExtensions) { |
| 519 | incomingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(rtpExtension.uri, rtpExtension.id)); |
| 520 | } |
| 521 | incomingVideoDescription->set_rtcp_mux(true); |
| 522 | incomingVideoDescription->set_rtcp_reduced_size(true); |
| 523 | incomingVideoDescription->set_direction(webrtc::RtpTransceiverDirection::kRecvOnly); |
| 524 | incomingVideoDescription->set_codecs(codecs); |
| 525 | incomingVideoDescription->set_bandwidth(-1); |
| 526 |
| 527 | threads->getWorkerThread()->BlockingCall([&]() { |
| 528 | _outgoingVideoChannel->SetPayloadTypeDemuxingEnabled(false); |
| 529 | std::string errorDesc; |
| 530 | _outgoingVideoChannel->SetLocalContent(outgoingVideoDescription.get(), webrtc::SdpType::kOffer, errorDesc); |
| 531 | _outgoingVideoChannel->SetRemoteContent(incomingVideoDescription.get(), webrtc::SdpType::kAnswer, errorDesc); |
| 532 |
| 533 | webrtc::RtpParameters rtpParameters = _outgoingVideoChannel->media_channel()->GetRtpSendParameters(mediaContent.ssrc); |
| 534 |
| 535 | if (isScreencast) { |
| 536 | rtpParameters.degradation_preference = webrtc::DegradationPreference::MAINTAIN_RESOLUTION; |
| 537 | } |
| 538 |
| 539 | _outgoingVideoChannel->media_channel()->SetRtpSendParameters(mediaContent.ssrc, rtpParameters); |
| 540 | }); |
| 541 |
| 542 | _outgoingVideoChannel->Enable(false); |
| 543 |
| 544 | threads->getWorkerThread()->BlockingCall([&]() { |
| 545 | _outgoingVideoChannel->media_channel()->SetVideoSend(mediaContent.ssrc, NULL, nullptr); |
| 546 | }); |
| 547 | } |
| 548 |
| 549 | ~OutgoingVideoChannel() { |
| 550 | _outgoingVideoChannel->Enable(false); |
| 551 | _threads->getNetworkThread()->BlockingCall([&]() { |
| 552 | _outgoingVideoChannel->SetRtpTransport(nullptr); |
| 553 | }); |
| 554 | _channelManager->DestroyChannel(_outgoingVideoChannel); |
| 555 | _outgoingVideoChannel = nullptr; |
| 556 | } |
| 557 |
| 558 | void setVideoCapture(std::shared_ptr<VideoCaptureInterface> videoCapture) { |
| 559 | _videoCapture = videoCapture; |
| 560 |
| 561 | if (_videoCapture) { |
| 562 | _outgoingVideoChannel->Enable(true); |
| 563 | auto videoCaptureImpl = GetVideoCaptureAssumingSameThread(_videoCapture.get()); |
| 564 |
| 565 | _threads->getWorkerThread()->BlockingCall([&]() { |
| 566 | _outgoingVideoChannel->media_channel()->SetVideoSend(_mainSsrc, NULL, videoCaptureImpl->source().get()); |
| 567 | }); |
| 568 |
| 569 | const auto weak = std::weak_ptr<OutgoingVideoChannel>(shared_from_this()); |
| 570 | videoCaptureImpl->setRotationUpdated([threads = _threads, weak](int angle) { |
| 571 | threads->getMediaThread()->PostTask([=] { |
| 572 | const auto strong = weak.lock(); |
| 573 | if (!strong) { |
| 574 | return; |
| 575 | } |
| 576 | signaling::MediaStateMessage::VideoRotation videoRotation = signaling::MediaStateMessage::VideoRotation::Rotation0; |
| 577 | switch (angle) { |
| 578 | case 0: { |
| 579 | videoRotation = signaling::MediaStateMessage::VideoRotation::Rotation0; |
| 580 | break; |
| 581 | } |
| 582 | case 90: { |
| 583 | videoRotation = signaling::MediaStateMessage::VideoRotation::Rotation90; |
| 584 | break; |
| 585 | } |
| 586 | case 180: { |
| 587 | videoRotation = signaling::MediaStateMessage::VideoRotation::Rotation180; |
| 588 | break; |
| 589 | } |
| 590 | case 270: { |
| 591 | videoRotation = signaling::MediaStateMessage::VideoRotation::Rotation270; |
| 592 | break; |
| 593 | } |
| 594 | default: { |
| 595 | videoRotation = signaling::MediaStateMessage::VideoRotation::Rotation0; |
| 596 | break; |
| 597 | } |
| 598 | } |
| 599 | if (strong->_videoRotation != videoRotation) { |
| 600 | strong->_videoRotation = videoRotation; |
| 601 | strong->_rotationUpdated(); |
| 602 | } |
| 603 | }); |
| 604 | }); |
| 605 |
| 606 | switch (videoCaptureImpl->getRotation()) { |
| 607 | case 0: { |
| 608 | _videoRotation = signaling::MediaStateMessage::VideoRotation::Rotation0; |
| 609 | break; |
| 610 | } |
| 611 | case 90: { |
| 612 | _videoRotation = signaling::MediaStateMessage::VideoRotation::Rotation90; |
| 613 | break; |
| 614 | } |
| 615 | case 180: { |
| 616 | _videoRotation = signaling::MediaStateMessage::VideoRotation::Rotation180; |
| 617 | break; |
| 618 | } |
| 619 | case 270: { |
| 620 | _videoRotation = signaling::MediaStateMessage::VideoRotation::Rotation270; |
| 621 | break; |
| 622 | } |
| 623 | default: { |
| 624 | _videoRotation = signaling::MediaStateMessage::VideoRotation::Rotation0; |
| 625 | break; |
| 626 | } |
| 627 | } |
| 628 | } else { |
| 629 | _videoRotation = signaling::MediaStateMessage::VideoRotation::Rotation0; |
| 630 | _outgoingVideoChannel->Enable(false); |
| 631 |
| 632 | _threads->getWorkerThread()->BlockingCall([&]() { |
| 633 | _outgoingVideoChannel->media_channel()->SetVideoSend(_mainSsrc, NULL, nullptr); |
| 634 | }); |
| 635 | } |
| 636 | } |
| 637 |
| 638 | uint32_t ssrc() const { |
| 639 | return _mainSsrc; |
| 640 | } |
| 641 |
| 642 | void setMaxBitrate(int bitrate) { |
| 643 | _threads->getWorkerThread()->BlockingCall([&]() { |
| 644 | webrtc::RtpParameters initialParameters = _outgoingVideoChannel->media_channel()->GetRtpSendParameters(_mainSsrc); |
| 645 | webrtc::RtpParameters updatedParameters = initialParameters; |
| 646 |
| 647 | if (updatedParameters.encodings.empty()) { |
| 648 | updatedParameters.encodings.push_back(webrtc::RtpEncodingParameters()); |
| 649 | } |
| 650 |
| 651 | updatedParameters.encodings[0].max_bitrate_bps = bitrate; |
| 652 |
| 653 | if (initialParameters != updatedParameters) { |
| 654 | _outgoingVideoChannel->media_channel()->SetRtpSendParameters(_mainSsrc, updatedParameters); |
| 655 | } |
| 656 | }); |
| 657 | } |
| 658 |
| 659 | public: |
| 660 | std::shared_ptr<VideoCaptureInterface> videoCapture() { |
| 661 | return _videoCapture; |
| 662 | } |
| 663 |
| 664 | signaling::MediaStateMessage::VideoRotation getRotation() { |
| 665 | return _videoRotation; |
| 666 | } |
| 667 |
| 668 | private: |
| 669 | void OnSentPacket_w(const rtc::SentPacket& sent_packet) { |
| 670 | _call->OnSentPacket(sent_packet); |
| 671 | } |
| 672 |
| 673 | private: |
| 674 | std::shared_ptr<Threads> _threads; |
| 675 |
| 676 | uint32_t _mainSsrc = 0; |
| 677 | webrtc::Call *_call = nullptr; |
| 678 | ChannelManager *_channelManager = nullptr; |
| 679 | cricket::VideoChannel *_outgoingVideoChannel = nullptr; |
| 680 |
| 681 | std::function<void()> _rotationUpdated; |
| 682 |
| 683 | std::shared_ptr<VideoCaptureInterface> _videoCapture; |
| 684 | signaling::MediaStateMessage::VideoRotation _videoRotation = signaling::MediaStateMessage::VideoRotation::Rotation0; |
| 685 | }; |
| 686 |
| 687 | class VideoSinkImpl : public rtc::VideoSinkInterface<webrtc::VideoFrame> { |
| 688 | public: |
| 689 | VideoSinkImpl() { |
| 690 | } |
| 691 |
| 692 | virtual ~VideoSinkImpl() { |
| 693 | } |
| 694 |
| 695 | virtual void OnFrame(const webrtc::VideoFrame& frame) override { |
| 696 | //_lastFrame = frame; |
| 697 | for (int i = (int)(_sinks.size()) - 1; i >= 0; i--) { |
| 698 | auto strong = _sinks[i].lock(); |
| 699 | if (!strong) { |
| 700 | _sinks.erase(_sinks.begin() + i); |
| 701 | } else { |
| 702 | strong->OnFrame(frame); |
| 703 | } |
| 704 | } |
| 705 | } |
| 706 |
| 707 | virtual void OnDiscardedFrame() override { |
| 708 | for (int i = (int)(_sinks.size()) - 1; i >= 0; i--) { |
| 709 | auto strong = _sinks[i].lock(); |
| 710 | if (!strong) { |
| 711 | _sinks.erase(_sinks.begin() + i); |
| 712 | } else { |
| 713 | strong->OnDiscardedFrame(); |
| 714 | } |
| 715 | } |
| 716 | } |
| 717 |
| 718 | void addSink(std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> impl) { |
| 719 | _sinks.push_back(impl); |
| 720 | if (_lastFrame) { |
| 721 | auto strong = impl.lock(); |
| 722 | if (strong) { |
| 723 | strong->OnFrame(_lastFrame.value()); |
| 724 | } |
| 725 | } |
| 726 | } |
| 727 |
| 728 | private: |
| 729 | std::vector<std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>>> _sinks; |
| 730 | absl::optional<webrtc::VideoFrame> _lastFrame; |
| 731 | }; |
| 732 |
| 733 | class IncomingV2VideoChannel : public sigslot::has_slots<> { |
| 734 | public: |
| 735 | IncomingV2VideoChannel( |
| 736 | ChannelManager *channelManager, |
| 737 | webrtc::Call *call, |
| 738 | webrtc::RtpTransport *rtpTransport, |
| 739 | rtc::UniqueRandomIdGenerator *randomIdGenerator, |
| 740 | signaling::MediaContent const &mediaContent, |
| 741 | std::shared_ptr<Threads> threads) : |
| 742 | _threads(threads), |
| 743 | _channelManager(channelManager), |
| 744 | _call(call) { |
| 745 | _videoSink.reset(new VideoSinkImpl()); |
| 746 |
| 747 | _videoBitrateAllocatorFactory = webrtc::CreateBuiltinVideoBitrateAllocatorFactory(); |
| 748 |
| 749 | const auto contentId = std::to_string(mediaContent.ssrc); |
| 750 |
| 751 | _videoChannel = _channelManager->CreateVideoChannel(call, cricket::MediaConfig(), contentId, false, NativeNetworkingImpl::getDefaulCryptoOptions(), cricket::VideoOptions(), _videoBitrateAllocatorFactory.get()); |
| 752 | _threads->getNetworkThread()->BlockingCall([&]() { |
| 753 | _videoChannel->SetRtpTransport(rtpTransport); |
| 754 | }); |
| 755 |
| 756 | std::vector<cricket::VideoCodec> codecs; |
| 757 | for (const auto &payloadType : mediaContent.payloadTypes) { |
| 758 | cricket::VideoCodec codec(payloadType.id, payloadType.name); |
| 759 | for (const auto ¶meter : payloadType.parameters) { |
| 760 | codec.SetParam(parameter.first, parameter.second); |
| 761 | } |
| 762 | for (const auto &feedbackType : payloadType.feedbackTypes) { |
| 763 | codec.AddFeedbackParam(cricket::FeedbackParam(feedbackType.type, feedbackType.subtype)); |
| 764 | } |
| 765 | codecs.push_back(std::move(codec)); |
| 766 | } |
| 767 |
| 768 | auto outgoingVideoDescription = std::make_unique<cricket::VideoContentDescription>(); |
| 769 | for (const auto &rtpExtension : mediaContent.rtpExtensions) { |
| 770 | outgoingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(rtpExtension.uri, rtpExtension.id)); |
| 771 | } |
| 772 | outgoingVideoDescription->set_rtcp_mux(true); |
| 773 | outgoingVideoDescription->set_rtcp_reduced_size(true); |
| 774 | outgoingVideoDescription->set_direction(webrtc::RtpTransceiverDirection::kRecvOnly); |
| 775 | outgoingVideoDescription->set_codecs(codecs); |
| 776 | outgoingVideoDescription->set_bandwidth(-1); |
| 777 |
| 778 | cricket::StreamParams videoRecvStreamParams; |
| 779 |
| 780 | _mainVideoSsrc = mediaContent.ssrc; |
| 781 |
| 782 | std::vector<uint32_t> allSsrcs; |
| 783 | for (const auto &group : mediaContent.ssrcGroups) { |
| 784 | for (auto ssrc : group.ssrcs) { |
| 785 | if (std::find(allSsrcs.begin(), allSsrcs.end(), ssrc) == allSsrcs.end()) { |
| 786 | allSsrcs.push_back(ssrc); |
| 787 | } |
| 788 | } |
| 789 |
| 790 | cricket::SsrcGroup parsedGroup(group.semantics, group.ssrcs); |
| 791 | videoRecvStreamParams.ssrc_groups.push_back(parsedGroup); |
| 792 | } |
| 793 | videoRecvStreamParams.ssrcs = allSsrcs; |
| 794 |
| 795 | videoRecvStreamParams.cname = "cname"; |
| 796 | videoRecvStreamParams.set_stream_ids({ contentId }); |
| 797 |
| 798 | auto incomingVideoDescription = std::make_unique<cricket::VideoContentDescription>(); |
| 799 | for (const auto &rtpExtension : mediaContent.rtpExtensions) { |
| 800 | incomingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(rtpExtension.uri, rtpExtension.id)); |
| 801 | } |
| 802 | incomingVideoDescription->set_rtcp_mux(true); |
| 803 | incomingVideoDescription->set_rtcp_reduced_size(true); |
| 804 | incomingVideoDescription->set_direction(webrtc::RtpTransceiverDirection::kSendOnly); |
| 805 | incomingVideoDescription->set_codecs(codecs); |
| 806 | incomingVideoDescription->set_bandwidth(-1); |
| 807 |
| 808 | incomingVideoDescription->AddStream(videoRecvStreamParams); |
| 809 |
| 810 | threads->getWorkerThread()->BlockingCall([&]() { |
| 811 | _videoChannel->SetPayloadTypeDemuxingEnabled(false); |
| 812 | std::string errorDesc; |
| 813 | _videoChannel->SetLocalContent(outgoingVideoDescription.get(), webrtc::SdpType::kOffer, errorDesc); |
| 814 | _videoChannel->SetRemoteContent(incomingVideoDescription.get(), webrtc::SdpType::kAnswer, errorDesc); |
| 815 |
| 816 | _videoChannel->media_channel()->SetSink(_mainVideoSsrc, _videoSink.get()); |
| 817 | }); |
| 818 |
| 819 | _videoChannel->Enable(true); |
| 820 | } |
| 821 |
| 822 | ~IncomingV2VideoChannel() { |
| 823 | _videoChannel->Enable(false); |
| 824 | _threads->getNetworkThread()->BlockingCall([&]() { |
| 825 | _videoChannel->SetRtpTransport(nullptr); |
| 826 | }); |
| 827 | _channelManager->DestroyChannel(_videoChannel); |
| 828 | _videoChannel = nullptr; |
| 829 | } |
| 830 |
| 831 | void addSink(std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> impl) { |
| 832 | _videoSink->addSink(impl); |
| 833 | } |
| 834 |
| 835 | uint32_t ssrc() const { |
| 836 | return _mainVideoSsrc; |
| 837 | } |
| 838 |
| 839 | private: |
| 840 | void OnSentPacket_w(const rtc::SentPacket& sent_packet) { |
| 841 | _call->OnSentPacket(sent_packet); |
| 842 | } |
| 843 |
| 844 | private: |
| 845 | std::shared_ptr<Threads> _threads; |
| 846 | uint32_t _mainVideoSsrc = 0; |
| 847 | std::unique_ptr<VideoSinkImpl> _videoSink; |
| 848 | std::unique_ptr<webrtc::VideoBitrateAllocatorFactory> _videoBitrateAllocatorFactory; |
| 849 | // Memory is managed by _channelManager |
| 850 | cricket::VideoChannel *_videoChannel; |
| 851 | // Memory is managed externally |
| 852 | ChannelManager *_channelManager = nullptr; |
| 853 | webrtc::Call *_call = nullptr; |
| 854 | }; |
| 855 |
| 856 | template<typename T> |
| 857 | struct StateLogRecord { |
| 858 | int64_t timestamp = 0; |
| 859 | T record; |
| 860 |
| 861 | explicit StateLogRecord(int32_t timestamp_, T &&record_) : |
| 862 | timestamp(timestamp_), |
| 863 | record(std::move(record_)) { |
| 864 | } |
| 865 | }; |
| 866 |
| 867 | struct NetworkStateLogRecord { |
| 868 | bool isConnected = false; |
| 869 | bool isFailed = false; |
| 870 | absl::optional<InstanceNetworking::RouteDescription> route; |
| 871 | absl::optional<InstanceNetworking::ConnectionDescription> connection; |
| 872 |
| 873 | bool operator==(NetworkStateLogRecord const &rhs) const { |
| 874 | if (isConnected != rhs.isConnected) { |
| 875 | return false; |
| 876 | } |
| 877 | if (isFailed != rhs.isFailed) { |
| 878 | return false; |
| 879 | } |
| 880 | if (route != rhs.route) { |
| 881 | return false; |
| 882 | } |
| 883 | if (connection != rhs.connection) { |
| 884 | return false; |
| 885 | } |
| 886 |
| 887 | return true; |
| 888 | } |
| 889 | }; |
| 890 |
| 891 | struct NetworkBitrateLogRecord { |
| 892 | int32_t bitrate = 0; |
| 893 | }; |
| 894 |
| 895 | } // namespace |
| 896 |
| 897 | class InstanceV2ImplInternal : public std::enable_shared_from_this<InstanceV2ImplInternal> { |
| 898 | public: |
| 899 | InstanceV2ImplInternal(Descriptor &&descriptor, std::shared_ptr<Threads> threads) : |
| 900 | _signalingProtocolVersion(signalingProtocolVersion(descriptor.version)), |
| 901 | _threads(threads), |
| 902 | _rtcServers(descriptor.rtcServers), |
| 903 | _proxy(std::move(descriptor.proxy)), |
| 904 | _directConnectionChannel(descriptor.directConnectionChannel), |
| 905 | _enableP2P(descriptor.config.enableP2P), |
| 906 | _encryptionKey(std::move(descriptor.encryptionKey)), |
| 907 | _stateUpdated(descriptor.stateUpdated), |
| 908 | _signalBarsUpdated(descriptor.signalBarsUpdated), |
| 909 | _audioLevelUpdated(descriptor.audioLevelsUpdated), |
| 910 | _remoteBatteryLevelIsLowUpdated(descriptor.remoteBatteryLevelIsLowUpdated), |
| 911 | _remoteMediaStateUpdated(descriptor.remoteMediaStateUpdated), |
| 912 | _remotePrefferedAspectRatioUpdated(descriptor.remotePrefferedAspectRatioUpdated), |
| 913 | _signalingDataEmitted(descriptor.signalingDataEmitted), |
| 914 | _createAudioDeviceModule(descriptor.createAudioDeviceModule), |
| 915 | _devicesConfig(descriptor.mediaDevicesConfig), |
| 916 | _statsLogPath(descriptor.config.statsLogPath), |
| 917 | _eventLog(std::make_unique<webrtc::RtcEventLogNull>()), |
| 918 | _taskQueueFactory(webrtc::CreateDefaultTaskQueueFactory()), |
| 919 | _initialInputDeviceId(std::move(descriptor.initialInputDeviceId)), |
| 920 | _initialOutputDeviceId(std::move(descriptor.initialOutputDeviceId)), |
| 921 | _videoCapture(descriptor.videoCapture), |
| 922 | _platformContext(descriptor.platformContext) { |
| 923 | webrtc::field_trial::InitFieldTrialsFromString( |
| 924 | "WebRTC-DataChannel-Dcsctp/Enabled/" |
| 925 | "WebRTC-Audio-MinimizeResamplingOnMobile/Enabled/" |
| 926 | "WebRTC-Audio-iOS-Holding/Enabled/" |
| 927 | "WebRTC-IceFieldTrials/skip_relay_to_non_relay_connections:true/" |
| 928 | ); |
| 929 | } |
| 930 |
| 931 | ~InstanceV2ImplInternal() { |
| 932 | _incomingAudioChannel.reset(); |
| 933 | _incomingVideoChannel.reset(); |
| 934 | _incomingScreencastChannel.reset(); |
| 935 | _outgoingAudioChannel.reset(); |
| 936 | _outgoingVideoChannel.reset(); |
| 937 | _outgoingScreencastChannel.reset(); |
| 938 | _currentSink.reset(); |
| 939 |
| 940 | _channelManager.reset(); |
| 941 |
| 942 | _threads->getWorkerThread()->BlockingCall([&]() { |
| 943 | _call.reset(); |
| 944 | _audioDeviceModule = nullptr; |
| 945 | }); |
| 946 |
| 947 | _contentNegotiationContext.reset(); |
| 948 |
| 949 | _networking->perform([](InstanceNetworking *networking) { |
| 950 | networking->stop(); |
| 951 | }); |
| 952 |
| 953 | _threads->getNetworkThread()->BlockingCall([]() { |
| 954 | }); |
| 955 | } |
| 956 |
| 957 | void start() { |
| 958 | _startTimestamp = rtc::TimeMillis(); |
| 959 |
| 960 | const auto weak = std::weak_ptr<InstanceV2ImplInternal>(shared_from_this()); |
| 961 |
| 962 | if (_signalingProtocolVersion == SignalingProtocolVersion::V3) { |
| 963 | _signalingConnection = std::make_unique<SignalingSctpConnection>( |
| 964 | _threads, |
| 965 | [threads = _threads, weak](const std::vector<uint8_t> &data) { |
| 966 | threads->getMediaThread()->PostTask([weak, data] { |
| 967 | const auto strong = weak.lock(); |
| 968 | if (!strong) { |
| 969 | return; |
| 970 | } |
| 971 |
| 972 | strong->onSignalingData(data); |
| 973 | }); |
| 974 | }, |
| 975 | [signalingDataEmitted = _signalingDataEmitted](const std::vector<uint8_t> &data) { |
| 976 | signalingDataEmitted(data); |
| 977 | } |
| 978 | ); |
| 979 | } |
| 980 | if (!_signalingConnection) { |
| 981 | _signalingConnection = std::make_unique<ExternalSignalingConnection>( |
| 982 | [threads = _threads, weak](const std::vector<uint8_t> &data) { |
| 983 | threads->getMediaThread()->PostTask([weak, data] { |
| 984 | const auto strong = weak.lock(); |
| 985 | if (!strong) { |
| 986 | return; |
| 987 | } |
| 988 |
| 989 | strong->onSignalingData(data); |
| 990 | }); |
| 991 | }, |
| 992 | [signalingDataEmitted = _signalingDataEmitted](const std::vector<uint8_t> &data) { |
| 993 | signalingDataEmitted(data); |
| 994 | } |
| 995 | ); |
| 996 | } |
| 997 |
| 998 | _signalingConnection->start(); |
| 999 |
| 1000 | absl::optional<Proxy> proxy; |
| 1001 | if (_proxy) { |
| 1002 | proxy = *(_proxy.get()); |
| 1003 | } |
| 1004 |
| 1005 | _networking.reset(new ThreadLocalObject<NativeNetworkingImpl>(_threads->getNetworkThread(), [weak, threads = _threads, encryptionKey = _encryptionKey, isOutgoing = _encryptionKey.isOutgoing, rtcServers = _rtcServers, proxy, enableP2P = _enableP2P, directConnectionChannel = _directConnectionChannel]() { |
| 1006 | if (directConnectionChannel) { |
| 1007 | return new NativeNetworkingImpl(InstanceNetworking::Configuration { |
| 1008 | .encryptionKey = encryptionKey, |
| 1009 | .isOutgoing = isOutgoing, |
| 1010 | .enableStunMarking = false, |
| 1011 | .enableTCP = false, |
| 1012 | .enableP2P = enableP2P, |
| 1013 | .rtcServers = rtcServers, |
| 1014 | .proxy = proxy, |
| 1015 | .stateUpdated = [threads, weak](const InstanceNetworking::State &state) { |
| 1016 | threads->getMediaThread()->PostTask([=] { |
| 1017 | const auto strong = weak.lock(); |
| 1018 | if (!strong) { |
| 1019 | return; |
| 1020 | } |
| 1021 | strong->onNetworkStateUpdated(state); |
| 1022 | }); |
| 1023 | }, |
| 1024 | .candidateGathered = [threads, weak](const cricket::Candidate &candidate) { |
| 1025 | threads->getMediaThread()->PostTask([=] { |
| 1026 | const auto strong = weak.lock(); |
| 1027 | if (!strong) { |
| 1028 | return; |
| 1029 | } |
| 1030 |
| 1031 | strong->sendCandidate(candidate); |
| 1032 | }); |
| 1033 | }, |
| 1034 | .transportMessageReceived = [threads, weak](rtc::CopyOnWriteBuffer const &packet, bool isMissing) { |
| 1035 | threads->getMediaThread()->PostTask([=] { |
| 1036 | const auto strong = weak.lock(); |
| 1037 | if (!strong) { |
| 1038 | return; |
| 1039 | } |
| 1040 | }); |
| 1041 | }, |
| 1042 | .rtcpPacketReceived = [threads, weak](rtc::CopyOnWriteBuffer const &packet, int64_t timestamp) { |
| 1043 | const auto strong = weak.lock(); |
| 1044 | if (!strong) { |
| 1045 | return; |
| 1046 | } |
| 1047 | strong->_call->Receiver()->DeliverPacket(webrtc::MediaType::ANY, packet, timestamp); |
| 1048 | }, |
| 1049 | .dataChannelStateUpdated = [threads, weak](bool isDataChannelOpen) { |
| 1050 | threads->getMediaThread()->PostTask([=] { |
| 1051 | const auto strong = weak.lock(); |
| 1052 | if (!strong) { |
| 1053 | return; |
| 1054 | } |
| 1055 | strong->onDataChannelStateUpdated(isDataChannelOpen); |
| 1056 | }); |
| 1057 | }, |
| 1058 | .dataChannelMessageReceived = [threads, weak](std::string const &message) { |
| 1059 | threads->getMediaThread()->PostTask([=] { |
| 1060 | const auto strong = weak.lock(); |
| 1061 | if (!strong) { |
| 1062 | return; |
| 1063 | } |
| 1064 | strong->onDataChannelMessage(message); |
| 1065 | }); |
| 1066 | }, |
| 1067 | .threads = threads, |
| 1068 | .directConnectionChannel = directConnectionChannel, |
| 1069 | }); |
| 1070 | } else { |
| 1071 | return new NativeNetworkingImpl(InstanceNetworking::Configuration{ |
| 1072 | .encryptionKey = encryptionKey, |
| 1073 | .isOutgoing = isOutgoing, |
| 1074 | .enableStunMarking = false, |
| 1075 | .enableTCP = false, |
| 1076 | .enableP2P = enableP2P, |
| 1077 | .rtcServers = rtcServers, |
| 1078 | .proxy = proxy, |
| 1079 | .stateUpdated = [threads, weak](const InstanceNetworking::State &state) { |
| 1080 | threads->getMediaThread()->PostTask([=] { |
| 1081 | const auto strong = weak.lock(); |
| 1082 | if (!strong) { |
| 1083 | return; |
| 1084 | } |
| 1085 | strong->onNetworkStateUpdated(state); |
| 1086 | }); |
| 1087 | }, |
| 1088 | .candidateGathered = [threads, weak](const cricket::Candidate &candidate) { |
| 1089 | threads->getMediaThread()->PostTask([=] { |
| 1090 | const auto strong = weak.lock(); |
| 1091 | if (!strong) { |
| 1092 | return; |
| 1093 | } |
| 1094 |
| 1095 | strong->sendCandidate(candidate); |
| 1096 | }); |
| 1097 | }, |
| 1098 | .transportMessageReceived = [threads, weak](rtc::CopyOnWriteBuffer const &packet, bool isMissing) { |
| 1099 | threads->getMediaThread()->PostTask([=] { |
| 1100 | const auto strong = weak.lock(); |
| 1101 | if (!strong) { |
| 1102 | return; |
| 1103 | } |
| 1104 | }); |
| 1105 | }, |
| 1106 | .rtcpPacketReceived = [threads, weak](rtc::CopyOnWriteBuffer const &packet, int64_t timestamp) { |
| 1107 | const auto strong = weak.lock(); |
| 1108 | if (!strong) { |
| 1109 | return; |
| 1110 | } |
| 1111 | strong->_call->Receiver()->DeliverPacket(webrtc::MediaType::ANY, packet, timestamp); |
| 1112 | }, |
| 1113 | .dataChannelStateUpdated = [threads, weak](bool isDataChannelOpen) { |
| 1114 | threads->getMediaThread()->PostTask([=] { |
| 1115 | const auto strong = weak.lock(); |
| 1116 | if (!strong) { |
| 1117 | return; |
| 1118 | } |
| 1119 | strong->onDataChannelStateUpdated(isDataChannelOpen); |
| 1120 | }); |
| 1121 | }, |
| 1122 | .dataChannelMessageReceived = [threads, weak](std::string const &message) { |
| 1123 | threads->getMediaThread()->PostTask([=] { |
| 1124 | const auto strong = weak.lock(); |
| 1125 | if (!strong) { |
| 1126 | return; |
| 1127 | } |
| 1128 | strong->onDataChannelMessage(message); |
| 1129 | }); |
| 1130 | }, |
| 1131 | .threads = threads, |
| 1132 | .directConnectionChannel = directConnectionChannel, |
| 1133 | }); |
| 1134 | } |
| 1135 | })); |
| 1136 |
| 1137 | PlatformInterface::SharedInstance()->configurePlatformAudio(); |
| 1138 |
| 1139 |
| 1140 | _threads->getWorkerThread()->BlockingCall([&]() { |
| 1141 | _audioDeviceModule = createAudioDeviceModule(); |
| 1142 | }); |
| 1143 |
| 1144 | cricket::MediaEngineDependencies mediaDeps; |
| 1145 | mediaDeps.task_queue_factory = _taskQueueFactory.get(); |
| 1146 | mediaDeps.audio_encoder_factory = webrtc::CreateAudioEncoderFactory<webrtc::AudioEncoderOpus, webrtc::AudioEncoderL16>(); |
| 1147 | mediaDeps.audio_decoder_factory = webrtc::CreateAudioDecoderFactory<webrtc::AudioDecoderOpus, webrtc::AudioDecoderL16>(); |
| 1148 |
| 1149 | mediaDeps.video_encoder_factory = PlatformInterface::SharedInstance()->makeVideoEncoderFactory(_platformContext, true); |
| 1150 | mediaDeps.video_decoder_factory = PlatformInterface::SharedInstance()->makeVideoDecoderFactory(_platformContext); |
| 1151 |
| 1152 | mediaDeps.adm = _audioDeviceModule; |
| 1153 |
| 1154 | webrtc::AudioProcessingBuilder builder; |
| 1155 | mediaDeps.audio_processing = builder.Create(); |
| 1156 |
| 1157 | _availableVideoFormats = mediaDeps.video_encoder_factory->GetSupportedFormats(); |
| 1158 |
| 1159 | std::unique_ptr<cricket::MediaEngineInterface> mediaEngine = cricket::CreateMediaEngine(std::move(mediaDeps)); |
| 1160 |
| 1161 | _channelManager = ChannelManager::Create( |
| 1162 | std::move(mediaEngine), |
| 1163 | _threads->getWorkerThread(), |
| 1164 | _threads->getNetworkThread() |
| 1165 | ); |
| 1166 |
| 1167 | webrtc::Call::Config callConfig(_eventLog.get(), _threads->getNetworkThread()); |
| 1168 | callConfig.task_queue_factory = _taskQueueFactory.get(); |
| 1169 | callConfig.trials = &fieldTrialsBasedConfig; |
| 1170 |
| 1171 | _threads->getNetworkThread()->BlockingCall([&]() { |
| 1172 | _rtpTransport = _networking->getSyncAssumingSameThread()->getRtpTransport(); |
| 1173 | }); |
| 1174 |
| 1175 | _threads->getWorkerThread()->BlockingCall([&]() { |
| 1176 | callConfig.audio_state = _channelManager->media_engine()->voice().GetAudioState(); |
| 1177 | _call.reset(webrtc::Call::Create(callConfig)); |
| 1178 |
| 1179 | // SetAudioInputDeviceById(_audioDeviceModule.get(), _devicesConfig.audioInputId); |
| 1180 | // SetAudioOutputDeviceById(_audioDeviceModule.get(), _devicesConfig.audioOutputId); |
| 1181 | }); |
| 1182 |
| 1183 | _uniqueRandomIdGenerator.reset(new rtc::UniqueRandomIdGenerator()); |
| 1184 |
| 1185 | _contentNegotiationContext = std::make_unique<ContentNegotiationContext>(fieldTrialsBasedConfig, _encryptionKey.isOutgoing, _uniqueRandomIdGenerator.get()); |
| 1186 | _contentNegotiationContext->copyCodecsFromChannelManager(_channelManager->media_engine(), false); |
| 1187 |
| 1188 | _outgoingAudioChannelId = _contentNegotiationContext->addOutgoingChannel(signaling::MediaContent::Type::Audio); |
| 1189 |
| 1190 | _videoBitrateAllocatorFactory = webrtc::CreateBuiltinVideoBitrateAllocatorFactory(); |
| 1191 |
| 1192 | _networking->perform([](InstanceNetworking *networking) { |
| 1193 | networking->start(); |
| 1194 | }); |
| 1195 |
| 1196 | if (_videoCapture) { |
| 1197 | setVideoCapture(_videoCapture); |
| 1198 | } |
| 1199 |
| 1200 | beginSignaling(); |
| 1201 |
| 1202 | adjustBitratePreferences(true); |
| 1203 |
| 1204 | beginQualityTimer(0); |
| 1205 | beginLogTimer(0); |
| 1206 |
| 1207 | InstanceNetworking::State initialNetworkState; |
| 1208 | initialNetworkState.isReadyToSendData = false; |
| 1209 | onNetworkStateUpdated(initialNetworkState); |
| 1210 | } |
| 1211 |
| 1212 | void beginQualityTimer(int delayMs) { |
| 1213 | const auto weak = std::weak_ptr<InstanceV2ImplInternal>(shared_from_this()); |
| 1214 | _threads->getMediaThread()->PostDelayedTask([weak]() { |
| 1215 | auto strong = weak.lock(); |
| 1216 | if (!strong) { |
| 1217 | return; |
| 1218 | } |
| 1219 |
| 1220 |
| 1221 |
| 1222 | strong->beginQualityTimer(500); |
| 1223 | }, webrtc::TimeDelta::Millis(delayMs)); |
| 1224 | } |
| 1225 |
| 1226 | void beginLogTimer(int delayMs) { |
| 1227 | const auto weak = std::weak_ptr<InstanceV2ImplInternal>(shared_from_this()); |
| 1228 | _threads->getMediaThread()->PostDelayedTask([weak]() { |
| 1229 | auto strong = weak.lock(); |
| 1230 | if (!strong) { |
| 1231 | return; |
| 1232 | } |
| 1233 |
| 1234 | strong->writeStateLogRecords(); |
| 1235 |
| 1236 | strong->beginLogTimer(1000); |
| 1237 | }, webrtc::TimeDelta::Millis(delayMs)); |
| 1238 | } |
| 1239 |
| 1240 | void writeStateLogRecords() { |
| 1241 | const auto weak = std::weak_ptr<InstanceV2ImplInternal>(shared_from_this()); |
| 1242 | _threads->getWorkerThread()->PostTask([weak]() { |
| 1243 | auto strong = weak.lock(); |
| 1244 | if (!strong) { |
| 1245 | return; |
| 1246 | } |
| 1247 |
| 1248 | auto stats = strong->_call->GetStats(); |
| 1249 | float sendBitrateKbps = ((float)stats.send_bandwidth_bps / 1000.0f); |
| 1250 |
| 1251 | strong->_threads->getMediaThread()->PostTask([weak, sendBitrateKbps]() { |
| 1252 | auto strong = weak.lock(); |
| 1253 | if (!strong) { |
| 1254 | return; |
| 1255 | } |
| 1256 |
| 1257 | float bitrateNorm = 16.0f; |
| 1258 | if (strong->_outgoingVideoChannel) { |
| 1259 | bitrateNorm = 600.0f; |
| 1260 | } |
| 1261 |
| 1262 | float signalBarsNorm = 4.0f; |
| 1263 | float adjustedQuality = sendBitrateKbps / bitrateNorm; |
| 1264 | adjustedQuality = fmaxf(0.0f, adjustedQuality); |
| 1265 | adjustedQuality = fminf(1.0f, adjustedQuality); |
| 1266 | if (strong->_signalBarsUpdated) { |
| 1267 | strong->_signalBarsUpdated((int)(adjustedQuality * signalBarsNorm)); |
| 1268 | } |
| 1269 |
| 1270 | NetworkBitrateLogRecord networkBitrateLogRecord; |
| 1271 | networkBitrateLogRecord.bitrate = (int32_t)sendBitrateKbps; |
| 1272 |
| 1273 | strong->_networkBitrateLogRecords.emplace_back(rtc::TimeMillis(), std::move(networkBitrateLogRecord)); |
| 1274 | }); |
| 1275 | }); |
| 1276 | } |
| 1277 |
| 1278 | void sendSignalingMessage(signaling::Message const &message) { |
| 1279 | auto data = message.serialize(); |
| 1280 | sendRawSignalingMessage(data); |
| 1281 | } |
| 1282 |
| 1283 | void sendRawSignalingMessage(std::vector<uint8_t> const &data) { |
| 1284 | RTC_LOG(LS_INFO) << "sendSignalingMessage: " << std::string(data.begin(), data.end()); |
| 1285 |
| 1286 | if (_signalingConnection && _signalingEncryptedConnection) { |
| 1287 | switch (_signalingProtocolVersion) { |
| 1288 | case SignalingProtocolVersion::V1: |
| 1289 | case SignalingProtocolVersion::V3: { |
| 1290 | std::vector<uint8_t> packetData; |
| 1291 | if (signalingProtocolSupportsCompression(_signalingProtocolVersion)) { |
| 1292 | if (const auto compressedData = gzipData(data)) { |
| 1293 | packetData = std::move(compressedData.value()); |
| 1294 | } else { |
| 1295 | RTC_LOG(LS_ERROR) << "Could not gzip signaling message"; |
| 1296 | } |
| 1297 | } else { |
| 1298 | packetData = data; |
| 1299 | } |
| 1300 |
| 1301 | if (const auto message = _signalingEncryptedConnection->encryptRawPacket(rtc::CopyOnWriteBuffer(packetData.data(), packetData.size()))) { |
| 1302 | _signalingConnection->send(std::vector<uint8_t>(message.value().data(), message.value().data() + message.value().size())); |
| 1303 | } else { |
| 1304 | RTC_LOG(LS_ERROR) << "Could not encrypt signaling message"; |
| 1305 | } |
| 1306 | break; |
| 1307 | } |
| 1308 | case SignalingProtocolVersion::V2: { |
| 1309 | rtc::CopyOnWriteBuffer message; |
| 1310 | message.AppendData(data.data(), data.size()); |
| 1311 |
| 1312 | commitSendSignalingMessage(_signalingEncryptedConnection->prepareForSendingRawMessage(message, true)); |
| 1313 |
| 1314 | break; |
| 1315 | } |
| 1316 | default: { |
| 1317 | RTC_DCHECK_NOTREACHED(); |
| 1318 |
| 1319 | break; |
| 1320 | } |
| 1321 | } |
| 1322 | } else { |
| 1323 | RTC_LOG(LS_ERROR) << "sendSignalingMessage encryption not available"; |
| 1324 | } |
| 1325 | } |
| 1326 |
| 1327 | void commitSendSignalingMessage(absl::optional<EncryptedConnection::EncryptedPacket> packet) { |
| 1328 | if (!packet) { |
| 1329 | return; |
| 1330 | } |
| 1331 |
| 1332 | if (_signalingConnection) { |
| 1333 | _signalingConnection->send(packet.value().bytes); |
| 1334 | } |
| 1335 | } |
| 1336 |
| 1337 | void beginSignaling() { |
| 1338 | const auto weak = std::weak_ptr<InstanceV2ImplInternal>(shared_from_this()); |
| 1339 |
| 1340 | _signalingEncryptedConnection = std::make_unique<EncryptedConnection>( |
| 1341 | EncryptedConnection::Type::Signaling, |
| 1342 | _encryptionKey, |
| 1343 | [weak, threads = _threads](int delayMs, int cause) { |
| 1344 | if (delayMs == 0) { |
| 1345 | threads->getMediaThread()->PostTask([weak, cause]() { |
| 1346 | const auto strong = weak.lock(); |
| 1347 | if (!strong) { |
| 1348 | return; |
| 1349 | } |
| 1350 |
| 1351 | strong->sendPendingSignalingServiceData(cause); |
| 1352 | }); |
| 1353 | } else { |
| 1354 | threads->getMediaThread()->PostDelayedTask([weak, cause]() { |
| 1355 | const auto strong = weak.lock(); |
| 1356 | if (!strong) { |
| 1357 | return; |
| 1358 | } |
| 1359 |
| 1360 | strong->sendPendingSignalingServiceData(cause); |
| 1361 | }, webrtc::TimeDelta::Millis(delayMs)); |
| 1362 | } |
| 1363 | } |
| 1364 | ); |
| 1365 |
| 1366 | if (_encryptionKey.isOutgoing) { |
| 1367 | sendInitialSetup(); |
| 1368 | } |
| 1369 | } |
| 1370 |
| 1371 | void sendPendingSignalingServiceData(int cause) { |
| 1372 | commitSendSignalingMessage(_signalingEncryptedConnection->prepareForSendingService(cause)); |
| 1373 | } |
| 1374 |
| 1375 | void createNegotiatedChannels() { |
| 1376 | const auto coordinatedState = _contentNegotiationContext->coordinatedState(); |
| 1377 | if (!coordinatedState) { |
| 1378 | return; |
| 1379 | } |
| 1380 |
| 1381 | if (_outgoingAudioChannelId) { |
| 1382 | const auto audioSsrc = _contentNegotiationContext->outgoingChannelSsrc(_outgoingAudioChannelId.value()); |
| 1383 | if (audioSsrc) { |
| 1384 | if (_outgoingAudioChannel && _outgoingAudioChannel->ssrc() != audioSsrc.value()) { |
| 1385 | _outgoingAudioChannel.reset(); |
| 1386 | } |
| 1387 |
| 1388 | absl::optional<signaling::MediaContent> outgoingAudioContent; |
| 1389 | for (const auto &content : coordinatedState->outgoingContents) { |
| 1390 | if (content.type == signaling::MediaContent::Type::Audio && content.ssrc == audioSsrc.value()) { |
| 1391 | outgoingAudioContent = content; |
| 1392 | break; |
| 1393 | } |
| 1394 | } |
| 1395 |
| 1396 | if (outgoingAudioContent) { |
| 1397 | if (!_outgoingAudioChannel) { |
| 1398 | _outgoingAudioChannel.reset(new OutgoingAudioChannel( |
| 1399 | _call.get(), |
| 1400 | _channelManager.get(), |
| 1401 | _uniqueRandomIdGenerator.get(), |
| 1402 | &_audioSource, |
| 1403 | _rtpTransport, |
| 1404 | outgoingAudioContent.value(), |
| 1405 | _threads |
| 1406 | )); |
| 1407 | _outgoingAudioChannel->setIsMuted(_isMicrophoneMuted); |
| 1408 | } |
| 1409 | } |
| 1410 | } |
| 1411 | } |
| 1412 |
| 1413 | if (_outgoingVideoChannelId) { |
| 1414 | const auto videoSsrc = _contentNegotiationContext->outgoingChannelSsrc(_outgoingVideoChannelId.value()); |
| 1415 | if (videoSsrc) { |
| 1416 | if (_outgoingVideoChannel && _outgoingVideoChannel->ssrc() != videoSsrc.value()) { |
| 1417 | _outgoingVideoChannel.reset(); |
| 1418 | } |
| 1419 |
| 1420 | absl::optional<signaling::MediaContent> outgoingVideoContent; |
| 1421 | for (const auto &content : coordinatedState->outgoingContents) { |
| 1422 | if (content.type == signaling::MediaContent::Type::Video && content.ssrc == videoSsrc.value()) { |
| 1423 | outgoingVideoContent = content; |
| 1424 | break; |
| 1425 | } |
| 1426 | } |
| 1427 |
| 1428 | if (outgoingVideoContent) { |
| 1429 | if (!_outgoingVideoChannel) { |
| 1430 | const auto weak = std::weak_ptr<InstanceV2ImplInternal>(shared_from_this()); |
| 1431 |
| 1432 | _outgoingVideoChannel.reset(new OutgoingVideoChannel( |
| 1433 | _threads, |
| 1434 | _channelManager.get(), |
| 1435 | _call.get(), |
| 1436 | _rtpTransport, |
| 1437 | _uniqueRandomIdGenerator.get(), |
| 1438 | _videoBitrateAllocatorFactory.get(), |
| 1439 | [threads = _threads, weak]() { |
| 1440 | threads->getMediaThread()->PostTask([=] { |
| 1441 | const auto strong = weak.lock(); |
| 1442 | if (!strong) { |
| 1443 | return; |
| 1444 | } |
| 1445 | strong->sendMediaState(); |
| 1446 | }); |
| 1447 | }, |
| 1448 | outgoingVideoContent.value(), |
| 1449 | false |
| 1450 | )); |
| 1451 |
| 1452 | if (_videoCapture) { |
| 1453 | _outgoingVideoChannel->setVideoCapture(_videoCapture); |
| 1454 | } |
| 1455 | } |
| 1456 | } |
| 1457 | } |
| 1458 | } |
| 1459 |
| 1460 | if (_outgoingScreencastChannelId) { |
| 1461 | const auto screencastSsrc = _contentNegotiationContext->outgoingChannelSsrc(_outgoingScreencastChannelId.value()); |
| 1462 | if (screencastSsrc) { |
| 1463 | if (_outgoingScreencastChannel && _outgoingScreencastChannel->ssrc() != screencastSsrc.value()) { |
| 1464 | _outgoingScreencastChannel.reset(); |
| 1465 | } |
| 1466 |
| 1467 | absl::optional<signaling::MediaContent> outgoingScreencastContent; |
| 1468 | for (const auto &content : coordinatedState->outgoingContents) { |
| 1469 | if (content.type == signaling::MediaContent::Type::Video && content.ssrc == screencastSsrc.value()) { |
| 1470 | outgoingScreencastContent = content; |
| 1471 | break; |
| 1472 | } |
| 1473 | } |
| 1474 |
| 1475 | if (outgoingScreencastContent) { |
| 1476 | if (!_outgoingScreencastChannel) { |
| 1477 | const auto weak = std::weak_ptr<InstanceV2ImplInternal>(shared_from_this()); |
| 1478 |
| 1479 | _outgoingScreencastChannel.reset(new OutgoingVideoChannel( |
| 1480 | _threads, |
| 1481 | _channelManager.get(), |
| 1482 | _call.get(), |
| 1483 | _rtpTransport, |
| 1484 | _uniqueRandomIdGenerator.get(), |
| 1485 | _videoBitrateAllocatorFactory.get(), |
| 1486 | [threads = _threads, weak]() { |
| 1487 | threads->getMediaThread()->PostTask([=] { |
| 1488 | const auto strong = weak.lock(); |
| 1489 | if (!strong) { |
| 1490 | return; |
| 1491 | } |
| 1492 | strong->sendMediaState(); |
| 1493 | }); |
| 1494 | }, |
| 1495 | outgoingScreencastContent.value(), |
| 1496 | true |
| 1497 | )); |
| 1498 |
| 1499 | if (_screencastCapture) { |
| 1500 | _outgoingScreencastChannel->setVideoCapture(_screencastCapture); |
| 1501 | } |
| 1502 | } |
| 1503 | } |
| 1504 | } |
| 1505 | } |
| 1506 |
| 1507 | for (const auto &content : coordinatedState->incomingContents) { |
| 1508 | switch (content.type) { |
| 1509 | case signaling::MediaContent::Type::Audio: { |
| 1510 | if (_incomingAudioChannel && _incomingAudioChannel->ssrc() != content.ssrc) { |
| 1511 | _incomingAudioChannel.reset(); |
| 1512 | } |
| 1513 |
| 1514 | if (!_incomingAudioChannel) { |
| 1515 | _incomingAudioChannel.reset(new IncomingV2AudioChannel( |
| 1516 | _channelManager.get(), |
| 1517 | _call.get(), |
| 1518 | _rtpTransport, |
| 1519 | _uniqueRandomIdGenerator.get(), |
| 1520 | content, |
| 1521 | [audioLevelUpdated = _audioLevelUpdated](float myLvl, float level) { |
| 1522 | audioLevelUpdated(myLvl, level); |
| 1523 | }, |
| 1524 | _threads |
| 1525 | )); |
| 1526 | } |
| 1527 |
| 1528 | break; |
| 1529 | } |
| 1530 | case signaling::MediaContent::Type::Video: { |
| 1531 | if (_incomingVideoChannel && _incomingVideoChannel->ssrc() != content.ssrc) { |
| 1532 | _incomingVideoChannel.reset(); |
| 1533 | } |
| 1534 |
| 1535 | if (!_incomingVideoChannel) { |
| 1536 | _incomingVideoChannel.reset(new IncomingV2VideoChannel( |
| 1537 | _channelManager.get(), |
| 1538 | _call.get(), |
| 1539 | _rtpTransport, |
| 1540 | _uniqueRandomIdGenerator.get(), |
| 1541 | content, |
| 1542 | _threads |
| 1543 | )); |
| 1544 | _incomingVideoChannel->addSink(_currentSink); |
| 1545 | } |
| 1546 |
| 1547 | break; |
| 1548 | } |
| 1549 | default: { |
| 1550 | RTC_FATAL() << "Unknown media type"; |
| 1551 | break; |
| 1552 | } |
| 1553 | } |
| 1554 | } |
| 1555 |
| 1556 | /* |
| 1557 |
| 1558 | if (_negotiatedOutgoingScreencastContent) { |
| 1559 | const auto weak = std::weak_ptr<InstanceV2ImplInternal>(shared_from_this()); |
| 1560 |
| 1561 | _outgoingScreencastChannel.reset(new OutgoingVideoChannel( |
| 1562 | _threads, |
| 1563 | _channelManager.get(), |
| 1564 | _call.get(), |
| 1565 | _rtpTransport, |
| 1566 | _uniqueRandomIdGenerator.get(), |
| 1567 | _videoBitrateAllocatorFactory.get(), |
| 1568 | [threads = _threads, weak]() { |
| 1569 | threads->getMediaThread()->PostTask([=] { |
| 1570 | const auto strong = weak.lock(); |
| 1571 | if (!strong) { |
| 1572 | return; |
| 1573 | } |
| 1574 | strong->sendMediaState(); |
| 1575 | }); |
| 1576 | }, |
| 1577 | _negotiatedOutgoingScreencastContent.value(), |
| 1578 | true |
| 1579 | )); |
| 1580 |
| 1581 | if (_screencastCapture) { |
| 1582 | _outgoingScreencastChannel->setVideoCapture(_screencastCapture); |
| 1583 | } |
| 1584 | } |
| 1585 |
| 1586 | if (_negotiatedOutgoingAudioContent) { |
| 1587 | _outgoingAudioChannel.reset(new OutgoingAudioChannel( |
| 1588 | _call.get(), |
| 1589 | _channelManager.get(), |
| 1590 | _uniqueRandomIdGenerator.get(), |
| 1591 | &_audioSource, |
| 1592 | _rtpTransport, |
| 1593 | _negotiatedOutgoingAudioContent.value(), |
| 1594 | _threads |
| 1595 | )); |
| 1596 | }*/ |
| 1597 |
| 1598 | adjustBitratePreferences(true); |
| 1599 | sendMediaState(); |
| 1600 | } |
| 1601 |
| 1602 | void sendInitialSetup() { |
| 1603 | const auto weak = std::weak_ptr<InstanceV2ImplInternal>(shared_from_this()); |
| 1604 |
| 1605 | _networking->perform([weak, threads = _threads, isOutgoing = _encryptionKey.isOutgoing](InstanceNetworking *networking) { |
| 1606 | auto localFingerprint = networking->getLocalFingerprint(); |
| 1607 | std::string hash; |
| 1608 | std::string fingerprint; |
| 1609 |
| 1610 | if (localFingerprint) { |
| 1611 | hash = localFingerprint->algorithm; |
| 1612 | fingerprint = localFingerprint->GetRfc4572Fingerprint(); |
| 1613 | } |
| 1614 |
| 1615 | std::string setup; |
| 1616 | if (isOutgoing) { |
| 1617 | setup = "actpass"; |
| 1618 | } else { |
| 1619 | setup = "passive"; |
| 1620 | } |
| 1621 |
| 1622 | auto localIceParams = networking->getLocalIceParameters(); |
| 1623 | std::string ufrag = localIceParams.ufrag; |
| 1624 | std::string pwd = localIceParams.pwd; |
| 1625 | bool supportsRenomination = localIceParams.supportsRenomination; |
| 1626 |
| 1627 | threads->getMediaThread()->PostTask([weak, ufrag, pwd, supportsRenomination, hash, fingerprint, setup]() { |
| 1628 | const auto strong = weak.lock(); |
| 1629 | if (!strong) { |
| 1630 | return; |
| 1631 | } |
| 1632 |
| 1633 | signaling::InitialSetupMessage data; |
| 1634 |
| 1635 | data.ufrag = ufrag; |
| 1636 | data.pwd = pwd; |
| 1637 | data.supportsRenomination = supportsRenomination; |
| 1638 |
| 1639 | signaling::DtlsFingerprint dtlsFingerprint; |
| 1640 | dtlsFingerprint.hash = hash; |
| 1641 | dtlsFingerprint.fingerprint = fingerprint; |
| 1642 | dtlsFingerprint.setup = setup; |
| 1643 | data.fingerprints.push_back(std::move(dtlsFingerprint)); |
| 1644 |
| 1645 | signaling::Message message; |
| 1646 | message.data = std::move(data); |
| 1647 | strong->sendSignalingMessage(message); |
| 1648 | }); |
| 1649 | }); |
| 1650 | } |
| 1651 |
| 1652 | void sendOfferIfNeeded() { |
| 1653 | if (const auto offer = _contentNegotiationContext->getPendingOffer()) { |
| 1654 | signaling::NegotiateChannelsMessage data; |
| 1655 |
| 1656 | data.exchangeId = offer->exchangeId; |
| 1657 |
| 1658 | data.contents = offer->contents; |
| 1659 |
| 1660 | signaling::Message message; |
| 1661 | message.data = std::move(data); |
| 1662 | sendSignalingMessage(message); |
| 1663 | } |
| 1664 | } |
| 1665 |
| 1666 | void receiveSignalingData(const std::vector<uint8_t> &data) { |
| 1667 | if (_signalingConnection) { |
| 1668 | _signalingConnection->receiveExternal(data); |
| 1669 | } else { |
| 1670 | RTC_LOG(LS_ERROR) << "receiveSignalingData: signalingConnection is not available"; |
| 1671 | } |
| 1672 | } |
| 1673 |
| 1674 | void onSignalingData(const std::vector<uint8_t> &data) { |
| 1675 | if (_signalingEncryptedConnection) { |
| 1676 | switch (_signalingProtocolVersion) { |
| 1677 | case SignalingProtocolVersion::V1: |
| 1678 | case SignalingProtocolVersion::V3: { |
| 1679 | if (const auto message = _signalingEncryptedConnection->decryptRawPacket(rtc::CopyOnWriteBuffer(data.data(), data.size()))) { |
| 1680 | processSignalingMessage(message.value()); |
| 1681 | } else { |
| 1682 | RTC_LOG(LS_ERROR) << "receiveSignalingData could not decrypt signaling data"; |
| 1683 | } |
| 1684 |
| 1685 | break; |
| 1686 | } |
| 1687 | case SignalingProtocolVersion::V2: { |
| 1688 | if (const auto packet = _signalingEncryptedConnection->handleIncomingRawPacket((const char *)data.data(), data.size())) { |
| 1689 | processSignalingMessage(packet.value().main.message); |
| 1690 |
| 1691 | for (const auto &additional : packet.value().additional) { |
| 1692 | processSignalingMessage(additional.message); |
| 1693 | } |
| 1694 | } |
| 1695 |
| 1696 | break; |
| 1697 | } |
| 1698 | default: { |
| 1699 | RTC_DCHECK_NOTREACHED(); |
| 1700 |
| 1701 | break; |
| 1702 | } |
| 1703 | } |
| 1704 | } else { |
| 1705 | RTC_LOG(LS_ERROR) << "receiveSignalingData encryption not available"; |
| 1706 | } |
| 1707 | } |
| 1708 |
| 1709 | void processSignalingMessage(rtc::CopyOnWriteBuffer const &data) { |
| 1710 | std::vector<uint8_t> decryptedData = std::vector<uint8_t>(data.data(), data.data() + data.size()); |
| 1711 |
| 1712 | if (isGzip(decryptedData)) { |
| 1713 | if (const auto decompressedData = gunzipData(decryptedData, 2 * 1024 * 1024)) { |
| 1714 | processSignalingData(decompressedData.value()); |
| 1715 | } else { |
| 1716 | RTC_LOG(LS_ERROR) << "receiveSignalingData could not decompress gzipped data"; |
| 1717 | } |
| 1718 | } else { |
| 1719 | processSignalingData(decryptedData); |
| 1720 | } |
| 1721 | } |
| 1722 |
| 1723 | void processSignalingData(const std::vector<uint8_t> &data) { |
| 1724 | RTC_LOG(LS_INFO) << "processSignalingData: " << std::string(data.begin(), data.end()); |
| 1725 |
| 1726 | const auto message = signaling::Message::parse(data); |
| 1727 | if (!message) { |
| 1728 | return; |
| 1729 | } |
| 1730 | const auto messageData = &message->data; |
| 1731 | if (const auto initialSetup = absl::get_if<signaling::InitialSetupMessage>(messageData)) { |
| 1732 | PeerIceParameters remoteIceParameters; |
| 1733 | remoteIceParameters.ufrag = initialSetup->ufrag; |
| 1734 | remoteIceParameters.pwd = initialSetup->pwd; |
| 1735 | remoteIceParameters.supportsRenomination = initialSetup->supportsRenomination; |
| 1736 |
| 1737 | std::unique_ptr<rtc::SSLFingerprint> fingerprint; |
| 1738 | std::string sslSetup; |
| 1739 | if (initialSetup->fingerprints.size() != 0) { |
| 1740 | fingerprint = rtc::SSLFingerprint::CreateUniqueFromRfc4572(initialSetup->fingerprints[0].hash, initialSetup->fingerprints[0].fingerprint); |
| 1741 | sslSetup = initialSetup->fingerprints[0].setup; |
| 1742 | } |
| 1743 |
| 1744 | _networking->perform([threads = _threads, remoteIceParameters = std::move(remoteIceParameters), fingerprint = std::move(fingerprint), sslSetup = std::move(sslSetup)](InstanceNetworking *networking) { |
| 1745 | networking->setRemoteParams(remoteIceParameters, fingerprint.get(), sslSetup); |
| 1746 | }); |
| 1747 |
| 1748 | _handshakeCompleted = true; |
| 1749 |
| 1750 | if (_encryptionKey.isOutgoing) { |
| 1751 | sendOfferIfNeeded(); |
| 1752 | } else { |
| 1753 | sendInitialSetup(); |
| 1754 | } |
| 1755 |
| 1756 | commitPendingIceCandidates(); |
| 1757 | } else if (const auto offerAnwer = absl::get_if<signaling::NegotiateChannelsMessage>(messageData)) { |
| 1758 | auto negotiationContents = std::make_unique<ContentNegotiationContext::NegotiationContents>(); |
| 1759 | negotiationContents->exchangeId = offerAnwer->exchangeId; |
| 1760 | negotiationContents->contents = offerAnwer->contents; |
| 1761 |
| 1762 | if (const auto response = _contentNegotiationContext->setRemoteNegotiationContent(std::move(negotiationContents))) { |
| 1763 | signaling::NegotiateChannelsMessage data; |
| 1764 |
| 1765 | data.exchangeId = response->exchangeId; |
| 1766 | data.contents = response->contents; |
| 1767 |
| 1768 | signaling::Message message; |
| 1769 | message.data = std::move(data); |
| 1770 | sendSignalingMessage(message); |
| 1771 | } |
| 1772 |
| 1773 | sendOfferIfNeeded(); |
| 1774 |
| 1775 | createNegotiatedChannels(); |
| 1776 | } else if (const auto candidatesList = absl::get_if<signaling::CandidatesMessage>(messageData)) { |
| 1777 | for (const auto &candidate : candidatesList->iceCandidates) { |
| 1778 | webrtc::JsepIceCandidate parseCandidate{ std::string(), 0 }; |
| 1779 | if (!parseCandidate.Initialize(candidate.sdpString, nullptr)) { |
| 1780 | RTC_LOG(LS_ERROR) << "Could not parse candidate: " << candidate.sdpString; |
| 1781 | continue; |
| 1782 | } |
| 1783 | _pendingIceCandidates.push_back(parseCandidate.candidate()); |
| 1784 | } |
| 1785 |
| 1786 | if (_handshakeCompleted) { |
| 1787 | commitPendingIceCandidates(); |
| 1788 | } |
| 1789 | } else if (const auto mediaState = absl::get_if<signaling::MediaStateMessage>(messageData)) { |
| 1790 | AudioState mappedAudioState; |
| 1791 | if (mediaState->isMuted) { |
| 1792 | mappedAudioState = AudioState::Muted; |
| 1793 | } else { |
| 1794 | mappedAudioState = AudioState::Active; |
| 1795 | } |
| 1796 |
| 1797 | VideoState mappedVideoState; |
| 1798 | switch (mediaState->videoState) { |
| 1799 | case signaling::MediaStateMessage::VideoState::Inactive: { |
| 1800 | mappedVideoState = VideoState::Inactive; |
| 1801 | break; |
| 1802 | } |
| 1803 | case signaling::MediaStateMessage::VideoState::Suspended: { |
| 1804 | mappedVideoState = VideoState::Paused; |
| 1805 | break; |
| 1806 | } |
| 1807 | case signaling::MediaStateMessage::VideoState::Active: { |
| 1808 | mappedVideoState = VideoState::Active; |
| 1809 | break; |
| 1810 | } |
| 1811 | default: { |
| 1812 | RTC_FATAL() << "Unknown videoState"; |
| 1813 | break; |
| 1814 | } |
| 1815 | } |
| 1816 |
| 1817 | VideoState mappedScreencastState; |
| 1818 | switch (mediaState->screencastState) { |
| 1819 | case signaling::MediaStateMessage::VideoState::Inactive: { |
| 1820 | mappedScreencastState = VideoState::Inactive; |
| 1821 | break; |
| 1822 | } |
| 1823 | case signaling::MediaStateMessage::VideoState::Suspended: { |
| 1824 | mappedScreencastState = VideoState::Paused; |
| 1825 | break; |
| 1826 | } |
| 1827 | case signaling::MediaStateMessage::VideoState::Active: { |
| 1828 | mappedScreencastState = VideoState::Active; |
| 1829 | break; |
| 1830 | } |
| 1831 | default: { |
| 1832 | RTC_FATAL() << "Unknown videoState"; |
| 1833 | break; |
| 1834 | } |
| 1835 | } |
| 1836 |
| 1837 | VideoState effectiveVideoState = mappedVideoState; |
| 1838 | if (mappedScreencastState == VideoState::Active || mappedScreencastState == VideoState::Paused) { |
| 1839 | effectiveVideoState = mappedScreencastState; |
| 1840 | } |
| 1841 |
| 1842 | if (_remoteMediaStateUpdated) { |
| 1843 | _remoteMediaStateUpdated(mappedAudioState, effectiveVideoState); |
| 1844 | } |
| 1845 |
| 1846 | if (_remoteBatteryLevelIsLowUpdated) { |
| 1847 | _remoteBatteryLevelIsLowUpdated(mediaState->isBatteryLow); |
| 1848 | } |
| 1849 | } |
| 1850 | } |
| 1851 |
| 1852 | void commitPendingIceCandidates() { |
| 1853 | if (_pendingIceCandidates.size() == 0) { |
| 1854 | return; |
| 1855 | } |
| 1856 | _networking->perform([threads = _threads, parsedCandidates = _pendingIceCandidates](InstanceNetworking *networking) { |
| 1857 | networking->addCandidates(parsedCandidates); |
| 1858 | }); |
| 1859 | _pendingIceCandidates.clear(); |
| 1860 | } |
| 1861 |
| 1862 | void onNetworkStateUpdated(InstanceNetworking::State const &state) { |
| 1863 | State mappedState; |
| 1864 | if (state.isFailed) { |
| 1865 | mappedState = State::Failed; |
| 1866 | } else if (state.isReadyToSendData) { |
| 1867 | mappedState = State::Established; |
| 1868 | } else { |
| 1869 | mappedState = State::Reconnecting; |
| 1870 | } |
| 1871 |
| 1872 | NetworkStateLogRecord record; |
| 1873 | record.isConnected = state.isReadyToSendData; |
| 1874 | record.route = state.route; |
| 1875 | record.connection = state.connection; |
| 1876 | record.isFailed = state.isFailed; |
| 1877 |
| 1878 | if (!_currentNetworkStateLogRecord || !(_currentNetworkStateLogRecord.value() == record)) { |
| 1879 | _currentNetworkStateLogRecord = record; |
| 1880 | _networkStateLogRecords.emplace_back(rtc::TimeMillis(), std::move(record)); |
| 1881 | } |
| 1882 |
| 1883 | _networkState = state; |
| 1884 | _stateUpdated(mappedState); |
| 1885 | } |
| 1886 |
| 1887 | void onDataChannelStateUpdated(bool isDataChannelOpen) { |
| 1888 | if (_isDataChannelOpen != isDataChannelOpen) { |
| 1889 | _isDataChannelOpen = isDataChannelOpen; |
| 1890 |
| 1891 | if (_isDataChannelOpen) { |
| 1892 | sendMediaState(); |
| 1893 | } |
| 1894 | } |
| 1895 | } |
| 1896 |
| 1897 | void sendDataChannelMessage(signaling::Message const &message) { |
| 1898 | if (!_isDataChannelOpen) { |
| 1899 | RTC_LOG(LS_ERROR) << "sendDataChannelMessage called, but data channel is not open"; |
| 1900 | return; |
| 1901 | } |
| 1902 | auto data = message.serialize(); |
| 1903 | std::string stringData(data.begin(), data.end()); |
| 1904 | RTC_LOG(LS_INFO) << "sendDataChannelMessage: " << stringData; |
| 1905 | _networking->perform([stringData = std::move(stringData)](InstanceNetworking *networking) { |
| 1906 | networking->sendDataChannelMessage(stringData); |
| 1907 | }); |
| 1908 | } |
| 1909 |
| 1910 | void onDataChannelMessage(std::string const &message) { |
| 1911 | RTC_LOG(LS_INFO) << "dataChannelMessage received: " << message; |
| 1912 | std::vector<uint8_t> data(message.begin(), message.end()); |
| 1913 | processSignalingData(data); |
| 1914 | } |
| 1915 |
| 1916 | void sendMediaState() { |
| 1917 | if (!_isDataChannelOpen) { |
| 1918 | return; |
| 1919 | } |
| 1920 | signaling::Message message; |
| 1921 | signaling::MediaStateMessage data; |
| 1922 | data.isMuted = _isMicrophoneMuted; |
| 1923 | data.isBatteryLow = _isBatteryLow; |
| 1924 | if (_outgoingVideoChannel) { |
| 1925 | if (_outgoingVideoChannel->videoCapture()) { |
| 1926 | data.videoState = signaling::MediaStateMessage::VideoState::Active; |
| 1927 | } else{ |
| 1928 | data.videoState = signaling::MediaStateMessage::VideoState::Inactive; |
| 1929 | } |
| 1930 | data.videoRotation = _outgoingVideoChannel->getRotation(); |
| 1931 | } else { |
| 1932 | data.videoState = signaling::MediaStateMessage::VideoState::Inactive; |
| 1933 | data.videoRotation = signaling::MediaStateMessage::VideoRotation::Rotation0; |
| 1934 | } |
| 1935 | if (_outgoingScreencastChannel) { |
| 1936 | if (_outgoingScreencastChannel->videoCapture()) { |
| 1937 | data.screencastState = signaling::MediaStateMessage::VideoState::Active; |
| 1938 | } else{ |
| 1939 | data.screencastState = signaling::MediaStateMessage::VideoState::Inactive; |
| 1940 | } |
| 1941 | } else { |
| 1942 | data.screencastState = signaling::MediaStateMessage::VideoState::Inactive; |
| 1943 | } |
| 1944 | message.data = std::move(data); |
| 1945 | sendDataChannelMessage(message); |
| 1946 | } |
| 1947 |
| 1948 | void sendCandidate(const cricket::Candidate &candidate) { |
| 1949 | cricket::Candidate patchedCandidate = candidate; |
| 1950 | patchedCandidate.set_component(1); |
| 1951 |
| 1952 | signaling::CandidatesMessage data; |
| 1953 |
| 1954 | signaling::IceCandidate serializedCandidate; |
| 1955 |
| 1956 | webrtc::JsepIceCandidate iceCandidate{ std::string(), 0 }; |
| 1957 | iceCandidate.SetCandidate(patchedCandidate); |
| 1958 | std::string serialized; |
| 1959 | const auto success = iceCandidate.ToString(&serialized); |
| 1960 | assert(success); |
| 1961 | (void)success; |
| 1962 |
| 1963 | serializedCandidate.sdpString = serialized; |
| 1964 |
| 1965 | data.iceCandidates.push_back(std::move(serializedCandidate)); |
| 1966 |
| 1967 | signaling::Message message; |
| 1968 | message.data = std::move(data); |
| 1969 | sendSignalingMessage(message); |
| 1970 | } |
| 1971 |
| 1972 | void setVideoCapture(std::shared_ptr<VideoCaptureInterface> videoCapture) { |
| 1973 | auto videoCaptureImpl = GetVideoCaptureAssumingSameThread(videoCapture.get()); |
| 1974 | if (videoCaptureImpl) { |
| 1975 | if (videoCaptureImpl->isScreenCapture()) { |
| 1976 | _videoCapture = nullptr; |
| 1977 | _screencastCapture = videoCapture; |
| 1978 |
| 1979 | if (_outgoingVideoChannel) { |
| 1980 | _outgoingVideoChannel->setVideoCapture(nullptr); |
| 1981 | } |
| 1982 | if (_outgoingVideoChannelId) { |
| 1983 | _contentNegotiationContext->removeOutgoingChannel(_outgoingVideoChannelId.value()); |
| 1984 | _outgoingVideoChannelId.reset(); |
| 1985 | } |
| 1986 |
| 1987 | if (_outgoingScreencastChannel) { |
| 1988 | _outgoingScreencastChannel->setVideoCapture(videoCapture); |
| 1989 | } |
| 1990 | if (!_outgoingScreencastChannelId) { |
| 1991 | _outgoingScreencastChannelId = _contentNegotiationContext->addOutgoingChannel(signaling::MediaContent::Type::Video); |
| 1992 | } |
| 1993 | } else { |
| 1994 | _videoCapture = videoCapture; |
| 1995 | _screencastCapture = nullptr; |
| 1996 |
| 1997 | if (_outgoingVideoChannel) { |
| 1998 | _outgoingVideoChannel->setVideoCapture(videoCapture); |
| 1999 | } |
| 2000 | if (!_outgoingVideoChannelId) { |
| 2001 | _outgoingVideoChannelId = _contentNegotiationContext->addOutgoingChannel(signaling::MediaContent::Type::Video); |
| 2002 | } |
| 2003 |
| 2004 | if (_outgoingScreencastChannel) { |
| 2005 | _outgoingScreencastChannel->setVideoCapture(nullptr); |
| 2006 | } |
| 2007 | if (_outgoingScreencastChannelId) { |
| 2008 | _contentNegotiationContext->removeOutgoingChannel(_outgoingScreencastChannelId.value()); |
| 2009 | _outgoingScreencastChannelId.reset(); |
| 2010 | } |
| 2011 | } |
| 2012 | } else { |
| 2013 | _videoCapture = nullptr; |
| 2014 | _screencastCapture = nullptr; |
| 2015 |
| 2016 | if (_outgoingVideoChannel) { |
| 2017 | _outgoingVideoChannel->setVideoCapture(nullptr); |
| 2018 | } |
| 2019 |
| 2020 | if (_outgoingScreencastChannel) { |
| 2021 | _outgoingScreencastChannel->setVideoCapture(nullptr); |
| 2022 | } |
| 2023 |
| 2024 | if (_outgoingVideoChannelId) { |
| 2025 | _contentNegotiationContext->removeOutgoingChannel(_outgoingVideoChannelId.value()); |
| 2026 | _outgoingVideoChannelId.reset(); |
| 2027 | } |
| 2028 |
| 2029 | if (_outgoingScreencastChannelId) { |
| 2030 | _contentNegotiationContext->removeOutgoingChannel(_outgoingScreencastChannelId.value()); |
| 2031 | _outgoingScreencastChannelId.reset(); |
| 2032 | } |
| 2033 | } |
| 2034 |
| 2035 | if (_handshakeCompleted) { |
| 2036 | sendOfferIfNeeded(); |
| 2037 | sendMediaState(); |
| 2038 | adjustBitratePreferences(true); |
| 2039 | createNegotiatedChannels(); |
| 2040 | } |
| 2041 | } |
| 2042 |
| 2043 | void setRequestedVideoAspect(float aspect) { |
| 2044 | } |
| 2045 |
| 2046 | void setNetworkType(NetworkType networkType) { |
| 2047 |
| 2048 | } |
| 2049 |
| 2050 | void setMuteMicrophone(bool muteMicrophone) { |
| 2051 | if (_isMicrophoneMuted != muteMicrophone) { |
| 2052 | _isMicrophoneMuted = muteMicrophone; |
| 2053 |
| 2054 | if (_outgoingAudioChannel) { |
| 2055 | _outgoingAudioChannel->setIsMuted(muteMicrophone); |
| 2056 | } |
| 2057 |
| 2058 | sendMediaState(); |
| 2059 | } |
| 2060 | } |
| 2061 |
| 2062 | void setIncomingVideoOutput(std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) { |
| 2063 | _currentSink = sink; |
| 2064 | if (_incomingVideoChannel) { |
| 2065 | _incomingVideoChannel->addSink(sink); |
| 2066 | } |
| 2067 | if (_incomingScreencastChannel) { |
| 2068 | _incomingScreencastChannel->addSink(sink); |
| 2069 | } |
| 2070 | } |
| 2071 |
| 2072 | void setAudioInputDevice(std::string id) { |
| 2073 | _threads->getWorkerThread()->BlockingCall([&]() { |
| 2074 | SetAudioInputDeviceById(_audioDeviceModule.get(), id); |
| 2075 | }); |
| 2076 | } |
| 2077 |
| 2078 | void setAudioOutputDevice(std::string id) { |
| 2079 | _threads->getWorkerThread()->BlockingCall([&]() { |
| 2080 | SetAudioOutputDeviceById(_audioDeviceModule.get(), id); |
| 2081 | }); |
| 2082 | } |
| 2083 |
| 2084 | void setIsLowBatteryLevel(bool isLowBatteryLevel) { |
| 2085 | if (_isBatteryLow != isLowBatteryLevel) { |
| 2086 | _isBatteryLow = isLowBatteryLevel; |
| 2087 | sendMediaState(); |
| 2088 | } |
| 2089 | } |
| 2090 |
| 2091 | void stop(std::function<void(FinalState)> completion) { |
| 2092 | FinalState finalState; |
| 2093 |
| 2094 | json11::Json::object statsLog; |
| 2095 |
| 2096 | for (int i = (int)_networkStateLogRecords.size() - 1; i >= 1; i--) { |
| 2097 | // coalesce events within 5ms |
| 2098 | if (_networkStateLogRecords[i].timestamp - _networkStateLogRecords[i - 1].timestamp < 5) { |
| 2099 | _networkStateLogRecords.erase(_networkStateLogRecords.begin() + i - 1); |
| 2100 | } |
| 2101 | } |
| 2102 |
| 2103 | json11::Json::array jsonNetworkStateLogRecords; |
| 2104 | int64_t baseTimestamp = 0; |
| 2105 | for (const auto &record : _networkStateLogRecords) { |
| 2106 | json11::Json::object jsonRecord; |
| 2107 |
| 2108 | if (baseTimestamp == 0) { |
| 2109 | baseTimestamp = record.timestamp; |
| 2110 | } |
| 2111 | jsonRecord.insert(std::make_pair("t", json11::Json(std::to_string(record.timestamp - baseTimestamp)))); |
| 2112 | jsonRecord.insert(std::make_pair("c", json11::Json(record.record.isConnected ? 1 : 0))); |
| 2113 | if (record.record.route) { |
| 2114 | jsonRecord.insert(std::make_pair("local", json11::Json(record.record.route->localDescription))); |
| 2115 | jsonRecord.insert(std::make_pair("remote", json11::Json(record.record.route->remoteDescription))); |
| 2116 | } |
| 2117 | if (record.record.connection) { |
| 2118 | json11::Json::object jsonConnection; |
| 2119 |
| 2120 | auto serializeCandidate = [](InstanceNetworking::ConnectionDescription::CandidateDescription const &candidate) -> json11::Json::object { |
| 2121 | json11::Json::object jsonCandidate; |
| 2122 |
| 2123 | jsonCandidate.insert(std::make_pair("type", json11::Json(candidate.type))); |
| 2124 | jsonCandidate.insert(std::make_pair("protocol", json11::Json(candidate.protocol))); |
| 2125 | jsonCandidate.insert(std::make_pair("address", json11::Json(candidate.address))); |
| 2126 |
| 2127 | return jsonCandidate; |
| 2128 | }; |
| 2129 |
| 2130 | jsonConnection.insert(std::make_pair("local", serializeCandidate(record.record.connection->local))); |
| 2131 | jsonConnection.insert(std::make_pair("remote", serializeCandidate(record.record.connection->remote))); |
| 2132 |
| 2133 | jsonRecord.insert(std::make_pair("network", std::move(jsonConnection))); |
| 2134 | } |
| 2135 | if (record.record.isFailed) { |
| 2136 | jsonRecord.insert(std::make_pair("failed", json11::Json(1))); |
| 2137 | } |
| 2138 |
| 2139 | jsonNetworkStateLogRecords.push_back(std::move(jsonRecord)); |
| 2140 | } |
| 2141 | statsLog.insert(std::make_pair("network", std::move(jsonNetworkStateLogRecords))); |
| 2142 |
| 2143 | json11::Json::array jsonNetworkBitrateLogRecords; |
| 2144 | for (const auto &record : _networkBitrateLogRecords) { |
| 2145 | json11::Json::object jsonRecord; |
| 2146 |
| 2147 | jsonRecord.insert(std::make_pair("b", json11::Json(record.record.bitrate))); |
| 2148 |
| 2149 | jsonNetworkBitrateLogRecords.push_back(std::move(jsonRecord)); |
| 2150 | } |
| 2151 | statsLog.insert(std::make_pair("bitrate", std::move(jsonNetworkBitrateLogRecords))); |
| 2152 |
| 2153 | auto jsonStatsLog = json11::Json(std::move(statsLog)); |
| 2154 |
| 2155 | if (!_statsLogPath.data.empty()) { |
| 2156 | std::ofstream file; |
| 2157 | file.open(_statsLogPath.data); |
| 2158 |
| 2159 | file << jsonStatsLog.dump(); |
| 2160 |
| 2161 | file.close(); |
| 2162 | } |
| 2163 |
| 2164 | completion(finalState); |
| 2165 | } |
| 2166 |
| 2167 | void adjustBitratePreferences(bool resetStartBitrate) { |
| 2168 | if (_outgoingAudioChannel) { |
| 2169 | _outgoingAudioChannel->setMaxBitrate(32 * 1024); |
| 2170 | } |
| 2171 | if (_outgoingVideoChannel) { |
| 2172 | _outgoingVideoChannel->setMaxBitrate(1000 * 1024); |
| 2173 | } |
| 2174 | } |
| 2175 |
| 2176 | private: |
| 2177 | rtc::scoped_refptr<webrtc::AudioDeviceModule> createAudioDeviceModule() { |
| 2178 | const auto create = [&](webrtc::AudioDeviceModule::AudioLayer layer) { |
| 2179 | #ifdef WEBRTC_IOS |
| 2180 | return rtc::make_ref_counted<webrtc::tgcalls_ios_adm::AudioDeviceModuleIOS>(false, false, 1); |
| 2181 | #else |
| 2182 | return webrtc::AudioDeviceModule::Create( |
| 2183 | layer, |
| 2184 | _taskQueueFactory.get()); |
| 2185 | #endif |
| 2186 | }; |
| 2187 | const auto check = [&](const rtc::scoped_refptr<webrtc::AudioDeviceModule> &result) { |
| 2188 | return (result && result->Init() == 0) ? result : nullptr; |
| 2189 | }; |
| 2190 | if (_createAudioDeviceModule) { |
| 2191 | if (const auto result = check(_createAudioDeviceModule(_taskQueueFactory.get()))) { |
| 2192 | return result; |
| 2193 | } |
| 2194 | } |
| 2195 | return check(create(webrtc::AudioDeviceModule::kPlatformDefaultAudio)); |
| 2196 | } |
| 2197 |
| 2198 | private: |
| 2199 | SignalingProtocolVersion _signalingProtocolVersion; |
| 2200 | std::shared_ptr<Threads> _threads; |
| 2201 | std::vector<RtcServer> _rtcServers; |
| 2202 | std::unique_ptr<Proxy> _proxy; |
| 2203 | std::shared_ptr<DirectConnectionChannel> _directConnectionChannel; |
| 2204 | bool _enableP2P = false; |
| 2205 | EncryptionKey _encryptionKey; |
| 2206 | std::function<void(State)> _stateUpdated; |
| 2207 | std::function<void(int)> _signalBarsUpdated; |
| 2208 | std::function<void(float, float )> _audioLevelUpdated; |
| 2209 | std::function<void(bool)> _remoteBatteryLevelIsLowUpdated; |
| 2210 | std::function<void(AudioState, VideoState)> _remoteMediaStateUpdated; |
| 2211 | std::function<void(float)> _remotePrefferedAspectRatioUpdated; |
| 2212 | std::function<void(const std::vector<uint8_t> &)> _signalingDataEmitted; |
| 2213 | std::function<rtc::scoped_refptr<webrtc::AudioDeviceModule>(webrtc::TaskQueueFactory*)> _createAudioDeviceModule; |
| 2214 | MediaDevicesConfig _devicesConfig; |
| 2215 | FilePath _statsLogPath; |
| 2216 |
| 2217 | std::unique_ptr<SignalingConnection> _signalingConnection; |
| 2218 | std::unique_ptr<EncryptedConnection> _signalingEncryptedConnection; |
| 2219 |
| 2220 | int64_t _startTimestamp = 0; |
| 2221 |
| 2222 | absl::optional<NetworkStateLogRecord> _currentNetworkStateLogRecord; |
| 2223 | std::vector<StateLogRecord<NetworkStateLogRecord>> _networkStateLogRecords; |
| 2224 | std::vector<StateLogRecord<NetworkBitrateLogRecord>> _networkBitrateLogRecords; |
| 2225 |
| 2226 | absl::optional<InstanceNetworking::State> _networkState; |
| 2227 |
| 2228 | bool _handshakeCompleted = false; |
| 2229 | std::vector<cricket::Candidate> _pendingIceCandidates; |
| 2230 | bool _isDataChannelOpen = false; |
| 2231 |
| 2232 | std::unique_ptr<webrtc::RtcEventLogNull> _eventLog; |
| 2233 | std::unique_ptr<webrtc::TaskQueueFactory> _taskQueueFactory; |
| 2234 | std::unique_ptr<webrtc::Call> _call; |
| 2235 | webrtc::LocalAudioSinkAdapter _audioSource; |
| 2236 | rtc::scoped_refptr<webrtc::AudioDeviceModule> _audioDeviceModule; |
| 2237 |
| 2238 | std::unique_ptr<rtc::UniqueRandomIdGenerator> _uniqueRandomIdGenerator; |
| 2239 | webrtc::RtpTransport *_rtpTransport = nullptr; |
| 2240 | std::unique_ptr<ChannelManager> _channelManager; |
| 2241 | std::unique_ptr<webrtc::VideoBitrateAllocatorFactory> _videoBitrateAllocatorFactory; |
| 2242 | std::string _initialInputDeviceId; |
| 2243 | std::string _initialOutputDeviceId; |
| 2244 |
| 2245 | std::unique_ptr<ContentNegotiationContext> _contentNegotiationContext; |
| 2246 |
| 2247 | std::shared_ptr<ThreadLocalObject<NativeNetworkingImpl>> _networking; |
| 2248 |
| 2249 | absl::optional<std::string> _outgoingAudioChannelId; |
| 2250 | std::unique_ptr<OutgoingAudioChannel> _outgoingAudioChannel; |
| 2251 | bool _isMicrophoneMuted = false; |
| 2252 |
| 2253 | std::vector<webrtc::SdpVideoFormat> _availableVideoFormats; |
| 2254 |
| 2255 | absl::optional<std::string> _outgoingVideoChannelId; |
| 2256 | std::shared_ptr<OutgoingVideoChannel> _outgoingVideoChannel; |
| 2257 | absl::optional<std::string> _outgoingScreencastChannelId; |
| 2258 | std::shared_ptr<OutgoingVideoChannel> _outgoingScreencastChannel; |
| 2259 |
| 2260 | bool _isBatteryLow = false; |
| 2261 |
| 2262 | std::unique_ptr<IncomingV2AudioChannel> _incomingAudioChannel; |
| 2263 | std::unique_ptr<IncomingV2VideoChannel> _incomingVideoChannel; |
| 2264 | std::unique_ptr<IncomingV2VideoChannel> _incomingScreencastChannel; |
| 2265 |
| 2266 | std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> _currentSink; |
| 2267 |
| 2268 | std::shared_ptr<VideoCaptureInterface> _videoCapture; |
| 2269 | std::shared_ptr<VideoCaptureInterface> _screencastCapture; |
| 2270 | std::shared_ptr<PlatformContext> _platformContext; |
| 2271 | }; |
| 2272 |
| 2273 | InstanceV2Impl::InstanceV2Impl(Descriptor &&descriptor) { |
| 2274 | if (descriptor.config.logPath.data.size() != 0) { |
| 2275 | _logSink = std::make_unique<LogSinkImpl>(descriptor.config.logPath); |
| 2276 | } |
| 2277 | #ifdef DEBUG |
| 2278 | rtc::LogMessage::LogToDebug(rtc::LS_VERBOSE); |
| 2279 | #else |
| 2280 | rtc::LogMessage::LogToDebug(rtc::LS_INFO); |
| 2281 | #endif |
| 2282 | rtc::LogMessage::SetLogToStderr(false); |
| 2283 | if (_logSink) { |
| 2284 | rtc::LogMessage::AddLogToStream(_logSink.get(), rtc::LS_INFO); |
| 2285 | } |
| 2286 |
| 2287 | _threads = StaticThreads::getThreads(); |
| 2288 | _internal.reset(new ThreadLocalObject<InstanceV2ImplInternal>(_threads->getMediaThread(), [descriptor = std::move(descriptor), threads = _threads]() mutable { |
| 2289 | return new InstanceV2ImplInternal(std::move(descriptor), threads); |
| 2290 | })); |
| 2291 | _internal->perform([](InstanceV2ImplInternal *internal) { |
| 2292 | internal->start(); |
| 2293 | }); |
| 2294 | } |
| 2295 |
| 2296 | InstanceV2Impl::~InstanceV2Impl() { |
| 2297 | rtc::LogMessage::RemoveLogToStream(_logSink.get()); |
| 2298 | } |
| 2299 |
| 2300 | void InstanceV2Impl::receiveSignalingData(const std::vector<uint8_t> &data) { |
| 2301 | _internal->perform([data](InstanceV2ImplInternal *internal) { |
| 2302 | internal->receiveSignalingData(data); |
| 2303 | }); |
| 2304 | } |
| 2305 |
| 2306 | void InstanceV2Impl::setVideoCapture(std::shared_ptr<VideoCaptureInterface> videoCapture) { |
| 2307 | _internal->perform([videoCapture](InstanceV2ImplInternal *internal) { |
| 2308 | internal->setVideoCapture(videoCapture); |
| 2309 | }); |
| 2310 | } |
| 2311 |
| 2312 | void InstanceV2Impl::setRequestedVideoAspect(float aspect) { |
| 2313 | _internal->perform([aspect](InstanceV2ImplInternal *internal) { |
| 2314 | internal->setRequestedVideoAspect(aspect); |
| 2315 | }); |
| 2316 | } |
| 2317 |
| 2318 | void InstanceV2Impl::setNetworkType(NetworkType networkType) { |
| 2319 | _internal->perform([networkType](InstanceV2ImplInternal *internal) { |
| 2320 | internal->setNetworkType(networkType); |
| 2321 | }); |
| 2322 | } |
| 2323 |
| 2324 | void InstanceV2Impl::setMuteMicrophone(bool muteMicrophone) { |
| 2325 | _internal->perform([muteMicrophone](InstanceV2ImplInternal *internal) { |
| 2326 | internal->setMuteMicrophone(muteMicrophone); |
| 2327 | }); |
| 2328 | } |
| 2329 |
| 2330 | void InstanceV2Impl::setIncomingVideoOutput(std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) { |
| 2331 | _internal->perform([sink](InstanceV2ImplInternal *internal) { |
| 2332 | internal->setIncomingVideoOutput(sink); |
| 2333 | }); |
| 2334 | } |
| 2335 |
| 2336 | void InstanceV2Impl::setAudioInputDevice(std::string id) { |
| 2337 | _internal->perform([id](InstanceV2ImplInternal *internal) { |
| 2338 | internal->setAudioInputDevice(id); |
| 2339 | }); |
| 2340 | } |
| 2341 |
| 2342 | void InstanceV2Impl::setAudioOutputDevice(std::string id) { |
| 2343 | _internal->perform([id](InstanceV2ImplInternal *internal) { |
| 2344 | internal->setAudioOutputDevice(id); |
| 2345 | }); |
| 2346 | } |
| 2347 |
| 2348 | void InstanceV2Impl::setIsLowBatteryLevel(bool isLowBatteryLevel) { |
| 2349 | _internal->perform([isLowBatteryLevel](InstanceV2ImplInternal *internal) { |
| 2350 | internal->setIsLowBatteryLevel(isLowBatteryLevel); |
| 2351 | }); |
| 2352 | } |
| 2353 |
| 2354 | void InstanceV2Impl::setInputVolume(float level) { |
| 2355 | } |
| 2356 |
| 2357 | void InstanceV2Impl::setOutputVolume(float level) { |
| 2358 | } |
| 2359 |
| 2360 | void InstanceV2Impl::setAudioOutputDuckingEnabled(bool enabled) { |
| 2361 | } |
| 2362 |
| 2363 | void InstanceV2Impl::setAudioOutputGainControlEnabled(bool enabled) { |
| 2364 | } |
| 2365 |
| 2366 | void InstanceV2Impl::setEchoCancellationStrength(int strength) { |
| 2367 | } |
| 2368 |
| 2369 | std::vector<std::string> InstanceV2Impl::GetVersions() { |
| 2370 | std::vector<std::string> result; |
| 2371 | result.push_back("7.0.0"); |
| 2372 | result.push_back("8.0.0"); |
| 2373 | result.push_back("9.0.0"); |
| 2374 | return result; |
| 2375 | } |
| 2376 |
| 2377 | int InstanceV2Impl::GetConnectionMaxLayer() { |
| 2378 | return 92; |
| 2379 | } |
| 2380 |
| 2381 | std::string InstanceV2Impl::getLastError() { |
| 2382 | return ""; |
| 2383 | } |
| 2384 |
| 2385 | std::string InstanceV2Impl::getDebugInfo() { |
| 2386 | return ""; |
| 2387 | } |
| 2388 |
| 2389 | int64_t InstanceV2Impl::getPreferredRelayId() { |
| 2390 | return 0; |
| 2391 | } |
| 2392 |
| 2393 | TrafficStats InstanceV2Impl::getTrafficStats() { |
| 2394 | return {}; |
| 2395 | } |
| 2396 |
| 2397 | PersistentState InstanceV2Impl::getPersistentState() { |
| 2398 | return {}; |
| 2399 | } |
| 2400 |
| 2401 | void InstanceV2Impl::stop(std::function<void(FinalState)> completion) { |
| 2402 | std::string debugLog; |
| 2403 | if (_logSink) { |
| 2404 | debugLog = _logSink->result(); |
| 2405 | } |
| 2406 | _internal->perform([completion, debugLog = std::move(debugLog)](InstanceV2ImplInternal *internal) mutable { |
| 2407 | internal->stop([completion, debugLog = std::move(debugLog)](FinalState finalState) mutable { |
| 2408 | finalState.debugLog = debugLog; |
| 2409 | completion(finalState); |
| 2410 | }); |
| 2411 | }); |
| 2412 | } |
| 2413 |
| 2414 | template <> |
| 2415 | bool Register<InstanceV2Impl>() { |
| 2416 | return Meta::RegisterOne<InstanceV2Impl>(); |
| 2417 | } |
| 2418 |
| 2419 | } // namespace tgcalls |
| 2420 |