Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(215)

Side by Side Diff: talk/app/webrtc/peerconnection.cc

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

Powered by Google App Engine
This is Rietveld 408576698