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