| #include "rtc_base/thread.h" |
| 6 | #include "rtc_base/logging.h" |
| 7 | #include "api/peer_connection_interface.h" |
| 8 | #include "api/task_queue/default_task_queue_factory.h" |
| 9 | #include "media/engine/webrtc_media_engine.h" |
| 10 | #include "api/audio_codecs/audio_decoder_factory_template.h" |
| 11 | #include "api/audio_codecs/audio_encoder_factory_template.h" |
| 12 | #include "api/audio_codecs/opus/audio_decoder_opus.h" |
| 13 | #include "api/audio_codecs/opus/audio_encoder_opus.h" |
| 14 | #include "api/audio_codecs/builtin_audio_encoder_factory.h" |
| 15 | #include "api/audio_codecs/builtin_audio_decoder_factory.h" |
| 16 | #include "api/rtc_event_log/rtc_event_log_factory.h" |
| 17 | #include "api/peer_connection_interface.h" |
| 18 | #include "api/video_track_source_proxy.h" |
| 19 | #include "system_wrappers/include/field_trial.h" |
| 20 | #include "api/stats/rtcstats_objects.h" |
| 21 | #include "modules/audio_processing/audio_buffer.h" |
| 22 | #include "modules/audio_device/include/audio_device_factory.h" |
| 23 | #include "common_audio/include/audio_util.h" |
| 24 | #include "common_audio/vad/include/webrtc_vad.h" |
| 25 | #include "modules/audio_processing/agc2/vad_with_level.h" |
| 26 |
| 27 | #include "ThreadLocalObject.h" |
| 28 | #include "Manager.h" |
| 29 | #include "NetworkManager.h" |
| 30 | #include "VideoCaptureInterfaceImpl.h" |
| 31 | #include "platform/PlatformInterface.h" |
| 32 | #include "LogSinkImpl.h" |
| 33 |
| 34 | #include <random> |
| 35 | #include <sstream> |
| 36 | #include <iostream> |
| 37 |
| 38 | namespace tgcalls { |
| 39 |
| 40 | namespace { |
| 41 |
| 42 | static std::vector<std::string> splitSdpLines(std::string const &sdp) { |
| 43 | std::vector<std::string> result; |
| 44 |
| 45 | std::istringstream sdpStream(sdp); |
| 46 |
| 47 | std::string s; |
| 48 | while (std::getline(sdpStream, s, '\n')) { |
| 49 | if (s.size() == 0) { |
| 50 | continue; |
| 51 | } |
| 52 | if (s[s.size() - 1] == '\r') { |
| 53 | s.resize(s.size() - 1); |
| 54 | } |
| 55 | result.push_back(s); |
| 56 | } |
| 57 |
| 58 | return result; |
| 59 | } |
| 60 |
| 61 | static std::vector<std::string> splitFingerprintLines(std::string const &line) { |
| 62 | std::vector<std::string> result; |
| 63 |
| 64 | std::istringstream sdpStream(line); |
| 65 |
| 66 | std::string s; |
| 67 | while (std::getline(sdpStream, s, ' ')) { |
| 68 | if (s.size() == 0) { |
| 69 | continue; |
| 70 | } |
| 71 | result.push_back(s); |
| 72 | } |
| 73 |
| 74 | return result; |
| 75 | } |
| 76 |
| 77 | static std::vector<std::string> getLines(std::vector<std::string> const &lines, std::string prefix) { |
| 78 | std::vector<std::string> result; |
| 79 |
| 80 | for (auto &line : lines) { |
| 81 | if (line.find(prefix) == 0) { |
| 82 | auto cleanLine = line; |
| 83 | cleanLine.replace(0, prefix.size(), ""); |
| 84 | result.push_back(cleanLine); |
| 85 | } |
| 86 | } |
| 87 |
| 88 | return result; |
| 89 | } |
| 90 |
| 91 | static absl::optional<GroupJoinPayload> parseSdpIntoJoinPayload(std::string const &sdp) { |
| 92 | GroupJoinPayload result; |
| 93 |
| 94 | auto lines = splitSdpLines(sdp); |
| 95 |
| 96 | std::vector<std::string> audioLines; |
| 97 | bool isAudioLine = false; |
| 98 | for (auto &line : lines) { |
| 99 | if (line.find("m=audio") == 0) { |
| 100 | isAudioLine = true; |
| 101 | } |
| 102 | if (isAudioLine) { |
| 103 | audioLines.push_back(line); |
| 104 | } |
| 105 | } |
| 106 |
| 107 | /*std::vector<uint32_t> audioSources; |
| 108 | for (auto &line : getLines(audioLines, "a=ssrc:")) { |
| 109 | std::istringstream iss(line); |
| 110 | uint32_t value = 0; |
| 111 | iss >> value; |
| 112 | if (std::find(audioSources.begin(), audioSources.end(), value) == audioSources.end()) { |
| 113 | audioSources.push_back(value); |
| 114 | } |
| 115 | } |
| 116 |
| 117 | if (audioSources.size() != 1) { |
| 118 | return absl::nullopt; |
| 119 | } |
| 120 | result.ssrc = audioSources[0];*/ |
| 121 | result.ssrc = 0; |
| 122 |
| 123 | auto ufragLines = getLines(lines, "a=ice-ufrag:"); |
| 124 | if (ufragLines.size() != 1) { |
| 125 | return absl::nullopt; |
| 126 | } |
| 127 | result.ufrag = ufragLines[0]; |
| 128 |
| 129 | auto pwdLines = getLines(lines, "a=ice-pwd:"); |
| 130 | if (pwdLines.size() != 1) { |
| 131 | return absl::nullopt; |
| 132 | } |
| 133 | result.pwd = pwdLines[0]; |
| 134 |
| 135 | for (auto &line : getLines(lines, "a=fingerprint:")) { |
| 136 | auto fingerprintComponents = splitFingerprintLines(line); |
| 137 | if (fingerprintComponents.size() != 2) { |
| 138 | continue; |
| 139 | } |
| 140 |
| 141 | GroupJoinPayloadFingerprint fingerprint; |
| 142 | fingerprint.hash = fingerprintComponents[0]; |
| 143 | fingerprint.fingerprint = fingerprintComponents[1]; |
| 144 | fingerprint.setup = "active"; |
| 145 | result.fingerprints.push_back(fingerprint); |
| 146 | } |
| 147 |
| 148 | return result; |
| 149 | } |
| 150 |
| 151 | struct StreamSpec { |
| 152 | bool isMain = false; |
| 153 | uint32_t streamId = 0; |
| 154 | uint32_t audioSsrcOrZero = 0; |
| 155 | bool isRemoved = false; |
| 156 | }; |
| 157 |
| 158 | static void appendSdp(std::vector<std::string> &lines, std::string const &line) { |
| 159 | lines.push_back(line); |
| 160 | } |
| 161 |
| 162 | static std::string createSdp(uint32_t sessionId, GroupJoinResponsePayload const &payload, bool isAnswer, std::vector<StreamSpec> const &bundleStreams) { |
| 163 | std::vector<std::string> sdp; |
| 164 |
| 165 | appendSdp(sdp, "v=0"); |
| 166 |
| 167 | std::ostringstream sessionIdString; |
| 168 | sessionIdString << "o=- "; |
| 169 | sessionIdString << sessionId; |
| 170 | sessionIdString << " 2 IN IP4 0.0.0.0"; |
| 171 | appendSdp(sdp, sessionIdString.str()); |
| 172 |
| 173 | appendSdp(sdp, "s=-"); |
| 174 | appendSdp(sdp, "t=0 0"); |
| 175 |
| 176 | std::ostringstream bundleString; |
| 177 | bundleString << "a=group:BUNDLE"; |
| 178 | for (auto &stream : bundleStreams) { |
| 179 | bundleString << " "; |
| 180 | if (stream.isMain) { |
| 181 | bundleString << "0"; |
| 182 | } else { |
| 183 | bundleString << "audio"; |
| 184 | bundleString << stream.streamId; |
| 185 | } |
| 186 | } |
| 187 | appendSdp(sdp, bundleString.str()); |
| 188 |
| 189 | appendSdp(sdp, "a=ice-lite"); |
| 190 |
| 191 | for (auto &stream : bundleStreams) { |
| 192 | std::ostringstream audioMidString; |
| 193 | if (stream.isMain) { |
| 194 | audioMidString << "0"; |
| 195 | } else { |
| 196 | audioMidString << "audio"; |
| 197 | audioMidString << stream.streamId; |
| 198 | } |
| 199 |
| 200 | std::ostringstream mLineString; |
| 201 | mLineString << "m=audio "; |
| 202 | if (stream.isMain) { |
| 203 | mLineString << "1"; |
| 204 | } else { |
| 205 | mLineString << "0"; |
| 206 | } |
| 207 | mLineString << " RTP/SAVPF 111 126"; |
| 208 |
| 209 | appendSdp(sdp, mLineString.str()); |
| 210 |
| 211 | if (stream.isMain) { |
| 212 | appendSdp(sdp, "c=IN IP4 0.0.0.0"); |
| 213 | } |
| 214 |
| 215 | std::ostringstream mLineMidString; |
| 216 | mLineMidString << "a=mid:"; |
| 217 | mLineMidString << audioMidString.str(); |
| 218 | appendSdp(sdp, mLineMidString.str()); |
| 219 |
| 220 | if (stream.isMain) { |
| 221 | std::ostringstream ufragString; |
| 222 | ufragString << "a=ice-ufrag:"; |
| 223 | ufragString << payload.ufrag; |
| 224 | appendSdp(sdp, ufragString.str()); |
| 225 |
| 226 | std::ostringstream pwdString; |
| 227 | pwdString << "a=ice-pwd:"; |
| 228 | pwdString << payload.pwd; |
| 229 | appendSdp(sdp, pwdString.str()); |
| 230 |
| 231 | for (auto &fingerprint : payload.fingerprints) { |
| 232 | std::ostringstream fingerprintString; |
| 233 | fingerprintString << "a=fingerprint:"; |
| 234 | fingerprintString << fingerprint.hash; |
| 235 | fingerprintString << " "; |
| 236 | fingerprintString << fingerprint.fingerprint; |
| 237 | appendSdp(sdp, fingerprintString.str()); |
| 238 | appendSdp(sdp, "a=setup:passive"); |
| 239 | } |
| 240 |
| 241 | for (auto &candidate : payload.candidates) { |
| 242 | std::ostringstream candidateString; |
| 243 | candidateString << "a=candidate:"; |
| 244 | candidateString << candidate.foundation; |
| 245 | candidateString << " "; |
| 246 | candidateString << candidate.component; |
| 247 | candidateString << " "; |
| 248 | candidateString << candidate.protocol; |
| 249 | candidateString << " "; |
| 250 | candidateString << candidate.priority; |
| 251 | candidateString << " "; |
| 252 | candidateString << candidate.ip; |
| 253 | candidateString << " "; |
| 254 | candidateString << candidate.port; |
| 255 | candidateString << " "; |
| 256 | candidateString << "typ "; |
| 257 | candidateString << candidate.type; |
| 258 | candidateString << " "; |
| 259 |
| 260 | if (candidate.type == "srflx" || candidate.type == "prflx" || candidate.type == "relay") { |
| 261 | if (candidate.relAddr.size() != 0 && candidate.relPort.size() != 0) { |
| 262 | candidateString << "raddr "; |
| 263 | candidateString << candidate.relAddr; |
| 264 | candidateString << " "; |
| 265 | candidateString << "rport "; |
| 266 | candidateString << candidate.relPort; |
| 267 | candidateString << " "; |
| 268 | } |
| 269 | } |
| 270 |
| 271 | if (candidate.protocol == "tcp") { |
| 272 | if (candidate.tcpType.size() != 0) { |
| 273 | candidateString << "tcptype "; |
| 274 | candidateString << candidate.tcpType; |
| 275 | candidateString << " "; |
| 276 | } |
| 277 | } |
| 278 |
| 279 | candidateString << "generation "; |
| 280 | candidateString << candidate.generation; |
| 281 |
| 282 | appendSdp(sdp, candidateString.str()); |
| 283 | } |
| 284 | } |
| 285 |
| 286 | appendSdp(sdp, "a=rtpmap:111 opus/48000/2"); |
| 287 | appendSdp(sdp, "a=rtpmap:126 telephone-event/8000"); |
| 288 | appendSdp(sdp, "a=fmtp:111 minptime=10; useinbandfec=1"); |
| 289 | appendSdp(sdp, "a=rtcp:1 IN IP4 0.0.0.0"); |
| 290 | appendSdp(sdp, "a=rtcp-mux"); |
| 291 | appendSdp(sdp, "a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level"); |
| 292 | appendSdp(sdp, "a=extmap:3 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"); |
| 293 | appendSdp(sdp, "a=extmap:5 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"); |
| 294 | appendSdp(sdp, "a=rtcp-fb:111 transport-cc"); |
| 295 |
| 296 | if (isAnswer && stream.isMain) { |
| 297 | appendSdp(sdp, "a=recvonly"); |
| 298 | } else { |
| 299 | if (stream.isMain) { |
| 300 | appendSdp(sdp, "a=sendrecv"); |
| 301 | } else { |
| 302 | appendSdp(sdp, "a=sendonly"); |
| 303 | appendSdp(sdp, "a=bundle-only"); |
| 304 | } |
| 305 |
| 306 | /*std::ostringstream ssrcGroupString; |
| 307 | ssrcGroupString << "a=ssrc-group:FID "; |
| 308 | ssrcGroupString << stream.audioSsrc; |
| 309 | appendSdp(sdp, ssrcGroupString.str());*/ |
| 310 |
| 311 | if (stream.isRemoved) { |
| 312 | appendSdp(sdp, "a=inactive"); |
| 313 | } else { |
| 314 | std::ostringstream cnameString; |
| 315 | cnameString << "a=ssrc:"; |
| 316 | cnameString << stream.audioSsrcOrZero; |
| 317 | cnameString << " cname:stream"; |
| 318 | cnameString << stream.streamId; |
| 319 | appendSdp(sdp, cnameString.str()); |
| 320 |
| 321 | std::ostringstream msidString; |
| 322 | msidString << "a=ssrc:"; |
| 323 | msidString << stream.audioSsrcOrZero; |
| 324 | msidString << " msid:stream"; |
| 325 | msidString << stream.streamId; |
| 326 | msidString << " audio" << stream.streamId; |
| 327 | appendSdp(sdp, msidString.str()); |
| 328 |
| 329 | std::ostringstream mslabelString; |
| 330 | mslabelString << "a=ssrc:"; |
| 331 | mslabelString << stream.audioSsrcOrZero; |
| 332 | mslabelString << " mslabel:audio"; |
| 333 | mslabelString << stream.streamId; |
| 334 | appendSdp(sdp, mslabelString.str()); |
| 335 |
| 336 | std::ostringstream labelString; |
| 337 | labelString << "a=ssrc:"; |
| 338 | labelString << stream.audioSsrcOrZero; |
| 339 | labelString << " label:audio"; |
| 340 | labelString << stream.streamId; |
| 341 | appendSdp(sdp, labelString.str()); |
| 342 | } |
| 343 | } |
| 344 | } |
| 345 |
| 346 | std::ostringstream result; |
| 347 | for (auto &line : sdp) { |
| 348 | result << line << "\n"; |
| 349 | } |
| 350 |
| 351 | return result.str(); |
| 352 | } |
| 353 |
| 354 | static std::string parseJoinResponseIntoSdp(uint32_t sessionId, uint32_t mainStreamAudioSsrc, GroupJoinResponsePayload const &payload, bool isAnswer, std::vector<uint32_t> const &allOtherSsrcs, std::set<uint32_t> const &activeOtherSsrcs) { |
| 355 |
| 356 | std::vector<StreamSpec> bundleStreams; |
| 357 |
| 358 | StreamSpec mainStream; |
| 359 | mainStream.isMain = true; |
| 360 | mainStream.streamId = 0; |
| 361 | mainStream.audioSsrcOrZero = mainStreamAudioSsrc; |
| 362 | mainStream.isRemoved = false; |
| 363 | bundleStreams.push_back(mainStream); |
| 364 |
| 365 | uint32_t numStreamsToAllocate = (uint32_t)allOtherSsrcs.size(); |
| 366 | /*if (numStreamsToAllocate < 10) { |
| 367 | numStreamsToAllocate = 10; |
| 368 | }*/ |
| 369 |
| 370 | for (uint32_t i = 0; i < numStreamsToAllocate; i++) { |
| 371 | StreamSpec stream; |
| 372 | stream.isMain = false; |
| 373 | if (i < allOtherSsrcs.size()) { |
| 374 | uint32_t ssrc = allOtherSsrcs[i]; |
| 375 | stream.audioSsrcOrZero = ssrc; |
| 376 | stream.isRemoved = activeOtherSsrcs.find(ssrc) == activeOtherSsrcs.end(); |
| 377 | stream.streamId = ssrc; |
| 378 | } else { |
| 379 | stream.audioSsrcOrZero = 0; |
| 380 | stream.isRemoved = true; |
| 381 | stream.streamId = 1 + (uint32_t)i; |
| 382 | } |
| 383 | bundleStreams.push_back(stream); |
| 384 | } |
| 385 |
| 386 | return createSdp(sessionId, payload, isAnswer, bundleStreams); |
| 387 | } |
| 388 |
| 389 | rtc::Thread *makeNetworkThread() { |
| 390 | static std::unique_ptr<rtc::Thread> value = rtc::Thread::CreateWithSocketServer(); |
| 391 | value->SetName("WebRTC-Group-Network", nullptr); |
| 392 | value->Start(); |
| 393 | return value.get(); |
| 394 | } |
| 395 |
| 396 | rtc::Thread *getNetworkThread() { |
| 397 | static rtc::Thread *value = makeNetworkThread(); |
| 398 | return value; |
| 399 | } |
| 400 |
| 401 | rtc::Thread *makeWorkerThread() { |
| 402 | static std::unique_ptr<rtc::Thread> value = rtc::Thread::Create(); |
| 403 | value->SetName("WebRTC-Group-Worker", nullptr); |
| 404 | value->Start(); |
| 405 | return value.get(); |
| 406 | } |
| 407 |
| 408 | rtc::Thread *getWorkerThread() { |
| 409 | static rtc::Thread *value = makeWorkerThread(); |
| 410 | return value; |
| 411 | } |
| 412 |
| 413 | rtc::Thread *getSignalingThread() { |
| 414 | return Manager::getMediaThread(); |
| 415 | } |
| 416 |
| 417 | rtc::Thread *getMediaThread() { |
| 418 | return Manager::getMediaThread(); |
| 419 | } |
| 420 |
| 421 | class FrameEncryptorImpl : public webrtc::FrameEncryptorInterface { |
| 422 | public: |
| 423 | FrameEncryptorImpl() { |
| 424 | } |
| 425 |
| 426 | virtual int Encrypt(cricket::MediaType media_type, |
| 427 | uint32_t ssrc, |
| 428 | rtc::ArrayView<const uint8_t> additional_data, |
| 429 | rtc::ArrayView<const uint8_t> frame, |
| 430 | rtc::ArrayView<uint8_t> encrypted_frame, |
| 431 | size_t* bytes_written) override { |
| 432 | memcpy(encrypted_frame.data(), frame.data(), frame.size()); |
| 433 | for (auto it = encrypted_frame.begin(); it != encrypted_frame.end(); it++) { |
| 434 | *it ^= 123; |
| 435 | } |
| 436 | *bytes_written = frame.size(); |
| 437 | return 0; |
| 438 | } |
| 439 |
| 440 | virtual size_t GetMaxCiphertextByteSize(cricket::MediaType media_type, |
| 441 | size_t frame_size) override { |
| 442 | return frame_size; |
| 443 | } |
| 444 | }; |
| 445 |
| 446 | class FrameDecryptorImpl : public webrtc::FrameDecryptorInterface { |
| 447 | public: |
| 448 | FrameDecryptorImpl() { |
| 449 | } |
| 450 |
| 451 | virtual webrtc::FrameDecryptorInterface::Result Decrypt(cricket::MediaType media_type, |
| 452 | const std::vector<uint32_t>& csrcs, |
| 453 | rtc::ArrayView<const uint8_t> additional_data, |
| 454 | rtc::ArrayView<const uint8_t> encrypted_frame, |
| 455 | rtc::ArrayView<uint8_t> frame) override { |
| 456 | memcpy(frame.data(), encrypted_frame.data(), encrypted_frame.size()); |
| 457 | for (auto it = frame.begin(); it != frame.end(); it++) { |
| 458 | *it ^= 123; |
| 459 | } |
| 460 | return webrtc::FrameDecryptorInterface::Result(webrtc::FrameDecryptorInterface::Status::kOk, encrypted_frame.size()); |
| 461 | } |
| 462 |
| 463 | virtual size_t GetMaxPlaintextByteSize(cricket::MediaType media_type, |
| 464 | size_t encrypted_frame_size) override { |
| 465 | return encrypted_frame_size; |
| 466 | } |
| 467 | }; |
| 468 |
| 469 | class PeerConnectionObserverImpl : public webrtc::PeerConnectionObserver { |
| 470 | private: |
| 471 | std::function<void(std::string, int, std::string)> _discoveredIceCandidate; |
| 472 | std::function<void(bool)> _connectionStateChanged; |
| 473 | std::function<void(rtc::scoped_refptr<webrtc::RtpTransceiverInterface>)> _onTrackAdded; |
| 474 | std::function<void(rtc::scoped_refptr<webrtc::RtpReceiverInterface>)> _onTrackRemoved; |
| 475 | std::function<void(uint32_t)> _onMissingSsrc; |
| 476 |
| 477 | public: |
| 478 | PeerConnectionObserverImpl( |
| 479 | std::function<void(std::string, int, std::string)> discoveredIceCandidate, |
| 480 | std::function<void(bool)> connectionStateChanged, |
| 481 | std::function<void(rtc::scoped_refptr<webrtc::RtpTransceiverInterface>)> onTrackAdded, |
| 482 | std::function<void(rtc::scoped_refptr<webrtc::RtpReceiverInterface>)> onTrackRemoved, |
| 483 | std::function<void(uint32_t)> onMissingSsrc |
| 484 | ) : |
| 485 | _discoveredIceCandidate(discoveredIceCandidate), |
| 486 | _connectionStateChanged(connectionStateChanged), |
| 487 | _onTrackAdded(onTrackAdded), |
| 488 | _onTrackRemoved(onTrackRemoved), |
| 489 | _onMissingSsrc(onMissingSsrc) { |
| 490 | } |
| 491 |
| 492 | virtual void OnSignalingChange(webrtc::PeerConnectionInterface::SignalingState new_state) override { |
| 493 | } |
| 494 |
| 495 | virtual void OnAddStream(rtc::scoped_refptr<webrtc::MediaStreamInterface> stream) override { |
| 496 | } |
| 497 |
| 498 | virtual void OnRemoveStream(rtc::scoped_refptr<webrtc::MediaStreamInterface> stream) override { |
| 499 | } |
| 500 |
| 501 | virtual void OnDataChannel(rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel) override { |
| 502 | } |
| 503 |
| 504 | virtual void OnRenegotiationNeeded() override { |
| 505 | } |
| 506 |
| 507 | virtual void OnIceConnectionChange(webrtc::PeerConnectionInterface::IceConnectionState new_state) override { |
| 508 | bool isConnected = false; |
| 509 | switch (new_state) { |
| 510 | case webrtc::PeerConnectionInterface::IceConnectionState::kIceConnectionConnected: |
| 511 | case webrtc::PeerConnectionInterface::IceConnectionState::kIceConnectionCompleted: |
| 512 | isConnected = true; |
| 513 | break; |
| 514 | default: |
| 515 | break; |
| 516 | } |
| 517 | _connectionStateChanged(isConnected); |
| 518 | } |
| 519 |
| 520 | virtual void OnStandardizedIceConnectionChange(webrtc::PeerConnectionInterface::IceConnectionState new_state) override { |
| 521 | } |
| 522 |
| 523 | virtual void OnConnectionChange(webrtc::PeerConnectionInterface::PeerConnectionState new_state) override { |
| 524 | } |
| 525 |
| 526 | virtual void OnIceGatheringChange(webrtc::PeerConnectionInterface::IceGatheringState new_state) override { |
| 527 | } |
| 528 |
| 529 | virtual void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override { |
| 530 | std::string sdp; |
| 531 | candidate->ToString(&sdp); |
| 532 | _discoveredIceCandidate(sdp, candidate->sdp_mline_index(), candidate->sdp_mid()); |
| 533 | } |
| 534 |
| 535 | virtual void OnIceCandidateError(const std::string& host_candidate, const std::string& url, int error_code, const std::string& error_text) override { |
| 536 | } |
| 537 |
| 538 | virtual void OnIceCandidateError(const std::string& address, |
| 539 | int port, |
| 540 | const std::string& url, |
| 541 | int error_code, |
| 542 | const std::string& error_text) override { |
| 543 | } |
| 544 |
| 545 | virtual void OnIceCandidatesRemoved(const std::vector<cricket::Candidate>& candidates) override { |
| 546 | } |
| 547 |
| 548 | virtual void OnIceConnectionReceivingChange(bool receiving) override { |
| 549 | } |
| 550 |
| 551 | virtual void OnIceSelectedCandidatePairChanged(const cricket::CandidatePairChangeEvent& event) override { |
| 552 | } |
| 553 |
| 554 | virtual void OnAddTrack(rtc::scoped_refptr<webrtc::RtpReceiverInterface> receiver, const std::vector<rtc::scoped_refptr<webrtc::MediaStreamInterface>>& streams) override { |
| 555 | } |
| 556 |
| 557 | virtual void OnTrack(rtc::scoped_refptr<webrtc::RtpTransceiverInterface> transceiver) override { |
| 558 | /*if (transceiver->receiver()) { |
| 559 | rtc::scoped_refptr<FrameDecryptorImpl> decryptor(new rtc::RefCountedObject<FrameDecryptorImpl>()); |
| 560 | transceiver->receiver()->SetFrameDecryptor(decryptor); |
| 561 | }*/ |
| 562 |
| 563 | _onTrackAdded(transceiver); |
| 564 | } |
| 565 |
| 566 | virtual void OnRemoveTrack(rtc::scoped_refptr<webrtc::RtpReceiverInterface> receiver) override { |
| 567 | _onTrackRemoved(receiver); |
| 568 | } |
| 569 |
| 570 | virtual void OnInterestingUsage(int usage_pattern) override { |
| 571 | } |
| 572 |
| 573 | virtual void OnErrorDemuxingPacket(uint32_t ssrc) override { |
| 574 | _onMissingSsrc(ssrc); |
| 575 | } |
| 576 | }; |
| 577 |
| 578 | class RTCStatsCollectorCallbackImpl : public webrtc::RTCStatsCollectorCallback { |
| 579 | public: |
| 580 | RTCStatsCollectorCallbackImpl(std::function<void(const rtc::scoped_refptr<const webrtc::RTCStatsReport> &)> completion) : |
| 581 | _completion(completion) { |
| 582 | } |
| 583 |
| 584 | virtual void OnStatsDelivered(const rtc::scoped_refptr<const webrtc::RTCStatsReport> &report) override { |
| 585 | _completion(report); |
| 586 | } |
| 587 |
| 588 | private: |
| 589 | std::function<void(const rtc::scoped_refptr<const webrtc::RTCStatsReport> &)> _completion; |
| 590 | }; |
| 591 |
| 592 | static const int kVadResultHistoryLength = 8; |
| 593 |
| 594 | class CombinedVad { |
| 595 | private: |
| 596 | webrtc::VadLevelAnalyzer _vadWithLevel; |
| 597 | float _vadResultHistory[kVadResultHistoryLength]; |
| 598 |
| 599 | public: |
| 600 | CombinedVad() { |
| 601 | for (int i = 0; i < kVadResultHistoryLength; i++) { |
| 602 | _vadResultHistory[i] = 0.0f; |
| 603 | } |
| 604 | } |
| 605 |
| 606 | ~CombinedVad() { |
| 607 | } |
| 608 |
| 609 | bool update(webrtc::AudioBuffer *buffer) { |
| 610 | webrtc::AudioFrameView<float> frameView(buffer->channels(), buffer->num_channels(), buffer->num_frames()); |
| 611 | auto result = _vadWithLevel.AnalyzeFrame(frameView); |
| 612 | for (int i = 1; i < kVadResultHistoryLength; i++) { |
| 613 | _vadResultHistory[i - 1] = _vadResultHistory[i]; |
| 614 | } |
| 615 | _vadResultHistory[kVadResultHistoryLength - 1] = result.speech_probability; |
| 616 |
| 617 | float movingAverage = 0.0f; |
| 618 | for (int i = 0; i < kVadResultHistoryLength; i++) { |
| 619 | movingAverage += _vadResultHistory[i]; |
| 620 | } |
| 621 | movingAverage /= (float)kVadResultHistoryLength; |
| 622 |
| 623 | bool vadResult = false; |
| 624 | if (movingAverage > 0.8f) { |
| 625 | vadResult = true; |
| 626 | } |
| 627 |
| 628 | return vadResult; |
| 629 | } |
| 630 | }; |
| 631 |
| 632 | class AudioTrackSinkInterfaceImpl: public webrtc::AudioTrackSinkInterface { |
| 633 | private: |
| 634 | std::function<void(float, bool)> _update; |
| 635 |
| 636 | int _peakCount = 0; |
| 637 | uint16_t _peak = 0; |
| 638 |
| 639 | CombinedVad _vad; |
| 640 |
| 641 | public: |
| 642 | AudioTrackSinkInterfaceImpl(std::function<void(float, bool)> update) : |
| 643 | _update(update) { |
| 644 | } |
| 645 |
| 646 | virtual ~AudioTrackSinkInterfaceImpl() { |
| 647 | } |
| 648 |
| 649 | virtual void OnData(const void *audio_data, int bits_per_sample, int sample_rate, size_t number_of_channels, size_t number_of_frames) override { |
| 650 | if (bits_per_sample == 16 && number_of_channels == 1) { |
| 651 | int16_t *samples = (int16_t *)audio_data; |
| 652 | int numberOfSamplesInFrame = (int)number_of_frames; |
| 653 |
| 654 | webrtc::AudioBuffer buffer(sample_rate, 1, 48000, 1, 48000, 1); |
| 655 | webrtc::StreamConfig config(sample_rate, 1); |
| 656 | buffer.CopyFrom(samples, config); |
| 657 |
| 658 | bool vadResult = _vad.update(&buffer); |
| 659 |
| 660 | for (int i = 0; i < numberOfSamplesInFrame; i++) { |
| 661 | int16_t sample = samples[i]; |
| 662 | if (sample < 0) { |
| 663 | sample = -sample; |
| 664 | } |
| 665 | if (_peak < sample) { |
| 666 | _peak = sample; |
| 667 | } |
| 668 | _peakCount += 1; |
| 669 | } |
| 670 |
| 671 | if (_peakCount >= 1200) { |
| 672 | float level = ((float)(_peak)) / 4000.0f; |
| 673 | _peak = 0; |
| 674 | _peakCount = 0; |
| 675 | _update(level, vadResult); |
| 676 | } |
| 677 | } |
| 678 | } |
| 679 | }; |
| 680 |
| 681 | class CreateSessionDescriptionObserverImpl : public webrtc::CreateSessionDescriptionObserver { |
| 682 | private: |
| 683 | std::function<void(std::string, std::string)> _completion; |
| 684 |
| 685 | public: |
| 686 | CreateSessionDescriptionObserverImpl(std::function<void(std::string, std::string)> completion) : |
| 687 | _completion(completion) { |
| 688 | } |
| 689 |
| 690 | virtual void OnSuccess(webrtc::SessionDescriptionInterface* desc) override { |
| 691 | if (desc) { |
| 692 | std::string sdp; |
| 693 | desc->ToString(&sdp); |
| 694 |
| 695 | _completion(sdp, desc->type()); |
| 696 | } |
| 697 | } |
| 698 |
| 699 | virtual void OnFailure(webrtc::RTCError error) override { |
| 700 | } |
| 701 | }; |
| 702 |
| 703 | class SetSessionDescriptionObserverImpl : public webrtc::SetSessionDescriptionObserver { |
| 704 | private: |
| 705 | std::function<void()> _completion; |
| 706 | std::function<void(webrtc::RTCError)> _error; |
| 707 |
| 708 | public: |
| 709 | SetSessionDescriptionObserverImpl(std::function<void()> completion, std::function<void(webrtc::RTCError)> error) : |
| 710 | _completion(completion), _error(error) { |
| 711 | } |
| 712 |
| 713 | virtual void OnSuccess() override { |
| 714 | _completion(); |
| 715 | } |
| 716 |
| 717 | virtual void OnFailure(webrtc::RTCError error) override { |
| 718 | _error(error); |
| 719 | } |
| 720 | }; |
| 721 |
| 722 | class AudioCaptureAnalyzer : public webrtc::CustomAudioAnalyzer { |
| 723 | private: |
| 724 | void Initialize(int sample_rate_hz, int num_channels) override { |
| 725 |
| 726 | } |
| 727 | // Analyzes the given capture or render signal. |
| 728 | void Analyze(const webrtc::AudioBuffer* audio) override { |
| 729 | _analyze(audio); |
| 730 | } |
| 731 | // Returns a string representation of the module state. |
| 732 | std::string ToString() const override { |
| 733 | return "analyzing"; |
| 734 | } |
| 735 |
| 736 | std::function<void(const webrtc::AudioBuffer*)> _analyze; |
| 737 |
| 738 | public: |
| 739 | AudioCaptureAnalyzer(std::function<void(const webrtc::AudioBuffer*)> analyze) : |
| 740 | _analyze(analyze) { |
| 741 | } |
| 742 |
| 743 | virtual ~AudioCaptureAnalyzer() = default; |
| 744 | }; |
| 745 |
| 746 | class WrappedAudioDeviceModule : public webrtc::AudioDeviceModule { |
| 747 | private: |
| 748 | rtc::scoped_refptr<webrtc::AudioDeviceModule> _impl; |
| 749 |
| 750 | public: |
| 751 | WrappedAudioDeviceModule(rtc::scoped_refptr<webrtc::AudioDeviceModule> impl) : |
| 752 | _impl(impl) { |
| 753 | } |
| 754 |
| 755 | virtual ~WrappedAudioDeviceModule() { |
| 756 | } |
| 757 |
| 758 | virtual int32_t ActiveAudioLayer(AudioLayer *audioLayer) const override { |
| 759 | return _impl->ActiveAudioLayer(audioLayer); |
| 760 | } |
| 761 |
| 762 | virtual int32_t RegisterAudioCallback(webrtc::AudioTransport *audioCallback) override { |
| 763 | return _impl->RegisterAudioCallback(audioCallback); |
| 764 | } |
| 765 |
| 766 | virtual int32_t Init() override { |
| 767 | return _impl->Init(); |
| 768 | } |
| 769 |
| 770 | virtual int32_t Terminate() override { |
| 771 | return _impl->Terminate(); |
| 772 | } |
| 773 |
| 774 | virtual bool Initialized() const override { |
| 775 | return _impl->Initialized(); |
| 776 | } |
| 777 |
| 778 | virtual int16_t PlayoutDevices() override { |
| 779 | return _impl->PlayoutDevices(); |
| 780 | } |
| 781 |
| 782 | virtual int16_t RecordingDevices() override { |
| 783 | return _impl->RecordingDevices(); |
| 784 | } |
| 785 |
| 786 | virtual int32_t PlayoutDeviceName(uint16_t index, char name[webrtc::kAdmMaxDeviceNameSize], char guid[webrtc::kAdmMaxGuidSize]) override { |
| 787 | return _impl->PlayoutDeviceName(index, name, guid); |
| 788 | } |
| 789 |
| 790 | virtual int32_t RecordingDeviceName(uint16_t index, char name[webrtc::kAdmMaxDeviceNameSize], char guid[webrtc::kAdmMaxGuidSize]) override { |
| 791 | return _impl->RecordingDeviceName(index, name, guid); |
| 792 | } |
| 793 |
| 794 | virtual int32_t SetPlayoutDevice(uint16_t index) override { |
| 795 | return _impl->SetPlayoutDevice(index); |
| 796 | } |
| 797 |
| 798 | virtual int32_t SetPlayoutDevice(WindowsDeviceType device) override { |
| 799 | return _impl->SetPlayoutDevice(device); |
| 800 | } |
| 801 |
| 802 | virtual int32_t SetRecordingDevice(uint16_t index) override { |
| 803 | return _impl->SetRecordingDevice(index); |
| 804 | } |
| 805 |
| 806 | virtual int32_t SetRecordingDevice(WindowsDeviceType device) override { |
| 807 | return _impl->SetRecordingDevice(device); |
| 808 | } |
| 809 |
| 810 | virtual int32_t PlayoutIsAvailable(bool *available) override { |
| 811 | return _impl->PlayoutIsAvailable(available); |
| 812 | } |
| 813 |
| 814 | virtual int32_t InitPlayout() override { |
| 815 | return _impl->InitPlayout(); |
| 816 | } |
| 817 |
| 818 | virtual bool PlayoutIsInitialized() const override { |
| 819 | return _impl->PlayoutIsInitialized(); |
| 820 | } |
| 821 |
| 822 | virtual int32_t RecordingIsAvailable(bool *available) override { |
| 823 | return _impl->RecordingIsAvailable(available); |
| 824 | } |
| 825 |
| 826 | virtual int32_t InitRecording() override { |
| 827 | return _impl->InitRecording(); |
| 828 | } |
| 829 |
| 830 | virtual bool RecordingIsInitialized() const override { |
| 831 | return _impl->RecordingIsInitialized(); |
| 832 | } |
| 833 |
| 834 | virtual int32_t StartPlayout() override { |
| 835 | return _impl->StartPlayout(); |
| 836 | } |
| 837 |
| 838 | virtual int32_t StopPlayout() override { |
| 839 | return _impl->StopPlayout(); |
| 840 | } |
| 841 |
| 842 | virtual bool Playing() const override { |
| 843 | return _impl->Playing(); |
| 844 | } |
| 845 |
| 846 | virtual int32_t StartRecording() override { |
| 847 | return _impl->StartRecording(); |
| 848 | } |
| 849 |
| 850 | virtual int32_t StopRecording() override { |
| 851 | return _impl->StopRecording(); |
| 852 | } |
| 853 |
| 854 | virtual bool Recording() const override { |
| 855 | return _impl->Recording(); |
| 856 | } |
| 857 |
| 858 | virtual int32_t InitSpeaker() override { |
| 859 | return _impl->InitSpeaker(); |
| 860 | } |
| 861 |
| 862 | virtual bool SpeakerIsInitialized() const override { |
| 863 | return _impl->SpeakerIsInitialized(); |
| 864 | } |
| 865 |
| 866 | virtual int32_t InitMicrophone() override { |
| 867 | return _impl->InitMicrophone(); |
| 868 | } |
| 869 |
| 870 | virtual bool MicrophoneIsInitialized() const override { |
| 871 | return _impl->MicrophoneIsInitialized(); |
| 872 | } |
| 873 |
| 874 | virtual int32_t SpeakerVolumeIsAvailable(bool *available) override { |
| 875 | return _impl->SpeakerVolumeIsAvailable(available); |
| 876 | } |
| 877 |
| 878 | virtual int32_t SetSpeakerVolume(uint32_t volume) override { |
| 879 | return _impl->SetSpeakerVolume(volume); |
| 880 | } |
| 881 |
| 882 | virtual int32_t SpeakerVolume(uint32_t* volume) const override { |
| 883 | return _impl->SpeakerVolume(volume); |
| 884 | } |
| 885 |
| 886 | virtual int32_t MaxSpeakerVolume(uint32_t *maxVolume) const override { |
| 887 | return _impl->MaxSpeakerVolume(maxVolume); |
| 888 | } |
| 889 |
| 890 | virtual int32_t MinSpeakerVolume(uint32_t *minVolume) const override { |
| 891 | return _impl->MinSpeakerVolume(minVolume); |
| 892 | } |
| 893 |
| 894 | virtual int32_t MicrophoneVolumeIsAvailable(bool *available) override { |
| 895 | return _impl->MicrophoneVolumeIsAvailable(available); |
| 896 | } |
| 897 |
| 898 | virtual int32_t SetMicrophoneVolume(uint32_t volume) override { |
| 899 | return _impl->SetMicrophoneVolume(volume); |
| 900 | } |
| 901 |
| 902 | virtual int32_t MicrophoneVolume(uint32_t *volume) const override { |
| 903 | return _impl->MicrophoneVolume(volume); |
| 904 | } |
| 905 |
| 906 | virtual int32_t MaxMicrophoneVolume(uint32_t *maxVolume) const override { |
| 907 | return _impl->MaxMicrophoneVolume(maxVolume); |
| 908 | } |
| 909 |
| 910 | virtual int32_t MinMicrophoneVolume(uint32_t *minVolume) const override { |
| 911 | return _impl->MinMicrophoneVolume(minVolume); |
| 912 | } |
| 913 |
| 914 | virtual int32_t SpeakerMuteIsAvailable(bool *available) override { |
| 915 | return _impl->SpeakerMuteIsAvailable(available); |
| 916 | } |
| 917 |
| 918 | virtual int32_t SetSpeakerMute(bool enable) override { |
| 919 | return _impl->SetSpeakerMute(enable); |
| 920 | } |
| 921 |
| 922 | virtual int32_t SpeakerMute(bool *enabled) const override { |
| 923 | return _impl->SpeakerMute(enabled); |
| 924 | } |
| 925 |
| 926 | virtual int32_t MicrophoneMuteIsAvailable(bool *available) override { |
| 927 | return _impl->MicrophoneMuteIsAvailable(available); |
| 928 | } |
| 929 |
| 930 | virtual int32_t SetMicrophoneMute(bool enable) override { |
| 931 | return _impl->SetMicrophoneMute(enable); |
| 932 | } |
| 933 |
| 934 | virtual int32_t MicrophoneMute(bool *enabled) const override { |
| 935 | return _impl->MicrophoneMute(enabled); |
| 936 | } |
| 937 |
| 938 | virtual int32_t StereoPlayoutIsAvailable(bool *available) const override { |
| 939 | return _impl->StereoPlayoutIsAvailable(available); |
| 940 | } |
| 941 |
| 942 | virtual int32_t SetStereoPlayout(bool enable) override { |
| 943 | return _impl->SetStereoPlayout(enable); |
| 944 | } |
| 945 |
| 946 | virtual int32_t StereoPlayout(bool *enabled) const override { |
| 947 | return _impl->StereoPlayout(enabled); |
| 948 | } |
| 949 |
| 950 | virtual int32_t StereoRecordingIsAvailable(bool *available) const override { |
| 951 | return _impl->StereoRecordingIsAvailable(available); |
| 952 | } |
| 953 |
| 954 | virtual int32_t SetStereoRecording(bool enable) override { |
| 955 | return _impl->SetStereoRecording(enable); |
| 956 | } |
| 957 |
| 958 | virtual int32_t StereoRecording(bool *enabled) const override { |
| 959 | return _impl->StereoRecording(enabled); |
| 960 | } |
| 961 |
| 962 | virtual int32_t PlayoutDelay(uint16_t* delayMS) const override { |
| 963 | return _impl->PlayoutDelay(delayMS); |
| 964 | } |
| 965 |
| 966 | virtual bool BuiltInAECIsAvailable() const override { |
| 967 | return _impl->BuiltInAECIsAvailable(); |
| 968 | } |
| 969 |
| 970 | virtual bool BuiltInAGCIsAvailable() const override { |
| 971 | return _impl->BuiltInAGCIsAvailable(); |
| 972 | } |
| 973 |
| 974 | virtual bool BuiltInNSIsAvailable() const override { |
| 975 | return _impl->BuiltInNSIsAvailable(); |
| 976 | } |
| 977 |
| 978 | virtual int32_t EnableBuiltInAEC(bool enable) override { |
| 979 | return _impl->EnableBuiltInAEC(enable); |
| 980 | } |
| 981 |
| 982 | virtual int32_t EnableBuiltInAGC(bool enable) override { |
| 983 | return _impl->EnableBuiltInAGC(enable); |
| 984 | } |
| 985 |
| 986 | virtual int32_t EnableBuiltInNS(bool enable) override { |
| 987 | return _impl->EnableBuiltInNS(enable); |
| 988 | } |
| 989 |
| 990 | virtual int32_t GetPlayoutUnderrunCount() const override { |
| 991 | return _impl->GetPlayoutUnderrunCount(); |
| 992 | } |
| 993 |
| 994 | #if defined(WEBRTC_IOS) |
| 995 | virtual int GetPlayoutAudioParameters(webrtc::AudioParameters *params) const override { |
| 996 | return _impl->GetPlayoutAudioParameters(params); |
| 997 | } |
| 998 | virtual int GetRecordAudioParameters(webrtc::AudioParameters *params) const override { |
| 999 | return _impl->GetRecordAudioParameters(params); |
| 1000 | } |
| 1001 | #endif // WEBRTC_IOS |
| 1002 | }; |
| 1003 |
| 1004 | template <typename Out> |
| 1005 | void split(const std::string &s, char delim, Out result) { |
| 1006 | std::istringstream iss(s); |
| 1007 | std::string item; |
| 1008 | while (std::getline(iss, item, delim)) { |
| 1009 | *result++ = item; |
| 1010 | } |
| 1011 | } |
| 1012 |
| 1013 | std::vector<std::string> split(const std::string &s, char delim) { |
| 1014 | std::vector<std::string> elems; |
| 1015 | split(s, delim, std::back_inserter(elems)); |
| 1016 | return elems; |
| 1017 | } |
| 1018 |
| 1019 | std::string adjustLocalDescription(const std::string &sdp) { |
| 1020 | std::vector<std::string> lines = split(sdp, '\n'); |
| 1021 |
| 1022 | std::string pattern = "c=IN "; |
| 1023 |
| 1024 | bool foundAudio = false; |
| 1025 | std::stringstream result; |
| 1026 | for (const auto &it : lines) { |
| 1027 | result << it << "\n"; |
| 1028 | if (!foundAudio && it.compare(0, pattern.size(), pattern) == 0) { |
| 1029 | foundAudio = true; |
| 1030 | result << "b=AS:" << 32 << "\n"; |
| 1031 | } |
| 1032 | } |
| 1033 |
| 1034 | return result.str(); |
| 1035 | } |
| 1036 |
| 1037 | } // namespace |
| 1038 |
| 1039 |
| 1040 |
| 1041 | class GroupInstanceManager : public std::enable_shared_from_this<GroupInstanceManager> { |
| 1042 | public: |
| 1043 | GroupInstanceManager(GroupInstanceDescriptor &&descriptor) : |
| 1044 | _networkStateUpdated(descriptor.networkStateUpdated), |
| 1045 | _audioLevelsUpdated(descriptor.audioLevelsUpdated), |
| 1046 | _initialInputDeviceId(descriptor.initialInputDeviceId), |
| 1047 | _initialOutputDeviceId(descriptor.initialOutputDeviceId), |
| 1048 | _platformContext(descriptor.platformContext) { |
| 1049 | auto generator = std::mt19937(std::random_device()()); |
| 1050 | auto distribution = std::uniform_int_distribution<uint32_t>(); |
| 1051 | do { |
| 1052 | _mainStreamAudioSsrc = distribution(generator); |
| 1053 | } while (!_mainStreamAudioSsrc); |
| 1054 | } |
| 1055 |
| 1056 | ~GroupInstanceManager() { |
| 1057 | assert(getMediaThread()->IsCurrent()); |
| 1058 |
| 1059 | destroyAudioDeviceModule(); |
| 1060 | if (_peerConnection) { |
| 1061 | _peerConnection->Close(); |
| 1062 | } |
| 1063 | } |
| 1064 |
| 1065 | void generateAndInsertFakeIncomingSsrc() { |
| 1066 | // At least on Windows recording can't be started without playout. |
| 1067 | // We keep a fake incoming stream, so that playout is always started. |
| 1068 | auto generator = std::mt19937(std::random_device()()); |
| 1069 | auto distribution = std::uniform_int_distribution<uint32_t>(); |
| 1070 | while (true) { |
| 1071 | _fakeIncomingSsrc = distribution(generator); |
| 1072 | if (_fakeIncomingSsrc != 0 |
| 1073 | && _fakeIncomingSsrc != _mainStreamAudioSsrc |
| 1074 | && std::find(_allOtherSsrcs.begin(), _allOtherSsrcs.end(), _fakeIncomingSsrc) == _allOtherSsrcs.end()) { |
| 1075 | break; |
| 1076 | } |
| 1077 | } |
| 1078 | _activeOtherSsrcs.emplace(_fakeIncomingSsrc); |
| 1079 | _allOtherSsrcs.emplace_back(_fakeIncomingSsrc); |
| 1080 | } |
| 1081 |
| 1082 | bool createAudioDeviceModule( |
| 1083 | const webrtc::PeerConnectionFactoryDependencies &dependencies) { |
| 1084 | _adm_thread = dependencies.worker_thread; |
| 1085 | if (!_adm_thread) { |
| 1086 | return false; |
| 1087 | } |
| 1088 | _adm_thread->Invoke<void>(RTC_FROM_HERE, [&] { |
| 1089 | const auto check = [&](webrtc::AudioDeviceModule::AudioLayer layer) { |
| 1090 | auto result = webrtc::AudioDeviceModule::Create( |
| 1091 | layer, |
| 1092 | dependencies.task_queue_factory.get()); |
| 1093 | return (result && (result->Init() == 0)) ? result : nullptr; |
| 1094 | }; |
| 1095 | #ifdef WEBRTC_WIN |
| 1096 | if (auto result = webrtc::CreateWindowsCoreAudioAudioDeviceModule(dependencies.task_queue_factory.get())) { |
| 1097 | if (result->Init() == 0) { |
| 1098 | _adm_use_withAudioDeviceModule = new rtc::RefCountedObject<WrappedAudioDeviceModule>(result); |
| 1099 | return; |
| 1100 | } |
| 1101 | } |
| 1102 | #endif // WEBRTC_WIN |
| 1103 | if (auto result = check(webrtc::AudioDeviceModule::kPlatformDefaultAudio)) { |
| 1104 | _adm_use_withAudioDeviceModule = new rtc::RefCountedObject<WrappedAudioDeviceModule>(result); |
| 1105 | #ifdef WEBRTC_LINUX |
| 1106 | } else if (auto result = check(webrtc::AudioDeviceModule::kLinuxAlsaAudio)) { |
| 1107 | _adm_use_withAudioDeviceModule = new rtc::RefCountedObject<WrappedAudioDeviceModule>(result); |
| 1108 | #endif // WEBRTC_LINUX |
| 1109 | } |
| 1110 | }); |
| 1111 | return (_adm_use_withAudioDeviceModule != nullptr); |
| 1112 | } |
| 1113 | void destroyAudioDeviceModule() { |
| 1114 | if (!_adm_thread) { |
| 1115 | return; |
| 1116 | } |
| 1117 | _adm_thread->Invoke<void>(RTC_FROM_HERE, [&] { |
| 1118 | _adm_use_withAudioDeviceModule = nullptr; |
| 1119 | }); |
| 1120 | } |
| 1121 |
| 1122 | void start() { |
| 1123 | const auto weak = std::weak_ptr<GroupInstanceManager>(shared_from_this()); |
| 1124 |
| 1125 | webrtc::field_trial::InitFieldTrialsFromString( |
| 1126 | //"WebRTC-Audio-SendSideBwe/Enabled/" |
| 1127 | "WebRTC-Audio-Allocation/min:6kbps,max:32kbps/" |
| 1128 | "WebRTC-Audio-OpusMinPacketLossRate/Enabled-1/" |
| 1129 | //"WebRTC-FlexFEC-03/Enabled/" |
| 1130 | //"WebRTC-FlexFEC-03-Advertised/Enabled/" |
| 1131 | "WebRTC-PcFactoryDefaultBitrates/min:6kbps,start:32kbps,max:32kbps/" |
| 1132 | ); |
| 1133 |
| 1134 | PlatformInterface::SharedInstance()->configurePlatformAudio(); |
| 1135 |
| 1136 | webrtc::PeerConnectionFactoryDependencies dependencies; |
| 1137 | dependencies.network_thread = getNetworkThread(); |
| 1138 | dependencies.worker_thread = getWorkerThread(); |
| 1139 | dependencies.signaling_thread = getSignalingThread(); |
| 1140 | dependencies.task_queue_factory = webrtc::CreateDefaultTaskQueueFactory(); |
| 1141 |
| 1142 | if (!createAudioDeviceModule(dependencies)) { |
| 1143 | return; |
| 1144 | } |
| 1145 |
| 1146 | cricket::MediaEngineDependencies mediaDeps; |
| 1147 | mediaDeps.task_queue_factory = dependencies.task_queue_factory.get(); |
| 1148 | mediaDeps.audio_encoder_factory = webrtc::CreateAudioEncoderFactory<webrtc::AudioEncoderOpus>(); |
| 1149 | mediaDeps.audio_decoder_factory = webrtc::CreateAudioDecoderFactory<webrtc::AudioDecoderOpus>(); |
| 1150 | mediaDeps.video_encoder_factory = PlatformInterface::SharedInstance()->makeVideoEncoderFactory(_platformContext); |
| 1151 | mediaDeps.video_decoder_factory = PlatformInterface::SharedInstance()->makeVideoDecoderFactory(_platformContext); |
| 1152 | mediaDeps.adm = _adm_use_withAudioDeviceModule; |
| 1153 |
| 1154 | std::shared_ptr<CombinedVad> myVad(new CombinedVad()); |
| 1155 |
| 1156 | auto analyzer = new AudioCaptureAnalyzer([&, weak, myVad](const webrtc::AudioBuffer* buffer) { |
| 1157 | if (!buffer) { |
| 1158 | return; |
| 1159 | } |
| 1160 | if (buffer->num_channels() != 1) { |
| 1161 | return; |
| 1162 | } |
| 1163 |
| 1164 | float peak = 0; |
| 1165 | int peakCount = 0; |
| 1166 | const float *samples = buffer->channels_const()[0]; |
| 1167 | for (int i = 0; i < buffer->num_frames(); i++) { |
| 1168 | float sample = samples[i]; |
| 1169 | if (sample < 0) { |
| 1170 | sample = -sample; |
| 1171 | } |
| 1172 | if (peak < sample) { |
| 1173 | peak = sample; |
| 1174 | } |
| 1175 | peakCount += 1; |
| 1176 | } |
| 1177 |
| 1178 | bool vadStatus = myVad->update((webrtc::AudioBuffer *)buffer); |
| 1179 |
| 1180 | getMediaThread()->PostTask(RTC_FROM_HERE, [weak, peak, peakCount, vadStatus](){ |
| 1181 | auto strong = weak.lock(); |
| 1182 | if (!strong) { |
| 1183 | return; |
| 1184 | } |
| 1185 |
| 1186 | strong->_myAudioLevelPeakCount += peakCount; |
| 1187 | if (strong->_myAudioLevelPeak < peak) { |
| 1188 | strong->_myAudioLevelPeak = peak; |
| 1189 | } |
| 1190 | if (strong->_myAudioLevelPeakCount >= 1200) { |
| 1191 | float level = strong->_myAudioLevelPeak / 4000.0f; |
| 1192 | if (strong->_isMuted) { |
| 1193 | level = 0.0f; |
| 1194 | } |
| 1195 | strong->_myAudioLevelPeak = 0; |
| 1196 | strong->_myAudioLevelPeakCount = 0; |
| 1197 | strong->_myAudioLevel = GroupLevelValue{ |
| 1198 | level, |
| 1199 | vadStatus, |
| 1200 | }; |
| 1201 | } |
| 1202 | }); |
| 1203 | }); |
| 1204 |
| 1205 | webrtc::AudioProcessingBuilder builder; |
| 1206 | builder.SetCaptureAnalyzer(std::unique_ptr<AudioCaptureAnalyzer>(analyzer)); |
| 1207 | webrtc::AudioProcessing *apm = builder.Create(); |
| 1208 |
| 1209 | webrtc::AudioProcessing::Config audioConfig; |
| 1210 | webrtc::AudioProcessing::Config::NoiseSuppression noiseSuppression; |
| 1211 | noiseSuppression.enabled = true; |
| 1212 | noiseSuppression.level = webrtc::AudioProcessing::Config::NoiseSuppression::kHigh; |
| 1213 | audioConfig.noise_suppression = noiseSuppression; |
| 1214 |
| 1215 | audioConfig.high_pass_filter.enabled = true; |
| 1216 |
| 1217 | audioConfig.voice_detection.enabled = true; |
| 1218 |
| 1219 | apm->ApplyConfig(audioConfig); |
| 1220 |
| 1221 | mediaDeps.audio_processing = apm; |
| 1222 |
| 1223 | mediaDeps.onUnknownAudioSsrc = [weak](uint32_t ssrc) { |
| 1224 | getMediaThread()->PostTask(RTC_FROM_HERE, [weak, ssrc](){ |
| 1225 | auto strong = weak.lock(); |
| 1226 | if (!strong) { |
| 1227 | return; |
| 1228 | } |
| 1229 | strong->onMissingSsrc(ssrc); |
| 1230 | }); |
| 1231 | }; |
| 1232 |
| 1233 | dependencies.media_engine = cricket::CreateMediaEngine(std::move(mediaDeps)); |
| 1234 | dependencies.call_factory = webrtc::CreateCallFactory(); |
| 1235 | dependencies.event_log_factory = |
| 1236 | std::make_unique<webrtc::RtcEventLogFactory>(dependencies.task_queue_factory.get()); |
| 1237 | dependencies.network_controller_factory = nullptr; |
| 1238 |
| 1239 | _nativeFactory = webrtc::CreateModularPeerConnectionFactory(std::move(dependencies)); |
| 1240 |
| 1241 | webrtc::PeerConnectionInterface::RTCConfiguration config; |
| 1242 | config.sdp_semantics = webrtc::SdpSemantics::kUnifiedPlan; |
| 1243 | //config.continual_gathering_policy = webrtc::PeerConnectionInterface::ContinualGatheringPolicy::GATHER_CONTINUALLY; |
| 1244 | config.audio_jitter_buffer_fast_accelerate = true; |
| 1245 | config.prioritize_most_likely_ice_candidate_pairs = true; |
| 1246 | config.presume_writable_when_fully_relayed = true; |
| 1247 | //config.audio_jitter_buffer_enable_rtx_handling = true; |
| 1248 |
| 1249 | /*webrtc::CryptoOptions cryptoOptions; |
| 1250 | webrtc::CryptoOptions::SFrame sframe; |
| 1251 | sframe.require_frame_encryption = true; |
| 1252 | cryptoOptions.sframe = sframe; |
| 1253 | config.crypto_options = cryptoOptions;*/ |
| 1254 |
| 1255 | _observer.reset(new PeerConnectionObserverImpl( |
| 1256 | [weak](std::string sdp, int mid, std::string sdpMid) { |
| 1257 | /*getMediaThread()->PostTask(RTC_FROM_HERE, [weak, sdp, mid, sdpMid](){ |
| 1258 | auto strong = weak.lock(); |
| 1259 | if (strong) { |
| 1260 | //strong->emitIceCandidate(sdp, mid, sdpMid); |
| 1261 | } |
| 1262 | });*/ |
| 1263 | }, |
| 1264 | [weak](bool isConnected) { |
| 1265 | getMediaThread()->PostTask(RTC_FROM_HERE, [weak, isConnected](){ |
| 1266 | auto strong = weak.lock(); |
| 1267 | if (strong) { |
| 1268 | strong->updateIsConnected(isConnected); |
| 1269 | } |
| 1270 | }); |
| 1271 | }, |
| 1272 | [weak](rtc::scoped_refptr<webrtc::RtpTransceiverInterface> transceiver) { |
| 1273 | getMediaThread()->PostTask(RTC_FROM_HERE, [weak, transceiver](){ |
| 1274 | auto strong = weak.lock(); |
| 1275 | if (!strong) { |
| 1276 | return; |
| 1277 | } |
| 1278 | strong->onTrackAdded(transceiver); |
| 1279 | }); |
| 1280 | }, |
| 1281 | [weak](rtc::scoped_refptr<webrtc::RtpReceiverInterface> receiver) { |
| 1282 | getMediaThread()->PostTask(RTC_FROM_HERE, [weak, receiver](){ |
| 1283 | auto strong = weak.lock(); |
| 1284 | if (!strong) { |
| 1285 | return; |
| 1286 | } |
| 1287 | strong->onTrackRemoved(receiver); |
| 1288 | }); |
| 1289 | }, |
| 1290 | [weak](uint32_t ssrc) { |
| 1291 | getMediaThread()->PostTask(RTC_FROM_HERE, [weak, ssrc](){ |
| 1292 | auto strong = weak.lock(); |
| 1293 | if (!strong) { |
| 1294 | return; |
| 1295 | } |
| 1296 | strong->onMissingSsrc(ssrc); |
| 1297 | }); |
| 1298 | } |
| 1299 | )); |
| 1300 | _peerConnection = _nativeFactory->CreatePeerConnection(config, nullptr, nullptr, _observer.get()); |
| 1301 | assert(_peerConnection != nullptr); |
| 1302 |
| 1303 | cricket::AudioOptions options; |
| 1304 | rtc::scoped_refptr<webrtc::AudioSourceInterface> audioSource = _nativeFactory->CreateAudioSource(options); |
| 1305 | std::stringstream name; |
| 1306 | name << "audio"; |
| 1307 | name << 0; |
| 1308 | std::vector<std::string> streamIds; |
| 1309 | streamIds.push_back(name.str()); |
| 1310 | _localAudioTrack = _nativeFactory->CreateAudioTrack(name.str(), audioSource); |
| 1311 | _localAudioTrack->set_enabled(false); |
| 1312 | auto addedTrack = _peerConnection->AddTrack(_localAudioTrack, streamIds); |
| 1313 |
| 1314 | if (addedTrack.ok()) { |
| 1315 | _localAudioTrackSender = addedTrack.value(); |
| 1316 | for (auto &it : _peerConnection->GetTransceivers()) { |
| 1317 | if (it->media_type() == cricket::MediaType::MEDIA_TYPE_AUDIO) { |
| 1318 | if (_localAudioTrackSender.get() == it->sender().get()) { |
| 1319 | it->SetDirection(webrtc::RtpTransceiverDirection::kRecvOnly); |
| 1320 | } |
| 1321 |
| 1322 | break; |
| 1323 | } |
| 1324 | } |
| 1325 | } |
| 1326 |
| 1327 | setAudioInputDevice(_initialInputDeviceId); |
| 1328 | setAudioOutputDevice(_initialOutputDeviceId); |
| 1329 |
| 1330 | // At least on Windows recording doesn't work without started playout. |
| 1331 | withAudioDeviceModule([weak](webrtc::AudioDeviceModule *adm) { |
| 1332 | #ifdef WEBRTC_WIN |
| 1333 | // At least on Windows starting/stopping playout while recording |
| 1334 | // is active leads to errors in recording and assertion violation. |
| 1335 | adm->EnableBuiltInAEC(false); |
| 1336 | #endif // WEBRTC_WIN |
| 1337 |
| 1338 | if (adm->InitPlayout() == 0) { |
| 1339 | adm->StartPlayout(); |
| 1340 | } else { |
| 1341 | getMediaThread()->PostDelayedTask(RTC_FROM_HERE, [weak](){ |
| 1342 | auto strong = weak.lock(); |
| 1343 | if (!strong) { |
| 1344 | return; |
| 1345 | } |
| 1346 | strong->withAudioDeviceModule([](webrtc::AudioDeviceModule *adm) { |
| 1347 | if (adm->InitPlayout() == 0) { |
| 1348 | adm->StartPlayout(); |
| 1349 | } |
| 1350 | }); |
| 1351 | }, 2000); |
| 1352 | } |
| 1353 | }); |
| 1354 |
| 1355 | //beginStatsTimer(100); |
| 1356 | beginLevelsTimer(50); |
| 1357 | } |
| 1358 |
| 1359 |
| 1360 | void setAudioInputDevice(std::string id) { |
| 1361 | #if !defined(WEBRTC_IOS) && !defined(WEBRTC_ANDROID) |
| 1362 | withAudioDeviceModule([&](webrtc::AudioDeviceModule *adm) { |
| 1363 | const auto recording = adm->Recording(); |
| 1364 | if (recording) { |
| 1365 | adm->StopRecording(); |
| 1366 | } |
| 1367 | const auto finish = [&] { |
| 1368 | if (recording) { |
| 1369 | adm->InitRecording(); |
| 1370 | adm->StartRecording(); |
| 1371 | } |
| 1372 | }; |
| 1373 | if (id == "default" || id.empty()) { |
| 1374 | if (const auto result = adm->SetRecordingDevice(webrtc::AudioDeviceModule::kDefaultCommunicationDevice)) { |
| 1375 | RTC_LOG(LS_ERROR) << "setAudioInputDevice(" << id << "): SetRecordingDevice(kDefaultCommunicationDevice) failed: " << result << "."; |
| 1376 | } else { |
| 1377 | RTC_LOG(LS_INFO) << "setAudioInputDevice(" << id << "): SetRecordingDevice(kDefaultCommunicationDevice) success."; |
| 1378 | } |
| 1379 | return finish(); |
| 1380 | } |
| 1381 | const auto count = adm |
| 1382 | ? adm->RecordingDevices() |
| 1383 | : int16_t(-666); |
| 1384 | if (count <= 0) { |
| 1385 | RTC_LOG(LS_ERROR) << "setAudioInputDevice(" << id << "): Could not get recording devices count: " << count << "."; |
| 1386 | return finish(); |
| 1387 | } |
| 1388 | for (auto i = 0; i != count; ++i) { |
| 1389 | char name[webrtc::kAdmMaxDeviceNameSize + 1] = { 0 }; |
| 1390 | char guid[webrtc::kAdmMaxGuidSize + 1] = { 0 }; |
| 1391 | adm->RecordingDeviceName(i, name, guid); |
| 1392 | if (id == guid) { |
| 1393 | const auto result = adm->SetRecordingDevice(i); |
| 1394 | if (result != 0) { |
| 1395 | RTC_LOG(LS_ERROR) << "setAudioInputDevice(" << id << ") name '" << std::string(name) << "' failed: " << result << "."; |
| 1396 | } else { |
| 1397 | RTC_LOG(LS_INFO) << "setAudioInputDevice(" << id << ") name '" << std::string(name) << "' success."; |
| 1398 | } |
| 1399 | return finish(); |
| 1400 | } |
| 1401 | } |
| 1402 | RTC_LOG(LS_ERROR) << "setAudioInputDevice(" << id << "): Could not find recording device."; |
| 1403 | return finish(); |
| 1404 | }); |
| 1405 | #endif |
| 1406 | } |
| 1407 |
| 1408 | void setAudioOutputDevice(std::string id) { |
| 1409 | #if !defined(WEBRTC_IOS) && !defined(WEBRTC_ANDROID) |
| 1410 | withAudioDeviceModule([&](webrtc::AudioDeviceModule *adm) { |
| 1411 | const auto playing = adm->Playing(); |
| 1412 | if (playing) { |
| 1413 | adm->StopPlayout(); |
| 1414 | } |
| 1415 | const auto finish = [&] { |
| 1416 | if (playing) { |
| 1417 | adm->InitPlayout(); |
| 1418 | adm->StartPlayout(); |
| 1419 | } |
| 1420 | }; |
| 1421 | if (id == "default" || id.empty()) { |
| 1422 | if (const auto result = adm->SetPlayoutDevice(webrtc::AudioDeviceModule::kDefaultCommunicationDevice)) { |
| 1423 | RTC_LOG(LS_ERROR) << "setAudioOutputDevice(" << id << "): SetPlayoutDevice(kDefaultCommunicationDevice) failed: " << result << "."; |
| 1424 | } else { |
| 1425 | RTC_LOG(LS_INFO) << "setAudioOutputDevice(" << id << "): SetPlayoutDevice(kDefaultCommunicationDevice) success."; |
| 1426 | } |
| 1427 | return finish(); |
| 1428 | } |
| 1429 | const auto count = adm |
| 1430 | ? adm->PlayoutDevices() |
| 1431 | : int16_t(-666); |
| 1432 | if (count <= 0) { |
| 1433 | RTC_LOG(LS_ERROR) << "setAudioOutputDevice(" << id << "): Could not get playout devices count: " << count << "."; |
| 1434 | return finish(); |
| 1435 | } |
| 1436 | for (auto i = 0; i != count; ++i) { |
| 1437 | char name[webrtc::kAdmMaxDeviceNameSize + 1] = { 0 }; |
| 1438 | char guid[webrtc::kAdmMaxGuidSize + 1] = { 0 }; |
| 1439 | adm->PlayoutDeviceName(i, name, guid); |
| 1440 | if (id == guid) { |
| 1441 | const auto result = adm->SetPlayoutDevice(i); |
| 1442 | if (result != 0) { |
| 1443 | RTC_LOG(LS_ERROR) << "setAudioOutputDevice(" << id << ") name '" << std::string(name) << "' failed: " << result << "."; |
| 1444 | } else { |
| 1445 | RTC_LOG(LS_INFO) << "setAudioOutputDevice(" << id << ") name '" << std::string(name) << "' success."; |
| 1446 | } |
| 1447 | return finish(); |
| 1448 | } |
| 1449 | } |
| 1450 | RTC_LOG(LS_ERROR) << "setAudioOutputDevice(" << id << "): Could not find playout device."; |
| 1451 | return finish(); |
| 1452 | }); |
| 1453 | #endif |
| 1454 | } |
| 1455 |
| 1456 | void setVolume(uint32_t ssrc, double volume) { |
| 1457 | auto current = _audioTrackVolumes.find(ssrc); |
| 1458 | bool updated = false; |
| 1459 | if (current != _audioTrackVolumes.end()) { |
| 1460 | if (abs(current->second - volume) > 0.001) { |
| 1461 | updated = true; |
| 1462 | } |
| 1463 | } else { |
| 1464 | if (volume < 1.0 - 0.001) { |
| 1465 | updated = true; |
| 1466 | } |
| 1467 | } |
| 1468 | if (updated) { |
| 1469 | _audioTrackVolumes[ssrc] = volume; |
| 1470 | auto track = _audioTracks.find(ssrc); |
| 1471 | if (track != _audioTracks.end()) { |
| 1472 | track->second->GetSource()->SetVolume(volume); |
| 1473 | } |
| 1474 | } |
| 1475 | } |
| 1476 |
| 1477 | void updateIsConnected(bool isConnected) { |
| 1478 | _isConnected = isConnected; |
| 1479 |
| 1480 | auto timestamp = rtc::TimeMillis(); |
| 1481 |
| 1482 | _isConnectedUpdateValidTaskId++; |
| 1483 |
| 1484 | if (!isConnected && _appliedOfferTimestamp > timestamp - 1000) { |
| 1485 | auto taskId = _isConnectedUpdateValidTaskId; |
| 1486 | const auto weak = std::weak_ptr<GroupInstanceManager>(shared_from_this()); |
| 1487 | getMediaThread()->PostDelayedTask(RTC_FROM_HERE, [weak, taskId]() { |
| 1488 | auto strong = weak.lock(); |
| 1489 | if (!strong) { |
| 1490 | return; |
| 1491 | } |
| 1492 | if (strong->_isConnectedUpdateValidTaskId == taskId) { |
| 1493 | strong->_networkStateUpdated(strong->_isConnected); |
| 1494 | } |
| 1495 | }, 1000); |
| 1496 | } else { |
| 1497 | _networkStateUpdated(_isConnected); |
| 1498 | } |
| 1499 | } |
| 1500 |
| 1501 | void stop() { |
| 1502 | _peerConnection->Close(); |
| 1503 | } |
| 1504 |
| 1505 | void emitJoinPayload(std::function<void(GroupJoinPayload)> completion) { |
| 1506 | const auto weak = std::weak_ptr<GroupInstanceManager>(shared_from_this()); |
| 1507 | webrtc::PeerConnectionInterface::RTCOfferAnswerOptions options; |
| 1508 | rtc::scoped_refptr<CreateSessionDescriptionObserverImpl> observer(new rtc::RefCountedObject<CreateSessionDescriptionObserverImpl>([weak, completion](std::string sdp, std::string type) { |
| 1509 | getMediaThread()->PostTask(RTC_FROM_HERE, [weak, sdp, type, completion](){ |
| 1510 | auto strong = weak.lock(); |
| 1511 | if (!strong) { |
| 1512 | return; |
| 1513 | } |
| 1514 |
| 1515 | auto lines = splitSdpLines(sdp); |
| 1516 | std::vector<std::string> resultSdp; |
| 1517 |
| 1518 | std::ostringstream generatedSsrcStringStream; |
| 1519 | generatedSsrcStringStream << strong->_mainStreamAudioSsrc; |
| 1520 | auto generatedSsrcString = generatedSsrcStringStream.str(); |
| 1521 |
| 1522 | for (auto &line : lines) { |
| 1523 | auto adjustedLine = line; |
| 1524 | if (adjustedLine.find("a=ssrc:") == 0) { |
| 1525 | int startIndex = 7; |
| 1526 | int i = startIndex; |
| 1527 | while (i < adjustedLine.size()) { |
| 1528 | if (!isdigit(adjustedLine[i])) { |
| 1529 | break; |
| 1530 | } |
| 1531 | i++; |
| 1532 | } |
| 1533 | if (i >= startIndex) { |
| 1534 | adjustedLine.replace(startIndex, i - startIndex, generatedSsrcString); |
| 1535 | } |
| 1536 | } |
| 1537 | appendSdp(resultSdp, adjustedLine); |
| 1538 | } |
| 1539 |
| 1540 | std::ostringstream result; |
| 1541 | for (auto &line : resultSdp) { |
| 1542 | result << line << "\n"; |
| 1543 | } |
| 1544 |
| 1545 | auto adjustedSdp = result.str(); |
| 1546 |
| 1547 | RTC_LOG(LoggingSeverity::WARNING) << "----- setLocalDescription join -----"; |
| 1548 | RTC_LOG(LoggingSeverity::WARNING) << adjustedSdp; |
| 1549 | RTC_LOG(LoggingSeverity::WARNING) << "-----"; |
| 1550 |
| 1551 | webrtc::SdpParseError error; |
| 1552 | webrtc::SessionDescriptionInterface *sessionDescription = webrtc::CreateSessionDescription(type, adjustLocalDescription(adjustedSdp), &error); |
| 1553 | if (sessionDescription != nullptr) { |
| 1554 | rtc::scoped_refptr<SetSessionDescriptionObserverImpl> observer(new rtc::RefCountedObject<SetSessionDescriptionObserverImpl>([weak, adjustedSdp, completion]() { |
| 1555 | auto strong = weak.lock(); |
| 1556 | if (!strong) { |
| 1557 | return; |
| 1558 | } |
| 1559 | auto payload = parseSdpIntoJoinPayload(adjustedSdp); |
| 1560 | if (payload) { |
| 1561 | payload->ssrc = strong->_mainStreamAudioSsrc; |
| 1562 | completion(payload.value()); |
| 1563 | } |
| 1564 | }, [](webrtc::RTCError error) { |
| 1565 | })); |
| 1566 | strong->_peerConnection->SetLocalDescription(observer, sessionDescription); |
| 1567 | } else { |
| 1568 | return; |
| 1569 | } |
| 1570 | }); |
| 1571 | })); |
| 1572 | _peerConnection->CreateOffer(observer, options); |
| 1573 | } |
| 1574 |
| 1575 | void setJoinResponsePayload(GroupJoinResponsePayload payload) { |
| 1576 | _joinPayload = payload; |
| 1577 | auto sdp = parseJoinResponseIntoSdp(_sessionId, _mainStreamAudioSsrc, payload, true, _allOtherSsrcs, _activeOtherSsrcs); |
| 1578 | setOfferSdp(sdp, true, true, false); |
| 1579 | } |
| 1580 |
| 1581 | void removeSsrcs(std::vector<uint32_t> ssrcs) { |
| 1582 | if (!_joinPayload) { |
| 1583 | return; |
| 1584 | } |
| 1585 |
| 1586 | bool updated = false; |
| 1587 | for (auto ssrc : ssrcs) { |
| 1588 | if (std::find(_allOtherSsrcs.begin(), _allOtherSsrcs.end(), ssrc) != _allOtherSsrcs.end() && std::find(_activeOtherSsrcs.begin(), _activeOtherSsrcs.end(), ssrc) != _activeOtherSsrcs.end()) { |
| 1589 | if (!_fakeIncomingSsrc || ssrc == _fakeIncomingSsrc) { |
| 1590 | generateAndInsertFakeIncomingSsrc(); |
| 1591 | } |
| 1592 | _activeOtherSsrcs.erase(ssrc); |
| 1593 | updated = true; |
| 1594 | } |
| 1595 | } |
| 1596 |
| 1597 | if (updated) { |
| 1598 | auto sdp = parseJoinResponseIntoSdp(_sessionId, _mainStreamAudioSsrc, _joinPayload.value(), false, _allOtherSsrcs, _activeOtherSsrcs); |
| 1599 | setOfferSdp(sdp, false, false, false); |
| 1600 | } |
| 1601 | } |
| 1602 |
| 1603 | void addSsrcsInternal(std::vector<uint32_t> const &ssrcs, bool completeMissingSsrcSetup) { |
| 1604 | if (!_joinPayload) { |
| 1605 | if (completeMissingSsrcSetup) { |
| 1606 | completeProcessingMissingSsrcs(); |
| 1607 | } |
| 1608 | return; |
| 1609 | } |
| 1610 |
| 1611 | for (auto ssrc : ssrcs) { |
| 1612 | if (std::find(_allOtherSsrcs.begin(), _allOtherSsrcs.end(), ssrc) == _allOtherSsrcs.end()) { |
| 1613 | _allOtherSsrcs.push_back(ssrc); |
| 1614 | _activeOtherSsrcs.insert(ssrc); |
| 1615 | } |
| 1616 | } |
| 1617 |
| 1618 | auto sdp = parseJoinResponseIntoSdp(_sessionId, _mainStreamAudioSsrc, _joinPayload.value(), false, _allOtherSsrcs, _activeOtherSsrcs); |
| 1619 | setOfferSdp(sdp, false, false, completeMissingSsrcSetup); |
| 1620 | } |
| 1621 |
| 1622 | void applyLocalSdp() { |
| 1623 | const auto weak = std::weak_ptr<GroupInstanceManager>(shared_from_this()); |
| 1624 | webrtc::PeerConnectionInterface::RTCOfferAnswerOptions options; |
| 1625 | rtc::scoped_refptr<CreateSessionDescriptionObserverImpl> observer(new rtc::RefCountedObject<CreateSessionDescriptionObserverImpl>([weak](std::string sdp, std::string type) { |
| 1626 | getMediaThread()->PostTask(RTC_FROM_HERE, [weak, sdp, type](){ |
| 1627 | auto strong = weak.lock(); |
| 1628 | if (!strong) { |
| 1629 | return; |
| 1630 | } |
| 1631 |
| 1632 | auto lines = splitSdpLines(sdp); |
| 1633 | std::vector<std::string> resultSdp; |
| 1634 |
| 1635 | std::ostringstream generatedSsrcStringStream; |
| 1636 | generatedSsrcStringStream << strong->_mainStreamAudioSsrc; |
| 1637 | auto generatedSsrcString = generatedSsrcStringStream.str(); |
| 1638 |
| 1639 | for (auto &line : lines) { |
| 1640 | auto adjustedLine = line; |
| 1641 | if (adjustedLine.find("a=ssrc:") == 0) { |
| 1642 | int startIndex = 7; |
| 1643 | int i = startIndex; |
| 1644 | while (i < adjustedLine.size()) { |
| 1645 | if (!isdigit(adjustedLine[i])) { |
| 1646 | break; |
| 1647 | } |
| 1648 | i++; |
| 1649 | } |
| 1650 | if (i >= startIndex) { |
| 1651 | adjustedLine.replace(startIndex, i - startIndex, generatedSsrcString); |
| 1652 | } |
| 1653 | } |
| 1654 | appendSdp(resultSdp, adjustedLine); |
| 1655 | } |
| 1656 |
| 1657 | std::ostringstream result; |
| 1658 | for (auto &line : resultSdp) { |
| 1659 | result << line << "\n"; |
| 1660 | } |
| 1661 |
| 1662 | auto adjustedSdp = result.str(); |
| 1663 |
| 1664 | RTC_LOG(LoggingSeverity::WARNING) << "----- setLocalDescription applyLocalSdp -----"; |
| 1665 | RTC_LOG(LoggingSeverity::WARNING) << adjustedSdp; |
| 1666 | RTC_LOG(LoggingSeverity::WARNING) << "-----"; |
| 1667 |
| 1668 | webrtc::SdpParseError error; |
| 1669 | webrtc::SessionDescriptionInterface *sessionDescription = webrtc::CreateSessionDescription(type, adjustLocalDescription(adjustedSdp), &error); |
| 1670 | if (sessionDescription != nullptr) { |
| 1671 | rtc::scoped_refptr<SetSessionDescriptionObserverImpl> observer(new rtc::RefCountedObject<SetSessionDescriptionObserverImpl>([weak, adjustedSdp]() { |
| 1672 | auto strong = weak.lock(); |
| 1673 | if (!strong) { |
| 1674 | return; |
| 1675 | } |
| 1676 |
| 1677 | if (!strong->_joinPayload) { |
| 1678 | return; |
| 1679 | } |
| 1680 |
| 1681 | auto sdp = parseJoinResponseIntoSdp(strong->_sessionId, strong->_mainStreamAudioSsrc, strong->_joinPayload.value(), true, strong->_allOtherSsrcs, strong->_activeOtherSsrcs); |
| 1682 | strong->setOfferSdp(sdp, false, true, false); |
| 1683 | }, [](webrtc::RTCError error) { |
| 1684 | })); |
| 1685 | strong->_peerConnection->SetLocalDescription(observer, sessionDescription); |
| 1686 | } else { |
| 1687 | return; |
| 1688 | } |
| 1689 | }); |
| 1690 | })); |
| 1691 | _peerConnection->CreateOffer(observer, options); |
| 1692 | } |
| 1693 |
| 1694 | void setOfferSdp(std::string const &offerSdp, bool isInitialJoinAnswer, bool isAnswer, bool completeMissingSsrcSetup) { |
| 1695 | if (!isAnswer && _appliedRemoteRescription == offerSdp) { |
| 1696 | if (completeMissingSsrcSetup) { |
| 1697 | completeProcessingMissingSsrcs(); |
| 1698 | } |
| 1699 | return; |
| 1700 | } |
| 1701 | _appliedRemoteRescription = offerSdp; |
| 1702 |
| 1703 | RTC_LOG(LoggingSeverity::WARNING) << "----- setOfferSdp " << (isAnswer ? "answer" : "offer") << " -----"; |
| 1704 | RTC_LOG(LoggingSeverity::WARNING) << offerSdp; |
| 1705 | RTC_LOG(LoggingSeverity::WARNING) << "-----"; |
| 1706 |
| 1707 | webrtc::SdpParseError error; |
| 1708 | webrtc::SessionDescriptionInterface *sessionDescription = webrtc::CreateSessionDescription(isAnswer ? "answer" : "offer", adjustLocalDescription(offerSdp), &error); |
| 1709 | if (!sessionDescription) { |
| 1710 | if (completeMissingSsrcSetup) { |
| 1711 | completeProcessingMissingSsrcs(); |
| 1712 | } |
| 1713 | return; |
| 1714 | } |
| 1715 |
| 1716 | if (!isAnswer) { |
| 1717 | _appliedOfferTimestamp = rtc::TimeMillis(); |
| 1718 | } |
| 1719 |
| 1720 | const auto weak = std::weak_ptr<GroupInstanceManager>(shared_from_this()); |
| 1721 | rtc::scoped_refptr<SetSessionDescriptionObserverImpl> observer(new rtc::RefCountedObject<SetSessionDescriptionObserverImpl>([weak, isInitialJoinAnswer, isAnswer, completeMissingSsrcSetup]() { |
| 1722 | getMediaThread()->PostTask(RTC_FROM_HERE, [weak, isInitialJoinAnswer, isAnswer, completeMissingSsrcSetup](){ |
| 1723 | auto strong = weak.lock(); |
| 1724 | if (!strong) { |
| 1725 | return; |
| 1726 | } |
| 1727 | if (!isAnswer) { |
| 1728 | strong->emitAnswer(completeMissingSsrcSetup); |
| 1729 | } else { |
| 1730 | if (isInitialJoinAnswer) { |
| 1731 | strong->completedInitialSetup(); |
| 1732 | } |
| 1733 |
| 1734 | if (completeMissingSsrcSetup) { |
| 1735 | strong->completeProcessingMissingSsrcs(); |
| 1736 | } |
| 1737 | } |
| 1738 | }); |
| 1739 | }, [weak, completeMissingSsrcSetup](webrtc::RTCError error) { |
| 1740 | getMediaThread()->PostTask(RTC_FROM_HERE, [weak, completeMissingSsrcSetup](){ |
| 1741 | auto strong = weak.lock(); |
| 1742 | if (!strong) { |
| 1743 | return; |
| 1744 | } |
| 1745 | if (completeMissingSsrcSetup) { |
| 1746 | strong->completeProcessingMissingSsrcs(); |
| 1747 | } |
| 1748 | }); |
| 1749 | })); |
| 1750 |
| 1751 | _peerConnection->SetRemoteDescription(observer, sessionDescription); |
| 1752 | } |
| 1753 |
| 1754 | void beginStatsTimer(int timeoutMs) { |
| 1755 | const auto weak = std::weak_ptr<GroupInstanceManager>(shared_from_this()); |
| 1756 | getMediaThread()->PostDelayedTask(RTC_FROM_HERE, [weak]() { |
| 1757 | getMediaThread()->PostTask(RTC_FROM_HERE, [weak](){ |
| 1758 | auto strong = weak.lock(); |
| 1759 | if (!strong) { |
| 1760 | return; |
| 1761 | } |
| 1762 | strong->collectStats(); |
| 1763 | }); |
| 1764 | }, timeoutMs); |
| 1765 | } |
| 1766 |
| 1767 | void beginLevelsTimer(int timeoutMs) { |
| 1768 | const auto weak = std::weak_ptr<GroupInstanceManager>(shared_from_this()); |
| 1769 | getMediaThread()->PostDelayedTask(RTC_FROM_HERE, [weak]() { |
| 1770 | auto strong = weak.lock(); |
| 1771 | if (!strong) { |
| 1772 | return; |
| 1773 | } |
| 1774 |
| 1775 | GroupLevelsUpdate levelsUpdate; |
| 1776 | levelsUpdate.updates.reserve(strong->_audioLevels.size() + 1); |
| 1777 | for (auto &it : strong->_audioLevels) { |
| 1778 | if (it.second.level > 0.001f) { |
| 1779 | levelsUpdate.updates.push_back(GroupLevelUpdate{ |
| 1780 | it.first, |
| 1781 | it.second, |
| 1782 | }); |
| 1783 | } |
| 1784 | } |
| 1785 | levelsUpdate.updates.push_back(GroupLevelUpdate{ 0, strong->_myAudioLevel }); |
| 1786 |
| 1787 | strong->_audioLevels.clear(); |
| 1788 | strong->_audioLevelsUpdated(levelsUpdate); |
| 1789 |
| 1790 | strong->beginLevelsTimer(50); |
| 1791 | }, timeoutMs); |
| 1792 | } |
| 1793 |
| 1794 | void collectStats() { |
| 1795 | const auto weak = std::weak_ptr<GroupInstanceManager>(shared_from_this()); |
| 1796 |
| 1797 | rtc::scoped_refptr<RTCStatsCollectorCallbackImpl> observer(new rtc::RefCountedObject<RTCStatsCollectorCallbackImpl>([weak](const rtc::scoped_refptr<const webrtc::RTCStatsReport> &stats) { |
| 1798 | getMediaThread()->PostTask(RTC_FROM_HERE, [weak, stats](){ |
| 1799 | auto strong = weak.lock(); |
| 1800 | if (!strong) { |
| 1801 | return; |
| 1802 | } |
| 1803 | strong->reportStats(stats); |
| 1804 | strong->beginStatsTimer(100); |
| 1805 | }); |
| 1806 | })); |
| 1807 | _peerConnection->GetStats(observer); |
| 1808 | } |
| 1809 |
| 1810 | void reportStats(const rtc::scoped_refptr<const webrtc::RTCStatsReport> &stats) { |
| 1811 | } |
| 1812 |
| 1813 | void onTrackAdded(rtc::scoped_refptr<webrtc::RtpTransceiverInterface> transceiver) { |
| 1814 | if (transceiver->direction() == webrtc::RtpTransceiverDirection::kRecvOnly && transceiver->media_type() == cricket::MediaType::MEDIA_TYPE_AUDIO) { |
| 1815 | if (transceiver->mid()) { |
| 1816 | auto streamId = transceiver->mid().value(); |
| 1817 | if (streamId.find("audio") != 0) { |
| 1818 | return; |
| 1819 | } |
| 1820 | streamId.replace(0, 5, ""); |
| 1821 | std::istringstream iss(streamId); |
| 1822 | uint32_t ssrc = 0; |
| 1823 | iss >> ssrc; |
| 1824 |
| 1825 | rtc::scoped_refptr<webrtc::AudioTrackInterface> remoteAudioTrack(static_cast<webrtc::AudioTrackInterface *>(transceiver->receiver()->track().get())); |
| 1826 | if (_audioTracks.find(ssrc) == _audioTracks.end()) { |
| 1827 | _audioTracks.insert(std::make_pair(ssrc, remoteAudioTrack)); |
| 1828 | } |
| 1829 | auto currentVolume = _audioTrackVolumes.find(ssrc); |
| 1830 | if (currentVolume != _audioTrackVolumes.end()) { |
| 1831 | remoteAudioTrack->GetSource()->SetVolume(currentVolume->second); |
| 1832 | } |
| 1833 | if (_audioTrackSinks.find(ssrc) == _audioTrackSinks.end()) { |
| 1834 | const auto weak = std::weak_ptr<GroupInstanceManager>(shared_from_this()); |
| 1835 | std::shared_ptr<AudioTrackSinkInterfaceImpl> sink(new AudioTrackSinkInterfaceImpl([weak, ssrc](float level, bool hasSpeech) { |
| 1836 | getMediaThread()->PostTask(RTC_FROM_HERE, [weak, ssrc, level, hasSpeech]() { |
| 1837 | auto strong = weak.lock(); |
| 1838 | if (!strong) { |
| 1839 | return; |
| 1840 | } |
| 1841 | auto current = strong->_audioLevels.find(ssrc); |
| 1842 | if (current != strong->_audioLevels.end()) { |
| 1843 | if (current->second.level < level) { |
| 1844 | strong->_audioLevels[ssrc] = GroupLevelValue{ |
| 1845 | level, |
| 1846 | hasSpeech, |
| 1847 | }; |
| 1848 | } |
| 1849 | } else { |
| 1850 | strong->_audioLevels.emplace( |
| 1851 | ssrc, |
| 1852 | GroupLevelValue{ |
| 1853 | level, |
| 1854 | hasSpeech, |
| 1855 | }); |
| 1856 | } |
| 1857 | }); |
| 1858 | })); |
| 1859 | _audioTrackSinks[ssrc] = sink; |
| 1860 | remoteAudioTrack->AddSink(sink.get()); |
| 1861 | //remoteAudioTrack->GetSource()->SetVolume(0.01); |
| 1862 | } |
| 1863 | } |
| 1864 | } |
| 1865 | } |
| 1866 |
| 1867 | void onTrackRemoved(rtc::scoped_refptr<webrtc::RtpReceiverInterface> receiver) { |
| 1868 | } |
| 1869 |
| 1870 | void onMissingSsrc(uint32_t ssrc) { |
| 1871 | if (_processedMissingSsrcs.find(ssrc) == _processedMissingSsrcs.end()) { |
| 1872 | _processedMissingSsrcs.insert(ssrc); |
| 1873 |
| 1874 | _missingSsrcQueue.insert(ssrc); |
| 1875 | if (!_isProcessingMissingSsrcs) { |
| 1876 | beginProcessingMissingSsrcs(); |
| 1877 | } |
| 1878 | } |
| 1879 | } |
| 1880 |
| 1881 | void beginProcessingMissingSsrcs() { |
| 1882 | if (_isProcessingMissingSsrcs) { |
| 1883 | return; |
| 1884 | } |
| 1885 | _isProcessingMissingSsrcs = true; |
| 1886 | auto timestamp = rtc::TimeMillis(); |
| 1887 | if (timestamp > _missingSsrcsProcessedTimestamp + 200) { |
| 1888 | applyMissingSsrcs(); |
| 1889 | } else { |
| 1890 | const auto weak = std::weak_ptr<GroupInstanceManager>(shared_from_this()); |
| 1891 | getMediaThread()->PostDelayedTask(RTC_FROM_HERE, [weak]() { |
| 1892 | auto strong = weak.lock(); |
| 1893 | if (!strong) { |
| 1894 | return; |
| 1895 | } |
| 1896 | strong->applyMissingSsrcs(); |
| 1897 | }, 200); |
| 1898 | } |
| 1899 | } |
| 1900 |
| 1901 | void applyMissingSsrcs() { |
| 1902 | assert(_isProcessingMissingSsrcs); |
| 1903 | if (_missingSsrcQueue.size() == 0) { |
| 1904 | completeProcessingMissingSsrcs(); |
| 1905 | return; |
| 1906 | } |
| 1907 |
| 1908 | std::vector<uint32_t> addSsrcs; |
| 1909 | for (auto ssrc : _missingSsrcQueue) { |
| 1910 | addSsrcs.push_back(ssrc); |
| 1911 | } |
| 1912 | _missingSsrcQueue.clear(); |
| 1913 |
| 1914 | const auto weak = std::weak_ptr<GroupInstanceManager>(shared_from_this()); |
| 1915 | addSsrcsInternal(addSsrcs, true); |
| 1916 | } |
| 1917 |
| 1918 | void completeProcessingMissingSsrcs() { |
| 1919 | assert(_isProcessingMissingSsrcs); |
| 1920 | _isProcessingMissingSsrcs = false; |
| 1921 | _missingSsrcsProcessedTimestamp = rtc::TimeMillis(); |
| 1922 |
| 1923 | if (_missingSsrcQueue.size() != 0) { |
| 1924 | beginProcessingMissingSsrcs(); |
| 1925 | } |
| 1926 | } |
| 1927 |
| 1928 | void completedInitialSetup() { |
| 1929 | //beginDebugSsrcTimer(1000); |
| 1930 | } |
| 1931 |
| 1932 | uint32_t _nextTestSsrc = 100; |
| 1933 |
| 1934 | void beginDebugSsrcTimer(int timeout) { |
| 1935 | const auto weak = std::weak_ptr<GroupInstanceManager>(shared_from_this()); |
| 1936 | getMediaThread()->PostDelayedTask(RTC_FROM_HERE, [weak]() { |
| 1937 | auto strong = weak.lock(); |
| 1938 | if (!strong) { |
| 1939 | return; |
| 1940 | } |
| 1941 |
| 1942 | if (strong->_nextTestSsrc >= 100 + 50) { |
| 1943 | return; |
| 1944 | } |
| 1945 |
| 1946 | strong->_nextTestSsrc++; |
| 1947 | strong->onMissingSsrc(strong->_nextTestSsrc); |
| 1948 |
| 1949 | strong->beginDebugSsrcTimer(20); |
| 1950 | }, timeout); |
| 1951 | } |
| 1952 |
| 1953 | void setIsMuted(bool isMuted) { |
| 1954 | if (!_localAudioTrackSender) { |
| 1955 | return; |
| 1956 | } |
| 1957 | if (_isMuted == isMuted) { |
| 1958 | return; |
| 1959 | } |
| 1960 |
| 1961 | for (auto &it : _peerConnection->GetTransceivers()) { |
| 1962 | if (it->media_type() == cricket::MediaType::MEDIA_TYPE_AUDIO) { |
| 1963 | if (_localAudioTrackSender.get() == it->sender().get()) { |
| 1964 | if (isMuted) { |
| 1965 | /*if (it->direction() == webrtc::RtpTransceiverDirection::kSendRecv) { |
| 1966 | it->SetDirection(webrtc::RtpTransceiverDirection::kRecvOnly); |
| 1967 |
| 1968 | applyLocalSdp(); |
| 1969 |
| 1970 | break; |
| 1971 | }*/ |
| 1972 | } else { |
| 1973 | if (it->direction() == webrtc::RtpTransceiverDirection::kRecvOnly) { |
| 1974 | it->SetDirection(webrtc::RtpTransceiverDirection::kSendRecv); |
| 1975 |
| 1976 | applyLocalSdp(); |
| 1977 |
| 1978 | break; |
| 1979 | } |
| 1980 | } |
| 1981 | } |
| 1982 |
| 1983 | break; |
| 1984 | } |
| 1985 | } |
| 1986 |
| 1987 | _isMuted = isMuted; |
| 1988 | _localAudioTrack->set_enabled(!isMuted); |
| 1989 |
| 1990 | RTC_LOG(LoggingSeverity::WARNING) << "setIsMuted: " << isMuted; |
| 1991 | } |
| 1992 |
| 1993 | void emitAnswer(bool completeMissingSsrcSetup) { |
| 1994 | const auto weak = std::weak_ptr<GroupInstanceManager>(shared_from_this()); |
| 1995 |
| 1996 | webrtc::PeerConnectionInterface::RTCOfferAnswerOptions options; |
| 1997 | rtc::scoped_refptr<CreateSessionDescriptionObserverImpl> observer(new rtc::RefCountedObject<CreateSessionDescriptionObserverImpl>([weak, completeMissingSsrcSetup](std::string sdp, std::string type) { |
| 1998 | getMediaThread()->PostTask(RTC_FROM_HERE, [weak, sdp, type, completeMissingSsrcSetup](){ |
| 1999 | auto strong = weak.lock(); |
| 2000 | if (!strong) { |
| 2001 | return; |
| 2002 | } |
| 2003 |
| 2004 | RTC_LOG(LoggingSeverity::WARNING) << "----- setLocalDescription answer -----"; |
| 2005 | RTC_LOG(LoggingSeverity::WARNING) << sdp; |
| 2006 | RTC_LOG(LoggingSeverity::WARNING) << "-----"; |
| 2007 |
| 2008 | webrtc::SdpParseError error; |
| 2009 | webrtc::SessionDescriptionInterface *sessionDescription = webrtc::CreateSessionDescription(type, adjustLocalDescription(sdp), &error); |
| 2010 | if (sessionDescription != nullptr) { |
| 2011 | rtc::scoped_refptr<SetSessionDescriptionObserverImpl> observer(new rtc::RefCountedObject<SetSessionDescriptionObserverImpl>([weak, sdp, completeMissingSsrcSetup]() { |
| 2012 | auto strong = weak.lock(); |
| 2013 | if (!strong) { |
| 2014 | return; |
| 2015 | } |
| 2016 |
| 2017 | if (completeMissingSsrcSetup) { |
| 2018 | strong->completeProcessingMissingSsrcs(); |
| 2019 | } |
| 2020 | }, [weak, completeMissingSsrcSetup](webrtc::RTCError error) { |
| 2021 | auto strong = weak.lock(); |
| 2022 | if (!strong) { |
| 2023 | return; |
| 2024 | } |
| 2025 |
| 2026 | if (completeMissingSsrcSetup) { |
| 2027 | strong->completeProcessingMissingSsrcs(); |
| 2028 | } |
| 2029 | })); |
| 2030 | strong->_peerConnection->SetLocalDescription(observer, sessionDescription); |
| 2031 | } else { |
| 2032 | if (completeMissingSsrcSetup) { |
| 2033 | strong->completeProcessingMissingSsrcs(); |
| 2034 | } |
| 2035 | } |
| 2036 | }); |
| 2037 | })); |
| 2038 | _peerConnection->CreateAnswer(observer, options); |
| 2039 | } |
| 2040 |
| 2041 | private: |
| 2042 | void withAudioDeviceModule(std::function<void(webrtc::AudioDeviceModule*)> callback) { |
| 2043 | _adm_thread->Invoke<void>(RTC_FROM_HERE, [&] { |
| 2044 | callback(_adm_use_withAudioDeviceModule.get()); |
| 2045 | }); |
| 2046 | } |
| 2047 |
| 2048 | std::function<void(bool)> _networkStateUpdated; |
| 2049 | std::function<void(GroupLevelsUpdate const &)> _audioLevelsUpdated; |
| 2050 |
| 2051 | int32_t _myAudioLevelPeakCount = 0; |
| 2052 | float _myAudioLevelPeak = 0; |
| 2053 | GroupLevelValue _myAudioLevel; |
| 2054 |
| 2055 | std::string _initialInputDeviceId; |
| 2056 | std::string _initialOutputDeviceId; |
| 2057 |
| 2058 | uint32_t _sessionId = 6543245; |
| 2059 | uint32_t _mainStreamAudioSsrc = 0; |
| 2060 | uint32_t _fakeIncomingSsrc = 0; |
| 2061 | absl::optional<GroupJoinResponsePayload> _joinPayload; |
| 2062 |
| 2063 | int64_t _appliedOfferTimestamp = 0; |
| 2064 | bool _isConnected = false; |
| 2065 | int _isConnectedUpdateValidTaskId = 0; |
| 2066 |
| 2067 | bool _isMuted = true; |
| 2068 |
| 2069 | std::vector<uint32_t> _allOtherSsrcs; |
| 2070 | std::set<uint32_t> _activeOtherSsrcs; |
| 2071 | std::set<uint32_t> _processedMissingSsrcs; |
| 2072 |
| 2073 | int64_t _missingSsrcsProcessedTimestamp = 0; |
| 2074 | bool _isProcessingMissingSsrcs = false; |
| 2075 | std::set<uint32_t> _missingSsrcQueue; |
| 2076 |
| 2077 | std::string _appliedRemoteRescription; |
| 2078 |
| 2079 | rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> _nativeFactory; |
| 2080 | std::unique_ptr<PeerConnectionObserverImpl> _observer; |
| 2081 | rtc::scoped_refptr<webrtc::PeerConnectionInterface> _peerConnection; |
| 2082 | std::unique_ptr<AudioTrackSinkInterfaceImpl> _localAudioTrackSink; |
| 2083 | rtc::scoped_refptr<webrtc::AudioTrackInterface> _localAudioTrack; |
| 2084 | rtc::scoped_refptr<webrtc::RtpSenderInterface> _localAudioTrackSender; |
| 2085 |
| 2086 | rtc::Thread *_adm_thread = nullptr; |
| 2087 | rtc::scoped_refptr<webrtc::AudioDeviceModule> _adm_use_withAudioDeviceModule; |
| 2088 |
| 2089 | std::map<uint32_t, rtc::scoped_refptr<webrtc::AudioTrackInterface>> _audioTracks; |
| 2090 | std::map<uint32_t, std::shared_ptr<AudioTrackSinkInterfaceImpl>> _audioTrackSinks; |
| 2091 | std::map<uint32_t, GroupLevelValue> _audioLevels; |
| 2092 | std::map<uint32_t, double> _audioTrackVolumes; |
| 2093 |
| 2094 | std::shared_ptr<PlatformContext> _platformContext; |
| 2095 | }; |
| 2096 |
| 2097 | GroupInstanceImpl::GroupInstanceImpl(GroupInstanceDescriptor &&descriptor) |
| 2098 | : _logSink(std::make_unique<LogSinkImpl>(descriptor.config.logPath)) { |
| 2099 | rtc::LogMessage::LogToDebug(rtc::LS_INFO); |
| 2100 | rtc::LogMessage::SetLogToStderr(true); |
| 2101 | if (_logSink) { |
| 2102 | rtc::LogMessage::AddLogToStream(_logSink.get(), rtc::LS_INFO); |
| 2103 | } |
| 2104 |
| 2105 | _manager.reset(new ThreadLocalObject<GroupInstanceManager>(getMediaThread(), [descriptor = std::move(descriptor)]() mutable { |
| 2106 | return new GroupInstanceManager(std::move(descriptor)); |
| 2107 | })); |
| 2108 | _manager->perform(RTC_FROM_HERE, [](GroupInstanceManager *manager) { |
| 2109 | manager->start(); |
| 2110 | }); |
| 2111 | } |
| 2112 |
| 2113 | GroupInstanceImpl::~GroupInstanceImpl() { |
| 2114 | if (_logSink) { |
| 2115 | rtc::LogMessage::RemoveLogToStream(_logSink.get()); |
| 2116 | } |
| 2117 | _manager = nullptr; |
| 2118 |
| 2119 | // Wait until _manager is destroyed, otherwise there is a race condition |
| 2120 | // in destruction of PeerConnection on media thread and network thread. |
| 2121 | getMediaThread()->Invoke<void>(RTC_FROM_HERE, [] {}); |
| 2122 | } |
| 2123 |
| 2124 | void GroupInstanceImpl::stop() { |
| 2125 | _manager->perform(RTC_FROM_HERE, [](GroupInstanceManager *manager) { |
| 2126 | manager->stop(); |
| 2127 | }); |
| 2128 | } |
| 2129 |
| 2130 | void GroupInstanceImpl::emitJoinPayload(std::function<void(GroupJoinPayload)> completion) { |
| 2131 | _manager->perform(RTC_FROM_HERE, [completion](GroupInstanceManager *manager) { |
| 2132 | manager->emitJoinPayload(completion); |
| 2133 | }); |
| 2134 | } |
| 2135 |
| 2136 | void GroupInstanceImpl::setJoinResponsePayload(GroupJoinResponsePayload payload) { |
| 2137 | _manager->perform(RTC_FROM_HERE, [payload](GroupInstanceManager *manager) { |
| 2138 | manager->setJoinResponsePayload(payload); |
| 2139 | }); |
| 2140 | } |
| 2141 |
| 2142 | void GroupInstanceImpl::removeSsrcs(std::vector<uint32_t> ssrcs) { |
| 2143 | _manager->perform(RTC_FROM_HERE, [ssrcs](GroupInstanceManager *manager) { |
| 2144 | manager->removeSsrcs(ssrcs); |
| 2145 | }); |
| 2146 | } |
| 2147 |
| 2148 | void GroupInstanceImpl::setIsMuted(bool isMuted) { |
| 2149 | _manager->perform(RTC_FROM_HERE, [isMuted](GroupInstanceManager *manager) { |
| 2150 | manager->setIsMuted(isMuted); |
| 2151 | }); |
| 2152 | } |
| 2153 |
| 2154 | void GroupInstanceImpl::setAudioInputDevice(std::string id) { |
| 2155 | _manager->perform(RTC_FROM_HERE, [id](GroupInstanceManager *manager) { |
| 2156 | manager->setAudioInputDevice(id); |
| 2157 | }); |
| 2158 | } |
| 2159 | void GroupInstanceImpl::setAudioOutputDevice(std::string id) { |
| 2160 | _manager->perform(RTC_FROM_HERE, [id](GroupInstanceManager *manager) { |
| 2161 | manager->setAudioOutputDevice(id); |
| 2162 | }); |
| 2163 | } |
| 2164 |
| 2165 | void GroupInstanceImpl::setVolume(uint32_t ssrc, double volume) { |
| 2166 | _manager->perform(RTC_FROM_HERE, [ssrc, volume](GroupInstanceManager *manager) { |
| 2167 | manager->setVolume(ssrc, volume); |
| 2168 | }); |
| 2169 | } |
| 2170 |
| 2171 | } // namespace tgcalls |
| 2172 |