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