| OLD | NEW |
| (Empty) |
| 1 /* | |
| 2 * Copyright 2012 The WebRTC project authors. All Rights Reserved. | |
| 3 * | |
| 4 * Use of this source code is governed by a BSD-style license | |
| 5 * that can be found in the LICENSE file in the root of the source | |
| 6 * tree. An additional intellectual property rights grant can be found | |
| 7 * in the file PATENTS. All contributing project authors may | |
| 8 * be found in the AUTHORS file in the root of the source tree. | |
| 9 */ | |
| 10 | |
| 11 #include "webrtc/api/peerconnection.h" | |
| 12 | |
| 13 #include <algorithm> | |
| 14 #include <cctype> // for isdigit | |
| 15 #include <utility> | |
| 16 #include <vector> | |
| 17 | |
| 18 #include "webrtc/api/audiotrack.h" | |
| 19 #include "webrtc/api/dtmfsender.h" | |
| 20 #include "webrtc/api/jsepicecandidate.h" | |
| 21 #include "webrtc/api/jsepsessiondescription.h" | |
| 22 #include "webrtc/api/mediaconstraintsinterface.h" | |
| 23 #include "webrtc/api/mediastream.h" | |
| 24 #include "webrtc/api/mediastreamobserver.h" | |
| 25 #include "webrtc/api/mediastreamproxy.h" | |
| 26 #include "webrtc/api/mediastreamtrackproxy.h" | |
| 27 #include "webrtc/api/remoteaudiosource.h" | |
| 28 #include "webrtc/api/rtpreceiver.h" | |
| 29 #include "webrtc/api/rtpsender.h" | |
| 30 #include "webrtc/api/streamcollection.h" | |
| 31 #include "webrtc/api/videocapturertracksource.h" | |
| 32 #include "webrtc/api/videotrack.h" | |
| 33 #include "webrtc/base/arraysize.h" | |
| 34 #include "webrtc/base/bind.h" | |
| 35 #include "webrtc/base/logging.h" | |
| 36 #include "webrtc/base/stringencode.h" | |
| 37 #include "webrtc/base/stringutils.h" | |
| 38 #include "webrtc/base/trace_event.h" | |
| 39 #include "webrtc/call/call.h" | |
| 40 #include "webrtc/logging/rtc_event_log/rtc_event_log.h" | |
| 41 #include "webrtc/media/sctp/sctpdataengine.h" | |
| 42 #include "webrtc/pc/channelmanager.h" | |
| 43 #include "webrtc/system_wrappers/include/clock.h" | |
| 44 #include "webrtc/system_wrappers/include/field_trial.h" | |
| 45 | |
| 46 namespace { | |
| 47 | |
| 48 using webrtc::DataChannel; | |
| 49 using webrtc::MediaConstraintsInterface; | |
| 50 using webrtc::MediaStreamInterface; | |
| 51 using webrtc::PeerConnectionInterface; | |
| 52 using webrtc::RtpSenderInternal; | |
| 53 using webrtc::RtpSenderInterface; | |
| 54 using webrtc::RtpSenderProxy; | |
| 55 using webrtc::RtpSenderProxyWithInternal; | |
| 56 using webrtc::StreamCollection; | |
| 57 | |
| 58 static const char kDefaultStreamLabel[] = "default"; | |
| 59 static const char kDefaultAudioTrackLabel[] = "defaulta0"; | |
| 60 static const char kDefaultVideoTrackLabel[] = "defaultv0"; | |
| 61 | |
| 62 // The min number of tokens must present in Turn host uri. | |
| 63 // e.g. user@turn.example.org | |
| 64 static const size_t kTurnHostTokensNum = 2; | |
| 65 // Number of tokens must be preset when TURN uri has transport param. | |
| 66 static const size_t kTurnTransportTokensNum = 2; | |
| 67 // The default stun port. | |
| 68 static const int kDefaultStunPort = 3478; | |
| 69 static const int kDefaultStunTlsPort = 5349; | |
| 70 static const char kTransport[] = "transport"; | |
| 71 | |
| 72 // NOTE: Must be in the same order as the ServiceType enum. | |
| 73 static const char* kValidIceServiceTypes[] = {"stun", "stuns", "turn", "turns"}; | |
| 74 | |
| 75 // The length of RTCP CNAMEs. | |
| 76 static const int kRtcpCnameLength = 16; | |
| 77 | |
| 78 // NOTE: A loop below assumes that the first value of this enum is 0 and all | |
| 79 // other values are incremental. | |
| 80 enum ServiceType { | |
| 81 STUN = 0, // Indicates a STUN server. | |
| 82 STUNS, // Indicates a STUN server used with a TLS session. | |
| 83 TURN, // Indicates a TURN server | |
| 84 TURNS, // Indicates a TURN server used with a TLS session. | |
| 85 INVALID, // Unknown. | |
| 86 }; | |
| 87 static_assert(INVALID == arraysize(kValidIceServiceTypes), | |
| 88 "kValidIceServiceTypes must have as many strings as ServiceType " | |
| 89 "has values."); | |
| 90 | |
| 91 enum { | |
| 92 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0, | |
| 93 MSG_SET_SESSIONDESCRIPTION_FAILED, | |
| 94 MSG_CREATE_SESSIONDESCRIPTION_FAILED, | |
| 95 MSG_GETSTATS, | |
| 96 MSG_FREE_DATACHANNELS, | |
| 97 }; | |
| 98 | |
| 99 struct SetSessionDescriptionMsg : public rtc::MessageData { | |
| 100 explicit SetSessionDescriptionMsg( | |
| 101 webrtc::SetSessionDescriptionObserver* observer) | |
| 102 : observer(observer) { | |
| 103 } | |
| 104 | |
| 105 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer; | |
| 106 std::string error; | |
| 107 }; | |
| 108 | |
| 109 struct CreateSessionDescriptionMsg : public rtc::MessageData { | |
| 110 explicit CreateSessionDescriptionMsg( | |
| 111 webrtc::CreateSessionDescriptionObserver* observer) | |
| 112 : observer(observer) {} | |
| 113 | |
| 114 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer; | |
| 115 std::string error; | |
| 116 }; | |
| 117 | |
| 118 struct GetStatsMsg : public rtc::MessageData { | |
| 119 GetStatsMsg(webrtc::StatsObserver* observer, | |
| 120 webrtc::MediaStreamTrackInterface* track) | |
| 121 : observer(observer), track(track) { | |
| 122 } | |
| 123 rtc::scoped_refptr<webrtc::StatsObserver> observer; | |
| 124 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track; | |
| 125 }; | |
| 126 | |
| 127 // |in_str| should be of format | |
| 128 // stunURI = scheme ":" stun-host [ ":" stun-port ] | |
| 129 // scheme = "stun" / "stuns" | |
| 130 // stun-host = IP-literal / IPv4address / reg-name | |
| 131 // stun-port = *DIGIT | |
| 132 // | |
| 133 // draft-petithuguenin-behave-turn-uris-01 | |
| 134 // turnURI = scheme ":" turn-host [ ":" turn-port ] | |
| 135 // turn-host = username@IP-literal / IPv4address / reg-name | |
| 136 bool GetServiceTypeAndHostnameFromUri(const std::string& in_str, | |
| 137 ServiceType* service_type, | |
| 138 std::string* hostname) { | |
| 139 const std::string::size_type colonpos = in_str.find(':'); | |
| 140 if (colonpos == std::string::npos) { | |
| 141 LOG(LS_WARNING) << "Missing ':' in ICE URI: " << in_str; | |
| 142 return false; | |
| 143 } | |
| 144 if ((colonpos + 1) == in_str.length()) { | |
| 145 LOG(LS_WARNING) << "Empty hostname in ICE URI: " << in_str; | |
| 146 return false; | |
| 147 } | |
| 148 *service_type = INVALID; | |
| 149 for (size_t i = 0; i < arraysize(kValidIceServiceTypes); ++i) { | |
| 150 if (in_str.compare(0, colonpos, kValidIceServiceTypes[i]) == 0) { | |
| 151 *service_type = static_cast<ServiceType>(i); | |
| 152 break; | |
| 153 } | |
| 154 } | |
| 155 if (*service_type == INVALID) { | |
| 156 return false; | |
| 157 } | |
| 158 *hostname = in_str.substr(colonpos + 1, std::string::npos); | |
| 159 return true; | |
| 160 } | |
| 161 | |
| 162 bool ParsePort(const std::string& in_str, int* port) { | |
| 163 // Make sure port only contains digits. FromString doesn't check this. | |
| 164 for (const char& c : in_str) { | |
| 165 if (!std::isdigit(c)) { | |
| 166 return false; | |
| 167 } | |
| 168 } | |
| 169 return rtc::FromString(in_str, port); | |
| 170 } | |
| 171 | |
| 172 // This method parses IPv6 and IPv4 literal strings, along with hostnames in | |
| 173 // standard hostname:port format. | |
| 174 // Consider following formats as correct. | |
| 175 // |hostname:port|, |[IPV6 address]:port|, |IPv4 address|:port, | |
| 176 // |hostname|, |[IPv6 address]|, |IPv4 address|. | |
| 177 bool ParseHostnameAndPortFromString(const std::string& in_str, | |
| 178 std::string* host, | |
| 179 int* port) { | |
| 180 RTC_DCHECK(host->empty()); | |
| 181 if (in_str.at(0) == '[') { | |
| 182 std::string::size_type closebracket = in_str.rfind(']'); | |
| 183 if (closebracket != std::string::npos) { | |
| 184 std::string::size_type colonpos = in_str.find(':', closebracket); | |
| 185 if (std::string::npos != colonpos) { | |
| 186 if (!ParsePort(in_str.substr(closebracket + 2, std::string::npos), | |
| 187 port)) { | |
| 188 return false; | |
| 189 } | |
| 190 } | |
| 191 *host = in_str.substr(1, closebracket - 1); | |
| 192 } else { | |
| 193 return false; | |
| 194 } | |
| 195 } else { | |
| 196 std::string::size_type colonpos = in_str.find(':'); | |
| 197 if (std::string::npos != colonpos) { | |
| 198 if (!ParsePort(in_str.substr(colonpos + 1, std::string::npos), port)) { | |
| 199 return false; | |
| 200 } | |
| 201 *host = in_str.substr(0, colonpos); | |
| 202 } else { | |
| 203 *host = in_str; | |
| 204 } | |
| 205 } | |
| 206 return !host->empty(); | |
| 207 } | |
| 208 | |
| 209 // Adds a STUN or TURN server to the appropriate list, | |
| 210 // by parsing |url| and using the username/password in |server|. | |
| 211 bool ParseIceServerUrl(const PeerConnectionInterface::IceServer& server, | |
| 212 const std::string& url, | |
| 213 cricket::ServerAddresses* stun_servers, | |
| 214 std::vector<cricket::RelayServerConfig>* turn_servers) { | |
| 215 // draft-nandakumar-rtcweb-stun-uri-01 | |
| 216 // stunURI = scheme ":" stun-host [ ":" stun-port ] | |
| 217 // scheme = "stun" / "stuns" | |
| 218 // stun-host = IP-literal / IPv4address / reg-name | |
| 219 // stun-port = *DIGIT | |
| 220 | |
| 221 // draft-petithuguenin-behave-turn-uris-01 | |
| 222 // turnURI = scheme ":" turn-host [ ":" turn-port ] | |
| 223 // [ "?transport=" transport ] | |
| 224 // scheme = "turn" / "turns" | |
| 225 // transport = "udp" / "tcp" / transport-ext | |
| 226 // transport-ext = 1*unreserved | |
| 227 // turn-host = IP-literal / IPv4address / reg-name | |
| 228 // turn-port = *DIGIT | |
| 229 RTC_DCHECK(stun_servers != nullptr); | |
| 230 RTC_DCHECK(turn_servers != nullptr); | |
| 231 std::vector<std::string> tokens; | |
| 232 cricket::ProtocolType turn_transport_type = cricket::PROTO_UDP; | |
| 233 RTC_DCHECK(!url.empty()); | |
| 234 rtc::tokenize(url, '?', &tokens); | |
| 235 std::string uri_without_transport = tokens[0]; | |
| 236 // Let's look into transport= param, if it exists. | |
| 237 if (tokens.size() == kTurnTransportTokensNum) { // ?transport= is present. | |
| 238 std::string uri_transport_param = tokens[1]; | |
| 239 rtc::tokenize(uri_transport_param, '=', &tokens); | |
| 240 if (tokens[0] == kTransport) { | |
| 241 // As per above grammar transport param will be consist of lower case | |
| 242 // letters. | |
| 243 if (!cricket::StringToProto(tokens[1].c_str(), &turn_transport_type) || | |
| 244 (turn_transport_type != cricket::PROTO_UDP && | |
| 245 turn_transport_type != cricket::PROTO_TCP)) { | |
| 246 LOG(LS_WARNING) << "Transport param should always be udp or tcp."; | |
| 247 return false; | |
| 248 } | |
| 249 } | |
| 250 } | |
| 251 | |
| 252 std::string hoststring; | |
| 253 ServiceType service_type; | |
| 254 if (!GetServiceTypeAndHostnameFromUri(uri_without_transport, | |
| 255 &service_type, | |
| 256 &hoststring)) { | |
| 257 LOG(LS_WARNING) << "Invalid transport parameter in ICE URI: " << url; | |
| 258 return false; | |
| 259 } | |
| 260 | |
| 261 // GetServiceTypeAndHostnameFromUri should never give an empty hoststring | |
| 262 RTC_DCHECK(!hoststring.empty()); | |
| 263 | |
| 264 // Let's break hostname. | |
| 265 tokens.clear(); | |
| 266 rtc::tokenize_with_empty_tokens(hoststring, '@', &tokens); | |
| 267 | |
| 268 std::string username(server.username); | |
| 269 if (tokens.size() > kTurnHostTokensNum) { | |
| 270 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring; | |
| 271 return false; | |
| 272 } | |
| 273 if (tokens.size() == kTurnHostTokensNum) { | |
| 274 if (tokens[0].empty() || tokens[1].empty()) { | |
| 275 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring; | |
| 276 return false; | |
| 277 } | |
| 278 username.assign(rtc::s_url_decode(tokens[0])); | |
| 279 hoststring = tokens[1]; | |
| 280 } else { | |
| 281 hoststring = tokens[0]; | |
| 282 } | |
| 283 | |
| 284 int port = kDefaultStunPort; | |
| 285 if (service_type == TURNS) { | |
| 286 port = kDefaultStunTlsPort; | |
| 287 turn_transport_type = cricket::PROTO_TCP; | |
| 288 } | |
| 289 | |
| 290 std::string address; | |
| 291 if (!ParseHostnameAndPortFromString(hoststring, &address, &port)) { | |
| 292 LOG(WARNING) << "Invalid hostname format: " << uri_without_transport; | |
| 293 return false; | |
| 294 } | |
| 295 | |
| 296 if (port <= 0 || port > 0xffff) { | |
| 297 LOG(WARNING) << "Invalid port: " << port; | |
| 298 return false; | |
| 299 } | |
| 300 | |
| 301 switch (service_type) { | |
| 302 case STUN: | |
| 303 case STUNS: | |
| 304 stun_servers->insert(rtc::SocketAddress(address, port)); | |
| 305 break; | |
| 306 case TURN: | |
| 307 case TURNS: { | |
| 308 bool secure = (service_type == TURNS); | |
| 309 turn_servers->push_back( | |
| 310 cricket::RelayServerConfig(address, port, username, server.password, | |
| 311 turn_transport_type, secure)); | |
| 312 break; | |
| 313 } | |
| 314 case INVALID: | |
| 315 default: | |
| 316 LOG(WARNING) << "Configuration not supported: " << url; | |
| 317 return false; | |
| 318 } | |
| 319 return true; | |
| 320 } | |
| 321 | |
| 322 // Check if we can send |new_stream| on a PeerConnection. | |
| 323 bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams, | |
| 324 webrtc::MediaStreamInterface* new_stream) { | |
| 325 if (!new_stream || !current_streams) { | |
| 326 return false; | |
| 327 } | |
| 328 if (current_streams->find(new_stream->label()) != nullptr) { | |
| 329 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label() | |
| 330 << " is already added."; | |
| 331 return false; | |
| 332 } | |
| 333 return true; | |
| 334 } | |
| 335 | |
| 336 bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) { | |
| 337 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV; | |
| 338 } | |
| 339 | |
| 340 // If the direction is "recvonly" or "inactive", treat the description | |
| 341 // as containing no streams. | |
| 342 // See: https://code.google.com/p/webrtc/issues/detail?id=5054 | |
| 343 std::vector<cricket::StreamParams> GetActiveStreams( | |
| 344 const cricket::MediaContentDescription* desc) { | |
| 345 return MediaContentDirectionHasSend(desc->direction()) | |
| 346 ? desc->streams() | |
| 347 : std::vector<cricket::StreamParams>(); | |
| 348 } | |
| 349 | |
| 350 bool IsValidOfferToReceiveMedia(int value) { | |
| 351 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options; | |
| 352 return (value >= Options::kUndefined) && | |
| 353 (value <= Options::kMaxOfferToReceiveMedia); | |
| 354 } | |
| 355 | |
| 356 // Add the stream and RTP data channel info to |session_options|. | |
| 357 void AddSendStreams( | |
| 358 cricket::MediaSessionOptions* session_options, | |
| 359 const std::vector<rtc::scoped_refptr< | |
| 360 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders, | |
| 361 const std::map<std::string, rtc::scoped_refptr<DataChannel>>& | |
| 362 rtp_data_channels) { | |
| 363 session_options->streams.clear(); | |
| 364 for (const auto& sender : senders) { | |
| 365 session_options->AddSendStream(sender->media_type(), sender->id(), | |
| 366 sender->internal()->stream_id()); | |
| 367 } | |
| 368 | |
| 369 // Check for data channels. | |
| 370 for (const auto& kv : rtp_data_channels) { | |
| 371 const DataChannel* channel = kv.second; | |
| 372 if (channel->state() == DataChannel::kConnecting || | |
| 373 channel->state() == DataChannel::kOpen) { | |
| 374 // |streamid| and |sync_label| are both set to the DataChannel label | |
| 375 // here so they can be signaled the same way as MediaStreams and Tracks. | |
| 376 // For MediaStreams, the sync_label is the MediaStream label and the | |
| 377 // track label is the same as |streamid|. | |
| 378 const std::string& streamid = channel->label(); | |
| 379 const std::string& sync_label = channel->label(); | |
| 380 session_options->AddSendStream(cricket::MEDIA_TYPE_DATA, streamid, | |
| 381 sync_label); | |
| 382 } | |
| 383 } | |
| 384 } | |
| 385 | |
| 386 uint32_t ConvertIceTransportTypeToCandidateFilter( | |
| 387 PeerConnectionInterface::IceTransportsType type) { | |
| 388 switch (type) { | |
| 389 case PeerConnectionInterface::kNone: | |
| 390 return cricket::CF_NONE; | |
| 391 case PeerConnectionInterface::kRelay: | |
| 392 return cricket::CF_RELAY; | |
| 393 case PeerConnectionInterface::kNoHost: | |
| 394 return (cricket::CF_ALL & ~cricket::CF_HOST); | |
| 395 case PeerConnectionInterface::kAll: | |
| 396 return cricket::CF_ALL; | |
| 397 default: | |
| 398 ASSERT(false); | |
| 399 } | |
| 400 return cricket::CF_NONE; | |
| 401 } | |
| 402 | |
| 403 // Helper method to set a voice/video channel on all applicable senders | |
| 404 // and receivers when one is created/destroyed by WebRtcSession. | |
| 405 // | |
| 406 // Used by On(Voice|Video)Channel(Created|Destroyed) | |
| 407 template <class SENDER, | |
| 408 class RECEIVER, | |
| 409 class CHANNEL, | |
| 410 class SENDERS, | |
| 411 class RECEIVERS> | |
| 412 void SetChannelOnSendersAndReceivers(CHANNEL* channel, | |
| 413 SENDERS& senders, | |
| 414 RECEIVERS& receivers, | |
| 415 cricket::MediaType media_type) { | |
| 416 for (auto& sender : senders) { | |
| 417 if (sender->media_type() == media_type) { | |
| 418 static_cast<SENDER*>(sender->internal())->SetChannel(channel); | |
| 419 } | |
| 420 } | |
| 421 for (auto& receiver : receivers) { | |
| 422 if (receiver->media_type() == media_type) { | |
| 423 if (!channel) { | |
| 424 receiver->internal()->Stop(); | |
| 425 } | |
| 426 static_cast<RECEIVER*>(receiver->internal())->SetChannel(channel); | |
| 427 } | |
| 428 } | |
| 429 } | |
| 430 | |
| 431 } // namespace | |
| 432 | |
| 433 namespace webrtc { | |
| 434 | |
| 435 // Generate a RTCP CNAME when a PeerConnection is created. | |
| 436 std::string GenerateRtcpCname() { | |
| 437 std::string cname; | |
| 438 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) { | |
| 439 LOG(LS_ERROR) << "Failed to generate CNAME."; | |
| 440 RTC_DCHECK(false); | |
| 441 } | |
| 442 return cname; | |
| 443 } | |
| 444 | |
| 445 bool ExtractMediaSessionOptions( | |
| 446 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options, | |
| 447 bool is_offer, | |
| 448 cricket::MediaSessionOptions* session_options) { | |
| 449 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions; | |
| 450 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) || | |
| 451 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) { | |
| 452 return false; | |
| 453 } | |
| 454 | |
| 455 // If constraints don't prevent us, we always accept video. | |
| 456 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) { | |
| 457 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0); | |
| 458 } else { | |
| 459 session_options->recv_audio = true; | |
| 460 } | |
| 461 // For offers, we only offer video if we have it or it's forced by options. | |
| 462 // For answers, we will always accept video (if offered). | |
| 463 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) { | |
| 464 session_options->recv_video = (rtc_options.offer_to_receive_video > 0); | |
| 465 } else if (is_offer) { | |
| 466 session_options->recv_video = false; | |
| 467 } else { | |
| 468 session_options->recv_video = true; | |
| 469 } | |
| 470 | |
| 471 session_options->vad_enabled = rtc_options.voice_activity_detection; | |
| 472 session_options->bundle_enabled = rtc_options.use_rtp_mux; | |
| 473 for (auto& kv : session_options->transport_options) { | |
| 474 kv.second.ice_restart = rtc_options.ice_restart; | |
| 475 } | |
| 476 | |
| 477 return true; | |
| 478 } | |
| 479 | |
| 480 bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints, | |
| 481 cricket::MediaSessionOptions* session_options) { | |
| 482 bool value = false; | |
| 483 size_t mandatory_constraints_satisfied = 0; | |
| 484 | |
| 485 // kOfferToReceiveAudio defaults to true according to spec. | |
| 486 if (!FindConstraint(constraints, | |
| 487 MediaConstraintsInterface::kOfferToReceiveAudio, &value, | |
| 488 &mandatory_constraints_satisfied) || | |
| 489 value) { | |
| 490 session_options->recv_audio = true; | |
| 491 } | |
| 492 | |
| 493 // kOfferToReceiveVideo defaults to false according to spec. But | |
| 494 // if it is an answer and video is offered, we should still accept video | |
| 495 // per default. | |
| 496 value = false; | |
| 497 if (!FindConstraint(constraints, | |
| 498 MediaConstraintsInterface::kOfferToReceiveVideo, &value, | |
| 499 &mandatory_constraints_satisfied) || | |
| 500 value) { | |
| 501 session_options->recv_video = true; | |
| 502 } | |
| 503 | |
| 504 if (FindConstraint(constraints, | |
| 505 MediaConstraintsInterface::kVoiceActivityDetection, &value, | |
| 506 &mandatory_constraints_satisfied)) { | |
| 507 session_options->vad_enabled = value; | |
| 508 } | |
| 509 | |
| 510 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value, | |
| 511 &mandatory_constraints_satisfied)) { | |
| 512 session_options->bundle_enabled = value; | |
| 513 } else { | |
| 514 // kUseRtpMux defaults to true according to spec. | |
| 515 session_options->bundle_enabled = true; | |
| 516 } | |
| 517 | |
| 518 bool ice_restart = false; | |
| 519 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart, | |
| 520 &value, &mandatory_constraints_satisfied)) { | |
| 521 // kIceRestart defaults to false according to spec. | |
| 522 ice_restart = true; | |
| 523 } | |
| 524 for (auto& kv : session_options->transport_options) { | |
| 525 kv.second.ice_restart = ice_restart; | |
| 526 } | |
| 527 | |
| 528 if (!constraints) { | |
| 529 return true; | |
| 530 } | |
| 531 return mandatory_constraints_satisfied == constraints->GetMandatory().size(); | |
| 532 } | |
| 533 | |
| 534 bool ParseIceServers(const PeerConnectionInterface::IceServers& servers, | |
| 535 cricket::ServerAddresses* stun_servers, | |
| 536 std::vector<cricket::RelayServerConfig>* turn_servers) { | |
| 537 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) { | |
| 538 if (!server.urls.empty()) { | |
| 539 for (const std::string& url : server.urls) { | |
| 540 if (url.empty()) { | |
| 541 LOG(LS_ERROR) << "Empty uri."; | |
| 542 return false; | |
| 543 } | |
| 544 if (!ParseIceServerUrl(server, url, stun_servers, turn_servers)) { | |
| 545 return false; | |
| 546 } | |
| 547 } | |
| 548 } else if (!server.uri.empty()) { | |
| 549 // Fallback to old .uri if new .urls isn't present. | |
| 550 if (!ParseIceServerUrl(server, server.uri, stun_servers, turn_servers)) { | |
| 551 return false; | |
| 552 } | |
| 553 } else { | |
| 554 LOG(LS_ERROR) << "Empty uri."; | |
| 555 return false; | |
| 556 } | |
| 557 } | |
| 558 // Candidates must have unique priorities, so that connectivity checks | |
| 559 // are performed in a well-defined order. | |
| 560 int priority = static_cast<int>(turn_servers->size() - 1); | |
| 561 for (cricket::RelayServerConfig& turn_server : *turn_servers) { | |
| 562 // First in the list gets highest priority. | |
| 563 turn_server.priority = priority--; | |
| 564 } | |
| 565 return true; | |
| 566 } | |
| 567 | |
| 568 PeerConnection::PeerConnection(PeerConnectionFactory* factory) | |
| 569 : factory_(factory), | |
| 570 observer_(NULL), | |
| 571 uma_observer_(NULL), | |
| 572 signaling_state_(kStable), | |
| 573 ice_connection_state_(kIceConnectionNew), | |
| 574 ice_gathering_state_(kIceGatheringNew), | |
| 575 event_log_(RtcEventLog::Create(webrtc::Clock::GetRealTimeClock())), | |
| 576 rtcp_cname_(GenerateRtcpCname()), | |
| 577 local_streams_(StreamCollection::Create()), | |
| 578 remote_streams_(StreamCollection::Create()) {} | |
| 579 | |
| 580 PeerConnection::~PeerConnection() { | |
| 581 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection"); | |
| 582 RTC_DCHECK(signaling_thread()->IsCurrent()); | |
| 583 // Need to detach RTP senders/receivers from WebRtcSession, | |
| 584 // since it's about to be destroyed. | |
| 585 for (const auto& sender : senders_) { | |
| 586 sender->internal()->Stop(); | |
| 587 } | |
| 588 for (const auto& receiver : receivers_) { | |
| 589 receiver->internal()->Stop(); | |
| 590 } | |
| 591 // Destroy stats_ because it depends on session_. | |
| 592 stats_.reset(nullptr); | |
| 593 // Now destroy session_ before destroying other members, | |
| 594 // because its destruction fires signals (such as VoiceChannelDestroyed) | |
| 595 // which will trigger some final actions in PeerConnection... | |
| 596 session_.reset(nullptr); | |
| 597 // port_allocator_ lives on the network thread and should be destroyed there. | |
| 598 network_thread()->Invoke<void>(RTC_FROM_HERE, | |
| 599 [this] { port_allocator_.reset(nullptr); }); | |
| 600 } | |
| 601 | |
| 602 bool PeerConnection::Initialize( | |
| 603 const PeerConnectionInterface::RTCConfiguration& configuration, | |
| 604 std::unique_ptr<cricket::PortAllocator> allocator, | |
| 605 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator, | |
| 606 PeerConnectionObserver* observer) { | |
| 607 TRACE_EVENT0("webrtc", "PeerConnection::Initialize"); | |
| 608 RTC_DCHECK(observer != nullptr); | |
| 609 if (!observer) { | |
| 610 return false; | |
| 611 } | |
| 612 observer_ = observer; | |
| 613 | |
| 614 port_allocator_ = std::move(allocator); | |
| 615 | |
| 616 // The port allocator lives on the network thread and should be initialized | |
| 617 // there. | |
| 618 if (!network_thread()->Invoke<bool>( | |
| 619 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n, | |
| 620 this, configuration))) { | |
| 621 return false; | |
| 622 } | |
| 623 | |
| 624 media_controller_.reset(factory_->CreateMediaController( | |
| 625 configuration.media_config, event_log_.get())); | |
| 626 | |
| 627 session_.reset(new WebRtcSession( | |
| 628 media_controller_.get(), factory_->network_thread(), | |
| 629 factory_->worker_thread(), factory_->signaling_thread(), | |
| 630 port_allocator_.get(), | |
| 631 std::unique_ptr<cricket::TransportController>( | |
| 632 factory_->CreateTransportController( | |
| 633 port_allocator_.get(), | |
| 634 configuration.redetermine_role_on_ice_restart)))); | |
| 635 | |
| 636 stats_.reset(new StatsCollector(this)); | |
| 637 stats_collector_ = RTCStatsCollector::Create(this); | |
| 638 | |
| 639 // Initialize the WebRtcSession. It creates transport channels etc. | |
| 640 if (!session_->Initialize(factory_->options(), std::move(cert_generator), | |
| 641 configuration)) { | |
| 642 return false; | |
| 643 } | |
| 644 | |
| 645 // Register PeerConnection as receiver of local ice candidates. | |
| 646 // All the callbacks will be posted to the application from PeerConnection. | |
| 647 session_->RegisterIceObserver(this); | |
| 648 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange); | |
| 649 session_->SignalVoiceChannelCreated.connect( | |
| 650 this, &PeerConnection::OnVoiceChannelCreated); | |
| 651 session_->SignalVoiceChannelDestroyed.connect( | |
| 652 this, &PeerConnection::OnVoiceChannelDestroyed); | |
| 653 session_->SignalVideoChannelCreated.connect( | |
| 654 this, &PeerConnection::OnVideoChannelCreated); | |
| 655 session_->SignalVideoChannelDestroyed.connect( | |
| 656 this, &PeerConnection::OnVideoChannelDestroyed); | |
| 657 session_->SignalDataChannelCreated.connect( | |
| 658 this, &PeerConnection::OnDataChannelCreated); | |
| 659 session_->SignalDataChannelDestroyed.connect( | |
| 660 this, &PeerConnection::OnDataChannelDestroyed); | |
| 661 session_->SignalDataChannelOpenMessage.connect( | |
| 662 this, &PeerConnection::OnDataChannelOpenMessage); | |
| 663 | |
| 664 configuration_ = configuration; | |
| 665 return true; | |
| 666 } | |
| 667 | |
| 668 rtc::scoped_refptr<StreamCollectionInterface> | |
| 669 PeerConnection::local_streams() { | |
| 670 return local_streams_; | |
| 671 } | |
| 672 | |
| 673 rtc::scoped_refptr<StreamCollectionInterface> | |
| 674 PeerConnection::remote_streams() { | |
| 675 return remote_streams_; | |
| 676 } | |
| 677 | |
| 678 bool PeerConnection::AddStream(MediaStreamInterface* local_stream) { | |
| 679 TRACE_EVENT0("webrtc", "PeerConnection::AddStream"); | |
| 680 if (IsClosed()) { | |
| 681 return false; | |
| 682 } | |
| 683 if (!CanAddLocalMediaStream(local_streams_, local_stream)) { | |
| 684 return false; | |
| 685 } | |
| 686 | |
| 687 local_streams_->AddStream(local_stream); | |
| 688 MediaStreamObserver* observer = new MediaStreamObserver(local_stream); | |
| 689 observer->SignalAudioTrackAdded.connect(this, | |
| 690 &PeerConnection::OnAudioTrackAdded); | |
| 691 observer->SignalAudioTrackRemoved.connect( | |
| 692 this, &PeerConnection::OnAudioTrackRemoved); | |
| 693 observer->SignalVideoTrackAdded.connect(this, | |
| 694 &PeerConnection::OnVideoTrackAdded); | |
| 695 observer->SignalVideoTrackRemoved.connect( | |
| 696 this, &PeerConnection::OnVideoTrackRemoved); | |
| 697 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer)); | |
| 698 | |
| 699 for (const auto& track : local_stream->GetAudioTracks()) { | |
| 700 OnAudioTrackAdded(track.get(), local_stream); | |
| 701 } | |
| 702 for (const auto& track : local_stream->GetVideoTracks()) { | |
| 703 OnVideoTrackAdded(track.get(), local_stream); | |
| 704 } | |
| 705 | |
| 706 stats_->AddStream(local_stream); | |
| 707 observer_->OnRenegotiationNeeded(); | |
| 708 return true; | |
| 709 } | |
| 710 | |
| 711 void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) { | |
| 712 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream"); | |
| 713 for (const auto& track : local_stream->GetAudioTracks()) { | |
| 714 OnAudioTrackRemoved(track.get(), local_stream); | |
| 715 } | |
| 716 for (const auto& track : local_stream->GetVideoTracks()) { | |
| 717 OnVideoTrackRemoved(track.get(), local_stream); | |
| 718 } | |
| 719 | |
| 720 local_streams_->RemoveStream(local_stream); | |
| 721 stream_observers_.erase( | |
| 722 std::remove_if( | |
| 723 stream_observers_.begin(), stream_observers_.end(), | |
| 724 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) { | |
| 725 return observer->stream()->label().compare(local_stream->label()) == | |
| 726 0; | |
| 727 }), | |
| 728 stream_observers_.end()); | |
| 729 | |
| 730 if (IsClosed()) { | |
| 731 return; | |
| 732 } | |
| 733 observer_->OnRenegotiationNeeded(); | |
| 734 } | |
| 735 | |
| 736 rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack( | |
| 737 MediaStreamTrackInterface* track, | |
| 738 std::vector<MediaStreamInterface*> streams) { | |
| 739 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack"); | |
| 740 if (IsClosed()) { | |
| 741 return nullptr; | |
| 742 } | |
| 743 if (streams.size() >= 2) { | |
| 744 LOG(LS_ERROR) | |
| 745 << "Adding a track with two streams is not currently supported."; | |
| 746 return nullptr; | |
| 747 } | |
| 748 // TODO(deadbeef): Support adding a track to two different senders. | |
| 749 if (FindSenderForTrack(track) != senders_.end()) { | |
| 750 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists."; | |
| 751 return nullptr; | |
| 752 } | |
| 753 | |
| 754 // TODO(deadbeef): Support adding a track to multiple streams. | |
| 755 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender; | |
| 756 if (track->kind() == MediaStreamTrackInterface::kAudioKind) { | |
| 757 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create( | |
| 758 signaling_thread(), | |
| 759 new AudioRtpSender(static_cast<AudioTrackInterface*>(track), | |
| 760 session_->voice_channel(), stats_.get())); | |
| 761 if (!streams.empty()) { | |
| 762 new_sender->internal()->set_stream_id(streams[0]->label()); | |
| 763 } | |
| 764 const TrackInfo* track_info = FindTrackInfo( | |
| 765 local_audio_tracks_, new_sender->internal()->stream_id(), track->id()); | |
| 766 if (track_info) { | |
| 767 new_sender->internal()->SetSsrc(track_info->ssrc); | |
| 768 } | |
| 769 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) { | |
| 770 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create( | |
| 771 signaling_thread(), | |
| 772 new VideoRtpSender(static_cast<VideoTrackInterface*>(track), | |
| 773 session_->video_channel())); | |
| 774 if (!streams.empty()) { | |
| 775 new_sender->internal()->set_stream_id(streams[0]->label()); | |
| 776 } | |
| 777 const TrackInfo* track_info = FindTrackInfo( | |
| 778 local_video_tracks_, new_sender->internal()->stream_id(), track->id()); | |
| 779 if (track_info) { | |
| 780 new_sender->internal()->SetSsrc(track_info->ssrc); | |
| 781 } | |
| 782 } else { | |
| 783 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind(); | |
| 784 return rtc::scoped_refptr<RtpSenderInterface>(); | |
| 785 } | |
| 786 | |
| 787 senders_.push_back(new_sender); | |
| 788 observer_->OnRenegotiationNeeded(); | |
| 789 return new_sender; | |
| 790 } | |
| 791 | |
| 792 bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) { | |
| 793 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack"); | |
| 794 if (IsClosed()) { | |
| 795 return false; | |
| 796 } | |
| 797 | |
| 798 auto it = std::find(senders_.begin(), senders_.end(), sender); | |
| 799 if (it == senders_.end()) { | |
| 800 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove."; | |
| 801 return false; | |
| 802 } | |
| 803 (*it)->internal()->Stop(); | |
| 804 senders_.erase(it); | |
| 805 | |
| 806 observer_->OnRenegotiationNeeded(); | |
| 807 return true; | |
| 808 } | |
| 809 | |
| 810 rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender( | |
| 811 AudioTrackInterface* track) { | |
| 812 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender"); | |
| 813 if (IsClosed()) { | |
| 814 return nullptr; | |
| 815 } | |
| 816 if (!track) { | |
| 817 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL."; | |
| 818 return NULL; | |
| 819 } | |
| 820 if (!local_streams_->FindAudioTrack(track->id())) { | |
| 821 LOG(LS_ERROR) << "CreateDtmfSender is called with a non local audio track."; | |
| 822 return NULL; | |
| 823 } | |
| 824 | |
| 825 rtc::scoped_refptr<DtmfSenderInterface> sender( | |
| 826 DtmfSender::Create(track, signaling_thread(), session_.get())); | |
| 827 if (!sender.get()) { | |
| 828 LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create."; | |
| 829 return NULL; | |
| 830 } | |
| 831 return DtmfSenderProxy::Create(signaling_thread(), sender.get()); | |
| 832 } | |
| 833 | |
| 834 rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender( | |
| 835 const std::string& kind, | |
| 836 const std::string& stream_id) { | |
| 837 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender"); | |
| 838 if (IsClosed()) { | |
| 839 return nullptr; | |
| 840 } | |
| 841 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender; | |
| 842 if (kind == MediaStreamTrackInterface::kAudioKind) { | |
| 843 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create( | |
| 844 signaling_thread(), | |
| 845 new AudioRtpSender(session_->voice_channel(), stats_.get())); | |
| 846 } else if (kind == MediaStreamTrackInterface::kVideoKind) { | |
| 847 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create( | |
| 848 signaling_thread(), new VideoRtpSender(session_->video_channel())); | |
| 849 } else { | |
| 850 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind; | |
| 851 return new_sender; | |
| 852 } | |
| 853 if (!stream_id.empty()) { | |
| 854 new_sender->internal()->set_stream_id(stream_id); | |
| 855 } | |
| 856 senders_.push_back(new_sender); | |
| 857 return new_sender; | |
| 858 } | |
| 859 | |
| 860 std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders() | |
| 861 const { | |
| 862 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret; | |
| 863 for (const auto& sender : senders_) { | |
| 864 ret.push_back(sender.get()); | |
| 865 } | |
| 866 return ret; | |
| 867 } | |
| 868 | |
| 869 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> | |
| 870 PeerConnection::GetReceivers() const { | |
| 871 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret; | |
| 872 for (const auto& receiver : receivers_) { | |
| 873 ret.push_back(receiver.get()); | |
| 874 } | |
| 875 return ret; | |
| 876 } | |
| 877 | |
| 878 bool PeerConnection::GetStats(StatsObserver* observer, | |
| 879 MediaStreamTrackInterface* track, | |
| 880 StatsOutputLevel level) { | |
| 881 TRACE_EVENT0("webrtc", "PeerConnection::GetStats"); | |
| 882 RTC_DCHECK(signaling_thread()->IsCurrent()); | |
| 883 if (!VERIFY(observer != NULL)) { | |
| 884 LOG(LS_ERROR) << "GetStats - observer is NULL."; | |
| 885 return false; | |
| 886 } | |
| 887 | |
| 888 stats_->UpdateStats(level); | |
| 889 // The StatsCollector is used to tell if a track is valid because it may | |
| 890 // remember tracks that the PeerConnection previously removed. | |
| 891 if (track && !stats_->IsValidTrack(track->id())) { | |
| 892 LOG(LS_WARNING) << "GetStats is called with an invalid track: " | |
| 893 << track->id(); | |
| 894 return false; | |
| 895 } | |
| 896 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS, | |
| 897 new GetStatsMsg(observer, track)); | |
| 898 return true; | |
| 899 } | |
| 900 | |
| 901 void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) { | |
| 902 RTC_DCHECK(stats_collector_); | |
| 903 stats_collector_->GetStatsReport(callback); | |
| 904 } | |
| 905 | |
| 906 PeerConnectionInterface::SignalingState PeerConnection::signaling_state() { | |
| 907 return signaling_state_; | |
| 908 } | |
| 909 | |
| 910 PeerConnectionInterface::IceConnectionState | |
| 911 PeerConnection::ice_connection_state() { | |
| 912 return ice_connection_state_; | |
| 913 } | |
| 914 | |
| 915 PeerConnectionInterface::IceGatheringState | |
| 916 PeerConnection::ice_gathering_state() { | |
| 917 return ice_gathering_state_; | |
| 918 } | |
| 919 | |
| 920 rtc::scoped_refptr<DataChannelInterface> | |
| 921 PeerConnection::CreateDataChannel( | |
| 922 const std::string& label, | |
| 923 const DataChannelInit* config) { | |
| 924 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel"); | |
| 925 #ifdef HAVE_QUIC | |
| 926 if (session_->data_channel_type() == cricket::DCT_QUIC) { | |
| 927 // TODO(zhihuang): Handle case when config is NULL. | |
| 928 if (!config) { | |
| 929 LOG(LS_ERROR) << "Missing config for QUIC data channel."; | |
| 930 return nullptr; | |
| 931 } | |
| 932 // TODO(zhihuang): Allow unreliable or ordered QUIC data channels. | |
| 933 if (!config->reliable || config->ordered) { | |
| 934 LOG(LS_ERROR) << "QUIC data channel does not implement unreliable or " | |
| 935 "ordered delivery."; | |
| 936 return nullptr; | |
| 937 } | |
| 938 return session_->quic_data_transport()->CreateDataChannel(label, config); | |
| 939 } | |
| 940 #endif // HAVE_QUIC | |
| 941 | |
| 942 bool first_datachannel = !HasDataChannels(); | |
| 943 | |
| 944 std::unique_ptr<InternalDataChannelInit> internal_config; | |
| 945 if (config) { | |
| 946 internal_config.reset(new InternalDataChannelInit(*config)); | |
| 947 } | |
| 948 rtc::scoped_refptr<DataChannelInterface> channel( | |
| 949 InternalCreateDataChannel(label, internal_config.get())); | |
| 950 if (!channel.get()) { | |
| 951 return nullptr; | |
| 952 } | |
| 953 | |
| 954 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or | |
| 955 // the first SCTP DataChannel. | |
| 956 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) { | |
| 957 observer_->OnRenegotiationNeeded(); | |
| 958 } | |
| 959 | |
| 960 return DataChannelProxy::Create(signaling_thread(), channel.get()); | |
| 961 } | |
| 962 | |
| 963 void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer, | |
| 964 const MediaConstraintsInterface* constraints) { | |
| 965 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer"); | |
| 966 if (!VERIFY(observer != nullptr)) { | |
| 967 LOG(LS_ERROR) << "CreateOffer - observer is NULL."; | |
| 968 return; | |
| 969 } | |
| 970 RTCOfferAnswerOptions options; | |
| 971 | |
| 972 bool value; | |
| 973 size_t mandatory_constraints = 0; | |
| 974 | |
| 975 if (FindConstraint(constraints, | |
| 976 MediaConstraintsInterface::kOfferToReceiveAudio, | |
| 977 &value, | |
| 978 &mandatory_constraints)) { | |
| 979 options.offer_to_receive_audio = | |
| 980 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0; | |
| 981 } | |
| 982 | |
| 983 if (FindConstraint(constraints, | |
| 984 MediaConstraintsInterface::kOfferToReceiveVideo, | |
| 985 &value, | |
| 986 &mandatory_constraints)) { | |
| 987 options.offer_to_receive_video = | |
| 988 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0; | |
| 989 } | |
| 990 | |
| 991 if (FindConstraint(constraints, | |
| 992 MediaConstraintsInterface::kVoiceActivityDetection, | |
| 993 &value, | |
| 994 &mandatory_constraints)) { | |
| 995 options.voice_activity_detection = value; | |
| 996 } | |
| 997 | |
| 998 if (FindConstraint(constraints, | |
| 999 MediaConstraintsInterface::kIceRestart, | |
| 1000 &value, | |
| 1001 &mandatory_constraints)) { | |
| 1002 options.ice_restart = value; | |
| 1003 } | |
| 1004 | |
| 1005 if (FindConstraint(constraints, | |
| 1006 MediaConstraintsInterface::kUseRtpMux, | |
| 1007 &value, | |
| 1008 &mandatory_constraints)) { | |
| 1009 options.use_rtp_mux = value; | |
| 1010 } | |
| 1011 | |
| 1012 CreateOffer(observer, options); | |
| 1013 } | |
| 1014 | |
| 1015 void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer, | |
| 1016 const RTCOfferAnswerOptions& options) { | |
| 1017 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer"); | |
| 1018 if (!VERIFY(observer != nullptr)) { | |
| 1019 LOG(LS_ERROR) << "CreateOffer - observer is NULL."; | |
| 1020 return; | |
| 1021 } | |
| 1022 | |
| 1023 cricket::MediaSessionOptions session_options; | |
| 1024 if (!GetOptionsForOffer(options, &session_options)) { | |
| 1025 std::string error = "CreateOffer called with invalid options."; | |
| 1026 LOG(LS_ERROR) << error; | |
| 1027 PostCreateSessionDescriptionFailure(observer, error); | |
| 1028 return; | |
| 1029 } | |
| 1030 | |
| 1031 session_->CreateOffer(observer, options, session_options); | |
| 1032 } | |
| 1033 | |
| 1034 void PeerConnection::CreateAnswer( | |
| 1035 CreateSessionDescriptionObserver* observer, | |
| 1036 const MediaConstraintsInterface* constraints) { | |
| 1037 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer"); | |
| 1038 if (!VERIFY(observer != nullptr)) { | |
| 1039 LOG(LS_ERROR) << "CreateAnswer - observer is NULL."; | |
| 1040 return; | |
| 1041 } | |
| 1042 | |
| 1043 cricket::MediaSessionOptions session_options; | |
| 1044 if (!GetOptionsForAnswer(constraints, &session_options)) { | |
| 1045 std::string error = "CreateAnswer called with invalid constraints."; | |
| 1046 LOG(LS_ERROR) << error; | |
| 1047 PostCreateSessionDescriptionFailure(observer, error); | |
| 1048 return; | |
| 1049 } | |
| 1050 | |
| 1051 session_->CreateAnswer(observer, session_options); | |
| 1052 } | |
| 1053 | |
| 1054 void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer, | |
| 1055 const RTCOfferAnswerOptions& options) { | |
| 1056 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer"); | |
| 1057 if (!VERIFY(observer != nullptr)) { | |
| 1058 LOG(LS_ERROR) << "CreateAnswer - observer is NULL."; | |
| 1059 return; | |
| 1060 } | |
| 1061 | |
| 1062 cricket::MediaSessionOptions session_options; | |
| 1063 if (!GetOptionsForAnswer(options, &session_options)) { | |
| 1064 std::string error = "CreateAnswer called with invalid options."; | |
| 1065 LOG(LS_ERROR) << error; | |
| 1066 PostCreateSessionDescriptionFailure(observer, error); | |
| 1067 return; | |
| 1068 } | |
| 1069 | |
| 1070 session_->CreateAnswer(observer, session_options); | |
| 1071 } | |
| 1072 | |
| 1073 void PeerConnection::SetLocalDescription( | |
| 1074 SetSessionDescriptionObserver* observer, | |
| 1075 SessionDescriptionInterface* desc) { | |
| 1076 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription"); | |
| 1077 if (IsClosed()) { | |
| 1078 return; | |
| 1079 } | |
| 1080 if (!VERIFY(observer != nullptr)) { | |
| 1081 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL."; | |
| 1082 return; | |
| 1083 } | |
| 1084 if (!desc) { | |
| 1085 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL."); | |
| 1086 return; | |
| 1087 } | |
| 1088 // Update stats here so that we have the most recent stats for tracks and | |
| 1089 // streams that might be removed by updating the session description. | |
| 1090 stats_->UpdateStats(kStatsOutputLevelStandard); | |
| 1091 std::string error; | |
| 1092 if (!session_->SetLocalDescription(desc, &error)) { | |
| 1093 PostSetSessionDescriptionFailure(observer, error); | |
| 1094 return; | |
| 1095 } | |
| 1096 | |
| 1097 // If setting the description decided our SSL role, allocate any necessary | |
| 1098 // SCTP sids. | |
| 1099 rtc::SSLRole role; | |
| 1100 if (session_->data_channel_type() == cricket::DCT_SCTP && | |
| 1101 session_->GetSslRole(session_->data_channel(), &role)) { | |
| 1102 AllocateSctpSids(role); | |
| 1103 } | |
| 1104 | |
| 1105 // Update state and SSRC of local MediaStreams and DataChannels based on the | |
| 1106 // local session description. | |
| 1107 const cricket::ContentInfo* audio_content = | |
| 1108 GetFirstAudioContent(desc->description()); | |
| 1109 if (audio_content) { | |
| 1110 if (audio_content->rejected) { | |
| 1111 RemoveTracks(cricket::MEDIA_TYPE_AUDIO); | |
| 1112 } else { | |
| 1113 const cricket::AudioContentDescription* audio_desc = | |
| 1114 static_cast<const cricket::AudioContentDescription*>( | |
| 1115 audio_content->description); | |
| 1116 UpdateLocalTracks(audio_desc->streams(), audio_desc->type()); | |
| 1117 } | |
| 1118 } | |
| 1119 | |
| 1120 const cricket::ContentInfo* video_content = | |
| 1121 GetFirstVideoContent(desc->description()); | |
| 1122 if (video_content) { | |
| 1123 if (video_content->rejected) { | |
| 1124 RemoveTracks(cricket::MEDIA_TYPE_VIDEO); | |
| 1125 } else { | |
| 1126 const cricket::VideoContentDescription* video_desc = | |
| 1127 static_cast<const cricket::VideoContentDescription*>( | |
| 1128 video_content->description); | |
| 1129 UpdateLocalTracks(video_desc->streams(), video_desc->type()); | |
| 1130 } | |
| 1131 } | |
| 1132 | |
| 1133 const cricket::ContentInfo* data_content = | |
| 1134 GetFirstDataContent(desc->description()); | |
| 1135 if (data_content) { | |
| 1136 const cricket::DataContentDescription* data_desc = | |
| 1137 static_cast<const cricket::DataContentDescription*>( | |
| 1138 data_content->description); | |
| 1139 if (rtc::starts_with(data_desc->protocol().data(), | |
| 1140 cricket::kMediaProtocolRtpPrefix)) { | |
| 1141 UpdateLocalRtpDataChannels(data_desc->streams()); | |
| 1142 } | |
| 1143 } | |
| 1144 | |
| 1145 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer); | |
| 1146 signaling_thread()->Post(RTC_FROM_HERE, this, | |
| 1147 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg); | |
| 1148 | |
| 1149 // MaybeStartGathering needs to be called after posting | |
| 1150 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates | |
| 1151 // before signaling that SetLocalDescription completed. | |
| 1152 session_->MaybeStartGathering(); | |
| 1153 } | |
| 1154 | |
| 1155 void PeerConnection::SetRemoteDescription( | |
| 1156 SetSessionDescriptionObserver* observer, | |
| 1157 SessionDescriptionInterface* desc) { | |
| 1158 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription"); | |
| 1159 if (IsClosed()) { | |
| 1160 return; | |
| 1161 } | |
| 1162 if (!VERIFY(observer != nullptr)) { | |
| 1163 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL."; | |
| 1164 return; | |
| 1165 } | |
| 1166 if (!desc) { | |
| 1167 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL."); | |
| 1168 return; | |
| 1169 } | |
| 1170 // Update stats here so that we have the most recent stats for tracks and | |
| 1171 // streams that might be removed by updating the session description. | |
| 1172 stats_->UpdateStats(kStatsOutputLevelStandard); | |
| 1173 std::string error; | |
| 1174 if (!session_->SetRemoteDescription(desc, &error)) { | |
| 1175 PostSetSessionDescriptionFailure(observer, error); | |
| 1176 return; | |
| 1177 } | |
| 1178 | |
| 1179 // If setting the description decided our SSL role, allocate any necessary | |
| 1180 // SCTP sids. | |
| 1181 rtc::SSLRole role; | |
| 1182 if (session_->data_channel_type() == cricket::DCT_SCTP && | |
| 1183 session_->GetSslRole(session_->data_channel(), &role)) { | |
| 1184 AllocateSctpSids(role); | |
| 1185 } | |
| 1186 | |
| 1187 const cricket::SessionDescription* remote_desc = desc->description(); | |
| 1188 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc); | |
| 1189 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc); | |
| 1190 const cricket::AudioContentDescription* audio_desc = | |
| 1191 GetFirstAudioContentDescription(remote_desc); | |
| 1192 const cricket::VideoContentDescription* video_desc = | |
| 1193 GetFirstVideoContentDescription(remote_desc); | |
| 1194 const cricket::DataContentDescription* data_desc = | |
| 1195 GetFirstDataContentDescription(remote_desc); | |
| 1196 | |
| 1197 // Check if the descriptions include streams, just in case the peer supports | |
| 1198 // MSID, but doesn't indicate so with "a=msid-semantic". | |
| 1199 if (remote_desc->msid_supported() || | |
| 1200 (audio_desc && !audio_desc->streams().empty()) || | |
| 1201 (video_desc && !video_desc->streams().empty())) { | |
| 1202 remote_peer_supports_msid_ = true; | |
| 1203 } | |
| 1204 | |
| 1205 // We wait to signal new streams until we finish processing the description, | |
| 1206 // since only at that point will new streams have all their tracks. | |
| 1207 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create()); | |
| 1208 | |
| 1209 // Find all audio rtp streams and create corresponding remote AudioTracks | |
| 1210 // and MediaStreams. | |
| 1211 if (audio_content) { | |
| 1212 if (audio_content->rejected) { | |
| 1213 RemoveTracks(cricket::MEDIA_TYPE_AUDIO); | |
| 1214 } else { | |
| 1215 bool default_audio_track_needed = | |
| 1216 !remote_peer_supports_msid_ && | |
| 1217 MediaContentDirectionHasSend(audio_desc->direction()); | |
| 1218 UpdateRemoteStreamsList(GetActiveStreams(audio_desc), | |
| 1219 default_audio_track_needed, audio_desc->type(), | |
| 1220 new_streams); | |
| 1221 } | |
| 1222 } | |
| 1223 | |
| 1224 // Find all video rtp streams and create corresponding remote VideoTracks | |
| 1225 // and MediaStreams. | |
| 1226 if (video_content) { | |
| 1227 if (video_content->rejected) { | |
| 1228 RemoveTracks(cricket::MEDIA_TYPE_VIDEO); | |
| 1229 } else { | |
| 1230 bool default_video_track_needed = | |
| 1231 !remote_peer_supports_msid_ && | |
| 1232 MediaContentDirectionHasSend(video_desc->direction()); | |
| 1233 UpdateRemoteStreamsList(GetActiveStreams(video_desc), | |
| 1234 default_video_track_needed, video_desc->type(), | |
| 1235 new_streams); | |
| 1236 } | |
| 1237 } | |
| 1238 | |
| 1239 // Update the DataChannels with the information from the remote peer. | |
| 1240 if (data_desc) { | |
| 1241 if (rtc::starts_with(data_desc->protocol().data(), | |
| 1242 cricket::kMediaProtocolRtpPrefix)) { | |
| 1243 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc)); | |
| 1244 } | |
| 1245 } | |
| 1246 | |
| 1247 // Iterate new_streams and notify the observer about new MediaStreams. | |
| 1248 for (size_t i = 0; i < new_streams->count(); ++i) { | |
| 1249 MediaStreamInterface* new_stream = new_streams->at(i); | |
| 1250 stats_->AddStream(new_stream); | |
| 1251 // Call both the raw pointer and scoped_refptr versions of the method | |
| 1252 // for compatibility. | |
| 1253 observer_->OnAddStream(new_stream); | |
| 1254 observer_->OnAddStream( | |
| 1255 rtc::scoped_refptr<MediaStreamInterface>(new_stream)); | |
| 1256 } | |
| 1257 | |
| 1258 UpdateEndedRemoteMediaStreams(); | |
| 1259 | |
| 1260 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer); | |
| 1261 signaling_thread()->Post(RTC_FROM_HERE, this, | |
| 1262 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg); | |
| 1263 } | |
| 1264 | |
| 1265 PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() { | |
| 1266 return configuration_; | |
| 1267 } | |
| 1268 | |
| 1269 bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration) { | |
| 1270 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration"); | |
| 1271 // TODO(deadbeef): Return false and log an error if there are any unsupported | |
| 1272 // modifications. | |
| 1273 if (port_allocator_) { | |
| 1274 if (!network_thread()->Invoke<bool>( | |
| 1275 RTC_FROM_HERE, | |
| 1276 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this, | |
| 1277 configuration))) { | |
| 1278 return false; | |
| 1279 } | |
| 1280 } | |
| 1281 | |
| 1282 // TODO(deadbeef): Shouldn't have to hop to the worker thread twice... | |
| 1283 session_->SetIceConfig(session_->ParseIceConfig(configuration)); | |
| 1284 | |
| 1285 configuration_ = configuration; | |
| 1286 return true; | |
| 1287 } | |
| 1288 | |
| 1289 bool PeerConnection::AddIceCandidate( | |
| 1290 const IceCandidateInterface* ice_candidate) { | |
| 1291 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate"); | |
| 1292 if (IsClosed()) { | |
| 1293 return false; | |
| 1294 } | |
| 1295 return session_->ProcessIceMessage(ice_candidate); | |
| 1296 } | |
| 1297 | |
| 1298 bool PeerConnection::RemoveIceCandidates( | |
| 1299 const std::vector<cricket::Candidate>& candidates) { | |
| 1300 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates"); | |
| 1301 return session_->RemoveRemoteIceCandidates(candidates); | |
| 1302 } | |
| 1303 | |
| 1304 void PeerConnection::RegisterUMAObserver(UMAObserver* observer) { | |
| 1305 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver"); | |
| 1306 uma_observer_ = observer; | |
| 1307 | |
| 1308 if (session_) { | |
| 1309 session_->set_metrics_observer(uma_observer_); | |
| 1310 } | |
| 1311 | |
| 1312 // Send information about IPv4/IPv6 status. | |
| 1313 if (uma_observer_ && port_allocator_) { | |
| 1314 port_allocator_->SetMetricsObserver(uma_observer_); | |
| 1315 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) { | |
| 1316 uma_observer_->IncrementEnumCounter( | |
| 1317 kEnumCounterAddressFamily, kPeerConnection_IPv6, | |
| 1318 kPeerConnectionAddressFamilyCounter_Max); | |
| 1319 } else { | |
| 1320 uma_observer_->IncrementEnumCounter( | |
| 1321 kEnumCounterAddressFamily, kPeerConnection_IPv4, | |
| 1322 kPeerConnectionAddressFamilyCounter_Max); | |
| 1323 } | |
| 1324 } | |
| 1325 } | |
| 1326 | |
| 1327 bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file, | |
| 1328 int64_t max_size_bytes) { | |
| 1329 return factory_->worker_thread()->Invoke<bool>( | |
| 1330 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file, | |
| 1331 max_size_bytes)); | |
| 1332 } | |
| 1333 | |
| 1334 void PeerConnection::StopRtcEventLog() { | |
| 1335 factory_->worker_thread()->Invoke<void>( | |
| 1336 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this)); | |
| 1337 } | |
| 1338 | |
| 1339 const SessionDescriptionInterface* PeerConnection::local_description() const { | |
| 1340 return session_->local_description(); | |
| 1341 } | |
| 1342 | |
| 1343 const SessionDescriptionInterface* PeerConnection::remote_description() const { | |
| 1344 return session_->remote_description(); | |
| 1345 } | |
| 1346 | |
| 1347 void PeerConnection::Close() { | |
| 1348 TRACE_EVENT0("webrtc", "PeerConnection::Close"); | |
| 1349 // Update stats here so that we have the most recent stats for tracks and | |
| 1350 // streams before the channels are closed. | |
| 1351 stats_->UpdateStats(kStatsOutputLevelStandard); | |
| 1352 | |
| 1353 session_->Close(); | |
| 1354 } | |
| 1355 | |
| 1356 void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/, | |
| 1357 WebRtcSession::State state) { | |
| 1358 switch (state) { | |
| 1359 case WebRtcSession::STATE_INIT: | |
| 1360 ChangeSignalingState(PeerConnectionInterface::kStable); | |
| 1361 break; | |
| 1362 case WebRtcSession::STATE_SENTOFFER: | |
| 1363 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer); | |
| 1364 break; | |
| 1365 case WebRtcSession::STATE_SENTPRANSWER: | |
| 1366 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer); | |
| 1367 break; | |
| 1368 case WebRtcSession::STATE_RECEIVEDOFFER: | |
| 1369 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer); | |
| 1370 break; | |
| 1371 case WebRtcSession::STATE_RECEIVEDPRANSWER: | |
| 1372 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer); | |
| 1373 break; | |
| 1374 case WebRtcSession::STATE_INPROGRESS: | |
| 1375 ChangeSignalingState(PeerConnectionInterface::kStable); | |
| 1376 break; | |
| 1377 case WebRtcSession::STATE_CLOSED: | |
| 1378 ChangeSignalingState(PeerConnectionInterface::kClosed); | |
| 1379 break; | |
| 1380 default: | |
| 1381 break; | |
| 1382 } | |
| 1383 } | |
| 1384 | |
| 1385 void PeerConnection::OnMessage(rtc::Message* msg) { | |
| 1386 switch (msg->message_id) { | |
| 1387 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: { | |
| 1388 SetSessionDescriptionMsg* param = | |
| 1389 static_cast<SetSessionDescriptionMsg*>(msg->pdata); | |
| 1390 param->observer->OnSuccess(); | |
| 1391 delete param; | |
| 1392 break; | |
| 1393 } | |
| 1394 case MSG_SET_SESSIONDESCRIPTION_FAILED: { | |
| 1395 SetSessionDescriptionMsg* param = | |
| 1396 static_cast<SetSessionDescriptionMsg*>(msg->pdata); | |
| 1397 param->observer->OnFailure(param->error); | |
| 1398 delete param; | |
| 1399 break; | |
| 1400 } | |
| 1401 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: { | |
| 1402 CreateSessionDescriptionMsg* param = | |
| 1403 static_cast<CreateSessionDescriptionMsg*>(msg->pdata); | |
| 1404 param->observer->OnFailure(param->error); | |
| 1405 delete param; | |
| 1406 break; | |
| 1407 } | |
| 1408 case MSG_GETSTATS: { | |
| 1409 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata); | |
| 1410 StatsReports reports; | |
| 1411 stats_->GetStats(param->track, &reports); | |
| 1412 param->observer->OnComplete(reports); | |
| 1413 delete param; | |
| 1414 break; | |
| 1415 } | |
| 1416 case MSG_FREE_DATACHANNELS: { | |
| 1417 sctp_data_channels_to_free_.clear(); | |
| 1418 break; | |
| 1419 } | |
| 1420 default: | |
| 1421 RTC_DCHECK(false && "Not implemented"); | |
| 1422 break; | |
| 1423 } | |
| 1424 } | |
| 1425 | |
| 1426 void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream, | |
| 1427 const std::string& track_id, | |
| 1428 uint32_t ssrc) { | |
| 1429 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>> | |
| 1430 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create( | |
| 1431 signaling_thread(), new AudioRtpReceiver(stream, track_id, ssrc, | |
| 1432 session_->voice_channel())); | |
| 1433 | |
| 1434 receivers_.push_back(receiver); | |
| 1435 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams; | |
| 1436 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream)); | |
| 1437 observer_->OnAddTrack(receiver, streams); | |
| 1438 } | |
| 1439 | |
| 1440 void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream, | |
| 1441 const std::string& track_id, | |
| 1442 uint32_t ssrc) { | |
| 1443 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>> | |
| 1444 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create( | |
| 1445 signaling_thread(), | |
| 1446 new VideoRtpReceiver(stream, track_id, factory_->worker_thread(), | |
| 1447 ssrc, session_->video_channel())); | |
| 1448 receivers_.push_back(receiver); | |
| 1449 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams; | |
| 1450 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream)); | |
| 1451 observer_->OnAddTrack(receiver, streams); | |
| 1452 } | |
| 1453 | |
| 1454 // TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote | |
| 1455 // description. | |
| 1456 void PeerConnection::DestroyReceiver(const std::string& track_id) { | |
| 1457 auto it = FindReceiverForTrack(track_id); | |
| 1458 if (it == receivers_.end()) { | |
| 1459 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id | |
| 1460 << " doesn't exist."; | |
| 1461 } else { | |
| 1462 (*it)->internal()->Stop(); | |
| 1463 receivers_.erase(it); | |
| 1464 } | |
| 1465 } | |
| 1466 | |
| 1467 void PeerConnection::OnIceConnectionChange( | |
| 1468 PeerConnectionInterface::IceConnectionState new_state) { | |
| 1469 RTC_DCHECK(signaling_thread()->IsCurrent()); | |
| 1470 // After transitioning to "closed", ignore any additional states from | |
| 1471 // WebRtcSession (such as "disconnected"). | |
| 1472 if (IsClosed()) { | |
| 1473 return; | |
| 1474 } | |
| 1475 ice_connection_state_ = new_state; | |
| 1476 observer_->OnIceConnectionChange(ice_connection_state_); | |
| 1477 } | |
| 1478 | |
| 1479 void PeerConnection::OnIceGatheringChange( | |
| 1480 PeerConnectionInterface::IceGatheringState new_state) { | |
| 1481 RTC_DCHECK(signaling_thread()->IsCurrent()); | |
| 1482 if (IsClosed()) { | |
| 1483 return; | |
| 1484 } | |
| 1485 ice_gathering_state_ = new_state; | |
| 1486 observer_->OnIceGatheringChange(ice_gathering_state_); | |
| 1487 } | |
| 1488 | |
| 1489 void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) { | |
| 1490 RTC_DCHECK(signaling_thread()->IsCurrent()); | |
| 1491 if (IsClosed()) { | |
| 1492 return; | |
| 1493 } | |
| 1494 observer_->OnIceCandidate(candidate); | |
| 1495 } | |
| 1496 | |
| 1497 void PeerConnection::OnIceCandidatesRemoved( | |
| 1498 const std::vector<cricket::Candidate>& candidates) { | |
| 1499 RTC_DCHECK(signaling_thread()->IsCurrent()); | |
| 1500 if (IsClosed()) { | |
| 1501 return; | |
| 1502 } | |
| 1503 observer_->OnIceCandidatesRemoved(candidates); | |
| 1504 } | |
| 1505 | |
| 1506 void PeerConnection::OnIceConnectionReceivingChange(bool receiving) { | |
| 1507 RTC_DCHECK(signaling_thread()->IsCurrent()); | |
| 1508 if (IsClosed()) { | |
| 1509 return; | |
| 1510 } | |
| 1511 observer_->OnIceConnectionReceivingChange(receiving); | |
| 1512 } | |
| 1513 | |
| 1514 void PeerConnection::ChangeSignalingState( | |
| 1515 PeerConnectionInterface::SignalingState signaling_state) { | |
| 1516 signaling_state_ = signaling_state; | |
| 1517 if (signaling_state == kClosed) { | |
| 1518 ice_connection_state_ = kIceConnectionClosed; | |
| 1519 observer_->OnIceConnectionChange(ice_connection_state_); | |
| 1520 if (ice_gathering_state_ != kIceGatheringComplete) { | |
| 1521 ice_gathering_state_ = kIceGatheringComplete; | |
| 1522 observer_->OnIceGatheringChange(ice_gathering_state_); | |
| 1523 } | |
| 1524 } | |
| 1525 observer_->OnSignalingChange(signaling_state_); | |
| 1526 } | |
| 1527 | |
| 1528 void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track, | |
| 1529 MediaStreamInterface* stream) { | |
| 1530 if (IsClosed()) { | |
| 1531 return; | |
| 1532 } | |
| 1533 auto sender = FindSenderForTrack(track); | |
| 1534 if (sender != senders_.end()) { | |
| 1535 // We already have a sender for this track, so just change the stream_id | |
| 1536 // so that it's correct in the next call to CreateOffer. | |
| 1537 (*sender)->internal()->set_stream_id(stream->label()); | |
| 1538 return; | |
| 1539 } | |
| 1540 | |
| 1541 // Normal case; we've never seen this track before. | |
| 1542 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender = | |
| 1543 RtpSenderProxyWithInternal<RtpSenderInternal>::Create( | |
| 1544 signaling_thread(), | |
| 1545 new AudioRtpSender(track, stream->label(), session_->voice_channel(), | |
| 1546 stats_.get())); | |
| 1547 senders_.push_back(new_sender); | |
| 1548 // If the sender has already been configured in SDP, we call SetSsrc, | |
| 1549 // which will connect the sender to the underlying transport. This can | |
| 1550 // occur if a local session description that contains the ID of the sender | |
| 1551 // is set before AddStream is called. It can also occur if the local | |
| 1552 // session description is not changed and RemoveStream is called, and | |
| 1553 // later AddStream is called again with the same stream. | |
| 1554 const TrackInfo* track_info = | |
| 1555 FindTrackInfo(local_audio_tracks_, stream->label(), track->id()); | |
| 1556 if (track_info) { | |
| 1557 new_sender->internal()->SetSsrc(track_info->ssrc); | |
| 1558 } | |
| 1559 } | |
| 1560 | |
| 1561 // TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around | |
| 1562 // indefinitely, when we have unified plan SDP. | |
| 1563 void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track, | |
| 1564 MediaStreamInterface* stream) { | |
| 1565 if (IsClosed()) { | |
| 1566 return; | |
| 1567 } | |
| 1568 auto sender = FindSenderForTrack(track); | |
| 1569 if (sender == senders_.end()) { | |
| 1570 LOG(LS_WARNING) << "RtpSender for track with id " << track->id() | |
| 1571 << " doesn't exist."; | |
| 1572 return; | |
| 1573 } | |
| 1574 (*sender)->internal()->Stop(); | |
| 1575 senders_.erase(sender); | |
| 1576 } | |
| 1577 | |
| 1578 void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track, | |
| 1579 MediaStreamInterface* stream) { | |
| 1580 if (IsClosed()) { | |
| 1581 return; | |
| 1582 } | |
| 1583 auto sender = FindSenderForTrack(track); | |
| 1584 if (sender != senders_.end()) { | |
| 1585 // We already have a sender for this track, so just change the stream_id | |
| 1586 // so that it's correct in the next call to CreateOffer. | |
| 1587 (*sender)->internal()->set_stream_id(stream->label()); | |
| 1588 return; | |
| 1589 } | |
| 1590 | |
| 1591 // Normal case; we've never seen this track before. | |
| 1592 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender = | |
| 1593 RtpSenderProxyWithInternal<RtpSenderInternal>::Create( | |
| 1594 signaling_thread(), new VideoRtpSender(track, stream->label(), | |
| 1595 session_->video_channel())); | |
| 1596 senders_.push_back(new_sender); | |
| 1597 const TrackInfo* track_info = | |
| 1598 FindTrackInfo(local_video_tracks_, stream->label(), track->id()); | |
| 1599 if (track_info) { | |
| 1600 new_sender->internal()->SetSsrc(track_info->ssrc); | |
| 1601 } | |
| 1602 } | |
| 1603 | |
| 1604 void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track, | |
| 1605 MediaStreamInterface* stream) { | |
| 1606 if (IsClosed()) { | |
| 1607 return; | |
| 1608 } | |
| 1609 auto sender = FindSenderForTrack(track); | |
| 1610 if (sender == senders_.end()) { | |
| 1611 LOG(LS_WARNING) << "RtpSender for track with id " << track->id() | |
| 1612 << " doesn't exist."; | |
| 1613 return; | |
| 1614 } | |
| 1615 (*sender)->internal()->Stop(); | |
| 1616 senders_.erase(sender); | |
| 1617 } | |
| 1618 | |
| 1619 void PeerConnection::PostSetSessionDescriptionFailure( | |
| 1620 SetSessionDescriptionObserver* observer, | |
| 1621 const std::string& error) { | |
| 1622 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer); | |
| 1623 msg->error = error; | |
| 1624 signaling_thread()->Post(RTC_FROM_HERE, this, | |
| 1625 MSG_SET_SESSIONDESCRIPTION_FAILED, msg); | |
| 1626 } | |
| 1627 | |
| 1628 void PeerConnection::PostCreateSessionDescriptionFailure( | |
| 1629 CreateSessionDescriptionObserver* observer, | |
| 1630 const std::string& error) { | |
| 1631 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer); | |
| 1632 msg->error = error; | |
| 1633 signaling_thread()->Post(RTC_FROM_HERE, this, | |
| 1634 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg); | |
| 1635 } | |
| 1636 | |
| 1637 bool PeerConnection::GetOptionsForOffer( | |
| 1638 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options, | |
| 1639 cricket::MediaSessionOptions* session_options) { | |
| 1640 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of | |
| 1641 // ContentInfos. | |
| 1642 if (session_->local_description()) { | |
| 1643 for (const cricket::ContentInfo& content : | |
| 1644 session_->local_description()->description()->contents()) { | |
| 1645 session_options->transport_options[content.name] = | |
| 1646 cricket::TransportOptions(); | |
| 1647 } | |
| 1648 } | |
| 1649 session_options->enable_ice_renomination = | |
| 1650 configuration_.enable_ice_renomination; | |
| 1651 | |
| 1652 if (!ExtractMediaSessionOptions(rtc_options, true, session_options)) { | |
| 1653 return false; | |
| 1654 } | |
| 1655 | |
| 1656 AddSendStreams(session_options, senders_, rtp_data_channels_); | |
| 1657 // Offer to receive audio/video if the constraint is not set and there are | |
| 1658 // send streams, or we're currently receiving. | |
| 1659 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) { | |
| 1660 session_options->recv_audio = | |
| 1661 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) || | |
| 1662 !remote_audio_tracks_.empty(); | |
| 1663 } | |
| 1664 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) { | |
| 1665 session_options->recv_video = | |
| 1666 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) || | |
| 1667 !remote_video_tracks_.empty(); | |
| 1668 } | |
| 1669 | |
| 1670 // Intentionally unset the data channel type for RTP data channel with the | |
| 1671 // second condition. Otherwise the RTP data channels would be successfully | |
| 1672 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail | |
| 1673 // when building with chromium. We want to leave RTP data channels broken, so | |
| 1674 // people won't try to use them. | |
| 1675 if (HasDataChannels() && session_->data_channel_type() != cricket::DCT_RTP) { | |
| 1676 session_options->data_channel_type = session_->data_channel_type(); | |
| 1677 } | |
| 1678 | |
| 1679 session_options->bundle_enabled = | |
| 1680 session_options->bundle_enabled && | |
| 1681 (session_options->has_audio() || session_options->has_video() || | |
| 1682 session_options->has_data()); | |
| 1683 | |
| 1684 session_options->rtcp_cname = rtcp_cname_; | |
| 1685 session_options->crypto_options = factory_->options().crypto_options; | |
| 1686 return true; | |
| 1687 } | |
| 1688 | |
| 1689 void PeerConnection::InitializeOptionsForAnswer( | |
| 1690 cricket::MediaSessionOptions* session_options) { | |
| 1691 session_options->recv_audio = false; | |
| 1692 session_options->recv_video = false; | |
| 1693 session_options->enable_ice_renomination = | |
| 1694 configuration_.enable_ice_renomination; | |
| 1695 } | |
| 1696 | |
| 1697 void PeerConnection::FinishOptionsForAnswer( | |
| 1698 cricket::MediaSessionOptions* session_options) { | |
| 1699 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of | |
| 1700 // ContentInfos. | |
| 1701 if (session_->remote_description()) { | |
| 1702 // Initialize the transport_options map. | |
| 1703 for (const cricket::ContentInfo& content : | |
| 1704 session_->remote_description()->description()->contents()) { | |
| 1705 session_options->transport_options[content.name] = | |
| 1706 cricket::TransportOptions(); | |
| 1707 } | |
| 1708 } | |
| 1709 AddSendStreams(session_options, senders_, rtp_data_channels_); | |
| 1710 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams | |
| 1711 // are not signaled in the SDP so does not go through that path and must be | |
| 1712 // handled here. | |
| 1713 // Intentionally unset the data channel type for RTP data channel. Otherwise | |
| 1714 // the RTP data channels would be successfully negotiated by default and the | |
| 1715 // unit tests in WebRtcDataBrowserTest will fail when building with chromium. | |
| 1716 // We want to leave RTP data channels broken, so people won't try to use them. | |
| 1717 if (session_->data_channel_type() != cricket::DCT_RTP) { | |
| 1718 session_options->data_channel_type = session_->data_channel_type(); | |
| 1719 } | |
| 1720 session_options->bundle_enabled = | |
| 1721 session_options->bundle_enabled && | |
| 1722 (session_options->has_audio() || session_options->has_video() || | |
| 1723 session_options->has_data()); | |
| 1724 | |
| 1725 session_options->crypto_options = factory_->options().crypto_options; | |
| 1726 } | |
| 1727 | |
| 1728 bool PeerConnection::GetOptionsForAnswer( | |
| 1729 const MediaConstraintsInterface* constraints, | |
| 1730 cricket::MediaSessionOptions* session_options) { | |
| 1731 InitializeOptionsForAnswer(session_options); | |
| 1732 if (!ParseConstraintsForAnswer(constraints, session_options)) { | |
| 1733 return false; | |
| 1734 } | |
| 1735 session_options->rtcp_cname = rtcp_cname_; | |
| 1736 | |
| 1737 FinishOptionsForAnswer(session_options); | |
| 1738 return true; | |
| 1739 } | |
| 1740 | |
| 1741 bool PeerConnection::GetOptionsForAnswer( | |
| 1742 const RTCOfferAnswerOptions& options, | |
| 1743 cricket::MediaSessionOptions* session_options) { | |
| 1744 InitializeOptionsForAnswer(session_options); | |
| 1745 if (!ExtractMediaSessionOptions(options, false, session_options)) { | |
| 1746 return false; | |
| 1747 } | |
| 1748 session_options->rtcp_cname = rtcp_cname_; | |
| 1749 | |
| 1750 FinishOptionsForAnswer(session_options); | |
| 1751 return true; | |
| 1752 } | |
| 1753 | |
| 1754 void PeerConnection::RemoveTracks(cricket::MediaType media_type) { | |
| 1755 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type); | |
| 1756 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false, | |
| 1757 media_type, nullptr); | |
| 1758 } | |
| 1759 | |
| 1760 void PeerConnection::UpdateRemoteStreamsList( | |
| 1761 const cricket::StreamParamsVec& streams, | |
| 1762 bool default_track_needed, | |
| 1763 cricket::MediaType media_type, | |
| 1764 StreamCollection* new_streams) { | |
| 1765 TrackInfos* current_tracks = GetRemoteTracks(media_type); | |
| 1766 | |
| 1767 // Find removed tracks. I.e., tracks where the track id or ssrc don't match | |
| 1768 // the new StreamParam. | |
| 1769 auto track_it = current_tracks->begin(); | |
| 1770 while (track_it != current_tracks->end()) { | |
| 1771 const TrackInfo& info = *track_it; | |
| 1772 const cricket::StreamParams* params = | |
| 1773 cricket::GetStreamBySsrc(streams, info.ssrc); | |
| 1774 bool track_exists = params && params->id == info.track_id; | |
| 1775 // If this is a default track, and we still need it, don't remove it. | |
| 1776 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) || | |
| 1777 track_exists) { | |
| 1778 ++track_it; | |
| 1779 } else { | |
| 1780 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type); | |
| 1781 track_it = current_tracks->erase(track_it); | |
| 1782 } | |
| 1783 } | |
| 1784 | |
| 1785 // Find new and active tracks. | |
| 1786 for (const cricket::StreamParams& params : streams) { | |
| 1787 // The sync_label is the MediaStream label and the |stream.id| is the | |
| 1788 // track id. | |
| 1789 const std::string& stream_label = params.sync_label; | |
| 1790 const std::string& track_id = params.id; | |
| 1791 uint32_t ssrc = params.first_ssrc(); | |
| 1792 | |
| 1793 rtc::scoped_refptr<MediaStreamInterface> stream = | |
| 1794 remote_streams_->find(stream_label); | |
| 1795 if (!stream) { | |
| 1796 // This is a new MediaStream. Create a new remote MediaStream. | |
| 1797 stream = MediaStreamProxy::Create(rtc::Thread::Current(), | |
| 1798 MediaStream::Create(stream_label)); | |
| 1799 remote_streams_->AddStream(stream); | |
| 1800 new_streams->AddStream(stream); | |
| 1801 } | |
| 1802 | |
| 1803 const TrackInfo* track_info = | |
| 1804 FindTrackInfo(*current_tracks, stream_label, track_id); | |
| 1805 if (!track_info) { | |
| 1806 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc)); | |
| 1807 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type); | |
| 1808 } | |
| 1809 } | |
| 1810 | |
| 1811 // Add default track if necessary. | |
| 1812 if (default_track_needed) { | |
| 1813 rtc::scoped_refptr<MediaStreamInterface> default_stream = | |
| 1814 remote_streams_->find(kDefaultStreamLabel); | |
| 1815 if (!default_stream) { | |
| 1816 // Create the new default MediaStream. | |
| 1817 default_stream = MediaStreamProxy::Create( | |
| 1818 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel)); | |
| 1819 remote_streams_->AddStream(default_stream); | |
| 1820 new_streams->AddStream(default_stream); | |
| 1821 } | |
| 1822 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO) | |
| 1823 ? kDefaultAudioTrackLabel | |
| 1824 : kDefaultVideoTrackLabel; | |
| 1825 const TrackInfo* default_track_info = | |
| 1826 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id); | |
| 1827 if (!default_track_info) { | |
| 1828 current_tracks->push_back( | |
| 1829 TrackInfo(kDefaultStreamLabel, default_track_id, 0)); | |
| 1830 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type); | |
| 1831 } | |
| 1832 } | |
| 1833 } | |
| 1834 | |
| 1835 void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label, | |
| 1836 const std::string& track_id, | |
| 1837 uint32_t ssrc, | |
| 1838 cricket::MediaType media_type) { | |
| 1839 MediaStreamInterface* stream = remote_streams_->find(stream_label); | |
| 1840 | |
| 1841 if (media_type == cricket::MEDIA_TYPE_AUDIO) { | |
| 1842 CreateAudioReceiver(stream, track_id, ssrc); | |
| 1843 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) { | |
| 1844 CreateVideoReceiver(stream, track_id, ssrc); | |
| 1845 } else { | |
| 1846 RTC_DCHECK(false && "Invalid media type"); | |
| 1847 } | |
| 1848 } | |
| 1849 | |
| 1850 void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label, | |
| 1851 const std::string& track_id, | |
| 1852 cricket::MediaType media_type) { | |
| 1853 MediaStreamInterface* stream = remote_streams_->find(stream_label); | |
| 1854 | |
| 1855 if (media_type == cricket::MEDIA_TYPE_AUDIO) { | |
| 1856 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource | |
| 1857 // will be notified which will end the AudioRtpReceiver::track(). | |
| 1858 DestroyReceiver(track_id); | |
| 1859 rtc::scoped_refptr<AudioTrackInterface> audio_track = | |
| 1860 stream->FindAudioTrack(track_id); | |
| 1861 if (audio_track) { | |
| 1862 stream->RemoveTrack(audio_track); | |
| 1863 } | |
| 1864 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) { | |
| 1865 // Stopping or destroying a VideoRtpReceiver will end the | |
| 1866 // VideoRtpReceiver::track(). | |
| 1867 DestroyReceiver(track_id); | |
| 1868 rtc::scoped_refptr<VideoTrackInterface> video_track = | |
| 1869 stream->FindVideoTrack(track_id); | |
| 1870 if (video_track) { | |
| 1871 // There's no guarantee the track is still available, e.g. the track may | |
| 1872 // have been removed from the stream by an application. | |
| 1873 stream->RemoveTrack(video_track); | |
| 1874 } | |
| 1875 } else { | |
| 1876 ASSERT(false && "Invalid media type"); | |
| 1877 } | |
| 1878 } | |
| 1879 | |
| 1880 void PeerConnection::UpdateEndedRemoteMediaStreams() { | |
| 1881 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove; | |
| 1882 for (size_t i = 0; i < remote_streams_->count(); ++i) { | |
| 1883 MediaStreamInterface* stream = remote_streams_->at(i); | |
| 1884 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) { | |
| 1885 streams_to_remove.push_back(stream); | |
| 1886 } | |
| 1887 } | |
| 1888 | |
| 1889 for (auto& stream : streams_to_remove) { | |
| 1890 remote_streams_->RemoveStream(stream); | |
| 1891 // Call both the raw pointer and scoped_refptr versions of the method | |
| 1892 // for compatibility. | |
| 1893 observer_->OnRemoveStream(stream.get()); | |
| 1894 observer_->OnRemoveStream(std::move(stream)); | |
| 1895 } | |
| 1896 } | |
| 1897 | |
| 1898 void PeerConnection::UpdateLocalTracks( | |
| 1899 const std::vector<cricket::StreamParams>& streams, | |
| 1900 cricket::MediaType media_type) { | |
| 1901 TrackInfos* current_tracks = GetLocalTracks(media_type); | |
| 1902 | |
| 1903 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc | |
| 1904 // don't match the new StreamParam. | |
| 1905 TrackInfos::iterator track_it = current_tracks->begin(); | |
| 1906 while (track_it != current_tracks->end()) { | |
| 1907 const TrackInfo& info = *track_it; | |
| 1908 const cricket::StreamParams* params = | |
| 1909 cricket::GetStreamBySsrc(streams, info.ssrc); | |
| 1910 if (!params || params->id != info.track_id || | |
| 1911 params->sync_label != info.stream_label) { | |
| 1912 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc, | |
| 1913 media_type); | |
| 1914 track_it = current_tracks->erase(track_it); | |
| 1915 } else { | |
| 1916 ++track_it; | |
| 1917 } | |
| 1918 } | |
| 1919 | |
| 1920 // Find new and active tracks. | |
| 1921 for (const cricket::StreamParams& params : streams) { | |
| 1922 // The sync_label is the MediaStream label and the |stream.id| is the | |
| 1923 // track id. | |
| 1924 const std::string& stream_label = params.sync_label; | |
| 1925 const std::string& track_id = params.id; | |
| 1926 uint32_t ssrc = params.first_ssrc(); | |
| 1927 const TrackInfo* track_info = | |
| 1928 FindTrackInfo(*current_tracks, stream_label, track_id); | |
| 1929 if (!track_info) { | |
| 1930 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc)); | |
| 1931 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type); | |
| 1932 } | |
| 1933 } | |
| 1934 } | |
| 1935 | |
| 1936 void PeerConnection::OnLocalTrackSeen(const std::string& stream_label, | |
| 1937 const std::string& track_id, | |
| 1938 uint32_t ssrc, | |
| 1939 cricket::MediaType media_type) { | |
| 1940 RtpSenderInternal* sender = FindSenderById(track_id); | |
| 1941 if (!sender) { | |
| 1942 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id | |
| 1943 << " has been configured in the local description."; | |
| 1944 return; | |
| 1945 } | |
| 1946 | |
| 1947 if (sender->media_type() != media_type) { | |
| 1948 LOG(LS_WARNING) << "An RtpSender has been configured in the local" | |
| 1949 << " description with an unexpected media type."; | |
| 1950 return; | |
| 1951 } | |
| 1952 | |
| 1953 sender->set_stream_id(stream_label); | |
| 1954 sender->SetSsrc(ssrc); | |
| 1955 } | |
| 1956 | |
| 1957 void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label, | |
| 1958 const std::string& track_id, | |
| 1959 uint32_t ssrc, | |
| 1960 cricket::MediaType media_type) { | |
| 1961 RtpSenderInternal* sender = FindSenderById(track_id); | |
| 1962 if (!sender) { | |
| 1963 // This is the normal case. I.e., RemoveStream has been called and the | |
| 1964 // SessionDescriptions has been renegotiated. | |
| 1965 return; | |
| 1966 } | |
| 1967 | |
| 1968 // A sender has been removed from the SessionDescription but it's still | |
| 1969 // associated with the PeerConnection. This only occurs if the SDP doesn't | |
| 1970 // match with the calls to CreateSender, AddStream and RemoveStream. | |
| 1971 if (sender->media_type() != media_type) { | |
| 1972 LOG(LS_WARNING) << "An RtpSender has been configured in the local" | |
| 1973 << " description with an unexpected media type."; | |
| 1974 return; | |
| 1975 } | |
| 1976 | |
| 1977 sender->SetSsrc(0); | |
| 1978 } | |
| 1979 | |
| 1980 void PeerConnection::UpdateLocalRtpDataChannels( | |
| 1981 const cricket::StreamParamsVec& streams) { | |
| 1982 std::vector<std::string> existing_channels; | |
| 1983 | |
| 1984 // Find new and active data channels. | |
| 1985 for (const cricket::StreamParams& params : streams) { | |
| 1986 // |it->sync_label| is actually the data channel label. The reason is that | |
| 1987 // we use the same naming of data channels as we do for | |
| 1988 // MediaStreams and Tracks. | |
| 1989 // For MediaStreams, the sync_label is the MediaStream label and the | |
| 1990 // track label is the same as |streamid|. | |
| 1991 const std::string& channel_label = params.sync_label; | |
| 1992 auto data_channel_it = rtp_data_channels_.find(channel_label); | |
| 1993 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) { | |
| 1994 continue; | |
| 1995 } | |
| 1996 // Set the SSRC the data channel should use for sending. | |
| 1997 data_channel_it->second->SetSendSsrc(params.first_ssrc()); | |
| 1998 existing_channels.push_back(data_channel_it->first); | |
| 1999 } | |
| 2000 | |
| 2001 UpdateClosingRtpDataChannels(existing_channels, true); | |
| 2002 } | |
| 2003 | |
| 2004 void PeerConnection::UpdateRemoteRtpDataChannels( | |
| 2005 const cricket::StreamParamsVec& streams) { | |
| 2006 std::vector<std::string> existing_channels; | |
| 2007 | |
| 2008 // Find new and active data channels. | |
| 2009 for (const cricket::StreamParams& params : streams) { | |
| 2010 // The data channel label is either the mslabel or the SSRC if the mslabel | |
| 2011 // does not exist. Ex a=ssrc:444330170 mslabel:test1. | |
| 2012 std::string label = params.sync_label.empty() | |
| 2013 ? rtc::ToString(params.first_ssrc()) | |
| 2014 : params.sync_label; | |
| 2015 auto data_channel_it = rtp_data_channels_.find(label); | |
| 2016 if (data_channel_it == rtp_data_channels_.end()) { | |
| 2017 // This is a new data channel. | |
| 2018 CreateRemoteRtpDataChannel(label, params.first_ssrc()); | |
| 2019 } else { | |
| 2020 data_channel_it->second->SetReceiveSsrc(params.first_ssrc()); | |
| 2021 } | |
| 2022 existing_channels.push_back(label); | |
| 2023 } | |
| 2024 | |
| 2025 UpdateClosingRtpDataChannels(existing_channels, false); | |
| 2026 } | |
| 2027 | |
| 2028 void PeerConnection::UpdateClosingRtpDataChannels( | |
| 2029 const std::vector<std::string>& active_channels, | |
| 2030 bool is_local_update) { | |
| 2031 auto it = rtp_data_channels_.begin(); | |
| 2032 while (it != rtp_data_channels_.end()) { | |
| 2033 DataChannel* data_channel = it->second; | |
| 2034 if (std::find(active_channels.begin(), active_channels.end(), | |
| 2035 data_channel->label()) != active_channels.end()) { | |
| 2036 ++it; | |
| 2037 continue; | |
| 2038 } | |
| 2039 | |
| 2040 if (is_local_update) { | |
| 2041 data_channel->SetSendSsrc(0); | |
| 2042 } else { | |
| 2043 data_channel->RemotePeerRequestClose(); | |
| 2044 } | |
| 2045 | |
| 2046 if (data_channel->state() == DataChannel::kClosed) { | |
| 2047 rtp_data_channels_.erase(it); | |
| 2048 it = rtp_data_channels_.begin(); | |
| 2049 } else { | |
| 2050 ++it; | |
| 2051 } | |
| 2052 } | |
| 2053 } | |
| 2054 | |
| 2055 void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label, | |
| 2056 uint32_t remote_ssrc) { | |
| 2057 rtc::scoped_refptr<DataChannel> channel( | |
| 2058 InternalCreateDataChannel(label, nullptr)); | |
| 2059 if (!channel.get()) { | |
| 2060 LOG(LS_WARNING) << "Remote peer requested a DataChannel but" | |
| 2061 << "CreateDataChannel failed."; | |
| 2062 return; | |
| 2063 } | |
| 2064 channel->SetReceiveSsrc(remote_ssrc); | |
| 2065 rtc::scoped_refptr<DataChannelInterface> proxy_channel = | |
| 2066 DataChannelProxy::Create(signaling_thread(), channel); | |
| 2067 // Call both the raw pointer and scoped_refptr versions of the method | |
| 2068 // for compatibility. | |
| 2069 observer_->OnDataChannel(proxy_channel.get()); | |
| 2070 observer_->OnDataChannel(std::move(proxy_channel)); | |
| 2071 } | |
| 2072 | |
| 2073 rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel( | |
| 2074 const std::string& label, | |
| 2075 const InternalDataChannelInit* config) { | |
| 2076 if (IsClosed()) { | |
| 2077 return nullptr; | |
| 2078 } | |
| 2079 if (session_->data_channel_type() == cricket::DCT_NONE) { | |
| 2080 LOG(LS_ERROR) | |
| 2081 << "InternalCreateDataChannel: Data is not supported in this call."; | |
| 2082 return nullptr; | |
| 2083 } | |
| 2084 InternalDataChannelInit new_config = | |
| 2085 config ? (*config) : InternalDataChannelInit(); | |
| 2086 if (session_->data_channel_type() == cricket::DCT_SCTP) { | |
| 2087 if (new_config.id < 0) { | |
| 2088 rtc::SSLRole role; | |
| 2089 if ((session_->GetSslRole(session_->data_channel(), &role)) && | |
| 2090 !sid_allocator_.AllocateSid(role, &new_config.id)) { | |
| 2091 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel."; | |
| 2092 return nullptr; | |
| 2093 } | |
| 2094 } else if (!sid_allocator_.ReserveSid(new_config.id)) { | |
| 2095 LOG(LS_ERROR) << "Failed to create a SCTP data channel " | |
| 2096 << "because the id is already in use or out of range."; | |
| 2097 return nullptr; | |
| 2098 } | |
| 2099 } | |
| 2100 | |
| 2101 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create( | |
| 2102 session_.get(), session_->data_channel_type(), label, new_config)); | |
| 2103 if (!channel) { | |
| 2104 sid_allocator_.ReleaseSid(new_config.id); | |
| 2105 return nullptr; | |
| 2106 } | |
| 2107 | |
| 2108 if (channel->data_channel_type() == cricket::DCT_RTP) { | |
| 2109 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) { | |
| 2110 LOG(LS_ERROR) << "DataChannel with label " << channel->label() | |
| 2111 << " already exists."; | |
| 2112 return nullptr; | |
| 2113 } | |
| 2114 rtp_data_channels_[channel->label()] = channel; | |
| 2115 } else { | |
| 2116 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP); | |
| 2117 sctp_data_channels_.push_back(channel); | |
| 2118 channel->SignalClosed.connect(this, | |
| 2119 &PeerConnection::OnSctpDataChannelClosed); | |
| 2120 } | |
| 2121 | |
| 2122 SignalDataChannelCreated(channel.get()); | |
| 2123 return channel; | |
| 2124 } | |
| 2125 | |
| 2126 bool PeerConnection::HasDataChannels() const { | |
| 2127 #ifdef HAVE_QUIC | |
| 2128 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() || | |
| 2129 (session_->quic_data_transport() && | |
| 2130 session_->quic_data_transport()->HasDataChannels()); | |
| 2131 #else | |
| 2132 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty(); | |
| 2133 #endif // HAVE_QUIC | |
| 2134 } | |
| 2135 | |
| 2136 void PeerConnection::AllocateSctpSids(rtc::SSLRole role) { | |
| 2137 for (const auto& channel : sctp_data_channels_) { | |
| 2138 if (channel->id() < 0) { | |
| 2139 int sid; | |
| 2140 if (!sid_allocator_.AllocateSid(role, &sid)) { | |
| 2141 LOG(LS_ERROR) << "Failed to allocate SCTP sid."; | |
| 2142 continue; | |
| 2143 } | |
| 2144 channel->SetSctpSid(sid); | |
| 2145 } | |
| 2146 } | |
| 2147 } | |
| 2148 | |
| 2149 void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) { | |
| 2150 RTC_DCHECK(signaling_thread()->IsCurrent()); | |
| 2151 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end(); | |
| 2152 ++it) { | |
| 2153 if (it->get() == channel) { | |
| 2154 if (channel->id() >= 0) { | |
| 2155 sid_allocator_.ReleaseSid(channel->id()); | |
| 2156 } | |
| 2157 // Since this method is triggered by a signal from the DataChannel, | |
| 2158 // we can't free it directly here; we need to free it asynchronously. | |
| 2159 sctp_data_channels_to_free_.push_back(*it); | |
| 2160 sctp_data_channels_.erase(it); | |
| 2161 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS, | |
| 2162 nullptr); | |
| 2163 return; | |
| 2164 } | |
| 2165 } | |
| 2166 } | |
| 2167 | |
| 2168 void PeerConnection::OnVoiceChannelCreated() { | |
| 2169 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>( | |
| 2170 session_->voice_channel(), senders_, receivers_, | |
| 2171 cricket::MEDIA_TYPE_AUDIO); | |
| 2172 } | |
| 2173 | |
| 2174 void PeerConnection::OnVoiceChannelDestroyed() { | |
| 2175 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver, | |
| 2176 cricket::VoiceChannel>( | |
| 2177 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO); | |
| 2178 } | |
| 2179 | |
| 2180 void PeerConnection::OnVideoChannelCreated() { | |
| 2181 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>( | |
| 2182 session_->video_channel(), senders_, receivers_, | |
| 2183 cricket::MEDIA_TYPE_VIDEO); | |
| 2184 } | |
| 2185 | |
| 2186 void PeerConnection::OnVideoChannelDestroyed() { | |
| 2187 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver, | |
| 2188 cricket::VideoChannel>( | |
| 2189 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO); | |
| 2190 } | |
| 2191 | |
| 2192 void PeerConnection::OnDataChannelCreated() { | |
| 2193 for (const auto& channel : sctp_data_channels_) { | |
| 2194 channel->OnTransportChannelCreated(); | |
| 2195 } | |
| 2196 } | |
| 2197 | |
| 2198 void PeerConnection::OnDataChannelDestroyed() { | |
| 2199 // Use a temporary copy of the RTP/SCTP DataChannel list because the | |
| 2200 // DataChannel may callback to us and try to modify the list. | |
| 2201 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs; | |
| 2202 temp_rtp_dcs.swap(rtp_data_channels_); | |
| 2203 for (const auto& kv : temp_rtp_dcs) { | |
| 2204 kv.second->OnTransportChannelDestroyed(); | |
| 2205 } | |
| 2206 | |
| 2207 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs; | |
| 2208 temp_sctp_dcs.swap(sctp_data_channels_); | |
| 2209 for (const auto& channel : temp_sctp_dcs) { | |
| 2210 channel->OnTransportChannelDestroyed(); | |
| 2211 } | |
| 2212 } | |
| 2213 | |
| 2214 void PeerConnection::OnDataChannelOpenMessage( | |
| 2215 const std::string& label, | |
| 2216 const InternalDataChannelInit& config) { | |
| 2217 rtc::scoped_refptr<DataChannel> channel( | |
| 2218 InternalCreateDataChannel(label, &config)); | |
| 2219 if (!channel.get()) { | |
| 2220 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message."; | |
| 2221 return; | |
| 2222 } | |
| 2223 | |
| 2224 rtc::scoped_refptr<DataChannelInterface> proxy_channel = | |
| 2225 DataChannelProxy::Create(signaling_thread(), channel); | |
| 2226 // Call both the raw pointer and scoped_refptr versions of the method | |
| 2227 // for compatibility. | |
| 2228 observer_->OnDataChannel(proxy_channel.get()); | |
| 2229 observer_->OnDataChannel(std::move(proxy_channel)); | |
| 2230 } | |
| 2231 | |
| 2232 RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) { | |
| 2233 auto it = std::find_if( | |
| 2234 senders_.begin(), senders_.end(), | |
| 2235 [id](const rtc::scoped_refptr< | |
| 2236 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) { | |
| 2237 return sender->id() == id; | |
| 2238 }); | |
| 2239 return it != senders_.end() ? (*it)->internal() : nullptr; | |
| 2240 } | |
| 2241 | |
| 2242 std::vector< | |
| 2243 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator | |
| 2244 PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) { | |
| 2245 return std::find_if( | |
| 2246 senders_.begin(), senders_.end(), | |
| 2247 [track](const rtc::scoped_refptr< | |
| 2248 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) { | |
| 2249 return sender->track() == track; | |
| 2250 }); | |
| 2251 } | |
| 2252 | |
| 2253 std::vector<rtc::scoped_refptr< | |
| 2254 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator | |
| 2255 PeerConnection::FindReceiverForTrack(const std::string& track_id) { | |
| 2256 return std::find_if( | |
| 2257 receivers_.begin(), receivers_.end(), | |
| 2258 [track_id](const rtc::scoped_refptr< | |
| 2259 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) { | |
| 2260 return receiver->id() == track_id; | |
| 2261 }); | |
| 2262 } | |
| 2263 | |
| 2264 PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks( | |
| 2265 cricket::MediaType media_type) { | |
| 2266 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO || | |
| 2267 media_type == cricket::MEDIA_TYPE_VIDEO); | |
| 2268 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_ | |
| 2269 : &remote_video_tracks_; | |
| 2270 } | |
| 2271 | |
| 2272 PeerConnection::TrackInfos* PeerConnection::GetLocalTracks( | |
| 2273 cricket::MediaType media_type) { | |
| 2274 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO || | |
| 2275 media_type == cricket::MEDIA_TYPE_VIDEO); | |
| 2276 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_ | |
| 2277 : &local_video_tracks_; | |
| 2278 } | |
| 2279 | |
| 2280 const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo( | |
| 2281 const PeerConnection::TrackInfos& infos, | |
| 2282 const std::string& stream_label, | |
| 2283 const std::string track_id) const { | |
| 2284 for (const TrackInfo& track_info : infos) { | |
| 2285 if (track_info.stream_label == stream_label && | |
| 2286 track_info.track_id == track_id) { | |
| 2287 return &track_info; | |
| 2288 } | |
| 2289 } | |
| 2290 return nullptr; | |
| 2291 } | |
| 2292 | |
| 2293 DataChannel* PeerConnection::FindDataChannelBySid(int sid) const { | |
| 2294 for (const auto& channel : sctp_data_channels_) { | |
| 2295 if (channel->id() == sid) { | |
| 2296 return channel; | |
| 2297 } | |
| 2298 } | |
| 2299 return nullptr; | |
| 2300 } | |
| 2301 | |
| 2302 bool PeerConnection::InitializePortAllocator_n( | |
| 2303 const RTCConfiguration& configuration) { | |
| 2304 cricket::ServerAddresses stun_servers; | |
| 2305 std::vector<cricket::RelayServerConfig> turn_servers; | |
| 2306 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) { | |
| 2307 return false; | |
| 2308 } | |
| 2309 | |
| 2310 port_allocator_->Initialize(); | |
| 2311 | |
| 2312 // To handle both internal and externally created port allocator, we will | |
| 2313 // enable BUNDLE here. | |
| 2314 int portallocator_flags = port_allocator_->flags(); | |
| 2315 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET | | |
| 2316 cricket::PORTALLOCATOR_ENABLE_IPV6; | |
| 2317 // If the disable-IPv6 flag was specified, we'll not override it | |
| 2318 // by experiment. | |
| 2319 if (configuration.disable_ipv6) { | |
| 2320 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6); | |
| 2321 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") == | |
| 2322 "Disabled") { | |
| 2323 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6); | |
| 2324 } | |
| 2325 | |
| 2326 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) { | |
| 2327 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP; | |
| 2328 LOG(LS_INFO) << "TCP candidates are disabled."; | |
| 2329 } | |
| 2330 | |
| 2331 if (configuration.candidate_network_policy == | |
| 2332 kCandidateNetworkPolicyLowCost) { | |
| 2333 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS; | |
| 2334 LOG(LS_INFO) << "Do not gather candidates on high-cost networks"; | |
| 2335 } | |
| 2336 | |
| 2337 port_allocator_->set_flags(portallocator_flags); | |
| 2338 // No step delay is used while allocating ports. | |
| 2339 port_allocator_->set_step_delay(cricket::kMinimumStepDelay); | |
| 2340 port_allocator_->set_candidate_filter( | |
| 2341 ConvertIceTransportTypeToCandidateFilter(configuration.type)); | |
| 2342 | |
| 2343 // Call this last since it may create pooled allocator sessions using the | |
| 2344 // properties set above. | |
| 2345 port_allocator_->SetConfiguration(stun_servers, turn_servers, | |
| 2346 configuration.ice_candidate_pool_size, | |
| 2347 configuration.prune_turn_ports); | |
| 2348 return true; | |
| 2349 } | |
| 2350 | |
| 2351 bool PeerConnection::ReconfigurePortAllocator_n( | |
| 2352 const RTCConfiguration& configuration) { | |
| 2353 cricket::ServerAddresses stun_servers; | |
| 2354 std::vector<cricket::RelayServerConfig> turn_servers; | |
| 2355 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) { | |
| 2356 return false; | |
| 2357 } | |
| 2358 port_allocator_->set_candidate_filter( | |
| 2359 ConvertIceTransportTypeToCandidateFilter(configuration.type)); | |
| 2360 // Call this last since it may create pooled allocator sessions using the | |
| 2361 // candidate filter set above. | |
| 2362 port_allocator_->SetConfiguration(stun_servers, turn_servers, | |
| 2363 configuration.ice_candidate_pool_size, | |
| 2364 configuration.prune_turn_ports); | |
| 2365 return true; | |
| 2366 } | |
| 2367 | |
| 2368 bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file, | |
| 2369 int64_t max_size_bytes) { | |
| 2370 return event_log_->StartLogging(file, max_size_bytes); | |
| 2371 } | |
| 2372 | |
| 2373 void PeerConnection::StopRtcEventLog_w() { | |
| 2374 event_log_->StopLogging(); | |
| 2375 } | |
| 2376 } // namespace webrtc | |
| OLD | NEW |