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