| 6 | #include "Instance.h" |
| 7 | #include "VideoCaptureInterfaceImpl.h" |
| 8 | #include "VideoCapturerInterface.h" |
| 9 | #include "CodecSelectHelper.h" |
| 10 | #include "Message.h" |
| 11 | #include "platform/PlatformInterface.h" |
| 12 | #include "StaticThreads.h" |
| 13 | #include "GroupNetworkManager.h" |
| 14 |
| 15 | #include "api/audio_codecs/audio_decoder_factory_template.h" |
| 16 | #include "api/audio_codecs/audio_encoder_factory_template.h" |
| 17 | #include "api/audio_codecs/opus/audio_decoder_opus.h" |
| 18 | #include "api/audio_codecs/opus/audio_decoder_multi_channel_opus.h" |
| 19 | #include "api/audio_codecs/opus/audio_encoder_opus.h" |
| 20 | #include "api/audio_codecs/L16/audio_decoder_L16.h" |
| 21 | #include "api/audio_codecs/L16/audio_encoder_L16.h" |
| 22 | #include "api/task_queue/default_task_queue_factory.h" |
| 23 | #include "media/engine/webrtc_media_engine.h" |
| 24 | #include "system_wrappers/include/field_trial.h" |
| 25 | #include "api/video/builtin_video_bitrate_allocator_factory.h" |
| 26 | #include "call/call.h" |
| 27 | #include "modules/rtp_rtcp/source/rtp_utility.h" |
| 28 | #include "api/call/audio_sink.h" |
| 29 | #include "modules/audio_processing/audio_buffer.h" |
| 30 | #include "absl/strings/match.h" |
| 31 | #include "modules/audio_processing/agc2/vad_with_level.h" |
| 32 | #include "pc/channel_manager.h" |
| 33 | #include "media/base/rtp_data_engine.h" |
| 34 | #include "audio/audio_state.h" |
| 35 | #include "modules/audio_coding/neteq/default_neteq_factory.h" |
| 36 | #include "modules/audio_coding/include/audio_coding_module.h" |
| 37 |
| 38 | #include "AudioFrame.h" |
| 39 | #include "ThreadLocalObject.h" |
| 40 | #include "Manager.h" |
| 41 | #include "NetworkManager.h" |
| 42 | #include "VideoCaptureInterfaceImpl.h" |
| 43 | #include "platform/PlatformInterface.h" |
| 44 | #include "LogSinkImpl.h" |
| 45 | #include "CodecSelectHelper.h" |
| 46 | #include "StreamingPart.h" |
| 47 | #include "AudioDeviceHelper.h" |
| 48 |
| 49 | #include <random> |
| 50 | #include <sstream> |
| 51 | #include <iostream> |
| 52 |
| 53 | namespace tgcalls { |
| 54 |
| 55 | namespace { |
| 56 |
| 57 | static int stringToInt(std::string const &string) { |
| 58 | std::stringstream stringStream(string); |
| 59 | int value = 0; |
| 60 | stringStream >> value; |
| 61 | return value; |
| 62 | } |
| 63 |
| 64 | static std::string intToString(int value) { |
| 65 | std::ostringstream stringStream; |
| 66 | stringStream << value; |
| 67 | return stringStream.str(); |
| 68 | } |
| 69 |
| 70 | static std::string uint32ToString(uint32_t value) { |
| 71 | std::ostringstream stringStream; |
| 72 | stringStream << value; |
| 73 | return stringStream.str(); |
| 74 | } |
| 75 |
| 76 | static uint32_t stringToUInt32(std::string const &string) { |
| 77 | std::stringstream stringStream(string); |
| 78 | uint32_t value = 0; |
| 79 | stringStream >> value; |
| 80 | return value; |
| 81 | } |
| 82 |
| 83 | static uint16_t stringToUInt16(std::string const &string) { |
| 84 | std::stringstream stringStream(string); |
| 85 | uint16_t value = 0; |
| 86 | stringStream >> value; |
| 87 | return value; |
| 88 | } |
| 89 |
| 90 | static std::string formatTimestampMillis(int64_t timestamp) { |
| 91 | std::ostringstream stringStream; |
| 92 | stringStream << std::fixed << std::setprecision(3) << (double)timestamp / 1000.0; |
| 93 | return stringStream.str(); |
| 94 | } |
| 95 |
| 96 | static VideoCaptureInterfaceObject *GetVideoCaptureAssumingSameThread(VideoCaptureInterface *videoCapture) { |
| 97 | return videoCapture |
| 98 | ? static_cast<VideoCaptureInterfaceImpl*>(videoCapture)->object()->getSyncAssumingSameThread() |
| 99 | : nullptr; |
| 100 | } |
| 101 |
| 102 | struct OutgoingVideoFormat { |
| 103 | cricket::VideoCodec videoCodec; |
| 104 | cricket::VideoCodec rtxCodec; |
| 105 | }; |
| 106 |
| 107 | static void addDefaultFeedbackParams(cricket::VideoCodec *codec) { |
| 108 | // Don't add any feedback params for RED and ULPFEC. |
| 109 | if (codec->name == cricket::kRedCodecName || codec->name == cricket::kUlpfecCodecName) { |
| 110 | return; |
| 111 | } |
| 112 | codec->AddFeedbackParam(cricket::FeedbackParam(cricket::kRtcpFbParamRemb, cricket::kParamValueEmpty)); |
| 113 | codec->AddFeedbackParam(cricket::FeedbackParam(cricket::kRtcpFbParamTransportCc, cricket::kParamValueEmpty)); |
| 114 | // Don't add any more feedback params for FLEXFEC. |
| 115 | if (codec->name == cricket::kFlexfecCodecName) { |
| 116 | return; |
| 117 | } |
| 118 | codec->AddFeedbackParam(cricket::FeedbackParam(cricket::kRtcpFbParamCcm, cricket::kRtcpFbCcmParamFir)); |
| 119 | codec->AddFeedbackParam(cricket::FeedbackParam(cricket::kRtcpFbParamNack, cricket::kParamValueEmpty)); |
| 120 | codec->AddFeedbackParam(cricket::FeedbackParam(cricket::kRtcpFbParamNack, cricket::kRtcpFbNackParamPli)); |
| 121 | } |
| 122 |
| 123 | static absl::optional<OutgoingVideoFormat> assignPayloadTypes(std::vector<webrtc::SdpVideoFormat> const &formats) { |
| 124 | if (formats.empty()) { |
| 125 | return absl::nullopt; |
| 126 | } |
| 127 |
| 128 | constexpr int kFirstDynamicPayloadType = 100; |
| 129 | constexpr int kLastDynamicPayloadType = 127; |
| 130 |
| 131 | int payload_type = kFirstDynamicPayloadType; |
| 132 |
| 133 | auto result = OutgoingVideoFormat(); |
| 134 |
| 135 | bool codecSelected = false; |
| 136 |
| 137 | for (const auto &format : formats) { |
| 138 | if (codecSelected) { |
| 139 | break; |
| 140 | } |
| 141 |
| 142 | cricket::VideoCodec codec(format); |
| 143 | codec.id = payload_type; |
| 144 | addDefaultFeedbackParams(&codec); |
| 145 |
| 146 | if (!absl::EqualsIgnoreCase(codec.name, cricket::kVp8CodecName)) { |
| 147 | continue; |
| 148 | } |
| 149 |
| 150 | result.videoCodec = codec; |
| 151 | codecSelected = true; |
| 152 |
| 153 | // Increment payload type. |
| 154 | ++payload_type; |
| 155 | if (payload_type > kLastDynamicPayloadType) { |
| 156 | RTC_LOG(LS_ERROR) << "Out of dynamic payload types, skipping the rest."; |
| 157 | break; |
| 158 | } |
| 159 |
| 160 | // Add associated RTX codec for non-FEC codecs. |
| 161 | if (!absl::EqualsIgnoreCase(codec.name, cricket::kUlpfecCodecName) && |
| 162 | !absl::EqualsIgnoreCase(codec.name, cricket::kFlexfecCodecName)) { |
| 163 | result.rtxCodec = cricket::VideoCodec::CreateRtxCodec(payload_type, codec.id); |
| 164 |
| 165 | // Increment payload type. |
| 166 | ++payload_type; |
| 167 | if (payload_type > kLastDynamicPayloadType) { |
| 168 | RTC_LOG(LS_ERROR) << "Out of dynamic payload types, skipping the rest."; |
| 169 | break; |
| 170 | } |
| 171 | } |
| 172 | } |
| 173 | return result; |
| 174 | } |
| 175 |
| 176 | struct VideoSsrcs { |
| 177 | struct SimulcastLayer { |
| 178 | uint32_t ssrc = 0; |
| 179 | uint32_t fidSsrc = 0; |
| 180 |
| 181 | SimulcastLayer(uint32_t ssrc_, uint32_t fidSsrc_) : |
| 182 | ssrc(ssrc_), fidSsrc(fidSsrc_) { |
| 183 | } |
| 184 |
| 185 | SimulcastLayer(const SimulcastLayer &other) : |
| 186 | ssrc(other.ssrc), fidSsrc(other.fidSsrc) { |
| 187 | } |
| 188 | }; |
| 189 |
| 190 | std::vector<SimulcastLayer> simulcastLayers; |
| 191 |
| 192 | VideoSsrcs() { |
| 193 | } |
| 194 |
| 195 | VideoSsrcs(const VideoSsrcs &other) : |
| 196 | simulcastLayers(other.simulcastLayers) { |
| 197 | } |
| 198 | }; |
| 199 |
| 200 | struct ChannelId { |
| 201 | uint32_t networkSsrc = 0; |
| 202 | uint32_t actualSsrc = 0; |
| 203 |
| 204 | ChannelId(uint32_t networkSsrc_, uint32_t actualSsrc_) : |
| 205 | networkSsrc(networkSsrc_), |
| 206 | actualSsrc(actualSsrc_) { |
| 207 | } |
| 208 |
| 209 | explicit ChannelId(uint32_t networkSsrc_) : |
| 210 | networkSsrc(networkSsrc_), |
| 211 | actualSsrc(networkSsrc_) { |
| 212 | } |
| 213 |
| 214 | bool operator <(const ChannelId& rhs) const { |
| 215 | if (networkSsrc != rhs.networkSsrc) { |
| 216 | return networkSsrc < rhs.networkSsrc; |
| 217 | } |
| 218 | return actualSsrc < rhs.actualSsrc; |
| 219 | } |
| 220 |
| 221 | std::string name() { |
| 222 | if (networkSsrc == actualSsrc) { |
| 223 | return uint32ToString(networkSsrc); |
| 224 | } else { |
| 225 | return uint32ToString(networkSsrc) + "to" + uint32ToString(actualSsrc); |
| 226 | } |
| 227 | } |
| 228 | }; |
| 229 |
| 230 |
| 231 | class NetworkInterfaceImpl : public cricket::MediaChannel::NetworkInterface { |
| 232 | public: |
| 233 | NetworkInterfaceImpl(std::function<void(rtc::CopyOnWriteBuffer const *, rtc::SentPacket)> sendPacket) : |
| 234 | _sendPacket(sendPacket) { |
| 235 |
| 236 | } |
| 237 |
| 238 | bool SendPacket(rtc::CopyOnWriteBuffer *packet, const rtc::PacketOptions& options) { |
| 239 | rtc::SentPacket sentPacket(options.packet_id, rtc::TimeMillis(), options.info_signaled_after_sent); |
| 240 | _sendPacket(packet, sentPacket); |
| 241 | return true; |
| 242 | } |
| 243 |
| 244 | bool SendRtcp(rtc::CopyOnWriteBuffer *packet, const rtc::PacketOptions& options) { |
| 245 | rtc::SentPacket sentPacket(options.packet_id, rtc::TimeMillis(), options.info_signaled_after_sent); |
| 246 | _sendPacket(packet, sentPacket); |
| 247 | return true; |
| 248 | } |
| 249 |
| 250 | int SetOption(cricket::MediaChannel::NetworkInterface::SocketType, rtc::Socket::Option, int) { |
| 251 | return -1; |
| 252 | } |
| 253 |
| 254 | private: |
| 255 | std::function<void(rtc::CopyOnWriteBuffer const *, rtc::SentPacket)> _sendPacket; |
| 256 | }; |
| 257 |
| 258 | static const int kVadResultHistoryLength = 8; |
| 259 |
| 260 | class CombinedVad { |
| 261 | private: |
| 262 | webrtc::VadLevelAnalyzer _vadWithLevel; |
| 263 | float _vadResultHistory[kVadResultHistoryLength]; |
| 264 |
| 265 | public: |
| 266 | CombinedVad() { |
| 267 | for (float & i : _vadResultHistory) { |
| 268 | i = 0.0f; |
| 269 | } |
| 270 | } |
| 271 |
| 272 | ~CombinedVad() = default; |
| 273 |
| 274 | bool update(webrtc::AudioBuffer *buffer) { |
| 275 | float speech_probability; |
| 276 | if (buffer) { |
| 277 | webrtc::AudioFrameView<float> frameView(buffer->channels(), buffer->num_channels(), buffer->num_frames()); |
| 278 | auto result = _vadWithLevel.AnalyzeFrame(frameView); |
| 279 | speech_probability = result.speech_probability; |
| 280 | } else { |
| 281 | speech_probability = std::min(1.0f, _vadResultHistory[kVadResultHistoryLength - 1] * 1.2f); |
| 282 | } |
| 283 | for (int i = 1; i < kVadResultHistoryLength; i++) { |
| 284 | _vadResultHistory[i - 1] = _vadResultHistory[i]; |
| 285 | } |
| 286 | _vadResultHistory[kVadResultHistoryLength - 1] = speech_probability; |
| 287 |
| 288 | float movingAverage = 0.0f; |
| 289 | for (float i : _vadResultHistory) { |
| 290 | movingAverage += i; |
| 291 | } |
| 292 | movingAverage /= (float)kVadResultHistoryLength; |
| 293 |
| 294 | bool vadResult = false; |
| 295 | if (movingAverage > 0.8f) { |
| 296 | vadResult = true; |
| 297 | } |
| 298 |
| 299 | return vadResult; |
| 300 | } |
| 301 | }; |
| 302 |
| 303 | class AudioSinkImpl: public webrtc::AudioSinkInterface { |
| 304 | public: |
| 305 | struct Update { |
| 306 | float level = 0.0f; |
| 307 | std::shared_ptr<webrtc::AudioBuffer> buffer; |
| 308 | std::shared_ptr<CombinedVad> vad; |
| 309 |
| 310 | Update(float level_, webrtc::AudioBuffer *buffer_, std::shared_ptr<CombinedVad> vad_) : |
| 311 | level(level_), buffer(std::shared_ptr<webrtc::AudioBuffer>(buffer_)), vad(vad_) { |
| 312 | } |
| 313 | }; |
| 314 |
| 315 | public: |
| 316 | AudioSinkImpl(std::function<void(Update)> update, |
| 317 | ChannelId channel_id, std::function<void(uint32_t, const AudioFrame &)> onAudioFrame) : |
| 318 | _update(update), _channel_id(channel_id), _onAudioFrame(std::move(onAudioFrame)) { |
| 319 | _vad = std::make_shared<CombinedVad>(); |
| 320 | } |
| 321 |
| 322 | virtual ~AudioSinkImpl() { |
| 323 | } |
| 324 |
| 325 | virtual void OnData(const Data& audio) override { |
| 326 | if (_onAudioFrame) { |
| 327 | AudioFrame frame; |
| 328 | frame.audio_samples = audio.data; |
| 329 | frame.num_samples = audio.samples_per_channel; |
| 330 | frame.bytes_per_sample = 2; |
| 331 | frame.num_channels = audio.channels; |
| 332 | frame.samples_per_sec = audio.sample_rate; |
| 333 | frame.elapsed_time_ms = 0; |
| 334 | frame.ntp_time_ms = 0; |
| 335 | _onAudioFrame(_channel_id.actualSsrc, frame); |
| 336 | } |
| 337 | if (audio.channels == 1) { |
| 338 | const auto samples = (const int16_t *) audio.data; |
| 339 | int numberOfSamplesInFrame = (int)audio.samples_per_channel; |
| 340 |
| 341 | for (int i = 0; i < numberOfSamplesInFrame; i++) { |
| 342 | int16_t sample = samples[i]; |
| 343 | if (sample < 0) { |
| 344 | sample = -sample; |
| 345 | } |
| 346 | if (_peak < sample) { |
| 347 | _peak = sample; |
| 348 | } |
| 349 | _peakCount += 1; |
| 350 | } |
| 351 |
| 352 | if (_peakCount >= 1200) { |
| 353 | float level = ((float)(_peak)) / 4000.0f; |
| 354 | _peak = 0; |
| 355 | _peakCount = 0; |
| 356 |
| 357 | webrtc::AudioBuffer *buffer; |
| 358 | if (!_skipNextSampleProcess) { |
| 359 | buffer = new webrtc::AudioBuffer(audio.sample_rate, 1, 48000, 1, 48000, 1); |
| 360 | webrtc::StreamConfig config(audio.sample_rate, 1); |
| 361 | buffer->CopyFrom(samples, config); |
| 362 | } else { |
| 363 | buffer = nullptr; |
| 364 | } |
| 365 |
| 366 | _update(Update(level, buffer, _vad)); |
| 367 | _skipNextSampleProcess = !_skipNextSampleProcess; |
| 368 | } |
| 369 | } |
| 370 | } |
| 371 |
| 372 | private: |
| 373 | std::function<void(Update)> _update; |
| 374 | ChannelId _channel_id; |
| 375 | std::function<void(uint32_t, const AudioFrame &)> _onAudioFrame; |
| 376 | std::shared_ptr<CombinedVad> _vad; |
| 377 |
| 378 | int _peakCount = 0; |
| 379 | uint16_t _peak = 0; |
| 380 | bool _skipNextSampleProcess = false; |
| 381 | }; |
| 382 |
| 383 | class VideoSinkImpl : public rtc::VideoSinkInterface<webrtc::VideoFrame> { |
| 384 | public: |
| 385 | VideoSinkImpl() { |
| 386 | } |
| 387 |
| 388 | virtual ~VideoSinkImpl() { |
| 389 | } |
| 390 |
| 391 | virtual void OnFrame(const webrtc::VideoFrame& frame) override { |
| 392 | _lastFrame = frame; |
| 393 | for (int i = (int)(_sinks.size()) - 1; i >= 0; i--) { |
| 394 | auto strong = _sinks[i].lock(); |
| 395 | if (!strong) { |
| 396 | _sinks.erase(_sinks.begin() + i); |
| 397 | } else { |
| 398 | strong->OnFrame(frame); |
| 399 | } |
| 400 | } |
| 401 | } |
| 402 |
| 403 | virtual void OnDiscardedFrame() override { |
| 404 | for (int i = (int)(_sinks.size()) - 1; i >= 0; i--) { |
| 405 | auto strong = _sinks[i].lock(); |
| 406 | if (!strong) { |
| 407 | _sinks.erase(_sinks.begin() + i); |
| 408 | } else { |
| 409 | strong->OnDiscardedFrame(); |
| 410 | } |
| 411 | } |
| 412 | } |
| 413 |
| 414 | void addSink(std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> impl) { |
| 415 | _sinks.push_back(impl); |
| 416 | if (_lastFrame) { |
| 417 | auto strong = impl.lock(); |
| 418 | if (strong) { |
| 419 | strong->OnFrame(_lastFrame.value()); |
| 420 | } |
| 421 | } |
| 422 | } |
| 423 |
| 424 | private: |
| 425 | std::vector<std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>>> _sinks; |
| 426 | absl::optional<webrtc::VideoFrame> _lastFrame; |
| 427 | }; |
| 428 |
| 429 | class AudioCaptureAnalyzer : public webrtc::CustomAudioAnalyzer { |
| 430 | private: |
| 431 | void Initialize(int sample_rate_hz, int num_channels) override { |
| 432 |
| 433 | } |
| 434 |
| 435 | void Analyze(const webrtc::AudioBuffer* buffer) override { |
| 436 | if (!buffer) { |
| 437 | return; |
| 438 | } |
| 439 | if (buffer->num_channels() != 1) { |
| 440 | return; |
| 441 | } |
| 442 |
| 443 | float peak = 0; |
| 444 | int peakCount = 0; |
| 445 | const float *samples = buffer->channels_const()[0]; |
| 446 | for (int i = 0; i < buffer->num_frames(); i++) { |
| 447 | float sample = samples[i]; |
| 448 | if (sample < 0) { |
| 449 | sample = -sample; |
| 450 | } |
| 451 | if (peak < sample) { |
| 452 | peak = sample; |
| 453 | } |
| 454 | peakCount += 1; |
| 455 | } |
| 456 |
| 457 | bool vadStatus = _vad.update((webrtc::AudioBuffer *)buffer); |
| 458 |
| 459 | _peakCount += peakCount; |
| 460 | if (_peak < peak) { |
| 461 | _peak = peak; |
| 462 | } |
| 463 | if (_peakCount >= 1200) { |
| 464 | float level = _peak / 4000.0f; |
| 465 | _peak = 0; |
| 466 | _peakCount = 0; |
| 467 |
| 468 | _updated(GroupLevelValue{ |
| 469 | level, |
| 470 | vadStatus, |
| 471 | }); |
| 472 | } |
| 473 | } |
| 474 |
| 475 | std::string ToString() const override { |
| 476 | return "analyzing"; |
| 477 | } |
| 478 |
| 479 | private: |
| 480 | std::function<void(GroupLevelValue const &)> _updated; |
| 481 |
| 482 | CombinedVad _vad; |
| 483 | int32_t _peakCount = 0; |
| 484 | float _peak = 0; |
| 485 |
| 486 | public: |
| 487 | AudioCaptureAnalyzer(std::function<void(GroupLevelValue const &)> updated) : |
| 488 | _updated(updated) { |
| 489 | } |
| 490 |
| 491 | virtual ~AudioCaptureAnalyzer() = default; |
| 492 | }; |
| 493 | class IncomingAudioChannel : public sigslot::has_slots<> { |
| 494 | public: |
| 495 | IncomingAudioChannel( |
| 496 | cricket::ChannelManager *channelManager, |
| 497 | webrtc::Call *call, |
| 498 | webrtc::RtpTransport *rtpTransport, |
| 499 | rtc::UniqueRandomIdGenerator *randomIdGenerator, |
| 500 | bool isRawPcm, |
| 501 | ChannelId ssrc, |
| 502 | std::function<void(AudioSinkImpl::Update)> &&onAudioLevelUpdated, |
| 503 | std::function<void(uint32_t, const AudioFrame &)> onAudioFrame, |
| 504 | Threads &threads) : |
| 505 | _ssrc(ssrc), |
| 506 | _channelManager(channelManager), |
| 507 | _call(call) { |
| 508 | _creationTimestamp = rtc::TimeMillis(); |
| 509 |
| 510 | cricket::AudioOptions audioOptions; |
| 511 | audioOptions.echo_cancellation = true; |
| 512 | audioOptions.noise_suppression = true; |
| 513 | audioOptions.audio_jitter_buffer_fast_accelerate = true; |
| 514 | audioOptions.audio_jitter_buffer_min_delay_ms = 50; |
| 515 |
| 516 | std::string streamId = std::string("stream") + ssrc.name(); |
| 517 |
| 518 | _audioChannel = _channelManager->CreateVoiceChannel(call, cricket::MediaConfig(), rtpTransport, threads.getMediaThread(), std::string("audio") + uint32ToString(ssrc.networkSsrc), false, GroupNetworkManager::getDefaulCryptoOptions(), randomIdGenerator, audioOptions); |
| 519 |
| 520 | const uint8_t opusMinBitrateKbps = 32; |
| 521 | const uint8_t opusMaxBitrateKbps = 32; |
| 522 | const uint8_t opusStartBitrateKbps = 32; |
| 523 | const uint8_t opusPTimeMs = 120; |
| 524 |
| 525 | cricket::AudioCodec opusCodec(111, "opus", 48000, 0, 2); |
| 526 | opusCodec.SetParam(cricket::kCodecParamMinBitrate, opusMinBitrateKbps); |
| 527 | opusCodec.SetParam(cricket::kCodecParamStartBitrate, opusStartBitrateKbps); |
| 528 | opusCodec.SetParam(cricket::kCodecParamMaxBitrate, opusMaxBitrateKbps); |
| 529 | opusCodec.SetParam(cricket::kCodecParamUseInbandFec, 1); |
| 530 | opusCodec.SetParam(cricket::kCodecParamPTime, opusPTimeMs); |
| 531 |
| 532 | cricket::AudioCodec pcmCodec(112, "l16", 48000, 0, 1); |
| 533 |
| 534 | auto outgoingAudioDescription = std::make_unique<cricket::AudioContentDescription>(); |
| 535 | if (!isRawPcm) { |
| 536 | outgoingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAudioLevelUri, 1)); |
| 537 | outgoingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAbsSendTimeUri, 2)); |
| 538 | outgoingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kTransportSequenceNumberUri, 3)); |
| 539 | } |
| 540 | outgoingAudioDescription->set_rtcp_mux(true); |
| 541 | outgoingAudioDescription->set_rtcp_reduced_size(true); |
| 542 | outgoingAudioDescription->set_direction(webrtc::RtpTransceiverDirection::kRecvOnly); |
| 543 | outgoingAudioDescription->set_codecs({ opusCodec, pcmCodec }); |
| 544 |
| 545 | auto incomingAudioDescription = std::make_unique<cricket::AudioContentDescription>(); |
| 546 | if (!isRawPcm) { |
| 547 | incomingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAudioLevelUri, 1)); |
| 548 | incomingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAbsSendTimeUri, 2)); |
| 549 | incomingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kTransportSequenceNumberUri, 3)); |
| 550 | } |
| 551 | incomingAudioDescription->set_rtcp_mux(true); |
| 552 | incomingAudioDescription->set_rtcp_reduced_size(true); |
| 553 | incomingAudioDescription->set_direction(webrtc::RtpTransceiverDirection::kSendOnly); |
| 554 | incomingAudioDescription->set_codecs({ opusCodec, pcmCodec }); |
| 555 | cricket::StreamParams streamParams = cricket::StreamParams::CreateLegacy(ssrc.networkSsrc); |
| 556 | streamParams.set_stream_ids({ streamId }); |
| 557 | incomingAudioDescription->AddStream(streamParams); |
| 558 |
| 559 | _audioChannel->SetPayloadTypeDemuxingEnabled(false); |
| 560 | _audioChannel->SetLocalContent(outgoingAudioDescription.get(), webrtc::SdpType::kOffer, nullptr); |
| 561 | _audioChannel->SetRemoteContent(incomingAudioDescription.get(), webrtc::SdpType::kAnswer, nullptr); |
| 562 |
| 563 | outgoingAudioDescription.reset(); |
| 564 | incomingAudioDescription.reset(); |
| 565 |
| 566 | std::unique_ptr<AudioSinkImpl> audioLevelSink(new AudioSinkImpl([onAudioLevelUpdated = std::move(onAudioLevelUpdated)](AudioSinkImpl::Update update) { |
| 567 | onAudioLevelUpdated(update); |
| 568 | }, _ssrc, std::move(onAudioFrame))); |
| 569 | _audioChannel->media_channel()->SetRawAudioSink(ssrc.networkSsrc, std::move(audioLevelSink)); |
| 570 |
| 571 | _audioChannel->SignalSentPacket().connect(this, &IncomingAudioChannel::OnSentPacket_w); |
| 572 | //_audioChannel->UpdateRtpTransport(nullptr); |
| 573 |
| 574 | _audioChannel->Enable(true); |
| 575 | } |
| 576 |
| 577 | ~IncomingAudioChannel() { |
| 578 | _audioChannel->SignalSentPacket().disconnect(this); |
| 579 | _audioChannel->Enable(false); |
| 580 | _channelManager->DestroyVoiceChannel(_audioChannel); |
| 581 | _audioChannel = nullptr; |
| 582 | } |
| 583 |
| 584 | void setVolume(double value) { |
| 585 | _audioChannel->media_channel()->SetOutputVolume(_ssrc.networkSsrc, value); |
| 586 | } |
| 587 |
| 588 | void updateActivity() { |
| 589 | _activityTimestamp = rtc::TimeMillis(); |
| 590 | } |
| 591 |
| 592 | int64_t getActivity() { |
| 593 | return _activityTimestamp; |
| 594 | } |
| 595 |
| 596 | private: |
| 597 | void OnSentPacket_w(const rtc::SentPacket& sent_packet) { |
| 598 | _call->OnSentPacket(sent_packet); |
| 599 | } |
| 600 |
| 601 | private: |
| 602 | ChannelId _ssrc; |
| 603 | // Memory is managed by _channelManager |
| 604 | cricket::VoiceChannel *_audioChannel = nullptr; |
| 605 | // Memory is managed externally |
| 606 | cricket::ChannelManager *_channelManager = nullptr; |
| 607 | webrtc::Call *_call = nullptr; |
| 608 | int64_t _creationTimestamp = 0; |
| 609 | int64_t _activityTimestamp = 0; |
| 610 | }; |
| 611 |
| 612 | class IncomingVideoChannel : public sigslot::has_slots<> { |
| 613 | public: |
| 614 | IncomingVideoChannel( |
| 615 | cricket::ChannelManager *channelManager, |
| 616 | webrtc::Call *call, |
| 617 | webrtc::RtpTransport *rtpTransport, |
| 618 | rtc::UniqueRandomIdGenerator *randomIdGenerator, |
| 619 | std::vector<webrtc::SdpVideoFormat> const &availableVideoFormats, |
| 620 | GroupParticipantDescription const &description, |
| 621 | Threads &threads) : |
| 622 | _channelManager(channelManager), |
| 623 | _call(call) { |
| 624 | _videoSink.reset(new VideoSinkImpl()); |
| 625 |
| 626 | std::string streamId = std::string("stream") + uint32ToString(description.audioSsrc); |
| 627 |
| 628 | _videoBitrateAllocatorFactory = webrtc::CreateBuiltinVideoBitrateAllocatorFactory(); |
| 629 |
| 630 | _videoChannel = _channelManager->CreateVideoChannel(call, cricket::MediaConfig(), rtpTransport, threads.getMediaThread(), std::string("video") + uint32ToString(description.audioSsrc), false, GroupNetworkManager::getDefaulCryptoOptions(), randomIdGenerator, cricket::VideoOptions(), _videoBitrateAllocatorFactory.get()); |
| 631 |
| 632 | auto payloadTypes = assignPayloadTypes(availableVideoFormats); |
| 633 | if (!payloadTypes.has_value()) { |
| 634 | return; |
| 635 | } |
| 636 |
| 637 | auto outgoingVideoDescription = std::make_unique<cricket::VideoContentDescription>(); |
| 638 | outgoingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAbsSendTimeUri, 2)); |
| 639 | outgoingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kTransportSequenceNumberUri, 3)); |
| 640 | outgoingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kVideoRotationUri, 13)); |
| 641 | outgoingVideoDescription->set_rtcp_mux(true); |
| 642 | outgoingVideoDescription->set_rtcp_reduced_size(true); |
| 643 | outgoingVideoDescription->set_direction(webrtc::RtpTransceiverDirection::kRecvOnly); |
| 644 | outgoingVideoDescription->set_codecs({ payloadTypes->videoCodec, payloadTypes->rtxCodec }); |
| 645 |
| 646 | cricket::StreamParams videoRecvStreamParams; |
| 647 |
| 648 | std::vector<uint32_t> allSsrcs; |
| 649 | for (const auto &group : description.videoSourceGroups) { |
| 650 | for (auto ssrc : group.ssrcs) { |
| 651 | if (std::find(allSsrcs.begin(), allSsrcs.end(), ssrc) == allSsrcs.end()) { |
| 652 | allSsrcs.push_back(ssrc); |
| 653 | } |
| 654 | } |
| 655 |
| 656 | if (group.semantics == "SIM") { |
| 657 | if (_mainVideoSsrc == 0) { |
| 658 | _mainVideoSsrc = group.ssrcs[0]; |
| 659 | } |
| 660 | } |
| 661 |
| 662 | cricket::SsrcGroup parsedGroup(group.semantics, group.ssrcs); |
| 663 | videoRecvStreamParams.ssrc_groups.push_back(parsedGroup); |
| 664 | } |
| 665 | videoRecvStreamParams.ssrcs = allSsrcs; |
| 666 |
| 667 | if (_mainVideoSsrc == 0) { |
| 668 | if (description.videoSourceGroups.size() == 1) { |
| 669 | _mainVideoSsrc = description.videoSourceGroups[0].ssrcs[0]; |
| 670 | } |
| 671 | } |
| 672 |
| 673 | videoRecvStreamParams.cname = "cname"; |
| 674 | videoRecvStreamParams.set_stream_ids({ streamId }); |
| 675 |
| 676 | auto incomingVideoDescription = std::make_unique<cricket::VideoContentDescription>(); |
| 677 | incomingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAbsSendTimeUri, 2)); |
| 678 | incomingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kTransportSequenceNumberUri, 3)); |
| 679 | incomingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kVideoRotationUri, 13)); |
| 680 | incomingVideoDescription->set_rtcp_mux(true); |
| 681 | incomingVideoDescription->set_rtcp_reduced_size(true); |
| 682 | incomingVideoDescription->set_direction(webrtc::RtpTransceiverDirection::kSendOnly); |
| 683 | incomingVideoDescription->set_codecs({ payloadTypes->videoCodec, payloadTypes->rtxCodec }); |
| 684 |
| 685 | incomingVideoDescription->AddStream(videoRecvStreamParams); |
| 686 |
| 687 | _videoChannel->SetPayloadTypeDemuxingEnabled(false); |
| 688 | _videoChannel->SetLocalContent(outgoingVideoDescription.get(), webrtc::SdpType::kOffer, nullptr); |
| 689 | _videoChannel->SetRemoteContent(incomingVideoDescription.get(), webrtc::SdpType::kAnswer, nullptr); |
| 690 |
| 691 | _videoChannel->media_channel()->SetSink(_mainVideoSsrc, _videoSink.get()); |
| 692 |
| 693 | _videoChannel->SignalSentPacket().connect(this, &IncomingVideoChannel::OnSentPacket_w); |
| 694 | //_videoChannel->UpdateRtpTransport(nullptr); |
| 695 |
| 696 | _videoChannel->Enable(true); |
| 697 | } |
| 698 |
| 699 | ~IncomingVideoChannel() { |
| 700 | _videoChannel->Enable(false); |
| 701 | _channelManager->DestroyVideoChannel(_videoChannel); |
| 702 | _videoChannel = nullptr; |
| 703 | } |
| 704 |
| 705 | void addSink(std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> impl) { |
| 706 | _videoSink->addSink(impl); |
| 707 | } |
| 708 |
| 709 | private: |
| 710 | void OnSentPacket_w(const rtc::SentPacket& sent_packet) { |
| 711 | _call->OnSentPacket(sent_packet); |
| 712 | } |
| 713 |
| 714 | private: |
| 715 | uint32_t _mainVideoSsrc = 0; |
| 716 | std::unique_ptr<VideoSinkImpl> _videoSink; |
| 717 | std::vector<GroupJoinPayloadVideoSourceGroup> _ssrcGroups; |
| 718 | std::unique_ptr<webrtc::VideoBitrateAllocatorFactory> _videoBitrateAllocatorFactory; |
| 719 | // Memory is managed by _channelManager |
| 720 | cricket::VideoChannel *_videoChannel; |
| 721 | // Memory is managed externally |
| 722 | cricket::ChannelManager *_channelManager = nullptr; |
| 723 | webrtc::Call *_call = nullptr; |
| 724 | }; |
| 725 |
| 726 | struct SsrcMappingInfo { |
| 727 | uint32_t ssrc = 0; |
| 728 | bool isVideo = false; |
| 729 | std::string endpointId; |
| 730 | }; |
| 731 |
| 732 | class MissingSsrcPacketBuffer { |
| 733 | public: |
| 734 | MissingSsrcPacketBuffer(int limit) : |
| 735 | _limit(limit) { |
| 736 | } |
| 737 |
| 738 | ~MissingSsrcPacketBuffer() { |
| 739 | } |
| 740 |
| 741 | void add(uint32_t ssrc, rtc::CopyOnWriteBuffer const &packet) { |
| 742 | if (_packets.size() == _limit) { |
| 743 | _packets.erase(_packets.begin()); |
| 744 | } |
| 745 | _packets.push_back(std::make_pair(ssrc, packet)); |
| 746 | } |
| 747 |
| 748 | std::vector<rtc::CopyOnWriteBuffer> get(uint32_t ssrc) { |
| 749 | std::vector<rtc::CopyOnWriteBuffer> result; |
| 750 | for (auto it = _packets.begin(); it != _packets.end(); ) { |
| 751 | if (it->first == ssrc) { |
| 752 | result.push_back(it->second); |
| 753 | _packets.erase(it); |
| 754 | } else { |
| 755 | it++; |
| 756 | } |
| 757 | } |
| 758 | return result; |
| 759 | } |
| 760 |
| 761 | private: |
| 762 | int _limit = 0; |
| 763 | std::vector<std::pair<uint32_t, rtc::CopyOnWriteBuffer>> _packets; |
| 764 |
| 765 | }; |
| 766 |
| 767 | class RequestedBroadcastPart { |
| 768 | public: |
| 769 | int64_t timestamp = 0; |
| 770 | std::shared_ptr<BroadcastPartTask> task; |
| 771 |
| 772 | explicit RequestedBroadcastPart(int64_t timestamp_, std::shared_ptr<BroadcastPartTask> task_) : |
| 773 | timestamp(timestamp_), task(task_) { |
| 774 | } |
| 775 | }; |
| 776 |
| 777 | struct DecodedBroadcastPart { |
| 778 | struct DecodedBroadcastPartChannel { |
| 779 | uint32_t ssrc = 0; |
| 780 | std::vector<int16_t> pcmData; |
| 781 | }; |
| 782 |
| 783 | DecodedBroadcastPart(int numSamples_, std::vector<DecodedBroadcastPartChannel> &&_channels) : |
| 784 | numSamples(numSamples_), channels(std::move(_channels)) { |
| 785 | } |
| 786 |
| 787 | int numSamples = 0; |
| 788 | std::vector<DecodedBroadcastPartChannel> channels; |
| 789 | }; |
| 790 |
| 791 | } // namespace |
| 792 |
| 793 | class GroupInstanceCustomInternal : public sigslot::has_slots<>, public std::enable_shared_from_this<GroupInstanceCustomInternal> { |
| 794 | public: |
| 795 | GroupInstanceCustomInternal(GroupInstanceDescriptor &&descriptor, std::shared_ptr<Threads> threads) : |
| 796 | _threads(std::move(threads)), |
| 797 | _networkStateUpdated(descriptor.networkStateUpdated), |
| 798 | _audioLevelsUpdated(descriptor.audioLevelsUpdated), |
| 799 | _onAudioFrame(descriptor.onAudioFrame), |
| 800 | _incomingVideoSourcesUpdated(descriptor.incomingVideoSourcesUpdated), |
| 801 | _participantDescriptionsRequired(descriptor.participantDescriptionsRequired), |
| 802 | _requestBroadcastPart(descriptor.requestBroadcastPart), |
| 803 | _videoCapture(descriptor.videoCapture), |
| 804 | _eventLog(std::make_unique<webrtc::RtcEventLogNull>()), |
| 805 | _taskQueueFactory(webrtc::CreateDefaultTaskQueueFactory()), |
| 806 | _createAudioDeviceModule(descriptor.createAudioDeviceModule), |
| 807 | _initialInputDeviceId(std::move(descriptor.initialInputDeviceId)), |
| 808 | _initialOutputDeviceId(std::move(descriptor.initialOutputDeviceId)), |
| 809 | _missingPacketBuffer(100), |
| 810 | _platformContext(descriptor.platformContext) { |
| 811 | assert(_threads->getMediaThread()->IsCurrent()); |
| 812 |
| 813 | auto generator = std::mt19937(std::random_device()()); |
| 814 | auto distribution = std::uniform_int_distribution<uint32_t>(); |
| 815 | do { |
| 816 | _outgoingAudioSsrc = distribution(generator) & 0x7fffffffU; |
| 817 | } while (!_outgoingAudioSsrc); |
| 818 |
| 819 | uint32_t outgoingVideoSsrcBase = _outgoingAudioSsrc + 1; |
| 820 | int numVideoSimulcastLayers = 2; |
| 821 | for (int layerIndex = 0; layerIndex < numVideoSimulcastLayers; layerIndex++) { |
| 822 | _outgoingVideoSsrcs.simulcastLayers.push_back(VideoSsrcs::SimulcastLayer(outgoingVideoSsrcBase + layerIndex * 2 + 0, outgoingVideoSsrcBase + layerIndex * 2 + 1)); |
| 823 | } |
| 824 | } |
| 825 |
| 826 | ~GroupInstanceCustomInternal() { |
| 827 | _call->SignalChannelNetworkState(webrtc::MediaType::AUDIO, webrtc::kNetworkDown); |
| 828 | _call->SignalChannelNetworkState(webrtc::MediaType::VIDEO, webrtc::kNetworkDown); |
| 829 |
| 830 | _incomingAudioChannels.clear(); |
| 831 | _incomingVideoChannels.clear(); |
| 832 |
| 833 | destroyOutgoingAudioChannel(); |
| 834 |
| 835 | if (_outgoingVideoChannel) { |
| 836 | _outgoingVideoChannel->SignalSentPacket().disconnect(this); |
| 837 | _outgoingVideoChannel->media_channel()->SetVideoSend(_outgoingVideoSsrcs.simulcastLayers[0].ssrc, nullptr, nullptr); |
| 838 | _outgoingVideoChannel->Enable(false); |
| 839 | _channelManager->DestroyVideoChannel(_outgoingVideoChannel); |
| 840 | _outgoingVideoChannel = nullptr; |
| 841 | } |
| 842 |
| 843 | _channelManager = nullptr; |
| 844 | _audioDeviceModule = nullptr; |
| 845 | } |
| 846 |
| 847 | void start() { |
| 848 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 849 |
| 850 | webrtc::field_trial::InitFieldTrialsFromString( |
| 851 | "WebRTC-Audio-Allocation/min:32kbps,max:32kbps/" |
| 852 | "WebRTC-Audio-OpusMinPacketLossRate/Enabled-1/" |
| 853 | ); |
| 854 |
| 855 | _networkManager.reset(new ThreadLocalObject<GroupNetworkManager>(_threads->getNetworkThread(), [weak, threads = _threads] () mutable { |
| 856 | return new GroupNetworkManager( |
| 857 | [=](const GroupNetworkManager::State &state) { |
| 858 | threads->getMediaThread()->PostTask(RTC_FROM_HERE, [=] { |
| 859 | const auto strong = weak.lock(); |
| 860 | if (!strong) { |
| 861 | return; |
| 862 | } |
| 863 | strong->setIsRtcConnected(state.isReadyToSendData); |
| 864 | }); |
| 865 | }, |
| 866 | [=](rtc::CopyOnWriteBuffer const &message, bool isUnresolved) { |
| 867 | threads->getMediaThread()->PostTask(RTC_FROM_HERE, [weak, message, isUnresolved]() mutable { |
| 868 | if (const auto strong = weak.lock()) { |
| 869 | strong->receivePacket(message, isUnresolved); |
| 870 | } |
| 871 | }); |
| 872 | }, |
| 873 | [=](rtc::CopyOnWriteBuffer const &message, int64_t timestamp) { |
| 874 | threads->getMediaThread()->PostTask(RTC_FROM_HERE, [weak, message, timestamp]() mutable { |
| 875 | if (const auto strong = weak.lock()) { |
| 876 | strong->receiveRtcpPacket(message, timestamp); |
| 877 | } |
| 878 | }); |
| 879 | }, |
| 880 | [=](bool isDataChannelOpen) { |
| 881 | threads->getMediaThread()->PostTask(RTC_FROM_HERE, [weak, isDataChannelOpen]() mutable { |
| 882 | if (const auto strong = weak.lock()) { |
| 883 | strong->updateIsDataChannelOpen(isDataChannelOpen); |
| 884 | } |
| 885 | }); |
| 886 | }, |
| 887 | [=](std::string const &message) { |
| 888 | threads->getMediaThread()->PostTask(RTC_FROM_HERE, [weak, message]() mutable { |
| 889 | if (const auto strong = weak.lock()) { |
| 890 | } |
| 891 | }); |
| 892 | }, threads); |
| 893 | })); |
| 894 |
| 895 | PlatformInterface::SharedInstance()->configurePlatformAudio(); |
| 896 |
| 897 | cricket::MediaEngineDependencies mediaDeps; |
| 898 | mediaDeps.task_queue_factory = _taskQueueFactory.get(); |
| 899 | mediaDeps.audio_encoder_factory = webrtc::CreateAudioEncoderFactory<webrtc::AudioEncoderOpus, webrtc::AudioEncoderL16>(); |
| 900 | mediaDeps.audio_decoder_factory = webrtc::CreateAudioDecoderFactory<webrtc::AudioDecoderOpus, webrtc::AudioDecoderL16>(); |
| 901 |
| 902 | mediaDeps.video_encoder_factory = PlatformInterface::SharedInstance()->makeVideoEncoderFactory(_platformContext); |
| 903 | mediaDeps.video_decoder_factory = PlatformInterface::SharedInstance()->makeVideoDecoderFactory(_platformContext); |
| 904 |
| 905 | auto analyzer = new AudioCaptureAnalyzer([weak, threads = _threads](GroupLevelValue const &level) { |
| 906 | threads->getProcessThread()->PostTask(RTC_FROM_HERE, [weak, level](){ |
| 907 | auto strong = weak.lock(); |
| 908 | if (!strong) { |
| 909 | return; |
| 910 | } |
| 911 | strong->_myAudioLevel = level; |
| 912 | }); |
| 913 | }); |
| 914 |
| 915 | webrtc::AudioProcessingBuilder builder; |
| 916 | builder.SetCaptureAnalyzer(std::unique_ptr<AudioCaptureAnalyzer>(analyzer)); |
| 917 |
| 918 | mediaDeps.audio_processing = builder.Create(); |
| 919 |
| 920 | _audioDeviceModule = createAudioDeviceModule(); |
| 921 | if (!_audioDeviceModule) { |
| 922 | return; |
| 923 | } |
| 924 | mediaDeps.adm = _audioDeviceModule; |
| 925 |
| 926 | _availableVideoFormats = mediaDeps.video_encoder_factory->GetSupportedFormats(); |
| 927 |
| 928 | std::unique_ptr<cricket::MediaEngineInterface> mediaEngine = cricket::CreateMediaEngine(std::move(mediaDeps)); |
| 929 |
| 930 | _channelManager.reset(new cricket::ChannelManager(std::move(mediaEngine), std::make_unique<cricket::RtpDataEngine>(), _threads->getMediaThread(), _threads->getNetworkThread())); |
| 931 | _channelManager->Init(); |
| 932 |
| 933 | setAudioInputDevice(_initialInputDeviceId); |
| 934 | setAudioOutputDevice(_initialOutputDeviceId); |
| 935 |
| 936 | webrtc::Call::Config callConfig(_eventLog.get()); |
| 937 | callConfig.task_queue_factory = _taskQueueFactory.get(); |
| 938 | callConfig.trials = &_fieldTrials; |
| 939 | callConfig.audio_state = _channelManager->media_engine()->voice().GetAudioState(); |
| 940 | _call.reset(webrtc::Call::Create(callConfig)); |
| 941 |
| 942 | _uniqueRandomIdGenerator.reset(new rtc::UniqueRandomIdGenerator()); |
| 943 |
| 944 | _threads->getNetworkThread()->Invoke<void>(RTC_FROM_HERE, [this]() { |
| 945 | _rtpTransport = _networkManager->getSyncAssumingSameThread()->getRtpTransport(); |
| 946 | }); |
| 947 |
| 948 | _videoBitrateAllocatorFactory = webrtc::CreateBuiltinVideoBitrateAllocatorFactory(); |
| 949 |
| 950 | //_outgoingVideoChannel = _channelManager->CreateVideoChannel(_call.get(), cricket::MediaConfig(), _rtpTransport, _threads->getMediaThread(), "1", false, GroupNetworkManager::getDefaulCryptoOptions(), _uniqueRandomIdGenerator.get(), cricket::VideoOptions(), _videoBitrateAllocatorFactory.get()); |
| 951 |
| 952 | configureSendVideo(); |
| 953 |
| 954 | if (_outgoingVideoChannel) { |
| 955 | _outgoingVideoChannel->SignalSentPacket().connect(this, &GroupInstanceCustomInternal::OnSentPacket_w); |
| 956 | //_outgoingVideoChannel->UpdateRtpTransport(nullptr); |
| 957 | } |
| 958 |
| 959 | beginLevelsTimer(50); |
| 960 |
| 961 | if (_videoCapture) { |
| 962 | setVideoCapture(_videoCapture, [](GroupJoinPayload) {}, true); |
| 963 | } |
| 964 |
| 965 | adjustBitratePreferences(true); |
| 966 |
| 967 | addIncomingAudioChannel("_dummy", ChannelId(1), true); |
| 968 |
| 969 | beginNetworkStatusTimer(0); |
| 970 | } |
| 971 |
| 972 | void destroyOutgoingAudioChannel() { |
| 973 | if (!_outgoingAudioChannel) { |
| 974 | return; |
| 975 | } |
| 976 |
| 977 | _outgoingAudioChannel->SignalSentPacket().disconnect(this); |
| 978 | _outgoingAudioChannel->media_channel()->SetAudioSend(_outgoingAudioSsrc, false, nullptr, &_audioSource); |
| 979 | _outgoingAudioChannel->Enable(false); |
| 980 | _channelManager->DestroyVoiceChannel(_outgoingAudioChannel); |
| 981 | _outgoingAudioChannel = nullptr; |
| 982 | } |
| 983 |
| 984 | void createOutgoingAudioChannel() { |
| 985 | if (_outgoingAudioChannel) { |
| 986 | return; |
| 987 | } |
| 988 |
| 989 | cricket::AudioOptions audioOptions; |
| 990 | audioOptions.echo_cancellation = true; |
| 991 | audioOptions.noise_suppression = true; |
| 992 | audioOptions.audio_jitter_buffer_fast_accelerate = true; |
| 993 |
| 994 | std::vector<std::string> streamIds; |
| 995 | streamIds.push_back("1"); |
| 996 |
| 997 | _outgoingAudioChannel = _channelManager->CreateVoiceChannel(_call.get(), cricket::MediaConfig(), _rtpTransport, _threads->getMediaThread(), "0", false, GroupNetworkManager::getDefaulCryptoOptions(), _uniqueRandomIdGenerator.get(), audioOptions); |
| 998 |
| 999 | const uint8_t opusMinBitrateKbps = 32; |
| 1000 | const uint8_t opusMaxBitrateKbps = 32; |
| 1001 | const uint8_t opusStartBitrateKbps = 32; |
| 1002 | const uint8_t opusPTimeMs = 120; |
| 1003 |
| 1004 | cricket::AudioCodec opusCodec(111, "opus", 48000, 0, 2); |
| 1005 | opusCodec.AddFeedbackParam(cricket::FeedbackParam(cricket::kRtcpFbParamTransportCc)); |
| 1006 | opusCodec.SetParam(cricket::kCodecParamMinBitrate, opusMinBitrateKbps); |
| 1007 | opusCodec.SetParam(cricket::kCodecParamStartBitrate, opusStartBitrateKbps); |
| 1008 | opusCodec.SetParam(cricket::kCodecParamMaxBitrate, opusMaxBitrateKbps); |
| 1009 | opusCodec.SetParam(cricket::kCodecParamUseInbandFec, 1); |
| 1010 | opusCodec.SetParam(cricket::kCodecParamPTime, opusPTimeMs); |
| 1011 |
| 1012 | auto outgoingAudioDescription = std::make_unique<cricket::AudioContentDescription>(); |
| 1013 | outgoingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAudioLevelUri, 1)); |
| 1014 | outgoingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAbsSendTimeUri, 2)); |
| 1015 | outgoingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kTransportSequenceNumberUri, 3)); |
| 1016 | outgoingAudioDescription->set_rtcp_mux(true); |
| 1017 | outgoingAudioDescription->set_rtcp_reduced_size(true); |
| 1018 | outgoingAudioDescription->set_direction(webrtc::RtpTransceiverDirection::kSendOnly); |
| 1019 | outgoingAudioDescription->set_codecs({ opusCodec }); |
| 1020 | outgoingAudioDescription->AddStream(cricket::StreamParams::CreateLegacy(_outgoingAudioSsrc)); |
| 1021 |
| 1022 | auto incomingAudioDescription = std::make_unique<cricket::AudioContentDescription>(); |
| 1023 | incomingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAudioLevelUri, 1)); |
| 1024 | incomingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAbsSendTimeUri, 2)); |
| 1025 | incomingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kTransportSequenceNumberUri, 3)); |
| 1026 | incomingAudioDescription->set_rtcp_mux(true); |
| 1027 | incomingAudioDescription->set_rtcp_reduced_size(true); |
| 1028 | incomingAudioDescription->set_direction(webrtc::RtpTransceiverDirection::kRecvOnly); |
| 1029 | incomingAudioDescription->set_codecs({ opusCodec }); |
| 1030 |
| 1031 | _outgoingAudioChannel->SetPayloadTypeDemuxingEnabled(false); |
| 1032 | _outgoingAudioChannel->SetLocalContent(outgoingAudioDescription.get(), webrtc::SdpType::kOffer, nullptr); |
| 1033 | _outgoingAudioChannel->SetRemoteContent(incomingAudioDescription.get(), webrtc::SdpType::kAnswer, nullptr); |
| 1034 |
| 1035 | _outgoingAudioChannel->SignalSentPacket().connect(this, &GroupInstanceCustomInternal::OnSentPacket_w); |
| 1036 | //_outgoingAudioChannel->UpdateRtpTransport(nullptr); |
| 1037 |
| 1038 | onUpdatedIsMuted(); |
| 1039 | } |
| 1040 |
| 1041 | void stop() { |
| 1042 | } |
| 1043 |
| 1044 | void beginLevelsTimer(int timeoutMs) { |
| 1045 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 1046 | _threads->getProcessThread()->PostDelayedTask(RTC_FROM_HERE, [weak]() { |
| 1047 | auto strong = weak.lock(); |
| 1048 | if (!strong) { |
| 1049 | return; |
| 1050 | } |
| 1051 |
| 1052 | GroupLevelsUpdate levelsUpdate; |
| 1053 | levelsUpdate.updates.reserve(strong->_audioLevels.size() + 1); |
| 1054 | for (auto &it : strong->_audioLevels) { |
| 1055 | if (it.second.level > 0.001f) { |
| 1056 | uint32_t effectiveSsrc = it.first.actualSsrc; |
| 1057 | if (std::find_if(levelsUpdate.updates.begin(), levelsUpdate.updates.end(), [&](GroupLevelUpdate const &item) { |
| 1058 | return item.ssrc == effectiveSsrc; |
| 1059 | }) != levelsUpdate.updates.end()) { |
| 1060 | continue; |
| 1061 | } |
| 1062 | levelsUpdate.updates.push_back(GroupLevelUpdate{ |
| 1063 | effectiveSsrc, |
| 1064 | it.second, |
| 1065 | }); |
| 1066 | } |
| 1067 | } |
| 1068 | auto myAudioLevel = strong->_myAudioLevel; |
| 1069 | if (strong->_isMuted) { |
| 1070 | myAudioLevel.level = 0.0f; |
| 1071 | myAudioLevel.voice = false; |
| 1072 | } |
| 1073 | levelsUpdate.updates.push_back(GroupLevelUpdate{ 0, myAudioLevel }); |
| 1074 |
| 1075 | strong->_audioLevels.clear(); |
| 1076 | if (strong->_audioLevelsUpdated) { |
| 1077 | strong->_audioLevelsUpdated(levelsUpdate); |
| 1078 | } |
| 1079 |
| 1080 | strong->beginLevelsTimer(50); |
| 1081 | }, timeoutMs); |
| 1082 | } |
| 1083 |
| 1084 | void beginNetworkStatusTimer(int delayMs) { |
| 1085 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 1086 | _threads->getMediaThread()->PostDelayedTask(RTC_FROM_HERE, [weak]() { |
| 1087 | auto strong = weak.lock(); |
| 1088 | if (!strong) { |
| 1089 | return; |
| 1090 | } |
| 1091 |
| 1092 | if (strong->_connectionMode == GroupConnectionMode::GroupConnectionModeBroadcast || strong->_broadcastEnabledUntilRtcIsConnectedAtTimestamp) { |
| 1093 | strong->updateBroadcastNetworkStatus(); |
| 1094 | } |
| 1095 |
| 1096 | strong->beginNetworkStatusTimer(500); |
| 1097 | }, delayMs); |
| 1098 | } |
| 1099 |
| 1100 | void updateBroadcastNetworkStatus() { |
| 1101 | auto timestamp = rtc::TimeMillis(); |
| 1102 |
| 1103 | bool isBroadcastConnected = true; |
| 1104 | if (_lastBroadcastPartReceivedTimestamp < timestamp - 3000) { |
| 1105 | isBroadcastConnected = false; |
| 1106 | } |
| 1107 |
| 1108 | if (_broadcastEnabledUntilRtcIsConnectedAtTimestamp) { |
| 1109 | auto timestamp = rtc::TimeMillis(); |
| 1110 | if (std::abs(timestamp - _broadcastEnabledUntilRtcIsConnectedAtTimestamp.value()) > 3000) { |
| 1111 | _broadcastEnabledUntilRtcIsConnectedAtTimestamp = absl::nullopt; |
| 1112 | if (_currentRequestedBroadcastPart) { |
| 1113 | if (_currentRequestedBroadcastPart->task) { |
| 1114 | _currentRequestedBroadcastPart->task->cancel(); |
| 1115 | } |
| 1116 | _currentRequestedBroadcastPart.reset(); |
| 1117 | } |
| 1118 | isBroadcastConnected = false; |
| 1119 | } |
| 1120 | } |
| 1121 |
| 1122 | if (isBroadcastConnected != _isBroadcastConnected) { |
| 1123 | _isBroadcastConnected = isBroadcastConnected; |
| 1124 | updateIsConnected(); |
| 1125 | } |
| 1126 | } |
| 1127 |
| 1128 | absl::optional<DecodedBroadcastPart> getNextBroadcastPart() { |
| 1129 | while (true) { |
| 1130 | if (_sourceBroadcastParts.size() != 0) { |
| 1131 | auto readChannels = _sourceBroadcastParts[0]->get10msPerChannel(); |
| 1132 | if (readChannels.size() == 0 || readChannels[0].pcmData.size() == 0) { |
| 1133 | _sourceBroadcastParts.erase(_sourceBroadcastParts.begin()); |
| 1134 | } else { |
| 1135 | std::vector<DecodedBroadcastPart::DecodedBroadcastPartChannel> channels; |
| 1136 |
| 1137 | int numSamples = (int)readChannels[0].pcmData.size(); |
| 1138 |
| 1139 | for (auto &readChannel : readChannels) { |
| 1140 | DecodedBroadcastPart::DecodedBroadcastPartChannel channel; |
| 1141 | channel.ssrc = readChannel.ssrc; |
| 1142 | channel.pcmData = std::move(readChannel.pcmData); |
| 1143 | channels.push_back(channel); |
| 1144 | } |
| 1145 |
| 1146 | absl::optional<DecodedBroadcastPart> decodedPart; |
| 1147 | decodedPart.emplace(numSamples, std::move(channels)); |
| 1148 |
| 1149 | return decodedPart; |
| 1150 | } |
| 1151 | } else { |
| 1152 | return absl::nullopt; |
| 1153 | } |
| 1154 | } |
| 1155 |
| 1156 | return absl::nullopt; |
| 1157 | } |
| 1158 |
| 1159 | void commitBroadcastPackets() { |
| 1160 | int numMillisecondsInQueue = 0; |
| 1161 | for (const auto &part : _sourceBroadcastParts) { |
| 1162 | numMillisecondsInQueue += part->getRemainingMilliseconds(); |
| 1163 | } |
| 1164 |
| 1165 | int commitMilliseconds = 20; |
| 1166 | if (numMillisecondsInQueue > 1000) { |
| 1167 | commitMilliseconds = numMillisecondsInQueue - 1000; |
| 1168 | } |
| 1169 |
| 1170 | std::set<ChannelId> channelsWithActivity; |
| 1171 |
| 1172 | for (int msIndex = 0; msIndex < commitMilliseconds; msIndex += 10) { |
| 1173 | auto packetData = getNextBroadcastPart(); |
| 1174 | if (!packetData) { |
| 1175 | break; |
| 1176 | } |
| 1177 |
| 1178 | for (const auto &decodedChannel : packetData->channels) { |
| 1179 | if (decodedChannel.ssrc == _outgoingAudioSsrc) { |
| 1180 | continue; |
| 1181 | } |
| 1182 |
| 1183 | ChannelId channelSsrc = ChannelId(decodedChannel.ssrc + 1000, decodedChannel.ssrc); |
| 1184 | if (_incomingAudioChannels.find(channelSsrc) == _incomingAudioChannels.end()) { |
| 1185 | std::ostringstream os; |
| 1186 | os << "broadcast" << channelSsrc.name(); |
| 1187 | addIncomingAudioChannel(os.str(), channelSsrc, true); |
| 1188 | } |
| 1189 |
| 1190 | webrtc::RtpPacket packet(nullptr, 12 + decodedChannel.pcmData.size() * 2); |
| 1191 |
| 1192 | packet.SetMarker(false); |
| 1193 | packet.SetPayloadType(112); |
| 1194 |
| 1195 | uint16_t packetSeq = 0; |
| 1196 |
| 1197 | auto it = _broadcastSeqBySsrc.find(channelSsrc.networkSsrc); |
| 1198 | if (it == _broadcastSeqBySsrc.end()) { |
| 1199 | packetSeq = 1000; |
| 1200 | _broadcastSeqBySsrc.insert(std::make_pair(channelSsrc.networkSsrc, packetSeq)); |
| 1201 | } else { |
| 1202 | it->second++; |
| 1203 | packetSeq = it->second; |
| 1204 | } |
| 1205 |
| 1206 | packet.SetSequenceNumber(packetSeq); |
| 1207 |
| 1208 | packet.SetTimestamp(_broadcastTimestamp); |
| 1209 |
| 1210 | packet.SetSsrc(channelSsrc.networkSsrc); |
| 1211 |
| 1212 | uint8_t *payload = packet.SetPayloadSize(decodedChannel.pcmData.size() * 2); |
| 1213 | memcpy(payload, decodedChannel.pcmData.data(), decodedChannel.pcmData.size() * 2); |
| 1214 |
| 1215 | for (int i = 0; i < decodedChannel.pcmData.size() * 2; i += 2) { |
| 1216 | auto temp = payload[i]; |
| 1217 | payload[i] = payload[i + 1]; |
| 1218 | payload[i + 1] = temp; |
| 1219 | } |
| 1220 |
| 1221 | auto buffer = packet.Buffer(); |
| 1222 | _call->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO, buffer, -1); |
| 1223 |
| 1224 | channelsWithActivity.insert(ChannelId(channelSsrc)); |
| 1225 | } |
| 1226 |
| 1227 | for (const auto channelId : channelsWithActivity) { |
| 1228 | const auto it = _incomingAudioChannels.find(channelId); |
| 1229 | if (it != _incomingAudioChannels.end()) { |
| 1230 | it->second->updateActivity(); |
| 1231 | } |
| 1232 | } |
| 1233 |
| 1234 | _broadcastTimestamp += packetData->numSamples; |
| 1235 | } |
| 1236 | } |
| 1237 |
| 1238 | void requestNextBroadcastPart() { |
| 1239 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 1240 | auto requestedPartId = _nextBroadcastTimestampMilliseconds; |
| 1241 | auto task = _requestBroadcastPart(_platformContext, requestedPartId, _broadcastPartDurationMilliseconds, [weak, threads = _threads, requestedPartId](BroadcastPart &&part) { |
| 1242 | threads->getMediaThread()->PostTask(RTC_FROM_HERE, [weak, part = std::move(part), requestedPartId]() mutable { |
| 1243 | auto strong = weak.lock(); |
| 1244 | if (!strong) { |
| 1245 | return; |
| 1246 | } |
| 1247 | if (strong->_currentRequestedBroadcastPart && strong->_currentRequestedBroadcastPart->timestamp == requestedPartId) { |
| 1248 | strong->onReceivedNextBroadcastPart(std::move(part)); |
| 1249 | } |
| 1250 | }); |
| 1251 | }); |
| 1252 | if (_currentRequestedBroadcastPart) { |
| 1253 | if (_currentRequestedBroadcastPart->task) { |
| 1254 | _currentRequestedBroadcastPart->task->cancel(); |
| 1255 | } |
| 1256 | _currentRequestedBroadcastPart.reset(); |
| 1257 | } |
| 1258 | _currentRequestedBroadcastPart.emplace(requestedPartId, task); |
| 1259 | } |
| 1260 |
| 1261 | void requestNextBroadcastPartWithDelay(int timeoutMs) { |
| 1262 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 1263 | _threads->getMediaThread()->PostDelayedTask(RTC_FROM_HERE, [weak]() { |
| 1264 | auto strong = weak.lock(); |
| 1265 | if (!strong) { |
| 1266 | return; |
| 1267 | } |
| 1268 |
| 1269 | strong->requestNextBroadcastPart(); |
| 1270 | }, timeoutMs); |
| 1271 | } |
| 1272 |
| 1273 | void onReceivedNextBroadcastPart(BroadcastPart &&part) { |
| 1274 | _currentRequestedBroadcastPart.reset(); |
| 1275 |
| 1276 | if (_connectionMode != GroupConnectionMode::GroupConnectionModeBroadcast && !_broadcastEnabledUntilRtcIsConnectedAtTimestamp) { |
| 1277 | return; |
| 1278 | } |
| 1279 |
| 1280 | int64_t responseTimestampMilliseconds = (int64_t)(part.responseTimestamp * 1000.0); |
| 1281 |
| 1282 | int64_t responseTimestampBoundary = (responseTimestampMilliseconds / _broadcastPartDurationMilliseconds) * _broadcastPartDurationMilliseconds; |
| 1283 |
| 1284 | switch (part.status) { |
| 1285 | case BroadcastPart::Status::Success: { |
| 1286 | _lastBroadcastPartReceivedTimestamp = rtc::TimeMillis(); |
| 1287 | updateBroadcastNetworkStatus(); |
| 1288 |
| 1289 | if (std::abs((int64_t)(part.responseTimestamp * 1000.0) - part.timestampMilliseconds) > 2000) { |
| 1290 | _nextBroadcastTimestampMilliseconds = std::max(part.timestampMilliseconds + _broadcastPartDurationMilliseconds, responseTimestampBoundary); |
| 1291 | } else { |
| 1292 | _nextBroadcastTimestampMilliseconds = part.timestampMilliseconds + _broadcastPartDurationMilliseconds; |
| 1293 | } |
| 1294 | _sourceBroadcastParts.emplace_back(new StreamingPart(std::move(part.oggData))); |
| 1295 | break; |
| 1296 | } |
| 1297 | case BroadcastPart::Status::NotReady: { |
| 1298 | _nextBroadcastTimestampMilliseconds = part.timestampMilliseconds; |
| 1299 | break; |
| 1300 | } |
| 1301 | case BroadcastPart::Status::ResyncNeeded: { |
| 1302 | _nextBroadcastTimestampMilliseconds = responseTimestampBoundary; |
| 1303 | break; |
| 1304 | } |
| 1305 | default: { |
| 1306 | //RTC_FATAL() << "Unknown part.status"; |
| 1307 | break; |
| 1308 | } |
| 1309 | } |
| 1310 |
| 1311 | int64_t nextDelay = _nextBroadcastTimestampMilliseconds - responseTimestampMilliseconds; |
| 1312 | int clippedDelay = std::max((int)nextDelay, 100); |
| 1313 |
| 1314 | //RTC_LOG(LS_INFO) << "requestNextBroadcastPartWithDelay(" << clippedDelay << ") (from " << nextDelay << ")"; |
| 1315 |
| 1316 | requestNextBroadcastPartWithDelay(clippedDelay); |
| 1317 | } |
| 1318 |
| 1319 | void beginBroadcastPartsDecodeTimer(int timeoutMs) { |
| 1320 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 1321 | _threads->getMediaThread()->PostDelayedTask(RTC_FROM_HERE, [weak]() { |
| 1322 | auto strong = weak.lock(); |
| 1323 | if (!strong) { |
| 1324 | return; |
| 1325 | } |
| 1326 |
| 1327 | if (strong->_connectionMode != GroupConnectionMode::GroupConnectionModeBroadcast && !strong->_broadcastEnabledUntilRtcIsConnectedAtTimestamp) { |
| 1328 | return; |
| 1329 | } |
| 1330 |
| 1331 | strong->commitBroadcastPackets(); |
| 1332 |
| 1333 | strong->beginBroadcastPartsDecodeTimer(20); |
| 1334 | }, timeoutMs); |
| 1335 | } |
| 1336 |
| 1337 | void configureSendVideo() { |
| 1338 | if (!_outgoingVideoChannel) { |
| 1339 | return; |
| 1340 | } |
| 1341 |
| 1342 | auto payloadTypes = assignPayloadTypes(_availableVideoFormats); |
| 1343 | if (!payloadTypes.has_value()) { |
| 1344 | return; |
| 1345 | } |
| 1346 |
| 1347 | GroupJoinPayloadVideoPayloadType vp8Payload; |
| 1348 | vp8Payload.id = payloadTypes.value().videoCodec.id; |
| 1349 | vp8Payload.name = payloadTypes.value().videoCodec.name; |
| 1350 | vp8Payload.clockrate = payloadTypes.value().videoCodec.clockrate; |
| 1351 | vp8Payload.channels = 0; |
| 1352 |
| 1353 | std::vector<GroupJoinPayloadVideoPayloadFeedbackType> vp8FeedbackTypes; |
| 1354 |
| 1355 | GroupJoinPayloadVideoPayloadFeedbackType fbGoogRemb; |
| 1356 | fbGoogRemb.type = "goog-remb"; |
| 1357 | vp8FeedbackTypes.push_back(fbGoogRemb); |
| 1358 |
| 1359 | GroupJoinPayloadVideoPayloadFeedbackType fbTransportCc; |
| 1360 | fbTransportCc.type = "transport-cc"; |
| 1361 | vp8FeedbackTypes.push_back(fbTransportCc); |
| 1362 |
| 1363 | GroupJoinPayloadVideoPayloadFeedbackType fbCcmFir; |
| 1364 | fbCcmFir.type = "ccm"; |
| 1365 | fbCcmFir.subtype = "fir"; |
| 1366 | vp8FeedbackTypes.push_back(fbCcmFir); |
| 1367 |
| 1368 | GroupJoinPayloadVideoPayloadFeedbackType fbNack; |
| 1369 | fbNack.type = "nack"; |
| 1370 | vp8FeedbackTypes.push_back(fbNack); |
| 1371 |
| 1372 | GroupJoinPayloadVideoPayloadFeedbackType fbNackPli; |
| 1373 | fbNackPli.type = "nack"; |
| 1374 | fbNackPli.subtype = "pli"; |
| 1375 | vp8FeedbackTypes.push_back(fbNackPli); |
| 1376 |
| 1377 | vp8Payload.feedbackTypes = vp8FeedbackTypes; |
| 1378 | vp8Payload.parameters = {}; |
| 1379 |
| 1380 | _videoPayloadTypes.push_back(std::move(vp8Payload)); |
| 1381 |
| 1382 | GroupJoinPayloadVideoPayloadType rtxPayload; |
| 1383 | rtxPayload.id = payloadTypes.value().rtxCodec.id; |
| 1384 | rtxPayload.name = payloadTypes.value().rtxCodec.name; |
| 1385 | rtxPayload.clockrate = payloadTypes.value().rtxCodec.clockrate; |
| 1386 | rtxPayload.parameters.push_back(std::make_pair("apt", intToString(payloadTypes.value().videoCodec.id))); |
| 1387 | _videoPayloadTypes.push_back(std::move(rtxPayload)); |
| 1388 |
| 1389 | auto outgoingVideoDescription = std::make_unique<cricket::VideoContentDescription>(); |
| 1390 | outgoingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAbsSendTimeUri, 2)); |
| 1391 | outgoingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kTransportSequenceNumberUri, 3)); |
| 1392 | outgoingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kVideoRotationUri, 13)); |
| 1393 |
| 1394 | for (const auto &extension : outgoingVideoDescription->rtp_header_extensions()) { |
| 1395 | _videoExtensionMap.push_back(std::make_pair(extension.id, extension.uri)); |
| 1396 | } |
| 1397 |
| 1398 | outgoingVideoDescription->set_rtcp_mux(true); |
| 1399 | outgoingVideoDescription->set_rtcp_reduced_size(true); |
| 1400 | outgoingVideoDescription->set_direction(webrtc::RtpTransceiverDirection::kSendOnly); |
| 1401 | outgoingVideoDescription->set_codecs({ payloadTypes->videoCodec, payloadTypes->rtxCodec }); |
| 1402 |
| 1403 | cricket::StreamParams videoSendStreamParams; |
| 1404 |
| 1405 | std::vector<uint32_t> simulcastGroupSsrcs; |
| 1406 | std::vector<cricket::SsrcGroup> fidGroups; |
| 1407 | for (const auto &layer : _outgoingVideoSsrcs.simulcastLayers) { |
| 1408 | simulcastGroupSsrcs.push_back(layer.ssrc); |
| 1409 |
| 1410 | videoSendStreamParams.ssrcs.push_back(layer.ssrc); |
| 1411 | videoSendStreamParams.ssrcs.push_back(layer.fidSsrc); |
| 1412 |
| 1413 | cricket::SsrcGroup fidGroup(cricket::kFidSsrcGroupSemantics, { layer.ssrc, layer.fidSsrc }); |
| 1414 | fidGroups.push_back(fidGroup); |
| 1415 | } |
| 1416 | if (simulcastGroupSsrcs.size() > 1) { |
| 1417 | cricket::SsrcGroup simulcastGroup(cricket::kSimSsrcGroupSemantics, simulcastGroupSsrcs); |
| 1418 | videoSendStreamParams.ssrc_groups.push_back(simulcastGroup); |
| 1419 |
| 1420 | GroupJoinPayloadVideoSourceGroup payloadSimulcastGroup; |
| 1421 | payloadSimulcastGroup.semantics = "SIM"; |
| 1422 | payloadSimulcastGroup.ssrcs = simulcastGroupSsrcs; |
| 1423 | _videoSourceGroups.push_back(payloadSimulcastGroup); |
| 1424 | } |
| 1425 |
| 1426 | for (auto fidGroup : fidGroups) { |
| 1427 | videoSendStreamParams.ssrc_groups.push_back(fidGroup); |
| 1428 |
| 1429 | GroupJoinPayloadVideoSourceGroup payloadFidGroup; |
| 1430 | payloadFidGroup.semantics = "FID"; |
| 1431 | payloadFidGroup.ssrcs = fidGroup.ssrcs; |
| 1432 | _videoSourceGroups.push_back(payloadFidGroup); |
| 1433 | } |
| 1434 |
| 1435 | videoSendStreamParams.cname = "cname"; |
| 1436 |
| 1437 | outgoingVideoDescription->AddStream(videoSendStreamParams); |
| 1438 |
| 1439 | auto incomingVideoDescription = std::make_unique<cricket::VideoContentDescription>(); |
| 1440 | incomingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAbsSendTimeUri, 2)); |
| 1441 | incomingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kTransportSequenceNumberUri, 3)); |
| 1442 | incomingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kVideoRotationUri, 13)); |
| 1443 | incomingVideoDescription->set_rtcp_mux(true); |
| 1444 | incomingVideoDescription->set_rtcp_reduced_size(true); |
| 1445 | incomingVideoDescription->set_direction(webrtc::RtpTransceiverDirection::kRecvOnly); |
| 1446 | incomingVideoDescription->set_codecs({ payloadTypes->videoCodec, payloadTypes->rtxCodec }); |
| 1447 |
| 1448 | _outgoingVideoChannel->SetPayloadTypeDemuxingEnabled(false); |
| 1449 | _outgoingVideoChannel->SetLocalContent(outgoingVideoDescription.get(), webrtc::SdpType::kOffer, nullptr); |
| 1450 | _outgoingVideoChannel->SetRemoteContent(incomingVideoDescription.get(), webrtc::SdpType::kAnswer, nullptr); |
| 1451 |
| 1452 | webrtc::RtpParameters rtpParameters = _outgoingVideoChannel->media_channel()->GetRtpSendParameters(_outgoingVideoSsrcs.simulcastLayers[0].ssrc); |
| 1453 | if (rtpParameters.encodings.size() == 3) { |
| 1454 | for (int i = 0; i < (int)rtpParameters.encodings.size(); i++) { |
| 1455 | if (i == 0) { |
| 1456 | rtpParameters.encodings[i].min_bitrate_bps = 50000; |
| 1457 | rtpParameters.encodings[i].max_bitrate_bps = 100000; |
| 1458 | rtpParameters.encodings[i].scale_resolution_down_by = 4.0; |
| 1459 | } else if (i == 1) { |
| 1460 | rtpParameters.encodings[i].max_bitrate_bps = 150000; |
| 1461 | rtpParameters.encodings[i].max_bitrate_bps = 200000; |
| 1462 | rtpParameters.encodings[i].scale_resolution_down_by = 2.0; |
| 1463 | } else if (i == 2) { |
| 1464 | rtpParameters.encodings[i].min_bitrate_bps = 300000; |
| 1465 | rtpParameters.encodings[i].max_bitrate_bps = 800000; |
| 1466 | } |
| 1467 | } |
| 1468 | } else if (rtpParameters.encodings.size() == 2) { |
| 1469 | for (int i = 0; i < (int)rtpParameters.encodings.size(); i++) { |
| 1470 | if (i == 0) { |
| 1471 | rtpParameters.encodings[i].min_bitrate_bps = 50000; |
| 1472 | rtpParameters.encodings[i].max_bitrate_bps = 100000; |
| 1473 | rtpParameters.encodings[i].scale_resolution_down_by = 4.0; |
| 1474 | } else if (i == 1) { |
| 1475 | rtpParameters.encodings[i].min_bitrate_bps = 200000; |
| 1476 | rtpParameters.encodings[i].max_bitrate_bps = 800000; |
| 1477 | } |
| 1478 | } |
| 1479 | } |
| 1480 |
| 1481 | _outgoingVideoChannel->media_channel()->SetRtpSendParameters(_outgoingVideoSsrcs.simulcastLayers[0].ssrc, rtpParameters); |
| 1482 | } |
| 1483 |
| 1484 | void OnSentPacket_w(const rtc::SentPacket& sent_packet) { |
| 1485 | _call->OnSentPacket(sent_packet); |
| 1486 | } |
| 1487 |
| 1488 | void adjustBitratePreferences(bool resetStartBitrate) { |
| 1489 | webrtc::BitrateConstraints preferences; |
| 1490 | if (_videoCapture) { |
| 1491 | preferences.min_bitrate_bps = 64000; |
| 1492 | if (resetStartBitrate) { |
| 1493 | preferences.start_bitrate_bps = (100 + 800 + 32 + 100) * 1000; |
| 1494 | } |
| 1495 | preferences.max_bitrate_bps = (100 + 200 + 800 + 32 + 100) * 1000; |
| 1496 | } else { |
| 1497 | preferences.min_bitrate_bps = 32000; |
| 1498 | if (resetStartBitrate) { |
| 1499 | preferences.start_bitrate_bps = 32000; |
| 1500 | } |
| 1501 | preferences.max_bitrate_bps = 32000; |
| 1502 | } |
| 1503 |
| 1504 | _call->GetTransportControllerSend()->SetSdpBitrateParameters(preferences); |
| 1505 | } |
| 1506 |
| 1507 | void setIsRtcConnected(bool isConnected) { |
| 1508 | if (_isRtcConnected == isConnected) { |
| 1509 | return; |
| 1510 | } |
| 1511 | _isRtcConnected = isConnected; |
| 1512 |
| 1513 | RTC_LOG(LS_INFO) << formatTimestampMillis(rtc::TimeMillis()) << ": " << "setIsRtcConnected: " << _isRtcConnected; |
| 1514 |
| 1515 | if (_broadcastEnabledUntilRtcIsConnectedAtTimestamp) { |
| 1516 | _broadcastEnabledUntilRtcIsConnectedAtTimestamp = absl::nullopt; |
| 1517 | if (_currentRequestedBroadcastPart) { |
| 1518 | if (_currentRequestedBroadcastPart->task) { |
| 1519 | _currentRequestedBroadcastPart->task->cancel(); |
| 1520 | } |
| 1521 | _currentRequestedBroadcastPart.reset(); |
| 1522 | } |
| 1523 | } |
| 1524 |
| 1525 | updateIsConnected(); |
| 1526 | } |
| 1527 |
| 1528 | void updateIsConnected() { |
| 1529 | bool isEffectivelyConnected = false; |
| 1530 | bool isTransitioningFromBroadcastToRtc = false; |
| 1531 | switch (_connectionMode) { |
| 1532 | case GroupConnectionMode::GroupConnectionModeNone: { |
| 1533 | isEffectivelyConnected = false; |
| 1534 | if (_broadcastEnabledUntilRtcIsConnectedAtTimestamp && _isBroadcastConnected) { |
| 1535 | isEffectivelyConnected = true; |
| 1536 | isTransitioningFromBroadcastToRtc = true; |
| 1537 | } |
| 1538 | break; |
| 1539 | } |
| 1540 | case GroupConnectionMode::GroupConnectionModeRtc: { |
| 1541 | isEffectivelyConnected = _isRtcConnected; |
| 1542 | if (_broadcastEnabledUntilRtcIsConnectedAtTimestamp && _isBroadcastConnected) { |
| 1543 | isEffectivelyConnected = true; |
| 1544 | isTransitioningFromBroadcastToRtc = true; |
| 1545 | } |
| 1546 | break; |
| 1547 | } |
| 1548 | case GroupConnectionMode::GroupConnectionModeBroadcast: { |
| 1549 | isEffectivelyConnected = _isBroadcastConnected; |
| 1550 | break; |
| 1551 | } |
| 1552 | } |
| 1553 |
| 1554 | GroupNetworkState effectiveNetworkState; |
| 1555 | effectiveNetworkState.isConnected = isEffectivelyConnected; |
| 1556 | effectiveNetworkState.isTransitioningFromBroadcastToRtc = isTransitioningFromBroadcastToRtc; |
| 1557 |
| 1558 | if (_effectiveNetworkState.isConnected != effectiveNetworkState.isConnected || _effectiveNetworkState.isTransitioningFromBroadcastToRtc != effectiveNetworkState.isTransitioningFromBroadcastToRtc) { |
| 1559 | _effectiveNetworkState = effectiveNetworkState; |
| 1560 |
| 1561 | if (_effectiveNetworkState.isConnected) { |
| 1562 | _call->SignalChannelNetworkState(webrtc::MediaType::AUDIO, webrtc::kNetworkUp); |
| 1563 | _call->SignalChannelNetworkState(webrtc::MediaType::VIDEO, webrtc::kNetworkUp); |
| 1564 | } else { |
| 1565 | _call->SignalChannelNetworkState(webrtc::MediaType::AUDIO, webrtc::kNetworkDown); |
| 1566 | _call->SignalChannelNetworkState(webrtc::MediaType::VIDEO, webrtc::kNetworkDown); |
| 1567 | } |
| 1568 |
| 1569 | if (_networkStateUpdated) { |
| 1570 | _networkStateUpdated(_effectiveNetworkState); |
| 1571 | } |
| 1572 | } |
| 1573 | } |
| 1574 |
| 1575 | void updateIsDataChannelOpen(bool isDataChannelOpen) { |
| 1576 | if (_isDataChannelOpen == isDataChannelOpen) { |
| 1577 | return; |
| 1578 | } |
| 1579 | _isDataChannelOpen = isDataChannelOpen; |
| 1580 |
| 1581 | if (_isDataChannelOpen) { |
| 1582 | maybeUpdateRemoteVideoConstaints(); |
| 1583 | } |
| 1584 | } |
| 1585 |
| 1586 | void receivePacket(rtc::CopyOnWriteBuffer const &packet, bool isUnresolved) { |
| 1587 | if (packet.size() >= 4) { |
| 1588 | if (packet.data()[0] == 0x13 && packet.data()[1] == 0x88 && packet.data()[2] == 0x13 && packet.data()[3] == 0x88) { |
| 1589 | // SCTP packet header (source port 5000, destination port 5000) |
| 1590 | return; |
| 1591 | } |
| 1592 | } |
| 1593 |
| 1594 | webrtc::RtpUtility::RtpHeaderParser rtpParser(packet.data(), packet.size()); |
| 1595 |
| 1596 | webrtc::RTPHeader header; |
| 1597 | if (rtpParser.RTCP()) { |
| 1598 | if (!rtpParser.ParseRtcp(&header)) { |
| 1599 | RTC_LOG(LS_INFO) << "Could not parse rtcp header"; |
| 1600 | return; |
| 1601 | } |
| 1602 |
| 1603 | _call->Receiver()->DeliverPacket(webrtc::MediaType::ANY, packet, -1); |
| 1604 | } else { |
| 1605 | if (!rtpParser.Parse(&header)) { |
| 1606 | // Probably a data channel message |
| 1607 | return; |
| 1608 | } |
| 1609 |
| 1610 | if (header.ssrc == _outgoingAudioSsrc) { |
| 1611 | return; |
| 1612 | } |
| 1613 |
| 1614 | auto it = _ssrcMapping.find(header.ssrc); |
| 1615 | if (it == _ssrcMapping.end()) { |
| 1616 | if (isUnresolved) { |
| 1617 | maybeReportUnknownSsrc(header.ssrc); |
| 1618 | _missingPacketBuffer.add(header.ssrc, packet); |
| 1619 | } |
| 1620 | } else { |
| 1621 | const auto it = _incomingAudioChannels.find(ChannelId(header.ssrc)); |
| 1622 | if (it != _incomingAudioChannels.end()) { |
| 1623 | it->second->updateActivity(); |
| 1624 | } |
| 1625 | } |
| 1626 | } |
| 1627 | } |
| 1628 |
| 1629 | void receiveRtcpPacket(rtc::CopyOnWriteBuffer const &packet, int64_t timestamp) { |
| 1630 | _call->Receiver()->DeliverPacket(webrtc::MediaType::ANY, packet, timestamp); |
| 1631 | } |
| 1632 |
| 1633 | void maybeReportUnknownSsrc(uint32_t ssrc) { |
| 1634 | if (_reportedUnknownSsrcs.find(ssrc) == _reportedUnknownSsrcs.end()) { |
| 1635 | _reportedUnknownSsrcs.insert(ssrc); |
| 1636 |
| 1637 | _pendingUnknownSsrcs.insert(ssrc); |
| 1638 |
| 1639 | if (!_isUnknownSsrcsScheduled) { |
| 1640 | auto timestamp = rtc::TimeMillis(); |
| 1641 | if (_lastUnknownSsrcsReport < timestamp - 100) { |
| 1642 | doReportPendingUnknownSsrcs(); |
| 1643 | } else { |
| 1644 | _isUnknownSsrcsScheduled = true; |
| 1645 |
| 1646 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 1647 | _threads->getMediaThread()->PostDelayedTask(RTC_FROM_HERE, [weak]() { |
| 1648 | auto strong = weak.lock(); |
| 1649 | if (!strong) { |
| 1650 | return; |
| 1651 | } |
| 1652 |
| 1653 | strong->_isUnknownSsrcsScheduled = false; |
| 1654 | strong->doReportPendingUnknownSsrcs(); |
| 1655 | }, 100); |
| 1656 | } |
| 1657 | } |
| 1658 | } |
| 1659 | } |
| 1660 |
| 1661 | void doReportPendingUnknownSsrcs() { |
| 1662 | std::vector<uint32_t> ssrcs; |
| 1663 | for (auto ssrc : _pendingUnknownSsrcs) { |
| 1664 | ssrcs.push_back(ssrc); |
| 1665 | } |
| 1666 | _pendingUnknownSsrcs.clear(); |
| 1667 |
| 1668 | if (ssrcs.size() != 0) { |
| 1669 | _lastUnknownSsrcsReport = rtc::TimeMillis(); |
| 1670 | if (_participantDescriptionsRequired) { |
| 1671 | _participantDescriptionsRequired(ssrcs); |
| 1672 | } else { |
| 1673 | std::vector<GroupParticipantDescription> participants; |
| 1674 | for (auto ssrc : ssrcs) { |
| 1675 | GroupParticipantDescription description; |
| 1676 | description.audioSsrc = ssrc; |
| 1677 | participants.push_back(std::move(description)); |
| 1678 | } |
| 1679 | addParticipants(std::move(participants)); |
| 1680 | } |
| 1681 | } |
| 1682 | } |
| 1683 |
| 1684 | void maybeDeliverBufferedPackets(uint32_t ssrc) { |
| 1685 | // TODO: Re-enable after implementing custom transport |
| 1686 | /*auto packets = _missingPacketBuffer.get(ssrc); |
| 1687 | if (packets.size() != 0) { |
| 1688 | auto it = _ssrcMapping.find(ssrc); |
| 1689 | if (it != _ssrcMapping.end()) { |
| 1690 | for (const auto &packet : packets) { |
| 1691 | _threads->getNetworkThread()->Invoke<void>(RTC_FROM_HERE, [this, packet]() { |
| 1692 | _rtpTransport->DemuxPacketInternal(packet, -1); |
| 1693 | }); |
| 1694 | } |
| 1695 | } |
| 1696 | }*/ |
| 1697 | } |
| 1698 |
| 1699 | void maybeUpdateRemoteVideoConstaints() { |
| 1700 | if (!_isDataChannelOpen) { |
| 1701 | return; |
| 1702 | } |
| 1703 |
| 1704 | std::vector<std::string> endpointIds; |
| 1705 | for (const auto &incomingVideoChannel : _incomingVideoChannels) { |
| 1706 | auto ssrcMapping = _ssrcMapping.find(incomingVideoChannel.first); |
| 1707 | if (ssrcMapping != _ssrcMapping.end()) { |
| 1708 | if (std::find(endpointIds.begin(), endpointIds.end(), ssrcMapping->second.endpointId) == endpointIds.end()) { |
| 1709 | endpointIds.push_back(ssrcMapping->second.endpointId); |
| 1710 | } |
| 1711 | } |
| 1712 | } |
| 1713 | std::sort(endpointIds.begin(), endpointIds.end()); |
| 1714 |
| 1715 | std::string pinnedEndpoint; |
| 1716 |
| 1717 | std::ostringstream string; |
| 1718 | string << "{" << "\n"; |
| 1719 | string << " \"colibriClass\": \"ReceiverVideoConstraintsChangedEvent\"," << "\n"; |
| 1720 | string << " \"videoConstraints\": [" << "\n"; |
| 1721 | bool isFirst = true; |
| 1722 | for (size_t i = 0; i < endpointIds.size(); i++) { |
| 1723 | int idealHeight = 180; |
| 1724 | if (_currentHighQualityVideoEndpointId == endpointIds[i]) { |
| 1725 | idealHeight = 720; |
| 1726 | } |
| 1727 |
| 1728 | if (isFirst) { |
| 1729 | isFirst = false; |
| 1730 | } else { |
| 1731 | if (i != 0) { |
| 1732 | string << ","; |
| 1733 | } |
| 1734 | } |
| 1735 | string << " {\n"; |
| 1736 | string << " \"id\": \"" << endpointIds[i] << "\",\n"; |
| 1737 | string << " \"idealHeight\": " << idealHeight << "\n"; |
| 1738 | string << " }"; |
| 1739 | string << "\n"; |
| 1740 | } |
| 1741 | string << " ]" << "\n"; |
| 1742 | string << "}"; |
| 1743 |
| 1744 | std::string result = string.str(); |
| 1745 | _networkManager->perform(RTC_FROM_HERE, [result = std::move(result)](GroupNetworkManager *networkManager) { |
| 1746 | networkManager->sendDataChannelMessage(result); |
| 1747 | }); |
| 1748 | } |
| 1749 |
| 1750 | void setConnectionMode(GroupConnectionMode connectionMode, bool keepBroadcastIfWasEnabled) { |
| 1751 | if (_connectionMode != connectionMode) { |
| 1752 | GroupConnectionMode previousMode = _connectionMode; |
| 1753 | _connectionMode = connectionMode; |
| 1754 | onConnectionModeUpdated(previousMode, keepBroadcastIfWasEnabled); |
| 1755 | } |
| 1756 | } |
| 1757 |
| 1758 | void onConnectionModeUpdated(GroupConnectionMode previousMode, bool keepBroadcastIfWasEnabled) { |
| 1759 | RTC_CHECK(_connectionMode != previousMode); |
| 1760 |
| 1761 | if (previousMode == GroupConnectionMode::GroupConnectionModeRtc) { |
| 1762 | _networkManager->perform(RTC_FROM_HERE, [](GroupNetworkManager *networkManager) { |
| 1763 | networkManager->stop(); |
| 1764 | }); |
| 1765 | } else if (previousMode == GroupConnectionMode::GroupConnectionModeBroadcast) { |
| 1766 | if (keepBroadcastIfWasEnabled) { |
| 1767 | _broadcastEnabledUntilRtcIsConnectedAtTimestamp = rtc::TimeMillis(); |
| 1768 | } else { |
| 1769 | if (_currentRequestedBroadcastPart) { |
| 1770 | if (_currentRequestedBroadcastPart->task) { |
| 1771 | _currentRequestedBroadcastPart->task->cancel(); |
| 1772 | } |
| 1773 | _currentRequestedBroadcastPart.reset(); |
| 1774 | } |
| 1775 | } |
| 1776 | } |
| 1777 |
| 1778 | if (_connectionMode == GroupConnectionMode::GroupConnectionModeNone) { |
| 1779 | destroyOutgoingAudioChannel(); |
| 1780 |
| 1781 | auto generator = std::mt19937(std::random_device()()); |
| 1782 | auto distribution = std::uniform_int_distribution<uint32_t>(); |
| 1783 | do { |
| 1784 | _outgoingAudioSsrc = distribution(generator) & 0x7fffffffU; |
| 1785 | } while (!_outgoingAudioSsrc); |
| 1786 |
| 1787 | if (!_isMuted) { |
| 1788 | createOutgoingAudioChannel(); |
| 1789 | } |
| 1790 | } |
| 1791 |
| 1792 | switch (_connectionMode) { |
| 1793 | case GroupConnectionMode::GroupConnectionModeNone: { |
| 1794 | break; |
| 1795 | } |
| 1796 | case GroupConnectionMode::GroupConnectionModeRtc: { |
| 1797 | _networkManager->perform(RTC_FROM_HERE, [](GroupNetworkManager *networkManager) { |
| 1798 | networkManager->start(); |
| 1799 | }); |
| 1800 | break; |
| 1801 | } |
| 1802 | case GroupConnectionMode::GroupConnectionModeBroadcast: { |
| 1803 | _broadcastTimestamp = 100001; |
| 1804 |
| 1805 | _isBroadcastConnected = false; |
| 1806 |
| 1807 | beginBroadcastPartsDecodeTimer(0); |
| 1808 | requestNextBroadcastPart(); |
| 1809 |
| 1810 | break; |
| 1811 | } |
| 1812 | default: { |
| 1813 | //RTC_FATAL() << "Unknown connectionMode"; |
| 1814 | break; |
| 1815 | } |
| 1816 | } |
| 1817 |
| 1818 | updateIsConnected(); |
| 1819 | } |
| 1820 |
| 1821 | void emitJoinPayload(std::function<void(GroupJoinPayload)> completion) { |
| 1822 | _networkManager->perform(RTC_FROM_HERE, [outgoingAudioSsrc = _outgoingAudioSsrc, videoPayloadTypes = _videoPayloadTypes, videoExtensionMap = _videoExtensionMap, videoSourceGroups = _videoSourceGroups, completion](GroupNetworkManager *networkManager) { |
| 1823 | GroupJoinPayload payload; |
| 1824 |
| 1825 | payload.ssrc = outgoingAudioSsrc; |
| 1826 |
| 1827 | /*payload.videoPayloadTypes = videoPayloadTypes; |
| 1828 | payload.videoExtensionMap = videoExtensionMap; |
| 1829 | payload.videoSourceGroups = videoSourceGroups;*/ |
| 1830 |
| 1831 | auto localIceParameters = networkManager->getLocalIceParameters(); |
| 1832 | payload.ufrag = localIceParameters.ufrag; |
| 1833 | payload.pwd = localIceParameters.pwd; |
| 1834 |
| 1835 | auto localFingerprint = networkManager->getLocalFingerprint(); |
| 1836 | if (localFingerprint) { |
| 1837 | GroupJoinPayloadFingerprint serializedFingerprint; |
| 1838 | serializedFingerprint.hash = localFingerprint->algorithm; |
| 1839 | serializedFingerprint.fingerprint = localFingerprint->GetRfc4572Fingerprint(); |
| 1840 | serializedFingerprint.setup = "passive"; |
| 1841 | payload.fingerprints.push_back(std::move(serializedFingerprint)); |
| 1842 | } |
| 1843 |
| 1844 | completion(payload); |
| 1845 | }); |
| 1846 | } |
| 1847 |
| 1848 | void setVideoCapture(std::shared_ptr<VideoCaptureInterface> videoCapture, std::function<void(GroupJoinPayload)> completion, bool isInitializing) { |
| 1849 | bool resetBitrate = (_videoCapture == nullptr) != (videoCapture == nullptr) && !isInitializing; |
| 1850 | if (!isInitializing && _videoCapture == videoCapture) { |
| 1851 | return; |
| 1852 | } |
| 1853 |
| 1854 | _videoCapture = videoCapture; |
| 1855 |
| 1856 | if (_outgoingVideoChannel) { |
| 1857 | if (_videoCapture) { |
| 1858 | _outgoingVideoChannel->Enable(true); |
| 1859 | _outgoingVideoChannel->media_channel()->SetVideoSend(_outgoingVideoSsrcs.simulcastLayers[0].ssrc, NULL, GetVideoCaptureAssumingSameThread(_videoCapture.get())->source()); |
| 1860 | } else { |
| 1861 | _outgoingVideoChannel->Enable(false); |
| 1862 | _outgoingVideoChannel->media_channel()->SetVideoSend(_outgoingVideoSsrcs.simulcastLayers[0].ssrc, NULL, nullptr); |
| 1863 | } |
| 1864 | } |
| 1865 |
| 1866 | if (resetBitrate) { |
| 1867 | adjustBitratePreferences(true); |
| 1868 | } |
| 1869 | } |
| 1870 |
| 1871 | void setAudioOutputDevice(const std::string &id) { |
| 1872 | #if not defined(WEBRTC_IOS) && not defined(WEBRTC_ANDROID) |
| 1873 | SetAudioOutputDeviceById(_audioDeviceModule.get(), id); |
| 1874 | #endif // WEBRTC_IOS |
| 1875 | } |
| 1876 |
| 1877 | void setAudioInputDevice(const std::string &id) { |
| 1878 | #if not defined(WEBRTC_IOS) && not defined(WEBRTC_ANDROID) |
| 1879 | SetAudioInputDeviceById(_audioDeviceModule.get(), id); |
| 1880 | #endif // WEBRTC_IOS |
| 1881 | } |
| 1882 |
| 1883 | void setJoinResponsePayload(GroupJoinResponsePayload payload, std::vector<tgcalls::GroupParticipantDescription> &&participants) { |
| 1884 | RTC_LOG(LS_INFO) << formatTimestampMillis(rtc::TimeMillis()) << ": " << "setJoinResponsePayload"; |
| 1885 |
| 1886 | _networkManager->perform(RTC_FROM_HERE, [payload](GroupNetworkManager *networkManager) { |
| 1887 | PeerIceParameters remoteIceParameters; |
| 1888 | remoteIceParameters.ufrag = payload.ufrag; |
| 1889 | remoteIceParameters.pwd = payload.pwd; |
| 1890 |
| 1891 | std::vector<cricket::Candidate> iceCandidates; |
| 1892 | for (auto const &candidate : payload.candidates) { |
| 1893 | rtc::SocketAddress address(candidate.ip, stringToInt(candidate.port)); |
| 1894 |
| 1895 | cricket::Candidate parsedCandidate( |
| 1896 | /*component=*/stringToInt(candidate.component), |
| 1897 | /*protocol=*/candidate.protocol, |
| 1898 | /*address=*/address, |
| 1899 | /*priority=*/stringToUInt32(candidate.priority), |
| 1900 | /*username=*/payload.ufrag, |
| 1901 | /*password=*/payload.pwd, |
| 1902 | /*type=*/candidate.type, |
| 1903 | /*generation=*/stringToUInt32(candidate.generation), |
| 1904 | /*foundation=*/candidate.foundation, |
| 1905 | /*network_id=*/stringToUInt16(candidate.network), |
| 1906 | /*network_cost=*/0 |
| 1907 | ); |
| 1908 | iceCandidates.push_back(parsedCandidate); |
| 1909 | } |
| 1910 |
| 1911 | std::unique_ptr<rtc::SSLFingerprint> fingerprint; |
| 1912 | if (payload.fingerprints.size() != 0) { |
| 1913 | fingerprint = rtc::SSLFingerprint::CreateUniqueFromRfc4572(payload.fingerprints[0].hash, payload.fingerprints[0].fingerprint); |
| 1914 | } |
| 1915 |
| 1916 | networkManager->setRemoteParams(remoteIceParameters, iceCandidates, fingerprint.get()); |
| 1917 | }); |
| 1918 |
| 1919 | addParticipants(std::move(participants)); |
| 1920 | } |
| 1921 |
| 1922 | void addParticipants(std::vector<GroupParticipantDescription> &&participants) { |
| 1923 | if (_disableIncomingChannels) { |
| 1924 | return; |
| 1925 | } |
| 1926 | for (const auto &participant : participants) { |
| 1927 | if (participant.audioSsrc == _outgoingAudioSsrc) { |
| 1928 | continue; |
| 1929 | } |
| 1930 |
| 1931 | _reportedUnknownSsrcs.erase(participant.audioSsrc); |
| 1932 |
| 1933 | if (_incomingAudioChannels.find(ChannelId(participant.audioSsrc)) == _incomingAudioChannels.end()) { |
| 1934 | addIncomingAudioChannel(participant.endpointId, ChannelId(participant.audioSsrc)); |
| 1935 | } |
| 1936 | if (participant.videoPayloadTypes.size() != 0 && participant.videoSourceGroups.size() != 0) { |
| 1937 | if (_incomingVideoChannels.find(participant.audioSsrc) == _incomingVideoChannels.end()) { |
| 1938 | addIncomingVideoChannel(participant); |
| 1939 | } |
| 1940 | } |
| 1941 | } |
| 1942 | } |
| 1943 |
| 1944 | void removeSsrcs(std::vector<uint32_t> ssrcs) { |
| 1945 | bool updatedIncomingVideoChannels = false; |
| 1946 |
| 1947 | for (auto ssrc : ssrcs) { |
| 1948 | auto it = _ssrcMapping.find(ssrc); |
| 1949 | if (it != _ssrcMapping.end()) { |
| 1950 | auto mainSsrc = it->second.ssrc; |
| 1951 | auto audioChannel = _incomingAudioChannels.find(ChannelId(mainSsrc)); |
| 1952 | if (audioChannel != _incomingAudioChannels.end()) { |
| 1953 | _incomingAudioChannels.erase(audioChannel); |
| 1954 | } |
| 1955 | auto videoChannel = _incomingVideoChannels.find(mainSsrc); |
| 1956 | if (videoChannel != _incomingVideoChannels.end()) { |
| 1957 | _incomingVideoChannels.erase(videoChannel); |
| 1958 | updatedIncomingVideoChannels = true; |
| 1959 | } |
| 1960 | } |
| 1961 | } |
| 1962 |
| 1963 | if (updatedIncomingVideoChannels) { |
| 1964 | updateIncomingVideoSources(); |
| 1965 | } |
| 1966 | } |
| 1967 |
| 1968 | void setIsMuted(bool isMuted) { |
| 1969 | if (_isMuted == isMuted) { |
| 1970 | return; |
| 1971 | } |
| 1972 | _isMuted = isMuted; |
| 1973 |
| 1974 | onUpdatedIsMuted(); |
| 1975 | } |
| 1976 |
| 1977 | void onUpdatedIsMuted() { |
| 1978 | if (!_isMuted) { |
| 1979 | if (!_outgoingAudioChannel) { |
| 1980 | createOutgoingAudioChannel(); |
| 1981 | } |
| 1982 | } |
| 1983 |
| 1984 | if (_outgoingAudioChannel) { |
| 1985 | _outgoingAudioChannel->Enable(!_isMuted); |
| 1986 | _outgoingAudioChannel->media_channel()->SetAudioSend(_outgoingAudioSsrc, _isRtcConnected && !_isMuted, nullptr, &_audioSource); |
| 1987 | } |
| 1988 | } |
| 1989 |
| 1990 | void addIncomingVideoOutput(uint32_t ssrc, std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) { |
| 1991 | auto it = _incomingVideoChannels.find(ssrc); |
| 1992 | if (it != _incomingVideoChannels.end()) { |
| 1993 | it->second->addSink(sink); |
| 1994 | } |
| 1995 | } |
| 1996 |
| 1997 | void addIncomingAudioChannel(std::string const &endpointId, ChannelId ssrc, bool isRawPcm = false) { |
| 1998 | if (_incomingAudioChannels.find(ssrc) != _incomingAudioChannels.end()) { |
| 1999 | return; |
| 2000 | } |
| 2001 |
| 2002 | if (_incomingAudioChannels.size() > 5) { |
| 2003 | int64_t minActivity = INT64_MAX; |
| 2004 | ChannelId minActivityChannelId(0, 0); |
| 2005 |
| 2006 | for (const auto &it : _incomingAudioChannels) { |
| 2007 | auto activity = it.second->getActivity(); |
| 2008 | if (activity < minActivity) { |
| 2009 | minActivity = activity; |
| 2010 | minActivityChannelId = it.first; |
| 2011 | } |
| 2012 | } |
| 2013 |
| 2014 | if (minActivityChannelId.networkSsrc != 0) { |
| 2015 | const auto it = _incomingAudioChannels.find(minActivityChannelId); |
| 2016 | if (it != _incomingAudioChannels.end()) { |
| 2017 | _incomingAudioChannels.erase(it); |
| 2018 | } |
| 2019 | auto reportedIt = _reportedUnknownSsrcs.find(minActivityChannelId.actualSsrc); |
| 2020 | if (reportedIt != _reportedUnknownSsrcs.end()) { |
| 2021 | _reportedUnknownSsrcs.erase(reportedIt); |
| 2022 | } |
| 2023 | auto mappingIt = _ssrcMapping.find(minActivityChannelId.actualSsrc); |
| 2024 | if (mappingIt != _ssrcMapping.end()) { |
| 2025 | _ssrcMapping.erase(mappingIt); |
| 2026 | } |
| 2027 | } |
| 2028 | } |
| 2029 |
| 2030 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 2031 |
| 2032 | std::unique_ptr<IncomingAudioChannel> channel(new IncomingAudioChannel( |
| 2033 | _channelManager.get(), |
| 2034 | _call.get(), |
| 2035 | _rtpTransport, |
| 2036 | _uniqueRandomIdGenerator.get(), |
| 2037 | isRawPcm, |
| 2038 | ssrc, |
| 2039 | [weak, ssrc = ssrc, threads = _threads](AudioSinkImpl::Update update) { |
| 2040 | threads->getProcessThread()->PostTask(RTC_FROM_HERE, [weak, ssrc, update]() { |
| 2041 | auto strong = weak.lock(); |
| 2042 | if (!strong) { |
| 2043 | return; |
| 2044 | } |
| 2045 | GroupLevelValue mappedUpdate; |
| 2046 | mappedUpdate.level = update.level; |
| 2047 | mappedUpdate.voice = update.vad->update(update.buffer.get()); |
| 2048 | strong->_audioLevels[ssrc] = mappedUpdate; |
| 2049 | }); |
| 2050 | }, |
| 2051 | _onAudioFrame, |
| 2052 | *_threads |
| 2053 | )); |
| 2054 |
| 2055 | auto volume = _volumeBySsrc.find(ssrc.actualSsrc); |
| 2056 | if (volume != _volumeBySsrc.end()) { |
| 2057 | channel->setVolume(volume->second); |
| 2058 | } |
| 2059 |
| 2060 | _incomingAudioChannels.insert(std::make_pair(ssrc, std::move(channel))); |
| 2061 |
| 2062 | SsrcMappingInfo mapping; |
| 2063 | mapping.ssrc = ssrc.networkSsrc; |
| 2064 | mapping.isVideo = false; |
| 2065 | mapping.endpointId = endpointId; |
| 2066 | _ssrcMapping.insert(std::make_pair(ssrc.networkSsrc, mapping)); |
| 2067 |
| 2068 | maybeDeliverBufferedPackets(ssrc.networkSsrc); |
| 2069 | } |
| 2070 |
| 2071 | void addIncomingVideoChannel(GroupParticipantDescription const &participant) { |
| 2072 | if (_incomingVideoChannels.find(participant.audioSsrc) != _incomingVideoChannels.end()) { |
| 2073 | return; |
| 2074 | } |
| 2075 |
| 2076 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 2077 |
| 2078 | std::unique_ptr<IncomingVideoChannel> channel(new IncomingVideoChannel( |
| 2079 | _channelManager.get(), |
| 2080 | _call.get(), |
| 2081 | _rtpTransport, |
| 2082 | _uniqueRandomIdGenerator.get(), |
| 2083 | _availableVideoFormats, |
| 2084 | participant, |
| 2085 | *_threads |
| 2086 | )); |
| 2087 | _incomingVideoChannels.insert(std::make_pair(participant.audioSsrc, std::move(channel))); |
| 2088 |
| 2089 | std::vector<uint32_t> allSsrcs; |
| 2090 | for (const auto &group : participant.videoSourceGroups) { |
| 2091 | for (auto ssrc : group.ssrcs) { |
| 2092 | if (_ssrcMapping.find(ssrc) == _ssrcMapping.end()) { |
| 2093 | allSsrcs.push_back(ssrc); |
| 2094 |
| 2095 | SsrcMappingInfo mapping; |
| 2096 | mapping.ssrc = participant.audioSsrc; |
| 2097 | mapping.isVideo = true; |
| 2098 | mapping.endpointId = participant.endpointId; |
| 2099 | _ssrcMapping.insert(std::make_pair(ssrc, mapping)); |
| 2100 | } |
| 2101 | } |
| 2102 | } |
| 2103 |
| 2104 | updateIncomingVideoSources(); |
| 2105 |
| 2106 | for (auto ssrc : allSsrcs) { |
| 2107 | maybeDeliverBufferedPackets(ssrc); |
| 2108 | } |
| 2109 | } |
| 2110 |
| 2111 | void updateIncomingVideoSources() { |
| 2112 | if (_incomingVideoSourcesUpdated) { |
| 2113 | std::vector<uint32_t> videoChannelSsrcs; |
| 2114 | for (const auto &it : _incomingVideoChannels) { |
| 2115 | videoChannelSsrcs.push_back(it.first); |
| 2116 | } |
| 2117 | _incomingVideoSourcesUpdated(videoChannelSsrcs); |
| 2118 | } |
| 2119 | } |
| 2120 |
| 2121 | void setVolume(uint32_t ssrc, double volume) { |
| 2122 | auto current = _volumeBySsrc.find(ssrc); |
| 2123 | if (current != _volumeBySsrc.end() && std::abs(current->second - volume) < 0.0001) { |
| 2124 | return; |
| 2125 | } |
| 2126 |
| 2127 | _volumeBySsrc[ssrc] = volume; |
| 2128 |
| 2129 | auto it = _incomingAudioChannels.find(ChannelId(ssrc)); |
| 2130 | if (it != _incomingAudioChannels.end()) { |
| 2131 | it->second->setVolume(volume); |
| 2132 | } |
| 2133 |
| 2134 | it = _incomingAudioChannels.find(ChannelId(ssrc + 1000, ssrc)); |
| 2135 | if (it != _incomingAudioChannels.end()) { |
| 2136 | it->second->setVolume(volume); |
| 2137 | } |
| 2138 | } |
| 2139 |
| 2140 | void setFullSizeVideoSsrc(uint32_t ssrc) { |
| 2141 | auto ssrcMapping = _ssrcMapping.find(ssrc); |
| 2142 | std::string currentHighQualityVideoEndpointId; |
| 2143 | if (ssrcMapping != _ssrcMapping.end()) { |
| 2144 | currentHighQualityVideoEndpointId = ssrcMapping->second.endpointId; |
| 2145 | } |
| 2146 | if (_currentHighQualityVideoEndpointId != currentHighQualityVideoEndpointId) { |
| 2147 | _currentHighQualityVideoEndpointId = currentHighQualityVideoEndpointId; |
| 2148 | maybeUpdateRemoteVideoConstaints(); |
| 2149 | } |
| 2150 | } |
| 2151 |
| 2152 | private: |
| 2153 | rtc::scoped_refptr<webrtc::AudioDeviceModule> createAudioDeviceModule() { |
| 2154 | const auto create = [&](webrtc::AudioDeviceModule::AudioLayer layer) { |
| 2155 | return webrtc::AudioDeviceModule::Create( |
| 2156 | layer, |
| 2157 | _taskQueueFactory.get()); |
| 2158 | }; |
| 2159 | const auto check = [&](const rtc::scoped_refptr<webrtc::AudioDeviceModule> &result) { |
| 2160 | return (result && result->Init() == 0) ? result : nullptr; |
| 2161 | }; |
| 2162 | if (_createAudioDeviceModule) { |
| 2163 | if (const auto result = check(_createAudioDeviceModule(_taskQueueFactory.get()))) { |
| 2164 | return result; |
| 2165 | } |
| 2166 | } |
| 2167 | return check(create(webrtc::AudioDeviceModule::kPlatformDefaultAudio)); |
| 2168 | } |
| 2169 |
| 2170 | private: |
| 2171 | std::shared_ptr<Threads> _threads; |
| 2172 | GroupConnectionMode _connectionMode = GroupConnectionMode::GroupConnectionModeNone; |
| 2173 |
| 2174 | std::function<void(GroupNetworkState)> _networkStateUpdated; |
| 2175 | std::function<void(GroupLevelsUpdate const &)> _audioLevelsUpdated; |
| 2176 | std::function<void(uint32_t, const AudioFrame &)> _onAudioFrame; |
| 2177 | std::function<void(std::vector<uint32_t> const &)> _incomingVideoSourcesUpdated; |
| 2178 | std::function<void(std::vector<uint32_t> const &)> _participantDescriptionsRequired; |
| 2179 | std::function<std::shared_ptr<BroadcastPartTask>(std::shared_ptr<PlatformContext>, int64_t, int64_t, std::function<void(BroadcastPart &&)>)> _requestBroadcastPart; |
| 2180 | std::shared_ptr<VideoCaptureInterface> _videoCapture; |
| 2181 | bool _disableIncomingChannels = false; |
| 2182 |
| 2183 | int64_t _lastUnknownSsrcsReport = 0; |
| 2184 | std::set<uint32_t> _pendingUnknownSsrcs; |
| 2185 | bool _isUnknownSsrcsScheduled = false; |
| 2186 | std::set<uint32_t> _reportedUnknownSsrcs; |
| 2187 |
| 2188 | std::unique_ptr<ThreadLocalObject<GroupNetworkManager>> _networkManager; |
| 2189 |
| 2190 | std::unique_ptr<webrtc::RtcEventLogNull> _eventLog; |
| 2191 | std::unique_ptr<webrtc::TaskQueueFactory> _taskQueueFactory; |
| 2192 | std::unique_ptr<cricket::MediaEngineInterface> _mediaEngine; |
| 2193 | std::unique_ptr<webrtc::Call> _call; |
| 2194 | webrtc::FieldTrialBasedConfig _fieldTrials; |
| 2195 | webrtc::LocalAudioSinkAdapter _audioSource; |
| 2196 | rtc::scoped_refptr<webrtc::AudioDeviceModule> _audioDeviceModule; |
| 2197 | std::function<rtc::scoped_refptr<webrtc::AudioDeviceModule>(webrtc::TaskQueueFactory*)> _createAudioDeviceModule; |
| 2198 | std::string _initialInputDeviceId; |
| 2199 | std::string _initialOutputDeviceId; |
| 2200 |
| 2201 | // _outgoingAudioChannel memory is managed by _channelManager |
| 2202 | cricket::VoiceChannel *_outgoingAudioChannel = nullptr; |
| 2203 | uint32_t _outgoingAudioSsrc = 0; |
| 2204 |
| 2205 | std::vector<webrtc::SdpVideoFormat> _availableVideoFormats; |
| 2206 |
| 2207 | std::vector<GroupJoinPayloadVideoPayloadType> _videoPayloadTypes; |
| 2208 | std::vector<std::pair<uint32_t, std::string>> _videoExtensionMap; |
| 2209 | std::vector<GroupJoinPayloadVideoSourceGroup> _videoSourceGroups; |
| 2210 |
| 2211 | std::unique_ptr<rtc::UniqueRandomIdGenerator> _uniqueRandomIdGenerator; |
| 2212 | webrtc::RtpTransport *_rtpTransport = nullptr; |
| 2213 | std::unique_ptr<cricket::ChannelManager> _channelManager; |
| 2214 |
| 2215 | std::unique_ptr<webrtc::VideoBitrateAllocatorFactory> _videoBitrateAllocatorFactory; |
| 2216 | // _outgoingVideoChannel memory is managed by _channelManager |
| 2217 | cricket::VideoChannel *_outgoingVideoChannel = nullptr; |
| 2218 | VideoSsrcs _outgoingVideoSsrcs; |
| 2219 |
| 2220 | std::map<ChannelId, GroupLevelValue> _audioLevels; |
| 2221 | GroupLevelValue _myAudioLevel; |
| 2222 |
| 2223 | bool _isMuted = true; |
| 2224 |
| 2225 | MissingSsrcPacketBuffer _missingPacketBuffer; |
| 2226 | std::map<uint32_t, SsrcMappingInfo> _ssrcMapping; |
| 2227 | std::map<uint32_t, double> _volumeBySsrc; |
| 2228 | std::map<ChannelId, std::unique_ptr<IncomingAudioChannel>> _incomingAudioChannels; |
| 2229 | std::map<uint32_t, std::unique_ptr<IncomingVideoChannel>> _incomingVideoChannels; |
| 2230 |
| 2231 | std::string _currentHighQualityVideoEndpointId; |
| 2232 |
| 2233 | int64_t _broadcastPartDurationMilliseconds = 500; |
| 2234 | std::vector<std::unique_ptr<StreamingPart>> _sourceBroadcastParts; |
| 2235 | std::map<uint32_t, uint16_t> _broadcastSeqBySsrc; |
| 2236 | uint32_t _broadcastTimestamp = 0; |
| 2237 | int64_t _nextBroadcastTimestampMilliseconds = 0; |
| 2238 | absl::optional<RequestedBroadcastPart> _currentRequestedBroadcastPart; |
| 2239 | int64_t _lastBroadcastPartReceivedTimestamp = 0; |
| 2240 |
| 2241 | bool _isRtcConnected = false; |
| 2242 | bool _isBroadcastConnected = false; |
| 2243 | absl::optional<int64_t> _broadcastEnabledUntilRtcIsConnectedAtTimestamp; |
| 2244 | bool _isDataChannelOpen = false; |
| 2245 | GroupNetworkState _effectiveNetworkState; |
| 2246 |
| 2247 | std::shared_ptr<PlatformContext> _platformContext; |
| 2248 | }; |
| 2249 |
| 2250 | GroupInstanceCustomImpl::GroupInstanceCustomImpl(GroupInstanceDescriptor &&descriptor) { |
| 2251 | if (descriptor.config.need_log) { |
| 2252 | _logSink = std::make_unique<LogSinkImpl>(descriptor.config.logPath); |
| 2253 | } |
| 2254 | rtc::LogMessage::LogToDebug(rtc::LS_INFO); |
| 2255 | rtc::LogMessage::SetLogToStderr(false); |
| 2256 | if (_logSink) { |
| 2257 | rtc::LogMessage::AddLogToStream(_logSink.get(), rtc::LS_INFO); |
| 2258 | } |
| 2259 |
| 2260 | _threads = descriptor.threads; |
| 2261 | _internal.reset(new ThreadLocalObject<GroupInstanceCustomInternal>(_threads->getMediaThread(), [descriptor = std::move(descriptor), threads = _threads]() mutable { |
| 2262 | return new GroupInstanceCustomInternal(std::move(descriptor), threads); |
| 2263 | })); |
| 2264 | _internal->perform(RTC_FROM_HERE, [](GroupInstanceCustomInternal *internal) { |
| 2265 | internal->start(); |
| 2266 | }); |
| 2267 | } |
| 2268 |
| 2269 | GroupInstanceCustomImpl::~GroupInstanceCustomImpl() { |
| 2270 | if (_logSink) { |
| 2271 | rtc::LogMessage::RemoveLogToStream(_logSink.get()); |
| 2272 | } |
| 2273 | _internal.reset(); |
| 2274 |
| 2275 | // Wait until _internal is destroyed |
| 2276 | _threads->getMediaThread()->Invoke<void>(RTC_FROM_HERE, [] {}); |
| 2277 | } |
| 2278 |
| 2279 | void GroupInstanceCustomImpl::stop() { |
| 2280 | _internal->perform(RTC_FROM_HERE, [](GroupInstanceCustomInternal *internal) { |
| 2281 | internal->stop(); |
| 2282 | }); |
| 2283 | } |
| 2284 |
| 2285 | void GroupInstanceCustomImpl::setConnectionMode(GroupConnectionMode connectionMode, bool keepBroadcastIfWasEnabled) { |
| 2286 | _internal->perform(RTC_FROM_HERE, [connectionMode, keepBroadcastIfWasEnabled](GroupInstanceCustomInternal *internal) { |
| 2287 | internal->setConnectionMode(connectionMode, keepBroadcastIfWasEnabled); |
| 2288 | }); |
| 2289 | } |
| 2290 |
| 2291 | void GroupInstanceCustomImpl::emitJoinPayload(std::function<void(GroupJoinPayload)> completion) { |
| 2292 | _internal->perform(RTC_FROM_HERE, [completion](GroupInstanceCustomInternal *internal) { |
| 2293 | internal->emitJoinPayload(completion); |
| 2294 | }); |
| 2295 | } |
| 2296 |
| 2297 | void GroupInstanceCustomImpl::setJoinResponsePayload(GroupJoinResponsePayload payload, std::vector<tgcalls::GroupParticipantDescription> &&participants) { |
| 2298 | _internal->perform(RTC_FROM_HERE, [payload, participants = std::move(participants)](GroupInstanceCustomInternal *internal) mutable { |
| 2299 | internal->setJoinResponsePayload(payload, std::move(participants)); |
| 2300 | }); |
| 2301 | } |
| 2302 |
| 2303 | void GroupInstanceCustomImpl::addParticipants(std::vector<GroupParticipantDescription> &&participants) { |
| 2304 | _internal->perform(RTC_FROM_HERE, [participants = std::move(participants)](GroupInstanceCustomInternal *internal) mutable { |
| 2305 | internal->addParticipants(std::move(participants)); |
| 2306 | }); |
| 2307 | } |
| 2308 |
| 2309 | void GroupInstanceCustomImpl::removeSsrcs(std::vector<uint32_t> ssrcs) { |
| 2310 | _internal->perform(RTC_FROM_HERE, [ssrcs = std::move(ssrcs)](GroupInstanceCustomInternal *internal) mutable { |
| 2311 | internal->removeSsrcs(ssrcs); |
| 2312 | }); |
| 2313 | } |
| 2314 |
| 2315 | void GroupInstanceCustomImpl::setIsMuted(bool isMuted) { |
| 2316 | _internal->perform(RTC_FROM_HERE, [isMuted](GroupInstanceCustomInternal *internal) { |
| 2317 | internal->setIsMuted(isMuted); |
| 2318 | }); |
| 2319 | } |
| 2320 |
| 2321 | void GroupInstanceCustomImpl::setVideoCapture(std::shared_ptr<VideoCaptureInterface> videoCapture, std::function<void(GroupJoinPayload)> completion) { |
| 2322 | _internal->perform(RTC_FROM_HERE, [videoCapture, completion](GroupInstanceCustomInternal *internal) { |
| 2323 | internal->setVideoCapture(videoCapture, completion, false); |
| 2324 | }); |
| 2325 | } |
| 2326 |
| 2327 | void GroupInstanceCustomImpl::setAudioOutputDevice(std::string id) { |
| 2328 | _internal->perform(RTC_FROM_HERE, [id](GroupInstanceCustomInternal *internal) { |
| 2329 | internal->setAudioOutputDevice(id); |
| 2330 | }); |
| 2331 | } |
| 2332 |
| 2333 | void GroupInstanceCustomImpl::setAudioInputDevice(std::string id) { |
| 2334 | _internal->perform(RTC_FROM_HERE, [id](GroupInstanceCustomInternal *internal) { |
| 2335 | internal->setAudioInputDevice(id); |
| 2336 | }); |
| 2337 | } |
| 2338 |
| 2339 | void GroupInstanceCustomImpl::addIncomingVideoOutput(uint32_t ssrc, std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) { |
| 2340 | _internal->perform(RTC_FROM_HERE, [ssrc, sink](GroupInstanceCustomInternal *internal) mutable { |
| 2341 | internal->addIncomingVideoOutput(ssrc, sink); |
| 2342 | }); |
| 2343 | } |
| 2344 |
| 2345 | void GroupInstanceCustomImpl::setVolume(uint32_t ssrc, double volume) { |
| 2346 | _internal->perform(RTC_FROM_HERE, [ssrc, volume](GroupInstanceCustomInternal *internal) { |
| 2347 | internal->setVolume(ssrc, volume); |
| 2348 | }); |
| 2349 | } |
| 2350 |
| 2351 | void GroupInstanceCustomImpl::setFullSizeVideoSsrc(uint32_t ssrc) { |
| 2352 | _internal->perform(RTC_FROM_HERE, [ssrc](GroupInstanceCustomInternal *internal) { |
| 2353 | internal->setFullSizeVideoSsrc(ssrc); |
| 2354 | }); |
| 2355 | } |
| 2356 |
| 2357 | } // namespace tgcalls |
| 2358 |