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