| #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 | #include "StaticThreads.h" |
| 34 |
| 35 | #include <random> |
| 36 | #include <sstream> |
| 37 | #include <iostream> |
| 38 |
| 39 | namespace tgcalls { |
| 40 |
| 41 | namespace { |
| 42 |
| 43 | static std::vector<std::string> splitSdpLines(std::string const &sdp) { |
| 44 | std::vector<std::string> result; |
| 45 |
| 46 | std::istringstream sdpStream(sdp); |
| 47 |
| 48 | std::string s; |
| 49 | while (std::getline(sdpStream, s, '\n')) { |
| 50 | if (s.size() == 0) { |
| 51 | continue; |
| 52 | } |
| 53 | if (s[s.size() - 1] == '\r') { |
| 54 | s.resize(s.size() - 1); |
| 55 | } |
| 56 | result.push_back(s); |
| 57 | } |
| 58 |
| 59 | return result; |
| 60 | } |
| 61 |
| 62 | static std::vector<std::string> splitFingerprintLines(std::string const &line) { |
| 63 | std::vector<std::string> result; |
| 64 |
| 65 | std::istringstream sdpStream(line); |
| 66 |
| 67 | std::string s; |
| 68 | while (std::getline(sdpStream, s, ' ')) { |
| 69 | if (s.size() == 0) { |
| 70 | continue; |
| 71 | } |
| 72 | result.push_back(s); |
| 73 | } |
| 74 |
| 75 | return result; |
| 76 | } |
| 77 |
| 78 | static std::vector<uint32_t> splitSsrcList(std::string const &line) { |
| 79 | std::vector<uint32_t> result; |
| 80 |
| 81 | std::istringstream sdpStream(line); |
| 82 |
| 83 | std::string s; |
| 84 | while (std::getline(sdpStream, s, ' ')) { |
| 85 | if (s.size() == 0) { |
| 86 | continue; |
| 87 | } |
| 88 |
| 89 | std::istringstream iss(s); |
| 90 | uint32_t ssrc = 0; |
| 91 | iss >> ssrc; |
| 92 |
| 93 | result.push_back(ssrc); |
| 94 | } |
| 95 |
| 96 | return result; |
| 97 | } |
| 98 |
| 99 | static std::vector<std::string> splitBundleMLines(std::string const &line) { |
| 100 | std::vector<std::string> result; |
| 101 |
| 102 | std::istringstream sdpStream(line); |
| 103 |
| 104 | std::string s; |
| 105 | while (std::getline(sdpStream, s, ' ')) { |
| 106 | if (s.size() == 0) { |
| 107 | continue; |
| 108 | } |
| 109 |
| 110 | result.push_back(s); |
| 111 | } |
| 112 |
| 113 | return result; |
| 114 | } |
| 115 |
| 116 | static std::vector<std::string> getLines(std::vector<std::string> const &lines, std::string prefix) { |
| 117 | std::vector<std::string> result; |
| 118 |
| 119 | for (auto &line : lines) { |
| 120 | if (line.find(prefix) == 0) { |
| 121 | auto cleanLine = line; |
| 122 | cleanLine.replace(0, prefix.size(), ""); |
| 123 | result.push_back(cleanLine); |
| 124 | } |
| 125 | } |
| 126 |
| 127 | return result; |
| 128 | } |
| 129 |
| 130 | static absl::optional<GroupJoinPayloadVideoPayloadType> parsePayloadType(uint32_t id, std::string const &line) { |
| 131 | std::string s; |
| 132 | std::istringstream lineStream(line); |
| 133 | std::string codec; |
| 134 | uint32_t clockrate = 0; |
| 135 | uint32_t channels = 0; |
| 136 | for (int i = 0; std::getline(lineStream, s, '/'); i++) { |
| 137 | if (s.size() == 0) { |
| 138 | continue; |
| 139 | } |
| 140 |
| 141 | if (i == 0) { |
| 142 | codec = s; |
| 143 | } else if (i == 1) { |
| 144 | std::istringstream iss(s); |
| 145 | iss >> clockrate; |
| 146 | } else if (i == 2) { |
| 147 | std::istringstream iss(s); |
| 148 | iss >> channels; |
| 149 | } |
| 150 | } |
| 151 | if (codec.size() != 0) { |
| 152 | GroupJoinPayloadVideoPayloadType payloadType; |
| 153 | payloadType.id = id; |
| 154 | payloadType.name = codec; |
| 155 | payloadType.clockrate = clockrate; |
| 156 | payloadType.channels = channels; |
| 157 | return payloadType; |
| 158 | } else { |
| 159 | return absl::nullopt; |
| 160 | } |
| 161 | } |
| 162 |
| 163 | static absl::optional<GroupJoinPayloadVideoPayloadFeedbackType> parseFeedbackType(std::string const &line) { |
| 164 | std::istringstream lineStream(line); |
| 165 | std::string s; |
| 166 |
| 167 | std::string type; |
| 168 | std::string subtype; |
| 169 | for (int i = 0; std::getline(lineStream, s, ' '); i++) { |
| 170 | if (s.size() == 0) { |
| 171 | continue; |
| 172 | } |
| 173 |
| 174 | if (i == 0) { |
| 175 | type = s; |
| 176 | } else if (i == 1) { |
| 177 | subtype = s; |
| 178 | } |
| 179 | } |
| 180 |
| 181 | if (type.size() != 0) { |
| 182 | GroupJoinPayloadVideoPayloadFeedbackType parsedType; |
| 183 | parsedType.type = type; |
| 184 | parsedType.subtype = subtype; |
| 185 | return parsedType; |
| 186 | } else { |
| 187 | return absl::nullopt; |
| 188 | } |
| 189 | } |
| 190 |
| 191 | static void parsePayloadParameter(std::string const &line, std::vector<std::pair<std::string, std::string>> &result) { |
| 192 | std::istringstream lineStream(line); |
| 193 | std::string s; |
| 194 |
| 195 | std::string key; |
| 196 | std::string value; |
| 197 | for (int i = 0; std::getline(lineStream, s, '='); i++) { |
| 198 | if (s.size() == 0) { |
| 199 | continue; |
| 200 | } |
| 201 |
| 202 | if (i == 0) { |
| 203 | key = s; |
| 204 | } else if (i == 1) { |
| 205 | value = s; |
| 206 | } |
| 207 | } |
| 208 | if (key.size() != 0 && value.size() != 0) { |
| 209 | result.push_back(std::make_pair(key, value)); |
| 210 | } |
| 211 | } |
| 212 |
| 213 | static std::vector<std::pair<std::string, std::string>> parsePayloadParameters(std::string const &line) { |
| 214 | std::vector<std::pair<std::string, std::string>> result; |
| 215 |
| 216 | std::istringstream lineStream(line); |
| 217 | std::string s; |
| 218 |
| 219 | while (std::getline(lineStream, s, ';')) { |
| 220 | if (s.size() == 0) { |
| 221 | continue; |
| 222 | } |
| 223 |
| 224 | parsePayloadParameter(s, result); |
| 225 | } |
| 226 |
| 227 | return result; |
| 228 | } |
| 229 |
| 230 | static absl::optional<GroupJoinPayload> parseSdpIntoJoinPayload(std::string const &sdp) { |
| 231 | GroupJoinPayload result; |
| 232 |
| 233 | auto lines = splitSdpLines(sdp); |
| 234 |
| 235 | std::vector<std::string> audioLines; |
| 236 | std::vector<std::string> videoLines; |
| 237 | bool isAudioLine = false; |
| 238 | bool isVideoLine = false; |
| 239 | for (auto &line : lines) { |
| 240 | if (line.find("m=audio") == 0) { |
| 241 | isAudioLine = true; |
| 242 | isVideoLine = false; |
| 243 | } else if (line.find("m=video") == 0) { |
| 244 | isAudioLine = false; |
| 245 | isVideoLine = true; |
| 246 | } else if (line.find("m=application") == 0) { |
| 247 | isAudioLine = false; |
| 248 | isVideoLine = true; |
| 249 | } |
| 250 | if (isAudioLine) { |
| 251 | audioLines.push_back(line); |
| 252 | } else if (isVideoLine) { |
| 253 | videoLines.push_back(line); |
| 254 | } |
| 255 | } |
| 256 |
| 257 | result.ssrc = 0; |
| 258 |
| 259 | auto ufragLines = getLines(audioLines, "a=ice-ufrag:"); |
| 260 | if (ufragLines.size() != 1) { |
| 261 | return absl::nullopt; |
| 262 | } |
| 263 | result.ufrag = ufragLines[0]; |
| 264 |
| 265 | auto pwdLines = getLines(audioLines, "a=ice-pwd:"); |
| 266 | if (pwdLines.size() != 1) { |
| 267 | return absl::nullopt; |
| 268 | } |
| 269 | result.pwd = pwdLines[0]; |
| 270 |
| 271 | for (auto &line : getLines(audioLines, "a=fingerprint:")) { |
| 272 | auto fingerprintComponents = splitFingerprintLines(line); |
| 273 | if (fingerprintComponents.size() != 2) { |
| 274 | continue; |
| 275 | } |
| 276 |
| 277 | GroupJoinPayloadFingerprint fingerprint; |
| 278 | fingerprint.hash = fingerprintComponents[0]; |
| 279 | fingerprint.fingerprint = fingerprintComponents[1]; |
| 280 | fingerprint.setup = "active"; |
| 281 | result.fingerprints.push_back(fingerprint); |
| 282 | } |
| 283 |
| 284 | for (auto &line : getLines(videoLines, "a=rtpmap:")) { |
| 285 | std::string s; |
| 286 | std::istringstream lineStream(line); |
| 287 | uint32_t id = 0; |
| 288 | for (int i = 0; std::getline(lineStream, s, ' '); i++) { |
| 289 | if (s.size() == 0) { |
| 290 | continue; |
| 291 | } |
| 292 |
| 293 | if (i == 0) { |
| 294 | std::istringstream iss(s); |
| 295 | iss >> id; |
| 296 | } else if (i == 1) { |
| 297 | if (id != 0) { |
| 298 | auto payloadType = parsePayloadType(id, s); |
| 299 | if (payloadType.has_value()) { |
| 300 | std::ostringstream fbPrefixStream; |
| 301 | fbPrefixStream << "a=rtcp-fb:"; |
| 302 | fbPrefixStream << id; |
| 303 | fbPrefixStream << " "; |
| 304 | for (auto &feedbackLine : getLines(videoLines, fbPrefixStream.str())) { |
| 305 | auto feedbackType = parseFeedbackType(feedbackLine); |
| 306 | if (feedbackType.has_value()) { |
| 307 | payloadType->feedbackTypes.push_back(feedbackType.value()); |
| 308 | } |
| 309 | } |
| 310 |
| 311 | std::ostringstream parametersPrefixStream; |
| 312 | parametersPrefixStream << "a=fmtp:"; |
| 313 | parametersPrefixStream << id; |
| 314 | parametersPrefixStream << " "; |
| 315 | for (auto ¶metersLine : getLines(videoLines, parametersPrefixStream.str())) { |
| 316 | payloadType->parameters = parsePayloadParameters(parametersLine); |
| 317 | } |
| 318 |
| 319 | result.videoPayloadTypes.push_back(payloadType.value()); |
| 320 | } |
| 321 | } |
| 322 | } |
| 323 | } |
| 324 | } |
| 325 |
| 326 | for (auto &line : getLines(videoLines, "a=extmap:")) { |
| 327 | std::string s; |
| 328 | std::istringstream lineStream(line); |
| 329 | uint32_t id = 0; |
| 330 | for (int i = 0; std::getline(lineStream, s, ' '); i++) { |
| 331 | if (s.size() == 0) { |
| 332 | continue; |
| 333 | } |
| 334 |
| 335 | if (i == 0) { |
| 336 | std::istringstream iss(s); |
| 337 | iss >> id; |
| 338 | } else if (i == 1) { |
| 339 | if (id != 0) { |
| 340 | result.videoExtensionMap.push_back(std::make_pair(id, s)); |
| 341 | } |
| 342 | } |
| 343 | } |
| 344 | } |
| 345 |
| 346 | for (auto &line : getLines(videoLines, "a=ssrc-group:FID ")) { |
| 347 | auto ssrcs = splitSsrcList(line); |
| 348 | GroupJoinPayloadVideoSourceGroup group; |
| 349 | group.semantics = "FID"; |
| 350 | group.ssrcs = ssrcs; |
| 351 | result.videoSourceGroups.push_back(std::move(group)); |
| 352 | } |
| 353 | for (auto &line : getLines(videoLines, "a=ssrc-group:SIM ")) { |
| 354 | auto ssrcs = splitSsrcList(line); |
| 355 | GroupJoinPayloadVideoSourceGroup group; |
| 356 | group.semantics = "SIM"; |
| 357 | group.ssrcs = ssrcs; |
| 358 | result.videoSourceGroups.push_back(std::move(group)); |
| 359 | } |
| 360 |
| 361 | return result; |
| 362 | } |
| 363 |
| 364 | struct StreamSpec { |
| 365 | bool isMain = false; |
| 366 | bool isOutgoing = false; |
| 367 | std::string mLine; |
| 368 | uint32_t streamId = 0; |
| 369 | uint32_t ssrc = 0; |
| 370 | std::vector<GroupJoinPayloadVideoSourceGroup> videoSourceGroups; |
| 371 | std::vector<GroupJoinPayloadVideoPayloadType> videoPayloadTypes; |
| 372 | std::vector<std::pair<uint32_t, std::string>> videoExtensionMap; |
| 373 | bool isRemoved = false; |
| 374 | bool isData = false; |
| 375 | bool isVideo = false; |
| 376 | }; |
| 377 |
| 378 | static void appendSdp(std::vector<std::string> &lines, std::string const &line, int index = -1) { |
| 379 | if (index >= 0) { |
| 380 | lines.insert(lines.begin() + index, line); |
| 381 | } else { |
| 382 | lines.push_back(line); |
| 383 | } |
| 384 | } |
| 385 |
| 386 | enum class SdpType { |
| 387 | kSdpTypeJoinAnswer, |
| 388 | kSdpTypeRemoteOffer, |
| 389 | kSdpTypeLocalAnswer |
| 390 | }; |
| 391 |
| 392 | static std::string createSdp(uint32_t sessionId, GroupJoinResponsePayload const &payload, SdpType type, std::vector<StreamSpec> const &bundleStreams) { |
| 393 | std::vector<std::string> sdp; |
| 394 |
| 395 | appendSdp(sdp, "v=0"); |
| 396 |
| 397 | std::ostringstream sessionIdString; |
| 398 | sessionIdString << "o=- "; |
| 399 | sessionIdString << sessionId; |
| 400 | sessionIdString << " 2 IN IP4 0.0.0.0"; |
| 401 | appendSdp(sdp, sessionIdString.str()); |
| 402 |
| 403 | appendSdp(sdp, "s=-"); |
| 404 | appendSdp(sdp, "t=0 0"); |
| 405 |
| 406 | std::ostringstream bundleString; |
| 407 | bundleString << "a=group:BUNDLE"; |
| 408 | for (auto &stream : bundleStreams) { |
| 409 | bundleString << " "; |
| 410 | bundleString << stream.mLine; |
| 411 | } |
| 412 | appendSdp(sdp, bundleString.str()); |
| 413 |
| 414 | appendSdp(sdp, "a=ice-lite"); |
| 415 |
| 416 | for (auto &stream : bundleStreams) { |
| 417 | std::ostringstream streamMidString; |
| 418 | streamMidString << "a=mid:" << stream.mLine; |
| 419 |
| 420 | if (stream.isData) { |
| 421 | appendSdp(sdp, "m=application 9 UDP/DTLS/SCTP webrtc-datachannel"); |
| 422 | appendSdp(sdp, "c=IN IP4 0.0.0.0"); |
| 423 |
| 424 | std::ostringstream ufragString; |
| 425 | ufragString << "a=ice-ufrag:"; |
| 426 | ufragString << payload.ufrag; |
| 427 | appendSdp(sdp, ufragString.str()); |
| 428 |
| 429 | std::ostringstream pwdString; |
| 430 | pwdString << "a=ice-pwd:"; |
| 431 | pwdString << payload.pwd; |
| 432 | appendSdp(sdp, pwdString.str()); |
| 433 |
| 434 | for (auto &fingerprint : payload.fingerprints) { |
| 435 | std::ostringstream fingerprintString; |
| 436 | fingerprintString << "a=fingerprint:"; |
| 437 | fingerprintString << fingerprint.hash; |
| 438 | fingerprintString << " "; |
| 439 | fingerprintString << fingerprint.fingerprint; |
| 440 | appendSdp(sdp, fingerprintString.str()); |
| 441 | appendSdp(sdp, "a=setup:passive"); |
| 442 | } |
| 443 |
| 444 | appendSdp(sdp, streamMidString.str()); |
| 445 | appendSdp(sdp, "a=sctp-port:5000"); |
| 446 | appendSdp(sdp, "a=max-message-size:262144"); |
| 447 | } else { |
| 448 | std::ostringstream mLineString; |
| 449 | if (stream.isVideo) { |
| 450 | mLineString << "m=video "; |
| 451 | } else { |
| 452 | mLineString << "m=audio "; |
| 453 | } |
| 454 | if (stream.isMain) { |
| 455 | mLineString << "1"; |
| 456 | } else { |
| 457 | mLineString << "0"; |
| 458 | } |
| 459 | if (stream.videoPayloadTypes.size() == 0) { |
| 460 | mLineString << " RTP/AVPF 111 126"; |
| 461 | } else { |
| 462 | mLineString << " RTP/AVPF"; |
| 463 | for (auto &it : stream.videoPayloadTypes) { |
| 464 | mLineString << " " << it.id; |
| 465 | } |
| 466 | } |
| 467 |
| 468 | appendSdp(sdp, mLineString.str()); |
| 469 |
| 470 | if (stream.isMain) { |
| 471 | appendSdp(sdp, "c=IN IP4 0.0.0.0"); |
| 472 | } |
| 473 |
| 474 | appendSdp(sdp, streamMidString.str()); |
| 475 |
| 476 | std::ostringstream ufragString; |
| 477 | ufragString << "a=ice-ufrag:"; |
| 478 | ufragString << payload.ufrag; |
| 479 | appendSdp(sdp, ufragString.str()); |
| 480 |
| 481 | std::ostringstream pwdString; |
| 482 | pwdString << "a=ice-pwd:"; |
| 483 | pwdString << payload.pwd; |
| 484 | appendSdp(sdp, pwdString.str()); |
| 485 |
| 486 | for (auto &fingerprint : payload.fingerprints) { |
| 487 | std::ostringstream fingerprintString; |
| 488 | fingerprintString << "a=fingerprint:"; |
| 489 | fingerprintString << fingerprint.hash; |
| 490 | fingerprintString << " "; |
| 491 | fingerprintString << fingerprint.fingerprint; |
| 492 | appendSdp(sdp, fingerprintString.str()); |
| 493 | appendSdp(sdp, "a=setup:passive"); |
| 494 | } |
| 495 |
| 496 | if (stream.isMain) { |
| 497 | for (auto &candidate : payload.candidates) { |
| 498 | std::ostringstream candidateString; |
| 499 | candidateString << "a=candidate:"; |
| 500 | candidateString << candidate.foundation; |
| 501 | candidateString << " "; |
| 502 | candidateString << candidate.component; |
| 503 | candidateString << " "; |
| 504 | candidateString << candidate.protocol; |
| 505 | candidateString << " "; |
| 506 | candidateString << candidate.priority; |
| 507 | candidateString << " "; |
| 508 | candidateString << candidate.ip; |
| 509 | candidateString << " "; |
| 510 | candidateString << candidate.port; |
| 511 | candidateString << " "; |
| 512 | candidateString << "typ "; |
| 513 | candidateString << candidate.type; |
| 514 | candidateString << " "; |
| 515 |
| 516 | if (candidate.type == "srflx" || candidate.type == "prflx" || candidate.type == "relay") { |
| 517 | if (candidate.relAddr.size() != 0 && candidate.relPort.size() != 0) { |
| 518 | candidateString << "raddr "; |
| 519 | candidateString << candidate.relAddr; |
| 520 | candidateString << " "; |
| 521 | candidateString << "rport "; |
| 522 | candidateString << candidate.relPort; |
| 523 | candidateString << " "; |
| 524 | } |
| 525 | } |
| 526 |
| 527 | if (candidate.protocol == "tcp") { |
| 528 | if (candidate.tcpType.size() != 0) { |
| 529 | candidateString << "tcptype "; |
| 530 | candidateString << candidate.tcpType; |
| 531 | candidateString << " "; |
| 532 | } |
| 533 | } |
| 534 |
| 535 | candidateString << "generation "; |
| 536 | candidateString << candidate.generation; |
| 537 |
| 538 | appendSdp(sdp, candidateString.str()); |
| 539 | } |
| 540 | } |
| 541 |
| 542 | if (!stream.isVideo) { |
| 543 | appendSdp(sdp, "a=rtpmap:111 opus/48000/2"); |
| 544 | appendSdp(sdp, "a=rtpmap:126 telephone-event/8000"); |
| 545 | appendSdp(sdp, "a=fmtp:111 minptime=10; useinbandfec=1"); |
| 546 | appendSdp(sdp, "a=rtcp:1 IN IP4 0.0.0.0"); |
| 547 | appendSdp(sdp, "a=rtcp-mux"); |
| 548 | appendSdp(sdp, "a=rtcp-rsize"); |
| 549 | appendSdp(sdp, "a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level"); |
| 550 | appendSdp(sdp, "a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"); |
| 551 | appendSdp(sdp, "a=extmap:3 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"); |
| 552 |
| 553 | bool addSsrcs = false; |
| 554 | if (stream.isRemoved) { |
| 555 | appendSdp(sdp, "a=inactive"); |
| 556 | } else if (type == SdpType::kSdpTypeJoinAnswer) { |
| 557 | if (stream.isOutgoing) { |
| 558 | appendSdp(sdp, "a=recvonly"); |
| 559 | } else { |
| 560 | appendSdp(sdp, "a=sendonly"); |
| 561 | appendSdp(sdp, "a=bundle-only"); |
| 562 | addSsrcs = true; |
| 563 | } |
| 564 | } else if (type == SdpType::kSdpTypeRemoteOffer) { |
| 565 | if (stream.isOutgoing) { |
| 566 | appendSdp(sdp, "a=recvonly"); |
| 567 | } else { |
| 568 | appendSdp(sdp, "a=sendonly"); |
| 569 | appendSdp(sdp, "a=bundle-only"); |
| 570 | addSsrcs = true; |
| 571 | } |
| 572 | } else if (type == SdpType::kSdpTypeLocalAnswer) { |
| 573 | if (stream.isOutgoing) { |
| 574 | appendSdp(sdp, "a=sendonly"); |
| 575 | addSsrcs = true; |
| 576 | } else { |
| 577 | appendSdp(sdp, "a=recvonly"); |
| 578 | appendSdp(sdp, "a=bundle-only"); |
| 579 | } |
| 580 | } |
| 581 |
| 582 | if (addSsrcs) { |
| 583 | std::ostringstream cnameString; |
| 584 | cnameString << "a=ssrc:"; |
| 585 | cnameString << stream.ssrc; |
| 586 | cnameString << " cname:stream"; |
| 587 | cnameString << stream.streamId; |
| 588 | appendSdp(sdp, cnameString.str()); |
| 589 |
| 590 | std::ostringstream msidString; |
| 591 | msidString << "a=ssrc:"; |
| 592 | msidString << stream.ssrc; |
| 593 | msidString << " msid:stream"; |
| 594 | msidString << stream.streamId; |
| 595 | msidString << " audio" << stream.streamId; |
| 596 | appendSdp(sdp, msidString.str()); |
| 597 |
| 598 | std::ostringstream mslabelString; |
| 599 | mslabelString << "a=ssrc:"; |
| 600 | mslabelString << stream.ssrc; |
| 601 | mslabelString << " mslabel:audio"; |
| 602 | mslabelString << stream.streamId; |
| 603 | appendSdp(sdp, mslabelString.str()); |
| 604 |
| 605 | std::ostringstream labelString; |
| 606 | labelString << "a=ssrc:"; |
| 607 | labelString << stream.ssrc; |
| 608 | labelString << " label:audio"; |
| 609 | labelString << stream.streamId; |
| 610 | appendSdp(sdp, labelString.str()); |
| 611 | } |
| 612 | } else { |
| 613 | appendSdp(sdp, "a=rtcp:1 IN IP4 0.0.0.0"); |
| 614 | appendSdp(sdp, "a=rtcp-mux"); |
| 615 | appendSdp(sdp, "a=rtcp-rsize"); |
| 616 |
| 617 | for (auto &it : stream.videoPayloadTypes) { |
| 618 | std::ostringstream rtpmapString; |
| 619 | rtpmapString << "a=rtpmap:"; |
| 620 | rtpmapString << it.id; |
| 621 | rtpmapString << " "; |
| 622 | rtpmapString << it.name; |
| 623 | rtpmapString << "/"; |
| 624 | rtpmapString << it.clockrate; |
| 625 | if (it.channels != 0) { |
| 626 | rtpmapString << "/"; |
| 627 | rtpmapString << it.channels; |
| 628 | } |
| 629 | appendSdp(sdp, rtpmapString.str()); |
| 630 |
| 631 | for (auto &feedbackType : it.feedbackTypes) { |
| 632 | std::ostringstream feedbackString; |
| 633 | feedbackString << "a=rtcp-fb:"; |
| 634 | feedbackString << it.id; |
| 635 | feedbackString << " "; |
| 636 | feedbackString << feedbackType.type; |
| 637 | if (feedbackType.subtype.size() != 0) { |
| 638 | feedbackString << " "; |
| 639 | feedbackString << feedbackType.subtype; |
| 640 | } |
| 641 | appendSdp(sdp, feedbackString.str()); |
| 642 | } |
| 643 |
| 644 | auto parameters = it.parameters; |
| 645 |
| 646 | if (it.name == "VP8") { |
| 647 | bool hasBitrate = false; |
| 648 | for (auto ¶m : parameters) { |
| 649 | if (param.first == "x-google-max-bitrate") { |
| 650 | hasBitrate = true; |
| 651 | } |
| 652 | } |
| 653 |
| 654 | if (!hasBitrate) { |
| 655 | parameters.push_back(std::make_pair("x-google-max-bitrate", "1200")); |
| 656 | //parameters.push_back(std::make_pair("x-google-start-bitrate", "300")); |
| 657 | } |
| 658 | } |
| 659 |
| 660 | if (parameters.size() != 0) { |
| 661 | std::ostringstream fmtpString; |
| 662 | fmtpString << "a=fmtp:"; |
| 663 | fmtpString << it.id; |
| 664 | fmtpString << " "; |
| 665 |
| 666 | for (int i = 0; i < parameters.size(); i++) { |
| 667 | if (i != 0) { |
| 668 | fmtpString << ";"; |
| 669 | } |
| 670 | fmtpString << parameters[i].first; |
| 671 | fmtpString << "="; |
| 672 | fmtpString << parameters[i].second; |
| 673 | } |
| 674 |
| 675 | appendSdp(sdp, fmtpString.str()); |
| 676 | } |
| 677 | } |
| 678 |
| 679 | for (auto &it : stream.videoExtensionMap) { |
| 680 | std::ostringstream extString; |
| 681 | extString << "a=extmap:"; |
| 682 | extString << it.first; |
| 683 | extString << " "; |
| 684 | extString << it.second; |
| 685 | appendSdp(sdp, extString.str()); |
| 686 | } |
| 687 |
| 688 | bool addSsrcs = false; |
| 689 | if (stream.isRemoved) { |
| 690 | appendSdp(sdp, "a=inactive"); |
| 691 | } else if (type == SdpType::kSdpTypeJoinAnswer) { |
| 692 | if (stream.isOutgoing) { |
| 693 | appendSdp(sdp, "a=recvonly"); |
| 694 | appendSdp(sdp, "a=bundle-only"); |
| 695 | } else { |
| 696 | appendSdp(sdp, "a=sendonly"); |
| 697 | appendSdp(sdp, "a=bundle-only"); |
| 698 | addSsrcs = true; |
| 699 | } |
| 700 | } else if (type == SdpType::kSdpTypeRemoteOffer) { |
| 701 | if (stream.isOutgoing) { |
| 702 | appendSdp(sdp, "a=recvonly"); |
| 703 | appendSdp(sdp, "a=bundle-only"); |
| 704 | } else { |
| 705 | appendSdp(sdp, "a=sendonly"); |
| 706 | appendSdp(sdp, "a=bundle-only"); |
| 707 | addSsrcs = true; |
| 708 | } |
| 709 | } else if (type == SdpType::kSdpTypeLocalAnswer) { |
| 710 | if (stream.isOutgoing) { |
| 711 | appendSdp(sdp, "a=sendonly"); |
| 712 | appendSdp(sdp, "a=bundle-only"); |
| 713 | addSsrcs = true; |
| 714 | } else { |
| 715 | appendSdp(sdp, "a=recvonly"); |
| 716 | appendSdp(sdp, "a=bundle-only"); |
| 717 | } |
| 718 | } |
| 719 |
| 720 | if (addSsrcs) { |
| 721 | std::vector<uint32_t> ssrcs; |
| 722 | for (auto &group : stream.videoSourceGroups) { |
| 723 | std::ostringstream groupString; |
| 724 | groupString << "a=ssrc-group:"; |
| 725 | groupString << group.semantics; |
| 726 |
| 727 | for (auto ssrc : group.ssrcs) { |
| 728 | groupString << " " << ssrc; |
| 729 |
| 730 | if (std::find(ssrcs.begin(), ssrcs.end(), ssrc) == ssrcs.end()) { |
| 731 | ssrcs.push_back(ssrc); |
| 732 | } |
| 733 | } |
| 734 |
| 735 | appendSdp(sdp, groupString.str()); |
| 736 | } |
| 737 |
| 738 | for (auto ssrc : ssrcs) { |
| 739 | std::ostringstream cnameString; |
| 740 | cnameString << "a=ssrc:"; |
| 741 | cnameString << ssrc; |
| 742 | cnameString << " cname:stream"; |
| 743 | cnameString << stream.streamId; |
| 744 | appendSdp(sdp, cnameString.str()); |
| 745 |
| 746 | std::ostringstream msidString; |
| 747 | msidString << "a=ssrc:"; |
| 748 | msidString << ssrc; |
| 749 | msidString << " msid:stream"; |
| 750 | msidString << stream.streamId; |
| 751 | msidString << " video" << stream.streamId; |
| 752 | appendSdp(sdp, msidString.str()); |
| 753 |
| 754 | std::ostringstream mslabelString; |
| 755 | mslabelString << "a=ssrc:"; |
| 756 | mslabelString << ssrc; |
| 757 | mslabelString << " mslabel:video"; |
| 758 | mslabelString << stream.streamId; |
| 759 | appendSdp(sdp, mslabelString.str()); |
| 760 |
| 761 | std::ostringstream labelString; |
| 762 | labelString << "a=ssrc:"; |
| 763 | labelString << ssrc; |
| 764 | labelString << " label:video"; |
| 765 | labelString << stream.streamId; |
| 766 | appendSdp(sdp, labelString.str()); |
| 767 | } |
| 768 | } |
| 769 | } |
| 770 | } |
| 771 | } |
| 772 |
| 773 | std::ostringstream result; |
| 774 | for (auto &line : sdp) { |
| 775 | result << line << "\n"; |
| 776 | } |
| 777 |
| 778 | return result.str(); |
| 779 | } |
| 780 |
| 781 | static std::string parseJoinResponseIntoSdp(uint32_t sessionId, GroupJoinPayload const &joinPayload, GroupJoinResponsePayload const &payload, SdpType type, std::vector<GroupParticipantDescription> const &allOtherParticipants, absl::optional<std::string> localVideoMid, absl::optional<std::string> dataChannelMid, std::vector<StreamSpec> &bundleStreamsState) { |
| 782 |
| 783 | std::vector<StreamSpec> bundleStreams; |
| 784 |
| 785 | StreamSpec mainStream; |
| 786 | mainStream.mLine = "0"; |
| 787 | mainStream.isMain = true; |
| 788 | mainStream.isOutgoing = true; |
| 789 | mainStream.streamId = 0; |
| 790 | mainStream.ssrc = joinPayload.ssrc; |
| 791 | mainStream.isRemoved = false; |
| 792 | mainStream.isVideo = false; |
| 793 | bundleStreams.push_back(mainStream); |
| 794 |
| 795 | if (dataChannelMid.has_value() && dataChannelMid.value() == "1") { |
| 796 | StreamSpec dataStream; |
| 797 | dataStream.mLine = dataChannelMid.value(); |
| 798 | dataStream.isMain = false; |
| 799 | dataStream.isOutgoing = true; |
| 800 | dataStream.streamId = 0; |
| 801 | dataStream.ssrc = 0; |
| 802 | dataStream.isRemoved = false; |
| 803 | dataStream.isData = true; |
| 804 | dataStream.isVideo = false; |
| 805 | bundleStreams.push_back(dataStream); |
| 806 | } |
| 807 |
| 808 | if (localVideoMid.has_value()) { |
| 809 | if (joinPayload.videoSourceGroups.size() != 0) { |
| 810 | StreamSpec mainVideoStream; |
| 811 | mainVideoStream.mLine = localVideoMid.value(); |
| 812 | mainVideoStream.isMain = false; |
| 813 | mainVideoStream.isOutgoing = true; |
| 814 | mainVideoStream.isVideo = true; |
| 815 | mainVideoStream.streamId = joinPayload.videoSourceGroups[0].ssrcs[0]; |
| 816 | mainVideoStream.ssrc = joinPayload.videoSourceGroups[0].ssrcs[0]; |
| 817 | mainVideoStream.videoSourceGroups = joinPayload.videoSourceGroups; |
| 818 | mainVideoStream.videoPayloadTypes = joinPayload.videoPayloadTypes; |
| 819 | mainVideoStream.videoExtensionMap = joinPayload.videoExtensionMap; |
| 820 |
| 821 | mainVideoStream.isRemoved = joinPayload.videoSourceGroups.size() == 0; |
| 822 | bundleStreams.push_back(mainVideoStream); |
| 823 | } |
| 824 | } |
| 825 |
| 826 | if (dataChannelMid.has_value() && dataChannelMid.value() == "2") { |
| 827 | StreamSpec dataStream; |
| 828 | dataStream.mLine = dataChannelMid.value(); |
| 829 | dataStream.isMain = false; |
| 830 | dataStream.isOutgoing = true; |
| 831 | dataStream.streamId = 0; |
| 832 | dataStream.ssrc = 0; |
| 833 | dataStream.isRemoved = false; |
| 834 | dataStream.isData = true; |
| 835 | dataStream.isVideo = false; |
| 836 | bundleStreams.push_back(dataStream); |
| 837 | } |
| 838 |
| 839 | for (auto &participant : allOtherParticipants) { |
| 840 | StreamSpec audioStream; |
| 841 | audioStream.isMain = false; |
| 842 |
| 843 | std::ostringstream audioMLine; |
| 844 | audioMLine << "audio" << participant.audioSsrc; |
| 845 | audioStream.mLine = audioMLine.str(); |
| 846 | audioStream.ssrc = participant.audioSsrc; |
| 847 | audioStream.isRemoved = participant.isRemoved; |
| 848 | audioStream.streamId = participant.audioSsrc; |
| 849 | bundleStreams.push_back(audioStream); |
| 850 |
| 851 | if (participant.videoPayloadTypes.size() != 0 && participant.videoSourceGroups.size() != 0 ) { |
| 852 | StreamSpec videoStream; |
| 853 | videoStream.isMain = false; |
| 854 |
| 855 | std::ostringstream videoMLine; |
| 856 | videoMLine << "video" << participant.audioSsrc; |
| 857 | videoStream.mLine = videoMLine.str(); |
| 858 | videoStream.isVideo = true; |
| 859 | videoStream.ssrc = participant.videoSourceGroups[0].ssrcs[0]; |
| 860 | videoStream.isRemoved = participant.isRemoved; |
| 861 | videoStream.streamId = participant.audioSsrc; |
| 862 | videoStream.videoSourceGroups = participant.videoSourceGroups; |
| 863 | videoStream.videoExtensionMap = participant.videoExtensionMap; |
| 864 | videoStream.videoPayloadTypes = participant.videoPayloadTypes; |
| 865 |
| 866 | bundleStreams.push_back(videoStream); |
| 867 | } |
| 868 | } |
| 869 |
| 870 | std::vector<StreamSpec> orderedStreams; |
| 871 | for (auto const &oldStream : bundleStreamsState) { |
| 872 | bool found = false; |
| 873 | for (int i = 0; i < (int)bundleStreams.size(); i++) { |
| 874 | if (bundleStreams[i].mLine == oldStream.mLine) { |
| 875 | found = true; |
| 876 | orderedStreams.push_back(bundleStreams[i]); |
| 877 | bundleStreams.erase(bundleStreams.begin() + i); |
| 878 | break; |
| 879 | } |
| 880 | } |
| 881 | if (!found) { |
| 882 | StreamSpec copyStream = oldStream; |
| 883 | copyStream.isRemoved = true; |
| 884 | orderedStreams.push_back(copyStream); |
| 885 | } |
| 886 | } |
| 887 | for (const auto &it : bundleStreams) { |
| 888 | orderedStreams.push_back(it); |
| 889 | } |
| 890 |
| 891 | bundleStreamsState = orderedStreams; |
| 892 |
| 893 | return createSdp(sessionId, payload, type, orderedStreams); |
| 894 | } |
| 895 |
| 896 | VideoCaptureInterfaceObject *GetVideoCaptureAssumingSameThread(VideoCaptureInterface *videoCapture) { |
| 897 | return videoCapture |
| 898 | ? static_cast<VideoCaptureInterfaceImpl*>(videoCapture)->object()->getSyncAssumingSameThread() |
| 899 | : nullptr; |
| 900 | } |
| 901 |
| 902 | class ErrorParsingLogSink final : public rtc::LogSink { |
| 903 | public: |
| 904 | ErrorParsingLogSink(std::function<void(uint32_t)> onMissingSsrc) : |
| 905 | _onMissingSsrc(onMissingSsrc) { |
| 906 |
| 907 | } |
| 908 |
| 909 | void OnLogMessage(const std::string &msg, rtc::LoggingSeverity severity, const char *tag) override { |
| 910 | handleMessage(msg); |
| 911 | } |
| 912 |
| 913 | void OnLogMessage(const std::string &message, rtc::LoggingSeverity severity) override { |
| 914 | handleMessage(message); |
| 915 | } |
| 916 |
| 917 | void OnLogMessage(const std::string &message) override { |
| 918 | handleMessage(message); |
| 919 | } |
| 920 |
| 921 | private: |
| 922 | void handleMessage(const std::string &message) { |
| 923 | const std::string pattern = "Failed to demux RTP packet:"; |
| 924 | const std::string ssrcPattern = "SSRC="; |
| 925 | auto index = message.find(pattern); |
| 926 | if (index != std::string::npos) { |
| 927 | index = message.find(ssrcPattern); |
| 928 | if (index != std::string::npos) { |
| 929 | std::string string = message; |
| 930 | string.erase(0, index + ssrcPattern.size()); |
| 931 |
| 932 | std::istringstream stream(string); |
| 933 | uint32_t ssrc = 0; |
| 934 | stream >> ssrc; |
| 935 | if (ssrc != 0) { |
| 936 | _onMissingSsrc(ssrc); |
| 937 | } |
| 938 | } |
| 939 | return; |
| 940 | } |
| 941 |
| 942 | const std::string pattern2 = "receive_rtp_config_ lookup failed for ssrc "; |
| 943 | index = message.find(pattern2); |
| 944 | if (index != std::string::npos) { |
| 945 | std::string string = message; |
| 946 | string.erase(0, index + pattern2.size()); |
| 947 |
| 948 | std::istringstream stream(string); |
| 949 | uint32_t ssrc = 0; |
| 950 | stream >> ssrc; |
| 951 | if (ssrc != 0) { |
| 952 | _onMissingSsrc(ssrc); |
| 953 | } |
| 954 |
| 955 | return; |
| 956 | } |
| 957 | } |
| 958 |
| 959 | private: |
| 960 | std::function<void(uint32_t)> _onMissingSsrc; |
| 961 |
| 962 | }; |
| 963 |
| 964 | class PeerConnectionObserverImpl : public webrtc::PeerConnectionObserver { |
| 965 | private: |
| 966 | std::function<void(std::string, int, std::string)> _discoveredIceCandidate; |
| 967 | std::function<void(bool)> _connectionStateChanged; |
| 968 | std::function<void(rtc::scoped_refptr<webrtc::RtpTransceiverInterface>)> _onTrackAdded; |
| 969 | std::function<void(rtc::scoped_refptr<webrtc::RtpReceiverInterface>)> _onTrackRemoved; |
| 970 | std::function<void(uint32_t)> _onMissingSsrc; |
| 971 |
| 972 | public: |
| 973 | PeerConnectionObserverImpl( |
| 974 | std::function<void(std::string, int, std::string)> discoveredIceCandidate, |
| 975 | std::function<void(bool)> connectionStateChanged, |
| 976 | std::function<void(rtc::scoped_refptr<webrtc::RtpTransceiverInterface>)> onTrackAdded, |
| 977 | std::function<void(rtc::scoped_refptr<webrtc::RtpReceiverInterface>)> onTrackRemoved, |
| 978 | std::function<void(uint32_t)> onMissingSsrc |
| 979 | ) : |
| 980 | _discoveredIceCandidate(discoveredIceCandidate), |
| 981 | _connectionStateChanged(connectionStateChanged), |
| 982 | _onTrackAdded(onTrackAdded), |
| 983 | _onTrackRemoved(onTrackRemoved), |
| 984 | _onMissingSsrc(onMissingSsrc) { |
| 985 | } |
| 986 |
| 987 | virtual void OnSignalingChange(webrtc::PeerConnectionInterface::SignalingState new_state) override { |
| 988 | } |
| 989 |
| 990 | virtual void OnAddStream(rtc::scoped_refptr<webrtc::MediaStreamInterface> stream) override { |
| 991 | } |
| 992 |
| 993 | virtual void OnRemoveStream(rtc::scoped_refptr<webrtc::MediaStreamInterface> stream) override { |
| 994 | } |
| 995 |
| 996 | virtual void OnDataChannel(rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel) override { |
| 997 |
| 998 | } |
| 999 |
| 1000 | virtual void OnRenegotiationNeeded() override { |
| 1001 | } |
| 1002 |
| 1003 | virtual void OnIceConnectionChange(webrtc::PeerConnectionInterface::IceConnectionState new_state) override { |
| 1004 | bool isConnected = false; |
| 1005 | switch (new_state) { |
| 1006 | case webrtc::PeerConnectionInterface::IceConnectionState::kIceConnectionConnected: |
| 1007 | case webrtc::PeerConnectionInterface::IceConnectionState::kIceConnectionCompleted: |
| 1008 | isConnected = true; |
| 1009 | break; |
| 1010 | default: |
| 1011 | break; |
| 1012 | } |
| 1013 | _connectionStateChanged(isConnected); |
| 1014 | } |
| 1015 |
| 1016 | virtual void OnStandardizedIceConnectionChange(webrtc::PeerConnectionInterface::IceConnectionState new_state) override { |
| 1017 | } |
| 1018 |
| 1019 | virtual void OnConnectionChange(webrtc::PeerConnectionInterface::PeerConnectionState new_state) override { |
| 1020 | } |
| 1021 |
| 1022 | virtual void OnIceGatheringChange(webrtc::PeerConnectionInterface::IceGatheringState new_state) override { |
| 1023 | } |
| 1024 |
| 1025 | virtual void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override { |
| 1026 | std::string sdp; |
| 1027 | candidate->ToString(&sdp); |
| 1028 | _discoveredIceCandidate(sdp, candidate->sdp_mline_index(), candidate->sdp_mid()); |
| 1029 | } |
| 1030 |
| 1031 | virtual void OnIceCandidateError(const std::string& host_candidate, const std::string& url, int error_code, const std::string& error_text) override { |
| 1032 | } |
| 1033 |
| 1034 | virtual void OnIceCandidateError(const std::string& address, |
| 1035 | int port, |
| 1036 | const std::string& url, |
| 1037 | int error_code, |
| 1038 | const std::string& error_text) override { |
| 1039 | } |
| 1040 |
| 1041 | virtual void OnIceCandidatesRemoved(const std::vector<cricket::Candidate>& candidates) override { |
| 1042 | } |
| 1043 |
| 1044 | virtual void OnIceConnectionReceivingChange(bool receiving) override { |
| 1045 | } |
| 1046 |
| 1047 | virtual void OnIceSelectedCandidatePairChanged(const cricket::CandidatePairChangeEvent& event) override { |
| 1048 | } |
| 1049 |
| 1050 | virtual void OnAddTrack(rtc::scoped_refptr<webrtc::RtpReceiverInterface> receiver, const std::vector<rtc::scoped_refptr<webrtc::MediaStreamInterface>>& streams) override { |
| 1051 | } |
| 1052 |
| 1053 | virtual void OnTrack(rtc::scoped_refptr<webrtc::RtpTransceiverInterface> transceiver) override { |
| 1054 | _onTrackAdded(transceiver); |
| 1055 | } |
| 1056 |
| 1057 | virtual void OnRemoveTrack(rtc::scoped_refptr<webrtc::RtpReceiverInterface> receiver) override { |
| 1058 | _onTrackRemoved(receiver); |
| 1059 | } |
| 1060 |
| 1061 | virtual void OnInterestingUsage(int usage_pattern) override { |
| 1062 | } |
| 1063 | }; |
| 1064 |
| 1065 | class DataChannelObserverImpl : public webrtc::DataChannelObserver { |
| 1066 | public: |
| 1067 | DataChannelObserverImpl(std::function<void()> stateChanged) : |
| 1068 | _stateChanged(stateChanged) { |
| 1069 | } |
| 1070 |
| 1071 | virtual void OnStateChange() override { |
| 1072 | RTC_LOG(LS_INFO) << "DataChannel state changed"; |
| 1073 | _stateChanged(); |
| 1074 | } |
| 1075 |
| 1076 | virtual void OnMessage(const webrtc::DataBuffer &buffer) override { |
| 1077 | RTC_LOG(LS_INFO) << "DataChannel message received: " << std::string((const char *)buffer.data.data(), buffer.data.size()); |
| 1078 | } |
| 1079 |
| 1080 | virtual void OnBufferedAmountChange(uint64_t sent_data_size) override { |
| 1081 | } |
| 1082 |
| 1083 | private: |
| 1084 | std::function<void()> _stateChanged; |
| 1085 | }; |
| 1086 |
| 1087 | class RTCStatsCollectorCallbackImpl : public webrtc::RTCStatsCollectorCallback { |
| 1088 | public: |
| 1089 | RTCStatsCollectorCallbackImpl(std::function<void(const rtc::scoped_refptr<const webrtc::RTCStatsReport> &)> completion) : |
| 1090 | _completion(completion) { |
| 1091 | } |
| 1092 |
| 1093 | virtual void OnStatsDelivered(const rtc::scoped_refptr<const webrtc::RTCStatsReport> &report) override { |
| 1094 | _completion(report); |
| 1095 | } |
| 1096 |
| 1097 | private: |
| 1098 | std::function<void(const rtc::scoped_refptr<const webrtc::RTCStatsReport> &)> _completion; |
| 1099 | }; |
| 1100 |
| 1101 | static const int kVadResultHistoryLength = 8; |
| 1102 |
| 1103 | class CombinedVad { |
| 1104 | private: |
| 1105 | webrtc::VadLevelAnalyzer _vadWithLevel; |
| 1106 | float _vadResultHistory[kVadResultHistoryLength]; |
| 1107 |
| 1108 | public: |
| 1109 | CombinedVad() { |
| 1110 | for (int i = 0; i < kVadResultHistoryLength; i++) { |
| 1111 | _vadResultHistory[i] = 0.0f; |
| 1112 | } |
| 1113 | } |
| 1114 |
| 1115 | ~CombinedVad() { |
| 1116 | } |
| 1117 |
| 1118 | bool update(webrtc::AudioBuffer *buffer) { |
| 1119 | webrtc::AudioFrameView<float> frameView(buffer->channels(), buffer->num_channels(), buffer->num_frames()); |
| 1120 | auto result = _vadWithLevel.AnalyzeFrame(frameView); |
| 1121 | for (int i = 1; i < kVadResultHistoryLength; i++) { |
| 1122 | _vadResultHistory[i - 1] = _vadResultHistory[i]; |
| 1123 | } |
| 1124 | _vadResultHistory[kVadResultHistoryLength - 1] = result.speech_probability; |
| 1125 |
| 1126 | float movingAverage = 0.0f; |
| 1127 | for (int i = 0; i < kVadResultHistoryLength; i++) { |
| 1128 | movingAverage += _vadResultHistory[i]; |
| 1129 | } |
| 1130 | movingAverage /= (float)kVadResultHistoryLength; |
| 1131 |
| 1132 | bool vadResult = false; |
| 1133 | if (movingAverage > 0.8f) { |
| 1134 | vadResult = true; |
| 1135 | } |
| 1136 |
| 1137 | return vadResult; |
| 1138 | } |
| 1139 | }; |
| 1140 |
| 1141 | class AudioTrackSinkInterfaceImpl: public webrtc::AudioTrackSinkInterface { |
| 1142 | private: |
| 1143 | std::function<void(float, bool)> _update; |
| 1144 |
| 1145 | int _peakCount = 0; |
| 1146 | uint16_t _peak = 0; |
| 1147 |
| 1148 | CombinedVad _vad; |
| 1149 |
| 1150 | public: |
| 1151 | AudioTrackSinkInterfaceImpl(std::function<void(float, bool)> update) : |
| 1152 | _update(update) { |
| 1153 | } |
| 1154 |
| 1155 | virtual ~AudioTrackSinkInterfaceImpl() { |
| 1156 | } |
| 1157 |
| 1158 | 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 { |
| 1159 | if (bits_per_sample == 16 && number_of_channels == 1) { |
| 1160 | int16_t *samples = (int16_t *)audio_data; |
| 1161 | int numberOfSamplesInFrame = (int)number_of_frames; |
| 1162 |
| 1163 | webrtc::AudioBuffer buffer(sample_rate, 1, 48000, 1, 48000, 1); |
| 1164 | webrtc::StreamConfig config(sample_rate, 1); |
| 1165 | buffer.CopyFrom(samples, config); |
| 1166 |
| 1167 | bool vadResult = _vad.update(&buffer); |
| 1168 |
| 1169 | for (int i = 0; i < numberOfSamplesInFrame; i++) { |
| 1170 | int16_t sample = samples[i]; |
| 1171 | if (sample < 0) { |
| 1172 | sample = -sample; |
| 1173 | } |
| 1174 | if (_peak < sample) { |
| 1175 | _peak = sample; |
| 1176 | } |
| 1177 | _peakCount += 1; |
| 1178 | } |
| 1179 |
| 1180 | if (_peakCount >= 1200) { |
| 1181 | float level = ((float)(_peak)) / 4000.0f; |
| 1182 | _peak = 0; |
| 1183 | _peakCount = 0; |
| 1184 | _update(level, vadResult); |
| 1185 | } |
| 1186 | } |
| 1187 | } |
| 1188 | }; |
| 1189 |
| 1190 | class CreateSessionDescriptionObserverImpl : public webrtc::CreateSessionDescriptionObserver { |
| 1191 | private: |
| 1192 | std::function<void(std::string, std::string)> _completion; |
| 1193 |
| 1194 | public: |
| 1195 | CreateSessionDescriptionObserverImpl(std::function<void(std::string, std::string)> completion) : |
| 1196 | _completion(completion) { |
| 1197 | } |
| 1198 |
| 1199 | virtual void OnSuccess(webrtc::SessionDescriptionInterface* desc) override { |
| 1200 | if (desc) { |
| 1201 | std::string sdp; |
| 1202 | desc->ToString(&sdp); |
| 1203 |
| 1204 | _completion(sdp, desc->type()); |
| 1205 | } |
| 1206 | } |
| 1207 |
| 1208 | virtual void OnFailure(webrtc::RTCError error) override { |
| 1209 | } |
| 1210 | }; |
| 1211 |
| 1212 | class SetSessionDescriptionObserverImpl : public webrtc::SetSessionDescriptionObserver { |
| 1213 | private: |
| 1214 | std::function<void()> _completion; |
| 1215 | std::function<void(webrtc::RTCError)> _error; |
| 1216 |
| 1217 | public: |
| 1218 | SetSessionDescriptionObserverImpl(std::function<void()> completion, std::function<void(webrtc::RTCError)> error) : |
| 1219 | _completion(completion), _error(error) { |
| 1220 | } |
| 1221 |
| 1222 | virtual void OnSuccess() override { |
| 1223 | _completion(); |
| 1224 | } |
| 1225 |
| 1226 | virtual void OnFailure(webrtc::RTCError error) override { |
| 1227 | _error(error); |
| 1228 | } |
| 1229 | }; |
| 1230 |
| 1231 | class AudioCaptureAnalyzer : public webrtc::CustomAudioAnalyzer { |
| 1232 | private: |
| 1233 | void Initialize(int sample_rate_hz, int num_channels) override { |
| 1234 |
| 1235 | } |
| 1236 | // Analyzes the given capture or render signal. |
| 1237 | void Analyze(const webrtc::AudioBuffer* audio) override { |
| 1238 | _analyze(audio); |
| 1239 | } |
| 1240 | // Returns a string representation of the module state. |
| 1241 | std::string ToString() const override { |
| 1242 | return "analyzing"; |
| 1243 | } |
| 1244 |
| 1245 | std::function<void(const webrtc::AudioBuffer*)> _analyze; |
| 1246 |
| 1247 | public: |
| 1248 | AudioCaptureAnalyzer(std::function<void(const webrtc::AudioBuffer*)> analyze) : |
| 1249 | _analyze(analyze) { |
| 1250 | } |
| 1251 |
| 1252 | virtual ~AudioCaptureAnalyzer() = default; |
| 1253 | }; |
| 1254 |
| 1255 | class WrappedAudioDeviceModule : public webrtc::AudioDeviceModule { |
| 1256 | private: |
| 1257 | rtc::scoped_refptr<webrtc::AudioDeviceModule> _impl; |
| 1258 |
| 1259 | public: |
| 1260 | WrappedAudioDeviceModule(rtc::scoped_refptr<webrtc::AudioDeviceModule> impl) : |
| 1261 | _impl(impl) { |
| 1262 | } |
| 1263 |
| 1264 | virtual ~WrappedAudioDeviceModule() { |
| 1265 | } |
| 1266 |
| 1267 | virtual int32_t ActiveAudioLayer(AudioLayer *audioLayer) const override { |
| 1268 | return _impl->ActiveAudioLayer(audioLayer); |
| 1269 | } |
| 1270 |
| 1271 | virtual int32_t RegisterAudioCallback(webrtc::AudioTransport *audioCallback) override { |
| 1272 | return _impl->RegisterAudioCallback(audioCallback); |
| 1273 | } |
| 1274 |
| 1275 | virtual int32_t Init() override { |
| 1276 | return _impl->Init(); |
| 1277 | } |
| 1278 |
| 1279 | virtual int32_t Terminate() override { |
| 1280 | return _impl->Terminate(); |
| 1281 | } |
| 1282 |
| 1283 | virtual bool Initialized() const override { |
| 1284 | return _impl->Initialized(); |
| 1285 | } |
| 1286 |
| 1287 | virtual int16_t PlayoutDevices() override { |
| 1288 | return _impl->PlayoutDevices(); |
| 1289 | } |
| 1290 |
| 1291 | virtual int16_t RecordingDevices() override { |
| 1292 | return _impl->RecordingDevices(); |
| 1293 | } |
| 1294 |
| 1295 | virtual int32_t PlayoutDeviceName(uint16_t index, char name[webrtc::kAdmMaxDeviceNameSize], char guid[webrtc::kAdmMaxGuidSize]) override { |
| 1296 | return _impl->PlayoutDeviceName(index, name, guid); |
| 1297 | } |
| 1298 |
| 1299 | virtual int32_t RecordingDeviceName(uint16_t index, char name[webrtc::kAdmMaxDeviceNameSize], char guid[webrtc::kAdmMaxGuidSize]) override { |
| 1300 | return _impl->RecordingDeviceName(index, name, guid); |
| 1301 | } |
| 1302 |
| 1303 | virtual int32_t SetPlayoutDevice(uint16_t index) override { |
| 1304 | return _impl->SetPlayoutDevice(index); |
| 1305 | } |
| 1306 |
| 1307 | virtual int32_t SetPlayoutDevice(WindowsDeviceType device) override { |
| 1308 | return _impl->SetPlayoutDevice(device); |
| 1309 | } |
| 1310 |
| 1311 | virtual int32_t SetRecordingDevice(uint16_t index) override { |
| 1312 | return _impl->SetRecordingDevice(index); |
| 1313 | } |
| 1314 |
| 1315 | virtual int32_t SetRecordingDevice(WindowsDeviceType device) override { |
| 1316 | return _impl->SetRecordingDevice(device); |
| 1317 | } |
| 1318 |
| 1319 | virtual int32_t PlayoutIsAvailable(bool *available) override { |
| 1320 | return _impl->PlayoutIsAvailable(available); |
| 1321 | } |
| 1322 |
| 1323 | virtual int32_t InitPlayout() override { |
| 1324 | return _impl->InitPlayout(); |
| 1325 | } |
| 1326 |
| 1327 | virtual bool PlayoutIsInitialized() const override { |
| 1328 | return _impl->PlayoutIsInitialized(); |
| 1329 | } |
| 1330 |
| 1331 | virtual int32_t RecordingIsAvailable(bool *available) override { |
| 1332 | return _impl->RecordingIsAvailable(available); |
| 1333 | } |
| 1334 |
| 1335 | virtual int32_t InitRecording() override { |
| 1336 | return _impl->InitRecording(); |
| 1337 | } |
| 1338 |
| 1339 | virtual bool RecordingIsInitialized() const override { |
| 1340 | return _impl->RecordingIsInitialized(); |
| 1341 | } |
| 1342 |
| 1343 | virtual int32_t StartPlayout() override { |
| 1344 | return _impl->StartPlayout(); |
| 1345 | } |
| 1346 |
| 1347 | virtual int32_t StopPlayout() override { |
| 1348 | return _impl->StopPlayout(); |
| 1349 | } |
| 1350 |
| 1351 | virtual bool Playing() const override { |
| 1352 | return _impl->Playing(); |
| 1353 | } |
| 1354 |
| 1355 | virtual int32_t StartRecording() override { |
| 1356 | return _impl->StartRecording(); |
| 1357 | } |
| 1358 |
| 1359 | virtual int32_t StopRecording() override { |
| 1360 | return _impl->StopRecording(); |
| 1361 | } |
| 1362 |
| 1363 | virtual bool Recording() const override { |
| 1364 | return _impl->Recording(); |
| 1365 | } |
| 1366 |
| 1367 | virtual int32_t InitSpeaker() override { |
| 1368 | return _impl->InitSpeaker(); |
| 1369 | } |
| 1370 |
| 1371 | virtual bool SpeakerIsInitialized() const override { |
| 1372 | return _impl->SpeakerIsInitialized(); |
| 1373 | } |
| 1374 |
| 1375 | virtual int32_t InitMicrophone() override { |
| 1376 | return _impl->InitMicrophone(); |
| 1377 | } |
| 1378 |
| 1379 | virtual bool MicrophoneIsInitialized() const override { |
| 1380 | return _impl->MicrophoneIsInitialized(); |
| 1381 | } |
| 1382 |
| 1383 | virtual int32_t SpeakerVolumeIsAvailable(bool *available) override { |
| 1384 | return _impl->SpeakerVolumeIsAvailable(available); |
| 1385 | } |
| 1386 |
| 1387 | virtual int32_t SetSpeakerVolume(uint32_t volume) override { |
| 1388 | return _impl->SetSpeakerVolume(volume); |
| 1389 | } |
| 1390 |
| 1391 | virtual int32_t SpeakerVolume(uint32_t* volume) const override { |
| 1392 | return _impl->SpeakerVolume(volume); |
| 1393 | } |
| 1394 |
| 1395 | virtual int32_t MaxSpeakerVolume(uint32_t *maxVolume) const override { |
| 1396 | return _impl->MaxSpeakerVolume(maxVolume); |
| 1397 | } |
| 1398 |
| 1399 | virtual int32_t MinSpeakerVolume(uint32_t *minVolume) const override { |
| 1400 | return _impl->MinSpeakerVolume(minVolume); |
| 1401 | } |
| 1402 |
| 1403 | virtual int32_t MicrophoneVolumeIsAvailable(bool *available) override { |
| 1404 | return _impl->MicrophoneVolumeIsAvailable(available); |
| 1405 | } |
| 1406 |
| 1407 | virtual int32_t SetMicrophoneVolume(uint32_t volume) override { |
| 1408 | return _impl->SetMicrophoneVolume(volume); |
| 1409 | } |
| 1410 |
| 1411 | virtual int32_t MicrophoneVolume(uint32_t *volume) const override { |
| 1412 | return _impl->MicrophoneVolume(volume); |
| 1413 | } |
| 1414 |
| 1415 | virtual int32_t MaxMicrophoneVolume(uint32_t *maxVolume) const override { |
| 1416 | return _impl->MaxMicrophoneVolume(maxVolume); |
| 1417 | } |
| 1418 |
| 1419 | virtual int32_t MinMicrophoneVolume(uint32_t *minVolume) const override { |
| 1420 | return _impl->MinMicrophoneVolume(minVolume); |
| 1421 | } |
| 1422 |
| 1423 | virtual int32_t SpeakerMuteIsAvailable(bool *available) override { |
| 1424 | return _impl->SpeakerMuteIsAvailable(available); |
| 1425 | } |
| 1426 |
| 1427 | virtual int32_t SetSpeakerMute(bool enable) override { |
| 1428 | return _impl->SetSpeakerMute(enable); |
| 1429 | } |
| 1430 |
| 1431 | virtual int32_t SpeakerMute(bool *enabled) const override { |
| 1432 | return _impl->SpeakerMute(enabled); |
| 1433 | } |
| 1434 |
| 1435 | virtual int32_t MicrophoneMuteIsAvailable(bool *available) override { |
| 1436 | return _impl->MicrophoneMuteIsAvailable(available); |
| 1437 | } |
| 1438 |
| 1439 | virtual int32_t SetMicrophoneMute(bool enable) override { |
| 1440 | return _impl->SetMicrophoneMute(enable); |
| 1441 | } |
| 1442 |
| 1443 | virtual int32_t MicrophoneMute(bool *enabled) const override { |
| 1444 | return _impl->MicrophoneMute(enabled); |
| 1445 | } |
| 1446 |
| 1447 | virtual int32_t StereoPlayoutIsAvailable(bool *available) const override { |
| 1448 | return _impl->StereoPlayoutIsAvailable(available); |
| 1449 | } |
| 1450 |
| 1451 | virtual int32_t SetStereoPlayout(bool enable) override { |
| 1452 | return _impl->SetStereoPlayout(enable); |
| 1453 | } |
| 1454 |
| 1455 | virtual int32_t StereoPlayout(bool *enabled) const override { |
| 1456 | return _impl->StereoPlayout(enabled); |
| 1457 | } |
| 1458 |
| 1459 | virtual int32_t StereoRecordingIsAvailable(bool *available) const override { |
| 1460 | return _impl->StereoRecordingIsAvailable(available); |
| 1461 | } |
| 1462 |
| 1463 | virtual int32_t SetStereoRecording(bool enable) override { |
| 1464 | return _impl->SetStereoRecording(enable); |
| 1465 | } |
| 1466 |
| 1467 | virtual int32_t StereoRecording(bool *enabled) const override { |
| 1468 | return _impl->StereoRecording(enabled); |
| 1469 | } |
| 1470 |
| 1471 | virtual int32_t PlayoutDelay(uint16_t* delayMS) const override { |
| 1472 | return _impl->PlayoutDelay(delayMS); |
| 1473 | } |
| 1474 |
| 1475 | virtual bool BuiltInAECIsAvailable() const override { |
| 1476 | return _impl->BuiltInAECIsAvailable(); |
| 1477 | } |
| 1478 |
| 1479 | virtual bool BuiltInAGCIsAvailable() const override { |
| 1480 | return _impl->BuiltInAGCIsAvailable(); |
| 1481 | } |
| 1482 |
| 1483 | virtual bool BuiltInNSIsAvailable() const override { |
| 1484 | return _impl->BuiltInNSIsAvailable(); |
| 1485 | } |
| 1486 |
| 1487 | virtual int32_t EnableBuiltInAEC(bool enable) override { |
| 1488 | return _impl->EnableBuiltInAEC(enable); |
| 1489 | } |
| 1490 |
| 1491 | virtual int32_t EnableBuiltInAGC(bool enable) override { |
| 1492 | return _impl->EnableBuiltInAGC(enable); |
| 1493 | } |
| 1494 |
| 1495 | virtual int32_t EnableBuiltInNS(bool enable) override { |
| 1496 | return _impl->EnableBuiltInNS(enable); |
| 1497 | } |
| 1498 |
| 1499 | virtual int32_t GetPlayoutUnderrunCount() const override { |
| 1500 | return _impl->GetPlayoutUnderrunCount(); |
| 1501 | } |
| 1502 |
| 1503 | #if defined(WEBRTC_IOS) |
| 1504 | virtual int GetPlayoutAudioParameters(webrtc::AudioParameters *params) const override { |
| 1505 | return _impl->GetPlayoutAudioParameters(params); |
| 1506 | } |
| 1507 | virtual int GetRecordAudioParameters(webrtc::AudioParameters *params) const override { |
| 1508 | return _impl->GetRecordAudioParameters(params); |
| 1509 | } |
| 1510 | #endif // WEBRTC_IOS |
| 1511 | }; |
| 1512 |
| 1513 | template <typename Out> |
| 1514 | void split(const std::string &s, char delim, Out result) { |
| 1515 | std::istringstream iss(s); |
| 1516 | std::string item; |
| 1517 | while (std::getline(iss, item, delim)) { |
| 1518 | *result++ = item; |
| 1519 | } |
| 1520 | } |
| 1521 |
| 1522 | std::string adjustLocalDescription(const std::string &sdp) { |
| 1523 | return sdp; |
| 1524 | } |
| 1525 |
| 1526 | class CustomVideoSinkInterfaceProxyImpl : public rtc::VideoSinkInterface<webrtc::VideoFrame> { |
| 1527 | public: |
| 1528 | CustomVideoSinkInterfaceProxyImpl() { |
| 1529 | } |
| 1530 |
| 1531 | virtual ~CustomVideoSinkInterfaceProxyImpl() { |
| 1532 | } |
| 1533 |
| 1534 | virtual void OnFrame(const webrtc::VideoFrame& frame) override { |
| 1535 | //_lastFrame = frame; |
| 1536 | for (int i = (int)(_sinks.size()) - 1; i >= 0; i--) { |
| 1537 | auto strong = _sinks[i].lock(); |
| 1538 | if (!strong) { |
| 1539 | _sinks.erase(_sinks.begin() + i); |
| 1540 | } else { |
| 1541 | strong->OnFrame(frame); |
| 1542 | } |
| 1543 | } |
| 1544 | } |
| 1545 |
| 1546 | virtual void OnDiscardedFrame() override { |
| 1547 | for (int i = (int)(_sinks.size()) - 1; i >= 0; i--) { |
| 1548 | auto strong = _sinks[i].lock(); |
| 1549 | if (!strong) { |
| 1550 | _sinks.erase(_sinks.begin() + i); |
| 1551 | } else { |
| 1552 | strong->OnDiscardedFrame(); |
| 1553 | } |
| 1554 | } |
| 1555 | } |
| 1556 |
| 1557 | void addSink(std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> impl) { |
| 1558 | _sinks.push_back(impl); |
| 1559 | if (_lastFrame) { |
| 1560 | auto strong = impl.lock(); |
| 1561 | if (strong) { |
| 1562 | strong->OnFrame(_lastFrame.value()); |
| 1563 | } |
| 1564 | } |
| 1565 | } |
| 1566 |
| 1567 | private: |
| 1568 | std::vector<std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>>> _sinks; |
| 1569 | absl::optional<webrtc::VideoFrame> _lastFrame; |
| 1570 | }; |
| 1571 |
| 1572 | } // namespace |
| 1573 |
| 1574 |
| 1575 |
| 1576 | class GroupInstanceManager : public std::enable_shared_from_this<GroupInstanceManager> { |
| 1577 | public: |
| 1578 | GroupInstanceManager(GroupInstanceDescriptor &&descriptor) : |
| 1579 | _networkStateUpdated(descriptor.networkStateUpdated), |
| 1580 | _audioLevelsUpdated(descriptor.audioLevelsUpdated), |
| 1581 | _incomingVideoSourcesUpdated(descriptor.incomingVideoSourcesUpdated), |
| 1582 | _participantDescriptionsRequired(descriptor.participantDescriptionsRequired), |
| 1583 | _initialInputDeviceId(descriptor.initialInputDeviceId), |
| 1584 | _initialOutputDeviceId(descriptor.initialOutputDeviceId), |
| 1585 | _createAudioDeviceModule(descriptor.createAudioDeviceModule), |
| 1586 | _videoCapture(descriptor.videoCapture), |
| 1587 | _platformContext(descriptor.platformContext) { |
| 1588 | auto generator = std::mt19937(std::random_device()()); |
| 1589 | auto distribution = std::uniform_int_distribution<uint32_t>(); |
| 1590 | do { |
| 1591 | _mainStreamAudioSsrc = distribution(generator); |
| 1592 | } while (!_mainStreamAudioSsrc); |
| 1593 | } |
| 1594 |
| 1595 | ~GroupInstanceManager() { |
| 1596 | assert(StaticThreads::getMediaThread()->IsCurrent()); |
| 1597 |
| 1598 | destroyAudioDeviceModule(); |
| 1599 | if (_peerConnection) { |
| 1600 | _peerConnection->Close(); |
| 1601 | } |
| 1602 |
| 1603 | if (_errorParsingLogSink) { |
| 1604 | rtc::LogMessage::RemoveLogToStream(_errorParsingLogSink.get()); |
| 1605 | } |
| 1606 | } |
| 1607 |
| 1608 | void generateAndInsertFakeIncomingSsrc() { |
| 1609 | // At least on Windows recording can't be started without playout. |
| 1610 | // We keep a fake incoming stream, so that playout is always started. |
| 1611 | /*auto generator = std::mt19937(std::random_device()()); |
| 1612 | auto distribution = std::uniform_int_distribution<uint32_t>(); |
| 1613 | while (true) { |
| 1614 | _fakeIncomingSsrc = distribution(generator); |
| 1615 | if (_fakeIncomingSsrc != 0 |
| 1616 | && _fakeIncomingSsrc != _mainStreamAudioSsrc |
| 1617 | && std::find(_allOtherSsrcs.begin(), _allOtherSsrcs.end(), _fakeIncomingSsrc) == _allOtherSsrcs.end()) { |
| 1618 | break; |
| 1619 | } |
| 1620 | } |
| 1621 | _activeOtherSsrcs.emplace(_fakeIncomingSsrc); |
| 1622 | _allOtherSsrcs.emplace_back(_fakeIncomingSsrc);*/ |
| 1623 | } |
| 1624 |
| 1625 | bool createAudioDeviceModule( |
| 1626 | const webrtc::PeerConnectionFactoryDependencies &dependencies) { |
| 1627 | _adm_thread = dependencies.worker_thread; |
| 1628 | if (!_adm_thread) { |
| 1629 | return false; |
| 1630 | } |
| 1631 | _adm_thread->Invoke<void>(RTC_FROM_HERE, [&] { |
| 1632 | const auto create = [&](webrtc::AudioDeviceModule::AudioLayer layer) { |
| 1633 | return webrtc::AudioDeviceModule::Create( |
| 1634 | layer, |
| 1635 | dependencies.task_queue_factory.get()); |
| 1636 | }; |
| 1637 | const auto finalize = [&](const rtc::scoped_refptr<webrtc::AudioDeviceModule> &result) { |
| 1638 | _adm_use_withAudioDeviceModule = new rtc::RefCountedObject<WrappedAudioDeviceModule>(result); |
| 1639 | }; |
| 1640 | const auto check = [&](const rtc::scoped_refptr<webrtc::AudioDeviceModule> &result) { |
| 1641 | if (!result || result->Init() != 0) { |
| 1642 | return false; |
| 1643 | } |
| 1644 | finalize(result); |
| 1645 | return true; |
| 1646 | }; |
| 1647 | if (_createAudioDeviceModule |
| 1648 | && check(_createAudioDeviceModule(dependencies.task_queue_factory.get()))) { |
| 1649 | return; |
| 1650 | } else if (check(create(webrtc::AudioDeviceModule::kPlatformDefaultAudio))) { |
| 1651 | return; |
| 1652 | } |
| 1653 | }); |
| 1654 | return (_adm_use_withAudioDeviceModule != nullptr); |
| 1655 | } |
| 1656 | void destroyAudioDeviceModule() { |
| 1657 | if (!_adm_thread) { |
| 1658 | return; |
| 1659 | } |
| 1660 | _adm_thread->Invoke<void>(RTC_FROM_HERE, [&] { |
| 1661 | _adm_use_withAudioDeviceModule = nullptr; |
| 1662 | }); |
| 1663 | } |
| 1664 |
| 1665 | void start() { |
| 1666 | const auto weak = std::weak_ptr<GroupInstanceManager>(shared_from_this()); |
| 1667 |
| 1668 | _errorParsingLogSink.reset(new ErrorParsingLogSink([weak](uint32_t ssrc) { |
| 1669 | StaticThreads::getMediaThread()->PostTask(RTC_FROM_HERE, [weak, ssrc](){ |
| 1670 | auto strong = weak.lock(); |
| 1671 | if (!strong) { |
| 1672 | return; |
| 1673 | } |
| 1674 |
| 1675 | std::vector<uint32_t> ssrcs; |
| 1676 | ssrcs.push_back(ssrc); |
| 1677 | strong->_participantDescriptionsRequired(ssrcs); |
| 1678 | }); |
| 1679 | })); |
| 1680 | rtc::LogMessage::AddLogToStream(_errorParsingLogSink.get(), rtc::LS_WARNING); |
| 1681 |
| 1682 | webrtc::field_trial::InitFieldTrialsFromString( |
| 1683 | //"WebRTC-Audio-SendSideBwe/Enabled/" |
| 1684 | "WebRTC-Audio-Allocation/min:32kbps,max:32kbps/" |
| 1685 | "WebRTC-Audio-OpusMinPacketLossRate/Enabled-1/" |
| 1686 | //"WebRTC-FlexFEC-03/Enabled/" |
| 1687 | //"WebRTC-FlexFEC-03-Advertised/Enabled/" |
| 1688 | "WebRTC-PcFactoryDefaultBitrates/min:32kbps,start:32kbps,max:32kbps/" |
| 1689 | "WebRTC-Video-DiscardPacketsWithUnknownSsrc/Enabled/" |
| 1690 | "WebRTC-Video-BufferPacketsWithUnknownSsrc/Enabled/" |
| 1691 | ); |
| 1692 |
| 1693 | PlatformInterface::SharedInstance()->configurePlatformAudio(); |
| 1694 |
| 1695 | webrtc::PeerConnectionFactoryDependencies dependencies; |
| 1696 | dependencies.network_thread = StaticThreads::getNetworkThread(); |
| 1697 | dependencies.worker_thread = StaticThreads::getWorkerThread(); |
| 1698 | dependencies.signaling_thread = StaticThreads::getMediaThread(); |
| 1699 | dependencies.task_queue_factory = webrtc::CreateDefaultTaskQueueFactory(); |
| 1700 |
| 1701 | if (!createAudioDeviceModule(dependencies)) { |
| 1702 | return; |
| 1703 | } |
| 1704 |
| 1705 | cricket::MediaEngineDependencies mediaDeps; |
| 1706 | mediaDeps.task_queue_factory = dependencies.task_queue_factory.get(); |
| 1707 | mediaDeps.audio_encoder_factory = webrtc::CreateAudioEncoderFactory<webrtc::AudioEncoderOpus>(); |
| 1708 | mediaDeps.audio_decoder_factory = webrtc::CreateAudioDecoderFactory<webrtc::AudioDecoderOpus>(); |
| 1709 | mediaDeps.video_encoder_factory = PlatformInterface::SharedInstance()->makeVideoEncoderFactory(_platformContext); |
| 1710 | mediaDeps.video_decoder_factory = PlatformInterface::SharedInstance()->makeVideoDecoderFactory(_platformContext); |
| 1711 | mediaDeps.adm = _adm_use_withAudioDeviceModule; |
| 1712 |
| 1713 | std::shared_ptr<CombinedVad> myVad(new CombinedVad()); |
| 1714 |
| 1715 | auto analyzer = new AudioCaptureAnalyzer([&, weak, myVad](const webrtc::AudioBuffer* buffer) { |
| 1716 | if (!buffer) { |
| 1717 | return; |
| 1718 | } |
| 1719 | if (buffer->num_channels() != 1) { |
| 1720 | return; |
| 1721 | } |
| 1722 |
| 1723 | float peak = 0; |
| 1724 | int peakCount = 0; |
| 1725 | const float *samples = buffer->channels_const()[0]; |
| 1726 | for (int i = 0; i < buffer->num_frames(); i++) { |
| 1727 | float sample = samples[i]; |
| 1728 | if (sample < 0) { |
| 1729 | sample = -sample; |
| 1730 | } |
| 1731 | if (peak < sample) { |
| 1732 | peak = sample; |
| 1733 | } |
| 1734 | peakCount += 1; |
| 1735 | } |
| 1736 |
| 1737 | bool vadStatus = myVad->update((webrtc::AudioBuffer *)buffer); |
| 1738 |
| 1739 | StaticThreads::getMediaThread()->PostTask(RTC_FROM_HERE, [weak, peak, peakCount, vadStatus](){ |
| 1740 | auto strong = weak.lock(); |
| 1741 | if (!strong) { |
| 1742 | return; |
| 1743 | } |
| 1744 |
| 1745 | strong->_myAudioLevelPeakCount += peakCount; |
| 1746 | if (strong->_myAudioLevelPeak < peak) { |
| 1747 | strong->_myAudioLevelPeak = peak; |
| 1748 | } |
| 1749 | if (strong->_myAudioLevelPeakCount >= 1200) { |
| 1750 | float level = strong->_myAudioLevelPeak / 4000.0f; |
| 1751 | if (strong->_isMuted) { |
| 1752 | level = 0.0f; |
| 1753 | } |
| 1754 | strong->_myAudioLevelPeak = 0; |
| 1755 | strong->_myAudioLevelPeakCount = 0; |
| 1756 | strong->_myAudioLevel = GroupLevelValue{ |
| 1757 | level, |
| 1758 | vadStatus, |
| 1759 | }; |
| 1760 | } |
| 1761 | }); |
| 1762 | }); |
| 1763 |
| 1764 | webrtc::AudioProcessingBuilder builder; |
| 1765 | builder.SetCaptureAnalyzer(std::unique_ptr<AudioCaptureAnalyzer>(analyzer)); |
| 1766 | webrtc::AudioProcessing *apm = builder.Create(); |
| 1767 |
| 1768 | webrtc::AudioProcessing::Config audioConfig; |
| 1769 | webrtc::AudioProcessing::Config::NoiseSuppression noiseSuppression; |
| 1770 | noiseSuppression.enabled = true; |
| 1771 | noiseSuppression.level = webrtc::AudioProcessing::Config::NoiseSuppression::kHigh; |
| 1772 | audioConfig.noise_suppression = noiseSuppression; |
| 1773 |
| 1774 | audioConfig.high_pass_filter.enabled = true; |
| 1775 |
| 1776 | audioConfig.voice_detection.enabled = true; |
| 1777 |
| 1778 | apm->ApplyConfig(audioConfig); |
| 1779 |
| 1780 | mediaDeps.audio_processing = apm; |
| 1781 |
| 1782 | /*mediaDeps.onUnknownAudioSsrc = [weak](uint32_t ssrc) { |
| 1783 | getMediaThread()->PostTask(RTC_FROM_HERE, [weak, ssrc](){ |
| 1784 | auto strong = weak.lock(); |
| 1785 | if (!strong) { |
| 1786 | return; |
| 1787 | } |
| 1788 | strong->onMissingSsrc(ssrc); |
| 1789 | }); |
| 1790 | };*/ |
| 1791 |
| 1792 | dependencies.media_engine = cricket::CreateMediaEngine(std::move(mediaDeps)); |
| 1793 | dependencies.call_factory = webrtc::CreateCallFactory(); |
| 1794 | dependencies.event_log_factory = |
| 1795 | std::make_unique<webrtc::RtcEventLogFactory>(dependencies.task_queue_factory.get()); |
| 1796 | dependencies.network_controller_factory = nullptr; |
| 1797 |
| 1798 | _nativeFactory = webrtc::CreateModularPeerConnectionFactory(std::move(dependencies)); |
| 1799 |
| 1800 | webrtc::PeerConnectionFactoryInterface::Options peerConnectionOptions; |
| 1801 | peerConnectionOptions.disable_encryption = true; |
| 1802 | _nativeFactory->SetOptions(peerConnectionOptions); |
| 1803 |
| 1804 | webrtc::PeerConnectionInterface::RTCConfiguration config; |
| 1805 | config.sdp_semantics = webrtc::SdpSemantics::kUnifiedPlan; |
| 1806 | //config.continual_gathering_policy = webrtc::PeerConnectionInterface::ContinualGatheringPolicy::GATHER_CONTINUALLY; |
| 1807 | config.audio_jitter_buffer_fast_accelerate = true; |
| 1808 | config.prioritize_most_likely_ice_candidate_pairs = true; |
| 1809 | config.presume_writable_when_fully_relayed = true; |
| 1810 | //config.audio_jitter_buffer_enable_rtx_handling = true; |
| 1811 | config.enable_rtp_data_channel = true; |
| 1812 | config.enable_dtls_srtp = false; |
| 1813 |
| 1814 | /*webrtc::CryptoOptions cryptoOptions; |
| 1815 | webrtc::CryptoOptions::SFrame sframe; |
| 1816 | sframe.require_frame_encryption = true; |
| 1817 | cryptoOptions.sframe = sframe; |
| 1818 | config.crypto_options = cryptoOptions;*/ |
| 1819 |
| 1820 | _observer.reset(new PeerConnectionObserverImpl( |
| 1821 | [weak](std::string sdp, int mid, std::string sdpMid) { |
| 1822 | /*getMediaThread()->PostTask(RTC_FROM_HERE, [weak, sdp, mid, sdpMid](){ |
| 1823 | auto strong = weak.lock(); |
| 1824 | if (strong) { |
| 1825 | //strong->emitIceCandidate(sdp, mid, sdpMid); |
| 1826 | } |
| 1827 | });*/ |
| 1828 | }, |
| 1829 | [weak](bool isConnected) { |
| 1830 | StaticThreads::getMediaThread()->PostTask(RTC_FROM_HERE, [weak, isConnected](){ |
| 1831 | auto strong = weak.lock(); |
| 1832 | if (strong) { |
| 1833 | strong->updateIsConnected(isConnected); |
| 1834 | } |
| 1835 | }); |
| 1836 | }, |
| 1837 | [weak](rtc::scoped_refptr<webrtc::RtpTransceiverInterface> transceiver) { |
| 1838 | StaticThreads::getMediaThread()->PostTask(RTC_FROM_HERE, [weak, transceiver](){ |
| 1839 | auto strong = weak.lock(); |
| 1840 | if (!strong) { |
| 1841 | return; |
| 1842 | } |
| 1843 | strong->onTrackAdded(transceiver); |
| 1844 | }); |
| 1845 | }, |
| 1846 | [weak](rtc::scoped_refptr<webrtc::RtpReceiverInterface> receiver) { |
| 1847 | StaticThreads::getMediaThread()->PostTask(RTC_FROM_HERE, [weak, receiver](){ |
| 1848 | auto strong = weak.lock(); |
| 1849 | if (!strong) { |
| 1850 | return; |
| 1851 | } |
| 1852 | strong->onTrackRemoved(receiver); |
| 1853 | }); |
| 1854 | }, |
| 1855 | [weak](uint32_t ssrc) { |
| 1856 | StaticThreads::getMediaThread()->PostTask(RTC_FROM_HERE, [weak, ssrc](){ |
| 1857 | auto strong = weak.lock(); |
| 1858 | if (!strong) { |
| 1859 | return; |
| 1860 | } |
| 1861 | strong->onMissingSsrc(ssrc); |
| 1862 | }); |
| 1863 | } |
| 1864 | )); |
| 1865 | _peerConnection = _nativeFactory->CreatePeerConnection(config, nullptr, nullptr, _observer.get()); |
| 1866 | assert(_peerConnection != nullptr); |
| 1867 |
| 1868 | cricket::AudioOptions options; |
| 1869 | rtc::scoped_refptr<webrtc::AudioSourceInterface> audioSource = _nativeFactory->CreateAudioSource(options); |
| 1870 | std::stringstream name; |
| 1871 | name << "audio"; |
| 1872 | name << 0; |
| 1873 | std::vector<std::string> streamIds; |
| 1874 | streamIds.push_back(name.str()); |
| 1875 | _localAudioTrack = _nativeFactory->CreateAudioTrack(name.str(), audioSource); |
| 1876 | _localAudioTrack->set_enabled(false); |
| 1877 | auto addedAudioTrack = _peerConnection->AddTrack(_localAudioTrack, streamIds); |
| 1878 |
| 1879 | if (addedAudioTrack.ok()) { |
| 1880 | _localAudioTrackSender = addedAudioTrack.value(); |
| 1881 | for (auto &it : _peerConnection->GetTransceivers()) { |
| 1882 | if (it->media_type() == cricket::MediaType::MEDIA_TYPE_AUDIO) { |
| 1883 | if (_localAudioTrackSender.get() == it->sender().get()) { |
| 1884 | const auto error = it->SetDirectionWithError(webrtc::RtpTransceiverDirection::kRecvOnly); |
| 1885 | (void)error; |
| 1886 | } |
| 1887 |
| 1888 | break; |
| 1889 | } |
| 1890 | } |
| 1891 | } |
| 1892 |
| 1893 | if (_videoCapture && false) { |
| 1894 | webrtc::DataChannelInit dataChannelConfig; |
| 1895 | _localDataChannel = _peerConnection->CreateDataChannel("1", &dataChannelConfig); |
| 1896 |
| 1897 | if (_localDataChannel) { |
| 1898 | _localDataChannelMid = "1"; |
| 1899 |
| 1900 | _localDataChannelObserver.reset(new DataChannelObserverImpl([weak]() { |
| 1901 | StaticThreads::getMediaThread()->PostTask(RTC_FROM_HERE, [weak](){ |
| 1902 | auto strong = weak.lock(); |
| 1903 | if (!strong) { |
| 1904 | return; |
| 1905 | } |
| 1906 | bool isOpen = strong->_localDataChannel->state() == webrtc::DataChannelInterface::DataState::kOpen; |
| 1907 | if (strong->_localDataChannelIsOpen != isOpen) { |
| 1908 | RTC_LOG(LS_INFO) << "DataChannel isOpen: " << isOpen; |
| 1909 | strong->_localDataChannelIsOpen = isOpen; |
| 1910 | if (isOpen) { |
| 1911 | strong->updateRemoteVideoConstaints(); |
| 1912 | } |
| 1913 | } |
| 1914 | }); |
| 1915 | })); |
| 1916 | _localDataChannel->RegisterObserver(_localDataChannelObserver.get()); |
| 1917 | } |
| 1918 | } |
| 1919 |
| 1920 | updateVideoTrack(false, [](auto result) {}); |
| 1921 |
| 1922 | setAudioInputDevice(_initialInputDeviceId); |
| 1923 | setAudioOutputDevice(_initialOutputDeviceId); |
| 1924 |
| 1925 | // At least on Windows recording doesn't work without started playout. |
| 1926 | withAudioDeviceModule([weak](webrtc::AudioDeviceModule *adm) { |
| 1927 | #ifdef WEBRTC_WIN |
| 1928 | // At least on Windows starting/stopping playout while recording |
| 1929 | // is active leads to errors in recording and assertion violation. |
| 1930 | adm->EnableBuiltInAEC(false); |
| 1931 | #endif // WEBRTC_WIN |
| 1932 |
| 1933 | if (adm->InitPlayout() == 0) { |
| 1934 | adm->StartPlayout(); |
| 1935 | } else { |
| 1936 | StaticThreads::getMediaThread()->PostDelayedTask(RTC_FROM_HERE, [weak](){ |
| 1937 | auto strong = weak.lock(); |
| 1938 | if (!strong) { |
| 1939 | return; |
| 1940 | } |
| 1941 | strong->withAudioDeviceModule([](webrtc::AudioDeviceModule *adm) { |
| 1942 | if (adm->InitPlayout() == 0) { |
| 1943 | adm->StartPlayout(); |
| 1944 | } |
| 1945 | }); |
| 1946 | }, 2000); |
| 1947 | } |
| 1948 | }); |
| 1949 |
| 1950 | beginLevelsTimer(50); |
| 1951 | //beginTestQualityTimer(2000); |
| 1952 | } |
| 1953 |
| 1954 |
| 1955 | void setAudioInputDevice(std::string id) { |
| 1956 | #if !defined(WEBRTC_IOS) && !defined(WEBRTC_ANDROID) |
| 1957 | withAudioDeviceModule([&](webrtc::AudioDeviceModule *adm) { |
| 1958 | const auto recording = adm->Recording(); |
| 1959 | if (recording) { |
| 1960 | adm->StopRecording(); |
| 1961 | } |
| 1962 | const auto finish = [&] { |
| 1963 | if (recording) { |
| 1964 | adm->InitRecording(); |
| 1965 | adm->StartRecording(); |
| 1966 | } |
| 1967 | }; |
| 1968 | if (id == "default" || id.empty()) { |
| 1969 | if (const auto result = adm->SetRecordingDevice(webrtc::AudioDeviceModule::kDefaultCommunicationDevice)) { |
| 1970 | RTC_LOG(LS_ERROR) << "setAudioInputDevice(" << id << "): SetRecordingDevice(kDefaultCommunicationDevice) failed: " << result << "."; |
| 1971 | } else { |
| 1972 | RTC_LOG(LS_INFO) << "setAudioInputDevice(" << id << "): SetRecordingDevice(kDefaultCommunicationDevice) success."; |
| 1973 | } |
| 1974 | return finish(); |
| 1975 | } |
| 1976 | const auto count = adm |
| 1977 | ? adm->RecordingDevices() |
| 1978 | : int16_t(-666); |
| 1979 | if (count <= 0) { |
| 1980 | RTC_LOG(LS_ERROR) << "setAudioInputDevice(" << id << "): Could not get recording devices count: " << count << "."; |
| 1981 | return finish(); |
| 1982 | } |
| 1983 | for (auto i = 0; i != count; ++i) { |
| 1984 | char name[webrtc::kAdmMaxDeviceNameSize + 1] = { 0 }; |
| 1985 | char guid[webrtc::kAdmMaxGuidSize + 1] = { 0 }; |
| 1986 | adm->RecordingDeviceName(i, name, guid); |
| 1987 | if (id == guid) { |
| 1988 | const auto result = adm->SetRecordingDevice(i); |
| 1989 | if (result != 0) { |
| 1990 | RTC_LOG(LS_ERROR) << "setAudioInputDevice(" << id << ") name '" << std::string(name) << "' failed: " << result << "."; |
| 1991 | } else { |
| 1992 | RTC_LOG(LS_INFO) << "setAudioInputDevice(" << id << ") name '" << std::string(name) << "' success."; |
| 1993 | } |
| 1994 | return finish(); |
| 1995 | } |
| 1996 | } |
| 1997 | RTC_LOG(LS_ERROR) << "setAudioInputDevice(" << id << "): Could not find recording device."; |
| 1998 | return finish(); |
| 1999 | }); |
| 2000 | #endif |
| 2001 | } |
| 2002 |
| 2003 | void setAudioOutputDevice(std::string id) { |
| 2004 | #if !defined(WEBRTC_IOS) && !defined(WEBRTC_ANDROID) |
| 2005 | withAudioDeviceModule([&](webrtc::AudioDeviceModule *adm) { |
| 2006 | const auto playing = adm->Playing(); |
| 2007 | if (playing) { |
| 2008 | adm->StopPlayout(); |
| 2009 | } |
| 2010 | const auto finish = [&] { |
| 2011 | if (playing) { |
| 2012 | adm->InitPlayout(); |
| 2013 | adm->StartPlayout(); |
| 2014 | } |
| 2015 | }; |
| 2016 | if (id == "default" || id.empty()) { |
| 2017 | if (const auto result = adm->SetPlayoutDevice(webrtc::AudioDeviceModule::kDefaultCommunicationDevice)) { |
| 2018 | RTC_LOG(LS_ERROR) << "setAudioOutputDevice(" << id << "): SetPlayoutDevice(kDefaultCommunicationDevice) failed: " << result << "."; |
| 2019 | } else { |
| 2020 | RTC_LOG(LS_INFO) << "setAudioOutputDevice(" << id << "): SetPlayoutDevice(kDefaultCommunicationDevice) success."; |
| 2021 | } |
| 2022 | return finish(); |
| 2023 | } |
| 2024 | const auto count = adm |
| 2025 | ? adm->PlayoutDevices() |
| 2026 | : int16_t(-666); |
| 2027 | if (count <= 0) { |
| 2028 | RTC_LOG(LS_ERROR) << "setAudioOutputDevice(" << id << "): Could not get playout devices count: " << count << "."; |
| 2029 | return finish(); |
| 2030 | } |
| 2031 | for (auto i = 0; i != count; ++i) { |
| 2032 | char name[webrtc::kAdmMaxDeviceNameSize + 1] = { 0 }; |
| 2033 | char guid[webrtc::kAdmMaxGuidSize + 1] = { 0 }; |
| 2034 | adm->PlayoutDeviceName(i, name, guid); |
| 2035 | if (id == guid) { |
| 2036 | const auto result = adm->SetPlayoutDevice(i); |
| 2037 | if (result != 0) { |
| 2038 | RTC_LOG(LS_ERROR) << "setAudioOutputDevice(" << id << ") name '" << std::string(name) << "' failed: " << result << "."; |
| 2039 | } else { |
| 2040 | RTC_LOG(LS_INFO) << "setAudioOutputDevice(" << id << ") name '" << std::string(name) << "' success."; |
| 2041 | } |
| 2042 | return finish(); |
| 2043 | } |
| 2044 | } |
| 2045 | RTC_LOG(LS_ERROR) << "setAudioOutputDevice(" << id << "): Could not find playout device."; |
| 2046 | return finish(); |
| 2047 | }); |
| 2048 | #endif |
| 2049 | } |
| 2050 |
| 2051 | void addIncomingVideoOutput(uint32_t ssrc, std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) { |
| 2052 | auto current = _remoteVideoTrackSinks.find(ssrc); |
| 2053 | if (current != _remoteVideoTrackSinks.end()) { |
| 2054 | current->second->addSink(sink); |
| 2055 | } else { |
| 2056 | std::unique_ptr<CustomVideoSinkInterfaceProxyImpl> sinkProxy(new CustomVideoSinkInterfaceProxyImpl()); |
| 2057 | sinkProxy->addSink(sink); |
| 2058 | _remoteVideoTrackSinks[ssrc] = std::move(sinkProxy); |
| 2059 | } |
| 2060 | } |
| 2061 |
| 2062 | void setVolume(uint32_t ssrc, double volume) { |
| 2063 | auto current = _audioTrackVolumes.find(ssrc); |
| 2064 | bool updated = false; |
| 2065 | if (current != _audioTrackVolumes.end()) { |
| 2066 | if (abs(current->second - volume) > 0.001) { |
| 2067 | updated = true; |
| 2068 | } |
| 2069 | } else { |
| 2070 | if (volume < 1.0 - 0.001) { |
| 2071 | updated = true; |
| 2072 | } |
| 2073 | } |
| 2074 | if (updated) { |
| 2075 | _audioTrackVolumes[ssrc] = volume; |
| 2076 | auto track = _audioTracks.find(ssrc); |
| 2077 | if (track != _audioTracks.end()) { |
| 2078 | track->second->GetSource()->SetVolume(volume); |
| 2079 | } |
| 2080 | } |
| 2081 | } |
| 2082 |
| 2083 | void setFullSizeVideoSsrc(uint32_t ssrc) { |
| 2084 | if (_currentFullSizeVideoSsrc == ssrc) { |
| 2085 | return; |
| 2086 | } |
| 2087 | bool update = false; |
| 2088 | if (_currentFullSizeVideoSsrc != 0) { |
| 2089 | if (setVideoConstraint(_currentFullSizeVideoSsrc, false, false)) { |
| 2090 | update = true; |
| 2091 | } |
| 2092 | } |
| 2093 | _currentFullSizeVideoSsrc = ssrc; |
| 2094 | if (_currentFullSizeVideoSsrc != 0) { |
| 2095 | if (setVideoConstraint(_currentFullSizeVideoSsrc, true, false)) { |
| 2096 | update = true; |
| 2097 | } |
| 2098 | } |
| 2099 | if (update) { |
| 2100 | updateRemoteVideoConstaints(); |
| 2101 | } |
| 2102 | } |
| 2103 |
| 2104 | void updateIsConnected(bool isConnected) { |
| 2105 | _isConnected = isConnected; |
| 2106 |
| 2107 | auto timestamp = rtc::TimeMillis(); |
| 2108 |
| 2109 | _isConnectedUpdateValidTaskId++; |
| 2110 |
| 2111 | if (!isConnected && _appliedOfferTimestamp > timestamp - 1000) { |
| 2112 | auto taskId = _isConnectedUpdateValidTaskId; |
| 2113 | const auto weak = std::weak_ptr<GroupInstanceManager>(shared_from_this()); |
| 2114 | StaticThreads::getMediaThread()->PostDelayedTask(RTC_FROM_HERE, [weak, taskId]() { |
| 2115 | auto strong = weak.lock(); |
| 2116 | if (!strong) { |
| 2117 | return; |
| 2118 | } |
| 2119 | if (strong->_isConnectedUpdateValidTaskId == taskId) { |
| 2120 | strong->_networkStateUpdated(strong->_isConnected); |
| 2121 | } |
| 2122 | }, 1000); |
| 2123 | } else { |
| 2124 | _networkStateUpdated(_isConnected); |
| 2125 | } |
| 2126 | } |
| 2127 |
| 2128 | void stop() { |
| 2129 | _peerConnection->Close(); |
| 2130 | } |
| 2131 |
| 2132 | std::string adjustLocalSdp(std::string const &sdp) { |
| 2133 | auto lines = splitSdpLines(sdp); |
| 2134 | std::vector<std::string> resultSdp; |
| 2135 |
| 2136 | std::ostringstream generatedSsrcStringStream; |
| 2137 | generatedSsrcStringStream << _mainStreamAudioSsrc; |
| 2138 | auto generatedSsrcString = generatedSsrcStringStream.str(); |
| 2139 |
| 2140 | auto bundleLines = getLines(lines, "a=group:BUNDLE "); |
| 2141 | std::vector<std::string> bundleMLines; |
| 2142 | if (bundleLines.size() != 0) { |
| 2143 | bundleMLines = splitBundleMLines(bundleLines[0]); |
| 2144 | } |
| 2145 |
| 2146 | bool hasVideo = false; |
| 2147 | std::string currentMid; |
| 2148 | int insertVideoLinesAtIndex = 0; |
| 2149 | for (auto &line : lines) { |
| 2150 | auto adjustedLine = line; |
| 2151 |
| 2152 | if (adjustedLine.find("a=group:BUNDLE ") == 0) { |
| 2153 | std::ostringstream bundleString; |
| 2154 | bundleString << "a=group:BUNDLE"; |
| 2155 | for (auto &mLine : bundleMLines) { |
| 2156 | bundleString << " " << mLine; |
| 2157 | } |
| 2158 | adjustedLine = bundleString.str(); |
| 2159 | } |
| 2160 |
| 2161 | if (adjustedLine.find("m=") == 0) { |
| 2162 | currentMid = ""; |
| 2163 | } |
| 2164 | if (adjustedLine.find("a=mid:") == 0) { |
| 2165 | currentMid = adjustedLine; |
| 2166 | currentMid.replace(0, std::string("a=mid:").size(), ""); |
| 2167 | } |
| 2168 |
| 2169 | if (adjustedLine.find("m=application") == 0) { |
| 2170 | insertVideoLinesAtIndex = (int)resultSdp.size(); |
| 2171 | } |
| 2172 |
| 2173 | if (currentMid == "0") { |
| 2174 | if (adjustedLine.find("a=ssrc:") == 0) { |
| 2175 | int startIndex = 7; |
| 2176 | int i = startIndex; |
| 2177 | while (i < adjustedLine.size()) { |
| 2178 | if (!isdigit(adjustedLine[i])) { |
| 2179 | break; |
| 2180 | } |
| 2181 | i++; |
| 2182 | } |
| 2183 | if (i >= startIndex) { |
| 2184 | adjustedLine.replace(startIndex, i - startIndex, generatedSsrcString); |
| 2185 | } |
| 2186 | } |
| 2187 | } else if (currentMid == "1") { |
| 2188 | if (adjustedLine.find("a=ssrc:") == 0 || adjustedLine.find("a=ssrc-group:") == 0) { |
| 2189 | hasVideo = true; |
| 2190 | adjustedLine.clear(); |
| 2191 | } |
| 2192 | } |
| 2193 |
| 2194 | if (adjustedLine.find("a=candidate") == 0) { |
| 2195 | adjustedLine.clear(); |
| 2196 | } |
| 2197 |
| 2198 | if (adjustedLine.size() != 0) { |
| 2199 | appendSdp(resultSdp, adjustedLine); |
| 2200 | if (currentMid == "1") { |
| 2201 | insertVideoLinesAtIndex = (int)resultSdp.size(); |
| 2202 | } |
| 2203 | } |
| 2204 | } |
| 2205 |
| 2206 | if (hasVideo) { |
| 2207 | std::vector<GroupJoinPayloadVideoSourceGroup> videoSourceGroups; |
| 2208 |
| 2209 | int ssrcDistance = 1; |
| 2210 |
| 2211 | GroupJoinPayloadVideoSourceGroup sim; |
| 2212 | sim.semantics = "SIM"; |
| 2213 | sim.ssrcs.push_back(_mainStreamAudioSsrc + ssrcDistance + 0); |
| 2214 | sim.ssrcs.push_back(_mainStreamAudioSsrc + ssrcDistance + 2); |
| 2215 | sim.ssrcs.push_back(_mainStreamAudioSsrc + ssrcDistance + 4); |
| 2216 | videoSourceGroups.push_back(sim); |
| 2217 |
| 2218 | GroupJoinPayloadVideoSourceGroup fid0; |
| 2219 | fid0.semantics = "FID"; |
| 2220 | fid0.ssrcs.push_back(_mainStreamAudioSsrc + ssrcDistance + 0); |
| 2221 | fid0.ssrcs.push_back(_mainStreamAudioSsrc + ssrcDistance + 1); |
| 2222 | videoSourceGroups.push_back(fid0); |
| 2223 |
| 2224 | GroupJoinPayloadVideoSourceGroup fid1; |
| 2225 | fid1.semantics = "FID"; |
| 2226 | fid1.ssrcs.push_back(_mainStreamAudioSsrc + ssrcDistance + 2); |
| 2227 | fid1.ssrcs.push_back(_mainStreamAudioSsrc + ssrcDistance + 3); |
| 2228 | videoSourceGroups.push_back(fid1); |
| 2229 |
| 2230 | GroupJoinPayloadVideoSourceGroup fid2; |
| 2231 | fid2.semantics = "FID"; |
| 2232 | fid2.ssrcs.push_back(_mainStreamAudioSsrc + ssrcDistance + 4); |
| 2233 | fid2.ssrcs.push_back(_mainStreamAudioSsrc + ssrcDistance + 5); |
| 2234 | videoSourceGroups.push_back(fid2); |
| 2235 |
| 2236 | std::string streamId = "video0"; |
| 2237 |
| 2238 | std::vector<uint32_t> ssrcs; |
| 2239 | for (auto &group : videoSourceGroups) { |
| 2240 | std::ostringstream groupString; |
| 2241 | groupString << "a=ssrc-group:"; |
| 2242 | groupString << group.semantics; |
| 2243 |
| 2244 | for (auto ssrc : group.ssrcs) { |
| 2245 | groupString << " " << ssrc; |
| 2246 |
| 2247 | if (std::find(ssrcs.begin(), ssrcs.end(), ssrc) == ssrcs.end()) { |
| 2248 | ssrcs.push_back(ssrc); |
| 2249 | } |
| 2250 | } |
| 2251 |
| 2252 | appendSdp(resultSdp, groupString.str(), insertVideoLinesAtIndex); |
| 2253 | insertVideoLinesAtIndex++; |
| 2254 | } |
| 2255 |
| 2256 | for (auto ssrc : ssrcs) { |
| 2257 | std::ostringstream cnameString; |
| 2258 | cnameString << "a=ssrc:"; |
| 2259 | cnameString << ssrc; |
| 2260 | cnameString << " cname:stream"; |
| 2261 | cnameString << streamId; |
| 2262 | appendSdp(resultSdp, cnameString.str(), insertVideoLinesAtIndex); |
| 2263 | insertVideoLinesAtIndex++; |
| 2264 |
| 2265 | std::ostringstream msidString; |
| 2266 | msidString << "a=ssrc:"; |
| 2267 | msidString << ssrc; |
| 2268 | msidString << " msid:stream"; |
| 2269 | msidString << streamId; |
| 2270 | msidString << " video" << streamId; |
| 2271 | appendSdp(resultSdp, msidString.str(), insertVideoLinesAtIndex); |
| 2272 | insertVideoLinesAtIndex++; |
| 2273 |
| 2274 | std::ostringstream mslabelString; |
| 2275 | mslabelString << "a=ssrc:"; |
| 2276 | mslabelString << ssrc; |
| 2277 | mslabelString << " mslabel:video"; |
| 2278 | mslabelString << streamId; |
| 2279 | appendSdp(resultSdp, mslabelString.str(), insertVideoLinesAtIndex); |
| 2280 | insertVideoLinesAtIndex++; |
| 2281 |
| 2282 | std::ostringstream labelString; |
| 2283 | labelString << "a=ssrc:"; |
| 2284 | labelString << ssrc; |
| 2285 | labelString << " label:video"; |
| 2286 | labelString << streamId; |
| 2287 | appendSdp(resultSdp, labelString.str(), insertVideoLinesAtIndex); |
| 2288 | insertVideoLinesAtIndex++; |
| 2289 | } |
| 2290 | } |
| 2291 |
| 2292 | std::ostringstream result; |
| 2293 | for (auto &line : resultSdp) { |
| 2294 | result << line << "\n"; |
| 2295 | } |
| 2296 |
| 2297 | return result.str(); |
| 2298 | } |
| 2299 |
| 2300 | void emitJoinPayload(std::function<void(GroupJoinPayload)> completion) { |
| 2301 | const auto weak = std::weak_ptr<GroupInstanceManager>(shared_from_this()); |
| 2302 | webrtc::PeerConnectionInterface::RTCOfferAnswerOptions options; |
| 2303 | rtc::scoped_refptr<CreateSessionDescriptionObserverImpl> observer(new rtc::RefCountedObject<CreateSessionDescriptionObserverImpl>([weak, completion](std::string sdp, std::string type) { |
| 2304 | StaticThreads::getMediaThread()->PostTask(RTC_FROM_HERE, [weak, sdp, type, completion](){ |
| 2305 | auto strong = weak.lock(); |
| 2306 | if (!strong) { |
| 2307 | return; |
| 2308 | } |
| 2309 |
| 2310 | auto adjustedSdp = strong->adjustLocalSdp(sdp); |
| 2311 |
| 2312 | RTC_LOG(LoggingSeverity::WARNING) << "----- setLocalDescription join -----"; |
| 2313 | RTC_LOG(LoggingSeverity::WARNING) << adjustedSdp; |
| 2314 | RTC_LOG(LoggingSeverity::WARNING) << "-----"; |
| 2315 |
| 2316 | webrtc::SdpParseError error; |
| 2317 | webrtc::SessionDescriptionInterface *sessionDescription = webrtc::CreateSessionDescription(type, adjustLocalDescription(adjustedSdp), &error); |
| 2318 | if (sessionDescription != nullptr) { |
| 2319 | rtc::scoped_refptr<SetSessionDescriptionObserverImpl> observer(new rtc::RefCountedObject<SetSessionDescriptionObserverImpl>([weak, adjustedSdp, completion]() { |
| 2320 | auto strong = weak.lock(); |
| 2321 | if (!strong) { |
| 2322 | return; |
| 2323 | } |
| 2324 |
| 2325 | if (strong->_localVideoTrackTransceiver) { |
| 2326 | strong->_localVideoMid = strong->_localVideoTrackTransceiver->mid(); |
| 2327 | if (strong->_localDataChannel) { |
| 2328 | if (strong->_localVideoMid && strong->_localVideoMid.value() == "1") { |
| 2329 | strong->_localDataChannelMid = "2"; |
| 2330 | } else { |
| 2331 | strong->_localDataChannelMid = "1"; |
| 2332 | } |
| 2333 | } |
| 2334 | } else { |
| 2335 | strong->_localVideoMid.reset(); |
| 2336 | } |
| 2337 |
| 2338 | auto payload = parseSdpIntoJoinPayload(adjustedSdp); |
| 2339 | if (payload) { |
| 2340 | payload->ssrc = strong->_mainStreamAudioSsrc; |
| 2341 | strong->_joinPayload = payload; |
| 2342 | completion(payload.value()); |
| 2343 | } |
| 2344 | }, [](webrtc::RTCError error) { |
| 2345 | })); |
| 2346 | strong->_peerConnection->SetLocalDescription(observer, sessionDescription); |
| 2347 | } else { |
| 2348 | return; |
| 2349 | } |
| 2350 | }); |
| 2351 | })); |
| 2352 | _peerConnection->CreateOffer(observer, options); |
| 2353 | } |
| 2354 |
| 2355 | void setJoinResponsePayload(GroupJoinResponsePayload payload, std::vector<tgcalls::GroupParticipantDescription> &&participants) { |
| 2356 | if (!_joinPayload) { |
| 2357 | return; |
| 2358 | } |
| 2359 | _joinResponsePayload = payload; |
| 2360 |
| 2361 | auto sdp = parseJoinResponseIntoSdp(_sessionId, _joinPayload.value(), payload, SdpType::kSdpTypeJoinAnswer, _allOtherParticipants, _localVideoMid, _localDataChannelMid, _bundleStreamsState); |
| 2362 | setOfferSdp(sdp, true, true, false); |
| 2363 |
| 2364 | addParticipantsInternal(std::move(participants), false); |
| 2365 | } |
| 2366 |
| 2367 | void removeSsrcs(std::vector<uint32_t> ssrcs) { |
| 2368 | if (!_joinPayload) { |
| 2369 | return; |
| 2370 | } |
| 2371 | if (!_joinResponsePayload) { |
| 2372 | return; |
| 2373 | } |
| 2374 |
| 2375 | bool updated = false; |
| 2376 | for (auto ssrc : ssrcs) { |
| 2377 | for (auto &participant : _allOtherParticipants) { |
| 2378 | if (participant.audioSsrc == ssrc) { |
| 2379 | if (!participant.isRemoved) { |
| 2380 | participant.isRemoved = true; |
| 2381 | updated = true; |
| 2382 | } |
| 2383 | } |
| 2384 | } |
| 2385 | } |
| 2386 |
| 2387 | if (updated) { |
| 2388 | auto sdp = parseJoinResponseIntoSdp(_sessionId, _joinPayload.value(), _joinResponsePayload.value(), SdpType::kSdpTypeRemoteOffer, _allOtherParticipants, _localVideoMid, _localDataChannelMid, _bundleStreamsState); |
| 2389 | setOfferSdp(sdp, false, false, false); |
| 2390 | } |
| 2391 | } |
| 2392 |
| 2393 | void addParticipants(std::vector<GroupParticipantDescription> &&participants) { |
| 2394 | addParticipantsInternal(std::move(participants), false); |
| 2395 | } |
| 2396 |
| 2397 | void addParticipantsInternal(std::vector<GroupParticipantDescription> const &participants, bool completeMissingSsrcSetup) { |
| 2398 | if (!_joinPayload || !_joinResponsePayload) { |
| 2399 | if (completeMissingSsrcSetup) { |
| 2400 | completeProcessingMissingSsrcs(); |
| 2401 | } |
| 2402 | return; |
| 2403 | } |
| 2404 |
| 2405 | std::vector<uint32_t> addedSsrcs; |
| 2406 |
| 2407 | for (auto &participant : participants) { |
| 2408 | bool found = false; |
| 2409 | for (auto &other : _allOtherParticipants) { |
| 2410 | if (other.audioSsrc == participant.audioSsrc) { |
| 2411 | found = true; |
| 2412 | break; |
| 2413 | } |
| 2414 | } |
| 2415 |
| 2416 | if (!found) { |
| 2417 | addedSsrcs.push_back(participant.audioSsrc); |
| 2418 | _allOtherParticipants.push_back(participant); |
| 2419 | //_activeOtherSsrcs.insert(participant.audioSsrc); |
| 2420 | } |
| 2421 | } |
| 2422 |
| 2423 | auto sdp = parseJoinResponseIntoSdp(_sessionId, _joinPayload.value(), _joinResponsePayload.value(), SdpType::kSdpTypeRemoteOffer, _allOtherParticipants, _localVideoMid, _localDataChannelMid, _bundleStreamsState); |
| 2424 | setOfferSdp(sdp, false, false, completeMissingSsrcSetup); |
| 2425 |
| 2426 | bool updated = false; |
| 2427 | for (auto &ssrc : addedSsrcs) { |
| 2428 | /*if (setVideoConstraint(ssrc, false, false)) { |
| 2429 | updated = true; |
| 2430 | }*/ |
| 2431 | } |
| 2432 | if (updated) { |
| 2433 | updateRemoteVideoConstaints(); |
| 2434 | } |
| 2435 | } |
| 2436 |
| 2437 | void applyLocalSdp() { |
| 2438 | const auto weak = std::weak_ptr<GroupInstanceManager>(shared_from_this()); |
| 2439 | webrtc::PeerConnectionInterface::RTCOfferAnswerOptions options; |
| 2440 | rtc::scoped_refptr<CreateSessionDescriptionObserverImpl> observer(new rtc::RefCountedObject<CreateSessionDescriptionObserverImpl>([weak](std::string sdp, std::string type) { |
| 2441 | StaticThreads::getMediaThread()->PostTask(RTC_FROM_HERE, [weak, sdp, type](){ |
| 2442 | auto strong = weak.lock(); |
| 2443 | if (!strong) { |
| 2444 | return; |
| 2445 | } |
| 2446 |
| 2447 | auto adjustedSdp = strong->adjustLocalSdp(sdp); |
| 2448 |
| 2449 | RTC_LOG(LoggingSeverity::WARNING) << "----- setLocalDescription applyLocalSdp -----"; |
| 2450 | RTC_LOG(LoggingSeverity::WARNING) << adjustedSdp; |
| 2451 | RTC_LOG(LoggingSeverity::WARNING) << "-----"; |
| 2452 |
| 2453 | webrtc::SdpParseError error; |
| 2454 | webrtc::SessionDescriptionInterface *sessionDescription = webrtc::CreateSessionDescription(type, adjustLocalDescription(adjustedSdp), &error); |
| 2455 | if (sessionDescription != nullptr) { |
| 2456 | rtc::scoped_refptr<SetSessionDescriptionObserverImpl> observer(new rtc::RefCountedObject<SetSessionDescriptionObserverImpl>([weak, adjustedSdp]() { |
| 2457 | auto strong = weak.lock(); |
| 2458 | if (!strong) { |
| 2459 | return; |
| 2460 | } |
| 2461 |
| 2462 | if (!strong->_joinPayload) { |
| 2463 | return; |
| 2464 | } |
| 2465 | if (!strong->_joinResponsePayload) { |
| 2466 | return; |
| 2467 | } |
| 2468 |
| 2469 | if (strong->_localVideoTrackTransceiver) { |
| 2470 | strong->_localVideoMid = strong->_localVideoTrackTransceiver->mid(); |
| 2471 | if (strong->_localDataChannel) { |
| 2472 | if (strong->_localVideoMid && strong->_localVideoMid.value() == "1") { |
| 2473 | strong->_localDataChannelMid = "2"; |
| 2474 | } else { |
| 2475 | strong->_localDataChannelMid = "1"; |
| 2476 | } |
| 2477 | } |
| 2478 | } else { |
| 2479 | strong->_localVideoMid.reset(); |
| 2480 | } |
| 2481 |
| 2482 | auto sdp = parseJoinResponseIntoSdp(strong->_sessionId, strong->_joinPayload.value(), strong->_joinResponsePayload.value(), SdpType::kSdpTypeJoinAnswer, strong->_allOtherParticipants, strong->_localVideoMid, strong->_localDataChannelMid, strong->_bundleStreamsState); |
| 2483 | strong->setOfferSdp(sdp, false, true, false); |
| 2484 | }, [](webrtc::RTCError error) { |
| 2485 | })); |
| 2486 | strong->_peerConnection->SetLocalDescription(observer, sessionDescription); |
| 2487 | } else { |
| 2488 | return; |
| 2489 | } |
| 2490 | }); |
| 2491 | })); |
| 2492 | _peerConnection->CreateOffer(observer, options); |
| 2493 | } |
| 2494 |
| 2495 | void setOfferSdp(std::string const &offerSdp, bool isInitialJoinAnswer, bool isAnswer, bool completeMissingSsrcSetup) { |
| 2496 | if (!isAnswer && _appliedRemoteDescription == offerSdp) { |
| 2497 | if (completeMissingSsrcSetup) { |
| 2498 | completeProcessingMissingSsrcs(); |
| 2499 | } |
| 2500 | return; |
| 2501 | } |
| 2502 |
| 2503 | if (_appliedRemoteDescription.size() != 0) { |
| 2504 | _appliedOfferTimestamp = rtc::TimeMillis(); |
| 2505 | } |
| 2506 |
| 2507 | _appliedRemoteDescription = offerSdp; |
| 2508 |
| 2509 | RTC_LOG(LoggingSeverity::WARNING) << "----- setOfferSdp " << (isAnswer ? "answer" : "offer") << " -----"; |
| 2510 | RTC_LOG(LoggingSeverity::WARNING) << offerSdp; |
| 2511 | RTC_LOG(LoggingSeverity::WARNING) << "-----"; |
| 2512 |
| 2513 | webrtc::SdpParseError error; |
| 2514 | webrtc::SessionDescriptionInterface *sessionDescription = webrtc::CreateSessionDescription(isAnswer ? "answer" : "offer", adjustLocalDescription(offerSdp), &error); |
| 2515 | if (!sessionDescription) { |
| 2516 | if (completeMissingSsrcSetup) { |
| 2517 | completeProcessingMissingSsrcs(); |
| 2518 | } |
| 2519 | return; |
| 2520 | } |
| 2521 |
| 2522 | const auto weak = std::weak_ptr<GroupInstanceManager>(shared_from_this()); |
| 2523 | rtc::scoped_refptr<SetSessionDescriptionObserverImpl> observer(new rtc::RefCountedObject<SetSessionDescriptionObserverImpl>([weak, isInitialJoinAnswer, isAnswer, completeMissingSsrcSetup]() { |
| 2524 | StaticThreads::getMediaThread()->PostTask(RTC_FROM_HERE, [weak, isInitialJoinAnswer, isAnswer, completeMissingSsrcSetup](){ |
| 2525 | auto strong = weak.lock(); |
| 2526 | if (!strong) { |
| 2527 | return; |
| 2528 | } |
| 2529 | if (!isAnswer) { |
| 2530 | strong->emitAnswer(completeMissingSsrcSetup); |
| 2531 | } else { |
| 2532 | if (isInitialJoinAnswer) { |
| 2533 | strong->completedInitialSetup(); |
| 2534 | } |
| 2535 |
| 2536 | if (completeMissingSsrcSetup) { |
| 2537 | strong->completeProcessingMissingSsrcs(); |
| 2538 | } |
| 2539 | } |
| 2540 | }); |
| 2541 | }, [weak, completeMissingSsrcSetup](webrtc::RTCError error) { |
| 2542 | RTC_LOG(LoggingSeverity::LS_ERROR) << "Error: " << error.message(); |
| 2543 | StaticThreads::getMediaThread()->PostTask(RTC_FROM_HERE, [weak, completeMissingSsrcSetup](){ |
| 2544 | auto strong = weak.lock(); |
| 2545 | if (!strong) { |
| 2546 | return; |
| 2547 | } |
| 2548 | if (completeMissingSsrcSetup) { |
| 2549 | strong->completeProcessingMissingSsrcs(); |
| 2550 | } |
| 2551 | }); |
| 2552 | })); |
| 2553 |
| 2554 | _peerConnection->SetRemoteDescription(observer, sessionDescription); |
| 2555 | } |
| 2556 |
| 2557 | void beginStatsTimer(int timeoutMs) { |
| 2558 | const auto weak = std::weak_ptr<GroupInstanceManager>(shared_from_this()); |
| 2559 | StaticThreads::getMediaThread()->PostDelayedTask(RTC_FROM_HERE, [weak]() { |
| 2560 | StaticThreads::getMediaThread()->PostTask(RTC_FROM_HERE, [weak](){ |
| 2561 | auto strong = weak.lock(); |
| 2562 | if (!strong) { |
| 2563 | return; |
| 2564 | } |
| 2565 | strong->collectStats(); |
| 2566 | }); |
| 2567 | }, timeoutMs); |
| 2568 | } |
| 2569 |
| 2570 | void beginLevelsTimer(int timeoutMs) { |
| 2571 | const auto weak = std::weak_ptr<GroupInstanceManager>(shared_from_this()); |
| 2572 | StaticThreads::getMediaThread()->PostDelayedTask(RTC_FROM_HERE, [weak]() { |
| 2573 | auto strong = weak.lock(); |
| 2574 | if (!strong) { |
| 2575 | return; |
| 2576 | } |
| 2577 |
| 2578 | GroupLevelsUpdate levelsUpdate; |
| 2579 | levelsUpdate.updates.reserve(strong->_audioLevels.size() + 1); |
| 2580 | for (auto &it : strong->_audioLevels) { |
| 2581 | if (it.second.level > 0.001f) { |
| 2582 | levelsUpdate.updates.push_back(GroupLevelUpdate{ |
| 2583 | it.first, |
| 2584 | it.second, |
| 2585 | }); |
| 2586 | } |
| 2587 | } |
| 2588 | levelsUpdate.updates.push_back(GroupLevelUpdate{ 0, strong->_myAudioLevel }); |
| 2589 |
| 2590 | strong->_audioLevels.clear(); |
| 2591 | strong->_audioLevelsUpdated(levelsUpdate); |
| 2592 |
| 2593 | strong->beginLevelsTimer(50); |
| 2594 | }, timeoutMs); |
| 2595 | } |
| 2596 |
| 2597 | void beginTestQualityTimer(int timeoutMs) { |
| 2598 | const auto weak = std::weak_ptr<GroupInstanceManager>(shared_from_this()); |
| 2599 | StaticThreads::getMediaThread()->PostDelayedTask(RTC_FROM_HERE, [weak]() { |
| 2600 | auto strong = weak.lock(); |
| 2601 | if (!strong) { |
| 2602 | return; |
| 2603 | } |
| 2604 |
| 2605 | strong->_debugQualityValue = !strong->_debugQualityValue; |
| 2606 | strong->updateRemoteVideoConstaints(); |
| 2607 |
| 2608 | strong->beginTestQualityTimer(5000); |
| 2609 | }, timeoutMs); |
| 2610 | } |
| 2611 |
| 2612 | void collectStats() { |
| 2613 | const auto weak = std::weak_ptr<GroupInstanceManager>(shared_from_this()); |
| 2614 |
| 2615 | rtc::scoped_refptr<RTCStatsCollectorCallbackImpl> observer(new rtc::RefCountedObject<RTCStatsCollectorCallbackImpl>([weak](const rtc::scoped_refptr<const webrtc::RTCStatsReport> &stats) { |
| 2616 | StaticThreads::getMediaThread()->PostTask(RTC_FROM_HERE, [weak, stats](){ |
| 2617 | auto strong = weak.lock(); |
| 2618 | if (!strong) { |
| 2619 | return; |
| 2620 | } |
| 2621 | strong->reportStats(stats); |
| 2622 | strong->beginStatsTimer(100); |
| 2623 | }); |
| 2624 | })); |
| 2625 | _peerConnection->GetStats(observer); |
| 2626 | } |
| 2627 |
| 2628 | void reportStats(const rtc::scoped_refptr<const webrtc::RTCStatsReport> &stats) { |
| 2629 | } |
| 2630 |
| 2631 | void onTrackAdded(rtc::scoped_refptr<webrtc::RtpTransceiverInterface> transceiver) { |
| 2632 | if (transceiver->direction() == webrtc::RtpTransceiverDirection::kRecvOnly && transceiver->media_type() == cricket::MediaType::MEDIA_TYPE_AUDIO) { |
| 2633 | if (transceiver->mid()) { |
| 2634 | auto streamId = transceiver->mid().value(); |
| 2635 | if (streamId.find("audio") != 0) { |
| 2636 | return; |
| 2637 | } |
| 2638 | streamId.replace(0, 5, ""); |
| 2639 | std::istringstream iss(streamId); |
| 2640 | uint32_t ssrc = 0; |
| 2641 | iss >> ssrc; |
| 2642 |
| 2643 | rtc::scoped_refptr<webrtc::AudioTrackInterface> remoteAudioTrack(static_cast<webrtc::AudioTrackInterface *>(transceiver->receiver()->track().get())); |
| 2644 | if (_audioTracks.find(ssrc) == _audioTracks.end()) { |
| 2645 | _audioTracks.insert(std::make_pair(ssrc, remoteAudioTrack)); |
| 2646 | } |
| 2647 | auto currentVolume = _audioTrackVolumes.find(ssrc); |
| 2648 | if (currentVolume != _audioTrackVolumes.end()) { |
| 2649 | remoteAudioTrack->GetSource()->SetVolume(currentVolume->second); |
| 2650 | } |
| 2651 | if (_audioTrackSinks.find(ssrc) == _audioTrackSinks.end()) { |
| 2652 | const auto weak = std::weak_ptr<GroupInstanceManager>(shared_from_this()); |
| 2653 | std::shared_ptr<AudioTrackSinkInterfaceImpl> sink(new AudioTrackSinkInterfaceImpl([weak, ssrc](float level, bool hasSpeech) { |
| 2654 | StaticThreads::getMediaThread()->PostTask(RTC_FROM_HERE, [weak, ssrc, level, hasSpeech]() { |
| 2655 | auto strong = weak.lock(); |
| 2656 | if (!strong) { |
| 2657 | return; |
| 2658 | } |
| 2659 | auto current = strong->_audioLevels.find(ssrc); |
| 2660 | if (current != strong->_audioLevels.end()) { |
| 2661 | if (current->second.level < level) { |
| 2662 | strong->_audioLevels[ssrc] = GroupLevelValue{ |
| 2663 | level, |
| 2664 | hasSpeech, |
| 2665 | }; |
| 2666 | } |
| 2667 | } else { |
| 2668 | strong->_audioLevels.emplace( |
| 2669 | ssrc, |
| 2670 | GroupLevelValue{ |
| 2671 | level, |
| 2672 | hasSpeech, |
| 2673 | }); |
| 2674 | } |
| 2675 | }); |
| 2676 | })); |
| 2677 | _audioTrackSinks[ssrc] = sink; |
| 2678 | remoteAudioTrack->AddSink(sink.get()); |
| 2679 | //remoteAudioTrack->GetSource()->SetVolume(0.01); |
| 2680 | } |
| 2681 | } |
| 2682 | } else if (transceiver->direction() == webrtc::RtpTransceiverDirection::kRecvOnly && transceiver->media_type() == cricket::MediaType::MEDIA_TYPE_VIDEO) { |
| 2683 | auto streamId = transceiver->mid().value(); |
| 2684 | if (streamId.find("video") != 0) { |
| 2685 | return; |
| 2686 | } |
| 2687 | streamId.replace(0, 5, ""); |
| 2688 | std::istringstream iss(streamId); |
| 2689 | uint32_t ssrc = 0; |
| 2690 | iss >> ssrc; |
| 2691 |
| 2692 | auto remoteVideoTrack = static_cast<webrtc::VideoTrackInterface *>(transceiver->receiver()->track().get()); |
| 2693 | if (_remoteVideoTracks.find(ssrc) == _remoteVideoTracks.end()) { |
| 2694 | _remoteVideoTracks[ssrc] = remoteVideoTrack; |
| 2695 | auto current = _remoteVideoTrackSinks.find(ssrc); |
| 2696 | if (current != _remoteVideoTrackSinks.end()) { |
| 2697 | remoteVideoTrack->AddOrUpdateSink(current->second.get(), rtc::VideoSinkWants()); |
| 2698 | } else { |
| 2699 | std::unique_ptr<CustomVideoSinkInterfaceProxyImpl> sink(new CustomVideoSinkInterfaceProxyImpl()); |
| 2700 | remoteVideoTrack->AddOrUpdateSink(sink.get(), rtc::VideoSinkWants()); |
| 2701 | _remoteVideoTrackSinks[ssrc] = std::move(sink); |
| 2702 | } |
| 2703 |
| 2704 | if (_incomingVideoSourcesUpdated) { |
| 2705 | std::vector<uint32_t> allSources; |
| 2706 | for (auto &it : _remoteVideoTracks) { |
| 2707 | allSources.push_back(it.first); |
| 2708 | } |
| 2709 | _incomingVideoSourcesUpdated(allSources); |
| 2710 | } |
| 2711 | } |
| 2712 | } |
| 2713 | } |
| 2714 |
| 2715 | void onTrackRemoved(rtc::scoped_refptr<webrtc::RtpReceiverInterface> receiver) { |
| 2716 | for (auto &transceiver : _peerConnection->GetTransceivers()) { |
| 2717 | if (transceiver->media_type() == cricket::MediaType::MEDIA_TYPE_VIDEO) { |
| 2718 | if (receiver.get() == transceiver->receiver().get()) { |
| 2719 | auto remoteVideoTrack = static_cast<webrtc::VideoTrackInterface *>(transceiver->receiver()->track().get()); |
| 2720 |
| 2721 | for (auto &it : _remoteVideoTracks) { |
| 2722 | if (it.second.get() == remoteVideoTrack) { |
| 2723 | auto sink = _remoteVideoTrackSinks.find(it.first); |
| 2724 | if (sink != _remoteVideoTrackSinks.end()) { |
| 2725 | remoteVideoTrack->RemoveSink(sink->second.get()); |
| 2726 | _remoteVideoTrackSinks.erase(it.first); |
| 2727 | } |
| 2728 | _remoteVideoTracks.erase(it.first); |
| 2729 |
| 2730 | if (_incomingVideoSourcesUpdated) { |
| 2731 | std::vector<uint32_t> allSources; |
| 2732 | for (auto &it : _remoteVideoTracks) { |
| 2733 | allSources.push_back(it.first); |
| 2734 | } |
| 2735 | _incomingVideoSourcesUpdated(allSources); |
| 2736 | } |
| 2737 |
| 2738 | break; |
| 2739 | } |
| 2740 | } |
| 2741 |
| 2742 | break; |
| 2743 | } |
| 2744 | } |
| 2745 | } |
| 2746 | } |
| 2747 |
| 2748 | void onMissingSsrc(uint32_t ssrc) { |
| 2749 | /*if (_processedMissingSsrcs.find(ssrc) == _processedMissingSsrcs.end()) { |
| 2750 | _processedMissingSsrcs.insert(ssrc); |
| 2751 |
| 2752 | _missingSsrcQueue.insert(ssrc); |
| 2753 | if (!_isProcessingMissingSsrcs) { |
| 2754 | beginProcessingMissingSsrcs(); |
| 2755 | } |
| 2756 | }*/ |
| 2757 | } |
| 2758 |
| 2759 | void beginProcessingMissingSsrcs() { |
| 2760 | if (_isProcessingMissingSsrcs) { |
| 2761 | return; |
| 2762 | } |
| 2763 | _isProcessingMissingSsrcs = true; |
| 2764 | auto timestamp = rtc::TimeMillis(); |
| 2765 | if (timestamp > _missingSsrcsProcessedTimestamp + 200) { |
| 2766 | applyMissingSsrcs(); |
| 2767 | } else { |
| 2768 | const auto weak = std::weak_ptr<GroupInstanceManager>(shared_from_this()); |
| 2769 | StaticThreads::getMediaThread()->PostDelayedTask(RTC_FROM_HERE, [weak]() { |
| 2770 | auto strong = weak.lock(); |
| 2771 | if (!strong) { |
| 2772 | return; |
| 2773 | } |
| 2774 | strong->applyMissingSsrcs(); |
| 2775 | }, 200); |
| 2776 | } |
| 2777 | } |
| 2778 |
| 2779 | void applyMissingSsrcs() { |
| 2780 | assert(_isProcessingMissingSsrcs); |
| 2781 | if (_missingSsrcQueue.size() == 0) { |
| 2782 | completeProcessingMissingSsrcs(); |
| 2783 | return; |
| 2784 | } |
| 2785 |
| 2786 | std::vector<GroupParticipantDescription> addParticipants; |
| 2787 | for (auto ssrc : _missingSsrcQueue) { |
| 2788 | GroupParticipantDescription participant; |
| 2789 | participant.audioSsrc = ssrc; |
| 2790 | addParticipants.push_back(participant); |
| 2791 | } |
| 2792 | _missingSsrcQueue.clear(); |
| 2793 |
| 2794 | const auto weak = std::weak_ptr<GroupInstanceManager>(shared_from_this()); |
| 2795 |
| 2796 | addParticipantsInternal(addParticipants, true); |
| 2797 | } |
| 2798 |
| 2799 | void completeProcessingMissingSsrcs() { |
| 2800 | assert(_isProcessingMissingSsrcs); |
| 2801 | _isProcessingMissingSsrcs = false; |
| 2802 | _missingSsrcsProcessedTimestamp = rtc::TimeMillis(); |
| 2803 |
| 2804 | if (_missingSsrcQueue.size() != 0) { |
| 2805 | beginProcessingMissingSsrcs(); |
| 2806 | } |
| 2807 | } |
| 2808 |
| 2809 | void completedInitialSetup() { |
| 2810 | //beginDebugSsrcTimer(1000); |
| 2811 | } |
| 2812 |
| 2813 | uint32_t _nextTestSsrc = 100; |
| 2814 |
| 2815 | void beginDebugSsrcTimer(int timeout) { |
| 2816 | const auto weak = std::weak_ptr<GroupInstanceManager>(shared_from_this()); |
| 2817 | StaticThreads::getMediaThread()->PostDelayedTask(RTC_FROM_HERE, [weak]() { |
| 2818 | auto strong = weak.lock(); |
| 2819 | if (!strong) { |
| 2820 | return; |
| 2821 | } |
| 2822 |
| 2823 | if (strong->_nextTestSsrc >= 100 + 50) { |
| 2824 | return; |
| 2825 | } |
| 2826 |
| 2827 | strong->_nextTestSsrc++; |
| 2828 | strong->onMissingSsrc(strong->_nextTestSsrc); |
| 2829 |
| 2830 | strong->beginDebugSsrcTimer(20); |
| 2831 | }, timeout); |
| 2832 | } |
| 2833 |
| 2834 | void setIsMuted(bool isMuted) { |
| 2835 | if (!_localAudioTrackSender) { |
| 2836 | return; |
| 2837 | } |
| 2838 | if (_isMuted == isMuted) { |
| 2839 | return; |
| 2840 | } |
| 2841 |
| 2842 | for (auto &it : _peerConnection->GetTransceivers()) { |
| 2843 | if (it->media_type() == cricket::MediaType::MEDIA_TYPE_AUDIO) { |
| 2844 | if (_localAudioTrackSender.get() == it->sender().get()) { |
| 2845 | if (isMuted) { |
| 2846 | } else { |
| 2847 | if (it->direction() != webrtc::RtpTransceiverDirection::kSendOnly) { |
| 2848 | const auto error = it->SetDirectionWithError(webrtc::RtpTransceiverDirection::kSendOnly); |
| 2849 | (void)error; |
| 2850 |
| 2851 | applyLocalSdp(); |
| 2852 | } |
| 2853 | } |
| 2854 | break; |
| 2855 | } |
| 2856 | } |
| 2857 | } |
| 2858 |
| 2859 | _isMuted = isMuted; |
| 2860 | _localAudioTrack->set_enabled(!isMuted); |
| 2861 |
| 2862 | RTC_LOG(LoggingSeverity::WARNING) << "setIsMuted: " << isMuted; |
| 2863 | } |
| 2864 |
| 2865 | void setVideoCapture(std::shared_ptr<VideoCaptureInterface> videoCapture, std::function<void(GroupJoinPayload)> completion) { |
| 2866 | _videoCapture = videoCapture; |
| 2867 |
| 2868 | updateVideoTrack(true, completion); |
| 2869 | } |
| 2870 |
| 2871 | void updateVideoTrack(bool applyNow, std::function<void(GroupJoinPayload)> completion) { |
| 2872 | if (_videoCapture) { |
| 2873 | VideoCaptureInterfaceObject *videoCaptureImpl = GetVideoCaptureAssumingSameThread(_videoCapture.get()); |
| 2874 |
| 2875 | //_videoCapture->setPreferredAspectRatio(1280.0f / 720.0f); |
| 2876 |
| 2877 | _localVideoTrack = _nativeFactory->CreateVideoTrack("video0", videoCaptureImpl->source()); |
| 2878 | _localVideoTrack->set_enabled(true); |
| 2879 | webrtc::RtpTransceiverInit videoInit; |
| 2880 | auto addedTransceiver = _peerConnection->AddTransceiver(_localVideoTrack, videoInit); |
| 2881 | if (addedTransceiver.ok()) { |
| 2882 | _localVideoTrackTransceiver = addedTransceiver.value(); |
| 2883 | for (auto &it : _peerConnection->GetTransceivers()) { |
| 2884 | if (it->media_type() == cricket::MediaType::MEDIA_TYPE_VIDEO) { |
| 2885 | if (_localVideoTrackTransceiver->sender().get() == it->sender().get()) { |
| 2886 | it->SetDirectionWithError(webrtc::RtpTransceiverDirection::kSendOnly); |
| 2887 |
| 2888 | auto capabilities = _nativeFactory->GetRtpSenderCapabilities( |
| 2889 | cricket::MediaType::MEDIA_TYPE_VIDEO); |
| 2890 |
| 2891 | std::vector<webrtc::RtpCodecCapability> codecs; |
| 2892 | bool hasVP8 = false; |
| 2893 | for (auto &codec : capabilities.codecs) { |
| 2894 | if (codec.name == cricket::kVp8CodecName) { |
| 2895 | if (!hasVP8) { |
| 2896 | codecs.insert(codecs.begin(), codec); |
| 2897 | hasVP8 = true; |
| 2898 | } |
| 2899 | } else if (codec.name == cricket::kRtxCodecName) { |
| 2900 | codecs.push_back(codec); |
| 2901 | } |
| 2902 | } |
| 2903 | it->SetCodecPreferences(codecs); |
| 2904 |
| 2905 | break; |
| 2906 | } |
| 2907 | } |
| 2908 | } |
| 2909 | } |
| 2910 | } else if (_localVideoTrack && _localVideoTrackTransceiver) { |
| 2911 | _localVideoTrack->set_enabled(false); |
| 2912 | _localVideoTrackTransceiver->SetDirectionWithError(webrtc::RtpTransceiverDirection::kInactive); |
| 2913 | for (auto &it : _peerConnection->GetTransceivers()) { |
| 2914 | if (it.get() == _localVideoTrackTransceiver.get()) { |
| 2915 | _peerConnection->RemoveTrack(it->sender()); |
| 2916 | break; |
| 2917 | } |
| 2918 | } |
| 2919 | _localVideoTrack = nullptr; |
| 2920 | _localVideoTrackTransceiver = nullptr; |
| 2921 | } |
| 2922 |
| 2923 | if (applyNow) { |
| 2924 | const auto weak = std::weak_ptr<GroupInstanceManager>(shared_from_this()); |
| 2925 | emitJoinPayload([weak, completion](auto result) { |
| 2926 | auto strong = weak.lock(); |
| 2927 | if (!strong) { |
| 2928 | return; |
| 2929 | } |
| 2930 |
| 2931 | if (!strong->_joinPayload) { |
| 2932 | return; |
| 2933 | } |
| 2934 | if (!strong->_joinResponsePayload) { |
| 2935 | return; |
| 2936 | } |
| 2937 |
| 2938 | auto sdp = parseJoinResponseIntoSdp(strong->_sessionId, strong->_joinPayload.value(), strong->_joinResponsePayload.value(), SdpType::kSdpTypeJoinAnswer, strong->_allOtherParticipants, strong->_localVideoMid, strong->_localDataChannelMid, strong->_bundleStreamsState); |
| 2939 | strong->setOfferSdp(sdp, false, true, false); |
| 2940 |
| 2941 | completion(result); |
| 2942 | }); |
| 2943 | } |
| 2944 | } |
| 2945 |
| 2946 | void emitAnswer(bool completeMissingSsrcSetup) { |
| 2947 | const auto weak = std::weak_ptr<GroupInstanceManager>(shared_from_this()); |
| 2948 |
| 2949 | webrtc::PeerConnectionInterface::RTCOfferAnswerOptions options; |
| 2950 | rtc::scoped_refptr<CreateSessionDescriptionObserverImpl> observer(new rtc::RefCountedObject<CreateSessionDescriptionObserverImpl>([weak, completeMissingSsrcSetup](std::string sdp, std::string type) { |
| 2951 | StaticThreads::getMediaThread()->PostTask(RTC_FROM_HERE, [weak, sdp, type, completeMissingSsrcSetup](){ |
| 2952 | auto strong = weak.lock(); |
| 2953 | if (!strong) { |
| 2954 | return; |
| 2955 | } |
| 2956 |
| 2957 | RTC_LOG(LoggingSeverity::WARNING) << "----- setLocalDescription answer -----"; |
| 2958 | RTC_LOG(LoggingSeverity::WARNING) << sdp; |
| 2959 | RTC_LOG(LoggingSeverity::WARNING) << "-----"; |
| 2960 |
| 2961 | webrtc::SdpParseError error; |
| 2962 | webrtc::SessionDescriptionInterface *sessionDescription = webrtc::CreateSessionDescription(type, adjustLocalDescription(sdp), &error); |
| 2963 | if (sessionDescription != nullptr) { |
| 2964 | rtc::scoped_refptr<SetSessionDescriptionObserverImpl> observer(new rtc::RefCountedObject<SetSessionDescriptionObserverImpl>([weak, sdp, completeMissingSsrcSetup]() { |
| 2965 | auto strong = weak.lock(); |
| 2966 | if (!strong) { |
| 2967 | return; |
| 2968 | } |
| 2969 |
| 2970 | if (completeMissingSsrcSetup) { |
| 2971 | strong->completeProcessingMissingSsrcs(); |
| 2972 | } |
| 2973 | }, [weak, completeMissingSsrcSetup](webrtc::RTCError error) { |
| 2974 | auto strong = weak.lock(); |
| 2975 | if (!strong) { |
| 2976 | return; |
| 2977 | } |
| 2978 |
| 2979 | if (completeMissingSsrcSetup) { |
| 2980 | strong->completeProcessingMissingSsrcs(); |
| 2981 | } |
| 2982 | })); |
| 2983 | strong->_peerConnection->SetLocalDescription(observer, sessionDescription); |
| 2984 | } else { |
| 2985 | if (completeMissingSsrcSetup) { |
| 2986 | strong->completeProcessingMissingSsrcs(); |
| 2987 | } |
| 2988 | } |
| 2989 | }); |
| 2990 | })); |
| 2991 | _peerConnection->CreateAnswer(observer, options); |
| 2992 | } |
| 2993 |
| 2994 | bool setVideoConstraint(uint32_t ssrc, bool highQuality, bool updateImmediately) { |
| 2995 | auto current = _videoConstraints.find(ssrc); |
| 2996 | bool updated = false; |
| 2997 | if (current != _videoConstraints.end()) { |
| 2998 | updated = current->second != highQuality; |
| 2999 | } else { |
| 3000 | updated = true; |
| 3001 | } |
| 3002 |
| 3003 | if (updated) { |
| 3004 | _videoConstraints[ssrc] = highQuality; |
| 3005 |
| 3006 | if (updateImmediately) { |
| 3007 | updateRemoteVideoConstaints(); |
| 3008 | } |
| 3009 | } |
| 3010 | return updated; |
| 3011 | } |
| 3012 |
| 3013 | void updateRemoteVideoConstaints() { |
| 3014 | if (!_localDataChannelIsOpen) { |
| 3015 | return; |
| 3016 | } |
| 3017 |
| 3018 | std::vector<uint32_t> keys; |
| 3019 | for (auto &it : _videoConstraints) { |
| 3020 | keys.push_back(it.first); |
| 3021 | } |
| 3022 | std::sort(keys.begin(), keys.end()); |
| 3023 |
| 3024 | std::string pinnedEndpoint; |
| 3025 |
| 3026 | std::ostringstream string; |
| 3027 | string << "{" << "\n"; |
| 3028 | string << " \"colibriClass\": \"ReceiverVideoConstraintsChangedEvent\"," << "\n"; |
| 3029 | string << " \"videoConstraints\": [" << "\n"; |
| 3030 | bool isFirst = true; |
| 3031 | for (size_t i = 0; i < keys.size(); i++) { |
| 3032 | auto it = _videoConstraints.find(keys[i]); |
| 3033 | int idealHeight = 720; |
| 3034 | if (!it->second) { |
| 3035 | idealHeight = 180; |
| 3036 | } |
| 3037 |
| 3038 | std::string endpointId; |
| 3039 | for (auto &participant : _allOtherParticipants) { |
| 3040 | if (participant.isRemoved) { |
| 3041 | continue; |
| 3042 | } |
| 3043 | if (participant.audioSsrc == keys[i]) { |
| 3044 | endpointId = participant.endpointId; |
| 3045 | break; |
| 3046 | } |
| 3047 | } |
| 3048 |
| 3049 | if (endpointId.size() == 0) { |
| 3050 | continue; |
| 3051 | } |
| 3052 |
| 3053 | if (isFirst) { |
| 3054 | isFirst = false; |
| 3055 | } else { |
| 3056 | if (i != 0) { |
| 3057 | string << ","; |
| 3058 | } |
| 3059 | } |
| 3060 | string << " {\n"; |
| 3061 | string << " \"id\": \"" << endpointId << "\",\n"; |
| 3062 | string << " \"idealHeight\": " << idealHeight << "\n"; |
| 3063 | string << " }"; |
| 3064 | string << "\n"; |
| 3065 | } |
| 3066 | string << " ]" << "\n"; |
| 3067 | string << "}"; |
| 3068 |
| 3069 | std::string result = string.str(); |
| 3070 | RTC_LOG(LS_INFO) << "DataChannel send message: " << result; |
| 3071 |
| 3072 | webrtc::DataBuffer buffer(result, false); |
| 3073 | _localDataChannel->Send(buffer); |
| 3074 |
| 3075 | /*if (pinnedEndpoint.size() != 0) { |
| 3076 | std::ostringstream string; |
| 3077 | string << "{" << "\n"; |
| 3078 | string << " \"colibriClass\": \"PinnedEndpointChangedEvent\"," << "\n"; |
| 3079 | string << " \"pinnedEndpoint\": \"" << pinnedEndpoint << "\"" << "\n"; |
| 3080 | string << "}"; |
| 3081 |
| 3082 | std::string result = string.str(); |
| 3083 |
| 3084 | RTC_LOG(LS_INFO) << "DataChannel send message: " << result; |
| 3085 |
| 3086 | webrtc::DataBuffer buffer(result, false); |
| 3087 | _localDataChannel->Send(buffer); |
| 3088 | }*/ |
| 3089 | } |
| 3090 |
| 3091 | private: |
| 3092 | void withAudioDeviceModule(std::function<void(webrtc::AudioDeviceModule*)> callback) { |
| 3093 | _adm_thread->Invoke<void>(RTC_FROM_HERE, [&] { |
| 3094 | callback(_adm_use_withAudioDeviceModule.get()); |
| 3095 | }); |
| 3096 | } |
| 3097 |
| 3098 | std::function<void(bool)> _networkStateUpdated; |
| 3099 | std::function<void(GroupLevelsUpdate const &)> _audioLevelsUpdated; |
| 3100 | std::function<void(std::vector<uint32_t> const &)> _incomingVideoSourcesUpdated; |
| 3101 | std::function<void(std::vector<uint32_t> const &)> _participantDescriptionsRequired; |
| 3102 |
| 3103 | int32_t _myAudioLevelPeakCount = 0; |
| 3104 | float _myAudioLevelPeak = 0; |
| 3105 | GroupLevelValue _myAudioLevel; |
| 3106 |
| 3107 | std::string _initialInputDeviceId; |
| 3108 | std::string _initialOutputDeviceId; |
| 3109 |
| 3110 | uint32_t _sessionId = 6543245; |
| 3111 | uint32_t _mainStreamAudioSsrc = 0; |
| 3112 | absl::optional<GroupJoinPayload> _joinPayload; |
| 3113 | uint32_t _fakeIncomingSsrc = 0; |
| 3114 | absl::optional<GroupJoinResponsePayload> _joinResponsePayload; |
| 3115 |
| 3116 | int64_t _appliedOfferTimestamp = 0; |
| 3117 | bool _isConnected = false; |
| 3118 | int _isConnectedUpdateValidTaskId = 0; |
| 3119 |
| 3120 | bool _isMuted = true; |
| 3121 |
| 3122 | std::vector<GroupParticipantDescription> _allOtherParticipants; |
| 3123 | std::set<uint32_t> _processedMissingSsrcs; |
| 3124 |
| 3125 | int64_t _missingSsrcsProcessedTimestamp = 0; |
| 3126 | bool _isProcessingMissingSsrcs = false; |
| 3127 | std::set<uint32_t> _missingSsrcQueue; |
| 3128 |
| 3129 | std::string _appliedRemoteDescription; |
| 3130 |
| 3131 | rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> _nativeFactory; |
| 3132 | std::unique_ptr<PeerConnectionObserverImpl> _observer; |
| 3133 | rtc::scoped_refptr<webrtc::PeerConnectionInterface> _peerConnection; |
| 3134 | std::unique_ptr<AudioTrackSinkInterfaceImpl> _localAudioTrackSink; |
| 3135 | rtc::scoped_refptr<webrtc::AudioTrackInterface> _localAudioTrack; |
| 3136 | rtc::scoped_refptr<webrtc::RtpSenderInterface> _localAudioTrackSender; |
| 3137 |
| 3138 | rtc::scoped_refptr<webrtc::VideoTrackInterface> _localVideoTrack; |
| 3139 | rtc::scoped_refptr<webrtc::RtpTransceiverInterface> _localVideoTrackTransceiver; |
| 3140 |
| 3141 | rtc::scoped_refptr<webrtc::DataChannelInterface> _localDataChannel; |
| 3142 | absl::optional<std::string> _localDataChannelMid; |
| 3143 | std::unique_ptr<DataChannelObserverImpl> _localDataChannelObserver; |
| 3144 | bool _localDataChannelIsOpen = false; |
| 3145 |
| 3146 | absl::optional<std::string> _localVideoMid; |
| 3147 |
| 3148 | std::vector<StreamSpec> _bundleStreamsState; |
| 3149 |
| 3150 | std::function<rtc::scoped_refptr<webrtc::AudioDeviceModule>(webrtc::TaskQueueFactory*)> _createAudioDeviceModule; |
| 3151 | rtc::Thread *_adm_thread = nullptr; |
| 3152 | rtc::scoped_refptr<webrtc::AudioDeviceModule> _adm_use_withAudioDeviceModule; |
| 3153 |
| 3154 | std::map<uint32_t, rtc::scoped_refptr<webrtc::AudioTrackInterface>> _audioTracks; |
| 3155 | std::map<uint32_t, double> _audioTrackVolumes; |
| 3156 | std::map<uint32_t, std::shared_ptr<AudioTrackSinkInterfaceImpl>> _audioTrackSinks; |
| 3157 | std::map<uint32_t, GroupLevelValue> _audioLevels; |
| 3158 |
| 3159 | std::map<uint32_t, bool> _videoConstraints; |
| 3160 | uint32_t _currentFullSizeVideoSsrc = 0; |
| 3161 |
| 3162 | bool _debugQualityValue = false; |
| 3163 |
| 3164 | std::map<uint32_t, rtc::scoped_refptr<webrtc::VideoTrackInterface>> _remoteVideoTracks; |
| 3165 | std::map<uint32_t, std::unique_ptr<CustomVideoSinkInterfaceProxyImpl>> _remoteVideoTrackSinks; |
| 3166 |
| 3167 | std::shared_ptr<VideoCaptureInterface> _videoCapture; |
| 3168 |
| 3169 | std::unique_ptr<ErrorParsingLogSink> _errorParsingLogSink; |
| 3170 |
| 3171 | std::shared_ptr<PlatformContext> _platformContext; |
| 3172 | }; |
| 3173 |
| 3174 | GroupInstanceImpl::GroupInstanceImpl(GroupInstanceDescriptor &&descriptor) |
| 3175 | : _logSink(std::make_unique<LogSinkImpl>(descriptor.config.logPath)) { |
| 3176 | rtc::LogMessage::LogToDebug(rtc::LS_INFO); |
| 3177 | rtc::LogMessage::SetLogToStderr(true); |
| 3178 | if (_logSink) { |
| 3179 | rtc::LogMessage::AddLogToStream(_logSink.get(), rtc::LS_INFO); |
| 3180 | } |
| 3181 |
| 3182 | _manager.reset(new ThreadLocalObject<GroupInstanceManager>(StaticThreads::getMediaThread(), [descriptor = std::move(descriptor)]() mutable { |
| 3183 | return new GroupInstanceManager(std::move(descriptor)); |
| 3184 | })); |
| 3185 | _manager->perform(RTC_FROM_HERE, [](GroupInstanceManager *manager) { |
| 3186 | manager->start(); |
| 3187 | }); |
| 3188 | } |
| 3189 |
| 3190 | GroupInstanceImpl::~GroupInstanceImpl() { |
| 3191 | if (_logSink) { |
| 3192 | rtc::LogMessage::RemoveLogToStream(_logSink.get()); |
| 3193 | } |
| 3194 | _manager = nullptr; |
| 3195 |
| 3196 | // Wait until _manager is destroyed, otherwise there is a race condition |
| 3197 | // in destruction of PeerConnection on media thread and network thread. |
| 3198 | StaticThreads::getMediaThread()->Invoke<void>(RTC_FROM_HERE, [] {}); |
| 3199 | } |
| 3200 |
| 3201 | void GroupInstanceImpl::stop() { |
| 3202 | _manager->perform(RTC_FROM_HERE, [](GroupInstanceManager *manager) { |
| 3203 | manager->stop(); |
| 3204 | }); |
| 3205 | } |
| 3206 |
| 3207 | void GroupInstanceImpl::emitJoinPayload(std::function<void(GroupJoinPayload)> completion) { |
| 3208 | _manager->perform(RTC_FROM_HERE, [completion](GroupInstanceManager *manager) { |
| 3209 | manager->emitJoinPayload(completion); |
| 3210 | }); |
| 3211 | } |
| 3212 |
| 3213 | void GroupInstanceImpl::setJoinResponsePayload(GroupJoinResponsePayload payload, std::vector<tgcalls::GroupParticipantDescription> &&participants) { |
| 3214 | _manager->perform(RTC_FROM_HERE, [payload, participants = std::move(participants)](GroupInstanceManager *manager) mutable { |
| 3215 | manager->setJoinResponsePayload(payload, std::move(participants)); |
| 3216 | }); |
| 3217 | } |
| 3218 |
| 3219 | void GroupInstanceImpl::removeSsrcs(std::vector<uint32_t> ssrcs) { |
| 3220 | _manager->perform(RTC_FROM_HERE, [ssrcs](GroupInstanceManager *manager) { |
| 3221 | manager->removeSsrcs(ssrcs); |
| 3222 | }); |
| 3223 | } |
| 3224 |
| 3225 | void GroupInstanceImpl::addParticipants(std::vector<GroupParticipantDescription> &&participants) { |
| 3226 | _manager->perform(RTC_FROM_HERE, [participants = std::move(participants)](GroupInstanceManager *manager) mutable { |
| 3227 | manager->addParticipants(std::move(participants)); |
| 3228 | }); |
| 3229 | } |
| 3230 |
| 3231 | void GroupInstanceImpl::setIsMuted(bool isMuted) { |
| 3232 | _manager->perform(RTC_FROM_HERE, [isMuted](GroupInstanceManager *manager) { |
| 3233 | manager->setIsMuted(isMuted); |
| 3234 | }); |
| 3235 | } |
| 3236 |
| 3237 | void GroupInstanceImpl::setVideoCapture(std::shared_ptr<VideoCaptureInterface> videoCapture, std::function<void(GroupJoinPayload)> completion) { |
| 3238 | _manager->perform(RTC_FROM_HERE, [videoCapture, completion = std::move(completion)](GroupInstanceManager *manager) mutable { |
| 3239 | manager->setVideoCapture(videoCapture, completion); |
| 3240 | }); |
| 3241 | } |
| 3242 |
| 3243 | void GroupInstanceImpl::setAudioInputDevice(std::string id) { |
| 3244 | _manager->perform(RTC_FROM_HERE, [id](GroupInstanceManager *manager) { |
| 3245 | manager->setAudioInputDevice(id); |
| 3246 | }); |
| 3247 | } |
| 3248 |
| 3249 | void GroupInstanceImpl::setAudioOutputDevice(std::string id) { |
| 3250 | _manager->perform(RTC_FROM_HERE, [id](GroupInstanceManager *manager) { |
| 3251 | manager->setAudioOutputDevice(id); |
| 3252 | }); |
| 3253 | } |
| 3254 |
| 3255 | void GroupInstanceImpl::addIncomingVideoOutput(uint32_t ssrc, std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) { |
| 3256 | _manager->perform(RTC_FROM_HERE, [ssrc, sink](GroupInstanceManager *manager) { |
| 3257 | manager->addIncomingVideoOutput(ssrc, sink); |
| 3258 | }); |
| 3259 | } |
| 3260 |
| 3261 | void GroupInstanceImpl::setVolume(uint32_t ssrc, double volume) { |
| 3262 | _manager->perform(RTC_FROM_HERE, [ssrc, volume](GroupInstanceManager *manager) { |
| 3263 | manager->setVolume(ssrc, volume); |
| 3264 | }); |
| 3265 | } |
| 3266 |
| 3267 | void GroupInstanceImpl::setFullSizeVideoSsrc(uint32_t ssrc) { |
| 3268 | _manager->perform(RTC_FROM_HERE, [ssrc](GroupInstanceManager *manager) { |
| 3269 | manager->setFullSizeVideoSsrc(ssrc); |
| 3270 | }); |
| 3271 | } |
| 3272 |
| 3273 | } // namespace tgcalls |
| 3274 |