| 7 |
| #include "VideoCaptureInterfaceImpl.h" |
| 8 | #include "VideoCapturerInterface.h" |
| 9 | #include "CodecSelectHelper.h" |
| 10 | #include "Message.h" |
| 11 | #include "platform/PlatformInterface.h" |
| 12 | #include "StaticThreads.h" |
| 13 | #include "GroupNetworkManager.h" |
| 14 |
| 15 | #include "api/audio_codecs/audio_decoder_factory_template.h" |
| 16 | #include "api/audio_codecs/audio_encoder_factory_template.h" |
| 17 | #include "api/audio_codecs/opus/audio_decoder_opus.h" |
| 18 | #include "api/audio_codecs/opus/audio_decoder_multi_channel_opus.h" |
| 19 | #include "api/audio_codecs/opus/audio_encoder_opus.h" |
| 20 | #include "api/audio_codecs/L16/audio_decoder_L16.h" |
| 21 | #include "api/audio_codecs/L16/audio_encoder_L16.h" |
| 22 | #include "api/task_queue/default_task_queue_factory.h" |
| 23 | #include "media/engine/webrtc_media_engine.h" |
| 24 | #include "system_wrappers/include/field_trial.h" |
| 25 | #include "api/video/builtin_video_bitrate_allocator_factory.h" |
| 26 | #include "call/call.h" |
| 27 | #include "media/base/rtp_utils.h" |
| 28 | #include "api/call/audio_sink.h" |
| 29 | #include "modules/audio_processing/audio_buffer.h" |
| 30 | #include "absl/strings/match.h" |
| 31 | #include "modules/audio_processing/agc2/vad_wrapper.h" |
| 32 | #include "pc/channel.h" |
| 33 | #include "pc/rtp_transport.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 | #include "common_audio/resampler/include/resampler.h" |
| 40 | #include "modules/rtp_rtcp/source/rtp_util.h" |
| 41 | #include "api/environment/environment_factory.h" |
| 42 | #include "api/peer_connection_interface.h" |
| 43 | #include "api/enable_media.h" |
| 44 |
| 45 | #include "ChannelManager.h" |
| 46 | #include "AudioFrame.h" |
| 47 | #include "ThreadLocalObject.h" |
| 48 | #include "Manager.h" |
| 49 | #include "NetworkManager.h" |
| 50 | #include "VideoCaptureInterfaceImpl.h" |
| 51 | #include "platform/PlatformInterface.h" |
| 52 | #include "LogSinkImpl.h" |
| 53 | #include "CodecSelectHelper.h" |
| 54 | #include "AudioStreamingPart.h" |
| 55 | #include "VideoStreamingPart.h" |
| 56 | #include "AudioDeviceHelper.h" |
| 57 | #include "FakeAudioDeviceModule.h" |
| 58 | #include "StreamingMediaContext.h" |
| 59 | #ifdef WEBRTC_IOS |
| 60 | #include "platform/darwin/iOS/tgcalls_audio_device_module_ios.h" |
| 61 | #endif |
| 62 | #include <mutex> |
| 63 | #include <random> |
| 64 | #include <sstream> |
| 65 | #include <iostream> |
| 66 |
| 67 |
| 68 | #ifndef USE_RNNOISE |
| 69 | #define USE_RNNOISE 1 |
| 70 | #endif |
| 71 |
| 72 | #if USE_RNNOISE |
| 73 | #include "rnnoise.h" |
| 74 | #endif |
| 75 |
| 76 | #include "GroupJoinPayloadInternal.h" |
| 77 | #include "FieldTrialsConfig.h" |
| 78 |
| 79 | #include "third-party/json11.hpp" |
| 80 |
| 81 | #include "common_video/h264/h264_common.h" |
| 82 | #include "common_video/h264/h264_bitstream_parser.h" |
| 83 |
| 84 | namespace tgcalls { |
| 85 |
| 86 | namespace { |
| 87 |
| 88 | template <typename Out> |
| 89 | void splitString(const std::string &s, char delim, Out result) { |
| 90 | std::istringstream iss(s); |
| 91 | std::string item; |
| 92 | while (std::getline(iss, item, delim)) { |
| 93 | *result++ = item; |
| 94 | } |
| 95 | } |
| 96 |
| 97 | std::vector<std::string> splitString(const std::string &s, char delim) { |
| 98 | std::vector<std::string> elems; |
| 99 | splitString(s, delim, std::back_inserter(elems)); |
| 100 | return elems; |
| 101 | } |
| 102 |
| 103 | static int stringToInt(std::string const &string) { |
| 104 | std::stringstream stringStream(string); |
| 105 | int value = 0; |
| 106 | stringStream >> value; |
| 107 | return value; |
| 108 | } |
| 109 |
| 110 | static std::string intToString(int value) { |
| 111 | return std::to_string(value); |
| 112 | } |
| 113 |
| 114 | static std::string uint32ToString(uint32_t value) { |
| 115 | return std::to_string(value); |
| 116 | } |
| 117 |
| 118 | static uint32_t stringToUInt32(std::string const &string) { |
| 119 | std::stringstream stringStream(string); |
| 120 | uint32_t value = 0; |
| 121 | stringStream >> value; |
| 122 | return value; |
| 123 | } |
| 124 |
| 125 | static uint16_t stringToUInt16(std::string const &string) { |
| 126 | std::stringstream stringStream(string); |
| 127 | uint16_t value = 0; |
| 128 | stringStream >> value; |
| 129 | return value; |
| 130 | } |
| 131 |
| 132 | static std::string formatTimestampMillis(int64_t timestamp) { |
| 133 | std::ostringstream stringStream; |
| 134 | stringStream.imbue(std::locale::classic()); |
| 135 | stringStream << std::fixed << std::setprecision(3) << (double)timestamp / 1000.0; |
| 136 | return stringStream.str(); |
| 137 | } |
| 138 |
| 139 | static VideoCaptureInterfaceObject *GetVideoCaptureAssumingSameThread(VideoCaptureInterface *videoCapture) { |
| 140 | return videoCapture |
| 141 | ? static_cast<VideoCaptureInterfaceImpl*>(videoCapture)->object()->getSyncAssumingSameThread() |
| 142 | : nullptr; |
| 143 | } |
| 144 |
| 145 | struct OutgoingVideoFormat { |
| 146 | cricket::VideoCodec videoCodec; |
| 147 | absl::optional<cricket::VideoCodec> rtxCodec; |
| 148 |
| 149 | OutgoingVideoFormat(cricket::VideoCodec const &videoCodec_, absl::optional<cricket::VideoCodec> rtxCodec_) : |
| 150 | videoCodec(videoCodec_), |
| 151 | rtxCodec(rtxCodec_) { |
| 152 | } |
| 153 | }; |
| 154 |
| 155 | static void addDefaultFeedbackParams(cricket::VideoCodec *codec) { |
| 156 | // Don't add any feedback params for RED and ULPFEC. |
| 157 | if (codec->name == cricket::kRedCodecName || codec->name == cricket::kUlpfecCodecName) { |
| 158 | return; |
| 159 | } |
| 160 | codec->AddFeedbackParam(cricket::FeedbackParam(cricket::kRtcpFbParamRemb, cricket::kParamValueEmpty)); |
| 161 | codec->AddFeedbackParam(cricket::FeedbackParam(cricket::kRtcpFbParamTransportCc, cricket::kParamValueEmpty)); |
| 162 | // Don't add any more feedback params for FLEXFEC. |
| 163 | if (codec->name == cricket::kFlexfecCodecName) { |
| 164 | return; |
| 165 | } |
| 166 | codec->AddFeedbackParam(cricket::FeedbackParam(cricket::kRtcpFbParamCcm, cricket::kRtcpFbCcmParamFir)); |
| 167 | codec->AddFeedbackParam(cricket::FeedbackParam(cricket::kRtcpFbParamNack, cricket::kParamValueEmpty)); |
| 168 | codec->AddFeedbackParam(cricket::FeedbackParam(cricket::kRtcpFbParamNack, cricket::kRtcpFbNackParamPli)); |
| 169 | } |
| 170 |
| 171 | struct H264FormatParameters { |
| 172 | std::string profileLevelId; |
| 173 | std::string packetizationMode; |
| 174 | std::string levelAssymetryAllowed; |
| 175 | }; |
| 176 |
| 177 | H264FormatParameters parseH264FormatParameters(webrtc::SdpVideoFormat const &format) { |
| 178 | H264FormatParameters result; |
| 179 |
| 180 | for (const auto ¶meter : format.parameters) { |
| 181 | if (parameter.first == "profile-level-id") { |
| 182 | result.profileLevelId = parameter.second; |
| 183 | } else if (parameter.first == "packetization-mode") { |
| 184 | result.packetizationMode = parameter.second; |
| 185 | } else if (parameter.first == "level-asymmetry-allowed") { |
| 186 | result.levelAssymetryAllowed = parameter.second; |
| 187 | } |
| 188 | } |
| 189 |
| 190 | return result; |
| 191 | } |
| 192 |
| 193 | static int getH264ProfileLevelIdPriority(std::string const &profileLevelId) { |
| 194 | if (profileLevelId == cricket::kH264ProfileLevelConstrainedHigh) { |
| 195 | return 0; |
| 196 | } else if (profileLevelId == cricket::kH264ProfileLevelConstrainedBaseline) { |
| 197 | return 1; |
| 198 | } else { |
| 199 | return 2; |
| 200 | } |
| 201 | } |
| 202 |
| 203 | static int getH264PacketizationModePriority(std::string const &packetizationMode) { |
| 204 | if (packetizationMode == "1") { |
| 205 | return 0; |
| 206 | } else { |
| 207 | return 1; |
| 208 | } |
| 209 | } |
| 210 |
| 211 | static int getH264LevelAssymetryAllowedPriority(std::string const &levelAssymetryAllowed) { |
| 212 | if (levelAssymetryAllowed == "1") { |
| 213 | return 0; |
| 214 | } else { |
| 215 | return 1; |
| 216 | } |
| 217 | } |
| 218 |
| 219 | static std::vector<webrtc::SdpVideoFormat> filterSupportedVideoFormats(std::vector<webrtc::SdpVideoFormat> const &formats) { |
| 220 | std::vector<webrtc::SdpVideoFormat> filteredFormats; |
| 221 |
| 222 | std::vector<std::string> filterCodecNames = { |
| 223 | cricket::kVp8CodecName, |
| 224 | cricket::kVp9CodecName, |
| 225 | cricket::kH264CodecName |
| 226 | }; |
| 227 |
| 228 | std::vector<webrtc::SdpVideoFormat> vp9Formats; |
| 229 | std::vector<webrtc::SdpVideoFormat> h264Formats; |
| 230 |
| 231 | for (const auto &format : formats) { |
| 232 | if (std::find(filterCodecNames.begin(), filterCodecNames.end(), format.name) == filterCodecNames.end()) { |
| 233 | continue; |
| 234 | } |
| 235 |
| 236 | if (format.name == cricket::kVp9CodecName) { |
| 237 | vp9Formats.push_back(format); |
| 238 | } else if (format.name == cricket::kH264CodecName) { |
| 239 | h264Formats.push_back(format); |
| 240 | } else { |
| 241 | filteredFormats.push_back(format); |
| 242 | } |
| 243 | } |
| 244 |
| 245 | if (!vp9Formats.empty()) { |
| 246 | bool added = false; |
| 247 | for (const auto &format : vp9Formats) { |
| 248 | if (added) { |
| 249 | break; |
| 250 | } |
| 251 | for (const auto ¶meter : format.parameters) { |
| 252 | if (parameter.first == "profile-id") { |
| 253 | if (parameter.second == "0") { |
| 254 | filteredFormats.push_back(format); |
| 255 | added = true; |
| 256 | break; |
| 257 | } |
| 258 | } |
| 259 | } |
| 260 | } |
| 261 |
| 262 | if (!added) { |
| 263 | filteredFormats.push_back(vp9Formats[0]); |
| 264 | } |
| 265 | } |
| 266 |
| 267 | if (!h264Formats.empty()) { |
| 268 | std::sort(h264Formats.begin(), h264Formats.end(), [](const webrtc::SdpVideoFormat &lhs, const webrtc::SdpVideoFormat &rhs) { |
| 269 | auto lhsParameters = parseH264FormatParameters(lhs); |
| 270 | auto rhsParameters = parseH264FormatParameters(rhs); |
| 271 |
| 272 | int lhsLevelIdPriority = getH264ProfileLevelIdPriority(lhsParameters.profileLevelId); |
| 273 | int lhsPacketizationModePriority = getH264PacketizationModePriority(lhsParameters.packetizationMode); |
| 274 | int lhsLevelAssymetryAllowedPriority = getH264LevelAssymetryAllowedPriority(lhsParameters.levelAssymetryAllowed); |
| 275 |
| 276 | int rhsLevelIdPriority = getH264ProfileLevelIdPriority(rhsParameters.profileLevelId); |
| 277 | int rhsPacketizationModePriority = getH264PacketizationModePriority(rhsParameters.packetizationMode); |
| 278 | int rhsLevelAssymetryAllowedPriority = getH264LevelAssymetryAllowedPriority(rhsParameters.levelAssymetryAllowed); |
| 279 |
| 280 | if (lhsLevelIdPriority != rhsLevelIdPriority) { |
| 281 | return lhsLevelIdPriority < rhsLevelIdPriority; |
| 282 | } |
| 283 | if (lhsPacketizationModePriority != rhsPacketizationModePriority) { |
| 284 | return lhsPacketizationModePriority < rhsPacketizationModePriority; |
| 285 | } |
| 286 | if (lhsLevelAssymetryAllowedPriority != rhsLevelAssymetryAllowedPriority) { |
| 287 | return lhsLevelAssymetryAllowedPriority < rhsLevelAssymetryAllowedPriority; |
| 288 | } |
| 289 |
| 290 | return false; |
| 291 | }); |
| 292 |
| 293 | filteredFormats.push_back(h264Formats[0]); |
| 294 | } |
| 295 |
| 296 | return filteredFormats; |
| 297 | } |
| 298 |
| 299 | static std::vector<OutgoingVideoFormat> assignPayloadTypes(std::vector<webrtc::SdpVideoFormat> const &formats) { |
| 300 | if (formats.empty()) { |
| 301 | return {}; |
| 302 | } |
| 303 |
| 304 | constexpr int kFirstDynamicPayloadType = 100; |
| 305 | constexpr int kLastDynamicPayloadType = 127; |
| 306 |
| 307 | int payload_type = kFirstDynamicPayloadType; |
| 308 |
| 309 | std::vector<OutgoingVideoFormat> result; |
| 310 |
| 311 | std::vector<std::string> filterCodecNames = { |
| 312 | cricket::kVp8CodecName, |
| 313 | cricket::kVp9CodecName, |
| 314 | cricket::kH264CodecName, |
| 315 | }; |
| 316 |
| 317 | for (const auto &codecName : filterCodecNames) { |
| 318 | for (const auto &format : formats) { |
| 319 | if (format.name != codecName) { |
| 320 | continue; |
| 321 | } |
| 322 |
| 323 | cricket::VideoCodec codec = cricket::CreateVideoCodec(format); |
| 324 | codec.id = payload_type; |
| 325 | addDefaultFeedbackParams(&codec); |
| 326 |
| 327 | // Increment payload type. |
| 328 | ++payload_type; |
| 329 | if (payload_type > kLastDynamicPayloadType) { |
| 330 | RTC_LOG(LS_ERROR) << "Out of dynamic payload types, skipping the rest."; |
| 331 | break; |
| 332 | } |
| 333 |
| 334 | absl::optional<cricket::Codec> rtxCodec; |
| 335 | // Add associated RTX codec for non-FEC codecs. |
| 336 | if (!absl::EqualsIgnoreCase(codec.name, cricket::kUlpfecCodecName) && |
| 337 | !absl::EqualsIgnoreCase(codec.name, cricket::kFlexfecCodecName)) { |
| 338 | rtxCodec = cricket::CreateVideoRtxCodec(payload_type, codec.id); |
| 339 |
| 340 | // Increment payload type. |
| 341 | ++payload_type; |
| 342 | if (payload_type > kLastDynamicPayloadType) { |
| 343 | RTC_LOG(LS_ERROR) << "Out of dynamic payload types, skipping the rest."; |
| 344 | break; |
| 345 | } |
| 346 | } |
| 347 |
| 348 | OutgoingVideoFormat resultFormat(codec, rtxCodec); |
| 349 |
| 350 | result.push_back(std::move(resultFormat)); |
| 351 | } |
| 352 | } |
| 353 |
| 354 | return result; |
| 355 | } |
| 356 |
| 357 | struct VideoSsrcs { |
| 358 | struct SimulcastLayer { |
| 359 | uint32_t ssrc = 0; |
| 360 | uint32_t fidSsrc = 0; |
| 361 |
| 362 | SimulcastLayer(uint32_t ssrc_, uint32_t fidSsrc_) : |
| 363 | ssrc(ssrc_), fidSsrc(fidSsrc_) { |
| 364 | } |
| 365 |
| 366 | SimulcastLayer(const SimulcastLayer &other) : |
| 367 | ssrc(other.ssrc), fidSsrc(other.fidSsrc) { |
| 368 | } |
| 369 | }; |
| 370 |
| 371 | std::vector<SimulcastLayer> simulcastLayers; |
| 372 |
| 373 | VideoSsrcs() { |
| 374 | } |
| 375 |
| 376 | VideoSsrcs(const VideoSsrcs &other) : |
| 377 | simulcastLayers(other.simulcastLayers) { |
| 378 | } |
| 379 | }; |
| 380 |
| 381 | struct InternalGroupLevelValue { |
| 382 | GroupLevelValue value; |
| 383 | int64_t timestamp = 0; |
| 384 | }; |
| 385 |
| 386 | struct InternalGroupActivityValue { |
| 387 | int64_t timestamp = 0; |
| 388 | }; |
| 389 |
| 390 | struct ChannelId { |
| 391 | uint32_t networkSsrc = 0; |
| 392 | uint32_t actualSsrc = 0; |
| 393 |
| 394 | ChannelId(uint32_t networkSsrc_, uint32_t actualSsrc_) : |
| 395 | networkSsrc(networkSsrc_), |
| 396 | actualSsrc(actualSsrc_) { |
| 397 | } |
| 398 |
| 399 | explicit ChannelId(uint32_t networkSsrc_) : |
| 400 | networkSsrc(networkSsrc_), |
| 401 | actualSsrc(networkSsrc_) { |
| 402 | } |
| 403 |
| 404 | bool operator <(const ChannelId& rhs) const { |
| 405 | if (networkSsrc != rhs.networkSsrc) { |
| 406 | return networkSsrc < rhs.networkSsrc; |
| 407 | } |
| 408 | return actualSsrc < rhs.actualSsrc; |
| 409 | } |
| 410 |
| 411 | std::string name() { |
| 412 | if (networkSsrc == actualSsrc) { |
| 413 | return uint32ToString(networkSsrc); |
| 414 | } else { |
| 415 | return uint32ToString(networkSsrc) + "to" + uint32ToString(actualSsrc); |
| 416 | } |
| 417 | } |
| 418 | }; |
| 419 |
| 420 | struct VideoChannelId { |
| 421 | std::string endpointId; |
| 422 |
| 423 | explicit VideoChannelId(std::string const &endpointId_) : |
| 424 | endpointId(endpointId_) { |
| 425 | } |
| 426 |
| 427 | bool operator <(const VideoChannelId& rhs) const { |
| 428 | return endpointId < rhs.endpointId; |
| 429 | } |
| 430 | }; |
| 431 |
| 432 | struct ChannelSsrcInfo { |
| 433 | enum class Type { |
| 434 | Audio, |
| 435 | Video |
| 436 | }; |
| 437 |
| 438 | Type type = Type::Audio; |
| 439 | std::vector<uint32_t> allSsrcs; |
| 440 | std::string videoEndpointId; |
| 441 | }; |
| 442 |
| 443 | struct RequestedMediaChannelDescriptions { |
| 444 | std::shared_ptr<RequestMediaChannelDescriptionTask> task; |
| 445 | std::vector<uint32_t> ssrcs; |
| 446 |
| 447 | RequestedMediaChannelDescriptions(std::shared_ptr<RequestMediaChannelDescriptionTask> task_, std::vector<uint32_t> ssrcs_) : |
| 448 | task(task_), ssrcs(std::move(ssrcs_)) { |
| 449 | } |
| 450 | }; |
| 451 |
| 452 | static const int kVadResultHistoryLength = 8; |
| 453 |
| 454 | class VadHistory { |
| 455 | private: |
| 456 | float _vadResultHistory[kVadResultHistoryLength]; |
| 457 |
| 458 | public: |
| 459 | VadHistory() { |
| 460 | for (int i = 0; i < kVadResultHistoryLength; i++) { |
| 461 | _vadResultHistory[i] = 0.0f; |
| 462 | } |
| 463 | } |
| 464 |
| 465 | ~VadHistory() { |
| 466 | } |
| 467 |
| 468 | bool update(float vadProbability) { |
| 469 | for (int i = 1; i < kVadResultHistoryLength; i++) { |
| 470 | _vadResultHistory[i - 1] = _vadResultHistory[i]; |
| 471 | } |
| 472 | _vadResultHistory[kVadResultHistoryLength - 1] = vadProbability; |
| 473 |
| 474 | float movingAverage = 0.0f; |
| 475 | for (int i = 0; i < kVadResultHistoryLength; i++) { |
| 476 | movingAverage += _vadResultHistory[i]; |
| 477 | } |
| 478 | movingAverage /= (float)kVadResultHistoryLength; |
| 479 |
| 480 | bool vadResult = false; |
| 481 | if (movingAverage > 0.8f) { |
| 482 | vadResult = true; |
| 483 | } |
| 484 |
| 485 | return vadResult; |
| 486 | } |
| 487 | }; |
| 488 |
| 489 | class CombinedVad { |
| 490 | private: |
| 491 | webrtc::VoiceActivityDetectorWrapper _vadWithLevel; |
| 492 | VadHistory _history; |
| 493 |
| 494 | public: |
| 495 | CombinedVad() : |
| 496 | _vadWithLevel(500, webrtc::GetAvailableCpuFeatures(), webrtc::AudioProcessing::kSampleRate48kHz) { |
| 497 | } |
| 498 |
| 499 | ~CombinedVad() { |
| 500 | } |
| 501 |
| 502 | bool update(webrtc::AudioBuffer *buffer) { |
| 503 | if (buffer->num_channels() <= 0) { |
| 504 | return _history.update(0.0f); |
| 505 | } |
| 506 | webrtc::AudioFrameView<float> frameView(buffer->channels(), (int)(buffer->num_channels()), (int)(buffer->num_frames())); |
| 507 | float peak = 0.0f; |
| 508 | for (const auto &x : frameView.channel(0)) { |
| 509 | peak = std::max(std::fabs(x), peak); |
| 510 | } |
| 511 | if (peak <= 0.01f) { |
| 512 | return _history.update(false); |
| 513 | } |
| 514 |
| 515 | auto result = _vadWithLevel.Analyze(frameView); |
| 516 |
| 517 | return _history.update(result); |
| 518 | } |
| 519 |
| 520 | bool update() { |
| 521 | return _history.update(0.0f); |
| 522 | } |
| 523 | }; |
| 524 |
| 525 | class SparseVad { |
| 526 | public: |
| 527 | SparseVad() { |
| 528 | } |
| 529 |
| 530 | bool update(webrtc::AudioBuffer *buffer) { |
| 531 | _sampleCount += buffer->num_frames(); |
| 532 | if (_sampleCount < 400) { |
| 533 | return _currentValue; |
| 534 | } |
| 535 | _sampleCount = 0; |
| 536 |
| 537 | _currentValue = _vad.update(buffer); |
| 538 |
| 539 | return _currentValue; |
| 540 | } |
| 541 |
| 542 | private: |
| 543 | CombinedVad _vad; |
| 544 | bool _currentValue = false; |
| 545 | size_t _sampleCount = 0; |
| 546 | }; |
| 547 |
| 548 | class AudioSinkImpl: public webrtc::AudioSinkInterface { |
| 549 | public: |
| 550 | struct Update { |
| 551 | float level = 0.0f; |
| 552 | bool hasSpeech = false; |
| 553 |
| 554 | Update(float level_, bool hasSpech_) : |
| 555 | level(level_), hasSpeech(hasSpech_) { |
| 556 | } |
| 557 |
| 558 | Update(const Update &other) : |
| 559 | level(other.level), hasSpeech(other.hasSpeech) { |
| 560 | } |
| 561 | }; |
| 562 |
| 563 | public: |
| 564 | AudioSinkImpl(std::function<void(Update)> update, |
| 565 | ChannelId channel_id, std::function<void(uint32_t, const AudioFrame &)> onAudioFrame) : |
| 566 | _update(update), _channel_id(channel_id), _onAudioFrame(std::move(onAudioFrame)) { |
| 567 | } |
| 568 |
| 569 | virtual ~AudioSinkImpl() { |
| 570 | } |
| 571 |
| 572 | virtual void OnData(const Data& audio) override { |
| 573 | if (_onAudioFrame) { |
| 574 | AudioFrame frame; |
| 575 | frame.audio_samples = audio.data; |
| 576 | frame.num_samples = audio.samples_per_channel; |
| 577 | frame.bytes_per_sample = 2; |
| 578 | frame.num_channels = audio.channels; |
| 579 | frame.samples_per_sec = audio.sample_rate; |
| 580 | frame.elapsed_time_ms = 0; |
| 581 | frame.ntp_time_ms = 0; |
| 582 | _onAudioFrame(_channel_id.actualSsrc, frame); |
| 583 | } |
| 584 | if (_update && audio.channels == 1) { |
| 585 | const int16_t *samples = (const int16_t *)audio.data; |
| 586 | int numberOfSamplesInFrame = (int)audio.samples_per_channel; |
| 587 |
| 588 | int16_t currentPeak = 0; |
| 589 | for (int i = 0; i < numberOfSamplesInFrame; i++) { |
| 590 | int16_t sample = samples[i]; |
| 591 | if (sample < 0) { |
| 592 | sample = -sample; |
| 593 | } |
| 594 | if (_peak < sample) { |
| 595 | _peak = sample; |
| 596 | } |
| 597 | if (currentPeak < sample) { |
| 598 | currentPeak = sample; |
| 599 | } |
| 600 | _peakCount += 1; |
| 601 | } |
| 602 |
| 603 | /*bool vadResult = false; |
| 604 | if (currentPeak > 10) { |
| 605 | webrtc::AudioBuffer buffer(audio.sample_rate, 1, 48000, 1, 48000, 1); |
| 606 | webrtc::StreamConfig config(audio.sample_rate, 1); |
| 607 | buffer.CopyFrom(samples, config); |
| 608 |
| 609 | vadResult = _vad.update(&buffer); |
| 610 | } else { |
| 611 | vadResult = _vad.update(); |
| 612 | }*/ |
| 613 |
| 614 | if (_peakCount >= 4400) { |
| 615 | float level = ((float)(_peak)) / 8000.0f; |
| 616 | _peak = 0; |
| 617 | _peakCount = 0; |
| 618 | _update(Update(level, level >= 1.0f)); |
| 619 | } |
| 620 | } |
| 621 | } |
| 622 |
| 623 | private: |
| 624 | std::function<void(Update)> _update; |
| 625 | ChannelId _channel_id; |
| 626 | std::function<void(uint32_t, const AudioFrame &)> _onAudioFrame; |
| 627 |
| 628 | int _peakCount = 0; |
| 629 | uint16_t _peak = 0; |
| 630 |
| 631 | CombinedVad _vad; |
| 632 |
| 633 | }; |
| 634 |
| 635 | class VideoSinkImpl : public rtc::VideoSinkInterface<webrtc::VideoFrame> { |
| 636 | public: |
| 637 | VideoSinkImpl(std::string const &endpointId) : |
| 638 | _endpointId(endpointId) { |
| 639 | } |
| 640 |
| 641 | virtual ~VideoSinkImpl() { |
| 642 | } |
| 643 |
| 644 | virtual void OnFrame(const webrtc::VideoFrame& frame) override { |
| 645 | std::unique_lock<std::mutex> lock{ _mutex }; |
| 646 | int64_t timestamp = rtc::TimeMillis(); |
| 647 | const int width = frame.video_frame_buffer()->width(); |
| 648 | const int height = frame.video_frame_buffer()->height(); |
| 649 | if (_hasLastFrameSize) { |
| 650 | if (_lastFrameWidth != width) { |
| 651 | int64_t deltaTime = std::abs(_lastFrameSizeChangeTimestamp - timestamp); |
| 652 | if (deltaTime < 200) { |
| 653 | RTC_LOG(LS_WARNING) << "VideoSinkImpl: frequent frame size change detected for " << _endpointId << ": " << _lastFrameSizeChangeHeight << " -> " << _lastFrameHeight << " -> " << height << " in " << deltaTime << " ms"; |
| 654 | } |
| 655 |
| 656 | _lastFrameSizeChangeHeight = _lastFrameHeight; |
| 657 | _lastFrameSizeChangeTimestamp = timestamp; |
| 658 | } |
| 659 | } else { |
| 660 | _lastFrameSizeChangeHeight = 0; |
| 661 | _lastFrameSizeChangeTimestamp = timestamp; |
| 662 | } |
| 663 | _lastFrameWidth = width; |
| 664 | _lastFrameHeight = height; |
| 665 | _hasLastFrameSize = true; |
| 666 | for (int i = (int)(_sinks.size()) - 1; i >= 0; i--) { |
| 667 | auto strong = _sinks[i].lock(); |
| 668 | if (!strong) { |
| 669 | _sinks.erase(_sinks.begin() + i); |
| 670 | } else { |
| 671 | strong->OnFrame(frame); |
| 672 | } |
| 673 | } |
| 674 | } |
| 675 |
| 676 | virtual void OnDiscardedFrame() override { |
| 677 | std::unique_lock<std::mutex> lock{ _mutex }; |
| 678 | for (int i = (int)(_sinks.size()) - 1; i >= 0; i--) { |
| 679 | auto strong = _sinks[i].lock(); |
| 680 | if (!strong) { |
| 681 | _sinks.erase(_sinks.begin() + i); |
| 682 | } else { |
| 683 | strong->OnDiscardedFrame(); |
| 684 | } |
| 685 | } |
| 686 | } |
| 687 |
| 688 | void addSink(std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> impl) { |
| 689 | if (const auto strong = impl.lock()) { |
| 690 | std::unique_lock<std::mutex> lock{ _mutex }; |
| 691 | _sinks.push_back(impl); |
| 692 | } |
| 693 | } |
| 694 |
| 695 | std::vector<std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>>> getSinks() { |
| 696 | return _sinks; |
| 697 | } |
| 698 |
| 699 | private: |
| 700 | std::vector<std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>>> _sinks; |
| 701 | bool _hasLastFrameSize = false; |
| 702 | int _lastFrameWidth = 0; |
| 703 | int _lastFrameHeight = 0; |
| 704 | std::mutex _mutex; |
| 705 | int64_t _lastFrameSizeChangeTimestamp = 0; |
| 706 | int _lastFrameSizeChangeHeight = 0; |
| 707 | std::string _endpointId; |
| 708 |
| 709 | }; |
| 710 |
| 711 | struct NoiseSuppressionConfiguration { |
| 712 | NoiseSuppressionConfiguration(bool isEnabled_) : |
| 713 | isEnabled(isEnabled_) { |
| 714 |
| 715 | } |
| 716 |
| 717 | bool isEnabled = false; |
| 718 | }; |
| 719 |
| 720 | #if USE_RNNOISE |
| 721 | class AudioCapturePostProcessor : public webrtc::CustomProcessing { |
| 722 | public: |
| 723 | AudioCapturePostProcessor(std::function<void(GroupLevelValue const &)> updated, std::shared_ptr<NoiseSuppressionConfiguration> noiseSuppressionConfiguration, std::vector<float> *externalAudioSamples, webrtc::Mutex *externalAudioSamplesMutex) : |
| 724 | _updated(updated), |
| 725 | _noiseSuppressionConfiguration(noiseSuppressionConfiguration), |
| 726 | _externalAudioSamples(externalAudioSamples), |
| 727 | _externalAudioSamplesMutex(externalAudioSamplesMutex) { |
| 728 | int frameSize = rnnoise_get_frame_size(); |
| 729 | _frameSamples.resize(frameSize); |
| 730 |
| 731 | _denoiseState = rnnoise_create(nullptr); |
| 732 | } |
| 733 |
| 734 | virtual ~AudioCapturePostProcessor() { |
| 735 | if (_denoiseState) { |
| 736 | rnnoise_destroy(_denoiseState); |
| 737 | } |
| 738 | } |
| 739 |
| 740 | private: |
| 741 | virtual void Initialize(int sample_rate_hz, int num_channels) override { |
| 742 | } |
| 743 |
| 744 | virtual void Process(webrtc::AudioBuffer *buffer) override { |
| 745 | if (!buffer) { |
| 746 | return; |
| 747 | } |
| 748 | if (buffer->num_channels() != 1) { |
| 749 | return; |
| 750 | } |
| 751 | if (!_denoiseState) { |
| 752 | return; |
| 753 | } |
| 754 | if (buffer->num_frames() != _frameSamples.size()) { |
| 755 | return; |
| 756 | } |
| 757 |
| 758 | float sourcePeak = 0.0f; |
| 759 | float *sourceSamples = buffer->channels()[0]; |
| 760 | for (int i = 0; i < _frameSamples.size(); i++) { |
| 761 | sourcePeak = std::max(std::fabs(sourceSamples[i]), sourcePeak); |
| 762 | } |
| 763 |
| 764 | if (_noiseSuppressionConfiguration->isEnabled) { |
| 765 | float vadProbability = 0.0f; |
| 766 | if (sourcePeak >= 0.01f) { |
| 767 | vadProbability = rnnoise_process_frame(_denoiseState, _frameSamples.data(), buffer->channels()[0]); |
| 768 | if (_noiseSuppressionConfiguration->isEnabled) { |
| 769 | memcpy(buffer->channels()[0], _frameSamples.data(), _frameSamples.size() * sizeof(float)); |
| 770 | } |
| 771 | } |
| 772 |
| 773 | float peak = 0; |
| 774 | int peakCount = 0; |
| 775 | const float *samples = buffer->channels_const()[0]; |
| 776 | for (int i = 0; i < buffer->num_frames(); i++) { |
| 777 | float sample = samples[i]; |
| 778 | if (sample < 0) { |
| 779 | sample = -sample; |
| 780 | } |
| 781 | if (peak < sample) { |
| 782 | peak = sample; |
| 783 | } |
| 784 | peakCount += 1; |
| 785 | } |
| 786 |
| 787 | bool vadStatus = _history.update(vadProbability); |
| 788 |
| 789 | _peakCount += peakCount; |
| 790 | if (_peak < peak) { |
| 791 | _peak = peak; |
| 792 | } |
| 793 | if (_peakCount >= 4400) { |
| 794 | float level = _peak / 4000.0f; |
| 795 | _peak = 0; |
| 796 | _peakCount = 0; |
| 797 |
| 798 | _updated(GroupLevelValue{ |
| 799 | level, |
| 800 | vadStatus, |
| 801 | }); |
| 802 | } |
| 803 | } else { |
| 804 | float peak = 0; |
| 805 | int peakCount = 0; |
| 806 | const float *samples = buffer->channels_const()[0]; |
| 807 | for (int i = 0; i < buffer->num_frames(); i++) { |
| 808 | float sample = samples[i]; |
| 809 | if (sample < 0) { |
| 810 | sample = -sample; |
| 811 | } |
| 812 | if (peak < sample) { |
| 813 | peak = sample; |
| 814 | } |
| 815 | peakCount += 1; |
| 816 | } |
| 817 |
| 818 | _peakCount += peakCount; |
| 819 | if (_peak < peak) { |
| 820 | _peak = peak; |
| 821 | } |
| 822 | if (_peakCount >= 1200) { |
| 823 | float level = _peak / 8000.0f; |
| 824 | _peak = 0; |
| 825 | _peakCount = 0; |
| 826 |
| 827 | _updated(GroupLevelValue{ |
| 828 | level, |
| 829 | level >= 1.0f, |
| 830 | }); |
| 831 | } |
| 832 | } |
| 833 |
| 834 | if (_externalAudioSamplesMutex && _externalAudioSamples) { |
| 835 | _externalAudioSamplesMutex->Lock(); |
| 836 | if (!_externalAudioSamples->empty()) { |
| 837 | float *bufferData = buffer->channels()[0]; |
| 838 | int takenSamples = 0; |
| 839 | for (int i = 0; i < _externalAudioSamples->size() && i < _frameSamples.size(); i++) { |
| 840 | float sample = (*_externalAudioSamples)[i]; |
| 841 | sample += bufferData[i]; |
| 842 | sample = std::min(sample, 32768.f); |
| 843 | sample = std::max(sample, -32768.f); |
| 844 | bufferData[i] = sample; |
| 845 | takenSamples++; |
| 846 | } |
| 847 | if (takenSamples != 0) { |
| 848 | _externalAudioSamples->erase(_externalAudioSamples->begin(), _externalAudioSamples->begin() + takenSamples); |
| 849 | } |
| 850 | } |
| 851 | _externalAudioSamplesMutex->Unlock(); |
| 852 | } |
| 853 | } |
| 854 |
| 855 | virtual std::string ToString() const override { |
| 856 | return "CustomPostProcessing"; |
| 857 | } |
| 858 |
| 859 | virtual void SetRuntimeSetting(webrtc::AudioProcessing::RuntimeSetting setting) override { |
| 860 | } |
| 861 |
| 862 | private: |
| 863 | std::function<void(GroupLevelValue const &)> _updated; |
| 864 | std::shared_ptr<NoiseSuppressionConfiguration> _noiseSuppressionConfiguration; |
| 865 |
| 866 | DenoiseState *_denoiseState = nullptr; |
| 867 | std::vector<float> _frameSamples; |
| 868 | int32_t _peakCount = 0; |
| 869 | float _peak = 0; |
| 870 | VadHistory _history; |
| 871 | SparseVad _vad; |
| 872 |
| 873 | std::vector<float> *_externalAudioSamples = nullptr; |
| 874 | webrtc::Mutex *_externalAudioSamplesMutex = nullptr; |
| 875 | }; |
| 876 | #endif |
| 877 |
| 878 | class AudioInjectionPostProcessor : public webrtc::CustomProcessing { |
| 879 | public: |
| 880 | AudioInjectionPostProcessor(std::vector<float> *externalAudioSamples, webrtc::Mutex *externalAudioSamplesMutex) : |
| 881 | _externalAudioSamples(externalAudioSamples), |
| 882 | _externalAudioSamplesMutex(externalAudioSamplesMutex) { |
| 883 | } |
| 884 |
| 885 | virtual ~AudioInjectionPostProcessor() { |
| 886 | } |
| 887 |
| 888 | private: |
| 889 | virtual void Initialize(int sample_rate_hz, int num_channels) override { |
| 890 | } |
| 891 |
| 892 | virtual void Process(webrtc::AudioBuffer *buffer) override { |
| 893 | if (!buffer) { |
| 894 | return; |
| 895 | } |
| 896 | if (buffer->num_channels() != 1) { |
| 897 | return; |
| 898 | } |
| 899 |
| 900 | if (_externalAudioSamplesMutex && _externalAudioSamples) { |
| 901 | _externalAudioSamplesMutex->Lock(); |
| 902 | if (!_externalAudioSamples->empty()) { |
| 903 | float *bufferData = buffer->channels()[0]; |
| 904 | int takenSamples = 0; |
| 905 | for (int i = 0; i < _externalAudioSamples->size() && i < buffer->num_frames(); i++) { |
| 906 | float sample = (*_externalAudioSamples)[i]; |
| 907 | sample += bufferData[i]; |
| 908 | sample = std::min(sample, 32768.f); |
| 909 | sample = std::max(sample, -32768.f); |
| 910 | bufferData[i] = sample; |
| 911 | takenSamples++; |
| 912 | } |
| 913 | if (takenSamples != 0) { |
| 914 | _externalAudioSamples->erase(_externalAudioSamples->begin(), _externalAudioSamples->begin() + takenSamples); |
| 915 | } |
| 916 | } |
| 917 | _externalAudioSamplesMutex->Unlock(); |
| 918 | } |
| 919 | } |
| 920 |
| 921 | virtual std::string ToString() const override { |
| 922 | return "CustomPostProcessing"; |
| 923 | } |
| 924 |
| 925 | virtual void SetRuntimeSetting(webrtc::AudioProcessing::RuntimeSetting setting) override { |
| 926 | } |
| 927 |
| 928 | private: |
| 929 | std::vector<float> *_externalAudioSamples = nullptr; |
| 930 | webrtc::Mutex *_externalAudioSamplesMutex = nullptr; |
| 931 | }; |
| 932 |
| 933 | class ExternalAudioRecorder : public FakeAudioDeviceModule::Recorder { |
| 934 | public: |
| 935 | ExternalAudioRecorder(std::vector<float> *externalAudioSamples, webrtc::Mutex *externalAudioSamplesMutex) : |
| 936 | _externalAudioSamples(externalAudioSamples), |
| 937 | _externalAudioSamplesMutex(externalAudioSamplesMutex) { |
| 938 | _samples.resize(480); |
| 939 | } |
| 940 |
| 941 | virtual ~ExternalAudioRecorder() { |
| 942 | } |
| 943 |
| 944 | virtual AudioFrame Record() override { |
| 945 | AudioFrame result; |
| 946 |
| 947 | _externalAudioSamplesMutex->Lock(); |
| 948 | if (!_externalAudioSamples->empty() && _externalAudioSamples->size() >= 480) { |
| 949 | size_t takenSamples = std::min(_samples.size(), _externalAudioSamples->size()); |
| 950 | webrtc::FloatS16ToS16(_externalAudioSamples->data(), takenSamples, _samples.data()); |
| 951 |
| 952 | result.num_samples = takenSamples; |
| 953 |
| 954 | if (takenSamples != 0) { |
| 955 | _externalAudioSamples->erase(_externalAudioSamples->begin(), _externalAudioSamples->begin() + takenSamples); |
| 956 | } |
| 957 | } else { |
| 958 | result.num_samples = 0; |
| 959 | } |
| 960 | _externalAudioSamplesMutex->Unlock(); |
| 961 |
| 962 | result.audio_samples = _samples.data(); |
| 963 | result.bytes_per_sample = 2; |
| 964 | result.num_channels = 1; |
| 965 | result.samples_per_sec = 48000; |
| 966 | result.elapsed_time_ms = 0; |
| 967 | result.ntp_time_ms = 0; |
| 968 |
| 969 | return result; |
| 970 | } |
| 971 |
| 972 | virtual int32_t WaitForUs() override { |
| 973 | _externalAudioSamplesMutex->Lock(); |
| 974 | _externalAudioSamplesMutex->Unlock(); |
| 975 |
| 976 | return 1000; |
| 977 | } |
| 978 |
| 979 | private: |
| 980 | std::vector<float> *_externalAudioSamples = nullptr; |
| 981 | webrtc::Mutex *_externalAudioSamplesMutex = nullptr; |
| 982 | std::vector<int16_t> _samples; |
| 983 | }; |
| 984 |
| 985 | class MyAudioLevelHolder { |
| 986 | public: |
| 987 | MyAudioLevelHolder() { |
| 988 | } |
| 989 |
| 990 | void set(GroupLevelValue value) { |
| 991 | webrtc::MutexLock lock(&_mutex); |
| 992 | _value = value; |
| 993 | } |
| 994 |
| 995 | GroupLevelValue get() { |
| 996 | webrtc::MutexLock lock(&_mutex); |
| 997 | return _value; |
| 998 | } |
| 999 |
| 1000 | private: |
| 1001 | webrtc::Mutex _mutex; |
| 1002 | GroupLevelValue _value; |
| 1003 | }; |
| 1004 |
| 1005 | class AudioLevelAndSpeechHolder { |
| 1006 | public: |
| 1007 | AudioLevelAndSpeechHolder() { |
| 1008 | } |
| 1009 |
| 1010 | void set(uint8_t audioLevel, bool hasSpeech) { |
| 1011 | webrtc::MutexLock lock(&_mutex); |
| 1012 | _audioLevel = audioLevel; |
| 1013 | _hasSpeech = hasSpeech; |
| 1014 | } |
| 1015 |
| 1016 | std::pair<uint8_t, bool> get() { |
| 1017 | webrtc::MutexLock lock(&_mutex); |
| 1018 | return std::make_pair(_audioLevel, _hasSpeech); |
| 1019 | } |
| 1020 |
| 1021 | private: |
| 1022 | webrtc::Mutex _mutex; |
| 1023 | uint8_t _audioLevel = 0; |
| 1024 | bool _hasSpeech = false; |
| 1025 | }; |
| 1026 |
| 1027 | // Constants for H264 NAL unit types and headers |
| 1028 | static constexpr uint8_t kTypeMask = 0x1F; |
| 1029 | static constexpr uint8_t kFuA = 28; |
| 1030 | static constexpr uint8_t kIdr = 5; |
| 1031 | static constexpr uint8_t kSps = 7; |
| 1032 | static constexpr uint8_t kPps = 8; |
| 1033 | static constexpr uint8_t kSei = 6; |
| 1034 | static constexpr uint8_t kStapA = 24; |
| 1035 | static constexpr size_t kNalHeaderSize = 1; |
| 1036 | static constexpr size_t kFuAHeaderSize = 2; |
| 1037 | constexpr size_t kLengthFieldSize = 2; |
| 1038 | constexpr size_t kStapAHeaderSize = kNalHeaderSize + kLengthFieldSize; |
| 1039 |
| 1040 | // Calculate bytes needed to include PPS ID in a slice header |
| 1041 | size_t calculateSliceHeaderBytesForPpsId(const uint8_t* data, size_t size) { |
| 1042 | if (size < 2) |
| 1043 | return 0; |
| 1044 |
| 1045 | // Convert to RBSP format (remove emulation prevention bytes) |
| 1046 | std::vector<uint8_t> rbsp = webrtc::H264::ParseRbsp(data, size); |
| 1047 | if (rbsp.size() < 2) |
| 1048 | return 0; |
| 1049 |
| 1050 | // Create a bitstream reader for the RBSP data (skipping NAL header) |
| 1051 | // We need to skip the NAL header (1 byte) but still read from the start of the slice header |
| 1052 | rtc::ArrayView<const uint8_t> rbspView(rbsp.data() + 1, rbsp.size() - 1); |
| 1053 | webrtc::BitstreamReader reader(rbspView); |
| 1054 |
| 1055 | // first_mb_in_slice: ue(v) |
| 1056 | reader.ReadExponentialGolomb(); |
| 1057 | if (!reader.Ok()) { |
| 1058 | return 4; // Default if parsing fails |
| 1059 | } |
| 1060 |
| 1061 | // slice_type: ue(v) |
| 1062 | reader.ReadExponentialGolomb(); |
| 1063 | if (!reader.Ok()) { |
| 1064 | return 4; // Default if parsing fails |
| 1065 | } |
| 1066 |
| 1067 | // pic_parameter_set_id: ue(v) - THIS IS WHAT WE NEED |
| 1068 | reader.ReadExponentialGolomb(); |
| 1069 | if (!reader.Ok()) { |
| 1070 | return 4; // Default if parsing fails |
| 1071 | } |
| 1072 |
| 1073 | // Calculate how many bytes we've read so far, plus 1 for NAL header |
| 1074 | // The consumed bits divided by 8 (rounded up) gives us the bytes read |
| 1075 | size_t bitsConsumed = rbspView.size() * 8 - reader.RemainingBitCount(); |
| 1076 | size_t bytesRead = 1 + (bitsConsumed + 7) / 8; // +1 for NAL header, +7 for ceiling division |
| 1077 |
| 1078 | // Add a margin to ensure we get all the PPS ID data |
| 1079 | return bytesRead + 1; |
| 1080 | } |
| 1081 |
| 1082 | /** |
| 1083 | * Calculates the size of the H264 header that needs to remain |
| 1084 | * unencrypted for Jitsi Videobridge to properly process the packet. |
| 1085 | * |
| 1086 | * This function works with WebRTC's Annex B format H.264 frames and ensures |
| 1087 | * the PPS ID is included in the unencrypted portion. |
| 1088 | * |
| 1089 | * @param frame The H264 RTP payload in Annex B format |
| 1090 | * @return The size of the header that must remain unencrypted |
| 1091 | */ |
| 1092 | uint32_t calculateH264FramePlaintextHeaderSize(rtc::ArrayView<const uint8_t> frame) { |
| 1093 | if (frame.empty()) { |
| 1094 | return 0; |
| 1095 | } |
| 1096 |
| 1097 | // Find all NAL units in the frame |
| 1098 | std::vector<webrtc::H264::NaluIndex> naluIndices = |
| 1099 | webrtc::H264::FindNaluIndices(frame.data(), frame.size()); |
| 1100 |
| 1101 | if (naluIndices.empty()) { |
| 1102 | // No valid NAL units found |
| 1103 | return 0; |
| 1104 | } |
| 1105 |
| 1106 | // Track the maximum offset we need to keep unencrypted |
| 1107 | size_t maxOffset = 0; |
| 1108 |
| 1109 | for (const auto& naluIndex : naluIndices) { |
| 1110 | // Start by including the start code and NAL header |
| 1111 | size_t headerEndOffset = naluIndex.payload_start_offset + kNalHeaderSize; |
| 1112 |
| 1113 | // Check if we have enough data to read the NAL unit type |
| 1114 | if (naluIndex.payload_size >= kNalHeaderSize) { |
| 1115 | // Get NAL unit type from the first byte after start code |
| 1116 | uint8_t nalType = frame[naluIndex.payload_start_offset] & kTypeMask; |
| 1117 |
| 1118 | // Extend header size based on NAL unit type |
| 1119 | if (nalType == kFuA) { |
| 1120 | // For fragmented units, we need the FU header as well |
| 1121 | if (naluIndex.payload_size >= kFuAHeaderSize) { |
| 1122 | headerEndOffset = naluIndex.payload_start_offset + kFuAHeaderSize; |
| 1123 |
| 1124 | // For the first fragment, we also need to include PPS ID |
| 1125 | bool isStartBit = (frame[naluIndex.payload_start_offset + 1] & 0x80) != 0; |
| 1126 | if (isStartBit) { |
| 1127 | // Get original NAL type from the FU header |
| 1128 | uint8_t originalNalType = frame[naluIndex.payload_start_offset + 1] & kTypeMask; |
| 1129 |
| 1130 | // If this is an IDR or non-IDR slice, include enough for PPS ID |
| 1131 | if (originalNalType == kIdr || originalNalType == 1) { |
| 1132 | // Add extra bytes to include PPS ID (typical size: 1-3 bytes after FU header) |
| 1133 | headerEndOffset += 4; // Conservative estimate |
| 1134 | } |
| 1135 | } |
| 1136 | } |
| 1137 | } else if (nalType == kStapA) { |
| 1138 | // For aggregation packets, we need the STAP-A header and first NAL's length field |
| 1139 | if (naluIndex.payload_size >= kStapAHeaderSize) { |
| 1140 | headerEndOffset = naluIndex.payload_start_offset + kStapAHeaderSize; |
| 1141 |
| 1142 | // Try to get the type of the first aggregated NAL |
| 1143 | if (naluIndex.payload_size > kStapAHeaderSize) { |
| 1144 | uint8_t firstNalType = frame[naluIndex.payload_start_offset + kStapAHeaderSize] & kTypeMask; |
| 1145 |
| 1146 | // If this is an IDR or non-IDR slice, include enough for PPS ID |
| 1147 | if (firstNalType == kIdr || firstNalType == 1) { |
| 1148 | // Add extra bytes to include PPS ID |
| 1149 | headerEndOffset += 4; // Conservative estimate |
| 1150 | } |
| 1151 | } |
| 1152 | } |
| 1153 | } |
| 1154 | // For slice NAL units (IDR=5 or non-IDR=1), include PPS ID |
| 1155 | else if (nalType == kIdr || nalType == 1) { |
| 1156 | // Calculate bytes needed to include PPS ID |
| 1157 | size_t ppsIdBytes = calculateSliceHeaderBytesForPpsId( |
| 1158 | frame.data() + naluIndex.payload_start_offset, |
| 1159 | naluIndex.payload_size); |
| 1160 |
| 1161 | headerEndOffset = naluIndex.payload_start_offset + ppsIdBytes; |
| 1162 | maxOffset = std::max(maxOffset, headerEndOffset); |
| 1163 | break; |
| 1164 | } |
| 1165 | // For keyframe related NAL units, ensure we keep their header |
| 1166 | else if (nalType == kSps || nalType == kPps || nalType == kSei) { |
| 1167 | // SPS and PPS need to be kept entirely in plaintext |
| 1168 | headerEndOffset = naluIndex.payload_start_offset + naluIndex.payload_size; |
| 1169 | } |
| 1170 | } |
| 1171 |
| 1172 | // Update the maximum offset |
| 1173 | maxOffset = std::max(maxOffset, headerEndOffset); |
| 1174 | } |
| 1175 |
| 1176 | return static_cast<uint32_t>(maxOffset); |
| 1177 | } |
| 1178 |
| 1179 | // VP8 Payload Header constants |
| 1180 | constexpr uint8_t P_BIT = 0x01; // Inverse key frame flag (0=key frame, 1=delta frame) |
| 1181 | // In bit position 0 |
| 1182 |
| 1183 | /** |
| 1184 | * Calculates the size of the VP8 header that needs to remain |
| 1185 | * unencrypted for proper frame handling. |
| 1186 | * |
| 1187 | * For VP8: |
| 1188 | * - If it's a key frame (P=0), leave 10 bytes unencrypted to cover the full uncompressed VP8 header |
| 1189 | * - If it's a delta frame (P=1), leave 1 byte unencrypted (just the payload header) |
| 1190 | * |
| 1191 | * Based on VP8 payload header format in RFC 7741 section 4.3: |
| 1192 | * 0 1 2 3 4 5 6 7 |
| 1193 | * +-+-+-+-+-+-+-+-+ |
| 1194 | * |Size0|H| VER |P| |
| 1195 | * +-+-+-+-+-+-+-+-+ |
| 1196 | * The diagram shows bit positions where P is at position 7 (leftmost bit). |
| 1197 | * |
| 1198 | * @param frame The VP8 payload data (after RTP header and VP8 payload descriptor) |
| 1199 | * @return The size of the header that must remain unencrypted |
| 1200 | */ |
| 1201 | uint32_t calculateVp8FramePlaintextHeaderSize(rtc::ArrayView<const uint8_t> frame) { |
| 1202 | // Ensure we have at least 1 byte |
| 1203 | if (frame.empty()) { |
| 1204 | return 0; |
| 1205 | } |
| 1206 |
| 1207 | // First byte of VP8 payload header |
| 1208 | uint8_t first_byte = frame[0]; |
| 1209 |
| 1210 | // Check P bit (inverse key frame flag) - bit 7 (0x80) |
| 1211 | bool is_key_frame = (first_byte & P_BIT) == 0; |
| 1212 |
| 1213 | if (is_key_frame) { |
| 1214 | // For key frames, leave 10 bytes unencrypted to cover the full uncompressed VP8 header |
| 1215 | // This includes the frame dimensions |
| 1216 | return frame.size() >= 10 ? 10 : ((uint32_t)frame.size()); |
| 1217 | } else { |
| 1218 | // For delta frames, just leave 1 byte unencrypted (payload header) |
| 1219 | return 1; |
| 1220 | } |
| 1221 | } |
| 1222 |
| 1223 | enum class FrameTransformerPayloadType { |
| 1224 | Unknown, |
| 1225 | Opus, |
| 1226 | H264, |
| 1227 | VP8 |
| 1228 | }; |
| 1229 |
| 1230 | class FrameTransformer : public webrtc::FrameTransformerInterface { |
| 1231 | public: |
| 1232 | FrameTransformer(bool isEncryptor, std::function<std::vector<uint8_t>(std::vector<uint8_t> const &, int64_t, bool, int32_t)> transform, int64_t userId, std::map<int32_t, FrameTransformerPayloadType> const &payloadTypeMapping, std::function<std::pair<uint8_t, bool>()> getAudioLevelAndSpeech, std::function<void(uint8_t, bool)> setAudioLevelAndSpeech) : |
| 1233 | _isEncryptor(isEncryptor), |
| 1234 | _transform(transform), |
| 1235 | _userId(userId), |
| 1236 | _payloadTypeMapping(payloadTypeMapping), |
| 1237 | _getAudioLevelAndSpeech(getAudioLevelAndSpeech), |
| 1238 | _setAudioLevelAndSpeech(setAudioLevelAndSpeech) { |
| 1239 | } |
| 1240 |
| 1241 | virtual void RegisterTransformedFrameCallback(rtc::scoped_refptr<webrtc::TransformedFrameCallback> callback) override { |
| 1242 | webrtc::MutexLock lock(&_mutex); |
| 1243 | assert(_sinkCallback == nullptr); |
| 1244 | _sinkCallback = callback; |
| 1245 | } |
| 1246 |
| 1247 | virtual void RegisterTransformedFrameSinkCallback(rtc::scoped_refptr<webrtc::TransformedFrameCallback> callback, uint32_t ssrc) override { |
| 1248 | webrtc::MutexLock lock(&_mutex); |
| 1249 | _sinkCallbackBySsrc[ssrc] = callback; |
| 1250 | } |
| 1251 |
| 1252 | virtual void UnregisterTransformedFrameSinkCallback(uint32_t ssrc) override { |
| 1253 | webrtc::MutexLock lock(&_mutex); |
| 1254 | _sinkCallbackBySsrc.erase(ssrc); |
| 1255 | } |
| 1256 |
| 1257 | virtual void Transform(std::unique_ptr<webrtc::TransformableFrameInterface> frame) override { |
| 1258 | webrtc::MutexLock lock(&_mutex); |
| 1259 |
| 1260 | const auto ssrc = frame->GetSsrc(); |
| 1261 | const auto i = _sinkCallbackBySsrc.find(ssrc); |
| 1262 | const auto sink = (i != _sinkCallbackBySsrc.end() && i->second) |
| 1263 | ? i->second.get() |
| 1264 | : _sinkCallback.get(); |
| 1265 | if (!sink) { |
| 1266 | return; |
| 1267 | } |
| 1268 |
| 1269 | FrameTransformerPayloadType payloadType = FrameTransformerPayloadType::Unknown; |
| 1270 | const auto foundPayloadType = _payloadTypeMapping.find(frame->GetPayloadType()); |
| 1271 | if (foundPayloadType != _payloadTypeMapping.end()) { |
| 1272 | payloadType = foundPayloadType->second; |
| 1273 | } |
| 1274 |
| 1275 | if (_isEncryptor) { |
| 1276 | if (payloadType == FrameTransformerPayloadType::H264 || payloadType == FrameTransformerPayloadType::VP8) { |
| 1277 | uint32_t plaintextHeaderSize = 0; |
| 1278 | if (payloadType == FrameTransformerPayloadType::H264) { |
| 1279 | plaintextHeaderSize = calculateH264FramePlaintextHeaderSize(frame->GetData()); |
| 1280 | } else if (payloadType == FrameTransformerPayloadType::VP8) { |
| 1281 | plaintextHeaderSize = calculateVp8FramePlaintextHeaderSize(frame->GetData()); |
| 1282 | } |
| 1283 |
| 1284 | if (plaintextHeaderSize > (uint32_t)frame->GetData().size()) { |
| 1285 | plaintextHeaderSize = (uint32_t)frame->GetData().size(); |
| 1286 | } |
| 1287 |
| 1288 | std::vector<uint8_t> frameData; |
| 1289 | frameData.resize(frame->GetData().size()); |
| 1290 | std::copy(frame->GetData().begin(), frame->GetData().end(), frameData.begin()); |
| 1291 |
| 1292 | auto result = _transform(frameData, _userId, _isEncryptor, plaintextHeaderSize); |
| 1293 |
| 1294 | if (!result.empty()) { |
| 1295 | frame->SetData(result); |
| 1296 | sink->OnTransformedFrame(std::move(frame)); |
| 1297 | } |
| 1298 | } else { |
| 1299 | std::vector<uint8_t> buffer; |
| 1300 | buffer.resize(frame->GetData().size() + 1 + 1); |
| 1301 | std::copy(frame->GetData().begin(), frame->GetData().end(), buffer.begin()); |
| 1302 |
| 1303 | buffer[buffer.size() - 1 - 1] = 0x01; |
| 1304 | std::pair<uint8_t, bool> audioLevelAndSpeech = std::make_pair(0, false); |
| 1305 | if (_getAudioLevelAndSpeech) { |
| 1306 | audioLevelAndSpeech = _getAudioLevelAndSpeech(); |
| 1307 | } |
| 1308 | uint8_t encodedAudioLevelAndSpeech = 0; |
| 1309 | if (audioLevelAndSpeech.second) { |
| 1310 | encodedAudioLevelAndSpeech = encodedAudioLevelAndSpeech | 0x80; |
| 1311 | } |
| 1312 | encodedAudioLevelAndSpeech |= audioLevelAndSpeech.first & 0x7f; |
| 1313 | buffer[buffer.size() - 1] = encodedAudioLevelAndSpeech; |
| 1314 |
| 1315 | auto result = _transform(buffer, _userId, _isEncryptor, 0); |
| 1316 | if (!result.empty()) { |
| 1317 | frame->SetData(result); |
| 1318 | sink->OnTransformedFrame(std::move(frame)); |
| 1319 | } |
| 1320 | } |
| 1321 | } else { |
| 1322 | if (payloadType != FrameTransformerPayloadType::Opus) { |
| 1323 | std::vector<uint8_t> encryptedFrame; |
| 1324 | encryptedFrame.resize(frame->GetData().size()); |
| 1325 | std::copy(frame->GetData().begin(), frame->GetData().end(), encryptedFrame.begin()); |
| 1326 |
| 1327 | auto decryptedFrame = _transform(encryptedFrame, _userId, false, 0); |
| 1328 | if (!decryptedFrame.empty()) { |
| 1329 | frame->SetData(decryptedFrame); |
| 1330 | sink->OnTransformedFrame(std::move(frame)); |
| 1331 | } |
| 1332 | } else { |
| 1333 | std::vector<uint8_t> buffer; |
| 1334 | buffer.resize(frame->GetData().size()); |
| 1335 | std::copy(frame->GetData().begin(), frame->GetData().end(), buffer.begin()); |
| 1336 |
| 1337 | auto result = _transform(buffer, _userId, false, 0); |
| 1338 | if (!result.empty()) { |
| 1339 | if (result.size() >= 2) { |
| 1340 | uint8_t extensionFlags = result[result.size() - 2]; |
| 1341 | if (extensionFlags & 0x01) { |
| 1342 | uint8_t audioLevelAndSpeech = result[result.size() - 1]; |
| 1343 | if (_setAudioLevelAndSpeech) { |
| 1344 | bool hasSpeech = (audioLevelAndSpeech & 0x80) != 0; |
| 1345 | uint8_t audioLevel = audioLevelAndSpeech & 0x7f; |
| 1346 | _setAudioLevelAndSpeech(audioLevel, hasSpeech); |
| 1347 | } |
| 1348 |
| 1349 | result.resize(result.size() - 2); |
| 1350 | } else { |
| 1351 | result.resize(result.size() - 1); |
| 1352 | } |
| 1353 | } |
| 1354 |
| 1355 | frame->SetData(result); |
| 1356 | sink->OnTransformedFrame(std::move(frame)); |
| 1357 | } |
| 1358 | } |
| 1359 | } |
| 1360 | } |
| 1361 |
| 1362 | private: |
| 1363 | bool _isEncryptor = false; |
| 1364 | std::function<std::vector<uint8_t>(std::vector<uint8_t> const &, int64_t, bool, int32_t)> _transform; |
| 1365 | int64_t _userId = 0; |
| 1366 | std::map<int32_t, FrameTransformerPayloadType> _payloadTypeMapping; |
| 1367 | std::function<std::pair<uint8_t, bool>()> _getAudioLevelAndSpeech; |
| 1368 | std::function<void(uint8_t, bool)> _setAudioLevelAndSpeech; |
| 1369 | webrtc::Mutex _mutex; |
| 1370 | rtc::scoped_refptr<webrtc::TransformedFrameCallback> _sinkCallback; |
| 1371 | std::map<uint32_t, rtc::scoped_refptr<webrtc::TransformedFrameCallback>> _sinkCallbackBySsrc; |
| 1372 | }; |
| 1373 |
| 1374 | class IncomingAudioChannel : public sigslot::has_slots<> { |
| 1375 | public: |
| 1376 | IncomingAudioChannel( |
| 1377 | ChannelManager *channelManager, |
| 1378 | webrtc::Call *call, |
| 1379 | webrtc::RtpTransport *rtpTransport, |
| 1380 | rtc::UniqueRandomIdGenerator *randomIdGenerator, |
| 1381 | bool isRawPcm, |
| 1382 | ChannelId ssrc, |
| 1383 | int64_t userId, |
| 1384 | std::function<void(AudioSinkImpl::Update)> &&onAudioLevelUpdated, |
| 1385 | std::function<void(uint32_t, const AudioFrame &)> onAudioFrame, |
| 1386 | std::shared_ptr<Threads> threads, |
| 1387 | std::function<std::vector<uint8_t>(std::vector<uint8_t> const &, int64_t, bool, int32_t)> e2eEncryptDecrypt, |
| 1388 | std::map<int32_t, FrameTransformerPayloadType> const &payloadTypeMapping, |
| 1389 | std::function<void(uint32_t, uint8_t, bool)> setAudioLevelAndSpeech) : |
| 1390 | _threads(threads), |
| 1391 | _ssrc(ssrc), |
| 1392 | _channelManager(channelManager), |
| 1393 | _call(call) { |
| 1394 | _creationTimestamp = rtc::TimeMillis(); |
| 1395 |
| 1396 | threads->getWorkerThread()->BlockingCall([this, rtpTransport, ssrc, onAudioFrame = std::move(onAudioFrame), onAudioLevelUpdated = std::move(onAudioLevelUpdated), isRawPcm, userId, e2eEncryptDecrypt, payloadTypeMapping, setAudioLevelAndSpeech]() mutable { |
| 1397 | cricket::AudioOptions audioOptions; |
| 1398 | audioOptions.audio_jitter_buffer_fast_accelerate = true; |
| 1399 | audioOptions.audio_jitter_buffer_min_delay_ms = 50; |
| 1400 |
| 1401 | std::string streamId = std::string("stream") + ssrc.name(); |
| 1402 |
| 1403 | _audioChannel = _channelManager->CreateVoiceChannel(_call, cricket::MediaConfig(), std::string("audio") + uint32ToString(ssrc.networkSsrc), false, GroupNetworkManager::getDefaulCryptoOptions(), audioOptions); |
| 1404 |
| 1405 | _threads->getNetworkThread()->BlockingCall([&]() { |
| 1406 | _audioChannel->SetRtpTransport(rtpTransport); |
| 1407 | }); |
| 1408 |
| 1409 | const uint8_t opusPTimeMs = 120; |
| 1410 |
| 1411 | cricket::AudioCodec opusCodec = cricket::CreateAudioCodec(111, "opus", 48000, 2); |
| 1412 | opusCodec.SetParam(cricket::kCodecParamUseInbandFec, 1); |
| 1413 | opusCodec.SetParam(cricket::kCodecParamPTime, opusPTimeMs); |
| 1414 |
| 1415 | cricket::AudioCodec pcmCodec = cricket::CreateAudioCodec(112, "l16", 48000, 1); |
| 1416 |
| 1417 | auto outgoingAudioDescription = std::make_unique<cricket::AudioContentDescription>(); |
| 1418 | if (!isRawPcm) { |
| 1419 | outgoingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAudioLevelUri, 1)); |
| 1420 | outgoingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAbsSendTimeUri, 2)); |
| 1421 | outgoingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kTransportSequenceNumberUri, 3)); |
| 1422 | } |
| 1423 | outgoingAudioDescription->set_rtcp_mux(true); |
| 1424 | outgoingAudioDescription->set_rtcp_reduced_size(true); |
| 1425 | outgoingAudioDescription->set_direction(webrtc::RtpTransceiverDirection::kRecvOnly); |
| 1426 | outgoingAudioDescription->set_codecs({ opusCodec, pcmCodec }); |
| 1427 | outgoingAudioDescription->set_bandwidth(1300000); |
| 1428 |
| 1429 | auto incomingAudioDescription = std::make_unique<cricket::AudioContentDescription>(); |
| 1430 | if (!isRawPcm) { |
| 1431 | incomingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAudioLevelUri, 1)); |
| 1432 | incomingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAbsSendTimeUri, 2)); |
| 1433 | incomingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kTransportSequenceNumberUri, 3)); |
| 1434 | } |
| 1435 | incomingAudioDescription->set_rtcp_mux(true); |
| 1436 | incomingAudioDescription->set_rtcp_reduced_size(true); |
| 1437 | incomingAudioDescription->set_direction(webrtc::RtpTransceiverDirection::kSendOnly); |
| 1438 | incomingAudioDescription->set_codecs({ opusCodec, pcmCodec }); |
| 1439 | incomingAudioDescription->set_bandwidth(1300000); |
| 1440 | cricket::StreamParams streamParams = cricket::StreamParams::CreateLegacy(ssrc.networkSsrc); |
| 1441 | streamParams.set_stream_ids({ streamId }); |
| 1442 | incomingAudioDescription->AddStream(streamParams); |
| 1443 |
| 1444 | std::string errorDesc; |
| 1445 | _audioChannel->SetPayloadTypeDemuxingEnabled(false); |
| 1446 | _audioChannel->SetLocalContent(outgoingAudioDescription.get(), webrtc::SdpType::kOffer, errorDesc); |
| 1447 | _audioChannel->SetRemoteContent(incomingAudioDescription.get(), webrtc::SdpType::kAnswer, errorDesc); |
| 1448 |
| 1449 | outgoingAudioDescription.reset(); |
| 1450 | incomingAudioDescription.reset(); |
| 1451 |
| 1452 | if (e2eEncryptDecrypt) { |
| 1453 | _audioChannel->receive_channel()->SetDepacketizerToDecoderFrameTransformer(_ssrc.networkSsrc, rtc::make_ref_counted<FrameTransformer>(false, e2eEncryptDecrypt, userId, payloadTypeMapping, nullptr, [ssrc, setAudioLevelAndSpeech](uint8_t audioLevel, bool hasSpeech) { |
| 1454 | setAudioLevelAndSpeech(ssrc.networkSsrc, audioLevel, hasSpeech); |
| 1455 | })); |
| 1456 | } |
| 1457 |
| 1458 | if (_ssrc.actualSsrc != 1) { |
| 1459 | std::unique_ptr<AudioSinkImpl> audioLevelSink(new AudioSinkImpl(std::move(onAudioLevelUpdated), _ssrc, std::move(onAudioFrame))); |
| 1460 | _audioChannel->receive_channel()->SetRawAudioSink(ssrc.networkSsrc, std::move(audioLevelSink)); |
| 1461 | } |
| 1462 | }); |
| 1463 |
| 1464 | _audioChannel->Enable(true); |
| 1465 | } |
| 1466 |
| 1467 | ~IncomingAudioChannel() { |
| 1468 | _threads->getNetworkThread()->BlockingCall([&]() { |
| 1469 | _audioChannel->SetRtpTransport(nullptr); |
| 1470 | }); |
| 1471 | _threads->getWorkerThread()->BlockingCall([this]() { |
| 1472 | _channelManager->DestroyChannel(_audioChannel); |
| 1473 | _audioChannel = nullptr; |
| 1474 | }); |
| 1475 | } |
| 1476 |
| 1477 | void setVolume(double value) { |
| 1478 | _threads->getWorkerThread()->BlockingCall([this, value]() { |
| 1479 | _audioChannel->receive_channel()->SetOutputVolume(_ssrc.networkSsrc, value); |
| 1480 | }); |
| 1481 | } |
| 1482 |
| 1483 | void updateActivity() { |
| 1484 | _activityTimestamp = rtc::TimeMillis(); |
| 1485 | } |
| 1486 |
| 1487 | int64_t getActivity() { |
| 1488 | return _activityTimestamp; |
| 1489 | } |
| 1490 |
| 1491 | private: |
| 1492 | void OnSentPacket_w(const rtc::SentPacket& sent_packet) { |
| 1493 | _call->OnSentPacket(sent_packet); |
| 1494 | } |
| 1495 |
| 1496 | private: |
| 1497 | std::shared_ptr<Threads> _threads; |
| 1498 | ChannelId _ssrc; |
| 1499 | // Memory is managed by _channelManager |
| 1500 | cricket::VoiceChannel *_audioChannel = nullptr; |
| 1501 | // Memory is managed externally |
| 1502 | ChannelManager *_channelManager = nullptr; |
| 1503 | webrtc::Call *_call = nullptr; |
| 1504 | int64_t _creationTimestamp = 0; |
| 1505 | int64_t _activityTimestamp = 0; |
| 1506 | }; |
| 1507 |
| 1508 | class IncomingVideoChannel : public sigslot::has_slots<> { |
| 1509 | public: |
| 1510 | IncomingVideoChannel( |
| 1511 | ChannelManager *channelManager, |
| 1512 | webrtc::Call *call, |
| 1513 | webrtc::RtpTransport *rtpTransport, |
| 1514 | rtc::UniqueRandomIdGenerator *randomIdGenerator, |
| 1515 | std::vector<webrtc::SdpVideoFormat> const &availableVideoFormats, |
| 1516 | GroupJoinVideoInformation sharedVideoInformation, |
| 1517 | uint32_t audioSsrc, |
| 1518 | int64_t userId, |
| 1519 | VideoChannelDescription::Quality minQuality, |
| 1520 | VideoChannelDescription::Quality maxQuality, |
| 1521 | GroupParticipantVideoInformation const &description, |
| 1522 | std::shared_ptr<Threads> threads, |
| 1523 | std::function<std::vector<uint8_t>(std::vector<uint8_t> const &, int64_t, bool, int32_t)> e2eEncryptDecrypt, |
| 1524 | std::map<int32_t, FrameTransformerPayloadType> const &payloadTypeMapping) : |
| 1525 | _threads(threads), |
| 1526 | _endpointId(description.endpointId), |
| 1527 | _channelManager(channelManager), |
| 1528 | _call(call), |
| 1529 | _requestedMinQuality(minQuality), |
| 1530 | _requestedMaxQuality(maxQuality) { |
| 1531 | _videoSink.reset(new VideoSinkImpl(_endpointId)); |
| 1532 |
| 1533 | _threads->getWorkerThread()->BlockingCall([this, rtpTransport, &availableVideoFormats, &description, randomIdGenerator, e2eEncryptDecrypt, userId, payloadTypeMapping]() mutable { |
| 1534 | uint32_t mid = randomIdGenerator->GenerateId(); |
| 1535 | std::string streamId = std::string("video") + uint32ToString(mid); |
| 1536 |
| 1537 | _videoBitrateAllocatorFactory = webrtc::CreateBuiltinVideoBitrateAllocatorFactory(); |
| 1538 |
| 1539 | auto payloadTypes = assignPayloadTypes(availableVideoFormats); |
| 1540 | std::vector<cricket::VideoCodec> codecs; |
| 1541 | for (const auto &payloadType : payloadTypes) { |
| 1542 | codecs.push_back(payloadType.videoCodec); |
| 1543 | if (payloadType.rtxCodec) { |
| 1544 | codecs.push_back(payloadType.rtxCodec.value()); |
| 1545 | } |
| 1546 | } |
| 1547 |
| 1548 | auto outgoingVideoDescription = std::make_unique<cricket::VideoContentDescription>(); |
| 1549 | outgoingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAudioLevelUri, 1)); |
| 1550 | outgoingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAbsSendTimeUri, 2)); |
| 1551 | outgoingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kTransportSequenceNumberUri, 3)); |
| 1552 | outgoingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kVideoRotationUri, 13)); |
| 1553 | outgoingVideoDescription->set_rtcp_mux(true); |
| 1554 | outgoingVideoDescription->set_rtcp_reduced_size(true); |
| 1555 | outgoingVideoDescription->set_direction(webrtc::RtpTransceiverDirection::kRecvOnly); |
| 1556 | outgoingVideoDescription->set_codecs(codecs); |
| 1557 | outgoingVideoDescription->set_bandwidth(1300000); |
| 1558 |
| 1559 | cricket::StreamParams videoRecvStreamParams; |
| 1560 |
| 1561 | std::vector<uint32_t> allSsrcs; |
| 1562 | for (const auto &group : description.ssrcGroups) { |
| 1563 | for (auto ssrc : group.ssrcs) { |
| 1564 | if (std::find(allSsrcs.begin(), allSsrcs.end(), ssrc) == allSsrcs.end()) { |
| 1565 | allSsrcs.push_back(ssrc); |
| 1566 | } |
| 1567 | } |
| 1568 |
| 1569 | if (group.semantics == "SIM") { |
| 1570 | if (_mainVideoSsrc == 0) { |
| 1571 | _mainVideoSsrc = group.ssrcs[0]; |
| 1572 | } |
| 1573 | } |
| 1574 |
| 1575 | cricket::SsrcGroup parsedGroup(group.semantics, group.ssrcs); |
| 1576 | videoRecvStreamParams.ssrc_groups.push_back(parsedGroup); |
| 1577 | } |
| 1578 | videoRecvStreamParams.ssrcs = allSsrcs; |
| 1579 |
| 1580 | if (_mainVideoSsrc == 0) { |
| 1581 | if (description.ssrcGroups.size() == 1) { |
| 1582 | _mainVideoSsrc = description.ssrcGroups[0].ssrcs[0]; |
| 1583 | } |
| 1584 | } |
| 1585 |
| 1586 | videoRecvStreamParams.cname = "cname"; |
| 1587 | videoRecvStreamParams.set_stream_ids({ streamId }); |
| 1588 |
| 1589 | auto incomingVideoDescription = std::make_unique<cricket::VideoContentDescription>(); |
| 1590 | incomingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAudioLevelUri, 1)); |
| 1591 | incomingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAbsSendTimeUri, 2)); |
| 1592 | incomingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kTransportSequenceNumberUri, 3)); |
| 1593 | incomingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kVideoRotationUri, 13)); |
| 1594 | incomingVideoDescription->set_rtcp_mux(true); |
| 1595 | incomingVideoDescription->set_rtcp_reduced_size(true); |
| 1596 | incomingVideoDescription->set_direction(webrtc::RtpTransceiverDirection::kSendOnly); |
| 1597 | incomingVideoDescription->set_codecs(codecs); |
| 1598 | incomingVideoDescription->set_bandwidth(1300000); |
| 1599 |
| 1600 | incomingVideoDescription->AddStream(videoRecvStreamParams); |
| 1601 |
| 1602 | _videoChannel = _channelManager->CreateVideoChannel(_call, cricket::MediaConfig(), std::string("video") + uint32ToString(mid), false, GroupNetworkManager::getDefaulCryptoOptions(), cricket::VideoOptions(), _videoBitrateAllocatorFactory.get()); |
| 1603 |
| 1604 | _threads->getNetworkThread()->BlockingCall([&]() { |
| 1605 | _videoChannel->SetRtpTransport(rtpTransport); |
| 1606 | }); |
| 1607 |
| 1608 | std::string errorDesc; |
| 1609 | _videoChannel->SetLocalContent(outgoingVideoDescription.get(), webrtc::SdpType::kOffer, errorDesc); |
| 1610 | _videoChannel->SetRemoteContent(incomingVideoDescription.get(), webrtc::SdpType::kAnswer, errorDesc); |
| 1611 | _videoChannel->SetPayloadTypeDemuxingEnabled(false); |
| 1612 | _videoChannel->receive_channel()->SetSink(_mainVideoSsrc, _videoSink.get()); |
| 1613 |
| 1614 | if (e2eEncryptDecrypt) { |
| 1615 | _videoChannel->receive_channel()->SetDepacketizerToDecoderFrameTransformer(_mainVideoSsrc, rtc::make_ref_counted<FrameTransformer>(false, e2eEncryptDecrypt, userId, payloadTypeMapping, nullptr, nullptr)); |
| 1616 | } |
| 1617 | }); |
| 1618 |
| 1619 | _videoChannel->Enable(true); |
| 1620 | } |
| 1621 |
| 1622 | ~IncomingVideoChannel() { |
| 1623 | _videoChannel->Enable(false); |
| 1624 | _threads->getNetworkThread()->BlockingCall([&]() { |
| 1625 | _videoChannel->SetRtpTransport(nullptr); |
| 1626 | }); |
| 1627 | _threads->getWorkerThread()->BlockingCall([this]() { |
| 1628 | _channelManager->DestroyChannel(_videoChannel); |
| 1629 | _videoChannel = nullptr; |
| 1630 | }); |
| 1631 | } |
| 1632 |
| 1633 | void addSink(std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> impl) { |
| 1634 | _videoSink->addSink(impl); |
| 1635 | } |
| 1636 |
| 1637 | std::vector<std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>>> getSinks() { |
| 1638 | return _videoSink->getSinks(); |
| 1639 | } |
| 1640 |
| 1641 | std::string const &endpointId() { |
| 1642 | return _endpointId; |
| 1643 | } |
| 1644 |
| 1645 | VideoChannelDescription::Quality requestedMinQuality() { |
| 1646 | return _requestedMinQuality; |
| 1647 | } |
| 1648 |
| 1649 | VideoChannelDescription::Quality requestedMaxQuality() { |
| 1650 | return _requestedMaxQuality; |
| 1651 | } |
| 1652 |
| 1653 | void setRequstedMinQuality(VideoChannelDescription::Quality quality) { |
| 1654 | _requestedMinQuality = quality; |
| 1655 | } |
| 1656 |
| 1657 | void setRequstedMaxQuality(VideoChannelDescription::Quality quality) { |
| 1658 | _requestedMaxQuality = quality; |
| 1659 | } |
| 1660 |
| 1661 | void setStats(absl::optional<GroupInstanceStats::IncomingVideoStats> stats) { |
| 1662 | _stats = stats; |
| 1663 | } |
| 1664 |
| 1665 | absl::optional<GroupInstanceStats::IncomingVideoStats> getStats() { |
| 1666 | return _stats; |
| 1667 | } |
| 1668 |
| 1669 | private: |
| 1670 | void OnSentPacket_w(const rtc::SentPacket& sent_packet) { |
| 1671 | //_call->OnSentPacket(sent_packet); |
| 1672 | } |
| 1673 |
| 1674 | private: |
| 1675 | std::shared_ptr<Threads> _threads; |
| 1676 | uint32_t _mainVideoSsrc = 0; |
| 1677 | std::string _endpointId; |
| 1678 | std::unique_ptr<VideoSinkImpl> _videoSink; |
| 1679 | std::vector<GroupJoinPayloadVideoSourceGroup> _ssrcGroups; |
| 1680 | std::unique_ptr<webrtc::VideoBitrateAllocatorFactory> _videoBitrateAllocatorFactory; |
| 1681 | // Memory is managed by _channelManager |
| 1682 | cricket::VideoChannel *_videoChannel; |
| 1683 | // Memory is managed externally |
| 1684 | ChannelManager *_channelManager = nullptr; |
| 1685 | webrtc::Call *_call = nullptr; |
| 1686 |
| 1687 | VideoChannelDescription::Quality _requestedMinQuality = VideoChannelDescription::Quality::Thumbnail; |
| 1688 | VideoChannelDescription::Quality _requestedMaxQuality = VideoChannelDescription::Quality::Thumbnail; |
| 1689 |
| 1690 | absl::optional<GroupInstanceStats::IncomingVideoStats> _stats; |
| 1691 | }; |
| 1692 |
| 1693 | class MissingSsrcPacketBuffer { |
| 1694 | public: |
| 1695 | MissingSsrcPacketBuffer(int limit) : |
| 1696 | _limit(limit) { |
| 1697 | } |
| 1698 |
| 1699 | ~MissingSsrcPacketBuffer() { |
| 1700 | } |
| 1701 |
| 1702 | void add(uint32_t ssrc, rtc::CopyOnWriteBuffer const &packet) { |
| 1703 | if (_packets.size() == _limit) { |
| 1704 | _packets.erase(_packets.begin()); |
| 1705 | } |
| 1706 | _packets.push_back(std::make_pair(ssrc, packet)); |
| 1707 | } |
| 1708 |
| 1709 | std::vector<rtc::CopyOnWriteBuffer> get(uint32_t ssrc) { |
| 1710 | std::vector<rtc::CopyOnWriteBuffer> result; |
| 1711 | for (auto it = _packets.begin(); it != _packets.end(); ) { |
| 1712 | if (it->first == ssrc) { |
| 1713 | result.push_back(it->second); |
| 1714 | _packets.erase(it); |
| 1715 | } else { |
| 1716 | it++; |
| 1717 | } |
| 1718 | } |
| 1719 | return result; |
| 1720 | } |
| 1721 |
| 1722 | private: |
| 1723 | int _limit = 0; |
| 1724 | std::vector<std::pair<uint32_t, rtc::CopyOnWriteBuffer>> _packets; |
| 1725 |
| 1726 | }; |
| 1727 |
| 1728 | class RequestedBroadcastPart { |
| 1729 | public: |
| 1730 | int64_t timestamp = 0; |
| 1731 | std::shared_ptr<BroadcastPartTask> task; |
| 1732 |
| 1733 | explicit RequestedBroadcastPart(int64_t timestamp_, std::shared_ptr<BroadcastPartTask> task_) : |
| 1734 | timestamp(timestamp_), task(task_) { |
| 1735 | } |
| 1736 | }; |
| 1737 |
| 1738 | struct DecodedBroadcastPart { |
| 1739 | struct DecodedBroadcastPartChannel { |
| 1740 | uint32_t ssrc = 0; |
| 1741 | std::vector<int16_t> pcmData; |
| 1742 | }; |
| 1743 |
| 1744 | DecodedBroadcastPart(int numSamples_, std::vector<DecodedBroadcastPartChannel> &&_channels) : |
| 1745 | numSamples(numSamples_), channels(std::move(_channels)) { |
| 1746 | } |
| 1747 |
| 1748 | int numSamples = 0; |
| 1749 | std::vector<DecodedBroadcastPartChannel> channels; |
| 1750 | }; |
| 1751 |
| 1752 | std::function<webrtc::scoped_refptr<webrtc::VideoTrackSourceInterface>()> videoCaptureToGetVideoSource(std::shared_ptr<VideoCaptureInterface> videoCapture) { |
| 1753 | return [videoCapture]() { |
| 1754 | VideoCaptureInterfaceObject *videoCaptureImpl = GetVideoCaptureAssumingSameThread(videoCapture.get()); |
| 1755 | return videoCaptureImpl ? videoCaptureImpl->source() : nullptr; |
| 1756 | }; |
| 1757 | } |
| 1758 |
| 1759 | class AudioDeviceDataObserverShared { |
| 1760 | public: |
| 1761 | AudioDeviceDataObserverShared() { |
| 1762 | } |
| 1763 |
| 1764 | ~AudioDeviceDataObserverShared() { |
| 1765 | } |
| 1766 |
| 1767 | void setStreamingContext(std::shared_ptr<StreamingMediaContext> streamingContext) { |
| 1768 | _mutex.Lock(); |
| 1769 | _streamingContext = streamingContext; |
| 1770 | _mutex.Unlock(); |
| 1771 | } |
| 1772 |
| 1773 | void mixAudio(int16_t *audio_samples, const size_t num_samples, const size_t num_channels, const uint32_t samples_per_sec) { |
| 1774 | _mutex.Lock(); |
| 1775 | const auto context = _streamingContext; |
| 1776 | _mutex.Unlock(); |
| 1777 |
| 1778 | if (context) { |
| 1779 | if (_samplesToResample.size() < 480 * num_channels) { |
| 1780 | _samplesToResample.resize(480 * num_channels); |
| 1781 | } |
| 1782 | memset(_samplesToResample.data(), 0, _samplesToResample.size() * sizeof(int16_t)); |
| 1783 |
| 1784 | context->getAudio(_samplesToResample.data(), 480, num_channels, 48000); |
| 1785 |
| 1786 | if (_resamplerFrequency != samples_per_sec || _resamplerNumChannels != num_channels) { |
| 1787 | _resamplerFrequency = samples_per_sec; |
| 1788 | _resamplerNumChannels = num_channels; |
| 1789 | _resampler = std::make_unique<webrtc::Resampler>(); |
| 1790 | if (_resampler->Reset(48000, samples_per_sec, num_channels) == -1) { |
| 1791 | _resampler = nullptr; |
| 1792 | } |
| 1793 | } |
| 1794 |
| 1795 | if (_resampler) { |
| 1796 | size_t outLen = 0; |
| 1797 | _resampler->Push(_samplesToResample.data(), _samplesToResample.size(), (int16_t *)audio_samples, num_samples * num_channels, outLen); |
| 1798 | } |
| 1799 | } |
| 1800 | } |
| 1801 |
| 1802 | private: |
| 1803 | webrtc::Mutex _mutex; |
| 1804 | std::unique_ptr<webrtc::Resampler> _resampler; |
| 1805 | uint32_t _resamplerFrequency = 0; |
| 1806 | size_t _resamplerNumChannels = 0; |
| 1807 | std::vector<int16_t> _samplesToResample; |
| 1808 | std::shared_ptr<StreamingMediaContext> _streamingContext; |
| 1809 | }; |
| 1810 |
| 1811 | class AudioDeviceDataObserverImpl : public webrtc::AudioDeviceDataObserver { |
| 1812 | public: |
| 1813 | AudioDeviceDataObserverImpl(std::shared_ptr<AudioDeviceDataObserverShared> shared) : |
| 1814 | _shared(shared) { |
| 1815 | } |
| 1816 |
| 1817 | virtual ~AudioDeviceDataObserverImpl() { |
| 1818 | } |
| 1819 |
| 1820 | virtual void OnCaptureData(const void* audio_samples, |
| 1821 | const size_t num_samples, |
| 1822 | const size_t bytes_per_sample, |
| 1823 | const size_t num_channels, |
| 1824 | const uint32_t samples_per_sec) override { |
| 1825 | } |
| 1826 |
| 1827 | virtual void OnRenderData(const void* audio_samples, |
| 1828 | const size_t num_samples, |
| 1829 | const size_t bytes_per_sample, |
| 1830 | const size_t num_channels, |
| 1831 | const uint32_t samples_per_sec) override { |
| 1832 | if (bytes_per_sample != num_channels * 2) { |
| 1833 | return; |
| 1834 | } |
| 1835 | if (samples_per_sec % 100 != 0) { |
| 1836 | return; |
| 1837 | } |
| 1838 | if (num_samples != samples_per_sec / 100) { |
| 1839 | return; |
| 1840 | } |
| 1841 |
| 1842 | if (_shared) { |
| 1843 | _shared->mixAudio((int16_t *)audio_samples, num_samples, num_channels, samples_per_sec); |
| 1844 | } |
| 1845 | } |
| 1846 |
| 1847 | private: |
| 1848 | std::shared_ptr<AudioDeviceDataObserverShared> _shared; |
| 1849 | }; |
| 1850 |
| 1851 | class CustomNetEqFactory: public webrtc::NetEqFactory { |
| 1852 | public: |
| 1853 | virtual ~CustomNetEqFactory() = default; |
| 1854 |
| 1855 | std::unique_ptr<webrtc::NetEq> CreateNetEq( |
| 1856 | const webrtc::NetEq::Config& config, |
| 1857 | const webrtc::scoped_refptr<webrtc::AudioDecoderFactory>& decoder_factory, webrtc::Clock* clock |
| 1858 | ) const override { |
| 1859 | webrtc::NetEq::Config updatedConfig = config; |
| 1860 | updatedConfig.sample_rate_hz = 48000; |
| 1861 | return webrtc::DefaultNetEqFactory().CreateNetEq(updatedConfig, decoder_factory, clock); |
| 1862 | } |
| 1863 | }; |
| 1864 |
| 1865 | std::unique_ptr<webrtc::NetEqFactory> createNetEqFactory() { |
| 1866 | return std::make_unique<CustomNetEqFactory>(); |
| 1867 | } |
| 1868 |
| 1869 | class CustomEchoDetector : public webrtc::EchoDetector { |
| 1870 | public: |
| 1871 | // (Re-)Initializes the submodule. |
| 1872 | virtual void Initialize(int capture_sample_rate_hz, |
| 1873 | int num_capture_channels, |
| 1874 | int render_sample_rate_hz, |
| 1875 | int num_render_channels) override { |
| 1876 | } |
| 1877 |
| 1878 | // Analysis (not changing) of the render signal. |
| 1879 | virtual void AnalyzeRenderAudio(rtc::ArrayView<const float> render_audio) override { |
| 1880 | } |
| 1881 |
| 1882 | // Analysis (not changing) of the capture signal. |
| 1883 | virtual void AnalyzeCaptureAudio( |
| 1884 | rtc::ArrayView<const float> capture_audio) override { |
| 1885 | } |
| 1886 |
| 1887 | // Collect current metrics from the echo detector. |
| 1888 | virtual Metrics GetMetrics() const override { |
| 1889 | return webrtc::EchoDetector::Metrics(); |
| 1890 | } |
| 1891 | }; |
| 1892 |
| 1893 | template<typename T> |
| 1894 | struct StateLogRecord { |
| 1895 | int64_t timestamp = 0; |
| 1896 | T record; |
| 1897 |
| 1898 | explicit StateLogRecord(int32_t timestamp_, T &&record_) : |
| 1899 | timestamp(timestamp_), |
| 1900 | record(std::move(record_)) { |
| 1901 | } |
| 1902 | }; |
| 1903 |
| 1904 | struct NetworkStateLogRecord { |
| 1905 | bool isConnected = false; |
| 1906 | bool isFailed = false; |
| 1907 |
| 1908 | bool operator==(NetworkStateLogRecord const &rhs) const { |
| 1909 | if (isConnected != rhs.isConnected) { |
| 1910 | return false; |
| 1911 | } |
| 1912 | if (isFailed != rhs.isFailed) { |
| 1913 | return false; |
| 1914 | } |
| 1915 |
| 1916 | return true; |
| 1917 | } |
| 1918 | }; |
| 1919 |
| 1920 | struct NetworkBitrateLogRecord { |
| 1921 | int32_t bitrate = 0; |
| 1922 | }; |
| 1923 |
| 1924 | GroupLevelValue mappedAudioLevel(GroupLevelValue const &value) { |
| 1925 | GroupLevelValue result = value; |
| 1926 | result.level = result.level * 2.0f; |
| 1927 | return result; |
| 1928 | } |
| 1929 |
| 1930 | } // namespace |
| 1931 |
| 1932 | class GroupInstanceCustomInternal : public sigslot::has_slots<>, public std::enable_shared_from_this<GroupInstanceCustomInternal> { |
| 1933 | public: |
| 1934 | GroupInstanceCustomInternal(GroupInstanceDescriptor &&descriptor, std::shared_ptr<Threads> threads) : |
| 1935 | _threads(std::move(threads)), |
| 1936 | _statsLogPath(descriptor.statsLogPath), |
| 1937 | _networkStateUpdated(descriptor.networkStateUpdated), |
| 1938 | _signalBarsUpdated(descriptor.signalBarsUpdated), |
| 1939 | _audioLevelsUpdated(descriptor.audioLevelsUpdated), |
| 1940 | _activitiesUpdated(descriptor.ssrcActivityUpdated), |
| 1941 | _onAudioFrame(descriptor.onAudioFrame), |
| 1942 | _requestMediaChannelDescriptions(descriptor.requestMediaChannelDescriptions), |
| 1943 | _requestCurrentTime(descriptor.requestCurrentTime), |
| 1944 | _requestAudioBroadcastPart(descriptor.requestAudioBroadcastPart), |
| 1945 | _requestVideoBroadcastPart(descriptor.requestVideoBroadcastPart), |
| 1946 | _videoCapture(descriptor.videoCapture), |
| 1947 | _videoCaptureSink(new VideoSinkImpl("VideoCapture")), |
| 1948 | _getVideoSource(descriptor.getVideoSource), |
| 1949 | _disableIncomingChannels(descriptor.disableIncomingChannels), |
| 1950 | _useDummyChannel(descriptor.useDummyChannel), |
| 1951 | _outgoingAudioBitrateKbit(descriptor.outgoingAudioBitrateKbit), |
| 1952 | _disableOutgoingAudioProcessing(descriptor.disableOutgoingAudioProcessing), |
| 1953 | #ifdef WEBRTC_IOS |
| 1954 | _disableAudioInput(descriptor.disableAudioInput), |
| 1955 | _enableSystemMute(descriptor.ios_enableSystemMute), |
| 1956 | #endif |
| 1957 | _isConference(descriptor.isConference), |
| 1958 | _minOutgoingVideoBitrateKbit(descriptor.minOutgoingVideoBitrateKbit), |
| 1959 | _videoContentType(descriptor.videoContentType), |
| 1960 | _videoCodecPreferences(std::move(descriptor.videoCodecPreferences)), |
| 1961 | _e2eEncryptDecrypt(descriptor.e2eEncryptDecrypt), |
| 1962 | _eventLog(std::make_unique<webrtc::RtcEventLogNull>()), |
| 1963 | _webrtcEnvironment(webrtc::EnvironmentFactory().Create()), |
| 1964 | _netEqFactory(createNetEqFactory()), |
| 1965 | _createAudioDeviceModule(descriptor.createAudioDeviceModule), |
| 1966 | _createWrappedAudioDeviceModule(descriptor.createWrappedAudioDeviceModule), |
| 1967 | _initialInputDeviceId(std::move(descriptor.initialInputDeviceId)), |
| 1968 | _initialOutputDeviceId(std::move(descriptor.initialOutputDeviceId)), |
| 1969 | _missingPacketBuffer(50), |
| 1970 | _onMutedSpeechActivityDetected(std::move(descriptor.onMutedSpeechActivityDetected)), |
| 1971 | _platformContext(descriptor.platformContext) { |
| 1972 | assert(_threads->getMediaThread()->IsCurrent()); |
| 1973 |
| 1974 | _threads->getWorkerThread()->BlockingCall([this] { |
| 1975 | _workerThreadSafery = webrtc::PendingTaskSafetyFlag::Create(); |
| 1976 | }); |
| 1977 | _threads->getNetworkThread()->BlockingCall([this] { |
| 1978 | _networkThreadSafery = webrtc::PendingTaskSafetyFlag::Create(); |
| 1979 | }); |
| 1980 |
| 1981 | if (_videoCapture) { |
| 1982 | assert(!_getVideoSource); |
| 1983 | _getVideoSource = videoCaptureToGetVideoSource(std::move(descriptor.videoCapture)); |
| 1984 | } |
| 1985 | generateSsrcs(); |
| 1986 |
| 1987 | _noiseSuppressionConfiguration = std::make_shared<NoiseSuppressionConfiguration>(descriptor.initialEnableNoiseSuppression); |
| 1988 |
| 1989 | _externalAudioRecorder.reset(new ExternalAudioRecorder(&_externalAudioSamples, &_externalAudioSamplesMutex)); |
| 1990 |
| 1991 | _myAudioLevel = std::make_shared<MyAudioLevelHolder>(); |
| 1992 |
| 1993 | if (_e2eEncryptDecrypt) { |
| 1994 | _myAudioLevelAndSpeech = std::make_shared<AudioLevelAndSpeechHolder>(); |
| 1995 | } |
| 1996 | } |
| 1997 |
| 1998 | ~GroupInstanceCustomInternal() { |
| 1999 | _incomingAudioChannels.clear(); |
| 2000 | _incomingVideoChannels.clear(); |
| 2001 | _serverBandwidthProbingVideoSsrc.reset(); |
| 2002 |
| 2003 | destroyOutgoingAudioChannel(); |
| 2004 | destroyOutgoingVideoChannel(); |
| 2005 |
| 2006 | _threads->getNetworkThread()->BlockingCall([this]() { |
| 2007 | _rtpTransport->UnsubscribeSentPacket(this); |
| 2008 | }); |
| 2009 |
| 2010 | _channelManager = nullptr; |
| 2011 |
| 2012 | _threads->getWorkerThread()->BlockingCall([this]() { |
| 2013 | if (_audioDeviceModule) { |
| 2014 | _audioDeviceModule->Stop(); |
| 2015 | _audioDeviceModule = nullptr; |
| 2016 | } |
| 2017 | _call.reset(); |
| 2018 | }); |
| 2019 | } |
| 2020 |
| 2021 | void start() { |
| 2022 | _startTimestamp = rtc::TimeMillis(); |
| 2023 |
| 2024 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 2025 |
| 2026 | webrtc::field_trial::InitFieldTrialsFromString( |
| 2027 | "WebRTC-DataChannel-Dcsctp/Enabled/" |
| 2028 | "WebRTC-Audio-Allocation/min:32kbps,max:32kbps/" |
| 2029 | "WebRTC-Audio-OpusMinPacketLossRate/Enabled-1/" |
| 2030 | "WebRTC-TaskQueuePacer/Enabled/" |
| 2031 | "WebRTC-VP8ConferenceTemporalLayers/1/" |
| 2032 | "WebRTC-Audio-MinimizeResamplingOnMobile/Enabled/" |
| 2033 | "WebRTC-BweLossExperiment/Enabled/" |
| 2034 | ); |
| 2035 |
| 2036 | bool takeAudioLevelFromNetwork = _e2eEncryptDecrypt == nullptr; |
| 2037 |
| 2038 | _networkManager.reset(new ThreadLocalObject<GroupNetworkManager>(_threads->getNetworkThread(), [weak, threads = _threads, takeAudioLevelFromNetwork] () mutable { |
| 2039 | return std::make_shared<GroupNetworkManager>( |
| 2040 | fieldTrialsBasedConfig, |
| 2041 | [=](const GroupNetworkManager::State &state) { |
| 2042 | threads->getMediaThread()->PostTask([=] { |
| 2043 | const auto strong = weak.lock(); |
| 2044 | if (!strong) { |
| 2045 | return; |
| 2046 | } |
| 2047 | strong->setIsRtcConnected(state.isReadyToSendData); |
| 2048 | }); |
| 2049 | }, |
| 2050 | [=](uint32_t ssrc, int payloadType) { |
| 2051 | threads->getMediaThread()->PostTask([weak, ssrc, payloadType]() mutable { |
| 2052 | if (const auto strong = weak.lock()) { |
| 2053 | strong->receiveUnknownSsrcPacket(ssrc, payloadType); |
| 2054 | } |
| 2055 | }); |
| 2056 | }, |
| 2057 | [=](bool isDataChannelOpen) { |
| 2058 | threads->getMediaThread()->PostTask([weak, isDataChannelOpen]() mutable { |
| 2059 | if (const auto strong = weak.lock()) { |
| 2060 | strong->updateIsDataChannelOpen(isDataChannelOpen); |
| 2061 | } |
| 2062 | }); |
| 2063 | }, |
| 2064 | [=](std::string const &message) { |
| 2065 | threads->getMediaThread()->PostTask([weak, message]() { |
| 2066 | if (const auto strong = weak.lock()) { |
| 2067 | strong->receiveDataChannelMessage(message); |
| 2068 | } |
| 2069 | }); |
| 2070 | }, |
| 2071 | [=](uint32_t ssrc, uint8_t audioLevel, bool isSpeech) { |
| 2072 | if (!takeAudioLevelFromNetwork) { |
| 2073 | return; |
| 2074 | } |
| 2075 | threads->getMediaThread()->PostTask([weak, ssrc, audioLevel, isSpeech]() { |
| 2076 | if (const auto strong = weak.lock()) { |
| 2077 | strong->updateSsrcAudioLevel(ssrc, audioLevel, isSpeech); |
| 2078 | } |
| 2079 | }); |
| 2080 | }, |
| 2081 | !takeAudioLevelFromNetwork, |
| 2082 | [=](uint32_t ssrc) { |
| 2083 | threads->getMediaThread()->PostTask([weak, ssrc]() { |
| 2084 | if (const auto strong = weak.lock()) { |
| 2085 | strong->updateSsrcActivity(ssrc); |
| 2086 | } |
| 2087 | }); |
| 2088 | }, threads); |
| 2089 | })); |
| 2090 |
| 2091 | #if USE_RNNOISE |
| 2092 | std::unique_ptr<webrtc::CustomProcessing> audioProcessor = nullptr; |
| 2093 | #endif |
| 2094 | if (_videoContentType != VideoContentType::Screencast) { |
| 2095 | int numChannels = 1; |
| 2096 | #ifdef WEBRTC_IOS |
| 2097 | if (_disableAudioInput) { |
| 2098 | numChannels = 2; |
| 2099 | } |
| 2100 | #endif |
| 2101 | PlatformInterface::SharedInstance()->configurePlatformAudio(numChannels); |
| 2102 |
| 2103 | #if USE_RNNOISE |
| 2104 | audioProcessor = std::make_unique<AudioCapturePostProcessor>([myAudioLevel = _myAudioLevel](GroupLevelValue const &level) { |
| 2105 | if (myAudioLevel) { |
| 2106 | myAudioLevel->set(level); |
| 2107 | } |
| 2108 | }, _noiseSuppressionConfiguration, nullptr, nullptr); |
| 2109 | #endif |
| 2110 | } else { |
| 2111 | #ifdef WEBRTC_IOS |
| 2112 | audioProcessor = std::make_unique<AudioInjectionPostProcessor>(&_externalAudioSamples, &_externalAudioSamplesMutex); |
| 2113 | #endif |
| 2114 | } |
| 2115 |
| 2116 | _audioDeviceDataObserverShared = std::make_shared<AudioDeviceDataObserverShared>(); |
| 2117 |
| 2118 | _threads->getWorkerThread()->BlockingCall([this, isMuted = _isMuted]() mutable { |
| 2119 | _audioDeviceModule = createAudioDeviceModule(); |
| 2120 | if (!_audioDeviceModule) { |
| 2121 | return; |
| 2122 | } |
| 2123 |
| 2124 | bool isDeviceMuteAvailable = false; |
| 2125 | if (_audioDeviceModule->MicrophoneMuteIsAvailable(&isDeviceMuteAvailable) == 0) { |
| 2126 | if (isDeviceMuteAvailable) { |
| 2127 | _audioDeviceModule->SetMicrophoneMute(isMuted); |
| 2128 | } |
| 2129 | } |
| 2130 | }); |
| 2131 |
| 2132 | webrtc::PeerConnectionFactoryDependencies peerConnectionFactoryDeps; |
| 2133 | peerConnectionFactoryDeps.signaling_thread = _threads->getMediaThread(); |
| 2134 | peerConnectionFactoryDeps.worker_thread = _threads->getWorkerThread(); |
| 2135 | peerConnectionFactoryDeps.network_thread = _threads->getNetworkThread(); |
| 2136 | peerConnectionFactoryDeps.task_queue_factory = webrtc::CreateDefaultTaskQueueFactory(); |
| 2137 | peerConnectionFactoryDeps.network_monitor_factory = PlatformInterface::SharedInstance()->createNetworkMonitorFactory(); |
| 2138 |
| 2139 | peerConnectionFactoryDeps.audio_encoder_factory = webrtc::CreateAudioEncoderFactory<webrtc::AudioEncoderOpus, webrtc::AudioEncoderL16>(); |
| 2140 | peerConnectionFactoryDeps.audio_decoder_factory = webrtc::CreateAudioDecoderFactory<webrtc::AudioDecoderOpus, webrtc::AudioDecoderL16>(); |
| 2141 |
| 2142 | peerConnectionFactoryDeps.video_encoder_factory = PlatformInterface::SharedInstance()->makeVideoEncoderFactory(_platformContext, false, _videoContentType == VideoContentType::Screencast); |
| 2143 | peerConnectionFactoryDeps.video_decoder_factory = PlatformInterface::SharedInstance()->makeVideoDecoderFactory(_platformContext); |
| 2144 |
| 2145 | #if USE_RNNOISE |
| 2146 | if (_audioLevelsUpdated && audioProcessor) { |
| 2147 | webrtc::AudioProcessingBuilder builder; |
| 2148 | builder.SetCapturePostProcessing(std::move(audioProcessor)); |
| 2149 |
| 2150 | builder.SetEchoDetector(rtc::make_ref_counted<CustomEchoDetector>()); |
| 2151 |
| 2152 | peerConnectionFactoryDeps.audio_processing = builder.Create(); |
| 2153 | } |
| 2154 | #endif |
| 2155 |
| 2156 | peerConnectionFactoryDeps.adm = _audioDeviceModule; |
| 2157 |
| 2158 | _availableVideoFormats = filterSupportedVideoFormats(peerConnectionFactoryDeps.video_encoder_factory->GetSupportedFormats()); |
| 2159 |
| 2160 | _payloadTypeMapping.insert(std::make_pair(111, FrameTransformerPayloadType::Opus)); |
| 2161 | auto tempVideoPayloadTypes = assignPayloadTypes(_availableVideoFormats); |
| 2162 | for (const auto &it : tempVideoPayloadTypes) { |
| 2163 | if (it.videoCodec.name == cricket::kVp8CodecName) { |
| 2164 | _payloadTypeMapping.insert(std::make_pair(it.videoCodec.id, FrameTransformerPayloadType::VP8)); |
| 2165 | } else if (it.videoCodec.name == cricket::kH264CodecName) { |
| 2166 | _payloadTypeMapping.insert(std::make_pair(it.videoCodec.id, FrameTransformerPayloadType::H264)); |
| 2167 | } |
| 2168 | } |
| 2169 |
| 2170 | webrtc::EnableMedia(peerConnectionFactoryDeps); |
| 2171 |
| 2172 | auto mediaEngine = peerConnectionFactoryDeps.media_factory->CreateMediaEngine(_webrtcEnvironment, peerConnectionFactoryDeps); |
| 2173 |
| 2174 | _channelManager = ChannelManager::Create( |
| 2175 | std::move(mediaEngine), |
| 2176 | _threads->getWorkerThread(), |
| 2177 | _threads->getNetworkThread() |
| 2178 | ); |
| 2179 |
| 2180 | setAudioInputDevice(_initialInputDeviceId); |
| 2181 | setAudioOutputDevice(_initialOutputDeviceId); |
| 2182 |
| 2183 | _threads->getWorkerThread()->BlockingCall([&]() { |
| 2184 | webrtc::CallConfig callConfig(_webrtcEnvironment, _threads->getNetworkThread()); |
| 2185 | callConfig.neteq_factory = _netEqFactory.get(); |
| 2186 | callConfig.audio_state = _channelManager->media_engine()->voice().GetAudioState(); |
| 2187 | _call = peerConnectionFactoryDeps.media_factory->CreateCall(callConfig); |
| 2188 | }); |
| 2189 |
| 2190 | _uniqueRandomIdGenerator.reset(new rtc::UniqueRandomIdGenerator()); |
| 2191 |
| 2192 | _threads->getNetworkThread()->BlockingCall([this]() { |
| 2193 | _rtpTransport = _networkManager->getSyncAssumingSameThread()->getRtpTransport(); |
| 2194 | _rtpTransport->SubscribeSentPacket(this, [this](const rtc::SentPacket &packet) { |
| 2195 | this->OnSentPacket_w(packet); |
| 2196 | }); |
| 2197 | _rtpTransport->SubscribeRtcpPacketReceived(this, [this](rtc::CopyOnWriteBuffer *packet, int64_t timestamp) { |
| 2198 | this->OnRtcpPacketReceived_n(packet, timestamp); |
| 2199 | }); |
| 2200 | }); |
| 2201 |
| 2202 | _videoBitrateAllocatorFactory = webrtc::CreateBuiltinVideoBitrateAllocatorFactory(); |
| 2203 |
| 2204 | if (_audioLevelsUpdated) { |
| 2205 | beginLevelsTimer(100); |
| 2206 | } |
| 2207 |
| 2208 | if (_getVideoSource) { |
| 2209 | setVideoSource(_getVideoSource, true); |
| 2210 | } |
| 2211 |
| 2212 | if (_useDummyChannel && _videoContentType != VideoContentType::Screencast) { |
| 2213 | addIncomingAudioChannel(ChannelId(1), true); |
| 2214 | } |
| 2215 |
| 2216 | if (_videoContentType == VideoContentType::Screencast) { |
| 2217 | setIsMuted(false); |
| 2218 | } |
| 2219 |
| 2220 | /*if (_videoContentType != VideoContentType::Screencast) { |
| 2221 | createOutgoingAudioChannel(); |
| 2222 | }*/ |
| 2223 |
| 2224 | beginNetworkStatusTimer(0); |
| 2225 | beginLogTimer(0); |
| 2226 | //beginAudioChannelCleanupTimer(0); |
| 2227 |
| 2228 | adjustBitratePreferences(true); |
| 2229 |
| 2230 | beginRemoteConstraintsUpdateTimer(5000); |
| 2231 | } |
| 2232 |
| 2233 | void beginLogTimer(int delayMs) { |
| 2234 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 2235 | _threads->getMediaThread()->PostDelayedTask([weak]() { |
| 2236 | auto strong = weak.lock(); |
| 2237 | if (!strong) { |
| 2238 | return; |
| 2239 | } |
| 2240 |
| 2241 | strong->writeStateLogRecords(); |
| 2242 |
| 2243 | strong->beginLogTimer(1000); |
| 2244 |
| 2245 | //strong->generateVideoKeyframe(); |
| 2246 | }, webrtc::TimeDelta::Millis(delayMs)); |
| 2247 | } |
| 2248 |
| 2249 | void writeStateLogRecords() { |
| 2250 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 2251 | _threads->getWorkerThread()->PostTask([weak]() { |
| 2252 | auto strong = weak.lock(); |
| 2253 | if (!strong) { |
| 2254 | return; |
| 2255 | } |
| 2256 |
| 2257 | auto stats = strong->_call->GetStats(); |
| 2258 | float sendBitrateKbps = ((float)stats.send_bandwidth_bps / 1000.0f); |
| 2259 |
| 2260 | strong->_threads->getMediaThread()->PostTask([weak, sendBitrateKbps]() { |
| 2261 | auto strong = weak.lock(); |
| 2262 | if (!strong) { |
| 2263 | return; |
| 2264 | } |
| 2265 |
| 2266 | float bitrateNorm = 16.0f; |
| 2267 | if (strong->_outgoingVideoChannel) { |
| 2268 | bitrateNorm = 600.0f; |
| 2269 | } |
| 2270 |
| 2271 | float signalBarsNorm = 4.0f; |
| 2272 | float adjustedQuality = sendBitrateKbps / bitrateNorm; |
| 2273 | adjustedQuality = fmaxf(0.0f, adjustedQuality); |
| 2274 | adjustedQuality = fminf(1.0f, adjustedQuality); |
| 2275 | if (strong->_signalBarsUpdated) { |
| 2276 | strong->_signalBarsUpdated((int)(adjustedQuality * signalBarsNorm)); |
| 2277 | } |
| 2278 |
| 2279 | NetworkBitrateLogRecord networkBitrateLogRecord; |
| 2280 | networkBitrateLogRecord.bitrate = (int32_t)sendBitrateKbps; |
| 2281 |
| 2282 | strong->_networkBitrateLogRecords.emplace_back(rtc::TimeMillis(), std::move(networkBitrateLogRecord)); |
| 2283 | }); |
| 2284 | }); |
| 2285 | } |
| 2286 |
| 2287 | void destroyOutgoingVideoChannel() { |
| 2288 | if (!_outgoingVideoChannel) { |
| 2289 | return; |
| 2290 | } |
| 2291 | _outgoingVideoChannel->Enable(false); |
| 2292 | _threads->getNetworkThread()->BlockingCall([&]() { |
| 2293 | _outgoingVideoChannel->SetRtpTransport(nullptr); |
| 2294 | }); |
| 2295 | _threads->getWorkerThread()->BlockingCall([this]() { |
| 2296 | _outgoingVideoChannel->send_channel()->SetVideoSend(_outgoingVideoSsrcs.simulcastLayers[0].ssrc, nullptr, nullptr); |
| 2297 | _channelManager->DestroyChannel(_outgoingVideoChannel); |
| 2298 | }); |
| 2299 | _outgoingVideoChannel = nullptr; |
| 2300 | } |
| 2301 |
| 2302 | void createOutgoingVideoChannel() { |
| 2303 | if (_outgoingVideoChannel |
| 2304 | || _videoContentType == VideoContentType::None) { |
| 2305 | return; |
| 2306 | } |
| 2307 | configureVideoParams(); |
| 2308 |
| 2309 | if (!_selectedPayloadType) { |
| 2310 | RTC_LOG(LS_ERROR) << "Could not select payload type."; |
| 2311 | return; |
| 2312 | } |
| 2313 |
| 2314 | cricket::VideoOptions videoOptions; |
| 2315 | if (_videoContentType == VideoContentType::Screencast) { |
| 2316 | #ifndef WEBRTC_IOS |
| 2317 | videoOptions.is_screencast = true; |
| 2318 | #endif |
| 2319 | } |
| 2320 | _outgoingVideoChannel = _channelManager->CreateVideoChannel(_call.get(), cricket::MediaConfig(), "1", false, GroupNetworkManager::getDefaulCryptoOptions(), videoOptions, _videoBitrateAllocatorFactory.get()); |
| 2321 | _threads->getNetworkThread()->BlockingCall([&]() { |
| 2322 | _outgoingVideoChannel->SetRtpTransport(_rtpTransport); |
| 2323 | }); |
| 2324 |
| 2325 | if (!_outgoingVideoChannel) { |
| 2326 | RTC_LOG(LS_ERROR) << "Could not create outgoing video channel."; |
| 2327 | return; |
| 2328 | } |
| 2329 |
| 2330 | cricket::StreamParams videoSendStreamParams; |
| 2331 |
| 2332 | std::vector<uint32_t> simulcastGroupSsrcs; |
| 2333 | std::vector<cricket::SsrcGroup> fidGroups; |
| 2334 | for (const auto &layer : _outgoingVideoSsrcs.simulcastLayers) { |
| 2335 | simulcastGroupSsrcs.push_back(layer.ssrc); |
| 2336 |
| 2337 | videoSendStreamParams.ssrcs.push_back(layer.ssrc); |
| 2338 | videoSendStreamParams.ssrcs.push_back(layer.fidSsrc); |
| 2339 |
| 2340 | cricket::SsrcGroup fidGroup(cricket::kFidSsrcGroupSemantics, { layer.ssrc, layer.fidSsrc }); |
| 2341 | fidGroups.push_back(fidGroup); |
| 2342 | } |
| 2343 | if (simulcastGroupSsrcs.size() > 1) { |
| 2344 | cricket::SsrcGroup simulcastGroup(cricket::kSimSsrcGroupSemantics, simulcastGroupSsrcs); |
| 2345 | videoSendStreamParams.ssrc_groups.push_back(simulcastGroup); |
| 2346 |
| 2347 | GroupJoinPayloadVideoSourceGroup payloadSimulcastGroup; |
| 2348 | payloadSimulcastGroup.semantics = "SIM"; |
| 2349 | payloadSimulcastGroup.ssrcs = simulcastGroupSsrcs; |
| 2350 | } |
| 2351 |
| 2352 | for (auto fidGroup : fidGroups) { |
| 2353 | videoSendStreamParams.ssrc_groups.push_back(fidGroup); |
| 2354 |
| 2355 | GroupJoinPayloadVideoSourceGroup payloadFidGroup; |
| 2356 | payloadFidGroup.semantics = "FID"; |
| 2357 | payloadFidGroup.ssrcs = fidGroup.ssrcs; |
| 2358 | } |
| 2359 |
| 2360 | videoSendStreamParams.cname = "cname"; |
| 2361 |
| 2362 | auto outgoingVideoDescription = std::make_unique<cricket::VideoContentDescription>(); |
| 2363 | for (const auto &extension : _videoExtensionMap) { |
| 2364 | outgoingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(extension.second, extension.first)); |
| 2365 | } |
| 2366 | outgoingVideoDescription->set_rtcp_mux(true); |
| 2367 | outgoingVideoDescription->set_rtcp_reduced_size(true); |
| 2368 | outgoingVideoDescription->set_direction(webrtc::RtpTransceiverDirection::kSendOnly); |
| 2369 | std::vector<cricket::Codec> outgoingVideoCodecs; |
| 2370 | outgoingVideoCodecs.push_back(_selectedPayloadType->videoCodec); |
| 2371 | if (_selectedPayloadType->rtxCodec) { |
| 2372 | outgoingVideoCodecs.push_back(_selectedPayloadType->rtxCodec.value()); |
| 2373 | } |
| 2374 | outgoingVideoDescription->set_codecs(outgoingVideoCodecs); |
| 2375 | outgoingVideoDescription->set_bandwidth(1300000); |
| 2376 | outgoingVideoDescription->AddStream(videoSendStreamParams); |
| 2377 |
| 2378 | auto incomingVideoDescription = std::make_unique<cricket::VideoContentDescription>(); |
| 2379 | for (const auto &extension : _videoExtensionMap) { |
| 2380 | incomingVideoDescription->AddRtpHeaderExtension(webrtc::RtpExtension(extension.second, extension.first)); |
| 2381 | } |
| 2382 | incomingVideoDescription->set_rtcp_mux(true); |
| 2383 | incomingVideoDescription->set_rtcp_reduced_size(true); |
| 2384 | incomingVideoDescription->set_direction(webrtc::RtpTransceiverDirection::kRecvOnly); |
| 2385 | incomingVideoDescription->set_codecs(outgoingVideoCodecs); |
| 2386 | incomingVideoDescription->set_bandwidth(1300000); |
| 2387 |
| 2388 | _threads->getWorkerThread()->BlockingCall([&]() { |
| 2389 | std::string errorDesc; |
| 2390 | _outgoingVideoChannel->SetRemoteContent(incomingVideoDescription.get(), webrtc::SdpType::kAnswer, errorDesc); |
| 2391 | _outgoingVideoChannel->SetLocalContent(outgoingVideoDescription.get(), webrtc::SdpType::kOffer, errorDesc); |
| 2392 | _outgoingVideoChannel->SetPayloadTypeDemuxingEnabled(false); |
| 2393 |
| 2394 | if (_e2eEncryptDecrypt) { |
| 2395 | for (auto ssrc : simulcastGroupSsrcs) { |
| 2396 | _outgoingVideoChannel->send_channel()->SetEncoderToPacketizerFrameTransformer(ssrc, rtc::make_ref_counted<FrameTransformer>(true, _e2eEncryptDecrypt, int64_t(), _payloadTypeMapping, nullptr, nullptr)); |
| 2397 | } |
| 2398 | } |
| 2399 | }); |
| 2400 |
| 2401 | adjustVideoSendParams(); |
| 2402 | updateVideoSend(); |
| 2403 | } |
| 2404 |
| 2405 | void adjustVideoSendParams() { |
| 2406 | if (!_outgoingVideoChannel) { |
| 2407 | return; |
| 2408 | } |
| 2409 |
| 2410 | if (_videoContentType == VideoContentType::Screencast) { |
| 2411 | _threads->getWorkerThread()->BlockingCall([this]() { |
| 2412 | webrtc::RtpParameters rtpParameters = _outgoingVideoChannel->send_channel()->GetRtpSendParameters(_outgoingVideoSsrcs.simulcastLayers[0].ssrc); |
| 2413 | if (rtpParameters.encodings.size() == 3) { |
| 2414 | for (int i = 0; i < (int)rtpParameters.encodings.size(); i++) { |
| 2415 | if (i == 0) { |
| 2416 | rtpParameters.encodings[i].min_bitrate_bps = 50000; |
| 2417 | rtpParameters.encodings[i].max_bitrate_bps = 100000; |
| 2418 | rtpParameters.encodings[i].scale_resolution_down_by = 4.0; |
| 2419 | rtpParameters.encodings[i].active = _outgoingVideoConstraint >= 180; |
| 2420 | } else if (i == 1) { |
| 2421 | rtpParameters.encodings[i].min_bitrate_bps = 150000; |
| 2422 | rtpParameters.encodings[i].max_bitrate_bps = 200000; |
| 2423 | rtpParameters.encodings[i].scale_resolution_down_by = 2.0; |
| 2424 | rtpParameters.encodings[i].active = _outgoingVideoConstraint >= 360; |
| 2425 | } else if (i == 2) { |
| 2426 | rtpParameters.encodings[i].min_bitrate_bps = 300000; |
| 2427 | rtpParameters.encodings[i].max_bitrate_bps = 800000 + 100000; |
| 2428 | rtpParameters.encodings[i].active = _outgoingVideoConstraint >= 720; |
| 2429 | } |
| 2430 | } |
| 2431 | } else if (rtpParameters.encodings.size() == 2) { |
| 2432 | for (int i = 0; i < (int)rtpParameters.encodings.size(); i++) { |
| 2433 | if (i == 0) { |
| 2434 | rtpParameters.encodings[i].min_bitrate_bps = 50000; |
| 2435 | rtpParameters.encodings[i].max_bitrate_bps = 100000; |
| 2436 | rtpParameters.encodings[i].scale_resolution_down_by = 2.0; |
| 2437 | } else if (i == 1) { |
| 2438 | rtpParameters.encodings[i].min_bitrate_bps = 200000; |
| 2439 | rtpParameters.encodings[i].max_bitrate_bps = 900000 + 100000; |
| 2440 | } |
| 2441 | } |
| 2442 | } else { |
| 2443 | rtpParameters.encodings[0].max_bitrate_bps = (800000 + 100000) * 2; |
| 2444 | } |
| 2445 |
| 2446 | _outgoingVideoChannel->send_channel()->SetRtpSendParameters(_outgoingVideoSsrcs.simulcastLayers[0].ssrc, rtpParameters); |
| 2447 | }); |
| 2448 | } else { |
| 2449 | _threads->getWorkerThread()->BlockingCall([this]() { |
| 2450 | webrtc::RtpParameters rtpParameters = _outgoingVideoChannel->send_channel()->GetRtpSendParameters(_outgoingVideoSsrcs.simulcastLayers[0].ssrc); |
| 2451 | if (rtpParameters.encodings.size() == 3) { |
| 2452 | for (int i = 0; i < (int)rtpParameters.encodings.size(); i++) { |
| 2453 | if (i == 0) { |
| 2454 | rtpParameters.encodings[i].min_bitrate_bps = 50000; |
| 2455 | rtpParameters.encodings[i].max_bitrate_bps = 60000; |
| 2456 | rtpParameters.encodings[i].scale_resolution_down_by = 4.0; |
| 2457 | rtpParameters.encodings[i].active = _outgoingVideoConstraint >= 180; |
| 2458 | } else if (i == 1) { |
| 2459 | rtpParameters.encodings[i].min_bitrate_bps = 100000; |
| 2460 | rtpParameters.encodings[i].max_bitrate_bps = 110000; |
| 2461 | rtpParameters.encodings[i].scale_resolution_down_by = 2.0; |
| 2462 | rtpParameters.encodings[i].active = _outgoingVideoConstraint >= 360; |
| 2463 | } else if (i == 2) { |
| 2464 | rtpParameters.encodings[i].min_bitrate_bps = 300000; |
| 2465 | rtpParameters.encodings[i].max_bitrate_bps = 800000 + 100000; |
| 2466 | rtpParameters.encodings[i].active = _outgoingVideoConstraint >= 720; |
| 2467 | } |
| 2468 | } |
| 2469 | } else if (rtpParameters.encodings.size() == 2) { |
| 2470 | for (int i = 0; i < (int)rtpParameters.encodings.size(); i++) { |
| 2471 | if (i == 0) { |
| 2472 | rtpParameters.encodings[i].min_bitrate_bps = 50000; |
| 2473 | rtpParameters.encodings[i].max_bitrate_bps = 100000; |
| 2474 | rtpParameters.encodings[i].scale_resolution_down_by = 4.0; |
| 2475 | } else if (i == 1) { |
| 2476 | rtpParameters.encodings[i].min_bitrate_bps = 200000; |
| 2477 | rtpParameters.encodings[i].max_bitrate_bps = 900000 + 100000; |
| 2478 | } |
| 2479 | } |
| 2480 | } else { |
| 2481 | rtpParameters.encodings[0].max_bitrate_bps = (800000 + 100000) * 2; |
| 2482 | } |
| 2483 |
| 2484 | _outgoingVideoChannel->send_channel()->SetRtpSendParameters(_outgoingVideoSsrcs.simulcastLayers[0].ssrc, rtpParameters); |
| 2485 | }); |
| 2486 | } |
| 2487 | } |
| 2488 |
| 2489 | void updateVideoSend() { |
| 2490 | if (!_outgoingVideoChannel) { |
| 2491 | return; |
| 2492 | } |
| 2493 |
| 2494 | webrtc::scoped_refptr<webrtc::VideoTrackSourceInterface> videoSource = _getVideoSource ? _getVideoSource() : nullptr; |
| 2495 | if (_getVideoSource) { |
| 2496 | _outgoingVideoChannel->Enable(true); |
| 2497 | } else { |
| 2498 | _outgoingVideoChannel->Enable(false); |
| 2499 | } |
| 2500 | _threads->getWorkerThread()->BlockingCall([this, videoSource]() { |
| 2501 | if (_getVideoSource) { |
| 2502 | _outgoingVideoChannel->send_channel()->SetVideoSend(_outgoingVideoSsrcs.simulcastLayers[0].ssrc, nullptr, videoSource.get()); |
| 2503 | } else { |
| 2504 | _outgoingVideoChannel->send_channel()->SetVideoSend(_outgoingVideoSsrcs.simulcastLayers[0].ssrc, nullptr, nullptr); |
| 2505 | } |
| 2506 | }); |
| 2507 | } |
| 2508 |
| 2509 | void generateVideoKeyframe() { |
| 2510 | if (!_outgoingVideoChannel) { |
| 2511 | return; |
| 2512 | } |
| 2513 | _threads->getWorkerThread()->BlockingCall([this]() { |
| 2514 | auto sendChannel = _outgoingVideoChannel->send_channel(); |
| 2515 | if (!sendChannel) { |
| 2516 | return; |
| 2517 | } |
| 2518 | sendChannel->GenerateSendKeyFrame(_outgoingVideoSsrcs.simulcastLayers[0].ssrc, {}); |
| 2519 | }); |
| 2520 | } |
| 2521 |
| 2522 | void destroyOutgoingAudioChannel() { |
| 2523 | if (!_outgoingAudioChannel) { |
| 2524 | return; |
| 2525 | } |
| 2526 |
| 2527 | _outgoingAudioChannel->Enable(false); |
| 2528 | _threads->getNetworkThread()->BlockingCall([&]() { |
| 2529 | _outgoingAudioChannel->SetRtpTransport(nullptr); |
| 2530 | }); |
| 2531 | _threads->getWorkerThread()->BlockingCall([this]() { |
| 2532 | _outgoingAudioChannel->send_channel()->SetAudioSend(_outgoingAudioSsrc, false, nullptr, &_audioSource); |
| 2533 | _channelManager->DestroyChannel(_outgoingAudioChannel); |
| 2534 | }); |
| 2535 | _outgoingAudioChannel = nullptr; |
| 2536 | } |
| 2537 |
| 2538 | void createOutgoingAudioChannel() { |
| 2539 | if (_outgoingAudioChannel) { |
| 2540 | return; |
| 2541 | } |
| 2542 |
| 2543 | cricket::AudioOptions audioOptions; |
| 2544 | if (_disableOutgoingAudioProcessing || _videoContentType == VideoContentType::Screencast) { |
| 2545 | audioOptions.echo_cancellation = false; |
| 2546 | audioOptions.noise_suppression = false; |
| 2547 | audioOptions.auto_gain_control = false; |
| 2548 | audioOptions.highpass_filter = false; |
| 2549 | //audioOptions.typing_detection = false; |
| 2550 | //audioOptions.residual_echo_detector = false; |
| 2551 | } else { |
| 2552 | audioOptions.echo_cancellation = true; |
| 2553 | audioOptions.noise_suppression = true; |
| 2554 | //audioOptions.residual_echo_detector = true; |
| 2555 | } |
| 2556 |
| 2557 | std::vector<std::string> streamIds; |
| 2558 | streamIds.push_back("1"); |
| 2559 |
| 2560 | _outgoingAudioChannel = _channelManager->CreateVoiceChannel(_call.get(), cricket::MediaConfig(), "0", false, GroupNetworkManager::getDefaulCryptoOptions(), audioOptions); |
| 2561 | _threads->getNetworkThread()->BlockingCall([&]() { |
| 2562 | _outgoingAudioChannel->SetRtpTransport(_rtpTransport); |
| 2563 | }); |
| 2564 |
| 2565 | const uint8_t opusMinBitrateKbps = _outgoingAudioBitrateKbit; |
| 2566 | const uint8_t opusMaxBitrateKbps = _outgoingAudioBitrateKbit; |
| 2567 | const uint8_t opusStartBitrateKbps = _outgoingAudioBitrateKbit; |
| 2568 | const uint8_t opusPTimeMs = 120; |
| 2569 |
| 2570 | cricket::AudioCodec opusCodec = cricket::CreateAudioCodec(111, "opus", 48000, 2); |
| 2571 | opusCodec.AddFeedbackParam(cricket::FeedbackParam(cricket::kRtcpFbParamTransportCc)); |
| 2572 | opusCodec.SetParam(cricket::kCodecParamMinBitrate, opusMinBitrateKbps); |
| 2573 | opusCodec.SetParam(cricket::kCodecParamStartBitrate, opusStartBitrateKbps); |
| 2574 | opusCodec.SetParam(cricket::kCodecParamMaxBitrate, opusMaxBitrateKbps); |
| 2575 | opusCodec.SetParam(cricket::kCodecParamUseInbandFec, 1); |
| 2576 | opusCodec.SetParam(cricket::kCodecParamPTime, opusPTimeMs); |
| 2577 |
| 2578 | auto outgoingAudioDescription = std::make_unique<cricket::AudioContentDescription>(); |
| 2579 | outgoingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAudioLevelUri, 1)); |
| 2580 | outgoingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAbsSendTimeUri, 2)); |
| 2581 | outgoingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kTransportSequenceNumberUri, 3)); |
| 2582 | outgoingAudioDescription->set_rtcp_mux(true); |
| 2583 | outgoingAudioDescription->set_rtcp_reduced_size(true); |
| 2584 | outgoingAudioDescription->set_direction(webrtc::RtpTransceiverDirection::kSendOnly); |
| 2585 | outgoingAudioDescription->set_codecs({ opusCodec }); |
| 2586 | outgoingAudioDescription->set_bandwidth(1300000); |
| 2587 | outgoingAudioDescription->AddStream(cricket::StreamParams::CreateLegacy(_outgoingAudioSsrc)); |
| 2588 |
| 2589 | auto incomingAudioDescription = std::make_unique<cricket::AudioContentDescription>(); |
| 2590 | incomingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAudioLevelUri, 1)); |
| 2591 | incomingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kAbsSendTimeUri, 2)); |
| 2592 | incomingAudioDescription->AddRtpHeaderExtension(webrtc::RtpExtension(webrtc::RtpExtension::kTransportSequenceNumberUri, 3)); |
| 2593 | incomingAudioDescription->set_rtcp_mux(true); |
| 2594 | incomingAudioDescription->set_rtcp_reduced_size(true); |
| 2595 | incomingAudioDescription->set_direction(webrtc::RtpTransceiverDirection::kRecvOnly); |
| 2596 | incomingAudioDescription->set_codecs({ opusCodec }); |
| 2597 | incomingAudioDescription->set_bandwidth(1300000); |
| 2598 |
| 2599 | _threads->getWorkerThread()->BlockingCall([&]() { |
| 2600 | std::string errorDesc; |
| 2601 | _outgoingAudioChannel->SetLocalContent(outgoingAudioDescription.get(), webrtc::SdpType::kOffer, errorDesc); |
| 2602 | _outgoingAudioChannel->SetRemoteContent(incomingAudioDescription.get(), webrtc::SdpType::kAnswer, errorDesc); |
| 2603 | _outgoingAudioChannel->SetPayloadTypeDemuxingEnabled(false); |
| 2604 |
| 2605 | if (_e2eEncryptDecrypt) { |
| 2606 | auto myAudioLevelAndSpeech = _myAudioLevelAndSpeech; |
| 2607 | _outgoingAudioChannel->send_channel()->SetEncoderToPacketizerFrameTransformer(_outgoingAudioSsrc, rtc::make_ref_counted<FrameTransformer>(true, _e2eEncryptDecrypt, int64_t(), _payloadTypeMapping, [myAudioLevelAndSpeech]() -> std::pair<uint8_t, bool> { |
| 2608 | if (myAudioLevelAndSpeech) { |
| 2609 | return myAudioLevelAndSpeech->get(); |
| 2610 | } else { |
| 2611 | return std::make_pair(0, false); |
| 2612 | } |
| 2613 | }, nullptr)); |
| 2614 | } |
| 2615 | }); |
| 2616 |
| 2617 | _outgoingAudioChannel->Enable(true); |
| 2618 |
| 2619 | onUpdatedIsMuted(); |
| 2620 |
| 2621 | adjustBitratePreferences(false); |
| 2622 | } |
| 2623 |
| 2624 | void stop() { |
| 2625 | _networkManager->perform([](GroupNetworkManager *networkManager) { |
| 2626 | networkManager->stop(); |
| 2627 | }); |
| 2628 |
| 2629 | json11::Json::object statsLog; |
| 2630 |
| 2631 | for (int i = (int)_networkStateLogRecords.size() - 1; i >= 1; i--) { |
| 2632 | // coalesce events within 5ms |
| 2633 | if (_networkStateLogRecords[i].timestamp - _networkStateLogRecords[i - 1].timestamp < 5) { |
| 2634 | _networkStateLogRecords.erase(_networkStateLogRecords.begin() + i - 1); |
| 2635 | } |
| 2636 | } |
| 2637 |
| 2638 | for (int i = (int)_remoteNetworkStateLogRecords.size() - 1; i >= 1; i--) { |
| 2639 | // coalesce events within 5ms |
| 2640 | if (_remoteNetworkStateLogRecords[i].timestamp - _remoteNetworkStateLogRecords[i - 1].timestamp < 5) { |
| 2641 | _remoteNetworkStateLogRecords.erase(_remoteNetworkStateLogRecords.begin() + i - 1); |
| 2642 | } |
| 2643 | } |
| 2644 |
| 2645 | json11::Json::array jsonNetworkStateLogRecords; |
| 2646 | int64_t baseTimestamp = 0; |
| 2647 | for (const auto &record : _networkStateLogRecords) { |
| 2648 | json11::Json::object jsonRecord; |
| 2649 |
| 2650 | if (baseTimestamp == 0) { |
| 2651 | baseTimestamp = record.timestamp; |
| 2652 | } |
| 2653 | jsonRecord.insert(std::make_pair("t", json11::Json(std::to_string(record.timestamp - baseTimestamp)))); |
| 2654 | jsonRecord.insert(std::make_pair("c", json11::Json(record.record.isConnected ? 1 : 0))); |
| 2655 | if (record.record.isFailed) { |
| 2656 | jsonRecord.insert(std::make_pair("failed", json11::Json(1))); |
| 2657 | } |
| 2658 |
| 2659 | jsonNetworkStateLogRecords.push_back(std::move(jsonRecord)); |
| 2660 | } |
| 2661 | statsLog.insert(std::make_pair("network", std::move(jsonNetworkStateLogRecords))); |
| 2662 |
| 2663 | json11::Json::array jsonRemoteNetworkStateLogRecords; |
| 2664 | for (const auto &record : _remoteNetworkStateLogRecords) { |
| 2665 | json11::Json::object jsonRecord; |
| 2666 |
| 2667 | jsonRecord.insert(std::make_pair("t", json11::Json(std::to_string(record.timestamp - baseTimestamp)))); |
| 2668 | jsonRecord.insert(std::make_pair("c", json11::Json(record.record.isConnected ? 1 : 0))); |
| 2669 | if (record.record.isFailed) { |
| 2670 | jsonRecord.insert(std::make_pair("failed", json11::Json(1))); |
| 2671 | } |
| 2672 |
| 2673 | jsonRemoteNetworkStateLogRecords.push_back(std::move(jsonRecord)); |
| 2674 | } |
| 2675 | statsLog.insert(std::make_pair("remotenetwork", std::move(jsonRemoteNetworkStateLogRecords))); |
| 2676 |
| 2677 | json11::Json::array jsonNetworkBitrateLogRecords; |
| 2678 | for (const auto &record : _networkBitrateLogRecords) { |
| 2679 | json11::Json::object jsonRecord; |
| 2680 |
| 2681 | jsonRecord.insert(std::make_pair("b", json11::Json(record.record.bitrate))); |
| 2682 |
| 2683 | jsonNetworkBitrateLogRecords.push_back(std::move(jsonRecord)); |
| 2684 | } |
| 2685 | statsLog.insert(std::make_pair("bitrate", std::move(jsonNetworkBitrateLogRecords))); |
| 2686 |
| 2687 | auto jsonStatsLog = json11::Json(std::move(statsLog)); |
| 2688 |
| 2689 | if (!_statsLogPath.empty()) { |
| 2690 | std::ofstream file; |
| 2691 | file.open(_statsLogPath); |
| 2692 |
| 2693 | file << jsonStatsLog.dump(); |
| 2694 |
| 2695 | file.close(); |
| 2696 | } |
| 2697 | } |
| 2698 |
| 2699 | void updateSsrcAudioLevel(uint32_t ssrc, uint8_t audioLevel, bool isSpeech) { |
| 2700 | // Convert from -dBov (0 to -127 dBov) to linear scale |
| 2701 | // audioLevel of 0 means 0 dBov (maximum level) |
| 2702 | // audioLevel of 127 means -127 dBov (minimum level) |
| 2703 | float mappedLevel = pow(10.0f, -audioLevel / 20.0f); |
| 2704 |
| 2705 | auto it = _audioLevels.find(ChannelId(ssrc)); |
| 2706 | if (it != _audioLevels.end()) { |
| 2707 | it->second.value.level = fmax(it->second.value.level, mappedLevel); |
| 2708 | if (isSpeech) { |
| 2709 | it->second.value.voice = true; |
| 2710 | } |
| 2711 | it->second.timestamp = rtc::TimeMillis(); |
| 2712 | } else { |
| 2713 | InternalGroupLevelValue updated; |
| 2714 | updated.value.level = mappedLevel; |
| 2715 | updated.value.voice = isSpeech; |
| 2716 | updated.timestamp = rtc::TimeMillis(); |
| 2717 | _audioLevels.insert(std::make_pair(ChannelId(ssrc), std::move(updated))); |
| 2718 | } |
| 2719 |
| 2720 | auto audioChannel = _incomingAudioChannels.find(ChannelId(ssrc)); |
| 2721 | if (audioChannel != _incomingAudioChannels.end()) { |
| 2722 | audioChannel->second->updateActivity(); |
| 2723 | } |
| 2724 | } |
| 2725 |
| 2726 | void updateSsrcActivity(uint32_t ssrc) { |
| 2727 | auto it = _ssrcActivities.find(ChannelId(ssrc)); |
| 2728 | if (it != _ssrcActivities.end()) { |
| 2729 | it->second.timestamp = rtc::TimeMillis(); |
| 2730 | } else { |
| 2731 | InternalGroupActivityValue updated; |
| 2732 | updated.timestamp = rtc::TimeMillis(); |
| 2733 | _ssrcActivities.insert(std::make_pair(ChannelId(ssrc), std::move(updated))); |
| 2734 | } |
| 2735 | } |
| 2736 |
| 2737 | void beginLevelsTimer(int timeoutMs) { |
| 2738 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 2739 | _threads->getMediaThread()->PostDelayedTask([weak]() { |
| 2740 | auto strong = weak.lock(); |
| 2741 | if (!strong) { |
| 2742 | return; |
| 2743 | } |
| 2744 |
| 2745 | //int64_t timestamp = rtc::TimeMillis(); |
| 2746 | //int64_t maxSampleTimeout = 400; |
| 2747 |
| 2748 | GroupLevelsUpdate levelsUpdate; |
| 2749 | levelsUpdate.updates.reserve(strong->_audioLevels.size() + 1); |
| 2750 | for (auto &it : strong->_audioLevels) { |
| 2751 | uint32_t effectiveSsrc = it.first.actualSsrc; |
| 2752 | if (std::find_if(levelsUpdate.updates.begin(), levelsUpdate.updates.end(), [&](GroupLevelUpdate const &item) { |
| 2753 | return item.ssrc == effectiveSsrc; |
| 2754 | }) != levelsUpdate.updates.end()) { |
| 2755 | continue; |
| 2756 | } |
| 2757 | levelsUpdate.updates.push_back(GroupLevelUpdate{ |
| 2758 | effectiveSsrc, |
| 2759 | mappedAudioLevel(it.second.value), |
| 2760 | }); |
| 2761 | if (it.second.value.level > 0.001f) { |
| 2762 | auto audioChannel = strong->_incomingAudioChannels.find(it.first); |
| 2763 | if (audioChannel != strong->_incomingAudioChannels.end()) { |
| 2764 | audioChannel->second->updateActivity(); |
| 2765 | } |
| 2766 | } |
| 2767 | } |
| 2768 | strong->_audioLevels.clear(); |
| 2769 |
| 2770 | auto myAudioLevel = strong->_myAudioLevel->get(); |
| 2771 | myAudioLevel.isMuted = strong->_isMuted; |
| 2772 | levelsUpdate.updates.push_back(GroupLevelUpdate{ 0, mappedAudioLevel(myAudioLevel) }); |
| 2773 |
| 2774 | GroupActivitiesUpdate activitiesUpdate; |
| 2775 | activitiesUpdate.updates.reserve(strong->_ssrcActivities.size()); |
| 2776 | for (auto &it : strong->_ssrcActivities) { |
| 2777 | uint32_t effectiveSsrc = it.first.actualSsrc; |
| 2778 | if (std::find_if(activitiesUpdate.updates.begin(), activitiesUpdate.updates.end(), [&](GroupActivityUpdate const &item) { |
| 2779 | return item.ssrc == effectiveSsrc; |
| 2780 | }) != activitiesUpdate.updates.end()) { |
| 2781 | continue; |
| 2782 | } |
| 2783 | activitiesUpdate.updates.push_back(GroupActivityUpdate{ |
| 2784 | effectiveSsrc |
| 2785 | }); |
| 2786 | } |
| 2787 | strong->_ssrcActivities.clear(); |
| 2788 |
| 2789 | if (strong->_audioLevelsUpdated) { |
| 2790 | strong->_audioLevelsUpdated(levelsUpdate); |
| 2791 | } |
| 2792 | if (strong->_activitiesUpdated) { |
| 2793 | strong->_activitiesUpdated(activitiesUpdate); |
| 2794 | } |
| 2795 |
| 2796 | if (strong->_myAudioLevelAndSpeech) { |
| 2797 | uint8_t compressedAudioLevel = 0; |
| 2798 |
| 2799 | // Convert from linear scale to -dBov (0 to -127 dBov) |
| 2800 | // audioLevel of 0 means 0 dBov (maximum level) |
| 2801 | // audioLevel of 127 means -127 dBov (minimum level) |
| 2802 | if (myAudioLevel.level > 0.0f) { |
| 2803 | float dBov = 20.0f * log10(myAudioLevel.level); |
| 2804 | compressedAudioLevel = static_cast<uint8_t>(std::clamp(static_cast<int>(-dBov), 0, 127)); |
| 2805 | } else { |
| 2806 | compressedAudioLevel = 127; // Minimum level (-127 dBov) |
| 2807 | } |
| 2808 |
| 2809 | strong->_myAudioLevelAndSpeech->set(compressedAudioLevel, myAudioLevel.voice && !myAudioLevel.isMuted); |
| 2810 | } |
| 2811 | bool isSpeech = myAudioLevel.voice && !myAudioLevel.isMuted; |
| 2812 | strong->_networkManager->perform([isSpeech = isSpeech](GroupNetworkManager *networkManager) { |
| 2813 | networkManager->setOutgoingVoiceActivity(isSpeech); |
| 2814 | }); |
| 2815 |
| 2816 | strong->beginLevelsTimer(100); |
| 2817 | }, webrtc::TimeDelta::Millis(timeoutMs)); |
| 2818 | } |
| 2819 |
| 2820 | void beginAudioChannelCleanupTimer(int delayMs) { |
| 2821 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 2822 | _threads->getMediaThread()->PostDelayedTask([weak]() { |
| 2823 | auto strong = weak.lock(); |
| 2824 | if (!strong) { |
| 2825 | return; |
| 2826 | } |
| 2827 |
| 2828 | auto timestamp = rtc::TimeMillis(); |
| 2829 |
| 2830 | std::vector<ChannelId> removeChannels; |
| 2831 | for (const auto &it : strong->_incomingAudioChannels) { |
| 2832 | if (it.first.networkSsrc == 1) { |
| 2833 | continue; |
| 2834 | } |
| 2835 | auto activity = it.second->getActivity(); |
| 2836 | if (activity < timestamp - 1000) { |
| 2837 | removeChannels.push_back(it.first); |
| 2838 | } |
| 2839 | } |
| 2840 |
| 2841 | for (const auto &channelId : removeChannels) { |
| 2842 | strong->removeIncomingAudioChannel(channelId); |
| 2843 | } |
| 2844 |
| 2845 | strong->beginAudioChannelCleanupTimer(500); |
| 2846 | }, webrtc::TimeDelta::Millis(delayMs)); |
| 2847 | } |
| 2848 |
| 2849 | void beginRemoteConstraintsUpdateTimer(int delayMs) { |
| 2850 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 2851 | _threads->getMediaThread()->PostDelayedTask([weak]() { |
| 2852 | auto strong = weak.lock(); |
| 2853 | if (!strong) { |
| 2854 | return; |
| 2855 | } |
| 2856 |
| 2857 | strong->maybeUpdateRemoteVideoConstraints(); |
| 2858 |
| 2859 | strong->beginRemoteConstraintsUpdateTimer(5000); |
| 2860 | }, webrtc::TimeDelta::Millis(delayMs)); |
| 2861 | } |
| 2862 |
| 2863 | void beginNetworkStatusTimer(int delayMs) { |
| 2864 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 2865 | _threads->getMediaThread()->PostDelayedTask([weak]() { |
| 2866 | auto strong = weak.lock(); |
| 2867 | if (!strong) { |
| 2868 | return; |
| 2869 | } |
| 2870 |
| 2871 | if (strong->_connectionMode == GroupConnectionMode::GroupConnectionModeBroadcast || strong->_broadcastEnabledUntilRtcIsConnectedAtTimestamp) { |
| 2872 | strong->updateBroadcastNetworkStatus(); |
| 2873 | } |
| 2874 |
| 2875 | strong->beginNetworkStatusTimer(500); |
| 2876 | }, webrtc::TimeDelta::Millis(delayMs)); |
| 2877 | } |
| 2878 |
| 2879 | void updateBroadcastNetworkStatus() { |
| 2880 | bool isBroadcastConnected = true; |
| 2881 |
| 2882 | if (isBroadcastConnected != _isBroadcastConnected) { |
| 2883 | _isBroadcastConnected = isBroadcastConnected; |
| 2884 | updateIsConnected(); |
| 2885 | } |
| 2886 | } |
| 2887 |
| 2888 | void configureVideoParams() { |
| 2889 | if (!_sharedVideoInformation) { |
| 2890 | return; |
| 2891 | } |
| 2892 | if (_selectedPayloadType) { |
| 2893 | // Already configured. |
| 2894 | return; |
| 2895 | } |
| 2896 |
| 2897 | _availablePayloadTypes = assignPayloadTypes(_availableVideoFormats); |
| 2898 | if (_availablePayloadTypes.empty()) { |
| 2899 | return; |
| 2900 | } |
| 2901 |
| 2902 | for (const auto &payloadType : _availablePayloadTypes) { |
| 2903 | GroupJoinPayloadVideoPayloadType payload; |
| 2904 | payload.id = payloadType.videoCodec.id; |
| 2905 | payload.name = payloadType.videoCodec.name; |
| 2906 | payload.clockrate = payloadType.videoCodec.clockrate; |
| 2907 | payload.channels = 0; |
| 2908 |
| 2909 | std::vector<GroupJoinPayloadVideoPayloadType::FeedbackType> feedbackTypes; |
| 2910 |
| 2911 | GroupJoinPayloadVideoPayloadType::FeedbackType fbGoogRemb; |
| 2912 | fbGoogRemb.type = "goog-remb"; |
| 2913 | feedbackTypes.push_back(fbGoogRemb); |
| 2914 |
| 2915 | GroupJoinPayloadVideoPayloadType::FeedbackType fbTransportCc; |
| 2916 | fbTransportCc.type = "transport-cc"; |
| 2917 | feedbackTypes.push_back(fbTransportCc); |
| 2918 |
| 2919 | GroupJoinPayloadVideoPayloadType::FeedbackType fbCcmFir; |
| 2920 | fbCcmFir.type = "ccm"; |
| 2921 | fbCcmFir.subtype = "fir"; |
| 2922 | feedbackTypes.push_back(fbCcmFir); |
| 2923 |
| 2924 | GroupJoinPayloadVideoPayloadType::FeedbackType fbNack; |
| 2925 | fbNack.type = "nack"; |
| 2926 | feedbackTypes.push_back(fbNack); |
| 2927 |
| 2928 | GroupJoinPayloadVideoPayloadType::FeedbackType fbNackPli; |
| 2929 | fbNackPli.type = "nack"; |
| 2930 | fbNackPli.subtype = "pli"; |
| 2931 | feedbackTypes.push_back(fbNackPli); |
| 2932 |
| 2933 | payload.feedbackTypes = feedbackTypes; |
| 2934 | payload.parameters = {}; |
| 2935 |
| 2936 | _videoPayloadTypes.push_back(std::move(payload)); |
| 2937 |
| 2938 | if (payloadType.rtxCodec) { |
| 2939 | GroupJoinPayloadVideoPayloadType rtxPayload; |
| 2940 | rtxPayload.id = payloadType.rtxCodec->id; |
| 2941 | rtxPayload.name = payloadType.rtxCodec->name; |
| 2942 | rtxPayload.clockrate = payloadType.rtxCodec->clockrate; |
| 2943 | rtxPayload.parameters.push_back(std::make_pair("apt", intToString(payloadType.videoCodec.id))); |
| 2944 | _videoPayloadTypes.push_back(std::move(rtxPayload)); |
| 2945 | } |
| 2946 | } |
| 2947 |
| 2948 | std::vector<std::string> codecPriorities; |
| 2949 | for (const auto name : _videoCodecPreferences) { |
| 2950 | std::string codecName; |
| 2951 | switch (name) { |
| 2952 | case VideoCodecName::VP8: { |
| 2953 | codecName = cricket::kVp8CodecName; |
| 2954 | break; |
| 2955 | } |
| 2956 | case VideoCodecName::VP9: { |
| 2957 | codecName = cricket::kVp9CodecName; |
| 2958 | break; |
| 2959 | } |
| 2960 | case VideoCodecName::H264: { |
| 2961 | codecName = cricket::kH264CodecName; |
| 2962 | break; |
| 2963 | } |
| 2964 | default: { |
| 2965 | break; |
| 2966 | } |
| 2967 | } |
| 2968 | if (codecName.size() != 0) { |
| 2969 | codecPriorities.push_back(std::move(codecName)); |
| 2970 | } |
| 2971 | } |
| 2972 | std::vector<std::string> defaultCodecPriorities = { |
| 2973 | cricket::kVp8CodecName, |
| 2974 | cricket::kVp9CodecName |
| 2975 | }; |
| 2976 |
| 2977 | bool enableH264 = false; |
| 2978 | for (const auto &payloadType : _sharedVideoInformation->payloadTypes) { |
| 2979 | if (payloadType.name == cricket::kH264CodecName) { |
| 2980 | enableH264 = true; |
| 2981 | break; |
| 2982 | } |
| 2983 | } |
| 2984 | if (enableH264) { |
| 2985 | defaultCodecPriorities.insert(defaultCodecPriorities.begin(), cricket::kH264CodecName); |
| 2986 | } |
| 2987 |
| 2988 | for (const auto &name : defaultCodecPriorities) { |
| 2989 | if (std::find(codecPriorities.begin(), codecPriorities.end(), name) == codecPriorities.end()) { |
| 2990 | codecPriorities.push_back(name); |
| 2991 | } |
| 2992 | } |
| 2993 |
| 2994 | for (const auto &codecName : codecPriorities) { |
| 2995 | if (_selectedPayloadType) { |
| 2996 | break; |
| 2997 | } |
| 2998 | for (const auto &payloadType : _availablePayloadTypes) { |
| 2999 | if (payloadType.videoCodec.name == codecName) { |
| 3000 | _selectedPayloadType = payloadType; |
| 3001 | break; |
| 3002 | } |
| 3003 | } |
| 3004 | } |
| 3005 | if (!_selectedPayloadType) { |
| 3006 | return; |
| 3007 | } |
| 3008 |
| 3009 | _videoExtensionMap.emplace_back(1, webrtc::RtpExtension::kAudioLevelUri); |
| 3010 | _videoExtensionMap.emplace_back(2, webrtc::RtpExtension::kAbsSendTimeUri); |
| 3011 | _videoExtensionMap.emplace_back(3, webrtc::RtpExtension::kTransportSequenceNumberUri); |
| 3012 | _videoExtensionMap.emplace_back(13, webrtc::RtpExtension::kVideoRotationUri); |
| 3013 | } |
| 3014 |
| 3015 | void OnSentPacket_w(const rtc::SentPacket& sent_packet) { |
| 3016 | _call->OnSentPacket(sent_packet); |
| 3017 | } |
| 3018 |
| 3019 | void OnRtcpPacketReceived_n(rtc::CopyOnWriteBuffer *buffer, int64_t packet_time_us) { |
| 3020 | rtc::CopyOnWriteBuffer packet = *buffer; |
| 3021 | if (_call) { |
| 3022 | _threads->getWorkerThread()->PostTask([this, packet]() { |
| 3023 | _call->Receiver()->DeliverRtcpPacket(packet); |
| 3024 | }); |
| 3025 | } |
| 3026 | } |
| 3027 |
| 3028 | void adjustBitratePreferences(bool resetStartBitrate) { |
| 3029 | webrtc::BitrateConstraints preferences; |
| 3030 | webrtc::BitrateSettings settings; |
| 3031 | if (_getVideoSource) { |
| 3032 | settings.min_bitrate_bps = _minOutgoingVideoBitrateKbit * 1024; |
| 3033 | if (resetStartBitrate) { |
| 3034 | preferences.start_bitrate_bps = std::max(preferences.min_bitrate_bps, 400 * 1000); |
| 3035 | } |
| 3036 | if (_videoContentType == VideoContentType::Screencast) { |
| 3037 | preferences.max_bitrate_bps = std::max(preferences.min_bitrate_bps, (1020 + 32) * 1000); |
| 3038 | } else { |
| 3039 | preferences.max_bitrate_bps = std::max(preferences.min_bitrate_bps, (1020 + 32) * 1000); |
| 3040 | } |
| 3041 | } else { |
| 3042 | preferences.min_bitrate_bps = 32000; |
| 3043 | if (resetStartBitrate) { |
| 3044 | preferences.start_bitrate_bps = 32000; |
| 3045 | } |
| 3046 | preferences.max_bitrate_bps = 32000; |
| 3047 | } |
| 3048 |
| 3049 | settings.min_bitrate_bps = preferences.min_bitrate_bps; |
| 3050 | settings.start_bitrate_bps = preferences.start_bitrate_bps; |
| 3051 | settings.max_bitrate_bps = preferences.max_bitrate_bps; |
| 3052 |
| 3053 | _threads->getWorkerThread()->BlockingCall([&]() { |
| 3054 | _call->GetTransportControllerSend()->SetSdpBitrateParameters(preferences); |
| 3055 | _call->SetClientBitratePreferences(settings); |
| 3056 | }); |
| 3057 | } |
| 3058 |
| 3059 | void setIsRtcConnected(bool isConnected) { |
| 3060 | if (_isRtcConnected == isConnected) { |
| 3061 | return; |
| 3062 | } |
| 3063 | _isRtcConnected = isConnected; |
| 3064 |
| 3065 | RTC_LOG(LS_INFO) << formatTimestampMillis(rtc::TimeMillis()) << ": " << "setIsRtcConnected: " << _isRtcConnected; |
| 3066 |
| 3067 | if (_broadcastEnabledUntilRtcIsConnectedAtTimestamp) { |
| 3068 | _broadcastEnabledUntilRtcIsConnectedAtTimestamp = absl::nullopt; |
| 3069 |
| 3070 | if (_streamingContext) { |
| 3071 | _streamingContext.reset(); |
| 3072 | _audioDeviceDataObserverShared->setStreamingContext(nullptr); |
| 3073 | } |
| 3074 | } |
| 3075 |
| 3076 | updateIsConnected(); |
| 3077 | } |
| 3078 |
| 3079 | void updateIsConnected() { |
| 3080 | bool isEffectivelyConnected = false; |
| 3081 | bool isTransitioningFromBroadcastToRtc = false; |
| 3082 | switch (_connectionMode) { |
| 3083 | case GroupConnectionMode::GroupConnectionModeNone: { |
| 3084 | isEffectivelyConnected = false; |
| 3085 | if (_broadcastEnabledUntilRtcIsConnectedAtTimestamp && _isBroadcastConnected) { |
| 3086 | isEffectivelyConnected = true; |
| 3087 | isTransitioningFromBroadcastToRtc = true; |
| 3088 | } |
| 3089 | break; |
| 3090 | } |
| 3091 | case GroupConnectionMode::GroupConnectionModeRtc: { |
| 3092 | isEffectivelyConnected = _isRtcConnected; |
| 3093 | if (_broadcastEnabledUntilRtcIsConnectedAtTimestamp && _isBroadcastConnected) { |
| 3094 | isEffectivelyConnected = true; |
| 3095 | isTransitioningFromBroadcastToRtc = true; |
| 3096 | } |
| 3097 | break; |
| 3098 | } |
| 3099 | case GroupConnectionMode::GroupConnectionModeBroadcast: { |
| 3100 | isEffectivelyConnected = _isBroadcastConnected; |
| 3101 | break; |
| 3102 | } |
| 3103 | } |
| 3104 |
| 3105 | GroupNetworkState effectiveNetworkState; |
| 3106 | effectiveNetworkState.isConnected = isEffectivelyConnected; |
| 3107 | effectiveNetworkState.isTransitioningFromBroadcastToRtc = isTransitioningFromBroadcastToRtc; |
| 3108 |
| 3109 | if (_effectiveNetworkState.isConnected != effectiveNetworkState.isConnected || _effectiveNetworkState.isTransitioningFromBroadcastToRtc != effectiveNetworkState.isTransitioningFromBroadcastToRtc) { |
| 3110 | _effectiveNetworkState = effectiveNetworkState; |
| 3111 |
| 3112 | if (_networkStateUpdated) { |
| 3113 | _networkStateUpdated(_effectiveNetworkState); |
| 3114 | } |
| 3115 | } |
| 3116 |
| 3117 | NetworkStateLogRecord record; |
| 3118 | record.isConnected = effectiveNetworkState.isConnected; |
| 3119 | record.isFailed = false; |
| 3120 |
| 3121 | if (effectiveNetworkState.isConnected && !_hasBeenConnected) { |
| 3122 | _hasBeenConnected = true; |
| 3123 | auto connectionTimeMs = rtc::TimeMillis() - _startTimestamp; |
| 3124 | RTC_LOG(LS_INFO) << "Connected in " << connectionTimeMs << " ms"; |
| 3125 | } |
| 3126 |
| 3127 | if (!_currentNetworkStateLogRecord || !(_currentNetworkStateLogRecord.value() == record)) { |
| 3128 | _currentNetworkStateLogRecord = record; |
| 3129 | _networkStateLogRecords.emplace_back(rtc::TimeMillis(), std::move(record)); |
| 3130 | } |
| 3131 | } |
| 3132 |
| 3133 | void updateIsDataChannelOpen(bool isDataChannelOpen) { |
| 3134 | if (_isDataChannelOpen == isDataChannelOpen) { |
| 3135 | return; |
| 3136 | } |
| 3137 | _isDataChannelOpen = isDataChannelOpen; |
| 3138 |
| 3139 | if (_isDataChannelOpen) { |
| 3140 | maybeUpdateRemoteVideoConstraints(); |
| 3141 | } |
| 3142 | } |
| 3143 |
| 3144 | void receiveUnknownSsrcPacket(uint32_t ssrc, int payloadType) { |
| 3145 | if (ssrc == _outgoingAudioSsrc) { |
| 3146 | return; |
| 3147 | } |
| 3148 |
| 3149 | auto ssrcInfo = _channelBySsrc.find(ssrc); |
| 3150 | if (ssrcInfo == _channelBySsrc.end()) { |
| 3151 | // opus |
| 3152 | if (payloadType == 111) { |
| 3153 | maybeRequestUnknownSsrc(ssrc); |
| 3154 | } |
| 3155 | } else { |
| 3156 | switch (ssrcInfo->second.type) { |
| 3157 | case ChannelSsrcInfo::Type::Audio: { |
| 3158 | const auto it = _incomingAudioChannels.find(ChannelId(ssrc)); |
| 3159 | if (it != _incomingAudioChannels.end()) { |
| 3160 | it->second->updateActivity(); |
| 3161 | } |
| 3162 |
| 3163 | break; |
| 3164 | } |
| 3165 | case ChannelSsrcInfo::Type::Video: { |
| 3166 | break; |
| 3167 | } |
| 3168 | default: { |
| 3169 | break; |
| 3170 | } |
| 3171 | } |
| 3172 | } |
| 3173 | } |
| 3174 |
| 3175 | void receiveRtcpPacket(rtc::CopyOnWriteBuffer const &packet, int64_t timestamp) { |
| 3176 | _threads->getWorkerThread()->PostTask([this, packet]() { |
| 3177 | _call->Receiver()->DeliverRtcpPacket(packet); |
| 3178 | }); |
| 3179 | } |
| 3180 |
| 3181 | void receiveDataChannelMessage(std::string const &message) { |
| 3182 | std::string parsingError; |
| 3183 | auto json = json11::Json::parse(message, parsingError); |
| 3184 | if (json.type() != json11::Json::OBJECT) { |
| 3185 | RTC_LOG(LS_WARNING) << "receiveDataChannelMessage: error parsing message: " << parsingError; |
| 3186 | return; |
| 3187 | } |
| 3188 |
| 3189 | if (json.is_object()) { |
| 3190 | const auto colibriClass = json.object_items().find("colibriClass"); |
| 3191 | if (colibriClass != json.object_items().end() && colibriClass->second.is_string()) { |
| 3192 | const auto messageType = colibriClass->second.string_value(); |
| 3193 | if (messageType == "SenderVideoConstraints") { |
| 3194 | const auto videoConstraints = json.object_items().find("videoConstraints"); |
| 3195 | if (videoConstraints != json.object_items().end() && videoConstraints->second.is_object()) { |
| 3196 | const auto idealHeight = videoConstraints->second.object_items().find("idealHeight"); |
| 3197 | if (idealHeight != videoConstraints->second.object_items().end() && idealHeight->second.is_number()) { |
| 3198 | int outgoingVideoConstraint = idealHeight->second.int_value(); |
| 3199 | if (_outgoingVideoConstraint != outgoingVideoConstraint) { |
| 3200 | if (_outgoingVideoConstraint > outgoingVideoConstraint) { |
| 3201 | _pendingOutgoingVideoConstraint = outgoingVideoConstraint; |
| 3202 |
| 3203 | int requestId = _pendingOutgoingVideoConstraintRequestId; |
| 3204 | _pendingOutgoingVideoConstraintRequestId += 1; |
| 3205 |
| 3206 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 3207 | _threads->getMediaThread()->PostDelayedTask([weak, requestId]() { |
| 3208 | auto strong = weak.lock(); |
| 3209 | if (!strong) { |
| 3210 | return; |
| 3211 | } |
| 3212 | if (strong->_pendingOutgoingVideoConstraint != -1 && strong->_pendingOutgoingVideoConstraintRequestId == requestId) { |
| 3213 | if (strong->_outgoingVideoConstraint != strong->_pendingOutgoingVideoConstraint) { |
| 3214 | strong->_outgoingVideoConstraint = strong->_pendingOutgoingVideoConstraint; |
| 3215 | strong->adjustVideoSendParams(); |
| 3216 | } |
| 3217 | strong->_pendingOutgoingVideoConstraint = -1; |
| 3218 | } |
| 3219 | }, webrtc::TimeDelta::Millis(2000)); |
| 3220 | } else { |
| 3221 | _pendingOutgoingVideoConstraint = -1; |
| 3222 | _pendingOutgoingVideoConstraintRequestId += 1; |
| 3223 | _outgoingVideoConstraint = outgoingVideoConstraint; |
| 3224 | adjustVideoSendParams(); |
| 3225 | } |
| 3226 | } |
| 3227 | } |
| 3228 | } |
| 3229 | } else if (messageType == "DebugMessage") { |
| 3230 | const auto message = json.object_items().find("message"); |
| 3231 | if (message != json.object_items().end() && message->second.is_string()) { |
| 3232 | std::vector<std::string> parts = splitString(message->second.string_value(), '\n'); |
| 3233 | for (const auto &part : parts) { |
| 3234 | std::string cleanString = part; |
| 3235 | std::size_t index = cleanString.find("="); |
| 3236 | if (index == std::string::npos) { |
| 3237 | continue; |
| 3238 | } |
| 3239 | cleanString.erase(cleanString.begin(), cleanString.begin() + index + 1); |
| 3240 |
| 3241 | index = cleanString.find("target="); |
| 3242 | if (index == std::string::npos) { |
| 3243 | continue; |
| 3244 | } |
| 3245 |
| 3246 | std::string endpointId = cleanString.substr(0, index); |
| 3247 | cleanString.erase(cleanString.begin(), cleanString.begin() + index + 7); |
| 3248 |
| 3249 | index = cleanString.find("p/"); |
| 3250 | if (index == std::string::npos) { |
| 3251 | continue; |
| 3252 | } |
| 3253 |
| 3254 | std::string targetQuality = cleanString.substr(0, index); |
| 3255 | cleanString.erase(cleanString.begin(), cleanString.begin() + index + 2); |
| 3256 |
| 3257 | index = cleanString.find("ideal="); |
| 3258 | if (index == std::string::npos) { |
| 3259 | continue; |
| 3260 | } |
| 3261 |
| 3262 | cleanString.erase(cleanString.begin(), cleanString.begin() + index + 6); |
| 3263 |
| 3264 | index = cleanString.find("p/"); |
| 3265 | if (index == std::string::npos) { |
| 3266 | continue; |
| 3267 | } |
| 3268 |
| 3269 | std::string availableQuality = cleanString.substr(0, index); |
| 3270 |
| 3271 | for (const auto &it : _incomingVideoChannels) { |
| 3272 | if (it.second->endpointId() == endpointId) { |
| 3273 | GroupInstanceStats::IncomingVideoStats incomingVideoStats; |
| 3274 | incomingVideoStats.receivingQuality = stringToInt(targetQuality); |
| 3275 | incomingVideoStats.availableQuality = stringToInt(availableQuality); |
| 3276 | it.second->setStats(incomingVideoStats); |
| 3277 | } |
| 3278 | } |
| 3279 | } |
| 3280 | } |
| 3281 | } |
| 3282 | } |
| 3283 | } |
| 3284 | } |
| 3285 |
| 3286 | void maybeRequestUnknownSsrc(uint32_t ssrc) { |
| 3287 | if (!_requestMediaChannelDescriptions) { |
| 3288 | MediaChannelDescription description; |
| 3289 | description.audioSsrc = ssrc; |
| 3290 | processMediaChannelDescriptionsResponse(-1, {description}); |
| 3291 | return; |
| 3292 | } |
| 3293 |
| 3294 | for (const auto &it : _requestedMediaChannelDescriptions) { |
| 3295 | if (std::find(it.second.ssrcs.begin(), it.second.ssrcs.end(), ssrc) != it.second.ssrcs.end()) { |
| 3296 | return; |
| 3297 | } |
| 3298 | } |
| 3299 |
| 3300 | int requestId = _nextMediaChannelDescriptionsRequestId; |
| 3301 | _nextMediaChannelDescriptionsRequestId += 1; |
| 3302 |
| 3303 | std::vector<uint32_t> requestSsrcs = { ssrc }; |
| 3304 |
| 3305 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 3306 | auto task = _requestMediaChannelDescriptions(requestSsrcs, [weak, threads = _threads, requestId](std::vector<MediaChannelDescription> &&descriptions) { |
| 3307 | threads->getMediaThread()->PostTask([weak, requestId, descriptions = std::move(descriptions)]() mutable { |
| 3308 | auto strong = weak.lock(); |
| 3309 | if (!strong) { |
| 3310 | return; |
| 3311 | } |
| 3312 |
| 3313 | strong->processMediaChannelDescriptionsResponse(requestId, descriptions); |
| 3314 | }); |
| 3315 | }); |
| 3316 | _requestedMediaChannelDescriptions.insert(std::make_pair(requestId, RequestedMediaChannelDescriptions(task, std::move(requestSsrcs)))); |
| 3317 | } |
| 3318 |
| 3319 | void processMediaChannelDescriptionsResponse(int requestId, std::vector<MediaChannelDescription> const &descriptions) { |
| 3320 | _requestedMediaChannelDescriptions.erase(requestId); |
| 3321 |
| 3322 | if (_disableIncomingChannels) { |
| 3323 | return; |
| 3324 | } |
| 3325 |
| 3326 | for (const auto &description : descriptions) { |
| 3327 | switch (description.type) { |
| 3328 | case MediaChannelDescription::Type::Audio: { |
| 3329 | if (description.audioSsrc != 0) { |
| 3330 | addIncomingAudioChannel(ChannelId(description.audioSsrc), description.userId); |
| 3331 | } |
| 3332 | break; |
| 3333 | } |
| 3334 | case MediaChannelDescription::Type::Video: { |
| 3335 | break; |
| 3336 | } |
| 3337 | default: { |
| 3338 | break; |
| 3339 | } |
| 3340 | } |
| 3341 | } |
| 3342 | } |
| 3343 |
| 3344 | void maybeDeliverBufferedPackets(uint32_t ssrc) { |
| 3345 | // TODO: Re-enable after implementing custom transport |
| 3346 | /*auto packets = _missingPacketBuffer.get(ssrc); |
| 3347 | if (packets.size() != 0) { |
| 3348 | auto it = _ssrcMapping.find(ssrc); |
| 3349 | if (it != _ssrcMapping.end()) { |
| 3350 | for (const auto &packet : packets) { |
| 3351 | _threads->getNetworkThread()->BlockingCall([this, packet]() { |
| 3352 | _rtpTransport->DemuxPacketInternal(packet, -1); |
| 3353 | }); |
| 3354 | } |
| 3355 | } |
| 3356 | }*/ |
| 3357 | } |
| 3358 |
| 3359 | void maybeUpdateRemoteVideoConstraints() { |
| 3360 | if (!_isDataChannelOpen) { |
| 3361 | return; |
| 3362 | } |
| 3363 |
| 3364 | std::string pinnedEndpoint; |
| 3365 |
| 3366 | json11::Json::object json; |
| 3367 | json.insert(std::make_pair("colibriClass", json11::Json("ReceiverVideoConstraints"))); |
| 3368 |
| 3369 | json11::Json::object defaultConstraints; |
| 3370 | defaultConstraints.insert(std::make_pair("maxHeight", json11::Json(0))); |
| 3371 | json.insert(std::make_pair("defaultConstraints", json11::Json(std::move(defaultConstraints)))); |
| 3372 |
| 3373 | json11::Json::array onStageEndpoints; |
| 3374 | json11::Json::object constraints; |
| 3375 |
| 3376 | for (const auto &incomingVideoChannel : _incomingVideoChannels) { |
| 3377 | json11::Json::object selectedConstraint; |
| 3378 |
| 3379 | switch (incomingVideoChannel.second->requestedMinQuality()) { |
| 3380 | case VideoChannelDescription::Quality::Full: { |
| 3381 | selectedConstraint.insert(std::make_pair("minHeight", json11::Json(720))); |
| 3382 | break; |
| 3383 | } |
| 3384 | case VideoChannelDescription::Quality::Medium: { |
| 3385 | selectedConstraint.insert(std::make_pair("minHeight", json11::Json(360))); |
| 3386 | break; |
| 3387 | } |
| 3388 | case VideoChannelDescription::Quality::Thumbnail: { |
| 3389 | selectedConstraint.insert(std::make_pair("minHeight", json11::Json(180))); |
| 3390 | break; |
| 3391 | } |
| 3392 | default: { |
| 3393 | break; |
| 3394 | } |
| 3395 | } |
| 3396 | switch (incomingVideoChannel.second->requestedMaxQuality()) { |
| 3397 | case VideoChannelDescription::Quality::Full: { |
| 3398 | onStageEndpoints.push_back(json11::Json(incomingVideoChannel.first.endpointId)); |
| 3399 | selectedConstraint.insert(std::make_pair("maxHeight", json11::Json(720))); |
| 3400 | break; |
| 3401 | } |
| 3402 | case VideoChannelDescription::Quality::Medium: { |
| 3403 | selectedConstraint.insert(std::make_pair("maxHeight", json11::Json(360))); |
| 3404 | break; |
| 3405 | } |
| 3406 | case VideoChannelDescription::Quality::Thumbnail: { |
| 3407 | selectedConstraint.insert(std::make_pair("maxHeight", json11::Json(180))); |
| 3408 | break; |
| 3409 | } |
| 3410 | default: { |
| 3411 | break; |
| 3412 | } |
| 3413 | } |
| 3414 |
| 3415 | constraints.insert(std::make_pair(incomingVideoChannel.first.endpointId, json11::Json(std::move(selectedConstraint)))); |
| 3416 | } |
| 3417 |
| 3418 | json.insert(std::make_pair("onStageEndpoints", json11::Json(std::move(onStageEndpoints)))); |
| 3419 | json.insert(std::make_pair("constraints", json11::Json(std::move(constraints)))); |
| 3420 |
| 3421 | std::string result = json11::Json(std::move(json)).dump(); |
| 3422 | _networkManager->perform([result = std::move(result)](GroupNetworkManager *networkManager) { |
| 3423 | networkManager->sendDataChannelMessage(result); |
| 3424 | }); |
| 3425 | } |
| 3426 |
| 3427 | void setConnectionMode(GroupConnectionMode connectionMode, bool keepBroadcastIfWasEnabled, bool isUnifiedBroadcast) { |
| 3428 | if (_connectionMode != connectionMode || connectionMode == GroupConnectionMode::GroupConnectionModeNone) { |
| 3429 | GroupConnectionMode previousMode = _connectionMode; |
| 3430 | _connectionMode = connectionMode; |
| 3431 | _isUnifiedBroadcast = isUnifiedBroadcast; |
| 3432 | onConnectionModeUpdated(previousMode, keepBroadcastIfWasEnabled); |
| 3433 | } |
| 3434 | } |
| 3435 |
| 3436 | void onConnectionModeUpdated(GroupConnectionMode previousMode, bool keepBroadcastIfWasEnabled) { |
| 3437 | RTC_CHECK(_connectionMode != previousMode || _connectionMode == GroupConnectionMode::GroupConnectionModeNone); |
| 3438 |
| 3439 | if (previousMode == GroupConnectionMode::GroupConnectionModeRtc) { |
| 3440 | _networkManager->perform([](GroupNetworkManager *networkManager) { |
| 3441 | networkManager->stop(); |
| 3442 | }); |
| 3443 | } else if (previousMode == GroupConnectionMode::GroupConnectionModeBroadcast) { |
| 3444 | if (keepBroadcastIfWasEnabled) { |
| 3445 | _broadcastEnabledUntilRtcIsConnectedAtTimestamp = rtc::TimeMillis(); |
| 3446 | } else { |
| 3447 | if (_streamingContext) { |
| 3448 | _streamingContext.reset(); |
| 3449 | _audioDeviceDataObserverShared->setStreamingContext(nullptr); |
| 3450 | } |
| 3451 | } |
| 3452 | } |
| 3453 |
| 3454 | if (_connectionMode == GroupConnectionMode::GroupConnectionModeNone) { |
| 3455 | destroyOutgoingAudioChannel(); |
| 3456 | destroyOutgoingVideoChannel(); |
| 3457 |
| 3458 | // Regenerate and reconfigure. |
| 3459 | generateSsrcs(); |
| 3460 |
| 3461 | if (!_isMuted) { |
| 3462 | createOutgoingAudioChannel(); |
| 3463 | } |
| 3464 | createOutgoingVideoChannel(); |
| 3465 | } |
| 3466 |
| 3467 | switch (_connectionMode) { |
| 3468 | case GroupConnectionMode::GroupConnectionModeNone: { |
| 3469 | break; |
| 3470 | } |
| 3471 | case GroupConnectionMode::GroupConnectionModeRtc: { |
| 3472 | _networkManager->perform([](GroupNetworkManager *networkManager) { |
| 3473 | networkManager->start(); |
| 3474 | }); |
| 3475 | break; |
| 3476 | } |
| 3477 | case GroupConnectionMode::GroupConnectionModeBroadcast: { |
| 3478 | _isBroadcastConnected = false; |
| 3479 |
| 3480 | if (!_streamingContext) { |
| 3481 | StreamingMediaContext::StreamingMediaContextArguments arguments; |
| 3482 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 3483 | arguments.threads = _threads; |
| 3484 | arguments.platformContext = _platformContext; |
| 3485 | arguments.isUnifiedBroadcast = _isUnifiedBroadcast; |
| 3486 | arguments.requestCurrentTime = _requestCurrentTime; |
| 3487 | arguments.requestAudioBroadcastPart = _requestAudioBroadcastPart; |
| 3488 | arguments.requestVideoBroadcastPart = _requestVideoBroadcastPart; |
| 3489 | arguments.updateAudioLevel = [weak, threads = _threads](uint32_t ssrc, float level, bool isSpeech) { |
| 3490 | assert(threads->getMediaThread()->IsCurrent()); |
| 3491 |
| 3492 | auto strong = weak.lock(); |
| 3493 | if (!strong) { |
| 3494 | return; |
| 3495 | } |
| 3496 |
| 3497 | InternalGroupLevelValue updated; |
| 3498 | updated.value.level = level; |
| 3499 | updated.value.voice = isSpeech; |
| 3500 | updated.timestamp = rtc::TimeMillis(); |
| 3501 | strong->_audioLevels.insert(std::make_pair(ChannelId(ssrc), std::move(updated))); |
| 3502 | }; |
| 3503 | _streamingContext = std::make_shared<StreamingMediaContext>(std::move(arguments)); |
| 3504 |
| 3505 | for (const auto &it : _pendingVideoSinks) { |
| 3506 | for (const auto &sink : it.second) { |
| 3507 | _streamingContext->addVideoSink(it.first.endpointId, sink); |
| 3508 | } |
| 3509 | } |
| 3510 |
| 3511 | for (const auto &it : _volumeBySsrc) { |
| 3512 | _streamingContext->setVolume(it.first, it.second); |
| 3513 | } |
| 3514 |
| 3515 | std::vector<StreamingMediaContext::VideoChannel> streamingVideoChannels; |
| 3516 | for (const auto &it : _pendingRequestedVideo) { |
| 3517 | streamingVideoChannels.emplace_back(it.maxQuality, it.endpointId); |
| 3518 | } |
| 3519 | _streamingContext->setActiveVideoChannels(streamingVideoChannels); |
| 3520 |
| 3521 | _audioDeviceDataObserverShared->setStreamingContext(_streamingContext); |
| 3522 | } |
| 3523 |
| 3524 | break; |
| 3525 | } |
| 3526 | default: { |
| 3527 | RTC_FATAL() << "Unknown connectionMode"; |
| 3528 | break; |
| 3529 | } |
| 3530 | } |
| 3531 |
| 3532 | updateIsConnected(); |
| 3533 | } |
| 3534 |
| 3535 | void generateSsrcs() { |
| 3536 | auto generator = std::mt19937(std::random_device()()); |
| 3537 | auto distribution = std::uniform_int_distribution<uint32_t>(); |
| 3538 | do { |
| 3539 | _outgoingAudioSsrc = distribution(generator) & 0x7fffffffU; |
| 3540 | } while (!_outgoingAudioSsrc); |
| 3541 |
| 3542 | uint32_t outgoingVideoSsrcBase = _outgoingAudioSsrc + 1; |
| 3543 | int numVideoSimulcastLayers = 3; |
| 3544 | if (_isConference) { |
| 3545 | numVideoSimulcastLayers = 1; |
| 3546 | } else if (_videoContentType == VideoContentType::Screencast) { |
| 3547 | numVideoSimulcastLayers = 2; |
| 3548 | } |
| 3549 | _outgoingVideoSsrcs.simulcastLayers.clear(); |
| 3550 | for (int layerIndex = 0; layerIndex < numVideoSimulcastLayers; layerIndex++) { |
| 3551 | _outgoingVideoSsrcs.simulcastLayers.push_back(VideoSsrcs::SimulcastLayer(outgoingVideoSsrcBase + layerIndex * 2 + 0, outgoingVideoSsrcBase + layerIndex * 2 + 1)); |
| 3552 | } |
| 3553 |
| 3554 | _videoSourceGroups.clear(); |
| 3555 |
| 3556 | std::vector<uint32_t> simulcastGroupSsrcs; |
| 3557 | std::vector<cricket::SsrcGroup> fidGroups; |
| 3558 | for (const auto &layer : _outgoingVideoSsrcs.simulcastLayers) { |
| 3559 | simulcastGroupSsrcs.push_back(layer.ssrc); |
| 3560 |
| 3561 | cricket::SsrcGroup fidGroup(cricket::kFidSsrcGroupSemantics, { layer.ssrc, layer.fidSsrc }); |
| 3562 | fidGroups.push_back(fidGroup); |
| 3563 | } |
| 3564 | if (simulcastGroupSsrcs.size() > 1) { |
| 3565 | cricket::SsrcGroup simulcastGroup(cricket::kSimSsrcGroupSemantics, simulcastGroupSsrcs); |
| 3566 |
| 3567 | GroupJoinPayloadVideoSourceGroup payloadSimulcastGroup; |
| 3568 | payloadSimulcastGroup.semantics = "SIM"; |
| 3569 | payloadSimulcastGroup.ssrcs = simulcastGroupSsrcs; |
| 3570 | _videoSourceGroups.push_back(payloadSimulcastGroup); |
| 3571 | } |
| 3572 |
| 3573 | for (auto fidGroup : fidGroups) { |
| 3574 | GroupJoinPayloadVideoSourceGroup payloadFidGroup; |
| 3575 | payloadFidGroup.semantics = "FID"; |
| 3576 | payloadFidGroup.ssrcs = fidGroup.ssrcs; |
| 3577 | _videoSourceGroups.push_back(payloadFidGroup); |
| 3578 | } |
| 3579 | } |
| 3580 |
| 3581 | void emitJoinPayload(std::function<void(GroupJoinPayload const &)> completion) { |
| 3582 | _networkManager->perform([outgoingAudioSsrc = _outgoingAudioSsrc, /*videoPayloadTypes = _videoPayloadTypes, videoExtensionMap = _videoExtensionMap, */videoSourceGroups = _videoSourceGroups, videoContentType = _videoContentType, completion](GroupNetworkManager *networkManager) { |
| 3583 | GroupJoinInternalPayload payload; |
| 3584 |
| 3585 | payload.audioSsrc = outgoingAudioSsrc; |
| 3586 |
| 3587 | if (videoContentType != VideoContentType::None) { |
| 3588 | GroupParticipantVideoInformation videoInformation; |
| 3589 | videoInformation.ssrcGroups = videoSourceGroups; |
| 3590 | payload.videoInformation = std::move(videoInformation); |
| 3591 | } |
| 3592 |
| 3593 | GroupJoinTransportDescription transportDescription; |
| 3594 |
| 3595 | auto localIceParameters = networkManager->getLocalIceParameters(); |
| 3596 | transportDescription.ufrag = localIceParameters.ufrag; |
| 3597 | transportDescription.pwd = localIceParameters.pwd; |
| 3598 |
| 3599 | auto localFingerprint = networkManager->getLocalFingerprint(); |
| 3600 | if (localFingerprint) { |
| 3601 | GroupJoinTransportDescription::Fingerprint serializedFingerprint; |
| 3602 | serializedFingerprint.hash = localFingerprint->algorithm; |
| 3603 | serializedFingerprint.fingerprint = localFingerprint->GetRfc4572Fingerprint(); |
| 3604 | serializedFingerprint.setup = "passive"; |
| 3605 | transportDescription.fingerprints.push_back(std::move(serializedFingerprint)); |
| 3606 | } |
| 3607 |
| 3608 | payload.transport = std::move(transportDescription); |
| 3609 |
| 3610 | GroupJoinPayload result; |
| 3611 | result.audioSsrc = payload.audioSsrc; |
| 3612 | result.json = payload.serialize(); |
| 3613 | completion(result); |
| 3614 | }); |
| 3615 | } |
| 3616 |
| 3617 | void setVideoSource(std::function<webrtc::scoped_refptr<webrtc::VideoTrackSourceInterface>()> getVideoSource, bool isInitializing) { |
| 3618 | bool resetBitrate = (!_getVideoSource) != (!getVideoSource) && !isInitializing; |
| 3619 | if (!isInitializing && _getVideoSource && getVideoSource && getVideoSource() == _getVideoSource()) { |
| 3620 | return; |
| 3621 | } |
| 3622 |
| 3623 | _getVideoSource = std::move(getVideoSource); |
| 3624 | updateVideoSend(); |
| 3625 | if (resetBitrate) { |
| 3626 | adjustBitratePreferences(true); |
| 3627 | } |
| 3628 | } |
| 3629 |
| 3630 | void setVideoCapture(std::shared_ptr<VideoCaptureInterface> videoCapture, bool isInitializing) { |
| 3631 | _videoCapture = videoCapture; |
| 3632 | setVideoSource(videoCaptureToGetVideoSource(std::move(videoCapture)), isInitializing); |
| 3633 | } |
| 3634 |
| 3635 | void setAudioOutputDevice(const std::string &id) { |
| 3636 | #ifndef WEBRTC_IOS |
| 3637 | _threads->getWorkerThread()->BlockingCall([&] { |
| 3638 | SetAudioOutputDeviceById(_audioDeviceModule.get(), id); |
| 3639 | }); |
| 3640 | #endif // WEBRTC_IOS |
| 3641 | } |
| 3642 |
| 3643 | void setAudioInputDevice(const std::string &id) { |
| 3644 | #ifndef WEBRTC_IOS |
| 3645 | _threads->getWorkerThread()->BlockingCall([&] { |
| 3646 | SetAudioInputDeviceById(_audioDeviceModule.get(), id); |
| 3647 | }); |
| 3648 | #endif // WEBRTC_IOS |
| 3649 | } |
| 3650 |
| 3651 | void addExternalAudioSamples(std::vector<uint8_t> &&samples) { |
| 3652 | if (samples.size() % 2 != 0) { |
| 3653 | return; |
| 3654 | } |
| 3655 | _externalAudioSamplesMutex.Lock(); |
| 3656 |
| 3657 | size_t previousSize = _externalAudioSamples.size(); |
| 3658 | _externalAudioSamples.resize(_externalAudioSamples.size() + samples.size() / 2); |
| 3659 | webrtc::S16ToFloatS16((const int16_t *)samples.data(), samples.size() / 2, _externalAudioSamples.data() + previousSize); |
| 3660 |
| 3661 | if (_externalAudioSamples.size() > 2 * 48000) { |
| 3662 | _externalAudioSamples.erase(_externalAudioSamples.begin(), _externalAudioSamples.begin() + (_externalAudioSamples.size() - 2 * 48000)); |
| 3663 | } |
| 3664 |
| 3665 | _externalAudioSamplesMutex.Unlock(); |
| 3666 | } |
| 3667 |
| 3668 | void setJoinResponsePayload(std::string const &payload) { |
| 3669 | RTC_LOG(LS_INFO) << formatTimestampMillis(rtc::TimeMillis()) << ": " << "setJoinResponsePayload: " << payload; |
| 3670 |
| 3671 | auto parsedPayload = GroupJoinResponsePayload::parse(payload); |
| 3672 | if (!parsedPayload) { |
| 3673 | RTC_LOG(LS_ERROR) << "Could not parse json response payload"; |
| 3674 | return; |
| 3675 | } |
| 3676 |
| 3677 | _sharedVideoInformation = parsedPayload->videoInformation; |
| 3678 |
| 3679 | _serverBandwidthProbingVideoSsrc.reset(); |
| 3680 |
| 3681 | if (parsedPayload->videoInformation && parsedPayload->videoInformation->serverVideoBandwidthProbingSsrc) { |
| 3682 | setServerBandwidthProbingChannelSsrc(parsedPayload->videoInformation->serverVideoBandwidthProbingSsrc); |
| 3683 | } |
| 3684 |
| 3685 | _networkManager->perform([parsedTransport = parsedPayload->transport](GroupNetworkManager *networkManager) { |
| 3686 | PeerIceParameters remoteIceParameters; |
| 3687 | remoteIceParameters.ufrag = parsedTransport.ufrag; |
| 3688 | remoteIceParameters.pwd = parsedTransport.pwd; |
| 3689 |
| 3690 | std::vector<cricket::Candidate> iceCandidates; |
| 3691 | for (auto const &candidate : parsedTransport.candidates) { |
| 3692 | rtc::SocketAddress address(candidate.ip, stringToInt(candidate.port)); |
| 3693 |
| 3694 | std::string candidateType = candidate.type; |
| 3695 | if (candidateType == "host") { |
| 3696 | candidateType = "local"; |
| 3697 | } |
| 3698 |
| 3699 | cricket::Candidate parsedCandidate( |
| 3700 | /*component=*/stringToInt(candidate.component), |
| 3701 | /*protocol=*/candidate.protocol, |
| 3702 | /*address=*/address, |
| 3703 | /*priority=*/stringToUInt32(candidate.priority), |
| 3704 | /*username=*/parsedTransport.ufrag, |
| 3705 | /*password=*/parsedTransport.pwd, |
| 3706 | /*type=*/candidateType, |
| 3707 | /*generation=*/stringToUInt32(candidate.generation), |
| 3708 | /*foundation=*/candidate.foundation, |
| 3709 | /*network_id=*/stringToUInt16(candidate.network), |
| 3710 | /*network_cost=*/0 |
| 3711 | ); |
| 3712 | iceCandidates.push_back(parsedCandidate); |
| 3713 | } |
| 3714 |
| 3715 | std::unique_ptr<rtc::SSLFingerprint> fingerprint; |
| 3716 | if (parsedTransport.fingerprints.size() != 0) { |
| 3717 | fingerprint = rtc::SSLFingerprint::CreateUniqueFromRfc4572(parsedTransport.fingerprints[0].hash, parsedTransport.fingerprints[0].fingerprint); |
| 3718 | } |
| 3719 |
| 3720 | networkManager->setRemoteParams(remoteIceParameters, iceCandidates, fingerprint.get()); |
| 3721 | }); |
| 3722 |
| 3723 | configureVideoParams(); |
| 3724 | createOutgoingVideoChannel(); |
| 3725 |
| 3726 | adjustBitratePreferences(true); |
| 3727 |
| 3728 | if (!_pendingRequestedVideo.empty()) { |
| 3729 | setRequestedVideoChannels(std::move(_pendingRequestedVideo)); |
| 3730 | _pendingRequestedVideo.clear(); |
| 3731 | } |
| 3732 | } |
| 3733 |
| 3734 | void setServerBandwidthProbingChannelSsrc(uint32_t probingSsrc) { |
| 3735 | RTC_CHECK(probingSsrc); |
| 3736 |
| 3737 | if (!_sharedVideoInformation || _availablePayloadTypes.empty()) { |
| 3738 | return; |
| 3739 | } |
| 3740 |
| 3741 | GroupParticipantVideoInformation videoInformation; |
| 3742 |
| 3743 | GroupJoinPayloadVideoSourceGroup sourceGroup; |
| 3744 | sourceGroup.ssrcs.push_back(probingSsrc); |
| 3745 | sourceGroup.semantics = "SIM"; |
| 3746 |
| 3747 | videoInformation.ssrcGroups.push_back(std::move(sourceGroup)); |
| 3748 |
| 3749 | _serverBandwidthProbingVideoSsrc.reset(new IncomingVideoChannel( |
| 3750 | _channelManager.get(), |
| 3751 | _call.get(), |
| 3752 | _rtpTransport, |
| 3753 | _uniqueRandomIdGenerator.get(), |
| 3754 | _availableVideoFormats, |
| 3755 | _sharedVideoInformation.value(), |
| 3756 | 123456, |
| 3757 | int64_t(), |
| 3758 | VideoChannelDescription::Quality::Thumbnail, |
| 3759 | VideoChannelDescription::Quality::Thumbnail, |
| 3760 | videoInformation, |
| 3761 | _threads, |
| 3762 | _e2eEncryptDecrypt, |
| 3763 | _payloadTypeMapping |
| 3764 | )); |
| 3765 |
| 3766 | ChannelSsrcInfo mapping; |
| 3767 | mapping.type = ChannelSsrcInfo::Type::Video; |
| 3768 | mapping.allSsrcs.push_back(probingSsrc); |
| 3769 | _channelBySsrc.insert(std::make_pair(probingSsrc, std::move(mapping))); |
| 3770 | } |
| 3771 |
| 3772 | void removeSsrcs(std::vector<uint32_t> ssrcs) { |
| 3773 | } |
| 3774 |
| 3775 | void removeIncomingVideoSource(uint32_t ssrc) { |
| 3776 | } |
| 3777 |
| 3778 | void setIsMuted(bool isMuted) { |
| 3779 | if (_isMuted == isMuted) { |
| 3780 | return; |
| 3781 | } |
| 3782 | _isMuted = isMuted; |
| 3783 |
| 3784 | if (!_isMuted && !_outgoingAudioChannel) { |
| 3785 | createOutgoingAudioChannel(); |
| 3786 | } |
| 3787 |
| 3788 | onUpdatedIsMuted(); |
| 3789 | } |
| 3790 |
| 3791 | void onUpdatedIsMuted() { |
| 3792 | if (_outgoingAudioChannel) { |
| 3793 | _threads->getWorkerThread()->BlockingCall([this]() { |
| 3794 | _outgoingAudioChannel->send_channel()->SetAudioSend(_outgoingAudioSsrc, !_isMuted, nullptr, &_audioSource); |
| 3795 |
| 3796 | if (_audioDeviceModule) { |
| 3797 | bool isDeviceMuteAvailable = false; |
| 3798 | if (_audioDeviceModule->MicrophoneMuteIsAvailable(&isDeviceMuteAvailable) == 0) { |
| 3799 | if (isDeviceMuteAvailable) { |
| 3800 | _audioDeviceModule->SetMicrophoneMute(_isMuted); |
| 3801 | } |
| 3802 | } |
| 3803 | } |
| 3804 | }); |
| 3805 |
| 3806 | _outgoingAudioChannel->Enable(!_isMuted); |
| 3807 | } else { |
| 3808 | _threads->getWorkerThread()->BlockingCall([this]() { |
| 3809 | if (_audioDeviceModule) { |
| 3810 | bool isDeviceMuteAvailable = false; |
| 3811 | if (_audioDeviceModule->MicrophoneMuteIsAvailable(&isDeviceMuteAvailable) == 0) { |
| 3812 | if (isDeviceMuteAvailable) { |
| 3813 | _audioDeviceModule->SetMicrophoneMute(_isMuted); |
| 3814 | } |
| 3815 | } |
| 3816 | } |
| 3817 | }); |
| 3818 |
| 3819 | } |
| 3820 | } |
| 3821 |
| 3822 | void setIsNoiseSuppressionEnabled(bool isNoiseSuppressionEnabled) { |
| 3823 | _noiseSuppressionConfiguration->isEnabled = isNoiseSuppressionEnabled; |
| 3824 | } |
| 3825 |
| 3826 | void addOutgoingVideoOutput(std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) { |
| 3827 | _videoCaptureSink->addSink(sink); |
| 3828 |
| 3829 | if (_videoCapture) { |
| 3830 | _videoCapture->setOutput(_videoCaptureSink); |
| 3831 | } |
| 3832 | } |
| 3833 |
| 3834 | void addIncomingVideoOutput(std::string const &endpointId, std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) { |
| 3835 | if (_sharedVideoInformation && endpointId == _sharedVideoInformation->endpointId) { |
| 3836 | if (_videoCapture) { |
| 3837 | _videoCaptureSink->addSink(sink); |
| 3838 | _videoCapture->setOutput(_videoCaptureSink); |
| 3839 | } |
| 3840 | } else { |
| 3841 | auto it = _incomingVideoChannels.find(VideoChannelId(endpointId)); |
| 3842 | if (it != _incomingVideoChannels.end()) { |
| 3843 | it->second->addSink(sink); |
| 3844 | } else { |
| 3845 | _pendingVideoSinks[VideoChannelId(endpointId)].push_back(sink); |
| 3846 | } |
| 3847 |
| 3848 | if (_streamingContext) { |
| 3849 | _streamingContext->addVideoSink(endpointId, sink); |
| 3850 | } |
| 3851 | } |
| 3852 | } |
| 3853 |
| 3854 | void addIncomingAudioChannel(ChannelId ssrc, int64_t userId, bool isRawPcm = false) { |
| 3855 | if (_incomingAudioChannels.find(ssrc) != _incomingAudioChannels.end()) { |
| 3856 | return; |
| 3857 | } |
| 3858 |
| 3859 | if (_incomingAudioChannels.size() > 10) { |
| 3860 | auto timestamp = rtc::TimeMillis(); |
| 3861 |
| 3862 | int64_t minActivity = INT64_MAX; |
| 3863 | ChannelId minActivityChannelId(0, 0); |
| 3864 |
| 3865 | for (const auto &it : _incomingAudioChannels) { |
| 3866 | if (it.first.networkSsrc == 1) { |
| 3867 | continue; |
| 3868 | } |
| 3869 | auto activity = it.second->getActivity(); |
| 3870 | if (activity < minActivity && activity < timestamp - 1000) { |
| 3871 | minActivity = activity; |
| 3872 | minActivityChannelId = it.first; |
| 3873 | } |
| 3874 | } |
| 3875 |
| 3876 | if (minActivityChannelId.networkSsrc != 0) { |
| 3877 | removeIncomingAudioChannel(minActivityChannelId); |
| 3878 | } |
| 3879 |
| 3880 | if (_incomingAudioChannels.size() > 10) { |
| 3881 | // Wait until there is a channel that hasn't been active in 1 second |
| 3882 | return; |
| 3883 | } |
| 3884 | } |
| 3885 |
| 3886 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 3887 |
| 3888 | std::function<void(AudioSinkImpl::Update)> onAudioSinkUpdate; |
| 3889 | if (ssrc.actualSsrc != ssrc.networkSsrc) { |
| 3890 | if (_audioLevelsUpdated) { |
| 3891 | onAudioSinkUpdate = [weak, ssrc = ssrc, threads = _threads](AudioSinkImpl::Update update) { |
| 3892 | threads->getMediaThread()->PostTask([weak, ssrc, update]() { |
| 3893 | auto strong = weak.lock(); |
| 3894 | if (!strong) { |
| 3895 | return; |
| 3896 | } |
| 3897 |
| 3898 | auto it = strong->_audioLevels.find(ChannelId(ssrc)); |
| 3899 | if (it != strong->_audioLevels.end()) { |
| 3900 | it->second.value.level = fmax(it->second.value.level, update.level); |
| 3901 | if (update.hasSpeech) { |
| 3902 | it->second.value.voice = true; |
| 3903 | } |
| 3904 | it->second.timestamp = rtc::TimeMillis(); |
| 3905 | } else { |
| 3906 | InternalGroupLevelValue updated; |
| 3907 | updated.value.level = update.level; |
| 3908 | updated.value.voice = update.hasSpeech; |
| 3909 | updated.timestamp = rtc::TimeMillis(); |
| 3910 | strong->_audioLevels.insert(std::make_pair(ChannelId(ssrc), std::move(updated))); |
| 3911 | } |
| 3912 | }); |
| 3913 | }; |
| 3914 | } |
| 3915 | } |
| 3916 |
| 3917 | std::unique_ptr<IncomingAudioChannel> channel(new IncomingAudioChannel( |
| 3918 | _channelManager.get(), |
| 3919 | _call.get(), |
| 3920 | _rtpTransport, |
| 3921 | _uniqueRandomIdGenerator.get(), |
| 3922 | isRawPcm, |
| 3923 | ssrc, |
| 3924 | userId, |
| 3925 | std::move(onAudioSinkUpdate), |
| 3926 | _onAudioFrame, |
| 3927 | _threads, |
| 3928 | _e2eEncryptDecrypt, |
| 3929 | _payloadTypeMapping, |
| 3930 | [weak, threads = _threads](uint32_t ssrc, uint8_t audioLevel, bool hasSpeech) { |
| 3931 | threads->getMediaThread()->PostTask([weak, ssrc, audioLevel, hasSpeech]() { |
| 3932 | if (const auto strong = weak.lock()) { |
| 3933 | strong->updateSsrcAudioLevel(ssrc, audioLevel, hasSpeech); |
| 3934 | } |
| 3935 | }); |
| 3936 | } |
| 3937 | )); |
| 3938 |
| 3939 | auto volume = _volumeBySsrc.find(ssrc.actualSsrc); |
| 3940 | if (volume != _volumeBySsrc.end()) { |
| 3941 | channel->setVolume(volume->second); |
| 3942 | } |
| 3943 |
| 3944 | _incomingAudioChannels.insert(std::make_pair(ssrc, std::move(channel))); |
| 3945 |
| 3946 | auto currentMapping = _channelBySsrc.find(ssrc.networkSsrc); |
| 3947 | if (currentMapping != _channelBySsrc.end()) { |
| 3948 | if (currentMapping->second.type == ChannelSsrcInfo::Type::Audio) { |
| 3949 | if (std::find(currentMapping->second.allSsrcs.begin(), currentMapping->second.allSsrcs.end(), ssrc.networkSsrc) == currentMapping->second.allSsrcs.end()) { |
| 3950 | currentMapping->second.allSsrcs.push_back(ssrc.networkSsrc); |
| 3951 | } |
| 3952 | } |
| 3953 | } else { |
| 3954 | ChannelSsrcInfo mapping; |
| 3955 | mapping.type = ChannelSsrcInfo::Type::Audio; |
| 3956 | mapping.allSsrcs.push_back(ssrc.networkSsrc); |
| 3957 | _channelBySsrc.insert(std::make_pair(ssrc.networkSsrc, std::move(mapping))); |
| 3958 | } |
| 3959 |
| 3960 | maybeDeliverBufferedPackets(ssrc.networkSsrc); |
| 3961 |
| 3962 | adjustBitratePreferences(false); |
| 3963 | } |
| 3964 |
| 3965 | void removeIncomingAudioChannel(ChannelId const &channelId) { |
| 3966 | const auto it = _incomingAudioChannels.find(channelId); |
| 3967 | if (it != _incomingAudioChannels.end()) { |
| 3968 | _incomingAudioChannels.erase(it); |
| 3969 | } |
| 3970 |
| 3971 | auto currentMapping = _channelBySsrc.find(channelId.networkSsrc); |
| 3972 | if (currentMapping != _channelBySsrc.end()) { |
| 3973 | if (currentMapping->second.type == ChannelSsrcInfo::Type::Audio) { |
| 3974 | auto ssrcs = currentMapping->second.allSsrcs; |
| 3975 | for (auto ssrc : ssrcs) { |
| 3976 | auto it = _channelBySsrc.find(ssrc); |
| 3977 | if (it != _channelBySsrc.end()) { |
| 3978 | _channelBySsrc.erase(it); |
| 3979 | } |
| 3980 | } |
| 3981 | } |
| 3982 | } |
| 3983 | } |
| 3984 |
| 3985 | void addIncomingVideoChannel(uint32_t audioSsrc, int64_t userId, GroupParticipantVideoInformation const &videoInformation, VideoChannelDescription::Quality minQuality, VideoChannelDescription::Quality maxQuality) { |
| 3986 | if (!_sharedVideoInformation) { |
| 3987 | return; |
| 3988 | } |
| 3989 | if (_incomingVideoChannels.find(VideoChannelId(videoInformation.endpointId)) != _incomingVideoChannels.end()) { |
| 3990 | return; |
| 3991 | } |
| 3992 |
| 3993 | const auto weak = std::weak_ptr<GroupInstanceCustomInternal>(shared_from_this()); |
| 3994 |
| 3995 | std::unique_ptr<IncomingVideoChannel> channel(new IncomingVideoChannel( |
| 3996 | _channelManager.get(), |
| 3997 | _call.get(), |
| 3998 | _rtpTransport, |
| 3999 | _uniqueRandomIdGenerator.get(), |
| 4000 | _availableVideoFormats, |
| 4001 | _sharedVideoInformation.value(), |
| 4002 | audioSsrc, |
| 4003 | userId, |
| 4004 | minQuality, |
| 4005 | maxQuality, |
| 4006 | videoInformation, |
| 4007 | _threads, |
| 4008 | _e2eEncryptDecrypt, |
| 4009 | _payloadTypeMapping |
| 4010 | )); |
| 4011 |
| 4012 | const auto pendingSinks = _pendingVideoSinks.find(VideoChannelId(videoInformation.endpointId)); |
| 4013 | if (pendingSinks != _pendingVideoSinks.end()) { |
| 4014 | for (const auto &sink : pendingSinks->second) { |
| 4015 | channel->addSink(sink); |
| 4016 | } |
| 4017 |
| 4018 | _pendingVideoSinks.erase(pendingSinks); |
| 4019 | } |
| 4020 |
| 4021 | _incomingVideoChannels.insert(std::make_pair(VideoChannelId(videoInformation.endpointId), std::move(channel))); |
| 4022 |
| 4023 | std::vector<uint32_t> allSsrcs; |
| 4024 | for (const auto &group : videoInformation.ssrcGroups) { |
| 4025 | for (auto ssrc : group.ssrcs) { |
| 4026 | if (std::find(allSsrcs.begin(), allSsrcs.end(), ssrc) == allSsrcs.end()) { |
| 4027 | allSsrcs.push_back(ssrc); |
| 4028 | } |
| 4029 | } |
| 4030 | } |
| 4031 |
| 4032 | for (auto ssrc : allSsrcs) { |
| 4033 | ChannelSsrcInfo mapping; |
| 4034 | mapping.type = ChannelSsrcInfo::Type::Video; |
| 4035 | mapping.allSsrcs = allSsrcs; |
| 4036 | mapping.videoEndpointId = videoInformation.endpointId; |
| 4037 | _channelBySsrc.insert(std::make_pair(ssrc, std::move(mapping))); |
| 4038 | } |
| 4039 |
| 4040 | for (auto ssrc : allSsrcs) { |
| 4041 | maybeDeliverBufferedPackets(ssrc); |
| 4042 | } |
| 4043 |
| 4044 | adjustBitratePreferences(false); |
| 4045 | } |
| 4046 |
| 4047 | void setVolume(uint32_t ssrc, double volume) { |
| 4048 | auto current = _volumeBySsrc.find(ssrc); |
| 4049 | if (current != _volumeBySsrc.end() && std::abs(current->second - volume) < 0.0001) { |
| 4050 | return; |
| 4051 | } |
| 4052 |
| 4053 | _volumeBySsrc[ssrc] = volume; |
| 4054 |
| 4055 | auto it = _incomingAudioChannels.find(ChannelId(ssrc)); |
| 4056 | if (it != _incomingAudioChannels.end()) { |
| 4057 | it->second->setVolume(volume); |
| 4058 | } |
| 4059 |
| 4060 | it = _incomingAudioChannels.find(ChannelId(ssrc + 1000, ssrc)); |
| 4061 | if (it != _incomingAudioChannels.end()) { |
| 4062 | it->second->setVolume(volume); |
| 4063 | } |
| 4064 |
| 4065 | if (_streamingContext) { |
| 4066 | _streamingContext->setVolume(ssrc, volume); |
| 4067 | } |
| 4068 | } |
| 4069 |
| 4070 | void setRequestedVideoChannels(std::vector<VideoChannelDescription> &&requestedVideoChannels) { |
| 4071 | if (_streamingContext) { |
| 4072 | std::vector<StreamingMediaContext::VideoChannel> streamingVideoChannels; |
| 4073 | for (const auto &it : requestedVideoChannels) { |
| 4074 | streamingVideoChannels.emplace_back(it.maxQuality, it.endpointId); |
| 4075 | } |
| 4076 | _streamingContext->setActiveVideoChannels(streamingVideoChannels); |
| 4077 | } |
| 4078 |
| 4079 | if (!_sharedVideoInformation) { |
| 4080 | _pendingRequestedVideo = std::move(requestedVideoChannels); |
| 4081 | return; |
| 4082 | } |
| 4083 | bool updated = false; |
| 4084 | std::vector<std::string> allEndpointIds; |
| 4085 |
| 4086 | for (const auto &description : requestedVideoChannels) { |
| 4087 | if (_sharedVideoInformation && _sharedVideoInformation->endpointId == description.endpointId) { |
| 4088 | continue; |
| 4089 | } |
| 4090 |
| 4091 | GroupParticipantVideoInformation videoInformation; |
| 4092 | videoInformation.endpointId = description.endpointId; |
| 4093 | for (const auto &group : description.ssrcGroups) { |
| 4094 | GroupJoinPayloadVideoSourceGroup parsedGroup; |
| 4095 | parsedGroup.semantics = group.semantics; |
| 4096 | parsedGroup.ssrcs = group.ssrcs; |
| 4097 | videoInformation.ssrcGroups.push_back(std::move(parsedGroup)); |
| 4098 | } |
| 4099 |
| 4100 | allEndpointIds.push_back(videoInformation.endpointId); |
| 4101 |
| 4102 | auto current = _incomingVideoChannels.find(VideoChannelId(videoInformation.endpointId)); |
| 4103 | if (current != _incomingVideoChannels.end()) { |
| 4104 | if (current->second->requestedMinQuality() != description.minQuality || current->second->requestedMaxQuality() != description.maxQuality) { |
| 4105 | current->second->setRequstedMinQuality(description.minQuality); |
| 4106 | current->second->setRequstedMaxQuality(description.maxQuality); |
| 4107 | updated = true; |
| 4108 | } |
| 4109 | continue; |
| 4110 | } |
| 4111 |
| 4112 | addIncomingVideoChannel(description.audioSsrc, description.userId, videoInformation, description.minQuality, description.maxQuality); |
| 4113 | updated = true; |
| 4114 | } |
| 4115 |
| 4116 | std::vector<std::string> removeEndpointIds; |
| 4117 | for (const auto &it : _incomingVideoChannels) { |
| 4118 | if (std::find(allEndpointIds.begin(), allEndpointIds.end(), it.first.endpointId) == allEndpointIds.end()) { |
| 4119 | removeEndpointIds.push_back(it.first.endpointId); |
| 4120 | updated = true; |
| 4121 | } |
| 4122 | } |
| 4123 |
| 4124 | for (const auto &endpointId : removeEndpointIds) { |
| 4125 | const auto it = _incomingVideoChannels.find(VideoChannelId(endpointId)); |
| 4126 | if (it != _incomingVideoChannels.end()) { |
| 4127 | auto sinks = it->second->getSinks(); |
| 4128 | for (const auto &sink : sinks) { |
| 4129 | _pendingVideoSinks[VideoChannelId(endpointId)].push_back(sink); |
| 4130 | } |
| 4131 | _incomingVideoChannels.erase(it); |
| 4132 | } |
| 4133 | } |
| 4134 |
| 4135 | if (updated) { |
| 4136 | maybeUpdateRemoteVideoConstraints(); |
| 4137 | } |
| 4138 | } |
| 4139 |
| 4140 | void getStats(std::function<void(GroupInstanceStats)> completion) { |
| 4141 | GroupInstanceStats result; |
| 4142 |
| 4143 | for (const auto &it : _incomingVideoChannels) { |
| 4144 | const auto videoStats = it.second->getStats(); |
| 4145 | if (videoStats) { |
| 4146 | result.incomingVideoStats.push_back(std::make_pair(it.second->endpointId(), videoStats.value())); |
| 4147 | } |
| 4148 | } |
| 4149 |
| 4150 | completion(result); |
| 4151 | } |
| 4152 |
| 4153 | void internal_addCustomNetworkEvent(bool isRemoteConnected) { |
| 4154 | NetworkStateLogRecord record; |
| 4155 | record.isConnected = isRemoteConnected; |
| 4156 | record.isFailed = false; |
| 4157 |
| 4158 | _remoteNetworkStateLogRecords.emplace_back(rtc::TimeMillis(), std::move(record)); |
| 4159 | } |
| 4160 |
| 4161 | private: |
| 4162 | webrtc::scoped_refptr<WrappedAudioDeviceModule> createAudioDeviceModule() { |
| 4163 | auto audioDeviceDataObserverShared = _audioDeviceDataObserverShared; |
| 4164 | auto onMutedSpeechActivityDetected = _onMutedSpeechActivityDetected; |
| 4165 | #ifdef WEBRTC_IOS |
| 4166 | bool disableRecording = _disableAudioInput; |
| 4167 | bool enableSystemMute = _enableSystemMute; |
| 4168 | #endif |
| 4169 | const auto create = [&](webrtc::AudioDeviceModule::AudioLayer layer) { |
| 4170 | #ifdef WEBRTC_IOS |
| 4171 | auto result = rtc::make_ref_counted<webrtc::tgcalls_ios_adm::AudioDeviceModuleIOS>(false, disableRecording, enableSystemMute, disableRecording ? 2 : 1); |
| 4172 | if (result) { |
| 4173 | result->mutedSpeechDetectionChanged = ^(bool value) { |
| 4174 | if (onMutedSpeechActivityDetected) { |
| 4175 | onMutedSpeechActivityDetected(value); |
| 4176 | } |
| 4177 | }; |
| 4178 | } |
| 4179 | return result; |
| 4180 | #else |
| 4181 | return webrtc::AudioDeviceModule::Create( |
| 4182 | layer, |
| 4183 | &_webrtcEnvironment.task_queue_factory()); |
| 4184 | #endif |
| 4185 | }; |
| 4186 | const auto check = [&](const webrtc::scoped_refptr<webrtc::AudioDeviceModule> &result) -> webrtc::scoped_refptr<WrappedAudioDeviceModule> { |
| 4187 | if (!result) { |
| 4188 | return nullptr; |
| 4189 | } |
| 4190 |
| 4191 | auto audioDeviceObserver = std::make_unique<AudioDeviceDataObserverImpl>(audioDeviceDataObserverShared); |
| 4192 | auto module = webrtc::CreateAudioDeviceWithDataObserver(result, std::move(audioDeviceObserver)); |
| 4193 |
| 4194 | if (module->Init() == 0) { |
| 4195 | return PlatformInterface::SharedInstance()->wrapAudioDeviceModule(module); |
| 4196 | } else { |
| 4197 | return nullptr; |
| 4198 | } |
| 4199 | }; |
| 4200 | if (_createWrappedAudioDeviceModule) { |
| 4201 | auto result = _createWrappedAudioDeviceModule(&_webrtcEnvironment.task_queue_factory()); |
| 4202 | if (result) { |
| 4203 | if (audioDeviceDataObserverShared) { |
| 4204 | auto audioDeviceObserver = std::make_unique<AudioDeviceDataObserverImpl>(audioDeviceDataObserverShared); |
| 4205 | auto moduleWithObserver = webrtc::CreateAudioDeviceWithDataObserver(result, std::move(audioDeviceObserver)); |
| 4206 | return rtc::make_ref_counted<DefaultWrappedAudioDeviceModule>(moduleWithObserver); |
| 4207 | } else { |
| 4208 | return result; |
| 4209 | } |
| 4210 | } |
| 4211 | } |
| 4212 | if (_createAudioDeviceModule) { |
| 4213 | if (const auto result = check(_createAudioDeviceModule(&_webrtcEnvironment.task_queue_factory()))) { |
| 4214 | return result; |
| 4215 | } |
| 4216 | } else if (_videoContentType == VideoContentType::Screencast) { |
| 4217 | FakeAudioDeviceModule::Options options; |
| 4218 | options.num_channels = 1; |
| 4219 | return check(FakeAudioDeviceModule::Creator(nullptr, _externalAudioRecorder, options)(&_webrtcEnvironment.task_queue_factory())); |
| 4220 | } |
| 4221 | return check(create(webrtc::AudioDeviceModule::kPlatformDefaultAudio)); |
| 4222 | } |
| 4223 |
| 4224 | private: |
| 4225 | std::shared_ptr<Threads> _threads; |
| 4226 | GroupConnectionMode _connectionMode = GroupConnectionMode::GroupConnectionModeNone; |
| 4227 | bool _isUnifiedBroadcast = false; |
| 4228 |
| 4229 | std::string _statsLogPath; |
| 4230 | std::function<void(GroupNetworkState)> _networkStateUpdated; |
| 4231 | std::function<void(int)> _signalBarsUpdated; |
| 4232 | std::function<void(GroupLevelsUpdate const &)> _audioLevelsUpdated; |
| 4233 | std::function<void(GroupActivitiesUpdate const &)> _activitiesUpdated; |
| 4234 | std::function<void(uint32_t, const AudioFrame &)> _onAudioFrame; |
| 4235 | std::function<std::shared_ptr<RequestMediaChannelDescriptionTask>(std::vector<uint32_t> const &, std::function<void(std::vector<MediaChannelDescription> &&)>)> _requestMediaChannelDescriptions; |
| 4236 | std::function<std::shared_ptr<BroadcastPartTask>(std::function<void(int64_t)>)> _requestCurrentTime; |
| 4237 | std::function<std::shared_ptr<BroadcastPartTask>(std::shared_ptr<PlatformContext>, int64_t, int64_t, std::function<void(BroadcastPart &&)>)> _requestAudioBroadcastPart; |
| 4238 | std::function<std::shared_ptr<BroadcastPartTask>(std::shared_ptr<PlatformContext>, int64_t, int64_t, int32_t, VideoChannelDescription::Quality, std::function<void(BroadcastPart &&)>)> _requestVideoBroadcastPart; |
| 4239 | std::shared_ptr<VideoCaptureInterface> _videoCapture; |
| 4240 | std::shared_ptr<VideoSinkImpl> _videoCaptureSink; |
| 4241 | std::function<webrtc::scoped_refptr<webrtc::VideoTrackSourceInterface>()> _getVideoSource; |
| 4242 | bool _disableIncomingChannels = false; |
| 4243 | bool _useDummyChannel{true}; |
| 4244 | int _outgoingAudioBitrateKbit{32}; |
| 4245 | bool _disableOutgoingAudioProcessing{false}; |
| 4246 | #ifdef WEBRTC_IOS |
| 4247 | bool _disableAudioInput{false}; |
| 4248 | bool _enableSystemMute{false}; |
| 4249 | #endif |
| 4250 | bool _isConference{false}; |
| 4251 | int _minOutgoingVideoBitrateKbit{100}; |
| 4252 | VideoContentType _videoContentType{VideoContentType::None}; |
| 4253 | std::vector<VideoCodecName> _videoCodecPreferences; |
| 4254 | std::function<std::vector<uint8_t>(std::vector<uint8_t> const &, int64_t, bool, int32_t)> _e2eEncryptDecrypt; |
| 4255 |
| 4256 | int _nextMediaChannelDescriptionsRequestId = 0; |
| 4257 | std::map<int, RequestedMediaChannelDescriptions> _requestedMediaChannelDescriptions; |
| 4258 |
| 4259 | std::unique_ptr<ThreadLocalObject<GroupNetworkManager>> _networkManager; |
| 4260 |
| 4261 | std::unique_ptr<webrtc::RtcEventLogNull> _eventLog; |
| 4262 | webrtc::Environment _webrtcEnvironment; |
| 4263 | std::unique_ptr<webrtc::NetEqFactory> _netEqFactory; |
| 4264 | std::unique_ptr<webrtc::Call> _call; |
| 4265 | webrtc::LocalAudioSinkAdapter _audioSource; |
| 4266 | std::shared_ptr<AudioDeviceDataObserverShared> _audioDeviceDataObserverShared; |
| 4267 | webrtc::scoped_refptr<WrappedAudioDeviceModule> _audioDeviceModule; |
| 4268 | std::function<webrtc::scoped_refptr<webrtc::AudioDeviceModule>(webrtc::TaskQueueFactory*)> _createAudioDeviceModule; |
| 4269 | std::function<webrtc::scoped_refptr<WrappedAudioDeviceModule>(webrtc::TaskQueueFactory*)> _createWrappedAudioDeviceModule; |
| 4270 | std::string _initialInputDeviceId; |
| 4271 | std::string _initialOutputDeviceId; |
| 4272 |
| 4273 | // _outgoingAudioChannel memory is managed by _channelManager |
| 4274 | cricket::VoiceChannel *_outgoingAudioChannel = nullptr; |
| 4275 | uint32_t _outgoingAudioSsrc = 0; |
| 4276 |
| 4277 | std::vector<webrtc::SdpVideoFormat> _availableVideoFormats; |
| 4278 | std::vector<OutgoingVideoFormat> _availablePayloadTypes; |
| 4279 | absl::optional<OutgoingVideoFormat> _selectedPayloadType; |
| 4280 |
| 4281 | std::vector<GroupJoinPayloadVideoPayloadType> _videoPayloadTypes; |
| 4282 | std::vector<std::pair<uint32_t, std::string>> _videoExtensionMap; |
| 4283 | std::vector<GroupJoinPayloadVideoSourceGroup> _videoSourceGroups; |
| 4284 |
| 4285 | std::unique_ptr<rtc::UniqueRandomIdGenerator> _uniqueRandomIdGenerator; |
| 4286 | webrtc::RtpTransport *_rtpTransport = nullptr; |
| 4287 | std::unique_ptr<ChannelManager> _channelManager; |
| 4288 |
| 4289 | std::unique_ptr<webrtc::VideoBitrateAllocatorFactory> _videoBitrateAllocatorFactory; |
| 4290 | // _outgoingVideoChannel memory is managed by _channelManager |
| 4291 | cricket::VideoChannel *_outgoingVideoChannel = nullptr; |
| 4292 | VideoSsrcs _outgoingVideoSsrcs; |
| 4293 | int _outgoingVideoConstraint = 720; |
| 4294 | int _pendingOutgoingVideoConstraint = -1; |
| 4295 | int _pendingOutgoingVideoConstraintRequestId = 0; |
| 4296 |
| 4297 | std::map<ChannelId, InternalGroupLevelValue> _audioLevels; |
| 4298 | std::shared_ptr<MyAudioLevelHolder> _myAudioLevel; |
| 4299 | std::shared_ptr<AudioLevelAndSpeechHolder> _myAudioLevelAndSpeech; |
| 4300 | std::map<ChannelId, InternalGroupActivityValue> _ssrcActivities; |
| 4301 |
| 4302 | bool _isMuted = true; |
| 4303 | std::shared_ptr<NoiseSuppressionConfiguration> _noiseSuppressionConfiguration; |
| 4304 |
| 4305 | MissingSsrcPacketBuffer _missingPacketBuffer; |
| 4306 | std::map<uint32_t, ChannelSsrcInfo> _channelBySsrc; |
| 4307 | std::map<uint32_t, double> _volumeBySsrc; |
| 4308 | std::map<ChannelId, std::unique_ptr<IncomingAudioChannel>> _incomingAudioChannels; |
| 4309 | std::map<VideoChannelId, std::unique_ptr<IncomingVideoChannel>> _incomingVideoChannels; |
| 4310 |
| 4311 | std::map<VideoChannelId, std::vector<std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>>>> _pendingVideoSinks; |
| 4312 | std::vector<VideoChannelDescription> _pendingRequestedVideo; |
| 4313 |
| 4314 | std::unique_ptr<IncomingVideoChannel> _serverBandwidthProbingVideoSsrc; |
| 4315 |
| 4316 | absl::optional<GroupJoinVideoInformation> _sharedVideoInformation; |
| 4317 |
| 4318 | std::vector<float> _externalAudioSamples; |
| 4319 | webrtc::Mutex _externalAudioSamplesMutex; |
| 4320 | std::shared_ptr<ExternalAudioRecorder> _externalAudioRecorder; |
| 4321 |
| 4322 | bool _isRtcConnected = false; |
| 4323 | bool _isBroadcastConnected = false; |
| 4324 | absl::optional<int64_t> _broadcastEnabledUntilRtcIsConnectedAtTimestamp; |
| 4325 | bool _isDataChannelOpen = false; |
| 4326 | GroupNetworkState _effectiveNetworkState; |
| 4327 |
| 4328 | int64_t _startTimestamp = 0; |
| 4329 | bool _hasBeenConnected = false; |
| 4330 |
| 4331 | absl::optional<NetworkStateLogRecord> _currentNetworkStateLogRecord; |
| 4332 | std::vector<StateLogRecord<NetworkStateLogRecord>> _networkStateLogRecords; |
| 4333 | std::vector<StateLogRecord<NetworkStateLogRecord>> _remoteNetworkStateLogRecords; |
| 4334 | std::vector<StateLogRecord<NetworkBitrateLogRecord>> _networkBitrateLogRecords; |
| 4335 |
| 4336 | std::shared_ptr<StreamingMediaContext> _streamingContext; |
| 4337 |
| 4338 | webrtc::scoped_refptr<webrtc::PendingTaskSafetyFlag> _workerThreadSafery; |
| 4339 | webrtc::scoped_refptr<webrtc::PendingTaskSafetyFlag> _networkThreadSafery; |
| 4340 |
| 4341 | std::function<void(bool)> _onMutedSpeechActivityDetected; |
| 4342 | std::shared_ptr<PlatformContext> _platformContext; |
| 4343 |
| 4344 | std::map<int32_t, FrameTransformerPayloadType> _payloadTypeMapping; |
| 4345 | }; |
| 4346 |
| 4347 | GroupInstanceCustomImpl::GroupInstanceCustomImpl(GroupInstanceDescriptor &&descriptor) { |
| 4348 | if (descriptor.config.need_log) { |
| 4349 | _logSink = std::make_unique<LogSinkImpl>(descriptor.config.logPath); |
| 4350 | rtc::LogMessage::SetLogToStderr(true); |
| 4351 | } else { |
| 4352 | rtc::LogMessage::SetLogToStderr(false); |
| 4353 | } |
| 4354 | rtc::LogMessage::LogToDebug(rtc::LS_INFO); |
| 4355 | if (_logSink) { |
| 4356 | rtc::LogMessage::AddLogToStream(_logSink.get(), rtc::LS_INFO); |
| 4357 | } |
| 4358 |
| 4359 | _threads = descriptor.threads; |
| 4360 | _internal.reset(new ThreadLocalObject<GroupInstanceCustomInternal>(_threads->getMediaThread(), [descriptor = std::move(descriptor), threads = _threads]() mutable { |
| 4361 | return std::make_shared<GroupInstanceCustomInternal>(std::move(descriptor), threads); |
| 4362 | })); |
| 4363 | _internal->perform([](GroupInstanceCustomInternal *internal) { |
| 4364 | internal->start(); |
| 4365 | }); |
| 4366 | } |
| 4367 |
| 4368 | GroupInstanceCustomImpl::~GroupInstanceCustomImpl() { |
| 4369 | if (_logSink) { |
| 4370 | rtc::LogMessage::RemoveLogToStream(_logSink.get()); |
| 4371 | } |
| 4372 | _internal.reset(); |
| 4373 |
| 4374 | // Wait until _internal is destroyed |
| 4375 | _threads->getMediaThread()->BlockingCall([] {}); |
| 4376 | } |
| 4377 |
| 4378 | void GroupInstanceCustomImpl::stop(std::function<void()> completion) { |
| 4379 | _internal->perform([completion](GroupInstanceCustomInternal *internal) { |
| 4380 | internal->stop(); |
| 4381 | if (completion) { |
| 4382 | completion(); |
| 4383 | } |
| 4384 | }); |
| 4385 | } |
| 4386 |
| 4387 | void GroupInstanceCustomImpl::setConnectionMode(GroupConnectionMode connectionMode, bool keepBroadcastIfWasEnabled, bool isUnifiedBroadcast) { |
| 4388 | _internal->perform([connectionMode, keepBroadcastIfWasEnabled, isUnifiedBroadcast](GroupInstanceCustomInternal *internal) { |
| 4389 | internal->setConnectionMode(connectionMode, keepBroadcastIfWasEnabled, isUnifiedBroadcast); |
| 4390 | }); |
| 4391 | } |
| 4392 |
| 4393 | void GroupInstanceCustomImpl::emitJoinPayload(std::function<void(GroupJoinPayload const &)> completion) { |
| 4394 | _internal->perform([completion](GroupInstanceCustomInternal *internal) { |
| 4395 | internal->emitJoinPayload(completion); |
| 4396 | }); |
| 4397 | } |
| 4398 |
| 4399 | void GroupInstanceCustomImpl::setJoinResponsePayload(std::string const &payload) { |
| 4400 | _internal->perform([payload](GroupInstanceCustomInternal *internal) { |
| 4401 | internal->setJoinResponsePayload(payload); |
| 4402 | }); |
| 4403 | } |
| 4404 |
| 4405 | void GroupInstanceCustomImpl::removeSsrcs(std::vector<uint32_t> ssrcs) { |
| 4406 | _internal->perform([ssrcs = std::move(ssrcs)](GroupInstanceCustomInternal *internal) mutable { |
| 4407 | internal->removeSsrcs(ssrcs); |
| 4408 | }); |
| 4409 | } |
| 4410 |
| 4411 | void GroupInstanceCustomImpl::removeIncomingVideoSource(uint32_t ssrc) { |
| 4412 | _internal->perform([ssrc](GroupInstanceCustomInternal *internal) mutable { |
| 4413 | internal->removeIncomingVideoSource(ssrc); |
| 4414 | }); |
| 4415 | } |
| 4416 |
| 4417 | void GroupInstanceCustomImpl::setIsMuted(bool isMuted) { |
| 4418 | _internal->perform([isMuted](GroupInstanceCustomInternal *internal) { |
| 4419 | internal->setIsMuted(isMuted); |
| 4420 | }); |
| 4421 | } |
| 4422 |
| 4423 | void GroupInstanceCustomImpl::setIsNoiseSuppressionEnabled(bool isNoiseSuppressionEnabled) { |
| 4424 | _internal->perform([isNoiseSuppressionEnabled](GroupInstanceCustomInternal *internal) { |
| 4425 | internal->setIsNoiseSuppressionEnabled(isNoiseSuppressionEnabled); |
| 4426 | }); |
| 4427 | } |
| 4428 |
| 4429 | void GroupInstanceCustomImpl::setVideoCapture(std::shared_ptr<VideoCaptureInterface> videoCapture) { |
| 4430 | _internal->perform([videoCapture](GroupInstanceCustomInternal *internal) { |
| 4431 | internal->setVideoCapture(videoCapture, false); |
| 4432 | }); |
| 4433 | } |
| 4434 |
| 4435 | void GroupInstanceCustomImpl::setVideoSource(std::function<webrtc::scoped_refptr<webrtc::VideoTrackSourceInterface>()> getVideoSource) { |
| 4436 | _internal->perform([getVideoSource](GroupInstanceCustomInternal *internal) { |
| 4437 | internal->setVideoSource(getVideoSource, false); |
| 4438 | }); |
| 4439 | } |
| 4440 |
| 4441 | void GroupInstanceCustomImpl::setAudioOutputDevice(std::string id) { |
| 4442 | _internal->perform([id](GroupInstanceCustomInternal *internal) { |
| 4443 | internal->setAudioOutputDevice(id); |
| 4444 | }); |
| 4445 | } |
| 4446 |
| 4447 | void GroupInstanceCustomImpl::setAudioInputDevice(std::string id) { |
| 4448 | _internal->perform([id](GroupInstanceCustomInternal *internal) { |
| 4449 | internal->setAudioInputDevice(id); |
| 4450 | }); |
| 4451 | } |
| 4452 |
| 4453 | void GroupInstanceCustomImpl::addExternalAudioSamples(std::vector<uint8_t> &&samples) { |
| 4454 | _internal->perform([samples = std::move(samples)](GroupInstanceCustomInternal *internal) mutable { |
| 4455 | internal->addExternalAudioSamples(std::move(samples)); |
| 4456 | }); |
| 4457 | } |
| 4458 |
| 4459 | void GroupInstanceCustomImpl::addOutgoingVideoOutput(std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) { |
| 4460 | _internal->perform([sink](GroupInstanceCustomInternal *internal) mutable { |
| 4461 | internal->addOutgoingVideoOutput(sink); |
| 4462 | }); |
| 4463 | } |
| 4464 |
| 4465 | void GroupInstanceCustomImpl::addIncomingVideoOutput(std::string const &endpointId, std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) { |
| 4466 | _internal->perform([endpointId, sink](GroupInstanceCustomInternal *internal) mutable { |
| 4467 | internal->addIncomingVideoOutput(endpointId, sink); |
| 4468 | }); |
| 4469 | } |
| 4470 |
| 4471 | void GroupInstanceCustomImpl::setVolume(uint32_t ssrc, double volume) { |
| 4472 | _internal->perform([ssrc, volume](GroupInstanceCustomInternal *internal) { |
| 4473 | internal->setVolume(ssrc, volume); |
| 4474 | }); |
| 4475 | } |
| 4476 |
| 4477 | void GroupInstanceCustomImpl::setRequestedVideoChannels(std::vector<VideoChannelDescription> &&requestedVideoChannels) { |
| 4478 | _internal->perform([requestedVideoChannels = std::move(requestedVideoChannels)](GroupInstanceCustomInternal *internal) mutable { |
| 4479 | internal->setRequestedVideoChannels(std::move(requestedVideoChannels)); |
| 4480 | }); |
| 4481 | } |
| 4482 |
| 4483 | void GroupInstanceCustomImpl::getStats(std::function<void(GroupInstanceStats)> completion) { |
| 4484 | _internal->perform([completion = std::move(completion)](GroupInstanceCustomInternal *internal) mutable { |
| 4485 | internal->getStats(completion); |
| 4486 | }); |
| 4487 | } |
| 4488 |
| 4489 | void GroupInstanceCustomImpl::internal_addCustomNetworkEvent(bool isRemoteConnected) { |
| 4490 | _internal->perform([isRemoteConnected](GroupInstanceCustomInternal *internal) { |
| 4491 | internal->internal_addCustomNetworkEvent(isRemoteConnected); |
| 4492 | }); |
| 4493 | } |
| 4494 |
| 4495 | std::vector<GroupInstanceInterface::AudioDevice> GroupInstanceInterface::getAudioDevices(AudioDevice::Type type) { |
| 4496 | auto result = std::vector<AudioDevice>(); |
| 4497 | #ifdef WEBRTC_LINUX //Not needed for ios, and some crl::sync stuff is needed for windows |
| 4498 | const auto resolve = [&] { |
| 4499 | const auto queueFactory = webrtc::CreateDefaultTaskQueueFactory(); |
| 4500 | const auto info = webrtc::AudioDeviceModule::Create( |
| 4501 | webrtc::AudioDeviceModule::kPlatformDefaultAudio, |
| 4502 | queueFactory.get()); |
| 4503 | if (!info || info->Init() < 0) { |
| 4504 | return; |
| 4505 | } |
| 4506 | const auto count = type == AudioDevice::Type::Input ? info->RecordingDevices() : info->PlayoutDevices(); |
| 4507 | if (count <= 0) { |
| 4508 | return; |
| 4509 | } |
| 4510 | for (auto i = int16_t(); i != count; ++i) { |
| 4511 | char name[webrtc::kAdmMaxDeviceNameSize + 1] = { 0 }; |
| 4512 | char id[webrtc::kAdmMaxGuidSize + 1] = { 0 }; |
| 4513 | if (type == AudioDevice::Type::Input) { |
| 4514 | info->RecordingDeviceName(i, name, id); |
| 4515 | } else { |
| 4516 | info->PlayoutDeviceName(i, name, id); |
| 4517 | } |
| 4518 | result.push_back({ id, name }); |
| 4519 | } |
| 4520 | }; |
| 4521 | resolve(); |
| 4522 | #endif |
| 4523 | return result; |
| 4524 | } |
| 4525 |
| 4526 | } // namespace tgcalls |
| 4527 |