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