| 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 "media/base/rtp_utils.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/cpu_features.h" |
| 32 | #include "modules/audio_processing/agc2/vad_wrapper.h" |
| 33 | #include "pc/channel.h" |
| 34 | #include "pc/rtp_transport.h" |
| 35 | #include "audio/audio_state.h" |
| 36 | #include "modules/audio_coding/neteq/default_neteq_factory.h" |
| 37 | #include "modules/audio_coding/include/audio_coding_module.h" |
| 38 | #include "common_audio/include/audio_util.h" |
| 39 | #include "modules/audio_device/include/audio_device_data_observer.h" |
| 40 | #include "common_audio/resampler/include/resampler.h" |
| 41 | #include "modules/rtp_rtcp/source/rtp_util.h" |
| 42 |
| 43 | #include "ChannelManager.h" |
| 44 | #include "AudioFrame.h" |
| 45 | #include "ThreadLocalObject.h" |
| 46 | #include "Manager.h" |
| 47 | #include "NetworkManager.h" |
| 48 | #include "VideoCaptureInterfaceImpl.h" |
| 49 | #include "platform/PlatformInterface.h" |
| 50 | #include "LogSinkImpl.h" |
| 51 | #include "CodecSelectHelper.h" |
| 52 | #include "AudioStreamingPart.h" |
| 53 | #include "VideoStreamingPart.h" |
| 54 | #include "AudioDeviceHelper.h" |
| 55 | #include "FakeAudioDeviceModule.h" |
| 56 | #include "StreamingMediaContext.h" |
| 57 | #ifdef WEBRTC_IOS |
| 58 | #include "platform/darwin/iOS/tgcalls_audio_device_module_ios.h" |
| 59 | #endif |
| 60 | #include <mutex> |
| 61 | #include <random> |
| 62 | #include <sstream> |
| 63 | #include <iostream> |
| 64 |
| 65 |
| 66 | #ifndef USE_RNNOISE |
| 67 | #define USE_RNNOISE 1 |
| 68 | #endif |
| 69 |
| 70 | #if USE_RNNOISE |
| 71 | #include "rnnoise.h" |
| 72 | #endif |
| 73 |
| 74 | #include "GroupJoinPayloadInternal.h" |
| 75 | #include "FieldTrialsConfig.h" |
| 76 |
| 77 | #include "third-party/json11.hpp" |
| 78 |
| 79 | namespace tgcalls { |
| 80 |
| 81 | namespace { |
| 82 |
| 83 | template <typename Out> |
| 84 | void splitString(const std::string &s, char delim, Out result) { |
| 85 | std::istringstream iss(s); |
| 86 | std::string item; |
| 87 | while (std::getline(iss, item, delim)) { |
| 88 | *result++ = item; |
| 89 | } |
| 90 | } |
| 91 |
| 92 | std::vector<std::string> splitString(const std::string &s, char delim) { |
| 93 | std::vector<std::string> elems; |
| 94 | splitString(s, delim, std::back_inserter(elems)); |
| 95 | return elems; |
| 96 | } |
| 97 |
| 98 | static int stringToInt(std::string const &string) { |
| 99 | std::stringstream stringStream(string); |
| 100 | int value = 0; |
| 101 | stringStream >> value; |
| 102 | return value; |
| 103 | } |
| 104 |
| 105 | static std::string intToString(int value) { |
| 106 | std::ostringstream stringStream; |
| 107 | stringStream << value; |
| 108 | return stringStream.str(); |
| 109 | } |
| 110 |
| 111 | static std::string uint32ToString(uint32_t value) { |
| 112 | std::ostringstream stringStream; |
| 113 | stringStream << value; |
| 114 | return stringStream.str(); |
| 115 | } |
| 116 |
| 117 | static uint32_t stringToUInt32(std::string const &string) { |
| 118 | std::stringstream stringStream(string); |
| 119 | uint32_t value = 0; |
| 120 | stringStream >> value; |
| 121 | return value; |
| 122 | } |
| 123 |
| 124 | static uint16_t stringToUInt16(std::string const &string) { |
| 125 | std::stringstream stringStream(string); |
| 126 | uint16_t value = 0; |
| 127 | stringStream >> value; |
| 128 | return value; |
| 129 | } |
| 130 |
| 131 | static std::string formatTimestampMillis(int64_t timestamp) { |
| 132 | std::ostringstream stringStream; |
| 133 | stringStream << std::fixed << std::setprecision(3) << (double)timestamp / 1000.0; |
| 134 | return stringStream.str(); |
| 135 | } |
| 136 |
| 137 | static VideoCaptureInterfaceObject *GetVideoCaptureAssumingSameThread(VideoCaptureInterface *videoCapture) { |
| 138 | return videoCapture |
| 139 | ? static_cast<VideoCaptureInterfaceImpl*>(videoCapture)->object()->getSyncAssumingSameThread() |
| 140 | : nullptr; |
| 141 | } |
| 142 |
| 143 | struct OutgoingVideoFormat { |
| 144 | cricket::VideoCodec videoCodec; |
| 145 | cricket::VideoCodec rtxCodec; |
| 146 | }; |
| 147 |
| 148 | static void addDefaultFeedbackParams(cricket::VideoCodec *codec) { |
| 149 | // Don't add any feedback params for RED and ULPFEC. |
| 150 | if (codec->name == cricket::kRedCodecName || codec->name == cricket::kUlpfecCodecName) { |
| 151 | return; |
| 152 | } |
| 153 | codec->AddFeedbackParam(cricket::FeedbackParam(cricket::kRtcpFbParamRemb, cricket::kParamValueEmpty)); |
| 154 | codec->AddFeedbackParam(cricket::FeedbackParam(cricket::kRtcpFbParamTransportCc, cricket::kParamValueEmpty)); |
| 155 | // Don't add any more feedback params for FLEXFEC. |
| 156 | if (codec->name == cricket::kFlexfecCodecName) { |
| 157 | return; |
| 158 | } |
| 159 | codec->AddFeedbackParam(cricket::FeedbackParam(cricket::kRtcpFbParamCcm, cricket::kRtcpFbCcmParamFir)); |
| 160 | codec->AddFeedbackParam(cricket::FeedbackParam(cricket::kRtcpFbParamNack, cricket::kParamValueEmpty)); |
| 161 | codec->AddFeedbackParam(cricket::FeedbackParam(cricket::kRtcpFbParamNack, cricket::kRtcpFbNackParamPli)); |
| 162 | } |
| 163 |
| 164 | struct H264FormatParameters { |
| 165 | std::string profileLevelId; |
| 166 | std::string packetizationMode; |
| 167 | std::string levelAssymetryAllowed; |
| 168 | }; |
| 169 |
| 170 | H264FormatParameters parseH264FormatParameters(webrtc::SdpVideoFormat const &format) { |
| 171 | H264FormatParameters result; |
| 172 |
| 173 | for (const auto ¶meter : format.parameters) { |
| 174 | if (parameter.first == "profile-level-id") { |
| 175 | result.profileLevelId = parameter.second; |
| 176 | } else if (parameter.first == "packetization-mode") { |
| 177 | result.packetizationMode = parameter.second; |
| 178 | } else if (parameter.first == "level-asymmetry-allowed") { |
| 179 | result.levelAssymetryAllowed = parameter.second; |
| 180 | } |
| 181 | } |
| 182 |
| 183 | return result; |
| 184 | } |
| 185 |
| 186 | static int getH264ProfileLevelIdPriority(std::string const &profileLevelId) { |
| 187 | if (profileLevelId == cricket::kH264ProfileLevelConstrainedHigh) { |
| 188 | return 0; |
| 189 | } else if (profileLevelId == cricket::kH264ProfileLevelConstrainedBaseline) { |
| 190 | return 1; |
| 191 | } else { |
| 192 | return 2; |
| 193 | } |
| 194 | } |
| 195 |
| 196 | static int getH264PacketizationModePriority(std::string const &packetizationMode) { |
| 197 | if (packetizationMode == "1") { |
| 198 | return 0; |
| 199 | } else { |
| 200 | return 1; |
| 201 | } |
| 202 | } |
| 203 |
| 204 | static int getH264LevelAssymetryAllowedPriority(std::string const &levelAssymetryAllowed) { |
| 205 | if (levelAssymetryAllowed == "1") { |
| 206 | return 0; |
| 207 | } else { |
| 208 | return 1; |
| 209 | } |
| 210 | } |
| 211 |
| 212 | static std::vector<webrtc::SdpVideoFormat> filterSupportedVideoFormats(std::vector<webrtc::SdpVideoFormat> const &formats) { |
| 213 | std::vector<webrtc::SdpVideoFormat> filteredFormats; |
| 214 |
| 215 | std::vector<std::string> filterCodecNames = { |
| 216 | cricket::kVp8CodecName, |
| 217 | cricket::kVp9CodecName, |
| 218 | cricket::kH264CodecName |
| 219 | }; |
| 220 |
| 221 | std::vector<webrtc::SdpVideoFormat> vp9Formats; |
| 222 | std::vector<webrtc::SdpVideoFormat> h264Formats; |
| 223 |
| 224 | for (const auto &format : formats) { |
| 225 | if (std::find(filterCodecNames.begin(), filterCodecNames.end(), format.name) == filterCodecNames.end()) { |
| 226 | continue; |
| 227 | } |
| 228 |
| 229 | if (format.name == cricket::kVp9CodecName) { |
| 230 | vp9Formats.push_back(format); |
| 231 | } else if (format.name == cricket::kH264CodecName) { |
| 232 | h264Formats.push_back(format); |
| 233 | } else { |
| 234 | filteredFormats.push_back(format); |
| 235 | } |
| 236 | } |
| 237 |
| 238 | if (!vp9Formats.empty()) { |
| 239 | bool added = false; |
| 240 | for (const auto &format : vp9Formats) { |
| 241 | if (added) { |
| 242 | break; |
| 243 | } |
| 244 | for (const auto ¶meter : format.parameters) { |
| 245 | if (parameter.first == "profile-id") { |
| 246 | if (parameter.second == "0") { |
| 247 | filteredFormats.push_back(format); |
| 248 | added = true; |
| 249 | break; |
| 250 | } |
| 251 | } |
| 252 | } |
| 253 | } |
| 254 |
| 255 | if (!added) { |
| 256 | filteredFormats.push_back(vp9Formats[0]); |
| 257 | } |
| 258 | } |
| 259 |
| 260 | if (!h264Formats.empty()) { |
| 261 | std::sort(h264Formats.begin(), h264Formats.end(), [](const webrtc::SdpVideoFormat &lhs, const webrtc::SdpVideoFormat &rhs) { |
| 262 | auto lhsParameters = parseH264FormatParameters(lhs); |
| 263 | auto rhsParameters = parseH264FormatParameters(rhs); |
| 264 |
| 265 | int lhsLevelIdPriority = getH264ProfileLevelIdPriority(lhsParameters.profileLevelId); |
| 266 | int lhsPacketizationModePriority = getH264PacketizationModePriority(lhsParameters.packetizationMode); |
| 267 | int lhsLevelAssymetryAllowedPriority = getH264LevelAssymetryAllowedPriority(lhsParameters.levelAssymetryAllowed); |
| 268 |
| 269 | int rhsLevelIdPriority = getH264ProfileLevelIdPriority(rhsParameters.profileLevelId); |
| 270 | int rhsPacketizationModePriority = getH264PacketizationModePriority(rhsParameters.packetizationMode); |
| 271 | int rhsLevelAssymetryAllowedPriority = getH264LevelAssymetryAllowedPriority(rhsParameters.levelAssymetryAllowed); |
| 272 |
| 273 | if (lhsLevelIdPriority != rhsLevelIdPriority) { |
| 274 | return lhsLevelIdPriority < rhsLevelIdPriority; |
| 275 | } |
| 276 | if (lhsPacketizationModePriority != rhsPacketizationModePriority) { |
| 277 | return lhsPacketizationModePriority < rhsPacketizationModePriority; |
| 278 | } |
| 279 | if (lhsLevelAssymetryAllowedPriority != rhsLevelAssymetryAllowedPriority) { |
| 280 | return lhsLevelAssymetryAllowedPriority < rhsLevelAssymetryAllowedPriority; |
| 281 | } |
| 282 |
| 283 | return false; |
| 284 | }); |
| 285 |
| 286 | filteredFormats.push_back(h264Formats[0]); |
| 287 | } |
| 288 |
| 289 | return filteredFormats; |
| 290 | } |
| 291 |
| 292 | static std::vector<OutgoingVideoFormat> assignPayloadTypes(std::vector<webrtc::SdpVideoFormat> const &formats) { |
| 293 | if (formats.empty()) { |
| 294 | return {}; |
| 295 | } |
| 296 |
| 297 | constexpr int kFirstDynamicPayloadType = 100; |
| 298 | constexpr int kLastDynamicPayloadType = 127; |
| 299 |
| 300 | int payload_type = kFirstDynamicPayloadType; |
| 301 |
| 302 | std::vector<OutgoingVideoFormat> result; |
| 303 |
| 304 | std::vector<std::string> filterCodecNames = { |
| 305 | cricket::kVp8CodecName, |
| 306 | cricket::kVp9CodecName, |
| 307 | cricket::kH264CodecName, |
| 308 | }; |
| 309 |
| 310 | for (const auto &codecName : filterCodecNames) { |
| 311 | for (const auto &format : formats) { |
| 312 | if (format.name != codecName) { |
| 313 | continue; |
| 314 | } |
| 315 |
| 316 | cricket::VideoCodec codec(format); |
| 317 | codec.id = payload_type; |
| 318 | addDefaultFeedbackParams(&codec); |
| 319 |
| 320 | OutgoingVideoFormat resultFormat; |
| 321 |
| 322 | resultFormat.videoCodec = codec; |
| 323 |
| 324 | // Increment payload type. |
| 325 | ++payload_type; |
| 326 | if (payload_type > kLastDynamicPayloadType) { |
| 327 | RTC_LOG(LS_ERROR) << "Out of dynamic payload types, skipping the rest."; |
| 328 | break; |
| 329 | } |
| 330 |
| 331 | // Add associated RTX codec for non-FEC codecs. |
| 332 | if (!absl::EqualsIgnoreCase(codec.name, cricket::kUlpfecCodecName) && |
| 333 | !absl::EqualsIgnoreCase(codec.name, cricket::kFlexfecCodecName)) { |
| 334 | resultFormat.rtxCodec = cricket::VideoCodec::CreateRtxCodec(payload_type, codec.id); |
| 335 |
| 336 | // Increment payload type. |
| 337 | ++payload_type; |
| 338 | if (payload_type > kLastDynamicPayloadType) { |
| 339 | RTC_LOG(LS_ERROR) << "Out of dynamic payload types, skipping the rest."; |
| 340 | break; |
| 341 | } |
| 342 | } |
| 343 |
| 344 | result.push_back(std::move(resultFormat)); |
| 345 | } |
| 346 | } |
| 347 |
| 348 | return result; |
| 349 | } |
| 350 |
| 351 | struct VideoSsrcs { |
| 352 | struct SimulcastLayer { |
| 353 | uint32_t ssrc = 0; |
| 354 | uint32_t fidSsrc = 0; |
| 355 |
| 356 | SimulcastLayer(uint32_t ssrc_, uint32_t fidSsrc_) : |
| 357 | ssrc(ssrc_), fidSsrc(fidSsrc_) { |
| 358 | } |
| 359 |
| 360 | SimulcastLayer(const SimulcastLayer &other) : |
| 361 | ssrc(other.ssrc), fidSsrc(other.fidSsrc) { |
| 362 | } |
| 363 | }; |
| 364 |
| 365 | std::vector<SimulcastLayer> simulcastLayers; |
| 366 |
| 367 | VideoSsrcs() { |
| 368 | } |
| 369 |
| 370 | VideoSsrcs(const VideoSsrcs &other) : |
| 371 | simulcastLayers(other.simulcastLayers) { |
| 372 | } |
| 373 | }; |
| 374 |
| 375 | struct InternalGroupLevelValue { |
| 376 | GroupLevelValue value; |
| 377 | int64_t timestamp = 0; |
| 378 | }; |
| 379 |
| 380 | struct ChannelId { |
| 381 | uint32_t networkSsrc = 0; |
| 382 | uint32_t actualSsrc = 0; |
| 383 |
| 384 | ChannelId(uint32_t networkSsrc_, uint32_t actualSsrc_) : |
| 385 | networkSsrc(networkSsrc_), |
| 386 | actualSsrc(actualSsrc_) { |
| 387 | } |
| 388 |
| 389 | explicit ChannelId(uint32_t networkSsrc_) : |
| 390 | networkSsrc(networkSsrc_), |
| 391 | actualSsrc(networkSsrc_) { |
| 392 | } |
| 393 |
| 394 | bool operator <(const ChannelId& rhs) const { |
| 395 | if (networkSsrc != rhs.networkSsrc) { |
| 396 | return networkSsrc < rhs.networkSsrc; |
| 397 | } |
| 398 | return actualSsrc < rhs.actualSsrc; |
| 399 | } |
| 400 |
| 401 | std::string name() { |
| 402 | if (networkSsrc == actualSsrc) { |
| 403 | return uint32ToString(networkSsrc); |
| 404 | } else { |
| 405 | return uint32ToString(networkSsrc) + "to" + uint32ToString(actualSsrc); |
| 406 | } |
| 407 | } |
| 408 | }; |
| 409 |
| 410 | struct VideoChannelId { |
| 411 | std::string endpointId; |
| 412 |
| 413 | explicit VideoChannelId(std::string const &endpointId_) : |
| 414 | endpointId(endpointId_) { |
| 415 | } |
| 416 |
| 417 | bool operator <(const VideoChannelId& rhs) const { |
| 418 | return endpointId < rhs.endpointId; |
| 419 | } |
| 420 | }; |
| 421 |
| 422 | struct ChannelSsrcInfo { |
| 423 | enum class Type { |
| 424 | Audio, |
| 425 | Video |
| 426 | }; |
| 427 |
| 428 | Type type = Type::Audio; |
| 429 | std::vector<uint32_t> allSsrcs; |
| 430 | std::string videoEndpointId; |
| 431 | }; |
| 432 |
| 433 | struct RequestedMediaChannelDescriptions { |
| 434 | std::shared_ptr<RequestMediaChannelDescriptionTask> task; |
| 435 | std::vector<uint32_t> ssrcs; |
| 436 |
| 437 | RequestedMediaChannelDescriptions(std::shared_ptr<RequestMediaChannelDescriptionTask> task_, std::vector<uint32_t> ssrcs_) : |
| 438 | task(task_), ssrcs(std::move(ssrcs_)) { |
| 439 | } |
| 440 | }; |
| 441 |
| 442 | static const int kVadResultHistoryLength = 6; |
| 443 |
| 444 | class VadHistory { |
| 445 | private: |
| 446 | float _vadResultHistory[kVadResultHistoryLength]; |
| 447 |
| 448 | public: |
| 449 | VadHistory() { |
| 450 | for (float & i : _vadResultHistory) { |
| 451 | i = 0.0f; |
| 452 | } |
| 453 | } |
| 454 |
| 455 | ~VadHistory() = default; |
| 456 |
| 457 | bool update(float vadProbability) { |
| 458 | if (vadProbability >= 0.0f) { |
| 459 | for (int i = 1; i < kVadResultHistoryLength; i++) { |
| 460 | _vadResultHistory[i - 1] = _vadResultHistory[i]; |
| 461 | } |
| 462 | _vadResultHistory[kVadResultHistoryLength - 1] = vadProbability; |
| 463 | } |
| 464 |
| 465 | float movingAverage = 0.0f; |
| 466 | for (float i : _vadResultHistory) { |
| 467 | movingAverage += i; |
| 468 | } |
| 469 | movingAverage /= (float)kVadResultHistoryLength; |
| 470 |
| 471 | return movingAverage > 0.6f; |
| 472 | } |
| 473 | }; |
| 474 |
| 475 | class CombinedVad { |
| 476 | private: |
| 477 | webrtc::VoiceActivityDetectorWrapper _vadWithLevel; |
| 478 | VadHistory _history; |
| 479 | bool _countFrames; |
| 480 | std::atomic<int32_t> _waitingFramesToProcess{0}; |
| 481 |
| 482 | public: |
| 483 | CombinedVad() : |
| 484 | _vadWithLevel(500, webrtc::GetAvailableCpuFeatures(), webrtc::AudioProcessing::kSampleRate48kHz) { |
| 485 | } |
| 486 |
| 487 | ~CombinedVad() = default; |
| 488 |
| 489 | bool incWaitingFrames() { |
| 490 | if (_waitingFramesToProcess > 5) { |
| 491 | return false; |
| 492 | } |
| 493 | _waitingFramesToProcess++; |
| 494 | return true; |
| 495 | } |
| 496 |
| 497 | bool update(webrtc::AudioBuffer *buffer) { |
| 498 | if (buffer->num_channels() <= 0) { |
| 499 | return _history.update(0.0f); |
| 500 | } |
| 501 | webrtc::AudioFrameView<float> frameView(buffer->channels(), (int)(buffer->num_channels()), (int)(buffer->num_frames())); |
| 502 | float peak = 0.0f; |
| 503 | for (const auto &x : frameView.channel(0)) { |
| 504 | peak = std::max(std::fabs(x), peak); |
| 505 | } |
| 506 | if (peak <= 0.01f) { |
| 507 | return _history.update(false); |
| 508 | } |
| 509 |
| 510 | auto result = _vadWithLevel.Analyze(frameView); |
| 511 |
| 512 | return _history.update(result); |
| 513 | } |
| 514 |
| 515 | bool update() { |
| 516 | return _history.update(0.0f); |
| 517 | } |
| 518 | }; |
| 519 |
| 520 | class SparseVad { |
| 521 | public: |
| 522 | SparseVad() { |
| 523 | } |
| 524 |
| 525 | bool update(webrtc::AudioBuffer *buffer) { |
| 526 | _sampleCount += buffer->num_frames(); |
| 527 | if (_sampleCount < 400) { |
| 528 | return _currentValue; |
| 529 | } |
| 530 | _sampleCount = 0; |
| 531 |
| 532 | _currentValue = _vad.update(buffer); |
| 533 |
| 534 | return _currentValue; |
| 535 | } |
| 536 |
| 537 | private: |
| 538 | CombinedVad _vad; |
| 539 | bool _currentValue = false; |
| 540 | size_t _sampleCount = 0; |
| 541 | }; |
| 542 |
| 543 | class AudioSinkImpl: public webrtc::AudioSinkInterface { |
| 544 | public: |
| 545 | struct Update { |
| 546 | float level = 0.0f; |
| 547 | bool hasSpeech = false; |
| 548 |
| 549 | Update(float level_, bool hasSpech_) : |
| 550 | level(level_), hasSpeech(hasSpech_) { |
| 551 | } |
| 552 |
| 553 | Update(const Update &other) : |
| 554 | level(other.level), hasSpeech(other.hasSpeech) { |
| 555 | } |
| 556 | }; |
| 557 |
| 558 | public: |
| 559 | AudioSinkImpl(std::function<void(Update)> update, |
| 560 | ChannelId channel_id, std::function<void(uint32_t, const AudioFrame &)> onAudioFrame) : |
| 561 | _update(update), _channel_id(channel_id), _onAudioFrame(std::move(onAudioFrame)) { |
| 562 | //_vad = std::make_shared<CombinedVad>(true); |
| 563 | } |
| 564 |
| 565 | virtual ~AudioSinkImpl() { |
| 566 | } |
| 567 |
| 568 | virtual void OnData(const Data& audio) override { |
| 569 | if (_onAudioFrame) { |
| 570 | AudioFrame frame; |
| 571 | frame.audio_samples = audio.data; |
| 572 | frame.num_samples = audio.samples_per_channel; |
| 573 | frame.bytes_per_sample = 2; |
| 574 | frame.num_channels = audio.channels; |
| 575 | frame.samples_per_sec = audio.sample_rate; |
| 576 | frame.elapsed_time_ms = 0; |
| 577 | frame.ntp_time_ms = 0; |
| 578 | _onAudioFrame(_channel_id.actualSsrc, frame); |
| 579 | } |
| 580 | if (_update && audio.channels == 1) { |
| 581 | const int16_t *samples = (const int16_t *)audio.data; |
| 582 | int numberOfSamplesInFrame = (int)audio.samples_per_channel; |
| 583 |
| 584 | int16_t currentPeak = 0; |
| 585 | for (int i = 0; i < numberOfSamplesInFrame; i++) { |
| 586 | int16_t sample = samples[i]; |
| 587 | if (sample < 0) { |
| 588 | sample = -sample; |
| 589 | } |
| 590 | if (_peak < sample) { |
| 591 | _peak = sample; |
| 592 | } |
| 593 | if (currentPeak < sample) { |
| 594 | currentPeak = sample; |
| 595 | } |
| 596 | _peakCount += 1; |
| 597 | } |
| 598 |
| 599 | if (_peakCount >= 4400) { |
| 600 | float level = ((float)(_peak)) / 8000.0f; |
| 601 | _peak = 0; |
| 602 | _peakCount = 0; |
| 603 | _update(Update(level, level >= 1.0f)); |
| 604 | } |
| 605 | } |
| 606 | } |
| 607 |
| 608 | private: |
| 609 | std::function<void(Update)> _update; |
| 610 | ChannelId _channel_id; |
| 611 | std::function<void(uint32_t, const AudioFrame &)> _onAudioFrame; |
| 612 | std::shared_ptr<CombinedVad> _vad; |
| 613 |
| 614 | int _peakCount = 0; |
| 615 | uint16_t _peak = 0; |
| 616 | }; |
| 617 |
| 618 | class VideoSinkImpl : public rtc::VideoSinkInterface<webrtc::VideoFrame> { |
| 619 | public: |
| 620 | VideoSinkImpl(std::string const &endpointId) : |
| 621 | _endpointId(endpointId) { |
| 622 | } |
| 623 |
| 624 | virtual ~VideoSinkImpl() { |
| 625 | } |
| 626 |
| 627 | virtual void OnFrame(const webrtc::VideoFrame& frame) override { |
| 628 | std::unique_lock<std::mutex> lock{ _mutex }; |
| 629 | int64_t timestamp = rtc::TimeMillis(); |
| 630 | if (_lastFrame) { |
| 631 | if (_lastFrame->video_frame_buffer()->width() != frame.video_frame_buffer()->width()) { |
| 632 | int64_t deltaTime = std::abs(_lastFrameSizeChangeTimestamp - timestamp); |
| 633 | if (deltaTime < 200) { |
| 634 | RTC_LOG(LS_WARNING) << "VideoSinkImpl: frequent frame size change detected for " << _endpointId << ": " << _lastFrameSizeChangeHeight << " -> " << _lastFrame->video_frame_buffer()->height() << " -> " << frame.video_frame_buffer()->height() << " in " << deltaTime << " ms"; |
| 635 | } |
| 636 |
| 637 | _lastFrameSizeChangeHeight = _lastFrame->video_frame_buffer()->height(); |
| 638 | _lastFrameSizeChangeTimestamp = timestamp; |
| 639 | } |
| 640 | } else { |
| 641 | _lastFrameSizeChangeHeight = 0; |
| 642 | _lastFrameSizeChangeTimestamp = timestamp; |
| 643 | } |
| 644 | _lastFrame = frame; |
| 645 | for (int i = (int)(_sinks.size()) - 1; i >= 0; i--) { |
| 646 | auto strong = _sinks[i].lock(); |
| 647 | if (!strong) { |
| 648 | _sinks.erase(_sinks.begin() + i); |
| 649 | } else { |
| 650 | strong->OnFrame(frame); |
| 651 | } |
| 652 | } |
| 653 | } |
| 654 |
| 655 | virtual void OnDiscardedFrame() override { |
| 656 | std::unique_lock<std::mutex> lock{ _mutex }; |
| 657 | for (int i = (int)(_sinks.size()) - 1; i >= 0; i--) { |
| 658 | auto strong = _sinks[i].lock(); |
| 659 | if (!strong) { |
| 660 | _sinks.erase(_sinks.begin() + i); |
| 661 | } else { |
| 662 | strong->OnDiscardedFrame(); |
| 663 | } |
| 664 | } |
| 665 | } |
| 666 |
| 667 | void addSink(std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> impl) { |
| 668 | if (const auto strong = impl.lock()) { |
| 669 | std::unique_lock<std::mutex> lock{ _mutex }; |
| 670 | _sinks.push_back(impl); |
| 671 | if (_lastFrame) { |
| 672 | strong->OnFrame(_lastFrame.value()); |
| 673 | } |
| 674 | } |
| 675 | } |
| 676 |
| 677 | std::vector<std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>>> getSinks() { |
| 678 | return _sinks; |
| 679 | } |
| 680 |
| 681 | private: |
| 682 | std::vector<std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>>> _sinks; |
| 683 | absl::optional<webrtc::VideoFrame> _lastFrame; |
| 684 | std::mutex _mutex; |
| 685 | int64_t _lastFrameSizeChangeTimestamp = 0; |
| 686 | int _lastFrameSizeChangeHeight = 0; |
| 687 | std::string _endpointId; |
| 688 |
| 689 | }; |
| 690 |
| 691 | struct NoiseSuppressionConfiguration { |
| 692 | NoiseSuppressionConfiguration(bool isEnabled_) : |
| 693 | isEnabled(isEnabled_) { |
| 694 |
| 695 | } |
| 696 |
| 697 | bool isEnabled = false; |
| 698 | }; |
| 699 |
| 700 | #if USE_RNNOISE |
| 701 | class AudioCapturePostProcessor : public webrtc::CustomProcessing { |
| 702 | public: |
| 703 | AudioCapturePostProcessor(std::function<void(GroupLevelValue const &)> updated, std::shared_ptr<NoiseSuppressionConfiguration> noiseSuppressionConfiguration, std::vector<float> *externalAudioSamples, webrtc::Mutex *externalAudioSamplesMutex) : |
| 704 | _updated(updated), |
| 705 | _noiseSuppressionConfiguration(noiseSuppressionConfiguration), |
| 706 | _externalAudioSamples(externalAudioSamples), |
| 707 | _externalAudioSamplesMutex(externalAudioSamplesMutex) { |
| 708 | int frameSize = rnnoise_get_frame_size(); |
| 709 | _frameSamples.resize(frameSize); |
| 710 |
| 711 | _denoiseState = rnnoise_create(nullptr); |
| 712 | } |
| 713 |
| 714 | virtual ~AudioCapturePostProcessor() { |
| 715 | if (_denoiseState) { |
| 716 | rnnoise_destroy(_denoiseState); |
| 717 | } |
| 718 | } |
| 719 |
| 720 | private: |
| 721 | virtual void Initialize(int sample_rate_hz, int num_channels) override { |
| 722 | } |
| 723 |
| 724 | virtual void Process(webrtc::AudioBuffer *buffer) override { |
| 725 | if (!buffer) { |
| 726 | return; |
| 727 | } |
| 728 | if (buffer->num_channels() != 1) { |
| 729 | return; |
| 730 | } |
| 731 | if (!_denoiseState) { |
| 732 | return; |
| 733 | } |
| 734 | if (buffer->num_frames() != _frameSamples.size()) { |
| 735 | return; |
| 736 | } |
| 737 |
| 738 | float sourcePeak = 0.0f; |
| 739 | float *sourceSamples = buffer->channels()[0]; |
| 740 | for (int i = 0; i < _frameSamples.size(); i++) { |
| 741 | sourcePeak = std::max(std::fabs(sourceSamples[i]), sourcePeak); |
| 742 | } |
| 743 |
| 744 | if (_noiseSuppressionConfiguration->isEnabled) { |
| 745 | float vadProbability = 0.0f; |
| 746 | if (sourcePeak >= 0.01f) { |
| 747 | vadProbability = rnnoise_process_frame(_denoiseState, _frameSamples.data(), buffer->channels()[0]); |
| 748 | if (_noiseSuppressionConfiguration->isEnabled) { |
| 749 | memcpy(buffer->channels()[0], _frameSamples.data(), _frameSamples.size() * sizeof(float)); |
| 750 | } |
| 751 | } |
| 752 |
| 753 | float peak = 0; |
| 754 | int peakCount = 0; |
| 755 | const float *samples = buffer->channels_const()[0]; |
| 756 | for (int i = 0; i < buffer->num_frames(); i++) { |
| 757 | float sample = samples[i]; |
| 758 | if (sample < 0) { |
| 759 | sample = -sample; |
| 760 | } |
| 761 | if (peak < sample) { |
| 762 | peak = sample; |
| 763 | } |
| 764 | peakCount += 1; |
| 765 | } |
| 766 |
| 767 | bool vadStatus = _history.update(vadProbability); |
| 768 |
| 769 | _peakCount += peakCount; |
| 770 | if (_peak < peak) { |
| 771 | _peak = peak; |
| 772 | } |
| 773 | if (_peakCount >= 4400) { |
| 774 | float level = _peak / 4000.0f; |
| 775 | _peak = 0; |
| 776 | _peakCount = 0; |
| 777 |
| 778 | _updated(GroupLevelValue{ |
| 779 | level, |
| 780 | vadStatus, |
| 781 | }); |
| 782 | } |
| 783 | } else { |
| 784 | float peak = 0; |
| 785 | int peakCount = 0; |
| 786 | const float *samples = buffer->channels_const()[0]; |
| 787 | for (int i = 0; i < buffer->num_frames(); i++) { |
| 788 | float sample = samples[i]; |
| 789 | if (sample < 0) { |
| 790 | sample = -sample; |
| 791 | } |
| 792 | if (peak < sample) { |
| 793 | peak = sample; |
| 794 | } |
| 795 | peakCount += 1; |
| 796 | } |
| 797 |
| 798 | _peakCount += peakCount; |
| 799 | if (_peak < peak) { |
| 800 | _peak = peak; |
| 801 | } |
| 802 | if (_peakCount >= 1200) { |
| 803 | float level = _peak / 8000.0f; |
| 804 | _peak = 0; |
| 805 | _peakCount = 0; |
| 806 |
| 807 | _updated(GroupLevelValue{ |
| 808 | level, |
| 809 | level >= 1.0f, |
| 810 | }); |
| 811 | } |
| 812 | } |
| 813 |
| 814 | if (_externalAudioSamplesMutex && _externalAudioSamples) { |
| 815 | _externalAudioSamplesMutex->Lock(); |
| 816 | if (!_externalAudioSamples->empty()) { |
| 817 | float *bufferData = buffer->channels()[0]; |
| 818 | int takenSamples = 0; |
| 819 | for (int i = 0; i < _externalAudioSamples->size() && i < _frameSamples.size(); i++) { |
| 820 | float sample = (*_externalAudioSamples)[i]; |
| 821 | sample += bufferData[i]; |
| 822 | sample = std::min(sample, 32768.f); |
| 823 | sample = std::max(sample, -32768.f); |
| 824 | bufferData[i] = sample; |
| 825 | takenSamples++; |
| 826 | } |
| 827 | if (takenSamples != 0) { |
| 828 | _externalAudioSamples->erase(_externalAudioSamples->begin(), _externalAudioSamples->begin() + takenSamples); |
| 829 | } |
| 830 | } |
| 831 | _externalAudioSamplesMutex->Unlock(); |
| 832 | } |
| 833 | } |
| 834 |
| 835 | virtual std::string ToString() const override { |
| 836 | return "CustomPostProcessing"; |
| 837 | } |
| 838 |
| 839 | virtual void SetRuntimeSetting(webrtc::AudioProcessing::RuntimeSetting setting) override { |
| 840 | } |
| 841 |
| 842 | private: |
| 843 | std::function<void(GroupLevelValue const &)> _updated; |
| 844 | std::shared_ptr<NoiseSuppressionConfiguration> _noiseSuppressionConfiguration; |
| 845 |
| 846 | DenoiseState *_denoiseState = nullptr; |
| 847 | std::vector<float> _frameSamples; |
| 848 | int32_t _peakCount = 0; |
| 849 | float _peak = 0; |
| 850 | VadHistory _history; |
| 851 | SparseVad _vad; |
| 852 |
| 853 | std::vector<float> *_externalAudioSamples = nullptr; |
| 854 | webrtc::Mutex *_externalAudioSamplesMutex = nullptr; |
| 855 | }; |
| 856 | #endif |
| 857 |
| 858 | class ExternalAudioRecorder : public FakeAudioDeviceModule::Recorder { |
| 859 | public: |
| 860 | ExternalAudioRecorder(std::vector<float> *externalAudioSamples, webrtc::Mutex *externalAudioSamplesMutex) : |
| 861 | _externalAudioSamples(externalAudioSamples), |
| 862 | _externalAudioSamplesMutex(externalAudioSamplesMutex) { |
| 863 | _samples.resize(480); |
| 864 | } |
| 865 |
| 866 | virtual ~ExternalAudioRecorder() { |
| 867 | } |
| 868 |
| 869 | virtual AudioFrame Record() override { |
| 870 | AudioFrame result; |
| 871 |
| 872 | _externalAudioSamplesMutex->Lock(); |
| 873 | if (!_externalAudioSamples->empty() && _externalAudioSamples->size() >= 480) { |
| 874 | size_t takenSamples = std::min(_samples.size(), _externalAudioSamples->size()); |
| 875 | webrtc::FloatS16ToS16(_externalAudioSamples->data(), takenSamples, _samples.data()); |
| 876 |
| 877 | result.num_samples = takenSamples; |
| 878 |
| 879 | if (takenSamples != 0) { |
| 880 | _externalAudioSamples->erase(_externalAudioSamples->begin(), _externalAudioSamples->begin() + takenSamples); |
| 881 | } |
| 882 | } else { |
| 883 | result.num_samples = 0; |
| 884 | } |
| 885 | _externalAudioSamplesMutex->Unlock(); |
| 886 |
| 887 | result.audio_samples = _samples.data(); |
| 888 | result.bytes_per_sample = 2; |
| 889 | result.num_channels = 1; |
| 890 | result.samples_per_sec = 48000; |
| 891 | result.elapsed_time_ms = 0; |
| 892 | result.ntp_time_ms = 0; |
| 893 |
| 894 | return result; |
| 895 | } |
| 896 |
| 897 | virtual int32_t WaitForUs() override { |
| 898 | _externalAudioSamplesMutex->Lock(); |
| 899 | _externalAudioSamplesMutex->Unlock(); |
| 900 |
| 901 | return 1000; |
| 902 | } |
| 903 |
| 904 | private: |
| 905 | std::vector<float> *_externalAudioSamples = nullptr; |
| 906 | webrtc::Mutex *_externalAudioSamplesMutex = nullptr; |
| 907 | std::vector<int16_t> _samples; |
| 908 | }; |
| 909 |
| 910 | class IncomingAudioChannel : public sigslot::has_slots<> { |
| 911 | public: |
| 912 | IncomingAudioChannel( |
| 913 | ChannelManager *channelManager, |
| 914 | webrtc::Call *call, |
| 915 | webrtc::RtpTransport *rtpTransport, |
| 916 | rtc::UniqueRandomIdGenerator *randomIdGenerator, |
| 917 | bool isRawPcm, |
| 918 | ChannelId ssrc, |
| 919 | std::function<void(AudioSinkImpl::Update)> &&onAudioLevelUpdated, |
| 920 | std::function<void(uint32_t, const AudioFrame &)> onAudioFrame, |
| 921 | std::shared_ptr<Threads> threads) : |
| 922 | _threads(threads), |
| 923 | _ssrc(ssrc), |
| 924 | _channelManager(channelManager), |
| 925 | _call(call) { |
| 926 | _creationTimestamp = rtc::TimeMillis(); |
| 927 |
| 928 | threads->getWorkerThread()->BlockingCall([this, rtpTransport, ssrc, onAudioFrame = std::move(onAudioFrame), onAudioLevelUpdated = std::move(onAudioLevelUpdated), isRawPcm]() mutable { |
| 929 | cricket::AudioOptions audioOptions; |
| 930 | audioOptions.audio_jitter_buffer_fast_accelerate = true; |
| 931 | audioOptions.audio_jitter_buffer_min_delay_ms = 50; |
| 932 |
| 933 | std::string streamId = std::string("stream") + ssrc.name(); |
| 934 |
| 935 | _audioChannel = _channelManager->CreateVoiceChannel(_call, cricket::MediaConfig(), std::string("audio") + uint32ToString(ssrc.networkSsrc), false, GroupNetworkManager::getDefaulCryptoOptions(), audioOptions); |
| 936 |
| 937 | _threads->getNetworkThread()->BlockingCall([&]() { |
| 938 | _audioChannel->SetRtpTransport(rtpTransport); |
| 939 | }); |
| 940 |
| 941 | const uint8_t opusPTimeMs = 120; |
| 942 |
| 943 | cricket::AudioCodec opusCodec(111, "opus", 48000, 0, 2); |
| 944 | opusCodec.SetParam(cricket::kCodecParamUseInbandFec, 1); |
| 945 | opusCodec.SetParam(cricket::kCodecParamPTime, opusPTimeMs); |
| 946 |
| 947 | cricket::AudioCodec pcmCodec(112, "l16", 48000, 0, 1); |
| 948 |
| 949 | auto outgoingAudioDescription = std::make_unique<cricket::AudioContentDescription>(); |
| 950 | if (!isRawPcm) { |
| 951 | outgoingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAudioLevelUri, 1)); |
| 952 | outgoingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAbsSendTimeUri, 2)); |
| 953 | outgoingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kTransportSequenceNumberUri, 3)); |
| 954 | } |
| 955 | outgoingAudioDescription->set_rtcp_mux(true); |
| 956 | outgoingAudioDescription->set_rtcp_reduced_size(true); |
| 957 | outgoingAudioDescription->set_direction(webrtc::RtpTransceiverDirection::kRecvOnly); |
| 958 | outgoingAudioDescription->set_codecs({ opusCodec, pcmCodec }); |
| 959 | outgoingAudioDescription->set_bandwidth(1300000); |
| 960 |
| 961 | auto incomingAudioDescription = std::make_unique<cricket::AudioContentDescription>(); |
| 962 | if (!isRawPcm) { |
| 963 | incomingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAudioLevelUri, 1)); |
| 964 | incomingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAbsSendTimeUri, 2)); |
| 965 | incomingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kTransportSequenceNumberUri, 3)); |
| 966 | } |
| 967 | incomingAudioDescription->set_rtcp_mux(true); |
| 968 | incomingAudioDescription->set_rtcp_reduced_size(true); |
| 969 | incomingAudioDescription->set_direction(webrtc::RtpTransceiverDirection::kSendOnly); |
| 970 | incomingAudioDescription->set_codecs({ opusCodec, pcmCodec }); |
| 971 | incomingAudioDescription->set_bandwidth(1300000); |
| 972 | cricket::StreamParams streamParams = cricket::StreamParams::CreateLegacy(ssrc.networkSsrc); |
| 973 | streamParams.set_stream_ids({ streamId }); |
| 974 | incomingAudioDescription->AddStream(streamParams); |
| 975 |
| 976 | std::string errorDesc; |
| 977 | _audioChannel->SetPayloadTypeDemuxingEnabled(false); |
| 978 | _audioChannel->SetLocalContent(outgoingAudioDescription.get(), webrtc::SdpType::kOffer, errorDesc); |
| 979 | _audioChannel->SetRemoteContent(incomingAudioDescription.get(), webrtc::SdpType::kAnswer, errorDesc); |
| 980 |
| 981 | outgoingAudioDescription.reset(); |
| 982 | incomingAudioDescription.reset(); |
| 983 |
| 984 | if (_ssrc.actualSsrc != 1) { |
| 985 | std::unique_ptr<AudioSinkImpl> audioLevelSink(new AudioSinkImpl(std::move(onAudioLevelUpdated), _ssrc, std::move(onAudioFrame))); |
| 986 | _audioChannel->media_channel()->SetRawAudioSink(ssrc.networkSsrc, std::move(audioLevelSink)); |
| 987 | } |
| 988 | }); |
| 989 |
| 990 | _audioChannel->Enable(true); |
| 991 | } |
| 992 |
| 993 | ~IncomingAudioChannel() { |
| 994 | _threads->getNetworkThread()->BlockingCall([&]() { |
| 995 | _audioChannel->SetRtpTransport(nullptr); |
| 996 | }); |
| 997 | _threads->getWorkerThread()->BlockingCall([this]() { |
| 998 | _channelManager->DestroyChannel(_audioChannel); |
| 999 | _audioChannel = nullptr; |
| 1000 | }); |
| 1001 | } |
| 1002 |
| 1003 | void setVolume(double value) { |
| 1004 | _threads->getWorkerThread()->BlockingCall([this, value]() { |
| 1005 | _audioChannel->media_channel()->SetOutputVolume(_ssrc.networkSsrc, value); |
| 1006 | }); |
| 1007 | } |
| 1008 |
| 1009 | void updateActivity() { |
| 1010 | _activityTimestamp = rtc::TimeMillis(); |
| 1011 | } |
| 1012 |
| 1013 | int64_t getActivity() { |
| 1014 | return _activityTimestamp; |
| 1015 | } |
| 1016 |
| 1017 | private: |
| 1018 | std::shared_ptr<Threads> _threads; |
| 1019 | ChannelId _ssrc; |
| 1020 | // Memory is managed by _channelManager |
| 1021 | cricket::VoiceChannel *_audioChannel = nullptr; |
| 1022 | // Memory is managed externally |
| 1023 | ChannelManager *_channelManager = nullptr; |
| 1024 | webrtc::Call *_call = nullptr; |
| 1025 | int64_t _creationTimestamp = 0; |
| 1026 | int64_t _activityTimestamp = 0; |
| 1027 | }; |
| 1028 |
| 1029 | class IncomingVideoChannel : public sigslot::has_slots<> { |
| 1030 | public: |
| 1031 | IncomingVideoChannel( |
| 1032 | ChannelManager *channelManager, |
| 1033 | webrtc::Call *call, |
| 1034 | webrtc::RtpTransport *rtpTransport, |
| 1035 | rtc::UniqueRandomIdGenerator *randomIdGenerator, |
| 1036 | std::vector<webrtc::SdpVideoFormat> const &availableVideoFormats, |
| 1037 | GroupJoinVideoInformation sharedVideoInformation, |
| 1038 | uint32_t audioSsrc, |
| 1039 | VideoChannelDescription::Quality minQuality, |
| 1040 | VideoChannelDescription::Quality maxQuality, |
| 1041 | GroupParticipantVideoInformation const &description, |
| 1042 | std::shared_ptr<Threads> threads) : |
| 1043 | _threads(threads), |
| 1044 | _endpointId(description.endpointId), |
| 1045 | _channelManager(channelManager), |
| 1046 | _call(call), |
| 1047 | _requestedMinQuality(minQuality), |
| 1048 | _requestedMaxQuality(maxQuality) { |
| 1049 | _videoSink.reset(new VideoSinkImpl(_endpointId)); |
| 1050 |
| 1051 | _threads->getWorkerThread()->BlockingCall([this, rtpTransport, &availableVideoFormats, &description, randomIdGenerator]() mutable { |
| 1052 | uint32_t mid = randomIdGenerator->GenerateId(); |
| 1053 | std::string streamId = std::string("video") + uint32ToString(mid); |
| 1054 |
| 1055 | _videoBitrateAllocatorFactory = webrtc::CreateBuiltinVideoBitrateAllocatorFactory(); |
| 1056 |
| 1057 | auto payloadTypes = assignPayloadTypes(availableVideoFormats); |
| 1058 | std::vector<cricket::VideoCodec> codecs; |
| 1059 | for (const auto &payloadType : payloadTypes) { |
| 1060 | codecs.push_back(payloadType.videoCodec); |
| 1061 | codecs.push_back(payloadType.rtxCodec); |
| 1062 | } |
| 1063 |
| 1064 | auto outgoingVideoDescription = std::make_unique<cricket::VideoContentDescription>(); |
| 1065 | outgoingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAbsSendTimeUri, 2)); |
| 1066 | outgoingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kTransportSequenceNumberUri, 3)); |
| 1067 | outgoingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kVideoRotationUri, 13)); |
| 1068 | outgoingVideoDescription->set_rtcp_mux(true); |
| 1069 | outgoingVideoDescription->set_rtcp_reduced_size(true); |
| 1070 | outgoingVideoDescription->set_direction(webrtc::RtpTransceiverDirection::kRecvOnly); |
| 1071 | outgoingVideoDescription->set_codecs(codecs); |
| 1072 | outgoingVideoDescription->set_bandwidth(1300000); |
| 1073 |
| 1074 | cricket::StreamParams videoRecvStreamParams; |
| 1075 |
| 1076 | std::vector<uint32_t> allSsrcs; |
| 1077 | for (const auto &group : description.ssrcGroups) { |
| 1078 | for (auto ssrc : group.ssrcs) { |
| 1079 | if (std::find(allSsrcs.begin(), allSsrcs.end(), ssrc) == allSsrcs.end()) { |
| 1080 | allSsrcs.push_back(ssrc); |
| 1081 | } |
| 1082 | } |
| 1083 |
| 1084 | if (group.semantics == "SIM") { |
| 1085 | if (_mainVideoSsrc == 0) { |
| 1086 | _mainVideoSsrc = group.ssrcs[0]; |
| 1087 | } |
| 1088 | } |
| 1089 |
| 1090 | cricket::SsrcGroup parsedGroup(group.semantics, group.ssrcs); |
| 1091 | videoRecvStreamParams.ssrc_groups.push_back(parsedGroup); |
| 1092 | } |
| 1093 | videoRecvStreamParams.ssrcs = allSsrcs; |
| 1094 |
| 1095 | if (_mainVideoSsrc == 0) { |
| 1096 | if (description.ssrcGroups.size() == 1) { |
| 1097 | _mainVideoSsrc = description.ssrcGroups[0].ssrcs[0]; |
| 1098 | } |
| 1099 | } |
| 1100 |
| 1101 | videoRecvStreamParams.cname = "cname"; |
| 1102 | videoRecvStreamParams.set_stream_ids({ streamId }); |
| 1103 |
| 1104 | auto incomingVideoDescription = std::make_unique<cricket::VideoContentDescription>(); |
| 1105 | incomingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAbsSendTimeUri, 2)); |
| 1106 | incomingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kTransportSequenceNumberUri, 3)); |
| 1107 | incomingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kVideoRotationUri, 13)); |
| 1108 | incomingVideoDescription->set_rtcp_mux(true); |
| 1109 | incomingVideoDescription->set_rtcp_reduced_size(true); |
| 1110 | incomingVideoDescription->set_direction(webrtc::RtpTransceiverDirection::kSendOnly); |
| 1111 | incomingVideoDescription->set_codecs(codecs); |
| 1112 | incomingVideoDescription->set_bandwidth(1300000); |
| 1113 |
| 1114 | incomingVideoDescription->AddStream(videoRecvStreamParams); |
| 1115 |
| 1116 | _videoChannel = _channelManager->CreateVideoChannel(_call, cricket::MediaConfig(), std::string("video") + uint32ToString(mid), false, GroupNetworkManager::getDefaulCryptoOptions(), cricket::VideoOptions(), _videoBitrateAllocatorFactory.get()); |
| 1117 |
| 1118 | _threads->getNetworkThread()->BlockingCall([&]() { |
| 1119 | _videoChannel->SetRtpTransport(rtpTransport); |
| 1120 | }); |
| 1121 |
| 1122 | std::string errorDesc; |
| 1123 | _videoChannel->SetLocalContent(outgoingVideoDescription.get(), webrtc::SdpType::kOffer, errorDesc); |
| 1124 | _videoChannel->SetRemoteContent(incomingVideoDescription.get(), webrtc::SdpType::kAnswer, errorDesc); |
| 1125 | _videoChannel->SetPayloadTypeDemuxingEnabled(false); |
| 1126 | _videoChannel->media_channel()->SetSink(_mainVideoSsrc, _videoSink.get()); |
| 1127 | }); |
| 1128 |
| 1129 | _videoChannel->Enable(true); |
| 1130 | } |
| 1131 |
| 1132 | ~IncomingVideoChannel() { |
| 1133 | _videoChannel->Enable(false); |
| 1134 | _threads->getNetworkThread()->BlockingCall([&]() { |
| 1135 | _videoChannel->SetRtpTransport(nullptr); |
| 1136 | }); |
| 1137 | _threads->getWorkerThread()->BlockingCall([this]() { |
| 1138 | _channelManager->DestroyChannel(_videoChannel); |
| 1139 | _videoChannel = nullptr; |
| 1140 | }); |
| 1141 | } |
| 1142 |
| 1143 | void addSink(std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> impl) { |
| 1144 | _videoSink->addSink(impl); |
| 1145 | } |
| 1146 |
| 1147 | std::vector<std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>>> getSinks() { |
| 1148 | return _videoSink->getSinks(); |
| 1149 | } |
| 1150 |
| 1151 | std::string const &endpointId() { |
| 1152 | return _endpointId; |
| 1153 | } |
| 1154 |
| 1155 | VideoChannelDescription::Quality requestedMinQuality() { |
| 1156 | return _requestedMinQuality; |
| 1157 | } |
| 1158 |
| 1159 | VideoChannelDescription::Quality requestedMaxQuality() { |
| 1160 | return _requestedMaxQuality; |
| 1161 | } |
| 1162 |
| 1163 | void setRequstedMinQuality(VideoChannelDescription::Quality quality) { |
| 1164 | _requestedMinQuality = quality; |
| 1165 | } |
| 1166 |
| 1167 | void setRequstedMaxQuality(VideoChannelDescription::Quality quality) { |
| 1168 | _requestedMaxQuality = quality; |
| 1169 | } |
| 1170 |
| 1171 | void setStats(absl::optional<GroupInstanceStats::IncomingVideoStats> stats) { |
| 1172 | _stats = stats; |
| 1173 | } |
| 1174 |
| 1175 | absl::optional<GroupInstanceStats::IncomingVideoStats> getStats() { |
| 1176 | return _stats; |
| 1177 | } |
| 1178 |
| 1179 | private: |
| 1180 | std::shared_ptr<Threads> _threads; |
| 1181 | uint32_t _mainVideoSsrc = 0; |
| 1182 | std::string _endpointId; |
| 1183 | std::unique_ptr<VideoSinkImpl> _videoSink; |
| 1184 | std::vector<GroupJoinPayloadVideoSourceGroup> _ssrcGroups; |
| 1185 | std::unique_ptr<webrtc::VideoBitrateAllocatorFactory> _videoBitrateAllocatorFactory; |
| 1186 | // Memory is managed by _channelManager |
| 1187 | cricket::VideoChannel *_videoChannel; |
| 1188 | // Memory is managed externally |
| 1189 | ChannelManager *_channelManager = nullptr; |
| 1190 | webrtc::Call *_call = nullptr; |
| 1191 |
| 1192 | VideoChannelDescription::Quality _requestedMinQuality = VideoChannelDescription::Quality::Thumbnail; |
| 1193 | VideoChannelDescription::Quality _requestedMaxQuality = VideoChannelDescription::Quality::Thumbnail; |
| 1194 |
| 1195 | absl::optional<GroupInstanceStats::IncomingVideoStats> _stats; |
| 1196 | }; |
| 1197 |
| 1198 | class MissingSsrcPacketBuffer { |
| 1199 | public: |
| 1200 | MissingSsrcPacketBuffer(int limit) : |
| 1201 | _limit(limit) { |
| 1202 | } |
| 1203 |
| 1204 | ~MissingSsrcPacketBuffer() { |
| 1205 | } |
| 1206 |
| 1207 | void add(uint32_t ssrc, rtc::CopyOnWriteBuffer const &packet) { |
| 1208 | if (_packets.size() == _limit) { |
| 1209 | _packets.erase(_packets.begin()); |
| 1210 | } |
| 1211 | _packets.push_back(std::make_pair(ssrc, packet)); |
| 1212 | } |
| 1213 |
| 1214 | std::vector<rtc::CopyOnWriteBuffer> get(uint32_t ssrc) { |
| 1215 | std::vector<rtc::CopyOnWriteBuffer> result; |
| 1216 | for (auto it = _packets.begin(); it != _packets.end(); ) { |
| 1217 | if (it->first == ssrc) { |
| 1218 | result.push_back(it->second); |
| 1219 | _packets.erase(it); |
| 1220 | } else { |
| 1221 | it++; |
| 1222 | } |
| 1223 | } |
| 1224 | return result; |
| 1225 | } |
| 1226 |
| 1227 | private: |
| 1228 | int _limit = 0; |
| 1229 | std::vector<std::pair<uint32_t, rtc::CopyOnWriteBuffer>> _packets; |
| 1230 |
| 1231 | }; |
| 1232 |
| 1233 | class RequestedBroadcastPart { |
| 1234 | public: |
| 1235 | int64_t timestamp = 0; |
| 1236 | std::shared_ptr<BroadcastPartTask> task; |
| 1237 |
| 1238 | explicit RequestedBroadcastPart(int64_t timestamp_, std::shared_ptr<BroadcastPartTask> task_) : |
| 1239 | timestamp(timestamp_), task(task_) { |
| 1240 | } |
| 1241 | }; |
| 1242 |
| 1243 | struct DecodedBroadcastPart { |
| 1244 | struct DecodedBroadcastPartChannel { |
| 1245 | uint32_t ssrc = 0; |
| 1246 | std::vector<int16_t> pcmData; |
| 1247 | }; |
| 1248 |
| 1249 | DecodedBroadcastPart(int numSamples_, std::vector<DecodedBroadcastPartChannel> &&_channels) : |
| 1250 | numSamples(numSamples_), channels(std::move(_channels)) { |
| 1251 | } |
| 1252 |
| 1253 | int numSamples = 0; |
| 1254 | std::vector<DecodedBroadcastPartChannel> channels; |
| 1255 | }; |
| 1256 |
| 1257 | std::function<rtc::scoped_refptr<webrtc::VideoTrackSourceInterface>()> videoCaptureToGetVideoSource(std::shared_ptr<VideoCaptureInterface> videoCapture) { |
| 1258 | return [videoCapture]() { |
| 1259 | VideoCaptureInterfaceObject *videoCaptureImpl = GetVideoCaptureAssumingSameThread(videoCapture.get()); |
| 1260 | return videoCaptureImpl ? videoCaptureImpl->source() : nullptr; |
| 1261 | }; |
| 1262 | } |
| 1263 |
| 1264 | class AudioDeviceDataObserverShared { |
| 1265 | public: |
| 1266 | AudioDeviceDataObserverShared() { |
| 1267 | } |
| 1268 |
| 1269 | ~AudioDeviceDataObserverShared() { |
| 1270 | } |
| 1271 |
| 1272 | void setStreamingContext(std::shared_ptr<StreamingMediaContext> streamingContext) { |
| 1273 | _mutex.Lock(); |
| 1274 | _streamingContext = streamingContext; |
| 1275 | _mutex.Unlock(); |
| 1276 | } |
| 1277 |
| 1278 | void mixAudio(int16_t *audio_samples, const size_t num_samples, const size_t num_channels, const uint32_t samples_per_sec) { |
| 1279 | _mutex.Lock(); |
| 1280 | const auto context = _streamingContext; |
| 1281 | _mutex.Unlock(); |
| 1282 |
| 1283 | if (context) { |
| 1284 | if (_samplesToResample.size() < 480 * num_channels) { |
| 1285 | _samplesToResample.resize(480 * num_channels); |
| 1286 | } |
| 1287 | memset(_samplesToResample.data(), 0, _samplesToResample.size() * sizeof(int16_t)); |
| 1288 |
| 1289 | context->getAudio(_samplesToResample.data(), 480, num_channels, 48000); |
| 1290 |
| 1291 | if (_resamplerFrequency != samples_per_sec || _resamplerNumChannels != num_channels) { |
| 1292 | _resamplerFrequency = samples_per_sec; |
| 1293 | _resamplerNumChannels = num_channels; |
| 1294 | _resampler = std::make_unique<webrtc::Resampler>(); |
| 1295 | if (_resampler->Reset(48000, samples_per_sec, num_channels) == -1) { |
| 1296 | _resampler = nullptr; |
| 1297 | } |
| 1298 | } |
| 1299 |
| 1300 | if (_resampler) { |
| 1301 | size_t outLen = 0; |
| 1302 | _resampler->Push(_samplesToResample.data(), _samplesToResample.size(), (int16_t *)audio_samples, num_samples * num_channels, outLen); |
| 1303 | } |
| 1304 | } |
| 1305 | } |
| 1306 |
| 1307 | private: |
| 1308 | webrtc::Mutex _mutex; |
| 1309 | std::unique_ptr<webrtc::Resampler> _resampler; |
| 1310 | uint32_t _resamplerFrequency = 0; |
| 1311 | size_t _resamplerNumChannels = 0; |
| 1312 | std::vector<int16_t> _samplesToResample; |
| 1313 | std::shared_ptr<StreamingMediaContext> _streamingContext; |
| 1314 | }; |
| 1315 |
| 1316 | class AudioDeviceDataObserverImpl : public webrtc::AudioDeviceDataObserver { |
| 1317 | public: |
| 1318 | AudioDeviceDataObserverImpl(std::shared_ptr<AudioDeviceDataObserverShared> shared) : |
| 1319 | _shared(shared) { |
| 1320 | } |
| 1321 |
| 1322 | virtual ~AudioDeviceDataObserverImpl() { |
| 1323 | } |
| 1324 |
| 1325 | virtual void OnCaptureData(const void* audio_samples, |
| 1326 | const size_t num_samples, |
| 1327 | const size_t bytes_per_sample, |
| 1328 | const size_t num_channels, |
| 1329 | const uint32_t samples_per_sec) override { |
| 1330 | } |
| 1331 |
| 1332 | virtual void OnRenderData(const void* audio_samples, |
| 1333 | const size_t num_samples, |
| 1334 | const size_t bytes_per_sample, |
| 1335 | const size_t num_channels, |
| 1336 | const uint32_t samples_per_sec) override { |
| 1337 | if (bytes_per_sample != num_channels * 2) { |
| 1338 | return; |
| 1339 | } |
| 1340 | if (samples_per_sec % 100 != 0) { |
| 1341 | return; |
| 1342 | } |
| 1343 | if (num_samples != samples_per_sec / 100) { |
| 1344 | return; |
| 1345 | } |
| 1346 |
| 1347 | if (_shared) { |
| 1348 | _shared->mixAudio((int16_t *)audio_samples, num_samples, num_channels, samples_per_sec); |
| 1349 | } |
| 1350 | } |
| 1351 |
| 1352 | private: |
| 1353 | std::shared_ptr<AudioDeviceDataObserverShared> _shared; |
| 1354 | }; |
| 1355 |
| 1356 | class CustomNetEqFactory: public webrtc::NetEqFactory { |
| 1357 | public: |
| 1358 | virtual ~CustomNetEqFactory() = default; |
| 1359 |
| 1360 | std::unique_ptr<webrtc::NetEq> CreateNetEq( |
| 1361 | const webrtc::NetEq::Config& config, |
| 1362 | const rtc::scoped_refptr<webrtc::AudioDecoderFactory>& decoder_factory, webrtc::Clock* clock |
| 1363 | ) const override { |
| 1364 | webrtc::NetEq::Config updatedConfig = config; |
| 1365 | updatedConfig.sample_rate_hz = 48000; |
| 1366 | return webrtc::DefaultNetEqFactory().CreateNetEq(updatedConfig, decoder_factory, clock); |
| 1367 | } |
| 1368 | }; |
| 1369 |
| 1370 | std::unique_ptr<webrtc::NetEqFactory> createNetEqFactory() { |
| 1371 | return std::make_unique<CustomNetEqFactory>(); |
| 1372 | } |
| 1373 |
| 1374 | class CustomEchoDetector : public webrtc::EchoDetector { |
| 1375 | public: |
| 1376 | // (Re-)Initializes the submodule. |
| 1377 | virtual void Initialize(int capture_sample_rate_hz, |
| 1378 | int num_capture_channels, |
| 1379 | int render_sample_rate_hz, |
| 1380 | int num_render_channels) override { |
| 1381 | } |
| 1382 |
| 1383 | // Analysis (not changing) of the render signal. |
| 1384 | virtual void AnalyzeRenderAudio(rtc::ArrayView<const float> render_audio) override { |
| 1385 | } |
| 1386 |
| 1387 | // Analysis (not changing) of the capture signal. |
| 1388 | virtual void AnalyzeCaptureAudio( |
| 1389 | rtc::ArrayView<const float> capture_audio) override { |
| 1390 | } |
| 1391 |
| 1392 | // Collect current metrics from the echo detector. |
| 1393 | virtual Metrics GetMetrics() const override { |
| 1394 | return webrtc::EchoDetector::Metrics(); |
| 1395 | } |
| 1396 | }; |
| 1397 |
| 1398 | } // namespace |
| 1399 |
| 1400 | int GroupInstanceCustomImpl::customAudioBitrate = 0; |
| 1401 |
| 1402 | class GroupInstanceCustomInternal : public sigslot::has_slots<>, public std::enable_shared_from_this<GroupInstanceCustomInternal> { |
| 1403 | public: |
| 1404 | GroupInstanceCustomInternal(GroupInstanceDescriptor &&descriptor, std::shared_ptr<Threads> threads) : |
| 1405 | _threads(std::move(threads)), |
| 1406 | _networkStateUpdated(descriptor.networkStateUpdated), |
| 1407 | _audioLevelsUpdated(descriptor.audioLevelsUpdated), |
| 1408 | _onAudioFrame(descriptor.onAudioFrame), |
| 1409 | _requestMediaChannelDescriptions(descriptor.requestMediaChannelDescriptions), |
| 1410 | _requestCurrentTime(descriptor.requestCurrentTime), |
| 1411 | _requestAudioBroadcastPart(descriptor.requestAudioBroadcastPart), |
| 1412 | _requestVideoBroadcastPart(descriptor.requestVideoBroadcastPart), |
| 1413 | _videoCapture(descriptor.videoCapture), |
| 1414 | _videoCaptureSink(new VideoSinkImpl("VideoCapture")), |
| 1415 | _getVideoSource(descriptor.getVideoSource), |
| 1416 | _disableIncomingChannels(descriptor.disableIncomingChannels), |
| 1417 | _useDummyChannel(descriptor.useDummyChannel), |
| 1418 | _outgoingAudioBitrateKbit(descriptor.outgoingAudioBitrateKbit), |
| 1419 | _disableOutgoingAudioProcessing(descriptor.disableOutgoingAudioProcessing), |
| 1420 | #ifdef WEBRTC_IOS |
| 1421 | _disableAudioInput(descriptor.disableAudioInput), |
| 1422 | #endif |
| 1423 | _minOutgoingVideoBitrateKbit(descriptor.minOutgoingVideoBitrateKbit), |
| 1424 | _videoContentType(descriptor.videoContentType), |
| 1425 | _videoCodecPreferences(std::move(descriptor.videoCodecPreferences)), |
| 1426 | _eventLog(std::make_unique<webrtc::RtcEventLogNull>()), |
| 1427 | _taskQueueFactory(webrtc::CreateDefaultTaskQueueFactory()), |
| 1428 | _netEqFactory(createNetEqFactory()), |
| 1429 | _createAudioDeviceModule(descriptor.createAudioDeviceModule), |
| 1430 | _initialInputDeviceId(std::move(descriptor.initialInputDeviceId)), |
| 1431 | _initialOutputDeviceId(std::move(descriptor.initialOutputDeviceId)), |
| 1432 | _missingPacketBuffer(50), |
| 1433 | _platformContext(descriptor.platformContext) { |
| 1434 | RTC_LOG(LS_INFO) << "Init GroupInstanceCustomImpl with audio bitrate " << _outgoingAudioBitrateKbit << "kbps"; |
| 1435 | assert(_threads->getMediaThread()->IsCurrent()); |
| 1436 |
| 1437 | GroupInstanceCustomImpl::customAudioBitrate = _outgoingAudioBitrateKbit * 1000; |
| 1438 |
| 1439 | _threads->getWorkerThread()->BlockingCall([this] { |
| 1440 | _workerThreadSafery = webrtc::PendingTaskSafetyFlag::Create(); |
| 1441 | }); |
| 1442 | _threads->getNetworkThread()->BlockingCall([this] { |
| 1443 | _networkThreadSafery = webrtc::PendingTaskSafetyFlag::Create(); |
| 1444 | }); |
| 1445 |
| 1446 | if (_videoCapture) { |
| 1447 | assert(!_getVideoSource); |
| 1448 | _getVideoSource = videoCaptureToGetVideoSource(std::move(descriptor.videoCapture)); |
| 1449 | } |
| 1450 | generateSsrcs(); |
| 1451 |
| 1452 | _noiseSuppressionConfiguration = std::make_shared<NoiseSuppressionConfiguration>(descriptor.initialEnableNoiseSuppression); |
| 1453 |
| 1454 | _externalAudioRecorder.reset(new ExternalAudioRecorder(&_externalAudioSamples, &_externalAudioSamplesMutex)); |
| 1455 | } |
| 1456 |
| 1457 | ~GroupInstanceCustomInternal() { |
| 1458 | RTC_LOG(LS_WARNING) << "~GroupInstanceCustomInternal, reset customAudioBitrate to zero"; |
| 1459 | GroupInstanceCustomImpl::customAudioBitrate = 0; |
| 1460 |
| 1461 | _incomingAudioChannels.clear(); |
| 1462 | _incomingVideoChannels.clear(); |
| 1463 | _serverBandwidthProbingVideoSsrc.reset(); |
| 1464 |
| 1465 | destroyOutgoingAudioChannel(); |
| 1466 | destroyOutgoingVideoChannel(); |
| 1467 |
| 1468 | _threads->getNetworkThread()->BlockingCall([this]() { |
| 1469 | _rtpTransport->SignalSentPacket.disconnect(this); |
| 1470 | _rtpTransport->SignalRtcpPacketReceived.disconnect(this); |
| 1471 | }); |
| 1472 |
| 1473 | _channelManager = nullptr; |
| 1474 |
| 1475 | _threads->getWorkerThread()->BlockingCall([this]() { |
| 1476 | if (_audioDeviceModule) { |
| 1477 | _audioDeviceModule->Stop(); |
| 1478 | _audioDeviceModule = nullptr; |
| 1479 | } |
| 1480 | _call.reset(); |
| 1481 | }); |
| 1482 | } |
| 1483 |
| 1484 | void start() { |
| 1485 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 1486 |
| 1487 | std::stringstream stringStream; |
| 1488 | stringStream << "WebRTC-DataChannel-Dcsctp/Enabled/" |
| 1489 | "WebRTC-Audio-Allocation/min:" << _outgoingAudioBitrateKbit << "kbps,max:" << _outgoingAudioBitrateKbit << "kbps/" |
| 1490 | << "WebRTC-Audio-OpusMinPacketLossRate/Enabled-1/" |
| 1491 | << "WebRTC-TaskQueuePacer/Enabled/" |
| 1492 | << "WebRTC-VP8ConferenceTemporalLayers/1/" |
| 1493 | << "WebRTC-Audio-MinimizeResamplingOnMobile/Enabled/" |
| 1494 | << "WebRTC-BweLossExperiment/Enabled/"; |
| 1495 | // << "WebRTC-MutedStateKillSwitch/Enabled/" |
| 1496 | // << "WebRTC-VP8IosMaxNumberOfThread/max_thread:1/" |
| 1497 |
| 1498 | auto webrtcInitStr = stringStream.str(); |
| 1499 | webrtc::field_trial::InitFieldTrialsFromString(webrtcInitStr.c_str()); |
| 1500 |
| 1501 | _networkManager.reset(new ThreadLocalObject<GroupNetworkManager>(_threads->getNetworkThread(), [weak, threads = _threads] () mutable { |
| 1502 | return new GroupNetworkManager( |
| 1503 | fieldTrialsBasedConfig, |
| 1504 | [=](const GroupNetworkManager::State &state) { |
| 1505 | threads->getMediaThread()->PostTask([=] { |
| 1506 | const auto strong = weak.lock(); |
| 1507 | if (!strong) { |
| 1508 | return; |
| 1509 | } |
| 1510 | strong->setIsRtcConnected(state.isReadyToSendData); |
| 1511 | }); |
| 1512 | }, |
| 1513 | [=](uint32_t ssrc, int payloadType) { |
| 1514 | threads->getMediaThread()->PostTask([weak, ssrc, payloadType]() mutable { |
| 1515 | if (const auto strong = weak.lock()) { |
| 1516 | strong->receiveUnknownSsrcPacket(ssrc, payloadType); |
| 1517 | } |
| 1518 | }); |
| 1519 | }, |
| 1520 | [=](bool isDataChannelOpen) { |
| 1521 | threads->getMediaThread()->PostTask([weak, isDataChannelOpen]() mutable { |
| 1522 | if (const auto strong = weak.lock()) { |
| 1523 | strong->updateIsDataChannelOpen(isDataChannelOpen); |
| 1524 | } |
| 1525 | }); |
| 1526 | }, |
| 1527 | [=](std::string const &message) { |
| 1528 | threads->getMediaThread()->PostTask([weak, message]() { |
| 1529 | if (const auto strong = weak.lock()) { |
| 1530 | strong->receiveDataChannelMessage(message); |
| 1531 | } |
| 1532 | }); |
| 1533 | }, |
| 1534 | [=](uint32_t ssrc, uint8_t audioLevel, bool isSpeech) { |
| 1535 | threads->getMediaThread()->PostTask([weak, ssrc, audioLevel, isSpeech]() { |
| 1536 | if (const auto strong = weak.lock()) { |
| 1537 | strong->updateSsrcAudioLevel(ssrc, audioLevel, isSpeech); |
| 1538 | } |
| 1539 | }); |
| 1540 | }, threads); |
| 1541 | })); |
| 1542 |
| 1543 | #if USE_RNNOISE |
| 1544 | std::unique_ptr<AudioCapturePostProcessor> audioProcessor = nullptr; |
| 1545 | #endif |
| 1546 | if (_videoContentType != VideoContentType::Screencast) { |
| 1547 | int numChannels = 1; |
| 1548 | #ifdef WEBRTC_IOS |
| 1549 | if (_disableAudioInput) { |
| 1550 | numChannels = 2; |
| 1551 | } |
| 1552 | #endif |
| 1553 | PlatformInterface::SharedInstance()->configurePlatformAudio(numChannels); |
| 1554 |
| 1555 | #if USE_RNNOISE |
| 1556 | audioProcessor = std::make_unique<AudioCapturePostProcessor>([weak, threads = _threads](GroupLevelValue const &level) { |
| 1557 | threads->getMediaThread()->PostTask([weak, level](){ |
| 1558 | auto strong = weak.lock(); |
| 1559 | if (!strong) { |
| 1560 | return; |
| 1561 | } |
| 1562 | strong->_myAudioLevel = level; |
| 1563 | }); |
| 1564 | }, _noiseSuppressionConfiguration, nullptr, nullptr); |
| 1565 | #endif |
| 1566 | } |
| 1567 |
| 1568 | _audioDeviceDataObserverShared = std::make_shared<AudioDeviceDataObserverShared>(); |
| 1569 |
| 1570 | _threads->getWorkerThread()->BlockingCall([this]() mutable { |
| 1571 | _audioDeviceModule = createAudioDeviceModule(); |
| 1572 | if (!_audioDeviceModule) { |
| 1573 | return; |
| 1574 | } |
| 1575 | }); |
| 1576 |
| 1577 | cricket::MediaEngineDependencies mediaDeps; |
| 1578 | mediaDeps.task_queue_factory = _taskQueueFactory.get(); |
| 1579 | mediaDeps.audio_encoder_factory = webrtc::CreateAudioEncoderFactory<webrtc::AudioEncoderOpus, webrtc::AudioEncoderL16>(); |
| 1580 | mediaDeps.audio_decoder_factory = webrtc::CreateAudioDecoderFactory<webrtc::AudioDecoderOpus, webrtc::AudioDecoderL16>(); |
| 1581 |
| 1582 | mediaDeps.video_encoder_factory = PlatformInterface::SharedInstance()->makeVideoEncoderFactory(_platformContext, false, _videoContentType == VideoContentType::Screencast); |
| 1583 | mediaDeps.video_decoder_factory = PlatformInterface::SharedInstance()->makeVideoDecoderFactory(_platformContext); |
| 1584 |
| 1585 | #if USE_RNNOISE |
| 1586 | if (_audioLevelsUpdated && audioProcessor) { |
| 1587 | webrtc::AudioProcessingBuilder builder; |
| 1588 | builder.SetCapturePostProcessing(std::move(audioProcessor)); |
| 1589 |
| 1590 | builder.SetEchoDetector(rtc::make_ref_counted<CustomEchoDetector>()); |
| 1591 |
| 1592 | mediaDeps.audio_processing = builder.Create(); |
| 1593 | } |
| 1594 | #endif |
| 1595 |
| 1596 | mediaDeps.adm = _audioDeviceModule; |
| 1597 |
| 1598 | _availableVideoFormats = filterSupportedVideoFormats(mediaDeps.video_encoder_factory->GetSupportedFormats()); |
| 1599 |
| 1600 | std::unique_ptr<cricket::MediaEngineInterface> mediaEngine = cricket::CreateMediaEngine(std::move(mediaDeps)); |
| 1601 |
| 1602 | _channelManager = ChannelManager::Create( |
| 1603 | std::move(mediaEngine), |
| 1604 | _threads->getWorkerThread(), |
| 1605 | _threads->getNetworkThread() |
| 1606 | ); |
| 1607 |
| 1608 | setAudioInputDevice(_initialInputDeviceId); |
| 1609 | setAudioOutputDevice(_initialOutputDeviceId); |
| 1610 |
| 1611 | _threads->getWorkerThread()->BlockingCall([this]() { |
| 1612 | webrtc::Call::Config callConfig(_eventLog.get(), _threads->getNetworkThread()); |
| 1613 | callConfig.neteq_factory = _netEqFactory.get(); |
| 1614 | callConfig.task_queue_factory = _taskQueueFactory.get(); |
| 1615 | callConfig.trials = &fieldTrialsBasedConfig; |
| 1616 | callConfig.audio_state = _channelManager->media_engine()->voice().GetAudioState(); |
| 1617 | _call.reset(webrtc::Call::Create(callConfig)); |
| 1618 | }); |
| 1619 |
| 1620 | _uniqueRandomIdGenerator.reset(new rtc::UniqueRandomIdGenerator()); |
| 1621 |
| 1622 | _threads->getNetworkThread()->BlockingCall([this]() { |
| 1623 | _rtpTransport = _networkManager->getSyncAssumingSameThread()->getRtpTransport(); |
| 1624 | _rtpTransport->SignalSentPacket.connect(this, &GroupInstanceCustomInternal::OnSentPacket_w); |
| 1625 | _rtpTransport->SignalRtcpPacketReceived.connect(this, &GroupInstanceCustomInternal::OnRtcpPacketReceived_n); |
| 1626 | }); |
| 1627 |
| 1628 | _videoBitrateAllocatorFactory = webrtc::CreateBuiltinVideoBitrateAllocatorFactory(); |
| 1629 |
| 1630 | if (_audioLevelsUpdated) { |
| 1631 | beginLevelsTimer(100); |
| 1632 | } |
| 1633 |
| 1634 | if (_getVideoSource) { |
| 1635 | setVideoSource(_getVideoSource, true); |
| 1636 | } |
| 1637 |
| 1638 | if (_useDummyChannel && _videoContentType != VideoContentType::Screencast) { |
| 1639 | addIncomingAudioChannel(ChannelId(1), true); |
| 1640 | } |
| 1641 |
| 1642 | if (_videoContentType == VideoContentType::Screencast) { |
| 1643 | setIsMuted(false); |
| 1644 | } |
| 1645 |
| 1646 | /*if (_videoContentType != VideoContentType::Screencast) { |
| 1647 | createOutgoingAudioChannel(); |
| 1648 | }*/ |
| 1649 |
| 1650 | beginNetworkStatusTimer(0); |
| 1651 | //beginAudioChannelCleanupTimer(0); |
| 1652 |
| 1653 | adjustBitratePreferences(true); |
| 1654 |
| 1655 | beginRemoteConstraintsUpdateTimer(5000); |
| 1656 | } |
| 1657 |
| 1658 | void destroyOutgoingVideoChannel() { |
| 1659 | if (!_outgoingVideoChannel) { |
| 1660 | return; |
| 1661 | } |
| 1662 | _outgoingVideoChannel->Enable(false); |
| 1663 | _threads->getNetworkThread()->BlockingCall([&]() { |
| 1664 | _outgoingVideoChannel->SetRtpTransport(nullptr); |
| 1665 | }); |
| 1666 | _threads->getWorkerThread()->BlockingCall([this]() { |
| 1667 | _outgoingVideoChannel->media_channel()->SetVideoSend(_outgoingVideoSsrcs.simulcastLayers[0].ssrc, nullptr, nullptr); |
| 1668 | _channelManager->DestroyChannel(_outgoingVideoChannel); |
| 1669 | }); |
| 1670 | _outgoingVideoChannel = nullptr; |
| 1671 | } |
| 1672 |
| 1673 | void createOutgoingVideoChannel() { |
| 1674 | if (_outgoingVideoChannel |
| 1675 | || _videoContentType == VideoContentType::None) { |
| 1676 | return; |
| 1677 | } |
| 1678 | configureVideoParams(); |
| 1679 |
| 1680 | if (!_selectedPayloadType) { |
| 1681 | RTC_LOG(LS_ERROR) << "Could not select payload type."; |
| 1682 | return; |
| 1683 | } |
| 1684 |
| 1685 | cricket::VideoOptions videoOptions; |
| 1686 | if (_videoContentType == VideoContentType::Screencast) { |
| 1687 | videoOptions.is_screencast = true; |
| 1688 | } |
| 1689 | _outgoingVideoChannel = _channelManager->CreateVideoChannel(_call.get(), cricket::MediaConfig(), "1", false, GroupNetworkManager::getDefaulCryptoOptions(), videoOptions, _videoBitrateAllocatorFactory.get()); |
| 1690 | _threads->getNetworkThread()->BlockingCall([&]() { |
| 1691 | _outgoingVideoChannel->SetRtpTransport(_rtpTransport); |
| 1692 | }); |
| 1693 |
| 1694 | if (!_outgoingVideoChannel) { |
| 1695 | RTC_LOG(LS_ERROR) << "Could not create outgoing video channel."; |
| 1696 | return; |
| 1697 | } |
| 1698 |
| 1699 | cricket::StreamParams videoSendStreamParams; |
| 1700 |
| 1701 | std::vector<uint32_t> simulcastGroupSsrcs; |
| 1702 | std::vector<cricket::SsrcGroup> fidGroups; |
| 1703 | for (const auto &layer : _outgoingVideoSsrcs.simulcastLayers) { |
| 1704 | simulcastGroupSsrcs.push_back(layer.ssrc); |
| 1705 |
| 1706 | videoSendStreamParams.ssrcs.push_back(layer.ssrc); |
| 1707 | videoSendStreamParams.ssrcs.push_back(layer.fidSsrc); |
| 1708 |
| 1709 | cricket::SsrcGroup fidGroup(cricket::kFidSsrcGroupSemantics, { layer.ssrc, layer.fidSsrc }); |
| 1710 | fidGroups.push_back(fidGroup); |
| 1711 | } |
| 1712 | if (simulcastGroupSsrcs.size() > 1) { |
| 1713 | cricket::SsrcGroup simulcastGroup(cricket::kSimSsrcGroupSemantics, simulcastGroupSsrcs); |
| 1714 | videoSendStreamParams.ssrc_groups.push_back(simulcastGroup); |
| 1715 |
| 1716 | GroupJoinPayloadVideoSourceGroup payloadSimulcastGroup; |
| 1717 | payloadSimulcastGroup.semantics = "SIM"; |
| 1718 | payloadSimulcastGroup.ssrcs = simulcastGroupSsrcs; |
| 1719 | } |
| 1720 |
| 1721 | for (auto fidGroup : fidGroups) { |
| 1722 | videoSendStreamParams.ssrc_groups.push_back(fidGroup); |
| 1723 |
| 1724 | GroupJoinPayloadVideoSourceGroup payloadFidGroup; |
| 1725 | payloadFidGroup.semantics = "FID"; |
| 1726 | payloadFidGroup.ssrcs = fidGroup.ssrcs; |
| 1727 | } |
| 1728 |
| 1729 | videoSendStreamParams.cname = "cname"; |
| 1730 |
| 1731 | auto outgoingVideoDescription = std::make_shared<cricket::VideoContentDescription>(); |
| 1732 | for (const auto &extension : _videoExtensionMap) { |
| 1733 | outgoingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(extension.second, extension.first)); |
| 1734 | } |
| 1735 | outgoingVideoDescription->set_rtcp_mux(true); |
| 1736 | outgoingVideoDescription->set_rtcp_reduced_size(true); |
| 1737 | outgoingVideoDescription->set_direction(webrtc::RtpTransceiverDirection::kSendOnly); |
| 1738 | outgoingVideoDescription->set_codecs({ _selectedPayloadType->videoCodec, _selectedPayloadType->rtxCodec }); |
| 1739 | outgoingVideoDescription->set_bandwidth(1300000); |
| 1740 | outgoingVideoDescription->AddStream(videoSendStreamParams); |
| 1741 |
| 1742 | auto incomingVideoDescription = std::make_shared<cricket::VideoContentDescription>(); |
| 1743 | for (const auto &extension : _videoExtensionMap) { |
| 1744 | incomingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(extension.second, extension.first)); |
| 1745 | } |
| 1746 | incomingVideoDescription->set_rtcp_mux(true); |
| 1747 | incomingVideoDescription->set_rtcp_reduced_size(true); |
| 1748 | incomingVideoDescription->set_direction(webrtc::RtpTransceiverDirection::kRecvOnly); |
| 1749 | incomingVideoDescription->set_codecs({ _selectedPayloadType->videoCodec, _selectedPayloadType->rtxCodec }); |
| 1750 | incomingVideoDescription->set_bandwidth(1300000); |
| 1751 |
| 1752 | _threads->getWorkerThread()->BlockingCall([&]() { |
| 1753 | std::string errorDesc; |
| 1754 | _outgoingVideoChannel->SetRemoteContent(incomingVideoDescription.get(), webrtc::SdpType::kAnswer, errorDesc); |
| 1755 | _outgoingVideoChannel->SetLocalContent(outgoingVideoDescription.get(), webrtc::SdpType::kOffer, errorDesc); |
| 1756 | _outgoingVideoChannel->SetPayloadTypeDemuxingEnabled(false); |
| 1757 | }); |
| 1758 |
| 1759 | adjustVideoSendParams(); |
| 1760 | updateVideoSend(); |
| 1761 | } |
| 1762 |
| 1763 | void adjustVideoSendParams() { |
| 1764 | if (!_outgoingVideoChannel) { |
| 1765 | return; |
| 1766 | } |
| 1767 |
| 1768 | if (_videoContentType == VideoContentType::Screencast) { |
| 1769 | _threads->getWorkerThread()->BlockingCall([this]() { |
| 1770 | webrtc::RtpParameters rtpParameters = _outgoingVideoChannel->media_channel()->GetRtpSendParameters(_outgoingVideoSsrcs.simulcastLayers[0].ssrc); |
| 1771 | if (rtpParameters.encodings.size() == 3) { |
| 1772 | for (int i = 0; i < (int)rtpParameters.encodings.size(); i++) { |
| 1773 | if (i == 0) { |
| 1774 | rtpParameters.encodings[i].min_bitrate_bps = 50000; |
| 1775 | rtpParameters.encodings[i].max_bitrate_bps = 100000; |
| 1776 | rtpParameters.encodings[i].scale_resolution_down_by = 4.0; |
| 1777 | rtpParameters.encodings[i].active = _outgoingVideoConstraint >= 180; |
| 1778 | } else if (i == 1) { |
| 1779 | rtpParameters.encodings[i].min_bitrate_bps = 150000; |
| 1780 | rtpParameters.encodings[i].max_bitrate_bps = 200000; |
| 1781 | rtpParameters.encodings[i].scale_resolution_down_by = 2.0; |
| 1782 | rtpParameters.encodings[i].active = _outgoingVideoConstraint >= 360; |
| 1783 | } else if (i == 2) { |
| 1784 | rtpParameters.encodings[i].min_bitrate_bps = 300000; |
| 1785 | rtpParameters.encodings[i].max_bitrate_bps = 800000 + 100000; |
| 1786 | rtpParameters.encodings[i].active = _outgoingVideoConstraint >= 720; |
| 1787 | } |
| 1788 | } |
| 1789 | } else if (rtpParameters.encodings.size() == 2) { |
| 1790 | for (int i = 0; i < (int)rtpParameters.encodings.size(); i++) { |
| 1791 | if (i == 0) { |
| 1792 | rtpParameters.encodings[i].min_bitrate_bps = 50000; |
| 1793 | rtpParameters.encodings[i].max_bitrate_bps = 100000; |
| 1794 | rtpParameters.encodings[i].scale_resolution_down_by = 2.0; |
| 1795 | } else if (i == 1) { |
| 1796 | rtpParameters.encodings[i].min_bitrate_bps = 200000; |
| 1797 | rtpParameters.encodings[i].max_bitrate_bps = 900000 + 100000; |
| 1798 | } |
| 1799 | } |
| 1800 | } else { |
| 1801 | rtpParameters.encodings[0].max_bitrate_bps = (800000 + 100000) * 2; |
| 1802 | } |
| 1803 |
| 1804 | _outgoingVideoChannel->media_channel()->SetRtpSendParameters(_outgoingVideoSsrcs.simulcastLayers[0].ssrc, rtpParameters); |
| 1805 | }); |
| 1806 | } else { |
| 1807 | _threads->getWorkerThread()->BlockingCall([this]() { |
| 1808 | webrtc::RtpParameters rtpParameters = _outgoingVideoChannel->media_channel()->GetRtpSendParameters(_outgoingVideoSsrcs.simulcastLayers[0].ssrc); |
| 1809 | if (rtpParameters.encodings.size() == 3) { |
| 1810 | for (int i = 0; i < (int)rtpParameters.encodings.size(); i++) { |
| 1811 | if (i == 0) { |
| 1812 | rtpParameters.encodings[i].min_bitrate_bps = 50000; |
| 1813 | rtpParameters.encodings[i].max_bitrate_bps = 60000; |
| 1814 | rtpParameters.encodings[i].scale_resolution_down_by = 4.0; |
| 1815 | rtpParameters.encodings[i].active = _outgoingVideoConstraint >= 180; |
| 1816 | } else if (i == 1) { |
| 1817 | rtpParameters.encodings[i].min_bitrate_bps = 100000; |
| 1818 | rtpParameters.encodings[i].max_bitrate_bps = 110000; |
| 1819 | rtpParameters.encodings[i].scale_resolution_down_by = 2.0; |
| 1820 | rtpParameters.encodings[i].active = _outgoingVideoConstraint >= 360; |
| 1821 | } else if (i == 2) { |
| 1822 | rtpParameters.encodings[i].min_bitrate_bps = 300000; |
| 1823 | rtpParameters.encodings[i].max_bitrate_bps = 800000 + 100000; |
| 1824 | rtpParameters.encodings[i].active = _outgoingVideoConstraint >= 720; |
| 1825 | } |
| 1826 | } |
| 1827 | } else if (rtpParameters.encodings.size() == 2) { |
| 1828 | for (int i = 0; i < (int)rtpParameters.encodings.size(); i++) { |
| 1829 | if (i == 0) { |
| 1830 | rtpParameters.encodings[i].min_bitrate_bps = 50000; |
| 1831 | rtpParameters.encodings[i].max_bitrate_bps = 100000; |
| 1832 | rtpParameters.encodings[i].scale_resolution_down_by = 4.0; |
| 1833 | } else if (i == 1) { |
| 1834 | rtpParameters.encodings[i].min_bitrate_bps = 200000; |
| 1835 | rtpParameters.encodings[i].max_bitrate_bps = 900000 + 100000; |
| 1836 | } |
| 1837 | } |
| 1838 | } else { |
| 1839 | rtpParameters.encodings[0].max_bitrate_bps = (800000 + 100000) * 2; |
| 1840 | } |
| 1841 |
| 1842 | _outgoingVideoChannel->media_channel()->SetRtpSendParameters(_outgoingVideoSsrcs.simulcastLayers[0].ssrc, rtpParameters); |
| 1843 | }); |
| 1844 | } |
| 1845 | } |
| 1846 |
| 1847 | void updateVideoSend() { |
| 1848 | if (!_outgoingVideoChannel) { |
| 1849 | return; |
| 1850 | } |
| 1851 |
| 1852 | rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> videoSource = _getVideoSource ? _getVideoSource() : nullptr; |
| 1853 | if (_getVideoSource) { |
| 1854 | _outgoingVideoChannel->Enable(true); |
| 1855 | } else { |
| 1856 | _outgoingVideoChannel->Enable(false); |
| 1857 | } |
| 1858 | _threads->getWorkerThread()->BlockingCall([this, videoSource]() { |
| 1859 | if (_getVideoSource) { |
| 1860 | _outgoingVideoChannel->media_channel()->SetVideoSend(_outgoingVideoSsrcs.simulcastLayers[0].ssrc, nullptr, videoSource.get()); |
| 1861 | } else { |
| 1862 | _outgoingVideoChannel->media_channel()->SetVideoSend(_outgoingVideoSsrcs.simulcastLayers[0].ssrc, nullptr, nullptr); |
| 1863 | } |
| 1864 | }); |
| 1865 | } |
| 1866 |
| 1867 | void destroyOutgoingAudioChannel() { |
| 1868 | if (!_outgoingAudioChannel) { |
| 1869 | return; |
| 1870 | } |
| 1871 |
| 1872 | _outgoingAudioChannel->Enable(false); |
| 1873 | _threads->getNetworkThread()->BlockingCall([&]() { |
| 1874 | _outgoingAudioChannel->SetRtpTransport(nullptr); |
| 1875 | }); |
| 1876 | _threads->getWorkerThread()->BlockingCall([this]() { |
| 1877 | _outgoingAudioChannel->media_channel()->SetAudioSend(_outgoingAudioSsrc, false, nullptr, &_audioSource); |
| 1878 | _channelManager->DestroyChannel(_outgoingAudioChannel); |
| 1879 | }); |
| 1880 | _outgoingAudioChannel = nullptr; |
| 1881 | } |
| 1882 |
| 1883 | void createOutgoingAudioChannel() { |
| 1884 | if (_outgoingAudioChannel) { |
| 1885 | return; |
| 1886 | } |
| 1887 |
| 1888 | cricket::AudioOptions audioOptions; |
| 1889 | if (_disableOutgoingAudioProcessing || _videoContentType == VideoContentType::Screencast) { |
| 1890 | RTC_LOG(LS_ERROR) << "outgoing audio processing disabled"; |
| 1891 | audioOptions.echo_cancellation = false; |
| 1892 | audioOptions.noise_suppression = false; |
| 1893 | audioOptions.auto_gain_control = false; |
| 1894 | audioOptions.highpass_filter = false; |
| 1895 | //audioOptions.typing_detection = false; |
| 1896 | //audioOptions.residual_echo_detector = false; |
| 1897 | } else { |
| 1898 | audioOptions.echo_cancellation = true; |
| 1899 | audioOptions.noise_suppression = true; |
| 1900 | //audioOptions.residual_echo_detector = true; |
| 1901 | } |
| 1902 |
| 1903 | std::vector<std::string> streamIds; |
| 1904 | streamIds.push_back("1"); |
| 1905 |
| 1906 | _outgoingAudioChannel = _channelManager->CreateVoiceChannel(_call.get(), cricket::MediaConfig(), "0", false, GroupNetworkManager::getDefaulCryptoOptions(), audioOptions); |
| 1907 | _threads->getNetworkThread()->BlockingCall([&]() { |
| 1908 | _outgoingAudioChannel->SetRtpTransport(_rtpTransport); |
| 1909 | }); |
| 1910 |
| 1911 | int opusMinBitrateKbps = _outgoingAudioBitrateKbit; |
| 1912 | int opusMaxBitrateKbps = _outgoingAudioBitrateKbit; |
| 1913 | int opusStartBitrateKbps = _outgoingAudioBitrateKbit; |
| 1914 | const uint8_t opusPTimeMs = _outgoingAudioBitrateKbit == 32 ? 120 : 10; |
| 1915 |
| 1916 | cricket::AudioCodec opusCodec(111, "opus", 48000, 0, 2); |
| 1917 | opusCodec.AddFeedbackParam(cricket::FeedbackParam(cricket::kRtcpFbParamTransportCc)); |
| 1918 | opusCodec.SetParam(cricket::kCodecParamMinBitrate, opusMinBitrateKbps); |
| 1919 | opusCodec.SetParam(cricket::kCodecParamStartBitrate, opusStartBitrateKbps); |
| 1920 | opusCodec.SetParam(cricket::kCodecParamMaxBitrate, opusMaxBitrateKbps); |
| 1921 | opusCodec.SetParam(cricket::kCodecParamUseInbandFec, 1); |
| 1922 | opusCodec.SetParam(cricket::kCodecParamPTime, opusPTimeMs); |
| 1923 |
| 1924 | auto outgoingAudioDescription = std::make_shared<cricket::AudioContentDescription>(); |
| 1925 | outgoingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAudioLevelUri, 1)); |
| 1926 | outgoingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAbsSendTimeUri, 2)); |
| 1927 | outgoingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kTransportSequenceNumberUri, 3)); |
| 1928 | outgoingAudioDescription->set_rtcp_mux(true); |
| 1929 | outgoingAudioDescription->set_rtcp_reduced_size(true); |
| 1930 | outgoingAudioDescription->set_direction(webrtc::RtpTransceiverDirection::kSendOnly); |
| 1931 | outgoingAudioDescription->set_codecs({ opusCodec }); |
| 1932 | outgoingAudioDescription->set_bandwidth(1300000); |
| 1933 | outgoingAudioDescription->AddStream(cricket::StreamParams::CreateLegacy(_outgoingAudioSsrc)); |
| 1934 |
| 1935 | auto incomingAudioDescription = std::make_shared<cricket::AudioContentDescription>(); |
| 1936 | incomingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAudioLevelUri, 1)); |
| 1937 | incomingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAbsSendTimeUri, 2)); |
| 1938 | incomingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kTransportSequenceNumberUri, 3)); |
| 1939 | incomingAudioDescription->set_rtcp_mux(true); |
| 1940 | incomingAudioDescription->set_rtcp_reduced_size(true); |
| 1941 | incomingAudioDescription->set_direction(webrtc::RtpTransceiverDirection::kRecvOnly); |
| 1942 | incomingAudioDescription->set_codecs({ opusCodec }); |
| 1943 | incomingAudioDescription->set_bandwidth(1300000); |
| 1944 |
| 1945 | _threads->getWorkerThread()->BlockingCall([&]() { |
| 1946 | std::string errorDesc; |
| 1947 | _outgoingAudioChannel->SetLocalContent(outgoingAudioDescription.get(), webrtc::SdpType::kOffer, errorDesc); |
| 1948 | _outgoingAudioChannel->SetRemoteContent(incomingAudioDescription.get(), webrtc::SdpType::kAnswer, errorDesc); |
| 1949 | _outgoingAudioChannel->SetPayloadTypeDemuxingEnabled(false); |
| 1950 | }); |
| 1951 |
| 1952 | _outgoingAudioChannel->Enable(true); |
| 1953 |
| 1954 | onUpdatedIsMuted(); |
| 1955 |
| 1956 | adjustBitratePreferences(false); |
| 1957 | } |
| 1958 |
| 1959 | void stop() { |
| 1960 | _networkManager->perform([](GroupNetworkManager *networkManager) { |
| 1961 | networkManager->stop(); |
| 1962 | }); |
| 1963 | } |
| 1964 |
| 1965 | void updateSsrcAudioLevel(uint32_t ssrc, uint8_t audioLevel, bool isSpeech) { |
| 1966 | float mappedLevelDb = ((float)audioLevel) / (float)(0x7f); |
| 1967 |
| 1968 | //mappedLevelDb = fabs(1.0f - mappedLevelDb); |
| 1969 | //float mappedLevel = pow(10.0f, mappedLevelDb * 0.1f); |
| 1970 |
| 1971 | //printf("mappedLevelDb: %f, mappedLevel: %f\n", mappedLevelDb, mappedLevel); |
| 1972 |
| 1973 | float mappedLevel = (fabs(1.0f - mappedLevelDb)) * 1.0f; |
| 1974 |
| 1975 | auto it = _audioLevels.find(ChannelId(ssrc)); |
| 1976 | if (it != _audioLevels.end()) { |
| 1977 | it->second.value.level = fmax(it->second.value.level, mappedLevel); |
| 1978 | if (isSpeech) { |
| 1979 | it->second.value.voice = true; |
| 1980 | } |
| 1981 | it->second.timestamp = rtc::TimeMillis(); |
| 1982 | } else { |
| 1983 | InternalGroupLevelValue updated; |
| 1984 | updated.value.level = mappedLevel; |
| 1985 | updated.value.voice = isSpeech; |
| 1986 | updated.timestamp = rtc::TimeMillis(); |
| 1987 | _audioLevels.insert(std::make_pair(ChannelId(ssrc), std::move(updated))); |
| 1988 | } |
| 1989 |
| 1990 | auto audioChannel = _incomingAudioChannels.find(ChannelId(ssrc)); |
| 1991 | if (audioChannel != _incomingAudioChannels.end()) { |
| 1992 | audioChannel->second->updateActivity(); |
| 1993 | } |
| 1994 | } |
| 1995 |
| 1996 | void beginLevelsTimer(int timeoutMs) { |
| 1997 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 1998 | _threads->getMediaThread()->PostDelayedTask([weak]() { |
| 1999 | auto strong = weak.lock(); |
| 2000 | if (!strong) { |
| 2001 | return; |
| 2002 | } |
| 2003 |
| 2004 | //int64_t timestamp = rtc::TimeMillis(); |
| 2005 | //int64_t maxSampleTimeout = 400; |
| 2006 |
| 2007 | GroupLevelsUpdate levelsUpdate; |
| 2008 | levelsUpdate.updates.reserve(strong->_audioLevels.size() + 1); |
| 2009 | for (auto &it : strong->_audioLevels) { |
| 2010 | /*if (it.second.value.level < 0.001f) { |
| 2011 | continue; |
| 2012 | } |
| 2013 | if (it.second.timestamp <= timestamp - maxSampleTimeout) { |
| 2014 | continue; |
| 2015 | }*/ |
| 2016 |
| 2017 | uint32_t effectiveSsrc = it.first.actualSsrc; |
| 2018 | if (std::find_if(levelsUpdate.updates.begin(), levelsUpdate.updates.end(), [&](GroupLevelUpdate const &item) { |
| 2019 | return item.ssrc == effectiveSsrc; |
| 2020 | }) != levelsUpdate.updates.end()) { |
| 2021 | continue; |
| 2022 | } |
| 2023 | levelsUpdate.updates.push_back(GroupLevelUpdate{ |
| 2024 | effectiveSsrc, |
| 2025 | it.second.value, |
| 2026 | }); |
| 2027 | if (it.second.value.level > 0.001f) { |
| 2028 | auto audioChannel = strong->_incomingAudioChannels.find(it.first); |
| 2029 | if (audioChannel != strong->_incomingAudioChannels.end()) { |
| 2030 | audioChannel->second->updateActivity(); |
| 2031 | } |
| 2032 | } |
| 2033 |
| 2034 | //it.second.value.level *= 0.5f; |
| 2035 | //it.second.value.voice = false; |
| 2036 | } |
| 2037 |
| 2038 | strong->_audioLevels.clear(); |
| 2039 |
| 2040 | auto myAudioLevel = strong->_myAudioLevel; |
| 2041 | myAudioLevel.isMuted = strong->_isMuted; |
| 2042 | levelsUpdate.updates.push_back(GroupLevelUpdate{ 0, myAudioLevel }); |
| 2043 |
| 2044 | if (strong->_audioLevelsUpdated) { |
| 2045 | strong->_audioLevelsUpdated(levelsUpdate); |
| 2046 | } |
| 2047 |
| 2048 | bool isSpeech = myAudioLevel.voice && !myAudioLevel.isMuted; |
| 2049 | strong->_networkManager->perform([isSpeech = isSpeech](GroupNetworkManager *networkManager) { |
| 2050 | networkManager->setOutgoingVoiceActivity(isSpeech); |
| 2051 | }); |
| 2052 |
| 2053 | strong->beginLevelsTimer(100); |
| 2054 | }, webrtc::TimeDelta::Millis(timeoutMs)); |
| 2055 | } |
| 2056 |
| 2057 | void beginAudioChannelCleanupTimer(int delayMs) { |
| 2058 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 2059 | _threads->getMediaThread()->PostDelayedTask([weak]() { |
| 2060 | auto strong = weak.lock(); |
| 2061 | if (!strong) { |
| 2062 | return; |
| 2063 | } |
| 2064 |
| 2065 | auto timestamp = rtc::TimeMillis(); |
| 2066 |
| 2067 | std::vector<ChannelId> removeChannels; |
| 2068 | for (const auto &it : strong->_incomingAudioChannels) { |
| 2069 | if (it.first.networkSsrc == 1) { |
| 2070 | continue; |
| 2071 | } |
| 2072 | auto activity = it.second->getActivity(); |
| 2073 | if (activity < timestamp - 1000) { |
| 2074 | removeChannels.push_back(it.first); |
| 2075 | } |
| 2076 | } |
| 2077 |
| 2078 | for (const auto &channelId : removeChannels) { |
| 2079 | strong->removeIncomingAudioChannel(channelId); |
| 2080 | } |
| 2081 |
| 2082 | strong->beginAudioChannelCleanupTimer(500); |
| 2083 | }, webrtc::TimeDelta::Millis(delayMs)); |
| 2084 | } |
| 2085 |
| 2086 | void beginRemoteConstraintsUpdateTimer(int delayMs) { |
| 2087 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 2088 | _threads->getMediaThread()->PostDelayedTask([weak]() { |
| 2089 | auto strong = weak.lock(); |
| 2090 | if (!strong) { |
| 2091 | return; |
| 2092 | } |
| 2093 |
| 2094 | strong->maybeUpdateRemoteVideoConstraints(); |
| 2095 |
| 2096 | strong->beginRemoteConstraintsUpdateTimer(5000); |
| 2097 | }, webrtc::TimeDelta::Millis(delayMs)); |
| 2098 | } |
| 2099 |
| 2100 | void beginNetworkStatusTimer(int delayMs) { |
| 2101 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 2102 | _threads->getMediaThread()->PostDelayedTask([weak]() { |
| 2103 | auto strong = weak.lock(); |
| 2104 | if (!strong) { |
| 2105 | return; |
| 2106 | } |
| 2107 |
| 2108 | if (strong->_connectionMode == GroupConnectionMode::GroupConnectionModeBroadcast || strong->_broadcastEnabledUntilRtcIsConnectedAtTimestamp) { |
| 2109 | strong->updateBroadcastNetworkStatus(); |
| 2110 | } |
| 2111 |
| 2112 | strong->beginNetworkStatusTimer(500); |
| 2113 | }, webrtc::TimeDelta::Millis(delayMs)); |
| 2114 | } |
| 2115 |
| 2116 | void updateBroadcastNetworkStatus() { |
| 2117 | bool isBroadcastConnected = true; |
| 2118 |
| 2119 | if (isBroadcastConnected != _isBroadcastConnected) { |
| 2120 | _isBroadcastConnected = isBroadcastConnected; |
| 2121 | updateIsConnected(); |
| 2122 | } |
| 2123 | } |
| 2124 |
| 2125 |
| 2126 | void configureVideoParams() { |
| 2127 | if (!_sharedVideoInformation) { |
| 2128 | return; |
| 2129 | } |
| 2130 | if (_selectedPayloadType) { |
| 2131 | // Already configured. |
| 2132 | return; |
| 2133 | } |
| 2134 |
| 2135 | _availablePayloadTypes = assignPayloadTypes(_availableVideoFormats); |
| 2136 | if (_availablePayloadTypes.empty()) { |
| 2137 | return; |
| 2138 | } |
| 2139 |
| 2140 | for (const auto &payloadType : _availablePayloadTypes) { |
| 2141 | GroupJoinPayloadVideoPayloadType payload; |
| 2142 | payload.id = payloadType.videoCodec.id; |
| 2143 | payload.name = payloadType.videoCodec.name; |
| 2144 | payload.clockrate = payloadType.videoCodec.clockrate; |
| 2145 | payload.channels = 0; |
| 2146 |
| 2147 | std::vector<GroupJoinPayloadVideoPayloadType::FeedbackType> feedbackTypes; |
| 2148 |
| 2149 | GroupJoinPayloadVideoPayloadType::FeedbackType fbGoogRemb; |
| 2150 | fbGoogRemb.type = "goog-remb"; |
| 2151 | feedbackTypes.push_back(fbGoogRemb); |
| 2152 |
| 2153 | GroupJoinPayloadVideoPayloadType::FeedbackType fbTransportCc; |
| 2154 | fbTransportCc.type = "transport-cc"; |
| 2155 | feedbackTypes.push_back(fbTransportCc); |
| 2156 |
| 2157 | GroupJoinPayloadVideoPayloadType::FeedbackType fbCcmFir; |
| 2158 | fbCcmFir.type = "ccm"; |
| 2159 | fbCcmFir.subtype = "fir"; |
| 2160 | feedbackTypes.push_back(fbCcmFir); |
| 2161 |
| 2162 | GroupJoinPayloadVideoPayloadType::FeedbackType fbNack; |
| 2163 | fbNack.type = "nack"; |
| 2164 | feedbackTypes.push_back(fbNack); |
| 2165 |
| 2166 | GroupJoinPayloadVideoPayloadType::FeedbackType fbNackPli; |
| 2167 | fbNackPli.type = "nack"; |
| 2168 | fbNackPli.subtype = "pli"; |
| 2169 | feedbackTypes.push_back(fbNackPli); |
| 2170 |
| 2171 | payload.feedbackTypes = feedbackTypes; |
| 2172 | payload.parameters = {}; |
| 2173 |
| 2174 | _videoPayloadTypes.push_back(std::move(payload)); |
| 2175 |
| 2176 | GroupJoinPayloadVideoPayloadType rtxPayload; |
| 2177 | rtxPayload.id = payloadType.rtxCodec.id; |
| 2178 | rtxPayload.name = payloadType.rtxCodec.name; |
| 2179 | rtxPayload.clockrate = payloadType.rtxCodec.clockrate; |
| 2180 | rtxPayload.parameters.push_back(std::make_pair("apt", intToString(payloadType.videoCodec.id))); |
| 2181 | _videoPayloadTypes.push_back(std::move(rtxPayload)); |
| 2182 | } |
| 2183 |
| 2184 | std::vector<std::string> codecPriorities; |
| 2185 | for (const auto name : _videoCodecPreferences) { |
| 2186 | std::string codecName; |
| 2187 | switch (name) { |
| 2188 | case VideoCodecName::VP8: { |
| 2189 | codecName = cricket::kVp8CodecName; |
| 2190 | break; |
| 2191 | } |
| 2192 | case VideoCodecName::VP9: { |
| 2193 | codecName = cricket::kVp9CodecName; |
| 2194 | break; |
| 2195 | } |
| 2196 | case VideoCodecName::H264: { |
| 2197 | codecName = cricket::kH264CodecName; |
| 2198 | break; |
| 2199 | } |
| 2200 | default: { |
| 2201 | break; |
| 2202 | } |
| 2203 | } |
| 2204 | if (codecName.size() != 0) { |
| 2205 | codecPriorities.push_back(std::move(codecName)); |
| 2206 | } |
| 2207 | } |
| 2208 | std::vector<std::string> defaultCodecPriorities = { |
| 2209 | cricket::kVp8CodecName, |
| 2210 | cricket::kVp9CodecName |
| 2211 | }; |
| 2212 |
| 2213 | bool enableH264 = false; |
| 2214 | for (const auto &payloadType : _sharedVideoInformation->payloadTypes) { |
| 2215 | if (payloadType.name == cricket::kH264CodecName) { |
| 2216 | enableH264 = true; |
| 2217 | break; |
| 2218 | } |
| 2219 | } |
| 2220 | if (enableH264) { |
| 2221 | defaultCodecPriorities.insert(defaultCodecPriorities.begin(), cricket::kH264CodecName); |
| 2222 | } |
| 2223 |
| 2224 | for (const auto &name : defaultCodecPriorities) { |
| 2225 | if (std::find(codecPriorities.begin(), codecPriorities.end(), name) == codecPriorities.end()) { |
| 2226 | codecPriorities.push_back(name); |
| 2227 | } |
| 2228 | } |
| 2229 |
| 2230 | for (const auto &codecName : codecPriorities) { |
| 2231 | if (_selectedPayloadType) { |
| 2232 | break; |
| 2233 | } |
| 2234 | for (const auto &payloadType : _availablePayloadTypes) { |
| 2235 | if (payloadType.videoCodec.name == codecName) { |
| 2236 | _selectedPayloadType = payloadType; |
| 2237 | break; |
| 2238 | } |
| 2239 | } |
| 2240 | } |
| 2241 | if (!_selectedPayloadType) { |
| 2242 | return; |
| 2243 | } |
| 2244 |
| 2245 | _videoExtensionMap.emplace_back(2, webrtc::RtpExtension::kAbsSendTimeUri); |
| 2246 | _videoExtensionMap.emplace_back(3, webrtc::RtpExtension::kTransportSequenceNumberUri); |
| 2247 | _videoExtensionMap.emplace_back(13, webrtc::RtpExtension::kVideoRotationUri); |
| 2248 | } |
| 2249 |
| 2250 | void OnSentPacket_w(const rtc::SentPacket& sent_packet) { |
| 2251 | _call->OnSentPacket(sent_packet); |
| 2252 | } |
| 2253 |
| 2254 | void OnRtcpPacketReceived_n(rtc::CopyOnWriteBuffer *buffer, int64_t packet_time_us) { |
| 2255 | rtc::CopyOnWriteBuffer packet = *buffer; |
| 2256 | if (_call) { |
| 2257 | _call->Receiver()->DeliverPacket(webrtc::MediaType::ANY, packet, packet_time_us); |
| 2258 | } |
| 2259 | } |
| 2260 |
| 2261 | void adjustBitratePreferences(bool resetStartBitrate) { |
| 2262 | webrtc::BitrateConstraints preferences; |
| 2263 | webrtc::BitrateSettings settings; |
| 2264 | if (_getVideoSource) { |
| 2265 | settings.min_bitrate_bps = _minOutgoingVideoBitrateKbit * 1024; |
| 2266 | if (resetStartBitrate) { |
| 2267 | preferences.start_bitrate_bps = std::max(preferences.min_bitrate_bps, 400 * 1000); |
| 2268 | } |
| 2269 | if (_videoContentType == VideoContentType::Screencast) { |
| 2270 | preferences.max_bitrate_bps = std::max(preferences.min_bitrate_bps, (1020 + 32) * 1000); |
| 2271 | } else { |
| 2272 | preferences.max_bitrate_bps = std::max(preferences.min_bitrate_bps, (1020 + 32) * 1000); |
| 2273 | } |
| 2274 | } else { |
| 2275 | preferences.min_bitrate_bps = _outgoingAudioBitrateKbit * 1024; |
| 2276 | if (resetStartBitrate) { |
| 2277 | preferences.start_bitrate_bps = _outgoingAudioBitrateKbit * 1024; |
| 2278 | } |
| 2279 | preferences.max_bitrate_bps = _outgoingAudioBitrateKbit * 1024; |
| 2280 | } |
| 2281 |
| 2282 | settings.min_bitrate_bps = preferences.min_bitrate_bps; |
| 2283 | settings.start_bitrate_bps = preferences.start_bitrate_bps; |
| 2284 | settings.max_bitrate_bps = preferences.max_bitrate_bps; |
| 2285 |
| 2286 | _call->GetTransportControllerSend()->SetSdpBitrateParameters(preferences); |
| 2287 | _threads->getWorkerThread()->BlockingCall([&]() { |
| 2288 | _call->SetClientBitratePreferences(settings); |
| 2289 | }); |
| 2290 | } |
| 2291 |
| 2292 | void setIsRtcConnected(bool isConnected) { |
| 2293 | if (_isRtcConnected == isConnected) { |
| 2294 | return; |
| 2295 | } |
| 2296 | _isRtcConnected = isConnected; |
| 2297 |
| 2298 | RTC_LOG(LS_INFO) << formatTimestampMillis(rtc::TimeMillis()) << ": " << "setIsRtcConnected: " << _isRtcConnected; |
| 2299 |
| 2300 | if (_broadcastEnabledUntilRtcIsConnectedAtTimestamp) { |
| 2301 | _broadcastEnabledUntilRtcIsConnectedAtTimestamp = absl::nullopt; |
| 2302 |
| 2303 | if (_streamingContext) { |
| 2304 | _streamingContext.reset(); |
| 2305 | _audioDeviceDataObserverShared->setStreamingContext(nullptr); |
| 2306 | } |
| 2307 | } |
| 2308 |
| 2309 | updateIsConnected(); |
| 2310 | } |
| 2311 |
| 2312 | void updateIsConnected() { |
| 2313 | bool isEffectivelyConnected = false; |
| 2314 | bool isTransitioningFromBroadcastToRtc = false; |
| 2315 | switch (_connectionMode) { |
| 2316 | case GroupConnectionMode::GroupConnectionModeNone: { |
| 2317 | isEffectivelyConnected = false; |
| 2318 | if (_broadcastEnabledUntilRtcIsConnectedAtTimestamp && _isBroadcastConnected) { |
| 2319 | isEffectivelyConnected = true; |
| 2320 | isTransitioningFromBroadcastToRtc = true; |
| 2321 | } |
| 2322 | break; |
| 2323 | } |
| 2324 | case GroupConnectionMode::GroupConnectionModeRtc: { |
| 2325 | isEffectivelyConnected = _isRtcConnected; |
| 2326 | if (_broadcastEnabledUntilRtcIsConnectedAtTimestamp && _isBroadcastConnected) { |
| 2327 | isEffectivelyConnected = true; |
| 2328 | isTransitioningFromBroadcastToRtc = true; |
| 2329 | } |
| 2330 | break; |
| 2331 | } |
| 2332 | case GroupConnectionMode::GroupConnectionModeBroadcast: { |
| 2333 | isEffectivelyConnected = _isBroadcastConnected; |
| 2334 | break; |
| 2335 | } |
| 2336 | } |
| 2337 |
| 2338 | GroupNetworkState effectiveNetworkState; |
| 2339 | effectiveNetworkState.isConnected = isEffectivelyConnected; |
| 2340 | effectiveNetworkState.isTransitioningFromBroadcastToRtc = isTransitioningFromBroadcastToRtc; |
| 2341 |
| 2342 | if (_effectiveNetworkState.isConnected != effectiveNetworkState.isConnected || _effectiveNetworkState.isTransitioningFromBroadcastToRtc != effectiveNetworkState.isTransitioningFromBroadcastToRtc) { |
| 2343 | _effectiveNetworkState = effectiveNetworkState; |
| 2344 |
| 2345 | if (_networkStateUpdated) { |
| 2346 | _networkStateUpdated(_effectiveNetworkState); |
| 2347 | } |
| 2348 | } |
| 2349 | } |
| 2350 |
| 2351 | void updateIsDataChannelOpen(bool isDataChannelOpen) { |
| 2352 | if (_isDataChannelOpen == isDataChannelOpen) { |
| 2353 | return; |
| 2354 | } |
| 2355 | _isDataChannelOpen = isDataChannelOpen; |
| 2356 |
| 2357 | if (_isDataChannelOpen) { |
| 2358 | maybeUpdateRemoteVideoConstraints(); |
| 2359 | } |
| 2360 | } |
| 2361 |
| 2362 | void receiveUnknownSsrcPacket(uint32_t ssrc, int payloadType) { |
| 2363 | if (ssrc == _outgoingAudioSsrc) { |
| 2364 | return; |
| 2365 | } |
| 2366 |
| 2367 | auto ssrcInfo = _channelBySsrc.find(ssrc); |
| 2368 | if (ssrcInfo == _channelBySsrc.end()) { |
| 2369 | // opus |
| 2370 | if (payloadType == 111) { |
| 2371 | maybeRequestUnknownSsrc(ssrc); |
| 2372 | } |
| 2373 | } else { |
| 2374 | switch (ssrcInfo->second.type) { |
| 2375 | case ChannelSsrcInfo::Type::Audio: { |
| 2376 | const auto it = _incomingAudioChannels.find(ChannelId(ssrc)); |
| 2377 | if (it != _incomingAudioChannels.end()) { |
| 2378 | it->second->updateActivity(); |
| 2379 | } |
| 2380 |
| 2381 | break; |
| 2382 | } |
| 2383 | case ChannelSsrcInfo::Type::Video: { |
| 2384 | break; |
| 2385 | } |
| 2386 | default: { |
| 2387 | break; |
| 2388 | } |
| 2389 | } |
| 2390 | } |
| 2391 | } |
| 2392 |
| 2393 | void receiveRtcpPacket(rtc::CopyOnWriteBuffer const &packet, int64_t timestamp) { |
| 2394 | _threads->getWorkerThread()->PostTask([this, packet, timestamp]() { |
| 2395 | _call->Receiver()->DeliverPacket(webrtc::MediaType::ANY, packet, timestamp); |
| 2396 | }); |
| 2397 | } |
| 2398 |
| 2399 | void receiveDataChannelMessage(std::string const &message) { |
| 2400 | std::string parsingError; |
| 2401 | auto json = json11::Json::parse(message, parsingError); |
| 2402 | if (json.type() != json11::Json::OBJECT) { |
| 2403 | RTC_LOG(LS_WARNING) << "receiveDataChannelMessage: error parsing message: " << parsingError; |
| 2404 | return; |
| 2405 | } |
| 2406 |
| 2407 | if (json.is_object()) { |
| 2408 | const auto colibriClass = json.object_items().find("colibriClass"); |
| 2409 | if (colibriClass != json.object_items().end() && colibriClass->second.is_string()) { |
| 2410 | const auto messageType = colibriClass->second.string_value(); |
| 2411 | if (messageType == "SenderVideoConstraints") { |
| 2412 | const auto videoConstraints = json.object_items().find("videoConstraints"); |
| 2413 | if (videoConstraints != json.object_items().end() && videoConstraints->second.is_object()) { |
| 2414 | const auto idealHeight = videoConstraints->second.object_items().find("idealHeight"); |
| 2415 | if (idealHeight != videoConstraints->second.object_items().end() && idealHeight->second.is_number()) { |
| 2416 | int outgoingVideoConstraint = idealHeight->second.int_value(); |
| 2417 | if (_outgoingVideoConstraint != outgoingVideoConstraint) { |
| 2418 | if (_outgoingVideoConstraint > outgoingVideoConstraint) { |
| 2419 | _pendingOutgoingVideoConstraint = outgoingVideoConstraint; |
| 2420 |
| 2421 | int requestId = _pendingOutgoingVideoConstraintRequestId; |
| 2422 | _pendingOutgoingVideoConstraintRequestId += 1; |
| 2423 |
| 2424 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 2425 | _threads->getMediaThread()->PostDelayedTask([weak, requestId]() { |
| 2426 | auto strong = weak.lock(); |
| 2427 | if (!strong) { |
| 2428 | return; |
| 2429 | } |
| 2430 | if (strong->_pendingOutgoingVideoConstraint != -1 && strong->_pendingOutgoingVideoConstraintRequestId == requestId) { |
| 2431 | if (strong->_outgoingVideoConstraint != strong->_pendingOutgoingVideoConstraint) { |
| 2432 | strong->_outgoingVideoConstraint = strong->_pendingOutgoingVideoConstraint; |
| 2433 | strong->adjustVideoSendParams(); |
| 2434 | } |
| 2435 | strong->_pendingOutgoingVideoConstraint = -1; |
| 2436 | } |
| 2437 | }, webrtc::TimeDelta::Millis(2000)); |
| 2438 | } else { |
| 2439 | _pendingOutgoingVideoConstraint = -1; |
| 2440 | _pendingOutgoingVideoConstraintRequestId += 1; |
| 2441 | _outgoingVideoConstraint = outgoingVideoConstraint; |
| 2442 | adjustVideoSendParams(); |
| 2443 | } |
| 2444 | } |
| 2445 | } |
| 2446 | } |
| 2447 | } else if (messageType == "DebugMessage") { |
| 2448 | const auto message = json.object_items().find("message"); |
| 2449 | if (message != json.object_items().end() && message->second.is_string()) { |
| 2450 | std::vector<std::string> parts = splitString(message->second.string_value(), '\n'); |
| 2451 | for (const auto &part : parts) { |
| 2452 | std::string cleanString = part; |
| 2453 | std::size_t index = cleanString.find("="); |
| 2454 | if (index == std::string::npos) { |
| 2455 | continue; |
| 2456 | } |
| 2457 | cleanString.erase(cleanString.begin(), cleanString.begin() + index + 1); |
| 2458 |
| 2459 | index = cleanString.find("target="); |
| 2460 | if (index == std::string::npos) { |
| 2461 | continue; |
| 2462 | } |
| 2463 |
| 2464 | std::string endpointId = cleanString.substr(0, index); |
| 2465 | cleanString.erase(cleanString.begin(), cleanString.begin() + index + 7); |
| 2466 |
| 2467 | index = cleanString.find("p/"); |
| 2468 | if (index == std::string::npos) { |
| 2469 | continue; |
| 2470 | } |
| 2471 |
| 2472 | std::string targetQuality = cleanString.substr(0, index); |
| 2473 | cleanString.erase(cleanString.begin(), cleanString.begin() + index + 2); |
| 2474 |
| 2475 | index = cleanString.find("ideal="); |
| 2476 | if (index == std::string::npos) { |
| 2477 | continue; |
| 2478 | } |
| 2479 |
| 2480 | cleanString.erase(cleanString.begin(), cleanString.begin() + index + 6); |
| 2481 |
| 2482 | index = cleanString.find("p/"); |
| 2483 | if (index == std::string::npos) { |
| 2484 | continue; |
| 2485 | } |
| 2486 |
| 2487 | std::string availableQuality = cleanString.substr(0, index); |
| 2488 |
| 2489 | for (const auto &it : _incomingVideoChannels) { |
| 2490 | if (it.second->endpointId() == endpointId) { |
| 2491 | GroupInstanceStats::IncomingVideoStats incomingVideoStats; |
| 2492 | incomingVideoStats.receivingQuality = stringToInt(targetQuality); |
| 2493 | incomingVideoStats.availableQuality = stringToInt(availableQuality); |
| 2494 | it.second->setStats(incomingVideoStats); |
| 2495 | } |
| 2496 | } |
| 2497 | } |
| 2498 | } |
| 2499 | } |
| 2500 | } |
| 2501 | } |
| 2502 | } |
| 2503 |
| 2504 | void maybeRequestUnknownSsrc(uint32_t ssrc) { |
| 2505 | if (!_requestMediaChannelDescriptions) { |
| 2506 | MediaChannelDescription description; |
| 2507 | description.audioSsrc = ssrc; |
| 2508 | processMediaChannelDescriptionsResponse(-1, {description}); |
| 2509 | return; |
| 2510 | } |
| 2511 |
| 2512 | for (const auto &it : _requestedMediaChannelDescriptions) { |
| 2513 | if (std::find(it.second.ssrcs.begin(), it.second.ssrcs.end(), ssrc) != it.second.ssrcs.end()) { |
| 2514 | return; |
| 2515 | } |
| 2516 | } |
| 2517 |
| 2518 | int requestId = _nextMediaChannelDescriptionsRequestId; |
| 2519 | _nextMediaChannelDescriptionsRequestId += 1; |
| 2520 |
| 2521 | std::vector<uint32_t> requestSsrcs = { ssrc }; |
| 2522 |
| 2523 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 2524 | auto task = _requestMediaChannelDescriptions(requestSsrcs, [weak, threads = _threads, requestId](std::vector<MediaChannelDescription> &&descriptions) { |
| 2525 | threads->getMediaThread()->PostTask([weak, requestId, descriptions = std::move(descriptions)]() mutable { |
| 2526 | auto strong = weak.lock(); |
| 2527 | if (!strong) { |
| 2528 | return; |
| 2529 | } |
| 2530 |
| 2531 | strong->processMediaChannelDescriptionsResponse(requestId, descriptions); |
| 2532 | }); |
| 2533 | }); |
| 2534 | _requestedMediaChannelDescriptions.insert(std::make_pair(requestId, RequestedMediaChannelDescriptions(task, std::move(requestSsrcs)))); |
| 2535 | } |
| 2536 |
| 2537 | void processMediaChannelDescriptionsResponse(int requestId, std::vector<MediaChannelDescription> const &descriptions) { |
| 2538 | _requestedMediaChannelDescriptions.erase(requestId); |
| 2539 |
| 2540 | if (_disableIncomingChannels) { |
| 2541 | return; |
| 2542 | } |
| 2543 |
| 2544 | for (const auto &description : descriptions) { |
| 2545 | switch (description.type) { |
| 2546 | case MediaChannelDescription::Type::Audio: { |
| 2547 | if (description.audioSsrc != 0) { |
| 2548 | addIncomingAudioChannel(ChannelId(description.audioSsrc)); |
| 2549 | } |
| 2550 | break; |
| 2551 | } |
| 2552 | case MediaChannelDescription::Type::Video: { |
| 2553 | break; |
| 2554 | } |
| 2555 | default: { |
| 2556 | break; |
| 2557 | } |
| 2558 | } |
| 2559 | } |
| 2560 | } |
| 2561 |
| 2562 | void maybeDeliverBufferedPackets(uint32_t ssrc) { |
| 2563 | // TODO: Re-enable after implementing custom transport |
| 2564 | /*auto packets = _missingPacketBuffer.get(ssrc); |
| 2565 | if (packets.size() != 0) { |
| 2566 | auto it = _ssrcMapping.find(ssrc); |
| 2567 | if (it != _ssrcMapping.end()) { |
| 2568 | for (const auto &packet : packets) { |
| 2569 | _threads->getNetworkThread()->BlockingCall([this, packet]() { |
| 2570 | _rtpTransport->DemuxPacketInternal(packet, -1); |
| 2571 | }); |
| 2572 | } |
| 2573 | } |
| 2574 | }*/ |
| 2575 | } |
| 2576 |
| 2577 | void maybeUpdateRemoteVideoConstraints() { |
| 2578 | if (!_isDataChannelOpen) { |
| 2579 | return; |
| 2580 | } |
| 2581 |
| 2582 | std::string pinnedEndpoint; |
| 2583 |
| 2584 | json11::Json::object json; |
| 2585 | json.insert(std::make_pair("colibriClass", json11::Json("ReceiverVideoConstraints"))); |
| 2586 |
| 2587 | json11::Json::object defaultConstraints; |
| 2588 | defaultConstraints.insert(std::make_pair("maxHeight", json11::Json(0))); |
| 2589 | json.insert(std::make_pair("defaultConstraints", json11::Json(std::move(defaultConstraints)))); |
| 2590 |
| 2591 | json11::Json::array onStageEndpoints; |
| 2592 | json11::Json::object constraints; |
| 2593 |
| 2594 | for (const auto &incomingVideoChannel : _incomingVideoChannels) { |
| 2595 | json11::Json::object selectedConstraint; |
| 2596 |
| 2597 | switch (incomingVideoChannel.second->requestedMinQuality()) { |
| 2598 | case VideoChannelDescription::Quality::Full: { |
| 2599 | selectedConstraint.insert(std::make_pair("minHeight", json11::Json(720))); |
| 2600 | break; |
| 2601 | } |
| 2602 | case VideoChannelDescription::Quality::Medium: { |
| 2603 | selectedConstraint.insert(std::make_pair("minHeight", json11::Json(360))); |
| 2604 | break; |
| 2605 | } |
| 2606 | case VideoChannelDescription::Quality::Thumbnail: { |
| 2607 | selectedConstraint.insert(std::make_pair("minHeight", json11::Json(180))); |
| 2608 | break; |
| 2609 | } |
| 2610 | default: { |
| 2611 | break; |
| 2612 | } |
| 2613 | } |
| 2614 | switch (incomingVideoChannel.second->requestedMaxQuality()) { |
| 2615 | case VideoChannelDescription::Quality::Full: { |
| 2616 | onStageEndpoints.push_back(json11::Json(incomingVideoChannel.first.endpointId)); |
| 2617 | selectedConstraint.insert(std::make_pair("maxHeight", json11::Json(720))); |
| 2618 | break; |
| 2619 | } |
| 2620 | case VideoChannelDescription::Quality::Medium: { |
| 2621 | selectedConstraint.insert(std::make_pair("maxHeight", json11::Json(360))); |
| 2622 | break; |
| 2623 | } |
| 2624 | case VideoChannelDescription::Quality::Thumbnail: { |
| 2625 | selectedConstraint.insert(std::make_pair("maxHeight", json11::Json(180))); |
| 2626 | break; |
| 2627 | } |
| 2628 | default: { |
| 2629 | break; |
| 2630 | } |
| 2631 | } |
| 2632 |
| 2633 | constraints.insert(std::make_pair(incomingVideoChannel.first.endpointId, json11::Json(std::move(selectedConstraint)))); |
| 2634 | } |
| 2635 |
| 2636 | json.insert(std::make_pair("onStageEndpoints", json11::Json(std::move(onStageEndpoints)))); |
| 2637 | json.insert(std::make_pair("constraints", json11::Json(std::move(constraints)))); |
| 2638 |
| 2639 | std::string result = json11::Json(std::move(json)).dump(); |
| 2640 | _networkManager->perform([result = std::move(result)](GroupNetworkManager *networkManager) { |
| 2641 | networkManager->sendDataChannelMessage(result); |
| 2642 | }); |
| 2643 | } |
| 2644 |
| 2645 | void setConnectionMode(GroupConnectionMode connectionMode, bool keepBroadcastIfWasEnabled, bool isUnifiedBroadcast) { |
| 2646 | if (_connectionMode != connectionMode || connectionMode == GroupConnectionMode::GroupConnectionModeNone) { |
| 2647 | GroupConnectionMode previousMode = _connectionMode; |
| 2648 | _connectionMode = connectionMode; |
| 2649 | _isUnifiedBroadcast = isUnifiedBroadcast; |
| 2650 | onConnectionModeUpdated(previousMode, keepBroadcastIfWasEnabled); |
| 2651 | } |
| 2652 | } |
| 2653 |
| 2654 | void onConnectionModeUpdated(GroupConnectionMode previousMode, bool keepBroadcastIfWasEnabled) { |
| 2655 | RTC_CHECK(_connectionMode != previousMode || _connectionMode == GroupConnectionMode::GroupConnectionModeNone); |
| 2656 |
| 2657 | if (previousMode == GroupConnectionMode::GroupConnectionModeRtc) { |
| 2658 | _networkManager->perform([](GroupNetworkManager *networkManager) { |
| 2659 | networkManager->stop(); |
| 2660 | }); |
| 2661 | } else if (previousMode == GroupConnectionMode::GroupConnectionModeBroadcast) { |
| 2662 | if (keepBroadcastIfWasEnabled) { |
| 2663 | _broadcastEnabledUntilRtcIsConnectedAtTimestamp = rtc::TimeMillis(); |
| 2664 | } else { |
| 2665 | if (_streamingContext) { |
| 2666 | _streamingContext.reset(); |
| 2667 | _audioDeviceDataObserverShared->setStreamingContext(nullptr); |
| 2668 | } |
| 2669 | } |
| 2670 | } |
| 2671 |
| 2672 | if (_connectionMode == GroupConnectionMode::GroupConnectionModeNone) { |
| 2673 | destroyOutgoingAudioChannel(); |
| 2674 | destroyOutgoingVideoChannel(); |
| 2675 |
| 2676 | // Regenerate and reconfigure. |
| 2677 | generateSsrcs(); |
| 2678 |
| 2679 | if (!_isMuted) { |
| 2680 | createOutgoingAudioChannel(); |
| 2681 | } |
| 2682 | createOutgoingVideoChannel(); |
| 2683 | } |
| 2684 |
| 2685 | switch (_connectionMode) { |
| 2686 | case GroupConnectionMode::GroupConnectionModeNone: { |
| 2687 | break; |
| 2688 | } |
| 2689 | case GroupConnectionMode::GroupConnectionModeRtc: { |
| 2690 | _networkManager->perform([](GroupNetworkManager *networkManager) { |
| 2691 | networkManager->start(); |
| 2692 | }); |
| 2693 | break; |
| 2694 | } |
| 2695 | case GroupConnectionMode::GroupConnectionModeBroadcast: { |
| 2696 | _isBroadcastConnected = false; |
| 2697 |
| 2698 | if (!_streamingContext) { |
| 2699 | StreamingMediaContext::StreamingMediaContextArguments arguments; |
| 2700 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 2701 | arguments.threads = _threads; |
| 2702 | arguments.platformContext = _platformContext; |
| 2703 | arguments.isUnifiedBroadcast = _isUnifiedBroadcast; |
| 2704 | arguments.requestCurrentTime = _requestCurrentTime; |
| 2705 | arguments.requestAudioBroadcastPart = _requestAudioBroadcastPart; |
| 2706 | arguments.requestVideoBroadcastPart = _requestVideoBroadcastPart; |
| 2707 | arguments.updateAudioLevel = [weak, threads = _threads](uint32_t ssrc, float level, bool isSpeech) { |
| 2708 | assert(threads->getMediaThread()->IsCurrent()); |
| 2709 |
| 2710 | auto strong = weak.lock(); |
| 2711 | if (!strong) { |
| 2712 | return; |
| 2713 | } |
| 2714 |
| 2715 | InternalGroupLevelValue updated; |
| 2716 | updated.value.level = level; |
| 2717 | updated.value.voice = isSpeech; |
| 2718 | updated.timestamp = rtc::TimeMillis(); |
| 2719 | strong->_audioLevels.insert(std::make_pair(ChannelId(ssrc), std::move(updated))); |
| 2720 | }; |
| 2721 | _streamingContext = std::make_shared<StreamingMediaContext>(std::move(arguments)); |
| 2722 |
| 2723 | for (const auto &it : _pendingVideoSinks) { |
| 2724 | for (const auto &sink : it.second) { |
| 2725 | _streamingContext->addVideoSink(it.first.endpointId, sink); |
| 2726 | } |
| 2727 | } |
| 2728 |
| 2729 | for (const auto &it : _volumeBySsrc) { |
| 2730 | _streamingContext->setVolume(it.first, it.second); |
| 2731 | } |
| 2732 |
| 2733 | std::vector<StreamingMediaContext::VideoChannel> streamingVideoChannels; |
| 2734 | for (const auto &it : _pendingRequestedVideo) { |
| 2735 | streamingVideoChannels.emplace_back(it.maxQuality, it.endpointId); |
| 2736 | } |
| 2737 | _streamingContext->setActiveVideoChannels(streamingVideoChannels); |
| 2738 |
| 2739 | _audioDeviceDataObserverShared->setStreamingContext(_streamingContext); |
| 2740 | } |
| 2741 |
| 2742 | break; |
| 2743 | } |
| 2744 | default: { |
| 2745 | RTC_FATAL() << "Unknown connectionMode"; |
| 2746 | break; |
| 2747 | } |
| 2748 | } |
| 2749 |
| 2750 | updateIsConnected(); |
| 2751 | } |
| 2752 |
| 2753 | void generateSsrcs() { |
| 2754 | auto generator = std::mt19937(std::random_device()()); |
| 2755 | auto distribution = std::uniform_int_distribution<uint32_t>(); |
| 2756 | do { |
| 2757 | _outgoingAudioSsrc = distribution(generator) & 0x7fffffffU; |
| 2758 | } while (!_outgoingAudioSsrc); |
| 2759 |
| 2760 | uint32_t outgoingVideoSsrcBase = _outgoingAudioSsrc + 1; |
| 2761 | int numVideoSimulcastLayers = 3; |
| 2762 | if (_videoContentType == VideoContentType::Screencast) { |
| 2763 | numVideoSimulcastLayers = 2; |
| 2764 | } |
| 2765 | _outgoingVideoSsrcs.simulcastLayers.clear(); |
| 2766 | for (int layerIndex = 0; layerIndex < numVideoSimulcastLayers; layerIndex++) { |
| 2767 | _outgoingVideoSsrcs.simulcastLayers.push_back(VideoSsrcs::SimulcastLayer(outgoingVideoSsrcBase + layerIndex * 2 + 0, outgoingVideoSsrcBase + layerIndex * 2 + 1)); |
| 2768 | } |
| 2769 |
| 2770 | _videoSourceGroups.clear(); |
| 2771 |
| 2772 | std::vector<uint32_t> simulcastGroupSsrcs; |
| 2773 | std::vector<cricket::SsrcGroup> fidGroups; |
| 2774 | for (const auto &layer : _outgoingVideoSsrcs.simulcastLayers) { |
| 2775 | simulcastGroupSsrcs.push_back(layer.ssrc); |
| 2776 |
| 2777 | cricket::SsrcGroup fidGroup(cricket::kFidSsrcGroupSemantics, { layer.ssrc, layer.fidSsrc }); |
| 2778 | fidGroups.push_back(fidGroup); |
| 2779 | } |
| 2780 | if (simulcastGroupSsrcs.size() > 1) { |
| 2781 | cricket::SsrcGroup simulcastGroup(cricket::kSimSsrcGroupSemantics, simulcastGroupSsrcs); |
| 2782 |
| 2783 | GroupJoinPayloadVideoSourceGroup payloadSimulcastGroup; |
| 2784 | payloadSimulcastGroup.semantics = "SIM"; |
| 2785 | payloadSimulcastGroup.ssrcs = simulcastGroupSsrcs; |
| 2786 | _videoSourceGroups.push_back(payloadSimulcastGroup); |
| 2787 | } |
| 2788 |
| 2789 | for (auto fidGroup : fidGroups) { |
| 2790 | GroupJoinPayloadVideoSourceGroup payloadFidGroup; |
| 2791 | payloadFidGroup.semantics = "FID"; |
| 2792 | payloadFidGroup.ssrcs = fidGroup.ssrcs; |
| 2793 | _videoSourceGroups.push_back(payloadFidGroup); |
| 2794 | } |
| 2795 | } |
| 2796 |
| 2797 | void emitJoinPayload(std::function<void(GroupJoinPayload const &)> completion) { |
| 2798 | _networkManager->perform([outgoingAudioSsrc = _outgoingAudioSsrc, /*videoPayloadTypes = _videoPayloadTypes, videoExtensionMap = _videoExtensionMap, */videoSourceGroups = _videoSourceGroups, videoContentType = _videoContentType, completion](GroupNetworkManager *networkManager) { |
| 2799 | GroupJoinInternalPayload payload; |
| 2800 |
| 2801 | payload.audioSsrc = outgoingAudioSsrc; |
| 2802 |
| 2803 | if (videoContentType != VideoContentType::None) { |
| 2804 | GroupParticipantVideoInformation videoInformation; |
| 2805 | videoInformation.ssrcGroups = videoSourceGroups; |
| 2806 | payload.videoInformation = std::move(videoInformation); |
| 2807 | } |
| 2808 |
| 2809 | GroupJoinTransportDescription transportDescription; |
| 2810 |
| 2811 | auto localIceParameters = networkManager->getLocalIceParameters(); |
| 2812 | transportDescription.ufrag = localIceParameters.ufrag; |
| 2813 | transportDescription.pwd = localIceParameters.pwd; |
| 2814 |
| 2815 | auto localFingerprint = networkManager->getLocalFingerprint(); |
| 2816 | if (localFingerprint) { |
| 2817 | GroupJoinTransportDescription::Fingerprint serializedFingerprint; |
| 2818 | serializedFingerprint.hash = localFingerprint->algorithm; |
| 2819 | serializedFingerprint.fingerprint = localFingerprint->GetRfc4572Fingerprint(); |
| 2820 | serializedFingerprint.setup = "passive"; |
| 2821 | transportDescription.fingerprints.push_back(std::move(serializedFingerprint)); |
| 2822 | } |
| 2823 |
| 2824 | payload.transport = std::move(transportDescription); |
| 2825 |
| 2826 | GroupJoinPayload result; |
| 2827 | result.audioSsrc = payload.audioSsrc; |
| 2828 | result.json = payload.serialize(); |
| 2829 | completion(result); |
| 2830 | }); |
| 2831 | } |
| 2832 |
| 2833 | void setVideoSource(std::function<rtc::scoped_refptr<webrtc::VideoTrackSourceInterface>()> getVideoSource, bool isInitializing) { |
| 2834 | bool resetBitrate = (!_getVideoSource) != (!getVideoSource) && !isInitializing; |
| 2835 | if (!isInitializing && _getVideoSource && getVideoSource && getVideoSource() == _getVideoSource()) { |
| 2836 | return; |
| 2837 | } |
| 2838 |
| 2839 | _getVideoSource = std::move(getVideoSource); |
| 2840 | updateVideoSend(); |
| 2841 | if (resetBitrate) { |
| 2842 | adjustBitratePreferences(true); |
| 2843 | } |
| 2844 | } |
| 2845 |
| 2846 | void setVideoCapture(std::shared_ptr<VideoCaptureInterface> videoCapture, bool isInitializing) { |
| 2847 | _videoCapture = videoCapture; |
| 2848 | setVideoSource(videoCaptureToGetVideoSource(std::move(videoCapture)), isInitializing); |
| 2849 | } |
| 2850 |
| 2851 | void setAudioOutputDevice(const std::string &id) { |
| 2852 | #if not defined(WEBRTC_IOS) && not defined(WEBRTC_ANDROID) |
| 2853 | _threads->getWorkerThread()->BlockingCall([&] { |
| 2854 | SetAudioOutputDeviceById(_audioDeviceModule.get(), id); |
| 2855 | }); |
| 2856 | #endif // WEBRTC_IOS |
| 2857 | } |
| 2858 |
| 2859 | void setAudioInputDevice(const std::string &id) { |
| 2860 | #if not defined(WEBRTC_IOS) && not defined(WEBRTC_ANDROID) |
| 2861 | _threads->getWorkerThread()->BlockingCall([&] { |
| 2862 | SetAudioInputDeviceById(_audioDeviceModule.get(), id); |
| 2863 | }); |
| 2864 | #endif // WEBRTC_IOS |
| 2865 | } |
| 2866 |
| 2867 | void addExternalAudioSamples(std::vector<uint8_t> &&samples) { |
| 2868 | if (samples.size() % 2 != 0) { |
| 2869 | return; |
| 2870 | } |
| 2871 | _externalAudioSamplesMutex.Lock(); |
| 2872 |
| 2873 | size_t previousSize = _externalAudioSamples.size(); |
| 2874 | _externalAudioSamples.resize(_externalAudioSamples.size() + samples.size() / 2); |
| 2875 | webrtc::S16ToFloatS16((const int16_t *)samples.data(), samples.size() / 2, _externalAudioSamples.data() + previousSize); |
| 2876 |
| 2877 | if (_externalAudioSamples.size() > 2 * 48000) { |
| 2878 | _externalAudioSamples.erase(_externalAudioSamples.begin(), _externalAudioSamples.begin() + (_externalAudioSamples.size() - 2 * 48000)); |
| 2879 | } |
| 2880 |
| 2881 | _externalAudioSamplesMutex.Unlock(); |
| 2882 | } |
| 2883 |
| 2884 | void setJoinResponsePayload(std::string const &payload) { |
| 2885 | RTC_LOG(LS_INFO) << formatTimestampMillis(rtc::TimeMillis()) << ": " << "setJoinResponsePayload"; |
| 2886 |
| 2887 | auto parsedPayload = GroupJoinResponsePayload::parse(payload); |
| 2888 | if (!parsedPayload) { |
| 2889 | RTC_LOG(LS_ERROR) << "Could not parse json response payload"; |
| 2890 | return; |
| 2891 | } |
| 2892 |
| 2893 | _sharedVideoInformation = parsedPayload->videoInformation; |
| 2894 |
| 2895 | _serverBandwidthProbingVideoSsrc.reset(); |
| 2896 |
| 2897 | if (parsedPayload->videoInformation && parsedPayload->videoInformation->serverVideoBandwidthProbingSsrc) { |
| 2898 | setServerBandwidthProbingChannelSsrc(parsedPayload->videoInformation->serverVideoBandwidthProbingSsrc); |
| 2899 | } |
| 2900 |
| 2901 | _networkManager->perform([parsedTransport = parsedPayload->transport](GroupNetworkManager *networkManager) { |
| 2902 | PeerIceParameters remoteIceParameters; |
| 2903 | remoteIceParameters.ufrag = parsedTransport.ufrag; |
| 2904 | remoteIceParameters.pwd = parsedTransport.pwd; |
| 2905 |
| 2906 | std::vector<cricket::Candidate> iceCandidates; |
| 2907 | for (auto const &candidate : parsedTransport.candidates) { |
| 2908 | rtc::SocketAddress address(candidate.ip, stringToInt(candidate.port)); |
| 2909 |
| 2910 | cricket::Candidate parsedCandidate( |
| 2911 | /*component=*/stringToInt(candidate.component), |
| 2912 | /*protocol=*/candidate.protocol, |
| 2913 | /*address=*/address, |
| 2914 | /*priority=*/stringToUInt32(candidate.priority), |
| 2915 | /*username=*/parsedTransport.ufrag, |
| 2916 | /*password=*/parsedTransport.pwd, |
| 2917 | /*type=*/candidate.type, |
| 2918 | /*generation=*/stringToUInt32(candidate.generation), |
| 2919 | /*foundation=*/candidate.foundation, |
| 2920 | /*network_id=*/stringToUInt16(candidate.network), |
| 2921 | /*network_cost=*/0 |
| 2922 | ); |
| 2923 | iceCandidates.push_back(parsedCandidate); |
| 2924 | } |
| 2925 |
| 2926 | std::unique_ptr<rtc::SSLFingerprint> fingerprint; |
| 2927 | if (parsedTransport.fingerprints.size() != 0) { |
| 2928 | fingerprint = rtc::SSLFingerprint::CreateUniqueFromRfc4572(parsedTransport.fingerprints[0].hash, parsedTransport.fingerprints[0].fingerprint); |
| 2929 | } |
| 2930 |
| 2931 | networkManager->setRemoteParams(remoteIceParameters, iceCandidates, fingerprint.get()); |
| 2932 | }); |
| 2933 |
| 2934 | configureVideoParams(); |
| 2935 | createOutgoingVideoChannel(); |
| 2936 |
| 2937 | adjustBitratePreferences(true); |
| 2938 |
| 2939 | if (!_pendingRequestedVideo.empty()) { |
| 2940 | setRequestedVideoChannels(std::move(_pendingRequestedVideo)); |
| 2941 | _pendingRequestedVideo.clear(); |
| 2942 | } |
| 2943 | } |
| 2944 |
| 2945 | void setServerBandwidthProbingChannelSsrc(uint32_t probingSsrc) { |
| 2946 | RTC_CHECK(probingSsrc); |
| 2947 |
| 2948 | if (!_sharedVideoInformation || _availablePayloadTypes.empty()) { |
| 2949 | return; |
| 2950 | } |
| 2951 |
| 2952 | GroupParticipantVideoInformation videoInformation; |
| 2953 |
| 2954 | GroupJoinPayloadVideoSourceGroup sourceGroup; |
| 2955 | sourceGroup.ssrcs.push_back(probingSsrc); |
| 2956 | sourceGroup.semantics = "SIM"; |
| 2957 |
| 2958 | videoInformation.ssrcGroups.push_back(std::move(sourceGroup)); |
| 2959 |
| 2960 | _serverBandwidthProbingVideoSsrc.reset(new IncomingVideoChannel( |
| 2961 | _channelManager.get(), |
| 2962 | _call.get(), |
| 2963 | _rtpTransport, |
| 2964 | _uniqueRandomIdGenerator.get(), |
| 2965 | _availableVideoFormats, |
| 2966 | _sharedVideoInformation.value(), |
| 2967 | 123456, |
| 2968 | VideoChannelDescription::Quality::Thumbnail, |
| 2969 | VideoChannelDescription::Quality::Thumbnail, |
| 2970 | videoInformation, |
| 2971 | _threads |
| 2972 | )); |
| 2973 |
| 2974 | ChannelSsrcInfo mapping; |
| 2975 | mapping.type = ChannelSsrcInfo::Type::Video; |
| 2976 | mapping.allSsrcs.push_back(probingSsrc); |
| 2977 | _channelBySsrc.insert(std::make_pair(probingSsrc, std::move(mapping))); |
| 2978 | } |
| 2979 |
| 2980 | void removeSsrcs(std::vector<uint32_t> ssrcs) { |
| 2981 | } |
| 2982 |
| 2983 | void removeIncomingVideoSource(uint32_t ssrc) { |
| 2984 | } |
| 2985 |
| 2986 | void setIsMuted(bool isMuted) { |
| 2987 | if (_isMuted == isMuted) { |
| 2988 | return; |
| 2989 | } |
| 2990 | _isMuted = isMuted; |
| 2991 |
| 2992 | if (!_isMuted && !_outgoingAudioChannel) { |
| 2993 | createOutgoingAudioChannel(); |
| 2994 | } |
| 2995 |
| 2996 | onUpdatedIsMuted(); |
| 2997 | } |
| 2998 |
| 2999 | void onUpdatedIsMuted() { |
| 3000 | if (_outgoingAudioChannel) { |
| 3001 | _threads->getWorkerThread()->BlockingCall([this]() { |
| 3002 | _outgoingAudioChannel->media_channel()->SetAudioSend(_outgoingAudioSsrc, !_isMuted, nullptr, &_audioSource); |
| 3003 | }); |
| 3004 |
| 3005 | _outgoingAudioChannel->Enable(!_isMuted); |
| 3006 | } |
| 3007 | } |
| 3008 |
| 3009 | void setIsNoiseSuppressionEnabled(bool isNoiseSuppressionEnabled) { |
| 3010 | _noiseSuppressionConfiguration->isEnabled = isNoiseSuppressionEnabled; |
| 3011 | } |
| 3012 |
| 3013 | void addOutgoingVideoOutput(std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) { |
| 3014 | _videoCaptureSink->addSink(sink); |
| 3015 |
| 3016 | if (_videoCapture) { |
| 3017 | _videoCapture->setOutput(_videoCaptureSink); |
| 3018 | } |
| 3019 | } |
| 3020 |
| 3021 | void addIncomingVideoOutput(std::string const &endpointId, std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) { |
| 3022 | if (_sharedVideoInformation && endpointId == _sharedVideoInformation->endpointId) { |
| 3023 | if (_videoCapture) { |
| 3024 | _videoCaptureSink->addSink(sink); |
| 3025 | _videoCapture->setOutput(_videoCaptureSink); |
| 3026 | } |
| 3027 | } else { |
| 3028 | auto it = _incomingVideoChannels.find(VideoChannelId(endpointId)); |
| 3029 | if (it != _incomingVideoChannels.end()) { |
| 3030 | it->second->addSink(sink); |
| 3031 | } else { |
| 3032 | _pendingVideoSinks[VideoChannelId(endpointId)].push_back(sink); |
| 3033 | } |
| 3034 |
| 3035 | if (_streamingContext) { |
| 3036 | _streamingContext->addVideoSink(endpointId, sink); |
| 3037 | } |
| 3038 | } |
| 3039 | } |
| 3040 |
| 3041 | void addIncomingAudioChannel(ChannelId ssrc, bool isRawPcm = false) { |
| 3042 | if (_incomingAudioChannels.find(ssrc) != _incomingAudioChannels.end()) { |
| 3043 | return; |
| 3044 | } |
| 3045 |
| 3046 | if (_incomingAudioChannels.size() > 10) { |
| 3047 | auto timestamp = rtc::TimeMillis(); |
| 3048 |
| 3049 | int64_t minActivity = INT64_MAX; |
| 3050 | ChannelId minActivityChannelId(0, 0); |
| 3051 |
| 3052 | for (const auto &it : _incomingAudioChannels) { |
| 3053 | if (it.first.networkSsrc == 1) { |
| 3054 | continue; |
| 3055 | } |
| 3056 | auto activity = it.second->getActivity(); |
| 3057 | if (activity < minActivity && activity < timestamp - 1000) { |
| 3058 | minActivity = activity; |
| 3059 | minActivityChannelId = it.first; |
| 3060 | } |
| 3061 | } |
| 3062 |
| 3063 | if (minActivityChannelId.networkSsrc != 0) { |
| 3064 | removeIncomingAudioChannel(minActivityChannelId); |
| 3065 | } |
| 3066 |
| 3067 | if (_incomingAudioChannels.size() > 10) { |
| 3068 | // Wait until there is a channel that hasn't been active in 1 second |
| 3069 | return; |
| 3070 | } |
| 3071 | } |
| 3072 |
| 3073 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 3074 |
| 3075 | std::function<void(AudioSinkImpl::Update)> onAudioSinkUpdate; |
| 3076 | if (ssrc.actualSsrc != ssrc.networkSsrc) { |
| 3077 | if (_audioLevelsUpdated) { |
| 3078 | onAudioSinkUpdate = [weak, ssrc = ssrc, threads = _threads](AudioSinkImpl::Update update) { |
| 3079 | threads->getMediaThread()->PostTask([weak, ssrc, update]() { |
| 3080 | auto strong = weak.lock(); |
| 3081 | if (!strong) { |
| 3082 | return; |
| 3083 | } |
| 3084 |
| 3085 | auto it = strong->_audioLevels.find(ChannelId(ssrc)); |
| 3086 | if (it != strong->_audioLevels.end()) { |
| 3087 | it->second.value.level = fmax(it->second.value.level, update.level); |
| 3088 | if (update.hasSpeech) { |
| 3089 | it->second.value.voice = true; |
| 3090 | } |
| 3091 | it->second.timestamp = rtc::TimeMillis(); |
| 3092 | } else { |
| 3093 | InternalGroupLevelValue updated; |
| 3094 | updated.value.level = update.level; |
| 3095 | updated.value.voice = update.hasSpeech; |
| 3096 | updated.timestamp = rtc::TimeMillis(); |
| 3097 | strong->_audioLevels.insert(std::make_pair(ChannelId(ssrc), std::move(updated))); |
| 3098 | } |
| 3099 | }); |
| 3100 | }; |
| 3101 | } |
| 3102 | } |
| 3103 |
| 3104 | std::unique_ptr<IncomingAudioChannel> channel(new IncomingAudioChannel( |
| 3105 | _channelManager.get(), |
| 3106 | _call.get(), |
| 3107 | _rtpTransport, |
| 3108 | _uniqueRandomIdGenerator.get(), |
| 3109 | isRawPcm, |
| 3110 | ssrc, |
| 3111 | std::move(onAudioSinkUpdate), |
| 3112 | _onAudioFrame, |
| 3113 | _threads |
| 3114 | )); |
| 3115 |
| 3116 | auto volume = _volumeBySsrc.find(ssrc.actualSsrc); |
| 3117 | if (volume != _volumeBySsrc.end()) { |
| 3118 | channel->setVolume(volume->second); |
| 3119 | } |
| 3120 |
| 3121 | _incomingAudioChannels.insert(std::make_pair(ssrc, std::move(channel))); |
| 3122 |
| 3123 | auto currentMapping = _channelBySsrc.find(ssrc.networkSsrc); |
| 3124 | if (currentMapping != _channelBySsrc.end()) { |
| 3125 | if (currentMapping->second.type == ChannelSsrcInfo::Type::Audio) { |
| 3126 | if (std::find(currentMapping->second.allSsrcs.begin(), currentMapping->second.allSsrcs.end(), ssrc.networkSsrc) == currentMapping->second.allSsrcs.end()) { |
| 3127 | currentMapping->second.allSsrcs.push_back(ssrc.networkSsrc); |
| 3128 | } |
| 3129 | } |
| 3130 | } else { |
| 3131 | ChannelSsrcInfo mapping; |
| 3132 | mapping.type = ChannelSsrcInfo::Type::Audio; |
| 3133 | mapping.allSsrcs.push_back(ssrc.networkSsrc); |
| 3134 | _channelBySsrc.insert(std::make_pair(ssrc.networkSsrc, std::move(mapping))); |
| 3135 | } |
| 3136 |
| 3137 | maybeDeliverBufferedPackets(ssrc.networkSsrc); |
| 3138 |
| 3139 | adjustBitratePreferences(false); |
| 3140 | } |
| 3141 |
| 3142 | void removeIncomingAudioChannel(ChannelId const &channelId) { |
| 3143 | const auto it = _incomingAudioChannels.find(channelId); |
| 3144 | if (it != _incomingAudioChannels.end()) { |
| 3145 | _incomingAudioChannels.erase(it); |
| 3146 | } |
| 3147 |
| 3148 | auto currentMapping = _channelBySsrc.find(channelId.networkSsrc); |
| 3149 | if (currentMapping != _channelBySsrc.end()) { |
| 3150 | if (currentMapping->second.type == ChannelSsrcInfo::Type::Audio) { |
| 3151 | auto ssrcs = currentMapping->second.allSsrcs; |
| 3152 | for (auto ssrc : ssrcs) { |
| 3153 | auto it = _channelBySsrc.find(ssrc); |
| 3154 | if (it != _channelBySsrc.end()) { |
| 3155 | _channelBySsrc.erase(it); |
| 3156 | } |
| 3157 | } |
| 3158 | } |
| 3159 | } |
| 3160 | } |
| 3161 |
| 3162 | void addIncomingVideoChannel(uint32_t audioSsrc, GroupParticipantVideoInformation const &videoInformation, VideoChannelDescription::Quality minQuality, VideoChannelDescription::Quality maxQuality) { |
| 3163 | if (!_sharedVideoInformation) { |
| 3164 | return; |
| 3165 | } |
| 3166 | if (_incomingVideoChannels.find(VideoChannelId(videoInformation.endpointId)) != _incomingVideoChannels.end()) { |
| 3167 | return; |
| 3168 | } |
| 3169 |
| 3170 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 3171 |
| 3172 | std::unique_ptr<IncomingVideoChannel> channel(new IncomingVideoChannel( |
| 3173 | _channelManager.get(), |
| 3174 | _call.get(), |
| 3175 | _rtpTransport, |
| 3176 | _uniqueRandomIdGenerator.get(), |
| 3177 | _availableVideoFormats, |
| 3178 | _sharedVideoInformation.value(), |
| 3179 | audioSsrc, |
| 3180 | minQuality, |
| 3181 | maxQuality, |
| 3182 | videoInformation, |
| 3183 | _threads |
| 3184 | )); |
| 3185 |
| 3186 | const auto pendingSinks = _pendingVideoSinks.find(VideoChannelId(videoInformation.endpointId)); |
| 3187 | if (pendingSinks != _pendingVideoSinks.end()) { |
| 3188 | for (const auto &sink : pendingSinks->second) { |
| 3189 | channel->addSink(sink); |
| 3190 | } |
| 3191 |
| 3192 | _pendingVideoSinks.erase(pendingSinks); |
| 3193 | } |
| 3194 |
| 3195 | _incomingVideoChannels.insert(std::make_pair(VideoChannelId(videoInformation.endpointId), std::move(channel))); |
| 3196 |
| 3197 | std::vector<uint32_t> allSsrcs; |
| 3198 | for (const auto &group : videoInformation.ssrcGroups) { |
| 3199 | for (auto ssrc : group.ssrcs) { |
| 3200 | if (std::find(allSsrcs.begin(), allSsrcs.end(), ssrc) == allSsrcs.end()) { |
| 3201 | allSsrcs.push_back(ssrc); |
| 3202 | } |
| 3203 | } |
| 3204 | } |
| 3205 |
| 3206 | for (auto ssrc : allSsrcs) { |
| 3207 | ChannelSsrcInfo mapping; |
| 3208 | mapping.type = ChannelSsrcInfo::Type::Video; |
| 3209 | mapping.allSsrcs = allSsrcs; |
| 3210 | mapping.videoEndpointId = videoInformation.endpointId; |
| 3211 | _channelBySsrc.insert(std::make_pair(ssrc, std::move(mapping))); |
| 3212 | } |
| 3213 |
| 3214 | for (auto ssrc : allSsrcs) { |
| 3215 | maybeDeliverBufferedPackets(ssrc); |
| 3216 | } |
| 3217 |
| 3218 | adjustBitratePreferences(false); |
| 3219 | } |
| 3220 |
| 3221 | void setVolume(uint32_t ssrc, double volume) { |
| 3222 | auto current = _volumeBySsrc.find(ssrc); |
| 3223 | if (current != _volumeBySsrc.end() && std::abs(current->second - volume) < 0.0001) { |
| 3224 | return; |
| 3225 | } |
| 3226 |
| 3227 | _volumeBySsrc[ssrc] = volume; |
| 3228 |
| 3229 | auto it = _incomingAudioChannels.find(ChannelId(ssrc)); |
| 3230 | if (it != _incomingAudioChannels.end()) { |
| 3231 | it->second->setVolume(volume); |
| 3232 | } |
| 3233 |
| 3234 | it = _incomingAudioChannels.find(ChannelId(ssrc + 1000, ssrc)); |
| 3235 | if (it != _incomingAudioChannels.end()) { |
| 3236 | it->second->setVolume(volume); |
| 3237 | } |
| 3238 |
| 3239 | if (_streamingContext) { |
| 3240 | _streamingContext->setVolume(ssrc, volume); |
| 3241 | } |
| 3242 | } |
| 3243 |
| 3244 | void setRequestedVideoChannels(std::vector<VideoChannelDescription> &&requestedVideoChannels) { |
| 3245 | if (_streamingContext) { |
| 3246 | std::vector<StreamingMediaContext::VideoChannel> streamingVideoChannels; |
| 3247 | for (const auto &it : requestedVideoChannels) { |
| 3248 | streamingVideoChannels.emplace_back(it.maxQuality, it.endpointId); |
| 3249 | } |
| 3250 | _streamingContext->setActiveVideoChannels(streamingVideoChannels); |
| 3251 | } |
| 3252 |
| 3253 | if (!_sharedVideoInformation) { |
| 3254 | _pendingRequestedVideo = std::move(requestedVideoChannels); |
| 3255 | return; |
| 3256 | } |
| 3257 | bool updated = false; |
| 3258 | std::vector<std::string> allEndpointIds; |
| 3259 |
| 3260 | for (const auto &description : requestedVideoChannels) { |
| 3261 | if (_sharedVideoInformation && _sharedVideoInformation->endpointId == description.endpointId) { |
| 3262 | continue; |
| 3263 | } |
| 3264 |
| 3265 | GroupParticipantVideoInformation videoInformation; |
| 3266 | videoInformation.endpointId = description.endpointId; |
| 3267 | for (const auto &group : description.ssrcGroups) { |
| 3268 | GroupJoinPayloadVideoSourceGroup parsedGroup; |
| 3269 | parsedGroup.semantics = group.semantics; |
| 3270 | parsedGroup.ssrcs = group.ssrcs; |
| 3271 | videoInformation.ssrcGroups.push_back(std::move(parsedGroup)); |
| 3272 | } |
| 3273 |
| 3274 | allEndpointIds.push_back(videoInformation.endpointId); |
| 3275 |
| 3276 | auto current = _incomingVideoChannels.find(VideoChannelId(videoInformation.endpointId)); |
| 3277 | if (current != _incomingVideoChannels.end()) { |
| 3278 | if (current->second->requestedMinQuality() != description.minQuality || current->second->requestedMaxQuality() != description.maxQuality) { |
| 3279 | current->second->setRequstedMinQuality(description.minQuality); |
| 3280 | current->second->setRequstedMaxQuality(description.maxQuality); |
| 3281 | updated = true; |
| 3282 | } |
| 3283 | continue; |
| 3284 | } |
| 3285 |
| 3286 | addIncomingVideoChannel(description.audioSsrc, videoInformation, description.minQuality, description.maxQuality); |
| 3287 | updated = true; |
| 3288 | } |
| 3289 |
| 3290 | std::vector<std::string> removeEndpointIds; |
| 3291 | for (const auto &it : _incomingVideoChannels) { |
| 3292 | if (std::find(allEndpointIds.begin(), allEndpointIds.end(), it.first.endpointId) == allEndpointIds.end()) { |
| 3293 | removeEndpointIds.push_back(it.first.endpointId); |
| 3294 | updated = true; |
| 3295 | } |
| 3296 | } |
| 3297 |
| 3298 | for (const auto &endpointId : removeEndpointIds) { |
| 3299 | const auto it = _incomingVideoChannels.find(VideoChannelId(endpointId)); |
| 3300 | if (it != _incomingVideoChannels.end()) { |
| 3301 | auto sinks = it->second->getSinks(); |
| 3302 | for (const auto &sink : sinks) { |
| 3303 | _pendingVideoSinks[VideoChannelId(endpointId)].push_back(sink); |
| 3304 | } |
| 3305 | _incomingVideoChannels.erase(it); |
| 3306 | } |
| 3307 | } |
| 3308 |
| 3309 | if (updated) { |
| 3310 | maybeUpdateRemoteVideoConstraints(); |
| 3311 | } |
| 3312 | } |
| 3313 |
| 3314 | void getStats(std::function<void(GroupInstanceStats)> completion) { |
| 3315 | GroupInstanceStats result; |
| 3316 |
| 3317 | for (const auto &it : _incomingVideoChannels) { |
| 3318 | const auto videoStats = it.second->getStats(); |
| 3319 | if (videoStats) { |
| 3320 | result.incomingVideoStats.push_back(std::make_pair(it.second->endpointId(), videoStats.value())); |
| 3321 | } |
| 3322 | } |
| 3323 |
| 3324 | completion(result); |
| 3325 | } |
| 3326 |
| 3327 | private: |
| 3328 | rtc::scoped_refptr<WrappedAudioDeviceModule> createAudioDeviceModule() { |
| 3329 | auto audioDeviceDataObserverShared = _audioDeviceDataObserverShared; |
| 3330 | #ifdef WEBRTC_IOS |
| 3331 | bool disableRecording = _disableAudioInput; |
| 3332 | #endif |
| 3333 | const auto create = [&](webrtc::AudioDeviceModule::AudioLayer layer) { |
| 3334 | #ifdef WEBRTC_IOS |
| 3335 | return rtc::make_ref_counted<webrtc::tgcalls_ios_adm::AudioDeviceModuleIOS>(false, disableRecording, disableRecording ? 2 : 1); |
| 3336 | #else |
| 3337 | return webrtc::AudioDeviceModule::Create( |
| 3338 | layer, |
| 3339 | _taskQueueFactory.get()); |
| 3340 | #endif |
| 3341 | }; |
| 3342 | const auto check = [&](const rtc::scoped_refptr<webrtc::AudioDeviceModule> &result) -> rtc::scoped_refptr<WrappedAudioDeviceModule> { |
| 3343 | if (!result) { |
| 3344 | return nullptr; |
| 3345 | } |
| 3346 |
| 3347 | auto audioDeviceObserver = std::make_unique<AudioDeviceDataObserverImpl>(audioDeviceDataObserverShared); |
| 3348 | auto module = webrtc::CreateAudioDeviceWithDataObserver(result, std::move(audioDeviceObserver)); |
| 3349 |
| 3350 | if (module->Init() == 0) { |
| 3351 | return PlatformInterface::SharedInstance()->wrapAudioDeviceModule(module); |
| 3352 | } else { |
| 3353 | return nullptr; |
| 3354 | } |
| 3355 | }; |
| 3356 | if (_createAudioDeviceModule) { |
| 3357 | if (const auto result = check(_createAudioDeviceModule(_taskQueueFactory.get()))) { |
| 3358 | return result; |
| 3359 | } |
| 3360 | } else if (_videoContentType == VideoContentType::Screencast) { |
| 3361 | #ifdef WEBRTC_ANDROID |
| 3362 | return check(create(webrtc::AudioDeviceModule::kAndroidScreenAudio)); |
| 3363 | #else |
| 3364 | FakeAudioDeviceModule::Options options; |
| 3365 | options.num_channels = 1; |
| 3366 | return check(FakeAudioDeviceModule::Creator(nullptr, _externalAudioRecorder, options)(_taskQueueFactory.get())); |
| 3367 | #endif |
| 3368 | } |
| 3369 | return check(create(webrtc::AudioDeviceModule::kPlatformDefaultAudio)); |
| 3370 | } |
| 3371 |
| 3372 | private: |
| 3373 | std::shared_ptr<Threads> _threads; |
| 3374 | GroupConnectionMode _connectionMode = GroupConnectionMode::GroupConnectionModeNone; |
| 3375 | bool _isUnifiedBroadcast = false; |
| 3376 |
| 3377 | std::function<void(GroupNetworkState)> _networkStateUpdated; |
| 3378 | std::function<void(GroupLevelsUpdate const &)> _audioLevelsUpdated; |
| 3379 | std::function<void(uint32_t, const AudioFrame &)> _onAudioFrame; |
| 3380 | std::function<std::shared_ptr<RequestMediaChannelDescriptionTask>(std::vector<uint32_t> const &, std::function<void(std::vector<MediaChannelDescription> &&)>)> _requestMediaChannelDescriptions; |
| 3381 | std::function<std::shared_ptr<BroadcastPartTask>(std::function<void(int64_t)>)> _requestCurrentTime; |
| 3382 | std::function<std::shared_ptr<BroadcastPartTask>(std::shared_ptr<PlatformContext>, int64_t, int64_t, std::function<void(BroadcastPart &&)>)> _requestAudioBroadcastPart; |
| 3383 | std::function<std::shared_ptr<BroadcastPartTask>(std::shared_ptr<PlatformContext>, int64_t, int64_t, int32_t, VideoChannelDescription::Quality, std::function<void(BroadcastPart &&)>)> _requestVideoBroadcastPart; |
| 3384 | std::shared_ptr<VideoCaptureInterface> _videoCapture; |
| 3385 | std::shared_ptr<VideoSinkImpl> _videoCaptureSink; |
| 3386 | std::function<rtc::scoped_refptr<webrtc::VideoTrackSourceInterface>()> _getVideoSource; |
| 3387 | bool _disableIncomingChannels = false; |
| 3388 | bool _useDummyChannel{true}; |
| 3389 | int _outgoingAudioBitrateKbit{32}; |
| 3390 | bool _disableOutgoingAudioProcessing{false}; |
| 3391 | #ifdef WEBRTC_IOS |
| 3392 | bool _disableAudioInput{false}; |
| 3393 | #endif |
| 3394 | int _minOutgoingVideoBitrateKbit{100}; |
| 3395 | VideoContentType _videoContentType{VideoContentType::None}; |
| 3396 | std::vector<VideoCodecName> _videoCodecPreferences; |
| 3397 |
| 3398 | int _nextMediaChannelDescriptionsRequestId = 0; |
| 3399 | std::map<int, RequestedMediaChannelDescriptions> _requestedMediaChannelDescriptions; |
| 3400 |
| 3401 | std::unique_ptr<ThreadLocalObject<GroupNetworkManager>> _networkManager; |
| 3402 |
| 3403 | std::unique_ptr<webrtc::RtcEventLogNull> _eventLog; |
| 3404 | std::unique_ptr<webrtc::TaskQueueFactory> _taskQueueFactory; |
| 3405 | std::unique_ptr<webrtc::NetEqFactory> _netEqFactory; |
| 3406 | std::unique_ptr<webrtc::Call> _call; |
| 3407 | webrtc::LocalAudioSinkAdapter _audioSource; |
| 3408 | std::shared_ptr<AudioDeviceDataObserverShared> _audioDeviceDataObserverShared; |
| 3409 | rtc::scoped_refptr<WrappedAudioDeviceModule> _audioDeviceModule; |
| 3410 | std::function<rtc::scoped_refptr<webrtc::AudioDeviceModule>(webrtc::TaskQueueFactory*)> _createAudioDeviceModule; |
| 3411 | std::string _initialInputDeviceId; |
| 3412 | std::string _initialOutputDeviceId; |
| 3413 |
| 3414 | // _outgoingAudioChannel memory is managed by _channelManager |
| 3415 | cricket::VoiceChannel *_outgoingAudioChannel = nullptr; |
| 3416 | uint32_t _outgoingAudioSsrc = 0; |
| 3417 |
| 3418 | std::vector<webrtc::SdpVideoFormat> _availableVideoFormats; |
| 3419 | std::vector<OutgoingVideoFormat> _availablePayloadTypes; |
| 3420 | absl::optional<OutgoingVideoFormat> _selectedPayloadType; |
| 3421 |
| 3422 | std::vector<GroupJoinPayloadVideoPayloadType> _videoPayloadTypes; |
| 3423 | std::vector<std::pair<uint32_t, std::string>> _videoExtensionMap; |
| 3424 | std::vector<GroupJoinPayloadVideoSourceGroup> _videoSourceGroups; |
| 3425 |
| 3426 | std::unique_ptr<rtc::UniqueRandomIdGenerator> _uniqueRandomIdGenerator; |
| 3427 | webrtc::RtpTransport *_rtpTransport = nullptr; |
| 3428 | std::unique_ptr<ChannelManager> _channelManager; |
| 3429 |
| 3430 | std::unique_ptr<webrtc::VideoBitrateAllocatorFactory> _videoBitrateAllocatorFactory; |
| 3431 | // _outgoingVideoChannel memory is managed by _channelManager |
| 3432 | cricket::VideoChannel *_outgoingVideoChannel = nullptr; |
| 3433 | VideoSsrcs _outgoingVideoSsrcs; |
| 3434 | int _outgoingVideoConstraint = 720; |
| 3435 | int _pendingOutgoingVideoConstraint = -1; |
| 3436 | int _pendingOutgoingVideoConstraintRequestId = 0; |
| 3437 |
| 3438 | std::map<ChannelId, InternalGroupLevelValue> _audioLevels; |
| 3439 | GroupLevelValue _myAudioLevel; |
| 3440 |
| 3441 | bool _isMuted = true; |
| 3442 | std::shared_ptr<NoiseSuppressionConfiguration> _noiseSuppressionConfiguration; |
| 3443 |
| 3444 | MissingSsrcPacketBuffer _missingPacketBuffer; |
| 3445 | std::map<uint32_t, ChannelSsrcInfo> _channelBySsrc; |
| 3446 | std::map<uint32_t, double> _volumeBySsrc; |
| 3447 | std::map<ChannelId, std::unique_ptr<IncomingAudioChannel>> _incomingAudioChannels; |
| 3448 | std::map<VideoChannelId, std::unique_ptr<IncomingVideoChannel>> _incomingVideoChannels; |
| 3449 |
| 3450 | std::map<VideoChannelId, std::vector<std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>>>> _pendingVideoSinks; |
| 3451 | std::vector<VideoChannelDescription> _pendingRequestedVideo; |
| 3452 |
| 3453 | std::unique_ptr<IncomingVideoChannel> _serverBandwidthProbingVideoSsrc; |
| 3454 |
| 3455 | absl::optional<GroupJoinVideoInformation> _sharedVideoInformation; |
| 3456 |
| 3457 | std::vector<float> _externalAudioSamples; |
| 3458 | webrtc::Mutex _externalAudioSamplesMutex; |
| 3459 | std::shared_ptr<ExternalAudioRecorder> _externalAudioRecorder; |
| 3460 |
| 3461 | bool _isRtcConnected = false; |
| 3462 | bool _isBroadcastConnected = false; |
| 3463 | absl::optional<int64_t> _broadcastEnabledUntilRtcIsConnectedAtTimestamp; |
| 3464 | bool _isDataChannelOpen = false; |
| 3465 | GroupNetworkState _effectiveNetworkState; |
| 3466 |
| 3467 | std::shared_ptr<StreamingMediaContext> _streamingContext; |
| 3468 |
| 3469 | rtc::scoped_refptr<webrtc::PendingTaskSafetyFlag> _workerThreadSafery; |
| 3470 | rtc::scoped_refptr<webrtc::PendingTaskSafetyFlag> _networkThreadSafery; |
| 3471 |
| 3472 | std::shared_ptr<PlatformContext> _platformContext; |
| 3473 | }; |
| 3474 |
| 3475 | GroupInstanceCustomImpl::GroupInstanceCustomImpl(GroupInstanceDescriptor &&descriptor) { |
| 3476 | if (descriptor.config.need_log) { |
| 3477 | _logSink = std::make_unique<LogSinkImpl>(descriptor.config.logPath); |
| 3478 | rtc::LogMessage::SetLogToStderr(true); |
| 3479 | } else { |
| 3480 | rtc::LogMessage::SetLogToStderr(false); |
| 3481 | } |
| 3482 | rtc::LogMessage::LogToDebug(rtc::LS_INFO); |
| 3483 | if (_logSink) { |
| 3484 | rtc::LogMessage::AddLogToStream(_logSink.get(), rtc::LS_INFO); |
| 3485 | } |
| 3486 |
| 3487 | _threads = descriptor.threads; |
| 3488 | _internal.reset(new ThreadLocalObject<GroupInstanceCustomInternal>(_threads->getMediaThread(), [descriptor = std::move(descriptor), threads = _threads]() mutable { |
| 3489 | return new GroupInstanceCustomInternal(std::move(descriptor), threads); |
| 3490 | })); |
| 3491 | _internal->perform([](GroupInstanceCustomInternal *internal) { |
| 3492 | internal->start(); |
| 3493 | }); |
| 3494 | } |
| 3495 |
| 3496 | GroupInstanceCustomImpl::~GroupInstanceCustomImpl() { |
| 3497 | if (_logSink) { |
| 3498 | rtc::LogMessage::RemoveLogToStream(_logSink.get()); |
| 3499 | } |
| 3500 | _internal.reset(); |
| 3501 |
| 3502 | // Wait until _internal is destroyed |
| 3503 | _threads->getMediaThread()->BlockingCall([] {}); |
| 3504 | } |
| 3505 |
| 3506 | void GroupInstanceCustomImpl::stop() { |
| 3507 | _internal->perform([](GroupInstanceCustomInternal *internal) { |
| 3508 | internal->stop(); |
| 3509 | }); |
| 3510 | } |
| 3511 |
| 3512 | void GroupInstanceCustomImpl::setConnectionMode(GroupConnectionMode connectionMode, bool keepBroadcastIfWasEnabled, bool isUnifiedBroadcast) { |
| 3513 | _internal->perform([connectionMode, keepBroadcastIfWasEnabled, isUnifiedBroadcast](GroupInstanceCustomInternal *internal) { |
| 3514 | internal->setConnectionMode(connectionMode, keepBroadcastIfWasEnabled, isUnifiedBroadcast); |
| 3515 | }); |
| 3516 | } |
| 3517 |
| 3518 | void GroupInstanceCustomImpl::emitJoinPayload(std::function<void(GroupJoinPayload const &)> completion) { |
| 3519 | _internal->perform([completion](GroupInstanceCustomInternal *internal) { |
| 3520 | internal->emitJoinPayload(completion); |
| 3521 | }); |
| 3522 | } |
| 3523 |
| 3524 | void GroupInstanceCustomImpl::setJoinResponsePayload(std::string const &payload) { |
| 3525 | _internal->perform([payload](GroupInstanceCustomInternal *internal) { |
| 3526 | internal->setJoinResponsePayload(payload); |
| 3527 | }); |
| 3528 | } |
| 3529 |
| 3530 | void GroupInstanceCustomImpl::removeSsrcs(std::vector<uint32_t> ssrcs) { |
| 3531 | _internal->perform([ssrcs = std::move(ssrcs)](GroupInstanceCustomInternal *internal) mutable { |
| 3532 | internal->removeSsrcs(ssrcs); |
| 3533 | }); |
| 3534 | } |
| 3535 |
| 3536 | void GroupInstanceCustomImpl::removeIncomingVideoSource(uint32_t ssrc) { |
| 3537 | _internal->perform([ssrc](GroupInstanceCustomInternal *internal) mutable { |
| 3538 | internal->removeIncomingVideoSource(ssrc); |
| 3539 | }); |
| 3540 | } |
| 3541 |
| 3542 | void GroupInstanceCustomImpl::setIsMuted(bool isMuted) { |
| 3543 | _internal->perform([isMuted](GroupInstanceCustomInternal *internal) { |
| 3544 | internal->setIsMuted(isMuted); |
| 3545 | }); |
| 3546 | } |
| 3547 |
| 3548 | void GroupInstanceCustomImpl::setIsNoiseSuppressionEnabled(bool isNoiseSuppressionEnabled) { |
| 3549 | _internal->perform([isNoiseSuppressionEnabled](GroupInstanceCustomInternal *internal) { |
| 3550 | internal->setIsNoiseSuppressionEnabled(isNoiseSuppressionEnabled); |
| 3551 | }); |
| 3552 | } |
| 3553 |
| 3554 | void GroupInstanceCustomImpl::setVideoCapture(std::shared_ptr<VideoCaptureInterface> videoCapture) { |
| 3555 | _internal->perform([videoCapture](GroupInstanceCustomInternal *internal) { |
| 3556 | internal->setVideoCapture(videoCapture, false); |
| 3557 | }); |
| 3558 | } |
| 3559 |
| 3560 | void GroupInstanceCustomImpl::setVideoSource(std::function<rtc::scoped_refptr<webrtc::VideoTrackSourceInterface>()> getVideoSource) { |
| 3561 | _internal->perform([getVideoSource](GroupInstanceCustomInternal *internal) { |
| 3562 | internal->setVideoSource(getVideoSource, false); |
| 3563 | }); |
| 3564 | } |
| 3565 |
| 3566 | void GroupInstanceCustomImpl::setAudioOutputDevice(std::string id) { |
| 3567 | _internal->perform([id](GroupInstanceCustomInternal *internal) { |
| 3568 | internal->setAudioOutputDevice(id); |
| 3569 | }); |
| 3570 | } |
| 3571 |
| 3572 | void GroupInstanceCustomImpl::setAudioInputDevice(std::string id) { |
| 3573 | _internal->perform([id](GroupInstanceCustomInternal *internal) { |
| 3574 | internal->setAudioInputDevice(id); |
| 3575 | }); |
| 3576 | } |
| 3577 |
| 3578 | void GroupInstanceCustomImpl::addExternalAudioSamples(std::vector<uint8_t> &&samples) { |
| 3579 | _internal->perform([samples = std::move(samples)](GroupInstanceCustomInternal *internal) mutable { |
| 3580 | internal->addExternalAudioSamples(std::move(samples)); |
| 3581 | }); |
| 3582 | } |
| 3583 |
| 3584 | void GroupInstanceCustomImpl::addOutgoingVideoOutput(std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) { |
| 3585 | _internal->perform([sink](GroupInstanceCustomInternal *internal) mutable { |
| 3586 | internal->addOutgoingVideoOutput(sink); |
| 3587 | }); |
| 3588 | } |
| 3589 |
| 3590 | void GroupInstanceCustomImpl::addIncomingVideoOutput(std::string const &endpointId, std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) { |
| 3591 | _internal->perform([endpointId, sink](GroupInstanceCustomInternal *internal) mutable { |
| 3592 | internal->addIncomingVideoOutput(endpointId, sink); |
| 3593 | }); |
| 3594 | } |
| 3595 |
| 3596 | void GroupInstanceCustomImpl::setVolume(uint32_t ssrc, double volume) { |
| 3597 | _internal->perform([ssrc, volume](GroupInstanceCustomInternal *internal) { |
| 3598 | internal->setVolume(ssrc, volume); |
| 3599 | }); |
| 3600 | } |
| 3601 |
| 3602 | void GroupInstanceCustomImpl::setRequestedVideoChannels(std::vector<VideoChannelDescription> &&requestedVideoChannels) { |
| 3603 | _internal->perform([requestedVideoChannels = std::move(requestedVideoChannels)](GroupInstanceCustomInternal *internal) mutable { |
| 3604 | internal->setRequestedVideoChannels(std::move(requestedVideoChannels)); |
| 3605 | }); |
| 3606 | } |
| 3607 |
| 3608 | void GroupInstanceCustomImpl::getStats(std::function<void(GroupInstanceStats)> completion) { |
| 3609 | _internal->perform([completion = std::move(completion)](GroupInstanceCustomInternal *internal) mutable { |
| 3610 | internal->getStats(completion); |
| 3611 | }); |
| 3612 | } |
| 3613 |
| 3614 | std::vector<GroupInstanceInterface::AudioDevice> GroupInstanceInterface::getAudioDevices(AudioDevice::Type type) { |
| 3615 | auto result = std::vector<AudioDevice>(); |
| 3616 | #ifdef WEBRTC_LINUX //Not needed for ios, and some crl::sync stuff is needed for windows |
| 3617 | const auto resolve = [&] { |
| 3618 | const auto queueFactory = webrtc::CreateDefaultTaskQueueFactory(); |
| 3619 | const auto info = webrtc::AudioDeviceModule::Create( |
| 3620 | webrtc::AudioDeviceModule::kPlatformDefaultAudio, |
| 3621 | queueFactory.get()); |
| 3622 | if (!info || info->Init() < 0) { |
| 3623 | return; |
| 3624 | } |
| 3625 | const auto count = type == AudioDevice::Type::Input ? info->RecordingDevices() : info->PlayoutDevices(); |
| 3626 | if (count <= 0) { |
| 3627 | return; |
| 3628 | } |
| 3629 | for (auto i = int16_t(); i != count; ++i) { |
| 3630 | char name[webrtc::kAdmMaxDeviceNameSize + 1] = { 0 }; |
| 3631 | char id[webrtc::kAdmMaxGuidSize + 1] = { 0 }; |
| 3632 | if (type == AudioDevice::Type::Input) { |
| 3633 | info->RecordingDeviceName(i, name, id); |
| 3634 | } else { |
| 3635 | info->PlayoutDeviceName(i, name, id); |
| 3636 | } |
| 3637 | result.push_back({ id, name }); |
| 3638 | } |
| 3639 | }; |
| 3640 | resolve(); |
| 3641 | #endif |
| 3642 | return result; |
| 3643 | } |
| 3644 |
| 3645 | } // namespace tgcalls |
| 3646 |